diff --git a/cpp/core/include/codepad.h b/cpp/core/include/codepad.h index df532c9..e26e0d7 100644 --- a/cpp/core/include/codepad.h +++ b/cpp/core/include/codepad.h @@ -305,6 +305,8 @@ CP_API cp_engine *cp_engine_new(const cp_host *host, int64_t budget_micros, void (*on_snapshot)(void *ctx, cp_snapshot *snapshot)); // NULL clears the language. A snapshot still in flight keeps the language it was parsed with. CP_API void cp_engine_set_language(cp_engine *engine, const cp_language *language); +// Looks up the injection names that found no language again and repaints, once the host resolves more of them. +CP_API void cp_engine_refresh_injections(cp_engine *engine); // Frees the snapshot on the worker, or on the calling thread once the engine is closed. engine may be NULL then. CP_API void cp_engine_release(cp_engine *engine, cp_snapshot *snapshot); // No engine work runs after it. The engine frees itself on the worker. diff --git a/cpp/core/src/engine.cpp b/cpp/core/src/engine.cpp index a10c6ce..bf2a69b 100644 --- a/cpp/core/src/engine.cpp +++ b/cpp/core/src/engine.cpp @@ -234,6 +234,28 @@ struct Engine : std::enable_shared_from_this { }); } + // Forgets the names that resolved to nothing, then runs the injection pass over the whole text. + void refresh_injections() { + submit([this] { + bool forgot = false; + for (auto it = resolved.begin(); it != resolved.end();) { + if (it->second) { + ++it; + continue; + } + it = resolved.erase(it); + forgot = true; + } + if (!text) return; + if (forgot) { + dirty.push_back(0); + dirty.push_back(static_cast(text->length())); + } + // A refresh queued behind another one finds no names left, so it runs the pass the first one deferred. + if (!dirty.empty()) reparse(); + }); + } + // Main thread. Returns the new epoch, 0 once closed. uint64_t attach(SharedText next, int32_t rev) { if (shut) return 0; @@ -712,6 +734,8 @@ extern "C" void cp_engine_set_language(cp_engine *engine, const cp_language *lan engine->engine->set_language(language); } +extern "C" void cp_engine_refresh_injections(cp_engine *engine) { engine->engine->refresh_injections(); } + extern "C" void cp_engine_release(cp_engine *engine, cp_snapshot *snapshot) { if (!snapshot) return; if (engine) { diff --git a/cpp/web/host.cpp b/cpp/web/host.cpp index 4bb17b2..164a7fa 100644 --- a/cpp/web/host.cpp +++ b/cpp/web/host.cpp @@ -3,6 +3,7 @@ #include #include +#include #include #include #include @@ -31,6 +32,8 @@ struct Editor { bool closed = false; std::vector changes; std::vector text; + // Injection names that found no language, in the order the engine asked. + std::vector missed; }; std::deque worker_q; @@ -64,12 +67,17 @@ const cp_language *find(const std::string &id) { } // An injection name, lowercased. A loaded id wins over the aliases, like LanguageRegistry.canonicalInjectionId. -const cp_language *resolve(void *, const char *name) { +// A name that finds nothing is kept for the page, which may load its language, unless an alias says it never injects. +const cp_language *resolve(void *ctx, const char *name) { std::string lower(name ? name : ""); for (char &c : lower) c = static_cast(tolower(static_cast(c))); if (const cp_language *language = find(lower)) return language; auto it = aliases.find(lower); - return it == aliases.end() || it->second.empty() ? nullptr : find(it->second); + if (it != aliases.end() && it->second.empty()) return nullptr; + const cp_language *found = it == aliases.end() ? nullptr : find(it->second); + auto &missed = static_cast(ctx)->missed; + if (!found && std::find(missed.begin(), missed.end(), lower) == missed.end()) missed.push_back(lower); + return found; } void on_change(void *ctx, const cp_change *c, const cp_unit *removed, const cp_unit *inserted, int32_t origin) { @@ -205,6 +213,26 @@ CPW int32_t cpw_snapshot_count(int32_t e) { return ed ? ed->snapshots : 0; } +// The injection names that found no language since the last call, joined by newlines. Returns the bytes they take, +// and keeps them for the next call when that is more than cap. +CPW int32_t cpw_take_missed(int32_t e, char *out, int32_t cap) { + Editor *ed = at(e); + if (!ed) return 0; + std::string joined; + for (const std::string &name : ed->missed) joined += (joined.empty() ? "" : "\n") + name; + auto size = static_cast(joined.size()); + if (size > cap) return size; + memcpy(out, joined.data(), joined.size()); + ed->missed.clear(); + return size; +} + +// Looks the editor's missing injection names up again, after a language they may name registered. +CPW void cpw_refresh(int32_t e) { + Editor *ed = at(e); + if (ed && ed->engine) cp_engine_refresh_injections(ed->engine); +} + // Pins the editor's history clock to millis, for tests. Below zero follows the page clock again. CPW void cpw_set_clock(int32_t e, double millis) { if (Editor *ed = at(e)) ed->clock = millis; diff --git a/example/src/EditorApp.web.tsx b/example/src/EditorApp.web.tsx index 761f84e..6f4f2de 100644 --- a/example/src/EditorApp.web.tsx +++ b/example/src/EditorApp.web.tsx @@ -1,6 +1,7 @@ -import { useMemo, useRef, useState } from 'react'; +import { useEffect, useMemo, useRef, useState } from 'react'; import { Pressable, ScrollView, StyleSheet, Text, View } from 'react-native'; import { CodeEditor, Codepad } from 'react-native-codepad'; +import { generateJavaScript } from './bench/generate'; import { GENERATED_FILES, SAMPLE_FILES } from './files'; import { NESTED_SNIPPET } from './screens/nestedSnippet'; import { THEMES } from './themes'; @@ -22,16 +23,35 @@ export function EditorApp() { const [fileId, setFileId] = useState('python'); const [themeIndex, setThemeIndex] = useState(0); const [scrollEnabled, setScrollEnabled] = useState(true); + const [suggestions, setSuggestions] = useState<'on' | 'off'>('off'); const [demo, setDemo] = useState('editor'); const theme = THEMES[themeIndex % THEMES.length]?.theme; + // Lines of the generated JavaScript file the typing bench opened, 0 for a picked file. + const [benchLines, setBenchLines] = useState(0); const file = FILES.find((f) => f.id === fileId) ?? FILES[0]; - const text = useMemo(() => file?.load() ?? '', [file]); + const text = useMemo( + () => (benchLines ? generateJavaScript(benchLines) : (file?.load() ?? '')), + [file, benchLines], + ); // Set when a file or a demo is picked, so the first paint counts from the tap. const started = useRef(performance.now()); const pick = (set: (value: T) => void, value: T) => { started.current = performance.now(); + setBenchLines(0); set(value); }; + + // scripts/bench-web.mjs opens its file through this hook. + useEffect(() => { + if (!__DEV__) return; + (globalThis as { __codepadBench?: { open(lines: number): void } }).__codepadBench = { + open: (lines) => { + started.current = performance.now(); + setDemo('editor'); + setBenchLines(lines); + }, + }; + }, []); const ready = (label: string) => () => console.log( `[example] ${label} first paint ${Math.round(performance.now() - started.current)} ms`, @@ -40,7 +60,7 @@ export function EditorApp() { return ( - + {(['editor', 'nested', 'two'] as Demo[]).map((d) => ( pick(setDemo, d)} /> ))} @@ -54,6 +74,11 @@ export function EditorApp() { on={!scrollEnabled} onPress={() => setScrollEnabled((s) => !s)} /> + setSuggestions((s) => (s === 'on' ? 'off' : 'on'))} + /> {FILES.map((f) => ( @@ -71,14 +96,16 @@ export function EditorApp() { {demo === 'editor' ? ( ) : null} {demo === 'nested' ? ( @@ -122,6 +149,7 @@ export function EditorApp() { const styles = StyleSheet.create({ page: { flex: 1, height: '100%' }, bar: { flexDirection: 'row', gap: 8, padding: 8, alignItems: 'center' }, + wrap: { flexWrap: 'wrap' }, files: { flexGrow: 0 }, chip: { paddingHorizontal: 10, paddingVertical: 6, borderRadius: 14, backgroundColor: '#8884' }, chipOn: { backgroundColor: '#0969da' }, diff --git a/package.json b/package.json index c2f283c..a9793ac 100644 --- a/package.json +++ b/package.json @@ -64,8 +64,10 @@ "bench:memory": "scripts/bench.sh memory", "bench:typing": "scripts/bench.sh typing", "ime:record": "scripts/ime-record.sh", + "ime:record:web": "node tests/ime-web/recorder/serve.mjs", "ime:record:ios": "scripts/ime-record-ios.sh", "bench:ios": "scripts/bench-ios.sh", + "bench:web": "node scripts/bench-web.mjs", "release": "release-it --only-version", "docs": "yarn workspace react-native-codepad-website dev", "docs:build": "yarn workspace react-native-codepad-website build", diff --git a/scripts/bench-web.mjs b/scripts/bench-web.mjs new file mode 100644 index 0000000..ac6d11c --- /dev/null +++ b/scripts/bench-web.mjs @@ -0,0 +1,61 @@ +// Typing bench in Chrome on a phone: yarn bench:web [lines] [port], the example served on that port through adb reverse. +import { execFileSync } from 'node:child_process'; +import { chromium } from 'playwright'; + +const lines = Number(process.argv[2] ?? 300); +const CHARS = 60; +const GAP_MS = 150; +const TEXT = 'let total = value + 1; '.repeat(3).slice(0, CHARS); +const PORT = 9222; +const WEB_PORT = process.argv[3] ?? '8082'; + +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +const pct = (sorted, q) => sorted[Math.min(sorted.length - 1, Math.floor(q * sorted.length))]; +const ms = (n) => `${n.toFixed(1)} ms`; + +execFileSync('adb', ['forward', `tcp:${PORT}`, 'localabstract:chrome_devtools_remote']); +const browser = await chromium.connectOverCDP(`http://127.0.0.1:${PORT}`); +try { + const page = browser + .contexts() + .flatMap((c) => c.pages()) + .find((p) => new RegExp(`//(localhost|127\\.0\\.0\\.1):${WEB_PORT}/`).test(p.url())); + if (!page) throw new Error(`open http://localhost:${WEB_PORT} in Chrome on the phone first`); + await page.evaluate(() => localStorage.setItem('codepad_debug', '1')); + await page.reload(); + await page.waitForFunction(() => globalThis.__codepadBench && globalThis.__codepadProbe); + const opened = page.waitForEvent('console', { + predicate: (m) => m.text().includes(`bench ${lines} first paint`), + timeout: 60000, + }); + await page.evaluate((n) => globalThis.__codepadBench.open(n), lines); + console.log((await opened).text()); + const box = await page.locator('[data-line="2"]').first().boundingBox(); + if (!box) throw new Error('the editor drew no line 2'); + await page.mouse.click(box.x + 4, box.y + box.height / 2); + await sleep(1000); + await page.evaluate(() => { + for (const list of Object.values(globalThis.__codepadProbe)) list.length = 0; + }); + const cdp = await page.context().newCDPSession(page); + for (const ch of TEXT) { + await cdp.send('Input.insertText', { text: ch }); + await sleep(GAP_MS); + } + await sleep(500); + const probe = await page.evaluate(() => globalThis.__codepadProbe); + const stats = (list) => { + const sorted = [...list].sort((a, b) => a - b); + return `p50 ${ms(pct(sorted, 0.5))}, p95 ${ms(pct(sorted, 0.95))}, max ${ms(sorted.at(-1) ?? 0)}`; + }; + console.log(`${lines} lines, ${probe.work.length} of ${CHARS} keys`); + for (const part of ['work', 'handler', 'engine', 'draw']) { + console.log(` ${part.padEnd(8)}${stats(probe[part])}`); + } + console.log(` largest frame ${ms(Math.max(0, ...probe.pumps))} of ${probe.pumps.length}`); + console.log(` engine tasks ${stats(probe.tasks)} of ${probe.tasks.length}`); + await page.evaluate(() => localStorage.removeItem('codepad_debug')); +} finally { + await browser.close(); + execFileSync('adb', ['forward', '--remove', `tcp:${PORT}`]); +} diff --git a/src/web/CodeEditor.tsx b/src/web/CodeEditor.tsx index af7f339..77f53b5 100644 --- a/src/web/CodeEditor.tsx +++ b/src/web/CodeEditor.tsx @@ -82,6 +82,8 @@ export const CodeEditor = forwardRef(function Co onChange, onChangeText, onContentSizeChange, + onFocus, + onBlur, }); handlers.current = { onReady, @@ -90,6 +92,8 @@ export const CodeEditor = forwardRef(function Co onChange, onChangeText, onContentSizeChange, + onFocus, + onBlur, }; const initial = useRef(initialValue); @@ -113,6 +117,11 @@ export const CodeEditor = forwardRef(function Co insertSpaces, autoIndent, autoCloseBrackets, + suggestions, + autoFocus, + avoidKeyboard, + onFocus: () => handlers.current.onFocus?.(), + onBlur: () => handlers.current.onBlur?.(), onContentSize: (width, height) => handlers.current.onContentSizeChange?.({ width, height }), onScroll: (x, y, contentWidth, contentHeight) => handlers.current.onScroll?.({ x, y, contentWidth, contentHeight }), @@ -149,6 +158,9 @@ export const CodeEditor = forwardRef(function Co insertSpaces, autoIndent, autoCloseBrackets, + suggestions, + autoFocus, + avoidKeyboard, ], ); const latest = useRef({ options, language }); @@ -172,7 +184,7 @@ export const CodeEditor = forwardRef(function Co v.setLanguage(latest.current.language); viewRef.current = v; for (const write of queued.current.splice(0)) { - v.apply(() => write.edit(v)); + write.edit(v); write.done(); } setView(v); @@ -195,14 +207,9 @@ export const CodeEditor = forwardRef(function Co }, []); useEffect(() => { - if (avoidKeyboard) notYet('avoidKeyboard'); - if (autoFocus) notYet('autoFocus'); - if (suggestions !== 'off') notYet('suggestions'); if (decorations) notYet('decorations'); if (onGapLayout) notYet('onGapLayout'); - if (onFocus) notYet('onFocus'); - if (onBlur) notYet('onBlur'); - }, [avoidKeyboard, autoFocus, suggestions, decorations, onGapLayout, onFocus, onBlur]); + }, [decorations, onGapLayout]); useEffect(() => { view?.setOptions(options); @@ -215,12 +222,15 @@ export const CodeEditor = forwardRef(function Co // Reads see an empty document until the core loads and after unmount. Writes made before the load wait for it. useImperativeHandle(ref, () => { const core = () => viewRef.current?.core; - const write = (edit: (v: EditorView) => void): Promise => { + // Runs on the view now, or once the core loads when the call comes before it. + const run = (call: (v: EditorView) => void): Promise => { const v = viewRef.current; - if (v) v.apply(() => edit(v)); - else if (!gone.current) return new Promise((done) => queued.current.push({ edit, done })); + if (v) call(v); + else if (!gone.current) + return new Promise((done) => queued.current.push({ edit: call, done })); return Promise.resolve(); }; + const write = (edit: (v: EditorView) => void) => run((v) => v.apply(() => edit(v))); return { getText: () => core()?.text() ?? '', getTextInRange: (range) => core()?.text(range.start, range.end) ?? '', @@ -242,7 +252,7 @@ export const CodeEditor = forwardRef(function Co getVisibleLines: () => viewRef.current?.visibleLines() ?? { first: 0, last: 0 }, canUndo: () => core()?.canUndo ?? false, canRedo: () => core()?.canRedo ?? false, - isFocused: () => false, + isFocused: () => viewRef.current?.focused ?? false, setText: (text, opts) => write((v) => v.core.setText(text, opts?.keepHistory ?? false)), setSelection: (sel) => write((v) => v.core.setSelection(sel.anchor, sel.head)), selectAll: () => write((v) => v.core.selectAll()), @@ -263,18 +273,18 @@ export const CodeEditor = forwardRef(function Co cut: () => later('cut', undefined), copy: () => later('copy', undefined), paste: () => later('paste', undefined), - focus: () => later('focus', undefined), - blur: () => later('blur', undefined), + focus: () => run((v) => v.focus()), + blur: () => run((v) => v.blur()), setSearch: () => later('setSearch', { count: 0, limited: false }), findNext: () => later('findNext', null), findPrevious: () => later('findPrevious', null), replaceCurrent: () => later('replaceCurrent', false), replaceAll: () => later('replaceAll', 0), clearSearch: () => later('clearSearch', undefined), - moveCaret: () => later('moveCaret', undefined), - typeText: () => later('typeText', undefined), - deleteBackward: () => later('deleteBackward', undefined), - deleteForward: () => later('deleteForward', undefined), + moveCaret: (direction, opts) => run((v) => v.moveCaret(direction, opts?.select ?? false)), + typeText: (text) => run((v) => v.typeText(text)), + deleteBackward: () => run((v) => v.deleteBackward()), + deleteForward: () => run((v) => v.deleteForward()), }; }, []); diff --git a/src/web/EditorView.ts b/src/web/EditorView.ts index 34f874d..c899553 100644 --- a/src/web/EditorView.ts +++ b/src/web/EditorView.ts @@ -1,12 +1,17 @@ /// import { githubLight } from '../themes/githubLight'; -import type { ContentInsets, Rect, Theme } from '../types'; -import { EditorCore, type WebChange } from './core/EditorCore'; +import type { CaretDirection, ContentInsets, Rect, Suggestions, Theme } from '../types'; +import { EditorCore, type MoveUnit, type WebChange } from './core/EditorCore'; import { Layout } from './core/Layout'; import type { CoreModule } from './core/module'; import { type DecodedFrame, decodeFrame } from './frame'; -import { ensureLanguage } from './loader'; -import { registerView, requestPump } from './pump'; +import { CaretMover, type LineGeometry } from './input/CaretMover'; +import { InputHost } from './input/InputHost'; +import { overlapOf, watchViewport } from './input/keyboardInset'; +import { keyCommand } from './input/keys'; +import { WebInputSession } from './input/WebInputSession'; +import { ensureInjected, ensureLanguage, onRegistered } from './loader'; +import { probeKey, probing, registerView, requestPump } from './pump'; import { type CssTheme, cssTheme } from './theme'; export type ViewOptions = { @@ -32,6 +37,11 @@ export type ViewOptions = { onFirstDraw?: () => void; onChange?: (change: WebChange) => void; onSelection?: (anchor: number, head: number, revision: number) => void; + suggestions: Suggestions; + autoFocus: boolean; + avoidKeyboard: boolean; + onFocus?: () => void; + onBlur?: () => void; }; // The defaults of website/docs/reference/props.md. @@ -53,10 +63,26 @@ export const DEFAULT_OPTIONS: ViewOptions = { insertSpaces: true, autoIndent: true, autoCloseBrackets: true, + suggestions: 'off', + autoFocus: false, + avoidKeyboard: false, }; const MONOSPACE = 'ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace'; const SNAPSHOT_INFO_INTS = 7; +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]/; +const MOVES: Partial> = { + left: ['char', false], + right: ['char', true], + wordLeft: ['word', false], + wordRight: ['word', true], + lineStart: ['lineStart', false], + lineEnd: ['lineEnd', true], + documentStart: ['docStart', false], + documentEnd: ['docEnd', true], +}; type Entry = { el: HTMLDivElement; @@ -91,9 +117,12 @@ export class EditorView { private language = ''; private languageReady = false; private appliedRevision = -1; + private drawnSnapshot = 0; private seenSnapshots = 0; private dirty = true; private destroyed = false; + // The next frame parses before it draws: the lines on screen lost colors an edit could not keep, or none came yet. + urgent = false; private drawn = false; private rowHeight = 0; private charWidth = 0; @@ -105,6 +134,49 @@ export class EditorView { private frameText = 0; private frameTextCap = 0; private readonly onScrollEvent = () => this.invalidate(); + private offViewport: () => void = () => {}; + // The keyboard's overlap with the editor, part of the bottom inset under avoidKeyboard. + private keyboard = 0; + // Injection names the engine found no language for, and the ids this view already refreshed after. + private readonly missed = new Set(); + private readonly refreshedFor = new Set(); + private readonly offRegistered = onRegistered(() => { + if (this.missed.size) this.loadMissed(); + }); + readonly session: WebInputSession; + private readonly input: InputHost; + private readonly selectionLayer = div('position:absolute;left:0;top:0;pointer-events:none;'); + private readonly composingLayer = div( + 'position:absolute;left:0;top:0;z-index:1;pointer-events:none;', + ); + private readonly caretEl = div( + 'position:absolute;width:2px;z-index:1;pointer-events:none;display:none;animation:codepad-blink 1s steps(1) infinite;', + ); + private inputting = false; + private readonly mover = new CaretMover(); + private movingVertically = false; + // The caret scrolls into view on the next draw, before the page paints. + private revealing = false; + // The caret as the last frame measured it, null while its line is not drawn. + private drawnCaret: Rect | null = null; + // The row of the drawn caret inside its wrapped line. + private drawnCaretRow = 0; + // Hidden copies of lines a caret move measured, dropped on the next draw. + private readonly measuring = new Map(); + private readonly geometry: LineGeometry = { + rows: (line) => Math.max(1, Math.round(this.lineEl(line).offsetHeight / this.rowHeight)), + rowOf: (line, column) => + Math.min(this.pointIn(this.lineEl(line), column).row, this.geometry.rows(line) - 1), + caretX: (line, column) => this.pointIn(this.lineEl(line), column).x, + columnAt: (line, row, x) => this.columnAt(line, row, x), + }; + private readonly onClickEvent = (e: MouseEvent) => this.click(e); + // A press on the text or the line numbers keeps the focus, so a click in a focused editor never blurs it. + private readonly onMouseDownEvent = (e: MouseEvent) => { + const target = e.target as Node; + const inside = this.textLayer.contains(target) || this.gutter.contains(target); + if (e.button === 0 && inside) e.preventDefault(); + }; constructor(host: HTMLElement, m: CoreModule, text = '') { this.m = m; @@ -118,7 +190,30 @@ export class EditorView { this.textLayer = div('position:absolute;left:0;top:0;width:100%;height:100%;'); this.activeLine = div('position:absolute;left:0;display:none;'); this.placeholderEl = div('position:absolute;white-space:pre;display:none;pointer-events:none;'); - this.textLayer.append(this.activeLine, this.placeholderEl); + this.textLayer.append( + this.activeLine, + this.selectionLayer, + this.placeholderEl, + this.composingLayer, + this.caretEl, + ); + this.textLayer.style.userSelect = 'none'; + this.textLayer.style.webkitUserSelect = 'none'; + this.caretEl.dataset.caret = ''; + this.selectionLayer.dataset.selection = ''; + this.session = new WebInputSession(this.core, (edit) => this.applyInput(edit)); + this.input = new InputHost(this.root, this.session, { + keyDown: (e) => this.keyDown(e), + clipboard: (cut) => this.clipboard(cut), + focusChanged: (focused) => { + this.safely(() => (focused ? this.o.onFocus?.() : this.o.onBlur?.())); + this.invalidate(); + }, + changed: () => this.invalidate(), + }); + this.scroller.addEventListener('click', this.onClickEvent); + this.scroller.addEventListener('mousedown', this.onMouseDownEvent); + blinkStyle(); this.content.append(this.gutter, this.textLayer); this.scroller.append(this.content); this.root.append(this.scroller); @@ -150,6 +245,12 @@ export class EditorView { before.lineNumbers !== this.o.lineNumbers || before.scrollEnabled !== this.o.scrollEnabled; if (before.scrollEnabled !== this.o.scrollEnabled) this.listenToPage(!this.o.scrollEnabled); + if (before.avoidKeyboard !== this.o.avoidKeyboard) { + this.offViewport(); + this.offViewport = this.o.avoidKeyboard ? watchViewport(this.onScrollEvent) : () => {}; + } + this.input.setSuggestions(this.o.suggestions); + this.input.setReadOnly(this.o.readOnly); if ( before.tabSize !== this.o.tabSize || before.insertSpaces !== this.o.insertSpaces || @@ -175,12 +276,15 @@ export class EditorView { if (id === this.language) return; this.language = id; this.languageReady = false; + this.missed.clear(); + this.refreshedFor.clear(); this.core.setLanguage(''); this.invalidate(); if (!id) return; ensureLanguage(this.m, id).then((ok) => { if (this.destroyed || this.language !== id || !ok) return; this.languageReady = this.core.setLanguage(id); + this.urgent = this.languageReady; this.invalidate(); }); } @@ -188,16 +292,347 @@ export class EditorView { // Runs an edit, then hands its changes and selection to the cache and the listeners. apply(edit: () => void): void { if (this.destroyed) return; + const outside = !this.inputting; + // An edit from outside the keyboard ends a composition first, so it undoes on its own. + if (outside) this.session.external(); edit(); const changes = this.core.takeChanges(); for (const change of changes) this.changed(change, changes.length); - for (const change of changes) this.o.onChange?.(change); const s = this.core.selection; - if (s.anchor !== this.lastSelection.anchor || s.head !== this.lastSelection.head) { - this.lastSelection = s; - this.o.onSelection?.(s.anchor, s.head, this.core.revision); - } + const moved = s.anchor !== this.lastSelection.anchor || s.head !== this.lastSelection.head; + if (moved) this.lastSelection = s; + if (moved && !this.movingVertically) this.mover.reset(); + if (outside) this.input.write(this.session.sync()); this.invalidate(); + // Listeners run last, so one that throws leaves the editor and the textarea in step. + for (const change of changes) this.safely(() => this.o.onChange?.(change)); + if (moved) this.safely(() => this.o.onSelection?.(s.anchor, s.head, this.core.revision)); + } + + focus(): void { + if (this.destroyed) return; + this.input.focus(); + } + + blur(): void { + if (this.destroyed) return; + this.input.blur(); + } + + get focused(): boolean { + return !this.destroyed && this.input.focused; + } + + // 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; + const d = document as Document & { + caretPositionFromPoint?(x: number, y: number): { offsetNode: Node; offset: number } | null; + caretRangeFromPoint?(x: number, y: number): Range | null; + }; + let node: Node | null = null; + let offset = 0; + const position = d.caretPositionFromPoint?.(clientX, clientY); + if (position) { + node = position.offsetNode; + offset = position.offset; + } else { + const range = d.caretRangeFromPoint?.(clientX, clientY); + if (range) { + node = range.startContainer; + offset = range.startOffset; + } + } + 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); + } + 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); + } + + // A point beside the text, past a line's end or in the space below the last line, finds the drawn line by height. + private offsetBeside(clientX: number, clientY: number): number | null { + let below = true; + for (const [line, entry] of this.cache) { + if (!this.attached.has(line)) continue; + const r = entry.el.getBoundingClientRect(); + if (clientY >= r.bottom) continue; + below = false; + if (clientY < r.top) continue; + const range = document.createRange(); + const [node, offset] = textPoint(entry.el, entry.text.length); + range.setStart(node, offset); + const end = range.getBoundingClientRect().right; + return this.core.lineStart(line) + (clientX >= end ? entry.text.length : 0); + } + return below ? this.core.length : null; + } + + // A keyboard edit or caret move shows the caret, a selection the page wrote back does not. + private applyInput(edit: () => void): void { + const start = probing ? performance.now() : 0; + const revision = this.core.revision; + const before = this.core.selection; + this.inputting = true; + try { + this.apply(edit); + } finally { + this.inputting = false; + } + const after = this.core.selection; + if ( + this.core.revision === revision && + after.anchor === before.anchor && + after.head === before.head + ) + return; + this.revealing = true; + if (probing) probeKey(this, performance.now() - start); + } + + // The selected text for copy or cut. A cut deletes it, except under readOnly. + private clipboard(cut: boolean): string | null { + const { anchor, head } = this.core.selection; + const from = Math.min(anchor, head); + const to = Math.max(anchor, head); + if (this.destroyed || from === to) return null; + const text = this.core.text(from, to); + if (cut && !this.o.readOnly) this.perform(() => this.core.inputReplace(from, to, '')); + return text; + } + + // A hardware key the editor runs itself. True when the browser must not act on it. + private keyDown(e: KeyboardEvent): boolean { + if (this.destroyed) return false; + const command = keyCommand(e, MAC); + if (!command) return false; + switch (command.kind) { + case 'move': + this.perform(() => this.core.move(command.unit, command.forward, command.extend)); + return true; + case 'vertical': + this.vertical(command.by === 'page', command.forward, command.extend); + return true; + case 'selectAll': + this.apply(() => this.core.selectAll()); + return true; + } + if (this.o.readOnly) return false; + const kind = command.kind; + this.perform(() => { + if (kind === 'tab') this.core.tab(); + else if (kind === 'shiftTab') this.core.shiftTab(); + else if (kind === 'undo') this.core.undo(); + else this.core.redo(); + }); + return true; + } + + // Runs an edit or a move from a key or the ref, then shows the caret. + private perform(edit: () => void): void { + this.revealing = true; + this.apply(edit); + } + + // Moves the caret by rows or by a page of rows, back to the same x after a shorter line. + private vertical(page: boolean, forward: boolean, extend: boolean): void { + const pageRows = Math.max(1, Math.floor(this.layout.viewportHeight / this.rowHeight)); + const rows = (page ? pageRows : 1) * (forward ? 1 : -1); + const { anchor, head } = this.core.selection; + const target = this.mover.target(this.core, this.geometry, head, rows); + this.movingVertically = true; + try { + this.perform(() => this.core.setSelection(extend ? anchor : target, target)); + } finally { + this.movingVertically = false; + } + } + + // As typed on the keyboard: auto close, indentation on a newline. Nothing under readOnly. + typeText(text: string): void { + if (this.destroyed || this.o.readOnly || text === '') return; + this.perform(() => this.core.typeText(text)); + } + + // Backspace, an empty auto closed pair in one go. Nothing under readOnly. + deleteBackward(): void { + if (this.destroyed || this.o.readOnly) return; + this.perform(() => this.core.backspace()); + } + + deleteForward(): void { + if (this.destroyed || this.o.readOnly) return; + this.perform(() => this.core.delete()); + } + + // Moves the caret like the matching key, under readOnly too. + moveCaret(direction: CaretDirection, extend: boolean): void { + if (this.destroyed) return; + const move = MOVES[direction]; + if (move) { + this.perform(() => this.core.move(move[0], move[1], extend)); + return; + } + const page = direction === 'pageUp' || direction === 'pageDown'; + this.vertical(page, direction === 'down' || direction === 'pageDown', extend); + } + + // The column nearest x (pixels from the line's left) on a row of a line, laid out first when not drawn. + columnAt(line: number, rowInLine: number, x: number): number { + if (this.destroyed) return 0; + const el = this.lineEl(line); + const text = this.core.line(line); + const length = text.length; + const rowOf = (c: number) => this.pointIn(el, c).row; + const xOf = (c: number) => this.pointIn(el, c).x; + // Rows only grow along a line, and x along a row. + const first = firstWhere(0, length + 1, (c) => rowOf(c) >= rowInLine); + if (first > length) return length; + const last = firstWhere(first, length + 1, (c) => rowOf(c) > rowInLine) - 1; + let column = first; + if (RTL_TEXT.test(text.slice(first, last + 1))) { + // x does not grow along a row that holds right to left text, so every column is measured. + for (let c = first + 1; c <= last; c++) + if (Math.abs(xOf(c) - x) < Math.abs(xOf(column) - x)) column = c; + } else { + const at = firstWhere(first, last + 1, (c) => xOf(c) >= x); + column = at; + if (at > last) column = last; + else if (at > first && x - xOf(at - 1) < xOf(at) - x) column = at - 1; + } + const unit = text.charCodeAt(column); + // Never between the two halves of an emoji. + if (column > 0 && unit >= 0xdc00 && unit <= 0xdfff) column--; + return column; + } + + // The element a line is measured in: the drawn one when it holds the current text, else a hidden copy. + private lineEl(line: number): HTMLDivElement { + const text = this.core.line(line); + const entry = this.cache.get(line); + if (entry && this.attached.has(line) && entry.text === text) return entry.el; + let copy = this.measuring.get(line); + if (copy && copy.text !== text) { + copy.el.remove(); + copy = undefined; + } + if (!copy) { + const el = this.makeLine(); + this.paint(el, text, null); + el.style.visibility = 'hidden'; + el.style.top = '0px'; + el.style.left = `${this.layout.textAreaLeft + this.layout.textPadding}px`; + el.style.width = this.o.softWrap ? `${this.layout.wrapWidth}px` : ''; + this.textLayer.append(el); + copy = { el, text }; + this.measuring.set(line, copy); + } + return copy.el; + } + + // The caret at a column of a line element, in pixels from its left edge and in rows from its top. + private pointIn(el: HTMLElement, column: number): { x: number; row: number } { + const box = el.getBoundingClientRect(); + const edge = caretEdge(el, column); + const middle = edge.top + edge.height / 2 - box.top; + return { x: edge.x - box.left, row: Math.max(0, Math.floor(middle / this.rowHeight)) }; + } + + private safely(call: () => void): void { + try { + call(); + } catch (e) { + queueMicrotask(() => { + throw e; + }); + } + } + + // A click places the caret and focuses the textarea inside the event, which iOS needs to show its keyboard. + private click(e: MouseEvent): void { + const offset = this.offsetAt(e.clientX, e.clientY); + if (offset !== null) this.apply(() => this.core.setSelection(offset, offset)); + this.focus(); + } + + // The caret, composing underline and selection, every read before every write so the page lays out once. + private drawInput(): void { + const box = this.textLayer.getBoundingClientRect(); + const { anchor, head } = this.core.selection; + const caret = this.caretRect(head); + this.drawnCaret = caret; + const rootBox = this.root.getBoundingClientRect(); + const caretLine = this.cache.get(this.core.lineAt(head))?.el; + this.drawnCaretRow = + caret && caretLine + ? Math.max( + 0, + Math.round( + (caret.y + rootBox.top - caretLine.getBoundingClientRect().top) / this.rowHeight, + ), + ) + : 0; + const composing = this.session.composing; + const bars = composing ? this.rangeRects(composing.start, composing.end) : []; + const from = Math.min(anchor, head); + const to = Math.max(anchor, head); + const selected = from < to ? this.rangeRects(from, to) : []; + if (caret && this.input.focused) { + put(this.caretEl, 'display', 'block'); + put(this.caretEl, 'left', `${caret.x + rootBox.left - box.left}px`); + put(this.caretEl, 'top', `${caret.y + rootBox.top - box.top}px`); + put(this.caretEl, 'height', `${caret.height}px`); + put(this.caretEl, 'background', this.css.cursor); + this.input.place(caret.x, caret.y); + } else { + put(this.caretEl, 'display', 'none'); + } + if (bars.length || this.composingLayer.childElementCount) { + this.composingLayer.replaceChildren( + ...bars.map((r) => { + const bar = div( + `position:absolute;left:${r.left - box.left}px;top:${r.bottom - box.top - 2}px;width:${r.width}px;height:2px;background:${this.css.cursor};`, + ); + bar.dataset.composing = ''; + return bar; + }), + ); + } + if (selected.length || this.selectionLayer.childElementCount) { + this.selectionLayer.replaceChildren( + ...selected.map((r) => + div( + `position:absolute;left:${r.left - box.left}px;top:${r.top - box.top}px;width:${Math.max(r.width, 4)}px;height:${r.height}px;background:${this.css.selection};`, + ), + ), + ); + } + } + + // The page boxes of the document range on the lines that are drawn. + private rangeRects(start: number, end: number): DOMRect[] { + const out: DOMRect[] = []; + const first = this.core.lineAt(start); + const last = this.core.lineAt(end); + for (let line = first; line <= last; line++) { + const entry = this.cache.get(line); + if (!entry || !this.attached.has(line)) continue; + const lineStart = this.core.lineStart(line); + const a = Math.max(start, lineStart) - lineStart; + const b = Math.min(end, lineStart + entry.text.length) - lineStart; + const range = document.createRange(); + const [sn, so] = textPoint(entry.el, a); + const [en, eo] = textPoint(entry.el, b); + range.setStart(sn, so); + range.setEnd(en, eo); + const rects = [...range.getClientRects()].filter((r) => r.width > 0); + // An empty part of a line inside the selection still shows a little. + if (rects.length === 0) rects.push(range.getBoundingClientRect()); + out.push(...rects); + } + return out; } // Scrolls so the line is at the top of the editor, or of the page when the editor does not scroll. @@ -215,19 +650,22 @@ export class EditorView { // Scrolls the least that shows the caret. revealSelection(): void { if (this.destroyed) return; - const caret = this.caretRect(this.core.selection.head); + this.revealing = true; + this.invalidate(); + } + + // Scrolls the least that shows the caret, by its line's row while the line is not drawn. True when it scrolled. + private revealCaret(): boolean { + const caret = this.drawnCaret; const line = this.core.lineAt(this.core.selection.head); let row = this.layout.rowStart(line); - const el = this.cache.get(line)?.el; - if (caret && el) { + if (caret) { // The caret's row inside a wrapped line, from where the browser drew it. - const lineY = el.getBoundingClientRect().top - this.root.getBoundingClientRect().top; - row += Math.max(0, Math.round((caret.y - lineY) / this.rowHeight)); + row += this.drawnCaretRow; } const top = row * this.rowHeight; const x = caret ? caret.x - this.layout.textLeft : 0; - if (this.layout.reveal(x, top, x + 1, top + this.rowHeight)) this.syncScroll(); - this.invalidate(); + return this.layout.reveal(x, top, x + 1, top + this.rowHeight); } // The caret at offset in view coordinates, or null when its line is not drawn. @@ -236,18 +674,8 @@ export class EditorView { const line = this.core.lineAt(offset); const entry = this.cache.get(line); if (!entry || !this.attached.has(line)) return null; - const column = offset - this.core.lineStart(line); const box = this.root.getBoundingClientRect(); - const lineBox = entry.el.getBoundingClientRect(); - // The base direction is left to right: the caret sits at the leading edge of the next character unless it - // reads right to left, then at the trailing edge of the previous one, so Chromium and WebKit agree. - const next = charRect(entry.el, column, true); - const prev = charRect(entry.el, column, false); - let edge: { x: number; top: number } = { x: lineBox.left, top: lineBox.top }; - if (next && !next.rtl) edge = { x: next.rect.left, top: next.rect.top }; - else if (prev && !prev.rtl) edge = { x: prev.rect.right, top: prev.rect.top }; - else if (next) edge = { x: next.rect.right, top: next.rect.top }; - else if (prev) edge = { x: prev.rect.left, top: prev.rect.top }; + const edge = caretEdge(entry.el, offset - this.core.lineStart(line)); return { x: edge.x - box.left, y: edge.top - box.top, width: 1, height: this.rowHeight }; } @@ -262,33 +690,56 @@ export class EditorView { if (this.core.snapshotCount !== this.seenSnapshots) { this.seenSnapshots = this.core.snapshotCount; this.dirty = true; + this.loadMissed(); } if (!this.dirty) return; this.dirty = false; + for (const copy of this.measuring.values()) copy.el.remove(); + this.measuring.clear(); this.configure(); + this.restaleRefreshed(); + let moved = this.frame(); + // A caret moved off screen scrolls into view before the paint: by row while its line is not drawn, then by x. + for (let pass = 0; this.revealing && pass < 2; pass++) { + if (this.drawnCaret) this.revealing = false; + if (!this.revealCaret()) break; + this.syncScroll(); + moved = this.frame(); + } + this.revealing = false; + if (moved) { + this.syncScroll(); + this.dirty = true; + } + this.report(); + if (this.dirty) requestPump(); + } + + // Lays out and places the visible lines at the current scroll. True when measuring moved the layout's scroll. + private frame(): boolean { const [sx, sy] = this.scrollPosition(); this.layout.beginDraw(sx, sy); - let moved = false; try { const frame = this.readFrame(); - moved = this.prepare(frame); + const moved = this.prepare(frame); this.place(frame); + this.drawInput(); + return moved; } finally { this.layout.endDraw(); } - if (moved) { - this.syncScroll(); - this.dirty = true; - } - this.report(); - if (this.dirty) requestPump(); } destroy(): void { if (this.destroyed) return; this.destroyed = true; this.unregister(); + this.offRegistered(); + this.input.destroy(); + this.scroller.removeEventListener('click', this.onClickEvent); + this.scroller.removeEventListener('mousedown', this.onMouseDownEvent); this.listenToPage(false); + this.offViewport(); this.resize?.disconnect(); document.fonts?.removeEventListener?.('loadingdone', this.remeasureEvent); this.scroller.removeEventListener('scroll', this.onScrollEvent); @@ -300,12 +751,42 @@ export class EditorView { requestPump(); } + // True when the next frame has something to draw: a change, or a snapshot not drawn yet. + pending(): boolean { + return !this.destroyed && (this.dirty || this.core.snapshotCount !== this.seenSnapshots); + } + private invalidate(): void { if (this.destroyed) return; this.dirty = true; requestPump(); } + // A new snapshot at the drawn revision is a refresh, so every cached line is queried again. + private restaleRefreshed(): void { + const snapshot = this.languageReady ? this.core.snapshot : 0; + if (snapshot === this.drawnSnapshot) return; + this.drawnSnapshot = snapshot; + if (snapshot === 0 || this.snapshotInfo(snapshot).revision !== this.appliedRevision) return; + for (const entry of this.cache.values()) entry.revision = -1; + } + + // Loads languages the engine could not find, like a fence's, and refreshes once per language that registered. + private loadMissed(): void { + for (const name of this.core.takeMissedLanguages()) this.missed.add(name); + if (!this.missed.size) return; + const language = this.language; + ensureInjected(this.m, [...this.missed]).then((ids) => { + if (this.destroyed || this.language !== language) return; + const fresh = ids.filter((id) => !this.refreshedFor.has(id)); + if (!fresh.length) return; + for (const id of fresh) this.refreshedFor.add(id); + this.missed.clear(); + this.core.refreshInjections(); + this.invalidate(); + }); + } + private readonly remeasureEvent = () => this.remeasure(); // A web font finished loading: every line is measured again. @@ -378,7 +859,12 @@ export class EditorView { if (this.layout.gutterWidth !== gutter) this.layout.gutterWidth = gutter; if (this.layout.textPadding !== o.textPadding) this.layout.textPadding = o.textPadding; this.layout.resize(width, height); - this.layout.setInsets(insets.top ?? 0, insets.bottom ?? 0, insets.left ?? 0, insets.right ?? 0); + // An editor that sizes to its text leaves the keyboard to the page. + const keyboard = o.avoidKeyboard && o.scrollEnabled ? overlapOf(this.root) : 0; + if (keyboard > this.keyboard && this.input.focused) this.revealing = true; + this.keyboard = keyboard; + const bottom = (insets.bottom ?? 0) + keyboard; + this.layout.setInsets(insets.top ?? 0, bottom, insets.left ?? 0, insets.right ?? 0); if (o.softWrap && this.layout.textAreaWidth !== before) this.relayout(); } @@ -504,6 +990,7 @@ export class EditorView { } if (revision >= 0) { this.appliedRevision = revision; + this.urgent = false; this.kept = null; } let widest = -1; @@ -524,10 +1011,10 @@ export class EditorView { const left = layout.textAreaLeft + layout.textPadding; const width = layout.textAreaLeft + layout.contentWidth + layout.insetRight; const height = layout.insetTop + layout.contentHeight + layout.insetBottom; - this.content.style.width = `${width}px`; - this.content.style.height = `${height}px`; - this.gutter.style.width = `${layout.insetLeft + layout.gutterWidth}px`; - this.gutter.style.height = `${height}px`; + put(this.content, 'width', `${width}px`); + put(this.content, 'height', `${height}px`); + put(this.gutter, 'width', `${layout.insetLeft + layout.gutterWidth}px`); + put(this.gutter, 'height', `${height}px`); if (!this.o.scrollEnabled) this.root.style.height = `${height}px`; const visible = new Set(); for (let line = frame.first; line <= frame.last; line++) { @@ -535,10 +1022,9 @@ export class EditorView { if (!entry) continue; visible.add(line); const top = layout.lineTop(line) + scrollY; - const s = entry.el.style; - s.top = `${top}px`; - s.left = `${left}px`; - s.width = this.o.softWrap ? `${layout.wrapWidth}px` : ''; + put(entry.el, 'top', `${top}px`); + put(entry.el, 'left', `${left}px`); + put(entry.el, 'width', this.o.softWrap ? `${layout.wrapWidth}px` : ''); if (!entry.el.isConnected) this.textLayer.append(entry.el); this.attached.add(line); this.number(line, top, frame.caretLine === line); @@ -556,14 +1042,14 @@ export class EditorView { this.evict(visible); const collapsed = frame.anchor === frame.head; const showActive = this.o.highlightActiveLine && collapsed && visible.has(frame.caretLine); - this.activeLine.style.display = showActive ? 'block' : 'none'; + put(this.activeLine, 'display', showActive ? 'block' : 'none'); if (showActive) { - this.activeLine.style.top = `${layout.lineTop(frame.caretLine) + scrollY}px`; - this.activeLine.style.height = `${layout.rows(frame.caretLine) * this.rowHeight}px`; - this.activeLine.style.width = `${width}px`; + put(this.activeLine, 'top', `${layout.lineTop(frame.caretLine) + scrollY}px`); + put(this.activeLine, 'height', `${layout.rows(frame.caretLine) * this.rowHeight}px`); + put(this.activeLine, 'width', `${width}px`); } const empty = frame.length === 0 && this.o.placeholder !== ''; - this.placeholderEl.style.display = empty ? 'block' : 'none'; + put(this.placeholderEl, 'display', empty ? 'block' : 'none'); if (empty) { this.placeholderEl.textContent = this.o.placeholder; this.placeholderEl.style.top = `${layout.insetTop}px`; @@ -579,10 +1065,10 @@ export class EditorView { this.gutter.append(el); this.gutterLines.set(line, el); } - el.textContent = String(line + 1); - el.style.top = `${top}px`; - el.style.width = `${this.layout.insetLeft + this.layout.gutterWidth - this.charWidth}px`; - el.style.color = active ? this.css.gutterActiveForeground : ''; + put(el, 'text', String(line + 1)); + put(el, 'top', `${top}px`); + put(el, 'width', `${this.layout.insetLeft + this.layout.gutterWidth - this.charWidth}px`); + put(el, 'color', active ? this.css.gutterActiveForeground : ''); } // Keeps about three screens of laid out lines. @@ -598,7 +1084,8 @@ export class EditorView { private report(): void { const layout = this.layout; const width = layout.textAreaLeft + layout.contentWidth + layout.insetRight; - const height = layout.insetTop + layout.contentHeight + layout.insetBottom; + // The keyboard's inset is not the content's size. + const height = layout.insetTop + layout.contentHeight + layout.insetBottom - this.keyboard; if (width !== this.lastContent.width || height !== this.lastContent.height) { this.lastContent = { width, height }; this.o.onContentSize?.(width, height); @@ -606,6 +1093,7 @@ export class EditorView { if (!this.drawn) { this.drawn = true; this.o.onFirstDraw?.(); + if (this.o.autoFocus) this.focus(); } const x = layout.scrollX; const y = this.o.scrollEnabled ? layout.scrollY : 0; @@ -649,6 +1137,7 @@ export class EditorView { // Moves the cache along an edit and keeps the edited line's spans shifted until the parse catches up. private changed(change: WebChange, count: number): void { if (count > 1) { + this.urgent = this.languageReady; this.kept = null; this.relayout(); return; @@ -656,7 +1145,18 @@ export class EditorView { const first = this.core.lineAt(change.start); const oldCount = lineSpan(change.removed); const newCount = lineSpan(change.inserted); + // Colors the edited lines show, from the cache or from an earlier edit since the last frame. + const inside = (line: number) => line >= first && line < first + oldCount; + const kept = this.kept; + let colored = + kept !== null && + ((inside(kept.line) && kept.spans !== null) || (inside(kept.line + 1) && kept.tail !== null)); + for (const [line, entry] of this.cache) { + if (colored) break; + colored = inside(line) && entry.spans !== null; + } this.keepSpans(first, oldCount, newCount, change); + if (colored && this.kept === null) this.urgent = true; const delta = newCount - oldCount; const moved: [number, Entry][] = []; for (const [line, entry] of this.cache) { @@ -673,9 +1173,19 @@ export class EditorView { } } + // The spans a line shows now: its cache entry, else what an edit since the last frame kept for it. + private shownSpans(line: number): Int32Array | null { + const entry = this.cache.get(line); + if (entry) return entry.spans; + const kept = this.kept; + if (!kept) return null; + if (line === kept.line) return kept.spans; + return line === kept.line + 1 ? kept.tail : null; + } + private keepSpans(first: number, oldCount: number, newCount: number, change: WebChange): void { + const spans = this.shownSpans(first); this.kept = null; - const spans = this.cache.get(first)?.spans; if (oldCount !== 1 || !spans) return; const column = change.start - this.core.lineStart(first); const revision = this.core.revision; @@ -700,6 +1210,41 @@ export class EditorView { } } +// The text node and offset at a column of a line element. +function textPoint(el: HTMLElement, column: number): [Node, number] { + const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT); + let at = 0; + let last: Text | null = null; + for (let node = walker.nextNode() as Text | null; node; node = walker.nextNode() as Text | null) { + if (column <= at + node.data.length) return [node, column - at]; + at += node.data.length; + last = node; + } + return last ? [last, last.data.length] : [el, 0]; +} + +// The column of a DOM point inside a line element. +function columnOf(el: HTMLElement, node: Node, offset: number): number { + const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT); + let at = 0; + for (let text = walker.nextNode() as Text | null; text; text = walker.nextNode() as Text | null) { + if (text === node) return at + offset; + if (node !== el && node.contains(text)) return at; + if (node === el && el.childNodes[offset]?.contains(text)) return at; + at += text.data.length; + } + return at; +} + +// The caret's blink, added to the page once. +function blinkStyle(): void { + if (document.getElementById('codepad-blink')) return; + const style = document.createElement('style'); + style.id = 'codepad-blink'; + style.textContent = '@keyframes codepad-blink { 50% { opacity: 0; } }'; + document.head.append(style); +} + function div(css: string): HTMLDivElement { const el = document.createElement('div'); el.style.cssText = css; @@ -735,6 +1280,46 @@ function sameSpans(a: Int32Array | null, b: Int32Array | null): boolean { const RTL = /^[֐-ࣿיִ-﷿ﹰ-]/; +// The caret at a column in page coordinates: the leading edge of the next character unless it reads right to left. +function caretEdge(el: HTMLElement, column: number): { x: number; top: number; height: number } { + const next = charRect(el, column, true); + const prev = charRect(el, column, false); + const at = (x: number, r: DOMRect) => ({ x, top: r.top, height: r.height }); + if (next && !next.rtl) return at(next.rect.left, next.rect); + if (prev && !prev.rtl) return at(prev.rect.right, prev.rect); + if (next) return at(next.rect.right, next.rect); + if (prev) return at(prev.rect.left, prev.rect); + const box = el.getBoundingClientRect(); + return { x: box.left, top: box.top, height: 0 }; +} + +const written = new WeakMap>(); + +// Writes a style, or the text under key text, only when it changed, so an unchanged draw keeps the layout valid. +function put(el: HTMLElement, key: string, value: string): void { + let last = written.get(el); + if (!last) { + last = {}; + written.set(el, last); + } + if (last[key] === value) return; + last[key] = value; + if (key === 'text') el.textContent = value; + else el.style.setProperty(key, value); +} + +// The first integer in [lo, hi) where test holds, or hi, for a test that stays true once it holds. +function firstWhere(lo: number, hi: number, test: (n: number) => boolean): number { + let a = lo; + let b = hi; + while (a < b) { + const mid = (a + b) >>> 1; + if (test(mid)) b = mid; + else a = mid + 1; + } + return a; +} + // The box of the character after column (forward) or before it, and whether it reads right to left. function charRect( el: HTMLElement, diff --git a/src/web/__tests__/CodeEditor.test.tsx b/src/web/__tests__/CodeEditor.test.tsx index f5e2bc6..bf3d34f 100644 --- a/src/web/__tests__/CodeEditor.test.tsx +++ b/src/web/__tests__/CodeEditor.test.tsx @@ -28,6 +28,19 @@ class MockView { apply(edit: () => void) { edit(); } + focused = false; + focus = jest.fn(() => { + this.focused = true; + this.options.onFocus?.(); + }); + blur = jest.fn(() => { + this.focused = false; + this.options.onBlur?.(); + }); + typeText = jest.fn(); + deleteBackward = jest.fn(); + deleteForward = jest.fn(); + moveCaret = jest.fn(); destroy() {} } @@ -126,3 +139,53 @@ test('settles a write made after the core failed to load', async () => { await expect(settled(write as Promise)).resolves.toBeUndefined(); warn.mockRestore(); }); + +test('focus and blur reach the view, isFocused reads it, and onFocus and onBlur fire', async () => { + const ref = createRef(); + const onFocus = jest.fn(); + const onBlur = jest.fn(); + await render(); + await act(async () => { + mockCore.resolve({}); + await tick(); + }); + await ref.current?.focus(); + expect(mockViews[0]?.focus).toHaveBeenCalledTimes(1); + expect(ref.current?.isFocused()).toBe(true); + await ref.current?.blur(); + expect(ref.current?.isFocused()).toBe(false); + expect([onFocus.mock.calls.length, onBlur.mock.calls.length]).toEqual([1, 1]); +}); + +test('typeText, deleteBackward, deleteForward and moveCaret made before the core loads reach the view', async () => { + const ref = createRef(); + await render(); + const calls = [ + ref.current?.typeText('x'), + ref.current?.deleteBackward(), + ref.current?.deleteForward(), + ref.current?.moveCaret('pageDown', { select: true }), + ]; + await act(async () => { + mockCore.resolve({}); + await tick(); + }); + await expect(settled(Promise.all(calls))).resolves.not.toBe('hung'); + const view = mockViews[0] as MockView; + expect(view.typeText).toHaveBeenCalledWith('x'); + expect(view.deleteBackward).toHaveBeenCalledTimes(1); + expect(view.deleteForward).toHaveBeenCalledTimes(1); + expect(view.moveCaret).toHaveBeenCalledWith('pageDown', true); +}); + +test('focus called before the core loads focuses the editor once it does', async () => { + const ref = createRef(); + await render(); + const focused = ref.current?.focus(); + await act(async () => { + mockCore.resolve({}); + await tick(); + }); + await expect(settled(focused as Promise)).resolves.toBeUndefined(); + expect(mockViews[0]?.focus).toHaveBeenCalledTimes(1); +}); diff --git a/src/web/__tests__/caret-mover.test.ts b/src/web/__tests__/caret-mover.test.ts new file mode 100644 index 0000000..ca1fd8c --- /dev/null +++ b/src/web/__tests__/caret-mover.test.ts @@ -0,0 +1,49 @@ +import { expect, test } from '@jest/globals'; +import { CaretMover, type DocLike, type LineGeometry } from '../input/CaretMover'; + +// Lines laid out in rows of width columns, each column 10 pixels wide. +function fixture(lines: string[], width: number): { doc: DocLike; geometry: LineGeometry } { + const starts = lines.map((_, i) => lines.slice(0, i).reduce((n, l) => n + l.length + 1, 0)); + const doc: DocLike = { + lineCount: lines.length, + length: lines.join('\n').length, + lineAt: (offset) => starts.filter((s) => s <= offset).length - 1, + lineStart: (line) => starts[line] as number, + }; + const len = (line: number) => (lines[line] as string).length; + const geometry: LineGeometry = { + rows: (line) => Math.max(1, Math.ceil(len(line) / width)), + rowOf: (line, column) => Math.min(Math.floor(column / width), geometry.rows(line) - 1), + caretX: (line, column) => (column - geometry.rowOf(line, column) * width) * 10, + columnAt: (line, row, x) => Math.min(row * width + Math.round(x / 10), len(line)), + }; + return { doc, geometry }; +} + +test('Down walks the rows of a wrapped line before the next line, keeping the goal x', () => { + const { doc, geometry } = fixture(['abcdefghij', 'xy', 'abcdefgh'], 4); + const mover = new CaretMover(); + const a = mover.target(doc, geometry, 1, 1); + expect(a).toBe(5); + const b = mover.target(doc, geometry, a, 1); + expect(b).toBe(9); + const c = mover.target(doc, geometry, b, 1); + expect(c).toBe(12); + expect(mover.target(doc, geometry, c, 1)).toBe(15); +}); + +test('Up from the first row goes to the start and Down from the last row to the end', () => { + const { doc, geometry } = fixture(['abc', 'def'], 80); + const mover = new CaretMover(); + expect(mover.target(doc, geometry, 2, -1)).toBe(0); + expect(mover.target(doc, geometry, 5, 3)).toBe(7); +}); + +test('reset drops the goal x', () => { + const { doc, geometry } = fixture(['abcdef', 'ab', 'abcdef'], 80); + const mover = new CaretMover(); + expect(mover.target(doc, geometry, 5, 1)).toBe(9); + expect(mover.target(doc, geometry, 9, 1)).toBe(15); + mover.reset(); + expect(mover.target(doc, geometry, 9, 1)).toBe(12); +}); diff --git a/src/web/__tests__/fences.test.ts b/src/web/__tests__/fences.test.ts new file mode 100644 index 0000000..9430617 --- /dev/null +++ b/src/web/__tests__/fences.test.ts @@ -0,0 +1,95 @@ +import { existsSync } from 'node:fs'; +import { join } from 'node:path'; +import { expect, test } from '@jest/globals'; +import { + builtCore, + cstring, + highlight, + loadCore, + loadGrammar, + pumpAll, + ROOT, +} from '../../../tests/web/core'; +import { EditorCore } from '../core/EditorCore'; + +const dir = builtCore('lib/web', 'yarn build:web'); +const grammar = (pkg: string, id: string) => ({ + wasm: join(ROOT, `languages/${pkg}/web/${id}.wasm`), + queries: join(ROOT, `languages/${pkg}/queries/${id}`), +}); +const markdown = grammar('markdown', 'markdown'); +const inline = grammar('markdown', 'markdown_inline'); +const python = grammar('python', 'python'); +const ready = dir !== null && [markdown, inline, python].every((g) => existsSync(g.wasm)); +if (dir && !ready) + console.warn('markdown or python grammar not built, run yarn build:web-grammars'); + +const FENCE = '```python\ndef f(): pass\n```\n'; + +(ready ? test : test.skip)('a fence colors once its language loads', async () => { + const m = await loadCore(dir as string); + loadGrammar(m, markdown.wasm, 'markdown', markdown.queries); + loadGrammar(m, inline.wasm, 'markdown_inline', inline.queries); + const core = new EditorCore(m, FENCE); + const keyword = cstring(m, 'keyword.function', (name) => m._cp_style_id(name)); + const fenceBody = () => { + const line = highlight(m, core.snapshot, 1, 1, core.lineStart(1))[0] as number[]; + const triples = []; + for (let i = 0; i + 2 < line.length; i += 3) triples.push(line.slice(i, i + 3)); + return triples; + }; + expect(core.setLanguage('markdown')).toBe(true); + pumpAll(m); + expect(core.takeMissedLanguages()).toEqual(['python']); + expect(fenceBody()).not.toContainEqual([0, 3, keyword]); + + loadGrammar(m, python.wasm, 'python', python.queries); + core.refreshInjections(); + pumpAll(m); + expect(fenceBody()).toContainEqual([0, 3, keyword]); + expect(core.takeMissedLanguages()).toEqual([]); + core.close(); + pumpAll(m); +}); + +(ready ? test : test.skip)('two refreshes queued before a pump still color the fence', async () => { + const m = await loadCore(dir as string); + loadGrammar(m, markdown.wasm, 'markdown', markdown.queries); + loadGrammar(m, inline.wasm, 'markdown_inline', inline.queries); + const core = new EditorCore(m, FENCE); + const keyword = cstring(m, 'keyword.function', (name) => m._cp_style_id(name)); + expect(core.setLanguage('markdown')).toBe(true); + pumpAll(m); + loadGrammar(m, python.wasm, 'python', python.queries); + core.refreshInjections(); + core.refreshInjections(); + pumpAll(m); + const line = highlight(m, core.snapshot, 1, 1, core.lineStart(1))[0] as number[]; + const triples = []; + for (let i = 0; i + 2 < line.length; i += 3) triples.push(line.slice(i, i + 3)); + expect(triples).toContainEqual([0, 3, keyword]); + core.close(); + pumpAll(m); +}); + +// The loader refreshes only after a new language registers, since a refresh looks the names up again. +(ready ? test : test.skip)( + 'a refresh while the language is still missing reports it again', + async () => { + const m = await loadCore(dir as string); + loadGrammar(m, markdown.wasm, 'markdown', markdown.queries); + loadGrammar(m, inline.wasm, 'markdown_inline', inline.queries); + const core = new EditorCore(m, FENCE); + core.setLanguage('markdown'); + pumpAll(m); + expect(core.takeMissedLanguages()).toEqual(['python']); + const before = core.snapshotCount; + core.refreshInjections(); + pumpAll(m); + expect(core.takeMissedLanguages()).toEqual(['python']); + expect(core.takeMissedLanguages()).toEqual([]); + expect(core.snapshotCount).toBe(before + 1); + core.close(); + pumpAll(m); + }, +); diff --git a/src/web/__tests__/ime-web.test.ts b/src/web/__tests__/ime-web.test.ts new file mode 100644 index 0000000..fbfea94 --- /dev/null +++ b/src/web/__tests__/ime-web.test.ts @@ -0,0 +1,103 @@ +import { existsSync, readdirSync, readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { expect, test } from '@jest/globals'; +import { builtCore, loadCore, ROOT } from '../../../tests/web/core'; +import { EditorCore } from '../core/EditorCore'; +import { type TextareaState, WebInputSession } from '../input/WebInputSession'; + +type Event = { + type: string; + inputType?: string; + data?: string | null; + isComposing: boolean; + windowStart: number; + ta: TextareaState; +}; +type Recording = { + settings: { autoCloseBrackets: boolean; autoIndent: boolean }; + initial: { text: string; selection: [number, number] }; + events: Event[]; + expected: { text: string }; +}; + +const dir = builtCore('lib/web', 'yarn build:web'); +const folder = join(ROOT, 'tests/ime-web'); +const files = existsSync(folder) + ? readdirSync(folder) + .filter((f) => f.endsWith('.json')) + .sort() + : []; +if (files.length === 0) console.warn('tests/ime-web holds no recording'); + +const state = (ta: TextareaState): TextareaState => ({ + value: ta.value, + start: ta.start, + end: ta.end, +}); + +// Replays what a browser keyboard did into a recorded textarea and checks the core after every edit. +for (const file of files) { + (dir ? test : test.skip)(file.replace(/\.json$/, ''), async () => { + const r = JSON.parse(readFileSync(join(folder, file), 'utf8')) as Recording; + const core = new EditorCore(await loadCore(dir as string), r.initial.text); + core.settings = { ...core.settings, ...r.settings }; + core.setSelection(r.initial.selection[0], r.initial.selection[1]); + const session = new WebInputSession(core, (edit) => edit()); + let model = r.initial.text; + let value = ''; + let first = true; + // The textarea state the session asked the page to write, until the recording shows the page writing it. + let pending: TextareaState | null = null; + for (const [i, e] of r.events.entries()) { + const at = `event ${i} ${e.type} ${e.inputType ?? ''}`; + if (e.type === 'sync') { + const got = first ? session.sync() : pending; + expect({ at, got, windowStart: session.windowStart }).toEqual({ + at, + got: state(e.ta), + windowStart: e.windowStart, + }); + first = false; + pending = null; + value = e.ta.value; + } else if (e.type === 'beforeinput') { + session.beforeInput(e.ta); + } else if (e.type === 'input') { + expect({ at, unwritten: pending }).toEqual({ at, unwritten: null }); + pending = session.input( + { inputType: e.inputType ?? '', data: e.data ?? null, isComposing: e.isComposing }, + e.ta, + ); + model = + model.slice(0, e.windowStart) + e.ta.value + model.slice(e.windowStart + value.length); + value = e.ta.value; + expect({ at, text: core.text() }).toEqual({ at, text: model }); + if (e.isComposing) { + const c = session.composing; + if (e.inputType === 'insertCompositionText') + expect({ at, composed: c && core.text(c.start, c.end) }).toEqual({ + at, + composed: e.data, + }); + } else { + const { anchor, head } = core.selection; + expect({ at, selection: [Math.min(anchor, head), Math.max(anchor, head)] }).toEqual({ + at, + selection: [e.windowStart + e.ta.start, e.windowStart + e.ta.end], + }); + } + } else if (e.type === 'compositionstart') { + session.compositionStart(e.ta); + } else if (e.type === 'compositionend') { + session.compositionEnd(); + pending = session.settle(e.ta) ?? pending; + } else if (e.type === 'selectionchange') { + pending = session.selectionChange(e.ta) ?? pending; + } else if (e.type === 'blur') { + session.finishComposition(); + } + } + expect(core.text()).toBe(r.expected.text); + core.close(); + }); +} diff --git a/src/web/__tests__/input-session.test.ts b/src/web/__tests__/input-session.test.ts new file mode 100644 index 0000000..3471c5b --- /dev/null +++ b/src/web/__tests__/input-session.test.ts @@ -0,0 +1,215 @@ +import { expect, test } from '@jest/globals'; +import { builtCore, loadCore } from '../../../tests/web/core'; +import { EditorCore, type EditorSettings } from '../core/EditorCore'; +import { type InputLike, type TextareaState, WebInputSession } from '../input/WebInputSession'; +import { WINDOW_CAP } from '../input/window'; + +const dir = builtCore('lib/web', 'yarn build:web'); +const run = dir ? test : test.skip; + +async function open(text: string, caret: number, settings: Partial = {}) { + const core = new EditorCore(await loadCore(dir as string), text); + core.settings = { ...core.settings, ...settings }; + core.setClock(1000); + core.setSelection(caret, caret); + const s = new WebInputSession(core, (edit) => edit()); + s.sync(); + return { core, s }; +} + +const ta = (value: string, start: number, end = start): TextareaState => ({ value, start, end }); +const typed = (data: string): InputLike => ({ inputType: 'insertText', data, isComposing: false }); +const composed = (data: string): InputLike => ({ + inputType: 'insertCompositionText', + data, + isComposing: true, +}); +const back: InputLike = { inputType: 'deleteContentBackward', data: null, isComposing: false }; +const enter: InputLike = { inputType: 'insertLineBreak', data: null, isComposing: false }; + +// Types one character the way a browser reports it, from the textarea before to the textarea after. +function type(s: WebInputSession, before: TextareaState, after: TextareaState, data: string) { + s.beforeInput(before); + return s.input(typed(data), after); +} + +run('a typed ( closes the pair and asks for a new window', async () => { + const { core, s } = await open('', 0); + expect(type(s, ta('', 0), ta('(', 1), '(')).toEqual(ta('()', 1)); + expect(core.text()).toBe('()'); + expect(core.selection).toEqual({ anchor: 1, head: 1 }); +}); + +run('Enter keeps the indent', async () => { + const { core, s } = await open(' a', 3); + s.beforeInput(ta(' a', 3)); + s.input(enter, ta(' a\n', 4)); + expect(core.text()).toBe(' a\n '); + expect(core.selection.head).toBe(6); +}); + +run('Enter before an existing newline lands at the caret', async () => { + const { core, s } = await open('a\nb', 1, { autoIndent: false }); + s.beforeInput(ta('a\nb', 1)); + s.input(enter, ta('a\n\nb', 2)); + expect(core.text()).toBe('a\n\nb'); + expect(core.selection.head).toBe(2); +}); + +run('Backspace inside an auto-closed pair deletes both', async () => { + const { core, s } = await open('', 0); + type(s, ta('', 0), ta('(', 1), '('); + s.beforeInput(ta('()', 1)); + s.input(back, ta(')', 0)); + expect(core.text()).toBe(''); +}); + +// The core starts a new undo step at a word boundary, as native does, so the emoji is a step of its own. +run('a typed emoji goes in whole and one undo takes it out whole', async () => { + const { core, s } = await open('', 0); + type(s, ta('', 0), ta('a', 1), 'a'); + type(s, ta('a', 1), ta('a😀', 3), '😀'); + expect(core.text()).toBe('a😀'); + expect(core.selection).toEqual({ anchor: 3, head: 3 }); + core.undo(); + expect(core.text()).toBe('a'); +}); + +run('Backspace after an emoji removes both units', async () => { + const { core, s } = await open('a😀', 3); + s.beforeInput(ta('a😀', 3)); + s.input(back, ta('a', 1)); + expect(core.text()).toBe('a'); + expect(core.selection).toEqual({ anchor: 1, head: 1 }); +}); + +run('a composed word undoes in one step', async () => { + const { core, s } = await open('ab', 2); + s.compositionStart(ta('ab', 2)); + s.beforeInput(ta('ab', 2)); + expect(s.input(composed('k'), ta('abk', 3))).toBeNull(); + s.beforeInput(ta('abk', 2, 3)); + expect(s.input(composed('か'), ta('abか', 3))).toBeNull(); + expect(s.composing).toEqual({ start: 2, end: 3 }); + s.compositionEnd(); + expect(s.composing).toBeNull(); + core.undo(); + expect(core.text()).toBe('ab'); +}); + +run( + 'an input with no change after compositionend leaves the composition one undo away', + async () => { + const { core, s } = await open('ab', 2); + s.compositionStart(ta('ab', 2)); + s.beforeInput(ta('ab', 2)); + s.input(composed('か'), ta('abか', 3)); + s.compositionEnd(); + s.beforeInput(ta('abか', 3)); + s.input(typed('か'), ta('abか', 3)); + core.undo(); + expect(core.text()).toBe('ab'); + }, +); + +run('a quote typed inside a composition does not auto-close', async () => { + const { core, s } = await open('', 0); + s.compositionStart(ta('', 0)); + expect(s.input(composed("don'"), ta("don'", 4))).toBeNull(); + expect(core.text()).toBe("don'"); +}); + +run('typing over a selection longer than the window replaces all of it', async () => { + const { core, s } = await open('a'.repeat(20000), 0); + core.selectAll(); + const window = s.sync() as TextareaState; + expect(window.value.length).toBeLessThanOrEqual(WINDOW_CAP); + expect([window.start, window.end]).toEqual([0, window.value.length]); + s.beforeInput(window); + s.input(typed('x'), ta('x', 1)); + expect(core.text()).toBe('x'); +}); + +run('a ref edit during a composition ends it', async () => { + const { core, s } = await open('ab', 2); + s.compositionStart(ta('ab', 2)); + s.input(composed('か'), ta('abか', 3)); + s.external(); + core.replace(0, 0, 'Z'); + expect(s.composing).toBeNull(); + expect(s.sync()).toEqual(ta('Zabか', 4)); + core.undo(); + expect(core.text()).toBe('abか'); +}); + +run('blur mid-composition keeps the text and closes the group', async () => { + const { core, s } = await open('ab', 2); + s.compositionStart(ta('ab', 2)); + s.input(composed('か'), ta('abか', 3)); + s.finishComposition(); + type(s, ta('abか', 3), ta('abかx', 4), 'x'); + core.undo(); + expect(core.text()).toBe('abか'); +}); + +run('the browser echoing a clamped select all leaves the whole document selected', async () => { + const text = 'x' + .repeat(40) + .concat('\n') + .repeat(Math.ceil((WINDOW_CAP * 3) / 41)); + const { core, s } = await open(text, 0); + core.selectAll(); + const written = s.sync() as TextareaState; + expect(s.selectionChange(written)).toBeNull(); + expect(core.selection).toEqual({ anchor: 0, head: core.length }); +}); + +const paste: InputLike = { inputType: 'insertFromPaste', data: null, isComposing: false }; + +run('a pasted ( and a pasted newline stay literal', async () => { + const { core, s } = await open(' a', 3); + s.beforeInput(ta(' a', 3)); + s.input(paste, ta(' a(', 4)); + expect(core.text()).toBe(' a('); + s.beforeInput(ta(' a(', 4)); + s.input(paste, ta(' a(\n', 5)); + expect(core.text()).toBe(' a(\n'); +}); + +run('typing over a selection starting before the window puts the caret after it', async () => { + const { core, s } = await open('a'.repeat(50000), 0); + core.setSelection(1000, 21000); + const w = s.sync() as TextareaState; + expect(s.windowStart).toBeGreaterThan(1000); + s.beforeInput(w); + s.input(typed('x'), ta(`x${w.value.slice(w.end)}`, 1)); + expect(core.text()).toBe(`${'a'.repeat(1000)}x${'a'.repeat(29000)}`); + expect(core.selection).toEqual({ anchor: 1001, head: 1001 }); +}); + +run('a caret moved away and back to where sync put it is followed', async () => { + const { core, s } = await open('abc', 2); + s.selectionChange(ta('abc', 1)); + expect(core.selection.head).toBe(1); + s.selectionChange(ta('abc', 2)); + expect(core.selection.head).toBe(2); +}); + +run( + 'an input sent after compositionend maps onto the window the textarea still holds', + async () => { + const text = ['a', 'b', 'c'].map((c) => c.repeat(6000)).join('\n'); + const { core, s } = await open(text, 0); + core.setSelection(core.lineStart(1) + 3000, core.lineStart(2) + 3000); + const w = s.sync() as TextareaState; + s.compositionStart(w); + const after = ta(`${w.value.slice(0, w.start)}X${w.value.slice(w.end)}`, w.start + 1); + s.beforeInput(w); + s.input(composed('X'), after); + s.compositionEnd(); + const committed = core.text(); + s.beforeInput(after); + s.input(typed('X'), after); + expect(core.text()).toBe(committed); + }, +); diff --git a/src/web/__tests__/keyboardInset.test.ts b/src/web/__tests__/keyboardInset.test.ts new file mode 100644 index 0000000..c3930a1 --- /dev/null +++ b/src/web/__tests__/keyboardInset.test.ts @@ -0,0 +1,13 @@ +import { expect, test } from '@jest/globals'; +import { keyboardOverlap } from '../input/keyboardInset'; + +test('the keyboard covers what lies below the visual viewport', () => { + expect(keyboardOverlap(800, 0, 500, 900)).toBe(300); + expect(keyboardOverlap(400, 0, 500, 900)).toBe(0); + expect(keyboardOverlap(800, 100, 500, 900)).toBe(200); +}); + +test('an editor that runs past the window with no keyboard gets no inset', () => { + expect(keyboardOverlap(1100, 0, 900, 900)).toBe(0); + expect(keyboardOverlap(1100, 0, 500, 900)).toBe(400); +}); diff --git a/src/web/__tests__/keys.test.ts b/src/web/__tests__/keys.test.ts new file mode 100644 index 0000000..bd7ede1 --- /dev/null +++ b/src/web/__tests__/keys.test.ts @@ -0,0 +1,98 @@ +import { expect, test } from '@jest/globals'; +import { type KeyLike, keyCommand } from '../input/keys'; + +const key = (name: string, mods: Partial = {}): KeyLike => ({ + key: name, + shiftKey: false, + altKey: false, + ctrlKey: false, + metaKey: false, + isComposing: false, + ...mods, +}); +const move = (unit: string, forward: boolean, extend = false) => ({ + kind: 'move', + unit, + forward, + extend, +}); + +test('arrows move by character, word and line with the platform modifier', () => { + expect(keyCommand(key('ArrowLeft'), true)).toEqual(move('char', false)); + expect(keyCommand(key('ArrowRight'), false)).toEqual(move('char', true)); + expect(keyCommand(key('ArrowLeft', { altKey: true }), true)).toEqual(move('word', false)); + expect(keyCommand(key('ArrowLeft', { ctrlKey: true }), false)).toEqual(move('word', false)); + expect(keyCommand(key('ArrowRight', { metaKey: true }), true)).toEqual(move('lineEnd', true)); + expect(keyCommand(key('ArrowLeft', { metaKey: true }), true)).toEqual(move('lineStart', false)); + expect(keyCommand(key('Home'), false)).toEqual(move('lineStart', false)); + expect(keyCommand(key('End'), true)).toEqual(move('lineEnd', true)); + expect(keyCommand(key('Home', { ctrlKey: true }), false)).toEqual(move('docStart', false)); + expect(keyCommand(key('ArrowUp', { metaKey: true }), true)).toEqual(move('docStart', false)); + expect(keyCommand(key('ArrowDown', { metaKey: true }), true)).toEqual(move('docEnd', true)); +}); + +test('Shift extends every move', () => { + expect(keyCommand(key('ArrowLeft', { shiftKey: true }), true)).toEqual(move('char', false, true)); + expect(keyCommand(key('End', { shiftKey: true, ctrlKey: true }), false)).toEqual( + move('docEnd', true, true), + ); + expect(keyCommand(key('ArrowDown', { shiftKey: true }), false)).toEqual({ + kind: 'vertical', + by: 'row', + forward: true, + extend: true, + }); +}); + +test('Up, Down, PageUp and PageDown move vertically', () => { + expect(keyCommand(key('ArrowUp'), false)).toEqual({ + kind: 'vertical', + by: 'row', + forward: false, + extend: false, + }); + expect(keyCommand(key('PageDown'), true)).toEqual({ + kind: 'vertical', + by: 'page', + forward: true, + extend: false, + }); +}); + +test('Tab, undo, redo and select all follow the platform', () => { + expect(keyCommand(key('Tab'), true)).toEqual({ kind: 'tab' }); + expect(keyCommand(key('Tab', { shiftKey: true }), false)).toEqual({ kind: 'shiftTab' }); + expect(keyCommand(key('z', { metaKey: true }), true)).toEqual({ kind: 'undo' }); + expect(keyCommand(key('Z', { metaKey: true, shiftKey: true }), true)).toEqual({ kind: 'redo' }); + expect(keyCommand(key('z', { ctrlKey: true }), false)).toEqual({ kind: 'undo' }); + expect(keyCommand(key('Z', { ctrlKey: true, shiftKey: true }), false)).toEqual({ + kind: 'redo', + }); + expect(keyCommand(key('y', { ctrlKey: true }), false)).toEqual({ kind: 'redo' }); + expect(keyCommand(key('a', { metaKey: true }), true)).toEqual({ kind: 'selectAll' }); + expect(keyCommand(key('a', { ctrlKey: true }), false)).toEqual({ kind: 'selectAll' }); +}); + +test('a shortcut on a layout whose key is not a Latin letter reads the physical key', () => { + expect(keyCommand(key('ئ', { metaKey: true, code: 'KeyZ' }), true)).toEqual({ kind: 'undo' }); +}); + +test('keys the textarea handles itself, and every key while composing, give null', () => { + for (const k of [ + key('Enter'), + key('Backspace'), + key('Delete'), + key('Unidentified'), + key('Process'), + key('a'), + key('z', { ctrlKey: true }), + key('y', { metaKey: true }), + key('Tab', { ctrlKey: true }), + key('ArrowLeft', { isComposing: true }), + key('ArrowLeft', { keyCode: 229 }), + ]) { + expect(keyCommand(k, true)).toBeNull(); + } + expect(keyCommand(key('z', { metaKey: true }), false)).toBeNull(); + expect(keyCommand(key('ArrowLeft', { altKey: true }), false)).toBeNull(); +}); diff --git a/src/web/__tests__/loader.test.ts b/src/web/__tests__/loader.test.ts index 5063df5..692319a 100644 --- a/src/web/__tests__/loader.test.ts +++ b/src/web/__tests__/loader.test.ts @@ -226,3 +226,21 @@ test('retries languages.json when its body was cut off by a network error', asyn dropped.clear(); await expect(loader.ensureLanguage(m, 'python')).resolves.toBe(true); }); + +test('loads the installed languages a fence names and resolves with them', async () => { + const m = await loader.loadCore(); + await expect(loader.ensureInjected(m, ['Python', 'py', 'rust'])).resolves.toEqual(['python']); + expect(loaded).toEqual(['python']); + expect(warn).not.toHaveBeenCalled(); +}); + +test('tells each listener once when a language registers, whatever loaded it', async () => { + const m = await loader.loadCore(); + const heard: string[] = []; + const off = loader.onRegistered((id) => heard.push(id)); + await loader.ensureLanguage(m, 'python'); + await loader.ensureInjected(m, ['python']); + off(); + await loader.ensureLanguage(m, 'css'); + expect(heard).toEqual(['python']); +}); diff --git a/src/web/core/EditorCore.ts b/src/web/core/EditorCore.ts index ac3647b..5a8c4c3 100644 --- a/src/web/core/EditorCore.ts +++ b/src/web/core/EditorCore.ts @@ -305,6 +305,19 @@ export class EditorCore { this.m._cp_editor_set_selection(this.handle, clampInt(anchor), clampInt(head)); } + // Edits between beginGroup and endGroup undo as one step, as a keyboard's composed word does. + beginGroup(): void { + this.m._cp_editor_begin_group(this.handle); + } + endGroup(): void { + this.m._cp_editor_end_group(this.handle); + } + + // True when a backspace at caret would take an auto-closed pair, like the caret between ( and ). + deletesPair(caret: number): boolean { + return this.m._cp_editor_deletes_pair(this.handle, clampUnsigned(caret)) !== 0; + } + move(unit: MoveUnit, forward: boolean, extend: boolean): void { this.m._cp_editor_move(this.handle, MOVES.indexOf(unit), forward ? 1 : 0, extend ? 1 : 0); } @@ -413,6 +426,23 @@ export class EditorCore { return this.m._cpw_snapshot_count(this.index); } + // The injection names that found no language since the last call, so the page can load them. + takeMissedLanguages(): string[] { + for (let cap = 256; ; ) { + const out = this.m._malloc(cap); + const size = this.m._cpw_take_missed(this.index, out, cap); + const joined = size > 0 && size <= cap ? this.m.UTF8ToString(out, size) : ''; + this.m._free(out); + if (size <= cap) return joined ? joined.split('\n') : []; + cap = size; + } + } + + // Looks the missing injection names up again and repaints, after a language they may name registered. + refreshInjections(): void { + this.m._cpw_refresh(this.index); + } + // Pins the history clock to millis, for tests and recordings. Below zero follows the page clock. setClock(millis: number): void { this.m._cpw_set_clock(this.index, millis); diff --git a/src/web/core/module.ts b/src/web/core/module.ts index 675d396..dcf93c7 100644 --- a/src/web/core/module.ts +++ b/src/web/core/module.ts @@ -33,6 +33,8 @@ export interface CoreModule { _cpw_layout(e: number): Ptr; _cpw_snapshot(e: number): Ptr; _cpw_snapshot_count(e: number): number; + _cpw_take_missed(e: number, out: Ptr, cap: number): number; + _cpw_refresh(e: number): void; _cpw_set_clock(e: number, millis: number): void; _cpw_pump(budgetMs: number): number; _cpw_take_changes( @@ -72,6 +74,9 @@ export interface CoreModule { _cp_editor_type(ed: Ptr, text: Ptr, length: number): void; _cp_editor_command(ed: Ptr, command: number): number; _cp_editor_set_selection(ed: Ptr, anchor: number, head: number): void; + _cp_editor_begin_group(ed: Ptr): void; + _cp_editor_end_group(ed: Ptr): void; + _cp_editor_deletes_pair(ed: Ptr, caret: number): number; _cp_editor_move(ed: Ptr, unit: number, forward: number, extend: number): void; _cp_editor_select_word_at(ed: Ptr, offset: number): void; _cp_editor_selection(ed: Ptr): bigint; diff --git a/src/web/input/CaretMover.ts b/src/web/input/CaretMover.ts new file mode 100644 index 0000000..8327726 --- /dev/null +++ b/src/web/input/CaretMover.ts @@ -0,0 +1,52 @@ +// The document as the mover reads it. +export type DocLike = { + readonly lineCount: number; + readonly length: number; + lineAt(offset: number): number; + lineStart(line: number): number; +}; + +// Visual rows of laid out lines, in pixels from the line's left edge, answered by the view. +export type LineGeometry = { + rows(line: number): number; + rowOf(line: number, column: number): number; + caretX(line: number, column: number): number; + columnAt(line: number, row: number, x: number): number; +}; + +// Up, down and page movement by visual rows, the web twin of CaretMover.kt. The goal x lasts until reset. +export class CaretMover { + private goalX: number | null = null; + + reset(): void { + this.goalX = null; + } + + // The offset rows visual rows from offset (negative is up), clamped to the document ends. + target(doc: DocLike, geometry: LineGeometry, offset: number, rows: number): number { + let line = doc.lineAt(offset); + const column = offset - doc.lineStart(line); + let row = geometry.rowOf(line, column); + const x = this.goalX ?? geometry.caretX(line, column); + this.goalX = x; + for (let left = rows; left < 0; left++) { + if (row > 0) { + row--; + } else { + if (line === 0) return 0; + line--; + row = geometry.rows(line) - 1; + } + } + for (let left = rows; left > 0; left--) { + if (row < geometry.rows(line) - 1) { + row++; + } else { + if (line === doc.lineCount - 1) return doc.length; + line++; + row = 0; + } + } + return doc.lineStart(line) + geometry.columnAt(line, row, x); + } +} diff --git a/src/web/input/InputHost.ts b/src/web/input/InputHost.ts new file mode 100644 index 0000000..64911e6 --- /dev/null +++ b/src/web/input/InputHost.ts @@ -0,0 +1,156 @@ +/// +import type { Suggestions } from '../../types'; +import type { TextareaState, WebInputSession } from './WebInputSession'; + +export type InputHooks = { + // True when the key ran an editor command, so the browser must not act on it. + keyDown(e: KeyboardEvent): boolean; + // The selected text for the clipboard, deleted first for a cut. Null leaves the event to the browser. + clipboard(cut: boolean): string | null; + focusChanged(focused: boolean): void; + changed(): void; +}; + +const SUGGESTION_ATTRIBUTES: [string, string, string][] = [ + ['autocomplete', 'on', 'off'], + ['autocorrect', 'on', 'off'], + ['autocapitalize', 'sentences', 'off'], + ['spellcheck', 'true', 'false'], +]; + +// The hidden textarea the keyboard types into, wired to a WebInputSession. +export class InputHost { + readonly textarea: HTMLTextAreaElement; + // iOS reports the selection as 0,0 for a moment after focus, so selection changes wait a frame. + private settling = false; + private settleTimer: ReturnType | undefined; + private readonly listeners: [EventTarget, string, EventListener][] = []; + + constructor( + root: HTMLElement, + private readonly session: WebInputSession, + private readonly hooks: InputHooks, + ) { + const ta = document.createElement('textarea'); + // 16px keeps iOS from zooming the page on focus. + ta.style.cssText = + 'position:absolute;left:0;top:0;width:2px;height:1px;padding:0;border:0;margin:0;opacity:0;' + + 'resize:none;overflow:hidden;white-space:pre;font-size:16px;line-height:1;color:transparent;' + + 'background:transparent;caret-color:transparent;outline:none;pointer-events:none;'; + this.textarea = ta; + this.setSuggestions('off'); + root.append(ta); + this.on(ta, 'beforeinput', () => this.session.beforeInput(this.state())); + this.on(ta, 'input', (e) => { + const ie = e as InputEvent; + this.write( + this.session.input( + { inputType: ie.inputType ?? '', data: ie.data ?? null, isComposing: !!ie.isComposing }, + this.state(), + ), + ); + this.hooks.changed(); + }); + this.on(ta, 'compositionstart', () => { + this.session.compositionStart(this.state()); + this.hooks.changed(); + }); + this.on(ta, 'compositionend', () => { + this.session.compositionEnd(); + this.hooks.changed(); + // A browser may still send the composition's last input after this event, so the window moves a task later. + clearTimeout(this.settleTimer); + this.settleTimer = setTimeout(() => { + this.settleTimer = undefined; + this.write(this.session.settle(this.state())); + this.hooks.changed(); + }, 0); + }); + this.on(ta, 'copy', (e) => this.clip(e as ClipboardEvent, false)); + this.on(ta, 'cut', (e) => this.clip(e as ClipboardEvent, true)); + this.on(ta, 'keydown', (e) => { + if (this.hooks.keyDown(e as KeyboardEvent)) e.preventDefault(); + }); + this.on(ta, 'focus', () => { + this.settling = true; + requestAnimationFrame(() => { + this.settling = false; + }); + this.hooks.focusChanged(true); + }); + this.on(ta, 'blur', () => { + this.session.finishComposition(); + this.hooks.focusChanged(false); + }); + this.on(document, 'selectionchange', () => { + if (this.settling || document.activeElement !== ta) return; + this.write(this.session.selectionChange(this.state())); + this.hooks.changed(); + }); + } + + get focused(): boolean { + return document.activeElement === this.textarea; + } + + state(): TextareaState { + const ta = this.textarea; + return { value: ta.value, start: ta.selectionStart, end: ta.selectionEnd }; + } + + write(state: TextareaState | null): void { + if (!state) return; + const ta = this.textarea; + if (ta.value !== state.value) ta.value = state.value; + if (ta.selectionStart !== state.start || ta.selectionEnd !== state.end) + ta.setSelectionRange(state.start, state.end); + } + + // Keeps the textarea at the caret, so the keyboard's candidate window opens there. + place(x: number, y: number): void { + const s = this.textarea.style; + const left = `${Math.round(x)}px`; + const top = `${Math.round(y)}px`; + // An unchanged write still invalidates the page's layout. + if (s.left !== left) s.left = left; + if (s.top !== top) s.top = top; + } + + focus(): void { + this.write(this.session.sync()); + this.textarea.focus({ preventScroll: true }); + } + + blur(): void { + this.textarea.blur(); + } + + setSuggestions(suggestions: Suggestions): void { + for (const [name, on, off] of SUGGESTION_ATTRIBUTES) + this.textarea.setAttribute(name, suggestions === 'on' ? on : off); + } + + // A read only textarea brings no keyboard on a phone, while selection still works. + setReadOnly(readOnly: boolean): void { + this.textarea.readOnly = readOnly; + } + + destroy(): void { + clearTimeout(this.settleTimer); + for (const [target, type, fn] of this.listeners) target.removeEventListener(type, fn); + this.textarea.remove(); + } + + // The textarea holds only a window, so the clipboard takes the editor's whole selection. + private clip(e: ClipboardEvent, cut: boolean): void { + const text = this.hooks.clipboard(cut); + if (text === null || !e.clipboardData) return; + e.clipboardData.setData('text/plain', text); + e.preventDefault(); + } + + private on(target: EventTarget, type: string, fn: EventListener): void { + target.addEventListener(type, fn); + this.listeners.push([target, type, fn]); + } +} diff --git a/src/web/input/WebInputSession.ts b/src/web/input/WebInputSession.ts new file mode 100644 index 0000000..7ada5f7 --- /dev/null +++ b/src/web/input/WebInputSession.ts @@ -0,0 +1,189 @@ +import type { EditorCore } from '../core/EditorCore'; +import { windowAround } from './window'; + +// What the keyboard's textarea holds: its value and its selection, in textarea units. +export type TextareaState = { value: string; start: number; end: number }; +export type InputLike = { inputType: string; data: string | null; isComposing: boolean }; +type Range = { start: number; end: number }; + +const codePoints = (s: string) => [...s].length; +// Input that auto-closes and indents as typing does. A paste or a replacement goes in as written. +const TYPED = new Set(['insertText', 'insertLineBreak', 'insertParagraph']); + +// The web twin of ImeSession: maps a textarea holding a window of the document onto the core. +export class WebInputSession { + private win = { start: 0, value: '', line: 0 }; + private before: Range | null = null; + private composed: Range | null = null; + // The textarea state sync last handed out. + private written: TextareaState | null = null; + + constructor( + private readonly core: EditorCore, + private readonly apply: (edit: () => void) => void, + ) {} + + get windowStart(): number { + return this.win.start; + } + + // The document range the keyboard is composing, drawn underlined. + get composing(): Range | null { + return this.composed ? { ...this.composed } : null; + } + + // The window around the core's selection, to write into the textarea. Null while composing. + sync(): TextareaState | null { + if (this.composed) return null; + const { start, end } = windowAround(this.core); + const { anchor, head } = this.core.selection; + this.win = { start, value: this.core.text(start, end), line: this.core.lineAt(head) }; + // A selection longer than the window shows as the whole window selected. + const clamp = (offset: number) => Math.min(Math.max(offset - start, 0), end - start); + this.written = { + value: this.win.value, + start: clamp(Math.min(anchor, head)), + end: clamp(Math.max(anchor, head)), + }; + return { ...this.written }; + } + + // The selection the edit replaces, which a diff alone cannot place (Enter before a newline). + beforeInput(ta: TextareaState): void { + this.before = { start: ta.start, end: ta.end }; + } + + input(e: InputLike, ta: TextareaState): TextareaState | null { + this.written = null; + const typing = TYPED.has(e.inputType); + let grown = false; + const old = this.win.value; + const next = ta.value; + const ws = this.win.start; + const sel = this.before ?? { start: ta.start, end: ta.start }; + this.before = null; + let p = 0; + const pMax = Math.min(sel.start, ta.start, old.length, next.length); + while (p < pMax && old.charCodeAt(p) === next.charCodeAt(p)) p++; + let s = 0; + const sMax = Math.min(old.length - Math.max(sel.end, p), next.length - Math.max(ta.end, p)); + while (s < sMax && old.charCodeAt(old.length - 1 - s) === next.charCodeAt(next.length - 1 - s)) + s++; + let start = ws + p; + let end = ws + old.length - s; + const inserted = next.slice(p, next.length - s); + const { anchor, head } = this.core.selection; + const selStart = Math.min(anchor, head); + const selEnd = Math.max(anchor, head); + const winEnd = ws + old.length; + // A selection longer than the window goes whole, though the textarea held only its middle. + if ( + selEnd > selStart && + (selStart < ws || selEnd > winEnd) && + start <= Math.max(selStart, ws) && + end >= Math.min(selEnd, winEnd) + ) { + start = Math.min(start, selStart); + grown = true; + end = Math.max(end, selEnd); + } + const composing = this.composed !== null || e.isComposing; + const lengthBefore = this.core.length; + let coreCaret = false; + this.apply(() => { + const removed = this.core.text(start, end); + if (composing) { + this.core.inputReplace(start, end, inserted); + if (this.composed) this.composed = { start, end: start + inserted.length }; + this.select(start + inserted.length, start + inserted.length); + coreCaret = true; + } else if (typing && start === end && inserted === '\n') { + this.select(start, start); + this.core.insertNewline(); + coreCaret = true; + } else if (typing && start === end && codePoints(inserted) === 1) { + this.select(start, start); + this.core.typeText(inserted); + coreCaret = true; + } else if ( + inserted === '' && + codePoints(removed) === 1 && + selStart === selEnd && + end === selEnd && + this.core.deletesPair(end) + ) { + this.core.inputReplace(start, end + 1, '', true); + coreCaret = true; + } else if (start !== end || inserted !== '') { + this.core.inputReplace(start, end, inserted, inserted === '' && codePoints(removed) === 1); + } + const caret = start + inserted.length; + if (grown) this.select(caret, caret); + else if (!coreCaret) this.select(ws + ta.start, ws + ta.end); + }); + const coreWindow = this.core.text(ws, winEnd + this.core.length - lengthBefore); + const caret = this.core.selection; + const mirrors = + coreWindow === next && + Math.min(caret.anchor, caret.head) === ws + ta.start && + Math.max(caret.anchor, caret.head) === ws + ta.end; + if (composing) { + this.win.value = next; + return null; + } + if (!mirrors) return this.sync(); + this.win.value = next; + return this.core.lineAt(caret.head) !== this.win.line ? this.sync() : null; + } + + compositionStart(ta: TextareaState): void { + const ws = this.win.start; + this.composed = { start: ws + ta.start, end: ws + ta.end }; + this.core.beginGroup(); + } + + // The window stays as the textarea shows it, since a browser may still send the composition's last input. + compositionEnd(): void { + this.finishComposition(); + } + + // After compositionend has settled: a new window when the caret left the window's middle line. + settle(ta: TextareaState): TextareaState | null { + return this.composed ? null : this.follow(ta); + } + + // The user moved the caret, ignored while composing and for the echo of what sync wrote. + selectionChange(ta: TextareaState): TextareaState | null { + if (this.composed || ta.value !== this.win.value) return null; + const w = this.written; + if (w && ta.value === w.value && ta.start === w.start && ta.end === w.end) return null; + const ws = this.win.start; + this.written = null; + this.apply(() => this.select(ws + ta.start, ws + ta.end)); + return this.follow(ta); + } + + // The core is about to change from outside the keyboard: the composition ends first, so the edit undoes alone. + external(): void { + this.finishComposition(); + } + + finishComposition(): void { + if (!this.composed) return; + this.composed = null; + this.core.endGroup(); + } + + // A new window once the head left the window's middle line or the core no longer matches the textarea. + private follow(ta: TextareaState): TextareaState | null { + const ws = this.win.start; + const head = this.core.selection.head; + const same = this.core.text(ws, ws + ta.value.length) === ta.value; + return !same || this.core.lineAt(head) !== this.win.line ? this.sync() : null; + } + + private select(anchor: number, head: number): void { + const s = this.core.selection; + if (s.anchor !== anchor || s.head !== head) this.core.setSelection(anchor, head); + } +} diff --git a/src/web/input/keyboardInset.ts b/src/web/input/keyboardInset.ts new file mode 100644 index 0000000..805df8a --- /dev/null +++ b/src/web/input/keyboardInset.ts @@ -0,0 +1,32 @@ +/// + +// The editor's overlap with what the visual viewport lost from the layout viewport, which a keyboard covers. +export function keyboardOverlap( + editorBottom: number, + viewportTop: number, + viewportHeight: number, + layoutHeight: number, +): number { + return Math.max(0, Math.min(editorBottom, layoutHeight) - (viewportTop + viewportHeight)); +} + +// The keyboard's overlap with an element's box, 0 where the page has no visual viewport or is pinch-zoomed. +export function overlapOf(el: HTMLElement): number { + const vv = typeof window === 'undefined' ? undefined : window.visualViewport; + if (!vv || Math.abs(vv.scale - 1) > 0.01) return 0; + const bottom = el.getBoundingClientRect().bottom; + const layout = document.documentElement.clientHeight; + return Math.round(keyboardOverlap(bottom, vv.offsetTop, vv.height, layout)); +} + +// Calls back when the visual viewport moves or resizes, as the keyboard opens, closes or animates. Returns the removal. +export function watchViewport(changed: () => void): () => void { + const vv = typeof window === 'undefined' ? undefined : window.visualViewport; + if (!vv) return () => {}; + vv.addEventListener('resize', changed); + vv.addEventListener('scroll', changed); + return () => { + vv.removeEventListener('resize', changed); + vv.removeEventListener('scroll', changed); + }; +} diff --git a/src/web/input/keys.ts b/src/web/input/keys.ts new file mode 100644 index 0000000..1ca0320 --- /dev/null +++ b/src/web/input/keys.ts @@ -0,0 +1,92 @@ +import type { MoveUnit } from '../core/EditorCore'; + +export type KeyLike = { + key: string; + shiftKey: boolean; + altKey: boolean; + ctrlKey: boolean; + metaKey: boolean; + isComposing: boolean; + code?: string; + keyCode?: number; +}; + +export type KeyCommand = + | { kind: 'move'; unit: MoveUnit; forward: boolean; extend: boolean } + | { kind: 'vertical'; by: 'row' | 'page'; forward: boolean; extend: boolean } + | { kind: 'tab' | 'shiftTab' | 'undo' | 'redo' | 'selectAll' }; + +// Keydown 229 is a key the keyboard's composition takes. +const COMPOSING_KEY_CODE = 229; + +// The letter of a shortcut, from the physical key when the layout's key is not a Latin letter. +function letter(k: KeyLike): string { + const key = k.key.toLowerCase(); + if (/^[a-z]$/.test(key)) return key; + return /^Key[A-Z]$/.test(k.code ?? '') ? (k.code as string).slice(3).toLowerCase() : key; +} + +// What a hardware key asks the editor to do, or null for a key the textarea handles itself. +export function keyCommand(k: KeyLike, mac: boolean): KeyCommand | null { + if (k.isComposing || k.keyCode === COMPOSING_KEY_CODE) return null; + const extend = k.shiftKey; + const move = (unit: MoveUnit, forward: boolean): KeyCommand => ({ + kind: 'move', + unit, + forward, + extend, + }); + const vertical = (by: 'row' | 'page', forward: boolean): KeyCommand => ({ + kind: 'vertical', + by, + forward, + extend, + }); + // Command on a Mac, Control elsewhere. + const primary = mac ? k.metaKey && !k.ctrlKey : k.ctrlKey && !k.metaKey; + const plain = !k.ctrlKey && !k.metaKey && !k.altKey; + switch (k.key) { + case 'ArrowLeft': + case 'ArrowRight': { + const forward = k.key === 'ArrowRight'; + if (plain) return move('char', forward); + if (mac && k.altKey && !k.metaKey && !k.ctrlKey) return move('word', forward); + if (mac && k.metaKey && !k.altKey && !k.ctrlKey) + return move(forward ? 'lineEnd' : 'lineStart', forward); + if (!mac && k.ctrlKey && !k.altKey && !k.metaKey) return move('word', forward); + return null; + } + case 'ArrowUp': + case 'ArrowDown': { + const forward = k.key === 'ArrowDown'; + if (plain) return vertical('row', forward); + if (mac && k.metaKey && !k.altKey && !k.ctrlKey) + return move(forward ? 'docEnd' : 'docStart', forward); + return null; + } + case 'PageUp': + case 'PageDown': + return plain ? vertical('page', k.key === 'PageDown') : null; + case 'Home': + case 'End': { + const forward = k.key === 'End'; + if (plain) return move(forward ? 'lineEnd' : 'lineStart', forward); + if ((k.ctrlKey || k.metaKey) && !k.altKey) + return move(forward ? 'docEnd' : 'docStart', forward); + return null; + } + case 'Tab': + if (!plain) return null; + return { kind: k.shiftKey ? 'shiftTab' : 'tab' }; + } + if (!primary || k.altKey) return null; + switch (letter(k)) { + case 'z': + return { kind: k.shiftKey ? 'redo' : 'undo' }; + case 'y': + return !mac && !k.shiftKey ? { kind: 'redo' } : null; + case 'a': + return k.shiftKey ? null : { kind: 'selectAll' }; + } + return null; +} diff --git a/src/web/input/window.ts b/src/web/input/window.ts new file mode 100644 index 0000000..b232bc1 --- /dev/null +++ b/src/web/input/window.ts @@ -0,0 +1,18 @@ +import type { EditorCore } from '../core/EditorCore'; + +// The most text the keyboard's textarea holds, like the native text window. +export const WINDOW_CAP = 8192; + +// The caret's line and its two neighbors, widened to the selection, at most WINDOW_CAP units around the head. +export function windowAround(core: EditorCore): { start: number; end: number } { + const { anchor, head } = core.selection; + const first = Math.max(0, core.lineAt(Math.min(anchor, head)) - 1); + const last = Math.min(core.lineCount - 1, core.lineAt(Math.max(anchor, head)) + 1); + let start = core.lineStart(first); + let end = core.lineEnd(last); + if (end - start > WINDOW_CAP) { + start = Math.min(Math.max(start, head - WINDOW_CAP / 2), end - WINDOW_CAP); + end = start + WINDOW_CAP; + } + return { start, end }; +} diff --git a/src/web/loader.ts b/src/web/loader.ts index 4b81d25..1b2e313 100644 --- a/src/web/loader.ts +++ b/src/web/loader.ts @@ -23,6 +23,29 @@ let manifest: Promise | null = null; let ids: string[] = []; // Each language registered on its own, resolving to the ids its injection query names, or null when it failed. const languages = new Map>(); +const registered = new Set<(id: string) => void>(); + +// Calls the listener with each language id the first time it registers, and returns its removal. +export function onRegistered(listener: (id: string) => void): () => void { + registered.add(listener); + return () => { + registered.delete(listener); + }; +} + +// Loads the installed languages that injection names map to, and resolves with the ids now registered. +export async function ensureInjected(m: CoreModule, names: string[]): Promise { + const list = await loadManifest().catch(() => null); + if (!list) return []; + const installed = (id: string) => list.languages.some((l) => l.id === id); + const ids = new Set(); + for (const name of names) { + const id = canonicalInjectionId(name, installed); + if (id && installed(id)) ids.add(id); + } + const loaded = await Promise.all([...ids].map((id) => ensureLanguage(m, id))); + return [...ids].filter((_, i) => loaded[i]); +} // The page's one core, injected by a script tag from the assets folder on first use. export function loadCore(): Promise { @@ -186,6 +209,7 @@ async function loadLanguage(m: CoreModule, id: string): Promise ); return null; } + for (const listener of [...registered]) listener(id); return [...injected]; } diff --git a/src/web/pump.ts b/src/web/pump.ts index 72fd53c..4f64fe8 100644 --- a/src/web/pump.ts +++ b/src/web/pump.ts @@ -1,14 +1,49 @@ import type { CoreModule } from './core/module'; -// The engine's share of a frame, so a key still draws inside it. +// The engine's share of a task, so a key still draws soon after it. export const PUMP_BUDGET_MS = 6; -type View = { draw(): void }; +// urgent: the view's next frame waits for the parse. pending: it has something to draw. +type View = { draw(): void; readonly urgent: boolean; pending(): boolean }; +// Per key: work and its three parts, the handler, the engine share of the frame that draws it, and that draw. +type Probe = { + work: number[]; + handler: number[]; + engine: number[]; + draw: number[]; + pumps: number[]; + // Each engine task run between frames. + tasks: number[]; +}; const views = new Set(); let core: CoreModule | null = null; let scheduled = false; +// With localStorage codepad_debug set to 1 at load, the bench reads key and frame times from globalThis. +const probe: Probe | null = debugOn() + ? { work: [], handler: [], engine: [], draw: [], pumps: [], tasks: [] } + : null; +if (probe) (globalThis as { __codepadProbe?: Probe }).__codepadProbe = probe; +let keyView: View | null = null; +let keyMs = 0; + +function debugOn(): boolean { + try { + return globalThis.localStorage?.getItem('codepad_debug') === '1'; + } catch { + return false; + } +} + +export const probing = probe !== null; + +// A key's handler time, counted into the work of the next frame that draws its view. +export function probeKey(view: View, ms: number): void { + keyView = view; + keyMs += ms; +} + export function setPumpCore(m: CoreModule): void { core = m; } @@ -22,7 +57,7 @@ export function registerView(view: View): () => void { }; } -// One shared frame: the engine runs its queued work, then every view draws. A view asks for the next frame here. +// One shared frame: every view draws, then the engine runs after the paint unless a view is urgent. export function requestPump(): void { if (scheduled) return; scheduled = true; @@ -31,7 +66,49 @@ export function requestPump(): void { function frame(): void { scheduled = false; - const left = core ? core._cpw_pump(PUMP_BUDGET_MS) : 0; - for (const view of [...views]) view.draw(); + const start = probe ? performance.now() : 0; + const urgent = [...views].some((v) => v.urgent); + const left = core && urgent ? core._cpw_pump(PUMP_BUDGET_MS) : 0; + const pumped = probe ? performance.now() - start : 0; + for (const view of [...views]) { + const drawStart = probe ? performance.now() : 0; + view.draw(); + if (probe && view === keyView) { + const drawn = performance.now() - drawStart; + probe.work.push(keyMs + pumped + drawn); + probe.handler.push(keyMs); + probe.engine.push(pumped); + probe.draw.push(drawn); + keyView = null; + keyMs = 0; + } + } + if (probe) probe.pumps.push(performance.now() - start); if (left > 0) requestPump(); + else postEngine(); +} + +let channel: MessageChannel | null = null; +let engineQueued = false; + +function postEngine(): void { + if (engineQueued || !core) return; + engineQueued = true; + if (!channel && typeof MessageChannel !== 'undefined') { + channel = new MessageChannel(); + channel.port1.onmessage = runEngine; + } + if (channel) channel.port2.postMessage(0); + else setTimeout(runEngine, 0); +} + +// The engine's queued work between frames: a snapshot it publishes draws in the next frame. +function runEngine(): void { + engineQueued = false; + if (!core) return; + const start = probe ? performance.now() : 0; + const left = core._cpw_pump(PUMP_BUDGET_MS); + if (probe) probe.tasks.push(performance.now() - start); + if ([...views].some((v) => v.pending())) requestPump(); + if (left > 0) postEngine(); } diff --git a/tests/ime-web/gboard-emoji.json b/tests/ime-web/gboard-emoji.json new file mode 100644 index 0000000..ca6a487 --- /dev/null +++ b/tests/ime-web/gboard-emoji.json @@ -0,0 +1,445 @@ +{ + "name": "gboard-emoji", + "browser": "chrome-android", + "keyboard": "Gboard EN FR, suggestions on, emoji suggestion then two Backspaces", + "ua": "Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/157.0.0.0 Mobile Safari/537.36", + "recordedAt": "2026-11-14T21:33:26.751Z", + "settings": { + "autoCloseBrackets": false, + "autoIndent": false + }, + "initial": { + "text": "def step_0(value):\n total = value + 1\n total = value + 2\n total = value + 3\n total = value + 4\ndef step_5(value):\n total = value + 6\n total = value + 7\n total = value + 8\n total = value + 9\ndef step_10(value):\n total = value + 11\n total = value + 12\n total = value + 13\n total = value + 14\ndef step_15(value):\n total = value + 16\n total = value + 17\n total = value + 18\n total = value + 19\ndef step_20(value):\n total = value + 21\n total = value + 22\n total = value + 23\n total = value + 24\ndef step_25(value):\n total = value + 26\n total = value + 27\n total = value + 28\n total = value + 29", + "selection": [233, 233] + }, + "events": [ + { + "t": 1, + "type": "sync", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):\n total = value + 11", + "start": 41, + "end": 41 + } + }, + { + "t": 1848, + "type": "focus", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):\n total = value + 11", + "start": 0, + "end": 0 + } + }, + { + "t": 1854, + "type": "selectionchange", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):\n total = value + 11", + "start": 41, + "end": 41 + } + }, + { + "t": 3103, + "type": "keydown", + "key": "Unidentified", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):\n total = value + 11", + "start": 41, + "end": 41 + } + }, + { + "t": 3106, + "type": "beforeinput", + "inputType": "insertText", + "data": " ", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):\n total = value + 11", + "start": 41, + "end": 41 + } + }, + { + "t": 3108, + "type": "input", + "inputType": "insertText", + "data": " ", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): \n total = value + 11", + "start": 42, + "end": 42 + } + }, + { + "t": 3116, + "type": "selectionchange", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): \n total = value + 11", + "start": 42, + "end": 42 + } + }, + { + "t": 3460, + "type": "keydown", + "key": "Unidentified", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): \n total = value + 11", + "start": 42, + "end": 42 + } + }, + { + "t": 3461, + "type": "beforeinput", + "inputType": "insertText", + "data": "h", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): \n total = value + 11", + "start": 42, + "end": 42 + } + }, + { + "t": 3461, + "type": "input", + "inputType": "insertText", + "data": "h", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): h\n total = value + 11", + "start": 43, + "end": 43 + } + }, + { + "t": 3467, + "type": "selectionchange", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): h\n total = value + 11", + "start": 43, + "end": 43 + } + }, + { + "t": 3756, + "type": "keydown", + "key": "Unidentified", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): h\n total = value + 11", + "start": 43, + "end": 43 + } + }, + { + "t": 3757, + "type": "beforeinput", + "inputType": "insertText", + "data": "e", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): h\n total = value + 11", + "start": 43, + "end": 43 + } + }, + { + "t": 3758, + "type": "input", + "inputType": "insertText", + "data": "e", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): he\n total = value + 11", + "start": 44, + "end": 44 + } + }, + { + "t": 3767, + "type": "selectionchange", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): he\n total = value + 11", + "start": 44, + "end": 44 + } + }, + { + "t": 4055, + "type": "keydown", + "key": "Unidentified", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): he\n total = value + 11", + "start": 44, + "end": 44 + } + }, + { + "t": 4056, + "type": "beforeinput", + "inputType": "insertText", + "data": "l", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): he\n total = value + 11", + "start": 44, + "end": 44 + } + }, + { + "t": 4057, + "type": "input", + "inputType": "insertText", + "data": "l", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): hel\n total = value + 11", + "start": 45, + "end": 45 + } + }, + { + "t": 4074, + "type": "selectionchange", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): hel\n total = value + 11", + "start": 45, + "end": 45 + } + }, + { + "t": 26410, + "type": "keydown", + "key": "Unidentified", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): hel\n total = value + 11", + "start": 45, + "end": 45 + } + }, + { + "t": 26411, + "type": "beforeinput", + "inputType": "deleteContentBackward", + "data": null, + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): hel\n total = value + 11", + "start": 42, + "end": 45 + } + }, + { + "t": 26412, + "type": "input", + "inputType": "deleteContentBackward", + "data": null, + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): \n total = value + 11", + "start": 42, + "end": 42 + } + }, + { + "t": 26413, + "type": "keydown", + "key": "Unidentified", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): \n total = value + 11", + "start": 42, + "end": 42 + } + }, + { + "t": 26414, + "type": "beforeinput", + "inputType": "insertText", + "data": "👋🏻 ", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): \n total = value + 11", + "start": 42, + "end": 42 + } + }, + { + "t": 26426, + "type": "input", + "inputType": "insertText", + "data": "👋🏻 ", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): 👋🏻 \n total = value + 11", + "start": 47, + "end": 47 + } + }, + { + "t": 26429, + "type": "selectionchange", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): 👋🏻 \n total = value + 11", + "start": 47, + "end": 47 + } + }, + { + "t": 27149, + "type": "keydown", + "key": "Backspace", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): 👋🏻 \n total = value + 11", + "start": 47, + "end": 47 + } + }, + { + "t": 27152, + "type": "beforeinput", + "inputType": "deleteContentBackward", + "data": null, + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): 👋🏻 \n total = value + 11", + "start": 47, + "end": 47 + } + }, + { + "t": 27156, + "type": "input", + "inputType": "deleteContentBackward", + "data": null, + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): 👋🏻\n total = value + 11", + "start": 46, + "end": 46 + } + }, + { + "t": 27162, + "type": "selectionchange", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): 👋🏻\n total = value + 11", + "start": 46, + "end": 46 + } + }, + { + "t": 27802, + "type": "keydown", + "key": "Unidentified", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): 👋🏻\n total = value + 11", + "start": 46, + "end": 46 + } + }, + { + "t": 27805, + "type": "beforeinput", + "inputType": "deleteContentBackward", + "data": null, + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): 👋🏻\n total = value + 11", + "start": 42, + "end": 46 + } + }, + { + "t": 27808, + "type": "input", + "inputType": "deleteContentBackward", + "data": null, + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): \n total = value + 11", + "start": 42, + "end": 42 + } + }, + { + "t": 27815, + "type": "selectionchange", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): \n total = value + 11", + "start": 42, + "end": 42 + } + }, + { + "t": 28560, + "type": "blur", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): \n total = value + 11", + "start": 42, + "end": 42 + } + } + ], + "expected": { + "text": "def step_0(value):\n total = value + 1\n total = value + 2\n total = value + 3\n total = value + 4\ndef step_5(value):\n total = value + 6\n total = value + 7\n total = value + 8\n total = value + 9\ndef step_10(value): \n total = value + 11\n total = value + 12\n total = value + 13\n total = value + 14\ndef step_15(value):\n total = value + 16\n total = value + 17\n total = value + 18\n total = value + 19\ndef step_20(value):\n total = value + 21\n total = value + 22\n total = value + 23\n total = value + 24\ndef step_25(value):\n total = value + 26\n total = value + 27\n total = value + 28\n total = value + 29" + } +} diff --git a/tests/ime-web/gboard-enter-backspace.json b/tests/ime-web/gboard-enter-backspace.json new file mode 100644 index 0000000..df8ba1b --- /dev/null +++ b/tests/ime-web/gboard-enter-backspace.json @@ -0,0 +1,282 @@ +{ + "name": "gboard-enter-backspace", + "browser": "chrome-android", + "keyboard": "Gboard EN FR, suggestions off", + "ua": "Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/157.0.0.0 Mobile Safari/537.36", + "recordedAt": "2026-11-14T21:32:28.645Z", + "settings": { + "autoCloseBrackets": false, + "autoIndent": false + }, + "initial": { + "text": "def step_0(value):\n total = value + 1\n total = value + 2\n total = value + 3\n total = value + 4\ndef step_5(value):\n total = value + 6\n total = value + 7\n total = value + 8\n total = value + 9\ndef step_10(value):\n total = value + 11\n total = value + 12\n total = value + 13\n total = value + 14\ndef step_15(value):\n total = value + 16\n total = value + 17\n total = value + 18\n total = value + 19\ndef step_20(value):\n total = value + 21\n total = value + 22\n total = value + 23\n total = value + 24\ndef step_25(value):\n total = value + 26\n total = value + 27\n total = value + 28\n total = value + 29", + "selection": [233, 233] + }, + "events": [ + { + "t": 1, + "type": "sync", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):\n total = value + 11", + "start": 41, + "end": 41 + } + }, + { + "t": 14724, + "type": "focus", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):\n total = value + 11", + "start": 0, + "end": 0 + } + }, + { + "t": 14732, + "type": "selectionchange", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):\n total = value + 11", + "start": 31, + "end": 31 + } + }, + { + "t": 16040, + "type": "keydown", + "key": "Enter", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):\n total = value + 11", + "start": 31, + "end": 31 + } + }, + { + "t": 16049, + "type": "beforeinput", + "inputType": "insertLineBreak", + "data": null, + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):\n total = value + 11", + "start": 31, + "end": 31 + } + }, + { + "t": 16055, + "type": "input", + "inputType": "insertLineBreak", + "data": null, + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_\n10(value):\n total = value + 11", + "start": 32, + "end": 32 + } + }, + { + "t": 16056, + "type": "sync", + "isComposing": false, + "windowStart": 214, + "ta": { + "value": "def step_\n10(value):\n total = value + 11", + "start": 10, + "end": 10 + } + }, + { + "t": 16062, + "type": "selectionchange", + "isComposing": false, + "windowStart": 214, + "ta": { + "value": "def step_\n10(value):\n total = value + 11", + "start": 10, + "end": 10 + } + }, + { + "t": 16529, + "type": "keydown", + "key": "Backspace", + "isComposing": false, + "windowStart": 214, + "ta": { + "value": "def step_\n10(value):\n total = value + 11", + "start": 10, + "end": 10 + } + }, + { + "t": 16532, + "type": "beforeinput", + "inputType": "deleteContentBackward", + "data": null, + "isComposing": false, + "windowStart": 214, + "ta": { + "value": "def step_\n10(value):\n total = value + 11", + "start": 10, + "end": 10 + } + }, + { + "t": 16541, + "type": "input", + "inputType": "deleteContentBackward", + "data": null, + "isComposing": false, + "windowStart": 214, + "ta": { + "value": "def step_10(value):\n total = value + 11", + "start": 9, + "end": 9 + } + }, + { + "t": 16546, + "type": "sync", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):\n total = value + 11", + "start": 31, + "end": 31 + } + }, + { + "t": 16552, + "type": "selectionchange", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):\n total = value + 11", + "start": 31, + "end": 31 + } + }, + { + "t": 17085, + "type": "keydown", + "key": "Backspace", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):\n total = value + 11", + "start": 31, + "end": 31 + } + }, + { + "t": 17086, + "type": "beforeinput", + "inputType": "deleteContentBackward", + "data": null, + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):\n total = value + 11", + "start": 31, + "end": 31 + } + }, + { + "t": 17087, + "type": "input", + "inputType": "deleteContentBackward", + "data": null, + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step10(value):\n total = value + 11", + "start": 30, + "end": 30 + } + }, + { + "t": 17098, + "type": "selectionchange", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step10(value):\n total = value + 11", + "start": 30, + "end": 30 + } + }, + { + "t": 17630, + "type": "keydown", + "key": "Unidentified", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step10(value):\n total = value + 11", + "start": 30, + "end": 30 + } + }, + { + "t": 17633, + "type": "beforeinput", + "inputType": "insertText", + "data": "x", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step10(value):\n total = value + 11", + "start": 30, + "end": 30 + } + }, + { + "t": 17636, + "type": "input", + "inputType": "insertText", + "data": "x", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef stepx10(value):\n total = value + 11", + "start": 31, + "end": 31 + } + }, + { + "t": 17644, + "type": "selectionchange", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef stepx10(value):\n total = value + 11", + "start": 31, + "end": 31 + } + }, + { + "t": 37408, + "type": "blur", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef stepx10(value):\n total = value + 11", + "start": 31, + "end": 31 + } + } + ], + "expected": { + "text": "def step_0(value):\n total = value + 1\n total = value + 2\n total = value + 3\n total = value + 4\ndef step_5(value):\n total = value + 6\n total = value + 7\n total = value + 8\n total = value + 9\ndef stepx10(value):\n total = value + 11\n total = value + 12\n total = value + 13\n total = value + 14\ndef step_15(value):\n total = value + 16\n total = value + 17\n total = value + 18\n total = value + 19\ndef step_20(value):\n total = value + 21\n total = value + 22\n total = value + 23\n total = value + 24\ndef step_25(value):\n total = value + 26\n total = value + 27\n total = value + 28\n total = value + 29" + } +} diff --git a/tests/ime-web/gboard-suggestion.json b/tests/ime-web/gboard-suggestion.json new file mode 100644 index 0000000..a689362 --- /dev/null +++ b/tests/ime-web/gboard-suggestion.json @@ -0,0 +1,799 @@ +{ + "name": "gboard-suggestion", + "browser": "chrome-android", + "keyboard": "Gboard EN FR, suggestions on, autocorrect off", + "ua": "Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/157.0.0.0 Mobile Safari/537.36", + "recordedAt": "2026-11-14T21:29:53.816Z", + "settings": { + "autoCloseBrackets": false, + "autoIndent": false + }, + "initial": { + "text": "def step_0(value):\n total = value + 1\n total = value + 2\n total = value + 3\n total = value + 4\ndef step_5(value):\n total = value + 6\n total = value + 7\n total = value + 8\n total = value + 9\ndef step_10(value):\n total = value + 11\n total = value + 12\n total = value + 13\n total = value + 14\ndef step_15(value):\n total = value + 16\n total = value + 17\n total = value + 18\n total = value + 19\ndef step_20(value):\n total = value + 21\n total = value + 22\n total = value + 23\n total = value + 24\ndef step_25(value):\n total = value + 26\n total = value + 27\n total = value + 28\n total = value + 29", + "selection": [233, 233] + }, + "events": [ + { + "t": 2, + "type": "sync", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):\n total = value + 11", + "start": 41, + "end": 41 + } + }, + { + "t": 61689, + "type": "focus", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):\n total = value + 11", + "start": 0, + "end": 0 + } + }, + { + "t": 61697, + "type": "selectionchange", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):\n total = value + 11", + "start": 41, + "end": 41 + } + }, + { + "t": 89250, + "type": "keydown", + "key": "Unidentified", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):\n total = value + 11", + "start": 41, + "end": 41 + } + }, + { + "t": 89258, + "type": "beforeinput", + "inputType": "insertText", + "data": " ", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):\n total = value + 11", + "start": 41, + "end": 41 + } + }, + { + "t": 89263, + "type": "input", + "inputType": "insertText", + "data": " ", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): \n total = value + 11", + "start": 42, + "end": 42 + } + }, + { + "t": 89270, + "type": "selectionchange", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): \n total = value + 11", + "start": 42, + "end": 42 + } + }, + { + "t": 89549, + "type": "keydown", + "key": "Unidentified", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): \n total = value + 11", + "start": 42, + "end": 42 + } + }, + { + "t": 89550, + "type": "beforeinput", + "inputType": "insertText", + "data": "p", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): \n total = value + 11", + "start": 42, + "end": 42 + } + }, + { + "t": 89553, + "type": "input", + "inputType": "insertText", + "data": "p", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): p\n total = value + 11", + "start": 43, + "end": 43 + } + }, + { + "t": 89559, + "type": "selectionchange", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): p\n total = value + 11", + "start": 43, + "end": 43 + } + }, + { + "t": 89844, + "type": "keydown", + "key": "Unidentified", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): p\n total = value + 11", + "start": 43, + "end": 43 + } + }, + { + "t": 89845, + "type": "beforeinput", + "inputType": "insertText", + "data": "r", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): p\n total = value + 11", + "start": 43, + "end": 43 + } + }, + { + "t": 89846, + "type": "input", + "inputType": "insertText", + "data": "r", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): pr\n total = value + 11", + "start": 44, + "end": 44 + } + }, + { + "t": 89850, + "type": "selectionchange", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): pr\n total = value + 11", + "start": 44, + "end": 44 + } + }, + { + "t": 90147, + "type": "keydown", + "key": "Unidentified", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): pr\n total = value + 11", + "start": 44, + "end": 44 + } + }, + { + "t": 90148, + "type": "beforeinput", + "inputType": "insertText", + "data": "i", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): pr\n total = value + 11", + "start": 44, + "end": 44 + } + }, + { + "t": 90149, + "type": "input", + "inputType": "insertText", + "data": "i", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): pri\n total = value + 11", + "start": 45, + "end": 45 + } + }, + { + "t": 90157, + "type": "selectionchange", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): pri\n total = value + 11", + "start": 45, + "end": 45 + } + }, + { + "t": 90455, + "type": "keydown", + "key": "Unidentified", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): pri\n total = value + 11", + "start": 45, + "end": 45 + } + }, + { + "t": 90456, + "type": "beforeinput", + "inputType": "insertText", + "data": "t", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): pri\n total = value + 11", + "start": 45, + "end": 45 + } + }, + { + "t": 90457, + "type": "input", + "inputType": "insertText", + "data": "t", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): prit\n total = value + 11", + "start": 46, + "end": 46 + } + }, + { + "t": 90466, + "type": "selectionchange", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): prit\n total = value + 11", + "start": 46, + "end": 46 + } + }, + { + "t": 90758, + "type": "keydown", + "key": "Unidentified", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): prit\n total = value + 11", + "start": 46, + "end": 46 + } + }, + { + "t": 90759, + "type": "beforeinput", + "inputType": "insertText", + "data": "n", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): prit\n total = value + 11", + "start": 46, + "end": 46 + } + }, + { + "t": 90760, + "type": "input", + "inputType": "insertText", + "data": "n", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): pritn\n total = value + 11", + "start": 47, + "end": 47 + } + }, + { + "t": 90765, + "type": "selectionchange", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): pritn\n total = value + 11", + "start": 47, + "end": 47 + } + }, + { + "t": 91214, + "type": "keydown", + "key": "Unidentified", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): pritn\n total = value + 11", + "start": 47, + "end": 47 + } + }, + { + "t": 91215, + "type": "beforeinput", + "inputType": "insertText", + "data": " ", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): pritn\n total = value + 11", + "start": 47, + "end": 47 + } + }, + { + "t": 91217, + "type": "input", + "inputType": "insertText", + "data": " ", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): pritn \n total = value + 11", + "start": 48, + "end": 48 + } + }, + { + "t": 91224, + "type": "selectionchange", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): pritn \n total = value + 11", + "start": 48, + "end": 48 + } + }, + { + "t": 91769, + "type": "keydown", + "key": "Unidentified", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): pritn \n total = value + 11", + "start": 48, + "end": 48 + } + }, + { + "t": 91771, + "type": "beforeinput", + "inputType": "insertText", + "data": "h", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): pritn \n total = value + 11", + "start": 48, + "end": 48 + } + }, + { + "t": 91774, + "type": "input", + "inputType": "insertText", + "data": "h", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): pritn h\n total = value + 11", + "start": 49, + "end": 49 + } + }, + { + "t": 91782, + "type": "selectionchange", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): pritn h\n total = value + 11", + "start": 49, + "end": 49 + } + }, + { + "t": 92073, + "type": "keydown", + "key": "Unidentified", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): pritn h\n total = value + 11", + "start": 49, + "end": 49 + } + }, + { + "t": 92073, + "type": "beforeinput", + "inputType": "insertText", + "data": "e", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): pritn h\n total = value + 11", + "start": 49, + "end": 49 + } + }, + { + "t": 92077, + "type": "input", + "inputType": "insertText", + "data": "e", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): pritn he\n total = value + 11", + "start": 50, + "end": 50 + } + }, + { + "t": 92080, + "type": "selectionchange", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): pritn he\n total = value + 11", + "start": 50, + "end": 50 + } + }, + { + "t": 92372, + "type": "keydown", + "key": "Unidentified", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): pritn he\n total = value + 11", + "start": 50, + "end": 50 + } + }, + { + "t": 92373, + "type": "beforeinput", + "inputType": "insertText", + "data": "l", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): pritn he\n total = value + 11", + "start": 50, + "end": 50 + } + }, + { + "t": 92374, + "type": "input", + "inputType": "insertText", + "data": "l", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): pritn hel\n total = value + 11", + "start": 51, + "end": 51 + } + }, + { + "t": 92382, + "type": "selectionchange", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): pritn hel\n total = value + 11", + "start": 51, + "end": 51 + } + }, + { + "t": 123023, + "type": "keydown", + "key": "Unidentified", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): pritn hel\n total = value + 11", + "start": 51, + "end": 51 + } + }, + { + "t": 123025, + "type": "beforeinput", + "inputType": "insertText", + "data": "lo ", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): pritn hel\n total = value + 11", + "start": 51, + "end": 51 + } + }, + { + "t": 123031, + "type": "input", + "inputType": "insertText", + "data": "lo ", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): pritn hello \n total = value + 11", + "start": 54, + "end": 54 + } + }, + { + "t": 123040, + "type": "selectionchange", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): pritn hello \n total = value + 11", + "start": 54, + "end": 54 + } + }, + { + "t": 123674, + "type": "keydown", + "key": "Unidentified", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): pritn hello \n total = value + 11", + "start": 54, + "end": 54 + } + }, + { + "t": 123675, + "type": "beforeinput", + "inputType": "insertText", + "data": "t", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): pritn hello \n total = value + 11", + "start": 54, + "end": 54 + } + }, + { + "t": 123676, + "type": "input", + "inputType": "insertText", + "data": "t", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): pritn hello t\n total = value + 11", + "start": 55, + "end": 55 + } + }, + { + "t": 123685, + "type": "selectionchange", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): pritn hello t\n total = value + 11", + "start": 55, + "end": 55 + } + }, + { + "t": 123988, + "type": "keydown", + "key": "Unidentified", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): pritn hello t\n total = value + 11", + "start": 55, + "end": 55 + } + }, + { + "t": 123990, + "type": "beforeinput", + "inputType": "insertText", + "data": "e", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): pritn hello t\n total = value + 11", + "start": 55, + "end": 55 + } + }, + { + "t": 123991, + "type": "input", + "inputType": "insertText", + "data": "e", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): pritn hello te\n total = value + 11", + "start": 56, + "end": 56 + } + }, + { + "t": 123996, + "type": "selectionchange", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): pritn hello te\n total = value + 11", + "start": 56, + "end": 56 + } + }, + { + "t": 124281, + "type": "keydown", + "key": "Unidentified", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): pritn hello te\n total = value + 11", + "start": 56, + "end": 56 + } + }, + { + "t": 124282, + "type": "beforeinput", + "inputType": "insertText", + "data": "h", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): pritn hello te\n total = value + 11", + "start": 56, + "end": 56 + } + }, + { + "t": 124283, + "type": "input", + "inputType": "insertText", + "data": "h", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): pritn hello teh\n total = value + 11", + "start": 57, + "end": 57 + } + }, + { + "t": 124293, + "type": "selectionchange", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): pritn hello teh\n total = value + 11", + "start": 57, + "end": 57 + } + }, + { + "t": 124739, + "type": "keydown", + "key": "Unidentified", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): pritn hello teh\n total = value + 11", + "start": 57, + "end": 57 + } + }, + { + "t": 124741, + "type": "beforeinput", + "inputType": "insertText", + "data": " ", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): pritn hello teh\n total = value + 11", + "start": 57, + "end": 57 + } + }, + { + "t": 124743, + "type": "input", + "inputType": "insertText", + "data": " ", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): pritn hello teh \n total = value + 11", + "start": 58, + "end": 58 + } + }, + { + "t": 124753, + "type": "selectionchange", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): pritn hello teh \n total = value + 11", + "start": 58, + "end": 58 + } + }, + { + "t": 167805, + "type": "blur", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): pritn hello teh \n total = value + 11", + "start": 58, + "end": 58 + } + } + ], + "expected": { + "text": "def step_0(value):\n total = value + 1\n total = value + 2\n total = value + 3\n total = value + 4\ndef step_5(value):\n total = value + 6\n total = value + 7\n total = value + 8\n total = value + 9\ndef step_10(value): pritn hello teh \n total = value + 11\n total = value + 12\n total = value + 13\n total = value + 14\ndef step_15(value):\n total = value + 16\n total = value + 17\n total = value + 18\n total = value + 19\ndef step_20(value):\n total = value + 21\n total = value + 22\n total = value + 23\n total = value + 24\ndef step_25(value):\n total = value + 26\n total = value + 27\n total = value + 28\n total = value + 29" + } +} diff --git a/tests/ime-web/ios-arabic.json b/tests/ime-web/ios-arabic.json new file mode 100644 index 0000000..18fb650 --- /dev/null +++ b/tests/ime-web/ios-arabic.json @@ -0,0 +1,396 @@ +{ + "name": "ios-arabic", + "browser": "safari-ios", + "keyboard": "Arabic, iOS 27.2 simulator", + "ua": "Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/27.2 Mobile/15E148 Safari/604.1", + "recordedAt": "2026-11-14T21:46:48.133Z", + "settings": { + "autoCloseBrackets": false, + "autoIndent": false + }, + "initial": { + "text": "def step_0(value):\n total = value + 1\n total = value + 2\n total = value + 3\n total = value + 4\ndef step_5(value):\n total = value + 6\n total = value + 7\n total = value + 8\n total = value + 9\ndef step_10(value):\n total = value + 11\n total = value + 12\n total = value + 13\n total = value + 14\ndef step_15(value):\n total = value + 16\n total = value + 17\n total = value + 18\n total = value + 19\ndef step_20(value):\n total = value + 21\n total = value + 22\n total = value + 23\n total = value + 24\ndef step_25(value):\n total = value + 26\n total = value + 27\n total = value + 28\n total = value + 29", + "selection": [233, 233] + }, + "events": [ + { + "t": 2, + "type": "sync", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):\n total = value + 11", + "start": 41, + "end": 41 + } + }, + { + "t": 11434, + "type": "focus", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):\n total = value + 11", + "start": 0, + "end": 0 + } + }, + { + "t": 39940, + "type": "keydown", + "key": "م", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):\n total = value + 11", + "start": 41, + "end": 41 + } + }, + { + "t": 40007, + "type": "beforeinput", + "inputType": "insertText", + "data": "م", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):\n total = value + 11", + "start": 41, + "end": 41 + } + }, + { + "t": 40066, + "type": "input", + "inputType": "insertText", + "data": "م", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):م\n total = value + 11", + "start": 42, + "end": 42 + } + }, + { + "t": 40075, + "type": "selectionchange", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):م\n total = value + 11", + "start": 42, + "end": 42 + } + }, + { + "t": 40240, + "type": "keydown", + "key": "ر", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):م\n total = value + 11", + "start": 42, + "end": 42 + } + }, + { + "t": 40249, + "type": "beforeinput", + "inputType": "insertText", + "data": "ر", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):م\n total = value + 11", + "start": 42, + "end": 42 + } + }, + { + "t": 40250, + "type": "input", + "inputType": "insertText", + "data": "ر", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):مر\n total = value + 11", + "start": 43, + "end": 43 + } + }, + { + "t": 40250, + "type": "selectionchange", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):مر\n total = value + 11", + "start": 43, + "end": 43 + } + }, + { + "t": 40640, + "type": "keydown", + "key": "ح", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):مر\n total = value + 11", + "start": 43, + "end": 43 + } + }, + { + "t": 40646, + "type": "beforeinput", + "inputType": "insertText", + "data": "ح", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):مر\n total = value + 11", + "start": 43, + "end": 43 + } + }, + { + "t": 40647, + "type": "input", + "inputType": "insertText", + "data": "ح", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):مرح\n total = value + 11", + "start": 44, + "end": 44 + } + }, + { + "t": 40647, + "type": "selectionchange", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):مرح\n total = value + 11", + "start": 44, + "end": 44 + } + }, + { + "t": 41056, + "type": "keydown", + "key": "ب", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):مرح\n total = value + 11", + "start": 44, + "end": 44 + } + }, + { + "t": 41064, + "type": "beforeinput", + "inputType": "insertText", + "data": "ب", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):مرح\n total = value + 11", + "start": 44, + "end": 44 + } + }, + { + "t": 41064, + "type": "input", + "inputType": "insertText", + "data": "ب", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):مرحب\n total = value + 11", + "start": 45, + "end": 45 + } + }, + { + "t": 41065, + "type": "selectionchange", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):مرحب\n total = value + 11", + "start": 45, + "end": 45 + } + }, + { + "t": 41476, + "type": "keydown", + "key": "ا", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):مرحب\n total = value + 11", + "start": 45, + "end": 45 + } + }, + { + "t": 41485, + "type": "beforeinput", + "inputType": "insertText", + "data": "ا", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):مرحب\n total = value + 11", + "start": 45, + "end": 45 + } + }, + { + "t": 41486, + "type": "input", + "inputType": "insertText", + "data": "ا", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):مرحبا\n total = value + 11", + "start": 46, + "end": 46 + } + }, + { + "t": 41486, + "type": "selectionchange", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):مرحبا\n total = value + 11", + "start": 46, + "end": 46 + } + }, + { + "t": 42123, + "type": "keydown", + "key": " ", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):مرحبا\n total = value + 11", + "start": 46, + "end": 46 + } + }, + { + "t": 42228, + "type": "beforeinput", + "inputType": "insertText", + "data": " ", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):مرحبا\n total = value + 11", + "start": 46, + "end": 46 + } + }, + { + "t": 42228, + "type": "input", + "inputType": "insertText", + "data": " ", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):مرحبا \n total = value + 11", + "start": 47, + "end": 47 + } + }, + { + "t": 42231, + "type": "selectionchange", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):مرحبا \n total = value + 11", + "start": 47, + "end": 47 + } + }, + { + "t": 44022, + "type": "keydown", + "key": "Backspace", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):مرحبا \n total = value + 11", + "start": 47, + "end": 47 + } + }, + { + "t": 44036, + "type": "beforeinput", + "inputType": "deleteContentBackward", + "data": null, + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):مرحبا \n total = value + 11", + "start": 47, + "end": 47 + } + }, + { + "t": 44036, + "type": "input", + "inputType": "deleteContentBackward", + "data": null, + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):مرحبا\n total = value + 11", + "start": 46, + "end": 46 + } + }, + { + "t": 44037, + "type": "selectionchange", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):مرحبا\n total = value + 11", + "start": 46, + "end": 46 + } + }, + { + "t": 44977, + "type": "blur", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):مرحبا\n total = value + 11", + "start": 46, + "end": 46 + } + } + ], + "expected": { + "text": "def step_0(value):\n total = value + 1\n total = value + 2\n total = value + 3\n total = value + 4\ndef step_5(value):\n total = value + 6\n total = value + 7\n total = value + 8\n total = value + 9\ndef step_10(value):مرحبا\n total = value + 11\n total = value + 12\n total = value + 13\n total = value + 14\ndef step_15(value):\n total = value + 16\n total = value + 17\n total = value + 18\n total = value + 19\ndef step_20(value):\n total = value + 21\n total = value + 22\n total = value + 23\n total = value + 24\ndef step_25(value):\n total = value + 26\n total = value + 27\n total = value + 28\n total = value + 29" + } +} diff --git a/tests/ime-web/ios-autocorrect.json b/tests/ime-web/ios-autocorrect.json new file mode 100644 index 0000000..efd2ca0 --- /dev/null +++ b/tests/ime-web/ios-autocorrect.json @@ -0,0 +1,666 @@ +{ + "name": "ios-autocorrect", + "browser": "safari-ios", + "keyboard": "English US, autocorrect on, iOS 27.2 simulator", + "ua": "Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/27.2 Mobile/15E148 Safari/604.1", + "recordedAt": "2026-11-14T21:45:35.162Z", + "settings": { + "autoCloseBrackets": false, + "autoIndent": false + }, + "initial": { + "text": "def step_0(value):\n total = value + 1\n total = value + 2\n total = value + 3\n total = value + 4\ndef step_5(value):\n total = value + 6\n total = value + 7\n total = value + 8\n total = value + 9\ndef step_10(value):\n total = value + 11\n total = value + 12\n total = value + 13\n total = value + 14\ndef step_15(value):\n total = value + 16\n total = value + 17\n total = value + 18\n total = value + 19\ndef step_20(value):\n total = value + 21\n total = value + 22\n total = value + 23\n total = value + 24\ndef step_25(value):\n total = value + 26\n total = value + 27\n total = value + 28\n total = value + 29", + "selection": [233, 233] + }, + "events": [ + { + "t": 3, + "type": "sync", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):\n total = value + 11", + "start": 41, + "end": 41 + } + }, + { + "t": 10467, + "type": "focus", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):\n total = value + 11", + "start": 0, + "end": 0 + } + }, + { + "t": 11926, + "type": "keydown", + "key": " ", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):\n total = value + 11", + "start": 41, + "end": 41 + } + }, + { + "t": 11960, + "type": "beforeinput", + "inputType": "insertText", + "data": " ", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):\n total = value + 11", + "start": 41, + "end": 41 + } + }, + { + "t": 11985, + "type": "input", + "inputType": "insertText", + "data": " ", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): \n total = value + 11", + "start": 42, + "end": 42 + } + }, + { + "t": 11987, + "type": "selectionchange", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): \n total = value + 11", + "start": 42, + "end": 42 + } + }, + { + "t": 12295, + "type": "keydown", + "key": "t", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): \n total = value + 11", + "start": 42, + "end": 42 + } + }, + { + "t": 12302, + "type": "beforeinput", + "inputType": "insertText", + "data": "t", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): \n total = value + 11", + "start": 42, + "end": 42 + } + }, + { + "t": 12303, + "type": "input", + "inputType": "insertText", + "data": "t", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): t\n total = value + 11", + "start": 43, + "end": 43 + } + }, + { + "t": 12304, + "type": "selectionchange", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): t\n total = value + 11", + "start": 43, + "end": 43 + } + }, + { + "t": 12711, + "type": "keydown", + "key": "e", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): t\n total = value + 11", + "start": 43, + "end": 43 + } + }, + { + "t": 12718, + "type": "beforeinput", + "inputType": "insertText", + "data": "e", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): t\n total = value + 11", + "start": 43, + "end": 43 + } + }, + { + "t": 12718, + "type": "input", + "inputType": "insertText", + "data": "e", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): te\n total = value + 11", + "start": 44, + "end": 44 + } + }, + { + "t": 12719, + "type": "selectionchange", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): te\n total = value + 11", + "start": 44, + "end": 44 + } + }, + { + "t": 13112, + "type": "keydown", + "key": "h", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): te\n total = value + 11", + "start": 44, + "end": 44 + } + }, + { + "t": 13119, + "type": "beforeinput", + "inputType": "insertText", + "data": "h", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): te\n total = value + 11", + "start": 44, + "end": 44 + } + }, + { + "t": 13119, + "type": "input", + "inputType": "insertText", + "data": "h", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): teh\n total = value + 11", + "start": 45, + "end": 45 + } + }, + { + "t": 13120, + "type": "selectionchange", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): teh\n total = value + 11", + "start": 45, + "end": 45 + } + }, + { + "t": 13761, + "type": "keydown", + "key": " ", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): teh\n total = value + 11", + "start": 45, + "end": 45 + } + }, + { + "t": 13763, + "type": "beforeinput", + "inputType": "insertReplacementText", + "data": "the", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): teh\n total = value + 11", + "start": 42, + "end": 45 + } + }, + { + "t": 13767, + "type": "input", + "inputType": "insertReplacementText", + "data": "the", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): the\n total = value + 11", + "start": 45, + "end": 45 + } + }, + { + "t": 13786, + "type": "selectionchange", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): the\n total = value + 11", + "start": 45, + "end": 45 + } + }, + { + "t": 13795, + "type": "beforeinput", + "inputType": "insertText", + "data": " ", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): the\n total = value + 11", + "start": 45, + "end": 45 + } + }, + { + "t": 13795, + "type": "input", + "inputType": "insertText", + "data": " ", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): the \n total = value + 11", + "start": 46, + "end": 46 + } + }, + { + "t": 13801, + "type": "selectionchange", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): the \n total = value + 11", + "start": 46, + "end": 46 + } + }, + { + "t": 14611, + "type": "keydown", + "key": "w", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): the \n total = value + 11", + "start": 46, + "end": 46 + } + }, + { + "t": 14620, + "type": "beforeinput", + "inputType": "insertText", + "data": "w", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): the \n total = value + 11", + "start": 46, + "end": 46 + } + }, + { + "t": 14620, + "type": "input", + "inputType": "insertText", + "data": "w", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): the w\n total = value + 11", + "start": 47, + "end": 47 + } + }, + { + "t": 14622, + "type": "selectionchange", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): the w\n total = value + 11", + "start": 47, + "end": 47 + } + }, + { + "t": 15011, + "type": "keydown", + "key": "r", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): the w\n total = value + 11", + "start": 47, + "end": 47 + } + }, + { + "t": 15017, + "type": "beforeinput", + "inputType": "insertText", + "data": "r", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): the w\n total = value + 11", + "start": 47, + "end": 47 + } + }, + { + "t": 15017, + "type": "input", + "inputType": "insertText", + "data": "r", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): the wr\n total = value + 11", + "start": 48, + "end": 48 + } + }, + { + "t": 15018, + "type": "selectionchange", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): the wr\n total = value + 11", + "start": 48, + "end": 48 + } + }, + { + "t": 15418, + "type": "keydown", + "key": "o", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): the wr\n total = value + 11", + "start": 48, + "end": 48 + } + }, + { + "t": 15432, + "type": "beforeinput", + "inputType": "insertText", + "data": "o", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): the wr\n total = value + 11", + "start": 48, + "end": 48 + } + }, + { + "t": 15432, + "type": "input", + "inputType": "insertText", + "data": "o", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): the wro\n total = value + 11", + "start": 49, + "end": 49 + } + }, + { + "t": 15433, + "type": "selectionchange", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): the wro\n total = value + 11", + "start": 49, + "end": 49 + } + }, + { + "t": 15829, + "type": "keydown", + "key": "l", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): the wro\n total = value + 11", + "start": 49, + "end": 49 + } + }, + { + "t": 15847, + "type": "beforeinput", + "inputType": "insertText", + "data": "l", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): the wro\n total = value + 11", + "start": 49, + "end": 49 + } + }, + { + "t": 15848, + "type": "input", + "inputType": "insertText", + "data": "l", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): the wrol\n total = value + 11", + "start": 50, + "end": 50 + } + }, + { + "t": 15848, + "type": "selectionchange", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): the wrol\n total = value + 11", + "start": 50, + "end": 50 + } + }, + { + "t": 16229, + "type": "keydown", + "key": "d", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): the wrol\n total = value + 11", + "start": 50, + "end": 50 + } + }, + { + "t": 16236, + "type": "beforeinput", + "inputType": "insertText", + "data": "d", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): the wrol\n total = value + 11", + "start": 50, + "end": 50 + } + }, + { + "t": 16236, + "type": "input", + "inputType": "insertText", + "data": "d", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): the wrold\n total = value + 11", + "start": 51, + "end": 51 + } + }, + { + "t": 16237, + "type": "selectionchange", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): the wrold\n total = value + 11", + "start": 51, + "end": 51 + } + }, + { + "t": 16897, + "type": "keydown", + "key": " ", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): the wrold\n total = value + 11", + "start": 51, + "end": 51 + } + }, + { + "t": 16900, + "type": "beforeinput", + "inputType": "insertReplacementText", + "data": "world", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): the wrold\n total = value + 11", + "start": 46, + "end": 51 + } + }, + { + "t": 16900, + "type": "input", + "inputType": "insertReplacementText", + "data": "world", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): the world\n total = value + 11", + "start": 51, + "end": 51 + } + }, + { + "t": 16900, + "type": "selectionchange", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): the world\n total = value + 11", + "start": 51, + "end": 51 + } + }, + { + "t": 16906, + "type": "beforeinput", + "inputType": "insertText", + "data": " ", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): the world\n total = value + 11", + "start": 51, + "end": 51 + } + }, + { + "t": 16906, + "type": "input", + "inputType": "insertText", + "data": " ", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): the world \n total = value + 11", + "start": 52, + "end": 52 + } + }, + { + "t": 16907, + "type": "selectionchange", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): the world \n total = value + 11", + "start": 52, + "end": 52 + } + }, + { + "t": 36080, + "type": "blur", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value): the world \n total = value + 11", + "start": 52, + "end": 52 + } + } + ], + "expected": { + "text": "def step_0(value):\n total = value + 1\n total = value + 2\n total = value + 3\n total = value + 4\ndef step_5(value):\n total = value + 6\n total = value + 7\n total = value + 8\n total = value + 9\ndef step_10(value): the world \n total = value + 11\n total = value + 12\n total = value + 13\n total = value + 14\ndef step_15(value):\n total = value + 16\n total = value + 17\n total = value + 18\n total = value + 19\ndef step_20(value):\n total = value + 21\n total = value + 22\n total = value + 23\n total = value + 24\ndef step_25(value):\n total = value + 26\n total = value + 27\n total = value + 28\n total = value + 29" + } +} diff --git a/tests/ime-web/ios-japanese-romaji.json b/tests/ime-web/ios-japanese-romaji.json new file mode 100644 index 0000000..68773e0 --- /dev/null +++ b/tests/ime-web/ios-japanese-romaji.json @@ -0,0 +1,779 @@ +{ + "name": "ios-japanese-romaji", + "browser": "safari-ios", + "keyboard": "Japanese Romaji, iOS 27.2 simulator", + "ua": "Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/27.2 Mobile/15E148 Safari/604.1", + "recordedAt": "2026-11-14T21:43:23.167Z", + "settings": { + "autoCloseBrackets": false, + "autoIndent": false + }, + "initial": { + "text": "def step_0(value):\n total = value + 1\n total = value + 2\n total = value + 3\n total = value + 4\ndef step_5(value):\n total = value + 6\n total = value + 7\n total = value + 8\n total = value + 9\ndef step_10(value):\n total = value + 11\n total = value + 12\n total = value + 13\n total = value + 14\ndef step_15(value):\n total = value + 16\n total = value + 17\n total = value + 18\n total = value + 19\ndef step_20(value):\n total = value + 21\n total = value + 22\n total = value + 23\n total = value + 24\ndef step_25(value):\n total = value + 26\n total = value + 27\n total = value + 28\n total = value + 29", + "selection": [233, 233] + }, + "events": [ + { + "t": 5, + "type": "sync", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):\n total = value + 11", + "start": 41, + "end": 41 + } + }, + { + "t": 14095, + "type": "focus", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):\n total = value + 11", + "start": 0, + "end": 0 + } + }, + { + "t": 17140, + "type": "keydown", + "key": "n", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):\n total = value + 11", + "start": 41, + "end": 41 + } + }, + { + "t": 17190, + "type": "compositionstart", + "data": "", + "isComposing": true, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):\n total = value + 11", + "start": 41, + "end": 41 + } + }, + { + "t": 17190, + "type": "compositionupdate", + "data": "n", + "isComposing": true, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):\n total = value + 11", + "start": 41, + "end": 41 + } + }, + { + "t": 17234, + "type": "beforeinput", + "inputType": "insertCompositionText", + "data": "n", + "isComposing": true, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):\n total = value + 11", + "start": 41, + "end": 41 + } + }, + { + "t": 17322, + "type": "input", + "inputType": "insertCompositionText", + "data": "n", + "isComposing": true, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):n\n total = value + 11", + "start": 41, + "end": 42 + } + }, + { + "t": 17323, + "type": "selectionchange", + "isComposing": true, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):n\n total = value + 11", + "start": 42, + "end": 42 + } + }, + { + "t": 17756, + "type": "keydown", + "key": "i", + "isComposing": true, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):n\n total = value + 11", + "start": 42, + "end": 42 + } + }, + { + "t": 17800, + "type": "compositionupdate", + "data": "に", + "isComposing": true, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):n\n total = value + 11", + "start": 41, + "end": 42 + } + }, + { + "t": 17800, + "type": "beforeinput", + "inputType": "insertCompositionText", + "data": "に", + "isComposing": true, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):n\n total = value + 11", + "start": 41, + "end": 42 + } + }, + { + "t": 18011, + "type": "input", + "inputType": "insertCompositionText", + "data": "に", + "isComposing": true, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):に\n total = value + 11", + "start": 41, + "end": 42 + } + }, + { + "t": 18085, + "type": "selectionchange", + "isComposing": true, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):に\n total = value + 11", + "start": 42, + "end": 42 + } + }, + { + "t": 18098, + "type": "keydown", + "key": "h", + "isComposing": true, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):に\n total = value + 11", + "start": 42, + "end": 42 + } + }, + { + "t": 18103, + "type": "compositionupdate", + "data": "にh", + "isComposing": true, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):に\n total = value + 11", + "start": 41, + "end": 42 + } + }, + { + "t": 18103, + "type": "beforeinput", + "inputType": "insertCompositionText", + "data": "にh", + "isComposing": true, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):に\n total = value + 11", + "start": 41, + "end": 42 + } + }, + { + "t": 18103, + "type": "input", + "inputType": "insertCompositionText", + "data": "にh", + "isComposing": true, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):にh\n total = value + 11", + "start": 41, + "end": 43 + } + }, + { + "t": 18104, + "type": "selectionchange", + "isComposing": true, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):にh\n total = value + 11", + "start": 43, + "end": 43 + } + }, + { + "t": 18333, + "type": "keydown", + "key": "o", + "isComposing": true, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):にh\n total = value + 11", + "start": 43, + "end": 43 + } + }, + { + "t": 18383, + "type": "compositionupdate", + "data": "にほ", + "isComposing": true, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):にh\n total = value + 11", + "start": 41, + "end": 43 + } + }, + { + "t": 18384, + "type": "beforeinput", + "inputType": "insertCompositionText", + "data": "にほ", + "isComposing": true, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):にh\n total = value + 11", + "start": 41, + "end": 43 + } + }, + { + "t": 18392, + "type": "input", + "inputType": "insertCompositionText", + "data": "にほ", + "isComposing": true, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):にほ\n total = value + 11", + "start": 41, + "end": 43 + } + }, + { + "t": 18439, + "type": "selectionchange", + "isComposing": true, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):にほ\n total = value + 11", + "start": 43, + "end": 43 + } + }, + { + "t": 18749, + "type": "keydown", + "key": "n", + "isComposing": true, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):にほ\n total = value + 11", + "start": 43, + "end": 43 + } + }, + { + "t": 18757, + "type": "compositionupdate", + "data": "にほn", + "isComposing": true, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):にほ\n total = value + 11", + "start": 41, + "end": 43 + } + }, + { + "t": 18758, + "type": "beforeinput", + "inputType": "insertCompositionText", + "data": "にほn", + "isComposing": true, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):にほ\n total = value + 11", + "start": 41, + "end": 43 + } + }, + { + "t": 18759, + "type": "input", + "inputType": "insertCompositionText", + "data": "にほn", + "isComposing": true, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):にほn\n total = value + 11", + "start": 41, + "end": 44 + } + }, + { + "t": 18760, + "type": "selectionchange", + "isComposing": true, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):にほn\n total = value + 11", + "start": 44, + "end": 44 + } + }, + { + "t": 61452, + "type": "compositionupdate", + "data": "日本", + "isComposing": true, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):にほn\n total = value + 11", + "start": 41, + "end": 44 + } + }, + { + "t": 61665, + "type": "beforeinput", + "inputType": "insertCompositionText", + "data": "日本", + "isComposing": true, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):にほn\n total = value + 11", + "start": 41, + "end": 44 + } + }, + { + "t": 61766, + "type": "input", + "inputType": "insertCompositionText", + "data": "日本", + "isComposing": true, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):日本\n total = value + 11", + "start": 41, + "end": 43 + } + }, + { + "t": 61878, + "type": "beforeinput", + "inputType": "deleteCompositionText", + "data": null, + "isComposing": true, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):日本\n total = value + 11", + "start": 41, + "end": 43 + } + }, + { + "t": 61889, + "type": "input", + "inputType": "deleteCompositionText", + "data": null, + "isComposing": true, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):\n total = value + 11", + "start": 41, + "end": 41 + } + }, + { + "t": 61957, + "type": "beforeinput", + "inputType": "insertFromComposition", + "data": "日本", + "isComposing": true, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):\n total = value + 11", + "start": 41, + "end": 41 + } + }, + { + "t": 61961, + "type": "input", + "inputType": "insertFromComposition", + "data": "日本", + "isComposing": true, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):日本\n total = value + 11", + "start": 43, + "end": 43 + } + }, + { + "t": 61970, + "type": "compositionend", + "data": "日本", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):日本\n total = value + 11", + "start": 43, + "end": 43 + } + }, + { + "t": 61978, + "type": "selectionchange", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):日本\n total = value + 11", + "start": 43, + "end": 43 + } + }, + { + "t": 62252, + "type": "keydown", + "key": "g", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):日本\n total = value + 11", + "start": 43, + "end": 43 + } + }, + { + "t": 62268, + "type": "compositionstart", + "data": "", + "isComposing": true, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):日本\n total = value + 11", + "start": 43, + "end": 43 + } + }, + { + "t": 62268, + "type": "compositionupdate", + "data": "g", + "isComposing": true, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):日本\n total = value + 11", + "start": 43, + "end": 43 + } + }, + { + "t": 62268, + "type": "beforeinput", + "inputType": "insertCompositionText", + "data": "g", + "isComposing": true, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):日本\n total = value + 11", + "start": 43, + "end": 43 + } + }, + { + "t": 62271, + "type": "input", + "inputType": "insertCompositionText", + "data": "g", + "isComposing": true, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):日本g\n total = value + 11", + "start": 43, + "end": 44 + } + }, + { + "t": 62287, + "type": "selectionchange", + "isComposing": true, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):日本g\n total = value + 11", + "start": 44, + "end": 44 + } + }, + { + "t": 62583, + "type": "keydown", + "key": "o", + "isComposing": true, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):日本g\n total = value + 11", + "start": 44, + "end": 44 + } + }, + { + "t": 62591, + "type": "compositionupdate", + "data": "ご", + "isComposing": true, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):日本g\n total = value + 11", + "start": 43, + "end": 44 + } + }, + { + "t": 62591, + "type": "beforeinput", + "inputType": "insertCompositionText", + "data": "ご", + "isComposing": true, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):日本g\n total = value + 11", + "start": 43, + "end": 44 + } + }, + { + "t": 62604, + "type": "input", + "inputType": "insertCompositionText", + "data": "ご", + "isComposing": true, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):日本ご\n total = value + 11", + "start": 43, + "end": 44 + } + }, + { + "t": 62630, + "type": "selectionchange", + "isComposing": true, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):日本ご\n total = value + 11", + "start": 44, + "end": 44 + } + }, + { + "t": 63532, + "type": "compositionupdate", + "data": "ご", + "isComposing": true, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):日本ご\n total = value + 11", + "start": 43, + "end": 44 + } + }, + { + "t": 63532, + "type": "beforeinput", + "inputType": "insertCompositionText", + "data": "ご", + "isComposing": true, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):日本ご\n total = value + 11", + "start": 43, + "end": 44 + } + }, + { + "t": 63532, + "type": "input", + "inputType": "insertCompositionText", + "data": "ご", + "isComposing": true, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):日本ご\n total = value + 11", + "start": 43, + "end": 44 + } + }, + { + "t": 63533, + "type": "beforeinput", + "inputType": "deleteCompositionText", + "data": null, + "isComposing": true, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):日本ご\n total = value + 11", + "start": 43, + "end": 44 + } + }, + { + "t": 63533, + "type": "input", + "inputType": "deleteCompositionText", + "data": null, + "isComposing": true, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):日本\n total = value + 11", + "start": 43, + "end": 43 + } + }, + { + "t": 63533, + "type": "beforeinput", + "inputType": "insertFromComposition", + "data": "ご", + "isComposing": true, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):日本\n total = value + 11", + "start": 43, + "end": 43 + } + }, + { + "t": 63534, + "type": "input", + "inputType": "insertFromComposition", + "data": "ご", + "isComposing": true, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):日本ご\n total = value + 11", + "start": 44, + "end": 44 + } + }, + { + "t": 63572, + "type": "compositionend", + "data": "ご", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):日本ご\n total = value + 11", + "start": 44, + "end": 44 + } + }, + { + "t": 63572, + "type": "selectionchange", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):日本ご\n total = value + 11", + "start": 44, + "end": 44 + } + }, + { + "t": 64500, + "type": "keydown", + "key": "Backspace", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):日本ご\n total = value + 11", + "start": 44, + "end": 44 + } + }, + { + "t": 64518, + "type": "beforeinput", + "inputType": "deleteContentBackward", + "data": null, + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):日本ご\n total = value + 11", + "start": 44, + "end": 44 + } + }, + { + "t": 64519, + "type": "input", + "inputType": "deleteContentBackward", + "data": null, + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):日本\n total = value + 11", + "start": 43, + "end": 43 + } + }, + { + "t": 64520, + "type": "selectionchange", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):日本\n total = value + 11", + "start": 43, + "end": 43 + } + }, + { + "t": 65568, + "type": "blur", + "isComposing": false, + "windowStart": 192, + "ta": { + "value": " total = value + 9\ndef step_10(value):日本\n total = value + 11", + "start": 43, + "end": 43 + } + } + ], + "expected": { + "text": "def step_0(value):\n total = value + 1\n total = value + 2\n total = value + 3\n total = value + 4\ndef step_5(value):\n total = value + 6\n total = value + 7\n total = value + 8\n total = value + 9\ndef step_10(value):日本\n total = value + 11\n total = value + 12\n total = value + 13\n total = value + 14\ndef step_15(value):\n total = value + 16\n total = value + 17\n total = value + 18\n total = value + 19\ndef step_20(value):\n total = value + 21\n total = value + 22\n total = value + 23\n total = value + 24\ndef step_25(value):\n total = value + 26\n total = value + 27\n total = value + 28\n total = value + 29" + } +} diff --git a/tests/ime-web/recorder/index.html b/tests/ime-web/recorder/index.html new file mode 100644 index 0000000..80515dd --- /dev/null +++ b/tests/ime-web/recorder/index.html @@ -0,0 +1,25 @@ + + + + + + Keyboard recorder + + + + +
+ + + + +

