Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
4d58551
perf(web): start an engine step only when a parse slice still fits th…
SectionTN Nov 17, 2026
8cb7da0
chore(web): a key count and the mean in the typing bench
SectionTN Nov 17, 2026
26e5cbc
perf(web): keep a line's element when a key edits only that line
SectionTN Nov 17, 2026
54a4deb
perf(web): skip moving the line cache when an edit stays inside one line
SectionTN Nov 17, 2026
89f0ebf
perf(web): follow a horizontal caret reveal without drawing the frame…
SectionTN Nov 17, 2026
a5e4bff
perf(web): read the editor's box once per draw and the caret row only…
SectionTN Nov 17, 2026
0ca13cd
feat(web): underlines, line backgrounds and gaps from the decorations…
SectionTN Nov 17, 2026
5097303
fix(web): clear removed decorations even when decorationsRevision is old
SectionTN Nov 17, 2026
8ea3e4e
fix(web): put the decorations on the view before its first draw
SectionTN Nov 17, 2026
936dfdc
feat(web): search, find and replace with the scan sliced in the page …
SectionTN Nov 17, 2026
1fcbd4f
test(web): check a sliced search scan against a second core's matches
SectionTN Nov 17, 2026
c980b0a
fix(example): reset the web find bar when the editor opens another file
SectionTN Nov 17, 2026
3a3e13d
fix(example): give the web find bar's controls roles and names
SectionTN Nov 17, 2026
68f4300
feat(web): bracket pair, clipboard ref methods and the animated scrol…
SectionTN Nov 17, 2026
583264a
fix(web): cut deletes only what it copied, and nothing once readOnly
SectionTN Nov 17, 2026
cdbcb49
fix(web): keep a shortcut on the key a Dvorak layout prints
SectionTN Nov 17, 2026
2724b26
test(web): tell the two pump rules apart on a loaded machine
SectionTN Nov 17, 2026
eb50a0e
fix(web): survive throwing listeners and take browser undo gestures
SectionTN Nov 17, 2026
8553818
chore(web): bench typing with a search and decorations on
SectionTN Nov 17, 2026
3598f9d
fix(web): repaint match and bracket marks when the text moves
SectionTN Nov 17, 2026
dac7694
fix(web): keep the caret on a line replaced with the same text
SectionTN Nov 17, 2026
491f7ad
fix(web): place overlay marks per line so gaps and typing keep them i…
SectionTN Nov 17, 2026
94d7d39
test(web): make the overlay guard fail when marks stay on an old row
SectionTN Nov 17, 2026
f753026
fix(web): paint only the matches in view on long unwrapped lines
SectionTN Nov 17, 2026
7a9ae56
perf(web): split underlines over the drawn lines only
SectionTN Nov 17, 2026
184009f
test(web): check that marks follow the text when the top inset changes
SectionTN Nov 17, 2026
55efbb3
chore(web): stop the typing bench on a bad flag operand
SectionTN Nov 17, 2026
0476515
chore(web): reject an infinite desktop rate in the typing bench
SectionTN Nov 17, 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
9 changes: 6 additions & 3 deletions cpp/web/host.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -238,10 +238,13 @@ CPW void cpw_set_clock(int32_t e, double millis) {
if (Editor *ed = at(e)) ed->clock = millis;
}

