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
32 changes: 31 additions & 1 deletion example/src/EditorApp.web.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
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 { 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,6 +27,9 @@ 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 [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.
Expand All @@ -41,6 +47,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 +105,7 @@ export function EditorApp() {
on={suggestions === 'on'}
onPress={() => setSuggestions((s) => (s === 'on' ? 'off' : 'on'))}
/>
<Chip label="decorations" on={decorate} onPress={() => setDecorate((d) => !d)} />
</View>
<ScrollView horizontal style={styles.files} contentContainerStyle={styles.bar}>
{FILES.map((f) => (
Expand All @@ -97,6 +124,9 @@ export function EditorApp() {
{demo === 'editor' ? (
<CodeEditor
key={benchLines ? `bench-${benchLines}` : file?.id}
ref={editor}
decorations={decorations.items}
decorationsRevision={decorations.revision}
style={styles.editor}
initialValue={text}
language={benchLines ? 'javascript' : file?.language}
Expand Down
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]);
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
37 changes: 25 additions & 12 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 Down Expand Up @@ -245,10 +261,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 Down
Loading
Loading