Skip to content

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

TypeScript

feat(Markdown, CodeBlock): contentWidth prop + compact header without line numbers (#1289)

Cindy Zhang5f08e02e542d
diff --git a/apps/storybook/stories/Markdown.stories.tsx b/apps/storybook/stories/Markdown.stories.tsx
index df7d7a2796..368d718e4d 100644
--- a/apps/storybook/stories/Markdown.stories.tsx
+++ b/apps/storybook/stories/Markdown.stories.tsx
@@ -74,7 +74,7 @@ const SAMPLE_MD = [
const STREAMING_RESPONSE = [
'## Setting Up a Design System',
'',
- 'A design system is more than a component library — it\'s a **shared language** between design and engineering. Here\'s how to build one that scales.',
+ "A design system is more than a component library — it's a **shared language** between design and engineering. Here's how to build one that scales.",
'',
'### 1. Start with Tokens',
'',
@@ -83,23 +83,23 @@ const STREAMING_RESPONSE = [
'```typescript',
'const tokens = {',
' color: {',
- ' primary: \'#0066FF\',',
- ' secondary: \'#6B7280\',',
- ' success: \'#10B981\',',
- ' danger: \'#EF4444\',',
+ " primary: '#0066FF',",
+ " secondary: '#6B7280',",
+ " success: '#10B981',",
+ " danger: '#EF4444',",
' },',
' spacing: {',
- ' xs: \'4px\',',
- ' sm: \'8px\',',
- ' md: \'16px\',',
- ' lg: \'24px\',',
- ' xl: \'32px\',',
+ " xs: '4px',",
+ " sm: '8px',",
+ " md: '16px',",
+ " lg: '24px',",
+ " xl: '32px',",
' },',
' radius: {',
- ' sm: \'4px\',',
- ' md: \'8px\',',
- ' lg: \'16px\',',
- ' full: \'9999px\',',
+ " sm: '4px',",
+ " md: '8px',",
+ " lg: '16px',",
+ " full: '9999px',",
' },',
'};',
'```',
@@ -113,7 +113,7 @@ const STREAMING_RESPONSE = [
'- **Composable** — small pieces that combine into complex UIs',
'- **Accessible** — keyboard navigation and screen reader support built-in',
'- **Themeable** — visual customization without forking',
- '- **Documented** — usage examples, props tables, and do/don\'t guidelines',
+ "- **Documented** — usage examples, props tables, and do/don't guidelines",
'',
'> The best design systems are *opinionated enough* to ensure consistency, but *flexible enough* to handle edge cases gracefully.',
'',
@@ -145,7 +145,7 @@ const STREAMING_RESPONSE = [
'',
'---',
'',
- 'The most important thing? **Ship early, iterate often.** A design system that exists and is used beats a perfect one that\'s still in planning.',
+ "The most important thing? **Ship early, iterate often.** A design system that exists and is used beats a perfect one that's still in planning.",
].join('\n');
export const Default: Story = {
@@ -223,7 +223,13 @@ export const Streaming: Story = {
return (
<div>
- <div style={{marginBlockEnd: 12, display: 'flex', gap: 8, alignItems: 'center'}}>
+ <div
+ style={{
+ marginBlockEnd: 12,
+ display: 'flex',
+ gap: 8,
+ alignItems: 'center',
+ }}>
<XDSButton
label="Replay"
variant="secondary"
@@ -232,10 +238,16 @@ export const Streaming: Story = {
isDisabled={isStreaming}
/>
<span style={{fontSize: 12, color: '#666'}}>
- {isStreaming ? `Streaming... ${charIndex}/${text.length}` : 'Complete'}
+ {isStreaming
+ ? `Streaming... ${charIndex}/${text.length}`
+ : 'Complete'}
</span>
</div>
- <XDSMarkdown key={key} isStreaming={isStreaming} density="compact" headingLevelStart={3}>
+ <XDSMarkdown
+ key={key}
+ isStreaming={isStreaming}
+ density="compact"
+ headingLevelStart={3}>
{text.slice(0, charIndex)}
</XDSMarkdown>
</div>
diff --git a/packages/core/src/CodeBlock/XDSCodeBlock.tsx b/packages/core/src/CodeBlock/XDSCodeBlock.tsx
index f53d07cd7f..615d276f19 100644
--- a/packages/core/src/CodeBlock/XDSCodeBlock.tsx
+++ b/packages/core/src/CodeBlock/XDSCodeBlock.tsx
@@ -19,6 +19,7 @@ import {
useState,
useCallback,
useMemo,
+ type CSSProperties,
} from 'react';
import * as React from 'react';
import type {XDSBaseProps} from '../XDSBaseProps';
@@ -32,8 +33,11 @@ import {
fontWeightVars,
typeScaleVars,
borderVars,
+ durationVars,
+ easeVars,
} from '../theme/tokens.stylex';
import {xdsClassName, mergeProps} from '../utils';
+import {XDSIcon} from '../Icon';
import {tokenize, tokenizeAsync, SYNC_TOKENIZE_THRESHOLD} from './tokenizer';
import type {Token} from './tokenizer';
import {ensureHighlightStyles} from './highlightStyles';
@@ -46,6 +50,7 @@ import {applyHighlightRangesChunked} from './highlightRanges';
const styles = stylex.create({
root: {
position: 'relative',
+ isolation: 'isolate',
display: 'flex',
flexDirection: 'column',
margin: 0,
@@ -58,12 +63,23 @@ const styles = stylex.create({
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
- paddingBlock: spacingVars['--spacing-2'],
paddingInline: spacingVars['--spacing-4'],
- borderBottom: `${borderVars['--border-width']} solid ${colorVars['--color-border']}`,
backgroundColor: 'var(--color-syntax-background)',
+ position: 'sticky',
+ top: 0,
+ zIndex: 1,
+ },
+ headerWithDivider: {
+ paddingBlock: spacingVars['--spacing-2'],
+ borderBottom: `${borderVars['--border-width']} solid ${colorVars['--color-border']}`,
+ },
+ headerCompact: {
+ paddingBlock: spacingVars['--spacing-2'],
},
headerTitle: {
+ display: 'flex',
+ alignItems: 'center',
+ gap: spacingVars['--spacing-1'],
fontSize: textSizeVars['--font-size-sm'],
fontFamily: typographyVars['--font-family-code'],
fontWeight: fontWeightVars['--font-weight-medium'],
@@ -75,10 +91,48 @@ const styles = stylex.create({
overflowX: 'auto',
overflowY: 'auto',
},
+
codeWrapper: {
display: 'flex',
minWidth: 'fit-content',
},
+ codeWrapperCompact: {
+ marginBlockStart: `calc(-1 * ${spacingVars['--spacing-2']})`,
+ },
+ // Collapse animation via grid-template-rows
+ collapseGrid: {
+ display: 'grid',
+ gridTemplateRows: '1fr',
+ transitionProperty: 'grid-template-rows',
+ transitionDuration: durationVars['--duration-medium'],
+ transitionTimingFunction: easeVars['--ease-standard'],
+ },
+ collapseGridCollapsed: {
+ gridTemplateRows: '0fr',
+ },
+ collapseInner: {
+ overflow: 'hidden',
+ minHeight: 0,
+ },
+ collapseChevron: {
+ display: 'inline-flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ flexShrink: 0,
+ width: '14px',
+ height: '14px',
+ color: 'var(--color-syntax-comment)',
+ transitionProperty: 'transform',
+ transitionDuration: durationVars['--duration-fast'],
+ transitionTimingFunction: easeVars['--ease-standard'],
+ },
+ collapseChevronCollapsed: {
+ transform: 'rotate(180deg)',
+ },
+ headerCollapsible: {
+ cursor: 'pointer',
+ userSelect: 'none',
+ },
gutter: {
flexShrink: 0,
paddingBlock: spacingVars['--spacing-3'],
@@ -139,6 +193,7 @@ const styles = stylex.create({
alignItems: 'center',
justifyContent: 'center',
padding: spacingVars['--spacing-1'],
+ marginInlineEnd: `calc(-1 * ${spacingVars['--spacing-2']})`,
border: 'none',
borderRadius: radiusVars['--radius-inner'],
backgroundColor: {
@@ -239,6 +294,20 @@ export interface XDSCodeBlockProps extends XDSBaseProps<HTMLPreElement> {
onCopy?: () => void;
isWrapped?: boolean;
maxHeight?: number | string;
+ /**
+ * Allow collapsing the code body into just the header bar.
+ * Starts expanded; the header becomes clickable to toggle.
+ * Only shows the toggle when the code exceeds `collapsibleThreshold` lines.
+ * @default false
+ */
+ isCollapsible?: boolean;
+ /**
+ * Minimum number of lines before the collapse toggle appears.
+ * Below this threshold the code block renders normally even when
+ * `isCollapsible` is true.
+ * @default 10
+ */
+ collapsibleThreshold?: number;
size?: 'sm' | 'md';
tokenizer?: (
code: string,
@@ -523,6 +592,8 @@ export function XDSCodeBlock({
onCopy,
isWrapped = false,
maxHeight,
+ isCollapsible = false,
+ collapsibleThreshold = 10,
size = 'md',
tokenizer: customTokenizer,
highlightMode = 'auto',
@@ -571,7 +642,12 @@ export function XDSCodeBlock({
hasLanguageLabel && language !== 'plaintext' ? language : null;
const showHeader = title != null || languageLabel != null;
- const scrollStyle: React.CSSProperties | undefined = maxHeight
+ // Collapse state — starts expanded, user can collapse long blocks
+ const canCollapse = isCollapsible && lines.length >= collapsibleThreshold;
+ const [isCollapsed, setIsCollapsed] = useState(false);
+
+ const scrollContainerRef = useRef<HTMLDivElement>(null);
+ const scrollStyle: CSSProperties | undefined = maxHeight
? {maxHeight: typeof maxHeight === 'number' ? `${maxHeight}px` : maxHeight}
: undefined;
@@ -615,6 +691,94 @@ export function XDSCodeBlock({
</button>
) : null;
+ // Header element — clickable when collapsible
+ const headerEl = showHeader ? (
+ <div
+ role={canCollapse ? 'button' : undefined}
+ tabIndex={canCollapse ? 0 : undefined}
+ aria-expanded={canCollapse ? !isCollapsed : undefined}
+ onClick={canCollapse ? () => setIsCollapsed(prev => !prev) : undefined}
+ onKeyDown={
+ canCollapse
+ ? (e: React.KeyboardEvent) => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ setIsCollapsed(prev => !prev);
+ }
+ }
+ : undefined
+ }
+ {...stylex.props(
+ styles.header,
+ hasLineNumbers ? styles.headerWithDivider : styles.headerCompact,
+ canCollapse && styles.headerCollapsible,
+ )}>
+ <span {...stylex.props(styles.headerTitle)}>
+ {title}
+ {title && languageLabel ? ' — ' : ''}
+ {languageLabel}
+ {canCollapse && (
+ <span
+ {...stylex.props(
+ styles.collapseChevron,
+ isCollapsed && styles.collapseChevronCollapsed,
+ )}>
+ <XDSIcon icon="chevronDown" size="xsm" color="inherit" />
+ </span>
+ )}
+ </span>
+ {copyButtonEl}
+ </div>
+ ) : null;
+
+ // Code body
+ const codeBody = (
+ <div
+ ref={scrollContainerRef}
+ {...stylex.props(styles.scrollContainer)}
+ style={scrollStyle}>
+ <div
+ {...stylex.props(
+ styles.codeWrapper,
+ showHeader && !hasLineNumbers && styles.codeWrapperCompact,
+ )}>
+ {hasLineNumbers && (
+ <div
+ {...stylex.props(styles.gutter, gutterSizeStyle)}
+ aria-hidden="true">
+ {lines.map((_, i) => (
+ <div key={i} {...stylex.props(styles.gutterLine)}>
+ {i + 1}
+ </div>
+ ))}
+ </div>
+ )}
+ {useSpans ? (
+ <SpanCodeContent
+ code={code}
+ language={language}
+ lines={lines}
+ lineOffsets={lineOffsets}
+ highlightSet={highlightSet}
+ isWrapped={isWrapped}
+ sizeStyle={sizeStyle}
+ customTokenizer={customTokenizer}
+ />
+ ) : (
+ <RangeCodeContent
+ code={code}
+ language={language}
+ lines={lines}
+ highlightSet={highlightSet}
+ isWrapped={isWrapped}
+ sizeStyle={sizeStyle}
+ customTokenizer={customTokenizer}
+ />
+ )}
+ </div>
+ </div>
+ );
+
return (
<pre
ref={ref}
@@ -625,53 +789,18 @@ export function XDSCodeBlock({
style,
)}
{...props}>
- {showHeader && (
- <div {...stylex.props(styles.header)}>
- <span {...stylex.props(styles.headerTitle)}>
- {languageLabel}
- {languageLabel && title ? ' — ' : ''}
- {title}
- </span>
- {copyButtonEl}
+ {headerEl}
+ {canCollapse ? (
+ <div
+ {...stylex.props(
+ styles.collapseGrid,
+ isCollapsed && styles.collapseGridCollapsed,
+ )}>
+ <div {...stylex.props(styles.collapseInner)}>{codeBody}</div>
</div>
+ ) : (
+ codeBody
)}
- <div {...stylex.props(styles.scrollContainer)} style={scrollStyle}>
- <div {...stylex.props(styles.codeWrapper)}>
- {hasLineNumbers && (
- <div
- {...stylex.props(styles.gutter, gutterSizeStyle)}
- aria-hidden="true">
- {lines.map((_, i) => (
- <div key={i} {...stylex.props(styles.gutterLine)}>
- {i + 1}
- </div>
- ))}
- </div>
- )}
- {useSpans ? (
- <SpanCodeContent
- code={code}
- language={language}
- lines={lines}
- lineOffsets={lineOffsets}
- highlightSet={highlightSet}
- isWrapped={isWrapped}
- sizeStyle={sizeStyle}
- customTokenizer={customTokenizer}
- />
- ) : (
- <RangeCodeContent
- code={code}
- language={language}
- lines={lines}
- highlightSet={highlightSet}
- isWrapped={isWrapped}
- sizeStyle={sizeStyle}
- customTokenizer={customTokenizer}
- />
- )}
- </div>
- </div>
{!showHeader && copyButtonEl}
</pre>
);
diff --git a/packages/core/src/Markdown/XDSMarkdown.tsx b/packages/core/src/Markdown/XDSMarkdown.tsx
index a4e52e8864..bb9f9c2171 100644
--- a/packages/core/src/Markdown/XDSMarkdown.tsx
+++ b/packages/core/src/Markdown/XDSMarkdown.tsx
@@ -84,6 +84,17 @@ export interface XDSMarkdownProps {
* @default 'label'
*/
citationStyle?: 'label' | 'number';
+ /**
+ * Max width for prose content (paragraphs, headings, lists, blockquotes).
+ * Tables and code blocks are unconstrained and can expand to the full
+ * container width. Use for readable line lengths in wide layouts.
+ *
+ * @example
+ * ```
+ * <XDSMarkdown contentWidth={640}>{text}</XDSMarkdown>
+ * ```
+ */
+ contentWidth?: number | string;
xstyle?: StyleXStyles;
className?: string;
style?: React.CSSProperties;
@@ -94,6 +105,15 @@ export interface XDSMarkdownProps {
// Styles
// ---------------------------------------------------------------------------
+const dynamicStyles = stylex.create({
+ proseWidth: (maxWidth: string) => ({
+ maxWidth,
+ }),
+ tableMinWidth: (minWidth: string) => ({
+ minWidth,
+ }),
+});
+
const styles = stylex.create({
root: {
fontFamily: typographyVars['--font-family-body'],
@@ -235,7 +255,8 @@ const styles = stylex.create({
},
table: {
borderCollapse: 'collapse',
- width: '100%',
+ width: 'auto',
+ maxWidth: '100%',
},
th: {
fontWeight: fontWeightVars['--font-weight-semibold'],
@@ -780,6 +801,7 @@ function renderBlock(
onLinkClick: XDSMarkdownProps['onLinkClick'] | undefined,
cursor: StreamingCursor,
citationCtx: CitationContext | null,
+ contentWidthValue: string | null,
): React.ReactNode {
const spacing = getElementSpacing(node, density);
const isFirst = index === 0;
@@ -802,6 +824,9 @@ function renderBlock(
styles.headingBase,
headingStyles[level],
spacing,
+ contentWidthValue != null
+ ? dynamicStyles.proseWidth(contentWidthValue)
+ : null,
isFirst && styles.noMarginBlockStart,
isLast && styles.noMarginBlockEnd,
)}>
@@ -817,6 +842,9 @@ function renderBlock(
key={index}
{...stylex.props(
spacing,
+ contentWidthValue != null
+ ? dynamicStyles.proseWidth(contentWidthValue)
+ : null,
isFirst && styles.noMarginBlockStart,
isLast && styles.noMarginBlockEnd,
)}>
@@ -836,7 +864,11 @@ function renderBlock(
isFirst && styles.noMarginBlockStart,
isLast && styles.noMarginBlockEnd,
)}>
- <XDSCodeBlock code={node.content} language={node.language} />
+ <XDSCodeBlock
+ code={node.content}
+ language={node.language}
+ isCollapsible
+ />
</div>
);
}
@@ -847,6 +879,9 @@ function renderBlock(
{...stylex.props(
styles.blockquote,
spacing,
+ contentWidthValue != null
+ ? dynamicStyles.proseWidth(contentWidthValue)
+ : null,
isFirst && styles.noMarginBlockStart,
isLast && styles.noMarginBlockEnd,
)}>
@@ -860,6 +895,7 @@ function renderBlock(
onLinkClick,
cursor,
citationCtx,
+ contentWidthValue,
),
)}
</blockquote>
@@ -917,6 +953,7 @@ function renderBlock(
onLinkClick,
cursor,
citationCtx,
+ contentWidthValue,
),
)}
</>
@@ -952,6 +989,9 @@ function renderBlock(
key={index}
{...stylex.props(
spacing,
+ contentWidthValue != null
+ ? dynamicStyles.proseWidth(contentWidthValue)
+ : null,
isFirst && styles.noMarginBlockStart,
isLast && styles.noMarginBlockEnd,
)}>
@@ -987,6 +1027,7 @@ function renderBlock(
onLinkClick,
cursor,
citationCtx,
+ contentWidthValue,
),
)}
</>
@@ -1024,7 +1065,13 @@ function renderBlock(
isFirst && styles.noMarginBlockStart,
isLast && styles.noMarginBlockEnd,
)}>
- <table {...stylex.props(styles.table)}>
+ <table
+ {...stylex.props(
+ styles.table,
+ contentWidthValue != null
+ ? dynamicStyles.tableMinWidth(contentWidthValue)
+ : null,
+ )}>
<thead>
<tr>
{node.headers.map((h, i) => (
@@ -1136,6 +1183,7 @@ export function XDSMarkdown({
onLinkClick,
sources,
citationStyle = 'label',
+ contentWidth = 680,
xstyle,
className,
style,
@@ -1208,6 +1256,11 @@ export function XDSMarkdown({
onLinkClick,
cursor,
citationCtx,
+ contentWidth
+ ? typeof contentWidth === 'number'
+ ? `${contentWidth}px`
+ : contentWidth
+ : null,
),
)}
</div>