svelte-highlight 7.23.2 → 7.24.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 (94) hide show
  1. package/AnsiOutput.svelte +33 -6
  2. package/AnsiOutput.svelte.d.ts +8 -0
  3. package/CodeToolbar.svelte +144 -0
  4. package/CodeToolbar.svelte.d.ts +125 -0
  5. package/CodeWindow.svelte +19 -0
  6. package/CodeWindow.svelte.d.ts +10 -0
  7. package/CopyButton.svelte +107 -3
  8. package/CopyButton.svelte.d.ts +17 -1
  9. package/DiffFileList.svelte +523 -0
  10. package/DiffFileList.svelte.d.ts +94 -0
  11. package/DiffFileListItem.svelte +44 -0
  12. package/DiffMinimap.svelte +99 -0
  13. package/DiffMinimap.svelte.d.ts +17 -0
  14. package/DiffStats.svelte +43 -0
  15. package/DiffStats.svelte.d.ts +17 -0
  16. package/DiffView.svelte +1213 -0
  17. package/DiffView.svelte.d.ts +76 -0
  18. package/FileTabs.svelte +2 -5
  19. package/Highlight.svelte +158 -2
  20. package/Highlight.svelte.d.ts +50 -2
  21. package/HighlightAuto.svelte.d.ts +3 -2
  22. package/HighlightAutoLazy.svelte +112 -0
  23. package/HighlightAutoLazy.svelte.d.ts +66 -0
  24. package/HighlightDiff.svelte +162 -0
  25. package/HighlightDiff.svelte.d.ts +102 -0
  26. package/HighlightEditable.svelte +65 -756
  27. package/HighlightEditable.svelte.d.ts +15 -5
  28. package/HighlightStream.svelte +117 -218
  29. package/HighlightStream.svelte.d.ts +8 -0
  30. package/HighlightSvelte.svelte.d.ts +3 -2
  31. package/HighlightVirtual.svelte +41 -8
  32. package/HighlightVirtual.svelte.d.ts +8 -0
  33. package/LangTag.svelte +33 -4
  34. package/LangTag.svelte.d.ts +6 -2
  35. package/LineNumbers.svelte +25 -4
  36. package/LineNumbers.svelte.d.ts +8 -0
  37. package/MarkdownStream.svelte +1 -0
  38. package/README.md +735 -18
  39. package/ToolbarButton.svelte +90 -0
  40. package/ToolbarButton.svelte.d.ts +106 -0
  41. package/Typewriter.svelte +59 -10
  42. package/Typewriter.svelte.d.ts +7 -0
  43. package/WrapToggle.svelte +34 -0
  44. package/WrapToggle.svelte.d.ts +39 -0
  45. package/action.js +7 -3
  46. package/ansi.d.ts +1 -3
  47. package/auto-detect.d.ts +52 -0
  48. package/auto-detect.js +208 -0
  49. package/code-region.d.ts +7 -0
  50. package/code-region.js +20 -0
  51. package/css-highlights.js +115 -0
  52. package/css-walk.js +50 -0
  53. package/diff-controller.d.ts +120 -0
  54. package/diff-controller.js +721 -0
  55. package/diff-edits.d.ts +101 -0
  56. package/diff-edits.js +890 -0
  57. package/diff-html.d.ts +8 -0
  58. package/diff-html.js +60 -0
  59. package/diff-languages.d.ts +4 -0
  60. package/diff-languages.js +73 -0
  61. package/diff.d.ts +161 -0
  62. package/diff.js +1111 -0
  63. package/editable-commands.js +81 -0
  64. package/editable-css-paint.js +5 -3
  65. package/editable-dom-paint.js +1 -1
  66. package/editable-history.js +199 -0
  67. package/editable-line-dom.js +176 -1
  68. package/editable-painter.js +356 -0
  69. package/editable.d.ts +118 -0
  70. package/editable.js +513 -0
  71. package/engine.d.ts +1 -1
  72. package/fence.js +1 -1
  73. package/highlight-cascade.js +679 -0
  74. package/highlight-theme.js +6 -47
  75. package/incremental-tokenize.js +1 -1
  76. package/index.d.ts +39 -6
  77. package/index.js +30 -0
  78. package/languages/detect-index.d.ts +16 -0
  79. package/languages/detect-index.js +6 -0
  80. package/languages/loaders.d.ts +8 -0
  81. package/languages/loaders.js +370 -0
  82. package/package.json +50 -2
  83. package/preprocessor.js +20 -5
  84. package/search.js +2 -2
  85. package/stream-highlighter.js +198 -0
  86. package/stream.css +16 -0
  87. package/stream.d.ts +60 -0
  88. package/stream.js +283 -0
  89. package/style-registry.js +34 -3
  90. package/themes/_base-css.d.ts +1 -0
  91. package/themes/_base-css.js +1 -0
  92. package/typewriter-units.d.ts +3 -0
  93. package/typewriter-units.js +43 -0
  94. package/virtual-window.js +9 -4
