diff --git a/cpp/web/host.cpp b/cpp/web/host.cpp index 164a7fa..e31c383 100644 --- a/cpp/web/host.cpp +++ b/cpp/web/host.cpp @@ -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 &q = !worker_q.empty() ? worker_q : main_q; Work w = q.front(); q.pop_front(); diff --git a/example/src/EditorApp.web.tsx b/example/src/EditorApp.web.tsx index 6f4f2de..3b09960 100644 --- a/example/src/EditorApp.web.tsx +++ b/example/src/EditorApp.web.tsx @@ -1,7 +1,9 @@ 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'; @@ -9,6 +11,7 @@ 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 ( @@ -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(null); const [demo, setDemo] = useState('editor'); const theme = THEMES[themeIndex % THEMES.length]?.theme; // Lines of the generated JavaScript file the typing bench opened, 0 for a picked file. @@ -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; @@ -79,6 +105,7 @@ export function EditorApp() { on={suggestions === 'on'} onPress={() => setSuggestions((s) => (s === 'on' ? 'off' : 'on'))} /> + setDecorate((d) => !d)} /> {FILES.map((f) => ( @@ -97,6 +124,9 @@ export function EditorApp() { {demo === 'editor' ? ( 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`); @@ -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}`); diff --git a/src/web/CodeEditor.tsx b/src/web/CodeEditor.tsx index 77f53b5..ac90520 100644 --- a/src/web/CodeEditor.tsx +++ b/src/web/CodeEditor.tsx @@ -2,6 +2,7 @@ import { type ComponentRef, forwardRef, + useCallback, useEffect, useImperativeHandle, useMemo, @@ -63,7 +64,7 @@ export const CodeEditor = forwardRef(function Co onBlur, onContentSizeChange, decorations, - decorationsRevision: _decorationsRevision, + decorationsRevision, onGapLayout, ...viewProps }, @@ -84,6 +85,7 @@ export const CodeEditor = forwardRef(function Co onContentSizeChange, onFocus, onBlur, + onGapLayout, }); handlers.current = { onReady, @@ -94,6 +96,7 @@ export const CodeEditor = forwardRef(function Co onContentSizeChange, onFocus, onBlur, + onGapLayout, }; const initial = useRef(initialValue); @@ -126,6 +129,7 @@ export const CodeEditor = forwardRef(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?.({ @@ -163,10 +167,20 @@ export const CodeEditor = forwardRef(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 }; + // 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; @@ -182,6 +196,8 @@ export const CodeEditor = forwardRef(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); @@ -204,12 +220,12 @@ export const CodeEditor = forwardRef(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); @@ -245,10 +261,7 @@ export const CodeEditor = forwardRef(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, diff --git a/src/web/EditorView.ts b/src/web/EditorView.ts index c899553..a00dacc 100644 --- a/src/web/EditorView.ts +++ b/src/web/EditorView.ts @@ -1,9 +1,10 @@ /// import { githubLight } from '../themes/githubLight'; -import type { CaretDirection, ContentInsets, Rect, Suggestions, Theme } from '../types'; +import type { CaretDirection, ContentInsets, Decoration, Rect, Suggestions, Theme } from '../types'; import { EditorCore, type MoveUnit, type WebChange } from './core/EditorCore'; import { Layout } from './core/Layout'; import type { CoreModule } from './core/module'; +import { measureBaseline, solidTop, waveAmplitude, wavePath } from './decorations'; import { type DecodedFrame, decodeFrame } from './frame'; import { CaretMover, type LineGeometry } from './input/CaretMover'; import { InputHost } from './input/InputHost'; @@ -42,8 +43,11 @@ export type ViewOptions = { avoidKeyboard: boolean; onFocus?: () => void; onBlur?: () => void; + onGapLayout?: (gaps: GapRect[]) => void; }; +export type GapRect = { line: number; rect: Rect }; + // The defaults of website/docs/reference/props.md. export const DEFAULT_OPTIONS: ViewOptions = { theme: githubLight, @@ -70,6 +74,7 @@ export const DEFAULT_OPTIONS: ViewOptions = { const MONOSPACE = 'ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace'; const SNAPSHOT_INFO_INTS = 7; +const SVG = 'http://www.w3.org/2000/svg'; const MAC = typeof navigator !== 'undefined' && /Mac|iPhone|iPad|iPod/.test(navigator.platform); // A run of Hebrew or Arabic script anywhere in a row. const RTL_TEXT = /[\u0590-\u08FF\uFB1D-\uFDFF\uFE70-\uFEFF]/; @@ -89,6 +94,8 @@ type Entry = { revision: number; spans: Int32Array | null; text: string; + // Edited since its last draw: the element is reused, but the frame reads the line again. + stale?: boolean; }; // The edited line's previous spans moved along an edit that stayed inside it, kept until a parse lands. @@ -145,6 +152,14 @@ export class EditorView { }); readonly session: WebInputSession; private readonly input: InputHost; + // The app's line backgrounds over the active line, and its underlines under the text. + private readonly lineBackgroundLayer = div('position:absolute;left:0;top:0;pointer-events:none;'); + private readonly underlineLayer = div('position:absolute;left:0;top:0;pointer-events:none;'); + private decorationsKey = ''; + private baseline = 0; + private drawnWindow = { first: 0, last: -1 }; + private drawnGaps: GapRect[] = []; + private reportedGaps = '[]'; private readonly selectionLayer = div('position:absolute;left:0;top:0;pointer-events:none;'); private readonly composingLayer = div( 'position:absolute;left:0;top:0;z-index:1;pointer-events:none;', @@ -192,7 +207,9 @@ export class EditorView { this.placeholderEl = div('position:absolute;white-space:pre;display:none;pointer-events:none;'); this.textLayer.append( this.activeLine, + this.lineBackgroundLayer, this.selectionLayer, + this.underlineLayer, this.placeholderEl, this.composingLayer, this.caretEl, @@ -201,6 +218,7 @@ export class EditorView { this.textLayer.style.webkitUserSelect = 'none'; this.caretEl.dataset.caret = ''; this.selectionLayer.dataset.selection = ''; + this.activeLine.dataset.activeLine = ''; this.session = new WebInputSession(this.core, (edit) => this.applyInput(edit)); this.input = new InputHost(this.root, this.session, { keyDown: (e) => this.keyDown(e), @@ -552,6 +570,7 @@ export class EditorView { // A click places the caret and focuses the textarea inside the event, which iOS needs to show its keyboard. private click(e: MouseEvent): void { + if (this.inGap(e.clientY)) return; const offset = this.offsetAt(e.clientX, e.clientY); if (offset !== null) this.apply(() => this.core.setSelection(offset, offset)); this.focus(); @@ -561,12 +580,13 @@ export class EditorView { private drawInput(): void { const box = this.textLayer.getBoundingClientRect(); const { anchor, head } = this.core.selection; - const caret = this.caretRect(head); - this.drawnCaret = caret; const rootBox = this.root.getBoundingClientRect(); + const caret = this.caretRect(head, rootBox); + this.drawnCaret = caret; const caretLine = this.cache.get(this.core.lineAt(head))?.el; + // Without soft wrap every line is one row. this.drawnCaretRow = - caret && caretLine + this.o.softWrap && caret && caretLine ? Math.max( 0, Math.round( @@ -579,6 +599,7 @@ export class EditorView { const from = Math.min(anchor, head); const to = Math.max(anchor, head); const selected = from < to ? this.rangeRects(from, to) : []; + const writeDecorations = this.planDecorations(box); if (caret && this.input.focused) { put(this.caretEl, 'display', 'block'); put(this.caretEl, 'left', `${caret.x + rootBox.left - box.left}px`); @@ -609,6 +630,7 @@ export class EditorView { ), ); } + writeDecorations(); } // The page boxes of the document range on the lines that are drawn. @@ -654,6 +676,147 @@ export class EditorView { this.invalidate(); } + // Decorations for the text at revision, below zero for the current text. An unknown revision keeps the set. + setDecorations(items: Decoration[], revision: number): void { + if (this.destroyed) return; + this.core.setDecorations(items, revision); + this.invalidate(); + } + + // The gap under line from the last draw, in the coordinates of caretRect, or null. + gapRect(line: number): Rect | null { + return this.drawnGaps.find((g) => g.line === line)?.rect ?? null; + } + + // Every gap as the full width rows under its line, in the coordinates of caretRect. + private gapRects(): GapRect[] { + const layout = this.layout; + const shift = this.o.scrollEnabled ? 0 : layout.scrollY; + return layout.gaps().map((g) => ({ + line: g.line, + rect: { x: 0, y: g.top + shift, width: layout.width, height: g.rows * this.rowHeight }, + })); + } + + // True when a page y falls in a gap, which belongs to the app's view there. + private inGap(clientY: number): boolean { + if (this.drawnGaps.length === 0) return false; + const y = clientY - this.root.getBoundingClientRect().top; + return this.drawnGaps.some((g) => y >= g.rect.y && y < g.rect.y + g.rect.height); + } + + // Reads the decorations' geometry now and returns their writes, so the draw keeps one read phase. + private planDecorations(box: DOMRect): () => void { + const items = this.core.decorations(); + const { first, last } = this.drawnWindow; + const key = + items.length === 0 + ? '' + : [ + this.core.decorationsVersion, + this.core.revision, + this.appliedRevision, + first, + last, + this.layout.wrapWidth, + this.rowHeight, + this.baseline, + ].join(':'); + if (key === this.decorationsKey) return () => {}; + this.decorationsKey = key; + const layout = this.layout; + const backgrounds: Element[] = []; + const underlines: Element[] = []; + const windowStart = this.core.lineStart(first); + const windowEnd = this.core.lineEnd(last); + for (const d of items) { + if (d.kind === 'lineBackground') { + if (d.line < first || d.line > last) continue; + const el = div( + `position:absolute;left:${layout.textAreaLeft}px;top:${layout.lineTop(d.line) + layout.scrollY}px;width:${layout.contentWidth + layout.insetRight}px;height:${layout.rows(d.line) * this.rowHeight}px;background:${d.color};`, + ); + el.dataset.lineBackground = ''; + backgrounds.push(el); + } else if (d.kind === 'underline') { + if (d.range.end < windowStart || d.range.start > windowEnd) continue; + for (const r of this.rowRects(d.range.start, d.range.end)) { + underlines.push( + this.underline(d, r.left - box.left, r.right - box.left, r.top - box.top), + ); + } + } + } + return () => { + this.lineBackgroundLayer.replaceChildren(...backgrounds); + this.underlineLayer.replaceChildren(...underlines); + }; + } + + // The range's page boxes on drawn lines, merged to one per row, with the top of that row. + private rowRects(start: number, end: number): { left: number; right: number; top: number }[] { + const out: { left: number; right: number; top: number }[] = []; + const last = this.core.lineAt(end); + for (let line = this.core.lineAt(start); line <= last; line++) { + const entry = this.cache.get(line); + if (!entry || entry.stale || !this.attached.has(line)) continue; + const lineStart = this.core.lineStart(line); + const a = Math.max(start, lineStart) - lineStart; + const b = Math.min(end, lineStart + entry.text.length) - lineStart; + if (b <= a) continue; + const range = document.createRange(); + const [sn, so] = textPoint(entry.el, a); + const [en, eo] = textPoint(entry.el, b); + range.setStart(sn, so); + range.setEnd(en, eo); + const lineTop = entry.el.getBoundingClientRect().top; + const rows = new Map(); + for (const r of range.getClientRects()) { + if (r.width <= 0) continue; + const row = Math.floor((r.top + r.height / 2 - lineTop) / this.rowHeight); + const seen = rows.get(row); + if (seen) { + seen.left = Math.min(seen.left, r.left); + seen.right = Math.max(seen.right, r.right); + } else rows.set(row, { left: r.left, right: r.right, top: lineTop + row * this.rowHeight }); + } + out.push(...rows.values()); + } + return out; + } + + // One underline piece on a row, solid as a bar or wavy as a clipped path, as DecorationPainter.kt draws them. + private underline( + d: Extract, + left: number, + right: number, + rowTop: number, + ): Element { + const thickness = d.thickness ?? 1; + const offset = d.offset ?? 2; + if (d.style !== 'wavy') { + const bar = div( + `position:absolute;left:${left}px;top:${solidTop(rowTop, this.baseline, offset)}px;width:${right - left}px;height:${Math.max(1, Math.round(thickness))}px;background:${d.color};`, + ); + bar.dataset.underline = ''; + return bar; + } + // The wave's centre sits a thickness below a solid line's top, and the box clips it like native. + const pad = waveAmplitude(thickness) + thickness; + const centre = rowTop + this.baseline + offset + thickness; + const svg = document.createElementNS(SVG, 'svg'); + svg.setAttribute('width', String(right - left)); + svg.setAttribute('height', String(2 * pad)); + svg.style.cssText = `position:absolute;left:${left}px;top:${centre - pad}px;overflow:hidden;`; + const path = document.createElementNS(SVG, 'path'); + path.setAttribute('d', wavePath(0, right - left, pad, thickness)); + path.setAttribute('fill', 'none'); + path.setAttribute('stroke', d.color); + path.setAttribute('stroke-width', String(thickness)); + svg.append(path); + svg.dataset.underline = ''; + return svg; + } + // Scrolls the least that shows the caret, by its line's row while the line is not drawn. True when it scrolled. private revealCaret(): boolean { const caret = this.drawnCaret; @@ -669,12 +832,12 @@ export class EditorView { } // The caret at offset in view coordinates, or null when its line is not drawn. - caretRect(offset: number): Rect | null { + caretRect(offset: number, rootBox?: DOMRect): Rect | null { if (this.destroyed) return null; const line = this.core.lineAt(offset); const entry = this.cache.get(line); - if (!entry || !this.attached.has(line)) return null; - const box = this.root.getBoundingClientRect(); + if (!entry || entry.stale || !this.attached.has(line)) return null; + const box = rootBox ?? this.root.getBoundingClientRect(); const edge = caretEdge(entry.el, offset - this.core.lineStart(line)); return { x: edge.x - box.left, y: edge.top - box.top, width: 1, height: this.rowHeight }; } @@ -702,8 +865,17 @@ export class EditorView { // A caret moved off screen scrolls into view before the paint: by row while its line is not drawn, then by x. for (let pass = 0; this.revealing && pass < 2; pass++) { if (this.drawnCaret) this.revealing = false; + const [beforeX, beforeY] = [this.layout.scrollX, this.layout.scrollY]; if (!this.revealCaret()) break; this.syncScroll(); + const caret = this.drawnCaret; + if (caret && this.layout.scrollY === beforeY) { + // Lines and the caret scroll with the content: only the textarea, placed in view coordinates, follows. + const x = caret.x - (this.layout.scrollX - beforeX); + this.drawnCaret = { ...caret, x }; + if (this.input.focused) this.input.place(x, caret.y); + break; + } moved = this.frame(); } this.revealing = false; @@ -723,6 +895,7 @@ export class EditorView { const frame = this.readFrame(); const moved = this.prepare(frame); this.place(frame); + this.drawnGaps = this.gapRects(); this.drawInput(); return moved; } finally { @@ -834,6 +1007,7 @@ export class EditorView { this.placeholderEl.style.color = this.css.gutterForeground; if (metrics) { this.charWidth = measureChar(this.root); + this.baseline = measureBaseline(this.root); this.layout.rowHeight = this.rowHeight; this.layout.wrap = o.softWrap; this.relayout(); @@ -896,7 +1070,7 @@ export class EditorView { const info = snapshot ? this.snapshotInfo(snapshot) : null; const incremental = info !== null && info.basedOn >= 0 && info.basedOn === this.appliedRevision; const pairs: number[] = []; - for (const [line, entry] of this.cache) pairs.push(line, entry.revision); + for (const [line, entry] of this.cache) if (!entry.stale) pairs.push(line, entry.revision); const entries = m._malloc(Math.max(1, pairs.length) * 4); m.HEAP32.set(pairs, entries >> 2); const lenPtr = m._malloc(4); @@ -1007,6 +1181,7 @@ export class EditorView { // Places the window's lines, numbers and active line, and takes every other line out of the page. private place(frame: DecodedFrame): void { const layout = this.layout; + this.drawnWindow = { first: frame.first, last: frame.last }; const scrollY = layout.scrollY; const left = layout.textAreaLeft + layout.textPadding; const width = layout.textAreaLeft + layout.contentWidth + layout.insetRight; @@ -1090,6 +1265,11 @@ export class EditorView { this.lastContent = { width, height }; this.o.onContentSize?.(width, height); } + const gaps = JSON.stringify(this.drawnGaps); + if (gaps !== this.reportedGaps) { + this.reportedGaps = gaps; + this.o.onGapLayout?.(this.drawnGaps); + } if (!this.drawn) { this.drawn = true; this.o.onFirstDraw?.(); @@ -1158,11 +1338,20 @@ export class EditorView { this.keepSpans(first, oldCount, newCount, change); if (colored && this.kept === null) this.urgent = true; const delta = newCount - oldCount; + // An edit inside one line moves no other line. + if (oldCount === 1 && newCount === 1) { + const entry = this.cache.get(first); + if (entry) entry.stale = true; + return; + } const moved: [number, Entry][] = []; for (const [line, entry] of this.cache) { if (line < first) moved.push([line, entry]); else if (line >= first + oldCount) moved.push([line + delta, entry]); - else entry.el.remove(); + else if (oldCount === 1 && newCount === 1) { + entry.stale = true; + moved.push([line, entry]); + } else entry.el.remove(); } this.cache.clear(); this.attached.clear(); @@ -1176,7 +1365,7 @@ export class EditorView { // The spans a line shows now: its cache entry, else what an edit since the last frame kept for it. private shownSpans(line: number): Int32Array | null { const entry = this.cache.get(line); - if (entry) return entry.spans; + if (entry && !entry.stale) return entry.spans; const kept = this.kept; if (!kept) return null; if (line === kept.line) return kept.spans; diff --git a/src/web/__tests__/CodeEditor.test.tsx b/src/web/__tests__/CodeEditor.test.tsx index bf3d34f..2dbd0f1 100644 --- a/src/web/__tests__/CodeEditor.test.tsx +++ b/src/web/__tests__/CodeEditor.test.tsx @@ -41,6 +41,8 @@ class MockView { deleteBackward = jest.fn(); deleteForward = jest.fn(); moveCaret = jest.fn(); + setDecorations = jest.fn(); + gapRect = jest.fn(() => null); destroy() {} } @@ -189,3 +191,49 @@ test('focus called before the core loads focuses the editor once it does', async await expect(settled(focused as Promise)).resolves.toBeUndefined(); expect(mockViews[0]?.focus).toHaveBeenCalledTimes(1); }); + +test('decorations passed before the core loads apply once it does', async () => { + const items = [{ kind: 'gap' as const, line: 0, rows: 2 }]; + await render(); + await act(async () => { + mockCore.resolve({}); + await tick(); + }); + expect(mockViews[0]?.setDecorations).toHaveBeenCalledWith(items, 3); +}); + +test('decorations passed at mount are on the view when it first draws, and sent once', async () => { + const items = [{ kind: 'gap' as const, line: 0, rows: 2 }]; + let atReady: unknown[][] = []; + const onReady = () => { + atReady = [...(mockViews[0]?.setDecorations.mock.calls ?? [])]; + }; + await render(); + await act(async () => { + mockCore.resolve({}); + await tick(); + }); + expect(atReady).toEqual([[items, 3]]); + expect(mockViews[0]?.setDecorations).toHaveBeenCalledTimes(1); +}); + +test('decorations without a revision are for the current text', async () => { + const items = [{ kind: 'lineBackground' as const, line: 1, color: 'red' }]; + await render(); + await act(async () => { + mockCore.resolve({}); + await tick(); + }); + expect(mockViews[0]?.setDecorations).toHaveBeenCalledWith(items, -1); +}); + +test('removing decorations clears them for the current text, whatever decorationsRevision says', async () => { + const items = [{ kind: 'gap' as const, line: 0, rows: 2 }]; + const { rerender } = await render(); + await act(async () => { + mockCore.resolve({}); + await tick(); + }); + await rerender(); + expect(mockViews[0]?.setDecorations).toHaveBeenLastCalledWith([], -1); +}); diff --git a/src/web/__tests__/decorations.test.ts b/src/web/__tests__/decorations.test.ts new file mode 100644 index 0000000..1b31447 --- /dev/null +++ b/src/web/__tests__/decorations.test.ts @@ -0,0 +1,21 @@ +import { expect, test } from '@jest/globals'; +import { solidTop, wavePath } from '../decorations'; + +test('a wave starts on the centre line heading down, half a wavelength per curve', () => { + const d = wavePath(0, 10, 5, 1); + // Thickness 1: half wavelength (4 + 0.375) / 2, swing 0.875 drawn as a control point twice as far. + expect(d.startsWith('M0 5 Q1.09375 6.75 2.1875 5 Q3.28125 3.25 4.375 5')).toBe(true); + const ends = [...d.matchAll(/Q\S+ \S+ (\S+) /g)].map((m) => Number(m[1])); + expect(ends).toHaveLength(5); + expect(ends.at(-1)).toBeGreaterThanOrEqual(10); +}); + +test('a wave scales with the thickness', () => { + const d = wavePath(4, 6, 0, 2); + expect(d.startsWith('M4 0 Q6.09375 3.5 8.1875 0')).toBe(true); +}); + +test('a solid underline sits offset below the baseline, on a whole pixel', () => { + expect(solidTop(20, 14.6, 2)).toBe(37); + expect(solidTop(0, 14.4, 2)).toBe(16); +}); diff --git a/src/web/__tests__/pump.test.ts b/src/web/__tests__/pump.test.ts new file mode 100644 index 0000000..08b155f --- /dev/null +++ b/src/web/__tests__/pump.test.ts @@ -0,0 +1,34 @@ +import { existsSync } from 'node:fs'; +import { join } from 'node:path'; +import { expect, test } from '@jest/globals'; +import { generateJavaScript } from '../../../example/src/bench/generate'; +import { builtCore, loadCore, loadGrammar, pumpAll, ROOT } from '../../../tests/web/core'; +import { EditorCore } from '../core/EditorCore'; + +const dir = builtCore('lib/web', 'yarn build:web'); +const javascript = join(ROOT, 'languages/javascript/web/javascript.wasm'); +const ready = dir !== null && existsSync(javascript); +if (dir && !ready) console.warn('javascript grammar not built, run yarn build:web-grammars'); + +// The jest preset rounds performance.now to whole milliseconds. +const now = () => Number(process.hrtime.bigint()) / 1e6; + +(ready ? test : test.skip)('one pump starts no second parse slice', async () => { + const m = await loadCore(dir as string); + loadGrammar(m, javascript, 'javascript', join(ROOT, 'languages/javascript/queries/javascript')); + const core = new EditorCore(m, generateJavaScript(100_000), 4000); + expect(core.setLanguage('javascript')).toBe(true); + const took: number[] = []; + for (let i = 0; i < 30; i++) { + const start = now(); + const left = m._cpw_pump(6, 4); + took.push(now() - start); + if (left === 0) break; + } + expect(took.length).toBe(30); + took.sort((a, b) => a - b); + // One 4 ms slice a call; two slices take about 8. + expect(took[15]).toBeLessThan(5.5); + core.close(); + pumpAll(m); +}); diff --git a/src/web/__tests__/vectors.test.ts b/src/web/__tests__/vectors.test.ts index 1d76b71..b1b5fb4 100644 --- a/src/web/__tests__/vectors.test.ts +++ b/src/web/__tests__/vectors.test.ts @@ -424,8 +424,8 @@ if (dir && !existsSync(javascript)) pumpAll(m); expect(core.snapshot).not.toBe(0); core.setText(js10k); - m._cpw_pump(1); - expect(m._cpw_pump(0)).toBeGreaterThan(0); + m._cpw_pump(1, 0); + expect(m._cpw_pump(0, 0)).toBeGreaterThan(0); core.close(); pumpAll(m); expect(m._cpw_test_held_snapshots()).toBe(0); diff --git a/src/web/core/EditorCore.ts b/src/web/core/EditorCore.ts index 5a8c4c3..111c771 100644 --- a/src/web/core/EditorCore.ts +++ b/src/web/core/EditorCore.ts @@ -31,7 +31,7 @@ export type WebChange = { export class SearchError extends Error {} // The engine's parse budget per slice, so the page's pump stays inside a frame. -export const DEFAULT_BUDGET_MICROS = 4000; +export const DEFAULT_BUDGET_MICROS = 3000; const ORIGINS: ChangeOrigin[] = ['input', 'api', 'undo', 'redo']; const MOVES: MoveUnit[] = ['char', 'word', 'lineStart', 'lineEnd', 'docStart', 'docEnd']; diff --git a/src/web/core/module.ts b/src/web/core/module.ts index dcf93c7..e4c2afc 100644 --- a/src/web/core/module.ts +++ b/src/web/core/module.ts @@ -36,7 +36,8 @@ export interface CoreModule { _cpw_take_missed(e: number, out: Ptr, cap: number): number; _cpw_refresh(e: number): void; _cpw_set_clock(e: number, millis: number): void; - _cpw_pump(budgetMs: number): number; + // Starts another queued item only while sliceMs still fits before budgetMs runs out. + _cpw_pump(budgetMs: number, sliceMs: number): number; _cpw_take_changes( e: number, out: Ptr, diff --git a/src/web/decorations.ts b/src/web/decorations.ts new file mode 100644 index 0000000..2065e85 --- /dev/null +++ b/src/web/decorations.ts @@ -0,0 +1,43 @@ +/// +// Underline geometry, the same as DecorationPainter.kt: Chrome's wavy underline, measured at 14 px for thickness 1 to 4. + +export function waveHalf(thickness: number): number { + return (4 * thickness + 0.375) / 2; +} + +// How far the centre line swings to either side. +export function waveAmplitude(thickness: number): number { + return 0.875 * thickness; +} + +// SVG path data, one quadratic per half wave, leaving the left edge on the centre line heading down. +export function wavePath(left: number, right: number, centre: number, thickness: number): string { + const half = waveHalf(thickness); + const swing = 2 * waveAmplitude(thickness); + let d = `M${left} ${centre}`; + let down = true; + for (let x = left; x < right; x += half) { + d += ` Q${x + half / 2} ${centre + (down ? swing : -swing)} ${x + half} ${centre}`; + down = !down; + } + return d; +} + +// The top of a solid underline: offset below the baseline, on a whole pixel like a browser draws it. +export function solidTop(rowTop: number, baseline: number, offset: number): number { + return Math.round(rowTop + baseline + offset); +} + +// From a row's top to its text baseline, in the root's font and line height. +export function measureBaseline(root: HTMLElement): number { + const line = document.createElement('div'); + line.style.cssText = 'position:absolute;visibility:hidden;white-space:pre;'; + line.textContent = '0'; + const mark = document.createElement('span'); + mark.style.cssText = 'display:inline-block;width:0;height:0;vertical-align:baseline;'; + line.append(mark); + root.append(line); + const baseline = mark.getBoundingClientRect().top - line.getBoundingClientRect().top; + line.remove(); + return baseline; +} diff --git a/src/web/pump.ts b/src/web/pump.ts index d99296c..82bfd4f 100644 --- a/src/web/pump.ts +++ b/src/web/pump.ts @@ -1,7 +1,10 @@ +import { DEFAULT_BUDGET_MICROS } from './core/EditorCore'; import type { CoreModule } from './core/module'; // The engine's share of a task, so a key still draws soon after it. export const PUMP_BUDGET_MS = 6; +// An engine step can run one parse slice, so the pump starts one only while a slice still fits. +const PARSE_SLICE_MS = DEFAULT_BUDGET_MICROS / 1000; // urgent: the view's next frame waits for the parse. pending: it has something to draw. type View = { draw(): void; readonly urgent: boolean; pending(): boolean }; @@ -68,7 +71,7 @@ function frame(): void { scheduled = false; const start = probe ? performance.now() : 0; const urgent = [...views].some((v) => v.urgent); - const left = core && urgent ? core._cpw_pump(PUMP_BUDGET_MS) : 0; + const left = core && urgent ? core._cpw_pump(PUMP_BUDGET_MS, PARSE_SLICE_MS) : 0; const pumped = probe ? performance.now() - start : 0; for (const view of [...views]) { if (probe && view === keyView) drawKeyed(probe, view, pumped); @@ -111,7 +114,7 @@ function runEngine(): void { engineQueued = false; if (!core) return; const start = probe ? performance.now() : 0; - const left = core._cpw_pump(PUMP_BUDGET_MS); + const left = core._cpw_pump(PUMP_BUDGET_MS, PARSE_SLICE_MS); if (probe) probe.tasks.push(performance.now() - start); if ([...views].some((v) => v.pending())) requestPump(); if (left > 0) postEngine(); diff --git a/tests/web/core.ts b/tests/web/core.ts index 57c6952..5486057 100644 --- a/tests/web/core.ts +++ b/tests/web/core.ts @@ -125,5 +125,5 @@ export function highlight( } export function pumpAll(m: RawCore, budgetMs = 8): void { - for (let i = 0; i < 100000 && m._cpw_pump(budgetMs) > 0; i++); + for (let i = 0; i < 100000 && m._cpw_pump(budgetMs, 0) > 0; i++); } diff --git a/tests/web/render.e2e.mjs b/tests/web/render.e2e.mjs index 795fe4f..10cd096 100644 --- a/tests/web/render.e2e.mjs +++ b/tests/web/render.e2e.mjs @@ -430,6 +430,268 @@ for (const engine of [chromium, webkit]) { await page.close(); }); + test("a typed letter keeps its line's element", async () => { + const { page } = await open(); + await page.evaluate(() => window.codepad.ensureLanguage('python')); + await editor(page, 'a', 'def a():\n return b\n'); + await page.evaluate(async () => { + window.views.a.setLanguage('python'); + await window.codepad.until(() => window.views.a.core.snapshot !== 0); + }); + await clickAt(page, 'a', 1, 12); + await page.evaluate(() => { + window.kept = document.querySelector('#a [data-line="1"]'); + }); + await page.keyboard.type('x'); + const same = await page.evaluate(async () => { + const v = window.views.a; + await window.codepad.until(() => v.core.snapshot !== 0 && v.core.revision > 0); + await window.codepad.frames(3); + return document.querySelector('#a [data-line="1"]') === window.kept; + }); + assert.equal(await textOf(page, 'a'), 'def a():\n return bx\n'); + assert.equal(same, true); + await page.close(); + }); + + test('typing past the right edge keeps the caret in view without soft wrap', async () => { + const { page } = await open(); + await editor(page, 'a', 'x'); + await clickAt(page, 'a', 0, 1); + await page.keyboard.type('a'.repeat(90)); + const { x, width, textarea } = await page.evaluate(async () => { + const v = window.views.a; + await window.codepad.frames(2); + const caret = v.caretRect(v.core.selection.head); + return { + x: caret?.x ?? -1, + width: document.getElementById('a').clientWidth, + textarea: Number.parseFloat(document.querySelector('#a textarea').style.left), + }; + }); + assert.ok(x >= 0 && x <= width, `caret x ${x} of ${width}`); + // The keyboard's candidate window opens at the textarea. + assert.ok(Math.abs(textarea - x) <= 1, `textarea at ${textarea}, caret at ${x}`); + await page.close(); + }); + + // The box of a line element and the underline bars, relative to the editor's root. + const boxes = (page, id, selector) => + page.evaluate( + async ([id, selector]) => { + await window.codepad.frames(2); + const root = document.getElementById(id).firstElementChild.getBoundingClientRect(); + return [...document.querySelectorAll(`#${id} ${selector}`)].map((el) => { + const r = el.getBoundingClientRect(); + return { + top: r.top - root.top, + bottom: r.bottom - root.top, + left: r.left - root.left, + right: r.right - root.left, + }; + }); + }, + [id, selector], + ); + + test('a solid underline sits under its range, one bar per wrapped row', async () => { + const { page } = await open(); + await editor(page, 'a', `${'word '.repeat(60)}\nnext`, { softWrap: true }); + await page.evaluate(() => + window.views.a.setDecorations( + [{ kind: 'underline', range: { start: 10, end: 200 }, color: 'red' }], + -1, + ), + ); + const bars = await boxes(page, 'a', '[data-underline]'); + const [line] = await boxes(page, 'a', '[data-line="0"]'); + const row = await page.evaluate(() => window.views.a.layout.rowHeight); + assert.ok(bars.length >= 2, `${bars.length} bars`); + for (const b of bars) { + assert.ok(b.top > line.top && b.bottom <= line.bottom + 1, JSON.stringify({ b, line })); + assert.ok( + b.left >= line.left - 1 && b.right <= line.right + 1, + JSON.stringify({ b, line }), + ); + assert.equal(Math.round(b.top - bars[0].top) % row, 0); + } + await page.close(); + }); + + test('a wavy underline draws one path per row clipped to its range', async () => { + const { page } = await open(); + await editor(page, 'a', 'let total = 1'); + await page.evaluate(() => + window.views.a.setDecorations( + [{ kind: 'underline', range: { start: 4, end: 9 }, color: 'blue', style: 'wavy' }], + -1, + ), + ); + const [wave] = await boxes(page, 'a', 'svg[data-underline]'); + const width = await page.evaluate(() => { + const el = document.querySelector('#a [data-line="0"]'); + const range = document.createRange(); + range.setStart(el.firstChild, 4); + range.setEnd(el.firstChild, 9); + return range.getBoundingClientRect().width; + }); + assert.ok(wave, 'no wave'); + assert.ok( + Math.abs(wave.right - wave.left - width) <= 1, + `${wave.right - wave.left} for ${width}`, + ); + assert.equal( + await page.evaluate(() => document.querySelectorAll('#a svg[data-underline] path').length), + 1, + ); + await page.close(); + }); + + test('a line background tints every row of its line above the active line', async () => { + const { page } = await open(); + await editor(page, 'a', `one\n${'word '.repeat(60)}\nthree`, { softWrap: true }); + await page.evaluate(() => + window.views.a.setDecorations( + [{ kind: 'lineBackground', line: 1, color: 'rgb(255, 0, 0)' }], + -1, + ), + ); + const [bg] = await boxes(page, 'a', '[data-line-background]'); + const [line] = await boxes(page, 'a', '[data-line="1"]'); + assert.ok( + Math.abs(bg.top - line.top) <= 1 && Math.abs(bg.bottom - line.bottom) <= 1, + JSON.stringify({ bg, line }), + ); + const above = await page.evaluate(() => { + const active = document.querySelector('#a [data-active-line]'); + const tint = document.querySelector('#a [data-line-background]'); + return !!(active.compareDocumentPosition(tint) & Node.DOCUMENT_POSITION_FOLLOWING); + }); + assert.equal(above, true); + await page.close(); + }); + + test('a gap pushes the next line down by rows times the row height and onGapLayout reports it', async () => { + const { page } = await open(); + await editor(page, 'a', 'a\nb\nc'); + await page.evaluate(() => { + window.gapsSeen = []; + window.views.a.setOptions({ onGapLayout: (gaps) => window.gapsSeen.push(gaps) }); + window.views.a.setDecorations([{ kind: 'gap', line: 0, rows: 2 }], -1); + }); + const [first] = await boxes(page, 'a', '[data-line="0"]'); + const [second] = await boxes(page, 'a', '[data-line="1"]'); + const row = await page.evaluate(() => window.views.a.layout.rowHeight); + assert.ok( + Math.abs(second.top - first.top - 3 * row) <= 1, + `${second.top - first.top} for ${3 * row}`, + ); + const last = await page.evaluate(() => window.gapsSeen.at(-1)); + assert.equal(last.length, 1); + assert.equal(last[0].line, 0); + assert.ok(Math.abs(last[0].rect.y - (first.top + row)) <= 1, JSON.stringify(last[0])); + assert.equal(last[0].rect.height, 2 * row); + assert.equal(last[0].rect.x, 0); + await page.close(); + }); + + test('a gap scrolled into view fires onGapLayout again', async () => { + const { page } = await open(); + await editor(page, 'a', Array.from({ length: 200 }, (_, i) => `line ${i}`).join('\n')); + const before = await page.evaluate(async () => { + window.gapsSeen = []; + window.views.a.setOptions({ onGapLayout: (gaps) => window.gapsSeen.push(gaps) }); + window.views.a.setDecorations([{ kind: 'gap', line: 150, rows: 2 }], -1); + await window.codepad.frames(2); + return { count: window.gapsSeen.length, y: window.gapsSeen.at(-1)[0].rect.y }; + }); + const after = await page.evaluate(async () => { + window.views.a.scrollToLine(140); + await window.codepad.frames(3); + return { count: window.gapsSeen.length, y: window.gapsSeen.at(-1)[0].rect.y }; + }); + assert.ok(after.count > before.count, JSON.stringify({ before, after })); + assert.ok(after.y < before.y, JSON.stringify({ before, after })); + await page.close(); + }); + + test('getGapRect is null for a line with no gap', async () => { + const { page } = await open(); + await editor(page, 'a', 'a\nb\nc'); + const rects = await page.evaluate(async () => { + window.views.a.setDecorations([{ kind: 'gap', line: 0, rows: 1 }], -1); + await window.codepad.frames(2); + return [window.views.a.gapRect(0), window.views.a.gapRect(1)]; + }); + assert.notEqual(rects[0], null); + assert.equal(rects[1], null); + await page.close(); + }); + + test('a gap under the last line grows the content height', async () => { + const { page } = await open(); + await editor(page, 'a', 'a\nb'); + const grew = await page.evaluate(async () => { + const v = window.views.a; + await window.codepad.frames(1); + const before = v.layout.contentHeight; + v.setDecorations([{ kind: 'gap', line: 1, rows: 3 }], -1); + await window.codepad.frames(2); + return { before, after: v.layout.contentHeight, row: v.layout.rowHeight }; + }); + assert.equal(grew.after - grew.before, 3 * grew.row); + await page.close(); + }); + + test('a click inside a gap leaves the caret where it was', async () => { + const { page } = await open(); + await editor(page, 'a', 'abc\ndef'); + await page.evaluate(async () => { + const v = window.views.a; + v.setDecorations([{ kind: 'gap', line: 0, rows: 3 }], -1); + v.apply(() => v.core.setSelection(1, 1)); + await window.codepad.frames(2); + }); + const [first] = await boxes(page, 'a', '[data-line="0"]'); + const row = await page.evaluate(() => window.views.a.layout.rowHeight); + const root = await page.evaluate(() => { + const r = document.getElementById('a').firstElementChild.getBoundingClientRect(); + return { left: r.left, top: r.top }; + }); + await page.mouse.click(root.left + first.left + 10, root.top + first.top + 2.5 * row); + assert.equal(await page.evaluate(() => window.views.a.core.selection.head), 1); + await page.close(); + }); + + test('decorations made for an older revision follow the edits since', async () => { + const { page } = await open(); + await editor(page, 'a', 'hello world'); + const range = await page.evaluate(() => { + const v = window.views.a; + const old = v.core.revision; + v.apply(() => v.core.replace(0, 0, 'XX')); + v.setDecorations([{ kind: 'underline', range: { start: 6, end: 11 }, color: 'red' }], old); + return v.core.decorations()[0].range; + }); + assert.deepEqual(range, { start: 8, end: 13 }); + await page.close(); + }); + + test('decorations for a revision more than 256 edits back keep the current set', async () => { + const { page } = await open(); + await editor(page, 'a', 'hello'); + const kept = await page.evaluate(() => { + const v = window.views.a; + const old = v.core.revision; + v.setDecorations([{ kind: 'lineBackground', line: 0, color: 'red' }], -1); + for (let i = 0; i < 300; i++) v.apply(() => v.core.replace(0, 0, 'x')); + v.setDecorations([{ kind: 'gap', line: 0, rows: 2 }], old); + return v.core.decorations().map((d) => d.kind); + }); + assert.deepEqual(kept, ['lineBackground']); + await page.close(); + }); + test('the frame after a letter, an Enter and a joining Backspace keeps the keyword colors', async () => { const { page } = await open(); await page.evaluate(async () => {