@motionscript/code 0.1.0-alpha.5 → 0.1.0-alpha.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/node.ts CHANGED
@@ -1,39 +1,51 @@
1
1
  import {
2
- node,
3
- RenderContext2D, RenderPass2D, Clip, EasingFunction, NodeConfig, Size2D, SizeConstraints,
4
- Node2D, Node2DProps, MeasureContext2D, InsetsResolved, InsetsProps,
5
- property, insetsProperty, lerpNumber, colorOps, type Color,
6
- command, driveCommand, type AssetScope, type Command, type CommandArgs, type Node, type TweenStepper, type Vector2,
2
+ Graphics2D,
3
+ Paint,
4
+ Types,
5
+ component2d,
6
+ lerpNumber,
7
+ type InsetsResolved,
8
+ type MeasureContext2D,
9
+ type Measurer,
10
+ type NodeOf,
11
+ type NormalizedColor,
12
+ type Piece,
13
+ type RenderContext,
14
+ type Size2D,
15
+ // Named so the emitted declaration reaches these through the sdk, not core.
16
+ type Color as _Color,
17
+ type Node2D as _Node2D,
18
+ type Node2DProps as _Node2DProps,
7
19
  } from "@motionscript/sdk";
8
20
  import {
9
- CodeRange,
10
- rangeToCharOffsets,
11
- charOffsetsToRange,
21
+ DefaultHighlightStyle,
12
22
  TokenAdvanceCache,
13
- IdLine,
14
- tokenizeCodeToIdLines,
23
+ canHighlight,
24
+ charOffsetsToRange,
15
25
  defaultCodeDiff,
16
- type CodeDiffStrategy,
17
- CodeLayout,
18
- CodeMetrics,
26
+ defaultCodePhases,
27
+ drawCode,
28
+ ensureHighlighter,
19
29
  layoutCode,
20
- metricsSignature,
21
- AnimToken,
22
- CodeTransition,
23
- StructuralTransition,
24
- RowBand,
25
- RowsTransition,
26
30
  makeAnim,
27
- defaultCodePhases,
28
- type CodePhaseStrategy,
29
- resolveTokenStates,
31
+ metricsSignature,
30
32
  moveProgress,
31
- canHighlight,
32
- ensureHighlighter,
33
33
  normalizeSource,
34
- CodeTheme,
35
- DefaultHighlightStyle,
36
- drawCode,
34
+ rangeToCharOffsets,
35
+ resolveTokenStates,
36
+ tokenizeCodeToIdLines,
37
+ type AnimToken,
38
+ type CodeDiffStrategy,
39
+ type CodeLayout,
40
+ type CodeMetrics,
41
+ type CodePhaseStrategy,
42
+ type CodeRange,
43
+ type CodeTheme,
44
+ type DimTransition,
45
+ type IdLine,
46
+ type RowBand,
47
+ type RowsTransition,
48
+ type StructuralTransition,
37
49
  } from "./engine";
38
50
 
39
51
  /** A row band's paint and corner radius when `highlightRows` is given neither. */
@@ -41,38 +53,9 @@ const ROW_BAND_COLOR = "rgba(255, 255, 255, 0.12)";
41
53
  const ROW_BAND_RADIUS = 6;
42
54
 
43
55
  /**
44
- * A listing and nothing else — no paint slots, and no box behind the tokens.
45
- *
46
- * It did carry a `fill`/`overlay`/`stroke`/`shadow` set and the corner radius
47
- * that shaped them, so a block could draw its own panel. That was one node doing
48
- * two jobs, and the second one is a `Rect`'s: a listing set on a card is a `Code`
49
- * inside a hugging `Rect`, which tracks the block's size for the same reason
50
- * every other hugging container tracks its child's. What is left here is the
51
- * listing — its source, how it is coloured, the face it is set in, and the space
52
- * it keeps around itself.
53
- */
54
- export interface CodeProps extends Node2DProps {
55
- code: string;
56
- language: string;
57
- fontSize: number;
58
- fontFamily: string;
59
- /** A built-in/registered theme name (e.g. `'github-dark'`), or a {@link CodeHighlightStyle} object. */
60
- theme: CodeTheme;
61
- lineHeight: number;
62
- letterSpacing: number;
63
- showLineNumbers: boolean;
64
- lineNumberGap: number;
65
- padding: InsetsProps;
66
- }
67
-
68
- /**
69
- * Construction-time-only options: pluggable engine behavior, set once when
70
- * the node is created. Deliberately *not* part of {@link CodeProps} — every
71
- * `@property` field accepts either a value or a zero-arg reactive binding
72
- * (`value | (() => value)`, see `PropInputs`), and the node's own reactive
73
- * write path (`_writeProp`) treats any function value as the latter. A
74
- * strategy *is* a function, so it can't be told apart from a binding that
75
- * computes one — it has to stay outside the reactive prop system entirely.
56
+ * Which token became which across an edit, and when each part of it happens.
57
+ * Arguments of {@link defineCode}: a strategy is a function, which a prop would
58
+ * take for a binding, so it is part of the component's definition instead.
76
59
  */
