Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 }]}>
{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
67 changes: 49 additions & 18 deletions src/web/CodeEditor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import {
type ComponentRef,
forwardRef,
useCallback,
useEffect,
useImperativeHandle,
useMemo,
Expand Down Expand Up @@ -63,7 +64,7 @@ export const CodeEditor = forwardRef<CodeEditorRef, CodeEditorProps>(function Co
onBlur,
onContentSizeChange,
decorations,
decorationsRevision: _decorationsRevision,
decorationsRevision,
onGapLayout,
...viewProps
},
Expand All @@ -84,6 +85,7 @@ export const CodeEditor = forwardRef<CodeEditorRef, CodeEditorProps>(function Co
onContentSizeChange,
onFocus,
onBlur,
onGapLayout,
});
handlers.current = {
onReady,
Expand All @@ -94,6 +96,7 @@ export const CodeEditor = forwardRef<CodeEditorRef, CodeEditorProps>(function Co
onContentSizeChange,
onFocus,
onBlur,
onGapLayout,
};
const initial = useRef(initialValue);

Expand Down Expand Up @@ -126,6 +129,7 @@ export const CodeEditor = forwardRef<CodeEditorRef, CodeEditorProps>(function Co
onScroll: (x, y, contentWidth, contentHeight) =>
handlers.current.onScroll?.({ x, y, contentWidth, contentHeight }),
onFirstDraw: () => handlers.current.onReady?.(),
onGapLayout: (gaps) => handlers.current.onGapLayout?.({ gaps }),
onChange: (c) => {
const h = handlers.current;
h.onChange?.({
Expand Down Expand Up @@ -163,10 +167,20 @@ export const CodeEditor = forwardRef<CodeEditorRef, CodeEditorProps>(function Co
avoidKeyboard,
],
);
const latest = useRef({ options, language });
latest.current = { options, language };
const latest = useRef({ options, language, decorations, decorationsRevision });
latest.current = { options, language, decorations, decorationsRevision };
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
// The decorations last sent, so the view gets them before its first draw and a repeat is not mapped twice.
const sent = useRef<{ items?: typeof decorations; revision?: number }>({});
const sendDecorations = useCallback((v: EditorView) => {
const { decorations: items, decorationsRevision: revision } = latest.current;
const last = sent.current;
if (items === last.items && revision === last.revision) return;
sent.current = { items, revision };
// A prop that goes away clears for the current text, and one that never came sends nothing.
if (items || last.items) v.setDecorations(items ?? [], items ? (revision ?? -1) : -1);
}, []);

// Options and language reach the view before its first draw, which the pump runs before React commits.
// Options, language and decorations reach the view before its first draw, which the pump runs before React commits.
useEffect(() => {
let alive = true;
let created: EditorView | null = null;
Expand All @@ -182,6 +196,8 @@ export const CodeEditor = forwardRef<CodeEditorRef, CodeEditorProps>(function Co
created = v;
v.setOptions(latest.current.options);
v.setLanguage(latest.current.language);
sent.current = {};
sendDecorations(v);
viewRef.current = v;
for (const write of queued.current.splice(0)) {
write.edit(v);
Expand All @@ -204,12 +220,12 @@ export const CodeEditor = forwardRef<CodeEditorRef, CodeEditorProps>(function Co
// A StrictMode remount runs the effect again before this fires and keeps the waiting writes.
setTimeout(() => gone.current && drop(), 0);
};
}, []);
}, [sendDecorations]);

// biome-ignore lint/correctness/useExhaustiveDependencies: sendDecorations reads the props through latest.
useEffect(() => {
if (decorations) notYet('decorations');
if (onGapLayout) notYet('onGapLayout');
}, [decorations, onGapLayout]);
if (view) sendDecorations(view);
}, [view, decorations, decorationsRevision]);

useEffect(() => {
view?.setOptions(options);
Expand All @@ -231,6 +247,24 @@ export const CodeEditor = forwardRef<CodeEditorRef, CodeEditorProps>(function Co
return Promise.resolve();
};
const write = (edit: (v: EditorView) => void) => run((v) => v.apply(() => edit(v)));
// A call with a result: on the view now, once it loads, or the fallback when no view comes.
const ask = <T,>(call: (v: EditorView) => Promise<T>, fallback: T): Promise<T> => {
const v = viewRef.current;
if (v) return call(v);
if (gone.current) return Promise.resolve(fallback);
return new Promise<T>((resolve, reject) => {
let started = false;
queued.current.push({
edit: (view) => {
started = true;
call(view).then(resolve, reject);
},
done: () => {
if (!started) resolve(fallback);
},
});
});
};
return {
getText: () => core()?.text() ?? '',
getTextInRange: (range) => core()?.text(range.start, range.end) ?? '',
Expand All @@ -245,10 +279,7 @@ export const CodeEditor = forwardRef<CodeEditorRef, CodeEditorProps>(function Co
const v = viewRef.current;
return v ? v.caretRect(v.core.selection.head) : null;
},
getGapRect: () => {
notYet('getGapRect');
return null;
},
getGapRect: (line) => viewRef.current?.gapRect(line) ?? null,
getVisibleLines: () => viewRef.current?.visibleLines() ?? { first: 0, last: 0 },
canUndo: () => core()?.canUndo ?? false,
canRedo: () => core()?.canRedo ?? false,
Expand All @@ -275,12 +306,12 @@ export const CodeEditor = forwardRef<CodeEditorRef, CodeEditorProps>(function Co
paste: () => later('paste', 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),
setSearch: (query) => ask((v) => v.setSearch(query), { count: 0, limited: false }),
findNext: () => ask((v) => v.findNext(), null),
findPrevious: () => ask((v) => v.findPrevious(), null),
replaceCurrent: (text) => ask((v) => v.replaceCurrent(text), false),
replaceAll: (text) => ask((v) => v.replaceAll(text), 0),
clearSearch: () => ask((v) => v.clearSearch(), undefined),
moveCaret: (direction, opts) => run((v) => v.moveCaret(direction, opts?.select ?? false)),
typeText: (text) => run((v) => v.typeText(text)),
deleteBackward: () => run((v) => v.deleteBackward()),
Expand Down
Loading
Loading