Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 8 additions & 4 deletions example/src/EditorApp.web.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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.
<Pressable onPress={onPress} role="button" style={[styles.chip, on && styles.chipOn]}>
<Pressable
onPress={onPress}
role="button"
{...((on === undefined ? {} : { 'aria-pressed': on }) as object)}
style={[styles.chip, on && styles.chipOn]}
>
<Text style={[styles.chipText, on && styles.chipTextOn]}>{label}</Text>
</Pressable>
);
Expand Down Expand Up @@ -100,7 +106,6 @@ export function EditorApp() {
))}
<Chip
label={THEMES[themeIndex % THEMES.length]?.label ?? ''}
on={false}
onPress={() => setThemeIndex((i) => i + 1)}
/>
<Chip
Expand All @@ -119,7 +124,6 @@ export function EditorApp() {
<Chip
key={action}
label={action}
on={false}
onPress={() =>
editor.current?.[action]().then(
() => setStatus(` done`),
Expand Down
25 changes: 14 additions & 11 deletions src/web/CodeEditor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -74,17 +74,20 @@ export const CodeEditor = forwardRef<CodeEditorRef, CodeEditorProps>(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(() => {
Comment thread
SectionTN marked this conversation as resolved.
Resolved
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.
Expand Down
10 changes: 8 additions & 2 deletions src/web/__tests__/CodeEditor.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -221,14 +221,19 @@ 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<never>(() => {});
function Hold({ wait }: { wait: boolean }) {
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);
Expand All @@ -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}
/>
<Hold wait={items !== shown} />
</Suspense>
Expand All @@ -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 () => {
Expand Down
132 changes: 88 additions & 44 deletions src/web/__tests__/pump.test.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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<string[][]> {
turns = [];
const reached = new Promise<void>((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<string[][]> {
turns = [];
const reached = new Promise<void>((done) => {
counted = { count, done };
});
const removals = new Map<string, () => void>();
// One object per task registered again as itself, as a search controller does.
const objects = new Map<string, { step(): boolean }>();
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'],
]);
});
});
21 changes: 12 additions & 9 deletions src/web/pump.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,14 +107,16 @@ function drawKeyed(p: Probe, view: View, pumped: number): void {
}

type Task = { step(budgetMs: number): boolean };
const tasks = new Set<Task>();
// 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);
};
}

Expand Down Expand Up @@ -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();
Expand Down
12 changes: 11 additions & 1 deletion tests/web/render.e2e.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
Loading