@motionscript/code 0.0.0-stage → 0.1.0-alpha.0

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.
Files changed (103) hide show
  1. package/CHANGELOG.md +5 -0
  2. package/LICENSE +201 -0
  3. package/README.md +76 -3
  4. package/dist/browser/chunks/chunk-HET2RCSD.js +2 -0
  5. package/dist/browser/chunks/chunk-HET2RCSD.js.map +7 -0
  6. package/dist/browser/chunks/chunk-SYZUZB3M.js +2 -0
  7. package/dist/browser/chunks/chunk-SYZUZB3M.js.map +7 -0
  8. package/dist/browser/chunks/dist-3F5TQHM6.js +2 -0
  9. package/dist/browser/chunks/dist-3F5TQHM6.js.map +7 -0
  10. package/dist/browser/chunks/dist-3SIR23P4.js +2 -0
  11. package/dist/browser/chunks/dist-3SIR23P4.js.map +7 -0
  12. package/dist/browser/chunks/dist-AQRNACF3.js +2 -0
  13. package/dist/browser/chunks/dist-AQRNACF3.js.map +7 -0
  14. package/dist/browser/chunks/dist-B46VH2YP.js +2 -0
  15. package/dist/browser/chunks/dist-B46VH2YP.js.map +7 -0
  16. package/dist/browser/chunks/dist-FH6BHJ6A.js +7 -0
  17. package/dist/browser/chunks/dist-FH6BHJ6A.js.map +7 -0
  18. package/dist/browser/chunks/dist-FQDUBZKU.js +2 -0
  19. package/dist/browser/chunks/dist-FQDUBZKU.js.map +7 -0
  20. package/dist/browser/chunks/dist-GPNEVCJI.js +2 -0
  21. package/dist/browser/chunks/dist-GPNEVCJI.js.map +7 -0
  22. package/dist/browser/chunks/dist-LRSXSDHT.js +2 -0
  23. package/dist/browser/chunks/dist-LRSXSDHT.js.map +7 -0
  24. package/dist/browser/chunks/dist-N4CNBNHL.js +2 -0
  25. package/dist/browser/chunks/dist-N4CNBNHL.js.map +7 -0
  26. package/dist/browser/chunks/dist-OXJDTPQ6.js +2 -0
  27. package/dist/browser/chunks/dist-OXJDTPQ6.js.map +7 -0
  28. package/dist/browser/chunks/dist-SH7H4MRK.js +2 -0
  29. package/dist/browser/chunks/dist-SH7H4MRK.js.map +7 -0
  30. package/dist/browser/chunks/dist-UG3NTKWL.js +2 -0
  31. package/dist/browser/chunks/dist-UG3NTKWL.js.map +7 -0
  32. package/dist/browser/chunks/dist-W5ZXIMV7.js +2 -0
  33. package/dist/browser/chunks/dist-W5ZXIMV7.js.map +7 -0
  34. package/dist/browser/index.js +8 -0
  35. package/dist/browser/index.js.map +7 -0
  36. package/dist/browser/manifest.json +11 -0
  37. package/dist/code-range.d.ts +69 -0
  38. package/dist/code-range.d.ts.map +1 -0
  39. package/dist/code-range.js +124 -0
  40. package/dist/code-range.js.map +1 -0
  41. package/dist/diff.d.ts +42 -0
  42. package/dist/diff.d.ts.map +1 -0
  43. package/dist/diff.js +179 -0
  44. package/dist/diff.js.map +1 -0
  45. package/dist/engine.d.ts +15 -0
  46. package/dist/engine.d.ts.map +1 -0
  47. package/dist/engine.js +17 -0
  48. package/dist/engine.js.map +1 -0
  49. package/dist/highlight.d.ts +43 -0
  50. package/dist/highlight.d.ts.map +1 -0
  51. package/dist/highlight.js +243 -0
  52. package/dist/highlight.js.map +1 -0
  53. package/dist/index.d.ts +4 -0
  54. package/dist/index.d.ts.map +1 -0
  55. package/dist/index.js +4 -0
  56. package/dist/index.js.map +1 -0
  57. package/dist/layout.d.ts +77 -0
  58. package/dist/layout.d.ts.map +1 -0
  59. package/dist/layout.js +74 -0
  60. package/dist/layout.js.map +1 -0
  61. package/dist/measure-cache.d.ts +38 -0
  62. package/dist/measure-cache.d.ts.map +1 -0
  63. package/dist/measure-cache.js +0 -0
  64. package/dist/measure-cache.js.map +1 -0
  65. package/dist/node.d.ts +293 -0
  66. package/dist/node.d.ts.map +1 -0
  67. package/dist/node.js +733 -0
  68. package/dist/node.js.map +1 -0
  69. package/dist/nodes.d.ts +18 -0
  70. package/dist/nodes.d.ts.map +1 -0
  71. package/dist/nodes.js +18 -0
  72. package/dist/nodes.js.map +1 -0
  73. package/dist/render.d.ts +28 -0
  74. package/dist/render.d.ts.map +1 -0
  75. package/dist/render.js +223 -0
  76. package/dist/render.js.map +1 -0
  77. package/dist/style.d.ts +88 -0
  78. package/dist/style.d.ts.map +1 -0
  79. package/dist/style.js +203 -0
  80. package/dist/style.js.map +1 -0
  81. package/dist/tokens.d.ts +24 -0
  82. package/dist/tokens.d.ts.map +1 -0
  83. package/dist/tokens.js +50 -0
  84. package/dist/tokens.js.map +1 -0
  85. package/dist/transitions.d.ts +115 -0
  86. package/dist/transitions.d.ts.map +1 -0
  87. package/dist/transitions.js +85 -0
  88. package/dist/transitions.js.map +1 -0
  89. package/package.json +82 -3
  90. package/registry.json +6 -0
  91. package/src/code-range.ts +156 -0
  92. package/src/diff.ts +216 -0
  93. package/src/engine.ts +21 -0
  94. package/src/highlight.ts +291 -0
  95. package/src/index.ts +3 -0
  96. package/src/layout.ts +157 -0
  97. package/src/measure-cache.ts +0 -0
  98. package/src/node.ts +834 -0
  99. package/src/nodes.ts +18 -0
  100. package/src/render.ts +247 -0
  101. package/src/style.ts +251 -0
  102. package/src/tokens.ts +75 -0
  103. package/src/transitions.ts +184 -0
