diff --git a/example/src/EditorApp.web.tsx b/example/src/EditorApp.web.tsx index b3e9478..119df4c 100644 --- a/example/src/EditorApp.web.tsx +++ b/example/src/EditorApp.web.tsx @@ -16,7 +16,8 @@ const NO_DECORATIONS: { items: Decoration[]; revision: number } = { items: [], r function Chip({ label, on, onPress }: { label: string; on: boolean; onPress: () => void }) { return ( - + // react-native-web gives Space to a Pressable only with the button role. + {label} ); diff --git a/example/src/chrome/FindBar.web.tsx b/example/src/chrome/FindBar.web.tsx index 0d8ee69..e21a525 100644 --- a/example/src/chrome/FindBar.web.tsx +++ b/example/src/chrome/FindBar.web.tsx @@ -23,7 +23,8 @@ export function FindBar({ scheme, editor, onStatus, onClose }: FindBarProps) { return ( - + {/* A live region, so a screen reader reads the new count while focus stays in the query. */} + {count ? `${index || '-'} of ${count}` : 'no results'} {button('.*', 'Regular expression', () => find.toggle('regex'), find.options.regex)} diff --git a/src/web/CodeEditor.tsx b/src/web/CodeEditor.tsx index 8a38075..6d06f94 100644 --- a/src/web/CodeEditor.tsx +++ b/src/web/CodeEditor.tsx @@ -5,6 +5,7 @@ import { useCallback, useEffect, useImperativeHandle, + useLayoutEffect, useMemo, useRef, useState, @@ -154,7 +155,10 @@ export const CodeEditor = forwardRef(function Co ], ); const latest = useRef({ options, language, decorations, decorationsRevision }); - latest.current = { options, language, decorations, decorationsRevision }; + // Written on commit, so the props of a render React drops never reach the view. + useLayoutEffect(() => { + 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) => { diff --git a/src/web/EditorView.ts b/src/web/EditorView.ts index 85ec710..c6b6b51 100644 --- a/src/web/EditorView.ts +++ b/src/web/EditorView.ts @@ -100,6 +100,8 @@ function browserClipboard(): Clipboard { 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]/; +// Rows of '0' widths the visible span reaches past the rows its probes find, enough for a row of Arial's narrowest letters. +const SPAN_ROWS = 3; const MOVES: Partial> = { left: ['char', false], right: ['char', true], @@ -406,6 +408,11 @@ export class EditorView { // The document offset under a page point, or null outside the drawn text. offsetAt(clientX: number, clientY: number): number | null { if (this.destroyed) return null; + return this.textOffsetAt(clientX, clientY) ?? this.offsetBeside(clientX, clientY); + } + + // The offset of the drawn text under a page point, or null when the point is not on a line. + private textOffsetAt(clientX: number, clientY: number): number | null { const d = document as Document & { caretPositionFromPoint?(x: number, y: number): { offsetNode: Node; offset: number } | null; caretRangeFromPoint?(x: number, y: number): Range | null; @@ -424,9 +431,7 @@ export class EditorView { } } const el = (node instanceof Element ? node : node?.parentElement)?.closest('[data-line]'); - if (!node || !(el instanceof HTMLElement) || !this.textLayer.contains(el)) { - return this.offsetBeside(clientX, clientY); - } + if (!node || !(el instanceof HTMLElement) || !this.textLayer.contains(el)) return null; const line = Number(el.dataset.line); const column = columnOf(el, node, offset); return this.core.lineStart(line) + Math.min(column, this.core.line(line).length); @@ -1110,6 +1115,8 @@ export class EditorView { for (let line = Math.max(this.core.lineAt(s), first); line <= end; line++) { const start = this.core.lineStart(line); const stop = this.core.lineEnd(line); + let a = Math.max(s, start); + let b = Math.min(e, stop); if (stop - start > screen) { clipped = true; let view: [number, number] | undefined; @@ -1122,12 +1129,15 @@ export class EditorView { } } if (e < view[0] || s > view[1]) continue; + // A wrapped match measures only its rows in view. Right-to-left text keeps the whole match, as in shownColumns. + const over = a < view[0] || b > view[1] + 1; + if (over && layout.wrapWidth > 0 && !RTL_TEXT.test(this.cache.get(line)?.text ?? '')) { + a = Math.max(a, view[0]); + b = Math.min(b, view[1] + 1); + if (b <= a) continue; + } } - const part: [number, number, boolean] = [ - Math.max(s, start) - start, - Math.min(e, stop) - start, - active, - ]; + const part: [number, number, boolean] = [a - start, b - start, active]; const list = parts.get(line); if (list) list.push(part); else parts.set(line, [part]); @@ -1167,17 +1177,21 @@ export class EditorView { const lo = this.core.lineStart(first); const hi = this.core.lineEnd(last); const layout = this.layout; - const left = rootBox.left + layout.textAreaLeft; - const right = left + layout.wrapWidth - 2; + // Both probes sit on the lines' left edge, clear of an overlay scrollbar, and find the top and bottom rows in view. + const x = rootBox.left + layout.textAreaLeft + layout.textPadding + 1; // The last drawn line's bottom, so a short document is hit on its text and not below it. const lastEl = this.attached.has(last) ? this.cache.get(last)?.el : undefined; const lastBottom = lastEl ? lastEl.getBoundingClientRect().bottom : Number.POSITIVE_INFINITY; const top = Math.max(rootBox.top, 0) + 1; const bottom = Math.min(rootBox.bottom, window.innerHeight, lastBottom) - 2; if (top >= bottom) return [0, -1]; - const a = this.offsetAt(left + 1, top); - const b = this.offsetAt(right, bottom); - return [a === null ? lo : Math.max(lo, a), b === null ? hi : Math.min(hi, b)]; + // A probe off the text keeps the drawn window's end on its side, so a miss widens the span. + const a = this.textOffsetAt(x, top); + const b = this.textOffsetAt(x, bottom); + const reach = SPAN_ROWS * Math.ceil(layout.wrapWidth / Math.max(1, this.charWidth)); + const from = a === null ? lo : Math.max(lo, a - reach); + const to = b === null ? hi : Math.min(hi, b + reach); + return to < from ? [lo, hi] : [from, to]; } // The offsets of an unwrapped line between the text area's edges. Right-to-left text keeps the whole line. diff --git a/src/web/__tests__/CodeEditor.test.tsx b/src/web/__tests__/CodeEditor.test.tsx index fd5d09b..e276936 100644 --- a/src/web/__tests__/CodeEditor.test.tsx +++ b/src/web/__tests__/CodeEditor.test.tsx @@ -1,6 +1,6 @@ import { beforeEach, expect, jest, test } from '@jest/globals'; import { act, render } from '@testing-library/react-native'; -import { createRef } from 'react'; +import { createRef, Suspense, startTransition, use, useState } from 'react'; import type { CodeEditorRef } from '../../types'; import type { ViewOptions } from '../EditorView'; @@ -221,6 +221,44 @@ test('decorations passed at mount are on the view when it first draws, and sent expect(mockViews[0]?.setDecorations).toHaveBeenCalledTimes(1); }); +test('a render that never commits keeps its decorations and options off the first draw', async () => { + const shown = [{ kind: 'gap' as const, line: 0, rows: 1 }]; + const pending = [{ kind: 'gap' as const, line: 1, rows: 2 }]; + const never = new Promise(() => {}); + function Hold({ wait }: { wait: boolean }) { + if (wait) use(never); + return null; + } + let update: (items: typeof shown) => void = () => {}; + function App() { + const [items, setItems] = useState(shown); + update = setItems; + return ( + + + + + ); + } + await render(); + // The transition renders the editor with the pending props, then suspends on Hold and never commits. + await act(async () => { + startTransition(() => update(pending)); + await tick(); + }); + await act(async () => { + mockCore.resolve({}); + await tick(); + }); + expect(mockViews[0]?.setDecorations.mock.calls[0]).toEqual([shown, 0]); + expect(mockViews[0]?.setDecorations).toHaveBeenCalledTimes(1); + expect(mockViews[0]?.options.fontSize).toBe(14); +}); + test('decorations without a revision are for the current text', async () => { const items = [{ kind: 'lineBackground' as const, line: 1, color: 'red' }]; await render(); diff --git a/src/web/__tests__/pump.test.ts b/src/web/__tests__/pump.test.ts index 5c0501a..ba69b32 100644 --- a/src/web/__tests__/pump.test.ts +++ b/src/web/__tests__/pump.test.ts @@ -4,6 +4,8 @@ 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'; +import type { CoreModule } from '../core/module'; +import { registerTask, setPumpCore } from '../pump'; const dir = builtCore('lib/web', 'yarn build:web'); const javascript = join(ROOT, 'languages/javascript/web/javascript.wasm'); @@ -32,3 +34,52 @@ const now = () => Number(process.hrtime.bigint()) / 1e6; core.close(); pumpAll(m); }); + +// Each engine turn as the list of tasks it stepped, with the engine taking engineMs of the turn. +let engineMs = 0; +let turns: string[][] = []; +// Resolves at the start of the turn after the ones counted, since engine turns can starve a timer. +let counted: { count: number; done: () => void } | null = null; +// The pump falls back to timers, since an open MessagePort keeps jest from exiting. +(globalThis as { MessageChannel?: unknown }).MessageChannel = undefined; +setPumpCore({ + _cpw_pump: () => { + if (counted && turns.length === counted.count) counted.done(); + turns.push([]); + const end = now() + engineMs; + while (now() < end); + return 0; + }, +} as unknown as CoreModule); + +async function runTasks(names: string[], count: number): Promise { + turns = []; + const reached = new Promise((done) => { + counted = { count, done }; + }); + const removals = names.map((name) => + registerTask({ + step: () => { + turns.at(-1)?.push(name); + return true; + }, + }), + ); + await reached; + counted = null; + for (const remove of removals) remove(); + return turns.slice(0, count); +} + +test('a turn whose engine used the whole budget steps one task, the next in line each turn', async () => { + engineMs = 8; + expect(await runTasks(['a', 'b', 'c'], 4)).toEqual([['a'], ['b'], ['c'], ['a']]); +}); + +test('a turn the engine left time in steps every task', async () => { + engineMs = 0; + expect(await runTasks(['a', 'b', 'c'], 2)).toEqual([ + ['a', 'b', 'c'], + ['a', 'b', 'c'], + ]); +}); diff --git a/src/web/pump.ts b/src/web/pump.ts index 847d1b6..47e1267 100644 --- a/src/web/pump.ts +++ b/src/web/pump.ts @@ -141,9 +141,20 @@ function runEngine(): void { if (!core) return; 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. + // Work outside the engine, like a search scan, shares what the engine left. Only the first task in line gets 1 ms past it. + let stepped = false; for (const task of [...tasks]) { - if (task.step(Math.max(1, PUMP_BUDGET_MS - (performance.now() - start)))) left++; + if (!tasks.has(task)) continue; + const budget = PUMP_BUDGET_MS - (performance.now() - start); + if (stepped && budget <= 0) { + left++; + continue; + } + stepped = true; + // To the back of the line, so the next turn starts with a task this one skipped. A task that finishes removes itself. + tasks.delete(task); + tasks.add(task); + if (task.step(Math.max(1, budget))) left++; } if (probe) probe.tasks.push(performance.now() - start); if ([...views].some((v) => v.pending())) requestPump(); diff --git a/tests/web/render.e2e.mjs b/tests/web/render.e2e.mjs index aff475c..53fa978 100644 --- a/tests/web/render.e2e.mjs +++ b/tests/web/render.e2e.mjs @@ -1138,9 +1138,17 @@ for (const engine of [chromium, webkit]) { a.scroller.scrollTop = 1500; b.scroller.scrollLeft = 4000; await window.codepad.frames(3); - return { wrapped, unwrapped, inA: inBox('a'), inB: inBox('b'), scrolledB: count('b') }; + return { + wrapped, + unwrapped, + inA: inBox('a'), + inB: inBox('b'), + scrolledA: count('a'), + scrolledB: count('b'), + }; }); assert.ok(painted.wrapped < 500, `wrapped ${painted.wrapped}`); + assert.ok(painted.scrolledA < 500, `wrapped after the scroll ${painted.scrolledA}`); assert.ok(painted.unwrapped < 300, `unwrapped ${painted.unwrapped}`); assert.ok(painted.inA > 0, `marks in view after the scroll down ${painted.inA}`); assert.ok(painted.inB > 0, `marks in view after the scroll right ${painted.inB}`); @@ -1148,6 +1156,39 @@ for (const engine of [chromium, webkit]) { await page.close(); }); + test('one match over a long wrapped line marks only the rows in view, and the rows a scroll brings in', async () => { + const { page } = await open(); + await editor(page, 'a', 'a'.repeat(100_000), { softWrap: true }); + const out = await page.evaluate(async () => { + const v = window.views.a; + await v.setSearch({ text: 'a+', regex: true }); + await window.codepad.frames(2); + const marks = () => [...document.querySelectorAll('#a [data-match]')]; + // Whether the first and last visible rows of the line each sit under a mark. + const covered = () => { + const root = document.getElementById('a').getBoundingClientRect(); + const line = document.querySelector('#a [data-line="0"]').getBoundingClientRect(); + const rects = marks().map((m) => m.getBoundingClientRect()); + const at = (y) => rects.some((r) => r.top <= y && r.bottom >= y); + const half = v.rowHeight / 2; + return [ + at(Math.max(root.top, line.top) + half), + at(Math.min(root.bottom, line.bottom) - half), + ]; + }; + const first = marks().length; + const top = covered(); + v.scroller.scrollTop = 20_000; + await window.codepad.frames(3); + return { first, top, scrolled: marks().length, after: covered() }; + }); + assert.ok(out.first < 200, `marks before the scroll ${out.first}`); + assert.deepEqual(out.top, [true, true]); + assert.ok(out.scrolled < 200, `marks after the scroll ${out.scrolled}`); + assert.deepEqual(out.after, [true, true]); + await page.close(); + }); + test('replacing a match with the same text keeps a caret on its line', async () => { const { page } = await open(); await page.evaluate(() => window.codepad.ensureLanguage('python'));