@@ -0,0 +1,721 @@
1
+ // Headless state for a rendered diff: the diff itself, highlighting, folds,
2
+ // review decisions, and navigation. Svelte components take a controller and
3
+ // read it as a store (`$diff`); anything else can call it directly.
4
+
5
+ import {
6
+ applyReview,
7
+ buildRows,
8
+ createDiffSession,
9
+ detectMoves,
10
+ diffStats,
11
+ toUnifiedPatch,
12
+ wordDiff,
13
+ } from "./diff.js";
14
+ import { patchToState } from "./diff-edits.js";
15
+ import { escapeText, overlayRanges } from "./diff-html.js";
16
+ import { createTokenizedDocument } from "./tokenized-document.js";
17
+
18
+ /**
19
+ * @typedef {{ side: "old" | "new", line: number, body: string, author?: string, tone?: "info" | "warning" | "error" | "suggestion" }} Annotation
20
+ *
21
+ * @typedef {import("./diff.js").Row & { note?: Annotation }} ViewRow
22
+ *
23
+ * @typedef {{
24
+ * language?: import("./languages").LanguageType<string>,
25
+ * view: "unified" | "split",
26
+ * context: number,
27
+ * wordDiff: boolean,
28
+ * ignoreWhitespace: boolean,
29
+ * detectMoves: boolean,
30
+ * annotations: Annotation[],
31
+ * tabSize: number,
32
+ * }} DiffOptions
33
+ *
34
+ * @typedef {{
35
+ * row: ViewRow,
36
+ * index: number,
37
+ * oldHtml: string,
38
+ * newHtml: string,
39
+ * }} RenderedRow
40
+ *
41
+ * @typedef {{
42
+ * reveal: { row: number, align: "start" | "center" | "third" },
43
+ * viewport: { start: number, end: number, count: number },
44
+ * navigate: { change: number, index: number, count: number },
45
+ * review: { decisions: Map<number, "accepted" | "rejected">, text: string },
46
+ * options: DiffOptions,
47
+ * }} DiffEvents
48
+ */
49
+
50
+ /** @type {DiffOptions} */
51
+ const DEFAULTS = {
52
+ view: "unified",
53
+ context: 3,
54
+ wordDiff: true,
55
+ ignoreWhitespace: false,
56
+ detectMoves: true,
57
+ annotations: [],
58
+ tabSize: 4,
59
+ };
60
+
61
+ const NO_MOVES = { oldMoves: new Map(), newMoves: new Map(), groups: 0 };
62
+
63
+ /** @param {Partial<DiffOptions>} [initial] */
64
+ export function createDiffController(initial = {}) {
65
+ /** @type {DiffOptions} */
66
+ let options = { ...DEFAULTS, ...initial };
67
+ let session = createDiffSession({
68
+ ignoreWhitespace: options.ignoreWhitespace,
69
+ });
70
+
71
+ let before = "";
72
+ let after = "";
73
+ let streaming = false;
74
+ /** @type {import("./diff-edits.js").FilePatch | null} */
75
+ let patch = null;
76
+
77
+ /** @type {import("./diff.js").DiffState & { beforeText?: string, afterText?: string }} */
78
+ let state = session.update("", "");
79
+
80
+ /** @type {ReturnType<typeof createTokenizedDocument> | null} */
81
+ let beforeDoc = null;
82
+ /** @type {ReturnType<typeof createTokenizedDocument> | null} */
83
+ let afterDoc = null;
84
+ let docLanguage = "";
85
+
86
+ /** @type {Set<string>} */
87
+ let expanded = new Set();
88
+ /** @type {Map<number, "accepted" | "rejected">} */
89
+ let decisions = new Map();
90
+ let current = -1;
91
+
92
+ /** @type {{ rows: ViewRow[], changeStarts: number[] } | null} */
93
+ let layout = null;
94
+ /** @type {{ state: object, moves: ReturnType<typeof detectMoves> } | null} */
95
+ let movesCache = null;
96
+ /** @type {{ state: object, map: Map<string, ReturnType<typeof wordDiff>> }} */
97
+ let wordCache = { state, map: new Map() };
98
+ /** @type {{ state: object, value: { old: number, new: number, gutter: number } } | null} */
99
+ let columnsCache = null;
100
+ // Widest line per side. A streamed `afterLines` grows in place, so only
101
+ // its new lines are measured.
102
+ const widths = {
103
+ /** @type {string[] | null} */ oldLines: null,
104
+ old: 0,
105
+ /** @type {string[] | null} */ newLines: null,
106
+ newCount: 0,
107
+ new: 0,
108
+ tabSize: 0,
109
+ };
110
+ /** @type {{ state: object, value: ReturnType<typeof diffStats> } | null} */
111
+ let statsCache = null;
112
+
113
+ let version = 0;
114
+ /** @type {Set<(value: any) => void>} */
115
+ const subscribers = new Set();
116
+ /** @type {{ [K in keyof DiffEvents]?: Set<(detail: DiffEvents[K]) => void> }} */
117
+ const listeners = {};
118
+
119
+ function notify() {
120
+ version++;
121
+ for (const fn of subscribers) fn(api);
122
+ }
123
+
124
+ /**
125
+ * @template {keyof DiffEvents} K
126
+ * @param {K} type
127
+ * @param {DiffEvents[K]} detail
128
+ */
129
+ function emit(type, detail) {
130
+ for (const fn of listeners[type] ?? []) fn(detail);
131
+ }
132
+
133
+ function syncDocs() {
134
+ const language = options.language;
135
+ if (!language) return;
136
+ if (!beforeDoc || !afterDoc || language.name !== docLanguage) {
137
+ beforeDoc = createTokenizedDocument({ language });
138
+ afterDoc = createTokenizedDocument({ language });
139
+ docLanguage = language.name;
140
+ }
141
+ beforeDoc.setCode(state.beforeText ?? before);
142
+ afterDoc.setCode(state.afterText ?? after);
143
+ }
144
+
145
+ function recompute() {
146
+ state = patch
147
+ ? patchToState(patch)
148
+ : session.update(before, after, { streaming });
149
+ layout = null;
150
+ syncDocs();
151
+ }
152
+
153
+ function resetView() {
154
+ decisions = new Map();
155
+ expanded = new Set();
156
+ current = -1;
157
+ }
158
+
159
+ function ensureLayout() {
160
+ if (layout) return layout;
161
+ let moves = NO_MOVES;
162
+ if (options.detectMoves && !state.streaming) {
163
+ if (movesCache?.state !== state) {
164
+ movesCache = { state, moves: detectMoves(state) };
165
+ }
166
+ moves = movesCache.moves;
167
+ }
168
+ const base = buildRows(state, {
169
+ view: options.view,
170
+ context: options.context,
171
+ expanded,
172
+ moves: moves.oldMoves,
173
+ movesNew: moves.newMoves,
174
+ });
175
+ const rows = withNotes(base, options.annotations);
176
+ /** @type {number[]} */
177
+ const changeStarts = [];
178
+ for (let i = 0; i < rows.length; i++) {
179
+ if (rows[i]?.first) changeStarts.push(i);
180
+ }
181
+ layout = { rows, changeStarts };
182
+ return layout;
183
+ }
184
+
185
+ /**
186
+ * @param {number} oldIndex
187
+ * @param {number} newIndex
188
+ */
189
+ function wordsFor(oldIndex, newIndex) {
190
+ if (wordCache.state !== state) wordCache = { state, map: new Map() };
191
+ const key = `${oldIndex}:${newIndex}`;
192
+ let hit = wordCache.map.get(key);
193
+ if (!hit) {
194
+ hit = wordDiff(
195
+ state.beforeLines[oldIndex] ?? "",
196
+ state.afterLines[newIndex] ?? "",
197
+ );
198
+ wordCache.map.set(key, hit);
199
+ }
200
+ return hit;
201
+ }
202
+
203
+ /**
204
+ * Shows a trailing carriage return, and a missing final newline when the
205
+ * two sides disagree about it.
206
+ * @param {string} html
207
+ * @param {number} index
208
+ * @param {string[]} lines
209
+ * @param {boolean} noEol
210
+ */
211
+ function markLineEnd(html, index, lines, noEol) {
212
+ const text = lines[index];
213
+ if (text === undefined) return html;
214
+ let out = html;
215
+ if (text.endsWith("\r")) {
216
+ const at = out.lastIndexOf("\r");
217
+ if (at !== -1) {
218
+ out = `${out.slice(0, at)}<span class="shl-diff-cr" title="Carriage return"></span>${out.slice(at + 1)}`;
219
+ }
220
+ }
221
+ if (
222
+ noEol &&
223
+ index === lines.length - 1 &&
224
+ state.beforeNoEol !== state.afterNoEol
225
+ ) {
226
+ out +=
227
+ '<span class="shl-diff-noeol" title="No newline at end of file"></span>';
228
+ }
229
+ return out;
230
+ }
231
+
232
+ /**
233
+ * @param {"old" | "new"} side
234
+ * @param {number[]} indices
235
+ */
236
+ function fetchLines(side, indices) {
237
+ const doc = side === "old" ? beforeDoc : afterDoc;
238
+ const lines = side === "old" ? state.beforeLines : state.afterLines;
239
+ /** @type {Map<number, string>} */
240
+ const out = new Map();
241
+ const sorted = [...new Set(indices)].sort((x, y) => x - y);
242
+ let i = 0;
243
+ while (i < sorted.length) {
244
+ const start = /** @type {number} */ (sorted[i]);
245
+ let end = start + 1;
246
+ // Fetch near-contiguous runs together, but never tokenize a fold.
247
+ while (
248
+ i + 1 < sorted.length &&
249
+ /** @type {number} */ (sorted[i + 1]) - end < 8
250
+ ) {
251
+ i++;
252
+ end = /** @type {number} */ (sorted[i]) + 1;
253
+ }
254
+ if (doc) {
255
+ const html = doc.lineRange(start, end);
256
+ for (let k = 0; k < html.length; k++) {
257
+ out.set(start + k, /** @type {string} */ (html[k]));
258
+ }
259
+ } else {
260
+ for (let k = start; k < end; k++) {
261
+ const text = k === lines.length ? (state.partial ?? "") : lines[k];
262
+ out.set(k, escapeText(text ?? ""));
263
+ }
264
+ }
265
+ i++;
266
+ }
267
+ return out;
268
+ }
269
+
270
+ /** @param {1 | -1} dir */
271
+ function jump(dir) {
272
+ const { rows, changeStarts } = ensureLayout();
273
+ if (changeStarts.length === 0) return undefined;
274
+ const at = changeStarts.findIndex((r) => rows[r]?.change === current);
275
+ const index =
276
+ at === -1
277
+ ? dir === 1
278
+ ? 0
279
+ : changeStarts.length - 1
280
+ : (at + dir + changeStarts.length) % changeStarts.length;
281
+ const rowIndex = /** @type {number} */ (changeStarts[index]);
282
+ current = /** @type {number} */ (rows[rowIndex]?.change);
283
+ notify();
284
+ emit("reveal", { row: rowIndex, align: "third" });
285
+ const detail = { change: current, index, count: changeStarts.length };
286
+ emit("navigate", detail);
287
+ return detail;
288
+ }
289
+
290
+ function reviewDetail() {
291
+ return { decisions, text: applyReview(state, decisions) };
292
+ }
293
+
294
+ const api = {
295
+ /** Store contract: `$diff` re-renders on every change. */
296
+ subscribe(/** @type {(value: any) => void} */ fn) {
297
+ subscribers.add(fn);
298
+ fn(api);
299
+ return () => subscribers.delete(fn);
300
+ },
301
+
302
+ /**
303
+ * @template {keyof DiffEvents} K
304
+ * @param {K} type
305
+ * @param {(detail: DiffEvents[K]) => void} fn
306
+ */
307
+ on(type, fn) {
308
+ if (!listeners[type]) listeners[type] = /** @type {any} */ (new Set());
309
+ const set = /** @type {Set<(detail: DiffEvents[K]) => void>} */ (
310
+ listeners[type]
311
+ );
312
+ set.add(fn);
313
+ return () => set.delete(fn);
314
+ },
315
+
316
+ /** Bumped on every change, for cheap memo keys. */
317
+ get version() {
318
+ return version;
319
+ },
320
+
321
+ /**
322
+ * Diffs two texts. With `streaming`, `after` may still be growing.
323
+ * Replacing (not growing) the texts resets folds and review.
324
+ * @param {string} nextBefore
325
+ * @param {string} nextAfter
326
+ * @param {{ streaming?: boolean }} [opts]
327
+ */
328
+ update(nextBefore, nextAfter, { streaming: nextStreaming = false } = {}) {
329
+ if (
330
+ !patch &&
331
+ nextBefore === before &&
332
+ nextAfter === after &&
333
+ nextStreaming === streaming
334
+ ) {
335
+ return;
336
+ }
337
+ const replaced =
338
+ patch !== null || nextBefore !== before || !nextAfter.startsWith(after);
339
+ before = nextBefore;
340
+ after = nextAfter;
341
+ streaming = nextStreaming;
342
+ patch = null;
343
+ if (replaced) resetView();
344
+ recompute();
345
+ notify();
346
+ },
347
+
348
+ /**
349
+ * Shows a parsed file patch instead of two texts.
350
+ * @param {import("./diff-edits.js").FilePatch | null} nextPatch
351
+ */
352
+ setPatch(nextPatch) {
353
+ if (nextPatch === patch) return;
354
+ patch = nextPatch;
355
+ resetView();
356
+ recompute();
357
+ notify();
358
+ },
359
+
360
+ /** @param {Partial<DiffOptions>} next */
361
+ setOptions(next) {
362
+ /** @type {Partial<DiffOptions>} */
363
+ const changed = {};
364
+ for (const key of /** @type {(keyof DiffOptions)[]} */ (
365
+ Object.keys(next)
366
+ )) {
367
+ if (next[key] !== undefined && next[key] !== options[key]) {
368
+ /** @type {any} */ (changed)[key] = next[key];
369
+ }
370
+ }
371
+ if (Object.keys(changed).length === 0) return;
372
+ options = { ...options, ...changed };
373
+ if ("ignoreWhitespace" in changed) {
374
+ session = createDiffSession({
375
+ ignoreWhitespace: options.ignoreWhitespace,
376
+ });
377
+ recompute();
378
+ } else {
379
+ layout = null;
380
+ if ("language" in changed) syncDocs();
381
+ }
382
+ notify();
383
+ emit("options", options);
384
+ },
385
+
386
+ options() {
387
+ return options;
388
+ },
389
+
390
+ state() {
391
+ return state;
392
+ },
393
+
394
+ rows() {
395
+ return ensureLayout().rows;
396
+ },
397
+
398
+ /**
399
+ * Rows `[start, end)` with highlighted HTML for each side, word diffs
400
+ * overlaid, and line-end markers.
401
+ * @param {number} start
402
+ * @param {number} end
403
+ * @returns {RenderedRow[]}
404
+ */
405
+ renderRows(start, end) {
406
+ const { rows } = ensureLayout();
407
+ const view = options.view;
408
+ const slice = rows.slice(start, end);
409
+ /** @type {number[]} */
410
+ const oldIdx = [];
411
+ /** @type {number[]} */
412
+ const newIdx = [];
413
+ for (const row of slice) {
414
+ if (row.kind === "fold" || row.kind === "pending" || row.note) continue;
415
+ if (
416
+ row.old !== undefined &&
417
+ (row.kind !== "context" || view === "split")
418
+ ) {
419
+ oldIdx.push(row.old);
420
+ }
421
+ if (row.new !== undefined) newIdx.push(row.new);
422
+ }
423
+ const oldHtml = fetchLines("old", oldIdx);
424
+ const newHtml = fetchLines("new", newIdx);
425
+ return slice.map((row, i) => {
426
+ let oHtml = row.old === undefined ? "" : (oldHtml.get(row.old) ?? "");
427
+ let nHtml = row.new === undefined ? "" : (newHtml.get(row.new) ?? "");
428
+ if (options.wordDiff && row.moved === undefined) {
429
+ const pairNew =
430
+ row.kind === "del"
431
+ ? row.pairNew
432
+ : row.kind === "change"
433
+ ? row.new
434
+ : undefined;
435
+ const pairOld =
436
+ row.kind === "add"
437
+ ? row.pairOld
438
+ : row.kind === "change"
439
+ ? row.old
440
+ : undefined;
441
+ if (
442
+ row.old !== undefined &&
443
+ pairNew !== undefined &&
444
+ row.kind !== "add"
445
+ ) {
446
+ oHtml = overlayRanges(
447
+ oHtml,
448
+ wordsFor(row.old, pairNew).old,
449
+ "shl-diff-word",
450
+ );
451
+ }
452
+ if (
453
+ row.new !== undefined &&
454
+ pairOld !== undefined &&
455
+ row.kind !== "del"
456
+ ) {
457
+ nHtml = overlayRanges(
458
+ nHtml,
459
+ wordsFor(pairOld, row.new).new,
460
+ "shl-diff-word",
461
+ );
462
+ }
463
+ }
464
+ if (row.old !== undefined) {
465
+ oHtml = markLineEnd(
466
+ oHtml,
467
+ row.old,
468
+ state.beforeLines,
469
+ state.beforeNoEol,
470
+ );
471
+ }
472
+ if (row.new !== undefined) {
473
+ nHtml = markLineEnd(
474
+ nHtml,
475
+ row.new,
476
+ state.afterLines,
477
+ state.afterNoEol,
478
+ );
479
+ }
480
+ return {
481
+ row,
482
+ index: start + i,
483
+ oldHtml: oHtml,
484
+ newHtml: nHtml,
485
+ };
486
+ });
487
+ },
488
+
489
+ stats() {
490
+ if (statsCache?.state !== state) {
491
+ statsCache = { state, value: diffStats(state) };
492
+ }
493
+ return statsCache.value;
494
+ },
495
+
496
+ /** Widest line per side in columns, and the gutter width in characters. */
497
+ columns() {
498
+ if (columnsCache?.state !== state) {
499
+ const tab = options.tabSize;
500
+ if (widths.tabSize !== tab) {
501
+ widths.oldLines = null;
502
+ widths.newLines = null;
503
+ widths.tabSize = tab;
504
+ }
505
+ if (widths.oldLines !== state.beforeLines) {
506
+ widths.oldLines = state.beforeLines;
507
+ widths.old = maxColumns(state.beforeLines, tab, 0);
508
+ }
509
+ if (
510
+ widths.newLines !== state.afterLines ||
511
+ state.afterLines.length < widths.newCount
512
+ ) {
513
+ widths.newLines = state.afterLines;
514
+ widths.newCount = 0;
515
+ widths.new = 0;
516
+ }
517
+ widths.new = Math.max(
518
+ widths.new,
519
+ maxColumns(state.afterLines, tab, widths.newCount),
520
+ );
521
+ widths.newCount = state.afterLines.length;
522
+ columnsCache = {
523
+ state,
524
+ value: {
525
+ old: widths.old,
526
+ new: Math.max(widths.new, (state.partial ?? "").length),
527
+ gutter:
528
+ String(
529
+ Math.max(state.beforeLines.length, state.afterLines.length + 1),
530
+ ).length + 2,
531
+ },
532
+ };
533
+ }
534
+ return columnsCache.value;
535
+ },
536
+
537
+ /** One mark per change, as fractions of the row count. */
538
+ marks() {
539
+ const { rows, changeStarts } = ensureLayout();
540
+ const total = rows.length;
541
+ if (total === 0) return [];
542
+ return changeStarts.map((rowIndex) => {
543
+ const id = /** @type {number} */ (rows[rowIndex]?.change);
544
+ let last = rowIndex;
545
+ let hasDel = false;
546
+ let hasAdd = false;
547
+ while (last < rows.length && rows[last]?.change === id) {
548
+ const r = /** @type {ViewRow} */ (rows[last]);
549
+ if (r.kind === "del" || (r.kind === "change" && r.old !== undefined))
550
+ hasDel = true;
551
+ if (r.kind === "add" || (r.kind === "change" && r.new !== undefined))
552
+ hasAdd = true;
553
+ last++;
554
+ }
555
+ return {
556
+ id,
557
+ rowIndex,
558
+ top: rowIndex / total,
559
+ height: (last - rowIndex) / total,
560
+ kind: hasDel && hasAdd ? "mod" : hasDel ? "del" : "add",
561
+ decision: decisions.get(id),
562
+ };
563
+ });
564
+ },
565
+
566
+ /** The change last navigated to or decided, or -1. */
567
+ current() {
568
+ return current;
569
+ },
570
+
571
+ isExpanded(/** @type {string} */ key) {
572
+ return expanded.has(key);
573
+ },
574
+
575
+ toggleFold(/** @type {string} */ key) {
576
+ const next = new Set(expanded);
577
+ if (next.has(key)) next.delete(key);
578
+ else next.add(key);
579
+ expanded = next;
580
+ layout = null;
581
+ notify();
582
+ },
583
+
584
+ expandAll() {
585
+ expanded = new Set(
586
+ ensureLayout()
587
+ .rows.filter((r) => r.kind === "fold" && !r.fold?.unknown)
588
+ .map((r) => r.key),
589
+ );
590
+ layout = null;
591
+ notify();
592
+ },
593
+
594
+ collapseAll() {
595
+ expanded = new Set();
596
+ layout = null;
597
+ notify();
598
+ },
599
+
600
+ nextChange() {
601
+ return jump(1);
602
+ },
603
+
604
+ prevChange() {
605
+ return jump(-1);
606
+ },
607
+
608
+ /**
609
+ * Asks views to scroll a row into view.
610
+ * @param {number} row
611
+ * @param {"start" | "center" | "third"} [align]
612
+ */
613
+ reveal(row, align = "center") {
614
+ emit("reveal", { row, align });
615
+ },
616
+
617
+ /**
618
+ * Views report which rows `[start, end)` they show, for minimaps.
619
+ * @param {number} start
620
+ * @param {number} end
621
+ */
622
+ setViewport(start, end) {
623
+ emit("viewport", { start, end, count: ensureLayout().rows.length });
624
+ },
625
+
626
+ decisions() {
627
+ return decisions;
628
+ },
629
+
630
+ /**
631
+ * @param {number} change
632
+ * @param {"accepted" | "rejected" | undefined} decision
633
+ */
634
+ decide(change, decision) {
635
+ const next = new Map(decisions);
636
+ if (decision) next.set(change, decision);
637
+ else next.delete(change);
638
+ decisions = next;
639
+ current = change;
640
+ notify();
641
+ emit("review", reviewDetail());
642
+ },
643
+
644
+ /** @param {"accepted" | "rejected"} decision */
645
+ decideAll(decision) {
646
+ decisions = new Map(
647
+ state.blocks
648
+ .filter((b) => b.type === "change")
649
+ .map((b) => [/** @type {number} */ (b.id), decision]),
650
+ );
651
+ notify();
652
+ emit("review", reviewDetail());
653
+ },
654
+
655
+ /** The text with rejected changes reverted. */
656
+ result() {
657
+ return applyReview(state, decisions);
658
+ },
659
+
660
+ /** @param {{ oldPath?: string, newPath?: string }} [paths] */
661
+ patch(paths) {
662
+ return toUnifiedPatch(state, { ...paths, context: options.context });
663
+ },
664
+ };
665
+
666
+ return api;
667
+ }
668
+
669
+ /** @typedef {ReturnType<typeof createDiffController>} DiffController */
670
+
671
+ /**
672
+ * @param {import("./diff.js").Row[]} list
673
+ * @param {Annotation[]} notes
674
+ * @returns {ViewRow[]}
675
+ */
676
+ function withNotes(list, notes) {
677
+ if (notes.length === 0) return list;
678
+ /** @type {Map<string, Annotation[]>} */
679
+ const byLine = new Map();
680
+ for (const note of notes) {
681
+ const key = `${note.side}:${note.line - 1}`;
682
+ const bucket = byLine.get(key) ?? [];
683
+ bucket.push(note);
684
+ byLine.set(key, bucket);
685
+ }
686
+ /** @type {ViewRow[]} */
687
+ const out = [];
688
+ for (const row of list) {
689
+ out.push(row);
690
+ const hits = [
691
+ ...(row.old === undefined ? [] : (byLine.get(`old:${row.old}`) ?? [])),
692
+ ...(row.new === undefined ? [] : (byLine.get(`new:${row.new}`) ?? [])),
693
+ ];
694
+ for (const [i, note] of hits.entries()) {
695
+ out.push({
696
+ key: `${row.key}n${i}`,
697
+ kind: /** @type {any} */ ("note"),
698
+ note,
699
+ });
700
+ }
701
+ }
702
+ return out;
703
+ }
704
+
705
+ /**
706
+ * @param {string[]} lines
707
+ * @param {number} tabSize
708
+ * @param {number} from first line to measure
709
+ */
710
+ function maxColumns(lines, tabSize, from) {
711
+ let max = 0;
712
+ for (let i = from; i < lines.length; i++) {
713
+ const line = /** @type {string} */ (lines[i]);
714
+ let cols = line.length;
715
+ if (line.includes("\t")) {
716
+ cols += (line.split("\t").length - 1) * (tabSize - 1);
717
+ }
718
+ if (cols > max) max = cols;
719
+ }
720
+ return max;
721
+ }