package/dist/node.js ADDED
@@ -0,0 +1,733 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ import { node, Clip, Node2D, property, insetsOps, lerpNumber, command, driveCommand, } from "@motionscript/core";
8
+ import { rangeToCharOffsets, charOffsetsToRange, TokenAdvanceCache, tokenizeCodeToIdLines, defaultCodeDiff, layoutCode, metricsSignature, makeAnim, defaultCodePhases, resolveTokenStates, moveProgress, canHighlight, ensureHighlighter, DefaultHighlightStyle, drawCode, } from "./engine.js";
9
+ let Code = class Code extends Node2D {
10
+ /** The settled structure. During an edit, the structure the edit lands on. */
11
+ tokenLines = [];
12
+ tokenized = false;
13
+ transitions = [];
14
+ // Caches expensive scope.measureText() calls; cleared when the font
15
+ // signature (fontSize|fontFamily) changes. See TokenAdvanceCache.
16
+ advanceCache = new TokenAdvanceCache();
17
+ // Layout cache for *settled* frames. Bumped whenever tokenLines is
18
+ // reassigned, so a cache hit only ever happens on identical content. Frames
19
+ // inside a structural edit are served from that edit's own two cached
20
+ // layouts instead (see StructuralTransition).
21
+ structureVersion = 0;
22
+ layoutCacheKey = null;
23
+ layoutCache = null;
24
+ // Persistent dim state set by highlight() — applied during render to all
25
+ // tokens whose id is NOT in the highlight set. null means "not highlighting".
26
+ highlightDimOpacity = null;
27
+ highlightedIds = new Set();
28
+ /**
29
+ * Which token became which across an edit, and when each part of that
30
+ * edit happens. Construction-time-only (see {@link CodeStrategies}) —
31
+ * resolved once here rather than left as `?? defaultX` at every call site.
32
+ */
33
+ diffStrategy;
34
+ phaseStrategy;
35
+ constructor(props) {
36
+ super(props);
37
+ this.diffStrategy = props.diffStrategy ?? defaultCodeDiff;
38
+ this.phaseStrategy = props.phaseStrategy ?? defaultCodePhases;
39
+ this.applyProp("width", props.width ?? "hug");
40
+ this.applyProp("height", props.height ?? "hug");
41
+ // Best-effort, for a highlighter constructed outside the asset pipeline
42
+ // entirely (a bare `new Code(...)` in a test or a headless measure). On
43
+ // the timeline the authoritative load is the one `declareAssets` declares,
44
+ // which `AssetManager.loadAt` awaits *before* this node is laid out — so
45
+ // there the tokens are right the first time rather than upgrading later.
46
+ // (Theme is a synchronous color style; only the language parser loads.)
47
+ ensureHighlighter(undefined, [this.language]).catch(() => { });
48
+ this.tokenize();
49
+ }
50
+ set(props) {
51
+ super.set(props);
52
+ if (props.code !== undefined || props.language !== undefined || props.theme !== undefined) {
53
+ this.tokenized = false;
54
+ }
55
+ }
56
+ tokenize() {
57
+ this.setLines(tokenizeCodeToIdLines(this.code, this.language, this.theme));
58
+ // Only consider ourselves tokenized once we actually highlighted; while
59
+ // the language is still loading we keep retrying on each render.
60
+ this.tokenized = canHighlight(this.language, this.theme);
61
+ }
62
+ /**
63
+ * Swap in a new settled structure, invalidating the layout cache.
64
+ *
65
+ * The one place `tokenLines` is written, because the cache key is a version
66
+ * counter rather than a hash of the content — a write that skipped the bump
67
+ * would keep serving the previous frame's geometry for the new listing.
68
+ */
69
+ setLines(lines) {
70
+ if (this.tokenLines === lines)
71
+ return;
72
+ this.tokenLines = lines;
73
+ this.structureVersion++;
74
+ this.layoutCache = null;
75
+ this.layoutCacheKey = null;
76
+ }
77
+ /**
78
+ * The monospaced face this block measures and draws with, and the syntax
79
+ * grammar it tokenizes with.
80
+ *
81
+ * Both belong to *layout*: token x positions are measured against the face,
82
+ * and how many tokens there are depends on the grammar. Declared here, the
83
+ * grammar goes on the timeline as an ordinary asset: `AssetManager.loadAt`
84
+ * waits for it before the frame is laid out, so the first measurement is the
85
+ * right one. Nothing is freed on eviction — parsers are cheap to keep
86
+ * resident. The loader touches no node: `renderContent` re-tokenizes once
87
+ * the grammar is there.
88
+ */
89
+ declareAssets(assets) {
90
+ super.declareAssets(assets);
91
+ assets.font(this.fontFamily);
92
+ assets.loader(`shiki:lang:${this.language}`, grammarLoader(this.language), { gate: "layout" });
93
+ }
94
+ // ── Geometry ────────────────────────────────────────────────────────────
95
+ metrics() {
96
+ return {
97
+ fontSize: this.fontSize,
98
+ fontFamily: this.fontFamily,
99
+ lineHeight: this.lineHeight,
100
+ letterSpacing: this.letterSpacing,
101
+ padding: this.padding,
102
+ showLineNumbers: this.showLineNumbers,
103
+ lineNumberGap: this.lineNumberGap,
104
+ };
105
+ }
106
+ /** The structural edit currently in flight, if any. */
107
+ activeEdit() {
108
+ for (let i = this.transitions.length - 1; i >= 0; i--) {
109
+ const tr = this.transitions[i];
110
+ if (tr.kind === "structural")
111
+ return tr;
112
+ }
113
+ return null;
114
+ }
115
+ settledLayout(m, scope) {
116
+ const key = `${this.structureVersion}|${metricsSignature(m)}|${this.advanceCache.signature(m.fontSize, m.fontFamily)}`;
117
+ if (this.layoutCache && this.layoutCacheKey === key)
118
+ return this.layoutCache;
119
+ const layout = layoutCode(this.tokenLines, m, this.advanceCache, scope);
120
+ this.layoutCache = layout;
121
+ this.layoutCacheKey = key;
122
+ return layout;
123
+ }
124
+ /**
125
+ * The one or two layouts this frame is drawn from.
126
+ *
127
+ * A settled frame has one. A frame inside an edit has two — where every
128
+ * token was, and where it is going — and the frame is a point between them.
129
+ * That is the whole reason an insert no longer piles its glyphs at the left
130
+ * margin: a token's destination is *computed*, not approximated by collapsing
131
+ * the advance of everything around it.
132
+ *
133
+ * Both endpoints are fixed for the edit's duration, so they are built once
134
+ * and cached on the transition rather than rebuilt per frame.
135
+ */
136
+ frameLayout(scope) {
137
+ const m = this.metrics();
138
+ const edit = this.activeEdit();
139
+ if (!edit) {
140
+ const layout = this.settledLayout(m, scope);
141
+ return { from: layout, to: layout, edit: null };
142
+ }
143
+ const key = `${metricsSignature(m)}|${this.advanceCache.signature(m.fontSize, m.fontFamily)}`;
144
+ if (edit.layoutKey !== key || !edit.fromLayout || !edit.toLayout) {
145
+ edit.fromLayout = layoutCode(edit.from, m, this.advanceCache, scope);
146
+ edit.toLayout = layoutCode(edit.to, m, this.advanceCache, scope);
147
+ edit.layoutKey = key;
148
+ }
149
+ return { from: edit.fromLayout, to: edit.toLayout, edit };
150
+ }
151
+ measure(constraints, scope) {
152
+ this.advanceCache.sync(this.advanceCache.signature(this.fontSize, this.fontFamily));
153
+ const wm = this.width;
154
+ const hm = this.height;
155
+ const { from, to, edit } = this.frameLayout(scope);
156
+ const t = moveProgress(edit);
157
+ const innerW = edit ? lerpNumber(from.innerW, to.innerW, t) : to.innerW;
158
+ const innerH = edit ? lerpNumber(from.innerH, to.innerH, t) : to.innerH;
159
+ const resolvedW = typeof wm === "number"
160
+ ? wm
161
+ : wm === "hug"
162
+ ? innerW + this.padding.left + this.padding.right
163
+ : constraints.maxWidth ?? 0;
164
+ const resolvedH = typeof hm === "number"
165
+ ? hm
166
+ : hm === "hug"
167
+ ? innerH + this.padding.top + this.padding.bottom
168
+ : constraints.maxHeight ?? 0;
169
+ return { width: resolvedW, height: resolvedH };
170
+ }
171
+ renderContent(ctx) {
172
+ // Refuse the ambient `<DefaultTextStyle>` / theme typography defaults for
173
+ // everything drawn inside this node.
174
+ //
175
+ // Those defaults describe the *document's* prose — a display face, a
176
+ // heading weight, a paragraph line-height — and a code block is not prose.
177
+ // Its own props are the vocabulary: `fontFamily` defaults to a monospaced
178
+ // face because column alignment depends on it, `letterSpacing` and
179
+ // `lineHeight` are tuned against that face, and every token is laid out at
180
+ // an x measured from those exact values. A scene-wide serif family or a
181
+ // 700 weight arriving through the draw scope would shape glyphs the
182
+ // geometry was never measured for, and the block would come apart
183
+ // column-by-column rather than merely look different.
184
+ ctx.pushTextStyle(null);
185
+ try {
186
+ // Keep retrying until the language+theme have actually loaded, so a frame
187
+ // that rendered as plain text upgrades to full highlighting the moment the
188
+ // asset loader resolves. Never mid-edit: re-tokenizing mints fresh ids,
189
+ // and an in-flight transition is keyed by the ones it captured.
190
+ if (!this.tokenized && !this.activeEdit() && canHighlight(this.language, this.theme)) {
191
+ this.tokenize();
192
+ }
193
+ super.renderContent(ctx);
194
+ }
195
+ finally {
196
+ ctx.popTextStyle();
197
+ }
198
+ }
199
+ renderSelf(ctx) {
200
+ this.drawSelf(ctx);
201
+ }
202
+ /** A listing holds a listing — `append`/`insert`/`erase` are how it grows. */
203
+ acceptsChild(_child) {
204
+ return false;
205
+ }
206
+ /**
207
+ * The node's laid-out rect as a clip outline, so `clip` and any backdrop
208
+ * effect are confined to the block rather than to nothing — a listing set on
209
+ * a card is exactly where a backdrop blur is asked for.
210
+ */
211
+ clipSelf() {
212
+ return new Clip().rect({
213
+ width: this.layoutBounds.width,
214
+ height: this.layoutBounds.height,
215
+ });
216
+ }
217
+ /**
218
+ * A listing is grabbed by its **text**, line by ragged line, rather than by
219
+ * the rectangle the lines were laid out in.
220
+ *
221
+ * The default narrows a node's grab region to the outline it declares, and
222
+ * this node's outline is a box it no longer paints anything into. Code is
223
+ * mostly whitespace: a ten-line snippet with one long line is a rectangle
224
+ * that is largely empty, and in an editor every one of those empty pixels
225
+ * swallows a click meant for whatever sits behind or beneath it. Short of the
226
+ * text itself there is nothing there to have clicked.
227
+ *
228
+ * So the region is the union of the lines' own extents — each a line-height
229
+ * slot as wide as that line's ink — plus the gutter where line numbers are
230
+ * showing, since those are drawn glyphs too.
231
+ *
232
+ * Answered from the **cached** layout, which is what the last frame drew
233
+ * from, because a hit test arrives with no measurement scope and text cannot
234
+ * be measured without one. Where there is no usable cache — before the first
235
+ * frame, or mid-edit, when the geometry is an interpolation of two structures
236
+ * held on the transition — the box is the honest answer rather than a
237
+ * silhouette measured against stale metrics.
238
+ */
239
+ hitTestSelf(local, tolerance) {
240
+ const layout = this.hitLayout();
241
+ if (!layout)
242
+ return super.hitTestSelf(local, tolerance);
243
+ // Never *wider* than the box: `hug` sizes to the ink, but a fixed width
244
+ // narrower than the longest line would otherwise be hit outside itself.
245
+ if (!super.hitTestSelf(local, tolerance))
246
+ return false;
247
+ const half = (this.fontSize * this.lineHeight) / 2;
248
+ // Line numbers sit in the gutter, to the left of every line's own start,
249
+ // so a numbered blank line is still grabbable — by its number.
250
+ const gutter = this.showLineNumbers ? layout.gutter : 0;
251
+ const left = layout.startX - gutter - tolerance;
252
+ for (let i = 0; i < layout.lineY.length; i++) {
253
+ const width = (layout.lineW[i] ?? 0) + gutter;
254
+ if (width <= 0)
255
+ continue;
256
+ if (Math.abs(local.y - layout.lineY[i]) > half + tolerance)
257
+ continue;
258
+ if (local.x >= left && local.x <= layout.startX + (layout.lineW[i] ?? 0) + tolerance) {
259
+ return true;
260
+ }
261
+ }
262
+ return false;
263
+ }
264
+ /**
265
+ * The layout a hit test may be answered from: the settled cache, and only
266
+ * while it still matches the node's current metrics.
267
+ *
268
+ * The key is the one {@link settledLayout} writes minus its scope-dependent
269
+ * half — every input to it (`metricsSignature`, the advance cache's own
270
+ * signature) is readable without a measurer, which is precisely what makes
271
+ * the check possible here.
272
+ */
273
+ hitLayout() {
274
+ if (!this.layoutCache || this.activeEdit())
275
+ return null;
276
+ const m = this.metrics();
277
+ const key = `${this.structureVersion}|${metricsSignature(m)}|${this.advanceCache.signature(m.fontSize, m.fontFamily)}`;
278
+ return this.layoutCacheKey === key ? this.layoutCache : null;
279
+ }
280
+ // ── Editing commands ────────────────────────────────────────────────────
281
+ /**
282
+ * Append `code` to the end of the listing.
283
+ *
284
+ * Stated as *what the source becomes*; {@link editTo} works out the rest —
285
+ * which is why appending a line that closes a block re-highlights the lines
286
+ * above it, instead of colouring the new text as its own program.
287
+ */
288
+ append(args) {
289
+ const { code } = args.data;
290
+ return this.editTo(this.joinedSource() + code, args.duration, args.easing);
291
+ }
292
+ /** Insert `code` above the listing. */
293
+ prepend(args) {
294
+ const { code } = args.data;
295
+ return this.editTo(code + this.joinedSource(), args.duration, args.easing);
296
+ }
297
+ /**
298
+ * Insert `code` at the given (line, col). Both are 1-indexed; col is the
299
+ * column BEFORE which the new content is inserted (col=1 means start of
300
+ * line). If `code` contains newlines, new lines are created in the middle
301
+ * of the existing line.
302
+ */
303
+ insert(args) {
304
+ const { position, code } = args.data;
305
+ const source = this.joinedSource();
306
+ const offset = this.offsetAt(position);
307
+ return this.editTo(source.slice(0, offset) + code + source.slice(offset), args.duration, args.easing);
308
+ }
309
+ /**
310
+ * Erase the code in `codeRange`.
311
+ *
312
+ * Named `erase` rather than `remove` because a `Code` is also a node, and
313
+ * `Node.remove(child)` takes a child out of the tree. Two methods spelled
314
+ * the same on one object, doing entirely different things, is worse than one
315
+ * of them having a slightly less obvious name.
316
+ *
317
+ * A range that covers whole lines takes their line breaks with it, so the
318
+ * rows below close up; a range inside a line takes only the characters, and
319
+ * the rest of the line reflows around the hole.
320
+ */
321
+ erase(args) {
322
+ const { target: codeRange } = args.data;
323
+ const { duration, easing } = args;
324
+ const source = this.joinedSource();
325
+ let { start, end } = rangeToCharOffsets(codeRange, this.lineLengths());
326
+ // `lines(2)` resolves to the *characters* of line 2, not to the row —
327
+ // taking those alone would leave an empty line behind where an editor
328
+ // would have closed the gap. This is also what makes a blank row
329
+ // removable at all: it has no characters, so its range is empty, and
330
+ // "delete nothing" is not what `lines(2)` was asking for.
331
+ const atLineStart = start === 0 || source[start - 1] === "\n";
332
+ const atLineEnd = end === source.length || source[end] === "\n";
333
+ if (atLineStart && atLineEnd) {
334
+ if (end < source.length)
335
+ end += 1;
336
+ else if (start > 0)
337
+ start -= 1;
338
+ }
339
+ else if (end <= start) {
340
+ return driveCommand(duration, () => { });
341
+ }
342
+ if (end <= start)
343
+ return driveCommand(duration, () => { });
344
+ return this.editTo(source.slice(0, start) + source.slice(end), duration, easing);
345
+ }
346
+ /** Replace the code in `codeRange` with `replacement`. */
347
+ replace(args) {
348
+ const { target: codeRange, replacement } = args.data;
349
+ const source = this.joinedSource();
350
+ const { start, end } = rangeToCharOffsets(codeRange, this.lineLengths());
351
+ return this.editTo(source.slice(0, start) + replacement + source.slice(end), args.duration, args.easing);
352
+ }
353
+ /**
354
+ * Highlight a range of code — or several at once (e.g.
355
+ * `CodeRanges.lines(2).word(5, 1, 3)`) — highlighted as one set: tokens
356
+ * within any of the ranges stay at opacity 1, tokens outside dim to
357
+ * `dim`. Persistent — call resetHighlight() to undo, or call highlight()
358
+ * again with a different range to cross-fade.
359
+ */
360
+ highlight(args) {
361
+ const { target: codeRange, dim } = args.data;
362
+ const { duration, easing } = args;
363
+ const toDim = dim ?? 0.4;
364
+ const matchIds = this.tokenIdsInRanges(normalizeCodeRanges(codeRange));
365
+ if (matchIds.size === 0)
366
+ return driveCommand(duration, () => { });
367
+ const fromDim = this.highlightDimOpacity ?? 1;
368
+ const hadPrevious = this.highlightedIds.size > 0;
369
+ const previousIds = this.highlightedIds;
370
+ const animTokens = [];
371
+ for (const line of this.tokenLines) {
372
+ for (const tok of line.tokens) {
373
+ const wasHighlighted = !hadPrevious || previousIds.has(tok.id);
374
+ const isHighlighted = matchIds.has(tok.id);
375
+ const fromOp = wasHighlighted ? 1 : fromDim;
376
+ const toOp = isHighlighted ? 1 : toDim;
377
+ if (fromOp === toOp)
378
+ continue;
379
+ animTokens.push(makeAnim(tok.id, { keys: [0, 1], values: [fromOp, toOp] }));
380
+ }
381
+ }
382
+ // Which tokens are dimmed is state the *next* highlight reads to know
383
+ // what it is cross-fading from, so it is committed at the end and put
384
+ // back below it — a `finally` could only ever have run forwards.
385
+ return this.runDim(animTokens, duration, easing, (done) => {
386
+ this.highlightDimOpacity = done ? toDim : (hadPrevious ? fromDim : null);
387
+ this.highlightedIds = done ? matchIds : previousIds;
388
+ });
389
+ }
390
+ /**
391
+ * Fade all dimmed tokens back to opacity 1 and clear the persistent
392
+ * highlight state.
393
+ */
394
+ resetHighlight(args) {
395
+ const { duration, easing } = args;
396
+ if (this.highlightDimOpacity === null)
397
+ return driveCommand(duration, () => { });
398
+ const fromDim = this.highlightDimOpacity;
399
+ const previousIds = this.highlightedIds;
400
+ const animTokens = [];
401
+ for (const line of this.tokenLines) {
402
+ for (const tok of line.tokens) {
403
+ const fromOp = previousIds.has(tok.id) ? 1 : fromDim;
404
+ if (fromOp === 1)
405
+ continue;
406
+ animTokens.push(makeAnim(tok.id, { keys: [0, 1], values: [fromOp, 1] }));
407
+ }
408
+ }
409
+ return this.runDim(animTokens, duration, easing, (done) => {
410
+ this.highlightDimOpacity = done ? null : fromDim;
411
+ this.highlightedIds = done ? new Set() : previousIds;
412
+ });
413
+ }
414
+ /**
415
+ * Animate the listing to a new source.
416
+ *
417
+ * The engine behind every editing command, and behind `to({ code })`. Every
418
+ * edit is expressed as the source it produces, tokenized, and then *diffed*
419
+ * against what is on screen — so a token that survived the edit keeps its
420
+ * identity and simply travels to its new column, and only what genuinely
421
+ * changed is faded.
422
+ *
423
+ * The result runs in three phases (see `phaseStrategy`): what is leaving
424
+ * fades out, what stays reflows, and only then does what is new arrive.
425
+ * Playing them together is what made a replacement read as a cross-dissolve
426
+ * of two unrelated listings rather than as an edit being made.
427
+ */
428
+ editTo(next, duration, easing) {
429
+ const from = this.tokenLines;
430
+ const fromCode = this.joinedSource();
431
+ if (next === fromCode)
432
+ return driveCommand(duration, () => { });
433
+ const edit = this.diffStrategy(from, tokenizeCodeToIdLines(next, this.language, this.theme));
434
+ const transition = {
435
+ kind: "structural",
436
+ from,
437
+ to: edit.lines,
438
+ removedIds: edit.removedIds,
439
+ addedIds: edit.addedIds,
440
+ enteringLineIds: edit.newLineIds,
441
+ fromColorById: edit.fromColorById,
442
+ phases: this.phaseStrategy(edit.removedIds.size > 0, edit.addedIds.size > 0),
443
+ progress: 0,
444
+ layoutKey: null,
445
+ fromLayout: null,
446
+ toLayout: null,
447
+ };
448
+ // A tokenize triggered by the grammar landing mid-edit would mint fresh
449
+ // ids underneath this transition, and the transition is keyed by the ones
450
+ // it captured — so the retry in `onRender` is gated on there being no edit
451
+ // in flight, which means this flag has to be honest now rather than once
452
+ // the edit settles.
453
+ this.tokenized = canHighlight(this.language, this.theme);
454
+ return driveCommand(duration, (t) => {
455
+ const running = t > 0 && t < 1;
456
+ const index = this.transitions.indexOf(transition);
457
+ if (running && index < 0)
458
+ this.transitions.push(transition);
459
+ else if (!running && index >= 0)
460
+ this.transitions.splice(index, 1);
461
+ transition.progress = easing ? easing(t) : t;
462
+ // The settle, in both directions: asked for a time before the edit
463
+ // starts, the listing is what preceded it; at or past the end, the
464
+ // result. A `finally` could only ever have run forwards.
465
+ if (t <= 0) {
466
+ this.setLines(from);
467
+ this._writeProp("code", fromCode);
468
+ }
469
+ else {
470
+ this.setLines(edit.lines);
471
+ this._writeProp("code", next);
472
+ }
473
+ });
474
+ }
475
+ /**
476
+ * Put a dim transition on the stack, drive its progress, take it off and
477
+ * commit at the end.
478
+ *
479
+ * A {@link Command} rather than a generator, which is what makes a listing
480
+ * scrubbable: membership is a function of `t` (on the stack for `0 < t < 1`,
481
+ * off it outside), `settle(done)` replaces the `finally` and takes *which
482
+ * way*, and `progress` is assigned from `t` rather than accumulated.
483
+ */
484
+ runDim(tokens, duration, easing, settle) {
485
+ const transition = { kind: "dim", tokens, progress: 0 };
486
+ return driveCommand(duration, (t) => {
487
+ const running = t > 0 && t < 1;
488
+ const index = this.transitions.indexOf(transition);
489
+ if (running && index < 0)
490
+ this.transitions.push(transition);
491
+ else if (!running && index >= 0)
492
+ this.transitions.splice(index, 1);
493
+ transition.progress = easing ? easing(t) : t;
494
+ settle?.(t >= 1);
495
+ });
496
+ }
497
+ /**
498
+ * Route a tweened `code` through the diff engine.
499
+ *
500
+ * `to({ code })` is the form an author reaches for first — it is how every
501
+ * other prop is animated — and a bare string prop would otherwise land in the
502
+ * generic tween's discrete-snap bucket and simply cut at the end. Intercepted
503
+ * here it becomes the same three-phase edit the named commands produce, while
504
+ * the rest of the step's props tween alongside it untouched.
505
+ */
506
+ _prepareStep(to, duration, easing) {
507
+ const next = to.code;
508
+ if (typeof next !== "string" || next === this.joinedSource()) {
509
+ return super._prepareStep(to, duration, easing);
510
+ }
511
+ const rest = { ...to };
512
+ delete rest.code;
513
+ // Prepared before the edit, so a step that also moves `fontSize` has
514
+ // snapshotted its own start value against the listing that is still on
515
+ // screen.
516
+ const others = super._prepareStep(rest, duration, easing);
517
+ const edit = this.editTo(next, duration, easing)._stepper();
518
+ return {
519
+ seek: (elapsed) => {
520
+ others.seek(elapsed);
521
+ edit.seek(elapsed);
522
+ },
523
+ advance: (dt) => {
524
+ const othersDone = others.advance(dt);
525
+ const editDone = edit.advance(dt);
526
+ return othersDone && editDone;
527
+ },
528
+ };
529
+ }
530
+ // ── Source queries ──────────────────────────────────────────────────────
531
+ /**
532
+ * Find every range matching the literal string `text` in the current
533
+ * source. Multi-line matches are supported.
534
+ */
535
+ findAllRanges(text) {
536
+ const ranges = [];
537
+ if (!text)
538
+ return ranges;
539
+ const source = this.joinedSource();
540
+ const lineLens = this.lineLengths();
541
+ let from = 0;
542
+ while (true) {
543
+ const idx = source.indexOf(text, from);
544
+ if (idx === -1)
545
+ break;
546
+ ranges.push(charOffsetsToRange(idx, idx + text.length, lineLens));
547
+ from = idx + Math.max(1, text.length);
548
+ }
549
+ return ranges;
550
+ }
551
+ /** Find the `index`th range matching `text`. Returns null if not found. */
552
+ findRangeAt(text, index) {
553
+ const all = this.findAllRanges(text);
554
+ return all[index] ?? null;
555
+ }
556
+ /** Find the first range matching `text`. Returns null if not found. */
557
+ findFirstRange(text) {
558
+ return this.findRangeAt(text, 0);
559
+ }
560
+ joinedSource() {
561
+ return this.tokenLines
562
+ .map(line => line.tokens.map(t => t.content).join(''))
563
+ .join('\n');
564
+ }
565
+ lineLengths() {
566
+ return this.tokenLines.map(line => line.tokens.reduce((acc, t) => acc + t.content.length, 0));
567
+ }
568
+ /** Character offset of a 1-indexed (line, col), clamped into the document. */
569
+ offsetAt(position) {
570
+ const lens = this.lineLengths();
571
+ if (lens.length === 0)
572
+ return 0;
573
+ const [rawLine, rawCol] = position;
574
+ const li = Math.max(0, Math.min(lens.length - 1, rawLine - 1));
575
+ let offset = 0;
576
+ for (let k = 0; k < li; k++)
577
+ offset += lens[k] + 1;
578
+ return offset + Math.max(0, Math.min(lens[li], rawCol - 1));
579
+ }
580
+ /**
581
+ * Resolve one or more CodeRanges to the set of token ids whose content
582
+ * overlaps any of them. Tokens that partially overlap are included.
583
+ */
584
+ tokenIdsInRanges(codeRanges) {
585
+ const result = new Set();
586
+ const lineLens = this.lineLengths();
587
+ if (lineLens.length === 0)
588
+ return result;
589
+ const offsets = codeRanges
590
+ .map(r => rangeToCharOffsets(r, lineLens))
591
+ .filter(({ start, end }) => end > start);
592
+ if (offsets.length === 0)
593
+ return result;
594
+ // Walk tokens with running offsets in the joined string, testing each
595
+ // token against every requested range's offsets.
596
+ let off = 0;
597
+ for (let li = 0; li < this.tokenLines.length; li++) {
598
+ const line = this.tokenLines[li];
599
+ for (const tok of line.tokens) {
600
+ const tStart = off;
601
+ const tEnd = off + tok.content.length;
602
+ if (offsets.some(({ start, end }) => tEnd > start && tStart < end))
603
+ result.add(tok.id);
604
+ off = tEnd;
605
+ }
606
+ if (li < this.tokenLines.length - 1)
607
+ off += 1; // newline
608
+ }
609
+ return result;
610
+ }
611
+ // ── Drawing ─────────────────────────────────────────────────────────────
612
+ /**
613
+ * Thin delegator: everything about *how* a frame is painted (settled or
614
+ * mid structural-edit, entry/exit motion, colour cross-fade) lives in
615
+ * `drawCode` (the engine's `render.ts`) as a pure function over plain
616
+ * state — this just gathers that state from the node's own instance
617
+ * fields and caches.
618
+ */
619
+ drawSelf(draw) {
620
+ this.advanceCache.sync(this.advanceCache.signature(this.fontSize, this.fontFamily));
621
+ drawCode(draw, {
622
+ tokenLines: this.tokenLines,
623
+ metrics: this.metrics(),
624
+ advanceCache: this.advanceCache,
625
+ ...this.frameLayout(draw),
626
+ tokenStates: resolveTokenStates(this.tokenLines, this.transitions, this.highlightDimOpacity, this.highlightedIds),
627
+ highlightActive: this.highlightDimOpacity !== null || this.transitions.some(tr => tr.kind === "dim"),
628
+ });
629
+ }
630
+ };
631
+ __decorate([
632
+ property({ default: "" })
633
+ ], Code.prototype, "code", void 0);
634
+ __decorate([
635
+ property({ default: "typescript" })
636
+ ], Code.prototype, "language", void 0);
637
+ __decorate([
638
+ property({ default: "Fira Mono" })
639
+ ], Code.prototype, "fontFamily", void 0);
640
+ __decorate([
641
+ property({ default: DefaultHighlightStyle.name })
642
+ ], Code.prototype, "theme", void 0);
643
+ __decorate([
644
+ property({ default: 16 })
645
+ ], Code.prototype, "fontSize", void 0);
646
+ __decorate([
647
+ property({ default: 1.6 })
648
+ ], Code.prototype, "lineHeight", void 0);
649
+ __decorate([
650
+ property({ default: 1.1 })
651
+ ], Code.prototype, "letterSpacing", void 0);
652
+ __decorate([
653
+ property({ default: false })
654
+ ], Code.prototype, "showLineNumbers", void 0);
655
+ __decorate([
656
+ property({ default: 2 })
657
+ ], Code.prototype, "lineNumberGap", void 0);
658
+ __decorate([
659
+ property({ default: 0, mapper: insetsOps.resolve, tween: insetsOps.lerp })
660
+ ], Code.prototype, "padding", void 0);
661
+ __decorate([
662
+ command({ args: [{ key: "code", kind: "text", multiline: true }] })
663
+ ], Code.prototype, "append", null);
664
+ __decorate([
665
+ command({ args: [{ key: "code", kind: "text", multiline: true }] })
666
+ ], Code.prototype, "prepend", null);
667
+ __decorate([
668
+ command({
669
+ args: [
670
+ // Two controls, one argument: the method takes a `[line, col]`
671
+ // tuple, so the pair a host draws is declared *inside* the value it
672
+ // composes into rather than flattened beside it.
673
+ {
674
+ key: "position", kind: "point", properties: {
675
+ line: { kind: "number", default: 1, min: 1, step: 1 },
676
+ col: { kind: "number", default: 1, min: 1, step: 1 },
677
+ },
678
+ },
679
+ { key: "code", kind: "text", default: "", multiline: true },
680
+ ],
681
+ })
682
+ ], Code.prototype, "insert", null);
683
+ __decorate([
684
+ command({ key: "remove", args: [{ key: "target", kind: "selector" }] })
685
+ ], Code.prototype, "erase", null);
686
+ __decorate([
687
+ command({ args: [{ key: "target", kind: "selector" }, { key: "replacement", kind: "text", default: "", multiline: true }] })
688
+ ], Code.prototype, "replace", null);
689
+ __decorate([
690
+ command({ args: [{ key: "target", kind: "selector" }, { key: "dim", kind: "number", default: 0.4, min: 0, max: 1, step: 0.01, scale: 100, unit: "%" }] })
691
+ ], Code.prototype, "highlight", null);
692
+ __decorate([
693
+ command()
694
+ ], Code.prototype, "resetHighlight", null);
695
+ Code = __decorate([
696
+ node({
697
+ key: "code",
698
+ parentKey: "node",
699
+ forkable: true,
700
+ layout: {
701
+ defaultWidthMode: "hug",
702
+ defaultHeightMode: "hug",
703
+ acceptsChildren: false,
704
+ },
705
+ })
706
+ ], Code);
707
+ export { Code };
708
+ /**
709
+ * Normalize `highlight()`'s `codeRange` argument to a plain array: a single
710
+ * `CodeRange` (a plain object, not iterable) becomes a one-element array; a
711
+ * `CodeRangeChain`/plain array of ranges spreads as-is. `CodeRange` and
712
+ * `CodeRangeChain` are distinguished by iterability, not `instanceof` — a
713
+ * bare array of `CodeRange`s (no chain) works the same way.
714
+ */
715
+ function normalizeCodeRanges(codeRange) {
716
+ const maybeIterable = codeRange;
717
+ if (typeof maybeIterable[Symbol.iterator] === "function") {
718
+ return [...codeRange];
719
+ }
720
+ return [codeRange];
721
+ }
722
+ const grammarLoaders = new Map();
723
+ // One function per language: blocks sharing a grammar declare one key, and a
724
+ // second load function for a key already declared is ignored with a warning.
725
+ function grammarLoader(language) {
726
+ let load = grammarLoaders.get(language);
727
+ if (load === undefined) {
728
+ load = () => ensureHighlighter(undefined, [language]);
729
+ grammarLoaders.set(language, load);
730
+ }
731
+ return load;
732
+ }
733
+ //# sourceMappingURL=node.js.map