Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 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
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
50 changes: 48 additions & 2 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,6 +52,26 @@ 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;
Expand Down Expand Up @@ -79,6 +110,9 @@ 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)} />
{status ? <Text style={styles.chipText}>{status}</Text> : null}
</View>
<ScrollView horizontal style={styles.files} contentContainerStyle={styles.bar}>
{FILES.map((f) => (
Expand All @@ -94,9 +128,21 @@ export function EditorApp() {
/>
))}
</ScrollView>
{finding && demo === 'editor' ? (
<FindBar
Comment thread
SectionTN marked this conversation as resolved.
Resolved
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 }]}>
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
{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 },
});
13 changes: 8 additions & 5 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]
// 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,19 @@ const args = process.argv.slice(2);
const positional = [];
let desktop = null;
let profile = false;
let keys = 60;
for (let i = 0; i < args.length; i++) {
if (args[i] === '--profile') profile = true;
else if (args[i] === '--keys') keys = Number(args[++i]);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
else if (args[i] === '--desktop') {
desktop = /^\d+(\.\d+)?$/.test(args[i + 1] ?? '') ? Number(args[++i]) : DEFAULT_RATE;
} 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 @@ -92,7 +94,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 +113,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