+    
+  
+
diff --git a/tests/ime-web/recorder/recorder.js b/tests/ime-web/recorder/recorder.js
new file mode 100644
index 0000000..ef2ac81
--- /dev/null
+++ b/tests/ime-web/recorder/recorder.js
@@ -0,0 +1,154 @@
+// Records what a browser keyboard sends to a textarea that holds a window of a document, as WebInputSession will.
+const WINDOW_CAP = 8192;
+const SAMPLE = Array.from({ length: 30 }, (_, i) =>
+  i % 5 === 0 ? `def step_${i}(value):` : `    total = value + ${i}`,
+).join('\n');
+const INITIAL_CARET = SAMPLE.indexOf('\n', SAMPLE.indexOf('step_10'));
+
+const ta = document.getElementById('ta');
+const statusLine = document.getElementById('status');
+const shown = document.getElementById('doc');
+const params = new URLSearchParams(location.search);
+const suggest = params.has('suggest');
+// The form fields can come from the URL, for keyboards that cannot type them in Latin letters.
+for (const field of ['name', 'browser', 'keyboard']) {
+  if (params.has(field)) document.getElementById(field).value = params.get(field);
+}
+for (const [name, on, off] of [
+  ['autocomplete', 'on', 'off'],
+  ['autocorrect', 'on', 'off'],
+  ['autocapitalize', 'sentences', 'off'],
+  ['spellcheck', 'true', 'false'],
+]) {
+  ta.setAttribute(name, suggest ? on : off);
+}
+
+let doc = SAMPLE;
+let anchor = INITIAL_CARET;
+let head = INITIAL_CARET;
+let win = { start: 0, value: '', line: 0 };
+let composing = false;
+let events = [];
+const started = performance.now();
+
+const lineAt = (offset) => doc.slice(0, offset).split('\n').length - 1;
+const lineStart = (line) => {
+  let at = 0;
+  for (let i = 0; i < line; i++) at = doc.indexOf('\n', at) + 1;
+  return at;
+};
+const lineEnd = (line) => {
+  const next = doc.indexOf('\n', lineStart(line));
+  return next < 0 ? doc.length : next;
+};
+const lastLine = () => lineAt(doc.length);
+
+// The caret's line and its two neighbors, widened to a selection, at most WINDOW_CAP units around the head.
+function windowAround() {
+  const first = Math.max(0, lineAt(Math.min(anchor, head)) - 1);
+  const last = Math.min(lastLine(), lineAt(Math.max(anchor, head)) + 1);
+  let start = lineStart(first);
+  let end = lineEnd(last);
+  if (end - start > WINDOW_CAP) {
+    start = Math.min(Math.max(start, head - WINDOW_CAP / 2), end - WINDOW_CAP);
+    end = start + WINDOW_CAP;
+  }
+  return { start, end };
+}
+
+const state = () => ({ value: ta.value, start: ta.selectionStart, end: ta.selectionEnd });
+
+function record(type, extra = {}) {
+  events.push({
+    t: Math.round(performance.now() - started),
+    type,
+    ...extra,
+    isComposing: composing,
+    windowStart: win.start,
+    ta: state(),
+  });
+  render();
+}
+
+function sync() {
+  const { start, end } = windowAround();
+  win = { start, value: doc.slice(start, end), line: lineAt(head) };
+  if (ta.value !== win.value) ta.value = win.value;
+  const a = anchor - start;
+  const h = head - start;
+  ta.setSelectionRange(Math.min(a, h), Math.max(a, h), h < a ? 'backward' : 'forward');
+  record('sync');
+}
+
+// Takes the model selection from the textarea and moves the window when the head left its middle line.
+function follow() {
+  const backward = ta.selectionDirection === 'backward';
+  anchor = win.start + (backward ? ta.selectionEnd : ta.selectionStart);
+  head = win.start + (backward ? ta.selectionStart : ta.selectionEnd);
+  if (!composing && lineAt(head) !== win.line) sync();
+}
+
+function render() {
+  statusLine.textContent = `head ${head}, line ${lineAt(head)}${composing ? ', composing' : ''}, ${events.length} events`;
+  shown.textContent = doc;
+}
+
+ta.addEventListener('keydown', (e) =>
+  record('keydown', { key: e.key, isComposing: e.isComposing }),
+);
+ta.addEventListener('beforeinput', (e) =>
+  record('beforeinput', { inputType: e.inputType, data: e.data }),
+);
+ta.addEventListener('input', (e) => {
+  doc = doc.slice(0, win.start) + ta.value + doc.slice(win.start + win.value.length);
+  win.value = ta.value;
+  record('input', { inputType: e.inputType, data: e.data });
+  follow();
+});
+ta.addEventListener('compositionstart', (e) => {
+  composing = true;
+  record('compositionstart', { data: e.data });
+});
+ta.addEventListener('compositionupdate', (e) => record('compositionupdate', { data: e.data }));
+ta.addEventListener('compositionend', (e) => {
+  composing = false;
+  record('compositionend', { data: e.data });
+  setTimeout(() => {
+    if (!composing) follow();
+  }, 0);
+});
+document.addEventListener('selectionchange', () => {
+  if (document.activeElement !== ta) return;
+  record('selectionchange');
+  if (!composing) follow();
+});
+ta.addEventListener('focus', () => record('focus'));
+ta.addEventListener('blur', () => record('blur'));
+
+function reset() {
+  doc = SAMPLE;
+  anchor = INITIAL_CARET;
+  head = INITIAL_CARET;
+  composing = false;
+  events = [];
+  sync();
+}
+
+document.getElementById('reset').addEventListener('click', reset);
+document.getElementById('save').addEventListener('click', async () => {
+  const recording = {
+    name: document.getElementById('name').value.trim(),
+    browser: document.getElementById('browser').value.trim(),
+    keyboard: document.getElementById('keyboard').value.trim(),
+    ua: navigator.userAgent,
+    recordedAt: new Date().toISOString(),
+    settings: { autoCloseBrackets: false, autoIndent: false },
+    initial: { text: SAMPLE, selection: [INITIAL_CARET, INITIAL_CARET] },
+    events,
+    expected: { text: doc },
+  };
+  const res = await fetch('save', { method: 'POST', body: JSON.stringify(recording) });
+  statusLine.textContent = `${res.status} ${await res.text()}`;
+});
+
+reset();
diff --git a/tests/ime-web/recorder/serve.mjs b/tests/ime-web/recorder/serve.mjs
new file mode 100644
index 0000000..d203b8d
--- /dev/null
+++ b/tests/ime-web/recorder/serve.mjs
@@ -0,0 +1,43 @@
+import { readFile, writeFile } from 'node:fs/promises';
+import { createServer } from 'node:http';
+import path from 'node:path';
+
+// Serves the keyboard recorder on loopback and saves each recording it posts into tests/ime-web.
+const here = import.meta.dirname;
+const out = path.join(here, '..');
+const NAME = /^[a-z0-9-]+$/;
+const PAGES = { '/': 'index.html', '/recorder.js': 'recorder.js' };
+const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8' };
+
+const server = createServer(async (req, res) => {
+  const { pathname } = new URL(req.url ?? '/', 'http://127.0.0.1');
+  if (req.method === 'POST' && pathname === '/save') {
+    let body = '';
+    for await (const chunk of req) body += chunk;
+    let recording = null;
+    try {
+      recording = JSON.parse(body);
+    } catch {}
+    if (typeof recording?.name !== 'string' || !NAME.test(recording.name)) {
+      res.writeHead(400).end('the name takes lowercase letters, digits and dashes');
+      return;
+    }
+    await writeFile(
+      path.join(out, `${recording.name}.json`),
+      `${JSON.stringify(recording, null, 2)}\n`,
+    );
+    res.writeHead(200).end('saved');
+    return;
+  }
+  const file = PAGES[pathname];
+  if (!file) {
+    res.writeHead(404).end();
+    return;
+  }
+  res.writeHead(200, { 'content-type': TYPES[path.extname(file)] });
+  res.end(await readFile(path.join(here, file)));
+});
+
+server.listen(Number(process.argv[2] ?? 8090), '127.0.0.1', () => {
+  console.log(`recorder on http://127.0.0.1:${server.address().port}/`);
+});
diff --git a/tests/web/recorder.test.ts b/tests/web/recorder.test.ts
new file mode 100644
index 0000000..09e4a2a
--- /dev/null
+++ b/tests/web/recorder.test.ts
@@ -0,0 +1,49 @@
+import assert from 'node:assert/strict';
+import { spawn } from 'node:child_process';
+import { existsSync, readFileSync, rmSync } from 'node:fs';
+import path from 'node:path';
+import { test } from 'node:test';
+
+const root = path.join(import.meta.dirname, '..', '..');
+const dir = path.join(root, 'tests', 'ime-web');
+
+// Starts the recorder on a free port and resolves its base URL from the line it prints.
+function start(): Promise<{ url: string; stop: () => void }> {
+  const child = spawn(process.execPath, [path.join(dir, 'recorder', 'serve.mjs'), '0'], {
+    stdio: ['ignore', 'pipe', 'inherit'],
+  });
+  return new Promise((resolve, reject) => {
+    child.on('error', reject);
+    child.on('exit', (code) => reject(new Error(`recorder exited with ${code}`)));
+    child.stdout.on('data', (chunk: Buffer) => {
+      const match = /http:\/\/127\.0\.0\.1:\d+\//.exec(chunk.toString());
+      if (match) resolve({ url: match[0], stop: () => child.kill() });
+    });
+  });
+}
+
+const post = (url: string, body: unknown) =>
+  fetch(`${url}save`, {
+    method: 'POST',
+    headers: { 'content-type': 'application/json' },
+    body: JSON.stringify(body),
+  });
+
+test('the recorder server writes only plain names inside tests/ime-web', async () => {
+  const { url, stop } = await start();
+  const written = path.join(dir, 'ok-name.json');
+  try {
+    const ok = await post(url, { name: 'ok-name', events: [] });
+    assert.equal(ok.status, 200);
+    assert.equal(JSON.parse(readFileSync(written, 'utf8')).name, 'ok-name');
+    for (const name of ['../escape', 'a/b', 'Upper', '']) {
+      const res = await post(url, { name, events: [] });
+      assert.equal(res.status, 400, name);
+    }
+    assert.equal(existsSync(path.join(root, 'tests', 'escape.json')), false);
+    assert.equal(existsSync(path.join(dir, 'a')), false);
+  } finally {
+    rmSync(written, { force: true });
+    stop();
+  }
+});
diff --git a/tests/web/render.e2e.mjs b/tests/web/render.e2e.mjs
index a027971..795fe4f 100644
--- a/tests/web/render.e2e.mjs
+++ b/tests/web/render.e2e.mjs
@@ -86,6 +86,567 @@ for (const engine of [chromium, webkit]) {
       return { page, warnings, errors };
     }
 
