Skip to content

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

TypeScript

fix(docsite): render markdown in doc text (#2813)

Cindy Zhangaee8f77a9abb
diff --git a/.changeset/markdown-inline-mode.md b/.changeset/markdown-inline-mode.md
new file mode 100644
index 0000000000..e7e437003a
--- /dev/null
+++ b/.changeset/markdown-inline-mode.md
@@ -0,0 +1,5 @@
+---
+'@xds/core': patch
+---
+
+`XDSMarkdown` now supports `display="inline"` for rendering inline markdown spans that inherit surrounding typography. Use it for doc text and table cells that need markdown formatting without block-level wrappers.
diff --git a/apps/docsite/src/components/MarkdownText.tsx b/apps/docsite/src/components/MarkdownText.tsx
new file mode 100644
index 0000000000..bb9fea2bf2
--- /dev/null
+++ b/apps/docsite/src/components/MarkdownText.tsx
@@ -0,0 +1,71 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+import type {ComponentProps} from 'react';
+import {XDSMarkdown} from '@xds/core/Markdown';
+import {XDSVStack} from '@xds/core/Layout';
+import {XDSText} from '@xds/core/Text';
+
+type XDSTextProps = ComponentProps<typeof XDSText>;
+
+interface MarkdownTextProps {
+ children: string;
+ type?: XDSTextProps['type'];
+ color?: XDSTextProps['color'];
+ weight?: XDSTextProps['weight'];
+ display?: XDSTextProps['display'];
+ style?: XDSTextProps['style'];
+}
+
+export function MarkdownText({
+ children,
+ type = 'body',
+ color,
+ weight,
+ display,
+ style,
+}: MarkdownTextProps) {
+ const paragraphs = splitMarkdownParagraphs(children);
+
+ if (paragraphs.length === 0) {
+ return null;
+ }
+
+ if (paragraphs.length === 1) {
+ return (
+ <XDSText
+ type={type}
+ color={color}
+ weight={weight}
+ display={display}
+ style={style}>
+ <XDSMarkdown display="inline">{paragraphs[0]}</XDSMarkdown>
+ </XDSText>
+ );
+ }
+
+ return (
+ <XDSVStack gap={2} style={style}>
+ {paragraphs.map((paragraph, index) => (
+ <XDSText
+ key={index}
+ as="p"
+ type={type}
+ color={color}
+ weight={weight}
+ display="block">
+ <XDSMarkdown display="inline">{paragraph}</XDSMarkdown>
+ </XDSText>
+ ))}
+ </XDSVStack>
+ );
+}
+
+function splitMarkdownParagraphs(markdown: string): string[] {
+ return markdown
+ .trim()
+ .split(/\n{2,}/)
+ .map(block => block.replace(/\s*\n\s*/g, ' ').trim())
+ .filter(Boolean);
+}
diff --git a/apps/docsite/src/components/component-detail/Anatomy.tsx b/apps/docsite/src/components/component-detail/Anatomy.tsx
index e89356bb99..5de978f1b9 100644
--- a/apps/docsite/src/components/component-detail/Anatomy.tsx
+++ b/apps/docsite/src/components/component-detail/Anatomy.tsx
@@ -8,6 +8,7 @@ import {XDSSection} from '@xds/core/Section';
import {XDSTable, pixel} from '@xds/core/Table';
import {XDSBadge} from '@xds/core/Badge';
import type {AnatomyElement} from '../../generated/componentRegistry';
+import {MarkdownText} from '../MarkdownText';
interface AnatomyProps {
elements: AnatomyElement[];
@@ -45,7 +46,15 @@ export function Anatomy({elements}: AnatomyProps) {
<XDSBadge label="required" variant="info" />
) : null,
},
- {key: 'description', header: 'Description'},
+ {
+ key: 'description',
+ header: 'Description',
+ renderCell: (item: Record<string, unknown>) => (
+ <MarkdownText type="body">
+ {item.description as string}
+ </MarkdownText>
+ ),
+ },
]}
density="spacious"
dividers="rows"
diff --git a/apps/docsite/src/components/component-detail/ComponentDetailClient.tsx b/apps/docsite/src/components/component-detail/ComponentDetailClient.tsx
index 2b1a831d86..818cbf4f94 100644
--- a/apps/docsite/src/components/component-detail/ComponentDetailClient.tsx
+++ b/apps/docsite/src/components/component-detail/ComponentDetailClient.tsx
@@ -18,6 +18,7 @@ import {ComponentPreviewTheme} from './ComponentPreviewTheme';
import {BestPractices} from './BestPractices';
import {HookSignature} from './HookSignature';
import {ExampleBlock} from './ExampleBlock';
+import {MarkdownText} from '../MarkdownText';
import {
InteractivePreviewStage,
useInteractiveState,
@@ -69,9 +70,9 @@ function OverviewContent({
<XDSHeading level={2} type="display-3">
Usage
</XDSHeading>
- <XDSText type="large" weight="normal">
+ <MarkdownText type="large" weight="normal">
{comp.usage.description}
- </XDSText>
+ </MarkdownText>
<CodeExampleBlock
code={importPath}
diff --git a/apps/docsite/src/components/component-detail/ExampleBlock.tsx b/apps/docsite/src/components/component-detail/ExampleBlock.tsx
index a66a8cc09c..f1e8e97ecd 100644
--- a/apps/docsite/src/components/component-detail/ExampleBlock.tsx
+++ b/apps/docsite/src/components/component-detail/ExampleBlock.tsx
@@ -16,6 +16,7 @@ import type {ExampleEntry} from '../../generated/exampleRegistry';
import {ComponentPreviewTheme} from './ComponentPreviewTheme';
import {buildPlaygroundHref} from '../playgroundLink';
import {trackOpenPlayground} from '../../lib/analytics';
+import {MarkdownText} from '../MarkdownText';
function LivePreview({entry}: {entry: ExampleEntry}) {
const [Component, setComponent] = useState<ComponentType | null>(null);
@@ -102,9 +103,9 @@ export function ExampleBlock({entry}: ExampleBlockProps) {
</XDSSection>
<XDSSection variant="muted" padding={tab === 'code' ? 0 : 4}>
{tab === 'description' ? (
- <XDSText type="body">
+ <MarkdownText type="body">
{entry.description || 'No description available.'}
- </XDSText>
+ </MarkdownText>
) : (
<CodeExampleBlock
code={entry.source}
diff --git a/apps/docsite/src/components/component-detail/HookSignature.tsx b/apps/docsite/src/components/component-detail/HookSignature.tsx
index a0b20785ec..d449b45d4c 100644
--- a/apps/docsite/src/components/component-detail/HookSignature.tsx
+++ b/apps/docsite/src/components/component-detail/HookSignature.tsx
@@ -13,6 +13,7 @@ import type {
HookParamDoc,
HookReturnDoc,
} from '../../generated/componentRegistry';
+import {MarkdownText} from '../MarkdownText';
interface HookSignatureProps {
params: HookParamDoc[];
@@ -39,9 +40,9 @@ function ParamRowMobile({param}: {param: HookParamDoc}) {
{formatParamType(param.type, param.default)}
</XDSText>
{param.description && (
- <XDSText type="body" color="secondary">
+ <MarkdownText type="body" color="secondary">
{param.description}
- </XDSText>
+ </MarkdownText>
)}
</XDSVStack>
);
@@ -57,9 +58,9 @@ function ReturnRowMobile({ret}: {ret: HookReturnDoc}) {
{ret.type}
</XDSText>
{ret.description && (
- <XDSText type="body" color="secondary">
+ <MarkdownText type="body" color="secondary">
{ret.description}
- </XDSText>
+ </MarkdownText>
)}
</XDSVStack>
);
@@ -126,7 +127,15 @@ export function HookSignature({params, returns}: HookSignatureProps) {
</XDSText>
),
},
- {key: 'description', header: 'Description'},
+ {
+ key: 'description',
+ header: 'Description',
+ renderCell: (item: Record<string, unknown>) => (
+ <MarkdownText type="body">
+ {item.description as string}
+ </MarkdownText>
+ ),
+ },
]}
density="spacious"
dividers="rows"
@@ -173,7 +182,15 @@ export function HookSignature({params, returns}: HookSignatureProps) {
</XDSText>
),
},
- {key: 'description', header: 'Description'},
+ {
+ key: 'description',
+ header: 'Description',
+ renderCell: (item: Record<string, unknown>) => (
+ <MarkdownText type="body">
+ {item.description as string}
+ </MarkdownText>
+ ),
+ },
]}
density="spacious"
dividers="rows"
diff --git a/apps/docsite/src/components/component-detail/PlaygroundPropsTable.tsx b/apps/docsite/src/components/component-detail/PlaygroundPropsTable.tsx
index 089570c6b4..d46c3da69c 100644
--- a/apps/docsite/src/components/component-detail/PlaygroundPropsTable.tsx
+++ b/apps/docsite/src/components/component-detail/PlaygroundPropsTable.tsx
@@ -31,6 +31,7 @@ import type {
ElementDescriptor,
PropDoc,
} from '../../generated/componentRegistry';
+import {MarkdownText} from '../MarkdownText';
function formatType(type: string, defaultValue?: string): React.ReactNode {
const parts = type.split(/\s*\|\s*/);
@@ -481,9 +482,9 @@ function PropRow({
{formatType(prop.type, prop.default)}
</XDSText>
{prop.description != null && prop.description !== '' && (
- <XDSText type="body" color="secondary">
+ <MarkdownText type="body" color="secondary">
{prop.description}
- </XDSText>
+ </MarkdownText>
)}
{knob && onChange && (
<InlineControl
@@ -509,9 +510,9 @@ function PropRow({
{formatType(prop.type, prop.default)}
</XDSText>
{prop.description != null && prop.description !== '' && (
- <XDSText type="body" color="secondary" style={{marginTop: 6}}>
+ <MarkdownText type="body" color="secondary" style={{marginTop: 6}}>
{prop.description}
- </XDSText>
+ </MarkdownText>
)}
</div>
{knob && onChange && (
diff --git a/apps/docsite/src/components/component-detail/PropsTable.tsx b/apps/docsite/src/components/component-detail/PropsTable.tsx
index afd3548d1d..657a188bf7 100644
--- a/apps/docsite/src/components/component-detail/PropsTable.tsx
+++ b/apps/docsite/src/components/component-detail/PropsTable.tsx
@@ -8,6 +8,7 @@ import {XDSSection} from '@xds/core/Section';
import {XDSTable, pixel} from '@xds/core/Table';
import {XDSBadge} from '@xds/core/Badge';
import type {PropDoc} from '../../generated/componentRegistry';
+import {MarkdownText} from '../MarkdownText';
function formatType(type: string, defaultValue?: string): string {
if (defaultValue != null) {
@@ -69,7 +70,15 @@ export function PropsTable({props, heading}: PropsTableProps) {
</XDSText>
),
},
- {key: 'description', header: 'Description'},
+ {
+ key: 'description',
+ header: 'Description',
+ renderCell: (item: Record<string, unknown>) => (
+ <MarkdownText type="body">
+ {item.description as string}
+ </MarkdownText>
+ ),
+ },
]}
density="spacious"
dividers="rows"
diff --git a/apps/docsite/src/components/docs/BestPracticesBlock.tsx b/apps/docsite/src/components/docs/BestPracticesBlock.tsx
index 4f170d5161..467d1666fb 100644
--- a/apps/docsite/src/components/docs/BestPracticesBlock.tsx
+++ b/apps/docsite/src/components/docs/BestPracticesBlock.tsx
@@ -5,6 +5,7 @@
import {XDSBadge} from '@xds/core/Badge';
import {XDSCard} from '@xds/core/Card';
import {XDSTable, pixel} from '@xds/core/Table';
+import {MarkdownText} from '../MarkdownText';
interface BestPracticesItem {
guidance: boolean;
@@ -33,7 +34,15 @@ export function BestPracticesBlock({items}: {items: BestPracticesItem[]}) {
/>
),
},
- {key: 'description', header: 'Practices'},
+ {
+ key: 'description',
+ header: 'Practices',
+ renderCell: (item: Record<string, unknown>) => (
+ <MarkdownText type="body">
+ {item.description as string}
+ </MarkdownText>
+ ),
+ },
]}
density="spacious"
dividers="rows"
diff --git a/apps/storybook/stories/Markdown.stories.tsx b/apps/storybook/stories/Markdown.stories.tsx
index 4231a63a62..895ca813a7 100644
--- a/apps/storybook/stories/Markdown.stories.tsx
+++ b/apps/storybook/stories/Markdown.stories.tsx
@@ -5,6 +5,7 @@ import type {Meta, StoryObj} from '@storybook/react';
import {XDSMarkdown} from '@xds/core/Markdown';
import {XDSButton} from '@xds/core/Button';
import {XDSLink} from '@xds/core/Link';
+import {XDSText} from '@xds/core/Text';
const meta: Meta<typeof XDSMarkdown> = {
title: 'Core/Markdown',
@@ -20,6 +21,10 @@ const meta: Meta<typeof XDSMarkdown> = {
options: [1, 2, 3, 4, 5, 6],
},
isStreaming: {control: 'boolean'},
+ display: {
+ control: 'select',
+ options: ['block', 'inline'],
+ },
},
};
@@ -181,6 +186,41 @@ export const ShiftedHeadings: Story = {
},
};
+export const InlineDisplay: Story = {
+ name: 'Inline Display',
+ render: () => (
+ <div style={{maxWidth: 680, display: 'grid', gap: 16}}>
+ <XDSText type="large" display="block">
+ <XDSMarkdown display="inline">
+ {
+ 'Use `value` with **controlled state** and [read the docs](https://example.com) without creating block wrappers.'
+ }
+ </XDSMarkdown>
+ </XDSText>
+
+ <div
+ style={{
+ border: '1px solid #ddd',
+ borderRadius: 8,
+ padding: 12,
+ display: 'grid',
+ gap: 6,
+ }}>
+ <XDSText type="body" weight="bold" display="block">
+ Prop description
+ </XDSText>
+ <XDSText type="body" color="secondary" display="block">
+ <XDSMarkdown display="inline">
+ {
+ 'Accepts an action item `{label, onClick?, icon?}`, a divider `{type: "divider"}`, or a section `{type: "section", items: [...]}`.'
+ }
+ </XDSMarkdown>
+ </XDSText>
+ </div>
+ </div>
+ ),
+};
+
export const TableFocused: Story = {
name: 'Table',
args: {
diff --git a/packages/core/src/Markdown/Markdown.doc.mjs b/packages/core/src/Markdown/Markdown.doc.mjs
index 9e39365118..ebf1e0b79f 100644
--- a/packages/core/src/Markdown/Markdown.doc.mjs
+++ b/packages/core/src/Markdown/Markdown.doc.mjs
@@ -24,6 +24,13 @@ export const docs = {
description: 'The markdown string to render.',
required: true,
},
+ {
+ name: 'display',
+ type: "'block' | 'inline'",
+ description:
+ "Display type. Markdown defaults to block. Use 'inline' for markdown spans embedded inside text.",
+ default: "'block'",
+ },
{
name: 'density',
type: "\'default\' | \'compact\'",
@@ -133,6 +140,18 @@ export const docs = {
],
},
examples: [
+ {
+ label: 'Inline display',
+ code: `
+import {XDSText} from '@xds/core/Text';
+
+<XDSText>
+ This description includes{' '}
+ <XDSMarkdown display="inline">{'\`inline code\` and **bold text**'}</XDSMarkdown>
+ .
+</XDSText>;
+`,
+ },
{
label: 'GFM autolinks',
code: `
@@ -176,6 +195,13 @@ export const docsZh = {
description: '要渲染的 Markdown 字符串。',
required: true,
},
+ {
+ name: 'display',
+ type: "'block' | 'inline'",
+ description:
+ "显示类型。Markdown 默认为 block。使用 'inline' 可在文本内嵌入 Markdown 片段。",
+ default: "'block'",
+ },
{
name: 'density',
type: "'default' | 'compact'",
diff --git a/packages/core/src/Markdown/XDSMarkdown.test.tsx b/packages/core/src/Markdown/XDSMarkdown.test.tsx
index 3d72b0c69c..2df3075e02 100644
--- a/packages/core/src/Markdown/XDSMarkdown.test.tsx
+++ b/packages/core/src/Markdown/XDSMarkdown.test.tsx
@@ -27,6 +27,26 @@ describe('XDSMarkdown', () => {
expect(screen.getByText('Hello world').tagName).toBe('P');
});
+ it('renders inline display without block wrappers', () => {
+ const {container} = render(
+ <XDSMarkdown display="inline">{'Use `code` and **bold**'}</XDSMarkdown>,
+ );
+
+ expect(container.firstElementChild?.tagName).toBe('SPAN');
+ expect(screen.queryByRole('document')).not.toBeInTheDocument();
+ expect(container.querySelector('p')).toBeNull();
+ expect(screen.getByText('code').tagName).toBe('CODE');
+ expect(screen.getByText('bold').tagName).toBe('STRONG');
+ });
+
+ it('renders links with inline display', () => {
+ render(<XDSMarkdown display="inline">{'[docs](/docs)'}</XDSMarkdown>);
+
+ const link = screen.getByText('docs');
+ expect(link.tagName).toBe('A');
+ expect(link.getAttribute('href')).toBe('/docs');
+ });
+
it('renders bold text', () => {
render(<XDSMarkdown>{'**bold text**'}</XDSMarkdown>);
expect(screen.getByText('bold text').tagName).toBe('STRONG');
diff --git a/packages/core/src/Markdown/XDSMarkdown.tsx b/packages/core/src/Markdown/XDSMarkdown.tsx
index ae92cc2e83..7041c45b3b 100644
--- a/packages/core/src/Markdown/XDSMarkdown.tsx
+++ b/packages/core/src/Markdown/XDSMarkdown.tsx
@@ -25,6 +25,7 @@ import {
durationVars,
easeVars,
} from '../theme/tokens.stylex';
+import type {XDSTextDisplay} from '../theme/types';
import {XDSCodeBlock, XDSCode} from '../CodeBlock';
import {XDSCheckboxList} from '../CheckboxList/XDSCheckboxList';
import {XDSCheckboxListItem} from '../CheckboxList/XDSCheckboxListItem';
@@ -47,6 +48,7 @@ import type {XDSCitationSource} from '../Citation/XDSCitation';
import {useXDSLinkComponent} from '../Link/useXDSLinkComponent';
import type {XDSLinkComponentType} from '../Link/types';
import {
+ parseInline,
parseMarkdown,
parseMarkdownIncremental,
createIncrementalState,
@@ -112,9 +114,15 @@ export interface XDSMarkdownComponents {
hr?: React.ComponentType<object>;
}
-export interface XDSMarkdownProps extends XDSBaseProps<HTMLDivElement> {
- ref?: React.Ref<HTMLDivElement>;
+export interface XDSMarkdownProps extends XDSBaseProps<HTMLElement> {
+ ref?: React.Ref<HTMLDivElement> | React.Ref<HTMLSpanElement>;
children: string;
+ /**
+ * Display type. Markdown defaults to block.
+ * Use 'inline' for markdown spans embedded inside surrounding text.
+ * @default 'block'
+ */
+ display?: XDSTextDisplay;
density?: 'default' | 'compact';
/**
* The HTML heading level that markdown `#` maps to.
@@ -231,6 +239,15 @@ const styles = stylex.create({
minWidth: 0,
overflowWrap: 'break-word',
},
+ inlineRoot: {
+ display: 'inline',
+ width: 'auto',
+ maxWidth: 'none',
+ fontFamily: 'inherit',
+ color: 'inherit',
+ lineHeight: 'inherit',
+ fontSize: 'inherit',
+ },
// Headings
headingBase: {
fontFamily: typographyVars['--font-family-heading'],
@@ -1517,6 +1534,7 @@ function renderBlock(
export function XDSMarkdown({
ref,
children,
+ display = 'block',
density = 'default',
headingLevelStart = 1,
isStreaming = false,
@@ -1561,6 +1579,9 @@ export function XDSMarkdown({
}
const blocks = useMemo(() => {
+ if (display === 'inline') {
+ return [];
+ }
if (isStreaming) {
if (smoothedText === '') {
incrementalStateRef.current = createIncrementalState();
@@ -1574,7 +1595,15 @@ export function XDSMarkdown({
);
}
return parseMarkdown(children, parseOptions);
- }, [smoothedText, children, isStreaming, parseOptions]);
+ }, [display, smoothedText, children, isStreaming, parseOptions]);
+
+ const inlineNodes = useMemo(() => {
+ if (display !== 'inline') {
+ return [];
+ }
+ const input = isStreaming ? trimStreamingArtifacts(smoothedText) : children;
+ return parseInline(input, parseOptions);
+ }, [display, smoothedText, children, isStreaming, parseOptions]);
// Track recent boundaries for stacked fade-in animation.
// The number of spans needed = ceil(animationDuration / tickInterval).
@@ -1591,15 +1620,19 @@ export function XDSMarkdown({
}, [token]);
const prevBlocksRef = useRef<BlockNode[]>([]);
+ const prevInlineNodesRef = useRef<InlineNode[]>([]);
const boundariesRef = useRef<number[]>([]);
const smoothedLen = smoothedText.length;
const boundaries = useMemo(() => {
void smoothedLen; // dep trigger
- const prevLen = countBlockTextLength(prevBlocksRef.current);
+ const prevLen =
+ display === 'inline'
+ ? countInlineTextLength(prevInlineNodesRef.current)
+ : countBlockTextLength(prevBlocksRef.current);
const next = computeBoundaries(boundariesRef.current, prevLen, maxSpans);
boundariesRef.current = next;
return next;
- }, [smoothedLen, maxSpans]);
+ }, [display, smoothedLen, maxSpans]);
const cursor: StreamingCursor = {
offset: 0,
@@ -1613,10 +1646,43 @@ export function XDSMarkdown({
? {sources, numberMap: new Map(), nextNumber: 1, style: citationStyle}
: null;
+ if (display === 'inline') {
+ const renderedInline = (
+ <span
+ ref={ref}
+ data-testid={testId}
+ {...mergeProps(
+ xdsThemeProps('markdown', {density}),
+ stylex.props(styles.root, styles.inlineRoot, xstyle),
+ className,
+ style,
+ )}>
+ {inlineNodes.map((node, i) =>
+ renderInline(
+ node,
+ i,
+ onLinkClick,
+ cursor,
+ citationCtx,
+ LinkComponent,
+ inlinePlugins,
+ components,
+ ),
+ )}
+ </span>
+ );
+
+ // Store current inline nodes for next render's boundary calculation.
+ prevInlineNodesRef.current = inlineNodes;
+ prevBlocksRef.current = [];
+
+ return renderedInline;
+ }
+
const rendered = (
<div
role="document"
- ref={ref}
+ ref={ref as React.Ref<HTMLDivElement>}
data-testid={testId}
{...mergeProps(
xdsThemeProps('markdown', {density}),
@@ -1652,6 +1718,7 @@ export function XDSMarkdown({
// This ref write is safe under StrictMode: both invocations produce the same
// blocks (same smoothedText → same useMemo result), so both write the same value.
prevBlocksRef.current = blocks;
+ prevInlineNodesRef.current = [];
return rendered;
}