@bridgebrew/ui 0.1.11-next.93 → 0.1.11

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.
@@ -0,0 +1,799 @@
1
+ import * as React from "react";
2
+
3
+ import { cn } from "../../../lib/utils";
4
+ import { Checkbox } from "../../core/checkbox";
5
+ import type { CodeToken } from "../../core/code-block";
6
+ import { codeTokenPalette } from "../../core/code-block/palette";
7
+ import { Icon } from "../../core/icon";
8
+ import {
9
+ changedWords,
10
+ gapsOf,
11
+ pairsOf,
12
+ parseDiff,
13
+ type CharRange,
14
+ type DiffFileModel,
15
+ type DiffGap,
16
+ type DiffLine,
17
+ type DiffStatus,
18
+ } from "./diff";
19
+
20
+ // A diff to read, file by file (`./diff.ts` parses it): each file a header (its icon, name, folder, +/−, a slot for
21
+ // actions) that sticks while the file scrolls, then its hunks, unified (one number column, the new one; "−" on a
22
+ // removed line) or split, the words that changed inside a removed/added pair marked, coloured from tokens a caller
23
+ // highlights (as CodeBlock: never the kit's bundle). The unchanged lines between hunks fold; with `loadLines` they
24
+ // expand by 20 or all. A generated file shows its header only until asked; a file reviewed (review mode) folds.
25
+
26
+ /** One file to show: its own patch (a `git diff` of that file, or its hunks), or where reading it stands. */
27
+ interface DiffViewFile {
28
+ path: string;
29
+ /** Its unified diff; `{ loading: true }` while read; `{ error }` when it could not be; none: not read yet (the caller
30
+ * reads it when `onFileVisible` names it). */
31
+ patch?: string | { loading: true } | { error: string } | undefined;
32
+ /** Its counts when known before its patch (else the patch's). */
33
+ added?: number | undefined;
34
+ removed?: number | undefined;
35
+ /** A lockfile, a build output: minimized until "Show diff". */
36
+ generated?: boolean | undefined;
37
+ /** Its status when known before its patch (else the patch's). */
38
+ status?: DiffStatus | undefined;
39
+ }
40
+
41
+ /** What a ref on DiffView gives. */
42
+ interface DiffViewHandle {
43
+ /** Scrolls the nearest scrolling ancestor to `path`'s file. */
44
+ scrollTo(path: string): void;
45
+ }
46
+
47
+ type Tokens = readonly (readonly CodeToken[])[];
48
+
49
+ interface DiffViewProps extends Omit<React.ComponentProps<"div">, "children" | "ref"> {
50
+ files: readonly DiffViewFile[];
51
+ /** One column of lines (default), or the old and the new side by side (lines wrap there). */
52
+ mode?: "unified" | "split";
53
+ /** Long lines wrap rather than scroll sideways. */
54
+ wrap?: boolean;
55
+ /** `code` cut into coloured tokens, line by line (Shiki's `codeToTokens(…).tokens`, css-variables theme), for
56
+ * `language` (the file's extension, `ts`, `json`; its name without one); `undefined`: plain. */
57
+ highlight?: (code: string, language: string) => Promise<Tokens | undefined>;
58
+ /** Lines `from` to `to` (1-based, inclusive) of `path`'s new text; fewer at its end. Without it, folds don't expand. */
59
+ loadLines?: (path: string, from: number, to: number) => Promise<readonly string[]>;
60
+ /** A file header's actions (a `⋯` menu), on its right. */
61
+ actions?: (file: DiffViewFile) => React.ReactNode;
62
+ /** Review mode: a Reviewed checkbox in each header; a reviewed file folds. */
63
+ review?: {
64
+ reviewed: ReadonlySet<string>;
65
+ onReviewedChange: (path: string, reviewed: boolean) => void;
66
+ };
67
+ /** A file came into view (or near it): read its patch when it has none. */
68
+ onFileVisible?: (path: string) => void;
69
+ /** The file to scroll to, at once and each time it changes. */
70
+ focus?: string | undefined;
71
+ ref?: React.Ref<DiffViewHandle>;
72
+ }
73
+
74
+ /** Lines one arrow of a fold shows. */
75
+ const STEP = 20;
76
+
77
+ /** The language `highlight` is asked for: the extension, else the name. */
78
+ const languageOf = (path: string) => {
79
+ const name = path.slice(path.lastIndexOf("/") + 1).toLowerCase();
80
+ const dot = name.lastIndexOf(".");
81
+ return dot > 0 ? name.slice(dot + 1) : name;
82
+ };
83
+
84
+ function DiffView({
85
+ files,
86
+ mode = "unified",
87
+ wrap = false,
88
+ highlight,
89
+ loadLines,
90
+ actions,
91
+ review,
92
+ onFileVisible,
93
+ focus,
94
+ ref,
95
+ className,
96
+ ...props
97
+ }: DiffViewProps) {
98
+ const root = React.useRef<HTMLDivElement>(null);
99
+ /** The file scrolled to, kept at the top while the files around it are read and grow, until the user scrolls. */
100
+ const pinned = React.useRef<string>(undefined);
101
+ const reveal = React.useCallback((path: string) => {
102
+ const found = [...(root.current?.querySelectorAll<HTMLElement>("[data-diff-file]") ?? [])].find(
103
+ (element) => element.dataset.diffFile === path,
104
+ );
105
+ found?.scrollIntoView?.({ block: "start" });
106
+ }, []);
107
+ const scrollTo = React.useCallback(
108
+ (path: string) => {
109
+ pinned.current = path;
110
+ reveal(path);
111
+ },
112
+ [reveal],
113
+ );
114
+ React.useImperativeHandle(ref, () => ({ scrollTo }), [scrollTo]);
115
+ React.useEffect(() => {
116
+ const element = root.current;
117
+ if (!element || typeof ResizeObserver === "undefined") return;
118
+ const observer = new ResizeObserver(() => {
119
+ if (pinned.current !== undefined) reveal(pinned.current);
120
+ });
121
+ observer.observe(element);
122
+ const release = () => {
123
+ pinned.current = undefined;
124
+ };
125
+ const events = ["wheel", "touchstart", "keydown", "pointerdown"] as const;
126
+ events.forEach((name) =>
127
+ window.addEventListener(name, release, { capture: true, passive: true }),
128
+ );
129
+ return () => {
130
+ observer.disconnect();
131
+ events.forEach((name) => window.removeEventListener(name, release, { capture: true }));
132
+ };
133
+ }, [reveal]);
134
+ const paths = files.map((file) => file.path).join("\n");
135
+ // The file asked for, scrolled to once it is there (files may come after the view), once per ask.
136
+ const focused = React.useRef<string>(undefined);
137
+ React.useEffect(() => {
138
+ if (focus === undefined || focused.current === focus) return;
139
+ if (!files.some((file) => file.path === focus)) return;
140
+ focused.current = focus;
141
+ scrollTo(focus);
142
+ }, [focus, paths, scrollTo]);
143
+
144
+ // The files seen (in view or near it): highlighted, and named to `onFileVisible`. Without IntersectionObserver
145
+ // (a test's DOM), every file counts as seen.
146
+ const observing = typeof IntersectionObserver !== "undefined";
147
+ const [seen, setSeen] = React.useState<ReadonlySet<string>>(new Set());
148
+ const visible = React.useRef(onFileVisible);
149
+ visible.current = onFileVisible;
150
+ React.useEffect(() => {
151
+ if (!observing || !root.current) return;
152
+ const observer = new IntersectionObserver(
153
+ (entries) => {
154
+ const shown = entries
155
+ .filter((entry) => entry.isIntersecting)
156
+ .map((entry) => (entry.target as HTMLElement).dataset.diffFile ?? "");
157
+ if (!shown.length) return;
158
+ shown.forEach((path) => visible.current?.(path));
159
+ setSeen((was) =>
160
+ shown.every((path) => was.has(path)) ? was : new Set([...was, ...shown]),
161
+ );
162
+ },
163
+ { rootMargin: "400px 0px" },
164
+ );
165
+ root.current
166
+ .querySelectorAll("[data-diff-file]")
167
+ .forEach((element) => observer.observe(element));
168
+ return () => observer.disconnect();
169
+ }, [paths, observing]);
170
+
171
+ return (
172
+ <div
173
+ ref={root}
174
+ data-slot="diff-view"
175
+ data-mode={mode}
176
+ className={cn("flex flex-col gap-3 text-sm", codeTokenPalette, className)}
177
+ {...props}
178
+ >
179
+ {files.map((file) => (
180
+ <FileSection
181
+ key={file.path}
182
+ file={file}
183
+ mode={mode}
184
+ wrap={wrap || mode === "split"}
185
+ highlight={!observing || seen.has(file.path) ? highlight : undefined}
186
+ loadLines={loadLines}
187
+ actions={actions}
188
+ review={review}
189
+ />
190
+ ))}
191
+ </div>
192
+ );
193
+ }
194
+
195
+ /** A file's added and removed lines. */
196
+ const Counts = ({ added, removed }: { added: number; removed: number }) => (
197
+ <span data-slot="diff-view-counts" className="shrink-0 font-mono text-xs tabular-nums">
198
+ {added > 0 && <span className="text-success">+{added.toLocaleString("en-US")}</span>}
199
+ {added > 0 && removed > 0 && " "}
200
+ {removed > 0 && <span className="text-destructive">−{removed.toLocaleString("en-US")}</span>}
201
+ </span>
202
+ );
203
+
204
+ /** A gap's lines shown: `top` from its start, `bottom` from its end; `to`: its end once read (a file's last gap). */
205
+ interface Revealed {
206
+ top: number;
207
+ bottom: number;
208
+ to?: number;
209
+ }
210
+
211
+ function FileSection({
212
+ file,
213
+ mode,
214
+ wrap,
215
+ highlight,
216
+ loadLines,
217
+ actions,
218
+ review,
219
+ }: Pick<DiffViewProps, "highlight" | "loadLines" | "actions" | "review"> & {
220
+ file: DiffViewFile;
221
+ mode: "unified" | "split";
222
+ wrap: boolean;
223
+ }) {
224
+ const patch = file.patch;
225
+ const model = React.useMemo(
226
+ () =>
227
+ typeof patch === "string"
228
+ ? (parseDiff(patch, file.path).find((each) => each.path === file.path) ??
229
+ parseDiff(patch, file.path)[0])
230
+ : undefined,
231
+ [patch, file.path],
232
+ );
233
+ const reviewed = review?.reviewed.has(file.path) ?? false;
234
+ const [showGenerated, setShowGenerated] = React.useState(false);
235
+ const slash = file.path.lastIndexOf("/");
236
+ const added = file.added ?? model?.added ?? 0;
237
+ const removed = file.removed ?? model?.removed ?? 0;
238
+ const status = file.status ?? model?.status;
239
+ return (
240
+ <section
241
+ aria-label={file.path}
242
+ data-diff-file={file.path}
243
+ data-reviewed={reviewed || undefined}
244
+ className="shrink-0 scroll-mt-0 overflow-clip rounded-default border border-border-subtle bg-background"
245
+ >
246
+ <header
247
+ data-slot="diff-view-header"
248
+ className="sticky top-0 z-[2] flex h-9 items-center gap-2 border-b border-border-subtle bg-surface px-3"
249
+ >
250
+ <Icon name="file" size={14} className="shrink-0 text-muted" />
251
+ <span className="min-w-0 truncate">
252
+ <span className="font-semibold">{file.path.slice(slash + 1)}</span>
253
+ {slash > 0 && <span className="ml-1.5 text-muted">{file.path.slice(0, slash + 1)}</span>}
254
+ {model?.oldPath && <span className="ml-1.5 text-muted">← {model.oldPath}</span>}
255
+ </span>
256
+ {(status === "added" || status === "deleted") && (
257
+ <span className="shrink-0 text-xs text-muted">
258
+ {status === "added" ? "New" : "Deleted"}
259
+ </span>
260
+ )}
261
+ <span className="flex-1" />
262
+ <Counts added={added} removed={removed} />
263
+ {review && (
264
+ <label className="flex shrink-0 cursor-pointer items-center gap-1.5 text-xs text-secondary">
265
+ <Checkbox
266
+ checked={reviewed}
267
+ onCheckedChange={(checked: boolean) => review.onReviewedChange(file.path, checked)}
268
+ />
269
+ Reviewed
270
+ </label>
271
+ )}
272
+ {actions?.(file)}
273
+ </header>
274
+ {reviewed ? null : file.generated && !showGenerated ? (
275
+ <p className="m-0 px-3 py-2 text-xs text-muted">
276
+ Generated file ·{" "}
277
+ <button
278
+ type="button"
279
+ className="cursor-pointer border-0 bg-transparent p-0 text-xs text-accent hover:underline"
280
+ onClick={() => setShowGenerated(true)}
281
+ >
282
+ Show diff
283
+ </button>
284
+ </p>
285
+ ) : patch === undefined || (typeof patch === "object" && "loading" in patch) ? (
286
+ <p
287
+ className="m-0 flex h-16 items-center px-3 text-xs text-muted"
288
+ data-slot="diff-view-reading"
289
+ >
290
+ Reading…
291
+ </p>
292
+ ) : typeof patch === "object" ? (
293
+ <p role="alert" className="m-0 px-3 py-2 text-xs text-destructive">
294
+ {patch.error}
295
+ </p>
296
+ ) : !model?.hunks.length ? (
297
+ <p className="m-0 px-3 py-2 text-xs text-muted">
298
+ No text diff (a binary file, an empty one or a mode change).
299
+ </p>
300
+ ) : (
301
+ <Hunks model={model} mode={mode} wrap={wrap} highlight={highlight} loadLines={loadLines} />
302
+ )}
303
+ </section>
304
+ );
305
+ }
306
+
307
+ /** A side's line, by number: `o12` the old side's line 12, `n12` the new side's. */
308
+ const keyOf = (line: DiffLine) => (line.kind === "removed" ? `o${line.old}` : `n${line.new}`);
309
+
310
+ function Hunks({
311
+ model,
312
+ mode,
313
+ wrap,
314
+ highlight,
315
+ loadLines,
316
+ }: Pick<DiffViewProps, "highlight" | "loadLines"> & {
317
+ model: DiffFileModel;
318
+ mode: "unified" | "split";
319
+ wrap: boolean;
320
+ }) {
321
+ const gaps = React.useMemo(() => gapsOf(model), [model]);
322
+ /** The lines of the new text read for the folds, by number. */
323
+ const [known, setKnown] = React.useState<ReadonlyMap<number, string>>(new Map());
324
+ const [revealed, setRevealed] = React.useState<ReadonlyMap<number, Revealed>>(new Map());
325
+ const [busy, setBusy] = React.useState(false);
326
+
327
+ // The words that changed in each removed/added pair.
328
+ const marks = React.useMemo(() => {
329
+ const found = new Map<string, CharRange[]>();
330
+ for (const hunk of model.hunks)
331
+ for (const { left, right } of pairsOf(hunk.lines))
332
+ if (left?.kind === "removed" && right?.kind === "added") {
333
+ const [before, after] = changedWords(left.text, right.text);
334
+ if (before.length) found.set(keyOf(left), before);
335
+ if (after.length) found.set(keyOf(right), after);
336
+ }
337
+ return found;
338
+ }, [model]);
339
+
340
+ // Each gap's lines shown, as context lines.
341
+ const shownOf = (index: number, gap: DiffGap) => {
342
+ const state = revealed.get(index) ?? { top: 0, bottom: 0 };
343
+ const to = gap.to ?? state.to;
344
+ const line = (number: number): DiffLine => ({
345
+ kind: "context",
346
+ text: known.get(number) ?? "",
347
+ old: number + gap.offset,
348
+ new: number,
349
+ });
350
+ const top = Array.from({ length: state.top }, (_, at) => line(gap.from + at));
351
+ const bottom =
352
+ to === undefined
353
+ ? []
354
+ : Array.from({ length: state.bottom }, (_, at) => line(to - state.bottom + 1 + at));
355
+ const hidden = to === undefined ? undefined : to - gap.from + 1 - state.top - state.bottom;
356
+ return { state, to, top, bottom, hidden };
357
+ };
358
+
359
+ // The tokens of each side's lines (the new side: context, added and revealed lines; the old: context and removed),
360
+ // each side highlighted as one text, in order.
361
+ const language = languageOf(model.path);
362
+ const [tokens, setTokens] = React.useState<ReadonlyMap<string, readonly CodeToken[]>>(new Map());
363
+ React.useEffect(() => {
364
+ if (!highlight) return;
365
+ let live = true;
366
+ const neu = new Map<number, string>(known);
367
+ const old = new Map<number, string>();
368
+ for (const hunk of model.hunks)
369
+ for (const line of hunk.lines) {
370
+ if (line.kind !== "removed") neu.set(line.new, line.text);
371
+ if (line.kind !== "added") old.set(line.old, line.text);
372
+ }
373
+ const side = async (lines: Map<number, string>, prefix: string) => {
374
+ const numbers = [...lines.keys()].sort((a, b) => a - b);
375
+ const cut = await highlight(numbers.map((number) => lines.get(number)).join("\n"), language);
376
+ return numbers.flatMap((number, at): [string, readonly CodeToken[]][] => {
377
+ const each = cut?.[at];
378
+ return each ? [[`${prefix}${number}`, each]] : [];
379
+ });
380
+ };
381
+ Promise.all([side(neu, "n"), side(old, "o")]).then(
382
+ ([a, b]) => {
383
+ if (!live) return;
384
+ setTokens(new Map([...a, ...b]));
385
+ },
386
+ () => {},
387
+ );
388
+ return () => {
389
+ live = false;
390
+ };
391
+ }, [highlight, model, known, language]);
392
+
393
+ const expand = (index: number, direction: "up" | "down" | "all") => {
394
+ if (!loadLines || busy) return;
395
+ const gap = gaps[index]!;
396
+ const { state, to, hidden } = shownOf(index, gap);
397
+ const start = gap.from + state.top;
398
+ const end = to === undefined ? undefined : to - state.bottom;
399
+ const [from, last] =
400
+ direction === "up" && end !== undefined
401
+ ? [Math.max(start, end - STEP + 1), end]
402
+ : direction === "all"
403
+ ? [start, end ?? start + 100_000]
404
+ : [start, Math.min(start + STEP - 1, end ?? Infinity)];
405
+ if (hidden !== undefined && hidden <= 0) return;
406
+ setBusy(true);
407
+ loadLines(model.path, from, last)
408
+ .then(
409
+ (lines) => {
410
+ setKnown((was) => {
411
+ const next = new Map(was);
412
+ lines.forEach((text, at) => next.set(from + at, text));
413
+ return next;
414
+ });
415
+ setRevealed((was) => {
416
+ const next = new Map(was);
417
+ const short = lines.length < last - from + 1;
418
+ const after =
419
+ direction === "up"
420
+ ? { ...state, bottom: state.bottom + lines.length }
421
+ : { ...state, top: state.top + lines.length };
422
+ // The file's end, found: the last gap ends there.
423
+ next.set(
424
+ index,
425
+ gap.to === undefined && short ? { ...after, to: from + lines.length - 1 } : after,
426
+ );
427
+ return next;
428
+ });
429
+ },
430
+ () => {},
431
+ )
432
+ .finally(() => setBusy(false));
433
+ };
434
+
435
+ // The number column fits the file's largest number.
436
+ const largest = Math.max(
437
+ ...known.keys(),
438
+ ...model.hunks.map((hunk) =>
439
+ Math.max(hunk.oldStart + hunk.oldCount, hunk.newStart + hunk.newCount),
440
+ ),
441
+ );
442
+ const width = `${String(largest).length + 2}ch`;
443
+ const line = (each: DiffLine) => (
444
+ <UnifiedLine
445
+ key={`${each.kind}${keyOf(each)}`}
446
+ line={each}
447
+ width={width}
448
+ wrap={wrap}
449
+ tokens={tokens.get(each.kind === "removed" ? `o${each.old}` : `n${each.new}`)}
450
+ marks={marks.get(keyOf(each))}
451
+ />
452
+ );
453
+ const splitRows = (lines: readonly DiffLine[], key: string) =>
454
+ pairsOf(lines).map(({ left, right }, at) => (
455
+ <div key={`${key}-${at}`} data-slot="diff-view-row" className="contents">
456
+ <SplitSide line={left} side="old" width={width} tokens={tokens} marks={marks} />
457
+ <SplitSide line={right} side="new" width={width} tokens={tokens} marks={marks} />
458
+ </div>
459
+ ));
460
+ const lines = (each: readonly DiffLine[], key: string) =>
461
+ mode === "split" ? splitRows(each, key) : each.map(line);
462
+
463
+ const gapRows = (index: number) => {
464
+ const gap = gaps[index];
465
+ if (!gap) return null;
466
+ const { top, bottom, hidden, to } = shownOf(index, gap);
467
+ // The gap after the last hunk: its end unknown until read.
468
+ const last = gap.to === undefined;
469
+ // A file's end, not read yet: without `loadLines`, nothing to say.
470
+ const open = hidden === undefined ? !!loadLines : hidden > 0;
471
+ return (
472
+ <React.Fragment key={`gap${index}`}>
473
+ {lines(top, `gap${index}top`)}
474
+ {open && (
475
+ <Fold
476
+ hidden={hidden}
477
+ section={last ? "" : gap.section}
478
+ split={mode === "split"}
479
+ width={width}
480
+ busy={busy}
481
+ expand={
482
+ loadLines &&
483
+ ((direction) => {
484
+ expand(index, direction);
485
+ })
486
+ }
487
+ directions={
488
+ hidden !== undefined && hidden <= STEP
489
+ ? []
490
+ : last
491
+ ? ["down"]
492
+ : index === 0 && gap.from === 1
493
+ ? ["up"]
494
+ : ["down", "up"]
495
+ }
496
+ />
497
+ )}
498
+ {to !== undefined && lines(bottom, `gap${index}bottom`)}
499
+ </React.Fragment>
500
+ );
501
+ };
502
+
503
+ // A gap sits before the hunk whose start it reaches; the last one after every hunk.
504
+ const gapBefore = new Map(
505
+ gaps.flatMap((gap, index) =>
506
+ gap.to === undefined
507
+ ? []
508
+ : [[model.hunks.findIndex((hunk) => hunk.newStart === gap.to! + 1), index] as const],
509
+ ),
510
+ );
511
+ return (
512
+ <div
513
+ data-slot="diff-view-body"
514
+ className={cn(
515
+ "text-xs leading-5",
516
+ mode === "split"
517
+ ? "grid grid-cols-[auto_minmax(0,1fr)_auto_minmax(0,1fr)]"
518
+ : !wrap && "overflow-x-auto",
519
+ )}
520
+ >
521
+ <div
522
+ className={cn(
523
+ mode === "split" ? "contents" : "min-w-full",
524
+ mode === "unified" && !wrap && "w-max",
525
+ )}
526
+ >
527
+ {model.hunks.map((hunk, at) => (
528
+ <React.Fragment key={`hunk${at}`}>
529
+ {gapBefore.has(at) && gapRows(gapBefore.get(at)!)}
530
+ {lines(hunk.lines, `hunk${at}`)}
531
+ </React.Fragment>
532
+ ))}
533
+ {gaps.length > 0 && gaps.at(-1)!.to === undefined && gapRows(gaps.length - 1)}
534
+ </div>
535
+ </div>
536
+ );
537
+ }
538
+
539
+ /** The row folding a gap: the next hunk's section, how many lines it hides, and the arrows that show them. */
540
+ function Fold({
541
+ hidden,
542
+ section,
543
+ split,
544
+ width,
545
+ busy,
546
+ expand,
547
+ directions,
548
+ }: {
549
+ hidden: number | undefined;
550
+ section: string;
551
+ split: boolean;
552
+ width: string;
553
+ busy: boolean;
554
+ expand: ((direction: "up" | "down" | "all") => void) | undefined;
555
+ directions: ("up" | "down")[];
556
+ }) {
557
+ const label =
558
+ hidden === undefined
559
+ ? "More lines"
560
+ : `${hidden.toLocaleString("en-US")} unchanged line${hidden === 1 ? "" : "s"}`;
561
+ return (
562
+ <div
563
+ data-slot="diff-view-fold"
564
+ className={cn(
565
+ "flex min-h-7 items-center bg-hover/60 font-mono text-muted",
566
+ split && "col-span-4",
567
+ )}
568
+ >
569
+ <span
570
+ className="sticky left-0 flex shrink-0 flex-col items-center justify-center self-stretch border-l-[3px] border-transparent bg-hover"
571
+ style={{ width }}
572
+ >
573
+ {expand &&
574
+ (directions.length ? directions : (["all"] as const)).map((direction) => (
575
+ <button
576
+ key={direction}
577
+ type="button"
578
+ disabled={busy}
579
+ aria-label={
580
+ direction === "all"
581
+ ? `Show ${label}`
582
+ : direction === "up"
583
+ ? `Show ${STEP} lines above`
584
+ : `Show ${STEP} lines below`
585
+ }
586
+ className="flex h-4 w-full cursor-pointer items-center justify-center border-0 bg-transparent p-0 text-muted hover:text-foreground disabled:cursor-default"
587
+ onClick={() => expand(direction)}
588
+ >
589
+ <Icon
590
+ name={
591
+ direction === "up"
592
+ ? "arrow-up"
593
+ : direction === "down"
594
+ ? "arrow-down"
595
+ : "chevrons-up-down"
596
+ }
597
+ size={12}
598
+ />
599
+ </button>
600
+ ))}
601
+ </span>
602
+ <span className="min-w-0 flex-1 truncate pl-2 whitespace-pre">{section}</span>
603
+ {expand ? (
604
+ <button
605
+ type="button"
606
+ disabled={busy}
607
+ className="sticky right-0 flex shrink-0 cursor-pointer items-center gap-1 border-0 bg-transparent px-3 font-sans text-xs text-muted hover:text-foreground"
608
+ onClick={() => expand("all")}
609
+ >
610
+ <Icon name="chevrons-up-down" size={12} />
611
+ {label}
612
+ </button>
613
+ ) : (
614
+ <span className="sticky right-0 shrink-0 px-3 font-sans text-xs">{label}</span>
615
+ )}
616
+ </div>
617
+ );
618
+ }
619
+
620
+ const tints = {
621
+ context: { row: "bg-background", bar: "border-transparent", mark: "" },
622
+ added: { row: "bg-success-subtle", bar: "border-success", mark: "bg-success/25" },
623
+ removed: { row: "bg-destructive-subtle", bar: "border-destructive", mark: "bg-destructive/25" },
624
+ } as const;
625
+
626
+ function UnifiedLine({
627
+ line,
628
+ width,
629
+ wrap,
630
+ tokens,
631
+ marks,
632
+ }: {
633
+ line: DiffLine;
634
+ width: string;
635
+ wrap: boolean;
636
+ tokens: readonly CodeToken[] | undefined;
637
+ marks: readonly CharRange[] | undefined;
638
+ }) {
639
+ const tint = tints[line.kind];
640
+ return (
641
+ <div
642
+ data-slot="diff-view-line"
643
+ data-kind={line.kind}
644
+ // Each slotted part names its font: a skin may set one on every `[data-slot]`.
645
+ className={cn("flex font-mono", tint.row)}
646
+ >
647
+ <span
648
+ data-slot="diff-view-number"
649
+ className={cn(
650
+ "sticky left-0 shrink-0 border-l-[3px] pr-2 text-right font-mono tabular-nums select-none",
651
+ tint.row,
652
+ tint.bar,
653
+ line.kind === "context"
654
+ ? "text-muted"
655
+ : line.kind === "added"
656
+ ? "text-success"
657
+ : "text-destructive",
658
+ )}
659
+ style={{ width }}
660
+ >
661
+ {line.kind === "removed" ? "−" : line.new}
662
+ </span>
663
+ <span
664
+ className={cn(
665
+ "pr-4 pl-3",
666
+ wrap ? "min-w-0 flex-1 whitespace-pre-wrap [overflow-wrap:anywhere]" : "whitespace-pre",
667
+ )}
668
+ >
669
+ <Text text={line.text} tokens={tokens} marks={marks} mark={tint.mark} />
670
+ </span>
671
+ </div>
672
+ );
673
+ }
674
+
675
+ function SplitSide({
676
+ line,
677
+ side,
678
+ width,
679
+ tokens,
680
+ marks,
681
+ }: {
682
+ line: DiffLine | undefined;
683
+ side: "old" | "new";
684
+ width: string;
685
+ tokens: ReadonlyMap<string, readonly CodeToken[]>;
686
+ marks: ReadonlyMap<string, CharRange[]>;
687
+ }) {
688
+ if (!line)
689
+ return (
690
+ <>
691
+ <span
692
+ data-slot="diff-view-number"
693
+ className="border-l-[3px] border-transparent bg-hover/60"
694
+ style={{ width }}
695
+ />
696
+ <span className="bg-hover/60" />
697
+ </>
698
+ );
699
+ const number =
700
+ side === "old"
701
+ ? line.kind === "added"
702
+ ? 0
703
+ : line.old
704
+ : line.kind === "removed"
705
+ ? 0
706
+ : line.new;
707
+ const kind = line.kind;
708
+ const tint = tints[kind];
709
+ const key = side === "old" ? `o${number}` : `n${number}`;
710
+ return (
711
+ <>
712
+ <span
713
+ data-slot="diff-view-number"
714
+ data-kind={kind}
715
+ className={cn(
716
+ "border-l-[3px] pr-2 text-right font-mono tabular-nums select-none",
717
+ tint.row,
718
+ tint.bar,
719
+ kind === "context"
720
+ ? "text-muted"
721
+ : kind === "added"
722
+ ? "text-success"
723
+ : "text-destructive",
724
+ )}
725
+ style={{ width }}
726
+ >
727
+ {number}
728
+ </span>
729
+ <span
730
+ data-slot="diff-view-line"
731
+ data-kind={kind}
732
+ className={cn(
733
+ "min-w-0 pr-3 pl-3 font-mono whitespace-pre-wrap [overflow-wrap:anywhere]",
734
+ tint.row,
735
+ )}
736
+ >
737
+ <Text
738
+ text={line.text}
739
+ tokens={tokens.get(kind === "context" ? `n${line.new}` : key)}
740
+ marks={marks.get(keyOf(line))}
741
+ mark={tint.mark}
742
+ />
743
+ </span>
744
+ </>
745
+ );
746
+ }
747
+
748
+ /** A line's text: cut by its tokens' colours and its changed words' marks. */
749
+ function Text({
750
+ text,
751
+ tokens,
752
+ marks,
753
+ mark,
754
+ }: {
755
+ text: string;
756
+ tokens: readonly CodeToken[] | undefined;
757
+ marks: readonly CharRange[] | undefined;
758
+ mark: string;
759
+ }) {
760
+ // Tokens that do not spell the line (a highlighter's surprise) are left out.
761
+ const usable =
762
+ tokens && tokens.map((token) => token.content).join("") === text ? tokens : undefined;
763
+ if (!usable && !marks?.length) return text || " ";
764
+ const spans: { start: number; end: number; color?: string | undefined }[] = [];
765
+ let at = 0;
766
+ for (const token of usable ?? [{ content: text }]) {
767
+ spans.push({
768
+ start: at,
769
+ end: at + token.content.length,
770
+ color: "color" in token ? token.color : undefined,
771
+ });
772
+ at += token.content.length;
773
+ }
774
+ const cuts = new Set([
775
+ 0,
776
+ text.length,
777
+ ...spans.flatMap((span) => [span.start, span.end]),
778
+ ...(marks ?? []).flat(),
779
+ ]);
780
+ const points = [...cuts].filter((cut) => cut >= 0 && cut <= text.length).sort((a, b) => a - b);
781
+ return points.slice(0, -1).map((start, index) => {
782
+ const end = points[index + 1]!;
783
+ const color = spans.find((span) => span.start <= start && start < span.end)?.color;
784
+ const marked = marks?.some(([from, to]) => from <= start && start < to);
785
+ return (
786
+ <span
787
+ key={start}
788
+ data-changed={marked || undefined}
789
+ className={cn(marked && cn("rounded-sm", mark))}
790
+ style={color ? { color } : undefined}
791
+ >
792
+ {text.slice(start, end)}
793
+ </span>
794
+ );
795
+ });
796
+ }
797
+
798
+ export { DiffView };
799
+ export type { DiffViewFile, DiffViewHandle, DiffViewProps };