From bc7d1bc0a4a1e0a0532c98045cb27979aa2fe72d Mon Sep 17 00:00:00 2001 From: Cindy Zhang Date: Thu, 19 Nov 2026 14:18:20 -0800 Subject: [PATCH] ci: Lab swizzle samples live with Lab, and pnpm lab:sync writes a new Lab component's route-lock entries and sample stub --- docs/contributing/pull-requests.md | 10 +- package.json | 1 + packages/cli/test/swizzle-proof/samples.mjs | 492 +------------------ packages/lab/swizzle-samples.mjs | 519 ++++++++++++++++++++ scripts/lab-sync.mjs | 354 +++++++++++++ scripts/lab-sync.test.mjs | 198 ++++++++ scripts/preflight.mjs | 8 + scripts/preflight.test.mjs | 2 + 8 files changed, 1095 insertions(+), 489 deletions(-) create mode 100644 packages/lab/swizzle-samples.mjs create mode 100644 scripts/lab-sync.mjs create mode 100644 scripts/lab-sync.test.mjs diff --git a/docs/contributing/pull-requests.md b/docs/contributing/pull-requests.md index 950922d89e774..1375745b919ab 100644 --- a/docs/contributing/pull-requests.md +++ b/docs/contributing/pull-requests.md @@ -148,7 +148,7 @@ pnpm preflight --quick # minutes: the changed packages, files and change, scoped the way CI scopes them: the typecheck of the changed packages and the packages that depend on them, ESLint on the changed files and Prettier on the changed TypeScript and Markdown files and `pnpm check:repo`, the Vitest tests the change reaches in each project, -`pnpm check:knowledge` and `pnpm check:changesets`. With `--browser` it also +`pnpm check:knowledge`, `pnpm check:changesets` and `pnpm lab:sync --check`. With `--browser` it also builds Storybook and runs the accessibility and Chromium interaction specs the change selects. It prints one PASS, FAIL or SKIP line a check, the command of each failing check, and "ready to flip" or "not ready: N"; it exits 1 when a @@ -161,7 +161,7 @@ jobs. `--quick` runs `pnpm review:pre`, the typecheck of the changed packages alone, ESLint on the changed files, the changed test files alone, `pnpm check:knowledge` -and `pnpm check:changesets`, in minutes. It is not CI-equivalent: it builds +`pnpm check:changesets` and `pnpm lab:sync --check`, in minutes. It is not CI-equivalent: it builds nothing, leaves out dependent packages, the tests the change reaches through an import, and the guards, and it ends with "run `pnpm preflight` before you flip" rather than "ready to flip". @@ -169,6 +169,12 @@ rather than "ready to flip". Preflight is not a required step. It reproduces the pre-review checklist and CI's checks; it does not reproduce a reviewer's judgment. +After you add a Lab component, run `pnpm lab:sync`. It writes the +component's shadcn route-lock entries and, when its doc names a required prop +with no default, a swizzle sample stub in `packages/lab/swizzle-samples.mjs` +(marked "generated by lab:sync; edit freely"). It never changes an existing +sample. `pnpm lab:sync --check` names what is missing and exits 1. + ### Find the governing records by hand | Command | What it answers | diff --git a/package.json b/package.json index eb586cc5fef43..83e3edf697df8 100644 --- a/package.json +++ b/package.json @@ -78,6 +78,7 @@ "rtl:audit": "node apps/storybook/rtl-audit/rtl-audit.mjs", "lab:readiness": "node internal/lab-readiness/audit.mjs", "lab:readiness:check": "node internal/lab-readiness/audit.mjs --check", + "lab:sync": "node scripts/lab-sync.mjs", "guard:modal-close": "node .github/scripts/modal-close-visibility.js", "guard:modal-close:webkit": "node .github/scripts/modal-close-visibility.js --browser webkit", "guard:theme-vars": "node .github/scripts/theme-var-reachability.js", diff --git a/packages/cli/test/swizzle-proof/samples.mjs b/packages/cli/test/swizzle-proof/samples.mjs index 1934bd0829f07..7330b153fbea0 100644 --- a/packages/cli/test/swizzle-proof/samples.mjs +++ b/packages/cli/test/swizzle-proof/samples.mjs @@ -9,6 +9,8 @@ * from the copy's own module when it exports them */ +import {labNeedsNoSample, labSamples} from '../../../lab/swizzle-samples.mjs'; + const noop = () => {}; const ref = () => ({current: null}); @@ -86,109 +88,6 @@ function chartsSample(React, mod, Pkg, slot) { }); } -function labChart(React, mod, Pkg, props, child) { - const h = React.createElement; - const Chart = mod.Chart ?? Pkg.Chart; - return h('div', {style: {width: 480, height: 320}}, h(Chart, props, child)); -} - -const monthly = { - data: [ - {month: 'Jan', v: 1, upper: 30, lower: 10}, - {month: 'Feb', v: 3, upper: 40, lower: 20}, - {month: 'Mar', v: 2, upper: 50, lower: 30}, - ], - xKey: 'month', - yKeys: ['v', 'upper', 'lower'], -}; -const xy = { - data: [ - {x: 0, y: 1}, - {x: 1, y: 2}, - {x: 2, y: 3}, - ], - xKey: 'x', - yKeys: ['y'], -}; -const ohlc = { - data: [ - {day: '1', open: 1, close: 2, high: 3, low: 0.5}, - {day: '2', open: 2, close: 1.5, high: 2.5, low: 1}, - {day: '3', open: 1.5, close: 3, high: 3.5, low: 1.2}, - ], - xKey: 'day', - yKeys: ['high', 'low'], -}; -const xyz = { - data: [ - {x: 0, y: 1, z: 0}, - {x: 2, y: 2, z: 2}, - {x: 1, y: 3, z: 1}, - ], - xKey: 'x', - yKey: 'y', - zKey: 'z', -}; - -function threeD(React, mod, Pkg, child) { - const h = React.createElement; - const ThreeDChart = mod.ThreeDChart ?? Pkg.ThreeDChart; - return h( - 'div', - {style: {width: 600, height: 400}}, - h(ThreeDChart, xyz, child), - ); -} - -function tour(React, Tour, TourStep) { - const h = React.createElement; - function Sample() { - const a = React.useRef(null); - const b = React.useRef(null); - return h( - React.Fragment, - null, - h('button', {type: 'button', ref: a}, 'Target A'), - h('button', {type: 'button', ref: b}, 'Target B'), - h( - Tour, - {isActive: true, onDismiss: noop}, - h(TourStep, {targetRef: a, heading: 'First'}, 'First body'), - h(TourStep, {targetRef: b, heading: 'Second'}, 'Second body'), - ), - ); - } - return h(Sample); -} - -function navigation(React, Stack, Screen) { - const h = React.createElement; - return h(Stack, { - label: 'Settings', - root: h( - Screen, - {title: 'Settings'}, - h('button', {type: 'button'}, 'General'), - ), - path: [], - onPathChange: noop, - getKey: entry => entry, - renderScreen: entry => h(Screen, {title: entry}, entry), - }); -} - -/** A media part inside a player from the same copy, so it reads that player. */ -function mediaPart(React, mod, Pkg, part) { - const h = React.createElement; - const MediaPlayer = mod.MediaPlayer ?? Pkg.MediaPlayer; - const MediaPlayerElement = mod.MediaPlayerElement ?? Pkg.MediaPlayerElement; - return h( - MediaPlayer, - {label: 'Clip'}, - h(MediaPlayerElement, {kind: 'video', src: '/clip.mp4'}), - part, - ); -} export const samples = { core__AlertDialog: ({C, React}) => React.createElement(C, { @@ -257,297 +156,6 @@ export const samples = { chartsSample(React, mod, Pkg, {legend: React.createElement(C)}), charts__ChartTooltip: ({C, React, mod, Pkg}) => chartsSample(React, mod, Pkg, {tooltip: React.createElement(C)}), - lab__ChartArea: ({C, React, mod, Pkg}) => - labChart( - React, - mod, - Pkg, - monthly, - React.createElement(C, { - yUpper: 'upper', - yLower: 'lower', - color: '#0064E0', - }), - ), - lab__ChartBar: ({C, React, mod, Pkg}) => - labChart(React, mod, Pkg, monthly, React.createElement(C, {dataKey: 'v'})), - lab__ChartLine: ({C, React, mod, Pkg}) => - labChart(React, mod, Pkg, monthly, React.createElement(C, {dataKey: 'v'})), - lab__ChartDot: ({C, React, mod, Pkg}) => - labChart(React, mod, Pkg, xy, React.createElement(C, {dataKey: 'y'})), - lab__ChartDotGL: ({C, React, mod, Pkg}) => - labChart( - React, - mod, - Pkg, - xy, - React.createElement(C, {dataKey: 'y', color: '#0064E0'}), - ), - lab__ChartDotGLInteractive: ({C, React, mod, Pkg}) => - labChart( - React, - mod, - Pkg, - xy, - React.createElement(C, {dataKey: 'y', color: '#0064E0'}), - ), - lab__ChartCandlestick: ({C, React, mod, Pkg}) => - labChart( - React, - mod, - Pkg, - ohlc, - React.createElement(C, { - high: 'high', - low: 'low', - open: 'open', - close: 'close', - }), - ), - lab__ChartHeatmapGL: ({C, React, mod, Pkg}) => - labChart( - React, - mod, - Pkg, - { - data: [ - {month: 'Jan', row: 'A', value: 1}, - {month: 'Jan', row: 'B', value: 2}, - {month: 'Feb', row: 'A', value: 3}, - {month: 'Feb', row: 'B', value: 4}, - ], - xKey: 'month', - yKeys: ['value'], - }, - React.createElement(C, { - xKey: 'month', - yKey: 'row', - valueKey: 'value', - colorRange: ['#000000', '#ffffff'], - }), - ), - lab__ChartStreamGL: ({C, React, mod, Pkg}) => - labChart( - React, - mod, - Pkg, - {data: [], xKey: 't', yKeys: ['v'], xDomain: [0, 10], yDomain: [0, 1]}, - React.createElement(C, {color: '#0064E0'}), - ), - lab__WeightedSVGIcon: ({C, React}) => - React.createElement(C, { - icon: { - name: 'swizzle-proof-dot', - layers: [ - { - from: 300, - to: 700, - paths: [{d: 'M12 4a8 8 0 1 0 0 16a8 8 0 1 0 0-16z'}], - }, - ], - }, - 'aria-label': 'Dot', - }), - lab__ChatVirtualizer: ({C, React}) => - // A fixed-height frame, so the browser step windows real rows. - React.createElement( - 'div', - {style: {height: 320, display: 'flex', flexDirection: 'column'}}, - React.createElement(C, { - data: [ - {id: 'a', text: 'First message'}, - {id: 'b', text: 'Second message'}, - {id: 'c', text: 'Third message'}, - ], - getRowKey: item => item.id, - renderItem: ({item}) => React.createElement('p', null, item.text), - }), - ), - lab__ChatReactionBar: ({C, React}) => - React.createElement(C, { - reactions: [ - {emoji: '👍', count: 2, label: 'Thumbs up'}, - {emoji: '🎉', count: 1, isSelected: true, label: 'Party'}, - ], - onReactionClick: noop, - onAddReaction: noop, - }), - lab__Tour: ({C, React, mod, Pkg}) => - tour(React, C, mod.TourStep ?? Pkg.TourStep), - lab__TourStep: ({C, React, mod, Pkg}) => tour(React, mod.Tour ?? Pkg.Tour, C), - lab__CodeEditor: ({C, React}) => - React.createElement(C, { - value: 'const answer = 42;', - onChange: noop, - language: 'typescript', - label: 'Edit snippet', - }), - lab__CommentComposer: ({C, React}) => - React.createElement(C, {value: '', onChange: noop, onSubmit: noop}), - lab__CommentPin: ({C, React}) => - React.createElement(C, { - label: 'Open annotation from Ada', - participants: [{id: 'ada', name: 'Ada Lovelace'}], - onClick: noop, - }), - lab__CommentThread: ({C, React}) => - React.createElement( - 'div', - {style: {width: 320}}, - React.createElement(C, { - comment: { - id: 'margin', - author: {id: 'maya', name: 'Maya Chen'}, - body: 'Should this say three days?', - createdAt: '2026-09-30T19:00:00Z', - }, - currentUser: {id: 'avery', name: 'Avery Kim'}, - onSubmit: noop, - }), - ), - lab__DiffViewer: ({C, React, mod, Pkg}) => { - const parse = mod.parseUnifiedDiff ?? Pkg.parseUnifiedDiff; - const patch = [ - 'diff --git a/a.ts b/a.ts', - '--- a/a.ts', - '+++ b/a.ts', - '@@ -1,2 +1,2 @@', - ' const a = 1;', - '-const b = 2;', - '+const b = 3;', - '', - ].join('\n'); - return React.createElement(C, {file: parse(patch)[0]}); - }, - lab__ListInput: ({C, React, Core}) => - React.createElement(C, { - label: 'Tags', - value: [{id: '1', label: 'Alpha'}], - onChange: noop, - getItemKey: item => item.id, - createItem: () => ({id: String(Date.now()), label: ''}), - columns: [ - { - key: 'label', - header: 'Label', - renderInput: ({item, label, isLabelHidden}) => - React.createElement(Core.TextInput, { - label, - isLabelHidden, - value: item.label, - onChange: noop, - }), - }, - ], - }), - lab__LogStream: ({C, React}) => - React.createElement(C, { - entries: [ - { - id: 'a', - timestamp: '14:02:11.482', - level: 'info', - source: 'api-gateway', - message: 'request accepted', - }, - { - id: 'b', - timestamp: '14:02:12.001', - level: 'warn', - source: 'api-gateway', - message: 'retrying upstream call', - }, - ], - }), - lab__SankeyChart: ({C, React, mod, Pkg}) => - React.createElement( - 'div', - {style: {width: 480, height: 320}}, - React.createElement( - C, - { - nodes: [ - {id: 'a', label: 'A', value: 10}, - {id: 'b', label: 'B', value: 10}, - {id: 'c', label: 'C', value: 10}, - ], - links: [ - {source: 'a', target: 'b', value: 5}, - {source: 'b', target: 'c', value: 5}, - ], - }, - React.createElement(mod.SankeyNode ?? Pkg.SankeyNode), - ), - ), - lab__Schedule: ({C, React, mod, Pkg}) => { - const view = ( - mod.createScheduleMonthlyView ?? Pkg.createScheduleMonthlyView - )(); - return React.createElement(C, { - view, - events: [], - date: Date.UTC(2026, 9, 30), - focusDate: Date.UTC(2026, 9, 30), - timezoneID: 'UTC', - }); - }, - lab__ThreeDBar: ({C, React, mod, Pkg}) => - threeD(React, mod, Pkg, React.createElement(C, {color: '#00aa00'})), - lab__ThreeDScatter: ({C, React, mod, Pkg}) => - threeD(React, mod, Pkg, React.createElement(C, {color: '#00aa00'})), - lab__ThreeDScatterGL: ({C, React, mod, Pkg}) => - threeD(React, mod, Pkg, React.createElement(C, {color: '#00aa00'})), - lab__ThreeDSurface: ({C, React, mod, Pkg}) => - threeD(React, mod, Pkg, React.createElement(C, {color: '#00aa00'})), - lab__ThreeDChart: ({C, React, mod, Pkg}) => - React.createElement( - 'div', - {style: {width: 600, height: 400}}, - React.createElement( - C, - xyz, - React.createElement(mod.ThreeDBar ?? Pkg.ThreeDBar, {color: '#00aa00'}), - ), - ), - lab__TransferList: ({C, React}) => - React.createElement(C, { - label: 'Columns', - options: [ - {value: 'name', label: 'Name'}, - {value: 'status', label: 'Status'}, - {value: 'owner', label: 'Owner'}, - ], - value: ['name'], - onChange: noop, - }), - lab__NavigationStack: ({C, React, mod, Pkg}) => - navigation(React, C, mod.NavigationScreen ?? Pkg.NavigationScreen), - lab__NavigationScreen: ({C, React, mod, Pkg}) => - navigation(React, mod.NavigationStack ?? Pkg.NavigationStack, C), - lab__PageControl: ({C, React}) => - React.createElement(C, { - totalPages: 3, - page: 0, - onChange: noop, - label: 'Pages', - }), - lab__TabBarItem: ({C, React, mod, Pkg}) => { - const TabBar = mod.TabBar ?? Pkg.TabBar; - return React.createElement( - TabBar, - {value: 'home', onChange: noop, label: 'Sections'}, - React.createElement(C, { - value: 'home', - label: 'Home', - icon: dotIcon(React), - }), - React.createElement(C, { - value: 'search', - label: 'Search', - icon: dotIcon(React), - }), - ); - }, core__ComplexSelector: ({C, React}) => React.createElement( C, @@ -559,11 +167,6 @@ export const samples = { 'Pick ' + value, ), ), - lab__SVGIcon: ({C, React, mod, Pkg}) => - React.createElement(C, { - icon: mod.bellIcon ?? Pkg.bellIcon, - 'aria-label': 'Notifications', - }), richtext__RichTextEditorToolbar: ({C, React, mod, Pkg}) => { const Editor = mod.RichTextEditor ?? Pkg.RichTextEditor; return React.createElement(Editor, { @@ -629,38 +232,6 @@ export const samples = { } return React.createElement(Sample); }, - lab__MediaPlayer: ({C, React, mod, Pkg}) => - React.createElement( - C, - {label: 'Clip'}, - React.createElement(mod.MediaPlayerElement ?? Pkg.MediaPlayerElement, { - kind: 'video', - src: '/clip.mp4', - }), - React.createElement(mod.MediaPlayButton ?? Pkg.MediaPlayButton), - ), - lab__MediaPlayerElement: ({C, React, mod, Pkg}) => - React.createElement( - mod.MediaPlayer ?? Pkg.MediaPlayer, - {label: 'Clip'}, - React.createElement(C, {kind: 'video', src: '/clip.mp4'}), - ), - lab__MediaPlayButton: ({C, React, mod, Pkg}) => - mediaPart(React, mod, Pkg, React.createElement(C)), - lab__MediaSeekButton: ({C, React, mod, Pkg}) => - mediaPart(React, mod, Pkg, React.createElement(C, {offset: 10})), - lab__MediaVolume: ({C, React, mod, Pkg}) => - mediaPart(React, mod, Pkg, React.createElement(C)), - lab__MediaTimeSlider: ({C, React, mod, Pkg}) => - mediaPart(React, mod, Pkg, React.createElement(C)), - lab__MediaTime: ({C, React, mod, Pkg}) => - mediaPart(React, mod, Pkg, React.createElement(C)), - lab__MediaCaptionsButton: ({C, React, mod, Pkg}) => - mediaPart(React, mod, Pkg, React.createElement(C)), - lab__MediaFullscreenButton: ({C, React, mod, Pkg}) => - mediaPart(React, mod, Pkg, React.createElement(C)), - lab__MediaPlaybackRate: ({C, React, mod, Pkg}) => - mediaPart(React, mod, Pkg, React.createElement(C)), core__Swipe: ({React, mod, Core}) => React.createElement(Core.Item, { label: 'Inbox', @@ -749,56 +320,6 @@ export const samples = { value: null, onChange: noop, }), - lab__ChatEmojiPicker: ({C, React}) => - React.createElement( - C, - {onSelect: noop}, - React.createElement('button', {type: 'button'}, 'Add reaction'), - ), - lab__CircleCheckIndicator: ({C, React}) => - React.createElement(C, {state: 'checked'}), - lab__CircularProgress: ({C, React}) => - React.createElement(C, {label: 'Uploading', value: 40}), - lab__DialogHeroHeader: ({C, React}) => - React.createElement(C, { - title: 'Welcome aboard', - media: React.createElement('div', {style: {height: 120}}), - }), - lab__EmojiPicker: ({C, React}) => React.createElement(C, {onSelect: noop}), - lab__LineClamp: ({C, React}) => - React.createElement( - C, - {maxLines: 2}, - 'A long paragraph that runs past two lines, so the clamp cuts it short and shows the rest only when it is expanded by the reader.', - ), - lab__SelectableCardGroup: ({C, React, mod, Pkg}) => { - const Item = mod.SelectableCardGroupItem ?? Pkg.SelectableCardGroupItem; - return React.createElement( - C, - {label: 'Plan', value: 'pro', onChange: noop}, - React.createElement(Item, {value: 'basic', label: 'Basic'}), - React.createElement(Item, {value: 'pro', label: 'Pro'}), - ); - }, - lab__Stat: ({C, React}) => - React.createElement(C, {label: 'Revenue', value: '$12.4k'}), - lab__TabBar: ({C, React, mod, Pkg}) => { - const Item = mod.TabBarItem ?? Pkg.TabBarItem; - return React.createElement( - C, - {value: 'home', onChange: noop, label: 'Sections'}, - React.createElement(Item, { - value: 'home', - label: 'Home', - icon: dotIcon(React), - }), - React.createElement(Item, { - value: 'search', - label: 'Search', - icon: dotIcon(React), - }), - ); - }, richtext__RichTextEditor: ({C, React}) => React.createElement(C, {label: 'Notes'}), richtext__RichTextView: ({C, React}) => @@ -823,6 +344,8 @@ export const samples = { }, }, }), + // Lab samples live with Lab (packages/lab/swizzle-samples.mjs). + ...labSamples, }; /** @@ -843,9 +366,4 @@ export const notRendered = { * (samples.test.mjs, and the proof before it renders). Every other such target * has a sample, so the browser step renders it with its required props. */ -export const needsNoSample = { - // Its rows are the tabs past the fourth, read from the copy's own - // TabBarItem, which the copy's entry does not export to a sample. - lab__TabBarMoreList: - "renders without onChange; its rows need the copy's TabBarItem, which its entry does not export", -}; +export const needsNoSample = {...labNeedsNoSample}; diff --git a/packages/lab/swizzle-samples.mjs b/packages/lab/swizzle-samples.mjs new file mode 100644 index 0000000000000..21d78cf9a26e0 --- /dev/null +++ b/packages/lab/swizzle-samples.mjs @@ -0,0 +1,519 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file swizzle-samples.mjs + * @input A Lab copy's component, its module, and the package modules + * @output The swizzle proof's samples for Lab targets whose playground + * defaults do not render on their own, and the Lab targets that render + * without a sample + * @position Read by packages/cli/test/swizzle-proof/samples.mjs, which spreads + * both into its own. `pnpm lab:sync` adds a stub here for a new Lab target + * with a required prop; it never changes an existing sample. + */ + +const noop = () => {}; + +/** A small icon for targets whose required `icon` takes any node. */ +const dotIcon = React => + React.createElement( + 'svg', + {viewBox: '0 0 16 16', width: 16, height: 16, 'aria-hidden': true}, + React.createElement('circle', {cx: 8, cy: 8, r: 6}), + ); + +function labChart(React, mod, Pkg, props, child) { + const h = React.createElement; + const Chart = mod.Chart ?? Pkg.Chart; + return h('div', {style: {width: 480, height: 320}}, h(Chart, props, child)); +} + +const monthly = { + data: [ + {month: 'Jan', v: 1, upper: 30, lower: 10}, + {month: 'Feb', v: 3, upper: 40, lower: 20}, + {month: 'Mar', v: 2, upper: 50, lower: 30}, + ], + xKey: 'month', + yKeys: ['v', 'upper', 'lower'], +}; +const xy = { + data: [ + {x: 0, y: 1}, + {x: 1, y: 2}, + {x: 2, y: 3}, + ], + xKey: 'x', + yKeys: ['y'], +}; +const ohlc = { + data: [ + {day: '1', open: 1, close: 2, high: 3, low: 0.5}, + {day: '2', open: 2, close: 1.5, high: 2.5, low: 1}, + {day: '3', open: 1.5, close: 3, high: 3.5, low: 1.2}, + ], + xKey: 'day', + yKeys: ['high', 'low'], +}; +const xyz = { + data: [ + {x: 0, y: 1, z: 0}, + {x: 2, y: 2, z: 2}, + {x: 1, y: 3, z: 1}, + ], + xKey: 'x', + yKey: 'y', + zKey: 'z', +}; + +function threeD(React, mod, Pkg, child) { + const h = React.createElement; + const ThreeDChart = mod.ThreeDChart ?? Pkg.ThreeDChart; + return h( + 'div', + {style: {width: 600, height: 400}}, + h(ThreeDChart, xyz, child), + ); +} + +function tour(React, Tour, TourStep) { + const h = React.createElement; + function Sample() { + const a = React.useRef(null); + const b = React.useRef(null); + return h( + React.Fragment, + null, + h('button', {type: 'button', ref: a}, 'Target A'), + h('button', {type: 'button', ref: b}, 'Target B'), + h( + Tour, + {isActive: true, onDismiss: noop}, + h(TourStep, {targetRef: a, heading: 'First'}, 'First body'), + h(TourStep, {targetRef: b, heading: 'Second'}, 'Second body'), + ), + ); + } + return h(Sample); +} + +function navigation(React, Stack, Screen) { + const h = React.createElement; + return h(Stack, { + label: 'Settings', + root: h( + Screen, + {title: 'Settings'}, + h('button', {type: 'button'}, 'General'), + ), + path: [], + onPathChange: noop, + getKey: entry => entry, + renderScreen: entry => h(Screen, {title: entry}, entry), + }); +} + +/** A media part inside a player from the same copy, so it reads that player. */ +function mediaPart(React, mod, Pkg, part) { + const h = React.createElement; + const MediaPlayer = mod.MediaPlayer ?? Pkg.MediaPlayer; + const MediaPlayerElement = mod.MediaPlayerElement ?? Pkg.MediaPlayerElement; + return h( + MediaPlayer, + {label: 'Clip'}, + h(MediaPlayerElement, {kind: 'video', src: '/clip.mp4'}), + part, + ); +} + +export const labSamples = { + lab__ChartArea: ({C, React, mod, Pkg}) => + labChart( + React, + mod, + Pkg, + monthly, + React.createElement(C, { + yUpper: 'upper', + yLower: 'lower', + color: '#0064E0', + }), + ), + lab__ChartBar: ({C, React, mod, Pkg}) => + labChart(React, mod, Pkg, monthly, React.createElement(C, {dataKey: 'v'})), + lab__ChartLine: ({C, React, mod, Pkg}) => + labChart(React, mod, Pkg, monthly, React.createElement(C, {dataKey: 'v'})), + lab__ChartDot: ({C, React, mod, Pkg}) => + labChart(React, mod, Pkg, xy, React.createElement(C, {dataKey: 'y'})), + lab__ChartDotGL: ({C, React, mod, Pkg}) => + labChart( + React, + mod, + Pkg, + xy, + React.createElement(C, {dataKey: 'y', color: '#0064E0'}), + ), + lab__ChartDotGLInteractive: ({C, React, mod, Pkg}) => + labChart( + React, + mod, + Pkg, + xy, + React.createElement(C, {dataKey: 'y', color: '#0064E0'}), + ), + lab__ChartCandlestick: ({C, React, mod, Pkg}) => + labChart( + React, + mod, + Pkg, + ohlc, + React.createElement(C, { + high: 'high', + low: 'low', + open: 'open', + close: 'close', + }), + ), + lab__ChartHeatmapGL: ({C, React, mod, Pkg}) => + labChart( + React, + mod, + Pkg, + { + data: [ + {month: 'Jan', row: 'A', value: 1}, + {month: 'Jan', row: 'B', value: 2}, + {month: 'Feb', row: 'A', value: 3}, + {month: 'Feb', row: 'B', value: 4}, + ], + xKey: 'month', + yKeys: ['value'], + }, + React.createElement(C, { + xKey: 'month', + yKey: 'row', + valueKey: 'value', + colorRange: ['#000000', '#ffffff'], + }), + ), + lab__ChartStreamGL: ({C, React, mod, Pkg}) => + labChart( + React, + mod, + Pkg, + {data: [], xKey: 't', yKeys: ['v'], xDomain: [0, 10], yDomain: [0, 1]}, + React.createElement(C, {color: '#0064E0'}), + ), + lab__WeightedSVGIcon: ({C, React}) => + React.createElement(C, { + icon: { + name: 'swizzle-proof-dot', + layers: [ + { + from: 300, + to: 700, + paths: [{d: 'M12 4a8 8 0 1 0 0 16a8 8 0 1 0 0-16z'}], + }, + ], + }, + 'aria-label': 'Dot', + }), + lab__ChatVirtualizer: ({C, React}) => + // A fixed-height frame, so the browser step windows real rows. + React.createElement( + 'div', + {style: {height: 320, display: 'flex', flexDirection: 'column'}}, + React.createElement(C, { + data: [ + {id: 'a', text: 'First message'}, + {id: 'b', text: 'Second message'}, + {id: 'c', text: 'Third message'}, + ], + getRowKey: item => item.id, + renderItem: ({item}) => React.createElement('p', null, item.text), + }), + ), + lab__ChatReactionBar: ({C, React}) => + React.createElement(C, { + reactions: [ + {emoji: '👍', count: 2, label: 'Thumbs up'}, + {emoji: '🎉', count: 1, isSelected: true, label: 'Party'}, + ], + onReactionClick: noop, + onAddReaction: noop, + }), + lab__Tour: ({C, React, mod, Pkg}) => + tour(React, C, mod.TourStep ?? Pkg.TourStep), + lab__TourStep: ({C, React, mod, Pkg}) => tour(React, mod.Tour ?? Pkg.Tour, C), + lab__CodeEditor: ({C, React}) => + React.createElement(C, { + value: 'const answer = 42;', + onChange: noop, + language: 'typescript', + label: 'Edit snippet', + }), + lab__CommentComposer: ({C, React}) => + React.createElement(C, {value: '', onChange: noop, onSubmit: noop}), + lab__CommentPin: ({C, React}) => + React.createElement(C, { + label: 'Open annotation from Ada', + participants: [{id: 'ada', name: 'Ada Lovelace'}], + onClick: noop, + }), + lab__CommentThread: ({C, React}) => + React.createElement( + 'div', + {style: {width: 320}}, + React.createElement(C, { + comment: { + id: 'margin', + author: {id: 'maya', name: 'Maya Chen'}, + body: 'Should this say three days?', + createdAt: '2026-09-30T19:00:00Z', + }, + currentUser: {id: 'avery', name: 'Avery Kim'}, + onSubmit: noop, + }), + ), + lab__DiffViewer: ({C, React, mod, Pkg}) => { + const parse = mod.parseUnifiedDiff ?? Pkg.parseUnifiedDiff; + const patch = [ + 'diff --git a/a.ts b/a.ts', + '--- a/a.ts', + '+++ b/a.ts', + '@@ -1,2 +1,2 @@', + ' const a = 1;', + '-const b = 2;', + '+const b = 3;', + '', + ].join('\n'); + return React.createElement(C, {file: parse(patch)[0]}); + }, + lab__ListInput: ({C, React, Core}) => + React.createElement(C, { + label: 'Tags', + value: [{id: '1', label: 'Alpha'}], + onChange: noop, + getItemKey: item => item.id, + createItem: () => ({id: String(Date.now()), label: ''}), + columns: [ + { + key: 'label', + header: 'Label', + renderInput: ({item, label, isLabelHidden}) => + React.createElement(Core.TextInput, { + label, + isLabelHidden, + value: item.label, + onChange: noop, + }), + }, + ], + }), + lab__LogStream: ({C, React}) => + React.createElement(C, { + entries: [ + { + id: 'a', + timestamp: '14:02:11.482', + level: 'info', + source: 'api-gateway', + message: 'request accepted', + }, + { + id: 'b', + timestamp: '14:02:12.001', + level: 'warn', + source: 'api-gateway', + message: 'retrying upstream call', + }, + ], + }), + lab__SankeyChart: ({C, React, mod, Pkg}) => + React.createElement( + 'div', + {style: {width: 480, height: 320}}, + React.createElement( + C, + { + nodes: [ + {id: 'a', label: 'A', value: 10}, + {id: 'b', label: 'B', value: 10}, + {id: 'c', label: 'C', value: 10}, + ], + links: [ + {source: 'a', target: 'b', value: 5}, + {source: 'b', target: 'c', value: 5}, + ], + }, + React.createElement(mod.SankeyNode ?? Pkg.SankeyNode), + ), + ), + lab__Schedule: ({C, React, mod, Pkg}) => { + const view = ( + mod.createScheduleMonthlyView ?? Pkg.createScheduleMonthlyView + )(); + return React.createElement(C, { + view, + events: [], + date: Date.UTC(2026, 9, 30), + focusDate: Date.UTC(2026, 9, 30), + timezoneID: 'UTC', + }); + }, + lab__ThreeDBar: ({C, React, mod, Pkg}) => + threeD(React, mod, Pkg, React.createElement(C, {color: '#00aa00'})), + lab__ThreeDScatter: ({C, React, mod, Pkg}) => + threeD(React, mod, Pkg, React.createElement(C, {color: '#00aa00'})), + lab__ThreeDScatterGL: ({C, React, mod, Pkg}) => + threeD(React, mod, Pkg, React.createElement(C, {color: '#00aa00'})), + lab__ThreeDSurface: ({C, React, mod, Pkg}) => + threeD(React, mod, Pkg, React.createElement(C, {color: '#00aa00'})), + lab__ThreeDChart: ({C, React, mod, Pkg}) => + React.createElement( + 'div', + {style: {width: 600, height: 400}}, + React.createElement( + C, + xyz, + React.createElement(mod.ThreeDBar ?? Pkg.ThreeDBar, {color: '#00aa00'}), + ), + ), + lab__TransferList: ({C, React}) => + React.createElement(C, { + label: 'Columns', + options: [ + {value: 'name', label: 'Name'}, + {value: 'status', label: 'Status'}, + {value: 'owner', label: 'Owner'}, + ], + value: ['name'], + onChange: noop, + }), + lab__NavigationStack: ({C, React, mod, Pkg}) => + navigation(React, C, mod.NavigationScreen ?? Pkg.NavigationScreen), + lab__NavigationScreen: ({C, React, mod, Pkg}) => + navigation(React, mod.NavigationStack ?? Pkg.NavigationStack, C), + lab__PageControl: ({C, React}) => + React.createElement(C, { + totalPages: 3, + page: 0, + onChange: noop, + label: 'Pages', + }), + lab__TabBarItem: ({C, React, mod, Pkg}) => { + const TabBar = mod.TabBar ?? Pkg.TabBar; + return React.createElement( + TabBar, + {value: 'home', onChange: noop, label: 'Sections'}, + React.createElement(C, { + value: 'home', + label: 'Home', + icon: dotIcon(React), + }), + React.createElement(C, { + value: 'search', + label: 'Search', + icon: dotIcon(React), + }), + ); + }, + lab__SVGIcon: ({C, React, mod, Pkg}) => + React.createElement(C, { + icon: mod.bellIcon ?? Pkg.bellIcon, + 'aria-label': 'Notifications', + }), + lab__MediaPlayer: ({C, React, mod, Pkg}) => + React.createElement( + C, + {label: 'Clip'}, + React.createElement(mod.MediaPlayerElement ?? Pkg.MediaPlayerElement, { + kind: 'video', + src: '/clip.mp4', + }), + React.createElement(mod.MediaPlayButton ?? Pkg.MediaPlayButton), + ), + lab__MediaPlayerElement: ({C, React, mod, Pkg}) => + React.createElement( + mod.MediaPlayer ?? Pkg.MediaPlayer, + {label: 'Clip'}, + React.createElement(C, {kind: 'video', src: '/clip.mp4'}), + ), + lab__MediaPlayButton: ({C, React, mod, Pkg}) => + mediaPart(React, mod, Pkg, React.createElement(C)), + lab__MediaSeekButton: ({C, React, mod, Pkg}) => + mediaPart(React, mod, Pkg, React.createElement(C, {offset: 10})), + lab__MediaVolume: ({C, React, mod, Pkg}) => + mediaPart(React, mod, Pkg, React.createElement(C)), + lab__MediaTimeSlider: ({C, React, mod, Pkg}) => + mediaPart(React, mod, Pkg, React.createElement(C)), + lab__MediaTime: ({C, React, mod, Pkg}) => + mediaPart(React, mod, Pkg, React.createElement(C)), + lab__MediaCaptionsButton: ({C, React, mod, Pkg}) => + mediaPart(React, mod, Pkg, React.createElement(C)), + lab__MediaFullscreenButton: ({C, React, mod, Pkg}) => + mediaPart(React, mod, Pkg, React.createElement(C)), + lab__MediaPlaybackRate: ({C, React, mod, Pkg}) => + mediaPart(React, mod, Pkg, React.createElement(C)), + lab__ChatEmojiPicker: ({C, React}) => + React.createElement( + C, + {onSelect: noop}, + React.createElement('button', {type: 'button'}, 'Add reaction'), + ), + lab__CircleCheckIndicator: ({C, React}) => + React.createElement(C, {state: 'checked'}), + lab__CircularProgress: ({C, React}) => + React.createElement(C, {label: 'Uploading', value: 40}), + lab__DialogHeroHeader: ({C, React}) => + React.createElement(C, { + title: 'Welcome aboard', + media: React.createElement('div', {style: {height: 120}}), + }), + lab__EmojiPicker: ({C, React}) => React.createElement(C, {onSelect: noop}), + lab__LineClamp: ({C, React}) => + React.createElement( + C, + {maxLines: 2}, + 'A long paragraph that runs past two lines, so the clamp cuts it short and shows the rest only when it is expanded by the reader.', + ), + lab__SelectableCardGroup: ({C, React, mod, Pkg}) => { + const Item = mod.SelectableCardGroupItem ?? Pkg.SelectableCardGroupItem; + return React.createElement( + C, + {label: 'Plan', value: 'pro', onChange: noop}, + React.createElement(Item, {value: 'basic', label: 'Basic'}), + React.createElement(Item, {value: 'pro', label: 'Pro'}), + ); + }, + lab__Stat: ({C, React}) => + React.createElement(C, {label: 'Revenue', value: '$12.4k'}), + lab__TabBar: ({C, React, mod, Pkg}) => { + const Item = mod.TabBarItem ?? Pkg.TabBarItem; + return React.createElement( + C, + {value: 'home', onChange: noop, label: 'Sections'}, + React.createElement(Item, { + value: 'home', + label: 'Home', + icon: dotIcon(React), + }), + React.createElement(Item, { + value: 'search', + label: 'Search', + icon: dotIcon(React), + }), + ); + }, + // lab:sync adds new samples above this line. +}; + +/** + * Lab targets whose doc names a required prop that neither a sample nor the + * doc's playground defaults give, and that render without it. + */ +export const labNeedsNoSample = { + // Its rows are the tabs past the fourth, read from the copy's own + // TabBarItem, which the copy's entry does not export to a sample. + lab__TabBarMoreList: + "renders without onChange; its rows need the copy's TabBarItem, which its entry does not export", +}; diff --git a/scripts/lab-sync.mjs b/scripts/lab-sync.mjs new file mode 100644 index 0000000000000..3502d26984611 --- /dev/null +++ b/scripts/lab-sync.mjs @@ -0,0 +1,354 @@ +#!/usr/bin/env node +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file lab-sync.mjs + * @input The Lab package's component docs (`packages/lab/src/**\/*.doc.mjs`) + * and block docs (`packages/lab/blocks/*.doc.mjs`), the shadcn route lock + * (`internal/shadcn-registry/routes.lock.json`) and the Lab swizzle samples + * (`packages/lab/swizzle-samples.mjs`). + * @output `pnpm lab:sync` writes each Lab component's, hook's, example's and + * showcase's route-lock entry, and a swizzle sample stub for a Lab target + * whose doc names a required prop with no default and that has no sample. + * It never changes an existing sample. `--check` writes nothing; it names + * each missing entry and exits 1. + * @position Run by hand after adding a Lab component, by `pnpm preflight`, and + * by CI's Lab lane. Names and paths come from the docsite's own registry + * identity helpers (apps/docsite/src/lib/shadcnRegistry.mjs), so they match + * what the docsite generator writes. + */ +/* global console, process */ +import fs from 'node:fs'; +import path from 'node:path'; +import {fileURLToPath, pathToFileURL} from 'node:url'; + +const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); +const LAB = '@astryxdesign/lab'; +export const ROUTE_LOCK = 'internal/shadcn-registry/routes.lock.json'; +export const LAB_SAMPLES = 'packages/lab/swizzle-samples.mjs'; +/** The line in LAB_SAMPLES that new stubs go above. */ +export const STUB_MARKER = ' // lab:sync adds new samples above this line.'; +export const STUB_NOTE = '// generated by lab:sync; edit freely'; + +// Each pass reads the samples file afresh; a URL Node has seen is cached. +let reads = 0; + +async function loadDoc(file) { + const m = await import(pathToFileURL(file).href); + return ( + m.doc ?? + m.default ?? + Object.values(m).find(v => v && typeof v === 'object' && v.name) ?? + null + ); +} + +function docFiles(dir, recursive) { + if (!fs.existsSync(dir)) return []; + return fs + .readdirSync(dir, {recursive}) + .map(String) + .filter(file => file.endsWith('.doc.mjs')) + .sort(); +} + +/** + * The route-lock entries the Lab docs give, by the docsite generator's own + * rules: a sub-component doc is its own entry; a family doc gives each + * documented sub-component (a name-only reference is not one), and itself + * when it has top-level props; any other doc gives itself. A name starting + * with `use`, or an entry with params, is a hook. Each Lab block gives an + * example or a showcase of the component it is for. + * @param {string} root the repository + * @param {{componentRegistryIdentity: Function, blockRegistryIdentity: Function}} identity + * @returns {Promise<{name: string, path: string, aliases: string[]}[]>} + */ +export async function labRouteEntries(root, identity) { + const entries = new Map(); + const add = id => + entries.set(id.name, {name: id.name, path: id.path, aliases: id.aliases}); + const strip = name => String(name || '').replace(/^XDS/, ''); + const src = path.join(root, 'packages/lab/src'); + for (const file of docFiles(src, true)) { + const doc = await loadDoc(path.join(src, file)); + if (!doc) continue; + if (doc.subComponentOf) { + const name = strip(doc.name); + if (!name) continue; + const hook = + name.startsWith('use') || + Array.isArray(doc.params) || + Array.isArray(doc.returns); + add( + identity.componentRegistryIdentity( + LAB, + name, + hook, + doc.registry ?? null, + ), + ); + } else if (Array.isArray(doc.components) && doc.components.length > 0) { + if (Array.isArray(doc.props) && doc.props.length > 0) { + const name = doc.name || strip(path.basename(file, '.doc.mjs')); + add( + identity.componentRegistryIdentity( + LAB, + name, + false, + doc.registry ?? null, + ), + ); + } + for (const sub of doc.components) { + const raw = sub?.name || ''; + const name = strip(raw); + if (!name || (Object.keys(sub).length === 1 && sub.name != null)) + continue; + const hook = + raw.startsWith('use') || + name.startsWith('use') || + Array.isArray(sub.params); + add( + identity.componentRegistryIdentity( + LAB, + name, + hook, + sub.registry ?? doc.registry ?? null, + ), + ); + } + } else { + const name = strip(doc.name); + if (!name) continue; + const hook = name.startsWith('use') || Array.isArray(doc.params); + add( + identity.componentRegistryIdentity( + LAB, + name, + hook, + doc.registry ?? null, + ), + ); + } + } + const blocks = path.join(root, 'packages/lab/blocks'); + for (const file of docFiles(blocks, false)) { + const doc = await loadDoc(path.join(blocks, file)); + if (!doc?.name) continue; + add( + identity.blockRegistryIdentity( + doc.name, + doc.exampleFor ?? null, + doc.isShowcase ?? false, + doc.registry ?? null, + ), + ); + } + return [...entries.values()]; +} + +/** + * The route lock with every Lab entry present and current. Other entries + * stay as they are; the items keep the generator's order (by path). + * @param {string} lockText the lock file's text + * @param {{name: string, path: string, aliases: string[]}[]} entries + * @returns {{text: string, missing: string[]}} `missing` names each entry + * added or changed + */ +export function syncRouteLock(lockText, entries) { + const lock = JSON.parse(lockText); + const byName = new Map(lock.items.map(item => [item.name, item])); + const missing = []; + for (const entry of entries) { + if (JSON.stringify(byName.get(entry.name)) === JSON.stringify(entry)) + continue; + missing.push(entry.name); + byName.set(entry.name, entry); + } + if (missing.length === 0) return {text: lockText, missing}; + const items = [...byName.values()].sort((a, b) => + a.path.localeCompare(b.path), + ); + return { + text: `${JSON.stringify({...lock, items}, null, 2)}\n`, + missing, + }; +} + +/** + * A stub value for a required prop, from its doc type: a string is the prop's + * name, a number 0, a boolean false, a node a short text, a function a no-op, + * a union of string literals its first one, an array empty. + * @param {{name: string, type?: string}} prop + * @returns {string} JavaScript source + */ +export function stubValue(prop) { + const type = String(prop.type ?? '').trim(); + if (/=>/.test(type)) return 'noop'; + if (/^string$/.test(type)) return JSON.stringify(prop.name); + if (/^number$/.test(type)) return '0'; + if (/^boolean$/.test(type)) return 'false'; + if (/^(?:React\.)?React(?:Node|Element)\b|^node$/i.test(type)) + return "'Sample'"; + const literal = /^'([^']*)'(?:\s*\|\s*'[^']*')*$/.exec(type); + if (literal) return JSON.stringify(literal[1]); + if (/\[\]$|^(?:ReadonlyArray|Array)` + * @param {{name: string, type?: string}[]} props the required props + * @returns {string} lines to insert in the samples object + */ +export function sampleStub(key, props) { + const args = props + .map(prop => ` ${JSON.stringify(prop.name)}: ${stubValue(prop)},`) + .join('\n'); + return [ + ` ${STUB_NOTE}`, + ` ${key}: ({C, React}) =>`, + ` React.createElement(C, {`, + args, + ` }),`, + ].join('\n'); +} + +/** + * The samples source with each stub inserted above the marker line. + * @param {string} source LAB_SAMPLES's text + * @param {string[]} stubs + */ +export function insertStubs(source, stubs) { + if (stubs.length === 0) return source; + if (!source.includes(STUB_MARKER)) + throw new Error( + `${LAB_SAMPLES} has no "${STUB_MARKER.trim()}" line to add samples above`, + ); + return source.replace(STUB_MARKER, `${stubs.join('\n')}\n${STUB_MARKER}`); +} + +/** + * The Lab swizzle targets that need a sample, with their required props: + * each Lab doc's component, as the swizzle proof names it (`lab__`), whose doc names a required prop its defaults leave out, and that + * has no sample and no mark. + * @param {string} root + * @param {{samples: object, needsNoSample: object, notRendered: object}} marks + * @param {(doc: any, name: string) => string[]} requiredWithoutDefault + * @returns {Promise<{key: string, props: {name: string, type?: string}[]}[]>} + */ +export async function unsampledTargets(root, marks, requiredWithoutDefault) { + const src = path.join(root, 'packages/lab/src'); + const out = []; + for (const file of docFiles(src, true)) { + const name = path.basename(file, '.doc.mjs'); + const key = `lab__${name}`; + if ( + marks.samples[key] || + marks.needsNoSample[key] || + marks.notRendered[key] + ) + continue; + const doc = await loadDoc(path.join(src, file)).catch(() => null); + if (!doc) continue; + const missing = requiredWithoutDefault(doc, name); + if (missing.length === 0) continue; + const entry = doc?.components?.find(c => c?.name === name) ?? doc; + const props = missing.map( + prop => (entry?.props ?? []).find(p => p?.name === prop) ?? {name: prop}, + ); + out.push({key, props}); + } + return out; +} + +/** + * One sync pass over `root`. + * @param {string} root + * @param {{write: boolean}} options + * @returns {Promise<{routes: string[], samples: string[]}>} what was missing + */ +export async function labSync(root, {write}) { + const identity = await import( + pathToFileURL(path.join(ROOT, 'apps/docsite/src/lib/shadcnRegistry.mjs')) + .href + ); + const {requiredWithoutDefault} = await import( + pathToFileURL(path.join(ROOT, 'packages/cli/test/swizzle-proof/proof.mjs')) + .href + ); + const lockFile = path.join(root, ROUTE_LOCK); + const lockText = fs.readFileSync(lockFile, 'utf8'); + const {text, missing: routes} = syncRouteLock( + lockText, + await labRouteEntries(root, identity), + ); + const samplesFile = path.join(root, LAB_SAMPLES); + const lab = await import( + `${pathToFileURL(samplesFile).href}?read=${(reads += 1)}` + ); + const shared = await import( + pathToFileURL( + path.join(ROOT, 'packages/cli/test/swizzle-proof/samples.mjs'), + ).href + ); + const targets = await unsampledTargets( + root, + { + samples: {...lab.labSamples}, + needsNoSample: {...lab.labNeedsNoSample}, + notRendered: shared.notRendered, + }, + requiredWithoutDefault, + ); + if (write) { + if (routes.length) fs.writeFileSync(lockFile, text); + if (targets.length) + fs.writeFileSync( + samplesFile, + insertStubs( + fs.readFileSync(samplesFile, 'utf8'), + targets.map(t => sampleStub(t.key, t.props)), + ), + ); + } + return {routes, samples: targets.map(t => t.key)}; +} + +if ( + process.argv[1] && + path.resolve(process.argv[1]) === fileURLToPath(import.meta.url) +) { + const check = process.argv.includes('--check'); + const root = process.env.LAB_SYNC_ROOT ?? ROOT; + labSync(root, {write: !check}) + .then(({routes, samples}) => { + if (routes.length === 0 && samples.length === 0) { + console.log( + 'lab:sync: every Lab route-lock entry and swizzle sample is present.', + ); + return; + } + const lines = [ + ...routes.map(name => ` route-lock entry ${name} (${ROUTE_LOCK})`), + ...samples.map(key => ` swizzle sample ${key} (${LAB_SAMPLES})`), + ]; + if (check) { + console.error( + `lab:sync --check: missing:\n${lines.join('\n')}\nRun \`pnpm lab:sync\` and commit the result.`, + ); + process.exitCode = 1; + } else { + console.log( + `lab:sync: wrote:\n${lines.join('\n')}\nReview the stubs (marked "${STUB_NOTE}").`, + ); + } + }) + .catch(error => { + console.error(error.message); + process.exitCode = 1; + }); +} diff --git a/scripts/lab-sync.test.mjs b/scripts/lab-sync.test.mjs new file mode 100644 index 0000000000000..63c78da24b94c --- /dev/null +++ b/scripts/lab-sync.test.mjs @@ -0,0 +1,198 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file lab-sync.test.mjs + * @input lab-sync.mjs, the repository's Lab docs, route lock and Lab samples, + * and a fixture Lab component in a temporary tree + * @output The repository needs no sync; a lock without its Lab entries comes + * back byte-identical (the generator's own order and format); a new Lab + * component gets its route entry and a sample stub, `--check` names both + * and fails before the sync and passes after it, and an existing sample is + * never changed. + * @position A Node test; it imports docs and needs no build + */ + +import {execFileSync, spawnSync} from 'node:child_process'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import {fileURLToPath} from 'node:url'; +import {describe, expect, it} from 'vitest'; +import * as identity from '../apps/docsite/src/lib/shadcnRegistry.mjs'; +import { + LAB_SAMPLES, + ROUTE_LOCK, + STUB_MARKER, + STUB_NOTE, + labRouteEntries, + labSync, + sampleStub, + stubValue, + syncRouteLock, +} from './lab-sync.mjs'; + +const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); +const SCRIPT = path.join(ROOT, 'scripts/lab-sync.mjs'); + +describe('lab:sync on the repository', () => { + it('finds every Lab route entry and swizzle sample present', async () => { + expect(await labSync(ROOT, {write: false})).toEqual({ + routes: [], + samples: [], + }); + }); + + it('writes back exactly the lock the docsite generator wrote', async () => { + const lock = fs.readFileSync(path.join(ROOT, ROUTE_LOCK), 'utf8'); + const entries = await labRouteEntries(ROOT, identity); + const names = new Set(entries.map(entry => entry.name)); + const parsed = JSON.parse(lock); + const without = `${JSON.stringify( + {...parsed, items: parsed.items.filter(item => !names.has(item.name))}, + null, + 2, + )}\n`; + const {text, missing} = syncRouteLock(without, entries); + expect(missing.length).toBe(entries.length); + expect(text).toBe(lock); + }); +}); + +describe('stubs', () => { + it('builds each required prop from its doc type', () => { + expect(stubValue({name: 'label', type: 'string'})).toBe('"label"'); + expect(stubValue({name: 'count', type: 'number'})).toBe('0'); + expect(stubValue({name: 'open', type: 'boolean'})).toBe('false'); + expect(stubValue({name: 'title', type: 'ReactNode'})).toBe("'Sample'"); + expect(stubValue({name: 'onChange', type: '(value: string) => void'})).toBe( + 'noop', + ); + expect(stubValue({name: 'kind', type: "'video' | 'audio'"})).toBe( + '"video"', + ); + expect(stubValue({name: 'items', type: 'string[]'})).toBe('[]'); + }); + + it('marks the stub as generated', () => { + expect(sampleStub('lab__Foo', [{name: 'label', type: 'string'}])).toContain( + STUB_NOTE, + ); + }); +}); + +/** A repository tree with one Lab component that has neither entry. */ +function fixture() { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'lab-sync-')); + const put = (file, text) => { + fs.mkdirSync(path.dirname(path.join(root, file)), {recursive: true}); + fs.writeFileSync(path.join(root, file), text); + }; + put( + 'packages/lab/src/Foo/Foo.doc.mjs', + `export default { + name: 'Foo', + props: [ + {name: 'label', type: 'string', required: true}, + {name: 'onChange', type: '(value: string) => void', required: true}, + {name: 'size', type: 'number'}, + {name: 'children', type: 'ReactNode', required: true}, + ], +}; +`, + ); + put( + 'packages/lab/src/Bar/Bar.doc.mjs', + `export default {name: 'Bar', props: [{name: 'value', type: 'number', required: true}]}; +`, + ); + put( + ROUTE_LOCK, + `${JSON.stringify( + { + version: 1, + items: [ + {name: 'component-alert', path: 'components/alert', aliases: []}, + { + name: 'component-lab-bar', + path: 'components/lab/bar', + aliases: [], + }, + ], + }, + null, + 2, + )}\n`, + ); + put( + LAB_SAMPLES, + `const noop = () => {}; + +export const labSamples = { + lab__Bar: ({C, React}) => React.createElement(C, {value: 7}), +${STUB_MARKER} +}; + +export const labNeedsNoSample = {}; +`, + ); + return root; +} + +describe('lab:sync on a new Lab component', () => { + it('writes its route entry and a sample stub, and keeps an existing sample', async () => { + const root = fixture(); + expect(await labSync(root, {write: false})).toEqual({ + routes: ['component-lab-foo'], + samples: ['lab__Foo'], + }); + const barBefore = fs.readFileSync(path.join(root, LAB_SAMPLES), 'utf8'); + await labSync(root, {write: true}); + const lock = JSON.parse( + fs.readFileSync(path.join(root, ROUTE_LOCK), 'utf8'), + ); + expect(lock.items.map(item => item.path)).toEqual([ + 'components/alert', + 'components/lab/bar', + 'components/lab/foo', + ]); + const samples = fs.readFileSync(path.join(root, LAB_SAMPLES), 'utf8'); + expect(samples).toContain( + 'lab__Bar: ({C, React}) => React.createElement(C, {value: 7}),', + ); + expect(samples).toContain(` ${STUB_NOTE}\n lab__Foo: ({C, React}) =>`); + expect(samples).toContain('"label": "label",'); + expect(samples).toContain('"onChange": noop,'); + expect(samples).not.toContain('"size"'); + expect(samples).not.toContain('"children"'); + expect(barBefore.split(STUB_MARKER)[0]).toBe( + samples.split(` ${STUB_NOTE}`)[0], + ); + expect(await labSync(root, {write: false})).toEqual({ + routes: [], + samples: [], + }); + const {labSamples} = await import(path.join(root, LAB_SAMPLES)); + expect(labSamples.lab__Foo).toBeTypeOf('function'); + }); + + it('--check fails naming each missing entry and the fix, and passes after the sync', () => { + const root = fixture(); + const env = {...process.env, LAB_SYNC_ROOT: root}; + const before = spawnSync(process.execPath, [SCRIPT, '--check'], { + env, + encoding: 'utf8', + }); + expect(before.status).toBe(1); + expect(before.stderr).toContain( + `route-lock entry component-lab-foo (${ROUTE_LOCK})`, + ); + expect(before.stderr).toContain(`swizzle sample lab__Foo (${LAB_SAMPLES})`); + expect(before.stderr).toContain('Run `pnpm lab:sync`'); + execFileSync(process.execPath, [SCRIPT], {env}); + const after = spawnSync(process.execPath, [SCRIPT, '--check'], { + env, + encoding: 'utf8', + }); + expect(after.status).toBe(0); + }); +}); diff --git a/scripts/preflight.mjs b/scripts/preflight.mjs index fb93a2be9acd2..42076d7ca64fa 100644 --- a/scripts/preflight.mjs +++ b/scripts/preflight.mjs @@ -37,6 +37,12 @@ export const NOT_RUN = /** Files CI's formatting step checks with Prettier. */ const FORMATTED = /\.(?:tsx?|md)$/; +/** Every Lab route-lock entry and swizzle sample is present (`pnpm lab:sync`). */ +const LAB_SYNC_CHECK = { + id: 'lab sync', + commands: [{kind: 'light', argv: ['pnpm', 'lab:sync', '--check']}], +}; + /** Files ESLint lints. */ const LINTED = /\.(?:[cm]?[jt]sx?)$/; /** Vitest test files. */ @@ -308,6 +314,7 @@ export function planChecks({ id: 'changesets', commands: [{kind: 'light', argv: ['pnpm', 'check:changesets']}], }); + checks.push(LAB_SYNC_CHECK); if (browser) { if (noBuild) { @@ -462,6 +469,7 @@ function quickChecks({scope, mergeBase, changed}) { id: 'changesets', commands: [{kind: 'light', argv: ['pnpm', 'check:changesets']}], }, + LAB_SYNC_CHECK, ]; } diff --git a/scripts/preflight.test.mjs b/scripts/preflight.test.mjs index b92043d20e91c..3cf69ea3e1c43 100644 --- a/scripts/preflight.test.mjs +++ b/scripts/preflight.test.mjs @@ -52,6 +52,7 @@ describe('planChecks', () => { 'vitest node', 'knowledge', 'changesets', + 'lab sync', ]); expect(argvs(byId(checks, 'build'))).toEqual(['pnpm build']); expect(argvs(byId(checks, 'typecheck'))[0]).toContain( @@ -149,6 +150,7 @@ describe('planChecks --quick', () => { 'changed tests', 'knowledge', 'changesets', + 'lab sync', ]); const typecheck = argvs(byId(checks, 'typecheck'))[0]; expect(typecheck).toContain('--filter [abc123]');