Skip to content

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

TypeScript

fix(theme)!: spacing tokens follow the root font size (#7359)

Christopher Chedeauf3a218198b7d
diff --git a/.changeset/spacing-tokens-rem.md b/.changeset/spacing-tokens-rem.md
new file mode 100644
index 0000000000..472861d6e2
--- /dev/null
+++ b/.changeset/spacing-tokens-rem.md
@@ -0,0 +1,22 @@
+---
+'@astryxdesign/core': minor
+'@astryxdesign/cli': minor
+---
+
+[breaking] Spacing tokens are rem (`--spacing-2: 0.5rem`), so gaps and padding follow the reader's root font size the way the type scale does. Every token value is unchanged at the default 16px root.
+
+One change shows at the default root: the `useTableRowExpansion` chevron now sits centered in its fixed 40px column instead of running past its edge (its button moves from 24–48px to 8–32px of the column). Under a theme with a larger spacing scale, such as matcha, the chevron is visible again and the detail panel lines up with the first column instead of starting 20px past it.
+
+@vjeux
+
+Old usage:
+The `--spacing-*` defaults were fixed px (`--spacing-2: 8px`), so `useTheme().token()`, `resolveThemeToken()`, `tokenDefaults` and `spacingDefaults` returned px strings, and spacing stayed the same size when a reader raised the browser font size.
+
+Replacement:
+The defaults are rem with the same value at a 16px root (`--spacing-2: 0.5rem`, `--spacing-4: 1rem`), and those readers return the rem string.
+
+Migration:
+CSS that reads `var(--spacing-*)` needs no change. Code that parses a spacing token as a px number converts the rem value with the root font size, or reads the element's computed length. A theme that wants fixed px spacing sets the tokens back, for example `defineTheme({tokens: {'--spacing-2': '8px'}})`.
+
+Codemod:
+None. A token read and parsed at runtime cannot be found and rewritten statically, and CSS uses need no rewrite.
diff --git a/apps/docsite/src/__tests__/theme-concentricity.test.ts b/apps/docsite/src/__tests__/theme-concentricity.test.ts
index c4fbdb242a..2337a6905e 100644
--- a/apps/docsite/src/__tests__/theme-concentricity.test.ts
+++ b/apps/docsite/src/__tests__/theme-concentricity.test.ts
@@ -1,11 +1,12 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
import {describe, it, expect} from 'vitest';
-import {expandRadiusScale} from '@astryxdesign/core/theme';
+import {expandRadiusScale, spacingDefaults} from '@astryxdesign/core/theme';
import {UNIFIED_PRESETS} from '../app/playground/themeEditor/constants';
import {
buildSpacingScale,
getConcentricityWarning,
+ spacingToPx,
} from '../app/playground/themeEditor/helpers';
const px = (value: string): number => parseInt(value, 10);
@@ -21,7 +22,7 @@ describe('theme editor presets — concentricity', () => {
for (const [name, preset] of Object.entries(UNIFIED_PRESETS)) {
it(`${name} preset nests its radius rungs concentrically`, () => {
const radii = expandRadiusScale({base: preset.radius, multiplier: 1});
- const gap = px(buildSpacingScale(preset.spacing)['--spacing-1']);
+ const gap = spacingToPx(buildSpacingScale(preset.spacing)['--spacing-1']);
const inner = px(radii['--radius-inner']);
const element = px(radii['--radius-element']);
const container = px(radii['--radius-container']);
@@ -82,3 +83,17 @@ describe('getConcentricityWarning', () => {
expect(getConcentricityWarning('spacing', 12, Number.NaN)).toBeNull();
});
});
+
+describe('buildSpacingScale', () => {
+ it('reproduces the default spacing scale from the default base', () => {
+ // Picking the default base must not write a single override, so the ramp
+ // it builds is the defaults themselves, unit included.
+ expect(buildSpacingScale(4)).toEqual(spacingDefaults);
+ });
+
+ it('reads a step in px whether it is written in rem or in px', () => {
+ expect(spacingToPx('0.5rem')).toBe(8);
+ expect(spacingToPx('12px')).toBe(12);
+ expect(spacingToPx('var(--spacing-2)')).toBeNaN();
+ });
+});
diff --git a/apps/docsite/src/app/playground/themeEditor/BaseStylesPanel.tsx b/apps/docsite/src/app/playground/themeEditor/BaseStylesPanel.tsx
index 080d51bc18..3731e74b2a 100644
--- a/apps/docsite/src/app/playground/themeEditor/BaseStylesPanel.tsx
+++ b/apps/docsite/src/app/playground/themeEditor/BaseStylesPanel.tsx
@@ -17,7 +17,7 @@ import {expandRadiusScale, expandTypeScale} from '@astryxdesign/core/theme';
import {ColorSwatch} from './ColorSwatch';
import {SelectableCard} from '@astryxdesign/core/SelectableCard';
import {FONT_OPTIONS, RATIO_OPTIONS, UNIFIED_PRESETS} from './constants';
-import {getConcentricityWarning} from './helpers';
+import {getConcentricityWarning, spacingToPx} from './helpers';
import {useLiveNumberInput} from '@/lib/useLiveNumberInput';
const styles = stylex.create({
@@ -238,9 +238,10 @@ export function BaseStylesPanel({
return keys.every(k => tokens[k] === expected[k]) ? inner : null;
})();
- // Spacing — linear scale where step N = base × N (base = --spacing-1).
+ // Spacing — linear scale where step N = base × N (base = --spacing-1), read
+ // in px whether a step is written in rem (the defaults) or px (a theme).
const spacingMatch = (() => {
- const base = parseInt(tokens['--spacing-1'] ?? '', 10);
+ const base = spacingToPx(tokens['--spacing-1']);
if (!Number.isFinite(base)) {
return null;
}
@@ -262,7 +263,7 @@ export function BaseStylesPanel({
'--spacing-12': 12,
};
const ok = Object.entries(steps).every(
- ([k, step]) => tokens[k] === `${Math.round(base * step)}px`,
+ ([k, step]) => spacingToPx(tokens[k]) === Math.round(base * step),
);
return ok ? base : null;
})();
diff --git a/apps/docsite/src/app/playground/themeEditor/RawTokensPanel.tsx b/apps/docsite/src/app/playground/themeEditor/RawTokensPanel.tsx
index fe498206c8..d1dd44d772 100644
--- a/apps/docsite/src/app/playground/themeEditor/RawTokensPanel.tsx
+++ b/apps/docsite/src/app/playground/themeEditor/RawTokensPanel.tsx
@@ -34,6 +34,7 @@ import {
import {ColorSwatch} from './ColorSwatch';
import {TokenRow} from './TokenRow';
import {COLOR_CATEGORIES, TYPOGRAPHY_CATEGORIES} from './constants';
+import {spacingToPx} from './helpers';
const s = stylex.create({
scrollX: {
@@ -117,7 +118,7 @@ interface EditorProps {
}
function SpacingEditor({tokenName, value, onChange}: EditorProps) {
- const numValue = parseInt(value, 10);
+ const numValue = spacingToPx(value);
return (
<TokenRow
tokenName={tokenName}
diff --git a/apps/docsite/src/app/playground/themeEditor/helpers.ts b/apps/docsite/src/app/playground/themeEditor/helpers.ts
index 3513270154..d6da461b07 100644
--- a/apps/docsite/src/app/playground/themeEditor/helpers.ts
+++ b/apps/docsite/src/app/playground/themeEditor/helpers.ts
@@ -64,16 +64,36 @@ export function getTokenLabel(tokenName: string): string {
.replace(/\b\w/g, c => c.toUpperCase());
}
+/** The root font size the editor's px controls are written against. */
+const DEFAULT_ROOT_FONT_SIZE_PX = 16;
+
+/**
+ * A spacing token value in px at the default 16px root: the default scale's
+ * `'0.5rem'` reads as 8, and a theme's own px value (`'12px'`) as written.
+ * `NaN` for anything else.
+ */
+export function spacingToPx(value: string | undefined): number {
+ const match = /^(\d*\.?\d+)(px|rem)$/.exec((value ?? '').trim());
+ if (match == null) {
+ return Number.NaN;
+ }
+ const length = Number.parseFloat(match[1]);
+ return match[2] === 'rem' ? length * DEFAULT_ROOT_FONT_SIZE_PX : length;
+}
+
/**
- * Build the `--spacing-*` token ramp from a base step: each token is
- * `round(base × step)px`. Token keys derive from the step (e.g. 0.5 → "0-5").
+ * Build the `--spacing-*` token ramp from a base step in px: each token is
+ * `round(base × step)` px, written in rem like the default scale so the ramp
+ * keeps following the reader's root font size, and the default base (4)
+ * reproduces the defaults exactly. Token keys derive from the step (e.g.
+ * 0.5 → "0-5").
*/
export function buildSpacingScale(base: number): Record<string, string> {
const steps = [0, 0.5, 1, 1.5, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
const patch: Record<string, string> = {};
for (const step of steps) {
patch[`--spacing-${String(step).replace('.', '-')}`] =
- `${Math.round(base * step)}px`;
+ `${Math.round(base * step) / DEFAULT_ROOT_FONT_SIZE_PX}rem`;
}
return patch;
}
@@ -113,7 +133,7 @@ export function getConcentricityWarning(
const radii = expandRadiusScale({base: radiusBase, multiplier: 1});
const container = parseInt(radii['--radius-container'], 10);
const element = parseInt(radii['--radius-element'], 10);
- const gap = parseInt(buildSpacingScale(spacingBase)['--spacing-1'], 10);
+ const gap = spacingToPx(buildSpacingScale(spacingBase)['--spacing-1']);
const suggestion =
control === 'radius'
? `Set radius to ${spacingBase}px`
diff --git a/apps/storybook/stories/TabList.stories.tsx b/apps/storybook/stories/TabList.stories.tsx
index 415af603e0..0358072d8f 100644
--- a/apps/storybook/stories/TabList.stories.tsx
+++ b/apps/storybook/stories/TabList.stories.tsx
@@ -97,6 +97,21 @@ function assertGeometry(label: string, actual: number, expected: number) {
const px = (value: string) => Number.parseFloat(value);
+/**
+ * A length-valued custom property as the px length it resolves to. The
+ * computed value of a custom property is the token as written (`1rem`), so it
+ * is measured on a probe that inherits it rather than parsed.
+ */
+const resolvedPx = (element: HTMLElement, name: string) => {
+ const probe = document.createElement('div');
+ probe.style.position = 'absolute';
+ probe.style.width = `var(${name})`;
+ element.append(probe);
+ const width = px(getComputedStyle(probe).width);
+ probe.remove();
+ return width;
+};
+
/**
* Browser geometry guard for `isFullBleed`. The strip must escape the
* wrapper's padding while the first label returns to the content inset. The
@@ -456,15 +471,9 @@ export const FullBleedGeometry: Story = {
padStart: px(innerStyle.paddingInlineStart),
padEnd: px(innerStyle.paddingInlineEnd),
padBlockEnd: px(innerStyle.paddingBlockEnd),
- varStart: px(
- innerStyle.getPropertyValue('--container-padding-inline-start'),
- ),
- varEnd: px(
- innerStyle.getPropertyValue('--container-padding-inline-end'),
- ),
- varBlockEnd: px(
- innerStyle.getPropertyValue('--container-padding-block-end'),
- ),
+ varStart: resolvedPx(inner, '--container-padding-inline-start'),
+ varEnd: resolvedPx(inner, '--container-padding-inline-end'),
+ varBlockEnd: resolvedPx(inner, '--container-padding-block-end'),
nav,
navRect: nav.getBoundingClientRect(),
strip,
diff --git a/packages/cli/assets/docs/spacing.doc.mjs b/packages/cli/assets/docs/spacing.doc.mjs
index f538d38893..ac25bf670a 100644
--- a/packages/cli/assets/docs/spacing.doc.mjs
+++ b/packages/cli/assets/docs/spacing.doc.mjs
@@ -18,7 +18,7 @@ export const docs = {
content: [
{
type: 'prose',
- text: 'The design system uses a 4px base-unit spacing scale. Component gap props accept step values that map to these tokens. The scale provides fine-grained control at the small end (2px, 4px, 6px) and consistent rhythm at larger sizes (multiples of 4px).',
+ text: 'The design system uses a 4px base-unit spacing scale, written in rem so gaps and padding grow with the reader\'s browser font size the way text does: each step is 0.25rem, which is 4px at the default 16px root. Component gap props accept step values that map to these tokens. The scale provides fine-grained control at the small end (2px, 4px, 6px) and consistent rhythm at larger sizes (multiples of 4px).',
},
],
},
@@ -28,7 +28,7 @@ export const docs = {
content: [
{
type: 'prose',
- text: 'Fifteen spacing tokens, from 0px to 48px.',
+ text: 'Fifteen spacing tokens, from 0 to 3rem (0px to 48px at the default 16px root).',
},
{
type: 'token-ref',
diff --git a/packages/cli/assets/docs/tree/tokens-spacing.doc.mjs b/packages/cli/assets/docs/tree/tokens-spacing.doc.mjs
index 506e3e0168..7e1e25b073 100644
--- a/packages/cli/assets/docs/tree/tokens-spacing.doc.mjs
+++ b/packages/cli/assets/docs/tree/tokens-spacing.doc.mjs
@@ -35,63 +35,63 @@ export const docs = {
"rows": [
[
"--spacing-0",
- "0px"
+ "0rem"
],
[
"--spacing-0-5",
- "2px"
+ "0.125rem"
],
[
"--spacing-1",
- "4px"
+ "0.25rem"
],
[
"--spacing-1-5",
- "6px"
+ "0.375rem"
],
[
"--spacing-2",
- "8px"
+ "0.5rem"
],
[
"--spacing-3",
- "12px"
+ "0.75rem"
],
[
"--spacing-4",
- "16px"
+ "1rem"
],
[
"--spacing-5",
- "20px"
+ "1.25rem"
],
[
"--spacing-6",
- "24px"
+ "1.5rem"
],
[
"--spacing-7",
- "28px"
+ "1.75rem"
],
[
"--spacing-8",
- "32px"
+ "2rem"
],
[
"--spacing-9",
- "36px"
+ "2.25rem"
],
[
"--spacing-10",
- "40px"
+ "2.5rem"
],
[
"--spacing-11",
- "44px"
+ "2.75rem"
],
[
"--spacing-12",
- "48px"
+ "3rem"
]
]
}
diff --git a/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.test.tsx b/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.test.tsx
index e8d241c0b0..47950ccc27 100644
--- a/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.test.tsx
+++ b/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.test.tsx
@@ -6,7 +6,6 @@ import {useState} from 'react';
import {Table} from '../../Table';
import type {TableColumn} from '../../types';
import {useTableRowExpansion} from './useTableRowExpansion';
-import {spacingDefaults} from '../../../theme/tokens.stylex';
import {InternationalizationProvider} from '../../../i18n';
// popover mock for context-menu tests
@@ -236,25 +235,50 @@ describe('useTableRowExpansion (detail panel)', () => {
// content does: the chevron column's width plus a cell's own padding.
render(<Harness initialExpanded={new Set(['a'])} />);
expect(screen.getByTestId('panel').closest('td')).toHaveStyle({
- paddingInlineStart: 'calc(var(--spacing-10) + var(--spacing-3))',
+ paddingInlineStart: 'calc(40px + var(--spacing-3))',
});
});
it('tracks the table density it is rendered at', () => {
render(<Harness initialExpanded={new Set(['a'])} density="spacious" />);
expect(screen.getByTestId('panel').closest('td')).toHaveStyle({
- paddingInlineStart: 'calc(var(--spacing-10) + var(--spacing-4))',
+ paddingInlineStart: 'calc(40px + var(--spacing-4))',
});
});
- it('sizes the chevron column at the spacing token the panel indents by', () => {
- // The column width is a number the layout does arithmetic on, so it cannot
- // be a token reference — but the panel's indent, which has to line up with
- // the first column, spells it as `--spacing-10`. Pin the two together so a
- // change to the scale cannot silently unalign them.
+ it("indents the panel by the chevron column's own width", () => {
+ // The column width is a number the layout does arithmetic on, so it stays
+ // in pixels at every root font size. The panel's indent has to line up
+ // with the first column, so it spells the same pixels, not a rem spacing
+ // token. Pin the two together so neither can move without the other.
render(<Harness initialExpanded={new Set(['a'])} />);
const chevronHeader = screen.getAllByRole('columnheader')[0];
- expect(chevronHeader).toHaveStyle({width: spacingDefaults['--spacing-10']});
+ const columnWidth = getComputedStyle(chevronHeader).width;
+ const panelCell = screen
+ .getByTestId('panel')
+ .closest('td') as HTMLTableCellElement;
+ expect(columnWidth).toBe('40px');
+ expect(getComputedStyle(panelCell).paddingInlineStart).toMatch(
+ new RegExp(`^calc\\(${columnWidth} \\+ `),
+ );
+ });
+
+ it('keeps the chevron column free of the cell insets', () => {
+ // The column is fixed pixels while a cell's insets follow the spacing
+ // scale; laid out after them, the button ran past the column's edge. The
+ // body cell drops its own inline-start inset (the button then centers
+ // itself; the browser spec measures that), and the header cell drops both.
+ render(<Harness initialExpanded={new Set(['a'])} />);
+ const button = screen.getAllByRole('button', {name: /collapse row/i})[0];
+ expect(
+ getComputedStyle(button.closest('td') as HTMLTableCellElement)
+ .paddingInlineStart,
+ ).toMatch(/^0(px)?$/);
+ // The header cell holds only a hidden label; its insets alone would
+ // outgrow the 40px column at a large root font size.
+ const header = getComputedStyle(screen.getAllByRole('columnheader')[0]);
+ expect(header.paddingInlineStart).toMatch(/^0(px)?$/);
+ expect(header.paddingInlineEnd).toMatch(/^0(px)?$/);
});
describe('row divider placement', () => {
diff --git a/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.tsx b/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.tsx
index c4c4607d4c..adabb5e997 100644
--- a/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.tsx
+++ b/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.tsx
@@ -44,6 +44,7 @@ import type {
TableColumn,
BodyRowRenderProps,
BodyCellRenderProps,
+ HeaderCellRenderProps,
} from '../../types';
// =============================================================================
@@ -116,12 +117,16 @@ export interface UseTableRowExpansionConfig<T extends Record<string, unknown>> {
* The chevron column's width, in pixels.
*
* A column width is a number the layout does arithmetic on, not a CSS value,
- * so this cannot be a token reference — but it is the pixel value of
- * `--spacing-10`, and the panel's indent (which has to line up with the first
- * real column) spells it as the token. The unit test pins the two together so
- * a change to the scale cannot silently unalign them.
+ * so this stays a fixed pixel width at every root font size. The panel's
+ * indent, which has to line up with the first real column, spells the same
+ * pixels rather than a spacing token: spacing is rem and grows with the root
+ * font size, which would push the panel past the column it lines up with. The
+ * unit test pins the two together so neither can move without the other.
*/
const EXPANSION_COLUMN_WIDTH_PX = 40;
+const EXPANSION_COLUMN_KEY = '__expansion';
+/** The chevron button: the spacing step, never wider than its column. */
+const CHEVRON_SIZE = `min(${spacingVars['--spacing-6']}, ${EXPANSION_COLUMN_WIDTH_PX}px)`;
const EXPANSION_COLUMN_WIDTH = {
type: 'pixel' as const,
value: EXPANSION_COLUMN_WIDTH_PX,
@@ -132,8 +137,8 @@ const expansionStyles = stylex.create({
display: 'inline-flex',
alignItems: 'center',
justifyContent: 'center',
- width: spacingVars['--spacing-6'],
- height: spacingVars['--spacing-6'],
+ width: CHEVRON_SIZE,
+ height: CHEVRON_SIZE,
backgroundColor: 'transparent',
borderWidth: 0,
borderStyle: 'none',
@@ -234,17 +239,56 @@ const dividerStyles = stylex.create({
* gives its own content.
*
* Written as a logical property so RTL mirrors it, and kept in `calc` so the
- * padding half still tracks the spacing scale.
+ * padding half still tracks the spacing scale, as the cell's own padding does.
*/
const panelIndentStyles = stylex.create({
compact: {
- paddingInlineStart: `calc(${spacingVars['--spacing-10']} + ${spacingVars['--spacing-2']})`,
+ paddingInlineStart: `calc(${EXPANSION_COLUMN_WIDTH_PX}px + ${spacingVars['--spacing-2']})`,
},
balanced: {
- paddingInlineStart: `calc(${spacingVars['--spacing-10']} + ${spacingVars['--spacing-3']})`,
+ paddingInlineStart: `calc(${EXPANSION_COLUMN_WIDTH_PX}px + ${spacingVars['--spacing-3']})`,
},
spacious: {
- paddingInlineStart: `calc(${spacingVars['--spacing-10']} + ${spacingVars['--spacing-4']})`,
+ paddingInlineStart: `calc(${EXPANSION_COLUMN_WIDTH_PX}px + ${spacingVars['--spacing-4']})`,
+ },
+});
+
+/**
+ * The chevron sits centered in its column, as the selection checkbox does.
+ *
+ * The column is a fixed pixel width, but its cells' insets follow the spacing
+ * scale: the first column's edge inset, plus the density padding a body cell
+ * moves onto its right-click trigger. Laid out after both, the button ran past
+ * the column's edge, which clips its hover chip and, under a larger spacing
+ * scale or root font size, pushes the glyph out of view; and the header cell's
+ * insets alone outgrow 40px at a large root, widening the column. So the
+ * header cell, which holds only a visually hidden label, drops its inline
+ * insets, the body cell drops its inline-start inset, and the button cancels
+ * the trigger's padding (the same density step the panel indent uses) and
+ * centers itself.
+ */
+const chevronHeaderCellStyles = stylex.create({
+ cell: {
+ paddingInlineStart: 0,
+ paddingInlineEnd: 0,
+ },
+});
+
+const chevronCellStyles = stylex.create({
+ cell: {
+ paddingInlineStart: 0,
+ },
+});
+
+const chevronOffsetStyles = stylex.create({
+ compact: {
+ marginInlineStart: `calc((${EXPANSION_COLUMN_WIDTH_PX}px - ${CHEVRON_SIZE}) / 2 - ${spacingVars['--spacing-2']})`,
+ },
+ balanced: {
+ marginInlineStart: `calc((${EXPANSION_COLUMN_WIDTH_PX}px - ${CHEVRON_SIZE}) / 2 - ${spacingVars['--spacing-3']})`,
+ },
+ spacious: {
+ marginInlineStart: `calc((${EXPANSION_COLUMN_WIDTH_PX}px - ${CHEVRON_SIZE}) / 2 - ${spacingVars['--spacing-4']})`,
},
});
@@ -260,10 +304,14 @@ function ExpansionChevron({
onToggle: () => void;
}) {
const t = useTranslator();
+ const ctx = useTableContext();
return (
<button
type="button"
- {...stylex.props(expansionStyles.chevronButton)}
+ {...stylex.props(
+ expansionStyles.chevronButton,
+ chevronOffsetStyles[ctx?.density ?? 'balanced'],
+ )}
onClick={e => {
e.stopPropagation();
onToggle();
@@ -369,7 +417,7 @@ export function useTableRowExpansion<T extends Record<string, unknown>>(
const expansionColumn = useMemo(
(): TableColumn<T> => ({
- key: '__expansion',
+ key: EXPANSION_COLUMN_KEY,
// A `<th>` with no discernible text is announced as an unlabelled
// column; the label is hidden because the column shows only chevrons.
header: (
@@ -406,9 +454,19 @@ export function useTableRowExpansion<T extends Record<string, unknown>>(
return withExpansion;
},
+ transformHeaderCell(
+ props: HeaderCellRenderProps,
+ column: TableColumn<T>,
+ ): HeaderCellRenderProps {
+ // Keep the chevron column at its fixed width (chevronCellStyles).
+ return column.key === EXPANSION_COLUMN_KEY
+ ? {...props, xstyle: [...props.xstyle, chevronHeaderCellStyles.cell]}
+ : props;
+ },
+
transformBodyCell(
props: BodyCellRenderProps,
- _column: TableColumn<T>,
+ column: TableColumn<T>,
item: T,
): BodyCellRenderProps {
// Contribute the expand/collapse action on every cell; BaseTable
@@ -423,11 +481,16 @@ export function useTableRowExpansion<T extends Record<string, unknown>>(
const isExpanded = expandedKeys.has(key);
return {
...props,
- // Hand the row divider to the panel below, so the line closes the
- // row-plus-panel pair instead of splitting it.
- xstyle: isExpanded
- ? [...props.xstyle, dividerStyles.expandedRowCell]
- : props.xstyle,
+ xstyle: [
+ ...props.xstyle,
+ // The chevron centers itself in its column (chevronCellStyles).
+ ...(column.key === EXPANSION_COLUMN_KEY
+ ? [chevronCellStyles.cell]
+ : []),
+ // Hand the row divider to the panel below, so the line closes the
+ // row-plus-panel pair instead of splitting it.
+ ...(isExpanded ? [dividerStyles.expandedRowCell] : []),
+ ],
contextMenuActions: () => [
...resolveContextActions(props.contextMenuActions),
{
diff --git a/packages/core/src/theme/__tests__/SpacingRootFontSize.a11y.chromium.spec.ts b/packages/core/src/theme/__tests__/SpacingRootFontSize.a11y.chromium.spec.ts
new file mode 100644
index 0000000000..ca88921f0e
--- /dev/null
+++ b/packages/core/src/theme/__tests__/SpacingRootFontSize.a11y.chromium.spec.ts
@@ -0,0 +1,198 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file SpacingRootFontSize.a11y.chromium.spec.ts
+ * @input The checked-in Stack and TableRowExpansion stories, and Chromium
+ * @output Browser evidence that spacing follows the root font size as text does
+ * @position Theme token proof (WCAG 2.2 SC 1.4.4 Resize Text). A reader who
+ * raises the browser's font size gets larger text from the rem type scale;
+ * the gaps and padding between that text have to grow with it, and stay
+ * exactly as they were at the default 16px root.
+ */
+
+import {expect, test, type Page} from '@playwright/test';
+import {
+ DEFAULT_STORYBOOK_DIR,
+ serveStorybook,
+ type StaticServer,
+} from '@astryxdesign/a11y-spec/storybook';
+
+/** Each spacing token and the step it multiplies by the 4px base unit. */
+const SPACING_STEPS: Readonly<Record<string, number>> = {
+ '--spacing-0': 0,
+ '--spacing-0-5': 0.5,
+ '--spacing-1': 1,
+ '--spacing-1-5': 1.5,
+ '--spacing-2': 2,
+ '--spacing-3': 3,
+ '--spacing-4': 4,
+ '--spacing-5': 5,
+ '--spacing-6': 6,
+ '--spacing-7': 7,
+ '--spacing-8': 8,
+ '--spacing-9': 9,
+ '--spacing-10': 10,
+ '--spacing-11': 11,
+ '--spacing-12': 12,
+};
+
+let storybook: StaticServer;
+
+test.beforeAll(async () => {
+ storybook = await serveStorybook(
+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,
+ );
+});
+
+test.afterAll(async () => {
+ await storybook?.close();
+});
+
+async function openStory(
+ page: Page,
+ id: string,
+ rootFontSizePx: number,
+ globals = '',
+) {
+ const query = globals === '' ? '' : `&globals=${globals}`;
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=${id}&viewMode=story${query}`,
+ {waitUntil: 'load'},
+ );
+ await page.locator('#storybook-root > *').first().waitFor();
+ // The browser's font-size setting changes the root font size; setting it
+ // on the root element is the same input, without restarting the browser.
+ await page.evaluate(size => {
+ document.documentElement.style.fontSize = `${size}px`;
+ }, rootFontSizePx);
+}
+
+/** Every spacing token's used length in px, read off a probe's width. */
+async function spacingLengths(page: Page): Promise<Record<string, number>> {
+ return page.evaluate(names => {
+ const probe = document.createElement('div');
+ probe.style.position = 'absolute';
+ document.body.append(probe);
+ const lengths: Record<string, number> = {};
+ for (const name of names) {
+ probe.style.width = `var(${name})`;
+ lengths[name] = Number.parseFloat(getComputedStyle(probe).width);
+ }
+ probe.remove();
+ return lengths;
+ }, Object.keys(SPACING_STEPS));
+}
+
+/** The left edge of the first text node that reads exactly `text`. */
+async function textLeft(page: Page, text: string): Promise<number> {
+ return page.evaluate(wanted => {
+ const walker = document.createTreeWalker(
+ document.body,
+ NodeFilter.SHOW_TEXT,
+ );
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {
+ if (node.textContent?.trim() === wanted) {
+ const range = document.createRange();
+ range.selectNodeContents(node);
+ return range.getBoundingClientRect().left;
+ }
+ }
+ throw new Error(`no text node reads "${wanted}"`);
+ }, text);
+}
+
+for (const rootFontSizePx of [16, 20]) {
+ const scale = rootFontSizePx / 16;
+
+ test(`every spacing step is ${4 * scale}px × step at a ${rootFontSizePx}px root`, async ({
+ page,
+ }) => {
+ await openStory(page, 'core-stack--vertical', rootFontSizePx);
+ const lengths = await spacingLengths(page);
+ for (const [name, step] of Object.entries(SPACING_STEPS)) {
+ expect(lengths[name], name).toBeCloseTo(4 * scale * step, 3);
+ }
+ });
+
+ test(`a stack's gap grows with its text at a ${rootFontSizePx}px root`, async ({
+ page,
+ }) => {
+ await openStory(page, 'core-stack--vertical', rootFontSizePx);
+ const stack = page.getByText('Item 1', {exact: true}).locator('..');
+ const gap = await stack.evaluate(
+ element => getComputedStyle(element).rowGap,
+ );
+ // gap={4} is --spacing-4: 16px at the default root, 20px at 20px.
+ expect(gap).toBe(`${16 * scale}px`);
+ });
+}
+
+test('a detail panel keeps its place beside the first column at any root size', async ({
+ page,
+}) => {
+ // The chevron column is a fixed pixel width, so the panel's indent spells
+ // those pixels while its padding half follows the spacing scale, as the
+ // cell's own padding does. A larger root font size must not slide the
+ // panel's content away from the first column's.
+ const offsets: number[] = [];
+ // 32px is text at 200%, where the column's own insets would outgrow it.
+ for (const rootFontSizePx of [16, 20, 32]) {
+ await openStory(
+ page,
+ 'core-tablerowexpansion--detail-panel',
+ rootFontSizePx,
+ );
+ await expect(page.getByText('Line items')).toBeVisible();
+ offsets.push(
+ (await textLeft(page, 'Line items')) -
+ (await textLeft(page, 'Ada Lovelace')),
+ );
+ }
+ expect(Math.abs(offsets[0])).toBeLessThanOrEqual(1);
+ for (const offset of offsets) {
+ expect(Math.abs(offset - offsets[0])).toBeLessThan(0.5);
+ }
+});
+
+test('the expansion chevron sits inside its column at any root size or spacing scale', async ({
+ page,
+}) => {
+ // The chevron column is a fixed pixel width while the cell's insets follow
+ // the spacing scale, so the chevron centers itself in the column instead of
+ // laying out after those insets and running past the column's edge.
+ for (const [rootFontSizePx, globals] of [
+ [16, ''],
+ [20, ''],
+ [32, ''],
+ [16, 'astryxTheme:matcha'],
+ ] as const) {
+ await openStory(
+ page,
+ 'core-tablerowexpansion--detail-panel',
+ rootFontSizePx,
+ globals,
+ );
+ const chevron = page.locator('button[aria-expanded="true"]').first();
+ await expect(chevron).toBeVisible();
+ const {glyph, cell} = await chevron.evaluate(button => {
+ const box = (element: Element) => {
+ const rect = element.getBoundingClientRect();
+ return {left: rect.left, right: rect.right};
+ };
+ const svg = button.querySelector('svg');
+ const td = button.closest('td');
+ if (svg == null || td == null) {
+ throw new Error('missing chevron glyph or cell');
+ }
+ return {glyph: box(svg), cell: box(td)};
+ });
+ const where = `${rootFontSizePx}px root ${globals}`;
+ expect(cell.right - cell.left, where).toBeCloseTo(40, 0);
+ expect(glyph.left, where).toBeGreaterThanOrEqual(cell.left);
+ expect(glyph.right, where).toBeLessThanOrEqual(cell.right);
+ expect(
+ Math.abs((glyph.left + glyph.right) / 2 - (cell.left + cell.right) / 2),
+ where,
+ ).toBeLessThan(1);
+ }
+});
diff --git a/packages/core/src/theme/tokens.stylex.ts b/packages/core/src/theme/tokens.stylex.ts
index 4ea09ea68e..84c3481ed8 100644
--- a/packages/core/src/theme/tokens.stylex.ts
+++ b/packages/core/src/theme/tokens.stylex.ts
@@ -151,22 +151,25 @@ export const colorVars = stylex.defineVars(colorDefaults);
// Spacing Tokens
// =============================================================================
+// rem, like the type scale, so gaps and padding grow with the reader's root
+// font size instead of tightening around larger text. At the default 16px
+// root every step is still 4px × step: --spacing-2 is 8px, --spacing-4 16px.
export const spacingDefaults = {
- '--spacing-0': '0px',
- '--spacing-0-5': '2px',
- '--spacing-1': '4px',
- '--spacing-1-5': '6px',
- '--spacing-2': '8px',
- '--spacing-3': '12px',
- '--spacing-4': '16px',
- '--spacing-5': '20px',
- '--spacing-6': '24px',
- '--spacing-7': '28px',
- '--spacing-8': '32px',
- '--spacing-9': '36px',
- '--spacing-10': '40px',
- '--spacing-11': '44px',
- '--spacing-12': '48px',
+ '--spacing-0': '0rem',
+ '--spacing-0-5': '0.125rem',
+ '--spacing-1': '0.25rem',
+ '--spacing-1-5': '0.375rem',
+ '--spacing-2': '0.5rem',
+ '--spacing-3': '0.75rem',
+ '--spacing-4': '1rem',
+ '--spacing-5': '1.25rem',
+ '--spacing-6': '1.5rem',
+ '--spacing-7': '1.75rem',
+ '--spacing-8': '2rem',
+ '--spacing-9': '2.25rem',
+ '--spacing-10': '2.5rem',
+ '--spacing-11': '2.75rem',
+ '--spacing-12': '3rem',
} as const;
export const spacingVars = stylex.defineVars(spacingDefaults);
diff --git a/packages/core/src/theme/tokens.test.ts b/packages/core/src/theme/tokens.test.ts
index ac8faf2651..f5d8542a74 100644
--- a/packages/core/src/theme/tokens.test.ts
+++ b/packages/core/src/theme/tokens.test.ts
@@ -39,7 +39,7 @@ describe('resolveThemeTokens', () => {
it('resolves defaults when no theme is provided', () => {
const tokens = resolveThemeTokens(null, {mode: 'light'});
expect(tokens['--color-text-primary']).toBe('#0A1317');
- expect(tokens['--spacing-1']).toBe('4px');
+ expect(tokens['--spacing-1']).toBe('0.25rem');
expect(tokens['--border-width']).toBe('1px');
});
diff --git a/packages/core/src/theme/useTheme.test.tsx b/packages/core/src/theme/useTheme.test.tsx
index ba7de97769..fc48c465ec 100644
--- a/packages/core/src/theme/useTheme.test.tsx
+++ b/packages/core/src/theme/useTheme.test.tsx
@@ -42,7 +42,7 @@ describe('useTheme', () => {
expect(result.current.name).toBe('default');
// Should resolve default light-dark() tokens for light mode (useMediaQuery mocked to false = light)
expect(result.current.token('--color-text-primary')).toBe('#0A1317');
- expect(result.current.token('--spacing-1')).toBe('4px');
+ expect(result.current.token('--spacing-1')).toBe('0.25rem');
expect(result.current.mode).toBe('light');
});
@@ -78,8 +78,8 @@ describe('useTheme', () => {
const {result} = renderHook(() => useTheme(), {
wrapper: ({children}) => wrapper({children, mode: 'light'}),
});
- // --spacing-1 is not overridden — should be the default '4px'
- expect(result.current.token('--spacing-1')).toBe('4px');
+ // --spacing-1 is not overridden — should be the default '0.25rem'
+ expect(result.current.token('--spacing-1')).toBe('0.25rem');
expect(result.current.token('--border-width')).toBe('1px');
});
@@ -139,7 +139,7 @@ describe('useTheme', () => {
const tokens = result.current.tokens;
expect(tokens['--color-accent']).toBe('#AA0000');
expect(tokens['--spacing-4']).toBe('20px');
- expect(tokens['--spacing-1']).toBe('4px');
+ expect(tokens['--spacing-1']).toBe('0.25rem');
});
it('uses the same token resolution as resolveThemeTokens', () => {
diff --git a/packages/core/src/theme/useTheme.ts b/packages/core/src/theme/useTheme.ts
index b07fe5ec6b..3ca35ad4bc 100644
--- a/packages/core/src/theme/useTheme.ts
+++ b/packages/core/src/theme/useTheme.ts
@@ -81,7 +81,7 @@ export interface UseThemeReturn {
* @example
* ```
* const accent = token('--color-accent'); // "#0064E0" in light mode
- * const spacing = token('--spacing-4'); // "16px"
+ * const spacing = token('--spacing-4'); // "1rem"
* ```
*/
token: (name: string) => string;
diff --git a/packages/lab/src/ListInput/ListInput.test.tsx b/packages/lab/src/ListInput/ListInput.test.tsx
index e0df60e137..aa869ee2ef 100644
--- a/packages/lab/src/ListInput/ListInput.test.tsx
+++ b/packages/lab/src/ListInput/ListInput.test.tsx
@@ -535,7 +535,7 @@ describe('ListInput', () => {
expect(addedAnimationIndex).toBeGreaterThanOrEqual(0);
expect(animate).toHaveBeenCalledTimes(1);
expect(animate.mock.calls[addedAnimationIndex]).toEqual([
- [{transform: 'translateY(8px)'}, {transform: 'translateY(0)'}],
+ [{transform: 'translateY(0.5rem)'}, {transform: 'translateY(0)'}],
{
duration: 230,
easing: 'cubic-bezier(0.24, 1, 0.4, 1)',