diff --git a/cpp/web/host.cpp b/cpp/web/host.cpp index 164a7fa2..e31c383a 100644 --- a/cpp/web/host.cpp +++ b/cpp/web/host.cpp @@ -238,10 +238,13 @@ CPW void cpw_set_clock(int32_t e, double millis) { if (Editor *ed = at(e)) ed->clock = millis; } -// Runs worker work, then main work, until both queues are empty or budget_ms is spent. Returns the items left. -CPW int32_t cpw_pump(double budget_ms) { +// Runs worker work, then main work, until both queues are empty or budget_ms is spent. After the first item, another +// starts only while a parse slice of slice_ms still fits. Returns the items left. +CPW int32_t cpw_pump(double budget_ms, double slice_ms) { double end = emscripten_get_now() + budget_ms; - while ((!worker_q.empty() || !main_q.empty()) && emscripten_get_now() < end) { + bool first = true; + while ((!worker_q.empty() || !main_q.empty()) && (first || emscripten_get_now() + slice_ms < end)) { + first = false; std::deque &q = !worker_q.empty() ? worker_q : main_q; Work w = q.front(); q.pop_front(); diff --git a/example/src/EditorApp.web.tsx b/example/src/EditorApp.web.tsx index 6f4f2de1..8b432590 100644 --- a/example/src/EditorApp.web.tsx +++ b/example/src/EditorApp.web.tsx @@ -1,7 +1,10 @@ import { useEffect, useMemo, useRef, useState } from 'react'; import { Pressable, ScrollView, StyleSheet, Text, View } from 'react-native'; -import { CodeEditor, Codepad } from 'react-native-codepad'; +import { CodeEditor, type CodeEditorRef, Codepad, type Decoration } from 'react-native-codepad'; import { generateJavaScript } from './bench/generate'; +import { FindBar } from './chrome/FindBar'; +import { schemeFor } from './chrome/theme'; +import { buildDemoDecorations } from './decorations'; import { GENERATED_FILES, SAMPLE_FILES } from './files'; import { NESTED_SNIPPET } from './screens/nestedSnippet'; import { THEMES } from './themes'; @@ -9,6 +12,7 @@ import { THEMES } from './themes'; type Demo = 'editor' | 'nested' | 'two'; const FILES = [...SAMPLE_FILES, ...GENERATED_FILES.filter((f) => f.id === 'js10k')]; const FONT = 'JetBrainsMono_400Regular'; +const NO_DECORATIONS: { items: Decoration[]; revision: number } = { items: [], revision: -1 }; function Chip({ label, on, onPress }: { label: string; on: boolean; onPress: () => void }) { return ( @@ -24,11 +28,18 @@ export function EditorApp() { const [themeIndex, setThemeIndex] = useState(0); const [scrollEnabled, setScrollEnabled] = useState(true); const [suggestions, setSuggestions] = useState<'on' | 'off'>('off'); + const [decorate, setDecorate] = useState(false); + const [finding, setFinding] = useState(false); + const [status, setStatus] = useState(''); + const [decorations, setDecorations] = useState(NO_DECORATIONS); + const editor = useRef(null); const [demo, setDemo] = useState('editor'); const theme = THEMES[themeIndex % THEMES.length]?.theme; // Lines of the generated JavaScript file the typing bench opened, 0 for a picked file. const [benchLines, setBenchLines] = useState(0); const file = FILES.find((f) => f.id === fileId) ?? FILES[0]; + // The editor and the find bar both remount when this changes, so the bar never shows a search the new editor lacks. + const editorKey = benchLines ? `bench-${benchLines}` : file?.id; const text = useMemo( () => (benchLines ? generateJavaScript(benchLines) : (file?.load() ?? '')), [file, benchLines], @@ -41,6 +52,26 @@ export function EditorApp() { set(value); }; + // The demo re-sends a fresh array four times a second, as a debounced checker would, tagged with its revision. + useEffect(() => { + if (!decorate) { + setDecorations(NO_DECORATIONS); + return; + } + const scheme = theme ? schemeFor(theme) : 'light'; + const send = () => { + const ed = editor.current; + if (ed) + setDecorations({ + items: buildDemoDecorations(ed.getText(), scheme), + revision: ed.getRevision(), + }); + }; + send(); + const timer = setInterval(send, 250); + return () => clearInterval(timer); + }, [decorate, theme]); + // scripts/bench-web.mjs opens its file through this hook. useEffect(() => { if (!__DEV__) return; @@ -79,6 +110,9 @@ export function EditorApp() { on={suggestions === 'on'} onPress={() => setSuggestions((s) => (s === 'on' ? 'off' : 'on'))} /> + setDecorate((d) => !d)} /> + setFinding((f) => !f)} /> + {status ? {status} : null} {FILES.map((f) => ( @@ -94,9 +128,21 @@ export function EditorApp() { /> ))} + {finding && demo === 'editor' ? ( + setFinding(false)} + /> + ) : null} {demo === 'editor' ? ( void, on?: boolean) => ( + + {label} + + ); + const { index, count } = find.match; + return ( + + + + {count ? `${index || '-'} of ${count}` : 'no results'} + + {button('.*', 'Regular expression', () => find.toggle('regex'), find.options.regex)} + {button('Aa', 'Match case', () => find.toggle('caseSensitive'), find.options.caseSensitive)} + {button('W', 'Whole word', () => find.toggle('wholeWord'), find.options.wholeWord)} + {button('prev', 'Previous match', find.previous)} + {button('next', 'Next match', find.next)} + + {button('replace', 'Replace', find.replaceOne)} + {button('all', 'Replace all', find.replaceAll)} + {button('close', 'Close find', onClose)} + + ); +} + +const styles = StyleSheet.create({ + bar: { flexDirection: 'row', flexWrap: 'wrap', gap: 6, padding: 8, alignItems: 'center' }, + field: { + minWidth: 120, + paddingHorizontal: 8, + paddingVertical: 4, + borderWidth: 1, + borderColor: '#8886', + borderRadius: 6, + }, + button: { paddingHorizontal: 8, paddingVertical: 4, borderRadius: 6, backgroundColor: '#8883' }, + on: { backgroundColor: '#0969da' }, + label: { fontSize: 13 }, +}); diff --git a/scripts/bench-web.mjs b/scripts/bench-web.mjs index 4a8bacbd..d9b3a350 100644 --- a/scripts/bench-web.mjs +++ b/scripts/bench-web.mjs @@ -1,4 +1,4 @@ -// Typing bench in Chrome: yarn bench:web [lines] [port] [--desktop [rate]] [--profile] +// Typing bench in Chrome: yarn bench:web [lines] [port] [--desktop [rate]] [--profile] [--keys n] // Without --desktop it drives Chrome on an Android device through adb, the example served on that port with adb reverse. // --desktop opens the example in a local Chromium at phone size with the CPU slowed by rate. --profile adds a CPU profile. import { execFileSync } from 'node:child_process'; @@ -14,17 +14,19 @@ const args = process.argv.slice(2); const positional = []; let desktop = null; let profile = false; +let keys = 60; for (let i = 0; i < args.length; i++) { if (args[i] === '--profile') profile = true; + else if (args[i] === '--keys') keys = Number(args[++i]); else if (args[i] === '--desktop') { desktop = /^\d+(\.\d+)?$/.test(args[i + 1] ?? '') ? Number(args[++i]) : DEFAULT_RATE; } else positional.push(args[i]); } const lines = Number(positional[0] ?? 300); const WEB_PORT = positional[1] ?? '8082'; -const CHARS = 60; +const CHARS = keys; const GAP_MS = 150; -const TEXT = 'let total = value + 1; '.repeat(3).slice(0, CHARS); +const TEXT = 'let total = value + 1; '.repeat(Math.ceil(CHARS / 23)).slice(0, CHARS); const PORT = 9222; const ROOTS = { drawKeyed: 'key draw', runEngine: 'engine', applyInput: 'handler' }; @@ -92,7 +94,8 @@ try { const probe = await page.evaluate(() => globalThis.__codepadProbe); const stats = (list) => { const sorted = [...list].sort((a, b) => a - b); - return `p50 ${ms(pct(sorted, 0.5))}, p95 ${ms(pct(sorted, 0.95))}, max ${ms(sorted.at(-1) ?? 0)}`; + const mean = list.reduce((a, b) => a + b, 0) / Math.max(1, list.length); + return `mean ${ms(mean)}, p50 ${ms(pct(sorted, 0.5))}, p95 ${ms(pct(sorted, 0.95))}, max ${ms(sorted.at(-1) ?? 0)}`; }; const where = desktop !== null ? `desktop at ${desktop}x` : 'device'; console.log(`${lines} lines, ${where}, ${probe.work.length} of ${CHARS} keys`); @@ -110,7 +113,7 @@ try { const top = summarize(taken, ROOTS, 12); for (const group of ['key draw', 'handler', 'engine', 'other']) { const total = (all[group] ?? []).reduce((sum, f) => sum + f.selfMs, 0); - console.log(` profile ${group}: ${ms(total)} over the 60 keys`); + console.log(` profile ${group}: ${ms(total)} over the ${CHARS} keys`); for (const f of top[group] ?? []) console.log(` ${ms(f.selfMs).padStart(9)} ${f.fn}`); } console.log(` profile saved to ${file}`); diff --git a/src/web/CodeEditor.tsx b/src/web/CodeEditor.tsx index 77f53b5d..8d49b883 100644 --- a/src/web/CodeEditor.tsx +++ b/src/web/CodeEditor.tsx @@ -2,6 +2,7 @@ import { type ComponentRef, forwardRef, + useCallback, useEffect, useImperativeHandle, useMemo, @@ -63,7 +64,7 @@ export const CodeEditor = forwardRef(function Co onBlur, onContentSizeChange, decorations, - decorationsRevision: _decorationsRevision, + decorationsRevision, onGapLayout, ...viewProps }, @@ -84,6 +85,7 @@ export const CodeEditor = forwardRef(function Co onContentSizeChange, onFocus, onBlur, + onGapLayout, }); handlers.current = { onReady, @@ -94,6 +96,7 @@ export const CodeEditor = forwardRef(function Co onContentSizeChange, onFocus, onBlur, + onGapLayout, }; const initial = useRef(initialValue); @@ -126,6 +129,7 @@ export const CodeEditor = forwardRef(function Co onScroll: (x, y, contentWidth, contentHeight) => handlers.current.onScroll?.({ x, y, contentWidth, contentHeight }), onFirstDraw: () => handlers.current.onReady?.(), + onGapLayout: (gaps) => handlers.current.onGapLayout?.({ gaps }), onChange: (c) => { const h = handlers.current; h.onChange?.({ @@ -163,10 +167,20 @@ export const CodeEditor = forwardRef(function Co avoidKeyboard, ], ); - const latest = useRef({ options, language }); - latest.current = { options, language }; + const latest = useRef({ options, language, decorations, decorationsRevision }); + latest.current = { options, language, decorations, decorationsRevision }; + // The decorations last sent, so the view gets them before its first draw and a repeat is not mapped twice. + const sent = useRef<{ items?: typeof decorations; revision?: number }>({}); + const sendDecorations = useCallback((v: EditorView) => { + const { decorations: items, decorationsRevision: revision } = latest.current; + const last = sent.current; + if (items === last.items && revision === last.revision) return; + sent.current = { items, revision }; + // A prop that goes away clears for the current text, and one that never came sends nothing. + if (items || last.items) v.setDecorations(items ?? [], items ? (revision ?? -1) : -1); + }, []); - // Options and language reach the view before its first draw, which the pump runs before React commits. + // Options, language and decorations reach the view before its first draw, which the pump runs before React commits. useEffect(() => { let alive = true; let created: EditorView | null = null; @@ -182,6 +196,8 @@ export const CodeEditor = forwardRef(function Co created = v; v.setOptions(latest.current.options); v.setLanguage(latest.current.language); + sent.current = {}; + sendDecorations(v); viewRef.current = v; for (const write of queued.current.splice(0)) { write.edit(v); @@ -204,12 +220,12 @@ export const CodeEditor = forwardRef(function Co // A StrictMode remount runs the effect again before this fires and keeps the waiting writes. setTimeout(() => gone.current && drop(), 0); }; - }, []); + }, [sendDecorations]); + // biome-ignore lint/correctness/useExhaustiveDependencies: sendDecorations reads the props through latest. useEffect(() => { - if (decorations) notYet('decorations'); - if (onGapLayout) notYet('onGapLayout'); - }, [decorations, onGapLayout]); + if (view) sendDecorations(view); + }, [view, decorations, decorationsRevision]); useEffect(() => { view?.setOptions(options); @@ -231,6 +247,24 @@ export const CodeEditor = forwardRef(function Co return Promise.resolve(); }; const write = (edit: (v: EditorView) => void) => run((v) => v.apply(() => edit(v))); + // A call with a result: on the view now, once it loads, or the fallback when no view comes. + const ask = (call: (v: EditorView) => Promise, fallback: T): Promise => { + const v = viewRef.current; + if (v) return call(v); + if (gone.current) return Promise.resolve(fallback); + return new Promise((resolve, reject) => { + let started = false; + queued.current.push({ + edit: (view) => { + started = true; + call(view).then(resolve, reject); + }, + done: () => { + if (!started) resolve(fallback); + }, + }); + }); + }; return { getText: () => core()?.text() ?? '', getTextInRange: (range) => core()?.text(range.start, range.end) ?? '', @@ -245,10 +279,7 @@ export const CodeEditor = forwardRef(function Co const v = viewRef.current; return v ? v.caretRect(v.core.selection.head) : null; }, - getGapRect: () => { - notYet('getGapRect'); - return null; - }, + getGapRect: (line) => viewRef.current?.gapRect(line) ?? null, getVisibleLines: () => viewRef.current?.visibleLines() ?? { first: 0, last: 0 }, canUndo: () => core()?.canUndo ?? false, canRedo: () => core()?.canRedo ?? false, @@ -275,12 +306,12 @@ export const CodeEditor = forwardRef(function Co paste: () => later('paste', undefined), focus: () => run((v) => v.focus()), blur: () => run((v) => v.blur()), - setSearch: () => later('setSearch', { count: 0, limited: false }), - findNext: () => later('findNext', null), - findPrevious: () => later('findPrevious', null), - replaceCurrent: () => later('replaceCurrent', false), - replaceAll: () => later('replaceAll', 0), - clearSearch: () => later('clearSearch', undefined), + setSearch: (query) => ask((v) => v.setSearch(query), { count: 0, limited: false }), + findNext: () => ask((v) => v.findNext(), null), + findPrevious: () => ask((v) => v.findPrevious(), null), + replaceCurrent: (text) => ask((v) => v.replaceCurrent(text), false), + replaceAll: (text) => ask((v) => v.replaceAll(text), 0), + clearSearch: () => ask((v) => v.clearSearch(), undefined), moveCaret: (direction, opts) => run((v) => v.moveCaret(direction, opts?.select ?? false)), typeText: (text) => run((v) => v.typeText(text)), deleteBackward: () => run((v) => v.deleteBackward()), diff --git a/src/web/EditorView.ts b/src/web/EditorView.ts index c899553b..21724097 100644 --- a/src/web/EditorView.ts +++ b/src/web/EditorView.ts @@ -1,9 +1,19 @@ /// import { githubLight } from '../themes/githubLight'; -import type { CaretDirection, ContentInsets, Rect, Suggestions, Theme } from '../types'; +import type { + CaretDirection, + ContentInsets, + Decoration, + Rect, + SearchHit, + SearchQuery, + Suggestions, + Theme, +} from '../types'; import { EditorCore, type MoveUnit, type WebChange } from './core/EditorCore'; import { Layout } from './core/Layout'; import type { CoreModule } from './core/module'; +import { measureBaseline, solidTop, waveAmplitude, wavePath } from './decorations'; import { type DecodedFrame, decodeFrame } from './frame'; import { CaretMover, type LineGeometry } from './input/CaretMover'; import { InputHost } from './input/InputHost'; @@ -12,6 +22,7 @@ import { keyCommand } from './input/keys'; import { WebInputSession } from './input/WebInputSession'; import { ensureInjected, ensureLanguage, onRegistered } from './loader'; import { probeKey, probing, registerView, requestPump } from './pump'; +import { firstEndingAfter, SearchController } from './search'; import { type CssTheme, cssTheme } from './theme'; export type ViewOptions = { @@ -42,8 +53,11 @@ export type ViewOptions = { avoidKeyboard: boolean; onFocus?: () => void; onBlur?: () => void; + onGapLayout?: (gaps: GapRect[]) => void; }; +export type GapRect = { line: number; rect: Rect }; + // The defaults of website/docs/reference/props.md. export const DEFAULT_OPTIONS: ViewOptions = { theme: githubLight, @@ -70,6 +84,7 @@ export const DEFAULT_OPTIONS: ViewOptions = { const MONOSPACE = 'ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace'; const SNAPSHOT_INFO_INTS = 7; +const SVG = 'http://www.w3.org/2000/svg'; const MAC = typeof navigator !== 'undefined' && /Mac|iPhone|iPad|iPod/.test(navigator.platform); // A run of Hebrew or Arabic script anywhere in a row. const RTL_TEXT = /[\u0590-\u08FF\uFB1D-\uFDFF\uFE70-\uFEFF]/; @@ -89,6 +104,8 @@ type Entry = { revision: number; spans: Int32Array | null; text: string; + // Edited since its last draw: the element is reused, but the frame reads the line again. + stale?: boolean; }; // The edited line's previous spans moved along an edit that stayed inside it, kept until a parse lands. @@ -145,6 +162,19 @@ export class EditorView { }); readonly session: WebInputSession; private readonly input: InputHost; + // The app's line backgrounds over the active line, and its underlines under the text. + private readonly lineBackgroundLayer = div('position:absolute;left:0;top:0;pointer-events:none;'); + private readonly underlineLayer = div('position:absolute;left:0;top:0;pointer-events:none;'); + // Search matches under the selection, the selected match in the active color. + private readonly matchLayer = div('position:absolute;left:0;top:0;pointer-events:none;'); + private matchesKey = ''; + private paintedPairs: number[] | null = null; + private readonly search: SearchController; + private decorationsKey = ''; + private baseline = 0; + private drawnWindow = { first: 0, last: -1 }; + private drawnGaps: GapRect[] = []; + private reportedGaps = '[]'; private readonly selectionLayer = div('position:absolute;left:0;top:0;pointer-events:none;'); private readonly composingLayer = div( 'position:absolute;left:0;top:0;z-index:1;pointer-events:none;', @@ -181,6 +211,7 @@ export class EditorView { constructor(host: HTMLElement, m: CoreModule, text = '') { this.m = m; this.core = new EditorCore(m, text); + this.search = new SearchController(this.core, () => this.invalidate()); this.layout = new Layout(this.core); this.root = div('position:relative;overflow:hidden;width:100%;height:100%;direction:ltr;'); this.scroller = div('position:absolute;inset:0;overflow:auto;'); @@ -192,7 +223,10 @@ export class EditorView { this.placeholderEl = div('position:absolute;white-space:pre;display:none;pointer-events:none;'); this.textLayer.append( this.activeLine, + this.lineBackgroundLayer, + this.matchLayer, this.selectionLayer, + this.underlineLayer, this.placeholderEl, this.composingLayer, this.caretEl, @@ -201,6 +235,7 @@ export class EditorView { this.textLayer.style.webkitUserSelect = 'none'; this.caretEl.dataset.caret = ''; this.selectionLayer.dataset.selection = ''; + this.activeLine.dataset.activeLine = ''; this.session = new WebInputSession(this.core, (edit) => this.applyInput(edit)); this.input = new InputHost(this.root, this.session, { keyDown: (e) => this.keyDown(e), @@ -297,7 +332,10 @@ export class EditorView { if (outside) this.session.external(); edit(); const changes = this.core.takeChanges(); - for (const change of changes) this.changed(change, changes.length); + for (const change of changes) { + this.search.onChange(change); + this.changed(change, changes.length); + } const s = this.core.selection; const moved = s.anchor !== this.lastSelection.anchor || s.head !== this.lastSelection.head; if (moved) this.lastSelection = s; @@ -552,6 +590,7 @@ export class EditorView { // A click places the caret and focuses the textarea inside the event, which iOS needs to show its keyboard. private click(e: MouseEvent): void { + if (this.inGap(e.clientY)) return; const offset = this.offsetAt(e.clientX, e.clientY); if (offset !== null) this.apply(() => this.core.setSelection(offset, offset)); this.focus(); @@ -561,12 +600,13 @@ export class EditorView { private drawInput(): void { const box = this.textLayer.getBoundingClientRect(); const { anchor, head } = this.core.selection; - const caret = this.caretRect(head); - this.drawnCaret = caret; const rootBox = this.root.getBoundingClientRect(); + const caret = this.caretRect(head, rootBox); + this.drawnCaret = caret; const caretLine = this.cache.get(this.core.lineAt(head))?.el; + // Without soft wrap every line is one row. this.drawnCaretRow = - caret && caretLine + this.o.softWrap && caret && caretLine ? Math.max( 0, Math.round( @@ -579,6 +619,8 @@ export class EditorView { const from = Math.min(anchor, head); const to = Math.max(anchor, head); const selected = from < to ? this.rangeRects(from, to) : []; + const writeDecorations = this.planDecorations(box); + const writeMatches = this.planMatches(box, rootBox, from, to); if (caret && this.input.focused) { put(this.caretEl, 'display', 'block'); put(this.caretEl, 'left', `${caret.x + rootBox.left - box.left}px`); @@ -609,6 +651,8 @@ export class EditorView { ), ); } + writeDecorations(); + writeMatches(); } // The page boxes of the document range on the lines that are drawn. @@ -654,6 +698,272 @@ export class EditorView { this.invalidate(); } + // Decorations for the text at revision, below zero for the current text. An unknown revision keeps the set. + setDecorations(items: Decoration[], revision: number): void { + if (this.destroyed) return; + this.core.setDecorations(items, revision); + this.invalidate(); + } + + // Resolves with the count once the scan is fresh. Rejects with PCRE2's message for an invalid regex. + setSearch(query: SearchQuery): Promise<{ count: number; limited: boolean }> { + if (this.destroyed) return Promise.resolve({ count: 0, limited: false }); + try { + this.search.setQuery(query); + } catch (e) { + this.invalidate(); + return Promise.reject(e); + } + this.invalidate(); + return this.whenFresh(() => ({ count: this.core.matchCount, limited: this.core.matchLimited })); + } + + clearSearch(): Promise { + if (!this.destroyed) { + this.search.setQuery(null); + this.invalidate(); + } + return Promise.resolve(); + } + + findNext(): Promise { + return this.whenFresh(() => this.find(true)); + } + + findPrevious(): Promise { + return this.whenFresh(() => this.find(false)); + } + + // Replaces the selected match and selects the next one. False when the selection is not a match. + replaceCurrent(text: string): Promise { + return this.whenFresh(() => { + let replaced = false as boolean; + this.apply(() => { + replaced = this.core.replaceCurrent(text); + }); + if (replaced) this.revealSelection(); + return replaced; + }); + } + + // Every match replaced as one undo step. Resolves with the count. + replaceAll(text: string): Promise { + return this.whenFresh(() => { + let count = 0; + this.apply(() => { + count = this.core.replaceAll(text); + }); + return count; + }); + } + + private find(forward: boolean): SearchHit | null { + let hit = null as SearchHit | null; + this.apply(() => { + hit = forward ? this.core.findNext() : this.core.findPrevious(); + }); + if (hit) this.revealSelection(); + return hit; + } + + // Runs once the matches belong to the current text, as native's whenSearchFresh. + private whenFresh(run: () => T): Promise { + return new Promise((resolve, reject) => + this.search.whenFresh(() => { + try { + resolve(run()); + } catch (e) { + reject(e); + } + }), + ); + } + + // The gap under line from the last draw, in the coordinates of caretRect, or null. + gapRect(line: number): Rect | null { + return this.drawnGaps.find((g) => g.line === line)?.rect ?? null; + } + + // Every gap as the full width rows under its line, in the coordinates of caretRect. + private gapRects(): GapRect[] { + const layout = this.layout; + const shift = this.o.scrollEnabled ? 0 : layout.scrollY; + return layout.gaps().map((g) => ({ + line: g.line, + rect: { x: 0, y: g.top + shift, width: layout.width, height: g.rows * this.rowHeight }, + })); + } + + // True when a page y falls in a gap, which belongs to the app's view there. + private inGap(clientY: number): boolean { + if (this.drawnGaps.length === 0) return false; + const y = clientY - this.root.getBoundingClientRect().top; + return this.drawnGaps.some((g) => y >= g.rect.y && y < g.rect.y + g.rect.height); + } + + // Reads the decorations' geometry now and returns their writes, so the draw keeps one read phase. + private planDecorations(box: DOMRect): () => void { + const items = this.core.decorations(); + const { first, last } = this.drawnWindow; + const key = + items.length === 0 + ? '' + : [ + this.core.decorationsVersion, + this.core.revision, + this.appliedRevision, + first, + last, + this.layout.wrapWidth, + this.rowHeight, + this.baseline, + ].join(':'); + if (key === this.decorationsKey) return () => {}; + this.decorationsKey = key; + const layout = this.layout; + const backgrounds: Element[] = []; + const underlines: Element[] = []; + const windowStart = this.core.lineStart(first); + const windowEnd = this.core.lineEnd(last); + for (const d of items) { + if (d.kind === 'lineBackground') { + if (d.line < first || d.line > last) continue; + const el = div( + `position:absolute;left:${layout.textAreaLeft}px;top:${layout.lineTop(d.line) + layout.scrollY}px;width:${layout.contentWidth + layout.insetRight}px;height:${layout.rows(d.line) * this.rowHeight}px;background:${d.color};`, + ); + el.dataset.lineBackground = ''; + backgrounds.push(el); + } else if (d.kind === 'underline') { + if (d.range.end < windowStart || d.range.start > windowEnd) continue; + for (const r of this.rowRects(d.range.start, d.range.end)) { + underlines.push( + this.underline(d, r.left - box.left, r.right - box.left, r.top - box.top), + ); + } + } + } + return () => { + this.lineBackgroundLayer.replaceChildren(...backgrounds); + this.underlineLayer.replaceChildren(...underlines); + }; + } + + // Reads the visible matches' boxes now and returns their writes, the selected match in the active color. + private planMatches(box: DOMRect, rootBox: DOMRect, from: number, to: number): () => void { + const pairs = this.search.matchesForPaint(); + const { first, last } = this.drawnWindow; + const key = + pairs.length === 0 + ? '' + : [ + this.core.revision, + this.appliedRevision, + first, + last, + from, + to, + this.layout.wrapWidth, + this.layout.scrollX, + ].join(':'); + if (key === this.matchesKey && pairs === this.paintedPairs) return () => {}; + this.matchesKey = key; + this.paintedPairs = pairs; + const [windowStart, windowEnd] = pairs.length ? this.visibleSpan(rootBox) : [0, -1]; + const marks: HTMLElement[] = []; + for (let i = firstEndingAfter(pairs, windowStart); i * 2 < pairs.length; i++) { + const s = pairs[i * 2] as number; + const e = pairs[i * 2 + 1] as number; + if (s > windowEnd) break; + const active = from < to && s === from && e === to; + for (const r of this.rangeRects(s, e)) { + const mark = div( + `position:absolute;left:${r.left - box.left}px;top:${r.top - box.top}px;width:${Math.max(r.width, 2)}px;height:${r.height}px;background:${active ? this.css.searchMatchActive : this.css.searchMatch};`, + ); + mark.dataset.match = ''; + if (active) mark.dataset.matchActive = ''; + marks.push(mark); + } + } + return () => this.matchLayer.replaceChildren(...marks); + } + + // The first and last offsets on screen, so a long line paints only the matches in view. + private visibleSpan(rootBox: DOMRect): [number, number] { + const { first, last } = this.drawnWindow; + const lo = this.core.lineStart(first); + const hi = this.core.lineEnd(last); + const top = Math.max(rootBox.top, 0) + 1; + const bottom = Math.min(rootBox.bottom, window.innerHeight) - 2; + const a = this.offsetAt(rootBox.left + this.layout.textAreaLeft + 1, top); + const b = this.offsetAt(rootBox.right - 2, bottom); + return [a === null ? lo : Math.max(lo, a), b === null ? hi : Math.min(hi, b)]; + } + + // The range's page boxes on drawn lines, merged to one per row, with the top of that row. + private rowRects(start: number, end: number): { left: number; right: number; top: number }[] { + const out: { left: number; right: number; top: number }[] = []; + const last = this.core.lineAt(end); + for (let line = this.core.lineAt(start); line <= last; line++) { + const entry = this.cache.get(line); + if (!entry || entry.stale || !this.attached.has(line)) continue; + const lineStart = this.core.lineStart(line); + const a = Math.max(start, lineStart) - lineStart; + const b = Math.min(end, lineStart + entry.text.length) - lineStart; + if (b <= a) continue; + const range = document.createRange(); + const [sn, so] = textPoint(entry.el, a); + const [en, eo] = textPoint(entry.el, b); + range.setStart(sn, so); + range.setEnd(en, eo); + const lineTop = entry.el.getBoundingClientRect().top; + const rows = new Map(); + for (const r of range.getClientRects()) { + if (r.width <= 0) continue; + const row = Math.floor((r.top + r.height / 2 - lineTop) / this.rowHeight); + const seen = rows.get(row); + if (seen) { + seen.left = Math.min(seen.left, r.left); + seen.right = Math.max(seen.right, r.right); + } else rows.set(row, { left: r.left, right: r.right, top: lineTop + row * this.rowHeight }); + } + out.push(...rows.values()); + } + return out; + } + + // One underline piece on a row, solid as a bar or wavy as a clipped path, as DecorationPainter.kt draws them. + private underline( + d: Extract, + left: number, + right: number, + rowTop: number, + ): Element { + const thickness = d.thickness ?? 1; + const offset = d.offset ?? 2; + if (d.style !== 'wavy') { + const bar = div( + `position:absolute;left:${left}px;top:${solidTop(rowTop, this.baseline, offset)}px;width:${right - left}px;height:${Math.max(1, Math.round(thickness))}px;background:${d.color};`, + ); + bar.dataset.underline = ''; + return bar; + } + // The wave's centre sits a thickness below a solid line's top, and the box clips it like native. + const pad = waveAmplitude(thickness) + thickness; + const centre = rowTop + this.baseline + offset + thickness; + const svg = document.createElementNS(SVG, 'svg'); + svg.setAttribute('width', String(right - left)); + svg.setAttribute('height', String(2 * pad)); + svg.style.cssText = `position:absolute;left:${left}px;top:${centre - pad}px;overflow:hidden;`; + const path = document.createElementNS(SVG, 'path'); + path.setAttribute('d', wavePath(0, right - left, pad, thickness)); + path.setAttribute('fill', 'none'); + path.setAttribute('stroke', d.color); + path.setAttribute('stroke-width', String(thickness)); + svg.append(path); + svg.dataset.underline = ''; + return svg; + } + // Scrolls the least that shows the caret, by its line's row while the line is not drawn. True when it scrolled. private revealCaret(): boolean { const caret = this.drawnCaret; @@ -669,12 +979,12 @@ export class EditorView { } // The caret at offset in view coordinates, or null when its line is not drawn. - caretRect(offset: number): Rect | null { + caretRect(offset: number, rootBox?: DOMRect): Rect | null { if (this.destroyed) return null; const line = this.core.lineAt(offset); const entry = this.cache.get(line); - if (!entry || !this.attached.has(line)) return null; - const box = this.root.getBoundingClientRect(); + if (!entry || entry.stale || !this.attached.has(line)) return null; + const box = rootBox ?? this.root.getBoundingClientRect(); const edge = caretEdge(entry.el, offset - this.core.lineStart(line)); return { x: edge.x - box.left, y: edge.top - box.top, width: 1, height: this.rowHeight }; } @@ -702,8 +1012,17 @@ export class EditorView { // A caret moved off screen scrolls into view before the paint: by row while its line is not drawn, then by x. for (let pass = 0; this.revealing && pass < 2; pass++) { if (this.drawnCaret) this.revealing = false; + const [beforeX, beforeY] = [this.layout.scrollX, this.layout.scrollY]; if (!this.revealCaret()) break; this.syncScroll(); + const caret = this.drawnCaret; + if (caret && this.layout.scrollY === beforeY) { + // Lines and the caret scroll with the content: only the textarea, placed in view coordinates, follows. + const x = caret.x - (this.layout.scrollX - beforeX); + this.drawnCaret = { ...caret, x }; + if (this.input.focused) this.input.place(x, caret.y); + break; + } moved = this.frame(); } this.revealing = false; @@ -723,6 +1042,7 @@ export class EditorView { const frame = this.readFrame(); const moved = this.prepare(frame); this.place(frame); + this.drawnGaps = this.gapRects(); this.drawInput(); return moved; } finally { @@ -746,6 +1066,7 @@ export class EditorView { this.root.remove(); if (this.frameInts) this.m._free(this.frameInts); if (this.frameText) this.m._free(this.frameText); + this.search.close(); this.core.close(); // The engine finishes closing in the pump, which may have no other editor to run for. requestPump(); @@ -834,6 +1155,7 @@ export class EditorView { this.placeholderEl.style.color = this.css.gutterForeground; if (metrics) { this.charWidth = measureChar(this.root); + this.baseline = measureBaseline(this.root); this.layout.rowHeight = this.rowHeight; this.layout.wrap = o.softWrap; this.relayout(); @@ -896,7 +1218,7 @@ export class EditorView { const info = snapshot ? this.snapshotInfo(snapshot) : null; const incremental = info !== null && info.basedOn >= 0 && info.basedOn === this.appliedRevision; const pairs: number[] = []; - for (const [line, entry] of this.cache) pairs.push(line, entry.revision); + for (const [line, entry] of this.cache) if (!entry.stale) pairs.push(line, entry.revision); const entries = m._malloc(Math.max(1, pairs.length) * 4); m.HEAP32.set(pairs, entries >> 2); const lenPtr = m._malloc(4); @@ -1007,6 +1329,7 @@ export class EditorView { // Places the window's lines, numbers and active line, and takes every other line out of the page. private place(frame: DecodedFrame): void { const layout = this.layout; + this.drawnWindow = { first: frame.first, last: frame.last }; const scrollY = layout.scrollY; const left = layout.textAreaLeft + layout.textPadding; const width = layout.textAreaLeft + layout.contentWidth + layout.insetRight; @@ -1090,6 +1413,11 @@ export class EditorView { this.lastContent = { width, height }; this.o.onContentSize?.(width, height); } + const gaps = JSON.stringify(this.drawnGaps); + if (gaps !== this.reportedGaps) { + this.reportedGaps = gaps; + this.o.onGapLayout?.(this.drawnGaps); + } if (!this.drawn) { this.drawn = true; this.o.onFirstDraw?.(); @@ -1158,11 +1486,20 @@ export class EditorView { this.keepSpans(first, oldCount, newCount, change); if (colored && this.kept === null) this.urgent = true; const delta = newCount - oldCount; + // An edit inside one line moves no other line. + if (oldCount === 1 && newCount === 1) { + const entry = this.cache.get(first); + if (entry) entry.stale = true; + return; + } const moved: [number, Entry][] = []; for (const [line, entry] of this.cache) { if (line < first) moved.push([line, entry]); else if (line >= first + oldCount) moved.push([line + delta, entry]); - else entry.el.remove(); + else if (oldCount === 1 && newCount === 1) { + entry.stale = true; + moved.push([line, entry]); + } else entry.el.remove(); } this.cache.clear(); this.attached.clear(); @@ -1176,7 +1513,7 @@ export class EditorView { // The spans a line shows now: its cache entry, else what an edit since the last frame kept for it. private shownSpans(line: number): Int32Array | null { const entry = this.cache.get(line); - if (entry) return entry.spans; + if (entry && !entry.stale) return entry.spans; const kept = this.kept; if (!kept) return null; if (line === kept.line) return kept.spans; diff --git a/src/web/__tests__/CodeEditor.test.tsx b/src/web/__tests__/CodeEditor.test.tsx index bf3d34f3..2dbd0f11 100644 --- a/src/web/__tests__/CodeEditor.test.tsx +++ b/src/web/__tests__/CodeEditor.test.tsx @@ -41,6 +41,8 @@ class MockView { deleteBackward = jest.fn(); deleteForward = jest.fn(); moveCaret = jest.fn(); + setDecorations = jest.fn(); + gapRect = jest.fn(() => null); destroy() {} } @@ -189,3 +191,49 @@ test('focus called before the core loads focuses the editor once it does', async await expect(settled(focused as Promise)).resolves.toBeUndefined(); expect(mockViews[0]?.focus).toHaveBeenCalledTimes(1); }); + +test('decorations passed before the core loads apply once it does', async () => { + const items = [{ kind: 'gap' as const, line: 0, rows: 2 }]; + await render(); + await act(async () => { + mockCore.resolve({}); + await tick(); + }); + expect(mockViews[0]?.setDecorations).toHaveBeenCalledWith(items, 3); +}); + +test('decorations passed at mount are on the view when it first draws, and sent once', async () => { + const items = [{ kind: 'gap' as const, line: 0, rows: 2 }]; + let atReady: unknown[][] = []; + const onReady = () => { + atReady = [...(mockViews[0]?.setDecorations.mock.calls ?? [])]; + }; + await render(); + await act(async () => { + mockCore.resolve({}); + await tick(); + }); + expect(atReady).toEqual([[items, 3]]); + expect(mockViews[0]?.setDecorations).toHaveBeenCalledTimes(1); +}); + +test('decorations without a revision are for the current text', async () => { + const items = [{ kind: 'lineBackground' as const, line: 1, color: 'red' }]; + await render(); + await act(async () => { + mockCore.resolve({}); + await tick(); + }); + expect(mockViews[0]?.setDecorations).toHaveBeenCalledWith(items, -1); +}); + +test('removing decorations clears them for the current text, whatever decorationsRevision says', async () => { + const items = [{ kind: 'gap' as const, line: 0, rows: 2 }]; + const { rerender } = await render(); + await act(async () => { + mockCore.resolve({}); + await tick(); + }); + await rerender(); + expect(mockViews[0]?.setDecorations).toHaveBeenLastCalledWith([], -1); +}); diff --git a/src/web/__tests__/decorations.test.ts b/src/web/__tests__/decorations.test.ts new file mode 100644 index 00000000..1b31447b --- /dev/null +++ b/src/web/__tests__/decorations.test.ts @@ -0,0 +1,21 @@ +import { expect, test } from '@jest/globals'; +import { solidTop, wavePath } from '../decorations'; + +test('a wave starts on the centre line heading down, half a wavelength per curve', () => { + const d = wavePath(0, 10, 5, 1); + // Thickness 1: half wavelength (4 + 0.375) / 2, swing 0.875 drawn as a control point twice as far. + expect(d.startsWith('M0 5 Q1.09375 6.75 2.1875 5 Q3.28125 3.25 4.375 5')).toBe(true); + const ends = [...d.matchAll(/Q\S+ \S+ (\S+) /g)].map((m) => Number(m[1])); + expect(ends).toHaveLength(5); + expect(ends.at(-1)).toBeGreaterThanOrEqual(10); +}); + +test('a wave scales with the thickness', () => { + const d = wavePath(4, 6, 0, 2); + expect(d.startsWith('M4 0 Q6.09375 3.5 8.1875 0')).toBe(true); +}); + +test('a solid underline sits offset below the baseline, on a whole pixel', () => { + expect(solidTop(20, 14.6, 2)).toBe(37); + expect(solidTop(0, 14.4, 2)).toBe(16); +}); diff --git a/src/web/__tests__/pump.test.ts b/src/web/__tests__/pump.test.ts new file mode 100644 index 00000000..08b155f4 --- /dev/null +++ b/src/web/__tests__/pump.test.ts @@ -0,0 +1,34 @@ +import { existsSync } from 'node:fs'; +import { join } from 'node:path'; +import { expect, test } from '@jest/globals'; +import { generateJavaScript } from '../../../example/src/bench/generate'; +import { builtCore, loadCore, loadGrammar, pumpAll, ROOT } from '../../../tests/web/core'; +import { EditorCore } from '../core/EditorCore'; + +const dir = builtCore('lib/web', 'yarn build:web'); +const javascript = join(ROOT, 'languages/javascript/web/javascript.wasm'); +const ready = dir !== null && existsSync(javascript); +if (dir && !ready) console.warn('javascript grammar not built, run yarn build:web-grammars'); + +// The jest preset rounds performance.now to whole milliseconds. +const now = () => Number(process.hrtime.bigint()) / 1e6; + +(ready ? test : test.skip)('one pump starts no second parse slice', async () => { + const m = await loadCore(dir as string); + loadGrammar(m, javascript, 'javascript', join(ROOT, 'languages/javascript/queries/javascript')); + const core = new EditorCore(m, generateJavaScript(100_000), 4000); + expect(core.setLanguage('javascript')).toBe(true); + const took: number[] = []; + for (let i = 0; i < 30; i++) { + const start = now(); + const left = m._cpw_pump(6, 4); + took.push(now() - start); + if (left === 0) break; + } + expect(took.length).toBe(30); + took.sort((a, b) => a - b); + // One 4 ms slice a call; two slices take about 8. + expect(took[15]).toBeLessThan(5.5); + core.close(); + pumpAll(m); +}); diff --git a/src/web/__tests__/search.test.ts b/src/web/__tests__/search.test.ts new file mode 100644 index 00000000..63e84556 --- /dev/null +++ b/src/web/__tests__/search.test.ts @@ -0,0 +1,128 @@ +import { expect, test } from '@jest/globals'; +import { generateJavaScript } from '../../../example/src/bench/generate'; +import { builtCore, loadCore } from '../../../tests/web/core'; +import { EditorCore, SearchError } from '../core/EditorCore'; +import { firstEndingAfter, mapThrough, SearchController } from '../search'; + +const dir = builtCore('lib/web', 'yarn build:web'); +const run = dir ? test : test.skip; + +// Runs the controller's scan to the end in steps of budgetMs. +function finish(c: SearchController, budgetMs = 1): number { + let steps = 0; + while (c.step(budgetMs)) steps++; + return steps; +} + +// The pairs a second core finds for text in one call, so the sliced scan is checked against an independent result. +function matchesOf( + m: ConstructorParameters[0], + text: string, + query: string, +): number[] { + const ref = new EditorCore(m, text); + ref.setSearch({ text: query, regex: false, caseSensitive: false, wholeWord: false }); + const pairs = ref.matches; + ref.close(); + return pairs; +} + +test('mapThrough keeps pairs before a change, shifts pairs after it and drops pairs it touches', () => { + const pairs = [0, 2, 5, 7, 10, 12, 4, 6]; + // Three units inserted at 6: [5, 7) is cut, [4, 6) ends where it starts and stays. + expect(mapThrough(pairs, { start: 6, end: 6, delta: 3 })).toEqual([0, 2, 13, 15, 4, 6]); + // Units 3 to 5 removed: [5, 7) starts at its end and moves back. + expect(mapThrough([0, 2, 5, 7], { start: 3, end: 5, delta: -2 })).toEqual([0, 2, 3, 5]); +}); + +test('firstEndingAfter finds the first match ending past an offset', () => { + expect(firstEndingAfter([0, 2, 5, 7, 10, 12], 6)).toBe(1); + expect(firstEndingAfter([0, 2, 5, 7, 10, 12], 12)).toBe(3); + expect(firstEndingAfter([], 0)).toBe(0); +}); + +run( + 'a scan over more matches than one batch holds finds the same pairs as one full search', + async () => { + const m = await loadCore(dir as string); + const core = new EditorCore(m, generateJavaScript(10_000)); + const c = new SearchController(core, () => {}); + c.setQuery({ text: 'e' }); + expect(core.searchStale).toBe(true); + expect(finish(c)).toBeGreaterThan(0); + expect(core.searchStale).toBe(false); + const sliced = c.matchesForPaint(); + expect(sliced.length).toBeGreaterThan(2 * 4096); + expect(sliced).toEqual(matchesOf(m, core.text(), 'e')); + expect(core.matchCount).toBe(sliced.length / 2); + c.close(); + core.close(); + }, +); + +run('an edit during a scan drops it and the accepted result is for the new revision', async () => { + const m = await loadCore(dir as string); + const core = new EditorCore(m, generateJavaScript(100_000)); + const c = new SearchController(core, () => {}); + c.setQuery({ text: 'value' }); + expect(c.step(1)).toBe(true); + expect(core.searchStale).toBe(true); + core.replace(0, 0, 'value '); + for (const change of core.takeChanges()) c.onChange(change); + finish(c); + expect(core.searchStale).toBe(false); + expect(c.matchesForPaint().slice(0, 2)).toEqual([0, 5]); + expect(c.matchesForPaint()).toEqual(matchesOf(m, core.text(), 'value')); + c.close(); + core.close(); +}); + +run('whenFresh runs at once when nothing is stale and after the accept otherwise', async () => { + const m = await loadCore(dir as string); + const core = new EditorCore(m, 'ab ab ab'); + let fresh = 0; + const c = new SearchController(core, () => {}); + c.whenFresh(() => fresh++); + expect(fresh).toBe(1); + c.setQuery({ text: 'ab' }); + c.whenFresh(() => fresh++); + expect(fresh).toBe(1); + finish(c); + expect(fresh).toBe(2); + expect(core.matchCount).toBe(3); + c.close(); + core.close(); +}); + +run('an invalid regex throws SearchError and leaves no matches', async () => { + const m = await loadCore(dir as string); + const core = new EditorCore(m, 'ab ab'); + const c = new SearchController(core, () => {}); + c.setQuery({ text: 'ab' }); + finish(c); + expect(c.matchesForPaint()).toHaveLength(4); + expect(() => c.setQuery({ text: '(', regex: true })).toThrow(SearchError); + expect(c.matchesForPaint()).toEqual([]); + expect(core.searchActive).toBe(false); + expect(c.step(1)).toBe(false); + c.close(); + core.close(); +}); + +run('two controllers on two editors keep their own results', async () => { + const m = await loadCore(dir as string); + const a = new EditorCore(m, 'one two one'); + const b = new EditorCore(m, 'two two two two'); + const ca = new SearchController(a, () => {}); + const cb = new SearchController(b, () => {}); + ca.setQuery({ text: 'one' }); + cb.setQuery({ text: 'two' }); + while (ca.step(1) || cb.step(1)); + expect(a.matchCount).toBe(2); + expect(b.matchCount).toBe(4); + expect(ca.matchesForPaint()).toEqual([0, 3, 8, 11]); + ca.close(); + cb.close(); + a.close(); + b.close(); +}); diff --git a/src/web/__tests__/vectors.test.ts b/src/web/__tests__/vectors.test.ts index 1d76b711..b1b5fb4f 100644 --- a/src/web/__tests__/vectors.test.ts +++ b/src/web/__tests__/vectors.test.ts @@ -424,8 +424,8 @@ if (dir && !existsSync(javascript)) pumpAll(m); expect(core.snapshot).not.toBe(0); core.setText(js10k); - m._cpw_pump(1); - expect(m._cpw_pump(0)).toBeGreaterThan(0); + m._cpw_pump(1, 0); + expect(m._cpw_pump(0, 0)).toBeGreaterThan(0); core.close(); pumpAll(m); expect(m._cpw_test_held_snapshots()).toBe(0); diff --git a/src/web/core/EditorCore.ts b/src/web/core/EditorCore.ts index 5a8c4c31..4d6232a0 100644 --- a/src/web/core/EditorCore.ts +++ b/src/web/core/EditorCore.ts @@ -31,7 +31,7 @@ export type WebChange = { export class SearchError extends Error {} // The engine's parse budget per slice, so the page's pump stays inside a frame. -export const DEFAULT_BUDGET_MICROS = 4000; +export const DEFAULT_BUDGET_MICROS = 3000; const ORIGINS: ChangeOrigin[] = ['input', 'api', 'undo', 'redo']; const MOVES: MoveUnit[] = ['char', 'word', 'lineStart', 'lineEnd', 'docStart', 'docEnd']; @@ -412,6 +412,31 @@ export class EditorCore { return this.m._cp_editor_replace_all(this.handle, this.heap.units(text), text.length); } + // The compiled query, retained for the caller, or 0 without a search. + searchQuery(): number { + return this.m._cp_editor_search_query(this.handle); + } + + // The text as it is now, retained for the caller, so a scan outlives later edits. + textSnapshot(): number { + return this.m._cp_editor_text(this.handle); + } + + // Matches a scan found on the text at revision. False when the document moved on. + acceptMatches(revision: number, pairs: number[], limited: boolean): boolean { + const ptr = this.heap.ints32(Math.max(1, pairs.length)); + this.m.HEAP32.set(pairs, ptr >> 2); + return ( + this.m._cp_editor_accept_matches( + this.handle, + revision, + ptr, + pairs.length, + limited ? 1 : 0, + ) !== 0 + ); + } + // A language id the page has not loaded clears the language, so the editor draws plain text. setLanguage(id: string): boolean { return withCString(this.m, id, (ptr) => this.m._cpw_set_language(this.index, ptr)) !== 0; diff --git a/src/web/core/module.ts b/src/web/core/module.ts index dcf93c7e..9d437dca 100644 --- a/src/web/core/module.ts +++ b/src/web/core/module.ts @@ -36,7 +36,8 @@ export interface CoreModule { _cpw_take_missed(e: number, out: Ptr, cap: number): number; _cpw_refresh(e: number): void; _cpw_set_clock(e: number, millis: number): void; - _cpw_pump(budgetMs: number): number; + // Starts another queued item only while sliceMs still fits before budgetMs runs out. + _cpw_pump(budgetMs: number, sliceMs: number): number; _cpw_take_changes( e: number, out: Ptr, @@ -100,6 +101,20 @@ export interface CoreModule { _cp_editor_match_limited(ed: Ptr): number; _cp_editor_matches(ed: Ptr, out: Ptr, cap: number): number; _cp_editor_find(ed: Ptr, forward: number, index: Ptr, total: Ptr): number; + // The compiled query and a text snapshot, each retained for the caller, and matches found on them. + _cp_editor_search_query(ed: Ptr): Ptr; + _cp_editor_text(ed: Ptr): Ptr; + _cp_text_release(text: Ptr): void; + _cp_search_release(search: Ptr): void; + // scan points at three ints: next, limited, budget_ms. Returns the ints written to out. + _cp_search_find(search: Ptr, text: Ptr, scan: Ptr, out: Ptr, cap: number): number; + _cp_editor_accept_matches( + ed: Ptr, + revision: number, + pairs: Ptr, + count: number, + limited: number, + ): number; _cp_editor_replace_current(ed: Ptr, text: Ptr, length: number): number; _cp_editor_replace_all(ed: Ptr, text: Ptr, length: number): number; diff --git a/src/web/decorations.ts b/src/web/decorations.ts new file mode 100644 index 00000000..2065e858 --- /dev/null +++ b/src/web/decorations.ts @@ -0,0 +1,43 @@ +/// +// Underline geometry, the same as DecorationPainter.kt: Chrome's wavy underline, measured at 14 px for thickness 1 to 4. + +export function waveHalf(thickness: number): number { + return (4 * thickness + 0.375) / 2; +} + +// How far the centre line swings to either side. +export function waveAmplitude(thickness: number): number { + return 0.875 * thickness; +} + +// SVG path data, one quadratic per half wave, leaving the left edge on the centre line heading down. +export function wavePath(left: number, right: number, centre: number, thickness: number): string { + const half = waveHalf(thickness); + const swing = 2 * waveAmplitude(thickness); + let d = `M${left} ${centre}`; + let down = true; + for (let x = left; x < right; x += half) { + d += ` Q${x + half / 2} ${centre + (down ? swing : -swing)} ${x + half} ${centre}`; + down = !down; + } + return d; +} + +// The top of a solid underline: offset below the baseline, on a whole pixel like a browser draws it. +export function solidTop(rowTop: number, baseline: number, offset: number): number { + return Math.round(rowTop + baseline + offset); +} + +// From a row's top to its text baseline, in the root's font and line height. +export function measureBaseline(root: HTMLElement): number { + const line = document.createElement('div'); + line.style.cssText = 'position:absolute;visibility:hidden;white-space:pre;'; + line.textContent = '0'; + const mark = document.createElement('span'); + mark.style.cssText = 'display:inline-block;width:0;height:0;vertical-align:baseline;'; + line.append(mark); + root.append(line); + const baseline = mark.getBoundingClientRect().top - line.getBoundingClientRect().top; + line.remove(); + return baseline; +} diff --git a/src/web/pump.ts b/src/web/pump.ts index d99296cb..cef60b20 100644 --- a/src/web/pump.ts +++ b/src/web/pump.ts @@ -1,7 +1,10 @@ +import { DEFAULT_BUDGET_MICROS } from './core/EditorCore'; import type { CoreModule } from './core/module'; // The engine's share of a task, so a key still draws soon after it. export const PUMP_BUDGET_MS = 6; +// An engine step can run one parse slice, so the pump starts one only while a slice still fits. +const PARSE_SLICE_MS = DEFAULT_BUDGET_MICROS / 1000; // urgent: the view's next frame waits for the parse. pending: it has something to draw. type View = { draw(): void; readonly urgent: boolean; pending(): boolean }; @@ -66,9 +69,10 @@ export function requestPump(): void { function frame(): void { scheduled = false; + lastFrame = performance.now(); const start = probe ? performance.now() : 0; const urgent = [...views].some((v) => v.urgent); - const left = core && urgent ? core._cpw_pump(PUMP_BUDGET_MS) : 0; + const left = core && urgent ? core._cpw_pump(PUMP_BUDGET_MS, PARSE_SLICE_MS) : 0; const pumped = probe ? performance.now() - start : 0; for (const view of [...views]) { if (probe && view === keyView) drawKeyed(probe, view, pumped); @@ -92,7 +96,22 @@ function drawKeyed(p: Probe, view: View, pumped: number): void { keyMs = 0; } +type Task = { step(budgetMs: number): boolean }; +const tasks = new Set(); + +// Adds work the engine task slices after the engine's own, until the returned removal. +export function registerTask(task: Task): () => void { + tasks.add(task); + if (core) postEngine(); + return () => { + tasks.delete(task); + }; +} + let channel: MessageChannel | null = null; +// Engine time with no frame between, after which the engine waits for a frame: Safari paints only between task chains. +const ENGINE_BEFORE_FRAME_MS = 2 * PUMP_BUDGET_MS; +let lastFrame = 0; let engineQueued = false; function postEngine(): void { @@ -110,9 +129,15 @@ function postEngine(): void { function runEngine(): void { engineQueued = false; if (!core) return; - const start = probe ? performance.now() : 0; - const left = core._cpw_pump(PUMP_BUDGET_MS); + const start = performance.now(); + let left = core._cpw_pump(PUMP_BUDGET_MS, PARSE_SLICE_MS); + // Work outside the engine, like a search scan, takes what the frame has left, at least 1 ms each. + for (const task of [...tasks]) { + if (task.step(Math.max(1, PUMP_BUDGET_MS - (performance.now() - start)))) left++; + } if (probe) probe.tasks.push(performance.now() - start); if ([...views].some((v) => v.pending())) requestPump(); - if (left > 0) postEngine(); + if (left === 0) return; + if (performance.now() - lastFrame < ENGINE_BEFORE_FRAME_MS) postEngine(); + else requestPump(); } diff --git a/src/web/search.ts b/src/web/search.ts new file mode 100644 index 00000000..a2b415c5 --- /dev/null +++ b/src/web/search.ts @@ -0,0 +1,165 @@ +import type { SearchQuery } from '../types'; +import type { EditorCore, WebChange } from './core/EditorCore'; +import { registerTask } from './pump'; + +// Match pairs one core call writes, as Searcher.swift. +const BATCH = 4096; + +// Shifts the pairs past a change and drops the ones it touched, as SearchSession.kt. +export function mapThrough( + pairs: number[], + change: { start: number; end: number; delta: number }, +): number[] { + const out: number[] = []; + for (let i = 0; i + 1 < pairs.length; i += 2) { + const s = pairs[i] as number; + const e = pairs[i + 1] as number; + if (e <= change.start) out.push(s, e); + else if (s >= change.end) out.push(s + change.delta, e + change.delta); + } + return out; +} + +// Index of the first match ending after offset, else the count. +export function firstEndingAfter(pairs: number[], offset: number): number { + let lo = 0; + let hi = pairs.length / 2; + while (lo < hi) { + const mid = (lo + hi) >>> 1; + if ((pairs[mid * 2 + 1] as number) <= offset) lo = mid + 1; + else hi = mid; + } + return lo; +} + +type Job = { + query: number; + text: number; + revision: number; + scan: number; + out: number; + pairs: number[]; +}; + +// Scans a text snapshot in pump slices and hands the matches to the core, as SearchController.kt does on its worker. +export class SearchController { + private job: Job | null = null; + private displayed: number[] = []; + private readonly waiting: (() => void)[] = []; + private unregister: (() => void) | null = null; + private closed = false; + + constructor( + private readonly core: EditorCore, + private readonly onFresh: () => void, + ) {} + + // Throws SearchError for an invalid regex, which also clears the search. Null clears it. + setQuery(query: SearchQuery | null): void { + this.cancel(); + this.displayed = []; + if (query === null) { + this.core.clearSearch(); + this.runWaiting(); + return; + } + try { + this.core.setSearch({ + text: query.text, + regex: query.regex ?? false, + caseSensitive: query.caseSensitive ?? false, + wholeWord: query.wholeWord ?? false, + }); + } catch (e) { + this.runWaiting(); + throw e; + } + this.schedule(); + } + + onChange(change: WebChange): void { + if (!this.core.searchActive) return; + this.displayed = mapThrough(this.displayed, { + start: change.start, + end: change.start + change.removedLength, + delta: change.insertedLength - change.removedLength, + }); + this.schedule(); + } + + // Runs block now when nothing is stale, else once the next accepted result lands. + whenFresh(block: () => void): void { + if (this.core.searchStale) this.waiting.push(block); + else block(); + } + + matchesForPaint(): number[] { + return this.displayed; + } + + // One slice of the scan. True while work is left. + step(budgetMs: number): boolean { + const job = this.job; + if (!job) return false; + const m = this.core.m; + const scan = job.scan >> 2; + m.HEAP32[scan + 2] = Math.max(1, Math.floor(budgetMs)); + const n = m._cp_search_find(job.query, job.text, job.scan, job.out, BATCH * 2); + const out = job.out >> 2; + for (let i = 0; i < n; i++) job.pairs.push(m.HEAP32[out + i] as number); + if (m.HEAP32[scan] !== -1) return true; + this.finish(job, m.HEAP32[scan + 1] !== 0); + return false; + } + + // Settles every waiting continuation against the current state and frees the scan. + close(): void { + this.closed = true; + this.cancel(); + this.runWaiting(); + } + + private schedule(): void { + if (this.closed) return; + this.cancel(); + const query = this.core.searchQuery(); + if (!query) return; + const m = this.core.m; + const scan = m._malloc(12); + m.HEAP32.set([0, 0, 1], scan >> 2); + this.job = { + query, + text: this.core.textSnapshot(), + revision: this.core.revision, + scan, + out: m._malloc(BATCH * 2 * 4), + pairs: [], + }; + this.unregister ??= registerTask(this); + } + + private finish(job: Job, limited: boolean): void { + this.cancel(); + if (!this.core.acceptMatches(job.revision, job.pairs, limited)) return; + this.displayed = job.pairs; + this.runWaiting(); + this.onFresh(); + } + + private cancel(): void { + const job = this.job; + this.job = null; + this.unregister?.(); + this.unregister = null; + if (!job) return; + const m = this.core.m; + m._cp_search_release(job.query); + m._cp_text_release(job.text); + m._free(job.scan); + m._free(job.out); + } + + private runWaiting(): void { + for (const block of this.waiting.splice(0)) block(); + } +} diff --git a/tests/web/core.ts b/tests/web/core.ts index 57c69528..54860572 100644 --- a/tests/web/core.ts +++ b/tests/web/core.ts @@ -125,5 +125,5 @@ export function highlight( } export function pumpAll(m: RawCore, budgetMs = 8): void { - for (let i = 0; i < 100000 && m._cpw_pump(budgetMs) > 0; i++); + for (let i = 0; i < 100000 && m._cpw_pump(budgetMs, 0) > 0; i++); } diff --git a/tests/web/render.e2e.mjs b/tests/web/render.e2e.mjs index 795fe4fc..c8001448 100644 --- a/tests/web/render.e2e.mjs +++ b/tests/web/render.e2e.mjs @@ -430,6 +430,404 @@ for (const engine of [chromium, webkit]) { await page.close(); }); + test("a typed letter keeps its line's element", async () => { + const { page } = await open(); + await page.evaluate(() => window.codepad.ensureLanguage('python')); + await editor(page, 'a', 'def a():\n return b\n'); + await page.evaluate(async () => { + window.views.a.setLanguage('python'); + await window.codepad.until(() => window.views.a.core.snapshot !== 0); + }); + await clickAt(page, 'a', 1, 12); + await page.evaluate(() => { + window.kept = document.querySelector('#a [data-line="1"]'); + }); + await page.keyboard.type('x'); + const same = await page.evaluate(async () => { + const v = window.views.a; + await window.codepad.until(() => v.core.snapshot !== 0 && v.core.revision > 0); + await window.codepad.frames(3); + return document.querySelector('#a [data-line="1"]') === window.kept; + }); + assert.equal(await textOf(page, 'a'), 'def a():\n return bx\n'); + assert.equal(same, true); + await page.close(); + }); + + test('typing past the right edge keeps the caret in view without soft wrap', async () => { + const { page } = await open(); + await editor(page, 'a', 'x'); + await clickAt(page, 'a', 0, 1); + await page.keyboard.type('a'.repeat(90)); + const { x, width, textarea } = await page.evaluate(async () => { + const v = window.views.a; + await window.codepad.frames(2); + const caret = v.caretRect(v.core.selection.head); + return { + x: caret?.x ?? -1, + width: document.getElementById('a').clientWidth, + textarea: Number.parseFloat(document.querySelector('#a textarea').style.left), + }; + }); + assert.ok(x >= 0 && x <= width, `caret x ${x} of ${width}`); + // The keyboard's candidate window opens at the textarea. + assert.ok(Math.abs(textarea - x) <= 1, `textarea at ${textarea}, caret at ${x}`); + await page.close(); + }); + + // The box of a line element and the underline bars, relative to the editor's root. + const boxes = (page, id, selector) => + page.evaluate( + async ([id, selector]) => { + await window.codepad.frames(2); + const root = document.getElementById(id).firstElementChild.getBoundingClientRect(); + return [...document.querySelectorAll(`#${id} ${selector}`)].map((el) => { + const r = el.getBoundingClientRect(); + return { + top: r.top - root.top, + bottom: r.bottom - root.top, + left: r.left - root.left, + right: r.right - root.left, + }; + }); + }, + [id, selector], + ); + + test('a solid underline sits under its range, one bar per wrapped row', async () => { + const { page } = await open(); + await editor(page, 'a', `${'word '.repeat(60)}\nnext`, { softWrap: true }); + await page.evaluate(() => + window.views.a.setDecorations( + [{ kind: 'underline', range: { start: 10, end: 200 }, color: 'red' }], + -1, + ), + ); + const bars = await boxes(page, 'a', '[data-underline]'); + const [line] = await boxes(page, 'a', '[data-line="0"]'); + const row = await page.evaluate(() => window.views.a.layout.rowHeight); + assert.ok(bars.length >= 2, `${bars.length} bars`); + for (const b of bars) { + assert.ok(b.top > line.top && b.bottom <= line.bottom + 1, JSON.stringify({ b, line })); + assert.ok( + b.left >= line.left - 1 && b.right <= line.right + 1, + JSON.stringify({ b, line }), + ); + assert.equal(Math.round(b.top - bars[0].top) % row, 0); + } + await page.close(); + }); + + test('a wavy underline draws one path per row clipped to its range', async () => { + const { page } = await open(); + await editor(page, 'a', 'let total = 1'); + await page.evaluate(() => + window.views.a.setDecorations( + [{ kind: 'underline', range: { start: 4, end: 9 }, color: 'blue', style: 'wavy' }], + -1, + ), + ); + const [wave] = await boxes(page, 'a', 'svg[data-underline]'); + const width = await page.evaluate(() => { + const el = document.querySelector('#a [data-line="0"]'); + const range = document.createRange(); + range.setStart(el.firstChild, 4); + range.setEnd(el.firstChild, 9); + return range.getBoundingClientRect().width; + }); + assert.ok(wave, 'no wave'); + assert.ok( + Math.abs(wave.right - wave.left - width) <= 1, + `${wave.right - wave.left} for ${width}`, + ); + assert.equal( + await page.evaluate(() => document.querySelectorAll('#a svg[data-underline] path').length), + 1, + ); + await page.close(); + }); + + test('a line background tints every row of its line above the active line', async () => { + const { page } = await open(); + await editor(page, 'a', `one\n${'word '.repeat(60)}\nthree`, { softWrap: true }); + await page.evaluate(() => + window.views.a.setDecorations( + [{ kind: 'lineBackground', line: 1, color: 'rgb(255, 0, 0)' }], + -1, + ), + ); + const [bg] = await boxes(page, 'a', '[data-line-background]'); + const [line] = await boxes(page, 'a', '[data-line="1"]'); + assert.ok( + Math.abs(bg.top - line.top) <= 1 && Math.abs(bg.bottom - line.bottom) <= 1, + JSON.stringify({ bg, line }), + ); + const above = await page.evaluate(() => { + const active = document.querySelector('#a [data-active-line]'); + const tint = document.querySelector('#a [data-line-background]'); + return !!(active.compareDocumentPosition(tint) & Node.DOCUMENT_POSITION_FOLLOWING); + }); + assert.equal(above, true); + await page.close(); + }); + + test('a gap pushes the next line down by rows times the row height and onGapLayout reports it', async () => { + const { page } = await open(); + await editor(page, 'a', 'a\nb\nc'); + await page.evaluate(() => { + window.gapsSeen = []; + window.views.a.setOptions({ onGapLayout: (gaps) => window.gapsSeen.push(gaps) }); + window.views.a.setDecorations([{ kind: 'gap', line: 0, rows: 2 }], -1); + }); + const [first] = await boxes(page, 'a', '[data-line="0"]'); + const [second] = await boxes(page, 'a', '[data-line="1"]'); + const row = await page.evaluate(() => window.views.a.layout.rowHeight); + assert.ok( + Math.abs(second.top - first.top - 3 * row) <= 1, + `${second.top - first.top} for ${3 * row}`, + ); + const last = await page.evaluate(() => window.gapsSeen.at(-1)); + assert.equal(last.length, 1); + assert.equal(last[0].line, 0); + assert.ok(Math.abs(last[0].rect.y - (first.top + row)) <= 1, JSON.stringify(last[0])); + assert.equal(last[0].rect.height, 2 * row); + assert.equal(last[0].rect.x, 0); + await page.close(); + }); + + test('a gap scrolled into view fires onGapLayout again', async () => { + const { page } = await open(); + await editor(page, 'a', Array.from({ length: 200 }, (_, i) => `line ${i}`).join('\n')); + const before = await page.evaluate(async () => { + window.gapsSeen = []; + window.views.a.setOptions({ onGapLayout: (gaps) => window.gapsSeen.push(gaps) }); + window.views.a.setDecorations([{ kind: 'gap', line: 150, rows: 2 }], -1); + await window.codepad.frames(2); + return { count: window.gapsSeen.length, y: window.gapsSeen.at(-1)[0].rect.y }; + }); + const after = await page.evaluate(async () => { + window.views.a.scrollToLine(140); + await window.codepad.frames(3); + return { count: window.gapsSeen.length, y: window.gapsSeen.at(-1)[0].rect.y }; + }); + assert.ok(after.count > before.count, JSON.stringify({ before, after })); + assert.ok(after.y < before.y, JSON.stringify({ before, after })); + await page.close(); + }); + + test('getGapRect is null for a line with no gap', async () => { + const { page } = await open(); + await editor(page, 'a', 'a\nb\nc'); + const rects = await page.evaluate(async () => { + window.views.a.setDecorations([{ kind: 'gap', line: 0, rows: 1 }], -1); + await window.codepad.frames(2); + return [window.views.a.gapRect(0), window.views.a.gapRect(1)]; + }); + assert.notEqual(rects[0], null); + assert.equal(rects[1], null); + await page.close(); + }); + + test('a gap under the last line grows the content height', async () => { + const { page } = await open(); + await editor(page, 'a', 'a\nb'); + const grew = await page.evaluate(async () => { + const v = window.views.a; + await window.codepad.frames(1); + const before = v.layout.contentHeight; + v.setDecorations([{ kind: 'gap', line: 1, rows: 3 }], -1); + await window.codepad.frames(2); + return { before, after: v.layout.contentHeight, row: v.layout.rowHeight }; + }); + assert.equal(grew.after - grew.before, 3 * grew.row); + await page.close(); + }); + + test('a click inside a gap leaves the caret where it was', async () => { + const { page } = await open(); + await editor(page, 'a', 'abc\ndef'); + await page.evaluate(async () => { + const v = window.views.a; + v.setDecorations([{ kind: 'gap', line: 0, rows: 3 }], -1); + v.apply(() => v.core.setSelection(1, 1)); + await window.codepad.frames(2); + }); + const [first] = await boxes(page, 'a', '[data-line="0"]'); + const row = await page.evaluate(() => window.views.a.layout.rowHeight); + const root = await page.evaluate(() => { + const r = document.getElementById('a').firstElementChild.getBoundingClientRect(); + return { left: r.left, top: r.top }; + }); + await page.mouse.click(root.left + first.left + 10, root.top + first.top + 2.5 * row); + assert.equal(await page.evaluate(() => window.views.a.core.selection.head), 1); + await page.close(); + }); + + test('decorations made for an older revision follow the edits since', async () => { + const { page } = await open(); + await editor(page, 'a', 'hello world'); + const range = await page.evaluate(() => { + const v = window.views.a; + const old = v.core.revision; + v.apply(() => v.core.replace(0, 0, 'XX')); + v.setDecorations([{ kind: 'underline', range: { start: 6, end: 11 }, color: 'red' }], old); + return v.core.decorations()[0].range; + }); + assert.deepEqual(range, { start: 8, end: 13 }); + await page.close(); + }); + + test('decorations for a revision more than 256 edits back keep the current set', async () => { + const { page } = await open(); + await editor(page, 'a', 'hello'); + const kept = await page.evaluate(() => { + const v = window.views.a; + const old = v.core.revision; + v.setDecorations([{ kind: 'lineBackground', line: 0, color: 'red' }], -1); + for (let i = 0; i < 300; i++) v.apply(() => v.core.replace(0, 0, 'x')); + v.setDecorations([{ kind: 'gap', line: 0, rows: 2 }], old); + return v.core.decorations().map((d) => d.kind); + }); + assert.deepEqual(kept, ['lineBackground']); + await page.close(); + }); + + test('matches paint under the text and the one equal to the selection in the active color', async () => { + const { page } = await open(); + await editor(page, 'a', 'ab ab ab'); + const painted = await page.evaluate(async () => { + const v = window.views.a; + await v.setSearch({ text: 'ab' }); + await v.findNext(); + await window.codepad.frames(2); + return { + all: document.querySelectorAll('#a [data-match]').length, + active: document.querySelectorAll('#a [data-match-active]').length, + }; + }); + assert.deepEqual(painted, { all: 3, active: 1 }); + await page.close(); + }); + + test('setSearch resolves the count and limited', async () => { + const { page } = await open(); + await editor(page, 'a', 'ab ab ab'); + const result = await page.evaluate(() => window.views.a.setSearch({ text: 'ab' })); + assert.deepEqual(result, { count: 3, limited: false }); + await page.close(); + }); + + test('setSearch with a bad regex rejects with the message, clears the painted matches, and findNext then resolves null', async () => { + const { page } = await open(); + await editor(page, 'a', 'ab ab ab'); + const out = await page.evaluate(async () => { + const v = window.views.a; + await v.setSearch({ text: 'ab' }); + let message = ''; + try { + await v.setSearch({ text: '(', regex: true }); + } catch (e) { + message = e.message; + } + await window.codepad.frames(2); + return { + message, + painted: document.querySelectorAll('#a [data-match]').length, + hit: await v.findNext(), + }; + }); + assert.ok(out.message.length > 0, 'no message'); + assert.equal(out.painted, 0); + assert.equal(out.hit, null); + await page.close(); + }); + + test('findNext after an edit waits for fresh matches and selects one in the new text', async () => { + const { page } = await open(); + await editor(page, 'a', 'x ab'); + const out = await page.evaluate(async () => { + const v = window.views.a; + await v.setSearch({ text: 'ab' }); + v.apply(() => v.core.replace(0, 0, 'ab ')); + v.apply(() => v.core.setSelection(0, 0)); + const hit = await v.findNext(); + return { hit, selection: v.core.selection }; + }); + assert.deepEqual(out.hit, { index: 0, total: 2 }); + assert.deepEqual(out.selection, { anchor: 0, head: 2 }); + await page.close(); + }); + + test('replaceAll is one undo step and resolves with the count', async () => { + const { page } = await open(); + await editor(page, 'a', 'ab ab ab'); + const out = await page.evaluate(async () => { + const v = window.views.a; + await v.setSearch({ text: 'ab' }); + const n = await v.replaceAll('X'); + const after = v.core.text(); + v.apply(() => v.core.undo()); + return { n, after, undone: v.core.text() }; + }); + assert.deepEqual(out, { n: 3, after: 'X X X', undone: 'ab ab ab' }); + await page.close(); + }); + + test('replaceCurrent is false when the selection is not a match', async () => { + const { page } = await open(); + await editor(page, 'a', 'ab ab'); + const replaced = await page.evaluate(async () => { + const v = window.views.a; + await v.setSearch({ text: 'ab' }); + return v.replaceCurrent('X'); + }); + assert.equal(replaced, false); + assert.equal(await textOf(page, 'a'), 'ab ab'); + await page.close(); + }); + + test('clearSearch removes the painted matches', async () => { + const { page } = await open(); + await editor(page, 'a', 'ab ab'); + const painted = await page.evaluate(async () => { + const v = window.views.a; + await v.setSearch({ text: 'ab' }); + await window.codepad.frames(2); + const before = document.querySelectorAll('#a [data-match]').length; + await v.clearSearch(); + await window.codepad.frames(2); + return [before, document.querySelectorAll('#a [data-match]').length]; + }); + assert.deepEqual(painted, [2, 0]); + await page.close(); + }); + + test('frames keep landing while another editor scans a long text', async () => { + const { page } = await open(); + await editor(page, 'a', 'one'); + await editor(page, 'b', Array.from({ length: 20000 }, () => 'word '.repeat(20)).join('\n')); + const out = await page.evaluate(async () => { + let frames = 0; + let longest = 0; + let last = performance.now(); + let counting = true; + const tick = (t) => { + frames++; + longest = Math.max(longest, t - last); + last = t; + if (counting) requestAnimationFrame(tick); + }; + requestAnimationFrame(tick); + const result = await window.views.b.setSearch({ text: '\\w+', regex: true }); + counting = false; + return { frames, longest, count: result.count }; + }); + assert.equal(out.count, 400000); + assert.ok(out.frames >= 5, JSON.stringify(out)); + assert.ok(out.longest < 100, JSON.stringify(out)); + await page.close(); + }); + test('the frame after a letter, an Enter and a joining Backspace keeps the keyword colors', async () => { const { page } = await open(); await page.evaluate(async () => {