77
60
  export interface CodeStrategies {
78
61
  /** Decides which token became which across an edit. Defaults to `defaultCodeDiff`. */
@@ -81,910 +64,442 @@ export interface CodeStrategies {
81
64
  phaseStrategy?: CodePhaseStrategy;
82
65
  }
83
66
 
84
- @node({
85
- key: "code",
86
- parentKey: "node",
87
- forkable: true,
88
- layout: {
89
- defaultWidthMode: "hug",
90
- defaultHeightMode: "hug",
91
- acceptsChildren: false,
92
- },
93
- })
94
- export class Code extends Node2D<CodeProps> {
95
-
96
- @property({ default: "" }) declare readonly code: string;
97
- @property({ default: "typescript" }) declare readonly language: string;
98
- @property({ default: "Fira Mono" }) declare readonly fontFamily: string;
99
- @property({ default: DefaultHighlightStyle.name }) declare readonly theme: CodeTheme;
100
- @property({ default: 16 }) declare readonly fontSize: number;
101
- @property({ default: 1.6 }) declare readonly lineHeight: number;
102
- // Extra horizontal space added after every glyph (in px), like CSS
103
- // letter-spacing. Folded into the advance a token is measured at, so
104
- // measurement and drawing stay in lockstep.
105
- @property({ default: 1.1 }) declare readonly letterSpacing: number;
106
- @property({ default: false }) declare readonly showLineNumbers: boolean;
107
- // Horizontal gap between the line-number column and the code text, expressed
108
- // in space-widths (so it scales with fontSize). Only applies when
109
- // showLineNumbers is on.
110
- @property({ default: 2 }) declare readonly lineNumberGap: number;
111
- @insetsProperty() declare readonly padding: InsetsResolved;
112
-
113
- /** The settled structure. During an edit, the structure the edit lands on. */
114
- private tokenLines: IdLine[] = [];
115
- /** The source `tokenLines` spells, so a frame compares it with `code` without joining every token. */
116
- private _linesSource: string = "";
117
- /** What `tokenLines` were coloured and split with, so a frame notices a `language` or `theme` that has moved since. */
118
- private _linesBasis: TokenBasis = { language: "", theme: "", highlighted: false };
119
- /** The last `code` seen and its normalised form, so a frame that finds it unchanged does not scan it. */
120
- private _rawCode: string | null = null;
121
- private _normalCode: string = "";
122
-
123
- private transitions: CodeTransition[] = [];
124
-
125
- // Caches expensive scope.measureText() calls; cleared when the font
126
- // signature (fontSize|fontFamily) changes. See TokenAdvanceCache.
127
- private advanceCache = new TokenAdvanceCache();
128
-
129
- // Layout cache for *settled* frames. Bumped whenever tokenLines is
130
- // reassigned, so a cache hit only ever happens on identical content. Frames
131
- // inside a structural edit are served from that edit's own two cached
132
- // layouts instead (see StructuralTransition).
133
- private structureVersion = 0;
134
- private layoutCacheKey: string | null = null;
135
- private layoutCache: CodeLayout | null = null;
136
-
137
- // Persistent dim state set by highlight() — applied during render to all
138
- // tokens whose id is NOT in the highlight set. null means "not highlighting".
139
- private highlightDimOpacity: number | null = null;
140
- private highlightedIds: Set<number> = new Set();
141
-
142
- // The bands highlightRows() left behind whole rows; empty means none.
143
- private rowBands: RowBand[] = [];
144
-
145
- /**
146
- * Which token became which across an edit, and when each part of that
147
- * edit happens. Construction-time-only (see {@link CodeStrategies}) —
148
- * resolved once here rather than left as `?? defaultX` at every call site.
149
- */
150
- private readonly diffStrategy: CodeDiffStrategy;
151
- private readonly phaseStrategy: CodePhaseStrategy;
152
-
153
- constructor(props?: NodeConfig<Code, CodeProps> & CodeStrategies) {
154
- super(props);
155
- this.diffStrategy = props?.diffStrategy ?? defaultCodeDiff;
156
- this.phaseStrategy = props?.phaseStrategy ?? defaultCodePhases;
157
- this.applyProp("width", props?.width ?? "hug");
158
- this.applyProp("height", props?.height ?? "hug");
159
- this.applyProp("_driven", false);
160
-
161
- // Best-effort, for a highlighter constructed outside the asset pipeline
162
- // entirely (a bare `new Code(...)` in a test or a headless measure). On
163
- // the timeline the authoritative load is the one `declareAssets` declares,
164
- // which `AssetManager.loadAt` awaits *before* this node is laid out — so
165
- // there the tokens are right the first time rather than upgrading later.
166
- // (Theme is a synchronous color style; only the language parser loads.)
167
- ensureHighlighter(undefined, [this.language]).catch(() => { });
168
- this._sync();
169
- }
170
-
171
- /**
172
- * Swap in a new settled structure, invalidating the layout cache.
173
- *
174
- * The one place `tokenLines` is written, because the cache key is a version
175
- * counter rather than a hash of the content — a write that skipped the bump
176
- * would keep serving the previous frame's geometry for the new listing.
177
- */
178
- private setLines(lines: IdLine[], source: string, basis: TokenBasis = this._basis()): void {
179
- if (this.tokenLines === lines) return;
180
- this.tokenLines = lines;
181
- this._linesSource = source;
182
- this._linesBasis = basis;
183
- this.structureVersion++;
184
- this.layoutCache = null;
185
- this.layoutCacheKey = null;
186
- }
187
-
188
- /**
189
- * The monospaced face this block measures and draws with, and the syntax
190
- * grammar it tokenizes with.
191
- *
192
- * Both belong to *layout*: token x positions are measured against the face,
193
- * and how many tokens there are depends on the grammar. Declared here, the
194
- * grammar goes on the timeline as an ordinary asset: `AssetManager.loadAt`
195
- * waits for it before the frame is laid out, so the first measurement is the
196
- * right one. Nothing is freed on eviction — parsers are cheap to keep
197
- * resident. The loader touches no node: `renderContent` re-tokenizes once
198
- * the grammar is there.
199
- */
200
- override declareAssets(assets: AssetScope): void {
201
- super.declareAssets(assets);
202
- assets.font(this.fontFamily);
203
- assets.loader(`shiki:lang:${this.language}`, grammarLoader(this.language), { gate: "layout" });
204
- }
205
-
206
- // ── Geometry ────────────────────────────────────────────────────────────
207
-
208
- private metrics(): CodeMetrics {
209
- return {
210
- fontSize: this.fontSize,
211
- fontFamily: this.fontFamily,
212
- lineHeight: this.lineHeight,
213
- letterSpacing: this.letterSpacing,
214
- padding: this.padding,
215
- showLineNumbers: this.showLineNumbers,
216
- lineNumberGap: this.lineNumberGap,
217
- };
218
- }
219
-
220
- /** The structural edit currently in flight, if any. */
221
- private activeEdit(): StructuralTransition | null {
222
- for (let i = this.transitions.length - 1; i >= 0; i--) {
223
- const tr = this.transitions[i];
224
- if (tr.kind === "structural") return tr;
225
- }
226
- return null;
227
- }
228
-
229
- /** The row-band change in flight, if any; the latest wins. */
230
- private activeRows(): RowsTransition | null {
231
- for (let i = this.transitions.length - 1; i >= 0; i--) {
232
- const tr = this.transitions[i];
233
- if (tr.kind === "rows") return tr;
234
- }
235
- return null;
236
- }
67
+ /** `code` part-way through a `to({ code })`: the source it leaves, the one it lands on, and how far along it is, eased. */
68
+ export interface CodeBlend {
69
+ readonly from: string;
70
+ readonly to: string;
71
+ readonly t: number;
72
+ }
237
73
 
238
- private settledLayout(m: CodeMetrics, scope: MeasureContext2D | RenderContext2D): CodeLayout {
239
- const key = `${this.structureVersion}|${metricsSignature(m)}|${this.advanceCache.signature(m.fontSize, m.fontFamily)}`;
240
- if (this.layoutCache && this.layoutCacheKey === key) return this.layoutCache;
241
- const layout = layoutCode(this.tokenLines, m, this.advanceCache, scope);
242
- this.layoutCache = layout;
243
- this.layoutCacheKey = key;
244
- return layout;
245
- }
74
+ /** What `code` holds: a source, or a {@link CodeBlend} while a `to({ code })` runs. */
75
+ export type CodeSource = string | CodeBlend;
246
76
 
247
- /**
248
- * The one or two layouts this frame is drawn from.
249
- *
250
- * A settled frame has one. A frame inside an edit has two — where every
251
- * token was, and where it is going — and the frame is a point between them.
252
- * That is the whole reason an insert no longer piles its glyphs at the left
253
- * margin: a token's destination is *computed*, not approximated by collapsing
254
- * the advance of everything around it.
255
- *
256
- * Both endpoints are fixed for the edit's duration, so they are built once
257
- * and cached on the transition rather than rebuilt per frame.
258
- */
259
- private frameLayout(scope: MeasureContext2D | RenderContext2D): {
260
- from: CodeLayout;
261
- to: CodeLayout;
262
- edit: StructuralTransition | null;
263
- } {
264
- const m = this.metrics();
265
- const edit = this.activeEdit();
266
- if (!edit) {
267
- const layout = this.settledLayout(m, scope);
268
- return { from: layout, to: layout, edit: null };
269
- }
270
- const key = `${metricsSignature(m)}|${this.advanceCache.signature(m.fontSize, m.fontFamily)}`;
271
- if (edit.layoutKey !== key || !edit.fromLayout || !edit.toLayout) {
272
- edit.fromLayout = layoutCode(edit.from, m, this.advanceCache, scope);
273
- edit.toLayout = layoutCode(edit.to, m, this.advanceCache, scope);
274
- edit.layoutKey = key;
275
- }
276
- return { from: edit.fromLayout, to: edit.toLayout, edit };
277
- }
77
+ /** A range argument: one range, several, or a chain that went through JSON as `{ list }`. */
78
+ export type CodeTarget = CodeRange | Iterable<CodeRange> | { readonly list: CodeRange[] };
278
79
 
279
- override measure(constraints: SizeConstraints, scope: MeasureContext2D): Partial<Size2D> {
280
- this._sync();
281
- this.advanceCache.sync(this.advanceCache.signature(this.fontSize, this.fontFamily));
282
- const wm = this.width;
283
- const hm = this.height;
284
-
285
- const { from, to, edit } = this.frameLayout(scope);
286
- const t = moveProgress(edit);
287
- const innerW = edit ? lerpNumber(from.innerW, to.innerW, t) : to.innerW;
288
- const innerH = edit ? lerpNumber(from.innerH, to.innerH, t) : to.innerH;
289
-
290
- const resolvedW = typeof wm === "number"
291
- ? wm
292
- : wm === "hug"
293
- ? innerW + this.padding.left + this.padding.right
294
- : constraints.maxWidth ?? 0;
295
-
296
- const resolvedH = typeof hm === "number"
297
- ? hm
298
- : hm === "hug"
299
- ? innerH + this.padding.top + this.padding.bottom
300
- : constraints.maxHeight ?? 0;
301
-
302
- return { width: resolvedW, height: resolvedH };
303
- }
80
+ /** What a structure was tokenized with: the grammar, the theme and whether the grammar had landed. */
81
+ export interface CodeTokenBasis {
82
+ readonly language: string;
83
+ readonly theme: CodeTheme;
84
+ readonly highlighted: boolean;
85
+ }
304
86
 
305
- protected override renderContent(ctx: RenderPass2D): void {
306
- // Refuse the ambient `<DefaultTextStyle>` / theme typography defaults for
307
- // everything drawn inside this node.
308
- //
309
- // Those defaults describe the *document's* prose — a display face, a
310
- // heading weight, a paragraph line-height — and a code block is not prose.
311
- // Its own props are the vocabulary: `fontFamily` defaults to a monospaced
312
- // face because column alignment depends on it, `letterSpacing` and
313
- // `lineHeight` are tuned against that face, and every token is laid out at
314
- // an x measured from those exact values. A scene-wide serif family or a
315
- // 700 weight arriving through the draw scope would shape glyphs the
316
- // geometry was never measured for, and the block would come apart
317
- // column-by-column rather than merely look different.
318
- ctx.pushTextStyle(null);
319
- try {
320
- // Also what upgrades a frame drawn as plain text to full highlighting
321
- // the moment the asset loader resolves the grammar.
322
- this._sync();
323
- super.renderContent(ctx);
324
- } finally {
325
- ctx.popTextStyle();
326
- }
327
- }
87
+ /** A listing a command left behind: its source, its tokens, and the basis they were made on. */
88
+ export interface CodeListing {
89
+ readonly source: string;
90
+ readonly lines: IdLine[];
91
+ readonly basis: CodeTokenBasis;
92
+ }
328
93
 
329
- protected override renderSelf(ctx: RenderContext2D): void {
330
- this.drawSelf(ctx);
331
- }
94
+ export interface CodeEditFrame {
95
+ readonly transition: StructuralTransition;
96
+ readonly progress: number;
97
+ }
332
98
 
333
- /** A listing holds a listing — `append`/`insert`/`erase` are how it grows. */
334
- protected override acceptsChild(_child: Node): boolean {
335
- return false;
336
- }
99
+ /** The dim `highlight` leaves: what stays bright, what the rest dims to, and the cross-fade in flight. */
100
+ export interface CodeFocus {
101
+ readonly dim: number | null;
102
+ readonly ids: Set<number>;
103
+ readonly fade: DimTransition | null;
104
+ }
337
105
 
338
- /**
339
- * The node's laid-out rect as a clip outline, so `clip` and any backdrop
340
- * effect are confined to the block rather than to nothing — a listing set on
341
- * a card is exactly where a backdrop blur is asked for.
342
- */
343
- protected override clipSelf(): Clip {
344
- return new Clip().rect({
345
- width: this.layoutBounds.width,
346
- height: this.layoutBounds.height,
347
- });
348
- }
106
+ export interface CodeBanding {
107
+ readonly bands: RowBand[];
108
+ readonly fade: RowsTransition | null;
109
+ }
349
110
 
350
- /**
351
- * A listing is grabbed by its **text**, line by ragged line, rather than by
352
- * the rectangle the lines were laid out in.
353
- *
354
- * The default narrows a node's grab region to the outline it declares, and
355
- * this node's outline is a box it no longer paints anything into. Code is
356
- * mostly whitespace: a ten-line snippet with one long line is a rectangle
357
- * that is largely empty, and in an editor every one of those empty pixels
358
- * swallows a click meant for whatever sits behind or beneath it. Short of the
359
- * text itself there is nothing there to have clicked.
360
- *
361
- * So the region is the union of the lines' own extents — each a line-height
362
- * slot as wide as that line's ink — plus the gutter where line numbers are
363
- * showing, since those are drawn glyphs too.
364
- *
365
- * Answered from the **cached** layout, which is what the last frame drew
366
- * from, because a hit test arrives with no measurement scope and text cannot
367
- * be measured without one. Where there is no usable cache — before the first
368
- * frame, or mid-edit, when the geometry is an interpolation of two structures
369
- * held on the transition — the box is the honest answer rather than a
370
- * silhouette measured against stale metrics.
371
- */
372
- protected override hitTestSelf(local: Vector2, tolerance: number): boolean {
373
- this._sync();
374
- const layout = this.hitLayout();
375
- if (!layout) return super.hitTestSelf(local, tolerance);
376
-
377
- // Never *wider* than the box: `hug` sizes to the ink, but a fixed width
378
- // narrower than the longest line would otherwise be hit outside itself.
379
- if (!super.hitTestSelf(local, tolerance)) return false;
380
-
381
- const half = (this.fontSize * this.lineHeight) / 2;
382
- // Line numbers sit in the gutter, to the left of every line's own start,
383
- // so a numbered blank line is still grabbable — by its number.
384
- const gutter = this.showLineNumbers ? layout.gutter : 0;
385
- const left = layout.startX - gutter - tolerance;
386
- for (let i = 0; i < layout.lineY.length; i++) {
387
- const width = (layout.lineW[i] ?? 0) + gutter;
388
- if (width <= 0) continue;
389
- if (Math.abs(local.y - layout.lineY[i]) > half + tolerance) continue;
390
- if (local.x >= left && local.x <= layout.startX + (layout.lineW[i] ?? 0) + tolerance) {
391
- return true;
392
- }
393
- }
394
- return false;
395
- }
111
+ /** Each `Code` component's strategies and edit cache, by the node class it generated. */
112
+ const kits = new WeakMap<object, Kit>();
396
113
 
397
- /**
398
- * The layout a hit test may be answered from: the settled cache, and only
399
- * while it still matches the node's current metrics.
400
- *
401
- * The key is the one {@link settledLayout} writes minus its scope-dependent
402
- * half — every input to it (`metricsSignature`, the advance cache's own
403
- * signature) is readable without a measurer, which is precisely what makes
404
- * the check possible here.
405
- */
406
- private hitLayout(): CodeLayout | null {
407
- if (!this.layoutCache || this.activeEdit()) return null;
408
- const m = this.metrics();
409
- const key = `${this.structureVersion}|${metricsSignature(m)}|${this.advanceCache.signature(m.fontSize, m.fontFamily)}`;
410
- return this.layoutCacheKey === key ? this.layoutCache : null;
411
- }
114
+ const NO_FOCUS: CodeFocus = { dim: null, ids: new Set(), fade: null };
115
+ const NO_BANDING: CodeBanding = { bands: [], fade: null };
412
116
 
413
- // ── Editing commands ────────────────────────────────────────────────────
414
-
415
- /**
416
- * Append `code` to the end of the listing.
417
- *
418
- * Stated as *what the source becomes*; {@link editTo} works out the rest —
419
- * which is why appending a line that closes a block re-highlights the lines
420
- * above it, instead of colouring the new text as its own program.
421
- */
422
- @command({ args: [{ key: "code", kind: "text", multiline: true }] })
423
- append(args: CommandArgs<{ code: string }> & { duration: number }): Command<Record<string, never>> {
424
- this._sync();
425
- const { code } = args.data as { code: string };
426
- return this.editTo(this.joinedSource() + code, args.duration, args.easing);
427
- }
117
+ /** A private entry: commands write it, documents and calls never see it. */
118
+ function own<T>(initial: T) {
119
+ return Types.custom<T, T, { readonly private: true }>(initial, { private: true });
120
+ }
428
121
 
429
- /** Insert `code` above the listing. */
430
- @command({ args: [{ key: "code", kind: "text", multiline: true }] })
431
- prepend(args: CommandArgs<{ code: string }> & { duration: number }): Command<Record<string, never>> {
432
- this._sync();
433
- const { code } = args.data as { code: string };
434
- return this.editTo(code + this.joinedSource(), args.duration, args.easing);
435
- }
122
+ const TARGET = Types.custom<CodeTarget | undefined>(undefined, { kind: "selector" });
123
+ const TEXT = Types.text("", { multiline: true });
436
124
 
437
- /**
438
- * Insert `code` at the given (line, col). Both are 1-indexed; col is the
439
- * column BEFORE which the new content is inserted (col=1 means start of
440
- * line). If `code` contains newlines, new lines are created in the middle
441
- * of the existing line.
442
- */
443
- @command({
444
- args: [
445
- // Two controls, one argument: the method takes a `[line, col]`
446
- // tuple, so the pair a host draws is declared *inside* the value it
447
- // composes into rather than flattened beside it.
448
- {
449
- key: "position", kind: "point", properties: {
450
- line: { kind: "number", default: 1, min: 1, step: 1 },
451
- col: { kind: "number", default: 1, min: 1, step: 1 },
125
+ /**
126
+ * A `Code` whose edits are paired and timed by `strategies`. {@link Code} is
127
+ * the one with the defaults; a project wanting another hands its own to the
128
+ * engine in its place (the key is the same).
129
+ *
130
+ * A listing and nothing else: no paint slots, and no box behind the tokens. A
131
+ * listing set on a card is a `Code` inside a hugging `Rect`.
132
+ */
133
+ export function defineCode(strategies: CodeStrategies = {}) {
134
+ const kit: Kit = {
135
+ diff: strategies.diffStrategy ?? defaultCodeDiff,
136
+ phases: strategies.phaseStrategy ?? defaultCodePhases,
137
+ edits: new WeakMap(),
138
+ };
139
+ const act = (timeline: { animate(frame: Frame): Piece; wait(seconds: number): Piece }, frame: Frame | null): Piece =>
140
+ (frame ? timeline.animate(frame) : timeline.wait(0));
141
+
142
+ const component = component2d({
143
+ key: "code",
144
+ state: {
145
+ code: Types.custom<string, CodeSource>("", { lerp: blendSource }),
146
+ language: "typescript",
147
+ fontFamily: "Fira Mono",
148
+ /** A built-in or registered theme name (e.g. `'github-dark'`), or a `CodeHighlightStyle` object. */
149
+ theme: Types.custom<CodeTheme>(DefaultHighlightStyle.name),
150
+ fontSize: 16,
151
+ lineHeight: 1.6,
152
+ // Extra space after every glyph, in px: folded into the advance a token is measured at.
153
+ letterSpacing: 1.1,
154
+ showLineNumbers: false,
155
+ // In space-widths, so it scales with fontSize.
156
+ lineNumberGap: 2,
157
+ listing: own<CodeListing | null>(null),
158
+ edit: own<CodeEditFrame | null>(null),
159
+ focus: own(NO_FOCUS),
160
+ banding: own(NO_BANDING),
161
+ },
162
+ defaults: { width: "hug", height: "hug" },
163
+ allowedChildren: [],
164
+ // The grammar gates layout: how many tokens there are, and so where each sits, depends on it.
165
+ load: (loader, state) => {
166
+ loader.font(state.fontFamily);
167
+ loader.task(`shiki:lang:${state.language}`, grammarLoader(state.language), { before: "layout" });
168
+ },
169
+ commands: {
170
+ /** Append `code` to the end of the listing. */
171
+ append: {
172
+ args: { code: TEXT },
173
+ run: (timeline, state) => {
174
+ const seen = current(state, kit);
175
+ return act(timeline, editFrame(kit, seen, seen.source + timeline.args.code, basisOf(state)));
452
176
  },
453
177
  },
454
- { key: "code", kind: "text", default: "", multiline: true },
455
- ],
456
- })
457
- insert(
458
- args: CommandArgs<{ position: [number, number]; code: string }> & { duration: number },
459
- ): Command<Record<string, never>> {
460
- this._sync();
461
- const { position, code } = args.data as { position: [number, number]; code: string };
462
- const source = this.joinedSource();
463
- const offset = this.offsetAt(position);
464
- return this.editTo(source.slice(0, offset) + code + source.slice(offset), args.duration, args.easing);
465
- }
466
-
467
- /**
468
- * Erase the code in `codeRange`.
469
- *
470
- * Named `erase` rather than `remove` because a `Code` is also a node, and
471
- * `Node.remove(child)` takes a child out of the tree. Two methods spelled
472
- * the same on one object, doing entirely different things, is worse than one
473
- * of them having a slightly less obvious name.
474
- *
475
- * A range that covers whole lines takes their line breaks with it, so the
476
- * rows below close up; a range inside a line takes only the characters, and
477
- * the rest of the line reflows around the hole.
478
- */
479
- @command({ key: "remove", args: [{ key: "target", kind: "selector" }] })
480
- erase(
481
- args: CommandArgs<{ target: CodeRange }> & { duration: number },
482
- ): Command<Record<string, never>> {
483
- this._sync();
484
- const { target: codeRange } = args.data as { target: CodeRange };
485
- const { duration, easing } = args;
486
- const source = this.joinedSource();
487
- let { start, end } = rangeToCharOffsets(codeRange, this.lineLengths());
488
- // `lines(2)` resolves to the *characters* of line 2, not to the row —
489
- // taking those alone would leave an empty line behind where an editor
490
- // would have closed the gap. This is also what makes a blank row
491
- // removable at all: it has no characters, so its range is empty, and
492
- // "delete nothing" is not what `lines(2)` was asking for.
493
- const atLineStart = start === 0 || source[start - 1] === "\n";
494
- const atLineEnd = end === source.length || source[end] === "\n";
495
- if (atLineStart && atLineEnd) {
496
- if (end < source.length) end += 1;
497
- else if (start > 0) start -= 1;
498
- } else if (end <= start) {
499
- return driveCommand(duration, () => { });
500
- }
501
- if (end <= start) return driveCommand(duration, () => { });
502
- return this.editTo(source.slice(0, start) + source.slice(end), duration, easing);
503
- }
178
+ /** Insert `code` above the listing. */
179
+ prepend: {
180
+ args: { code: TEXT },
181
+ run: (timeline, state) => {
182
+ const seen = current(state, kit);
183
+ return act(timeline, editFrame(kit, seen, timeline.args.code + seen.source, basisOf(state)));
184
+ },
185
+ },
186
+ /** Insert `code` before the 1-indexed `[line, col]`, clamped into the listing. */
187
+ insert: {
188
+ args: {
189
+ position: Types.custom<[number, number] | undefined>(undefined, {
190
+ kind: "point",
191
+ properties: {
192
+ line: { kind: "number", default: 1, min: 1, step: 1 },
193
+ col: { kind: "number", default: 1, min: 1, step: 1 },
194
+ },
195
+ }),
196
+ code: TEXT,
197
+ },
198
+ run: (timeline, state) => {
199
+ const seen = current(state, kit);
200
+ const offset = offsetAt(seen.lines, timeline.args.position as [number, number]);
201
+ const next = seen.source.slice(0, offset) + timeline.args.code + seen.source.slice(offset);
202
+ return act(timeline, editFrame(kit, seen, next, basisOf(state)));
203
+ },
204
+ },
205
+ /**
206
+ * Erase the code in `target`. A range of whole lines takes their line
207
+ * breaks with it, so the rows below close up.
208
+ */
209
+ remove: {
210
+ args: { target: TARGET },
211
+ run: (timeline, state) => act(timeline, eraseFrame(kit, state, timeline.args.target as CodeRange)),
212
+ },
213
+ replace: {
214
+ args: { target: TARGET, replacement: TEXT },
215
+ run: (timeline, state) => {
216
+ const seen = current(state, kit);
217
+ const { start, end } = rangeToCharOffsets(timeline.args.target as CodeRange, lineLengths(seen.lines));
218
+ const next = seen.source.slice(0, start) + timeline.args.replacement + seen.source.slice(end);
219
+ return act(timeline, editFrame(kit, seen, next, basisOf(state)));
220
+ },
221
+ },
222
+ /**
223
+ * Dim everything outside `target` (one range or several) to `dim`.
224
+ * Persistent: a second highlight cross-fades from this one.
225
+ */
226
+ highlight: {
227
+ args: {
228
+ target: TARGET,
229
+ dim: Types.number(0.4, { min: 0, max: 1, step: 0.01, scale: 100, unit: "%" }),
230
+ },
231
+ run: (timeline, state) => act(timeline, highlightFrame(kit, state, timeline.args.target, timeline.args.dim)),
232
+ },
233
+ /** Fade every dimmed token back to full and clear the highlight. */
234
+ resetHighlight: (timeline, state) => act(timeline, resetHighlightFrame(kit, state)),
235
+ /**
236
+ * Lay a band of `color` behind every line a range touches. A second
237
+ * call slides the bands onto their new rows, paired in order; a band
238
+ * keeps to its lines through an edit.
239
+ */
240
+ highlightRows: {
241
+ args: {
242
+ target: TARGET,
243
+ color: Types.color(ROW_BAND_COLOR),
244
+ radius: Types.number(ROW_BAND_RADIUS, { min: 0, step: 1 }),
245
+ },
246
+ run: (timeline, state) => {
247
+ const seen = current(state, kit);
248
+ const bands = rowBandsIn(seen.lines, normalizeCodeRanges(timeline.args.target), timeline.args.color, Math.max(0, timeline.args.radius ?? ROW_BAND_RADIUS));
249
+ return act(timeline, rowsFrame(seen, state.banding.bands, bands));
250
+ },
251
+ },
252
+ /** Fade every row band out and clear them. */
253
+ resetRowHighlight: (timeline, state) => act(timeline, rowsFrame(current(state, kit), state.banding.bands, [])),
254
+ },
255
+ measure: (measurer, state) => measureListing(measurer, state, kit),
256
+ // Refuses the ambient text style: every column is measured against this face, so an
257
+ // inherited family or weight would shape glyphs the geometry was never measured for.
258
+ render:(ctx, state) => ctx.textStyle(null, () => drawListing(ctx, state, kit)),
259
+ });
260
+ kits.set(component.node, kit);
261
+ return component;
262
+ }
504
263
 
505
- /** Replace the code in `codeRange` with `replacement`. */
506
- @command({ args: [{ key: "target", kind: "selector" }, { key: "replacement", kind: "text", default: "", multiline: true }] })
507
- replace(
508
- args: CommandArgs<{ target: CodeRange; replacement: string }> & { duration: number },
509
- ): Command<Record<string, never>> {
510
- this._sync();
511
- const { target: codeRange, replacement } = args.data as { target: CodeRange; replacement: string };
512
- const source = this.joinedSource();
513
- const { start, end } = rangeToCharOffsets(codeRange, this.lineLengths());
514
- return this.editTo(source.slice(0, start) + replacement + source.slice(end), args.duration, args.easing);
515
- }
264
+ /**
265
+ * A syntax-highlighted listing whose edits animate token by token: each edit
266
+ * is diffed against what is on screen, so a token that survives travels to
267
+ * its new column and only what changed fades.
268
+ */
269
+ export const Code = defineCode();
270
+ export type Code = NodeOf<typeof Code>;
271
+ export type CodeProps = NonNullable<Parameters<typeof Code>[0]>;
272
+
273
+ /** What a listing shows now: its source, its token rows, and the edit in flight, if any. */
274
+ export function listingOf(code: Code): { readonly source: string; readonly lines: readonly IdLine[]; readonly edit: StructuralTransition | null } {
275
+ const kit = kits.get(code.constructor);
276
+ if (!kit) throw new TypeError("listingOf takes a node a `Code` component built.");
277
+ const view = shown(code, kit);
278
+ return { source: view.source, lines: view.lines, edit: editOf(view) };
279
+ }
516
280
 
517
- /**
518
- * Highlight a range of code — or several at once (e.g.
519
- * `CodeRanges.lines(2).word(5, 1, 3)`) — highlighted as one set: tokens
520
- * within any of the ranges stay at opacity 1, tokens outside dim to
521
- * `dim`. Persistent — call resetHighlight() to undo, or call highlight()
522
- * again with a different range to cross-fade.
523
- */
524
- @command({ args: [{ key: "target", kind: "selector" }, { key: "dim", kind: "number", default: 0.4, min: 0, max: 1, step: 0.01, scale: 100, unit: "%" }] })
525
- highlight(
526
- args: CommandArgs<{ target: CodeRange | Iterable<CodeRange>; dim?: number }> & { duration: number },
527
- ): Command<Record<string, never>> {
528
- this._sync();
529
- const { target: codeRange, dim } = args.data as { target: CodeRange | Iterable<CodeRange>; dim?: number };
530
- const { duration, easing } = args;
531
- const toDim = dim ?? 0.4;
532
- const matchIds = this.tokenIdsInRanges(normalizeCodeRanges(codeRange));
533
- if (matchIds.size === 0) return driveCommand(duration, () => { });
534
-
535
- const fromDim = this.highlightDimOpacity ?? 1;
536
- const hadPrevious = this.highlightedIds.size > 0;
537
- const previousIds = this.highlightedIds;
538
-
539
- const animTokens: AnimToken[] = [];
540
- for (const line of this.tokenLines) {
541
- for (const tok of line.tokens) {
542
- const wasHighlighted = !hadPrevious || previousIds.has(tok.id);
543
- const isHighlighted = matchIds.has(tok.id);
544
- const fromOp = wasHighlighted ? 1 : fromDim;
545
- const toOp = isHighlighted ? 1 : toDim;
546
- if (fromOp === toOp) continue;
547
- animTokens.push(makeAnim(tok.id, { keys: [0, 1], values: [fromOp, toOp] }));
548
- }
549
- }
281
+ /** Every range matching the literal `text` in `source`, in order and not overlapping. Multi-line matches are found too. */
282
+ export function findAllRanges(source: CodeSource, text: string): CodeRange[] {
283
+ const ranges: CodeRange[] = [];
284
+ if (!text) return ranges;
285
+ const joined = normalizeSource(sourceText(source));
286
+ const lineLens = joined.split("\n").map((line) => line.length);
287
+ let from = 0;
288
+ while (true) {
289
+ const idx = joined.indexOf(text, from);
290
+ if (idx === -1) break;
291
+ ranges.push(charOffsetsToRange(idx, idx + text.length, lineLens));
292
+ from = idx + Math.max(1, text.length);
293
+ }
294
+ return ranges;
295
+ }
550
296
 
551
- // Which tokens are dimmed is state the *next* highlight reads to know
552
- // what it is cross-fading from, so it is committed at the end and put
553
- // back below it — a `finally` could only ever have run forwards.
554
- return this.runDim(animTokens, duration, easing, (done) => {
555
- this.highlightDimOpacity = done ? toDim : (hadPrevious ? fromDim : null);
556
- this.highlightedIds = done ? matchIds : previousIds;
557
- });
558
- }
297
+ /** The `index`th range matching `text`, or `null`. */
298
+ export function findRangeAt(source: CodeSource, text: string, index: number): CodeRange | null {
299
+ return findAllRanges(source, text)[index] ?? null;
300
+ }
559
301
 
560
- /**
561
- * Fade all dimmed tokens back to opacity 1 and clear the persistent
562
- * highlight state.
563
- */
564
- @command()
565
- resetHighlight(args: CommandArgs<Record<string, never>> & { duration: number }): Command<Record<string, never>> {
566
- this._sync();
567
- const { duration, easing } = args;
568
- if (this.highlightDimOpacity === null) return driveCommand(duration, () => { });
569
-
570
- const fromDim = this.highlightDimOpacity;
571
- const previousIds = this.highlightedIds;
572
-
573
- const animTokens: AnimToken[] = [];
574
- for (const line of this.tokenLines) {
575
- for (const tok of line.tokens) {
576
- const fromOp = previousIds.has(tok.id) ? 1 : fromDim;
577
- if (fromOp === 1) continue;
578
- animTokens.push(makeAnim(tok.id, { keys: [0, 1], values: [fromOp, 1] }));
579
- }
580
- }
302
+ /** The first range matching `text`, or `null`. */
303
+ export function findFirstRange(source: CodeSource, text: string): CodeRange | null {
304
+ return findRangeAt(source, text, 0);
305
+ }
581
306
 
582
- return this.runDim(animTokens, duration, easing, (done) => {
583
- this.highlightDimOpacity = done ? null : fromDim;
584
- this.highlightedIds = done ? new Set() : previousIds;
585
- });
586
- }
307
+ // ── What a listing shows ────────────────────────────────────────────────────
587
308
 
588
- /**
589
- * Lay a band of `color` behind whole rows: every line a range touches, across
590
- * the block. Persistent, and independent of {@link highlight}'s dimming. A
591
- * second call slides and resizes the bands onto their new rows, pairing them
592
- * in the order given; `resetRowHighlight()` fades them out. A band keeps to
593
- * its lines when an edit moves them.
594
- */
595
- @command({
596
- args: [
597
- { key: "target", kind: "selector" },
598
- { key: "color", kind: "color", default: ROW_BAND_COLOR },
599
- { key: "radius", kind: "number", default: ROW_BAND_RADIUS, min: 0, step: 1 },
600
- ],
601
- })
602
- highlightRows(
603
- args: CommandArgs<{ target: CodeRange | Iterable<CodeRange>; color?: Color; radius?: number }> & { duration: number },
604
- ): Command<Record<string, never>> {
605
- this._sync();
606
- const { target, color, radius } = args.data as { target: CodeRange | Iterable<CodeRange>; color?: Color; radius?: number };
607
- const paint = colorOps.resolve(color ?? ROW_BAND_COLOR);
608
- const bands = this.rowBandsIn(normalizeCodeRanges(target), paint, Math.max(0, radius ?? ROW_BAND_RADIUS));
609
- return this.runRows(this.rowBands, bands, args.duration, args.easing);
610
- }
309
+ interface Kit {
310
+ readonly diff: CodeDiffStrategy;
311
+ readonly phases: CodePhaseStrategy;
312
+ /** The edit from a listing to a source and basis, built once: a `to({ code })` asks for it every frame. */
313
+ readonly edits: WeakMap<IdLine[], Map<string, Map<string, Edited>>>;
314
+ }
611
315
 
612
- /** Fade every row band out and clear them. */
613
- @command()
614
- resetRowHighlight(args: CommandArgs<Record<string, never>> & { duration: number }): Command<Record<string, never>> {
615
- this._sync();
616
- return this.runRows(this.rowBands, [], args.duration, args.easing);
617
- }
316
+ interface Edited {
317
+ readonly transition: StructuralTransition;
318
+ readonly listing: CodeListing;
319
+ }
618
320
 
619
- /**
620
- * Animate the listing to a new source.
621
- *
622
- * The engine behind every editing command, and behind `to({ code })`. Every
623
- * edit is expressed as the source it produces, tokenized, and then *diffed*
624
- * against what is on screen — so a token that survived the edit keeps its
625
- * identity and simply travels to its new column, and only what genuinely
626
- * changed is faded.
627
- *
628
- * The result runs in three phases (see `phaseStrategy`): what is leaving
629
- * fades out, what stays reflows, and only then does what is new arrive.
630
- * Playing them together is what made a replacement read as a cross-dissolve
631
- * of two unrelated listings rather than as an edit being made.
632
- */
633
- private editTo(next: string, duration: number, easing?: EasingFunction): Command<Record<string, never>> {
634
- if (!this.mounted) return driveCommand(duration, () => { });
635
- next = normalizeSource(next);
636
- const from = this.tokenLines;
637
- const fromCode = this.joinedSource();
638
- if (next === fromCode) return driveCommand(duration, () => { });
639
-
640
- const fromBasis = this._linesBasis;
641
- const basis = this._basis();
642
- const edit = this.diffStrategy(from, tokenizeCodeToIdLines(next, this.language, this.theme));
643
-
644
- const transition: StructuralTransition = {
645
- kind: "structural",
646
- from,
647
- to: edit.lines,
648
- removedIds: edit.removedIds,
649
- addedIds: edit.addedIds,
650
- enteringLineIds: edit.newLineIds,
651
- fromColorById: edit.fromColorById,
652
- phases: this.phaseStrategy(edit.removedIds.size > 0, edit.addedIds.size > 0),
653
- progress: 0,
654
- layoutKey: null,
655
- fromLayout: null,
656
- toLayout: null,
657
- };
321
+ /** What the structure resolves from. A command's snapshot and a node's own state view both are one. */
322
+ interface ListingState {
323
+ readonly code: CodeSource;
324
+ readonly language: string;
325
+ readonly theme: CodeTheme;
326
+ readonly listing: CodeListing | null;
327
+ readonly edit: CodeEditFrame | null;
328
+ }
658
329
 
659
- // A re-tokenize triggered by the grammar landing mid-edit would mint fresh
660
- // ids underneath this transition, and the transition is keyed by the ones
661
- // it captured — so `_sync` leaves the structure alone while an edit is in
662
- // flight, and compares the basis recorded here once it settles.
663
-
664
- return driveCommand(duration, (t) => {
665
- this._drive();
666
- const running = t > 0 && t < 1;
667
- const index = this.transitions.indexOf(transition);
668
- if (running && index < 0) this.transitions.push(transition);
669
- else if (!running && index >= 0) this.transitions.splice(index, 1);
670
-
671
- transition.progress = easing ? easing(t) : t;
672
-
673
- // The settle, in both directions: asked for a time before the edit
674
- // starts, the listing is what preceded it; at or past the end, the
675
- // result. A `finally` could only ever have run forwards.
676
- if (t <= 0) {
677
- this.setLines(from, fromCode, fromBasis);
678
- this._writeProp("code", fromCode);
679
- } else {
680
- this.setLines(edit.lines, next, basis);
681
- this._writeProp("code", next);
682
- }
683
- });
684
- }
330
+ interface LayoutState extends ListingState {
331
+ readonly fontSize: number;
332
+ readonly fontFamily: string;
333
+ readonly lineHeight: number;
334
+ readonly letterSpacing: number;
335
+ readonly padding: InsetsResolved;
336
+ readonly showLineNumbers: boolean;
337
+ readonly lineNumberGap: number;
338
+ }
685
339
 
686
- /**
687
- * Put a dim transition on the stack, drive its progress, take it off and
688
- * commit at the end.
689
- *
690
- * A {@link Command} rather than a generator, which is what makes a listing
691
- * scrubbable: membership is a function of `t` (on the stack for `0 < t < 1`,
692
- * off it outside), `settle(done)` replaces the `finally` and takes *which
693
- * way*, and `progress` is assigned from `t` rather than accumulated.
694
- */
695
- private runDim(
696
- tokens: AnimToken[],
697
- duration: number,
698
- easing?: EasingFunction,
699
- settle?: (done: boolean) => void,
700
- ): Command<Record<string, never>> {
701
- if (!this.mounted) return driveCommand(duration, () => { });
702
- const transition = { kind: "dim" as const, tokens, progress: 0 };
703
-
704
- return driveCommand(duration, (t) => {
705
- this._drive();
706
- const running = t > 0 && t < 1;
707
- const index = this.transitions.indexOf(transition);
708
- if (running && index < 0) this.transitions.push(transition);
709
- else if (!running && index >= 0) this.transitions.splice(index, 1);
710
-
711
- transition.progress = easing ? easing(t) : t;
712
- settle?.(t >= 1);
713
- });
714
- }
340
+ interface DrawState extends LayoutState {
341
+ readonly focus: CodeFocus;
342
+ readonly banding: CodeBanding;
343
+ }
715
344
 
716
- /** The same membership rule as {@link runDim}: on the stack strictly inside the run, settled at either end. */
717
- private runRows(
718
- from: RowBand[],
719
- to: RowBand[],
720
- duration: number,
721
- easing?: EasingFunction,
722
- ): Command<Record<string, never>> {
723
- if (!this.mounted || (from.length === 0 && to.length === 0)) return driveCommand(duration, () => { });
724
- const transition: RowsTransition = { kind: "rows", from, to, progress: 0 };
725
-
726
- return driveCommand(duration, (t) => {
727
- this._drive();
728
- const running = t > 0 && t < 1;
729
- const index = this.transitions.indexOf(transition);
730
- if (running && index < 0) this.transitions.push(transition);
731
- else if (!running && index >= 0) this.transitions.splice(index, 1);
732
-
733
- transition.progress = easing ? easing(t) : t;
734
- this.rowBands = t >= 1 ? to : from;
735
- });
736
- }
345
+ /** The structure a frame draws, and the edit it is part-way through. */
346
+ interface Shown {
347
+ readonly source: string;
348
+ readonly lines: IdLine[];
349
+ readonly transition: StructuralTransition | null;
350
+ readonly progress: number;
351
+ }
737
352
 
738
- /**
739
- * Route a tweened `code` through the diff engine.
740
- *
741
- * `to({ code })` is the form an author reaches for first — it is how every
742
- * other prop is animated — and a bare string prop would otherwise land in the
743
- * generic tween's discrete-snap bucket and simply cut at the end. Intercepted
744
- * here it becomes the same three-phase edit the named commands produce, while
745
- * the rest of the step's props tween alongside it untouched.
746
- */
747
- override _prepareStep(
748
- to: Partial<CodeProps>,
749
- duration: number,
750
- easing?: EasingFunction,
751
- ): TweenStepper {
752
- if (!this.mounted) return super._prepareStep(to, duration, easing);
753
- this._sync();
754
- const next = typeof to.code === "string" ? normalizeSource(to.code) : undefined;
755
- if (next === undefined || next === this.joinedSource()) {
756
- return super._prepareStep(to, duration, easing);
757
- }
353
+ /**
354
+ * A `to({ code })` mid-flight comes first: it wrote `code` after any edit
355
+ * command did. Then an edit command in flight, then the settled listing.
356
+ */
357
+ function shown(s: ListingState, kit: Kit): Shown {
358
+ const code = s.code;
359
+ if (typeof code !== "string") {
360
+ const { transition } = edited(settled(s, code.from, kit), code.to, basisOf(s), kit);
361
+ return { source: code.to, lines: transition.to, transition, progress: code.t };
362
+ }
363
+ if (s.edit) return { source: normalizeSource(code), lines: s.edit.transition.to, transition: s.edit.transition, progress: s.edit.progress };
364
+ const listing = settled(s, normalizeSource(code), kit);
365
+ return { source: listing.source, lines: listing.lines, transition: null, progress: 1 };
366
+ }
758
367
 
759
- const rest: Partial<CodeProps> = { ...to };
760
- delete rest.code;
761
- // Prepared before the edit, so a step that also moves `fontSize` has
762
- // snapshotted its own start value against the listing that is still on
763
- // screen.
764
- const others = super._prepareStep(rest, duration, easing);
765
- const edit = this.editTo(next, duration, easing)._stepper();
766
-
767
- return {
768
- seek: (elapsed: number) => {
769
- others.seek(elapsed);
770
- edit.seek(elapsed);
771
- },
772
- advance: (dt: number): boolean => {
773
- const othersDone = others.advance(dt);
774
- const editDone = edit.advance(dt);
775
- return othersDone && editDone;
776
- },
777
- };
778
- }
368
+ function editOf(view: Shown): StructuralTransition | null {
369
+ return view.transition ? { ...view.transition, progress: view.progress } : null;
370
+ }
779
371
 
780
- // ── Source queries ──────────────────────────────────────────────────────
781
-
782
- /**
783
- * Find every range matching the literal string `text` in the current
784
- * source. Multi-line matches are supported.
785
- */
786
- findAllRanges(text: string): CodeRange[] {
787
- const ranges: CodeRange[] = [];
788
- if (!text) return ranges;
789
- this._sync();
790
- const source = this.joinedSource();
791
- const lineLens = this.lineLengths();
792
- let from = 0;
793
- while (true) {
794
- const idx = source.indexOf(text, from);
795
- if (idx === -1) break;
796
- ranges.push(charOffsetsToRange(idx, idx + text.length, lineLens));
797
- from = idx + Math.max(1, text.length);
798
- }
799
- return ranges;
800
- }
372
+ /** The listing a command starts from. */
373
+ function current(s: ListingState, kit: Kit): CodeListing {
374
+ return settled(s, normalizeSource(sourceText(s.code)), kit);
375
+ }
801
376
 
802
- /** Find the `index`th range matching `text`. Returns null if not found. */
803
- findRangeAt(text: string, index: number): CodeRange | null {
804
- const all = this.findAllRanges(text);
805
- return all[index] ?? null;
806
- }
377
+ /**
378
+ * The structure `source` settles on. Until a listing command has acted, the
379
+ * props are all there is; after one, it is the listing that command left,
380
+ * recoloured keeping its ids when only the theme moved, and diffed onward
381
+ * when the source has (a `to({ code })` that landed, a binding).
382
+ */
383
+ function settled(s: ListingState, source: string, kit: Kit): CodeListing {
384
+ const basis = basisOf(s);
385
+ const pinned = s.listing;
386
+ if (!pinned) return derived(source, basis);
387
+ if (pinned.source !== source) return edited(pinned, source, basis, kit).listing;
388
+ if (sameBasis(pinned.basis, basis)) return pinned;
389
+ if (pinned.basis.language === basis.language && pinned.basis.highlighted === basis.highlighted) return recoloured(pinned, basis);
390
+ return derived(source, basis);
391
+ }
807
392
 
808
- /** Find the first range matching `text`. Returns null if not found. */
809
- findFirstRange(text: string): CodeRange | null {
810
- return this.findRangeAt(text, 0);
811
- }
393
+ function basisOf(s: { readonly language: string; readonly theme: CodeTheme }): CodeTokenBasis {
394
+ return { language: s.language, theme: s.theme, highlighted: canHighlight(s.language, s.theme) };
395
+ }
812
396
 
813
- private joinedSource(): string {
814
- return this._linesSource;
815
- }
397
+ function sameBasis(a: CodeTokenBasis, b: CodeTokenBasis): boolean {
398
+ return a.language === b.language && a.theme === b.theme && a.highlighted === b.highlighted;
399
+ }
816
400
 
817
- private lineLengths(): number[] {
818
- return this.tokenLines.map(line =>
819
- line.tokens.reduce((acc, t) => acc + t.content.length, 0),
820
- );
821
- }
401
+ /** The source `code` names: where a `to({ code })` is heading, mid-tween. */
402
+ function sourceText(code: CodeSource): string {
403
+ return typeof code === "string" ? code : code.to;
404
+ }
822
405
 
823
- /** Character offset of a 1-indexed (line, col), clamped into the document. */
824
- private offsetAt(position: [number, number]): number {
825
- const lens = this.lineLengths();
826
- if (lens.length === 0) return 0;
827
- const [rawLine, rawCol] = position;
828
- const li = Math.max(0, Math.min(lens.length - 1, rawLine - 1));
829
- let offset = 0;
830
- for (let k = 0; k < li; k++) offset += lens[k] + 1;
831
- return offset + Math.max(0, Math.min(lens[li], rawCol - 1));
832
- }
406
+ /**
407
+ * Mid-tween `code` holds both sources, so the frame can draw the edit between
408
+ * them; at either end it is a source again.
409
+ */
410
+ function blendSource(from: CodeSource, to: CodeSource, t: number): CodeSource {
411
+ const leaving = sourceText(from);
412
+ const arriving = sourceText(to);
413
+ const a = normalizeSource(leaving);
414
+ const b = normalizeSource(arriving);
415
+ // Nothing to edit: it snaps at the end, as any text does.
416
+ if (a === b) return t >= 1 ? arriving : leaving;
417
+ if (t <= 0) return a;
418
+ if (t >= 1) return b;
419
+ return { from: a, to: b, t };
420
+ }
833
421
 
834
- /**
835
- * Resolve one or more CodeRanges to the set of token ids whose content
836
- * overlaps any of them. Tokens that partially overlap are included.
837
- */
838
- private tokenIdsInRanges(codeRanges: CodeRange[]): Set<number> {
839
- const result = new Set<number>();
840
- const lineLens = this.lineLengths();
841
- if (lineLens.length === 0) return result;
842
- const offsets = codeRanges
843
- .map(r => rangeToCharOffsets(r, lineLens))
844
- .filter(({ start, end }) => end > start);
845
- if (offsets.length === 0) return result;
846
-
847
- // Walk tokens with running offsets in the joined string, testing each
848
- // token against every requested range's offsets.
849
- let off = 0;
850
- for (let li = 0; li < this.tokenLines.length; li++) {
851
- const line = this.tokenLines[li];
852
- for (const tok of line.tokens) {
853
- const tStart = off;
854
- const tEnd = off + tok.content.length;
855
- if (offsets.some(({ start, end }) => tEnd > start && tStart < end)) result.add(tok.id);
856
- off = tEnd;
857
- }
858
- if (li < this.tokenLines.length - 1) off += 1; // newline
859
- }
860
- return result;
861
- }
422
+ const DERIVED = new Map<string, Map<string, CodeListing>>();
423
+ /** Sources kept tokenized per basis, oldest dropped first; a bound `code` can name any number of them. */
424
+ const DERIVED_LISTINGS = 256;
862
425
 
863
- // ── Drawing ─────────────────────────────────────────────────────────────
864
-
865
- /** One band per range, over every line it touches; a range past the end of the listing gives none. */
866
- private rowBandsIn(codeRanges: CodeRange[], color: RowBand["color"], radius: number): RowBand[] {
867
- const count = this.tokenLines.length;
868
- const bands: RowBand[] = [];
869
- for (const range of codeRanges) {
870
- const first = Math.max(1, Math.round(range.startLine ?? 1));
871
- const last = Math.min(count, range.endLine == null || range.endLine === Infinity ? count : Math.round(range.endLine));
872
- if (first > last) continue;
873
- bands.push({ startId: this.tokenLines[first - 1].id, endId: this.tokenLines[last - 1].id, color, radius });
874
- }
875
- return bands;
876
- }
426
+ /** The props' own listing, the same object (and ids) each time it is asked for again. */
427
+ function derived(source: string, basis: CodeTokenBasis): CodeListing {
428
+ return recall(DERIVED, basisKey(basis), source, DERIVED_LISTINGS, () => ({ source, lines: tokenize(source, basis), basis }));
429
+ }
877
430
 
878
- /**
879
- * Thin delegator: everything about *how* a frame is painted (settled or
880
- * mid structural-edit, entry/exit motion, colour cross-fade) lives in
881
- * `drawCode` (the engine's `render.ts`) as a pure function over plain
882
- * state — this just gathers that state from the node's own instance
883
- * fields and caches.
884
- */
885
- protected drawSelf(draw: RenderContext2D): void {
886
- this.advanceCache.sync(this.advanceCache.signature(this.fontSize, this.fontFamily));
887
- drawCode(draw, {
888
- tokenLines: this.tokenLines,
889
- metrics: this.metrics(),
890
- advanceCache: this.advanceCache,
891
- ...this.frameLayout(draw),
892
- tokenStates: resolveTokenStates(this.tokenLines, this.transitions, this.highlightDimOpacity, this.highlightedIds),
893
- highlightActive: this.highlightDimOpacity !== null || this.transitions.some(tr => tr.kind === "dim"),
894
- rowBands: this.rowBands,
895
- rowsEdit: this.activeRows(),
896
- boxW: this.layoutBounds.width,
897
- });
898
- }
431
+ const RECOLOURED = new WeakMap<IdLine[], Map<string, Map<string, CodeListing>>>();
432
+
433
+ /** `pinned` in another theme: the same text split the same way keeps the ids a highlight or a band names. */
434
+ function recoloured(pinned: CodeListing, basis: CodeTokenBasis): CodeListing {
435
+ let shelf = RECOLOURED.get(pinned.lines);
436
+ if (!shelf) RECOLOURED.set(pinned.lines, shelf = new Map());
437
+ return recall(shelf, basisKey(basis), pinned.source, 4, () => {
438
+ const lines = tokenize(pinned.source, basis);
439
+ adoptIds(pinned.lines, lines);
440
+ return { source: pinned.source, lines, basis };
441
+ });
442
+ }
899
443
 
900
- /**
901
- * Whether a listing command has applied since the timeline last restored the
902
- * props.
903
- *
904
- * A slot rather than a field because slots are all a restore puts back. The
905
- * structure, highlight and transitions live outside the props, and only a
906
- * command that has started writes them, so before the first one starts (or
907
- * after a seek back past it) they still hold whatever the last evaluation
908
- * left — the end of every command, after compile. This reads false again
909
- * there, and `_sync` derives them from the props instead.
910
- */
911
- declare private readonly _driven: boolean;
912
-
913
- /** Each source the props have named, tokenized once, so a listing derived again keeps the ids a highlight selected. */
914
- private readonly _derived = new Map<string, { language: string; theme: CodeTheme; highlighted: boolean; lines: IdLine[] }>();
915
-
916
- /** The first command to apply after a restore starts from the props' listing. */
917
- private _drive(): void {
918
- this._sync();
919
- this._writeProp("_driven", true);
920
- }
444
+ function edited(from: CodeListing, next: string, basis: CodeTokenBasis, kit: Kit): Edited {
445
+ let shelf = kit.edits.get(from.lines);
446
+ if (!shelf) kit.edits.set(from.lines, shelf = new Map());
447
+ return recall(shelf, basisKey(basis), next, 16, () => buildEdit(kit, from.lines, next, basis));
448
+ }
921
449
 
922
- /**
923
- * Bring the settled structure up to the props it is derived from.
924
- *
925
- * Pulled from every reader rather than pushed from a prop write, because
926
- * `code`, `language` and `theme` can each be tweened or bound, and neither
927
- * has a write to hang a subscription on. Never mid-edit: re-tokenizing mints
928
- * fresh ids, and an in-flight transition is keyed by the ones it captured.
929
- */
930
- private _sync(): void {
931
- const code = this._normalised();
932
- if (!this._driven) {
933
- this.transitions.length = 0;
934
- this.highlightDimOpacity = null;
935
- if (this.highlightedIds.size > 0) this.highlightedIds = new Set();
936
- if (this.rowBands.length > 0) this.rowBands = [];
937
- this.setLines(this._structureFor(code), code);
938
- } else if (!this.activeEdit()) {
939
- const basis = this._basis();
940
- const was = this._linesBasis;
941
- if (this._linesSource === code && was.language === basis.language && was.theme === basis.theme && was.highlighted === basis.highlighted) return;
942
- const lines = this._structureFor(code);
943
- // The same text split the same way, only coloured differently: the
944
- // tokens are the ones a highlight or a transition already names.
945
- if (this._linesSource === code && was.language === basis.language && was.highlighted === basis.highlighted) {
946
- adoptIds(this.tokenLines, lines);
947
- }
948
- this.setLines(lines, code, basis);
949
- }
950
- }
450
+ function buildEdit(kit: Kit, from: IdLine[], next: string, basis: CodeTokenBasis): Edited {
451
+ const edit = kit.diff(from, tokenize(next, basis));
452
+ const transition: StructuralTransition = {
453
+ kind: "structural",
454
+ from,
455
+ to: edit.lines,
456
+ removedIds: edit.removedIds,
457
+ addedIds: edit.addedIds,
458
+ enteringLineIds: edit.newLineIds,
459
+ fromColorById: edit.fromColorById,
460
+ phases: kit.phases(edit.removedIds.size > 0, edit.addedIds.size > 0),
461
+ progress: 0,
462
+ layoutKey: null,
463
+ fromLayout: null,
464
+ toLayout: null,
465
+ };
466
+ return { transition, listing: { source: next, lines: edit.lines, basis } };
467
+ }
951
468
 
952
- private _normalised(): string {
953
- const code = this.code;
954
- if (code !== this._rawCode) {
955
- this._rawCode = code;
956
- this._normalCode = normalizeSource(code);
957
- }
958
- return this._normalCode;
959
- }
469
+ function tokenize(source: string, basis: CodeTokenBasis): IdLine[] {
470
+ // Best effort outside the asset pipeline (a test, a headless measure): on the timeline `load` has the grammar in first.
471
+ if (!basis.highlighted) ensureHighlighter(undefined, [basis.language]).catch(() => { });
472
+ return tokenizeCodeToIdLines(source, basis.language, basis.theme);
473
+ }
960
474
 
961
- private _basis(): TokenBasis {
962
- return { language: this.language, theme: this.theme, highlighted: canHighlight(this.language, this.theme) };
963
- }
475
+ const styleIds = new WeakMap<object, number>();
476
+ let nextStyleId = 1;
964
477
 
965
- private _structureFor(code: string): IdLine[] {
966
- const { language, theme, highlighted } = this._basis();
967
- let entry = this._derived.get(code);
968
- if (!entry || entry.language !== language || entry.theme !== theme || entry.highlighted !== highlighted) {
969
- entry = {
970
- language,
971
- theme,
972
- highlighted,
973
- lines: tokenizeCodeToIdLines(code, language, theme),
974
- };
975
- this._derived.delete(code);
976
- this._derived.set(code, entry);
977
- if (this._derived.size > DERIVED_LISTINGS) this._derived.delete(this._derived.keys().next().value as string);
978
- }
979
- return entry.lines;
478
+ function basisKey(basis: CodeTokenBasis): string {
479
+ let theme: string;
480
+ if (typeof basis.theme === "string") theme = `name:${basis.theme}`;
481
+ else {
482
+ let id = styleIds.get(basis.theme);
483
+ if (id === undefined) styleIds.set(basis.theme, id = nextStyleId++);
484
+ theme = `style:${id}`;
980
485
  }
486
+ return `${basis.language}\n${basis.highlighted ? 1 : 0}\n${theme}`;
981
487
  }
982
488
 
983
- /** What a structure was tokenized with: the grammar, the theme and whether the grammar had landed. */
984
- interface TokenBasis {
985
- language: string;
986
- theme: CodeTheme;
987
- highlighted: boolean;
489
+ /** Memoized by basis, then by source; a basis keeps `limit` sources, least recently asked for dropped first. */
490
+ function recall<T>(shelf: Map<string, Map<string, T>>, basis: string, source: string, limit: number, make: () => T): T {
491
+ let row = shelf.get(basis);
492
+ if (!row) shelf.set(basis, row = new Map());
493
+ const hit = row.get(source);
494
+ if (hit !== undefined) {
495
+ row.delete(source);
496
+ row.set(source, hit);
497
+ return hit;
498
+ }
499
+ const made = make();
500
+ row.set(source, made);
501
+ if (row.size > limit) row.delete(row.keys().next().value as string);
502
+ return made;
988
503
  }
989
504
 
990
505
  /** Carry `from`'s line and token ids onto `to` when the two spell the same tokens. */
@@ -1002,18 +517,164 @@ function adoptIds(from: IdLine[], to: IdLine[]): void {
1002
517
  }
1003
518
  }
1004
519
 
1005
- /** Sources a node keeps tokenized, oldest dropped first; a bound `code` can name any number of them. */
1006
- const DERIVED_LISTINGS = 16;
520
+ // ── Commands ────────────────────────────────────────────────────────────────
521
+
522
+ /** What a listing command writes at a point of its own eased time. */
523
+ interface ListingWrites {
524
+ readonly code?: string;
525
+ readonly listing?: CodeListing | null;
526
+ readonly edit?: CodeEditFrame | null;
527
+ readonly focus?: CodeFocus;
528
+ readonly banding?: CodeBanding;
529
+ }
530
+
531
+ type Frame = (t: number) => ListingWrites;
532
+
533
+ /**
534
+ * Each command writes the listing it acted on, at every time it is asked for,
535
+ * so the ids it captured are the ones drawn; before it starts the timeline has
536
+ * put back the props, and the listing is derived from them again.
537
+ */
538
+ function editFrame(kit: Kit, seen: CodeListing, source: string, basis: CodeTokenBasis): Frame | null {
539
+ const next = normalizeSource(source);
540
+ if (next === seen.source) return null;
541
+ const { transition, listing } = buildEdit(kit, seen.lines, next, basis);
542
+ // Three phases (see `phaseStrategy`): what leaves fades out, what stays reflows, then what is new arrives.
543
+ return (t) => (t <= 0 ? { code: seen.source, listing: seen, edit: null }
544
+ : t >= 1 ? { code: next, listing, edit: null }
545
+ : { code: next, listing, edit: { transition, progress: t } });
546
+ }
547
+
548
+ function eraseFrame(kit: Kit, state: ListingState, target: CodeRange): Frame | null {
549
+ const seen = current(state, kit);
550
+ const source = seen.source;
551
+ let { start, end } = rangeToCharOffsets(target, lineLengths(seen.lines));
552
+ // `lines(2)` resolves to the characters of line 2: the row goes too, as an editor would close the gap. That is also what makes a blank row removable.
553
+ const atLineStart = start === 0 || source[start - 1] === "\n";
554
+ const atLineEnd = end === source.length || source[end] === "\n";
555
+ if (atLineStart && atLineEnd) {
556
+ if (end < source.length) end += 1;
557
+ else if (start > 0) start -= 1;
558
+ } else if (end <= start) {
559
+ return null;
560
+ }
561
+ if (end <= start) return null;
562
+ return editFrame(kit, seen, source.slice(0, start) + source.slice(end), basisOf(state));
563
+ }
564
+
565
+ function highlightFrame(kit: Kit, state: ListingState & { readonly focus: CodeFocus }, target: CodeTarget | undefined, dim: number): Frame | null {
566
+ const seen = current(state, kit);
567
+ const toDim = dim ?? 0.4;
568
+ const matchIds = tokenIdsInRanges(seen.lines, normalizeCodeRanges(target));
569
+ if (matchIds.size === 0) return null;
570
+
571
+ const previous = state.focus;
572
+ const fromDim = previous.dim ?? 1;
573
+ const hadPrevious = previous.ids.size > 0;
574
+ const tokens: AnimToken[] = [];
575
+ for (const line of seen.lines) {
576
+ for (const tok of line.tokens) {
577
+ const fromOp = !hadPrevious || previous.ids.has(tok.id) ? 1 : fromDim;
578
+ const toOp = matchIds.has(tok.id) ? 1 : toDim;
579
+ if (fromOp === toOp) continue;
580
+ tokens.push(makeAnim(tok.id, { keys: [0, 1], values: [fromOp, toOp] }));
581
+ }
582
+ }
583
+ // Which tokens are dimmed is what the next highlight cross-fades from, so it is committed at the end and put back below it.
584
+ const before: CodeFocus = { dim: hadPrevious ? fromDim : null, ids: previous.ids, fade: null };
585
+ const done: CodeFocus = { dim: toDim, ids: matchIds, fade: null };
586
+ return (t) => ({
587
+ listing: seen,
588
+ focus: t <= 0 ? before : t >= 1 ? done : { ...before, fade: { kind: "dim", tokens, progress: t } },
589
+ });
590
+ }
591
+
592
+ function resetHighlightFrame(kit: Kit, state: ListingState & { readonly focus: CodeFocus }): Frame | null {
593
+ const previous = state.focus;
594
+ if (previous.dim === null) return null;
595
+ const seen = current(state, kit);
596
+ const fromDim = previous.dim;
597
+ const tokens: AnimToken[] = [];
598
+ for (const line of seen.lines) {
599
+ for (const tok of line.tokens) {
600
+ const fromOp = previous.ids.has(tok.id) ? 1 : fromDim;
601
+ if (fromOp === 1) continue;
602
+ tokens.push(makeAnim(tok.id, { keys: [0, 1], values: [fromOp, 1] }));
603
+ }
604
+ }
605
+ const before: CodeFocus = { dim: fromDim, ids: previous.ids, fade: null };
606
+ return (t) => ({
607
+ listing: seen,
608
+ focus: t >= 1 ? NO_FOCUS : t <= 0 ? before : { ...before, fade: { kind: "dim", tokens, progress: t } },
609
+ });
610
+ }
611
+
612
+ function rowsFrame(seen: CodeListing, from: RowBand[], to: RowBand[]): Frame | null {
613
+ if (from.length === 0 && to.length === 0) return null;
614
+ return (t) => ({
615
+ listing: seen,
616
+ banding: t >= 1 ? { bands: to, fade: null }
617
+ : t <= 0 ? { bands: from, fade: null }
618
+ : { bands: from, fade: { kind: "rows", from, to, progress: t } },
619
+ });
620
+ }
621
+
622
+ function lineLengths(lines: IdLine[]): number[] {
623
+ return lines.map((line) => line.tokens.reduce((acc, t) => acc + t.content.length, 0));
624
+ }
625
+
626
+ /** Character offset of a 1-indexed (line, col), clamped into the document. */
627
+ function offsetAt(lines: IdLine[], position: [number, number]): number {
628
+ const lens = lineLengths(lines);
629
+ if (lens.length === 0) return 0;
630
+ const [rawLine, rawCol] = position;
631
+ const li = Math.max(0, Math.min(lens.length - 1, rawLine - 1));
632
+ let offset = 0;
633
+ for (let k = 0; k < li; k++) offset += lens[k] + 1;
634
+ return offset + Math.max(0, Math.min(lens[li], rawCol - 1));
635
+ }
636
+
637
+ /** The ids of every token any of `codeRanges` overlaps, partly or wholly. */
638
+ function tokenIdsInRanges(lines: IdLine[], codeRanges: CodeRange[]): Set<number> {
639
+ const result = new Set<number>();
640
+ const lineLens = lineLengths(lines);
641
+ if (lineLens.length === 0) return result;
642
+ const offsets = codeRanges
643
+ .map((r) => rangeToCharOffsets(r, lineLens))
644
+ .filter(({ start, end }) => end > start);
645
+ if (offsets.length === 0) return result;
646
+
647
+ let off = 0;
648
+ for (let li = 0; li < lines.length; li++) {
649
+ for (const tok of lines[li].tokens) {
650
+ const tStart = off;
651
+ const tEnd = off + tok.content.length;
652
+ if (offsets.some(({ start, end }) => tEnd > start && tStart < end)) result.add(tok.id);
653
+ off = tEnd;
654
+ }
655
+ if (li < lines.length - 1) off += 1;
656
+ }
657
+ return result;
658
+ }
659
+
660
+ /** One band per range, over every line it touches; a range past the end of the listing gives none. */
661
+ function rowBandsIn(lines: IdLine[], codeRanges: CodeRange[], color: NormalizedColor, radius: number): RowBand[] {
662
+ const count = lines.length;
663
+ const bands: RowBand[] = [];
664
+ for (const range of codeRanges) {
665
+ const first = Math.max(1, Math.round(range.startLine ?? 1));
666
+ const last = Math.min(count, range.endLine == null || range.endLine === Infinity ? count : Math.round(range.endLine));
667
+ if (first > last) continue;
668
+ bands.push({ startId: lines[first - 1].id, endId: lines[last - 1].id, color, radius });
669
+ }
670
+ return bands;
671
+ }
1007
672
 
1008
673
  /**
1009
- * Normalize `highlight()`'s `codeRange` argument to a plain array: a single
1010
- * `CodeRange` (a plain object, not iterable) becomes a one-element array; a
1011
- * `CodeRangeChain`/plain array of ranges spreads as-is. `CodeRange` and
1012
- * `CodeRangeChain` are distinguished by iterability, not `instanceof` — a
1013
- * bare array of `CodeRange`s (no chain) works the same way. The `{ list }` shape
1014
- * a chain used to serialise as is read as the chain it came from.
674
+ * A single range (a plain object) as a one-element array; a chain or an array
675
+ * of ranges as itself; the `{ list }` a chain serialises as, as that chain.
1015
676
  */
1016
- function normalizeCodeRanges(codeRange: CodeRange | Iterable<CodeRange> | { list: CodeRange[] }): CodeRange[] {
677
+ function normalizeCodeRanges(codeRange: CodeTarget | undefined): CodeRange[] {
1017
678
  const maybeIterable = codeRange as Partial<Iterable<CodeRange>>;
1018
679
  if (typeof maybeIterable[Symbol.iterator] === "function") {
1019
680
  return [...(codeRange as Iterable<CodeRange>)];
@@ -1036,3 +697,158 @@ function grammarLoader(language: string): () => Promise<void> {
1036
697
  return load;
1037
698
  }
1038
699
 
700
+ // ── Geometry and drawing ────────────────────────────────────────────────────
701
+
702
+ interface Layouts {
703
+ readonly from: CodeLayout;
704
+ readonly to: CodeLayout;
705
+ }
706
+
707
+ /**
708
+ * A node's measurements, kept between frames: the advance of each token, and
709
+ * the layouts last built, reused while what they were built from is unchanged.
710
+ */
711
+ interface Measured {
712
+ readonly advances: TokenAdvanceCache;
713
+ measurer: Measurer | null;
714
+ /** The measurer of the node's last measure, as the engine's helpers take one. */
715
+ scope: MeasureContext2D | null;
716
+ settled: { readonly lines: IdLine[]; readonly key: string; readonly layout: CodeLayout } | null;
717
+ edit: { readonly transition: StructuralTransition; readonly key: string; readonly from: CodeLayout; readonly to: CodeLayout } | null;
718
+ }
719
+
720
+ /** By the node's state view, one object per node that `measure` and `render` are both handed. */
721
+ const measuredBy = new WeakMap<object, Measured>();
722
+
723
+ function measuredOf(state: object): Measured {
724
+ let found = measuredBy.get(state);
725
+ if (!found) measuredBy.set(state, found = { advances: new TokenAdvanceCache(), measurer: null, scope: null, settled: null, edit: null });
726
+ return found;
727
+ }
728
+
729
+ function metricsOf(s: LayoutState): CodeMetrics {
730
+ return {
731
+ fontSize: s.fontSize,
732
+ fontFamily: s.fontFamily,
733
+ lineHeight: s.lineHeight,
734
+ letterSpacing: s.letterSpacing,
735
+ padding: s.padding,
736
+ showLineNumbers: s.showLineNumbers,
737
+ lineNumberGap: s.lineNumberGap,
738
+ };
739
+ }
740
+
741
+ /**
742
+ * The one or two layouts a frame is drawn from: a settled frame has one, a
743
+ * frame inside an edit two (where every token was, and where it is going).
744
+ * `null` for a node never measured, which has nothing to measure them with.
745
+ */
746
+ function layoutsOf(measured: Measured, view: Shown, m: CodeMetrics): Layouts | null {
747
+ const signature = measured.advances.signature(m.fontSize, m.fontFamily);
748
+ measured.advances.sync(signature);
749
+ const key = `${metricsSignature(m)}|${signature}`;
750
+ const scope = measured.scope;
751
+ if (!view.transition) {
752
+ const hit = measured.settled;
753
+ if (hit && hit.lines === view.lines && hit.key === key) return { from: hit.layout, to: hit.layout };
754
+ if (!scope) return null;
755
+ const layout = layoutCode(view.lines, m, measured.advances, scope);
756
+ measured.settled = { lines: view.lines, key, layout };
757
+ return { from: layout, to: layout };
758
+ }
759
+ const hit = measured.edit;
760
+ if (hit && hit.transition === view.transition && hit.key === key) return hit;
761
+ if (!scope) return null;
762
+ const both = {
763
+ transition: view.transition,
764
+ key,
765
+ from: layoutCode(view.transition.from, m, measured.advances, scope),
766
+ to: layoutCode(view.transition.to, m, measured.advances, scope),
767
+ };
768
+ measured.edit = both;
769
+ return both;
770
+ }
771
+
772
+ function measureListing(measurer: Measurer, s: LayoutState, kit: Kit): Size2D {
773
+ const measured = measuredOf(s);
774
+ if (measured.measurer !== measurer) {
775
+ measured.measurer = measurer;
776
+ measured.scope = {
777
+ measureText: (text, fontSize, fontFamily, fontWeight, letterSpacing) =>
778
+ measurer.text(text, { fontFamily, fontSize, fontWeight, letterSpacing }),
779
+ };
780
+ }
781
+ const view = shown(s, kit);
782
+ const m = metricsOf(s);
783
+ const layouts = layoutsOf(measured, view, m);
784
+ if (!layouts) return { width: 0, height: 0 };
785
+ const t = moveProgress(view.transition ? { phases: view.transition.phases, progress: view.progress } : null);
786
+ const innerW = view.transition ? lerpNumber(layouts.from.innerW, layouts.to.innerW, t) : layouts.to.innerW;
787
+ const innerH = view.transition ? lerpNumber(layouts.from.innerH, layouts.to.innerH, t) : layouts.to.innerH;
788
+ return { width: innerW + m.padding.left + m.padding.right, height: innerH + m.padding.top + m.padding.bottom };
789
+ }
790
+
791
+ const NO_PAINT: Paint.PaintState = { fill: [], stroke: [], shadow: [], overlay: [], start: 0, end: 1, clip: false };
792
+ const NOTHING = (): void => { };
793
+
794
+ function drawListing(ctx: RenderContext, s: DrawState, kit: Kit): void {
795
+ const measured = measuredOf(s);
796
+ const view = shown(s, kit);
797
+ const m = metricsOf(s);
798
+ const layouts = layoutsOf(measured, view, m);
799
+ // Paints nothing: it declares the outline picking and backdrop effects read.
800
+ Paint.draw(ctx, NO_PAINT, null, { clipShape: outlineOf(view, layouts, m, ctx.size), children: NOTHING });
801
+ const scope = measured.scope;
802
+ if (!layouts || !scope) return;
803
+ const { focus, banding } = s;
804
+ drawCode({ draw: (graphics) => ctx.draw(graphics), measureText: scope.measureText }, {
805
+ tokenLines: view.lines,
806
+ metrics: m,
807
+ advanceCache: measured.advances,
808
+ from: layouts.from,
809
+ to: layouts.to,
810
+ edit: editOf(view),
811
+ tokenStates: resolveTokenStates(view.lines, focus.fade ? [focus.fade] : [], focus.dim, focus.ids),
812
+ highlightActive: focus.dim !== null || focus.fade !== null,
813
+ rowBands: banding.bands,
814
+ rowsEdit: banding.fade,
815
+ boxW: ctx.size.width,
816
+ });
817
+ }
818
+
819
+ /**
820
+ * A listing is grabbed by its text, line by ragged line: each line a slot as
821
+ * wide as its ink, plus the gutter where numbers show, inside the box. Code is
822
+ * mostly whitespace, and its empty corners would swallow clicks meant for what
823
+ * is behind it. Mid-edit, or before it is laid out, the box.
824
+ */
825
+ function outlineOf(view: Shown, layouts: Layouts | null, m: CodeMetrics, size: Size2D): Graphics2D {
826
+ const box = { x: 0, y: 0, width: size.width, height: size.height };
827
+ if (view.transition || !layouts) return new Graphics2D().rect(box);
828
+ const layout = layouts.to;
829
+ const half = (m.fontSize * m.lineHeight) / 2;
830
+ const gutter = m.showLineNumbers ? layout.gutter : 0;
831
+ const left = Math.max(layout.startX - gutter, -size.width / 2);
832
+ const outline = new Graphics2D();
833
+ let lines = 0;
834
+ for (let i = 0; i < layout.lineY.length; i++) {
835
+ const ink = layout.lineW[i] ?? 0;
836
+ if (ink + gutter <= 0) continue;
837
+ const right = Math.min(layout.startX + ink, size.width / 2);
838
+ const y = layout.lineY[i];
839
+ const top = Math.min(y + half, size.height / 2);
840
+ const bottom = Math.max(y - half, -size.height / 2);
841
+ if (right < left || top < bottom) continue;
842
+ // The row's own centre where the box leaves it whole, so a whole row is tested at its own centre.
843
+ const whole = top === y + half && bottom === y - half;
844
+ outline.rect({
845
+ x: (left + right) / 2,
846
+ y: whole ? y : (top + bottom) / 2,
847
+ width: right - left,
848
+ height: whole ? 2 * half : top - bottom,
849
+ });
850
+ lines++;
851
+ }
852
+ // No line has ink: the box with itself cut away, so nothing is grabbed (an empty outline would fall back to the box).
853
+ return lines > 0 ? outline : new Graphics2D().rect(box).rect(box).cut();
854
+ }