+    // An editor on host id, kept as window.views[id], with its text drawn.
+    async function editor(page, id, text, options = {}) {
+      await page.evaluate(
+        async ([id, text, options]) => {
+          const { EditorView, loadCore, until } = window.codepad;
+          const view = new EditorView(document.getElementById(id), await loadCore(), text);
+          view.setOptions(options);
+          window.views = { ...window.views, [id]: view };
+          await until(() => document.querySelector(`#${id} [data-line="0"]`));
+        },
+        [id, text, options],
+      );
+    }
+
+    // Clicks the left edge of a column in a drawn line.
+    async function clickAt(page, id, line, column) {
+      await page.waitForSelector(`#${id} [data-line="${line}"]`, { state: 'attached' });
+      const { x, y } = await page.evaluate(
+        ([id, line, column]) => {
+          const el = document.querySelector(`#${id} [data-line="${line}"]`);
+          const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
+          let at = 0;
+          for (let node = walker.nextNode(); node; node = walker.nextNode()) {
+            if (column <= at + node.data.length) {
+              const range = document.createRange();
+              range.setStart(node, column - at);
+              range.setEnd(node, column - at);
+              const r = range.getBoundingClientRect();
+              return { x: r.left + 1, y: r.top + r.height / 2 };
+            }
+            at += node.data.length;
+          }
+          const r = el.getBoundingClientRect();
+          return { x: r.right + 4, y: r.top + r.height / 2 };
+        },
+        [id, line, column],
+      );
+      await page.mouse.click(x, y);
+    }
+
+    const textOf = (page, id) => page.evaluate((id) => window.views[id].core.text(), id);
+    const visible = (page, selector) =>
+      page.evaluate((s) => {
+        const el = document.querySelector(s);
+        return !!el && el.style.display !== 'none' && el.getBoundingClientRect().width > 0;
+      }, selector);
+
+    // Starts a composition of text at the caret: the browser's own IME in Chromium, dispatched events in WebKit.
+    async function compose(page, id, text) {
+      if (engine === chromium) {
+        const cdp = await page.context().newCDPSession(page);
+        await cdp.send('Input.imeSetComposition', {
+          text,
+          selectionStart: text.length,
+          selectionEnd: text.length,
+        });
+        return cdp;
+      }
+      await page.evaluate(
+        ([id, text]) => {
+          const ta = document.querySelector(`#${id} textarea`);
+          const at = ta.selectionStart;
+          ta.dispatchEvent(new CompositionEvent('compositionstart', { data: '' }));
+          ta.value = ta.value.slice(0, at) + text + ta.value.slice(at);
+          ta.setSelectionRange(at + text.length, at + text.length);
+          ta.dispatchEvent(
+            new InputEvent('input', {
+              inputType: 'insertCompositionText',
+              data: text,
+              isComposing: true,
+            }),
+          );
+        },
+        [id, text],
+      );
+      return null;
+    }
+
+    async function commit(page, id, cdp, composed, text) {
+      if (cdp) return cdp.send('Input.insertText', { text });
+      await page.evaluate(
+        ([id, composed, text]) => {
+          const ta = document.querySelector(`#${id} textarea`);
+          const end = ta.selectionStart;
+          ta.value = ta.value.slice(0, end - composed.length) + text + ta.value.slice(end);
+          const at = end - composed.length + text.length;
+          ta.setSelectionRange(at, at);
+          ta.dispatchEvent(
+            new InputEvent('input', {
+              inputType: 'insertCompositionText',
+              data: text,
+              isComposing: true,
+            }),
+          );
+          ta.dispatchEvent(new CompositionEvent('compositionend', { data: text }));
+        },
+        [id, composed, text],
+      );
+    }
+
+    test('a click places the caret and typing inserts there', async () => {
+      const { page, errors } = await open();
+      await editor(page, 'a', 'abcdef\nghijkl\n');
+      await clickAt(page, 'a', 1, 3);
+      await page.keyboard.type('xy');
+      assert.equal(await textOf(page, 'a'), 'abcdef\nghixyjkl\n');
+      assert.deepEqual(errors, []);
+      await page.close();
+    });
+
+    test('Enter splits the line and Backspace joins it again', async () => {
+      const { page } = await open();
+      await editor(page, 'a', 'ab', { autoIndent: false });
+      await clickAt(page, 'a', 0, 1);
+      await page.keyboard.press('Enter');
+      assert.equal(await textOf(page, 'a'), 'a\nb');
+      await page.keyboard.press('Backspace');
+      assert.equal(await textOf(page, 'a'), 'ab');
+      await page.close();
+    });
+
+    test('a composition shows its underline then commits', async () => {
+      const { page, errors } = await open();
+      await editor(page, 'a', 'ab');
+      await clickAt(page, 'a', 0, 2);
+      const cdp = await compose(page, 'a', 'か');
+      await page.waitForFunction(() => window.views.a.core.text() === 'abか');
+      await page.evaluate(() => window.codepad.frames(2));
+      assert.equal(await visible(page, '#a [data-composing]'), true);
+      await commit(page, 'a', cdp, 'か', '蚊');
+      await page.waitForFunction(() => window.views.a.core.text() === 'ab蚊');
+      await page.evaluate(() => window.codepad.frames(2));
+      assert.equal(await visible(page, '#a [data-composing]'), false);
+      assert.deepEqual(errors, []);
+      await page.close();
+    });
+
+    test('clicking elsewhere mid-composition leaves no underline', async () => {
+      const { page } = await open();
+      await editor(page, 'a', 'ab\ncd');
+      await clickAt(page, 'a', 0, 2);
+      await compose(page, 'a', 'か');
+      await page.waitForFunction(() => window.views.a.core.text() === 'abか\ncd');
+      await clickAt(page, 'a', 1, 1);
+      await page.evaluate(() => window.codepad.frames(2));
+      assert.equal(await visible(page, '#a [data-composing]'), false);
+      assert.equal(await textOf(page, 'a'), 'abか\ncd');
+      await page.close();
+    });
+
+    test('readOnly keeps the text and still places the caret', async () => {
+      const { page } = await open();
+      await editor(page, 'a', 'abc', { readOnly: true });
+      await clickAt(page, 'a', 0, 1);
+      await page.keyboard.type('x');
+      assert.equal(await textOf(page, 'a'), 'abc');
+      assert.equal(await page.evaluate(() => window.views.a.core.selection.head), 1);
+      await page.close();
+    });
+
+    test('an onChange that throws keeps the edit and the sync', async () => {
+      const { page, errors } = await open();
+      await editor(page, 'a', '');
+      await page.evaluate(() =>
+        window.views.a.setOptions({
+          onChange: () => {
+            throw new Error('boom');
+          },
+        }),
+      );
+      await clickAt(page, 'a', 0, 0);
+      await page.keyboard.type('ab');
+      assert.equal(await textOf(page, 'a'), 'ab');
+      assert.equal(await page.evaluate(() => document.querySelector('#a textarea').value), 'ab');
+      assert.ok(
+        errors.some((e) => /boom/.test(e)),
+        String(errors),
+      );
+      await page.close();
+    });
+
+    test('only the focused editor draws a caret and takes keys', async () => {
+      const { page } = await open();
+      await editor(page, 'a', 'one');
+      await editor(page, 'b', 'two');
+      await clickAt(page, 'a', 0, 3);
+      await clickAt(page, 'b', 0, 3);
+      await page.keyboard.type('z');
+      assert.equal(await textOf(page, 'b'), 'twoz');
+      assert.equal(await textOf(page, 'a'), 'one');
+      await page.evaluate(() => window.codepad.frames(2));
+      assert.equal(await visible(page, '#a [data-caret]'), false);
+      assert.equal(await visible(page, '#b [data-caret]'), true);
+      await page.close();
+    });
+
+    test('onFocus and onBlur fire once per change', async () => {
+      const { page } = await open();
+      await editor(page, 'a', 'one');
+      await editor(page, 'b', 'two');
+      await page.evaluate(() => {
+        window.counts = { focus: 0, blur: 0 };
+        window.views.a.setOptions({
+          onFocus: () => window.counts.focus++,
+          onBlur: () => window.counts.blur++,
+        });
+      });
+      await clickAt(page, 'a', 0, 1);
+      await clickAt(page, 'a', 0, 2);
+      await clickAt(page, 'b', 0, 1);
+      assert.deepEqual(await page.evaluate(() => window.counts), { focus: 1, blur: 1 });
+      await page.close();
+    });
+
+    test('select all then Backspace empties a file longer than the textarea window', async () => {
+      const { page } = await open();
+      await editor(
+        page,
+        'a',
+        Array.from({ length: 3000 }, (_, i) => `line number ${i}`).join('\n'),
+      );
+      await clickAt(page, 'a', 0, 0);
+      await page.keyboard.press(`${process.platform === 'darwin' ? 'Meta' : 'Control'}+a`);
+      await page.evaluate(() => window.codepad.frames(3));
+      await page.keyboard.press('Backspace');
+      assert.equal(await textOf(page, 'a'), '');
+      await page.close();
+    });
+
+    test('copy and cut after select all carry the whole document', async () => {
+      const { page } = await open();
+      const text = Array.from({ length: 3000 }, (_, i) => `line number ${i}`).join('\n');
+      await editor(page, 'a', text);
+      await clickAt(page, 'a', 0, 0);
+      await page.keyboard.press(`${process.platform === 'darwin' ? 'Meta' : 'Control'}+a`);
+      const result = await page.evaluate(async () => {
+        await window.codepad.frames(2);
+        const ta = document.querySelector('#a textarea');
+        const clip = (type) => {
+          const data = new DataTransfer();
+          ta.dispatchEvent(
+            new ClipboardEvent(type, { clipboardData: data, bubbles: true, cancelable: true }),
+          );
+          return data.getData('text/plain').length;
+        };
+        const copied = clip('copy');
+        const cut = clip('cut');
+        return { copied, cut, left: window.views.a.core.length };
+      });
+      assert.deepEqual(result, { copied: text.length, cut: text.length, left: 0 });
+      await page.close();
+    });
+
+    test('a click on a line number keeps the focus where it is', async () => {
+      const { page } = await open();
+      await editor(page, 'a', 'one\ntwo');
+      await page.evaluate(() => {
+        window.counts = { focus: 0, blur: 0 };
+        window.views.a.setOptions({
+          onFocus: () => window.counts.focus++,
+          onBlur: () => window.counts.blur++,
+        });
+      });
+      await clickAt(page, 'a', 0, 1);
+      const { x, y } = await page.evaluate(() => {
+        const host = document.getElementById('a').getBoundingClientRect();
+        const line = document.querySelector('#a [data-line="1"]').getBoundingClientRect();
+        return { x: host.left + 4, y: line.top + line.height / 2 };
+      });
+      await page.mouse.click(x, y);
+      assert.deepEqual(await page.evaluate(() => window.counts), { focus: 1, blur: 0 });
+      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');
+      await clickAt(page, 'a', 0, 3);
+      for (const step of [
+        (v) => v.apply(() => v.core.replace(0, 0, 'Q')),
+        (v) => v.apply(() => v.core.setText('new')),
+        (v) => v.apply(() => v.core.undo()),
+      ]) {
+        await page.evaluate(`(${step})(window.views.a)`);
+        const head = await page.evaluate(() => window.views.a.core.selection.head);
+        const before = await textOf(page, 'a');
+        await page.keyboard.type('z');
+        assert.equal(await textOf(page, 'a'), `${before.slice(0, head)}z${before.slice(head)}`);
+      }
+      await page.close();
+    });
+
+    const head = (page) => page.evaluate(() => window.views.a.core.selection.head);
+
+    test('ArrowDown keeps the column across a shorter line', async () => {
+      const { page, errors } = await open();
+      await editor(page, 'a', 'abcdef\nab\nabcdef');
+      await clickAt(page, 'a', 0, 5);
+      await page.keyboard.press('ArrowDown');
+      assert.equal(await head(page), 9);
+      await page.keyboard.press('ArrowDown');
+      assert.equal(await head(page), 15);
+      assert.deepEqual(errors, []);
+      await page.close();
+    });
+
+    test('ArrowDown on the last visible row scrolls and moves', async () => {
+      const { page } = await open();
+      await editor(page, 'a', Array.from({ length: 100 }, (_, i) => `line ${i}`).join('\n'));
+      await clickAt(page, 'a', 0, 2);
+      const rows = await page.evaluate(() => {
+        const v = window.views.a;
+        return Math.ceil(v.layout.viewportHeight / v.layout.rowHeight);
+      });
+      for (let i = 0; i < rows + 3; i++) await page.keyboard.press('ArrowDown');
+      const result = await page.evaluate(async () => {
+        const v = window.views.a;
+        await window.codepad.frames(2);
+        const caret = v.caretRect(v.core.selection.head);
+        return { line: v.core.lineAt(v.core.selection.head), y: caret?.y ?? null };
+      });
+      assert.equal(result.line, rows + 3);
+      assert.ok(result.y !== null && result.y >= 0 && result.y < 300, `caret y ${result.y}`);
+      await page.close();
+    });
+
+    test('Enter on the last visible row keeps the caret in view', async () => {
+      const { page } = await open();
+      await editor(page, 'a', Array.from({ length: 40 }, (_, i) => `line ${i}`).join('\n'));
+      const last = await page.evaluate(() => {
+        const v = window.views.a;
+        return Math.floor(v.layout.viewportHeight / v.layout.rowHeight) - 1;
+      });
+      await clickAt(page, 'a', last, 6);
+      for (let i = 0; i < 3; i++) await page.keyboard.press('Enter');
+      const y = await page.evaluate(async () => {
+        const v = window.views.a;
+        await window.codepad.frames(2);
+        return v.caretRect(v.core.selection.head)?.y ?? null;
+      });
+      assert.ok(y !== null && y >= 0 && y < 300, `caret y ${y}`);
+      await page.close();
+    });
+
+    test('the frame after a letter, an Enter and a joining Backspace keeps the keyword colors', async () => {
+      const { page } = await open();
+      await page.evaluate(async () => {
+        const { EditorView, ensureLanguage, loadCore, until } = window.codepad;
+        await ensureLanguage('python');
+        const host = document.getElementById('a');
+        const view = new EditorView(host, await loadCore(), 'def a():\n    return b\n');
+        view.setLanguage('python');
+        window.views = { a: view };
+        await until(() => host.querySelector('[data-line="1"] span'));
+      });
+      await clickAt(page, 'a', 0, 8);
+      const result = await page.evaluate(async (keyword) => {
+        const v = window.views.a;
+        const colored = (line) =>
+          [...document.querySelectorAll(`#a [data-line="${line}"] span`)].filter(
+            (s) => getComputedStyle(s).color === keyword,
+          ).length;
+        const nextFrame = () => new Promise((r) => requestAnimationFrame(() => r()));
+        const out = {};
+        v.apply(() => v.core.typeText('x'));
+        await nextFrame();
+        out.letter = colored(0);
+        v.apply(() => v.core.setSelection(20, 20));
+        await window.codepad.frames(2);
+        v.apply(() => v.core.insertNewline());
+        await nextFrame();
+        out.enter = colored(1);
+        await window.codepad.frames(2);
+        const joinFrom = v.core.lineEnd(1);
+        v.apply(() => v.core.replace(joinFrom, v.core.selection.head, ''));
+        await nextFrame();
+        out.join = colored(1);
+        out.text = v.core.text();
+        return out;
+      }, KEYWORD);
+      assert.deepEqual(result, {
+        letter: 1,
+        enter: 1,
+        join: 1,
+        text: 'def a():x\n    return b\n',
+      });
+      await page.close();
+    });
+
+    test('two edits before a frame and a join under a blank line keep the keyword colors', async () => {
+      const { page } = await open();
+      const result = await page.evaluate(async (keyword) => {
+        const { EditorView, ensureLanguage, frames, loadCore, until } = window.codepad;
+        await ensureLanguage('python');
+        const host = document.getElementById('a');
+        const v = new EditorView(
+          host,
+          await loadCore(),
+          'def a():\n    pass\n\ndef c():\n    pass\n',
+        );
+        v.setLanguage('python');
+        await until(() => host.querySelector('[data-line="3"] span'));
+        const colored = (line) =>
+          [...host.querySelectorAll(`[data-line="${line}"] span`)].filter(
+            (s) => getComputedStyle(s).color === keyword,
+          ).length;
+        const nextFrame = () => new Promise((r) => requestAnimationFrame(() => r()));
+        v.apply(() => v.core.setSelection(8, 8));
+        await frames(2);
+        v.apply(() => v.core.typeText('x'));
+        v.apply(() => v.core.typeText('y'));
+        await nextFrame();
+        const twice = colored(0);
+        await frames(3);
+        const blank = v.core.lineEnd(2);
+        v.apply(() => v.core.replace(blank, blank + 1, ''));
+        await nextFrame();
+        return { twice, join: colored(2), text: v.core.text() };
+      }, KEYWORD);
+      assert.deepEqual(result, {
+        twice: 1,
+        join: 1,
+        text: 'def a():xy\n    pass\ndef c():\n    pass\n',
+      });
+      await page.close();
+    });
+
+    test('PageDown moves by the visible rows', async () => {
+      const { page } = await open();
+      await editor(page, 'a', Array.from({ length: 100 }, (_, i) => `line ${i}`).join('\n'));
+      await clickAt(page, 'a', 0, 0);
+      // The page the key moves by, read once the first frames have settled the scrollbars.
+      const rows = await page.evaluate(async () => {
+        await window.codepad.frames(3);
+        const v = window.views.a;
+        return Math.floor(v.layout.viewportHeight / v.layout.rowHeight);
+      });
+      await page.keyboard.press('PageDown');
+      const result = await page.evaluate(async () => {
+        const v = window.views.a;
+        await window.codepad.frames(2);
+        const caret = v.caretRect(v.core.selection.head);
+        return {
+          line: v.core.lineAt(v.core.selection.head),
+          y: caret?.y ?? null,
+        };
+      });
+      assert.equal(result.line, rows);
+      assert.ok(result.y !== null && result.y >= 0 && result.y < 300, `caret y ${result.y}`);
+      await page.close();
+    });
+
+    test('a caret move after an edit to a line not drawn measures its new text', async () => {
+      const { page } = await open();
+      await editor(page, 'a', Array.from({ length: 100 }, (_, i) => `line ${i}`).join('\n'), {
+        softWrap: true,
+      });
+      const line = await page.evaluate(() => {
+        const v = window.views.a;
+        v.moveCaret('pageDown', false);
+        v.moveCaret('pageDown', false);
+        const at = v.core.lineAt(v.core.selection.head);
+        const start = v.core.lineStart(at);
+        v.apply(() => v.core.replace(start, v.core.lineEnd(at), 'x'.repeat(300)));
+        v.apply(() => v.core.setSelection(start + 20, start + 20));
+        v.moveCaret('down', false);
+        return { at, now: v.core.lineAt(v.core.selection.head) };
+      });
+      assert.equal(line.now, line.at);
+      await page.close();
+    });
+
+    test('ArrowDown into right-to-left text lands on the nearest column', async () => {
+      const { page } = await open();
+      await editor(page, 'a', 'abcdefghijklmnopq\nab مرحبا بالعالم cd');
+      const columns = await page.evaluate(() => {
+        const v = window.views.a;
+        const out = [];
+        for (let c = 4; c <= 15; c++) {
+          v.apply(() => v.core.setSelection(c, c));
+          const goal = v.caretRect(c).x;
+          v.moveCaret('down', false);
+          const start = v.core.lineStart(1);
+          const x = (o) => v.caretRect(o).x;
+          let best = Infinity;
+          for (let o = start; o <= v.core.lineEnd(1); o++)
+            best = Math.min(best, Math.abs(x(o) - goal));
+          out.push(Math.abs(x(v.core.selection.head) - goal) - best);
+        }
+        return out;
+      });
+      assert.ok(Math.max(...columns) < 1, `extra distance ${columns}`);
+      await page.close();
+    });
+
+    test('Shift+ArrowRight draws a selection', async () => {
+      const { page } = await open();
+      await editor(page, 'a', 'abcdef');
+      await clickAt(page, 'a', 0, 1);
+      await page.keyboard.press('Shift+ArrowRight');
+      await page.keyboard.press('Shift+ArrowRight');
+      const result = await page.evaluate(async () => {
+        const v = window.views.a;
+        await window.codepad.frames(2);
+        const boxes = [...document.querySelectorAll('#a [data-selection] > div')];
+        return { selection: v.core.selection, width: boxes[0]?.getBoundingClientRect().width ?? 0 };
+      });
+      assert.deepEqual(result.selection, { anchor: 1, head: 3 });
+      assert.ok(result.width > 0, 'no selection drawn');
+      await page.close();
+    });
+
+    test('Tab indents, keeps the focus, and the platform undo key takes it back', async () => {
+      const { page } = await open();
+      await editor(page, 'a', 'abc');
+      await clickAt(page, 'a', 0, 0);
+      await page.keyboard.press('Tab');
+      assert.notEqual(await textOf(page, 'a'), 'abc');
+      assert.equal(await page.evaluate(() => document.activeElement?.tagName), 'TEXTAREA');
+      await page.keyboard.press(`${process.platform === 'darwin' ? 'Meta' : 'Control'}+z`);
+      assert.equal(await textOf(page, 'a'), 'abc');
+      await page.close();
+    });
+
+    test('ref typeText auto-closes and moveCaret up keeps the goal column', async () => {
+      const { page } = await open();
+      await editor(page, 'a', 'abcdefghij\nab\nabcdef');
+      const result = await page.evaluate(() => {
+        const v = window.views.a;
+        v.apply(() => v.core.setSelection(20, 20));
+        v.typeText('(');
+        const typed = { text: v.core.text(), head: v.core.selection.head };
+        v.moveCaret('up', false);
+        const first = v.core.selection.head;
+        v.moveCaret('up', false);
+        return { typed, first, second: v.core.selection.head };
+      });
+      assert.deepEqual(result, {
+        typed: { text: 'abcdefghij\nab\nabcdef()', head: 21 },
+        first: 13,
+        second: 7,
+      });
+      await page.close();
+    });
+
+    test('the typing ref methods do nothing under readOnly while moveCaret still moves', async () => {
+      const { page } = await open();
+      await editor(page, 'a', 'abc', { readOnly: true });
+      const result = await page.evaluate(() => {
+        const v = window.views.a;
+        v.apply(() => v.core.setSelection(1, 1));
+        v.typeText('x');
+        v.deleteBackward();
+        v.deleteForward();
+        v.moveCaret('right', true);
+        return { text: v.core.text(), selection: v.core.selection };
+      });
+      assert.deepEqual(result, { text: 'abc', selection: { anchor: 1, head: 2 } });
+      await page.close();
+    });
+
     test('colors python keywords', async () => {
       const { page, errors } = await open();
       const color = await page.evaluate(async () => {
@@ -156,6 +717,32 @@ for (const engine of [chromium, webkit]) {
       await page.close();
     });
 
+    test('a composition ended just before unmount reads nothing from the closed core', async () => {
+      const { page, errors } = await open();
+      const reads = await page.evaluate(async () => {
+        const { EditorView, loadCore, until } = window.codepad;
+        const m = await loadCore();
+        const a = new EditorView(document.getElementById('a'), m, 'first');
+        await until(() => document.querySelector('#a [data-line="0"]'));
+        const ta = document.querySelector('#a textarea');
+        ta.dispatchEvent(new CompositionEvent('compositionstart'));
+        ta.dispatchEvent(new CompositionEvent('compositionend'));
+        a.destroy();
+        let count = 0;
+        Object.defineProperty(a.core, 'selection', {
+          get: () => {
+            count++;
+            return { anchor: 0, head: 0 };
+          },
+        });
+        await new Promise((resolve) => setTimeout(resolve, 20));
+        return count;
+      });
+      assert.equal(reads, 0);
+      assert.deepEqual(errors, []);
+      await page.close();
+    });
+
     test('unmounting during a parse closes the engine and keeps no snapshot', async () => {
       const { page, errors } = await open('test');
       const result = await page.evaluate(async () => {
@@ -445,5 +1032,64 @@ for (const engine of [chromium, webkit]) {
       assert.deepEqual(errors, []);
       await page.close();
     });
+
+    // The color of "func" in a Go fence, a language no injection query names, so only the fence loads it.
+    async function fenceKeywordColor(page, hosts) {
+      return page.evaluate(async (ids) => {
+        const { EditorView, loadCore, until } = window.codepad;
+        const m = await loadCore();
+        const text = '# Title\n```go\nfunc f() {}\n```\n';
+        const def = (id) =>
+          [...document.querySelectorAll(`#${id} [data-line="2"] span`)].find(
+            (s) => s.textContent === 'func',
+          );
+        const colors = [];
+        for (const id of ids) {
+          new EditorView(document.getElementById(id), m, text).setLanguage('markdown');
+          await until(() => def(id) && getComputedStyle(def(id)).color !== 'rgb(31, 35, 40)');
+          colors.push(getComputedStyle(def(id)).color);
+        }
+        return colors;
+      }, hosts);
+    }
+
+    test('a markdown fence colors go, which no injection query names', async () => {
+      const { page, errors } = await open();
+      assert.deepEqual(await fenceKeywordColor(page, ['a']), [KEYWORD]);
+      assert.deepEqual(errors, []);
+      await page.close();
+    });
+
+    test('a second markdown editor colors the same fence', async () => {
+      const { page, errors } = await open();
+      assert.deepEqual(await fenceKeywordColor(page, ['a', 'b']), [KEYWORD, KEYWORD]);
+      assert.deepEqual(errors, []);
+      await page.close();
+    });
+
+    test('a fence naming a language that is not installed draws plain and refreshes nothing', async () => {
+      const { page, errors } = await open();
+      const refreshes = await page.evaluate(async () => {
+        const { EditorView, frames, loadCore, until } = window.codepad;
+        const view = new EditorView(
+          document.getElementById('a'),
+          await loadCore(),
+          '```zig\nconst x = 1;\n```\n',
+        );
+        let count = 0;
+        const refresh = view.core.refreshInjections.bind(view.core);
+        view.core.refreshInjections = () => {
+          count++;
+          refresh();
+        };
+        view.setLanguage('markdown');
+        await until(() => view.core.snapshotCount > 0);
+        await frames(10);
+        return count;
+      });
+      assert.equal(refreshes, 0);
+      assert.deepEqual(errors, []);
+      await page.close();
+    });
   });
 }