Skip to content

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

TypeScript

feat(Toolbar): replace density with size, add XDSSizeContext cascade (#1448)

Cindy Zhangb3c9116ea82f
diff --git a/.github/scripts/codemod-verify.mjs b/.github/scripts/codemod-verify.mjs
index 59787e8ed5..7d67618ef5 100644
--- a/.github/scripts/codemod-verify.mjs
+++ b/.github/scripts/codemod-verify.mjs
@@ -156,7 +156,9 @@ async function main() {
// Also format the expected (PR) versions for a fair comparison
const formattedExpected = {};
for (const file of revertedFiles) {
- const tmpFile = file + '.expected.tmp';
+ // Use the original file extension so prettier can infer the parser
+ const ext = path.extname(file);
+ const tmpFile = file.replace(ext, `.expected${ext}`);
fs.writeFileSync(tmpFile, prVersions[file]);
try {
run(`npx prettier --write "${tmpFile}"`);
diff --git a/apps/sandbox/src/app/(fullscreen)/pages/docsite/page.tsx b/apps/sandbox/src/app/(fullscreen)/pages/docsite/page.tsx
index 0f41e1b024..6057df50b8 100644
--- a/apps/sandbox/src/app/(fullscreen)/pages/docsite/page.tsx
+++ b/apps/sandbox/src/app/(fullscreen)/pages/docsite/page.tsx
@@ -380,10 +380,7 @@ function DocsiteLandingTemplate() {
}
const qs = params.toString();
- router.replace(
- `/pages/docsite/${qs ? '?' + qs : ''}`,
- {scroll: false},
- );
+ router.replace(`/pages/docsite/${qs ? '?' + qs : ''}`, {scroll: false});
}, [
previewTarget,
useTarget,
@@ -455,15 +452,20 @@ function DocsiteLandingTemplate() {
[generatingSource],
);
- const handleUse = useCallback((index: number) => {
- viewBeforeEditorRef.current = activeView;
- setPreviewTarget(null);
- setUseTarget(index);
- setPanelTab('configure');
- setChatOpen(true);
- }, [activeView]);
+ const handleUse = useCallback(
+ (index: number) => {
+ viewBeforeEditorRef.current = activeView;
+ setPreviewTarget(null);
+ setUseTarget(index);
+ setPanelTab('configure');
+ setChatOpen(true);
+ },
+ [activeView],
+ );
- const viewBeforeEditorRef = useRef<'craft' | 'explore' | 'docs' | 'profile'>('craft');
+ const viewBeforeEditorRef = useRef<'craft' | 'explore' | 'docs' | 'profile'>(
+ 'craft',
+ );
const handleBackFromUse = useCallback(() => {
setUseTarget(null);
setChatOpen(false);
@@ -520,35 +522,38 @@ function DocsiteLandingTemplate() {
setActiveFilters(new Set());
}, []);
- const handleProfileAction = useCallback((action: 'craft' | 'bookmarked' | 'used' | 'settings') => {
- if (action === 'settings') {
- setIsSettingsOpen(true);
- } else if (action === 'craft') {
- setPreviewTarget(null);
- setCraftTitle('My Craft');
- setIsCraftResults(true);
- setIsProfileResults(true);
- setCraftStatusFilter('all');
- setCraftLoading(true);
- if (craftLoadingTimer.current) clearTimeout(craftLoadingTimer.current);
- craftLoadingTimer.current = setTimeout(() => {
- setCraftLoading(false);
- craftLoadingTimer.current = null;
- }, 900);
- } else {
- const label = action === 'bookmarked' ? 'Bookmarked' : 'Used';
- setPreviewTarget(null);
- setCraftTitle(label);
- setIsProfileResults(true);
- setIsCraftResults(false);
- setCraftLoading(true);
- if (craftLoadingTimer.current) clearTimeout(craftLoadingTimer.current);
- craftLoadingTimer.current = setTimeout(() => {
- setCraftLoading(false);
- craftLoadingTimer.current = null;
- }, 900);
- }
- }, []);
+ const handleProfileAction = useCallback(
+ (action: 'craft' | 'bookmarked' | 'used' | 'settings') => {
+ if (action === 'settings') {
+ setIsSettingsOpen(true);
+ } else if (action === 'craft') {
+ setPreviewTarget(null);
+ setCraftTitle('My Craft');
+ setIsCraftResults(true);
+ setIsProfileResults(true);
+ setCraftStatusFilter('all');
+ setCraftLoading(true);
+ if (craftLoadingTimer.current) clearTimeout(craftLoadingTimer.current);
+ craftLoadingTimer.current = setTimeout(() => {
+ setCraftLoading(false);
+ craftLoadingTimer.current = null;
+ }, 900);
+ } else {
+ const label = action === 'bookmarked' ? 'Bookmarked' : 'Used';
+ setPreviewTarget(null);
+ setCraftTitle(label);
+ setIsProfileResults(true);
+ setIsCraftResults(false);
+ setCraftLoading(true);
+ if (craftLoadingTimer.current) clearTimeout(craftLoadingTimer.current);
+ craftLoadingTimer.current = setTimeout(() => {
+ setCraftLoading(false);
+ craftLoadingTimer.current = null;
+ }, 900);
+ }
+ },
+ [],
+ );
const filteredTemplates = useMemo(() => {
return TEMPLATES.map((t, i) => ({...t, originalIndex: i})).filter(t => {
@@ -558,22 +563,34 @@ function DocsiteLandingTemplate() {
});
}, [templateFilter]);
- const craftStatusCounts = useMemo(() => ({
- published: PROFILE_CRAFT_ITEMS.filter(i => i.status === 'Published').length,
- draft: PROFILE_CRAFT_ITEMS.filter(i => i.status === 'Draft').length,
- review: PROFILE_CRAFT_ITEMS.filter(i => i.status === 'In Review').length,
- }), []);
+ const craftStatusCounts = useMemo(
+ () => ({
+ published: PROFILE_CRAFT_ITEMS.filter(i => i.status === 'Published')
+ .length,
+ draft: PROFILE_CRAFT_ITEMS.filter(i => i.status === 'Draft').length,
+ review: PROFILE_CRAFT_ITEMS.filter(i => i.status === 'In Review').length,
+ }),
+ [],
+ );
const filteredCraftItems = useMemo(() => {
if (craftStatusFilter === 'all') return PROFILE_CRAFT_ITEMS;
- return PROFILE_CRAFT_ITEMS.filter(item => item.status === craftStatusFilter);
+ return PROFILE_CRAFT_ITEMS.filter(
+ item => item.status === craftStatusFilter,
+ );
}, [craftStatusFilter]);
// Editor flow — same layout for all cards
if (useTarget !== null && activeView === 'craft') {
const isBlankCanvas = useTarget === -1;
const t = isBlankCanvas
- ? {name: 'Untitled', src: '', size: 'medium' as const, author: '', isOfficial: false}
+ ? {
+ name: 'Untitled',
+ src: '',
+ size: 'medium' as const,
+ author: '',
+ isOfficial: false,
+ }
: TEMPLATES[useTarget % TEMPLATES.length];
return (
<div
@@ -899,15 +916,31 @@ function DocsiteLandingTemplate() {
'craftTitleSlideIn 400ms 100ms cubic-bezier(0.16, 1, 0.3, 1) both',
}}>
{[
- {value: 'all', label: `All (${PROFILE_CRAFT_ITEMS.length})`},
- {value: 'Published', label: `Published (${craftStatusCounts.published})`},
- {value: 'Draft', label: `Draft (${craftStatusCounts.draft})`},
- {value: 'In Review', label: `In Review (${craftStatusCounts.review})`},
+ {
+ value: 'all',
+ label: `All (${PROFILE_CRAFT_ITEMS.length})`,
+ },
+ {
+ value: 'Published',
+ label: `Published (${craftStatusCounts.published})`,
+ },
+ {
+ value: 'Draft',
+ label: `Draft (${craftStatusCounts.draft})`,
+ },
+ {
+ value: 'In Review',
+ label: `In Review (${craftStatusCounts.review})`,
+ },
].map(tab => (
<XDSButton
key={tab.value}
label={tab.label}
- variant={craftStatusFilter === tab.value ? 'primary' : 'secondary'}
+ variant={
+ craftStatusFilter === tab.value
+ ? 'primary'
+ : 'secondary'
+ }
size="sm"
onClick={() => setCraftStatusFilter(tab.value)}
/>
@@ -964,7 +997,7 @@ function DocsiteLandingTemplate() {
</XDSText>
<XDSToolbar
label="View controls"
- density="compact"
+ size="sm"
startContent={
<>
<XDSButton
@@ -1285,8 +1318,7 @@ function DocsiteLandingTemplate() {
background:
'linear-gradient(90deg, var(--color-background-muted, #f0f0f0) 0%, var(--color-background-surface, #fafafa) 50%, var(--color-background-muted, #f0f0f0) 100%)',
backgroundSize: '800px 100%',
- animation:
- 'craftShimmer 1.6s ease-in-out infinite',
+ animation: 'craftShimmer 1.6s ease-in-out infinite',
borderRadius: '16px 16px 0 0',
}}
/>
@@ -1305,8 +1337,7 @@ function DocsiteLandingTemplate() {
background:
'linear-gradient(90deg, var(--color-background-muted, #f0f0f0) 0%, var(--color-background-surface, #fafafa) 50%, var(--color-background-muted, #f0f0f0) 100%)',
backgroundSize: '800px 100%',
- animation:
- 'craftShimmer 1.6s ease-in-out infinite',
+ animation: 'craftShimmer 1.6s ease-in-out infinite',
}}
/>
<div
@@ -1317,8 +1348,7 @@ function DocsiteLandingTemplate() {
background:
'linear-gradient(90deg, var(--color-background-muted, #f0f0f0) 0%, var(--color-background-surface, #fafafa) 50%, var(--color-background-muted, #f0f0f0) 100%)',
backgroundSize: '800px 100%',
- animation:
- 'craftShimmer 1.6s ease-in-out infinite',
+ animation: 'craftShimmer 1.6s ease-in-out infinite',
}}
/>
</div>
@@ -1350,7 +1380,8 @@ function DocsiteLandingTemplate() {
style={{
aspectRatio: '16 / 9',
overflow: 'hidden',
- backgroundColor: 'var(--color-background-muted, #f0f0f0)',
+ backgroundColor:
+ 'var(--color-background-muted, #f0f0f0)',
}}>
<img
src={item.img}
@@ -1423,7 +1454,10 @@ function DocsiteLandingTemplate() {
</div>
<div style={{marginLeft: 'auto'}}>
<XDSText type="supporting" color="secondary">
- {new Date(item.lastUpdated).toLocaleDateString('en-US', {month: 'short', day: 'numeric'})}
+ {new Date(item.lastUpdated).toLocaleDateString(
+ 'en-US',
+ {month: 'short', day: 'numeric'},
+ )}
</XDSText>
</div>
</div>
@@ -1431,7 +1465,12 @@ function DocsiteLandingTemplate() {
</XDSCard>
))}
{filteredCraftItems.length === 0 && (
- <div style={{gridColumn: '1 / -1', padding: 32, textAlign: 'center' as const}}>
+ <div
+ style={{
+ gridColumn: '1 / -1',
+ padding: 32,
+ textAlign: 'center' as const,
+ }}>
<XDSText type="body" color="secondary">
No items match this filter.
</XDSText>
@@ -1439,67 +1478,65 @@ function DocsiteLandingTemplate() {
)}
</div>
) : (
- <div
- style={{
- maxWidth: 2000,
- margin: '0 auto',
- display: 'grid',
- gridTemplateColumns: isMobile
- ? '1fr'
- : isTablet
- ? 'repeat(2, 1fr)'
- : 'repeat(3, 1fr)',
- gap: 16,
- }}>
- {filteredTemplates.map((template, i) => (
- <div
- key={`${template.name}-${template.originalIndex}`}
- style={{
- ...(craftTitle
- ? {
- animation: `craftCardFadeIn 400ms ${i * 50}ms cubic-bezier(0.16, 1, 0.3, 1) both`,
- }
- : undefined),
- filter: previewImageFilter,
- transition: 'filter 300ms ease',
- }}>
- <TemplateCard
- src={template.src}
- name={template.name}
- isSelected={selected.has(template.originalIndex)}
- isGenerating={
- isGenerating &&
- generatingSource !== template.originalIndex
- }
- cardSize={template.size}
- onSelect={() =>
- setSelected(prev => {
- const next = new Set(prev);
- if (next.has(template.originalIndex)) {
- next.delete(template.originalIndex);
- } else {
- next.add(template.originalIndex);
- }
- return next;
- })
- }
- onMoreLikeThis={() =>
- handleMoreLikeThis(template.originalIndex)
- }
- onUse={() => handleUse(template.originalIndex)}
- onPreview={() => handlePreview(template.originalIndex)}
- />
- </div>
- ))}
- </div>
+ <div
+ style={{
+ maxWidth: 2000,
+ margin: '0 auto',
+ display: 'grid',
+ gridTemplateColumns: isMobile
+ ? '1fr'
+ : isTablet
+ ? 'repeat(2, 1fr)'
+ : 'repeat(3, 1fr)',
+ gap: 16,
+ }}>
+ {filteredTemplates.map((template, i) => (
+ <div
+ key={`${template.name}-${template.originalIndex}`}
+ style={{
+ ...(craftTitle
+ ? {
+ animation: `craftCardFadeIn 400ms ${i * 50}ms cubic-bezier(0.16, 1, 0.3, 1) both`,
+ }
+ : undefined),
+ filter: previewImageFilter,
+ transition: 'filter 300ms ease',
+ }}>
+ <TemplateCard
+ src={template.src}
+ name={template.name}
+ isSelected={selected.has(template.originalIndex)}
+ isGenerating={
+ isGenerating &&
+ generatingSource !== template.originalIndex
+ }
+ cardSize={template.size}
+ onSelect={() =>
+ setSelected(prev => {
+ const next = new Set(prev);
+ if (next.has(template.originalIndex)) {
+ next.delete(template.originalIndex);
+ } else {
+ next.add(template.originalIndex);
+ }
+ return next;
+ })
+ }
+ onMoreLikeThis={() =>
+ handleMoreLikeThis(template.originalIndex)
+ }
+ onUse={() => handleUse(template.originalIndex)}
+ onPreview={() => handlePreview(template.originalIndex)}
+ />
+ </div>
+ ))}
+ </div>
)}
</div>
</div>
</div>
</div>
-
{!chatOpen && <AIComposer />}
-
{/* Bottom drawer overlay */}
{previewTarget !== null &&
(() => {
@@ -1529,23 +1566,39 @@ function DocsiteLandingTemplate() {
isBookmarked={card4Bookmarked}
onBookmarkToggle={() => setCard4Bookmarked(prev => !prev)}
moreLikeThis={moreLikeThisImages}
- onMoreLikeThisClick={(mlItem) => setPreviewTarget(mlItem.key as number)}
+ onMoreLikeThisClick={mlItem =>
+ setPreviewTarget(mlItem.key as number)
+ }
exploreTags={[
- 'website', 'dashboard', 'admin panel', 'settings',
- 'form layout', 'data table', 'sidebar nav', 'landing page',
- 'e-commerce', 'documentation', 'profile page',
+ 'website',
+ 'dashboard',
+ 'admin panel',
+ 'settings',
+ 'form layout',
+ 'data table',
+ 'sidebar nav',
+ 'landing page',
+ 'e-commerce',
+ 'documentation',
+ 'profile page',
]}
onExploreTagClick={handleTokenClick}
componentTags={[
- 'XDSAppShell', 'XDSTopNav', 'XDSVStack', 'XDSHStack',
- 'XDSHeading', 'XDSText', 'XDSButton', 'XDSCard',
- 'XDSBadge', 'XDSAvatar',
+ 'XDSAppShell',
+ 'XDSTopNav',
+ 'XDSVStack',
+ 'XDSHStack',
+ 'XDSHeading',
+ 'XDSText',
+ 'XDSButton',
+ 'XDSCard',
+ 'XDSBadge',
+ 'XDSAvatar',
]}
onComponentTagClick={handleTokenClick}
/>
);
})()}
-
{/* Settings dialog */}
<XDSDialog
isOpen={isSettingsOpen}
@@ -1556,28 +1609,46 @@ function DocsiteLandingTemplate() {
<XDSStack direction="vertical" gap={4} style={{padding: '8px 0'}}>
<XDSStack direction="horizontal" hAlign="between" vAlign="center">
<XDSStack direction="vertical" gap={1}>
- <XDSText type="body" style={{fontWeight: 600}}>Dark mode</XDSText>
- <XDSText type="supporting" color="secondary">Switch between light and dark appearance</XDSText>
+ <XDSText type="body" style={{fontWeight: 600}}>
+ Dark mode
+ </XDSText>
+ <XDSText type="supporting" color="secondary">
+ Switch between light and dark appearance
+ </XDSText>
</XDSStack>
<XDSButton
label={previewMode === 'dark' ? 'On' : 'Off'}
variant="secondary"
size="sm"
- onClick={() => setPreviewMode(previewMode === 'dark' ? 'light' : 'dark')}
+ onClick={() =>
+ setPreviewMode(previewMode === 'dark' ? 'light' : 'dark')
+ }
/>
</XDSStack>
<XDSDivider />
<XDSStack direction="horizontal" hAlign="between" vAlign="center">
<XDSStack direction="vertical" gap={1}>
- <XDSText type="body" style={{fontWeight: 600}}>Theme</XDSText>
- <XDSText type="supporting" color="secondary">Choose a visual theme for previews</XDSText>
+ <XDSText type="body" style={{fontWeight: 600}}>
+ Theme
+ </XDSText>
+ <XDSText type="supporting" color="secondary">
+ Choose a visual theme for previews
+ </XDSText>
</XDSStack>
<XDSDropdownMenu
- button={{label: previewTheme.charAt(0).toUpperCase() + previewTheme.slice(1), variant: 'secondary', size: 'sm'}}
+ button={{
+ label:
+ previewTheme.charAt(0).toUpperCase() + previewTheme.slice(1),
+ variant: 'secondary',
+ size: 'sm',
+ }}
items={[
{label: 'Default', onClick: () => setPreviewTheme('default')},
{label: 'Neutral', onClick: () => setPreviewTheme('neutral')},
- {label: 'Brutalist', onClick: () => setPreviewTheme('brutalist')},
+ {
+ label: 'Brutalist',
+ onClick: () => setPreviewTheme('brutalist'),
+ },
{label: 'Meta', onClick: () => setPreviewTheme('meta')},
{label: 'WhatsApp', onClick: () => setPreviewTheme('whatsapp')},
]}
@@ -1586,12 +1657,21 @@ function DocsiteLandingTemplate() {
<XDSDivider />
<XDSStack direction="horizontal" hAlign="between" vAlign="center">
<XDSStack direction="vertical" gap={1}>
- <XDSText type="body" style={{fontWeight: 600}}>Default sort</XDSText>
- <XDSText type="supporting" color="secondary">How templates are ordered by default</XDSText>
+ <XDSText type="body" style={{fontWeight: 600}}>
+ Default sort
+ </XDSText>
+ <XDSText type="supporting" color="secondary">
+ How templates are ordered by default
+ </XDSText>
</XDSStack>
<XDSDropdownMenu
button={{
- label: sortOption === 'trending' ? 'Trending' : sortOption === 'newest' ? 'Newest first' : 'Oldest first',
+ label:
+ sortOption === 'trending'
+ ? 'Trending'
+ : sortOption === 'newest'
+ ? 'Newest first'
+ : 'Oldest first',
variant: 'secondary',
size: 'sm',
}}
diff --git a/apps/storybook/stories/Toolbar.stories.tsx b/apps/storybook/stories/Toolbar.stories.tsx
index 68a27df007..37ac050480 100644
--- a/apps/storybook/stories/Toolbar.stories.tsx
+++ b/apps/storybook/stories/Toolbar.stories.tsx
@@ -35,7 +35,7 @@ const meta: Meta<typeof XDSToolbar> = {
},
argTypes: {
label: {control: 'text'},
- density: {control: 'radio', options: ['default', 'compact']},
+ size: {control: 'radio', options: ['sm', 'md', 'lg']},
orientation: {control: 'radio', options: ['horizontal', 'vertical']},
variant: {control: 'select', options: ['transparent', 'section', 'wash']},
gap: {control: 'number'},
@@ -123,7 +123,7 @@ export const EndOnly: Story = {
export const Compact: Story = {
args: {
label: 'Compact toolbar',
- density: 'compact',
+ size: 'sm',
startContent: (
<>
<XDSButton label="Cut" variant="ghost" size="sm" />
@@ -168,7 +168,7 @@ export const InsideCard: Story = {
<XDSCard width={600}>
<XDSToolbar
label="User list actions"
- density="compact"
+ size="sm"
dividers={['bottom']}
startContent={<XDSHeading level={4}>Users</XDSHeading>}
endContent={
@@ -306,7 +306,7 @@ export const StackedToolbars: Story = {
<XDSCard width={700}>
<XDSToolbar
label="Primary actions"
- density="compact"
+ size="sm"
dividers={['bottom']}
startContent={<XDSHeading level={4}>Orders</XDSHeading>}
endContent={
@@ -331,7 +331,7 @@ export const StackedToolbars: Story = {
/>
<XDSToolbar
label="Filters"
- density="compact"
+ size="sm"
variant="wash"
startContent={
<>
diff --git a/packages/cli/src/codemods/__tests__/registry.test.mjs b/packages/cli/src/codemods/__tests__/registry.test.mjs
index 7d60b8e7e9..039e749a7e 100644
--- a/packages/cli/src/codemods/__tests__/registry.test.mjs
+++ b/packages/cli/src/codemods/__tests__/registry.test.mjs
@@ -4,7 +4,7 @@ import {versions, getTransformsBetween} from '../registry.mjs';
describe('registry', () => {
describe('versions', () => {
test('are sorted in ascending semver order across digit boundaries', () => {
- expect(versions).toEqual(['0.0.2', '0.0.6', '0.0.7', '0.0.8', '0.0.10', '0.0.12']);
+ expect(versions).toEqual(['0.0.2', '0.0.6', '0.0.7', '0.0.8', '0.0.10', '0.0.12', '0.0.14']);
});
});
diff --git a/packages/cli/src/codemods/__tests__/toolbar-density-to-size.test.mjs b/packages/cli/src/codemods/__tests__/toolbar-density-to-size.test.mjs
new file mode 100644
index 0000000000..a282a4c5eb
--- /dev/null
+++ b/packages/cli/src/codemods/__tests__/toolbar-density-to-size.test.mjs
@@ -0,0 +1,67 @@
+import {describe, expect, test} from 'vitest';
+import {applyTransform} from 'jscodeshift/dist/testUtils.js';
+import transform from '../transforms/v0.0.14/toolbar-density-to-size.mjs';
+
+const opts = {parser: 'tsx'};
+
+describe('toolbar-density-to-size', () => {
+ test('converts density="compact" to size="sm"', () => {
+ const input = `<XDSToolbar label="Actions" density="compact" />`;
+ const output = applyTransform({default: transform, parser: 'tsx'}, opts, {source: input});
+ expect(output).toContain("size='sm'");
+ expect(output).not.toContain('density');
+ });
+
+ test('removes density="default" entirely', () => {
+ const input = `<XDSToolbar label="Actions" density="default" />`;
+ const output = applyTransform({default: transform, parser: 'tsx'}, opts, {source: input});
+ expect(output).not.toContain('density');
+ expect(output).not.toContain('size');
+ expect(output).toContain('label="Actions"');
+ });
+
+ test('converts dynamic density to ternary', () => {
+ const input = `<XDSToolbar label="Actions" density={d} />`;
+ const output = applyTransform({default: transform, parser: 'tsx'}, opts, {source: input});
+ expect(output).toContain("size={d === 'compact' ? 'sm' : 'md'}");
+ expect(output).not.toContain('density');
+ });
+
+ test('leaves XDSToolbar without density unchanged', () => {
+ const input = `<XDSToolbar label="Actions" variant="wash" />`;
+ const output = applyTransform({default: transform, parser: 'tsx'}, opts, {source: input});
+ // Transform returns undefined (no changes), applyTransform returns ''
+ expect(output).toBe('');
+ });
+
+ test('does not transform density on other components', () => {
+ const input = `<XDSList density="spacious" />`;
+ const output = applyTransform({default: transform, parser: 'tsx'}, opts, {source: input});
+ // No XDSToolbar found, transform returns undefined
+ expect(output).toBe('');
+ });
+
+ test('converts density in Storybook args objects', () => {
+ const input = `import {XDSToolbar} from '@xds/core/Toolbar';
+const x = { density: 'compact' };`;
+ const output = applyTransform({default: transform, parser: 'tsx'}, opts, {source: input});
+ expect(output).toContain("size: 'sm'");
+ expect(output).not.toContain("density: 'compact'");
+ });
+
+ test('converts density in argTypes with options', () => {
+ const input = `import {XDSToolbar} from '@xds/core/Toolbar';
+const meta = { argTypes: { density: { control: 'radio', options: ['default', 'compact'] } } };`;
+ const output = applyTransform({default: transform, parser: 'tsx'}, opts, {source: input});
+ expect(output).toContain('size:');
+ expect(output).toContain("'sm'");
+ expect(output).toContain("'md'");
+ expect(output).toContain("'lg'");
+ });
+
+ test('skips object property transform when no XDSToolbar import', () => {
+ const input = `const x = { density: 'compact' };`;
+ const output = applyTransform({default: transform, parser: 'tsx'}, opts, {source: input});
+ expect(output).toBe('');
+ });
+});
diff --git a/packages/cli/src/codemods/registry.mjs b/packages/cli/src/codemods/registry.mjs
index ef445bc4d2..7f5c347736 100644
--- a/packages/cli/src/codemods/registry.mjs
+++ b/packages/cli/src/codemods/registry.mjs
@@ -12,6 +12,7 @@ const registry = new Map([
['0.0.8', () => import('./transforms/v0.0.8/index.mjs')],
['0.0.10', () => import('./transforms/v0.0.10/index.mjs')],
['0.0.12', () => import('./transforms/v0.0.12/index.mjs')],
+ ['0.0.14', () => import('./transforms/v0.0.14/index.mjs')],
]);
/**
diff --git a/packages/cli/src/codemods/transforms/v0.0.14/index.mjs b/packages/cli/src/codemods/transforms/v0.0.14/index.mjs
new file mode 100644
index 0000000000..8a21187370
--- /dev/null
+++ b/packages/cli/src/codemods/transforms/v0.0.14/index.mjs
@@ -0,0 +1,17 @@
+/**
+ * @file v0.0.14 transform manifest
+ *
+ * Lists all codemods for the v0.0.14 release in the order they should run.
+ */
+
+import toolbarDensityToSize, {
+ meta as toolbarDensityToSizeMeta,
+} from './toolbar-density-to-size.mjs';
+
+export default [
+ {
+ name: 'toolbar-density-to-size',
+ transform: toolbarDensityToSize,
+ meta: toolbarDensityToSizeMeta,
+ },
+];
diff --git a/packages/cli/src/codemods/transforms/v0.0.14/toolbar-density-to-size.mjs b/packages/cli/src/codemods/transforms/v0.0.14/toolbar-density-to-size.mjs
new file mode 100644
index 0000000000..0b5d1d1fdd
--- /dev/null
+++ b/packages/cli/src/codemods/transforms/v0.0.14/toolbar-density-to-size.mjs
@@ -0,0 +1,157 @@
+/**
+ * @file Codemod: Migrate XDSToolbar density prop to size prop
+ *
+ * In the next release, XDSToolbar replaces `density` with `size`:
+ * - `density="compact"` → `size="sm"`
+ * - `density="default"` → removed (md is the default)
+ * - No density prop → no change needed
+ *
+ * The new `size` prop also cascades to child components (Button, TextInput,
+ * TabList, Selector, etc.) via XDSSizeContext, so explicit `size` props on
+ * children inside a toolbar may become redundant. That cleanup is left to
+ * developers since it's a design decision, not a correctness issue.
+ */
+
+export const meta = {
+ title: 'Migrate XDSToolbar density to size',
+ description:
+ 'Replaces `density="compact"` with `size="sm"` and removes `density="default"` ' +
+ '(md is the new default) on XDSToolbar components. Also handles Storybook ' +
+ 'args/argTypes objects that reference the density prop.',
+ pr: '#1448',
+};
+
+/** Map from old density values to new size values (null = remove prop). */
+const DENSITY_TO_SIZE = {
+ compact: 'sm',
+ default: null, // md is the default, no prop needed
+};
+
+export default function transformer(file, api) {
+ const j = api.jscodeshift;
+ const root = j(file.source);
+ let hasChanges = false;
+
+ root.find(j.JSXOpeningElement).forEach((path) => {
+ const name = path.node.name;
+ const componentName =
+ name.type === 'JSXIdentifier' ? name.name : null;
+ if (componentName !== 'XDSToolbar') return;
+
+ const attrs = path.node.attributes;
+ const densityIdx = attrs.findIndex(
+ (a) => a.type === 'JSXAttribute' && a.name?.name === 'density',
+ );
+ if (densityIdx === -1) return;
+
+ const densityAttr = attrs[densityIdx];
+ const value = densityAttr.value;
+
+ // density="compact" or density="default" (string literal)
+ if (value && (value.type === 'StringLiteral' || value.type === 'Literal')) {
+ const densityValue = value.value;
+ const sizeValue = DENSITY_TO_SIZE[densityValue];
+
+ if (sizeValue === undefined) {
+ // Unknown density value — leave it for manual review
+ return;
+ }
+
+ if (sizeValue === null) {
+ // density="default" → remove the prop entirely
+ attrs.splice(densityIdx, 1);
+ } else {
+ // density="compact" → size="sm"
+ attrs[densityIdx] = j.jsxAttribute(
+ j.jsxIdentifier('size'),
+ j.stringLiteral(sizeValue),
+ );
+ }
+ hasChanges = true;
+ return;
+ }
+
+ // density={expression} — rename prop to size, wrap in ternary
+ // density={someVar} → size={someVar === 'compact' ? 'sm' : 'md'}
+ if (
+ value &&
+ value.type === 'JSXExpressionContainer' &&
+ value.expression.type !== 'JSXEmptyExpression'
+ ) {
+ const expr = value.expression;
+ const newExpr = j.conditionalExpression(
+ j.binaryExpression('===', expr, j.stringLiteral('compact')),
+ j.stringLiteral('sm'),
+ j.stringLiteral('md'),
+ );
+ attrs[densityIdx] = j.jsxAttribute(
+ j.jsxIdentifier('size'),
+ j.jsxExpressionContainer(newExpr),
+ );
+ hasChanges = true;
+ }
+ });
+
+ // ---- 2. Object properties: Storybook args/argTypes ----
+ // Handles patterns like:
+ // args: { density: 'compact' } → args: { size: 'sm' }
+ // argTypes: { density: {...} } → argTypes: { size: {...} }
+ // Only transforms when the file imports XDSToolbar (scoping check).
+ const importsToolbar = root.find(j.ImportSpecifier, {
+ imported: {name: 'XDSToolbar'},
+ }).length > 0;
+
+ if (importsToolbar) {
+ // jscodeshift uses Property (default parser) or ObjectProperty (babel/tsx parser)
+ const PropertyType = j.ObjectProperty ?? j.Property;
+ root.find(PropertyType, {key: {name: 'density'}}).forEach((path) => {
+ const value = path.node.value;
+
+ // args: { density: 'compact' } → args: { size: 'sm' }
+ if (value.type === 'StringLiteral' || value.type === 'Literal') {
+ const densityValue = value.value;
+ const sizeValue = DENSITY_TO_SIZE[densityValue];
+ if (sizeValue === undefined) return;
+
+ if (sizeValue === null) {
+ // density: 'default' → remove property
+ const parent = path.parent.node;
+ if (parent.type === 'ObjectExpression') {
+ const idx = parent.properties.indexOf(path.node);
+ if (idx !== -1) {
+ parent.properties.splice(idx, 1);
+ hasChanges = true;
+ }
+ }
+ } else {
+ // density: 'compact' → size: 'sm'
+ path.node.key = j.identifier('size');
+ path.node.value = j.stringLiteral(sizeValue);
+ hasChanges = true;
+ }
+ return;
+ }
+
+ // argTypes: { density: {control: 'radio', options: [...]} }
+ // → argTypes: { size: {control: 'radio', options: ['sm', 'md', 'lg']} }
+ if (value.type === 'ObjectExpression') {
+ path.node.key = j.identifier('size');
+ // Update options array if present
+ const optionsProp = value.properties.find(
+ (p) => p.key?.name === 'options',
+ );
+ if (optionsProp && optionsProp.value.type === 'ArrayExpression') {
+ optionsProp.value = j.arrayExpression([
+ j.stringLiteral('sm'),
+ j.stringLiteral('md'),
+ j.stringLiteral('lg'),
+ ]);
+ }
+ hasChanges = true;
+ }
+ });
+ }
+
+ if (!hasChanges) return undefined;
+ return root.toSource({quote: 'single'});
+}
diff --git a/packages/cli/templates/blocks/components/Toolbar/ToolbarCompactDensity.tsx b/packages/cli/templates/blocks/components/Toolbar/ToolbarCompactDensity.tsx
index 3f787ed7ca..fcb1da2253 100644
--- a/packages/cli/templates/blocks/components/Toolbar/ToolbarCompactDensity.tsx
+++ b/packages/cli/templates/blocks/components/Toolbar/ToolbarCompactDensity.tsx
@@ -7,7 +7,7 @@ export default function ToolbarCompactDensity() {
return (
<XDSToolbar
label="Compact actions"
- density="compact"
+ size="sm"
startContent={
<>
<XDSButton label="Cut" variant="ghost" size="sm" />
diff --git a/packages/core/package.json b/packages/core/package.json
index 5fd781ca0d..ff1a2f0592 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -346,6 +346,12 @@
"import": "./dist/SideNav/index.mjs",
"require": "./dist/SideNav/index.js"
},
+ "./SizeContext": {
+ "source": "./src/SizeContext/index.ts",
+ "types": "./dist/SizeContext/index.d.ts",
+ "import": "./dist/SizeContext/index.mjs",
+ "require": "./dist/SizeContext/index.js"
+ },
"./Skeleton": {
"source": "./src/Skeleton/index.ts",
"types": "./dist/Skeleton/index.d.ts",
diff --git a/packages/core/src/Button/XDSButton.tsx b/packages/core/src/Button/XDSButton.tsx
index 65c5263fb0..127eab71b3 100644
--- a/packages/core/src/Button/XDSButton.tsx
+++ b/packages/core/src/Button/XDSButton.tsx
@@ -32,6 +32,7 @@ import {XDSTooltip} from '../Tooltip/XDSTooltip';
import {XDSSpinner} from '../Spinner';
import {edgeCompensation} from '../Layout/edgeCompensation.stylex';
+import {useXDSSize} from '../SizeContext/XDSSizeContext';
import {xdsClassName, mergeProps} from '../utils';
import {useXDSLinkComponent} from '../Link/useXDSLinkComponent';
import type {XDSLinkComponentType} from '../Link/types';
@@ -431,7 +432,7 @@ const edgeCompStyles = stylex.create({
export function XDSButton({
label,
variant = 'secondary',
- size = 'md',
+ size: sizeProp,
type = 'button',
isDisabled = false,
isLoading = false,
@@ -451,6 +452,8 @@ export function XDSButton({
ref,
...props
}: XDSButtonProps): ReactNode {
+ const size = useXDSSize(sizeProp, 'md');
+
const [isPending, startTransition] = useTransition();
const actionInFlightRef = useRef(false);
const isLoadingState = isLoading || isPending;
diff --git a/packages/core/src/MoreMenu/XDSMoreMenu.tsx b/packages/core/src/MoreMenu/XDSMoreMenu.tsx
index 3a7cdcc0f7..a8dfa356aa 100644
--- a/packages/core/src/MoreMenu/XDSMoreMenu.tsx
+++ b/packages/core/src/MoreMenu/XDSMoreMenu.tsx
@@ -19,6 +19,7 @@
import {type ReactNode} from 'react';
import {getIcon} from '../Icon/globalIconRegistry';
import {XDSDropdownMenu} from '../DropdownMenu/XDSDropdownMenu';
+import {useXDSSize} from '../SizeContext/XDSSizeContext';
import type {XDSDropdownMenuOption} from '../DropdownMenu';
import type {XDSButtonVariant, XDSButtonSize} from '../Button';
@@ -86,12 +87,13 @@ export function XDSMoreMenu({
items,
label = 'More options',
variant = 'ghost',
- size = 'md',
+ size: sizeProp,
icon,
isDisabled = false,
'data-testid': testId,
ref,
}: XDSMoreMenuProps) {
+ const size = useXDSSize(sizeProp, 'md');
const moreIcon = getIcon('moreHorizontal');
return (
diff --git a/packages/core/src/NumberInput/XDSNumberInput.tsx b/packages/core/src/NumberInput/XDSNumberInput.tsx
index 24dfcc9793..92ab56f57d 100644
--- a/packages/core/src/NumberInput/XDSNumberInput.tsx
+++ b/packages/core/src/NumberInput/XDSNumberInput.tsx
@@ -42,6 +42,7 @@ import {
inputStatusFocusWithinStyles,
} from '../Field';
import {XDSIcon, type XDSIconType} from '../Icon';
+import {useXDSSize} from '../SizeContext/XDSSizeContext';
const styles = stylex.create({
wrapper: {
@@ -329,7 +330,7 @@ export function XDSNumberInput({
startIcon,
labelIcon,
status,
- size = 'md',
+ size: sizeProp,
onChange,
value,
placeholder,
@@ -353,6 +354,7 @@ export function XDSNumberInput({
ref,
...rest
}: XDSNumberInputProps) {
+ const size = useXDSSize(sizeProp, 'md');
const id = useId();
const descriptionID = useId();
const statusMessageID = useId();
diff --git a/packages/core/src/SegmentedControl/XDSSegmentedControl.tsx b/packages/core/src/SegmentedControl/XDSSegmentedControl.tsx
index 6e37dda3c9..99a7ac5e7c 100644
--- a/packages/core/src/SegmentedControl/XDSSegmentedControl.tsx
+++ b/packages/core/src/SegmentedControl/XDSSegmentedControl.tsx
@@ -19,6 +19,7 @@ import {colorVars, spacingVars, radiusVars} from '../theme/tokens.stylex';
import {XDSSegmentedControlContext} from './XDSSegmentedControlContext';
import type {XDSSegmentedControlSize} from './XDSSegmentedControlContext';
import {xdsClassName, mergeProps} from '../utils';
+import {useXDSSize} from '../SizeContext/XDSSizeContext';
export interface XDSSegmentedControlProps {
/**
@@ -114,13 +115,14 @@ export function XDSSegmentedControl({
value,
onChange,
label,
- size = 'md',
+ size: sizeProp,
isDisabled = false,
children,
xstyle,
className,
style,
}: XDSSegmentedControlProps) {
+ const size = useXDSSize(sizeProp, 'md') as XDSSegmentedControlSize;
const containerRef = useRef<HTMLDivElement>(null);
const handleKeyDown = useCallback(
diff --git a/packages/core/src/Selector/XDSSelector.tsx b/packages/core/src/Selector/XDSSelector.tsx
index 48b33cbb0f..a9a350c885 100644
--- a/packages/core/src/Selector/XDSSelector.tsx
+++ b/packages/core/src/Selector/XDSSelector.tsx
@@ -56,6 +56,7 @@ import {
import {useCombobox, useSelectedItemOffset} from './hooks';
import {XDSSelectorOption} from './XDSSelectorOption';
import {xdsClassName, mergeProps} from '../utils';
+import {useXDSSize} from '../SizeContext/XDSSizeContext';
import {XDSBaseProps} from '../XDSBaseProps';
const styles = stylex.create({
@@ -451,7 +452,7 @@ export function XDSSelector<T extends XDSSelectorOptionType>(
onChangeAction,
isLoading = false,
placeholder = 'Select...',
- size = 'md',
+ size: sizeProp,
status,
labelTooltip,
children,
@@ -463,6 +464,7 @@ export function XDSSelector<T extends XDSSelectorOptionType>(
...rest
} = props as XDSSelectorPropsClearable<T>;
const hasClear = hasClearProp === true;
+ const size = useXDSSize(sizeProp, 'md') as XDSSelectorSize;
// Normalize null to undefined for internal use (null is the clear sentinel)
const normalizedValue = value === null ? undefined : value;
diff --git a/packages/core/src/SizeContext/XDSSizeContext.ts b/packages/core/src/SizeContext/XDSSizeContext.ts
new file mode 100644
index 0000000000..844c8a2fc3
--- /dev/null
+++ b/packages/core/src/SizeContext/XDSSizeContext.ts
@@ -0,0 +1,49 @@
+'use client';
+
+/**
+ * @file XDSSizeContext.ts
+ * @input React createContext, useContext
+ * @output Exports XDSSizeContext, useXDSSize, XDSElementSize, XDSSizeProvider
+ * @position Context provider; consumed by Button, TextInput, TabList, Selector, etc.
+ *
+ * Generic size context that lets container components (Toolbar, TopNav, Card headers)
+ * cascade a default size to interactive children. Children use the context as a
+ * fallback — an explicit `size` prop always wins.
+ */
+
+import {createContext, useContext} from 'react';
+
+/**
+ * Standard element sizes used across interactive components.
+ */
+export type XDSElementSize = 'sm' | 'md' | 'lg';
+
+/**
+ * Context for cascading a default size from container to children.
+ *
+ * `null` means no container is providing a size — components use their own default.
+ */
+export const XDSSizeContext = createContext<XDSElementSize | null>(null);
+
+/**
+ * Resolve the effective size from an explicit prop, inherited context, or default.
+ *
+ * @param sizeProp - Explicit size prop from the component (wins if set)
+ * @param defaultSize - Fallback when neither prop nor context provides a size
+ * @returns The resolved size
+ *
+ * @example
+ * ```ts
+ * // In a component:
+ * const size = useXDSSize(sizeProp, 'md');
+ * ```
+ */
+export function useXDSSize<T extends string = XDSElementSize>(
+ sizeProp?: T,
+ defaultSize: T = 'md' as T,
+): T {
+ const inherited = useContext(XDSSizeContext);
+ return sizeProp ?? (inherited as T | null) ?? defaultSize;
+}
+
+export const XDSSizeProvider = XDSSizeContext.Provider;
diff --git a/packages/core/src/SizeContext/index.ts b/packages/core/src/SizeContext/index.ts
new file mode 100644
index 0000000000..d5c0396a4e
--- /dev/null
+++ b/packages/core/src/SizeContext/index.ts
@@ -0,0 +1,13 @@
+/**
+ * @file index.ts
+ * @input XDSSizeContext.ts
+ * @output Re-exports size context utilities
+ * @position Public entry point for @xds/core/SizeContext
+ */
+
+export {
+ XDSSizeContext,
+ XDSSizeProvider,
+ useXDSSize,
+ type XDSElementSize,
+} from './XDSSizeContext';
diff --git a/packages/core/src/TabList/XDSTabList.tsx b/packages/core/src/TabList/XDSTabList.tsx
index c1187ab603..94924ecdbe 100644
--- a/packages/core/src/TabList/XDSTabList.tsx
+++ b/packages/core/src/TabList/XDSTabList.tsx
@@ -18,6 +18,7 @@ import {borderVars, colorVars, spacingVars} from '../theme/tokens.stylex';
import {XDSBaseProps} from '../XDSBaseProps';
import {XDSTabListContext} from './XDSTabListContext';
import type {XDSTabListSize} from './XDSTabListContext';
+import {useXDSSize} from '../SizeContext/XDSSizeContext';
import {xdsClassName, mergeProps} from '../utils';
export interface XDSTabListProps extends Omit<
@@ -91,7 +92,7 @@ const styles = stylex.create({
export function XDSTabList({
value,
onChange,
- size = 'md',
+ size: sizeProp,
layout = 'hug',
hasDivider = false,
xstyle,
@@ -100,6 +101,8 @@ export function XDSTabList({
children,
...restProps
}: XDSTabListProps) {
+ const size = useXDSSize(sizeProp, 'md') as XDSTabListSize;
+
const contextValue = useMemo(
() => ({value, onChange, size, layout}),
[value, onChange, size, layout],
diff --git a/packages/core/src/TextInput/XDSTextInput.tsx b/packages/core/src/TextInput/XDSTextInput.tsx
index b2fe6d7135..7ce1686f54 100644
--- a/packages/core/src/TextInput/XDSTextInput.tsx
+++ b/packages/core/src/TextInput/XDSTextInput.tsx
@@ -108,6 +108,7 @@ export type {
XDSInputStatusType as XDSTextInputStatusType,
} from '../Field';
import {xdsClassName, mergeProps} from '../utils';
+import {useXDSSize} from '../SizeContext/XDSSizeContext';
import {XDSBaseProps} from '../XDSBaseProps';
export type XDSTextInputType = 'text' | 'password' | 'email';
@@ -237,7 +238,7 @@ export function XDSTextInput({
isDisabled = false,
startIcon,
status,
- size = 'md',
+ size: sizeProp,
onChange,
onChangeAction,
isLoading = false,
@@ -255,6 +256,8 @@ export function XDSTextInput({
ref,
...rest
}: XDSTextInputProps) {
+ const size = useXDSSize(sizeProp, 'md');
+
const id = useId();
const descriptionID = useId();
const statusMessageID = useId();
diff --git a/packages/core/src/Tokenizer/XDSTokenizer.tsx b/packages/core/src/Tokenizer/XDSTokenizer.tsx
index d1bcfb6e1b..a3697280af 100644
--- a/packages/core/src/Tokenizer/XDSTokenizer.tsx
+++ b/packages/core/src/Tokenizer/XDSTokenizer.tsx
@@ -24,6 +24,7 @@ import React, {
import * as stylex from '@stylexjs/stylex';
import type {StyleXStyles} from '@stylexjs/stylex';
import {XDSBaseTypeahead} from '../Typeahead/XDSBaseTypeahead';
+import {useXDSSize} from '../SizeContext/XDSSizeContext';
import {
XDSField,
type XDSInputStatus,
@@ -358,7 +359,7 @@ export function XDSTokenizer<T extends XDSSearchableItem>({
hasClear = false,
endContent,
hasAutoFocus,
- size = 'md',
+ size: sizeProp,
tokenOverflowBehavior = 'none',
debounceMs,
hasCreate = false,
@@ -369,6 +370,7 @@ export function XDSTokenizer<T extends XDSSearchableItem>({
'data-testid': testId,
ref,
}: XDSTokenizerProps<T>) {
+ const size = useXDSSize(sizeProp, 'md') as XDSTokenizerSize;
const inputId = useId();
const descriptionId = useId();
const statusMessageId = useId();
diff --git a/packages/core/src/Toolbar/XDSToolbar.test.tsx b/packages/core/src/Toolbar/XDSToolbar.test.tsx
index 05fdeb9e5e..484f26e095 100644
--- a/packages/core/src/Toolbar/XDSToolbar.test.tsx
+++ b/packages/core/src/Toolbar/XDSToolbar.test.tsx
@@ -130,16 +130,22 @@ describe('XDSToolbar', () => {
);
});
- it('applies density class', () => {
- render(<XDSToolbar label="Actions" density="compact" />);
+ it('applies size class', () => {
+ render(<XDSToolbar label="Actions" size="sm" />);
const toolbar = screen.getByRole('toolbar');
- expect(toolbar.className).toContain('compact');
+ expect(toolbar.className).toContain('sm');
});
- it('applies default density class', () => {
+ it('defaults to md size', () => {
render(<XDSToolbar label="Actions" />);
const toolbar = screen.getByRole('toolbar');
- expect(toolbar.className).toContain('default');
+ expect(toolbar.className).toContain('md');
+ });
+
+ it('applies lg size class', () => {
+ render(<XDSToolbar label="Actions" size="lg" />);
+ const toolbar = screen.getByRole('toolbar');
+ expect(toolbar.className).toContain('lg');
});
it('forwards ref to root element', () => {
diff --git a/packages/core/src/Toolbar/XDSToolbar.tsx b/packages/core/src/Toolbar/XDSToolbar.tsx
index 935a5308d6..1adcb999e3 100644
--- a/packages/core/src/Toolbar/XDSToolbar.tsx
+++ b/packages/core/src/Toolbar/XDSToolbar.tsx
@@ -2,7 +2,7 @@
/**
* @file XDSToolbar.tsx
- * @input Uses XDSSection, useListFocus, StyleX, spacingVars
+ * @input Uses XDSSection, XDSSizeContext, useListFocus, edgeSignals, StyleX, spacingVars, sizeVars
* @output Exports XDSToolbar component and XDSToolbarProps
* @position Core implementation; consumed by index.ts
*
@@ -17,11 +17,14 @@ import {type ReactNode} from 'react';
import type {XDSBaseProps} from '../XDSBaseProps';
import type {XDSSectionVariant} from '../Section/XDSSection';
import type {SpacingStep} from '../utils/types';
+import type {XDSElementSize} from '../SizeContext/XDSSizeContext';
import * as stylex from '@stylexjs/stylex';
-import {spacingVars} from '../theme/tokens.stylex';
+import {spacingVars, sizeVars} from '../theme/tokens.stylex';
import {xdsClassName, mergeProps} from '../utils';
import {XDSSection} from '../Section/XDSSection';
import {useListFocus} from '../hooks/useListFocus';
+import {XDSSizeProvider} from '../SizeContext/XDSSizeContext';
+import {edgeSignals} from '../Layout/edgeCompensation.stylex';
/**
* Map SpacingStep values to spacingVars keys.
@@ -58,18 +61,7 @@ const styles = stylex.create({
flexDirection: 'column',
alignItems: 'stretch',
},
- // Compact density: tighter height
- compact: {
- minHeight: spacingVars['--spacing-8'],
- },
- defaultDensity: {
- minHeight: spacingVars['--spacing-10'],
- },
// Slot containers
- // Start and end slots add horizontal padding (spacing-2 = 8px) so that
- // combined with the section's 8px padding, content aligns at 16px from edges.
- // This split enables future edge compensation: ghost buttons can negate
- // the slot padding while the section padding remains.
startSlot: {
display: 'flex',
alignItems: 'center',
@@ -98,6 +90,33 @@ const styles = stylex.create({
},
});
+/**
+ * Size-specific styles. Each size sets:
+ * - minHeight: element token + vertical breathing room
+ * - --container-padding-inline: so ghost buttons auto-compensate at edges
+ */
+const sizeStyles = stylex.create({
+ sm: {
+ minHeight: sizeVars['--size-element-sm'],
+ },
+ md: {
+ minHeight: sizeVars['--size-element-md'],
+ },
+ lg: {
+ minHeight: sizeVars['--size-element-lg'],
+ },
+});
+
+/**
+ * Container padding value per size for edge compensation.
+ * Maps to the same spacing tokens used for the Section padding.
+ */
+const containerPaddingValue: Record<XDSElementSize, string> = {
+ sm: '4px',
+ md: '8px',
+ lg: '12px',
+};
+
// Dynamic styles for configurable gap
const dynamicStyles = stylex.create({
gap: (gapValue: string) => ({
@@ -105,6 +124,17 @@ const dynamicStyles = stylex.create({
}),
});
+/**
+ * Default padding per toolbar size.
+ */
+const defaultPaddingForSize: Record<XDSElementSize, SpacingStep> = {
+ sm: 1,
+ md: 2,
+ lg: 3,
+};
+
+export type XDSToolbarSize = XDSElementSize;
+
export interface XDSToolbarProps extends XDSBaseProps<HTMLDivElement> {
/** Ref forwarded to the root XDSSection element */
ref?: React.Ref<HTMLElement>;
@@ -127,12 +157,15 @@ export interface XDSToolbarProps extends XDSBaseProps<HTMLDivElement> {
*/
label: string;
/**
- * Density of the toolbar.
- * - 'default': Standard height (40px min)
- * - 'compact': Reduced height (32px min)
- * @default 'default'
+ * Size of the toolbar. Coordinates with Button, TextInput, TabList, and Selector —
+ * children inherit this size as their default via XDSSizeContext.
+ *
+ * - `'sm'`: Compact — fits sm buttons/inputs (28px elements)
+ * - `'md'`: Standard — fits md buttons/inputs (32px elements)
+ * - `'lg'`: Spacious — fits lg buttons/inputs (36px elements)
+ * @default 'md'
*/
- density?: 'compact' | 'default';
+ size?: XDSToolbarSize;
/**
* Gap between items within each slot, using the spacing scale.
* @default 2
@@ -151,8 +184,7 @@ export interface XDSToolbarProps extends XDSBaseProps<HTMLDivElement> {
variant?: XDSSectionVariant;
/**
* Internal padding using the spacing scale.
- * Passed through to XDSSection.
- * @default 2 (8px) — combined with 8px slot padding = 16px from edges
+ * Passed through to XDSSection. Defaults based on size (sm=1/4px, md=2/8px, lg=3/12px).
*/
padding?: SpacingStep;
/**
@@ -170,12 +202,13 @@ export interface XDSToolbarProps extends XDSBaseProps<HTMLDivElement> {
* General-purpose toolbar with start, center, and end content slots.
*
* Built on XDSSection, provides flex/grid layout with roving tabindex
- * keyboard navigation via useListFocus.
+ * keyboard navigation via useListFocus. Cascades `size` to child components
+ * (Button, TextInput, TabList, Selector) via XDSSizeContext, and applies
+ * edge compensation so ghost buttons align flush at container edges.
*
* @example
* ```
- * <XDSToolbar
- * label="Actions"
+ * <XDSToolbar label="Actions" size="sm"
* startContent={<XDSButton label="Cut" variant="ghost" />}
* endContent={<XDSButton label="Settings" variant="ghost" />}
* />
@@ -186,7 +219,7 @@ export function XDSToolbar({
centerContent,
endContent,
label,
- density = 'default',
+ size = 'md',
gap = 2,
orientation = 'horizontal',
variant = 'transparent',
@@ -203,6 +236,7 @@ export function XDSToolbar({
const hasEndContent = endContent != null;
const gapVar = spacingVars[spacingStepToVar[gap]] as string;
+ const resolvedPadding = padding ?? defaultPaddingForSize[size];
const {listRef, handleKeyDown} = useListFocus({
itemSelector: 'button, input, [tabindex="0"]',
@@ -210,71 +244,92 @@ export function XDSToolbar({
});
return (
- <XDSSection
- ref={ref}
- variant={variant}
- padding={padding ?? 2}
- dividers={dividers}
- xstyle={xstyle}
- className={className}
- style={style}>
- <div
- ref={listRef as React.RefObject<HTMLDivElement>}
- role="toolbar"
- aria-label={label}
- aria-orientation={orientation}
- onKeyDown={handleKeyDown}
- {...mergeProps(
- xdsClassName('toolbar', {density}),
- stylex.props(
- hasCenterContent ? styles.baseGrid : styles.baseFlex,
- orientation === 'vertical' && styles.vertical,
- density === 'compact' ? styles.compact : styles.defaultDensity,
- dynamicStyles.gap(gapVar),
- ),
- )}
- {...props}>
- {hasCenterContent ? (
- // Three-slot grid layout
- <>
- <div {...stylex.props(styles.startSlot, dynamicStyles.gap(gapVar))}>
- {startContent}
- </div>
- <div
- {...stylex.props(styles.centerSlot, dynamicStyles.gap(gapVar))}>
- {centerContent}
- </div>
- <div {...stylex.props(styles.endSlot, dynamicStyles.gap(gapVar))}>
- {endContent}
- </div>
- </>
- ) : (
- // Two-slot flex layout
- <>
- {hasStartContent && (
+ <XDSSizeProvider value={size}>
+ <XDSSection
+ ref={ref}
+ variant={variant}
+ padding={resolvedPadding}
+ dividers={dividers}
+ xstyle={xstyle}
+ className={className}
+ style={
+ {
+ ...style,
+ '--container-padding-inline': containerPaddingValue[size],
+ } as React.CSSProperties
+ }>
+ <div
+ ref={listRef as React.RefObject<HTMLDivElement>}
+ role="toolbar"
+ aria-label={label}
+ aria-orientation={orientation}
+ onKeyDown={handleKeyDown}
+ {...mergeProps(
+ xdsClassName('toolbar', {size}),
+ stylex.props(
+ hasCenterContent ? styles.baseGrid : styles.baseFlex,
+ orientation === 'vertical' && styles.vertical,
+ sizeStyles[size],
+ dynamicStyles.gap(gapVar),
+ ),
+ )}
+ {...props}>
+ {hasCenterContent ? (
+ // Three-slot grid layout
+ <>
<div
{...stylex.props(
styles.startSlot,
- !hasEndContent && styles.startOnly,
+ edgeSignals.start,
dynamicStyles.gap(gapVar),
)}>
{startContent}
</div>
- )}
- {hasEndContent && (
+ <div
+ {...stylex.props(styles.centerSlot, dynamicStyles.gap(gapVar))}>
+ {centerContent}
+ </div>
<div
{...stylex.props(
styles.endSlot,
- !hasStartContent && styles.endOnly,
+ edgeSignals.end,
dynamicStyles.gap(gapVar),
)}>
{endContent}
</div>
- )}
- </>
- )}
- </div>
- </XDSSection>
+ </>
+ ) : (
+ // Two-slot flex layout
+ <>
+ {hasStartContent && (
+ <div
+ {...stylex.props(
+ styles.startSlot,
+ !hasEndContent && styles.startOnly,
+ // Edge signal: start slot is at the start edge;
+ // if no end content, it's also at the end edge.
+ !hasEndContent ? edgeSignals.both : edgeSignals.start,
+ dynamicStyles.gap(gapVar),
+ )}>
+ {startContent}
+ </div>
+ )}
+ {hasEndContent && (
+ <div
+ {...stylex.props(
+ styles.endSlot,
+ !hasStartContent && styles.endOnly,
+ !hasStartContent ? edgeSignals.both : edgeSignals.end,
+ dynamicStyles.gap(gapVar),
+ )}>
+ {endContent}
+ </div>
+ )}
+ </>
+ )}
+ </div>
+ </XDSSection>
+ </XDSSizeProvider>
);
}
diff --git a/packages/core/src/Toolbar/index.ts b/packages/core/src/Toolbar/index.ts
index 9f49e8ea6e..a1d7b7632d 100644
--- a/packages/core/src/Toolbar/index.ts
+++ b/packages/core/src/Toolbar/index.ts
@@ -10,4 +10,4 @@
*/
export {XDSToolbar} from './XDSToolbar';
-export type {XDSToolbarProps} from './XDSToolbar';
+export type {XDSToolbarProps, XDSToolbarSize} from './XDSToolbar';
diff --git a/packages/core/src/Typeahead/XDSTypeahead.tsx b/packages/core/src/Typeahead/XDSTypeahead.tsx
index f494469e87..258a3c8424 100644
--- a/packages/core/src/Typeahead/XDSTypeahead.tsx
+++ b/packages/core/src/Typeahead/XDSTypeahead.tsx
@@ -20,6 +20,7 @@ import React, {useCallback, useId, useRef, useState} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {StyleXStyles} from '@stylexjs/stylex';
import {XDSBaseTypeahead} from './XDSBaseTypeahead';
+import {useXDSSize} from '../SizeContext/XDSSizeContext';
import {
XDSField,
type XDSInputStatus,
@@ -223,7 +224,7 @@ export function XDSTypeahead<T extends XDSSearchableItem>({
isDisabled = false,
hasClear = true,
hasAutoFocus,
- size = 'md',
+ size: sizeProp,
debounceMs,
onChangeQuery,
onOpenChange,
@@ -232,6 +233,7 @@ export function XDSTypeahead<T extends XDSSearchableItem>({
style,
'data-testid': testId,
}: XDSTypeaheadProps<T>) {
+ const size = useXDSSize(sizeProp, 'md') as XDSTypeaheadSize;
const inputId = useId();
const descriptionId = useId();
const statusMessageId = useId();
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 5fa4949c5d..cab3cec536 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -72,6 +72,7 @@ export * from './AlertDialog';
export * from './Dialog';
export * from './DropdownMenu';
export * from './MoreMenu';
+export * from './SizeContext';
export * from './Toolbar';
export * from './TopNav';
export * from './SideNav';