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
3 changes: 2 additions & 1 deletion example/src/EditorApp.web.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
<Pressable onPress={onPress} style={[styles.chip, on && styles.chipOn]}>
// react-native-web gives Space to a Pressable only with the button role.
<Pressable onPress={onPress} role="button" style={[styles.chip, on && styles.chipOn]}>
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
<Text style={[styles.chipText, on && styles.chipTextOn]}>{label}</Text>
</Pressable>
);
Expand Down
3 changes: 2 additions & 1 deletion example/src/chrome/FindBar.web.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@ export function FindBar({ scheme, editor, onStatus, onClose }: FindBarProps) {
return (
<View style={styles.bar}>
<TextInput placeholder="Find" style={field} onChangeText={find.setQuery} autoFocus />
<Text style={[styles.label, { color }]}>
{/* A live region, so a screen reader reads the new count while focus stays in the query. */}
<Text aria-live="polite" style={[styles.label, { color }]}>
{count ? `${index || '-'} of ${count}` : 'no results'}
</Text>
{button('.*', 'Regular expression', () => find.toggle('regex'), find.options.regex)}
Expand Down
6 changes: 5 additions & 1 deletion src/web/CodeEditor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
useCallback,
useEffect,
useImperativeHandle,
useLayoutEffect,
useMemo,
useRef,
useState,
Expand Down Expand Up @@ -154,7 +155,10 @@ export const CodeEditor = forwardRef<CodeEditorRef, CodeEditorProps>(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) => {
Expand Down
40 changes: 27 additions & 13 deletions src/web/EditorView.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Record<CaretDirection, [MoveUnit, boolean]>> = {
left: ['char', false],
right: ['char', true],
Expand Down Expand Up @@ -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;
Expand All @@ -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);
Expand Down Expand Up @@ -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;
Expand All @@ -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]);
Expand Down Expand Up @@ -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.
Expand Down
40 changes: 39 additions & 1 deletion src/web/__tests__/CodeEditor.test.tsx
Original file line number Diff line number Diff line change
@@ -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';

Expand Down Expand Up @@ -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<never>(() => {});
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 (
<Suspense fallback={null}>
<CodeEditor
decorations={items}
decorationsRevision={0}
fontSize={items === shown ? 14 : 20}
/>
<Hold wait={items !== shown} />
</Suspense>
);
}
await render(<App />);
// 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);
Comment thread
SectionTN marked this conversation as resolved.
Resolved
});

test('decorations without a revision are for the current text', async () => {
const items = [{ kind: 'lineBackground' as const, line: 1, color: 'red' }];
await render(<CodeEditor decorations={items} />);
Expand Down
51 changes: 51 additions & 0 deletions src/web/__tests__/pump.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down Expand Up @@ -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);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
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 };
});
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'],
]);
});
15 changes: 13 additions & 2 deletions src/web/pump.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Comment thread
SectionTN marked this conversation as resolved.
Resolved
const budget = PUMP_BUDGET_MS - (performance.now() - start);
if (stepped && budget <= 0) {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
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();
Expand Down
43 changes: 42 additions & 1 deletion tests/web/render.e2e.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -1138,16 +1138,57 @@ 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}`);
assert.ok(painted.scrolledB < 300, `unwrapped after the scroll ${painted.scrolledB}`);
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() };
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
});
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'));
Expand Down
Loading