diff --git a/example/src/EditorApp.web.tsx b/example/src/EditorApp.web.tsx index 119df4c..e56bb00 100644 --- a/example/src/EditorApp.web.tsx +++ b/example/src/EditorApp.web.tsx @@ -14,10 +14,16 @@ 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 }) { +// A toggle passes on, an action leaves it out. react-native-web forwards aria-pressed, which React Native's types lack. +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} ); @@ -100,7 +106,6 @@ export function EditorApp() { ))} setThemeIndex((i) => i + 1)} /> editor.current?.[action]().then( () => setStatus(` done`), diff --git a/src/web/CodeEditor.tsx b/src/web/CodeEditor.tsx index 6d06f94..a90eabe 100644 --- a/src/web/CodeEditor.tsx +++ b/src/web/CodeEditor.tsx @@ -74,17 +74,20 @@ export const CodeEditor = forwardRef(function Co onBlur, onGapLayout, }); - handlers.current = { - onReady, - onScroll, - onSelectionChange, - onChange, - onChangeText, - onContentSizeChange, - onFocus, - onBlur, - onGapLayout, - }; + // Written on commit, so a render React drops never calls its handlers. + useLayoutEffect(() => { + handlers.current = { + onReady, + onScroll, + onSelectionChange, + onChange, + onChangeText, + onContentSizeChange, + onFocus, + onBlur, + onGapLayout, + }; + }); const initial = useRef(initialValue); // The callbacks read the latest handlers and the view through refs, so the object only follows the props. diff --git a/src/web/__tests__/CodeEditor.test.tsx b/src/web/__tests__/CodeEditor.test.tsx index e276936..304fa7e 100644 --- a/src/web/__tests__/CodeEditor.test.tsx +++ b/src/web/__tests__/CodeEditor.test.tsx @@ -221,7 +221,7 @@ 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 () => { +test('a render that never commits keeps its decorations, options and handlers 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(() => {}); @@ -229,6 +229,11 @@ test('a render that never commits keeps its decorations and options off the firs if (wait) use(never); return null; } + // Which render's onReady ran, with the font size the view had at its first draw. + const ready: [string, number | undefined][] = []; + const readyFrom = (name: string) => () => ready.push([name, mockViews[0]?.options.fontSize]); + const committedReady = readyFrom('committed'); + const droppedReady = readyFrom('dropped'); let update: (items: typeof shown) => void = () => {}; function App() { const [items, setItems] = useState(shown); @@ -239,6 +244,7 @@ test('a render that never commits keeps its decorations and options off the firs decorations={items} decorationsRevision={0} fontSize={items === shown ? 14 : 20} + onReady={items === shown ? committedReady : droppedReady} /> @@ -256,7 +262,7 @@ test('a render that never commits keeps its decorations and options off the firs }); expect(mockViews[0]?.setDecorations.mock.calls[0]).toEqual([shown, 0]); expect(mockViews[0]?.setDecorations).toHaveBeenCalledTimes(1); - expect(mockViews[0]?.options.fontSize).toBe(14); + expect(ready).toEqual([['committed', 14]]); }); test('decorations without a revision are for the current text', async () => { diff --git a/src/web/__tests__/pump.test.ts b/src/web/__tests__/pump.test.ts index ba69b32..5023915 100644 --- a/src/web/__tests__/pump.test.ts +++ b/src/web/__tests__/pump.test.ts @@ -1,6 +1,6 @@ import { existsSync } from 'node:fs'; import { join } from 'node:path'; -import { expect, test } from '@jest/globals'; +import { afterAll, beforeAll, describe, expect, jest, 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'; @@ -35,51 +35,95 @@ const now = () => Number(process.hrtime.bigint()) / 1e6; 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 }; +describe('engine tasks', () => { + // A clock only the engine and the tasks move, so a paused test worker cannot change a turn. + let clock = 0; + // 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; + beforeAll(() => { + jest.spyOn(performance, 'now').mockImplementation(() => clock); + // 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([]); + clock += engineMs; + return 0; + }, + } as unknown as CoreModule); }); - const removals = names.map((name) => - registerTask({ - step: () => { - turns.at(-1)?.push(name); + afterAll(() => { + jest.restoreAllMocks(); + }); + + // A task takes cost ms of the clock. once runs on its first step and can register a task again. + type Spec = { name: string; cost?: number; once?: (again: (name: string) => void) => void }; + + async function runTasks(specs: Spec[], count: number): Promise { + turns = []; + const reached = new Promise((done) => { + counted = { count, done }; + }); + const removals = new Map void>(); + // One object per task registered again as itself, as a search controller does. + const objects = new Map(); + for (const spec of specs) { + let once = spec.once; + const step = () => { + turns.at(-1)?.push(spec.name); + clock += spec.cost ?? 0; + const run = once; + once = undefined; + run?.((name) => { + removals.get(name)?.(); + const again = objects.get(name); + if (again) removals.set(name, registerTask(again)); + }); return true; - }, - }), - ); - await reached; - counted = null; - for (const remove of removals) remove(); - return turns.slice(0, count); -} + }; + objects.set(spec.name, { step }); + } + for (const [name, task] of objects) removals.set(name, registerTask(task)); + await reached; + counted = null; + for (const remove of removals.values()) 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']]); -}); + const named = (...names: string[]) => names.map((name) => ({ name })); -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'], - ]); + test('a turn whose engine used the whole budget steps one task, the next in line each turn', async () => { + engineMs = 8; + expect(await runTasks(named('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(named('a', 'b', 'c'), 2)).toEqual([ + ['a', 'b', 'c'], + ['a', 'b', 'c'], + ]); + }); + + test('a task after the first waits for the next turn when less than 1 ms is left', async () => { + engineMs = 0; + const specs = [{ name: 'a', cost: 5.5 }, ...named('b', 'c')]; + expect(await runTasks(specs, 2)).toEqual([['a'], ['b', 'c', 'a']]); + }); + + test('a task registered again during a turn waits for the next turn, not its old place', async () => { + engineMs = 0; + const specs = [ + { name: 'a', once: (again: (name: string) => void) => again('b') }, + ...named('b', 'c'), + ]; + expect(await runTasks(specs, 2)).toEqual([ + ['a', 'c'], + ['a', 'b', 'c'], + ]); + }); }); diff --git a/src/web/pump.ts b/src/web/pump.ts index 47e1267..a8806ca 100644 --- a/src/web/pump.ts +++ b/src/web/pump.ts @@ -107,14 +107,16 @@ function drawKeyed(p: Probe, view: View, pumped: number): void { } type Task = { step(budgetMs: number): boolean }; -const tasks = new Set(); +// One entry per registration, so a task registered again mid-turn is not stepped in its old place. +const tasks = new Set<{ task: Task }>(); // Adds work the engine task slices after the engine's own, until the returned removal. export function registerTask(task: Task): () => void { - tasks.add(task); + const entry = { task }; + tasks.add(entry); if (core) postEngine(); return () => { - tasks.delete(task); + tasks.delete(entry); }; } @@ -143,18 +145,19 @@ function runEngine(): void { let left = core._cpw_pump(PUMP_BUDGET_MS, PARSE_SLICE_MS); // 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 (!tasks.has(task)) continue; + for (const entry of [...tasks]) { + if (!tasks.has(entry)) continue; const budget = PUMP_BUDGET_MS - (performance.now() - start); - if (stepped && budget <= 0) { + // After the first task, one that would not get a whole millisecond waits for the next turn. + if (stepped && budget < 1) { 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++; + tasks.delete(entry); + tasks.add(entry); + if (entry.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 53fa978..e24a56d 100644 --- a/tests/web/render.e2e.mjs +++ b/tests/web/render.e2e.mjs @@ -1176,14 +1176,24 @@ for (const engine of [chromium, webkit]) { at(Math.min(root.bottom, line.bottom) - half), ]; }; + const lineTop = () => + document.querySelector('#a [data-line="0"]').getBoundingClientRect().top; const first = marks().length; const top = covered(); + const before = lineTop(); v.scroller.scrollTop = 20_000; await window.codepad.frames(3); - return { first, top, scrolled: marks().length, after: covered() }; + return { + first, + top, + moved: before - lineTop(), + 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.moved > 10_000, `the line moved ${out.moved} px`); assert.ok(out.scrolled < 200, `marks after the scroll ${out.scrolled}`); assert.deepEqual(out.after, [true, true]); await page.close();