Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
4649226
test(web): a recorder for the browser keyboard events
SectionTN Nov 14, 2026
b96987b
test(web): keyboard recordings from Chrome on Android and Safari on iOS
SectionTN Nov 14, 2026
20e9c2f
fix(web): load the language a markdown fence names
SectionTN Nov 14, 2026
b7da020
feat(web): map the keyboard's textarea onto the core
SectionTN Nov 14, 2026
8ea9fac
feat(web): type into the editor with a caret and focus
SectionTN Nov 14, 2026
4d5d157
feat(web): arrow keys, shortcuts and the typing ref methods
SectionTN Nov 14, 2026
974bd97
feat(web): avoidKeyboard follows the visual viewport
SectionTN Nov 14, 2026
1022d41
chore(web): a typing bench for Chrome on a phone
SectionTN Nov 14, 2026
827d829
perf(web): write only the styles a draw changes
SectionTN Nov 15, 2026
671f904
chore(example): a suggestions switch on the web example
SectionTN Nov 15, 2026
53a0922
perf(web): draw a key's frame before the parse runs
SectionTN Nov 15, 2026
de06c84
fix(web): keep a select all whole when the browser echoes it
SectionTN Nov 15, 2026
b27af19
fix(web): leave avoidKeyboard at zero when no keyboard is open
SectionTN Nov 15, 2026
a326b12
fix(web): run ref focus and blur made before the core loads
SectionTN Nov 15, 2026
a5e1926
fix(web): no plain frame after two quick edits or a join under a blan…
SectionTN Nov 15, 2026
46ef63c
test(web): read the PageDown page size before the key
SectionTN Nov 15, 2026
26a1857
fix(web): paste as written and keep the caret right after long replac…
SectionTN Nov 15, 2026
959f887
fix(web): keep the textarea window until a composition has settled
SectionTN Nov 15, 2026
c30c244
fix(web): copy and cut the whole selection, not the textarea window
SectionTN Nov 15, 2026
ed8b8dd
fix(web): land vertical moves on the nearest column in right-to-left …
SectionTN Nov 15, 2026
53f747f
fix(core): color a fence when two refreshes queue before the pump
SectionTN Nov 15, 2026
b0be278
fix(web): stop the composition settle once the editor unmounts
SectionTN Nov 15, 2026
de1ef38
fix(web): add no undo step for an input that changes nothing
SectionTN Nov 15, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions cpp/core/include/codepad.h
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
24 changes: 24 additions & 0 deletions cpp/core/src/engine.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,28 @@ struct Engine : std::enable_shared_from_this<Engine> {
});
}

// 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<int32_t>(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;
Expand Down Expand Up @@ -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) {
Expand Down
32 changes: 30 additions & 2 deletions cpp/web/host.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
#include <dlfcn.h>
#include <emscripten/emscripten.h>

#include <algorithm>
#include <cctype>
#include <cstring>
#include <deque>
Expand Down Expand Up @@ -31,6 +32,8 @@ struct Editor {
bool closed = false;
std::vector<int32_t> changes;
std::vector<cp_unit> text;
// Injection names that found no language, in the order the engine asked.
std::vector<std::string> missed;
};

std::deque<Work> worker_q;
Expand Down Expand Up @@ -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<char>(tolower(static_cast<unsigned char>(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<Editor *>(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) {
Expand Down Expand Up @@ -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<int32_t>(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;
Expand Down
40 changes: 34 additions & 6 deletions example/src/EditorApp.web.tsx
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -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<Demo>('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 = <T,>(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`,
Expand All @@ -40,7 +60,7 @@ export function EditorApp() {

return (
<View style={[styles.page, { backgroundColor: theme?.background }]}>
<View style={styles.bar}>
<View style={[styles.bar, styles.wrap]}>
{(['editor', 'nested', 'two'] as Demo[]).map((d) => (
<Chip key={d} label={d} on={demo === d} onPress={() => pick(setDemo, d)} />
))}
Expand All @@ -54,6 +74,11 @@ export function EditorApp() {
on={!scrollEnabled}
onPress={() => setScrollEnabled((s) => !s)}
/>
<Chip
label={`suggestions ${suggestions}`}
on={suggestions === 'on'}
onPress={() => setSuggestions((s) => (s === 'on' ? 'off' : 'on'))}
/>
</View>
<ScrollView horizontal style={styles.files} contentContainerStyle={styles.bar}>
{FILES.map((f) => (
Expand All @@ -71,14 +96,16 @@ export function EditorApp() {
</ScrollView>
{demo === 'editor' ? (
<CodeEditor
key={file?.id}
key={benchLines ? `bench-${benchLines}` : file?.id}
style={styles.editor}
initialValue={text}
language={file?.language}
language={benchLines ? 'javascript' : file?.language}
theme={theme}
fontFamily={FONT}
scrollEnabled={scrollEnabled}
onReady={ready(file?.name ?? '')}
suggestions={suggestions}
avoidKeyboard
onReady={ready(benchLines ? `bench ${benchLines}` : (file?.name ?? ''))}
/>
) : null}
{demo === 'nested' ? (
Expand Down Expand Up @@ -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' },
Expand Down
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
61 changes: 61 additions & 0 deletions scripts/bench-web.mjs
Original file line number Diff line number Diff line change
@@ -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}`]);
}
44 changes: 27 additions & 17 deletions src/web/CodeEditor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,8 @@ export const CodeEditor = forwardRef<CodeEditorRef, CodeEditorProps>(function Co
onChange,
onChangeText,
onContentSizeChange,
onFocus,
onBlur,
});
handlers.current = {
onReady,
Expand All @@ -90,6 +92,8 @@ export const CodeEditor = forwardRef<CodeEditorRef, CodeEditorProps>(function Co
onChange,
onChangeText,
onContentSizeChange,
onFocus,
onBlur,
};
const initial = useRef(initialValue);

Expand All @@ -113,6 +117,11 @@ export const CodeEditor = forwardRef<CodeEditorRef, CodeEditorProps>(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 }),
Expand Down Expand Up @@ -149,6 +158,9 @@ export const CodeEditor = forwardRef<CodeEditorRef, CodeEditorProps>(function Co
insertSpaces,
autoIndent,
autoCloseBrackets,
suggestions,
autoFocus,
avoidKeyboard,
],
);
const latest = useRef({ options, language });
Expand All @@ -172,7 +184,7 @@ export const CodeEditor = forwardRef<CodeEditorRef, CodeEditorProps>(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);
Expand All @@ -195,14 +207,9 @@ export const CodeEditor = forwardRef<CodeEditorRef, CodeEditorProps>(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);
Expand All @@ -215,12 +222,15 @@ export const CodeEditor = forwardRef<CodeEditorRef, CodeEditorProps>(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<void> => {
// Runs on the view now, or once the core loads when the call comes before it.
const run = (call: (v: EditorView) => void): Promise<void> => {
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) ?? '',
Expand All @@ -242,7 +252,7 @@ export const CodeEditor = forwardRef<CodeEditorRef, CodeEditorProps>(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()),
Expand All @@ -263,18 +273,18 @@ export const CodeEditor = forwardRef<CodeEditorRef, CodeEditorProps>(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()),
};
}, []);

Expand Down
Loading
Loading