An open source design system that's fully customizable and agent ready
TypeScript
docs(core): surface literal values for union types in component docs (#1645) (#3842)
AK20b7402f1738
diff --git a/.changeset/doc-union-literal-values.md b/.changeset/doc-union-literal-values.mdnew file mode 100644index 0000000000..8225b42c58--- /dev/null+++ b/.changeset/doc-union-literal-values.md@@ -0,0 +1,15 @@+---+'@astryxdesign/core': patch+---++[docs] Surface literal values for union types in component docs (#1645)++Prop docs named their union types without ever showing the values behind them — `gap: SpacingStep`, `align: GridAlignment`, `sort: TableSortState<TSortKey>`, `status: InputStatus`. Readers without an IDE (agents especially) had to guess, and guessed wrong: `gap={16}` (pixels, not a scale step), `direction: 'desc'` (the type says `'descending'`).++Those props now show their values — `gap: 0 | 0.5 | 1 | 1.5 | 2 | 3 | 4 | 5 | 6 | 8 | 10`, `direction: 'ascending' | 'descending'`, `status: {type: 'warning' | 'error' | 'success', …}` — across 28 doc files, improving both the `astryx component` CLI output and the docsite prop tables. Where spelling a type out would mislead the docsite playground into rendering the wrong control (Lightbox's `media`, AppShell's `mobileNav`), the values are given in the prop description instead.++Four latent doc bugs surfaced along the way: Card was missing its `transparent` variant, Text was missing `type="inherit"`, Field's `status` never named its legal values, and `useTableFiltering`'s `variant` documented only `'popover' | 'inline'` while source has offered `'inline-compact'` all along.++A new guard (`docPropLiterals.test.ts`) derives both the literal-union registry and each component's prop declarations from the TypeScript sources at test time, so a doc that names a union instead of inlining it — or that goes stale when a union gains a member — now fails the suite. It reads hook config bags (`UseTableSortableConfig`) as well as `{Name}Props`, and matches literals on a boundary rather than a substring, so neither `useTableSortable`'s `direction` nor a value masked by a longer sibling (`'sm'` inside `'xsm'`, the spacing step `1` inside `1.5`) can go stale unnoticed.++@AKnassadiff --git a/apps/docsite/src/__tests__/component-prop-controls.test.ts b/apps/docsite/src/__tests__/component-prop-controls.test.tsindex bc8b63a844..c93865aa61 100644--- a/apps/docsite/src/__tests__/component-prop-controls.test.ts+++ b/apps/docsite/src/__tests__/component-prop-controls.test.ts@@ -7,6 +7,7 @@ import {coerceEnumOption,parsePropType,} from '../components/component-detail/parsePropType';+import {isSupportedProp} from '../app/playground/propertyEditor/isSupportedProp';describe('component detail prop controls', () => {it('treats InputStatus as an editable status object control', () => {@@ -100,4 +101,113 @@ describe('component detail prop controls', () => {expect(control.options).toEqual(Object.keys(getIconRegistry()));}});++ /**+ * Inlining a union into a doc's `type` changes what control the playground+ * renders for it (#1645). For most props that is an improvement — an+ * unknown type becomes a real enum picker. For two it would be a+ * regression, and those two are deliberately left naming their type. These+ * assertions pin both halves of that bargain so a later "let's finish the+ * job and inline the last few" cannot quietly break the preview.+ */+ describe('inlining a union does not degrade the playground control (#1645)', () => {+ it('leaves SpacingStep exactly as it was — same enum, before and after', () => {+ const inlined = '0 | 0.5 | 1 | 1.5 | 2 | 3 | 4 | 5 | 6 | 8 | 10';+ const expected = {+ kind: 'enum',+ options: ['0', '0.5', '1', '1.5', '2', '3', '4', '5', '6', '8', '10'],+ allowEmpty: false,+ };+ // SpacingStep is special-cased in parsePropType, so both spellings must+ // land on the identical descriptor — the docs change is a no-op here.+ expect(parsePropType('SpacingStep', 'gap')).toEqual(expected);+ expect(parsePropType(inlined, 'gap')).toEqual(expected);+ expect(parsePropType(inlined, 'gap')).toEqual(+ parsePropType('SpacingStep', 'gap'),+ );+ });++ it('upgrades GridAlignment, TextSize and TextType from unknown to enum', () => {+ // Named, these are opaque: no control at all. Inlined, they become+ // pickers — the whole point of the change.+ expect(parsePropType('GridAlignment', 'align')).toEqual({+ kind: 'unknown',+ });+ expect(+ parsePropType("'start' | 'center' | 'end' | 'stretch'", 'align'),+ ).toEqual({+ kind: 'enum',+ options: ['start', 'center', 'end', 'stretch'],+ allowEmpty: false,+ });++ expect(parsePropType('TextSize', 'size')).toEqual({kind: 'unknown'});+ expect(+ parsePropType(+ "'4xs' | '3xs' | '2xs' | 'xsm' | 'sm' | 'base' | 'lg' | 'xl' | " ++ "'2xl' | '3xl' | '4xl'",+ 'size',+ ),+ ).toMatchObject({kind: 'enum', allowEmpty: false});++ expect(parsePropType('TextType', 'type')).toEqual({kind: 'unknown'});+ const textType = parsePropType(+ "'body' | 'large' | 'label' | 'supporting' | 'code' | 'display-1' | " ++ "'display-2' | 'display-3' | 'inherit'",+ 'type',+ );+ expect(textType).toMatchObject({kind: 'enum', allowEmpty: false});+ if (textType.kind === 'enum') {+ // 'inherit' is one of the latent doc bugs this change fixed.+ expect(textType.options).toContain('inherit');+ }+ });++ it('hides AppShell.mobileNav, and the gate is the exact type string', () => {+ // Production never asks parsePropType about this prop without its+ // slotElements (PropertyEditor passes all three arguments), so assert on+ // the gate the editor actually uses rather than on a call shape it never+ // makes.+ const slotElements = [{__element: 'MobileNav', props: {}}];+ const prop = (type: string) => ({+ name: 'mobileNav',+ type,+ description: '',+ slotElements,+ });++ expect(isSupportedProp(prop('ReactNode'))).toBe(false);++ // Widening to the true union drops the UNSUPPORTED_PROP_TYPES+ // exact-string match. The prop survives that only because slotElements+ // independently resolves it to a non-editable `element` control — a+ // second gate, not the one the doc leans on. Keep the bare `ReactNode`+ // so the hide never depends on that coincidence.+ const widened =+ "false | {hasToggle?: boolean, breakpoint?: 'sm' | 'md' | 'lg' | 'none'} | ReactNode";+ expect(parsePropType(widened, 'mobileNav', slotElements)).toMatchObject({+ kind: 'element',+ });+ expect(isSupportedProp(prop(widened))).toBe(false);+ });++ it('keeps Lightbox.media naming its type, because the real shape yields a string control', () => {+ // Named, it stays unknown and uneditable, so the preview keeps receiving+ // a real object.+ expect(parsePropType('LightboxMedia | LightboxMedia[]', 'media')).toEqual(+ {kind: 'unknown'},+ );+ // Spelled out, the shape carries LightboxMedia's real `caption?:+ // ReactNode` (Lightbox.tsx). That trips NODE_TYPE_RE, the prop becomes an+ // *editable string*, and the editor hands the preview raw text where a+ // media object belongs. Assert that exact bad outcome — a bare "not an+ // enum" would pass for `unknown` too, and so could never catch it.+ expect(+ parsePropType(+ "{src: string, alt: string, caption?: ReactNode, type?: 'image' | 'video'}",+ 'media',+ ),+ ).toEqual({kind: 'string'});+ });+ });});diff --git a/apps/docsite/src/app/playground/propertyEditor/PropertyEditor.tsx b/apps/docsite/src/app/playground/propertyEditor/PropertyEditor.tsxindex 9defc0a180..89ac66b01b 100644--- a/apps/docsite/src/app/playground/propertyEditor/PropertyEditor.tsx+++ b/apps/docsite/src/app/playground/propertyEditor/PropertyEditor.tsx@@ -34,7 +34,6 @@ import {coerceDefault,coerceEnumOption,parsePropType,- type PropControlDescriptor,} from '../../../components/component-detail/parsePropType';import type {PropDoc} from '../../../generated/componentRegistry';import {@@ -42,9 +41,9 @@ import {formatAttr,removeAttribute,setAttribute,- type AttrInfo,type InstanceInfo,} from './componentInstances';+import {isEditable, isSupportedProp} from './isSupportedProp';import {getComponentByModule} from './componentLookup';const NUMERIC_RE = /^-?\d+(\.\d+)?$/;@@ -67,35 +66,6 @@ const s = stylex.create({},});-function isEditable(control: PropControlDescriptor, attr?: AttrInfo): boolean {- if (attr?.valueKind === 'expression') {- return false;- }- return (- control.kind === 'boolean' ||- control.kind === 'enum' ||- control.kind === 'string' ||- control.kind === 'number'- );-}--// Prop types that have no inline control in the popover and so are-// hidden entirely (ReactNode parses to a string control but isn't meaningfully-// editable here; StyleXStyles/AriaRole have no control at all).-const UNSUPPORTED_PROP_TYPES = new Set([- 'ReactNode',- 'StyleXStyles',- 'AriaRole',-]);--/** Whether a prop can be edited through the editor (and should be shown). */-function isSupportedProp(prop: PropDoc): boolean {- if (UNSUPPORTED_PROP_TYPES.has(prop.type.trim())) {- return false;- }- return isEditable(parsePropType(prop.type, prop.name, prop.slotElements));-}-interface PropRowProps {prop: PropDoc;instance: InstanceInfo;diff --git a/apps/docsite/src/app/playground/propertyEditor/isSupportedProp.ts b/apps/docsite/src/app/playground/propertyEditor/isSupportedProp.tsnew file mode 100644index 0000000000..1e1c2fe4b5--- /dev/null+++ b/apps/docsite/src/app/playground/propertyEditor/isSupportedProp.ts@@ -0,0 +1,53 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Decides which props the playground's property editor will show.+ * @input A PropDoc (its `type` string and `slotElements`), plus the parsed control.+ * @output Whether the editor renders a control for the prop at all.+ * @position Pure gate for PropertyEditor — kept out of the component so tests can+ * reach it without booting StyleX.+ */++import {+ parsePropType,+ type PropControlDescriptor,+} from '../../../components/component-detail/parsePropType';+import type {PropDoc} from '../../../generated/componentRegistry';+import type {AttrInfo} from './componentInstances';++export function isEditable(+ control: PropControlDescriptor,+ attr?: AttrInfo,+): boolean {+ if (attr?.valueKind === 'expression') {+ return false;+ }+ return (+ control.kind === 'boolean' ||+ control.kind === 'enum' ||+ control.kind === 'string' ||+ control.kind === 'number'+ );+}++// Prop types that have no inline control in the popover and so are+// hidden entirely (ReactNode parses to a string control but isn't meaningfully+// editable here; StyleXStyles/AriaRole have no control at all).+//+// Matched as an EXACT type string. A doc that widens one of these into a union+// — say `false | MobileNavConfig | ReactNode` — no longer matches and falls+// through to the parse below, so keep the bare name in the doc if the intent is+// to hide the prop. See AppShell.doc.mjs's `mobileNav`.+const UNSUPPORTED_PROP_TYPES = new Set([+ 'ReactNode',+ 'StyleXStyles',+ 'AriaRole',+]);++/** Whether a prop can be edited through the editor (and should be shown). */+export function isSupportedProp(prop: PropDoc): boolean {+ if (UNSUPPORTED_PROP_TYPES.has(prop.type.trim())) {+ return false;+ }+ return isEditable(parsePropType(prop.type, prop.name, prop.slotElements));+}diff --git a/packages/cli/src/lib/component-format.mjs b/packages/cli/src/lib/component-format.mjsindex 78a28f70de..76e2bb529c 100644--- a/packages/cli/src/lib/component-format.mjs+++ b/packages/cli/src/lib/component-format.mjs@@ -34,15 +34,30 @@ function getTargetDataAttributes(target) {];}+/**+ * Escape a value for a markdown table cell.+ *+ * A prop type is a union, and a union is spelled with the same `|` that GFM+ * uses to separate cells — backticks do not protect it. A row with more cells+ * than the header has columns gets the excess *discarded*, so an unescaped+ * `gap: 0 | 0.5 | ...` silently eats its own Default and Description columns.+ * <!-- SYNC: packages/core/src/Markdown/parser.ts (splits on unescaped pipes) -->+ */+export function mdCell(value) {+ return String(value ?? '').replace(/\|/g, '\\|');+}+function formatPropsTable(props) {if (!props || props.length === 0) return '';const lines = [];lines.push('| Prop | Type | Default | Description |');lines.push('|------|------|---------|-------------|');for (const p of props) {- const def = p.default ? `\`${p.default}\`` : '—';+ const def = p.default ? `\`${mdCell(p.default)}\`` : '—';const req = p.required ? ' **(required)**' : '';- lines.push(`| \`${p.name}\` | \`${p.type}\` | ${def} | ${p.description}${req} |`);+ lines.push(+ `| \`${mdCell(p.name)}\` | \`${mdCell(p.type)}\` | ${def} | ${mdCell(p.description)}${req} |`,+ );}return lines.join('\n');}@@ -177,7 +192,7 @@ export function formatFull(docs, options = {}) {sections.push('|---------|----------|-------------|');for (const el of docs.usage.anatomy) {const req = el.required ? 'Yes' : 'No';- sections.push(`| ${el.name} | ${req} | ${el.description} |`);+ sections.push(`| ${mdCell(el.name)} | ${req} | ${mdCell(el.description)} |`);}sections.push('');}@@ -282,7 +297,9 @@ export function formatFull(docs, options = {}) {varLines.push('| CSS Variable | Default | Description |');varLines.push('|-------------|---------|-------------|');for (const v of publicVars) {- varLines.push(`| \`${v.name}\` | \`${v.default}\` | ${v.description} |`);+ varLines.push(+ `| \`${mdCell(v.name)}\` | \`${mdCell(v.default)}\` | ${mdCell(v.description)} |`,+ );}sections.push(varLines.join('\n') + '\n');}@@ -378,8 +395,8 @@ export function formatCompact(docs, componentName, importHint) {propLines.push('| CSS Property | Sets |');propLines.push('|-------------|------|');for (const d of docs.theming.derived) {- const target = d.expand === 'container' ? 'container layout tokens' : (d.vars || []).map(v => `\`${v}\``).join(', ');- propLines.push(`| \`${d.property}\` | ${target} |`);+ const target = d.expand === 'container' ? 'container layout tokens' : (d.vars || []).map(v => `\`${mdCell(v)}\``).join(', ');+ propLines.push(`| \`${mdCell(d.property)}\` | ${target} |`);}sections.push(propLines.join('\n') + '\n');}@@ -395,6 +412,19 @@ export function formatCompact(docs, componentName, importHint) {** For multi-component docs, extracts the entry matching componentName.*/+/**+ * Longest union `--detail brief` will spell out inside the one-line signature.+ *+ * The signature is a glance, not a reference: a six-member enum like+ * `start|center|end|between|around|evenly` reads at a glance, an eleven-member+ * spacing scale does not — and Stack carries four of them (gap, padding,+ * paddingInline, paddingBlock), so it printed the same scale four times. Longer+ * unions fall through to the terse prop list, exactly as they did when the type+ * was still the bare name `SpacingStep`. The full values are always one+ * `astryx component <Name>` away.+ */+const SIGNATURE_UNION_MAX_MEMBERS = 8;+export function formatBrief(docs, componentName, importHint, options = {}) {const displayName = componentName.startsWith('XDS')? componentName.slice(3)@@ -421,13 +451,15 @@ export function formatBrief(docs, componentName, importHint, options = {}) {const otherProps = [];for (const prop of props) {- if (prop.type.includes('|') && !prop.type.includes('ReactNode')) {- const values = prop.type- .replace(/['"]/g, '')- .split('|')- .map(v => v.trim())- .join('|');- signatureProps.push(`${prop.name}: ${values}`);+ const values =+ prop.type.includes('|') && !prop.type.includes('ReactNode')+ ? prop.type+ .replace(/['"]/g, '')+ .split('|')+ .map(v => v.trim())+ : null;+ if (values && values.length <= SIGNATURE_UNION_MAX_MEMBERS) {+ signatureProps.push(`${prop.name}: ${values.join('|')}`);} else if (prop.required) {otherProps.unshift(`${prop.name}: ${prop.type.split('|')[0].trim()}`);} else {diff --git a/packages/cli/src/lib/component-format.test.mjs b/packages/cli/src/lib/component-format.test.mjsindex a997c2de84..d8dc736da2 100644--- a/packages/cli/src/lib/component-format.test.mjs+++ b/packages/cli/src/lib/component-format.test.mjs@@ -1,7 +1,7 @@// Copyright (c) Meta Platforms, Inc. and affiliates.import {describe, it, expect} from 'vitest';-import {formatFull} from './component-format.mjs';+import {formatBrief, formatFull} from './component-format.mjs';describe('formatFull sub-component rendering', () => {// Regression guard: sub-components are sometimes declared as a bare@@ -93,3 +93,97 @@ describe('formatFull theming override keys', () => {expect(out).not.toContain("'astryx-table-cell': {");});});++/** Pipes that actually separate cells — a `\|` is content, not a separator. */+function cellPipes(row) {+ return (row.match(/(?<!\\)\|/g) || []).length;+}++describe('markdown table cells escape their pipes', () => {+ // A prop type is a union, and a union is spelled with `|` — the very+ // character GFM uses to separate cells. Backticks do not protect it: a row+ // with more cells than the header has columns gets its excess *discarded*,+ // so an unescaped `gap: 0 | 0.5 | ...` silently eats its own Default and+ // Description columns. See packages/core/src/Markdown/parser.ts, which+ // splits on unescaped pipes and preserves `\|` as literal.+ it('keeps a union-typed prop row at four cells', () => {+ const docs = {+ name: 'Grid',+ description: 'A grid.',+ props: [+ {+ name: 'gap',+ type: '0 | 0.5 | 1 | 1.5 | 2 | 3 | 4 | 5 | 6 | 8 | 10',+ default: '2',+ description: 'Spacing between all items.',+ },+ ],+ };+ const row = formatFull(docs)+ .split('\n')+ .find(l => l.startsWith('| `gap`'));++ // A 4-column row has exactly 5 separators. Unescaped, this row had 15.+ expect(cellPipes(row)).toBe(5);+ expect(row).toContain('\\|');+ // The columns the unescaped pipes were swallowing.+ expect(row).toContain('`2`');+ expect(row).toContain('Spacing between all items.');+ });++ it('escapes pipes in a description too', () => {+ const docs = {+ name: 'AppShell',+ description: 'A shell.',+ props: [+ {+ name: 'mobileNav',+ type: 'ReactNode',+ description: "Config. breakpoint is 'sm' | 'md' | 'lg' | 'none'.",+ },+ ],+ };+ const row = formatFull(docs)+ .split('\n')+ .find(l => l.startsWith('| `mobileNav`'));++ expect(cellPipes(row)).toBe(5);+ });+});++describe('formatBrief signature stays terse', () => {+ // `--detail brief` exists to be token-cheap. It hoists union-typed props into+ // the signature because a short enum reads at a glance — but an 11-member+ // spacing scale does not, and Stack carries four of them (gap, padding,+ // paddingInline, paddingBlock), so the same scale got printed four times.+ // Long unions stay in the terse prop list, exactly as they did when the type+ // was still the bare name `SpacingStep`.+ it('hoists a short enum but not a long scale', () => {+ const docs = {+ name: 'HStack',+ description: 'A stack.',+ props: [+ {+ name: 'gap',+ type: '0 | 0.5 | 1 | 1.5 | 2 | 3 | 4 | 5 | 6 | 8 | 10',+ description: 'Gap.',+ },+ {name: 'wrap', type: "'nowrap' | 'wrap' | 'wrap-reverse'", description: 'Wrap.'},+ {+ name: 'hAlign',+ type: "'start' | 'center' | 'end' | 'between' | 'around' | 'evenly'",+ description: 'Align.',+ },+ ],+ };+ const signature = formatBrief(docs, 'HStack', '').split('\n')[0];++ // Short enums still earn their place in the signature.+ expect(signature).toContain('wrap: nowrap|wrap|wrap-reverse');+ expect(signature).toContain('hAlign: start|center|end|between|around|evenly');+ // The long scale does not.+ expect(signature).not.toContain('0|0.5|1|1.5|2|3|4|5|6|8|10');+ // But the prop is still named, so it is not lost.+ expect(formatBrief(docs, 'HStack', '')).toContain('gap');+ });+});diff --git a/packages/cli/src/lib/hook-format.mjs b/packages/cli/src/lib/hook-format.mjsindex 45e37de152..d13b87d688 100644--- a/packages/cli/src/lib/hook-format.mjs+++ b/packages/cli/src/lib/hook-format.mjs@@ -11,6 +11,7 @@import {discoverHooks, findHookDoc} from './hook-discovery.mjs';import {loadDocs} from './component-loader.mjs';+import {mdCell} from './component-format.mjs';/*** Build a signature string from hook docs.@@ -51,9 +52,11 @@ function formatParamsTable(params) {lines.push('| Param | Type | Default | Description |');lines.push('|-------|------|---------|-------------|');for (const p of params) {- const def = p.default ? `\`${p.default}\`` : '\u2014';+ const def = p.default ? `\`${mdCell(p.default)}\`` : '\u2014';const req = p.required ? ' **(required)**' : '';- lines.push(`| \`${p.name}\` | \`${p.type}\` | ${def} | ${p.description}${req} |`);+ lines.push(+ `| \`${mdCell(p.name)}\` | \`${mdCell(p.type)}\` | ${def} | ${mdCell(p.description)}${req} |`,+ );}return lines.join('\n');}@@ -67,7 +70,9 @@ function formatReturnsTable(returns) {lines.push('| Field | Type | Description |');lines.push('|-------|------|-------------|');for (const r of returns) {- lines.push(`| \`${r.name}\` | \`${r.type}\` | ${r.description} |`);+ lines.push(+ `| \`${mdCell(r.name)}\` | \`${mdCell(r.type)}\` | ${mdCell(r.description)} |`,+ );}return lines.join('\n');}diff --git a/packages/core/src/AppShell/AppShell.doc.mjs b/packages/core/src/AppShell/AppShell.doc.mjsindex 388a27f57c..e71788cbd7 100644--- a/packages/core/src/AppShell/AppShell.doc.mjs+++ b/packages/core/src/AppShell/AppShell.doc.mjs@@ -45,9 +45,15 @@ export const docs = {},{name: 'mobileNav',+ // Kept as the bare `ReactNode`, not widened to the true+ // `false | MobileNavConfig | ReactNode`: the docsite playground hides a+ // prop by exact-matching the type string against UNSUPPORTED_PROP_TYPES,+ // and widening drops that match. This prop's slotElements happen to hide+ // it a second way today, but the hide should not rest on that+ // coincidence. The legal values live in the description instead (#1645).type: 'ReactNode',description:- 'Mobile navigation configuration. Accepts false (disable), config object (tune auto behavior), or ReactNode (full custom drawer).',+ "Mobile navigation configuration. Accepts false (disable), a config object (tune auto behavior), or ReactNode (full custom drawer). The config object is {hasToggle?: boolean, isOpen?: boolean, onOpenChange?: (isOpen: boolean) => void, content?: ReactNode, breakpoint?: 'sm' | 'md' | 'lg' | 'none', defaultIsMobile?: boolean}; breakpoint defaults to 'md'.",slotElements: [{__element: 'MobileNav', props: {}}],},{@@ -139,7 +145,7 @@ export const docsZh = {},{name: 'topNav', type: 'ReactNode', description: '顶部导航插槽,通常为 TopNav。'},{name: 'sideNav', type: 'ReactNode', description: '侧边导航插槽,通常为 SideNav。'},- {name: 'mobileNav', type: 'ReactNode', description: '移动端导航配置。接受 false(禁用)、配置对象(调整自动行为)或 ReactNode(完全自定义抽屉)。'},+ {name: 'mobileNav', type: 'ReactNode', description: "移动端导航配置。接受 false(禁用)、配置对象(调整自动行为)或 ReactNode(完全自定义抽屉)。配置对象为 {hasToggle?, isOpen?, onOpenChange?, content?, breakpoint?: 'sm' | 'md' | 'lg' | 'none', defaultIsMobile?};breakpoint 默认为 'md'。"},{name: 'banner', type: 'ReactNode', description: '横幅插槽,用于全局公告,放置在 topNav 上方。'},{name: 'height',diff --git a/packages/core/src/Card/Card.doc.mjs b/packages/core/src/Card/Card.doc.mjsindex f3fee77eed..c4f2fc39c2 100644--- a/packages/core/src/Card/Card.doc.mjs+++ b/packages/core/src/Card/Card.doc.mjs@@ -62,9 +62,9 @@ export const docs = {},{name: 'variant',- type: "'default' | 'muted' | 'blue' | 'cyan' | 'gray' | 'green' | 'orange' | 'pink' | 'purple' | 'red' | 'teal' | 'yellow'",+ type: "'default' | 'transparent' | 'muted' | 'blue' | 'cyan' | 'gray' | 'green' | 'orange' | 'pink' | 'purple' | 'red' | 'teal' | 'yellow'",description:- 'Background color variant. `default` uses the standard card background. `muted` uses the muted background for de-emphasised cards. The non-semantic variants use the corresponding `--color-<name>-background` token.',+ 'Background color variant. `default` uses the standard card background. `transparent` drops the background entirely. `muted` uses the muted background for de-emphasised cards. The non-semantic variants use the corresponding `--color-background-<name>` token.',default: "'default'",},],@@ -169,6 +169,6 @@ export const docsDense = {minHeight: 'min card height',children: 'content inside card',padding: 'internal padding via spacing scale',- variant: 'background color variant; `default` = standard card bg, `muted` = muted bg for de-emphasised cards; non-semantic variants use the corresponding `--color-<name>-background` token',+ variant: 'background color variant; `default` = standard card bg, `transparent` = no background at all, `muted` = muted bg for de-emphasised cards; non-semantic variants use the corresponding `--color-background-<name>` token',},};diff --git a/packages/core/src/Chat/ChatMessageList.doc.mjs b/packages/core/src/Chat/ChatMessageList.doc.mjsindex 8cbb18e229..02766f0317 100644--- a/packages/core/src/Chat/ChatMessageList.doc.mjs+++ b/packages/core/src/Chat/ChatMessageList.doc.mjs@@ -42,7 +42,7 @@ export const docs = {},{name: 'gap',- type: 'SpacingStep',+ type: '0 | 0.5 | 1 | 1.5 | 2 | 3 | 4 | 5 | 6 | 8 | 10',description: 'Gap between top-level message rows. Defaults to the selected density; override for LLM event streams or independent rows that need different spacing from density.',},{diff --git a/packages/core/src/Chat/ChatToolCalls.doc.mjs b/packages/core/src/Chat/ChatToolCalls.doc.mjsindex 2424ac8b63..0f63cc33da 100644--- a/packages/core/src/Chat/ChatToolCalls.doc.mjs+++ b/packages/core/src/Chat/ChatToolCalls.doc.mjs@@ -38,7 +38,7 @@ export const docs = {name: 'calls',type: 'ChatToolCallItem[]',description:- 'Array of tool call data. Each item has name, status, target, duration, node, additions, deletions, stats, errorMessage, resultDetail, key, and data.',+ "Array of tool call data. Each item has name, status, target, duration, node, additions, deletions, stats, errorMessage, resultDetail, key, and data. status is one of 'pending', 'running', 'complete', or 'error' (defaults to 'complete').",required: true,},{diff --git a/packages/core/src/CheckboxList/CheckboxList.doc.mjs b/packages/core/src/CheckboxList/CheckboxList.doc.mjsindex 950171170e..f5a7ddf4c9 100644--- a/packages/core/src/CheckboxList/CheckboxList.doc.mjs+++ b/packages/core/src/CheckboxList/CheckboxList.doc.mjs@@ -85,7 +85,7 @@ export const docs = {},{name: 'status',- type: 'InputStatus',+ type: "{type: 'warning' | 'error' | 'success', message?: string}",description: 'Status indicator ({ type, message }).',},{diff --git a/packages/core/src/ClickableCard/ClickableCard.doc.mjs b/packages/core/src/ClickableCard/ClickableCard.doc.mjsindex 9bdde0dc09..0cc92aec7b 100644--- a/packages/core/src/ClickableCard/ClickableCard.doc.mjs+++ b/packages/core/src/ClickableCard/ClickableCard.doc.mjs@@ -26,7 +26,7 @@ export const docs = {{name: 'target', type: 'string', description: 'Link target.', default: "'_self'"},{name: 'isDisabled', type: 'boolean', description: 'Disables the card.', default: 'false'},{name: 'children', type: 'ReactNode', description: 'Card content.'},- {name: 'padding', type: "SpacingStep", description: 'Inner padding.', default: '4'},+ {name: 'padding', type: '0 | 0.5 | 1 | 1.5 | 2 | 3 | 4 | 5 | 6 | 8 | 10', description: 'Inner padding.', default: '4'},{name: 'variant', type: "'default' | 'transparent' | 'muted' | 'blue' | 'cyan' | 'gray' | 'green' | 'orange' | 'pink' | 'purple' | 'red' | 'teal' | 'yellow'", description: 'Background color variant.', default: "'default'"},{name: 'width', type: 'SizeValue', description: 'Card width.'},{name: 'height', type: 'SizeValue', description: 'Card height.'},diff --git a/packages/core/src/DateInput/DateInput.doc.mjs b/packages/core/src/DateInput/DateInput.doc.mjsindex dd2fdbbc38..fdab1deecf 100644--- a/packages/core/src/DateInput/DateInput.doc.mjs+++ b/packages/core/src/DateInput/DateInput.doc.mjs@@ -111,7 +111,7 @@ export const docs = {},{name: 'status',- type: 'InputStatus',+ type: "{type: 'warning' | 'error' | 'success', message?: string}",description:'Status indicator object for error, warning, or success states with a message.',},@@ -374,7 +374,7 @@ export const docsZh = {},{name: 'status',- type: 'InputStatus',+ type: "{type: 'warning' | 'error' | 'success', message?: string}",description: '错误、警告或成功状态的状态指示对象,附带消息。',},{diff --git a/packages/core/src/DateRangeInput/DateRangeInput.doc.mjs b/packages/core/src/DateRangeInput/DateRangeInput.doc.mjsindex 75865168d4..b9822b0794 100644--- a/packages/core/src/DateRangeInput/DateRangeInput.doc.mjs+++ b/packages/core/src/DateRangeInput/DateRangeInput.doc.mjs@@ -124,7 +124,7 @@ export const docs = {},{name: 'status',- type: 'InputStatus',+ type: "{type: 'warning' | 'error' | 'success', message?: string}",description: 'Status indicator for error, warning, or success states.',},{diff --git a/packages/core/src/DateTimeInput/DateTimeInput.doc.mjs b/packages/core/src/DateTimeInput/DateTimeInput.doc.mjsindex 585434a969..cf8992d0ca 100644--- a/packages/core/src/DateTimeInput/DateTimeInput.doc.mjs+++ b/packages/core/src/DateTimeInput/DateTimeInput.doc.mjs@@ -157,7 +157,7 @@ export const docs = {},{name: 'status',- type: 'InputStatus',+ type: "{type: 'warning' | 'error' | 'success', message?: string}",description:'Status indicator object for error, warning, or success states with a message.',},@@ -449,7 +449,7 @@ export const docsZh = {},{name: 'status',- type: 'InputStatus',+ type: "{type: 'warning' | 'error' | 'success', message?: string}",description: '错误、警告或成功状态的状态指示对象,附带消息。',},{diff --git a/packages/core/src/Field/Field.doc.mjs b/packages/core/src/Field/Field.doc.mjsindex d95d9ae40b..024072c0a7 100644--- a/packages/core/src/Field/Field.doc.mjs+++ b/packages/core/src/Field/Field.doc.mjs@@ -104,8 +104,8 @@ export const docs = {},{name: 'status',- type: 'FieldStatus',- description: 'Status indicator with type and optional message. When message is set, displays a colored status box.',+ type: "{type: 'warning' | 'error' | 'success', message?: string, messageID?: string}",+ description: 'Status indicator with type and optional message. When message is set, displays a colored status box. messageID is for wiring aria-describedby on the input.',},{name: 'statusVariant',diff --git a/packages/core/src/Grid/Grid.doc.mjs b/packages/core/src/Grid/Grid.doc.mjsindex 4ecadaaf9b..53cc7e36ab 100644--- a/packages/core/src/Grid/Grid.doc.mjs+++ b/packages/core/src/Grid/Grid.doc.mjs@@ -60,28 +60,28 @@ export const docs = {},{name: 'gap',- type: 'SpacingStep',+ type: '0 | 0.5 | 1 | 1.5 | 2 | 3 | 4 | 5 | 6 | 8 | 10',description: 'Spacing between all items.',},{name: 'rowGap',- type: 'SpacingStep',+ type: '0 | 0.5 | 1 | 1.5 | 2 | 3 | 4 | 5 | 6 | 8 | 10',description: 'Row spacing; overrides `gap` for the row axis.',},{name: 'columnGap',- type: 'SpacingStep',+ type: '0 | 0.5 | 1 | 1.5 | 2 | 3 | 4 | 5 | 6 | 8 | 10',description: 'Column spacing; overrides `gap` for the column axis.',},{name: 'align',- type: 'GridAlignment',+ type: "'start' | 'center' | 'end' | 'stretch'",description: 'Vertical alignment of items.',default: "'stretch'",},{name: 'justify',- type: 'GridAlignment',+ type: "'start' | 'center' | 'end' | 'stretch'",description: 'Horizontal alignment of items.',default: "'stretch'",},diff --git a/packages/core/src/InputGroup/InputGroup.doc.mjs b/packages/core/src/InputGroup/InputGroup.doc.mjsindex 91150921ae..d7085b45df 100644--- a/packages/core/src/InputGroup/InputGroup.doc.mjs+++ b/packages/core/src/InputGroup/InputGroup.doc.mjs@@ -76,7 +76,7 @@ export const docs = {},{name: 'status',- type: 'InputStatus',+ type: "{type: 'warning' | 'error' | 'success', message?: string}",description: 'Status indicator applied to the group border.',},{diff --git a/packages/core/src/Lightbox/Lightbox.doc.mjs b/packages/core/src/Lightbox/Lightbox.doc.mjsindex 8518b7277f..95f22bb4e3 100644--- a/packages/core/src/Lightbox/Lightbox.doc.mjs+++ b/packages/core/src/Lightbox/Lightbox.doc.mjs@@ -22,8 +22,13 @@ export const docs = {},{name: 'media',+ // Left as the named type on purpose: the shape carries `caption?:+ // ReactNode`, so spelling it out makes the docsite playground parse the+ // whole prop as an editable *string*, which would feed the preview text+ // where a media object belongs. The shape and its legal values live in+ // the description instead (#1645).type: 'LightboxMedia | LightboxMedia[]',- description: 'Media to display. Pass a single object for one item, or an array for gallery mode with prev/next navigation. Each item has src, alt, optional caption and type.',+ description: "Media to display. Pass a single object for one item, or an array for gallery mode with prev/next navigation. Each item is {src: string, alt: string, caption?: ReactNode, type?: 'image' | 'video'}; type defaults to 'image', and zoom/pan is disabled for 'video'.",required: true,},{@@ -100,7 +105,7 @@ export const docsZh = {{name: 'media',type: 'LightboxMedia | LightboxMedia[]',- description: '要显示的媒体。传入单个对象或数组(用于画廊模式的上一张/下一张导航)。',+ description: "要显示的媒体。传入单个对象或数组(用于画廊模式的上一张/下一张导航)。每项为 {src, alt, caption?, type?: 'image' | 'video'};type 默认为 'image','video' 禁用缩放/平移。",required: true,},{diff --git a/packages/core/src/OverflowList/OverflowList.doc.mjs b/packages/core/src/OverflowList/OverflowList.doc.mjsindex 54949253a4..368358f08a 100644--- a/packages/core/src/OverflowList/OverflowList.doc.mjs+++ b/packages/core/src/OverflowList/OverflowList.doc.mjs@@ -50,7 +50,7 @@ export const docs = {},{name: 'gap',- type: 'SpacingStep',+ type: '0 | 0.5 | 1 | 1.5 | 2 | 3 | 4 | 5 | 6 | 8 | 10',description:'Gap between items as a spacing token step (0, 0.5, 1, 1.5, 2, 3, 4, 5, 6, 8, 10).',default: '2',@@ -116,7 +116,7 @@ export const docsZh = {},{name: 'gap',- type: 'SpacingStep',+ type: '0 | 0.5 | 1 | 1.5 | 2 | 3 | 4 | 5 | 6 | 8 | 10',description:'项目间距,使用间距步进值(0、0.5、1、1.5、2、3、4、5、6、8、10)。',default: '2',diff --git a/packages/core/src/PowerSearch/PowerSearch.doc.mjs b/packages/core/src/PowerSearch/PowerSearch.doc.mjsindex 93d4e6a55f..5f9d388713 100644--- a/packages/core/src/PowerSearch/PowerSearch.doc.mjs+++ b/packages/core/src/PowerSearch/PowerSearch.doc.mjs@@ -23,7 +23,7 @@ export const docs = {},{name: 'onChange',- type: '(filters: ReadonlyArray<PowerSearchFilter>, changeType: PowerSearchChangeType, index: number) => void',+ type: "(filters: ReadonlyArray<PowerSearchFilter>, changeType: 'add' | 'edit' | 'remove', index: number) => void",description:"Called when filters change. changeType is 'add', 'edit', or 'remove'. index is the affected filter's position.",required: true,@@ -79,7 +79,7 @@ export const docs = {},{name: 'status',- type: 'InputStatus',+ type: "{type: 'warning' | 'error' | 'success', message?: string}",description:'Validation status object with type and optional message.',},@@ -177,7 +177,7 @@ export const docsZh = {},{name: 'onChange',- type: '(filters: ReadonlyArray<PowerSearchFilter>, changeType: PowerSearchChangeType, index: number) => void',+ type: "(filters: ReadonlyArray<PowerSearchFilter>, changeType: 'add' | 'edit' | 'remove', index: number) => void",description:"当过滤器变更时调用。changeType 为 'add'、'edit' 或 'remove'。index 为受影响的过滤器位置。",required: true,@@ -232,7 +232,7 @@ export const docsZh = {},{name: 'status',- type: 'InputStatus',+ type: "{type: 'warning' | 'error' | 'success', message?: string}",description: '带有类型和可选消息的验证状态对象。',},{diff --git a/packages/core/src/RadioList/RadioList.doc.mjs b/packages/core/src/RadioList/RadioList.doc.mjsindex fda0445a61..c49f9160a7 100644--- a/packages/core/src/RadioList/RadioList.doc.mjs+++ b/packages/core/src/RadioList/RadioList.doc.mjs@@ -100,7 +100,7 @@ export const docs = {},{name: 'status',- type: 'InputStatus',+ type: "{type: 'warning' | 'error' | 'success', message?: string}",description: 'Status indicator ({ type, message }).',},{diff --git a/packages/core/src/Section/Section.doc.mjs b/packages/core/src/Section/Section.doc.mjsindex 91706c9643..9b171a8881 100644--- a/packages/core/src/Section/Section.doc.mjs+++ b/packages/core/src/Section/Section.doc.mjs@@ -49,13 +49,13 @@ export const docs = {},{name: 'padding',- type: 'SpacingStep',+ type: '0 | 0.5 | 1 | 1.5 | 2 | 3 | 4 | 5 | 6 | 8 | 10',description: 'Internal padding using the spacing scale (0, 0.5, 1, 1.5, 2, 3, 4, 5, 6, 8, 10). Use padding={0} for edge-to-edge content.',default: '4',},{name: 'paddingBlock',- type: 'SpacingStep',+ type: '0 | 0.5 | 1 | 1.5 | 2 | 3 | 4 | 5 | 6 | 8 | 10',description: 'Block (vertical) padding override. Overrides only the block-axis padding while preserving inline padding from `padding` or the container theme default. Accepts the spacing scale (0, 0.5, 1, 1.5, 2, 3, 4, 5, 6, 8, 10).',},{@@ -131,13 +131,13 @@ export const docsZh = {},{name: 'padding',- type: 'SpacingStep',+ type: '0 | 0.5 | 1 | 1.5 | 2 | 3 | 4 | 5 | 6 | 8 | 10',description: '使用间距比例的内部内边距(0, 0.5, 1, 1.5, 2, 3, 4, 5, 6, 8, 10)。使用 padding={0} 实现全宽内容。',default: '4',},{name: 'paddingBlock',- type: 'SpacingStep',+ type: '0 | 0.5 | 1 | 1.5 | 2 | 3 | 4 | 5 | 6 | 8 | 10',description: '块(垂直)方向内边距覆盖。仅覆盖块轴内边距,同时保留来自 padding 或容器主题默认值的行内内边距。使用间距比例(0, 0.5, 1, 1.5, 2, 3, 4, 5, 6, 8, 10)。',},{diff --git a/packages/core/src/SelectableCard/SelectableCard.doc.mjs b/packages/core/src/SelectableCard/SelectableCard.doc.mjsindex 9ca0d8c725..5978e6ca55 100644--- a/packages/core/src/SelectableCard/SelectableCard.doc.mjs+++ b/packages/core/src/SelectableCard/SelectableCard.doc.mjs@@ -25,7 +25,7 @@ export const docs = {{name: 'onChange', type: '(isSelected: boolean) => void', description: 'Called when toggled.', required: true},{name: 'isDisabled', type: 'boolean', description: 'Disables the card.', default: 'false'},{name: 'children', type: 'ReactNode', description: 'Card content.'},- {name: 'padding', type: "SpacingStep", description: 'Inner padding.', default: '4'},+ {name: 'padding', type: '0 | 0.5 | 1 | 1.5 | 2 | 3 | 4 | 5 | 6 | 8 | 10', description: 'Inner padding.', default: '4'},{name: 'variant', type: "'default' | 'transparent' | 'muted' | 'blue' | 'cyan' | 'gray' | 'green' | 'orange' | 'pink' | 'purple' | 'red' | 'teal' | 'yellow'", description: 'Background color variant.', default: "'default'"},{name: 'width', type: 'SizeValue', description: 'Card width.'},{name: 'height', type: 'SizeValue', description: 'Card height.'},diff --git a/packages/core/src/Slider/Slider.doc.mjs b/packages/core/src/Slider/Slider.doc.mjsindex 52dcc78982..0aa701354e 100644--- a/packages/core/src/Slider/Slider.doc.mjs+++ b/packages/core/src/Slider/Slider.doc.mjs@@ -132,7 +132,7 @@ export const docs = {},{name: 'status',- type: 'InputStatus',+ type: "{type: 'warning' | 'error' | 'success', message?: string}",description:'Status indicator object (`{ type, message }`) for validation feedback.',},@@ -286,7 +286,7 @@ export const docsZh = {},{name: 'status',- type: 'InputStatus',+ type: "{type: 'warning' | 'error' | 'success', message?: string}",description:'验证反馈的状态指示器对象(`{ type, message }`)。',},diff --git a/packages/core/src/Stack/Stack.doc.mjs b/packages/core/src/Stack/Stack.doc.mjsindex 14a9f7eb9a..813478eec6 100644--- a/packages/core/src/Stack/Stack.doc.mjs+++ b/packages/core/src/Stack/Stack.doc.mjs@@ -24,25 +24,25 @@ export const docs = {props: [{name: 'gap',- type: 'SpacingStep',+ type: '0 | 0.5 | 1 | 1.5 | 2 | 3 | 4 | 5 | 6 | 8 | 10',description:'Spacing step (number literal): 0, 0.5, 1, 1.5, 2, 3, 4, 5, 6, 8, 10. Pass as a JSX number expression e.g. gap={4}, NOT a string like gap="4".',},{name: 'padding',- type: 'SpacingStep',+ type: '0 | 0.5 | 1 | 1.5 | 2 | 3 | 4 | 5 | 6 | 8 | 10',description:'Inner padding on all sides, using the spacing scale (0, 0.5, 1, 1.5, 2, 3, 4, 5, 6, 8, 10). Matches the padding prop on Card, LayoutContent, and LayoutPanel. Pass as a JSX number expression e.g. padding={3}.',},{name: 'paddingInline',- type: 'SpacingStep',+ type: '0 | 0.5 | 1 | 1.5 | 2 | 3 | 4 | 5 | 6 | 8 | 10',description:'Inline (horizontal) padding, using the spacing scale. Overrides padding on the inline axis when both are set.',},{name: 'paddingBlock',- type: 'SpacingStep',+ type: '0 | 0.5 | 1 | 1.5 | 2 | 3 | 4 | 5 | 6 | 8 | 10',description:'Block (vertical) padding, using the spacing scale. Overrides padding on the block axis when both are set.',},@@ -127,25 +127,25 @@ export const docs = {props: [{name: 'gap',- type: 'SpacingStep',+ type: '0 | 0.5 | 1 | 1.5 | 2 | 3 | 4 | 5 | 6 | 8 | 10',description:'Spacing step (number literal): 0, 0.5, 1, 1.5, 2, 3, 4, 5, 6, 8, 10. Pass as a JSX number expression e.g. gap={4}, NOT a string like gap="4".',},{name: 'padding',- type: 'SpacingStep',+ type: '0 | 0.5 | 1 | 1.5 | 2 | 3 | 4 | 5 | 6 | 8 | 10',description:'Inner padding on all sides, using the spacing scale (0, 0.5, 1, 1.5, 2, 3, 4, 5, 6, 8, 10). Matches the padding prop on Card, LayoutContent, and LayoutPanel. Pass as a JSX number expression e.g. padding={3}.',},{name: 'paddingInline',- type: 'SpacingStep',+ type: '0 | 0.5 | 1 | 1.5 | 2 | 3 | 4 | 5 | 6 | 8 | 10',description:'Inline (horizontal) padding, using the spacing scale. Overrides padding on the inline axis when both are set.',},{name: 'paddingBlock',- type: 'SpacingStep',+ type: '0 | 0.5 | 1 | 1.5 | 2 | 3 | 4 | 5 | 6 | 8 | 10',description:'Block (vertical) padding, using the spacing scale. Overrides padding on the block axis when both are set.',},@@ -289,7 +289,7 @@ export const docsZh = {props: [{name: 'gap',- type: 'SpacingStep',+ type: '0 | 0.5 | 1 | 1.5 | 2 | 3 | 4 | 5 | 6 | 8 | 10',description:'间距步进(数字字面量):0、0.5、1、1.5、2、3、4、5、6、8、10。在 JSX 中使用数字表达式 e.g. gap={4},不要使用字符串 gap="4"。',},@@ -358,7 +358,7 @@ export const docsZh = {props: [{name: 'gap',- type: 'SpacingStep',+ type: '0 | 0.5 | 1 | 1.5 | 2 | 3 | 4 | 5 | 6 | 8 | 10',description:'间距步进(数字字面量):0、0.5、1、1.5、2、3、4、5、6、8、10。在 JSX 中使用数字表达式 e.g. gap={4},不要使用字符串 gap="4"。',},diff --git a/packages/core/src/Switch/Switch.doc.mjs b/packages/core/src/Switch/Switch.doc.mjsindex 3ff5649ec1..f005a32f31 100644--- a/packages/core/src/Switch/Switch.doc.mjs+++ b/packages/core/src/Switch/Switch.doc.mjs@@ -90,7 +90,7 @@ export const docs = {},{name: 'status',- type: 'InputStatus',+ type: "{type: 'warning' | 'error' | 'success', message?: string}",description:'Status indicator with type and message. Displays a colored message box below the switch and sets aria-invalid when type is "error".',},@@ -236,7 +236,7 @@ export const docsZh = {},{name: 'status',- type: 'InputStatus',+ type: "{type: 'warning' | 'error' | 'success', message?: string}",description:'带类型和消息的状态指示器。在开关下方显示彩色消息框,当类型为 "error" 时设置 aria-invalid。',},diff --git a/packages/core/src/Table/useTableFiltering.doc.mjs b/packages/core/src/Table/useTableFiltering.doc.mjsindex cefea0f682..640f6599cc 100644--- a/packages/core/src/Table/useTableFiltering.doc.mjs+++ b/packages/core/src/Table/useTableFiltering.doc.mjs@@ -23,7 +23,7 @@ export const docs = {},{name: 'variant',- type: "'popover' | 'inline'",+ type: "'popover' | 'inline' | 'inline-compact'",description: 'Display variant for filter controls.',default: "'popover'",},@@ -50,7 +50,7 @@ export const docsZh = {},{name: 'variant',- type: "'popover' | 'inline'",+ type: "'popover' | 'inline' | 'inline-compact'",description: '筛选控件的显示变体。',default: "'popover'",},diff --git a/packages/core/src/Table/useTableSortable.doc.mjs b/packages/core/src/Table/useTableSortable.doc.mjsindex b310905e15..04cd4fceed 100644--- a/packages/core/src/Table/useTableSortable.doc.mjs+++ b/packages/core/src/Table/useTableSortable.doc.mjs@@ -13,20 +13,20 @@ export const docs = {props: [{name: 'sort',- type: 'TableSortState<TSortKey>',- description: 'Current sort state. Ordered array of {sortKey, direction} entries. First entry is the primary sort.',+ type: "Array<{sortKey: TSortKey, direction: 'ascending' | 'descending'}>",+ description: "Current sort state (TableSortState<TSortKey>). Ordered array of entries; the first is the primary sort, the rest are tiebreakers. An empty array means unsorted. Direction is the full word — 'ascending' / 'descending', not 'asc' / 'desc'.",required: true,},{name: 'onSortChange',- type: '(sort: TableSortState<TSortKey>) => void',- description: 'Called when the user clicks a header cell to change sort.',+ type: "(sort: Array<{sortKey: TSortKey, direction: 'ascending' | 'descending'}>) => void",+ description: 'Called when the user clicks a header cell to change sort. Receives the next sort state.',required: true,},{name: 'allowUnsortedState',type: 'boolean',- description: 'Allow cycling back to unsorted. When true: asc, desc, unsorted. When false: asc, desc, asc.',+ description: "Allow cycling back to unsorted. When true: 'ascending', 'descending', unsorted. When false: 'ascending', 'descending', 'ascending'.",default: 'false',},{@@ -45,20 +45,20 @@ export const docsZh = {props: [{name: 'sort',- type: 'TableSortState<TSortKey>',- description: '当前排序状态。{sortKey, direction} 条目的有序数组。第一个条目是主排序。',+ type: "Array<{sortKey: TSortKey, direction: 'ascending' | 'descending'}>",+ description: "当前排序状态。{sortKey, direction} 条目的有序数组。第一个条目是主排序。方向值为完整单词 'ascending' / 'descending',不是 'asc' / 'desc'。",required: true,},{name: 'onSortChange',- type: '(sort: TableSortState<TSortKey>) => void',+ type: "(sort: Array<{sortKey: TSortKey, direction: 'ascending' | 'descending'}>) => void",description: '用户点击表头单元格更改排序时调用。',required: true,},{name: 'allowUnsortedState',type: 'boolean',- description: '允许循环回到未排序状态。为 true 时:升序、降序、未排序。为 false 时:升序、降序、升序。',+ description: "允许循环回到未排序状态。为 true 时:'ascending'、'descending'、未排序。为 false 时:'ascending'、'descending'、'ascending'。",default: 'false',},{@@ -75,9 +75,9 @@ export const docsDense = {displayName: 'useTableSortable',description: 'Headless multi-sort plugin. Consumer owns sort state + callback. Shift+click for secondary sort. Sort indicators auto-render in header cells.',propDescriptions: {- sort: 'Current sort state; ordered array of {sortKey, direction} entries.',+ sort: "Current sort state; ordered array of {sortKey, direction: 'ascending'|'descending'} entries. Not 'asc'/'desc'.",onSortChange: 'Called on header click to change sort.',- allowUnsortedState: 'Allow cycling to unsorted. true: asc>desc>unsorted. false: asc>desc>asc.',+ allowUnsortedState: "Allow cycling to unsorted. true: ascending>descending>unsorted. false: ascending>descending>ascending.",isMultiSortEnabled: 'Enable multi-sort via Shift+click. Regular click replaces sort state.',},};diff --git a/packages/core/src/Text/Text.doc.mjs b/packages/core/src/Text/Text.doc.mjsindex e4714d98f8..91e356aec9 100644--- a/packages/core/src/Text/Text.doc.mjs+++ b/packages/core/src/Text/Text.doc.mjs@@ -23,8 +23,8 @@ export const docs = {props: [{name: 'type',- type: "'body' | 'large' | 'label' | 'supporting' | 'code' | 'display-1' | 'display-2' | 'display-3'",- description: 'Semantic text type. Determines size, weight, and line-height from the theme. Note: this prop is called `type`, not `variant`.',+ type: "'body' | 'large' | 'label' | 'supporting' | 'code' | 'display-1' | 'display-2' | 'display-3' | 'inherit'",+ description: "Semantic text type. Determines size, weight, and line-height from the theme. 'inherit' takes all three from the surrounding text instead. Themes may add custom types. Note: this prop is called `type`, not `variant`.",default: "'body'",},{diff --git a/packages/core/src/TimeInput/TimeInput.doc.mjs b/packages/core/src/TimeInput/TimeInput.doc.mjsindex b385aa7ed0..5f7c91b534 100644--- a/packages/core/src/TimeInput/TimeInput.doc.mjs+++ b/packages/core/src/TimeInput/TimeInput.doc.mjs@@ -225,7 +225,7 @@ export const docs = {},{name: 'status',- type: 'InputStatus',+ type: "{type: 'warning' | 'error' | 'success', message?: string}",description:'Status indicator that colors the border and displays an icon. When a message is provided it is rendered below the input.',},@@ -368,7 +368,7 @@ export const docsZh = {},{name: 'status',- type: 'InputStatus',+ type: "{type: 'warning' | 'error' | 'success', message?: string}",description:'为边框着色并显示图标的状态指示器。当提供消息时,消息渲染在输入框下方。',},diff --git a/packages/core/src/Timestamp/Timestamp.doc.mjs b/packages/core/src/Timestamp/Timestamp.doc.mjsindex 4663840e77..025d03ad81 100644--- a/packages/core/src/Timestamp/Timestamp.doc.mjs+++ b/packages/core/src/Timestamp/Timestamp.doc.mjs@@ -61,24 +61,24 @@ export const docs = {},{name: 'type',- type: 'TextType',+ type: "'body' | 'large' | 'label' | 'supporting' | 'code' | 'display-1' | 'display-2' | 'display-3' | 'inherit'",description: 'Semantic text type from Text. Determines size, weight, and line-height.',default: "'supporting'",},{name: 'size',- type: 'TextSize',+ type: "'4xs' | '3xs' | '2xs' | 'xsm' | 'sm' | 'base' | 'lg' | 'xl' | '2xl' | '3xl' | '4xl'",description: 'Explicit font size override. Overrides the size from type.',},{name: 'color',- type: 'TextColor',+ type: "'primary' | 'secondary' | 'disabled' | 'placeholder' | 'accent' | 'inherit'",description: 'Text color.',default: "'secondary'",},{name: 'weight',- type: 'TextWeight',+ type: "'normal' | 'medium' | 'semibold' | 'bold'",description: 'Font weight override.',},],diff --git a/packages/core/src/Tokenizer/Tokenizer.doc.mjs b/packages/core/src/Tokenizer/Tokenizer.doc.mjsindex a6a73d5540..4d6bfbe254 100644--- a/packages/core/src/Tokenizer/Tokenizer.doc.mjs+++ b/packages/core/src/Tokenizer/Tokenizer.doc.mjs@@ -84,7 +84,7 @@ export const docs = {},{name: 'status',- type: 'InputStatus',+ type: "{type: 'warning' | 'error' | 'success', message?: string}",description:'Validation status object with type and message for error/warning/success states.',},@@ -296,7 +296,7 @@ export const docsZh = {},{name: 'status',- type: 'InputStatus',+ type: "{type: 'warning' | 'error' | 'success', message?: string}",description:'\u9a8c\u8bc1\u72b6\u6001\u5bf9\u8c61\uff0c\u5305\u542b\u7c7b\u578b\u548c\u6d88\u606f\uff0c\u7528\u4e8e\u9519\u8bef/\u8b66\u544a/\u6210\u529f\u72b6\u6001\u3002',},diff --git a/packages/core/src/Toolbar/Toolbar.doc.mjs b/packages/core/src/Toolbar/Toolbar.doc.mjsindex 3a3c713287..3e82b2e230 100644--- a/packages/core/src/Toolbar/Toolbar.doc.mjs+++ b/packages/core/src/Toolbar/Toolbar.doc.mjs@@ -116,7 +116,7 @@ export const docs = {},{name: 'gap',- type: 'SpacingStep',+ type: '0 | 0.5 | 1 | 1.5 | 2 | 3 | 4 | 5 | 6 | 8 | 10',description: 'Gap between items within each slot.',default: '1',},diff --git a/packages/core/src/Typeahead/Typeahead.doc.mjs b/packages/core/src/Typeahead/Typeahead.doc.mjsindex f69d3395f1..9b241cbe93 100644--- a/packages/core/src/Typeahead/Typeahead.doc.mjs+++ b/packages/core/src/Typeahead/Typeahead.doc.mjs@@ -85,7 +85,7 @@ export const docs = {},{name: 'status',- type: 'InputStatus',+ type: "{type: 'warning' | 'error' | 'success', message?: string}",description:'Validation status object with type and message for error/warning/success states.',},diff --git a/packages/core/src/docPropLiterals.test.ts b/packages/core/src/docPropLiterals.test.tsnew file mode 100644index 0000000000..8f88380be4--- /dev/null+++ b/packages/core/src/docPropLiterals.test.ts@@ -0,0 +1,902 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/* eslint-disable @typescript-eslint/no-require-imports */+/**+ * @file Guards doc prop types against opaque named unions (#1645).+ * @input Every {Name}.doc.mjs plus the TypeScript sources they describe.+ * @output Fails when a documented prop type hides its legal literal values.+ * @position Repo-wide doc-shape guard, sibling of docPropReferences.test.ts.+ *+ * A prop type of `SpacingStep` or `TableSortState<TSortKey>` names a type+ * without revealing what may be written into it. Readers without an IDE —+ * agents especially — then guess: `gap={16}` (pixels, not a scale step),+ * `direction: 'desc'` (the type says `'descending'`). Both fail to compile.+ * `PropDoc.type` in docs-types.ts already asks for inlined unions+ * (`"'primary' | 'secondary' | 'ghost'"`); this test holds docs to it.+ *+ * Two ways a doc prop can hide values, checked at different strictness:+ *+ * 1. DIRECT — the prop type *is* (or contains) a literal-union type name.+ * `gap: SpacingStep` must read `gap: 0 | 0.5 | 1 | …`. The name never+ * buys the reader anything the literals don't, so inlining is required;+ * prose is not an escape (see ENUMERATED_IN_PROSE for the one exception).+ *+ * 2. INDIRECT — the prop type names a composite whose own definition+ * carries a literal union: `status: InputStatus` hides+ * `'warning' | 'error' | 'success'`, `sort: TableSortState` hides+ * `direction: 'ascending' | 'descending'`. Here the values may be+ * surfaced in the type (spell the shape out — preferred when the object+ * is small) *or* in the description, because forcing a twelve-field+ * object into the type column would make the docs worse, not better.+ *+ * Both registries are derived from the TypeScript sources at test time, so a+ * new member on a union (or a renamed one) fails here until docs catch up.+ */++import {describe, it, expect} from 'vitest';+import {readdirSync, readFileSync} from 'node:fs';+import {join, relative} from 'node:path';++const SRC_DIR = __dirname;++type DocExport = {+ name?: string;+ props?: PropEntry[];+ components?: {name?: string; props?: PropEntry[]}[];+};++type DocModule = {+ docs?: DocExport;+ docsZh?: DocExport;+};++type PropEntry = {name: string; type?: string; description?: string};++/**+ * Unions too large to read inside a prop-type cell. Exempt from inlining,+ * but only while the prop's description enumerates every member — the+ * values still have to be discoverable from the docs alone.+ */+const ENUMERATED_IN_PROSE = new Set(['IconName']);++/**+ * Generic wrappers whose type argument is still a value the consumer writes,+ * so the walk descends through them. Every other generic (`ReactElement<P>`,+ * `Record<K, V>`, `Ref<T>`) wraps a type the consumer never spells out by+ * hand, and descending into it would demand, say, all 26 icon names in+ * Button's `endContent` docs.+ */+const TRANSPARENT_WRAPPERS = new Set(['Array', 'ReadonlyArray']);++/**+ * A union of nothing but string/number literals (plus null/undefined).+ *+ * Built so each separator has exactly ONE way to be parsed. The obvious+ * spelling — `(?:\s*\|?\s*LITERAL\s*(?:\|\s*)?)+` — lets a repetition's+ * trailing `(?:\|\s*)?` and the next one's leading `\|?` both claim the same+ * pipe, so every separator doubles the parse tree. On a union that *fails* to+ * match (a literal prefix ending in a named type, e.g. `'a' | 'b' | … |+ * ComponentType` — an ordinary TS pattern) the engine explores all 2^n of them:+ * measured at 1.2s for 10 members and 7.8s for 12. This form is linear, and+ * agrees with the old one on every type alias in the package.+ */+const LITERAL = String.raw`(?:'[^']*'|-?\d+(?:\.\d+)?|null|undefined)`;+const LITERAL_UNION = new RegExp(+ String.raw`^\s*\|?\s*${LITERAL}(?:\s*\|\s*${LITERAL})*\s*$`,+);++function findFiles(dir: string, suffixes: string[]): string[] {+ const out: string[] = [];+ for (const entry of readdirSync(dir, {withFileTypes: true})) {+ const full = join(dir, entry.name);+ if (entry.isDirectory()) {+ out.push(...findFiles(full, suffixes));+ } else if (suffixes.some(s => entry.name.endsWith(s))) {+ out.push(full);+ }+ }+ return out;+}++/** Strip comments so a doc block's prose never reads as type syntax. */+function stripComments(src: string): string {+ return src.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/.*$/gm, '');+}++/**+ * Names a consumer would have to write values for, given a type expression.+ * Skips string literals, generic parameters, and the type arguments of any+ * wrapper that isn't transparent.+ */+function authoredTypeNames(expr: string): string[] {+ const names: string[] = [];+ const text = expr.replace(/'[^']*'/g, "''");+ let i = 0;+ while (i < text.length) {+ const match = /[A-Za-z_$][A-Za-z0-9_$]*/.exec(text.slice(i));+ if (!match) {+ break;+ }+ const start = i + match.index;+ const name = match[0];+ let end = start + name.length;+ if (/^[A-Z]/.test(name)) {+ names.push(name);+ }+ // A '<' directly after the name opens that name's type arguments.+ const rest = text.slice(end);+ const open = /^\s*</.exec(rest);+ if (open) {+ let depth = 0;+ let j = end + open[0].length - 1;+ for (; j < text.length; j++) {+ if (text[j] === '<') {+ depth++;+ } else if (text[j] === '>') {+ depth--;+ if (depth === 0) {+ break;+ }+ }+ }+ const args = text.slice(end + open[0].length, j);+ if (TRANSPARENT_WRAPPERS.has(name)) {+ names.push(...authoredTypeNames(args));+ }+ end = j + 1;+ }+ i = end;+ }+ return names;+}++// --- Registries, read straight from the TypeScript sources -----------------++/** Literal-union type name → its members, e.g. "'start' | 'center'". */+const literalUnions = new Map<string, string>();+/** Every other exported type/interface name → its definition body. */+const namedBodies = new Map<string, string>();++for (const file of findFiles(SRC_DIR, ['.ts', '.tsx'])) {+ if (file.includes('.test.')) {+ continue;+ }+ const src = stripComments(readFileSync(file, 'utf8'));+ for (const m of src.matchAll(+ /export type ([A-Z][A-Za-z0-9]*)(?:<[^>]*>)?\s*=\s*([^;]+);/g,+ )) {+ const [, name, rhsRaw] = m;+ const rhs = rhsRaw.replace(/\s+/g, ' ').trim();+ if (LITERAL_UNION.test(rhs)) {+ literalUnions.set(+ name,+ rhs+ .replace(/^\|\s*/, '')+ .split('|')+ .map(s => s.trim())+ .filter(Boolean)+ .join(' | '),+ );+ } else {+ namedBodies.set(name, rhs);+ }+ }+ for (const m of src.matchAll(+ /export interface ([A-Z][A-Za-z0-9]*)(?:<[^>]*>)?\s*(?:extends [^{]+)?\{/g,+ )) {+ const open = src.indexOf('{', m.index);+ let depth = 0;+ let close = open;+ for (; close < src.length; close++) {+ if (src[close] === '{') {+ depth++;+ } else if (src[close] === '}') {+ depth--;+ if (depth === 0) {+ break;+ }+ }+ }+ namedBodies.set(m[1], src.slice(open, close + 1).replace(/\s+/g, ' '));+ }+}++/** Literal unions a consumer must know to author a value of `name`. */+function requiredUnions(+ name: string,+ seen = new Set<string>(),+): Map<string, string> {+ const found = new Map<string, string>();+ if (seen.has(name)) {+ return found;+ }+ seen.add(name);+ const literals = literalUnions.get(name);+ if (literals) {+ found.set(name, literals);+ return found;+ }+ const body = namedBodies.get(name);+ if (!body) {+ return found;+ }+ for (const inner of authoredTypeNames(body)) {+ for (const [k, v] of requiredUnions(inner, seen)) {+ found.set(k, v);+ }+ }+ return found;+}++// --- Source prop declarations, per component directory ---------------------++/**+ * "{dir}::{Component}Props" → prop name → the type expression source declares.+ *+ * Keyed by the exact prop bag, never by directory: Chat/ alone holds+ * ChatComposer, ChatMessage and ChatToolCalls, each with a differently-typed+ * `status`, and judging one component's docs against a sibling's declaration+ * is a false accusation. A component with no `{Name}Props` bag here (Heading+ * re-exports its props from elsewhere) is simply not checked by this pass —+ * a missed prop costs nothing, a wrong failure costs the guard its+ * credibility.+ */+const sourcePropTypes = new Map<string, Map<string, string>>();++/**+ * Bag name → its members, for bags whose name is unique across the package;+ * `null` marks a name declared in more than one place, which is never+ * resolved rather than resolved wrongly.+ *+ * A hook's config bag does not live in the directory its doc does:+ * `useTableSortable.doc.mjs` sits in `Table/`, but `UseTableSortableConfig`+ * is declared in `Table/plugins/sortable/`. Directory-keying alone therefore+ * cannot see it — which is why `sort`, the very prop #1645 was filed about,+ * had no source-side guard at all until this index existed.+ */+const bagsByName = new Map<string, Map<string, string> | null>();++/**+ * Bags a hook's config may be called. Astryx spells it `Use{Name}Config` or+ * `Use{Name}Options` (see UseTableSortableConfig, UsePopoverOptions); the+ * other two are cheap insurance and cost nothing when absent.+ */+const HOOK_BAG_SUFFIXES = ['Config', 'Options', 'Props', 'Params'];++for (const file of findFiles(SRC_DIR, ['.ts', '.tsx'])) {+ if (file.includes('.test.')) {+ continue;+ }+ const dir = file.slice(0, file.lastIndexOf('/'));+ const src = stripComments(readFileSync(file, 'utf8'));+ for (const m of src.matchAll(+ /export (?:interface|type) ([A-Z][A-Za-z0-9]*(?:Props|Config|Options|Params))(?:<[^>]*>)?\s*(?:extends [^{]+|=\s*)?\{/g,+ )) {+ const open = src.indexOf('{', m.index);+ let depth = 0;+ let close = open;+ for (; close < src.length; close++) {+ if (src[close] === '{') {+ depth++;+ } else if (src[close] === '}') {+ depth--;+ if (depth === 0) {+ break;+ }+ }+ }+ const body = src.slice(open + 1, close);+ const byProp = new Map<string, string>();+ // Top-level `name?: Type;` members only — nested object literals would+ // need a real parser, and a missed prop costs nothing here.+ let depthInBody = 0;+ for (const rawLine of body.split(/[;\n]/)) {+ // `=>` is an arrow, not a closing angle bracket: counting it as one+ // drives the depth negative and silently swallows every prop below a+ // callback member. (It did, until this line.)+ const line = rawLine.replace(/=>/g, '');+ const opens = (line.match(/[{(<]/g) || []).length;+ const closes = (line.match(/[})>]/g) || []).length;+ const member = /^\s*([a-z][A-Za-z0-9]*)\??\s*:\s*(.+?)\s*$/.exec(rawLine);+ if (depthInBody === 0 && member) {+ byProp.set(member[1], member[2]);+ }+ depthInBody = Math.max(0, depthInBody + opens - closes);+ }+ sourcePropTypes.set(`${dir}::${m[1]}`, byProp);+ // Second index, keyed by bag name alone, for the cross-directory hook+ // lookup below. A duplicate name poisons the entry: guessing between two+ // declarations is how a guard earns a false accusation.+ bagsByName.set(m[1], bagsByName.has(m[1]) ? null : byProp);+ }+}++/**+ * The type source declares for `Component.prop`, if it can be found.+ *+ * Two lookups, most-specific first:+ * 1. The component's own `{Name}Props` bag in its own directory. Exact, and+ * the only pass that runs for components — Chat/ holds three differently+ * typed `status` props, so a directory-wide search would misjudge them.+ * 2. For hooks only (`useThing`), the uniquely-named `UseThingConfig` /+ * `UseThingOptions` bag, wherever in the package it is declared.+ *+ * Anything else stays undefined and is judged on the doc alone: a missed prop+ * costs nothing, a wrong failure costs the guard its credibility. (Heading+ * re-exports its props and so has no bag here — deliberately unresolved.)+ */+function declaredType(+ dir: string,+ component: string,+ prop: string,+): string | undefined {+ const own = sourcePropTypes.get(`${dir}::${component}Props`)?.get(prop);+ if (own !== undefined) {+ return own;+ }+ if (!/^use[A-Z]/.test(component)) {+ return undefined;+ }+ const pascal = component[0].toUpperCase() + component.slice(1);+ for (const suffix of HOOK_BAG_SUFFIXES) {+ const declared = bagsByName.get(`${pascal}${suffix}`)?.get(prop);+ if (declared !== undefined) {+ return declared;+ }+ }+ return undefined;+}++// --- Doc props -------------------------------------------------------------++const docFiles = findFiles(SRC_DIR, ['.doc.mjs']);++interface DocProp {+ file: string;+ dir: string;+ component: string;+ prop: string;+ type: string;+ description: string;+}++const docProps: DocProp[] = [];+for (const file of docFiles) {+ const mod = require(file) as DocModule;+ // A type is language-neutral: the translated docs carry their own props[]+ // (the `--zh` CLI surface renders them), so they are held to the same bar.+ for (const key of ['docs', 'docsZh'] as const) {+ const docs = mod[key];+ if (!docs) {+ continue;+ }+ const entries = [+ {name: docs.name, props: docs.props},+ ...(docs.components || []),+ ];+ for (const {name, props} of entries) {+ if (!name || !Array.isArray(props)) {+ continue;+ }+ for (const prop of props) {+ if (typeof prop.type !== 'string') {+ continue;+ }+ docProps.push({+ file: `${relative(SRC_DIR, file)}${key === 'docsZh' ? ' (zh)' : ''}`,+ dir: file.slice(0, file.lastIndexOf('/')),+ component: name,+ prop: prop.name,+ type: prop.type,+ description: prop.description || '',+ });+ }+ }+ }+}++function escapeRe(s: string): string {+ return s.replace(/[.*+?^${}()|[\]\\-]/g, '\\$&');+}++/** The value members of a union — `null`/`undefined` carry nothing to spell. */+function literalMembers(literals: string): string[] {+ return literals+ .split('|')+ .map(s => s.trim())+ .filter(s => s.startsWith("'") || /^-?\d/.test(s));+}++/**+ * Where a literal has to be written to count as surfaced.+ *+ * `code` — a type column. The literal must appear *as a literal*: quotes+ * intact for strings, digit-boundary-anchored for numbers.+ * `prose` — a free-text description. Quotes are optional (prose may say+ * `direction is ascending or descending`), but the boundary still holds.+ *+ * The boundary is the whole point. A bare `text.includes('sm')` is satisfied+ * by `'xsm'`, and `text.includes('1')` by `1.5` or `10` — so a doc could drop+ * a member and stay "green" purely because a longer sibling contains its+ * characters. Every union whose members share substrings (TextSize, TextType,+ * SpacingStep, IconName) is exposed to that, which is most of them.+ */+type Surface = 'code' | 'prose';++function isSurfaced(text: string, literal: string, surface: Surface): boolean {+ const isString = literal.startsWith("'");+ const inner = isString ? literal.slice(1, -1) : literal;+ if (isString) {+ // In code, the quotes are part of the literal: 'xsm' does not contain+ // the *literal* 'sm', only the characters. In prose they are optional.+ const body = escapeRe(inner);+ return surface === 'code'+ ? new RegExp(`['"\`]${body}['"\`]`).test(text)+ : new RegExp(`(?<![\\w-])${body}(?![\\w-])`).test(text);+ }+ // Numbers: reject a match that is really part of a longer number — `1` must+ // not be found inside `1.5`, `10` or `-1`. A trailing dot is allowed only+ // when it is sentence punctuation ("steps go 0, 0.5, 1."), not a decimal.+ return new RegExp(`(?<![\\w.-])${escapeRe(inner)}(?![\\w-])(?!\\.\\d)`).test(+ text,+ );+}++/** Members of `literals` not written out in `text`. */+function missingFrom(+ text: string,+ literals: string,+ surface: Surface = 'code',+): string[] {+ return literalMembers(literals).filter(+ literal => !isSurfaced(text, literal, surface),+ );+}++interface Violation {+ where: string;+ detail: string;+}++/**+ * Reasons this one prop hides values a reader would have to guess at.+ *+ * `resolveFrom` is the type expression whose unions the reader must know;+ * `type`/`description` are what the docs actually say. They are the same+ * expression for the doc-side pass, and differ for the source-side pass,+ * where the component's own `.tsx` declaration is the authority and the docs+ * are the thing on trial. That second pass is what makes the guard+ * drift-proof: inlined literals go stale the moment the union in source+ * gains a member, and only the source knows that happened.+ *+ * Pure — the synthetic cases below exercise it directly, so the guard is+ * proven to bite without dirtying a real doc.+ */+function hiddenValueReasons(+ type: string,+ description: string,+ resolveFrom: string = type,+): string[] {+ const reasons: string[] = [];+ for (const named of authoredTypeNames(resolveFrom)) {+ for (const [union, literals] of requiredUnions(named)) {+ if (ENUMERATED_IN_PROSE.has(union)) {+ const missing = missingFrom(description, literals, 'prose');+ if (missing.length > 0) {+ reasons.push(+ `${union} is exempt from inlining only while its description ` ++ `enumerates every value; these are missing from the ` ++ `description: ${missing.join(', ')}.`,+ );+ }+ } else if (named === union) {+ // DIRECT: the name is the union. Inlining is always affordable, so+ // the type column is the only surface that counts.+ if (missingFrom(type, literals, 'code').length > 0) {+ reasons.push(+ `names the union ${union} instead of inlining it. ` ++ `Write: "${literals}".`,+ );+ }+ } else if (+ // INDIRECT: the union hides inside a composite. Spell the shape out+ // in the type, or name the values in the description. Each surface is+ // read on its own terms — the type as code, the description as prose —+ // rather than concatenated, so a value half-spelled in one and+ // half-mentioned in the other cannot pass for a value that is written+ // down anywhere.+ literalMembers(literals).some(+ literal =>+ !isSurfaced(type, literal, 'code') &&+ !isSurfaced(description, literal, 'prose'),+ )+ ) {+ reasons.push(+ `${named} hides ${union} = ${literals}, and neither the type nor ` ++ `the description says so. Spell the shape out in the type ` ++ `(preferred for small objects) or name the legal values in the ` ++ `description, so a reader without an IDE can see what is legal.`,+ );+ }+ }+ }+ return reasons;+}++function findViolations(): Violation[] {+ const violations: Violation[] = [];+ for (const {file, dir, component, prop, type, description} of docProps) {+ const where = `${file} — ${component}.${prop}: "${type}"`;+ const seen = new Set<string>();+ const report = (detail: string) => {+ if (!seen.has(detail)) {+ seen.add(detail);+ violations.push({where, detail});+ }+ };+ // Pass 1: what the docs themselves name.+ for (const detail of hiddenValueReasons(type, description)) {+ report(detail);+ }+ // Pass 2: what the component actually declares in source.+ const declared = declaredType(dir, component, prop);+ if (declared) {+ for (const detail of hiddenValueReasons(type, description, declared)) {+ report(`source declares \`${prop}: ${declared}\` — ${detail}`);+ }+ }+ }+ return violations;+}++describe('doc prop types surface their literal values (#1645)', () => {+ it('sanity: finds doc props and literal-union types in source', () => {+ expect(docProps.length).toBeGreaterThan(0);+ expect(literalUnions.size).toBeGreaterThan(0);+ });++ it('sanity: the registries read the real source definitions', () => {+ expect(literalUnions.get('SpacingStep')).toBe(+ '0 | 0.5 | 1 | 1.5 | 2 | 3 | 4 | 5 | 6 | 8 | 10',+ );+ expect(literalUnions.get('TableSortDirection')).toBe(+ "'ascending' | 'descending'",+ );+ expect([...requiredUnions('InputStatus').keys()]).toContain(+ 'InputStatusType',+ );+ expect([...requiredUnions('TableSortState').keys()]).toContain(+ 'TableSortDirection',+ );+ });++ it('sanity: does not descend into opaque generic wrappers', () => {+ // Button's endContent is ReactElement<IconProps>; the consumer writes+ // <Icon icon="check" />, not an IconProps object, so IconName's 26+ // values are Icon's business, not Button's.+ expect(authoredTypeNames('ReactElement<IconProps>')).toEqual([+ 'ReactElement',+ ]);+ expect(authoredTypeNames('Record<string, MarkdownSource>')).toEqual([+ 'Record',+ ]);+ expect(+ authoredTypeNames('ReadonlyArray<TableSortEntry<TSortKey>>'),+ ).toEqual(['ReadonlyArray', 'TableSortEntry']);+ });++ it('LITERAL_UNION rejects a long near-miss union in linear time', () => {+ // Every `export type` in the package is fed to this regex, so it must stay+ // cheap on the ones that DON'T match. The dangerous shape is a long literal+ // prefix ending in something that isn't a literal — `'a' | 'b' | … |+ // ComponentType`, the autocomplete escape hatch — which the regex can only+ // reject after trying every way to parse it. An ambiguous pattern has 2^n+ // of those. This union is 24 members long: linear, it is instant; ambiguous,+ // it would outlive the CI job.+ const nearMiss =+ Array.from({length: 24}, (_, i) => `'v${i}'`).join(' | ') ++ ' | ComponentType';+ const start = performance.now();+ expect(LITERAL_UNION.test(nearMiss)).toBe(false);+ expect(performance.now() - start).toBeLessThan(100);+ });++ it('no documented prop type hides its legal values', () => {+ const violations = findViolations();+ expect(+ violations,+ violations.map(v => `${v.where}\n ${v.detail}`).join('\n'),+ ).toEqual([]);+ });++ describe('the guard bites (synthetic props, not real docs)', () => {+ it('flags a bare literal-union name and accepts the inlined form', () => {+ expect(hiddenValueReasons('SpacingStep', 'Gap between items.')).toEqual([+ expect.stringContaining('names the union SpacingStep'),+ ]);+ expect(+ hiddenValueReasons(+ '0 | 0.5 | 1 | 1.5 | 2 | 3 | 4 | 5 | 6 | 8 | 10',+ 'Gap between items.',+ ),+ ).toEqual([]);+ });++ it('is not fooled by prose alone for a direct union', () => {+ // The #1645 failure mode: prose hints at the scale, the type column+ // still says nothing, and the CLI signature builder (which splits the+ // type on `|`) still has no values to print.+ expect(+ hiddenValueReasons('SpacingStep', 'Steps: 0, 0.5, 1, 1.5, 2, 3, 4.'),+ ).not.toEqual([]);+ });++ it('flags a partially inlined union — one forgotten member is enough', () => {+ // Judged against what source declares, so a doc that drops 'stretch'+ // (or an inlined SpacingStep that misses a step the scale later gains)+ // is caught even though the doc no longer names the type at all.+ expect(+ hiddenValueReasons(+ "'start' | 'center' | 'end'",+ 'Alignment.',+ 'GridAlignment',+ ),+ ).toEqual([expect.stringContaining('GridAlignment')]);+ expect(+ hiddenValueReasons(+ "'start' | 'center' | 'end' | 'stretch'",+ 'Alignment.',+ 'GridAlignment',+ ),+ ).toEqual([]);+ });++ it('the source-side pass indexes the real component prop bags', () => {+ const gridDir = docProps.find(p => p.component === 'Grid')!.dir;+ expect(declaredType(gridDir, 'Grid', 'gap')).toBe('SpacingStep');+ expect(declaredType(gridDir, 'Grid', 'align')).toBe('GridAlignment');+ });++ it('never judges a component against a sibling in the same directory', () => {+ // Chat/ declares three differently-typed `status` props. Reading+ // ChatComposer's docs against ChatMessageMetadata's declaration would+ // be a false accusation, so the index is keyed by prop bag, not folder.+ const chatDir = docProps.find(p => p.component === 'ChatComposer')!.dir;+ expect(declaredType(chatDir, 'ChatComposer', 'status')).toBe(+ 'ChatComposerStatus',+ );+ expect(declaredType(chatDir, 'ChatMessageMetadata', 'status')).toBe(+ 'ChatMessageStatus',+ );+ // Heading re-exports its props, so there is no HeadingProps bag here:+ // the pass must stay silent rather than borrow TextProps.+ const textDir = docProps.find(p => p.component === 'Text')!.dir;+ expect(declaredType(textDir, 'Heading', 'type')).toBeUndefined();+ });++ it('flags a composite that hides a union, and takes either surface', () => {+ expect(hiddenValueReasons('InputStatus', 'Validation status.')).toEqual([+ expect.stringContaining('InputStatus hides InputStatusType'),+ ]);+ // Spelled out in the type…+ expect(+ hiddenValueReasons(+ "{type: 'warning' | 'error' | 'success', message?: string}",+ 'Validation status.',+ ),+ ).toEqual([]);+ // …or named in the description.+ expect(+ hiddenValueReasons(+ 'InputStatus',+ "Validation status. type is 'warning', 'error', or 'success'.",+ ),+ ).toEqual([]);+ });++ it("catches the issue's headline: sort direction is not 'asc'/'desc'", () => {+ expect(+ hiddenValueReasons(+ 'TableSortState<TSortKey>',+ 'Ordered array of {sortKey, direction} entries.',+ ),+ ).toEqual([expect.stringContaining("'ascending' | 'descending'")]);+ // The word "descending" contains "ascending"'s literal only as a+ // substring of itself, so a doc naming just one is still flagged.+ expect(+ hiddenValueReasons(+ 'TableSortState<TSortKey>',+ "Entries sort 'ascending' by default.",+ ),+ ).toEqual([expect.stringContaining("'ascending' | 'descending'")]);+ });++ it('lets a value-free type through untouched', () => {+ expect(hiddenValueReasons('boolean', 'Disables the control.')).toEqual(+ [],+ );+ expect(hiddenValueReasons('ReactNode', 'Slot content.')).toEqual([]);+ expect(hiddenValueReasons('(value: string) => void', 'Called.')).toEqual(+ [],+ );+ });++ it('a longer sibling literal does not mask a shorter one', () => {+ // A substring match lies: 'sm' looks "present" inside 'xsm', and the+ // spacing step 1 looks "present" inside 1.5 and 10. Both unions below+ // are complete EXCEPT for the masked member — so the *only* thing that+ // can fail them is the guard noticing the masked one is really gone.+ // (Every other member is still listed. A test that drops extra members+ // too would pass on the substring match alone and prove nothing —+ // which is precisely why GridAlignment, whose members share no+ // substrings, cannot exercise this class at all.)+ expect(+ hiddenValueReasons(+ // TextSize without 'sm'. 'xsm' is still there, masking it.+ "'4xs' | '3xs' | '2xs' | 'xsm' | 'base' | 'lg' | 'xl' | '2xl' | " ++ "'3xl' | '4xl'",+ 'Size.',+ 'TextSize',+ ),+ ).toEqual([expect.stringContaining('TextSize')]);+ expect(+ hiddenValueReasons(+ // SpacingStep without the step 1. 1.5 and 10 still mask it.+ '0 | 0.5 | 1.5 | 2 | 3 | 4 | 5 | 6 | 8 | 10',+ 'Gap.',+ 'SpacingStep',+ ),+ ).toEqual([expect.stringContaining('SpacingStep')]);+ // …and the complete unions still pass, so the boundary match is not+ // simply rejecting everything.+ expect(+ hiddenValueReasons(+ "'4xs' | '3xs' | '2xs' | 'xsm' | 'sm' | 'base' | 'lg' | 'xl' | " ++ "'2xl' | '3xl' | '4xl'",+ 'Size.',+ 'TextSize',+ ),+ ).toEqual([]);+ expect(+ hiddenValueReasons(+ '0 | 0.5 | 1 | 1.5 | 2 | 3 | 4 | 5 | 6 | 8 | 10',+ 'Gap.',+ 'SpacingStep',+ ),+ ).toEqual([]);+ });++ it('holds the prose exemption to its bargain', () => {+ // IconName may stay named — but only while every value is in the prose.+ const enumerated = docProps.find(+ p => p.component === 'Icon' && p.prop === 'icon',+ );+ expect(enumerated?.type).toContain('IconName');+ expect(+ hiddenValueReasons(enumerated!.type, enumerated!.description),+ ).toEqual([]);+ // Drop the enumeration and the exemption stops covering it.+ expect(+ hiddenValueReasons('IconName | ComponentType<SVGProps>', 'An icon.'),+ ).toEqual([expect.stringContaining('exempt from inlining only while')]);+ });+ });++ /**+ * The synthetic cases above prove the predicate bites. These prove the+ * *shipped docs are actually wired to it* — each one takes a real doc+ * entry, stages the exact drift the PR exists to prevent, and asserts the+ * guard fails. A guard that green-lights the regression it was built to+ * catch is decoration; these are the tests that stop it becoming one.+ */+ describe('the guard bites the real docs when they drift', () => {+ const realProp = (component: string, prop: string): DocProp => {+ const found = docProps.find(+ p =>+ p.component === component &&+ p.prop === prop &&+ !p.file.includes('(zh)'),+ );+ if (!found) {+ throw new Error(`no doc prop ${component}.${prop}`);+ }+ return found;+ };++ /** What source says this doc prop is — the authority drift is judged against. */+ const authority = (p: DocProp): string => {+ const declared = declaredType(p.dir, p.component, p.prop);+ if (!declared) {+ throw new Error(+ `${p.component}.${p.prop} has no source declaration, so nothing ` ++ `holds its inlined literals to the union in source.`,+ );+ }+ return declared;+ };++ it("#1645's headline prop is guarded: useTableSortable.sort", () => {+ // The hook's config bag is UseTableSortableConfig, and it lives in+ // Table/plugins/sortable/ while the doc sits in Table/ — so this only+ // resolves because the source pass looks past `{Name}Props` *and* past+ // the doc's own directory.+ const sort = realProp('useTableSortable', 'sort');+ expect(authority(sort)).toBe('TableSortState<TSortKey>');+ // The shipped doc is honest today…+ expect(+ hiddenValueReasons(sort.type, sort.description, authority(sort)),+ ).toEqual([]);+ // …and the moment it stops naming 'descending', the guard fails. This+ // is the doc lying about the legal sort values all over again — the+ // literal bug #1645 was filed for.+ const stale = (s: string) => s.replace(/'?descending'?/g, '');+ expect(stale(sort.type)).not.toBe(sort.type);+ expect(+ hiddenValueReasons(+ stale(sort.type),+ stale(sort.description),+ authority(sort),+ ),+ ).toEqual([expect.stringContaining("'ascending' | 'descending'")]);+ });++ it('Timestamp.size cannot quietly lose a step masked by a sibling', () => {+ const size = realProp('Timestamp', 'size');+ expect(authority(size)).toBe('TextSize');+ expect(+ hiddenValueReasons(size.type, size.description, authority(size)),+ ).toEqual([]);+ // Delete 'sm'. A substring match calls it present — 'xsm' contains it.+ const stale = size.type.replace("'sm' | ", '');+ expect(stale).not.toBe(size.type);+ expect(stale).toContain("'xsm'");+ expect(+ hiddenValueReasons(stale, size.description, authority(size)),+ ).toEqual([expect.stringContaining('TextSize')]);+ });++ /**+ * The two props that must NOT be inlined. Everything else in this file+ * pushes toward spelling unions out; these two push back, because the+ * docsite playground reads `type` to choose a control. What each one is+ * really protecting differs, and the specifics live next to the playground+ * itself — see apps/docsite/src/__tests__/component-prop-controls.test.ts,+ * which exercises the actual gate. These only pin the doc's shape, so the+ * next person to "finish the job" trips here first.+ */+ it('AppShell.mobileNav stays a bare ReactNode (the editor hides on an exact string)', () => {+ const nav = realProp('AppShell', 'mobileNav');+ // PropertyEditor's UNSUPPORTED_PROP_TYPES is a Set of exact type strings.+ // Widening drops that match, and the prop would then be hidden only by+ // the second, incidental gate (its slotElements). Keep the exact string.+ expect(nav.type).toBe('ReactNode');+ // The values still have to be discoverable — they live in the prose.+ expect(nav.description).toContain('breakpoint');+ expect(nav.description).toContain("'md'");+ });++ it('Lightbox.media keeps naming its type (spelling it out yields a string control)', () => {+ const media = realProp('Lightbox', 'media');+ expect(media.type).toBe('LightboxMedia | LightboxMedia[]');+ // Same bargain as IconName: named is allowed only while the prose+ // carries the values a consumer must write.+ expect(media.description).toContain("'image'");+ expect(media.description).toContain("'video'");+ });++ it('Grid.gap cannot quietly lose the step 1, masked by 1.5 and 10', () => {+ const gap = realProp('Grid', 'gap');+ expect(authority(gap)).toBe('SpacingStep');+ expect(+ hiddenValueReasons(gap.type, gap.description, authority(gap)),+ ).toEqual([]);+ const stale = gap.type.replace('1 | 1.5', '1.5');+ expect(stale).not.toBe(gap.type);+ expect(stale).toContain('1.5');+ expect(stale).toContain('10');+ expect(+ hiddenValueReasons(stale, gap.description, authority(gap)),+ ).toEqual([expect.stringContaining('SpacingStep')]);+ });+ });+});