Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

docsite: link hook param and return types to their definitions (#5443)

Cindy Zhangc050bc5a8d13
diff --git a/apps/docsite/scripts/generate-data.mjs b/apps/docsite/scripts/generate-data.mjs
index 710e9a86cf..2f292e71d0 100644
--- a/apps/docsite/scripts/generate-data.mjs
+++ b/apps/docsite/scripts/generate-data.mjs
@@ -661,21 +661,27 @@ async function generateComponentRegistry() {
}
}
- // Surface the shape of non-primitive prop types (issue #2682): when a
- // documented prop type references a named type exported from this
- // package's source (e.g. `SearchSource<T>`), record the reference on the
- // prop and attach the extracted declaration to the entry so the props
- // table can render it on demand.
+ // Surface the shape of non-primitive types (issue #2682): when a
+ // documented prop, hook parameter, or hook return type references a named
+ // type exported from this package's source (e.g. `SearchSource<T>`,
+ // `ToastOptions`), record the reference on the row and attach the
+ // extracted declaration to the entry so the docs table can render it on
+ // demand.
const typeIndex = buildTypeDefinitionIndex(
pkg.srcDir,
path.relative(CONTENT_ROOT, pkg.srcDir),
);
for (const comp of components) {
const referenced = new Map();
- for (const prop of comp.props) {
- const typeRefs = collectPropTypeRefs(prop.type, typeIndex);
+ const rows = [
+ ...comp.props,
+ ...(comp.params ?? []),
+ ...(comp.returns ?? []),
+ ];
+ for (const row of rows) {
+ const typeRefs = collectPropTypeRefs(row.type, typeIndex);
if (typeRefs.length > 0) {
- prop.typeRefs = typeRefs;
+ row.typeRefs = typeRefs;
for (const name of typeRefs) {
referenced.set(name, typeIndex.get(name));
}
@@ -774,12 +780,18 @@ export interface HookParamDoc {
description: string;
default?: string;
required?: boolean;
+ /** Names of package-exported types referenced by \`type\`, resolvable
+ * against the owning entry's \`typeDefs\`. */
+ typeRefs?: string[];
}
export interface HookReturnDoc {
name: string;
type: string;
description: string;
+ /** Names of package-exported types referenced by \`type\`, resolvable
+ * against the owning entry's \`typeDefs\`. */
+ typeRefs?: string[];
}
export interface ComponentEntry {
@@ -806,7 +818,8 @@ export interface ComponentEntry {
hidden: boolean;
parentDoc: string | null;
props: PropDoc[];
- /** Declarations for every type referenced from \`props[].typeRefs\`. */
+ /** Declarations for every type referenced from \`props[]\`, \`params[]\`, or
+ * \`returns[]\` \`typeRefs\`. */
typeDefs: TypeDefinition[];
usage: UsageDoc | null;
theming: ThemingDoc | null;
diff --git a/apps/docsite/src/__tests__/type-definitions.test.ts b/apps/docsite/src/__tests__/type-definitions.test.ts
index fd2b241706..97c081e105 100644
--- a/apps/docsite/src/__tests__/type-definitions.test.ts
+++ b/apps/docsite/src/__tests__/type-definitions.test.ts
@@ -187,12 +187,9 @@ describe('splitTypeRefSegments', () => {
});
});
-describe('props table trigger', () => {
+describe('type definition trigger', () => {
const source = fs.readFileSync(
- path.resolve(
- __dirname,
- '../components/component-detail/PlaygroundPropsTable.tsx',
- ),
+ path.resolve(__dirname, '../components/component-detail/TypeRefText.tsx'),
'utf8',
);
@@ -209,6 +206,15 @@ describe('props table trigger', () => {
describe('generated registry', () => {
const allEntries = Object.values(components).flat();
+ it('attaches typeRefs and matching typeDefs to a hook return field', () => {
+ const entry = allEntries.find(e => e.name === 'useToast');
+ expect(entry).toBeDefined();
+ const showToast = entry!.returns?.find(r => r.name === 'showToast');
+ expect(showToast?.typeRefs).toEqual(['ToastOptions']);
+ const def = entry!.typeDefs.find(d => d.name === 'ToastOptions');
+ expect(def?.definition).toContain('export interface ToastOptions');
+ });
+
it('attaches typeRefs and matching typeDefs to BaseTypeahead', () => {
const entry = allEntries.find(e => e.name === 'BaseTypeahead');
expect(entry).toBeDefined();
@@ -218,10 +224,14 @@ describe('generated registry', () => {
expect(def?.definition).toContain('export interface SearchSource<');
});
- it('only records typeDefs that some prop references', () => {
+ it('only records typeDefs that some documented row references', () => {
for (const entry of allEntries) {
const referenced = new Set(
- entry.props.flatMap(prop => prop.typeRefs ?? []),
+ [
+ ...entry.props,
+ ...(entry.params ?? []),
+ ...(entry.returns ?? []),
+ ].flatMap(row => row.typeRefs ?? []),
);
expect(entry.typeDefs.map(d => d.name).sort()).toEqual(
[...referenced].sort(),
diff --git a/apps/docsite/src/components/component-detail/ComponentDetailClient.tsx b/apps/docsite/src/components/component-detail/ComponentDetailClient.tsx
index ffb4004403..300d283bbc 100644
--- a/apps/docsite/src/components/component-detail/ComponentDetailClient.tsx
+++ b/apps/docsite/src/components/component-detail/ComponentDetailClient.tsx
@@ -121,7 +121,11 @@ function OverviewContent({
)}
{isHook && comp.params && comp.returns && (
- <HookSignature params={comp.params} returns={comp.returns} />
+ <HookSignature
+ params={comp.params}
+ returns={comp.returns}
+ typeDefs={comp.typeDefs}
+ />
)}
{!isHook && !hasInteractivePlayground(comp) && comp.props.length > 0 && (
diff --git a/apps/docsite/src/components/component-detail/HookSignature.tsx b/apps/docsite/src/components/component-detail/HookSignature.tsx
index dc0ed23b7e..5a47cf28a3 100644
--- a/apps/docsite/src/components/component-detail/HookSignature.tsx
+++ b/apps/docsite/src/components/component-detail/HookSignature.tsx
@@ -12,12 +12,15 @@ import {useMediaQuery} from '@astryxdesign/core/hooks';
import type {
HookParamDoc,
HookReturnDoc,
+ TypeDefinition,
} from '../../generated/componentRegistry';
import {MarkdownText} from '../MarkdownText';
+import {resolveTypeRefs, TypeRefText} from './TypeRefText';
interface HookSignatureProps {
params: HookParamDoc[];
returns: HookReturnDoc[];
+ typeDefs: TypeDefinition[];
}
function formatParamType(type: string, defaultValue?: string): string {
@@ -27,7 +30,43 @@ function formatParamType(type: string, defaultValue?: string): string {
return type;
}
-function ParamRowMobile({param}: {param: HookParamDoc}) {
+/**
+ * Type text for a hook parameter or return field. When the documented type
+ * references named types exported from the hook's package (e.g.
+ * `ToastOptions`), each referenced name becomes an inline definition trigger
+ * that opens the declaration — the same treatment the component props table
+ * gives prop types (#2682). Rows with no resolved references stay plain text.
+ */
+function HookTypeText({
+ type,
+ typeRefs,
+ defaultValue,
+ typeDefs,
+}: {
+ type: string;
+ typeRefs?: string[];
+ defaultValue?: string;
+ typeDefs: TypeDefinition[];
+}) {
+ const defs = resolveTypeRefs(typeRefs, typeDefs);
+ if (defs.length === 0) {
+ return <>{formatParamType(type, defaultValue)}</>;
+ }
+ return (
+ <>
+ <TypeRefText type={type} defs={defs} />
+ {defaultValue != null && ` (default: ${defaultValue})`}
+ </>
+ );
+}
+
+function ParamRowMobile({
+ param,
+ typeDefs,
+}: {
+ param: HookParamDoc;
+ typeDefs: TypeDefinition[];
+}) {
return (
<VStack gap={1} style={{paddingBlock: 8}}>
<HStack gap={1} vAlign="center">
@@ -37,7 +76,12 @@ function ParamRowMobile({param}: {param: HookParamDoc}) {
{param.required && <Badge label="required" variant="info" />}
</HStack>
<Text type="code" color="secondary">
- {formatParamType(param.type, param.default)}
+ <HookTypeText
+ type={param.type}
+ typeRefs={param.typeRefs}
+ defaultValue={param.default}
+ typeDefs={typeDefs}
+ />
</Text>
{param.description && (
<MarkdownText type="body" color="secondary">
@@ -48,14 +92,24 @@ function ParamRowMobile({param}: {param: HookParamDoc}) {
);
}
-function ReturnRowMobile({ret}: {ret: HookReturnDoc}) {
+function ReturnRowMobile({
+ ret,
+ typeDefs,
+}: {
+ ret: HookReturnDoc;
+ typeDefs: TypeDefinition[];
+}) {
return (
<VStack gap={1} style={{paddingBlock: 8}}>
<Text type="code" weight="bold">
{ret.name}
</Text>
<Text type="code" color="secondary">
- {ret.type}
+ <HookTypeText
+ type={ret.type}
+ typeRefs={ret.typeRefs}
+ typeDefs={typeDefs}
+ />
</Text>
{ret.description && (
<MarkdownText type="body" color="secondary">
@@ -66,19 +120,22 @@ function ReturnRowMobile({ret}: {ret: HookReturnDoc}) {
);
}
-export function HookSignature({params, returns}: HookSignatureProps) {
+export function HookSignature({params, returns, typeDefs}: HookSignatureProps) {
const isMobile = useMediaQuery('(max-width: 768px)');
const paramData = params.map(p => ({
name: p.name as unknown,
required: p.required as unknown,
- type: formatParamType(p.type, p.default) as unknown,
+ type: p.type as unknown,
+ typeRefs: p.typeRefs as unknown,
+ default: p.default as unknown,
description: (p.description ?? '') as unknown,
})) as Record<string, unknown>[];
const returnData = returns.map(r => ({
name: r.name as unknown,
type: r.type as unknown,
+ typeRefs: r.typeRefs as unknown,
description: (r.description ?? '') as unknown,
})) as Record<string, unknown>[];
@@ -92,7 +149,7 @@ export function HookSignature({params, returns}: HookSignatureProps) {
params.map(p => (
<div key={p.name}>
<Divider />
- <ParamRowMobile param={p} />
+ <ParamRowMobile param={p} typeDefs={typeDefs} />
</div>
))
) : (
@@ -123,7 +180,12 @@ export function HookSignature({params, returns}: HookSignatureProps) {
width: pixel(240),
renderCell: (item: Record<string, unknown>) => (
<Text type="code" color="secondary">
- {item.type as string}
+ <HookTypeText
+ type={item.type as string}
+ typeRefs={item.typeRefs as string[] | undefined}
+ defaultValue={item.default as string | undefined}
+ typeDefs={typeDefs}
+ />
</Text>
),
},
@@ -152,7 +214,7 @@ export function HookSignature({params, returns}: HookSignatureProps) {
returns.map(r => (
<div key={r.name}>
<Divider />
- <ReturnRowMobile ret={r} />
+ <ReturnRowMobile ret={r} typeDefs={typeDefs} />
</div>
))
) : (
@@ -178,7 +240,11 @@ export function HookSignature({params, returns}: HookSignatureProps) {
width: pixel(240),
renderCell: (item: Record<string, unknown>) => (
<Text type="code" color="secondary">
- {item.type as string}
+ <HookTypeText
+ type={item.type as string}
+ typeRefs={item.typeRefs as string[] | undefined}
+ typeDefs={typeDefs}
+ />
</Text>
),
},
diff --git a/apps/docsite/src/components/component-detail/PlaygroundPropsTable.tsx b/apps/docsite/src/components/component-detail/PlaygroundPropsTable.tsx
index 0837aada9b..0e2e8a0ca7 100644
--- a/apps/docsite/src/components/component-detail/PlaygroundPropsTable.tsx
+++ b/apps/docsite/src/components/component-detail/PlaygroundPropsTable.tsx
@@ -10,12 +10,9 @@
'use client';
import {createElement, useState} from 'react';
-import * as stylex from '@stylexjs/stylex';
import {Heading, Text} from '@astryxdesign/core/Text';
import {HStack, VStack} from '@astryxdesign/core/Layout';
import {Divider} from '@astryxdesign/core';
-import {Card} from '@astryxdesign/core/Card';
-import {Popover} from '@astryxdesign/core/Popover';
import {Switch} from '@astryxdesign/core/Switch';
import {TextInput} from '@astryxdesign/core/TextInput';
import {NumberInput} from '@astryxdesign/core/NumberInput';
@@ -27,11 +24,8 @@ import {Minus, Plus} from 'lucide-react';
import {useMediaQuery} from '@astryxdesign/core/hooks';
import {allSyntaxPresets} from '@astryxdesign/core/theme/syntax';
import {themeObjectsFull} from '../../generated/themeRegistry';
-import {
- coerceEnumOption,
- splitTypeRefSegments,
- type PropControlDescriptor,
-} from './parsePropType';
+import {coerceEnumOption, type PropControlDescriptor} from './parsePropType';
+import {resolveTypeRefs, TypeRefText} from './TypeRefText';
import type {KnobProp} from './InteractivePreview';
import {resolveElementDescriptor} from './resolveElements';
import type {
@@ -39,40 +33,8 @@ import type {
PropDoc,
TypeDefinition,
} from '../../generated/componentRegistry';
-import {CodeExampleBlock} from '../CodeExampleBlock';
import {MarkdownText} from '../MarkdownText';
-const styles = stylex.create({
- // Inline link treatment for type-name definition triggers, mirroring the
- // authored-docs link pattern (docs/inlineMarkdown.tsx) on a button element
- // so the trigger stays keyboard-focusable with a visible focus ring.
- typeRefTrigger: {
- backgroundColor: 'transparent',
- borderStyle: 'none',
- padding: 0,
- fontFamily: 'inherit',
- fontSize: 'inherit',
- lineHeight: 'inherit',
- cursor: 'pointer',
- color: 'var(--color-text-accent)',
- textDecorationLine: 'underline',
- textDecorationThickness: '1px',
- textUnderlineOffset: '0.16em',
- transition: 'color 120ms ease, text-decoration-color 120ms ease',
- ':hover': {
- '@media (hover: hover)': {
- color: 'var(--color-accent)',
- textDecorationThickness: '2px',
- },
- },
- ':focus-visible': {
- borderRadius: 'var(--radius-sm)',
- outline: '2px solid var(--color-accent)',
- outlineOffset: 2,
- },
- },
-});
-
function formatType(type: string, defaultValue?: string): React.ReactNode {
const parts = type.split(/\s*\|\s*/);
const isEnum = parts.length > 1 && parts.every(p => /^['"]/.test(p.trim()));
@@ -104,46 +66,10 @@ function formatType(type: string, defaultValue?: string): React.ReactNode {
return type;
}
-/**
- * Inline definition trigger for a type name in the type column: the name
- * itself renders as a link-styled button that opens the extracted declaration
- * so readers can inspect the shape without leaving the props table (#2682).
- * The popover mirrors the Popover + Card + CodeExampleBlock pattern used by
- * PackageActions.
- */
-function TypeDefinitionTrigger({def}: {def: TypeDefinition}) {
- return (
- <Popover
- width="min(480px, calc(100vw - 32px))"
- label={`${def.name} type definition`}
- content={
- <VStack gap={1}>
- <Text type="supporting" color="secondary">
- {def.sourcePath}
- </Text>
- <Card padding={0}>
- <CodeExampleBlock
- code={def.definition}
- language="typescript"
- size="sm"
- hasCopyButton
- maxHeight={320}
- width="100%"
- />
- </Card>
- </VStack>
- }>
- <button type="button" {...stylex.props(styles.typeRefTrigger)}>
- {def.name}
- </button>
- </Popover>
- );
-}
-
/**
* Type-column text for a prop. When the documented type references named
* types exported from the component's package (e.g. `SearchSource<T>`), each
- * referenced name becomes a {@link TypeDefinitionTrigger}; surrounding type
+ * referenced name becomes an inline definition trigger; surrounding type
* syntax (generics punctuation, unions) stays plain text. Props with no
* resolved references keep the plain formatType rendering.
*/
@@ -154,29 +80,14 @@ function PropTypeText({
prop: PropDoc;
typeDefs: TypeDefinition[];
}) {
- const defs = (prop.typeRefs ?? [])
- .map(name => typeDefs.find(def => def.name === name))
- .filter(def => def != null);
+ const defs = resolveTypeRefs(prop.typeRefs, typeDefs);
if (defs.length === 0) {
return <>{formatType(prop.type, prop.default)}</>;
}
- const segments = splitTypeRefSegments(
- prop.type,
- defs.map(def => def.name),
- );
return (
<>
- {segments.map((segment, i) => {
- const def = segment.isRef
- ? defs.find(d => d.name === segment.text)
- : undefined;
- return def ? (
- <TypeDefinitionTrigger key={i} def={def} />
- ) : (
- <span key={i}>{segment.text}</span>
- );
- })}
+ <TypeRefText type={prop.type} defs={defs} />
{prop.default != null && (
<span style={{opacity: 0.6}}> (default: {prop.default})</span>
)}
diff --git a/apps/docsite/src/components/component-detail/TypeRefText.tsx b/apps/docsite/src/components/component-detail/TypeRefText.tsx
new file mode 100644
index 0000000000..52a614a3dc
--- /dev/null
+++ b/apps/docsite/src/components/component-detail/TypeRefText.tsx
@@ -0,0 +1,135 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file TypeRefText.tsx
+ * @input A documented type string plus the entry's extracted type declarations
+ * @output Type text whose resolved type names are inline definition triggers
+ * @position Shared by the component props table and the hook signature tables.
+ */
+
+'use client';
+
+import * as stylex from '@stylexjs/stylex';
+import {Text} from '@astryxdesign/core/Text';
+import {VStack} from '@astryxdesign/core/Layout';
+import {Card} from '@astryxdesign/core/Card';
+import {Popover} from '@astryxdesign/core/Popover';
+import {splitTypeRefSegments} from './parsePropType';
+import type {TypeDefinition} from '../../generated/componentRegistry';
+import {CodeExampleBlock} from '../CodeExampleBlock';
+
+const styles = stylex.create({
+ // Inline link treatment for type-name definition triggers, mirroring the
+ // authored-docs link pattern (docs/inlineMarkdown.tsx) on a button element
+ // so the trigger stays keyboard-focusable with a visible focus ring.
+ typeRefTrigger: {
+ backgroundColor: 'transparent',
+ borderStyle: 'none',
+ padding: 0,
+ // A button's UA text-align is `center`, which centres a wrapped type name
+ // in the fixed-width Type column of the hook tables.
+ textAlign: 'start',
+ fontFamily: 'inherit',
+ fontSize: 'inherit',
+ lineHeight: 'inherit',
+ cursor: 'pointer',
+ color: 'var(--color-text-accent)',
+ textDecorationLine: 'underline',
+ textDecorationThickness: '1px',
+ textUnderlineOffset: '0.16em',
+ transition: 'color 120ms ease, text-decoration-color 120ms ease',
+ ':hover': {
+ '@media (hover: hover)': {
+ color: 'var(--color-accent)',
+ textDecorationThickness: '2px',
+ },
+ },
+ ':focus-visible': {
+ borderRadius: 'var(--radius-sm)',
+ outline: '2px solid var(--color-accent)',
+ outlineOffset: 2,
+ },
+ },
+});
+
+/**
+ * Inline definition trigger for a type name: the name itself renders as a
+ * link-styled button that opens the extracted declaration so readers can
+ * inspect the shape without leaving the table (#2682). The popover mirrors
+ * the Popover + Card + CodeExampleBlock pattern used by PackageActions.
+ */
+function TypeDefinitionTrigger({def}: {def: TypeDefinition}) {
+ return (
+ <Popover
+ width="min(480px, calc(100vw - 32px))"
+ label={`${def.name} type definition`}
+ content={
+ <VStack gap={1}>
+ <Text type="supporting" color="secondary">
+ {def.sourcePath}
+ </Text>
+ <Card padding={0}>
+ <CodeExampleBlock
+ code={def.definition}
+ language="typescript"
+ size="sm"
+ hasCopyButton
+ maxHeight={320}
+ width="100%"
+ />
+ </Card>
+ </VStack>
+ }>
+ <button type="button" {...stylex.props(styles.typeRefTrigger)}>
+ {def.name}
+ </button>
+ </Popover>
+ );
+}
+
+/**
+ * Resolve the type names a documented row references against the declarations
+ * attached to its registry entry. Unresolvable names are dropped, so an empty
+ * result means the row has no shape to surface and the caller should render
+ * its own plain type text.
+ */
+export function resolveTypeRefs(
+ typeRefs: string[] | undefined,
+ typeDefs: TypeDefinition[],
+): TypeDefinition[] {
+ return (typeRefs ?? [])
+ .map(name => typeDefs.find(def => def.name === name))
+ .filter(def => def != null);
+}
+
+/**
+ * A type string with each resolved name rendered as a
+ * {@link TypeDefinitionTrigger}; surrounding type syntax (generics
+ * punctuation, unions) stays plain text.
+ */
+export function TypeRefText({
+ type,
+ defs,
+}: {
+ type: string;
+ defs: TypeDefinition[];
+}) {
+ const segments = splitTypeRefSegments(
+ type,
+ defs.map(def => def.name),
+ );
+ return (
+ <>
+ {segments.map((segment, i) => {
+ const def = segment.isRef
+ ? defs.find(d => d.name === segment.text)
+ : undefined;
+ return def ? (
+ <TypeDefinitionTrigger key={i} def={def} />
+ ) : (
+ <span key={i}>{segment.text}</span>
+ );
+ })}
+ </>
+ );
+}