Skip to content
Open
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
2 changes: 2 additions & 0 deletions example/src/chrome/FindBar.web.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,9 @@ export function FindBar({ scheme, editor, onStatus, onClose }: FindBarProps) {

const styles = StyleSheet.create({
bar: { flexDirection: 'row', flexWrap: 'wrap', gap: 6, padding: 8, alignItems: 'center' },
// 16px keeps Safari from zooming the page when a field takes the focus.
field: {
fontSize: 16,
minWidth: 120,
paddingHorizontal: 8,
paddingVertical: 4,
Expand Down
9 changes: 5 additions & 4 deletions src/web/EditorView.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1194,15 +1194,18 @@ export class EditorView {
}

findNext(): Promise<SearchHit | null> {
if (this.destroyed) return Promise.resolve(null);
return this.whenFresh(() => this.find(true));
}

findPrevious(): Promise<SearchHit | null> {
if (this.destroyed) return Promise.resolve(null);
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<boolean> {
if (this.destroyed) return Promise.resolve(false);
return this.whenFresh(() => {
let replaced = false as boolean;
this.apply(() => {
Expand All @@ -1215,6 +1218,7 @@ export class EditorView {

// Every match replaced as one undo step. Resolves with the count.
replaceAll(text: string): Promise<number> {
if (this.destroyed) return Promise.resolve(0);
return this.whenFresh(() => {
let count = 0;
this.apply(() => {
Expand Down Expand Up @@ -2113,10 +2117,7 @@ export class EditorView {
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 if (oldCount === 1 && newCount === 1) {
entry.stale = true;
moved.push([line, entry]);
} else entry.el.remove();
else entry.el.remove();
}
this.cache.clear();
this.attached.clear();
Expand Down
35 changes: 34 additions & 1 deletion src/web/__tests__/pump.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ 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';
import { registerTask, registerView, setPumpCore } from '../pump';

const dir = builtCore('lib/web', 'yarn build:web');
const javascript = join(ROOT, 'languages/javascript/web/javascript.wasm');
Expand Down Expand Up @@ -127,3 +127,36 @@ describe('engine tasks', () => {
]);
});
});

describe('frames', () => {
test('two views throwing in one frame surface both errors', () => {
const g = globalThis as { requestAnimationFrame?: (cb: () => void) => number };
const saved = g.requestAnimationFrame;
const frames: (() => void)[] = [];
g.requestAnimationFrame = (cb) => frames.push(cb);
const thrown: string[] = [];
const microtask = jest.spyOn(globalThis, 'queueMicrotask').mockImplementation((fn) => {
try {
fn();
} catch (e) {
thrown.push((e as Error).message);
}
});
const throwing = (name: string) => ({
urgent: false,
pending: () => false,
draw: () => {
throw new Error(name);
},
});
const removals = [registerView(throwing('a')), registerView(throwing('b'))];
try {
for (const frame of frames.splice(0)) frame();
expect(thrown).toEqual(['a', 'b']);
} finally {
for (const remove of removals) remove();
microtask.mockRestore();
g.requestAnimationFrame = saved;
}
});
});
24 changes: 19 additions & 5 deletions src/web/input/InputHost.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export class InputHost {
// iOS reports the selection as 0,0 for a moment after focus, so selection changes wait a frame.
private settling = false;
private settleTimer: ReturnType<typeof setTimeout> | undefined;
private readonly listeners: [EventTarget, string, EventListener][] = [];
private readonly listeners: [EventTarget, string, EventListener, boolean][] = [];

constructor(
root: HTMLElement,
Expand All @@ -51,6 +51,19 @@ export class InputHost {
}
this.session.beforeInput(this.state());
});
// WebKit aims a shake undo at the field the user last typed in, even while this textarea has the focus.
this.on(
document,
'beforeinput',
(e) => {
const type = (e as InputEvent).inputType;
if (type !== 'historyUndo' && type !== 'historyRedo') return;
if (e.target === ta || document.activeElement !== ta) return;
e.preventDefault();
this.hooks.history(type === 'historyUndo');
},
true,
);
this.on(ta, 'input', (e) => {
const ie = e as InputEvent;
this.write(
Expand Down Expand Up @@ -147,7 +160,8 @@ export class InputHost {

destroy(): void {
clearTimeout(this.settleTimer);
for (const [target, type, fn] of this.listeners) target.removeEventListener(type, fn);
for (const [target, type, fn, capture] of this.listeners)
target.removeEventListener(type, fn, capture);
this.textarea.remove();
}

Expand All @@ -169,8 +183,8 @@ export class InputHost {
e.preventDefault();
}

private on(target: EventTarget, type: string, fn: EventListener): void {
target.addEventListener(type, fn);
this.listeners.push([target, type, fn]);
private on(target: EventTarget, type: string, fn: EventListener, capture = false): void {
target.addEventListener(type, fn, capture);
this.listeners.push([target, type, fn, capture]);
}
}
22 changes: 17 additions & 5 deletions src/web/pump.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,11 +62,21 @@ export function registerView(view: View): () => void {

// One shared frame: every view draws, then the engine runs after the paint unless a view is urgent.
export function requestPump(): void {
// A hidden tab gets no frames, so the engine starts its queued work on posted tasks.
if (tabHidden()) postEngine();
requestFrame();
}

function requestFrame(): void {
if (scheduled) return;
scheduled = true;
requestAnimationFrame(frame);
}

function tabHidden(): boolean {
return typeof document !== 'undefined' && document.hidden;
}

function frame(): void {
scheduled = false;
lastFrame = performance.now();
Expand All @@ -87,9 +97,10 @@ function frame(): void {
if (probe) probe.pumps.push(performance.now() - start);
if (left > 0) requestPump();
else postEngine();
if (failures.length)
// Each error on its own, so the page reports every view that failed.
for (const failure of failures)
queueMicrotask(() => {
throw failures[0];
throw failure;
});
}

Expand Down Expand Up @@ -160,8 +171,9 @@ function runEngine(): void {
if (entry.task.step(Math.max(1, budget))) left++;
}
if (probe) probe.tasks.push(performance.now() - start);
if ([...views].some((v) => v.pending())) requestPump();
if ([...views].some((v) => v.pending())) requestFrame();
if (left === 0) return;
if (performance.now() - lastFrame < ENGINE_BEFORE_FRAME_MS) postEngine();
else requestPump();
// Without frames there is no paint to wait for.
if (performance.now() - lastFrame < ENGINE_BEFORE_FRAME_MS || tabHidden()) postEngine();
else requestFrame();
}
69 changes: 69 additions & 0 deletions tests/web/render.e2e.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -1030,6 +1030,75 @@ for (const engine of [chromium, webkit]) {
await page.close();
});

test('a hidden tab finishes a first parse', async () => {
const { page, errors } = await open();
const parsed = await page.evaluate(async () => {
Object.defineProperty(document, 'hidden', { configurable: true, get: () => true });
window.requestAnimationFrame = () => 0;
const { EditorView, loadCore } = window.codepad;
const v = new EditorView(document.getElementById('a'), await loadCore(), 'let x = 1;\n');
v.setLanguage('javascript');
const end = performance.now() + 3000;
while (performance.now() < end) {
if (v.core.snapshot !== 0) return true;
await new Promise((r) => setTimeout(r, 20));
}
return false;
});
assert.equal(parsed, true);
assert.deepEqual(errors, []);
await page.close();
});

test('findNext on a destroyed view resolves null', async () => {
const { page, errors } = await open();
await editor(page, 'a', 'one two one');
const out = await page.evaluate(async () => {
const v = window.views.a;
await v.setSearch({ text: 'one' });
v.destroy();
const late = new Promise((r) => setTimeout(() => r('pending'), 1000));
const settle = (p) => Promise.race([p, late]);
return [
await settle(v.findNext()),
await settle(v.findPrevious()),
await settle(v.replaceCurrent('x')),
await settle(v.replaceAll('x')),
];
});
assert.deepEqual(out, [null, null, false, 0]);
assert.deepEqual(errors, []);
await page.close();
});

test('a historyUndo aimed at another field undoes the focused editor and leaves the field', async () => {
const { page, errors } = await open();
await editor(page, 'a', 'abc');
await clickAt(page, 'a', 0, 3);
await page.keyboard.type('x');
const out = await page.evaluate(() => {
const field = document.createElement('input');
field.value = 'fed';
document.body.append(field);
const ta = document.querySelector('#a textarea');
const e = new InputEvent('beforeinput', {
inputType: 'historyUndo',
bubbles: true,
cancelable: true,
});
field.dispatchEvent(e);
return {
prevented: e.defaultPrevented,
text: window.views.a.core.text(),
field: field.value,
focused: document.activeElement === ta,
};
});
assert.deepEqual(out, { prevented: true, text: 'abc', field: 'fed', focused: true });
assert.deepEqual(errors, []);
await page.close();
});

test('typing after replaceRange, setText and undo lands at the core caret', async () => {
const { page } = await open();
await editor(page, 'a', 'abc');
Expand Down