An open source design system that's fully customizable and agent ready
TypeScript
fix(DiffViewer): a change too large to compare line by line is labeled and folded, not shown as a silent replace (#9462)
Cindy Zhang437f54847cb5
diff --git a/.changeset/diff-viewer-large-change-keys.md b/.changeset/diff-viewer-large-change-keys.mdnew file mode 100644index 0000000000..7d70269468--- /dev/null+++ b/.changeset/diff-viewer-large-change-keys.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[feat] Adds three `@astryx.diffViewer.*` keys to the `en` catalog for the lab `DiffViewer`'s large-change fold: its "Large change: N lines" label and its Show full diff / Hide full diff button. No existing string changes; locales without a translation fall back to English.++@cixzhangdiff --git a/apps/storybook/stories/DiffViewer.stories.tsx b/apps/storybook/stories/DiffViewer.stories.tsxindex 692217c341..1fd3dfe24d 100644--- a/apps/storybook/stories/DiffViewer.stories.tsx+++ b/apps/storybook/stories/DiffViewer.stories.tsx@@ -253,6 +253,34 @@ export const FromTwoTexts: Story = {},};+/**+ * A rewrite too large to compare line by line: the changed lines fold behind a+ * labeled control until the reader shows them.+ */+export const LargeChange: Story = {+ args: {+ file: createDiffFile({+ path: 'src/generated/schema.ts',+ oldValue: [+ '// Generated file. Do not edit.',+ ...Array.from(+ {length: 6000},+ (_, i) => `export const field${i} = 'v1-${i}';`,+ ),+ 'export default {};',+ ].join('\n'),+ newValue: [+ '// Generated file. Do not edit.',+ ...Array.from(+ {length: 6000},+ (_, i) => `export const field${i} = 'v2-${i}';`,+ ),+ 'export default {};',+ ].join('\n'),+ }),+ },+};+/** File header actions: a "Viewed" checkbox that also folds the file away. */export const ViewedToggle: Story = {render: args => {diff --git a/packages/core/locales/en.json b/packages/core/locales/en.jsonindex a7b79c6e7c..5f8b41ca8c 100644--- a/packages/core/locales/en.json+++ b/packages/core/locales/en.json@@ -607,6 +607,18 @@"defaultMessage": "No content changes","description": "Message in a lab DiffViewer when a file changed only its path or mode, so there are no line changes to show."},+ "@astryx.diffViewer.largeChange": {+ "defaultMessage": "Large change: {count, plural, one {# line} other {# lines}}",+ "description": "Label of a folded block in a lab DiffViewer. The change was too large to compare line by line, so the block shows its old lines as removed and its new lines as added, folded until the reader opens it. `{count}` is the number of removed plus added lines in the block; some can be the same on both sides, because the block was not compared. Keep it short: it shares one row with the Show full diff button."+ },+ "@astryx.diffViewer.showFullDiff": {+ "defaultMessage": "Show full diff",+ "description": "Button beside `@astryx.diffViewer.largeChange` in a lab DiffViewer that shows the folded lines of a large change. Pairs with `@astryx.diffViewer.hideFullDiff`."+ },+ "@astryx.diffViewer.hideFullDiff": {+ "defaultMessage": "Hide full diff",+ "description": "Button beside `@astryx.diffViewer.largeChange` in a lab DiffViewer that folds the lines of a large change again after `@astryx.diffViewer.showFullDiff` showed them."+ },"@astryx.markdownHeadingLinks.copied": {"defaultMessage": "Link copied","description": "Accessible name on the Markdown heading copy button and text announced to a polite live region for ~1.5s after a successful copy. Sentence meaning \"Link copied\"; pairs with `markdownHeadingLinks.copy`."diff --git a/packages/lab/src/DiffViewer/DiffViewer.doc.mjs b/packages/lab/src/DiffViewer/DiffViewer.doc.mjsindex ba9a7b0045..9165a5af5b 100644--- a/packages/lab/src/DiffViewer/DiffViewer.doc.mjs+++ b/packages/lab/src/DiffViewer/DiffViewer.doc.mjs@@ -30,7 +30,7 @@ export const docs = {usage: {description:- 'Read-only, syntax-highlighted diff of one file for code review surfaces. Renders a file header (path, Added/Deleted/Renamed token, +/− line counts, a headerEnd slot, and an optional disclosure) over the file\'s hunks in unified or split (side-by-side) view. Rows use the same syntax-theme diff slots as CodeBlock with isDiff, so one syntax theme styles both. renderLineAnnotation adds a full-width row under any line (for review comments) and onLineNumberClick turns line numbers into buttons. Build the file model with parseUnifiedDiff(patch), which returns one file per file in a git or diff -u patch, or with createDiffFile({oldValue, newValue}) when you hold two versions of a text. Display options cover how a change is marked (classic +/− glyphs, bars, or none), whether changed rows are tinted, and word- or character-level highlighting of what changed inside each removed/added line pair. Each changed line carries a visually hidden "Added"/"Removed" label, so the change reads without colour in every mode. Unwrapped, line numbers and change indicators stay pinned while the code scrolls; in split view each side is its own scroller, so the split stays fixed at half and half, the sides scroll sideways in lockstep, and a row is as tall as its taller side. While code overflows sideways, sideways overscroll is off, so trackpads neither bounce past a line nor swipe the browser back. In right-to-left pages the hunk area stays left-to-right, like a code editor: annotation content reads in the page direction, and annotation rows scroll with the code. Rows are plain DOM with no virtualization: collapse or window very large files.',+ 'Read-only, syntax-highlighted diff of one file for code review surfaces. Renders a file header (path, Added/Deleted/Renamed token, +/− line counts, a headerEnd slot, and an optional disclosure) over the file\'s hunks in unified or split (side-by-side) view. Rows use the same syntax-theme diff slots as CodeBlock with isDiff, so one syntax theme styles both. renderLineAnnotation adds a full-width row under any line (for review comments) and onLineNumberClick turns line numbers into buttons. Build the file model with parseUnifiedDiff(patch), which returns one file per file in a git or diff -u patch, or with createDiffFile({oldValue, newValue}) when you hold two versions of a text. Display options cover how a change is marked (classic +/− glyphs, bars, or none), whether changed rows are tinted, and word- or character-level highlighting of what changed inside each removed/added line pair. Each changed line carries a visually hidden "Added"/"Removed" label, so the change reads without colour in every mode. Unwrapped, line numbers and change indicators stay pinned while the code scrolls; in split view each side is its own scroller, so the split stays fixed at half and half, the sides scroll sideways in lockstep, and a row is as tall as its taller side. While code overflows sideways, sideways overscroll is off, so trackpads neither bounce past a line nor swipe the browser back. In right-to-left pages the hunk area stays left-to-right, like a code editor: annotation content reads in the page direction, and annotation rows scroll with the code. When a change is too large to compare line by line, createDiffFile marks its hunk with isReplacedBlock: it lists every old line as removed and every new line as added. DiffViewer folds those lines behind a "Large change: N lines" row, where N counts the block\'s removed plus added lines, with a Show full diff button. A block opens by itself when one of its lines has an annotation, so no review comment is hidden. Rows are plain DOM with no virtualization: collapse or window very large files.',bestPractices: [{guidance: true,diff --git a/packages/lab/src/DiffViewer/DiffViewer.test.tsx b/packages/lab/src/DiffViewer/DiffViewer.test.tsxindex 908a76aba0..daecf4afc0 100644--- a/packages/lab/src/DiffViewer/DiffViewer.test.tsx+++ b/packages/lab/src/DiffViewer/DiffViewer.test.tsx@@ -6,7 +6,7 @@ import userEvent from '@testing-library/user-event';import {createRef} from 'react';import {DiffViewer} from './DiffViewer';import {parseUnifiedDiff} from './parseUnifiedDiff';-import type {DiffViewerLineRef} from './diffTypes';+import type {DiffViewerFile, DiffViewerLineRef} from './diffTypes';import {createDiffFile} from './createDiffFile';import {dockerfile} from '@astryxdesign/core/CodeBlock/languages/dockerfile';import {graphql} from '@astryxdesign/core/CodeBlock/languages/graphql';@@ -602,6 +602,167 @@ describe('DiffViewer', () => {expect(screen.getByText('No content changes')).toBeInTheDocument();});+ describe('replaced blocks', () => {+ // The shape createDiffFile gives a change too large to compare line by+ // line: shared context, every old line removed, every new line added.+ const LINE_COUNT = 3;+ const numbers = Array.from({length: LINE_COUNT}, (_, i) => i);+ const REPLACED: DiffViewerFile = {+ oldPath: 'big.txt',+ newPath: 'big.txt',+ status: 'modified',+ isBinary: false,+ hunks: [+ {+ header: `@@ -1,${LINE_COUNT + 2} +1,${LINE_COUNT + 2} @@`,+ oldStart: 1,+ oldLines: LINE_COUNT + 2,+ newStart: 1,+ newLines: LINE_COUNT + 2,+ isReplacedBlock: true,+ lines: [+ {+ kind: 'context',+ content: 'head',+ oldLineNumber: 1,+ newLineNumber: 1,+ },+ ...numbers.map(i => ({+ kind: 'removed' as const,+ content: `old ${i}`,+ oldLineNumber: i + 2,+ newLineNumber: null,+ })),+ ...numbers.map(i => ({+ kind: 'added' as const,+ content: `new ${i}`,+ oldLineNumber: null,+ newLineNumber: i + 2,+ })),+ {+ kind: 'context',+ content: 'tail',+ oldLineNumber: LINE_COUNT + 2,+ newLineNumber: LINE_COUNT + 2,+ },+ ],+ },+ ],+ };++ it('folds the changed lines behind a labeled control', () => {+ const {container} = render(<DiffViewer file={REPLACED} />);+ expect(screen.getByText('Large change: 6 lines')).toBeTruthy();+ const button = screen.getByRole('button', {name: 'Show full diff'});+ expect(button.getAttribute('aria-expanded')).toBe('false');+ // The hunk header, the leading context, the fold, the trailing context.+ expect(codeRows(container)).toHaveLength(4);+ expect(container.querySelector('[data-diff="removed"]')).toBeNull();+ expect(screen.getByText('head')).toBeTruthy();+ expect(screen.getByText('tail')).toBeTruthy();+ // The header still counts the whole change.+ expect(screen.getByText('3 lines added, 3 lines removed')).toBeTruthy();+ });++ it('shows and hides the full diff from the keyboard', async () => {+ const user = userEvent.setup();+ const {container} = render(<DiffViewer file={REPLACED} />);+ const button = screen.getByRole('button', {name: 'Show full diff'});+ button.focus();+ await user.keyboard('{Enter}');+ const hide = screen.getByRole('button', {name: 'Hide full diff'});+ expect(hide.getAttribute('aria-expanded')).toBe('true');+ expect(hide).toBe(document.activeElement);+ expect(container.querySelectorAll('[data-diff="removed"]')).toHaveLength(+ LINE_COUNT,+ );+ expect(container.querySelectorAll('[data-diff="added"]')).toHaveLength(+ LINE_COUNT,+ );+ await user.keyboard(' ');+ expect(+ screen+ .getByRole('button', {name: 'Show full diff'})+ .getAttribute('aria-expanded'),+ ).toBe('false');+ expect(container.querySelector('[data-diff="added"]')).toBeNull();+ });++ it('gives the expanded block no inline highlight', async () => {+ const user = userEvent.setup();+ const {container} = render(<DiffViewer file={REPLACED} />);+ await user.click(screen.getByRole('button', {name: 'Show full diff'}));+ expect(changedText(container, 'removed')).toEqual([]);+ expect(changedText(container, 'added')).toEqual([]);+ });++ it('puts one control in split view and labels the fold on both sides', async () => {+ const user = userEvent.setup();+ const {container} = render(+ <DiffViewer file={REPLACED} viewMode="split" />,+ );+ expect(+ screen.getAllByRole('button', {name: 'Show full diff'}),+ ).toHaveLength(1);+ for (const side of ['old', 'new'] as const) {+ const rows = paneRows(container, side);+ // The hunk header, the leading context, the fold, the trailing context.+ expect(rows).toHaveLength(4);+ expect(rows[2].textContent).toContain('Large change: 6 lines');+ }+ await user.click(screen.getByRole('button', {name: 'Show full diff'}));+ expect(paneRows(container, 'old')).toHaveLength(4 + LINE_COUNT);+ expect(paneRows(container, 'new')).toHaveLength(4 + LINE_COUNT);+ });++ it('folds the block again for a new file', async () => {+ const user = userEvent.setup();+ const {rerender} = render(<DiffViewer file={REPLACED} />);+ await user.click(screen.getByRole('button', {name: 'Show full diff'}));+ rerender(<DiffViewer file={{...REPLACED}} />);+ expect(screen.getByRole('button', {name: 'Show full diff'})).toBeTruthy();+ });++ it('opens a block that holds an annotated line, and can still fold it', async () => {+ const user = userEvent.setup();+ const {container} = render(+ <DiffViewer+ file={REPLACED}+ renderLineAnnotation={ref =>+ ref.side === 'old' && ref.lineNumber === 3 ? (+ <span>Why was this removed?</span>+ ) : null+ }+ />,+ );+ expect(screen.getByText('Why was this removed?')).toBeTruthy();+ const hide = screen.getByRole('button', {name: 'Hide full diff'});+ expect(hide.getAttribute('aria-expanded')).toBe('true');+ await user.click(hide);+ expect(screen.queryByText('Why was this removed?')).toBeNull();+ expect(container.querySelector('[data-diff="removed"]')).toBeNull();+ });++ it('keeps a block folded when its annotations render nothing', () => {+ render(+ <DiffViewer+ file={REPLACED}+ renderLineAnnotation={ref => (ref.side === 'old' ? '' : false)}+ />,+ );+ expect(+ screen+ .getByRole('button', {name: 'Show full diff'})+ .getAttribute('aria-expanded'),+ ).toBe('false');+ });++ it('shows no fold for an ordinary diff', () => {+ render(<DiffViewer file={FILE} />);+ expect(screen.queryByRole('button', {name: 'Show full diff'})).toBeNull();+ });+ });+it('shows a message for binary files', () => {const [binary] = parseUnifiedDiff('diff --git a/x.png b/x.png\nBinary files a/x.png and b/x.png differ\n',diff --git a/packages/lab/src/DiffViewer/DiffViewer.tsx b/packages/lab/src/DiffViewer/DiffViewer.tsxindex e877d67afa..27d5827f66 100644--- a/packages/lab/src/DiffViewer/DiffViewer.tsx+++ b/packages/lab/src/DiffViewer/DiffViewer.tsx@@ -4,7 +4,7 @@* @file DiffViewer.tsx* @input Uses React, StyleX, theme tokens, the shared CodeBlock tokenizer and* syntax-theme slots (incl. the diff row slots), useScrollableArea,- * Token, Icon, VisuallyHidden, and the i18n translator+ * Token, Icon, Button, VisuallyHidden, and the i18n translator* @output Exports DiffViewer component, DiffViewerProps, DiffViewerViewMode,* DiffViewerChangeIndicator, DiffViewerInlineHighlight* @position Lab implementation; read-only, syntax-highlighted file diff for@@ -12,6 +12,8 @@** Renders one DiffViewerFile: a file header (path, status, +/- counts, a* caller slot, optional disclosure) over its hunks in unified or split view.+ * A hunk marked `isReplacedBlock` shows a labeled fold in place of its+ * changed lines until the reader opens it.* Unified view is one table. Split view is two side-by-side panes (each an* ARIA table) whose rows share one grid's row tracks through `subgrid`, so a* row is as tall as its taller side while each pane scrolls sideways on its@@ -62,6 +64,7 @@ import {useScrollableArea,type ScrollableElementProps,} from '@astryxdesign/core/hooks';+import {Button} from '@astryxdesign/core/Button';import {useTranslator} from '@astryxdesign/core/i18n';import {Icon} from '@astryxdesign/core/Icon';import {@@ -81,6 +84,7 @@ import {} from '@astryxdesign/core/theme/tokens.stylex';import {focusOutlineProps,+ isRenderable,mergeProps,rtlStyles,themeProps,@@ -314,13 +318,72 @@ interface LineCell {emphasis: readonly InlineRange[];}+/** The control that folds a replaced block's changed lines. */+interface ReplacedBlockFold {+ hunkIndex: number;+ /** Index of the hunk cell the fold row goes before. */+ at: number;+ /** Removed plus added lines in the block. */+ changedLines: number;+ isExpanded: boolean;+}++interface HunkCells {+ cells: LineCell[];+ fold: ReplacedBlockFold | null;+}++type FoldRow = {type: 'fold'; key: string; fold: ReplacedBlockFold};+type UnifiedRow =| {type: 'hunk'; key: string; header: string}- | {type: 'line'; key: string; cell: LineCell};+ | {type: 'line'; key: string; cell: LineCell}+ | FoldRow;type SplitRow =| {type: 'hunk'; key: string; header: string}- | {type: 'pair'; key: string; old: LineCell | null; new: LineCell | null};+ | {type: 'pair'; key: string; old: LineCell | null; new: LineCell | null}+ | FoldRow;++/**+ * The caller's annotation for a line, or null when it renders nothing. An+ * annotation row is drawn only for a note that renders, so+ * `hasThread && <Thread />` adds no empty row.+ */+function lineAnnotation(+ renderLineAnnotation: (ref: DiffViewerLineRef) => ReactNode,+ ref: DiffViewerLineRef,+): ReactNode {+ const note = renderLineAnnotation(ref);+ return isRenderable(note) ? note : null;+}++/**+ * Replaced blocks with an annotation on one of their changed lines. Such a+ * block starts open, so a review comment is never hidden behind the fold.+ */+function findAnnotatedBlocks(+ file: DiffViewerFile,+ renderLineAnnotation: ((ref: DiffViewerLineRef) => ReactNode) | undefined,+): Set<number> {+ const blocks = new Set<number>();+ if (renderLineAnnotation == null) {+ return blocks;+ }+ file.hunks.forEach((hunk, hunkIndex) => {+ if (hunk.isReplacedBlock !== true) {+ return;+ }+ const isAnnotated = hunk.lines.some(line => {+ const ref = line.kind === 'context' ? null : lineRef(line, hunkIndex);+ return ref != null && lineAnnotation(renderLineAnnotation, ref) != null;+ });+ if (isAnnotated) {+ blocks.add(hunkIndex);+ }+ });+ return blocks;+}function lineRef(line: DiffViewerLine,@@ -373,60 +436,113 @@ function addInlineEmphasis(}/**- * Tokenize each hunk's old and new side as continuous text, so constructs- * that span lines (block comments, template strings) keep their paint within- * the hunk, then hand each line the tokens of the side it renders from.+ * Tokenize a run of hunk lines with its old and new side each as continuous+ * text, so constructs that span lines (block comments, template strings) keep+ * their paint within the run, and give each line the tokens of the side it+ * renders from.+ */+function tokenizeRun(+ lines: readonly DiffViewerLine[],+ language: string | CodeLanguage,+): TokenLine[] {+ if (language === 'plaintext') {+ return lines.map(() => []);+ }+ const sideText = (kind: 'added' | 'removed') =>+ lines+ .filter(line => line.kind !== kind)+ .map(line => line.content)+ .join('\n');+ const oldTokens = tokenize(sideText('added'), language);+ const newTokens = tokenize(sideText('removed'), language);+ let oldIndex = 0;+ let newIndex = 0;+ return lines.map(line => {+ if (line.kind === 'removed') {+ return oldTokens[oldIndex++] ?? [];+ }+ if (line.kind === 'added') {+ return newTokens[newIndex++] ?? [];+ }+ oldIndex++;+ return newTokens[newIndex++] ?? [];+ });+}++/**+ * Build each hunk's line cells. A folded replaced block keeps only the+ * context around it, and its changed lines are not tokenized.*/function buildCells(file: DiffViewerFile,language: string | CodeLanguage,inlineHighlight: DiffViewerInlineHighlight,-): LineCell[][] {+ expandedBlocks: ReadonlySet<number>,+): HunkCells[] {return file.hunks.map((hunk, hunkIndex) => {- const oldLines = hunk.lines.filter(line => line.kind !== 'added');- const newLines = hunk.lines.filter(line => line.kind !== 'removed');- const highlight = language !== 'plaintext';- const oldTokens = highlight- ? tokenize(oldLines.map(line => line.content).join('\n'), language)- : [];- const newTokens = highlight- ? tokenize(newLines.map(line => line.content).join('\n'), language)- : [];- let oldIndex = 0;- let newIndex = 0;const cells: LineCell[] = [];- for (const line of hunk.lines) {- let tokens: TokenLine;- if (line.kind === 'removed') {- tokens = oldTokens[oldIndex++] ?? [];- } else if (line.kind === 'added') {- tokens = newTokens[newIndex++] ?? [];- } else {- oldIndex++;- tokens = newTokens[newIndex++] ?? [];- }- const ref = lineRef(line, hunkIndex);- if (ref != null) {- cells.push({line, ref, tokens, emphasis: []});+ const addRun = (lines: readonly DiffViewerLine[]) => {+ const tokens = tokenizeRun(lines, language);+ lines.forEach((line, i) => {+ const ref = lineRef(line, hunkIndex);+ if (ref != null) {+ cells.push({line, ref, tokens: tokens[i], emphasis: []});+ }+ });+ };++ const changeStart =+ hunk.isReplacedBlock === true+ ? hunk.lines.findIndex(line => line.kind !== 'context')+ : -1;+ if (changeStart === -1) {+ addRun(hunk.lines);+ if (inlineHighlight !== 'none') {+ addInlineEmphasis(cells, inlineHighlight);}+ return {cells, fold: null};}- if (inlineHighlight !== 'none') {- addInlineEmphasis(cells, inlineHighlight);++ // A replaced block's removed and added lines are not edits of each+ // other, so they get no inline highlight.+ const isExpanded = expandedBlocks.has(hunkIndex);+ const changedLines = hunk.lines.filter(+ line => line.kind !== 'context',+ ).length;+ if (isExpanded) {+ addRun(hunk.lines);+ const at = cells.findIndex(cell => cell.line.kind !== 'context');+ return {+ cells,+ fold: {hunkIndex, at, changedLines, isExpanded},+ };}- return cells;+ // Leading and trailing context are tokenized apart: the hidden lines+ // between them can open or close a comment or a string.+ addRun(hunk.lines.slice(0, changeStart));+ const at = cells.length;+ addRun(hunk.lines.slice(changeStart + changedLines));+ return {cells, fold: {hunkIndex, at, changedLines, isExpanded}};});}function buildUnifiedRows(file: DiffViewerFile,- cells: LineCell[][],+ cells: HunkCells[],): UnifiedRow[] {const rows: UnifiedRow[] = [];file.hunks.forEach((hunk, h) => {rows.push({type: 'hunk', key: `h${h}`, header: hunk.header});- cells[h].forEach((cell, i) => {+ const {cells: hunkCells, fold} = cells[h];+ hunkCells.forEach((cell, i) => {+ if (fold != null && fold.at === i) {+ rows.push({type: 'fold', key: `h${h}f`, fold});+ }rows.push({type: 'line', key: `h${h}l${i}`, cell});});+ if (fold != null && fold.at === hunkCells.length) {+ rows.push({type: 'fold', key: `h${h}f`, fold});+ }});return rows;}@@ -435,13 +551,17 @@ function buildUnifiedRows(* Pair each run of removed lines with the run of added lines that follows it,* row by row; context lines appear on both sides of one row.*/-function buildSplitRows(file: DiffViewerFile, cells: LineCell[][]): SplitRow[] {+function buildSplitRows(file: DiffViewerFile, cells: HunkCells[]): SplitRow[] {const rows: SplitRow[] = [];file.hunks.forEach((hunk, h) => {rows.push({type: 'hunk', key: `h${h}`, header: hunk.header});- const hunkCells = cells[h];+ const {cells: hunkCells, fold} = cells[h];let i = 0;while (i < hunkCells.length) {+ // The fold sits where a run of changes starts or ends, never inside one.+ if (fold != null && fold.at === i) {+ rows.push({type: 'fold', key: `h${h}f`, fold});+ }const cell = hunkCells[i];if (cell.line.kind === 'context') {rows.push({type: 'pair', key: `h${h}l${i}`, old: cell, new: cell});@@ -466,6 +586,9 @@ function buildSplitRows(file: DiffViewerFile, cells: LineCell[][]): SplitRow[] {});}}+ if (fold != null && fold.at === hunkCells.length) {+ rows.push({type: 'fold', key: `h${h}f`, fold});+ }});return rows;}@@ -867,6 +990,25 @@ const styles = stylex.create({borderBlockStyle: 'solid',borderBlockColor: colorVars['--color-border'],},+ fold: {+ paddingBlock: spacingVars['--spacing-2'],+ paddingInline: spacingVars['--spacing-3'],+ textAlign: 'start',+ backgroundColor: 'var(--color-syntax-diff-header)',+ color: colorVars['--color-text-secondary'],+ fontFamily: typographyVars['--font-family-body'],+ fontSize: typeScaleVars['--text-supporting-size'],+ lineHeight: typeScaleVars['--text-supporting-leading'],+ borderBlockWidth: borderVars['--border-width'],+ borderBlockStyle: 'solid',+ borderBlockColor: colorVars['--color-border'],+ },+ foldContent: {+ display: 'inline-flex',+ alignItems: 'center',+ flexWrap: 'wrap',+ gap: spacingVars['--spacing-3'],+ },// Unwrapped, the header text stays at the visible start while the code// scrolls.hunkTextSticky: {@@ -1158,9 +1300,38 @@ export function DiffViewer({onCollapsedChange?.(next);};+ // A replaced block starts folded unless one of its lines is annotated. The+ // reader's toggles are kept per file; a new file starts over.+ const [blockToggles, setBlockToggles] = useState<{+ file: DiffViewerFile;+ isExpanded: ReadonlyMap<number, boolean>;+ } | null>(null);+ const toggles = blockToggles?.file === file ? blockToggles.isExpanded : null;+ const annotatedBlocks = findAnnotatedBlocks(file, renderLineAnnotation);+ const isBlockExpanded = (hunkIndex: number) =>+ toggles?.get(hunkIndex) ?? annotatedBlocks.has(hunkIndex);+ const toggleBlock = (hunkIndex: number) => {+ const next = new Map(toggles);+ next.set(hunkIndex, !isBlockExpanded(hunkIndex));+ setBlockToggles({file, isExpanded: next});+ };+ // A key of the open blocks keeps the set stable across renders, so the+ // cells are built again only when a block opens or closes.+ const expandedKey = file.hunks+ .flatMap((hunk, hunkIndex) =>+ hunk.isReplacedBlock === true && isBlockExpanded(hunkIndex)+ ? [hunkIndex]+ : [],+ )+ .join(',');+ const expandedBlocks = useMemo(+ () => new Set(expandedKey === '' ? [] : expandedKey.split(',').map(Number)),+ [expandedKey],+ );+const cells = useMemo(- () => buildCells(file, language, inlineHighlight),- [file, language, inlineHighlight],+ () => buildCells(file, language, inlineHighlight, expandedBlocks),+ [file, language, inlineHighlight, expandedBlocks],);const unifiedRows = useMemo(() => (viewMode === 'unified' ? buildUnifiedRows(file, cells) : []),@@ -1352,21 +1523,36 @@ export function DiffViewer({);};+ const renderFold = (fold: ReplacedBlockFold) => (+ <span+ {...stylex.props(styles.foldContent, isPinned && styles.hunkTextSticky)}>+ <span>+ {t('@astryx.diffViewer.largeChange', {count: fold.changedLines})}+ </span>+ <Button+ size="sm"+ variant="secondary"+ label={+ fold.isExpanded+ ? t('@astryx.diffViewer.hideFullDiff')+ : t('@astryx.diffViewer.showFullDiff')+ }+ aria-expanded={fold.isExpanded}+ onClick={() => toggleBlock(fold.hunkIndex)}+ />+ </span>+ );+const renderHunkText = (header: string) => (<span {...stylex.props(styles.ltr, isPinned && styles.hunkTextSticky)}>{header}</span>);- // `null`, `undefined` and booleans render nothing in React, so they draw no- // row either; that keeps `hasThread && <Thread />` from adding empty rows.- const annotationFor = (cell: LineCell | null): ReactNode => {- if (cell == null || renderLineAnnotation == null) {- return null;- }- const note = renderLineAnnotation(cell.ref);- return typeof note === 'boolean' ? null : note;- };+ const annotationFor = (cell: LineCell | null): ReactNode =>+ cell == null || renderLineAnnotation == null+ ? null+ : lineAnnotation(renderLineAnnotation, cell.ref);// Name every column so a screen reader moving across a row hears which// number is which (and, in split view, which side's code it is in).@@ -1424,6 +1610,15 @@ export function DiffViewer({</tr>);}+ if (row.type === 'fold') {+ return (+ <tr key={row.key}>+ <td colSpan={columns} {...stylex.props(styles.fold)}>+ {renderFold(row.fold)}+ </td>+ </tr>+ );+ }const note = annotationFor(row.cell);return (<Fragment key={row.key}>@@ -1497,7 +1692,7 @@ export function DiffViewer({const renderSplit = () => {const items = splitRows.map(row =>- row.type === 'hunk'+ row.type !== 'pair'? {row, oldNote: null, newNote: null}: {row,@@ -1511,7 +1706,7 @@ export function DiffViewer({const hasSizer = !isWrapped;const sizerText = hasSizer? widestLine(- cells.flatMap(hunkCells => hunkCells.map(cell => cell.line.content)),+ cells.flatMap(hunk => hunk.cells.map(cell => cell.line.content)),): '';const rowCount =@@ -1587,6 +1782,39 @@ export function DiffViewer({);continue;}+ if (row.type === 'fold') {+ // Only the old side holds the control; the new side keeps its row+ // as tall and gives its own table's readers the label.+ rows.push(+ <div key={row.key} role="row" {...stylex.props(styles.paneRow)}>+ <div+ role="cell"+ {...stylex.props(+ styles.fold,+ styles.paneSpan,+ isWrapped && styles.codeWrapped,+ )}>+ {isOld ? (+ renderFold(row.fold)+ ) : (+ <>+ <span+ aria-hidden="true"+ {...stylex.props(styles.invisible)}>+ {renderFold(row.fold)}+ </span>+ <VisuallyHidden>+ {t('@astryx.diffViewer.largeChange', {+ count: row.fold.changedLines,+ })}+ </VisuallyHidden>+ </>+ )}+ </div>+ </div>,+ );+ continue;+ }const cell = isOld ? row.old : row.new;rows.push(<divdiff --git a/packages/lab/src/DiffViewer/createDiffFile.test.ts b/packages/lab/src/DiffViewer/createDiffFile.test.tsindex d715c924dc..b353a4d36f 100644--- a/packages/lab/src/DiffViewer/createDiffFile.test.ts+++ b/packages/lab/src/DiffViewer/createDiffFile.test.ts@@ -135,11 +135,30 @@ describe('createDiffFile', () => {expect(kinds[0]).toBe('context');expect(kinds[kinds.length - 1]).toBe('context');expect(kinds.indexOf('added')).toBe(lineCount + 1);+ expect(hunk.isReplacedBlock).toBe(true);const {oldSide, newSide} = sides(file);expect(oldSide).toEqual(['head', ...oldLines, 'tail']);expect(newSide).toEqual(['head', ...newLines, 'tail']);});+ it('does not mark a minimal diff as a replaced block', () => {+ const file = createDiffFile({oldValue: 'a\nb\n', newValue: 'a\nB\n'});+ expect(file.hunks[0].isReplacedBlock).toBeUndefined();+ });++ it('keeps a long one-sided change minimal, not a replaced block', () => {+ // Only additions: adding every new line is already the minimal diff.+ const lineCount = 6000;+ const added = Array.from({length: lineCount}, (_, i) => `new ${i}`);+ const file = createDiffFile({+ oldValue: ['head', 'tail'].join('\n'),+ newValue: ['head', ...added, 'tail'].join('\n'),+ });+ expect(file.hunks).toHaveLength(1);+ expect(file.hunks[0].isReplacedBlock).toBeUndefined();+ expect(file.hunks[0].newLines).toBe(lineCount + 2);+ });+it('handles a very long text changed only at both ends', () => {// Every line in between is matched by the search, so the edit script// holds one op per line: more than a call can take as spread arguments.diff --git a/packages/lab/src/DiffViewer/createDiffFile.ts b/packages/lab/src/DiffViewer/createDiffFile.tsindex d92d42a8bb..ba0bc29a23 100644--- a/packages/lab/src/DiffViewer/createDiffFile.ts+++ b/packages/lab/src/DiffViewer/createDiffFile.ts@@ -10,8 +10,8 @@** Shared leading and trailing lines are matched without a search. The minimal* search over the rest stops after MAX_EDIT_DISTANCE changed lines, so memory- * stays bounded for any input; a middle that differs more than that is shown- * as one replaced block rather than a minimal diff.+ * stays bounded for any input; a middle that differs more than that becomes+ * one replaced block, marked with `isReplacedBlock` on its hunk.** SYNC: When modified, update:* - /packages/lab/src/DiffViewer/createDiffFile.test.ts@@ -70,13 +70,19 @@ function splitLines(value: string): string[] {*/const MAX_EDIT_DISTANCE = 2000;+interface EditScript {+ ops: Op[];+ /** True when the middle was replaced as a whole, not compared line by line. */+ isReplacedBlock: boolean;+}+/*** Line edit script from `a` to `b`. Shared leading and trailing lines are* context without a search; the middle uses Myers' O(ND) shortest edit script,* or, when it needs more than MAX_EDIT_DISTANCE edits, removes the old middle* and adds the new one.*/-function diffLines(a: string[], b: string[]): Op[] {+function diffLines(a: string[], b: string[]): EditScript {let head = 0;while (head < a.length && head < b.length && a[head] === b[head]) {head++;@@ -92,7 +98,10 @@ function diffLines(a: string[], b: string[]): Op[] {for (let i = 0; i < head; i++) {ops.push({kind: 'context', a: i, b: i});}- const middle = myers(a, b, head, tailA, tailB);+ // When one side of the middle is empty, adding or removing the other side+ // is already the minimal script.+ const isOneSided = tailA === head || tailB === head;+ const middle = isOneSided ? null : myers(a, b, head, tailA, tailB);if (middle != null) {// A loop, not a spread: one call argument per op overflows the stack on// long inputs.@@ -110,7 +119,7 @@ function diffLines(a: string[], b: string[]): Op[] {for (let i = 0; tailA + i < a.length; i++) {ops.push({kind: 'context', a: tailA + i, b: tailB + i});}- return ops;+ return {ops, isReplacedBlock: middle == null && !isOneSided};}/**@@ -225,7 +234,7 @@ export function createDiffFile({const a = splitLines(oldValue);const b = splitLines(newValue);- const ops = diffLines(a, b);+ const {ops, isReplacedBlock} = diffLines(a, b);const changed: number[] = [];ops.forEach((op, i) => {@@ -302,6 +311,8 @@ export function createDiffFile({newStart,newLines: newCount,lines,+ // A replaced block is the only change, so it fills the only hunk.+ ...(isReplacedBlock ? {isReplacedBlock: true} : {}),});g = h;}diff --git a/packages/lab/src/DiffViewer/diffTypes.ts b/packages/lab/src/DiffViewer/diffTypes.tsindex 60bf39156d..d2166c88b5 100644--- a/packages/lab/src/DiffViewer/diffTypes.ts+++ b/packages/lab/src/DiffViewer/diffTypes.ts@@ -46,6 +46,13 @@ export interface DiffViewerHunk {newStart: number;newLines: number;lines: DiffViewerLine[];+ /**+ * True when the change was too large to compare line by line, so the hunk+ * lists every old line as removed and every new line as added instead of a+ * minimal diff. `createDiffFile` sets it; DiffViewer folds the changed lines+ * behind a labeled control that shows them on request.+ */+ isReplacedBlock?: boolean;}/** One file's changes. */