An open source design system that's fully customizable and agent ready
TypeScript
feat(lab): DiffViewer — unified/split file diff for code review (#7536)
Brian Latchman97a00379a701
diff --git a/.changeset/diff-viewer-catalog-keys.md b/.changeset/diff-viewer-catalog-keys.mdnew file mode 100644index 0000000000..4ab33a2535--- /dev/null+++ b/.changeset/diff-viewer-catalog-keys.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[feat] Adds the `@astryx.diffViewer.*` keys to the `en` catalog so the lab `DiffViewer` reads its file-status badges, line counts, line-number button labels, per-line "Added"/"Removed" labels, and empty-state messages from the translation runtime. No existing string changes; locales without a translation fall back to English.++@latxhdiff --git a/apps/storybook/stories/DiffViewer.stories.tsx b/apps/storybook/stories/DiffViewer.stories.tsxnew file mode 100644index 0000000000..9cfbd9539b--- /dev/null+++ b/apps/storybook/stories/DiffViewer.stories.tsx@@ -0,0 +1,302 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import type {Meta, StoryObj} from '@storybook/react';+import {useState} from 'react';+import {+ DiffViewer,+ parseUnifiedDiff,+ type DiffViewerLineRef,+} from '@astryxdesign/lab';+import {Button} from '@astryxdesign/core/Button';+import {Card} from '@astryxdesign/core/Card';+import {CheckboxInput} from '@astryxdesign/core/CheckboxInput';+import {HStack, StackItem, VStack} from '@astryxdesign/core/Stack';+import {Text} from '@astryxdesign/core/Text';++const PATCH = `diff --git a/src/cart/total.ts b/src/cart/total.ts+index 4c1a2b7..9e0f3d1 100644+--- a/src/cart/total.ts++++ b/src/cart/total.ts+@@ -1,16 +1,18 @@+ import type {CartItem} from './types';++import {roundCurrency} from '../money';++ /**+- * Sum the price of every item in the cart.++ * Sum the price of every item in the cart, applying the discount once++ * after the subtotal so rounding errors do not compound per item.+ */+-export function cartTotal(items: CartItem[], discount = 0) {+- let total = 0;+- for (const item of items) {+- total += item.price * item.quantity * (1 - discount);+- }+- return total;++export function cartTotal(items: CartItem[], discount = 0): number {++ const subtotal = items.reduce(++ (sum, item) => sum + item.price * item.quantity,++ 0,++ );++ return roundCurrency(subtotal * (1 - discount));+ }++ export function isEmpty(items: CartItem[]) {+ return items.length === 0;+ }+@@ -40,7 +42,7 @@ export function formatTotal(total: number, currency: string) {+ const formatter = new Intl.NumberFormat(undefined, {+ style: 'currency',+ currency,+- maximumFractionDigits: 3,++ maximumFractionDigits: 2,+ });+ return formatter.format(total);+ }+diff --git a/src/money.ts b/src/money.ts+new file mode 100644+index 0000000..b3f1c2e+--- /dev/null++++ b/src/money.ts+@@ -0,0 +1,4 @@++/** Round to whole cents. */++export function roundCurrency(value: number): number {++ return Math.round(value * 100) / 100;++}+diff --git a/src/cart/legacy.ts b/src/cart/legacyTotals.ts+similarity index 100%+rename from src/cart/legacy.ts+rename to src/cart/legacyTotals.ts+diff --git a/public/receipt.png b/public/receipt.png+index 1f2e3d4..5a6b7c8 100644+Binary files a/public/receipt.png and b/public/receipt.png differ+`;++const FILES = parseUnifiedDiff(PATCH);+const [TOTAL_FILE] = FILES;++const meta: Meta<typeof DiffViewer> = {+ title: 'Lab/DiffViewer',+ component: DiffViewer,+ tags: ['autodocs'],+ parameters: {+ layout: 'padded',+ },+ args: {+ file: TOTAL_FILE,+ },+ decorators: [+ Story => (+ <div style={{maxWidth: 1080, padding: 16}}>+ <Story />+ </div>+ ),+ ],+};++export default meta;+type Story = StoryObj<typeof DiffViewer>;++/** One file, unified view (the default). */+export const Default: Story = {};++/** Old file on the left, new file on the right. */+export const Split: Story = {+ args: {viewMode: 'split'},+};++/** Long lines wrap instead of scrolling. */+export const Wrapped: Story = {+ args: {viewMode: 'split', isWrapped: true},+ decorators: [+ Story => (+ <div style={{maxWidth: 720}}>+ <Story />+ </div>+ ),+ ],+};++const LONG_LINE_FILE =+ parseUnifiedDiff(`diff --git a/src/cart/discounts.ts b/src/cart/discounts.ts+--- a/src/cart/discounts.ts++++ b/src/cart/discounts.ts+@@ -1,4 +1,4 @@+ import type {CartItem} from './types';+-export const discountFor = (item: CartItem, rules: ReadonlyArray<{sku: string; percent: number}>) => rules.find(rule => rule.sku === item.sku)?.percent ?? 0;++export const discountFor = (item: CartItem, rules: ReadonlyArray<{sku: string; percent: number; expiresAt?: number}>) => rules.find(rule => rule.sku === item.sku && (rule.expiresAt == null || rule.expiresAt > Date.now()))?.percent ?? 0;++ export const NO_DISCOUNT = 0;+`)[0];++/**+ * A right-to-left page with lines wider than the viewer. The hunk area stays+ * left-to-right like a code editor, so every line opens at its start. The file+ * header and comment text follow the page. Comment rows belong to the code+ * layout: each comment reads from its side's right edge and, like the code+ * beside it, may need a horizontal scroll to bring into view.+ */+export const RightToLeft: Story = {+ args: {+ file: LONG_LINE_FILE,+ viewMode: 'split',+ renderLineAnnotation: (ref: DiffViewerLineRef) => {+ if (ref.side === 'old' && ref.lineNumber === 2) {+ return <Text type="body">كان الخصم لا يتحقق من تاريخ الانتهاء.</Text>;+ }+ if (ref.side === 'new' && ref.lineNumber === 2) {+ return <Text type="body">تحقق من تاريخ انتهاء الخصم قبل الدمج.</Text>;+ }+ return null;+ },+ },+ decorators: [+ Story => (+ <div dir="rtl" style={{maxWidth: 960}}>+ <Story />+ </div>+ ),+ ],+};++/** A whole patch: one DiffViewer per file, incl. added, renamed, and binary files. */+export const MultiFilePatch: Story = {+ render: args => (+ <VStack gap={3}>+ {FILES.map(file => (+ <DiffViewer key={file.newPath ?? file.oldPath} {...args} file={file} />+ ))}+ </VStack>+ ),+};++/** File header actions: a "Viewed" checkbox that also folds the file away. */+export const ViewedToggle: Story = {+ render: args => {+ const [isViewed, setIsViewed] = useState(false);+ const [isCollapsed, setIsCollapsed] = useState(false);+ return (+ <DiffViewer+ {...args}+ isCollapsed={isCollapsed}+ onCollapsedChange={setIsCollapsed}+ headerEnd={+ <CheckboxInput+ label="Viewed"+ value={isViewed}+ onChange={checked => {+ setIsViewed(checked);+ setIsCollapsed(checked);+ }}+ />+ }+ />+ );+ },+};++interface Comment {+ id: number;+ side: DiffViewerLineRef['side'];+ lineNumber: number;+}++/**+ * Review comments: click a line number to open a comment under that line.+ * Anchors (side + lineNumber) stay put when switching view modes.+ */+export const ReviewComments: Story = {+ render: args => {+ const [viewMode, setViewMode] = useState<'unified' | 'split'>('unified');+ const [comments, setComments] = useState<Comment[]>([+ {id: 1, side: 'new', lineNumber: 13},+ ]);+ return (+ <VStack gap={3}>+ <HStack gap={2} vAlign="center">+ <StackItem size="fill">+ <Text type="supporting" color="secondary">+ Click a line number to add a comment.+ </Text>+ </StackItem>+ <Button+ label={viewMode === 'unified' ? 'Split view' : 'Unified view'}+ variant="secondary"+ onClick={() =>+ setViewMode(mode => (mode === 'unified' ? 'split' : 'unified'))+ }+ />+ </HStack>+ <DiffViewer+ {...args}+ viewMode={viewMode}+ onLineNumberClick={ref =>+ setComments(current => [+ ...current,+ {id: Date.now(), side: ref.side, lineNumber: ref.lineNumber},+ ])+ }+ renderLineAnnotation={ref => {+ const here = comments.filter(+ comment =>+ comment.side === ref.side &&+ comment.lineNumber === ref.lineNumber,+ );+ if (here.length === 0) {+ return null;+ }+ return (+ <VStack gap={2}>+ {here.map(comment => (+ <Card key={comment.id}>+ <HStack gap={2} vAlign="center">+ <StackItem size="fill">+ <Text>+ {`Comment on ${comment.side} line ${comment.lineNumber}`}+ </Text>+ </StackItem>+ <Button+ label="Resolve"+ variant="ghost"+ size="sm"+ onClick={() =>+ setComments(current =>+ current.filter(c => c.id !== comment.id),+ )+ }+ />+ </HStack>+ </Card>+ ))}+ </VStack>+ );+ }}+ />+ </VStack>+ );+ },+};++/**+ * A multi-sentence comment wraps within the width the code sets; it never+ * widens the table.+ */+export const LongComment: Story = {+ args: {+ renderLineAnnotation: (ref: DiffViewerLineRef) =>+ ref.side === 'new' && ref.lineNumber === 13 ? (+ <Text type="body">+ Rounding once after the subtotal fixes the drift we saw on large+ carts, but it changes totals for carts that relied on per-item+ rounding. Before this lands, check the receipt snapshots, confirm the+ discount still applies to gift cards, and add a test with a 33%+ discount on three items so the rounding rule is pinned. If any partner+ integrations read the per-item totals, they need a heads-up as well.+ </Text>+ ) : null,+ },+};++/** Without line numbers, capped height. */+export const Compact: Story = {+ args: {hasLineNumbers: false, maxHeight: 240},+};diff --git a/internal/shadcn-registry/routes.lock.json b/internal/shadcn-registry/routes.lock.jsonindex 3327c4d6ee..855b48341a 100644--- a/internal/shadcn-registry/routes.lock.json+++ b/internal/shadcn-registry/routes.lock.json@@ -556,6 +556,11 @@"path": "components/lab/code-editor","aliases": []},+ {+ "name": "component-lab-diff-viewer",+ "path": "components/lab/diff-viewer",+ "aliases": []+ },{"name": "component-lab-drawer","path": "components/lab/drawer",@@ -4255,6 +4260,11 @@"path": "showcases/dialog/default","aliases": []},+ {+ "name": "showcase-diff-viewer-unified-diff-from-a-patch",+ "path": "showcases/diff-viewer/unified-diff-from-a-patch",+ "aliases": []+ },{"name": "showcase-divider-variants","path": "showcases/divider/variants",diff --git a/packages/core/locales/en.json b/packages/core/locales/en.jsonindex d8b0e9a254..f5a7da21cf 100644--- a/packages/core/locales/en.json+++ b/packages/core/locales/en.json@@ -527,6 +527,82 @@"defaultMessage": "This {itemName} is already {boundary, select, first {first} last {last} other {}}.","description": "Screen-reader-only live announcement when an arrow-key reorder attempt has no effect because the record is already at that end of the list. `{itemName}` is the consumer's singular noun for one record; `{boundary}` is always exactly \"first\" or \"last\"."},+ "@astryx.diffViewer.label": {+ "defaultMessage": "Diff",+ "description": "Accessible name of a lab DiffViewer's scrollable code area when the file has no path to name it."+ },+ "@astryx.diffViewer.renamedPath": {+ "defaultMessage": "{oldPath} → {newPath}",+ "description": "File path shown in a lab DiffViewer header when the file was renamed. `{oldPath}` and `{newPath}` are file paths and must stay untranslated; keep the arrow pointing from the old path to the new one."+ },+ "@astryx.diffViewer.statusAdded": {+ "defaultMessage": "Added",+ "description": "Badge in a lab DiffViewer file header marking a file that the change creates."+ },+ "@astryx.diffViewer.statusDeleted": {+ "defaultMessage": "Deleted",+ "description": "Badge in a lab DiffViewer file header marking a file that the change removes."+ },+ "@astryx.diffViewer.statusRenamed": {+ "defaultMessage": "Renamed",+ "description": "Badge in a lab DiffViewer file header marking a file that the change moves to a new path."+ },+ "@astryx.diffViewer.addedCount": {+ "defaultMessage": "+{count, number}",+ "description": "Compact count of added lines shown in a lab DiffViewer file header, e.g. \"+12\". Hidden from screen readers, which hear `@astryx.diffViewer.stats` instead."+ },+ "@astryx.diffViewer.removedCount": {+ "defaultMessage": "−{count, number}",+ "description": "Compact count of removed lines shown in a lab DiffViewer file header, e.g. \"−3\" (a minus sign). Hidden from screen readers, which hear `@astryx.diffViewer.stats` instead."+ },+ "@astryx.diffViewer.stats": {+ "defaultMessage": "{added, plural, one {# line added} other {# lines added}}, {removed, plural, one {# line removed} other {# lines removed}}",+ "description": "Screen-reader text for the line counts in a lab DiffViewer file header, e.g. \"12 lines added, 3 lines removed\"."+ },+ "@astryx.diffViewer.added": {+ "defaultMessage": "Added",+ "description": "Screen-reader text marking one line of a lab DiffViewer as added by the change; sighted readers see a + sign and a tinted row."+ },+ "@astryx.diffViewer.removed": {+ "defaultMessage": "Removed",+ "description": "Screen-reader text marking one line of a lab DiffViewer as removed by the change; sighted readers see a - sign and a tinted row."+ },+ "@astryx.diffViewer.lineNumberButton": {+ "defaultMessage": "{side, select, old {Original line {line, number}} other {Changed line {line, number}}}",+ "description": "Accessible label of a clickable line number in a lab DiffViewer (callers use it, for example, to start a comment on that line). `side` is `old` for the file before the change and `new` for the file after it; `line` is the line number in that version."+ },+ "@astryx.diffViewer.columnOldLine": {+ "defaultMessage": "Original line number",+ "description": "Screen-reader-only header of a lab DiffViewer column holding line numbers in the file before the change. Pairs with `@astryx.diffViewer.lineNumberButton` (\"Original line …\")."+ },+ "@astryx.diffViewer.columnNewLine": {+ "defaultMessage": "Changed line number",+ "description": "Screen-reader-only header of a lab DiffViewer column holding line numbers in the file after the change. Pairs with `@astryx.diffViewer.lineNumberButton` (\"Changed line …\")."+ },+ "@astryx.diffViewer.columnChange": {+ "defaultMessage": "Change",+ "description": "Screen-reader-only header of a lab DiffViewer column that marks each line as added or removed (noun: the kind of change)."+ },+ "@astryx.diffViewer.columnCode": {+ "defaultMessage": "Code",+ "description": "Screen-reader-only header of the source-code column in a lab DiffViewer's single-column (unified) view."+ },+ "@astryx.diffViewer.columnOldCode": {+ "defaultMessage": "Original code",+ "description": "Screen-reader-only header of the source-code column for the file before the change, in a lab DiffViewer's side-by-side (split) view."+ },+ "@astryx.diffViewer.columnNewCode": {+ "defaultMessage": "Changed code",+ "description": "Screen-reader-only header of the source-code column for the file after the change, in a lab DiffViewer's side-by-side (split) view."+ },+ "@astryx.diffViewer.binary": {+ "defaultMessage": "Binary file not shown",+ "description": "Message in place of line changes in a lab DiffViewer when the file is binary and has no text diff."+ },+ "@astryx.diffViewer.noChanges": {+ "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.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/blocks/DiffViewerShowcase.doc.mjs b/packages/lab/blocks/DiffViewerShowcase.doc.mjsnew file mode 100644index 0000000000..c38ab7c606--- /dev/null+++ b/packages/lab/blocks/DiffViewerShowcase.doc.mjs@@ -0,0 +1,22 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */+export default {+ type: 'block',+ name: 'Unified diff from a patch',+ displayName: 'Unified diff from a patch',+ description:+ 'A patch parsed with parseUnifiedDiff and rendered in unified or split view. Clicking a line number selects that line and opens an annotation row under it, the way a review comment would appear.',+ exampleFor: 'DiffViewer',+ isReady: true,+ isShowcase: true,+ aspectRatio: 16 / 9,+ componentsUsed: [+ 'DiffViewer',+ 'Button',+ 'HStack',+ 'StackItem',+ 'VStack',+ 'Text',+ ],+};diff --git a/packages/lab/blocks/DiffViewerShowcase.tsx b/packages/lab/blocks/DiffViewerShowcase.tsxnew file mode 100644index 0000000000..6af459fae1--- /dev/null+++ b/packages/lab/blocks/DiffViewerShowcase.tsx@@ -0,0 +1,81 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @input A unified diff string parsed with parseUnifiedDiff+ * @output One DiffViewer with a unified/split toggle and click-to-comment line numbers+ * @position Lab DiffViewer's docsite showcase and copyable CLI block+ */++import {useState} from 'react';+import {+ DiffViewer,+ parseUnifiedDiff,+ type DiffViewerLineRef,+} from '@astryxdesign/lab';+import {Button} from '@astryxdesign/core/Button';+import {HStack, StackItem, VStack} from '@astryxdesign/core/Stack';+import {Text} from '@astryxdesign/core/Text';++const PATCH = `diff --git a/src/cart/total.ts b/src/cart/total.ts+--- a/src/cart/total.ts++++ b/src/cart/total.ts+@@ -1,9 +1,11 @@+ import type {CartItem} from './types';++import {roundCurrency} from '../money';++-export function cartTotal(items: CartItem[], discount = 0) {+- let total = 0;+- for (const item of items) {+- total += item.price * item.quantity * (1 - discount);+- }+- return total;++export function cartTotal(items: CartItem[], discount = 0): number {++ const subtotal = items.reduce(++ (sum, item) => sum + item.price * item.quantity,++ 0,++ );++ return roundCurrency(subtotal * (1 - discount));+ }+`;++const [FILE] = parseUnifiedDiff(PATCH);++export default function DiffViewerShowcase() {+ const [viewMode, setViewMode] = useState<'unified' | 'split'>('unified');+ const [selected, setSelected] = useState<DiffViewerLineRef | null>(null);++ return (+ <VStack gap={3}>+ <HStack gap={2} vAlign="center">+ <StackItem size="fill">+ <Text type="supporting" color="secondary">+ {selected == null+ ? 'Click a line number to select a line.'+ : `Selected ${selected.side} line ${selected.lineNumber}`}+ </Text>+ </StackItem>+ <Button+ label={viewMode === 'unified' ? 'Split view' : 'Unified view'}+ variant="secondary"+ onClick={() =>+ setViewMode(mode => (mode === 'unified' ? 'split' : 'unified'))+ }+ />+ </HStack>+ <DiffViewer+ file={FILE}+ viewMode={viewMode}+ onLineNumberClick={ref => setSelected(ref)}+ renderLineAnnotation={ref =>+ selected != null &&+ ref.side === selected.side &&+ ref.lineNumber === selected.lineNumber ? (+ <Text>{`Comment on ${ref.side} line ${ref.lineNumber}`}</Text>+ ) : null+ }+ />+ </VStack>+ );+}diff --git a/packages/lab/src/DiffViewer/DiffViewer.doc.mjs b/packages/lab/src/DiffViewer/DiffViewer.doc.mjsnew file mode 100644index 0000000000..4d4062a158--- /dev/null+++ b/packages/lab/src/DiffViewer/DiffViewer.doc.mjs@@ -0,0 +1,177 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').ComponentDoc} */++export const docs = {+ name: 'DiffViewer',+ displayName: 'Diff Viewer',+ group: 'DiffViewer',+ category: 'Content',+ keywords: [+ 'diff',+ 'patch',+ 'code review',+ 'changes',+ 'split',+ 'unified',+ 'side by side',+ 'compare',+ ],++ theming: {+ targets: [+ {className: 'astryx-diff-viewer', visualProps: ['viewMode']},+ {className: 'astryx-diff-viewer-header'},+ {className: 'astryx-diff-viewer-path'},+ ],+ },++ 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. Each changed line carries a visually hidden "Added"/"Removed" label, so the change reads without colour. 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.',+ bestPractices: [+ {+ guidance: true,+ description:+ 'Render one DiffViewer per file and lay out the list yourself; parseUnifiedDiff(patch).map(file => <DiffViewer key={file.newPath ?? file.oldPath} file={file} />) is the multi-file case.',+ },+ {+ guidance: true,+ description:+ 'Anchor review comments with the DiffViewerLineRef side + lineNumber pair: it is the same in unified and split view.',+ },+ {+ guidance: true,+ description:+ 'Put file-level actions such as a "Viewed" checkbox in headerEnd, and drive isCollapsed from the same state if viewed files should fold away.',+ },+ {+ guidance: false,+ description:+ 'Use DiffViewer for a short diff inside prose or a chat message; a CodeBlock with isDiff (or a ```diff fence in Markdown) is the lighter fit there.',+ },+ ],+ },++ examples: [+ {+ label: 'Unified diff from a patch',+ code: `const [file] = parseUnifiedDiff(patch);++<DiffViewer file={file} />`,+ },+ {+ label: 'Split view',+ code: '<DiffViewer file={file} viewMode="split" />',+ },+ {+ label: 'Review comments',+ code: `<DiffViewer+ file={file}+ onLineNumberClick={(ref) => startComment(ref.side, ref.lineNumber)}+ renderLineAnnotation={(ref) => {+ const thread = threads.get(\`\${ref.side}:\${ref.lineNumber}\`);+ return thread ? <CommentThread thread={thread} /> : null;+ }}+/>`,+ },+ ],++ props: [+ {+ name: 'file',+ type: 'DiffViewerFile',+ description:+ 'The file to render: paths, status, binary flag, and hunks of numbered lines. Build it with parseUnifiedDiff.',+ required: true,+ },+ {+ name: 'viewMode',+ type: "'unified' | 'split'",+ description:+ "'unified' shows one column with removed lines above their replacements; 'split' shows the old file on the left and the new file on the right, pairing each removed line with the added line that replaced it.",+ default: "'unified'",+ },+ {+ name: 'language',+ type: 'string',+ description:+ 'Syntax-highlighting language. Defaults to one inferred from the file extension; unknown extensions render as plain text.',+ },+ {+ name: 'hasLineNumbers',+ type: 'boolean',+ description: 'Show the old and new line-number gutters.',+ default: 'true',+ },+ {+ name: 'isWrapped',+ type: 'boolean',+ description: 'Wrap long lines instead of scrolling them horizontally.',+ default: 'false',+ },+ {+ name: 'isCollapsible',+ type: 'boolean',+ description:+ 'Make the file header a disclosure that hides and shows the hunks. Applies when the file has a path to name the control.',+ default: 'true',+ },+ {+ name: 'isCollapsed',+ type: 'boolean',+ description: 'Controlled collapsed state. Pair with onCollapsedChange.',+ },+ {+ name: 'defaultIsCollapsed',+ type: 'boolean',+ description: 'Initial collapsed state when uncontrolled.',+ default: 'false',+ },+ {+ name: 'onCollapsedChange',+ type: '(isCollapsed: boolean) => void',+ description:+ 'Called with the next collapsed state when the header is toggled.',+ },+ {+ name: 'headerEnd',+ type: 'ReactNode',+ description:+ 'Content at the end of the file header, such as a "Viewed" checkbox or a file actions menu.',+ },+ {+ name: 'renderLineAnnotation',+ type: '(ref: DiffViewerLineRef) => ReactNode',+ description:+ "Render content in a full-width row under a line, such as review comments; return null for lines with nothing to show. In split view the row sits under the line's own side.",+ },+ {+ name: 'onLineNumberClick',+ type: '(ref: DiffViewerLineRef, event: MouseEvent<HTMLButtonElement>) => void',+ description:+ "Makes each line's number a button, for example to start a comment on that line. The button is the number the line is anchored to: the original number of a removed line, and the changed-file number of an added or unchanged line (an unchanged line's original number stays plain text). Each line number is its own Tab stop.",+ },+ {+ name: 'maxHeight',+ type: 'number | string',+ description: 'Maximum height of the hunk area before it scrolls.',+ },+ {+ name: 'syntaxTheme',+ type: 'SyntaxThemeDefinition',+ description:+ 'Per-instance syntax theme, as on CodeBlock. Without it the nearest SyntaxTheme or the theme syntax colors apply.',+ },+ {+ name: 'ref',+ type: 'Ref<HTMLDivElement>',+ description: 'Ref forwarded to the root element.',+ },+ {+ name: 'xstyle',+ type: 'StyleXStyles',+ description: 'StyleX styles for layout customization.',+ },+ ],+};diff --git a/packages/lab/src/DiffViewer/DiffViewer.test.tsx b/packages/lab/src/DiffViewer/DiffViewer.test.tsxnew file mode 100644index 0000000000..ee2d8c5474--- /dev/null+++ b/packages/lab/src/DiffViewer/DiffViewer.test.tsx@@ -0,0 +1,326 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {describe, it, expect, vi} from 'vitest';+import {render, screen, within} from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import {createRef} from 'react';+import {DiffViewer} from './DiffViewer';+import {parseUnifiedDiff} from './parseUnifiedDiff';+import type {DiffViewerLineRef} from './diffTypes';++const PATCH = `diff --git a/src/greet.ts b/src/greet.ts+--- a/src/greet.ts++++ b/src/greet.ts+@@ -1,4 +1,5 @@+ export function greet(name: string) {+- return 'Hello ' + name;++ const greeting = 'Hello';++ return \`\${greeting}, \${name}\`;+ }++`;++const [FILE] = parseUnifiedDiff(PATCH);++function codeRows(container: HTMLElement) {+ return Array.from(container.querySelectorAll('tbody tr'));+}++describe('DiffViewer', () => {+ it('renders the path, the change counts, and every line', () => {+ render(<DiffViewer file={FILE} />);+ expect(screen.getByText('src/greet.ts')).toBeInTheDocument();+ expect(screen.getByText('+2')).toBeInTheDocument();+ expect(screen.getByText('−1')).toBeInTheDocument();+ expect(+ screen.getByText('2 lines added, 1 line removed'),+ ).toBeInTheDocument();+ expect(screen.getByText('@@ -1,4 +1,5 @@')).toBeInTheDocument();+ expect(screen.getByText('const')).toBeInTheDocument();+ });++ it('keeps code text intact through syntax highlighting', () => {+ const {container} = render(<DiffViewer file={FILE} />);+ const removed = container.querySelector('td[data-diff="removed"]');+ expect(removed?.textContent).toBe(" return 'Hello ' + name;");+ // ts inferred from the extension: tokens are painted with span classes.+ expect(container.querySelector('.astryx-token-keyword')).not.toBeNull();+ });++ it('marks changed lines for assistive technology', () => {+ const {container} = render(<DiffViewer file={FILE} />);+ const addedCells = container.querySelectorAll('td[data-diff="added"]');+ expect(addedCells).toHaveLength(2);+ expect(screen.getAllByText('Added')).toHaveLength(2);+ expect(screen.getAllByText('Removed')).toHaveLength(1);+ });++ it('renders one row per line plus the hunk header in unified view', () => {+ const {container} = render(<DiffViewer file={FILE} />);+ // 1 hunk header + 6 lines.+ expect(codeRows(container)).toHaveLength(7);+ });++ it('pairs removed and added lines side by side in split view', () => {+ const {container} = render(<DiffViewer file={FILE} viewMode="split" />);+ // 1 hunk header + context + 2 paired change rows + 2 context.+ const rows = codeRows(container);+ expect(rows).toHaveLength(6);+ const firstChange = rows[2];+ expect(firstChange.querySelector('td[data-diff="removed"]')).not.toBeNull();+ expect(firstChange.querySelector('td[data-diff="added"]')).not.toBeNull();+ // The second added line has no removed counterpart.+ expect(rows[3].querySelector('td[data-diff="removed"]')).toBeNull();+ expect(rows[3].querySelector('td[data-diff="added"]')).not.toBeNull();+ });++ it('hides the line-number gutters when hasLineNumbers is false', () => {+ const {container} = render(+ <DiffViewer file={FILE} hasLineNumbers={false} />,+ );+ const firstLine = codeRows(container)[1];+ expect(firstLine.querySelectorAll('td')).toHaveLength(2);+ });++ it('collapses and expands from the header', async () => {+ const user = userEvent.setup();+ const onCollapsedChange = vi.fn();+ const {container} = render(+ <DiffViewer file={FILE} onCollapsedChange={onCollapsedChange} />,+ );+ const toggle = screen.getByRole('button', {name: 'src/greet.ts'});+ expect(toggle).toHaveAttribute('aria-expanded', 'true');+ const regionId = toggle.getAttribute('aria-controls');+ expect(regionId).toBeTruthy();+ expect(container.querySelector(`[id="${regionId}"]`)).not.toBeNull();++ await user.click(toggle);+ expect(onCollapsedChange).toHaveBeenLastCalledWith(true);+ expect(toggle).toHaveAttribute('aria-expanded', 'false');+ expect(container.querySelector('table')).toBeNull();++ await user.click(toggle);+ expect(onCollapsedChange).toHaveBeenLastCalledWith(false);+ expect(container.querySelector('table')).not.toBeNull();+ });++ it('follows a controlled collapsed state', async () => {+ const user = userEvent.setup();+ const onCollapsedChange = vi.fn();+ const {container} = render(+ <DiffViewer+ file={FILE}+ isCollapsed+ onCollapsedChange={onCollapsedChange}+ />,+ );+ await user.click(screen.getByRole('button', {name: 'src/greet.ts'}));+ expect(onCollapsedChange).toHaveBeenCalledWith(false);+ // Still collapsed: the caller owns the state.+ expect(container.querySelector('table')).toBeNull();+ });++ it('renders the path as plain text when not collapsible', () => {+ render(<DiffViewer file={FILE} isCollapsible={false} />);+ expect(+ screen.queryByRole('button', {name: 'src/greet.ts'}),+ ).not.toBeInTheDocument();+ expect(screen.getByText('src/greet.ts')).toBeInTheDocument();+ });++ it('renders annotation rows under the lines they belong to', () => {+ const seen: DiffViewerLineRef[] = [];+ const {container} = render(+ <DiffViewer+ file={FILE}+ renderLineAnnotation={ref => {+ seen.push(ref);+ return ref.side === 'new' && ref.lineNumber === 2 ? (+ <p>Nice rename</p>+ ) : null;+ }}+ />,+ );+ expect(screen.getByText('Nice rename')).toBeInTheDocument();+ // Called for every line, with the canonical side (deduped: a render may+ // repeat).+ expect([+ ...new Set(seen.map(ref => `${ref.side}${ref.lineNumber}`)),+ ]).toEqual(['new1', 'old2', 'new2', 'new3', 'new4', 'new5']);+ const rows = codeRows(container);+ const noteRow = rows.findIndex(row => row.textContent === 'Nice rename');+ expect(+ rows[noteRow - 1].querySelector('td[data-diff="added"]')?.textContent,+ ).toBe(" const greeting = 'Hello';");+ });++ it('draws no annotation row when the callback returns false', () => {+ for (const viewMode of ['unified', 'split'] as const) {+ const {container, unmount} = render(+ <DiffViewer+ file={FILE}+ viewMode={viewMode}+ renderLineAnnotation={ref =>+ ref.side === 'new' && ref.lineNumber === 2 && <p>Only note</p>+ }+ />,+ );+ expect(screen.getByText('Only note')).toBeInTheDocument();+ // One annotation row on top of the line rows of each view.+ expect(container.querySelectorAll('tbody tr')).toHaveLength(+ viewMode === 'unified' ? 8 : 7,+ );+ unmount();+ }+ });++ it('places split-view annotations on their own side', () => {+ const {container} = render(+ <DiffViewer+ file={FILE}+ viewMode="split"+ renderLineAnnotation={ref =>+ ref.side === 'old' && ref.lineNumber === 2 ? <p>Old note</p> : null+ }+ />,+ );+ const note = screen.getByText('Old note');+ const row = note.closest('tr');+ expect(row?.children).toHaveLength(2);+ expect(row?.children[0]).toContainElement(note);+ expect(container.querySelectorAll('tbody tr')).toHaveLength(7);+ });++ it('makes line numbers buttons that report their line', async () => {+ const user = userEvent.setup();+ const onLineNumberClick = vi.fn();+ render(<DiffViewer file={FILE} onLineNumberClick={onLineNumberClick} />);+ await user.click(screen.getByRole('button', {name: 'Changed line 3'}));+ expect(onLineNumberClick).toHaveBeenCalledTimes(1);+ const [ref] = onLineNumberClick.mock.calls[0] as [DiffViewerLineRef];+ expect(ref).toMatchObject({side: 'new', lineNumber: 3, hunkIndex: 0});+ expect(ref.line.kind).toBe('added');++ await user.click(screen.getByRole('button', {name: 'Original line 2'}));+ expect(onLineNumberClick.mock.calls[1][0]).toMatchObject({+ side: 'old',+ lineNumber: 2,+ });+ });++ it('makes only the anchor side of each line a button, labelled with the line it reports', async () => {+ const user = userEvent.setup();+ for (const viewMode of ['unified', 'split'] as const) {+ const onLineNumberClick = vi.fn();+ const {unmount} = render(+ <DiffViewer+ file={FILE}+ viewMode={viewMode}+ onLineNumberClick={onLineNumberClick}+ />,+ );+ const buttons = screen+ .getAllByRole('button')+ .filter(b => b.hasAttribute('data-diff-line-button'));+ // One per line: 4 context (new side), 1 removed (old), 2 added (new).+ expect(buttons).toHaveLength(6);+ for (const button of buttons) {+ await user.click(button);+ const [ref] = onLineNumberClick.mock.lastCall as [DiffViewerLineRef];+ const side = ref.side === 'old' ? 'Original' : 'Changed';+ expect(button).toHaveAccessibleName(`${side} line ${ref.lineNumber}`);+ }+ // A context line's old number is plain text, not a second button.+ expect(+ screen.queryByRole('button', {name: 'Original line 1'}),+ ).not.toBeInTheDocument();+ unmount();+ }+ });++ it('names every column for assistive technology', () => {+ const {unmount} = render(<DiffViewer file={FILE} />);+ expect(+ screen.getAllByRole('columnheader').map(th => th.textContent),+ ).toEqual([+ 'Original line number',+ 'Changed line number',+ 'Change',+ 'Code',+ ]);+ unmount();++ render(<DiffViewer file={FILE} viewMode="split" hasLineNumbers={false} />);+ expect(+ screen.getAllByRole('columnheader').map(th => th.textContent),+ ).toEqual(['Change', 'Original code', 'Change', 'Changed code']);+ });++ it('keeps every line-number button in the Tab order with no arrow-key movement', async () => {+ const user = userEvent.setup();+ render(<DiffViewer file={FILE} onLineNumberClick={() => {}} />);+ const buttons = screen+ .getAllByRole('button')+ .filter(b => b.hasAttribute('data-diff-line-button'));+ expect(buttons.length).toBeGreaterThan(2);+ expect(buttons.every(b => b.tabIndex === 0)).toBe(true);++ buttons[0].focus();+ await user.keyboard('{ArrowDown}');+ expect(document.activeElement).toBe(buttons[0]);+ await user.tab();+ expect(document.activeElement).toBe(buttons[1]);+ });++ it('shows the file status and the rename path', () => {+ const [renamed] = parseUnifiedDiff(+ 'diff --git a/a.ts b/b.ts\nrename from a.ts\nrename to b.ts\n',+ );+ render(<DiffViewer file={renamed} />);+ expect(screen.getByText('Renamed')).toBeInTheDocument();+ expect(screen.getByText('a.ts → b.ts')).toBeInTheDocument();+ expect(screen.getByText('No content changes')).toBeInTheDocument();+ });++ 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',+ );+ render(<DiffViewer file={binary} />);+ expect(screen.getByText('Binary file not shown')).toBeInTheDocument();+ });++ it('renders the headerEnd slot', () => {+ render(+ <DiffViewer+ file={FILE}+ headerEnd={<button type="button">Viewed</button>}+ />,+ );+ const header = screen+ .getByText('src/greet.ts')+ .closest('.astryx-diff-viewer-header');+ expect(header).not.toBeNull();+ expect(+ within(header as HTMLElement).getByRole('button', {name: 'Viewed'}),+ ).toBeInTheDocument();+ });++ it('forwards ref, className, and DOM props to the root', () => {+ const ref = createRef<HTMLDivElement>();+ render(+ <DiffViewer+ ref={ref}+ file={FILE}+ className="custom"+ data-testid="viewer"+ viewMode="split"+ />,+ );+ const root = screen.getByTestId('viewer');+ expect(ref.current).toBe(root);+ expect(root).toHaveClass('custom');+ expect(root).toHaveClass('astryx-diff-viewer');+ expect(root).toHaveAttribute('data-view-mode', 'split');+ });+});diff --git a/packages/lab/src/DiffViewer/DiffViewer.tsx b/packages/lab/src/DiffViewer/DiffViewer.tsxnew file mode 100644index 0000000000..b86ea1b696--- /dev/null+++ b/packages/lab/src/DiffViewer/DiffViewer.tsx@@ -0,0 +1,1146 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @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+ * @output Exports DiffViewer component, DiffViewerProps, DiffViewerViewMode+ * @position Lab implementation; read-only, syntax-highlighted file diff for+ * code review surfaces+ *+ * Renders one DiffViewerFile: a file header (path, status, +/- counts, a+ * caller slot, optional disclosure) over a table of hunks in unified or split+ * view. Rows take their tint, gutter, and header paint from the same+ * syntax-theme slots CodeBlock's diff layer uses, so a syntax theme styles+ * both. Callers can render annotation rows under any line (review comments)+ * and make the line numbers actionable.+ *+ * Known limit: rows are plain DOM — there is NO virtualization. Very large+ * files should be windowed or collapsed by the caller.+ *+ * SYNC: When modified, update these files to stay in sync:+ * - /packages/lab/src/DiffViewer/DiffViewer.doc.mjs (props table, notes)+ * - /packages/lab/src/DiffViewer/DiffViewer.test.tsx (behavior tests)+ * - /packages/lab/src/DiffViewer/index.ts (exports if types change)+ * - /apps/storybook/stories/DiffViewer.stories.tsx (examples and visual coverage)+ */++'use client';++import {+ Fragment,+ useId,+ useInsertionEffect,+ useMemo,+ useState,+ type CSSProperties,+ type MouseEvent,+ type ReactNode,+ type Ref,+} from 'react';+import * as stylex from '@stylexjs/stylex';++import type {BaseProps} from '@astryxdesign/core';+import {+ ensureHighlightStyles,+ tokenize,+ type SyntaxToken,+ type TokenLine,+} from '@astryxdesign/core/CodeBlock';+import {useScrollableArea} from '@astryxdesign/core/hooks';+import {useTranslator} from '@astryxdesign/core/i18n';+import {Icon} from '@astryxdesign/core/Icon';+import {+ SyntaxTheme,+ type SyntaxThemeDefinition,+} from '@astryxdesign/core/theme/syntax';+import {+ borderVars,+ colorVars,+ durationVars,+ easeVars,+ fontWeightVars,+ radiusVars,+ spacingVars,+ typeScaleVars,+ typographyVars,+} from '@astryxdesign/core/theme/tokens.stylex';+import {+ focusOutlineProps,+ mergeProps,+ rtlStyles,+ themeProps,+} from '@astryxdesign/core/utils';+import {Token, type TokenColor} from '@astryxdesign/core/Token';+import {VisuallyHidden} from '@astryxdesign/core/VisuallyHidden';++import type {+ DiffViewerFile,+ DiffViewerFileStatus,+ DiffViewerLine,+ DiffViewerLineRef,+ DiffViewerSide,+} from './diffTypes';++/** How hunks are laid out: one column, or old and new side by side. */+export type DiffViewerViewMode = 'unified' | 'split';++export interface DiffViewerProps extends BaseProps<HTMLDivElement> {+ /** Ref forwarded to the root element. */+ ref?: Ref<HTMLDivElement>;+ /**+ * The file to render. Build one with `parseUnifiedDiff(patch)` (one per+ * file in the patch).+ */+ file: DiffViewerFile;+ /**+ * `unified` shows one column with removed lines above their replacements;+ * `split` shows the old file on the left and the new file on the right,+ * pairing each removed line with the added line that replaced it. The hunk+ * area reads left-to-right in every page direction, like a code editor;+ * the file header and annotation content follow the page, and annotation+ * rows scroll with the code.+ * @default 'unified'+ */+ viewMode?: DiffViewerViewMode;+ /**+ * Syntax-highlighting language. Defaults to one inferred from the file's+ * extension; unknown extensions render as plain text.+ */+ language?: string;+ /**+ * Show the old and new line-number gutters.+ * @default true+ */+ hasLineNumbers?: boolean;+ /**+ * Wrap long lines instead of scrolling them horizontally.+ * @default false+ */+ isWrapped?: boolean;+ /**+ * Make the file header a disclosure that hides and shows the hunks. Needs a+ * file path to name the control.+ * @default true+ */+ isCollapsible?: boolean;+ /** Controlled collapsed state. Pair with `onCollapsedChange`. */+ isCollapsed?: boolean;+ /**+ * Initial collapsed state when uncontrolled.+ * @default false+ */+ defaultIsCollapsed?: boolean;+ /** Called with the next collapsed state when the header is toggled. */+ onCollapsedChange?: (isCollapsed: boolean) => void;+ /**+ * Content at the end of the file header, e.g. a "Viewed" checkbox or a menu+ * of file actions.+ */+ headerEnd?: ReactNode;+ /**+ * Render content in a full-width row under a line, e.g. review comments.+ * Return `null` (or `false`) for lines with nothing to show. Called once per line with+ * its {@link DiffViewerLineRef}; in split view the row sits under the+ * line's own side.+ */+ renderLineAnnotation?: (ref: DiffViewerLineRef) => ReactNode;+ /**+ * Makes each line's number a button (e.g. to start a comment on that line).+ * Receives the line's {@link DiffViewerLineRef}. Only the number on the+ * line's anchor side is a button, so an unchanged line's original number+ * stays plain text. Each button is its own Tab stop, like any other set of+ * independent buttons.+ */+ onLineNumberClick?: (+ ref: DiffViewerLineRef,+ event: MouseEvent<HTMLButtonElement>,+ ) => void;+ /** Maximum height of the hunk area before it scrolls. */+ maxHeight?: number | string;+ /**+ * Per-instance syntax theme, as on CodeBlock. Without it the nearest+ * `SyntaxTheme` or the theme's syntax colors apply.+ */+ syntaxTheme?: SyntaxThemeDefinition;+}++// ---------------------------------------------------------------------------+// Language inference+// ---------------------------------------------------------------------------++const EXTENSION_LANGUAGES: Record<string, string> = {+ ts: 'ts',+ mts: 'ts',+ cts: 'ts',+ tsx: 'tsx',+ js: 'js',+ mjs: 'js',+ cjs: 'js',+ jsx: 'jsx',+ json: 'json',+ html: 'html',+ htm: 'html',+ xml: 'xml',+ svg: 'svg',+ css: 'css',+ scss: 'scss',+ less: 'less',+ py: 'python',+ sh: 'bash',+ bash: 'bash',+ zsh: 'zsh',+ php: 'php',+ hack: 'hack',+ yaml: 'yaml',+ yml: 'yaml',+ md: 'markdown',+ markdown: 'markdown',+};++function inferLanguage(path: string | null): string {+ if (path == null) {+ return 'plaintext';+ }+ const base = path.slice(path.lastIndexOf('/') + 1);+ const dot = base.lastIndexOf('.');+ if (dot <= 0) {+ return 'plaintext';+ }+ return EXTENSION_LANGUAGES[base.slice(dot + 1).toLowerCase()] ?? 'plaintext';+}++// ---------------------------------------------------------------------------+// Row model+// ---------------------------------------------------------------------------++interface LineCell {+ line: DiffViewerLine;+ ref: DiffViewerLineRef;+ tokens: TokenLine;+}++type UnifiedRow =+ | {type: 'hunk'; key: string; header: string}+ | {type: 'line'; key: string; cell: LineCell};++type SplitRow =+ | {type: 'hunk'; key: string; header: string}+ | {type: 'pair'; key: string; old: LineCell | null; new: LineCell | null};++function lineRef(+ line: DiffViewerLine,+ hunkIndex: number,+): DiffViewerLineRef | null {+ if (line.kind === 'removed') {+ return line.oldLineNumber == null+ ? null+ : {side: 'old', lineNumber: line.oldLineNumber, line, hunkIndex};+ }+ return line.newLineNumber == null+ ? null+ : {side: 'new', lineNumber: line.newLineNumber, line, hunkIndex};+}++/**+ * 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.+ */+function buildCells(file: DiffViewerFile, language: string): LineCell[][] {+ 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});+ }+ }+ return cells;+ });+}++function buildUnifiedRows(+ file: DiffViewerFile,+ cells: LineCell[][],+): UnifiedRow[] {+ const rows: UnifiedRow[] = [];+ file.hunks.forEach((hunk, h) => {+ rows.push({type: 'hunk', key: `h${h}`, header: hunk.header});+ cells[h].forEach((cell, i) => {+ rows.push({type: 'line', key: `h${h}l${i}`, cell});+ });+ });+ return rows;+}++/**+ * 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[] {+ const rows: SplitRow[] = [];+ file.hunks.forEach((hunk, h) => {+ rows.push({type: 'hunk', key: `h${h}`, header: hunk.header});+ const hunkCells = cells[h];+ let i = 0;+ while (i < hunkCells.length) {+ const cell = hunkCells[i];+ if (cell.line.kind === 'context') {+ rows.push({type: 'pair', key: `h${h}l${i}`, old: cell, new: cell});+ i++;+ continue;+ }+ const removed: LineCell[] = [];+ const added: LineCell[] = [];+ while (i < hunkCells.length && hunkCells[i].line.kind === 'removed') {+ removed.push(hunkCells[i++]);+ }+ while (i < hunkCells.length && hunkCells[i].line.kind === 'added') {+ added.push(hunkCells[i++]);+ }+ const count = Math.max(removed.length, added.length);+ for (let r = 0; r < count; r++) {+ rows.push({+ type: 'pair',+ key: `h${h}l${i}r${r}`,+ old: removed[r] ?? null,+ new: added[r] ?? null,+ });+ }+ }+ });+ return rows;+}++function buildSpans(text: string, tokens: SyntaxToken[]): ReactNode {+ if (text === '') {+ return '\u200b';+ }+ if (tokens.length === 0) {+ return text;+ }+ const parts: ReactNode[] = [];+ let cursor = 0;+ for (const token of tokens) {+ if (token.start > cursor) {+ parts.push(text.slice(cursor, token.start));+ }+ const end = Math.min(token.end, text.length);+ if (end > token.start) {+ parts.push(+ <span+ key={`${token.start}-${token.type}`}+ className={`astryx-token-${token.type}`}>+ {text.slice(token.start, end)}+ </span>,+ );+ }+ cursor = Math.max(cursor, end);+ }+ if (cursor < text.length) {+ parts.push(text.slice(cursor));+ }+ return parts;+}++// ---------------------------------------------------------------------------+// Styles+// ---------------------------------------------------------------------------++const styles = stylex.create({+ root: {+ display: 'flex',+ flexDirection: 'column',+ minWidth: 0,+ overflow: 'hidden',+ borderRadius: radiusVars['--radius-element'],+ borderWidth: borderVars['--border-width'],+ borderStyle: 'solid',+ borderColor: colorVars['--color-border'],+ backgroundColor: 'var(--color-syntax-background)',+ },+ header: {+ display: 'flex',+ alignItems: 'center',+ gap: spacingVars['--spacing-2'],+ minWidth: 0,+ paddingBlock: spacingVars['--spacing-2'],+ paddingInline: spacingVars['--spacing-3'],+ backgroundColor: colorVars['--color-background-surface'],+ color: colorVars['--color-text-primary'],+ fontSize: typeScaleVars['--text-supporting-size'],+ lineHeight: typeScaleVars['--text-supporting-leading'],+ },+ headerDivider: {+ borderBottomWidth: borderVars['--border-width'],+ borderBottomStyle: 'solid',+ borderBottomColor: colorVars['--color-border'],+ },+ toggle: {+ display: 'flex',+ alignItems: 'center',+ gap: spacingVars['--spacing-1'],+ minWidth: 0,+ padding: 0,+ borderWidth: 0,+ borderStyle: 'none',+ borderRadius: radiusVars['--radius-element'],+ backgroundColor: 'transparent',+ color: 'inherit',+ font: 'inherit',+ textAlign: 'start',+ cursor: {+ default: 'pointer',+ ':is(:disabled,[aria-disabled="true"])': 'default',+ },+ },+ chevron: {+ display: 'inline-flex',+ flexShrink: 0,+ color: colorVars['--color-icon-secondary'],+ transitionProperty: 'transform',+ transitionDuration: {+ default: durationVars['--duration-fast'],+ '@media (prefers-reduced-motion: reduce)': '0s',+ },+ transitionTimingFunction: easeVars['--ease-standard'],+ },+ chevronExpanded: {+ transform: 'rotate(90deg)',+ },+ path: {+ minWidth: 0,+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ fontFamily: typographyVars['--font-family-code'],+ fontWeight: fontWeightVars['--font-weight-medium'],+ },+ stats: {+ display: 'inline-flex',+ gap: spacingVars['--spacing-1'],+ flexShrink: 0,+ fontFamily: typographyVars['--font-family-code'],+ },+ statAdded: {+ color: colorVars['--color-text-green'],+ },+ statRemoved: {+ color: colorVars['--color-text-red'],+ },+ headerEnd: {+ display: 'flex',+ alignItems: 'center',+ gap: spacingVars['--spacing-2'],+ marginInlineStart: 'auto',+ flexShrink: 0,+ },+ // The hunk area reads left-to-right in every page direction, as code+ // editors do: line numbers stay on the left and a line wider than the+ // viewer opens at its start. Under RTL a mirrored table would open scrolled+ // to the lines' ends, cutting off every line's start.+ viewport: {+ minWidth: 0,+ direction: 'ltr',+ },+ message: {+ paddingBlock: spacingVars['--spacing-3'],+ paddingInline: spacingVars['--spacing-4'],+ color: colorVars['--color-text-secondary'],+ fontSize: typeScaleVars['--text-supporting-size'],+ },+ table: {+ borderCollapse: 'collapse',+ borderSpacing: 0,+ fontFamily: typographyVars['--font-family-code'],+ fontSize: typeScaleVars['--text-code-size'],+ lineHeight: typeScaleVars['--text-code-leading'],+ color: 'var(--color-syntax-variable)',+ tabSize: 2,+ },+ tableScroll: {+ width: 'max-content',+ minWidth: '100%',+ },+ tableWrapped: {+ width: '100%',+ tableLayout: 'fixed',+ },+ gutter: {+ paddingBlock: 0,+ paddingInline: spacingVars['--spacing-2'],+ textAlign: 'end',+ verticalAlign: 'top',+ whiteSpace: 'nowrap',+ userSelect: 'none',+ color: 'var(--color-syntax-punctuation)',+ },+ gutterAdded: {+ color: 'var(--color-syntax-added-marker)',+ },+ gutterRemoved: {+ color: 'var(--color-syntax-removed-marker)',+ },+ gutterButton: {+ display: 'inline',+ padding: 0,+ margin: 0,+ borderWidth: 0,+ borderStyle: 'none',+ borderRadius: radiusVars['--radius-element'],+ backgroundColor: 'transparent',+ color: 'inherit',+ font: 'inherit',+ cursor: {+ default: 'pointer',+ ':is(:disabled,[aria-disabled="true"])': 'default',+ },+ textDecorationLine: {+ default: 'none',+ ':hover:where(:not(:disabled,[aria-disabled="true"]))': 'underline',+ },+ },+ marker: {+ paddingBlock: 0,+ paddingInlineStart: spacingVars['--spacing-1'],+ paddingInlineEnd: spacingVars['--spacing-2'],+ verticalAlign: 'top',+ whiteSpace: 'pre',+ userSelect: 'none',+ color: colorVars['--color-text-secondary'],+ },+ markerAdded: {+ color: 'var(--color-syntax-added-marker)',+ },+ markerRemoved: {+ color: 'var(--color-syntax-removed-marker)',+ },+ // Code, hunk headers, paths, and counts read left-to-right in every page+ // direction.+ ltr: {+ direction: 'ltr',+ unicodeBidi: 'isolate',+ },+ code: {+ textAlign: 'start',+ paddingBlock: 0,+ paddingInlineStart: 0,+ paddingInlineEnd: spacingVars['--spacing-4'],+ verticalAlign: 'top',+ whiteSpace: 'pre',+ },+ // Break at spaces first, and inside a token only when a word cannot fit.+ codeWrapped: {+ whiteSpace: 'pre-wrap',+ wordBreak: 'normal',+ overflowWrap: 'anywhere',+ },+ // Split view: the old side's code cell carries the divider between sides.+ codeOldSide: {+ borderInlineEndWidth: borderVars['--border-width'],+ borderInlineEndStyle: 'solid',+ borderInlineEndColor: colorVars['--color-border'],+ },+ added: {+ backgroundColor: 'var(--color-syntax-added)',+ },+ removed: {+ backgroundColor: 'var(--color-syntax-removed)',+ },+ // The empty half of a split row whose other side has no counterpart.+ filler: {+ backgroundColor: 'var(--color-syntax-diff-header)',+ },+ hunk: {+ paddingBlock: spacingVars['--spacing-1'],+ paddingInline: spacingVars['--spacing-3'],+ backgroundColor: 'var(--color-syntax-diff-header)',+ color: 'var(--color-syntax-punctuation)',+ whiteSpace: 'pre',+ borderBlockWidth: borderVars['--border-width'],+ borderBlockStyle: 'solid',+ borderBlockColor: colorVars['--color-border'],+ },+ // Column headers exist for assistive technology only: their text is+ // visually hidden, so the header row takes no height.+ columnHeader: {+ padding: 0,+ borderWidth: 0,+ },+ markerCol: {+ width: `calc(1ch + ${spacingVars['--spacing-1']} + ${spacingVars['--spacing-2']})`,+ },+ // Annotation cells stay left-to-right like the rest of the hunk area, so+ // they start at its visible left edge and the split divider stays put.+ annotation: {+ paddingBlock: spacingVars['--spacing-2'],+ paddingInline: spacingVars['--spacing-3'],+ verticalAlign: 'top',+ whiteSpace: 'normal',+ fontFamily: typographyVars['--font-family-body'],+ fontSize: typeScaleVars['--text-body-size'],+ lineHeight: typeScaleVars['--text-body-leading'],+ color: colorVars['--color-text-primary'],+ backgroundColor: colorVars['--color-background-surface'],+ borderBlockWidth: borderVars['--border-width'],+ borderBlockStyle: 'solid',+ borderBlockColor: colorVars['--color-border'],+ },+});++// The caller's content (review comments) reads in the page's direction. Its+// row stays in the left-to-right hunk area and scrolls with the code, as in a+// code editor. Inline-size containment keeps the content out of the table's+// max-content width, so a long comment wraps within the width the code sets+// instead of widening the table; long unbroken words wrap too.+const annotationStyles = stylex.create({+ content: {+ direction: {default: null, ':is([dir="rtl"] *)': 'rtl'},+ overflowWrap: 'anywhere',+ contain: 'inline-size',+ },+});++const dynamicStyles = stylex.create({+ gutterWidth: (digits: number) => ({+ width: `calc(${digits}ch + 2 * ${spacingVars['--spacing-2']})`,+ }),+});++// ---------------------------------------------------------------------------+// Component+// ---------------------------------------------------------------------------++// File status is a category of change, not an alert, so it is a coloured+// Token rather than a status Badge.+const STATUS_COLORS: Partial<Record<DiffViewerFileStatus, TokenColor>> = {+ added: 'green',+ deleted: 'red',+ renamed: 'blue',+};++/**+ * Read-only, syntax-highlighted diff of one file, in unified or split view,+ * for code review surfaces. Supports review-comment annotation rows under any+ * line and actionable line numbers.+ *+ * @example+ * ```+ * const [file] = parseUnifiedDiff(patch);+ * <DiffViewer file={file} viewMode="split" />+ * ```+ */+export function DiffViewer({+ ref,+ file,+ viewMode = 'unified',+ language: languageProp,+ hasLineNumbers = true,+ isWrapped = false,+ isCollapsible = true,+ isCollapsed: isCollapsedProp,+ defaultIsCollapsed = false,+ onCollapsedChange,+ headerEnd,+ renderLineAnnotation,+ onLineNumberClick,+ maxHeight,+ syntaxTheme,+ xstyle,+ className,+ style,+ ...props+}: DiffViewerProps) {+ const t = useTranslator();+ const bodyId = useId();++ useInsertionEffect(() => {+ ensureHighlightStyles();+ }, []);++ const path = file.newPath ?? file.oldPath;+ const language = languageProp ?? inferLanguage(path);+ const displayPath =+ file.status === 'renamed' && file.oldPath != null && file.newPath != null+ ? t('@astryx.diffViewer.renamedPath', {+ oldPath: file.oldPath,+ newPath: file.newPath,+ })+ : path;++ const [uncontrolledCollapsed, setUncontrolledCollapsed] =+ useState(defaultIsCollapsed);+ const canCollapse = isCollapsible && displayPath != null;+ const isCollapsed = canCollapse && (isCollapsedProp ?? uncontrolledCollapsed);+ const toggleCollapsed = () => {+ const next = !isCollapsed;+ if (isCollapsedProp === undefined) {+ setUncontrolledCollapsed(next);+ }+ onCollapsedChange?.(next);+ };++ const cells = useMemo(() => buildCells(file, language), [file, language]);+ const unifiedRows = useMemo(+ () => (viewMode === 'unified' ? buildUnifiedRows(file, cells) : []),+ [viewMode, file, cells],+ );+ const splitRows = useMemo(+ () => (viewMode === 'split' ? buildSplitRows(file, cells) : []),+ [viewMode, file, cells],+ );++ let addedCount = 0;+ let removedCount = 0;+ let maxLineNumber = 1;+ for (const hunk of file.hunks) {+ for (const line of hunk.lines) {+ if (line.kind === 'added') {+ addedCount++;+ } else if (line.kind === 'removed') {+ removedCount++;+ }+ maxLineNumber = Math.max(+ maxLineNumber,+ line.oldLineNumber ?? 0,+ line.newLineNumber ?? 0,+ );+ }+ }+ const digits = String(maxLineNumber).length;++ const {getViewportProps, getContentProps} = useScrollableArea({+ axis: 'both',+ keyboardAccess: {+ owner: 'viewport',+ role: 'group',+ label: displayPath ?? t('@astryx.diffViewer.label'),+ },+ });+ const scrollStyle: CSSProperties | undefined =+ maxHeight != null+ ? {+ maxHeight:+ typeof maxHeight === 'number' ? `${maxHeight}px` : maxHeight,+ }+ : undefined;++ // --- cells ---------------------------------------------------------------++ const renderGutter = (+ cell: LineCell | null,+ side: DiffViewerSide,+ key: string,+ ) => {+ if (!hasLineNumbers) {+ return null;+ }+ const number =+ cell == null+ ? null+ : side === 'old'+ ? cell.line.oldLineNumber+ : cell.line.newLineNumber;+ const kind = cell?.line.kind;+ // Only the gutter of the line's own anchor side is a button: a context+ // line anchors to its new number, so its old number stays plain text+ // rather than a second button whose label names a line it does not report.+ const actionRef =+ number != null && cell != null && cell.ref.side === side+ ? cell.ref+ : null;+ return (+ <td+ key={key}+ {...stylex.props(+ styles.gutter,+ kind === 'added' && [styles.added, styles.gutterAdded],+ kind === 'removed' && [styles.removed, styles.gutterRemoved],+ cell == null && styles.filler,+ )}>+ {actionRef != null && onLineNumberClick != null ? (+ <button+ type="button"+ data-diff-line-button=""+ aria-label={t('@astryx.diffViewer.lineNumberButton', {+ side,+ line: number,+ })}+ onClick={event => onLineNumberClick(actionRef, event)}+ {...focusOutlineProps.focusVisible(styles.gutterButton)}>+ {number}+ </button>+ ) : (+ number+ )}+ </td>+ );+ };++ const renderMarker = (cell: LineCell | null, key: string) => {+ const kind = cell?.line.kind;+ return (+ <td+ key={key}+ {...stylex.props(+ styles.marker,+ kind === 'added' && [styles.added, styles.markerAdded],+ kind === 'removed' && [styles.removed, styles.markerRemoved],+ cell == null && styles.filler,+ )}>+ {kind === 'added' && (+ <>+ <span aria-hidden="true">+</span>+ <VisuallyHidden>{t('@astryx.diffViewer.added')}</VisuallyHidden>+ </>+ )}+ {kind === 'removed' && (+ <>+ <span aria-hidden="true">-</span>+ <VisuallyHidden>{t('@astryx.diffViewer.removed')}</VisuallyHidden>+ </>+ )}+ </td>+ );+ };++ const renderCode = (cell: LineCell | null, key: string, isOld = false) => {+ const kind = cell?.line.kind;+ return (+ <td+ key={key}+ data-diff={kind != null && kind !== 'context' ? kind : undefined}+ {...stylex.props(+ styles.code,+ styles.ltr,+ isWrapped && styles.codeWrapped,+ isOld && styles.codeOldSide,+ kind === 'added' && styles.added,+ kind === 'removed' && styles.removed,+ cell == null && styles.filler,+ )}>+ {cell != null && buildSpans(cell.line.content, cell.tokens)}+ </td>+ );+ };++ // `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;+ };++ // --- tables --------------------------------------------------------------++ const gutterCols = hasLineNumbers ? 2 : 0;+ const unifiedColumns = gutterCols + 2;+ const sideColumns = (hasLineNumbers ? 1 : 0) + 2;++ const gutterCol = (key: string) => (+ <col key={key} {...stylex.props(dynamicStyles.gutterWidth(digits))} />+ );+ const markerCol = (key: string) => (+ <col key={key} {...stylex.props(styles.markerCol)} />+ );+ // Name every column so a screen reader moving across a row hears which+ // number is which and which side of a split row it is on.+ const columnHeader = (key: string, label: string) => (+ <th key={key} scope="col" {...stylex.props(styles.columnHeader)}>+ <VisuallyHidden>{label}</VisuallyHidden>+ </th>+ );++ let table: ReactNode;+ if (viewMode === 'split') {+ table = (+ <table+ {...stylex.props(+ styles.table,+ isWrapped ? styles.tableWrapped : styles.tableScroll,+ )}>+ <colgroup>+ {hasLineNumbers && gutterCol('og')}+ {markerCol('om')}+ <col />+ {hasLineNumbers && gutterCol('ng')}+ {markerCol('nm')}+ <col />+ </colgroup>+ <thead>+ <tr>+ {hasLineNumbers &&+ columnHeader('og', t('@astryx.diffViewer.columnOldLine'))}+ {columnHeader('om', t('@astryx.diffViewer.columnChange'))}+ {columnHeader('oc', t('@astryx.diffViewer.columnOldCode'))}+ {hasLineNumbers &&+ columnHeader('ng', t('@astryx.diffViewer.columnNewLine'))}+ {columnHeader('nm', t('@astryx.diffViewer.columnChange'))}+ {columnHeader('nc', t('@astryx.diffViewer.columnNewCode'))}+ </tr>+ </thead>+ <tbody>+ {splitRows.map(row => {+ if (row.type === 'hunk') {+ return (+ <tr key={row.key}>+ <td colSpan={sideColumns * 2} {...stylex.props(styles.hunk)}>+ <span {...stylex.props(styles.ltr)}>{row.header}</span>+ </td>+ </tr>+ );+ }+ const isContext = row.old?.line.kind === 'context';+ const oldNote = isContext ? null : annotationFor(row.old);+ const newNote = annotationFor(row.new);+ const hasNote = oldNote != null || newNote != null;+ return (+ <Fragment key={row.key}>+ <tr>+ {renderGutter(row.old, 'old', 'og')}+ {renderMarker(row.old, 'om')}+ {renderCode(row.old, 'oc', true)}+ {renderGutter(row.new, 'new', 'ng')}+ {renderMarker(row.new, 'nm')}+ {renderCode(row.new, 'nc')}+ </tr>+ {hasNote && (+ <tr>+ <td+ colSpan={sideColumns}+ {...stylex.props(styles.annotation, styles.codeOldSide)}>+ {oldNote != null && (+ <div {...stylex.props(annotationStyles.content)}>+ {oldNote}+ </div>+ )}+ </td>+ <td+ colSpan={sideColumns}+ {...stylex.props(styles.annotation)}>+ {newNote != null && (+ <div {...stylex.props(annotationStyles.content)}>+ {newNote}+ </div>+ )}+ </td>+ </tr>+ )}+ </Fragment>+ );+ })}+ </tbody>+ </table>+ );+ } else {+ table = (+ <table+ {...stylex.props(+ styles.table,+ isWrapped ? styles.tableWrapped : styles.tableScroll,+ )}>+ <colgroup>+ {hasLineNumbers && gutterCol('og')}+ {hasLineNumbers && gutterCol('ng')}+ {markerCol('m')}+ <col />+ </colgroup>+ <thead>+ <tr>+ {hasLineNumbers &&+ columnHeader('og', t('@astryx.diffViewer.columnOldLine'))}+ {hasLineNumbers &&+ columnHeader('ng', t('@astryx.diffViewer.columnNewLine'))}+ {columnHeader('m', t('@astryx.diffViewer.columnChange'))}+ {columnHeader('c', t('@astryx.diffViewer.columnCode'))}+ </tr>+ </thead>+ <tbody>+ {unifiedRows.map(row => {+ if (row.type === 'hunk') {+ return (+ <tr key={row.key}>+ <td colSpan={unifiedColumns} {...stylex.props(styles.hunk)}>+ <span {...stylex.props(styles.ltr)}>{row.header}</span>+ </td>+ </tr>+ );+ }+ const note = annotationFor(row.cell);+ return (+ <Fragment key={row.key}>+ <tr>+ {renderGutter(row.cell, 'old', 'og')}+ {renderGutter(row.cell, 'new', 'ng')}+ {renderMarker(row.cell, 'm')}+ {renderCode(row.cell, 'c')}+ </tr>+ {note != null && (+ <tr>+ <td+ colSpan={unifiedColumns}+ {...stylex.props(styles.annotation)}>+ <div {...stylex.props(annotationStyles.content)}>+ {note}+ </div>+ </td>+ </tr>+ )}+ </Fragment>+ );+ })}+ </tbody>+ </table>+ );+ }++ let body: ReactNode;+ if (file.isBinary) {+ body = (+ <div {...stylex.props(styles.message)}>+ {t('@astryx.diffViewer.binary')}+ </div>+ );+ } else if (file.hunks.length === 0) {+ body = (+ <div {...stylex.props(styles.message)}>+ {t('@astryx.diffViewer.noChanges')}+ </div>+ );+ } else {+ body = (+ <div+ {...getViewportProps<HTMLDivElement>({+ ...stylex.props(styles.viewport),+ style: scrollStyle,+ })}>+ <div {...getContentProps<HTMLDivElement>({})}>{table}</div>+ </div>+ );+ }++ // --- header --------------------------------------------------------------++ const statusColor = STATUS_COLORS[file.status];+ const statusLabel =+ file.status === 'added'+ ? t('@astryx.diffViewer.statusAdded')+ : file.status === 'deleted'+ ? t('@astryx.diffViewer.statusDeleted')+ : file.status === 'renamed'+ ? t('@astryx.diffViewer.statusRenamed')+ : null;++ const pathEl = (+ <span+ {...mergeProps(+ themeProps('diff-viewer-path'),+ stylex.props(styles.path, styles.ltr),+ )}>+ {displayPath}+ </span>+ );++ const header =+ displayPath != null || headerEnd != null ? (+ <div+ {...mergeProps(+ themeProps('diff-viewer-header'),+ stylex.props(styles.header, !isCollapsed && styles.headerDivider),+ )}>+ {canCollapse ? (+ <button+ type="button"+ aria-expanded={!isCollapsed}+ aria-controls={bodyId}+ onClick={toggleCollapsed}+ {...focusOutlineProps.focusVisible(styles.toggle)}>+ <span+ {...stylex.props(+ styles.chevron,+ !isCollapsed && styles.chevronExpanded,+ )}>+ <span {...stylex.props(isCollapsed && rtlStyles.mirror)}>+ <Icon icon="chevronRight" size="xsm" color="inherit" />+ </span>+ </span>+ {pathEl}+ </button>+ ) : (+ pathEl+ )}+ {statusColor != null && statusLabel != null && (+ <Token size="sm" color={statusColor} label={statusLabel} />+ )}+ {(addedCount > 0 || removedCount > 0) && (+ <span {...stylex.props(styles.stats, styles.ltr)}>+ <span aria-hidden="true" {...stylex.props(styles.statAdded)}>+ {t('@astryx.diffViewer.addedCount', {count: addedCount})}+ </span>+ <span aria-hidden="true" {...stylex.props(styles.statRemoved)}>+ {t('@astryx.diffViewer.removedCount', {count: removedCount})}+ </span>+ <VisuallyHidden>+ {t('@astryx.diffViewer.stats', {+ added: addedCount,+ removed: removedCount,+ })}+ </VisuallyHidden>+ </span>+ )}+ {headerEnd != null && (+ <div {...stylex.props(styles.headerEnd)}>{headerEnd}</div>+ )}+ </div>+ ) : null;++ const root = (+ <div+ ref={ref}+ {...mergeProps(+ themeProps('diff-viewer', {viewMode}),+ stylex.props(styles.root, xstyle),+ className,+ style,+ )}+ {...props}>+ {header}+ <div id={bodyId} hidden={isCollapsed}>+ {isCollapsed ? null : body}+ </div>+ </div>+ );++ return syntaxTheme ? (+ <SyntaxTheme theme={syntaxTheme}>{root}</SyntaxTheme>+ ) : (+ root+ );+}++DiffViewer.displayName = 'DiffViewer';diff --git a/packages/lab/src/DiffViewer/diffTypes.ts b/packages/lab/src/DiffViewer/diffTypes.tsindex 2ce23a7a50..d376a607da 100644--- a/packages/lab/src/DiffViewer/diffTypes.ts+++ b/packages/lab/src/DiffViewer/diffTypes.ts@@ -10,6 +10,7 @@* consumed by DiffViewer** SYNC: When modified, update:+ * - /packages/lab/src/DiffViewer/DiffViewer.doc.mjs (types in the props table)* - /packages/lab/src/DiffViewer/index.ts (type exports)*/diff --git a/packages/lab/src/DiffViewer/index.ts b/packages/lab/src/DiffViewer/index.tsindex 369bcefea0..437aaeb7ac 100644--- a/packages/lab/src/DiffViewer/index.ts+++ b/packages/lab/src/DiffViewer/index.ts@@ -1,13 +1,18 @@// Copyright (c) Meta Platforms, Inc. and affiliates.+'use client';+/*** @file index.ts- * @input Imports from parseUnifiedDiff.ts and diffTypes.ts- * @output Exports the structured diff model and the unified-diff parser- * @position Entry point for the DiffViewer folder; re-exported by- * /packages/lab/src/index.ts+ * @input Imports from DiffViewer.tsx, parseUnifiedDiff.ts, diffTypes.ts+ * @output Exports DiffViewer, its diff model types, and the patch parser+ * @position Component entry point; re-exported by /packages/lab/src/index.ts+ *+ * SYNC: When modified, update /packages/lab/src/DiffViewer/DiffViewer.doc.mjs*/+export {DiffViewer} from './DiffViewer';+export type {DiffViewerProps, DiffViewerViewMode} from './DiffViewer';export {parseUnifiedDiff} from './parseUnifiedDiff';export type {DiffViewerFile,diff --git a/packages/lab/src/DiffViewer/parseUnifiedDiff.ts b/packages/lab/src/DiffViewer/parseUnifiedDiff.tsindex e65eb53c6f..dec8fa9a04 100644--- a/packages/lab/src/DiffViewer/parseUnifiedDiff.ts+++ b/packages/lab/src/DiffViewer/parseUnifiedDiff.ts@@ -13,6 +13,7 @@** SYNC: When modified, update:* - /packages/lab/src/DiffViewer/parseUnifiedDiff.test.ts+ * - /packages/lab/src/DiffViewer/DiffViewer.doc.mjs (utilities section)*/import type {diff --git a/packages/lab/src/index.ts b/packages/lab/src/index.tsindex c10b47561e..9c34bef061 100644--- a/packages/lab/src/index.ts+++ b/packages/lab/src/index.ts@@ -258,9 +258,12 @@ export {type LogStreamLevel,} from './LogStream';-// DiffViewer — the structured diff model and the unified-diff parser+// DiffViewer — read-only file diff (unified/split) for code review surfacesexport {+ DiffViewer,parseUnifiedDiff,+ type DiffViewerProps,+ type DiffViewerViewMode,type DiffViewerFile,type DiffViewerFileStatus,type DiffViewerHunk,