// Runs worker work, then main work, until both queues are empty or budget_ms is spent. Returns the items left.
CPW int32_t cpw_pump(double budget_ms) {
// Runs worker work, then main work, until both queues are empty or budget_ms is spent. After the first item, another
// starts only while a parse slice of slice_ms still fits. Returns the items left.
CPW int32_t cpw_pump(double budget_ms, double slice_ms) {
double end = emscripten_get_now() + budget_ms;
while ((!worker_q.empty() || !main_q.empty()) && emscripten_get_now() < end) {
bool first = true;
while ((!worker_q.empty() || !main_q.empty()) && (first || emscripten_get_now() + slice_ms < end)) {
first = false;
std::deque<Work> &q = !worker_q.empty() ? worker_q : main_q;
Work w = q.front();
q.pop_front();
Expand Down
69 changes: 65 additions & 4 deletions example/src/EditorApp.web.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { Pressable, ScrollView, StyleSheet, Text, View } from 'react-native';
import { CodeEditor, Codepad } from 'react-native-codepad';
import { CodeEditor, type CodeEditorRef, Codepad, type Decoration } from 'react-native-codepad';
import { generateJavaScript } from './bench/generate';
import { FindBar } from './chrome/FindBar';
import { schemeFor } from './chrome/theme';
import { buildDemoDecorations } from './decorations';
import { GENERATED_FILES, SAMPLE_FILES } from './files';
import { NESTED_SNIPPET } from './screens/nestedSnippet';
import { THEMES } from './themes';

type Demo = 'editor' | 'nested' | 'two';
const FILES = [...SAMPLE_FILES, ...GENERATED_FILES.filter((f) => f.id === 'js10k')];
const FONT = 'JetBrainsMono_400Regular';
const NO_DECORATIONS: { items: Decoration[]; revision: number } = { items: [], revision: -1 };

function Chip({ label, on, onPress }: { label: string; on: boolean; onPress: () => void }) {
return (
Expand All @@ -24,11 +28,18 @@ export function EditorApp() {
const [themeIndex, setThemeIndex] = useState(0);
const [scrollEnabled, setScrollEnabled] = useState(true);
const [suggestions, setSuggestions] = useState<'on' | 'off'>('off');
const [decorate, setDecorate] = useState(false);
const [finding, setFinding] = useState(false);
const [status, setStatus] = useState('');
const [decorations, setDecorations] = useState(NO_DECORATIONS);
const editor = useRef<CodeEditorRef>(null);
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];
// The editor and the find bar both remount when this changes, so the bar never shows a search the new editor lacks.
const editorKey = benchLines ? `bench-${benchLines}` : file?.id;
const text = useMemo(
() => (benchLines ? generateJavaScript(benchLines) : (file?.load() ?? '')),
[file, benchLines],
Expand All @@ -41,15 +52,37 @@ export function EditorApp() {
set(value);
};

// The demo re-sends a fresh array four times a second, as a debounced checker would, tagged with its revision.
useEffect(() => {
if (!decorate) {
setDecorations(NO_DECORATIONS);
return;
}
const scheme = theme ? schemeFor(theme) : 'light';
const send = () => {
const ed = editor.current;
if (ed)
setDecorations({
items: buildDemoDecorations(ed.getText(), scheme),
revision: ed.getRevision(),
});
};
send();
const timer = setInterval(send, 250);
return () => clearInterval(timer);
}, [decorate, theme]);

// scripts/bench-web.mjs opens its file through this hook.
useEffect(() => {
if (!__DEV__) return;
(globalThis as { __codepadBench?: { open(lines: number): void } }).__codepadBench = {
open: (lines) => {
(globalThis as { __codepadBench?: object }).__codepadBench = {
open: (lines: number) => {
started.current = performance.now();
setDemo('editor');
setBenchLines(lines);
},
search: (text: string) => editor.current?.setSearch({ text }),
decorate: () => setDecorate(true),
};
}, []);
const ready = (label: string) => () =>
Expand Down Expand Up @@ -79,6 +112,22 @@ export function EditorApp() {
on={suggestions === 'on'}
onPress={() => setSuggestions((s) => (s === 'on' ? 'off' : 'on'))}
/>
<Chip label="decorations" on={decorate} onPress={() => setDecorate((d) => !d)} />
<Chip label="find" on={finding} onPress={() => setFinding((f) => !f)} />
{(['cut', 'copy', 'paste'] as const).map((action) => (
<Chip
key={action}
label={action}
on={false}
onPress={() =>
editor.current?.[action]().then(
() => setStatus(` done`),
(e: Error) => setStatus(e.message),
)
}
/>
))}
{status ? <Text style={styles.chipText}>{status}</Text> : null}
</View>
<ScrollView horizontal style={styles.files} contentContainerStyle={styles.bar}>
{FILES.map((f) => (
Expand All @@ -94,9 +143,21 @@ export function EditorApp() {
/>
))}
</ScrollView>
{finding && demo === 'editor' ? (
Comment thread
SectionTN marked this conversation as resolved.
Resolved
<FindBar
key={editorKey}
scheme={theme ? schemeFor(theme) : 'light'}
editor={editor}
onStatus={setStatus}
onClose={() => setFinding(false)}
/>
) : null}
{demo === 'editor' ? (
<CodeEditor
key={benchLines ? `bench-${benchLines}` : file?.id}
key={editorKey}
ref={editor}
decorations={decorations.items}
decorationsRevision={decorations.revision}
style={styles.editor}
initialValue={text}
language={benchLines ? 'javascript' : file?.language}
Expand Down
55 changes: 55 additions & 0 deletions example/src/chrome/FindBar.web.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { Pressable, StyleSheet, Text, TextInput, View } from 'react-native';
import type { FindBarProps } from './types';
import { useFind } from './useFind';

// The find bar on the web: query, the three options, previous and next, replacement, replace and replace all.
export function FindBar({ scheme, editor, onStatus, onClose }: FindBarProps) {
const find = useFind(editor, onStatus);
const color = scheme === 'dark' ? '#e6edf3' : '#1f2328';
const field = [styles.field, { color }];
// An option passes its state as aria-pressed, which react-native-web forwards but React Native's types lack.
const button = (label: string, name: string, onPress: () => void, on?: boolean) => (
<Pressable
onPress={onPress}
role="button"
aria-label={name}
{...((on === undefined ? {} : { 'aria-pressed': on }) as object)}
style={[styles.button, on && styles.on]}
>
<Text style={[styles.label, { color: on ? '#fff' : color }]}>{label}</Text>
</Pressable>
);
const { index, count } = find.match;
return (
<View style={styles.bar}>
<TextInput placeholder="Find" style={field} onChangeText={find.setQuery} autoFocus />
<Text style={[styles.label, { color }]}>
{count ? `${index || '-'} of ${count}` : 'no results'}
</Text>
{button('.*', 'Regular expression', () => find.toggle('regex'), find.options.regex)}
{button('Aa', 'Match case', () => find.toggle('caseSensitive'), find.options.caseSensitive)}
{button('W', 'Whole word', () => find.toggle('wholeWord'), find.options.wholeWord)}
{button('prev', 'Previous match', find.previous)}
{button('next', 'Next match', find.next)}
<TextInput placeholder="Replace" style={field} onChangeText={find.setReplacement} />
{button('replace', 'Replace', find.replaceOne)}
{button('all', 'Replace all', find.replaceAll)}
{button('close', 'Close find', onClose)}
</View>
);
}

const styles = StyleSheet.create({
bar: { flexDirection: 'row', flexWrap: 'wrap', gap: 6, padding: 8, alignItems: 'center' },
field: {
minWidth: 120,
paddingHorizontal: 8,
paddingVertical: 4,
borderWidth: 1,
borderColor: '#8886',
borderRadius: 6,
},
button: { paddingHorizontal: 8, paddingVertical: 4, borderRadius: 6, backgroundColor: '#8883' },
on: { backgroundColor: '#0969da' },
label: { fontSize: 13 },
});
35 changes: 29 additions & 6 deletions scripts/bench-web.mjs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Typing bench in Chrome: yarn bench:web [lines] [port] [--desktop [rate]] [--profile]
// Typing bench in Chrome: yarn bench:web [lines] [port] [--desktop [rate]] [--profile] [--keys n] [--search text] [--decorate]
// Without --desktop it drives Chrome on an Android device through adb, the example served on that port with adb reverse.
// --desktop opens the example in a local Chromium at phone size with the CPU slowed by rate. --profile adds a CPU profile.
import { execFileSync } from 'node:child_process';
Expand All @@ -14,17 +14,36 @@ const args = process.argv.slice(2);
const positional = [];
let desktop = null;
let profile = false;
let keys = 60;
let search = '';
let decorate = false;
// A bad operand stops the bench before a browser opens.
const fail = (message) => {
console.error(`bench-web: ${message}`);
process.exit(1);
};
for (let i = 0; i < args.length; i++) {
if (args[i] === '--profile') profile = true;
else if (args[i] === '--keys') {
keys = Number(args[++i]);
if (!Number.isSafeInteger(keys) || keys < 1) fail('--keys takes a whole number, 1 or more');
} else if (args[i] === '--search') {
search = args[++i] ?? '';
if (!search) fail('--search takes the text to search for');
} else if (args[i] === '--decorate') decorate = true;
else if (args[i] === '--desktop') {
desktop = /^\d+(\.\d+)?$/.test(args[i + 1] ?? '') ? Number(args[++i]) : DEFAULT_RATE;
// The rate is optional, so the next operand is one unless it is another flag.
const next = args[i + 1];
desktop = next === undefined || next.startsWith('--') ? DEFAULT_RATE : Number(args[++i]);
if (!Number.isFinite(desktop) || desktop < 1)
fail('--desktop takes a finite CPU slowdown rate of 1 or more');
} else positional.push(args[i]);
}
const lines = Number(positional[0] ?? 300);
const WEB_PORT = positional[1] ?? '8082';
const CHARS = 60;
const CHARS = keys;
const GAP_MS = 150;
const TEXT = 'let total = value + 1; '.repeat(3).slice(0, CHARS);
const TEXT = 'let total = value + 1; '.repeat(Math.ceil(CHARS / 23)).slice(0, CHARS);
const PORT = 9222;
const ROOTS = { drawKeyed: 'key draw', runEngine: 'engine', applyInput: 'handler' };

Expand Down Expand Up @@ -70,6 +89,9 @@ try {
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');
// A search and the demo decorations add draw work to every key.
if (search) await page.evaluate((t) => globalThis.__codepadBench.search(t), search);
if (decorate) await page.evaluate(() => globalThis.__codepadBench.decorate());
await page.mouse.click(box.x + 4, box.y + box.height / 2);
await sleep(1000);
const cdp = await page.context().newCDPSession(page);
Expand All @@ -92,7 +114,8 @@ try {
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)}`;
const mean = list.reduce((a, b) => a + b, 0) / Math.max(1, list.length);
return `mean ${ms(mean)}, p50 ${ms(pct(sorted, 0.5))}, p95 ${ms(pct(sorted, 0.95))}, max ${ms(sorted.at(-1) ?? 0)}`;
};
const where = desktop !== null ? `desktop at ${desktop}x` : 'device';
console.log(`${lines} lines, ${where}, ${probe.work.length} of ${CHARS} keys`);
Expand All @@ -110,7 +133,7 @@ try {
const top = summarize(taken, ROOTS, 12);
for (const group of ['key draw', 'handler', 'engine', 'other']) {
const total = (all[group] ?? []).reduce((sum, f) => sum + f.selfMs, 0);
console.log(` profile ${group}: ${ms(total)} over the 60 keys`);
console.log(` profile ${group}: ${ms(total)} over the ${CHARS} keys`);
for (const f of top[group] ?? []) console.log(` ${ms(f.selfMs).padStart(9)} ${f.fn}`);
}
console.log(` profile saved to ${file}`);
Expand Down
Loading
Loading