@bevel-software/platform-core-frontend 0.7.3 → 0.7.5

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.
@@ -1,338 +1,338 @@
1
- import { useMemo } from 'react';
2
- import Markdown from 'react-markdown';
3
- import type { FileDiffPayload } from '@bevel-software/platform-shared';
4
- import { computeDiff, type DiffLine } from '../../workspace/utils/diff';
5
- import { parseFrontmatter, labelFor, type FrontmatterData } from '../../workspace/utils/frontmatter';
6
- import { escapeSpacesInLinkDestinations } from '../../../shared/markdown/Markdown';
7
- import {
8
- KB_REMARK_PLUGINS,
9
- KB_DIFF_REHYPE_PLUGINS,
10
- useKbMarkdownComponents,
11
- } from '../../workspace/components/renderers/kbMarkdownPipeline';
12
-
13
- const MAX_RENDERED_LINES = 5000;
14
-
15
- interface MarkdownDiffViewerProps {
16
- payload: FileDiffPayload;
17
- /**
18
- * Resolver for an internal `.md` link inside the diff. Omitted → such links
19
- * render as inert anchors, which is the right default for a view of a PAST
20
- * state: the file history panel shows a commit, and there is no meaningful
21
- * "current" document for a relative link to resolve against.
22
- *
23
- * A caller that DOES pass one must bind it to the branch the diff is OF —
24
- * the change request's branch, not whatever branch is checked out. The
25
- * navigation hooks in `kb-routes` resolve against `git.status.branch`, so
26
- * handing them through unbound would silently send a reviewer to a different
27
- * branch's copy of the file they just clicked.
28
- */
29
- onOpenFile?: (href: string) => void;
30
- /** Same contract as {@link onOpenFile}, for bare node-id links. */
31
- onOpenNodeId?: (id: string) => void;
32
- /**
33
- * Whether this view owns a scroller and its own padding. `true` (the
34
- * default) keeps the self-contained box the change-request dialog and the
35
- * file-history panel rely on.
36
- *
37
- * Pass `false` when the PARENT is the scroller. The review panel is: a
38
- * centred column whose CHILD scrolls leaves the gutters either side outside
39
- * the scroll hit area, so the wheel does nothing over them. Making the
40
- * panel-width parent scroll and putting the measure on an inner container
41
- * fixes that — but only if this stops owning `overflow-auto`, since two
42
- * nested `h-full overflow-auto` boxes leave the outer one unable to scroll
43
- * and stack both paddings.
44
- *
45
- * Mirrors `KbMarkdownView.scroll`, for the same reason and with the same
46
- * default.
47
- */
48
- scroll?: boolean;
49
- }
50
-
51
- /**
52
- * Frontmatter-aware diff renderer for markdown files. Splits the diff into
53
- * frontmatter and body regions; renders the frontmatter as a structured
54
- * key-by-key red/green panel (rather than raw `key: value` lines), and the
55
- * body as either a markdown-rendered preview with red/green change blocks or
56
- * a git-conflict-marker view for side-by-side text inspection.
57
- *
58
- * The body renders through the shared KB markdown pipeline
59
- * (`kbMarkdownPipeline`), so a diff reads like the document it is a diff of:
60
- * id-links, `<details>` blocks and mermaid diagrams behave as they do in the
61
- * knowledge view rather than as raw text.
62
- *
63
- * Resolvers arrive as PROPS and no hook is called here. That is deliberate:
64
- * this component renders inside the change-request dialog and the file-history
65
- * panel, both of which are mounted in places (and tested in ways) that have no
66
- * Router and no Git/Workspace context — and it is reachable from the embed
67
- * routes, which sit outside those providers entirely. A `useNavigate()` in
68
- * here would be a runtime crash in all three.
69
- */
70
- export function MarkdownDiffViewer({ payload, onOpenFile, onOpenNodeId, scroll = true }: MarkdownDiffViewerProps) {
71
- const data = useMemo(() => {
72
- const baseline = payload.baseline ?? '';
73
- const current = payload.current ?? '';
74
- // Cheap pre-check: count newlines before doing the LCS + frontmatter +
75
- // markdown-rendering work. The diff line count can't exceed baselineLines +
76
- // currentLines, so if their sum already exceeds the render cap we know the
77
- // result is "too large" and can skip the heavy computation entirely.
78
- const rawLineCount = countNewlines(baseline) + countNewlines(current) + 2;
79
- if (rawLineCount > MAX_RENDERED_LINES) {
80
- return {
81
- tooLarge: true as const,
82
- rawLineCount,
83
- lines: [] as DiffLine[],
84
- bodyBlocks: [] as DisplayBlock[],
85
- frontmatterChanged: false,
86
- oldFrontmatter: {} as FrontmatterData,
87
- newFrontmatter: {} as FrontmatterData,
88
- };
89
- }
90
- const lines = computeDiff(baseline, current);
91
- const oldFmEnd = frontmatterLineCount(baseline);
92
- const newFmEnd = frontmatterLineCount(current);
93
- const split = splitDiffByFrontmatter(lines, oldFmEnd, newFmEnd);
94
- return {
95
- tooLarge: false as const,
96
- rawLineCount,
97
- lines,
98
- bodyBlocks: groupDiffBlocks(split.body),
99
- frontmatterChanged: split.frontmatter.some((l) => l.type !== 'same'),
100
- oldFrontmatter: parseFrontmatter(baseline).data,
101
- newFrontmatter: parseFrontmatter(current).data,
102
- };
103
- }, [payload]);
104
-
105
- if (data.tooLarge || data.lines.length > MAX_RENDERED_LINES) {
106
- const shown = data.tooLarge ? data.rawLineCount : data.lines.length;
107
- return (
108
- <div className="h-full flex items-center justify-center text-xs text-ink-muted px-6 text-center">
109
- Diff is too large to render ({shown.toLocaleString()} lines).
110
- Accept or reject from the file list.
111
- </div>
112
- );
113
- }
114
-
115
- return (
116
- <div className={scroll ? 'h-full overflow-auto bg-white px-4 py-3' : 'min-w-0'}>
117
- {data.frontmatterChanged && (
118
- <FrontmatterDiffPanel
119
- oldData={data.oldFrontmatter}
120
- newData={data.newFrontmatter}
121
- />
122
- )}
123
- <DiffPreview
124
- blocks={data.bodyBlocks}
125
- onOpenFile={onOpenFile}
126
- onOpenNodeId={onOpenNodeId}
127
- />
128
- </div>
129
- );
130
- }
131
-
132
- function countNewlines(s: string): number {
133
- let count = 0;
134
- for (let i = 0; i < s.length; i++) {
135
- if (s.charCodeAt(i) === 10) count++;
136
- }
137
- return count;
138
- }
139
-
140
- // ── frontmatter helpers ─────────────────────────────────────────────────
141
-
142
- /**
143
- * Count how many lines the frontmatter block occupies (including both `---`
144
- * delimiters) when `content` is split on '\n'. Returns 0 when there is no
145
- * frontmatter so callers can skip the frontmatter-split logic.
146
- */
147
- function frontmatterLineCount(content: string): number {
148
- const lines = content.split('\n').map((l) => (l.endsWith('\r') ? l.slice(0, -1) : l));
149
- if (lines[0] !== '---') return 0;
150
- for (let i = 1; i < lines.length; i++) {
151
- if (lines[i] === '---') return i + 1;
152
- }
153
- return 0;
154
- }
155
-
156
- /**
157
- * Walk the diff lines, tracking old- and new-line cursors, and split them
158
- * into the lines that fall inside the frontmatter region and the lines
159
- * that fall inside the body. `oldFmEnd` / `newFmEnd` are exclusive upper
160
- * bounds (i.e. the number of frontmatter lines on each side).
161
- */
162
- function splitDiffByFrontmatter(
163
- lines: DiffLine[],
164
- oldFmEnd: number,
165
- newFmEnd: number,
166
- ): { frontmatter: DiffLine[]; body: DiffLine[] } {
167
- const frontmatter: DiffLine[] = [];
168
- const body: DiffLine[] = [];
169
- let oldIdx = 0;
170
- let newIdx = 0;
171
- for (const line of lines) {
172
- const inOldFm = oldIdx < oldFmEnd;
173
- const inNewFm = newIdx < newFmEnd;
174
- if (line.type === 'same') {
175
- if (inOldFm && inNewFm) frontmatter.push(line);
176
- else body.push(line);
177
- oldIdx++;
178
- newIdx++;
179
- } else if (line.type === 'removed') {
180
- if (inOldFm) frontmatter.push(line);
181
- else body.push(line);
182
- oldIdx++;
183
- } else {
184
- if (inNewFm) frontmatter.push(line);
185
- else body.push(line);
186
- newIdx++;
187
- }
188
- }
189
- return { frontmatter, body };
190
- }
191
-
192
- function FrontmatterDiffPanel({
193
- oldData,
194
- newData,
195
- }: {
196
- oldData: FrontmatterData;
197
- newData: FrontmatterData;
198
- }) {
199
- const keys = Array.from(new Set([...Object.keys(oldData), ...Object.keys(newData)]));
200
- const visible = keys.filter((k) => {
201
- const o = oldData[k];
202
- const n = newData[k];
203
- const oEmpty = o === undefined || (Array.isArray(o) ? o.length === 0 : o === '');
204
- const nEmpty = n === undefined || (Array.isArray(n) ? n.length === 0 : n === '');
205
- return !(oEmpty && nEmpty);
206
- });
207
- if (visible.length === 0) return null;
208
-
209
- const formatValue = (v: string | string[] | undefined): string => {
210
- if (v === undefined) return '';
211
- return Array.isArray(v) ? v.join(', ') : v;
212
- };
213
-
214
- return (
215
- <div className="mb-4 rounded-lg border border-line-strong bg-sunken divide-y divide-line">
216
- {visible.map((key) => {
217
- const oldVal = formatValue(oldData[key]);
218
- const newVal = formatValue(newData[key]);
219
- const changed = oldVal !== newVal;
220
- return (
221
- <div key={key} className="flex items-start gap-3 px-3 py-2 text-xs">
222
- <span className="shrink-0 text-ink-muted w-28">{labelFor(key)}</span>
223
- {changed ? (
224
- <div className="flex-1 space-y-1 break-words">
225
- {oldVal && (
226
- <div className="bg-red-100 text-red-700 px-2 py-0.5 rounded-sm">{oldVal}</div>
227
- )}
228
- {newVal && (
229
- <div className="bg-emerald-100 text-emerald-700 px-2 py-0.5 rounded-sm">{newVal}</div>
230
- )}
231
- </div>
232
- ) : (
233
- <span className="text-ink break-words">{oldVal}</span>
234
- )}
235
- </div>
236
- );
237
- })}
238
- </div>
239
- );
240
- }
241
-
242
- // ── body diff helpers ───────────────────────────────────────────────────
243
-
244
- /**
245
- * Group consecutive same/changed runs into display blocks: runs of "same"
246
- * lines, and "conflict" blocks bundling consecutive removed+added runs
247
- * together — the same shape git uses for merge conflicts.
248
- */
249
- type DisplayBlock =
250
- | { type: 'same'; lines: string[] }
251
- | { type: 'conflict'; removed: string[]; added: string[] };
252
-
253
- function groupDiffBlocks(lines: DiffLine[]): DisplayBlock[] {
254
- const result: DisplayBlock[] = [];
255
- let i = 0;
256
- while (i < lines.length) {
257
- if (lines[i].type === 'same') {
258
- const block: DisplayBlock = { type: 'same', lines: [] };
259
- while (i < lines.length && lines[i].type === 'same') {
260
- block.lines.push(lines[i].text);
261
- i++;
262
- }
263
- result.push(block);
264
- } else {
265
- const block: DisplayBlock = { type: 'conflict', removed: [], added: [] };
266
- while (i < lines.length && lines[i].type === 'removed') {
267
- block.removed.push(lines[i].text);
268
- i++;
269
- }
270
- while (i < lines.length && lines[i].type === 'added') {
271
- block.added.push(lines[i].text);
272
- i++;
273
- }
274
- result.push(block);
275
- }
276
- }
277
- return result;
278
- }
279
-
280
- function DiffPreview({
281
- blocks,
282
- onOpenFile,
283
- onOpenNodeId,
284
- }: {
285
- blocks: DisplayBlock[];
286
- onOpenFile?: (href: string) => void;
287
- onOpenNodeId?: (id: string) => void;
288
- }) {
289
- // `'source'`: a diagram whose ```mermaid fence straddles a change boundary
290
- // reaches the renderer truncated and cannot parse, so the error box would
291
- // replace the red/green source — the only useful content in that block — on
292
- // every EDITED diagram. Untouched ones sit whole inside a single unchanged
293
- // fragment and still render as diagrams.
294
- //
295
- // No `headingLink`: a diff shows no copy-anchor buttons, and the slug ids
296
- // they depend on are deliberately absent (see KB_DIFF_REHYPE_PLUGINS).
297
- const components = useKbMarkdownComponents({
298
- onOpenFile,
299
- onOpenNodeId,
300
- onMermaidError: 'source',
301
- });
302
-
303
- // Each block is parsed as a standalone document, so the space-escaping that
304
- // makes `[Foo](Some File.md)` resolve has to be applied per fragment.
305
- const fragment = (text: string) => (
306
- <Markdown
307
- remarkPlugins={KB_REMARK_PLUGINS}
308
- rehypePlugins={KB_DIFF_REHYPE_PLUGINS}
309
- components={components}
310
- >
311
- {escapeSpacesInLinkDestinations(text)}
312
- </Markdown>
313
- );
314
-
315
- return (
316
- <div className="prose prose-sm max-w-none">
317
- {blocks.map((block, i) => {
318
- if (block.type === 'same') {
319
- return <div key={i}>{fragment(block.lines.join('\n'))}</div>;
320
- }
321
- return (
322
- <div key={i} className="my-2">
323
- {block.removed.length > 0 && (
324
- <div className="bg-red-50 border-l-2 border-red-700 px-3 py-1 rounded-sm">
325
- {fragment(block.removed.join('\n'))}
326
- </div>
327
- )}
328
- {block.added.length > 0 && (
329
- <div className="bg-emerald-50 border-l-2 border-emerald-700 px-3 py-1 rounded-sm mt-1">
330
- {fragment(block.added.join('\n'))}
331
- </div>
332
- )}
333
- </div>
334
- );
335
- })}
336
- </div>
337
- );
338
- }
1
+ import { useMemo } from 'react';
2
+ import Markdown from 'react-markdown';
3
+ import type { FileDiffPayload } from '@bevel-software/platform-shared';
4
+ import { computeDiff, type DiffLine } from '../../workspace/utils/diff';
5
+ import { parseFrontmatter, labelFor, type FrontmatterData } from '../../workspace/utils/frontmatter';
6
+ import { escapeSpacesInLinkDestinations } from '../../../shared/markdown/Markdown';
7
+ import {
8
+ KB_REMARK_PLUGINS,
9
+ KB_DIFF_REHYPE_PLUGINS,
10
+ useKbMarkdownComponents,
11
+ } from '../../workspace/components/renderers/kbMarkdownPipeline';
12
+
13
+ const MAX_RENDERED_LINES = 5000;
14
+
15
+ interface MarkdownDiffViewerProps {
16
+ payload: FileDiffPayload;
17
+ /**
18
+ * Resolver for an internal `.md` link inside the diff. Omitted → such links
19
+ * render as inert anchors, which is the right default for a view of a PAST
20
+ * state: the file history panel shows a commit, and there is no meaningful
21
+ * "current" document for a relative link to resolve against.
22
+ *
23
+ * A caller that DOES pass one must bind it to the branch the diff is OF —
24
+ * the change request's branch, not whatever branch is checked out. The
25
+ * navigation hooks in `kb-routes` resolve against `git.status.branch`, so
26
+ * handing them through unbound would silently send a reviewer to a different
27
+ * branch's copy of the file they just clicked.
28
+ */
29
+ onOpenFile?: (href: string) => void;
30
+ /** Same contract as {@link onOpenFile}, for bare node-id links. */
31
+ onOpenNodeId?: (id: string) => void;
32
+ /**
33
+ * Whether this view owns a scroller and its own padding. `true` (the
34
+ * default) keeps the self-contained box the change-request dialog and the
35
+ * file-history panel rely on.
36
+ *
37
+ * Pass `false` when the PARENT is the scroller. The review panel is: a
38
+ * centred column whose CHILD scrolls leaves the gutters either side outside
39
+ * the scroll hit area, so the wheel does nothing over them. Making the
40
+ * panel-width parent scroll and putting the measure on an inner container
41
+ * fixes that — but only if this stops owning `overflow-auto`, since two
42
+ * nested `h-full overflow-auto` boxes leave the outer one unable to scroll
43
+ * and stack both paddings.
44
+ *
45
+ * Mirrors `KbMarkdownView.scroll`, for the same reason and with the same
46
+ * default.
47
+ */
48
+ scroll?: boolean;
49
+ }
50
+
51
+ /**
52
+ * Frontmatter-aware diff renderer for markdown files. Splits the diff into
53
+ * frontmatter and body regions; renders the frontmatter as a structured
54
+ * key-by-key red/green panel (rather than raw `key: value` lines), and the
55
+ * body as either a markdown-rendered preview with red/green change blocks or
56
+ * a git-conflict-marker view for side-by-side text inspection.
57
+ *
58
+ * The body renders through the shared KB markdown pipeline
59
+ * (`kbMarkdownPipeline`), so a diff reads like the document it is a diff of:
60
+ * id-links, `<details>` blocks and mermaid diagrams behave as they do in the
61
+ * knowledge view rather than as raw text.
62
+ *
63
+ * Resolvers arrive as PROPS and no hook is called here. That is deliberate:
64
+ * this component renders inside the change-request dialog and the file-history
65
+ * panel, both of which are mounted in places (and tested in ways) that have no
66
+ * Router and no Git/Workspace context — and it is reachable from the embed
67
+ * routes, which sit outside those providers entirely. A `useNavigate()` in
68
+ * here would be a runtime crash in all three.
69
+ */
70
+ export function MarkdownDiffViewer({ payload, onOpenFile, onOpenNodeId, scroll = true }: MarkdownDiffViewerProps) {
71
+ const data = useMemo(() => {
72
+ const baseline = payload.baseline ?? '';
73
+ const current = payload.current ?? '';
74
+ // Cheap pre-check: count newlines before doing the LCS + frontmatter +
75
+ // markdown-rendering work. The diff line count can't exceed baselineLines +
76
+ // currentLines, so if their sum already exceeds the render cap we know the
77
+ // result is "too large" and can skip the heavy computation entirely.
78
+ const rawLineCount = countNewlines(baseline) + countNewlines(current) + 2;
79
+ if (rawLineCount > MAX_RENDERED_LINES) {
80
+ return {
81
+ tooLarge: true as const,
82
+ rawLineCount,
83
+ lines: [] as DiffLine[],
84
+ bodyBlocks: [] as DisplayBlock[],
85
+ frontmatterChanged: false,
86
+ oldFrontmatter: {} as FrontmatterData,
87
+ newFrontmatter: {} as FrontmatterData,
88
+ };
89
+ }
90
+ const lines = computeDiff(baseline, current);
91
+ const oldFmEnd = frontmatterLineCount(baseline);
92
+ const newFmEnd = frontmatterLineCount(current);
93
+ const split = splitDiffByFrontmatter(lines, oldFmEnd, newFmEnd);
94
+ return {
95
+ tooLarge: false as const,
96
+ rawLineCount,
97
+ lines,
98
+ bodyBlocks: groupDiffBlocks(split.body),
99
+ frontmatterChanged: split.frontmatter.some((l) => l.type !== 'same'),
100
+ oldFrontmatter: parseFrontmatter(baseline).data,
101
+ newFrontmatter: parseFrontmatter(current).data,
102
+ };
103
+ }, [payload]);
104
+
105
+ if (data.tooLarge || data.lines.length > MAX_RENDERED_LINES) {
106
+ const shown = data.tooLarge ? data.rawLineCount : data.lines.length;
107
+ return (
108
+ <div className="h-full flex items-center justify-center text-xs text-ink-muted px-6 text-center">
109
+ Diff is too large to render ({shown.toLocaleString()} lines).
110
+ Accept or reject from the file list.
111
+ </div>
112
+ );
113
+ }
114
+
115
+ return (
116
+ <div className={scroll ? 'h-full overflow-auto bg-white px-4 py-3' : 'min-w-0'}>
117
+ {data.frontmatterChanged && (
118
+ <FrontmatterDiffPanel
119
+ oldData={data.oldFrontmatter}
120
+ newData={data.newFrontmatter}
121
+ />
122
+ )}
123
+ <DiffPreview
124
+ blocks={data.bodyBlocks}
125
+ onOpenFile={onOpenFile}
126
+ onOpenNodeId={onOpenNodeId}
127
+ />
128
+ </div>
129
+ );
130
+ }
131
+
132
+ function countNewlines(s: string): number {
133
+ let count = 0;
134
+ for (let i = 0; i < s.length; i++) {
135
+ if (s.charCodeAt(i) === 10) count++;
136
+ }
137
+ return count;
138
+ }
139
+
140
+ // ── frontmatter helpers ─────────────────────────────────────────────────
141
+
142
+ /**
143
+ * Count how many lines the frontmatter block occupies (including both `---`
144
+ * delimiters) when `content` is split on '\n'. Returns 0 when there is no
145
+ * frontmatter so callers can skip the frontmatter-split logic.
146
+ */
147
+ function frontmatterLineCount(content: string): number {
148
+ const lines = content.split('\n').map((l) => (l.endsWith('\r') ? l.slice(0, -1) : l));
149
+ if (lines[0] !== '---') return 0;
150
+ for (let i = 1; i < lines.length; i++) {
151
+ if (lines[i] === '---') return i + 1;
152
+ }
153
+ return 0;
154
+ }
155
+
156
+ /**
157
+ * Walk the diff lines, tracking old- and new-line cursors, and split them
158
+ * into the lines that fall inside the frontmatter region and the lines
159
+ * that fall inside the body. `oldFmEnd` / `newFmEnd` are exclusive upper
160
+ * bounds (i.e. the number of frontmatter lines on each side).
161
+ */
162
+ function splitDiffByFrontmatter(
163
+ lines: DiffLine[],
164
+ oldFmEnd: number,
165
+ newFmEnd: number,
166
+ ): { frontmatter: DiffLine[]; body: DiffLine[] } {
167
+ const frontmatter: DiffLine[] = [];
168
+ const body: DiffLine[] = [];
169
+ let oldIdx = 0;
170
+ let newIdx = 0;
171
+ for (const line of lines) {
172
+ const inOldFm = oldIdx < oldFmEnd;
173
+ const inNewFm = newIdx < newFmEnd;
174
+ if (line.type === 'same') {
175
+ if (inOldFm && inNewFm) frontmatter.push(line);
176
+ else body.push(line);
177
+ oldIdx++;
178
+ newIdx++;
179
+ } else if (line.type === 'removed') {
180
+ if (inOldFm) frontmatter.push(line);
181
+ else body.push(line);
182
+ oldIdx++;
183
+ } else {
184
+ if (inNewFm) frontmatter.push(line);
185
+ else body.push(line);
186
+ newIdx++;
187
+ }
188
+ }
189
+ return { frontmatter, body };
190
+ }
191
+
192
+ function FrontmatterDiffPanel({
193
+ oldData,
194
+ newData,
195
+ }: {
196
+ oldData: FrontmatterData;
197
+ newData: FrontmatterData;
198
+ }) {
199
+ const keys = Array.from(new Set([...Object.keys(oldData), ...Object.keys(newData)]));
200
+ const visible = keys.filter((k) => {
201
+ const o = oldData[k];
202
+ const n = newData[k];
203
+ const oEmpty = o === undefined || (Array.isArray(o) ? o.length === 0 : o === '');
204
+ const nEmpty = n === undefined || (Array.isArray(n) ? n.length === 0 : n === '');
205
+ return !(oEmpty && nEmpty);
206
+ });
207
+ if (visible.length === 0) return null;
208
+
209
+ const formatValue = (v: string | string[] | undefined): string => {
210
+ if (v === undefined) return '';
211
+ return Array.isArray(v) ? v.join(', ') : v;
212
+ };
213
+
214
+ return (
215
+ <div className="mb-4 rounded-lg border border-line-strong bg-sunken divide-y divide-line">
216
+ {visible.map((key) => {
217
+ const oldVal = formatValue(oldData[key]);
218
+ const newVal = formatValue(newData[key]);
219
+ const changed = oldVal !== newVal;
220
+ return (
221
+ <div key={key} className="flex items-start gap-3 px-3 py-2 text-xs">
222
+ <span className="shrink-0 text-ink-muted w-28">{labelFor(key)}</span>
223
+ {changed ? (
224
+ <div className="flex-1 space-y-1 break-words">
225
+ {oldVal && (
226
+ <div className="bg-red-100 text-red-700 px-2 py-0.5 rounded-sm">{oldVal}</div>
227
+ )}
228
+ {newVal && (
229
+ <div className="bg-emerald-100 text-emerald-700 px-2 py-0.5 rounded-sm">{newVal}</div>
230
+ )}
231
+ </div>
232
+ ) : (
233
+ <span className="text-ink break-words">{oldVal}</span>
234
+ )}
235
+ </div>
236
+ );
237
+ })}
238
+ </div>
239
+ );
240
+ }
241
+
242
+ // ── body diff helpers ───────────────────────────────────────────────────
243
+
244
+ /**
245
+ * Group consecutive same/changed runs into display blocks: runs of "same"
246
+ * lines, and "conflict" blocks bundling consecutive removed+added runs
247
+ * together — the same shape git uses for merge conflicts.
248
+ */
249
+ type DisplayBlock =
250
+ | { type: 'same'; lines: string[] }
251
+ | { type: 'conflict'; removed: string[]; added: string[] };
252
+
253
+ function groupDiffBlocks(lines: DiffLine[]): DisplayBlock[] {
254
+ const result: DisplayBlock[] = [];
255
+ let i = 0;
256
+ while (i < lines.length) {
257
+ if (lines[i].type === 'same') {
258
+ const block: DisplayBlock = { type: 'same', lines: [] };
259
+ while (i < lines.length && lines[i].type === 'same') {
260
+ block.lines.push(lines[i].text);
261
+ i++;
262
+ }
263
+ result.push(block);
264
+ } else {
265
+ const block: DisplayBlock = { type: 'conflict', removed: [], added: [] };
266
+ while (i < lines.length && lines[i].type === 'removed') {
267
+ block.removed.push(lines[i].text);
268
+ i++;
269
+ }
270
+ while (i < lines.length && lines[i].type === 'added') {
271
+ block.added.push(lines[i].text);
272
+ i++;
273
+ }
274
+ result.push(block);
275
+ }
276
+ }
277
+ return result;
278
+ }
279
+
280
+ function DiffPreview({
281
+ blocks,
282
+ onOpenFile,
283
+ onOpenNodeId,
284
+ }: {
285
+ blocks: DisplayBlock[];
286
+ onOpenFile?: (href: string) => void;
287
+ onOpenNodeId?: (id: string) => void;
288
+ }) {
289
+ // `'source'`: a diagram whose ```mermaid fence straddles a change boundary
290
+ // reaches the renderer truncated and cannot parse, so the error box would
291
+ // replace the red/green source — the only useful content in that block — on
292
+ // every EDITED diagram. Untouched ones sit whole inside a single unchanged
293
+ // fragment and still render as diagrams.
294
+ //
295
+ // No `headingLink`: a diff shows no copy-anchor buttons, and the slug ids
296
+ // they depend on are deliberately absent (see KB_DIFF_REHYPE_PLUGINS).
297
+ const components = useKbMarkdownComponents({
298
+ onOpenFile,
299
+ onOpenNodeId,
300
+ onMermaidError: 'source',
301
+ });
302
+
303
+ // Each block is parsed as a standalone document, so the space-escaping that
304
+ // makes `[Foo](Some File.md)` resolve has to be applied per fragment.
305
+ const fragment = (text: string) => (
306
+ <Markdown
307
+ remarkPlugins={KB_REMARK_PLUGINS}
308
+ rehypePlugins={KB_DIFF_REHYPE_PLUGINS}
309
+ components={components}
310
+ >
311
+ {escapeSpacesInLinkDestinations(text)}
312
+ </Markdown>
313
+ );
314
+
315
+ return (
316
+ <div className="prose prose-sm max-w-none">
317
+ {blocks.map((block, i) => {
318
+ if (block.type === 'same') {
319
+ return <div key={i}>{fragment(block.lines.join('\n'))}</div>;
320
+ }
321
+ return (
322
+ <div key={i} className="my-2">
323
+ {block.removed.length > 0 && (
324
+ <div className="bg-red-50 border-l-2 border-red-700 px-3 py-1 rounded-sm">
325
+ {fragment(block.removed.join('\n'))}
326
+ </div>
327
+ )}
328
+ {block.added.length > 0 && (
329
+ <div className="bg-emerald-50 border-l-2 border-emerald-700 px-3 py-1 rounded-sm mt-1">
330
+ {fragment(block.added.join('\n'))}
331
+ </div>
332
+ )}
333
+ </div>
334
+ );
335
+ })}
336
+ </div>
337
+ );
338
+ }