Skip to content

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

TypeScript

fix(Toolbar): the three-lane row wraps instead of letting lanes overlap at large text (#10563)

Cindy Zhang0c0f9515f70f
diff --git a/.changeset/toolbar-wraps-at-large-text.md b/.changeset/toolbar-wraps-at-large-text.md
new file mode 100644
index 0000000000..939ed68325
--- /dev/null
+++ b/.changeset/toolbar-wraps-at-large-text.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] A `Toolbar` with `centerContent` wraps its row when its lanes don't fit, as at a larger text size on a phone, instead of letting the center title spill over the buttons beside it and past the screen's edge. The end lane, and the center lane when it does not fit beside the start lane, move to a following line. The center sits at the toolbar's middle as before while each side lane fits in half of the width it leaves. In a narrow container, a center `TabList` now shows all its tabs and the row wraps, and its tabs scroll only when they are wider than the toolbar.
+
+@cixzhang
diff --git a/apps/storybook/stories/Toolbar.stories.tsx b/apps/storybook/stories/Toolbar.stories.tsx
index d7a27e6c7c..6c823d4978 100644
--- a/apps/storybook/stories/Toolbar.stories.tsx
+++ b/apps/storybook/stories/Toolbar.stories.tsx
@@ -72,7 +72,7 @@ export const Default: Story = {
},
};
-/** Three-slot layout: CSS grid 1fr auto 1fr. Center content stays centered regardless of start/end width. */
+/** Three-slot layout. The center sits at the middle while each side lane fits in half of the width it leaves; when the lanes do not fit, the row wraps. */
export const ThreeSlot: Story = {
render: () => (
<Toolbar
@@ -486,3 +486,33 @@ export const WithCenterTabNavigation: Story = {
);
},
};
+
+/** Center tab navigation with an end action and no start lane. */
+export const CenterTabNavigationEndOnly: Story = {
+ name: 'Composition: Center Tab Navigation, End Only',
+ render: () => {
+ const [tab, setTab] = useState('overview');
+ return (
+ <Card>
+ <Toolbar
+ label="Center tab navigation"
+ dividers={['bottom']}
+ centerContent={
+ <TabList
+ value={tab}
+ onChange={setTab}
+ aria-label="Center tab navigation">
+ <Tab value="overview" label="Overview" />
+ <Tab value="analytics" label="Analytics" />
+ <Tab value="settings" label="Settings" />
+ </TabList>
+ }
+ endContent={<Button label="New item" />}
+ />
+ <Section>
+ <Text type="body">Content for the center tab navigation</Text>
+ </Section>
+ </Card>
+ );
+ },
+};
diff --git a/docs/specs/components/Toolbar/Toolbar.spec.md b/docs/specs/components/Toolbar/Toolbar.spec.md
index b6f6aa8608..29fa92486c 100644
--- a/docs/specs/components/Toolbar/Toolbar.spec.md
+++ b/docs/specs/components/Toolbar/Toolbar.spec.md
@@ -15,6 +15,7 @@ verified_by:
packages/core/src/Toolbar/Toolbar.test.tsx,
packages/core/src/Toolbar/__tests__/Toolbar.a11y.test.tsx,
packages/core/src/Toolbar/__tests__/Toolbar.a11y.chromium.spec.ts,
+ packages/core/src/Toolbar/__tests__/ToolbarTextSize.interaction.browser.spec.ts,
packages/core/src/Section/Section.test.tsx,
packages/core/src/theme/themingTargets.test.ts,
scripts/check-knowledge.mjs,
@@ -44,7 +45,7 @@ system_specs: [spec:AST-020]
| Behavior | A Section-wrapped `role="toolbar"` row with start, optional center, and end lanes. The row is one tab stop; arrow keys, Home, and End move focus among its controls along its orientation. |
| End-user impact | Keyboard users Tab into the toolbar once and move between its controls with arrows, without losing text-caret keys inside an input or arrow keys inside an open menu; screen-reader users hear a named toolbar and its orientation. |
| Builder impact | None. |
-| Compatibility/readiness | Records shipped behavior; no public change. Four implementation gaps (see Current-state impact). |
+| Compatibility/readiness | Three-lane layout change: the row wraps when its lanes do not fit (FR2); no public API change. Five current-state items (see Current-state impact). |
| Review checks | Reject more than one tab stop, arrows that steal caret keys from a text input mid-line, caller props that replace `role`, `aria-label`, or `aria-orientation`, or moving outer chrome into Toolbar. |
| Governing rules | `family:layout-regions`; `spec:AST-020` (toolbar pattern binding); `architecture:container-padding`. |
@@ -58,9 +59,12 @@ keyboard model, and size cascade. Consumer usage lives in `Toolbar.doc.mjs`.
## Compatibility and migration
-- Released default preserved: `yes`
-- Compatibility class: records shipped behavior; runtime, DOM, styling,
- targets, and public API remain unchanged
+- Released default preserved: `no` for the three-lane layout: when the lanes
+ do not fit one row, the row wraps (FR2), and in a narrow container a center
+ TabList keeps all of its tabs instead of scrolling them in place
+- Compatibility class: layout change to the three-lane row under FR2; DOM,
+ targets, and public API remain unchanged, and while the lanes fit one row
+ the layout is unchanged
- Controlled/uncontrolled behavior: not applicable
- Migration decision: none
@@ -76,6 +80,13 @@ Consumer migration instructions belong in consumer docs and release notes.
`orientation="vertical"` and `centerContent`, the three lanes stay in one row
while `aria-orientation` is vertical and ArrowDown and ArrowUp move between
them, so the visual order and the announced axis disagree.
+- **A scrolling TabList in the center lane wraps the row first.** In a narrow
+ container, a center lane that holds a TabList keeps all of its tabs while
+ they fit the toolbar, so the row wraps and the end lane moves to a second
+ line; the tabs scroll only when they are wider than the toolbar. With a
+ bottom divider, the selected tab's indicator sits on the rail while the lanes
+ share one line and on its tab while the row is wrapped; after a resize that
+ wraps or unwraps the row, the indicator can lag by one frame.
- **The tab stop does not follow a pointer click.** After a click on a control
that does not hold the stop, the stop stays on the earlier control, so
Shift+Tab from the clicked control lands on that earlier control inside the
@@ -109,15 +120,15 @@ owns the shared structural-region boundary.
## Behavioral and layout contract
-| ID | Invariant | Basis |
-| --- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------- |
-| FR1 | The render contains Section-owned Outer chrome around one Toolbar carrying `role="toolbar"`, `aria-label` from `label`, `aria-orientation`, and the `toolbar` target with `size`. Caller `role`, `aria-label`, and `aria-orientation` are dropped; other DOM props reach the toolbar row; `ref`, `className`, `style`, and `xstyle` reach the Section. | Current source, docs, tests, and family |
-| FR2 | Without center content the Toolbar is a flex line of the present start and end lanes, a row when horizontal and a column of lanes when vertical; with center content it is a three-lane grid whose lanes sit side by side in either orientation. Each lane lays its controls out in a row. No lane clips its content, and the center lane can shrink below its content width. `gap` spaces controls within and between lanes. | Current source and focused structure tests |
-| FR3 | Variant (default `transparent`), selected divider edges, and block padding by size remain delegated to Section, while Toolbar retains toolbar semantics, keyboard behavior, and internal layout. | Current source, docs, and family contract |
-| FR4 | The row MUST be a single tab stop. ArrowRight and ArrowLeft (horizontal) or ArrowDown and ArrowUp (vertical) move focus between its controls, wrapping at the ends and skipping disabled controls; Home and End move to the first and last. Implementation gap: only buttons, inputs, links, and elements with `tabindex` share the stop, so `textarea` and `select` carry their own tab stops, and a pointer click does not move the stop (Current-state impact). Arrows do not move focus out of a text input whose caret is mid-line, and inside an open composed menu arrow keys belong to the menu. The toolbar keeps its tab stop after a composed menu is dismissed from outside, and keeps its own arrow movement when rendered inside a popover. | APG toolbar pattern; current source and tests |
-| FR5 | Caller `onKeyDown`, `onFocus`, and `onBlur` run first; when the caller cancels the event, the built-in handling is skipped. | Current source and tests |
-| FR6 | Keyboard focus entering the row can show a brief, self-dismissing hint for its arrow-key axis. | Current source |
-| FR7 | `size` (default `md`) is provided to descendant controls as their default size; Toolbar starts its own size scope and does not inherit an outer size provider (`architecture:component-size-cascade` INV7). | Current source and tests |
+| ID | Invariant | Basis |
+| --- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------- |
+| FR1 | The render contains Section-owned Outer chrome around one Toolbar carrying `role="toolbar"`, `aria-label` from `label`, `aria-orientation`, and the `toolbar` target with `size`. Caller `role`, `aria-label`, and `aria-orientation` are dropped; other DOM props reach the toolbar row; `ref`, `className`, `style`, and `xstyle` reach the Section. | Current source, docs, tests, and family |
+| FR2 | Without center content the Toolbar is a flex line of the present start and end lanes, a row when horizontal and a column of lanes when vertical; with center content it has three lanes that sit side by side in either orientation, with the center lane at the toolbar's middle while each side lane fits in half of the width the center leaves. Each lane lays its controls out in a row. No lane clips or overlaps another; when the lanes do not fit one row at their minimum widths, the row wraps and the end lane moves to a following line, with the center lane too when it does not fit beside the start lane, and a start or end lane whose controls do not fit a line of their own wraps them (`spec:AST-102` FR4). `gap` spaces controls within and between lanes. | Current source and focused structure tests |
+| FR3 | Variant (default `transparent`), selected divider edges, and block padding by size remain delegated to Section, while Toolbar retains toolbar semantics, keyboard behavior, and internal layout. | Current source, docs, and family contract |
+| FR4 | The row MUST be a single tab stop. ArrowRight and ArrowLeft (horizontal) or ArrowDown and ArrowUp (vertical) move focus between its controls, wrapping at the ends and skipping disabled controls; Home and End move to the first and last. Implementation gap: only buttons, inputs, links, and elements with `tabindex` share the stop, so `textarea` and `select` carry their own tab stops, and a pointer click does not move the stop (Current-state impact). Arrows do not move focus out of a text input whose caret is mid-line, and inside an open composed menu arrow keys belong to the menu. The toolbar keeps its tab stop after a composed menu is dismissed from outside, and keeps its own arrow movement when rendered inside a popover. | APG toolbar pattern; current source and tests |
+| FR5 | Caller `onKeyDown`, `onFocus`, and `onBlur` run first; when the caller cancels the event, the built-in handling is skipped. | Current source and tests |
+| FR6 | Keyboard focus entering the row can show a brief, self-dismissing hint for its arrow-key axis. | Current source |
+| FR7 | `size` (default `md`) is provided to descendant controls as their default size; Toolbar starts its own size scope and does not inherit an outer size provider (`architecture:component-size-cascade` INV7). | Current source and tests |
### Allowed variation
@@ -187,20 +198,21 @@ become additional Toolbar-owned anatomy or targets.
## Verification map
-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
-| ------------------- | ------------------------------------------------------------------------------------------------------------ | --------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | ----------------------------- |
-| FR1 | `Toolbar.test.tsx` role, name, pass-through, and Section suites | Empty and populated Toolbar | Removing the role/name, Toolbar target, Section composition, or delegated Section target fails current evidence. | `audit:Toolbar/anatomy` |
-| FR2 | `Toolbar.test.tsx` slot and child-count suites | Start-only, end-only, two-lane, and three-lane | Changing current slot presence or two-/three-lane structure fails focused assertions. | `audit:Toolbar/layout` |
-| FR3 | `Toolbar.test.tsx` variant and block-inset tests | Default and passed variant | A variant that no longer reaches Section fails. | `audit:Toolbar/theming` |
-| FR4, FR5, AR1–AR2 | `Toolbar.test.tsx` keyboard and composition suites; `Toolbar.a11y.test.tsx`; `Toolbar.a11y.chromium.spec.ts` | Horizontal, vertical, text input, MoreMenu, popover | Extra tab stops, stolen caret keys, or ignored caller cancellation fails. | `audit:Toolbar/accessibility` |
-| Target inventory | `packages/core/src/theme/themingTargets.test.ts` | Toolbar and delegated Section targets | Runtime and documented target metadata drift fails target validation. | `audit:Toolbar/theming` |
-| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and current local target | Missing, extra, prefixed, or stale mappings fail repository validation. | `audit:Toolbar/theming` |
+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
+| ------------------- | ----------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- |
+| FR1 | `Toolbar.test.tsx` role, name, pass-through, and Section suites | Empty and populated Toolbar | Removing the role/name, Toolbar target, Section composition, or delegated Section target fails current evidence. | `audit:Toolbar/anatomy` |
+| FR2 | `Toolbar.test.tsx` slot and child-count suites | Start-only, end-only, two-lane, and three-lane | Changing current slot presence or two-/three-lane structure fails focused assertions. | `audit:Toolbar/layout` |
+| FR2 wrap | `ToolbarTextSize.interaction.browser.spec.ts` at a 402 px viewport at 165% and 194% default font size, and at 1024 px at 100% | Three Slot; default text size | Lane text that overlaps another lane or leaves the screen, a page that scrolls sideways, or a center that moves off the middle at 100% fails. | `audit:Toolbar/layout` |
+| FR3 | `Toolbar.test.tsx` variant and block-inset tests | Default and passed variant | A variant that no longer reaches Section fails. | `audit:Toolbar/theming` |
+| FR4, FR5, AR1–AR2 | `Toolbar.test.tsx` keyboard and composition suites; `Toolbar.a11y.test.tsx`; `Toolbar.a11y.chromium.spec.ts` | Horizontal, vertical, text input, MoreMenu, popover | Extra tab stops, stolen caret keys, or ignored caller cancellation fails. | `audit:Toolbar/accessibility` |
+| Target inventory | `packages/core/src/theme/themingTargets.test.ts` | Toolbar and delegated Section targets | Runtime and documented target metadata drift fails target validation. | `audit:Toolbar/theming` |
+| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and current local target | Missing, extra, prefixed, or stale mappings fail repository validation. | `audit:Toolbar/theming` |
Read from source, with no focused test yet:
- FR1: caller `role`, `aria-label`, and `aria-orientation` being dropped, and
`className`, `style`, and `xstyle` reaching Section.
-- FR2: the flex and grid layouts themselves, and `gap` spacing.
+- FR2: the two- and three-lane layouts themselves, and `gap` spacing.
- FR3: divider edges.
- FR5: caller `onFocus` and `onBlur` running first and their cancellation.
- FR4: `textarea` and `select` keeping their own tab stops, and the stop
diff --git a/packages/core/src/Toolbar/Toolbar.doc.mjs b/packages/core/src/Toolbar/Toolbar.doc.mjs
index 79f9a2e928..ec28221cdd 100644
--- a/packages/core/src/Toolbar/Toolbar.doc.mjs
+++ b/packages/core/src/Toolbar/Toolbar.doc.mjs
@@ -91,7 +91,7 @@ export const docs = {
name: 'centerContent',
type: 'ReactNode',
description:
- 'Centered content. Switches layout to CSS grid (1fr auto 1fr).',
+ 'Centered content. Switches to the three-lane layout: centered while each side lane fits in half of the width it leaves, and the row wraps when the lanes do not fit.',
slotElements: [
{__element: 'Text', props: {type: 'body', weight: 'bold'}, children: 'Center'},
{
@@ -188,7 +188,7 @@ export const docsZh = {
propDescriptions: {
label: '工具栏的无障碍标签,作为 aria-label 应用。',
startContent: '起始内容(LTR 中靠左对齐)。',
- centerContent: '居中内容。切换为 CSS grid(1fr auto 1fr)。',
+ centerContent: '居中内容。切换为三栏布局:两侧各栏都能放进中间栏剩余宽度的一半时居中;各栏放不下时换行。',
endContent: '结束内容(LTR 中靠右对齐)。',
size: '工具栏尺寸。控制最小高度,子组件通过 SizeContext 继承此尺寸作为默认值。',
gap: '插槽内项目间距。',
@@ -239,7 +239,7 @@ export const docsDense = {
propDescriptions: {
label: 'A11y label, aria-label on toolbar.',
startContent: 'Start-aligned content.',
- centerContent: 'Centered content; switches to 3-col grid.',
+ centerContent: 'Centered content; three lanes, wraps when they do not fit.',
endContent: 'End-aligned content.',
size: 'Toolbar size; controls min-height + cascades to children via SizeContext.',
gap: 'Gap between slot items.',
diff --git a/packages/core/src/Toolbar/Toolbar.test.tsx b/packages/core/src/Toolbar/Toolbar.test.tsx
index c15ec67bb4..d7a119c824 100644
--- a/packages/core/src/Toolbar/Toolbar.test.tsx
+++ b/packages/core/src/Toolbar/Toolbar.test.tsx
@@ -249,7 +249,7 @@ describe('Toolbar', () => {
expect(clipsOverflow(slotOf('end'))).toBe(false);
});
- it('still lets the center slot shrink below its content width', () => {
+ it('sizes the center slot from its minimum width and wraps the row instead', () => {
render(
<Toolbar
label="Actions"
@@ -258,9 +258,13 @@ describe('Toolbar', () => {
endContent={<span data-testid="end">End</span>}
/>,
);
- // The `auto` track only shrinks for an item whose minimum width is zero.
- // Dropping the clip must not turn a narrow toolbar into a wider one.
- expect(parseFloat(getComputedStyle(slotOf('center')).minWidth)).toBe(0);
+ // The center lane claims its content's minimum width when the row
+ // decides where to wrap, so its text never spills over the lanes beside
+ // it; a row that does not fit wraps.
+ expect(getComputedStyle(slotOf('center')).flexBasis).toBe('min-content');
+ expect(getComputedStyle(screen.getByRole('toolbar')).flexWrap).toBe(
+ 'wrap',
+ );
});
});
diff --git a/packages/core/src/Toolbar/Toolbar.tsx b/packages/core/src/Toolbar/Toolbar.tsx
index 5d24ab943f..c6b70196c0 100644
--- a/packages/core/src/Toolbar/Toolbar.tsx
+++ b/packages/core/src/Toolbar/Toolbar.tsx
@@ -17,7 +17,7 @@
* - /packages/cli/assets/templates/blocks/components/Toolbar/ (showcase blocks)
*/
-import {useCallback, type ReactNode} from 'react';
+import {useCallback, useState, type ReactNode} from 'react';
import type {BaseProps} from '../BaseProps';
import type {SectionVariant} from '../Section/Section';
import type {SpacingStep} from '../utils/types';
@@ -31,6 +31,8 @@ import {useKeyboardHint} from '../hooks/useKeyboardHint';
import {SizeProvider} from '../SizeContext/SizeContext';
import {edgeCompSlot} from '../Layout/edgeCompensation.stylex';
import {themeProps} from '../utils/themeProps';
+import {observeResize} from '../utils/sharedResizeObserver';
+import {useAttachment} from '../hooks/useAttachment';
/**
* Map SpacingStep values to spacingVars keys.
@@ -56,12 +58,20 @@ const styles = stylex.create({
alignItems: 'center',
justifyContent: 'space-between',
},
- // Three-slot layout (with centerContent): CSS grid 1fr auto 1fr
- baseGrid: {
- display: 'grid',
- gridTemplateColumns: '1fr auto 1fr',
+ // Three-lane layout. The side lanes share the width the center leaves
+ // equally, so the center stays at the middle while each fits its half. When
+ // the lanes do not fit, the row wraps. The end lane moves to a following
+ // line. The center lane moves too when it does not fit beside the start lane.
+ baseThreeLane: {
+ display: 'flex',
+ flexWrap: 'wrap',
alignItems: 'center',
},
+ // Lanes stay side by side in a vertical toolbar too; only the cross-axis
+ // alignment follows the orientation.
+ verticalThreeLane: {
+ alignItems: 'stretch',
+ },
// Vertical orientation
vertical: {
flexDirection: 'column',
@@ -72,15 +82,29 @@ const styles = stylex.create({
display: 'flex',
alignItems: 'center',
},
- // `minWidth: 0` lets the `auto` track shrink below the content's width, so a
- // wide center never widens the toolbar. The slot deliberately does not clip
- // (`overflow`): clipping would cut off the box-shadow and focus ring of its
- // outermost children, which paint outside their own box.
+ // The center basis is its minimum width, so the row wraps before its text
+ // overlaps a side lane. Alone on a line narrower than its content, the lane
+ // shrinks, so a TabList scrolls. The slot does not clip, because clipping
+ // cuts off the focus ring and shadow of its outer children.
centerSlot: {
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
+ flexGrow: 1000,
+ flexShrink: 1,
+ flexBasis: 'min-content',
minWidth: 0,
+ maxWidth: 'max-content',
+ },
+ // The side lanes share the width the center leaves. A lane keeps its
+ // controls on one line, so the row wraps first. Only a lane wider than the
+ // toolbar wraps its own controls.
+ sideLane: {
+ flexGrow: 1,
+ flexShrink: 1,
+ flexWrap: 'wrap',
+ // `fit-content` is the lane's full row, capped at the toolbar's width.
+ minWidth: stylex.firstThatWorks('fit-content', '-webkit-fit-content'),
},
endSlot: {
display: 'flex',
@@ -104,10 +128,26 @@ const sizeStyles = stylex.create({
});
// Dynamic styles for configurable gap and tab indicator offset
+// Edge compensation's marker (edgeCompensation.stylex.ts), restated here:
+// StyleX resolves a style's keys within its own file.
+const FIRST_EDGE_COMP = ':has(> [data-astryx-edge-comp]:first-child)';
+const LAST_EDGE_COMP = ':has(> [data-astryx-edge-comp]:last-child)';
+
const dynamicStyles = stylex.create({
gap: (gapValue: string) => ({
gap: gapValue,
}),
+ // Edge compensation pulls a side lane out by a negative margin, which flex
+ // counts toward the lane's share of the row. This basis gives that width
+ // back, so the lane's share excludes it and the center stays at the middle.
+ sideLaneBasis: (amount: string) => ({
+ flexBasis: {
+ default: '0px',
+ [FIRST_EDGE_COMP]: amount,
+ [LAST_EDGE_COMP]: amount,
+ [`${FIRST_EDGE_COMP}${LAST_EDGE_COMP}`]: `calc(2 * ${amount})`,
+ },
+ }),
tabIndicatorBottom: (offset: string) => ({
'--_tab-indicator-bottom': offset,
}),
@@ -124,6 +164,23 @@ const defaultBlockPaddingForSize: Record<ElementSize, SpacingStep> = {
lg: 2,
};
+/**
+ * Whether a three-lane row has wrapped: its lanes no longer share one
+ * vertical band.
+ */
+function lanesHaveWrapped(row: Element): boolean {
+ // An empty lane is a box with no height, so it shares every line.
+ const boxes = [...row.children]
+ .slice(0, 3)
+ .map(lane => lane.getBoundingClientRect())
+ .filter(box => box.height > 0);
+ return (
+ boxes.length > 1 &&
+ Math.max(...boxes.map(box => box.top)) >=
+ Math.min(...boxes.map(box => box.bottom))
+ );
+}
+
const blockPaddingVarForSize: Record<ElementSize, string> = {
sm: spacingVars['--spacing-2'],
md: spacingVars['--spacing-2'],
@@ -152,7 +209,9 @@ export interface ToolbarProps extends BaseProps<HTMLDivElement> {
startContent?: ReactNode;
/**
* Content centered between start and end.
- * When provided, switches layout to CSS grid (1fr auto 1fr).
+ * When provided, switches to the three-lane layout: the center sits at the
+ * toolbar's middle while each side lane fits in half of the width it leaves,
+ * and the row wraps when the lanes do not fit.
*/
centerContent?: ReactNode;
/**
@@ -210,7 +269,7 @@ const toolbarTabStop = oneTabStopAmong(TOOLBAR_ITEMS, TOOLBAR_BOUNDARY);
/**
* General-purpose toolbar with start, center, and end content slots.
*
- * Built on Section, provides flex/grid layout with roving tabindex
+ * Built on Section, provides a flex layout with roving tabindex
* keyboard navigation via useListFocus. Cascades `size` to child components
* (Button, TextInput, TabList, Selector) via SizeContext, and applies
* edge compensation so ghost buttons align flush at container edges.
@@ -263,6 +322,22 @@ export function Toolbar({
tabStopOrder: toolbarTabStop,
});
+ // A bottom divider drops a tab's indicator onto its rail through the block
+ // padding. That is right only while the lanes share one line, so a wrapped
+ // row keeps the indicator on its tab. The row reports a wrap after layout,
+ // in a resize observation.
+ const watchesWrap = hasCenterContent && hasBottomDivider;
+ const [isWrapped, setIsWrapped] = useState(false);
+ useAttachment(
+ listRef,
+ row =>
+ watchesWrap
+ ? observeResize(row, () => setIsWrapped(lanesHaveWrapped(row)))
+ : () => {},
+ watchesWrap,
+ );
+ const dropsIndicatorOnRail = hasBottomDivider && !(watchesWrap && isWrapped);
+
const {
hintElement,
onKeyDown: onHintKeyDown,
@@ -326,8 +401,9 @@ export function Toolbar({
{...mergeProps(
themeProps('toolbar', {size}),
stylex.props(
- hasCenterContent ? styles.baseGrid : styles.baseFlex,
- orientation === 'vertical' && styles.vertical,
+ hasCenterContent ? styles.baseThreeLane : styles.baseFlex,
+ orientation === 'vertical' &&
+ (hasCenterContent ? styles.verticalThreeLane : styles.vertical),
sizeStyles.base,
dynamicStyles.gap(gapVar),
// Only drop the tab indicator through the toolbar's block padding
@@ -335,7 +411,7 @@ export function Toolbar({
// Without a divider, leave `--_tab-indicator-bottom` unset so a
// nested TabList's indicator keeps its own default (hugging the
// tab) instead of floating down into the toolbar's padding.
- hasBottomDivider &&
+ dropsIndicatorOnRail &&
dynamicStyles.tabIndicatorBottom(
`calc(-1 * (${blockPaddingVarForSize[size]} + 1px))`,
),
@@ -343,11 +419,13 @@ export function Toolbar({
)}
{...props}>
{hasCenterContent ? (
- // Three-slot grid layout
+ // Three-slot layout
<>
<div
{...stylex.props(
styles.startSlot,
+ styles.sideLane,
+ dynamicStyles.sideLaneBasis(edgeCompInsetForSize[size]),
edgeCompSlot.inset(edgeCompInsetForSize[size]),
dynamicStyles.gap(gapVar),
)}>
@@ -360,6 +438,8 @@ export function Toolbar({
<div
{...stylex.props(
styles.endSlot,
+ styles.sideLane,
+ dynamicStyles.sideLaneBasis(edgeCompInsetForSize[size]),
edgeCompSlot.inset(edgeCompInsetForSize[size]),
dynamicStyles.gap(gapVar),
)}>
diff --git a/packages/core/src/Toolbar/__tests__/ToolbarTextSize.interaction.browser.spec.ts b/packages/core/src/Toolbar/__tests__/ToolbarTextSize.interaction.browser.spec.ts
new file mode 100644
index 0000000000..4516907a6b
--- /dev/null
+++ b/packages/core/src/Toolbar/__tests__/ToolbarTextSize.interaction.browser.spec.ts
@@ -0,0 +1,195 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ToolbarTextSize.interaction.browser.spec.ts
+ * @input The built Toolbar Three Slot story on a 402 px viewport, at
+ * Chromium's default font size and at 165% and 194% of it (iOS Dynamic Type
+ * AX1 and AX2 relative to the default body size)
+ * @output Real-browser evidence that the three lanes never overlap or leave
+ * the screen, that the row wraps when they do not fit, and that the center
+ * sits at the toolbar's middle at the default text size
+ * @position Browser proof of Toolbar FR2's wrap (AST-102 FR4)
+ */
+
+import {expect, test, type Page} from '@astryxdesign/a11y-spec/playwright';
+import {
+ DEFAULT_STORYBOOK_DIR,
+ serveStorybook,
+ type StaticServer,
+} from '@astryxdesign/a11y-spec/storybook';
+
+let storybook: StaticServer;
+
+test.beforeAll(async () => {
+ storybook = await serveStorybook(
+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,
+ );
+});
+
+test.afterAll(async () => {
+ await storybook?.close();
+});
+
+test.skip(
+ ({browserName}) => browserName !== 'chromium',
+ 'Page.setFontSizes is a Chromium DevTools command',
+);
+
+test.use({viewport: {width: 402, height: 874}});
+
+/** Sets the browser's default font size, which rem-based text follows. */
+async function setDefaultFontSize(page: Page, px: number): Promise<void> {
+ const session = await page.context().newCDPSession(page);
+ await session.send('Page.setFontSizes', {
+ fontSizes: {standard: px, fixed: Math.round((px * 13) / 16)},
+ });
+}
+
+/** Each lane's text and controls as boxes, plus the toolbar's box. */
+async function readLanes(page: Page) {
+ return page.evaluate(() => {
+ const toolbar = document.querySelector<HTMLElement>('[role="toolbar"]');
+ if (toolbar == null) {
+ throw new Error('No toolbar');
+ }
+ const toolbarBox = toolbar.getBoundingClientRect();
+ // The three lane elements; the keyboard hint is not a lane.
+ const lanes = [...toolbar.children]
+ .filter((lane): lane is HTMLElement => lane instanceof HTMLElement)
+ .slice(0, 3)
+ .map(lane => {
+ const range = document.createRange();
+ range.selectNodeContents(lane);
+ const box = range.getBoundingClientRect();
+ return {
+ text: lane.innerText.trim(),
+ left: box.left,
+ right: box.right,
+ top: box.top,
+ bottom: box.bottom,
+ };
+ });
+ return {
+ scrollWidth: document.documentElement.scrollWidth,
+ viewportWidth: document.documentElement.clientWidth,
+ toolbarCenter: (toolbarBox.left + toolbarBox.right) / 2,
+ lanes,
+ };
+ });
+}
+
+async function openThreeSlot(page: Page, px: number): Promise<void> {
+ await setDefaultFontSize(page, px);
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=core-toolbar--three-slot&viewMode=story`,
+ );
+ await page.locator('[role="toolbar"]').waitFor();
+}
+
+test('at the default text size the center sits at the middle', async ({
+ page,
+}) => {
+ // Wide enough that the start and end lanes share the rest equally.
+ await page.setViewportSize({width: 1024, height: 768});
+ await openThreeSlot(page, 16);
+ const {lanes, toolbarCenter} = await readLanes(page);
+ expect(lanes).toHaveLength(3);
+ const center = lanes[1];
+ expect(
+ Math.abs((center.left + center.right) / 2 - toolbarCenter),
+ ).toBeLessThan(1);
+ // One line: the lanes' contents differ in height but share a vertical band.
+ expect(
+ Math.max(...lanes.map(lane => lane.top)) <
+ Math.min(...lanes.map(lane => lane.bottom)),
+ ).toBe(true);
+});
+
+for (const [size, px] of [
+ ['165%', 26],
+ ['194%', 31],
+] as const) {
+ test(`at ${size} text size no lane overlaps another or leaves the screen`, async ({
+ page,
+ }) => {
+ await openThreeSlot(page, px);
+ const {scrollWidth, viewportWidth, lanes} = await readLanes(page);
+ expect(scrollWidth).toBeLessThanOrEqual(viewportWidth);
+ for (const lane of lanes) {
+ expect(lane.left, lane.text).toBeGreaterThanOrEqual(0);
+ expect(lane.right, lane.text).toBeLessThanOrEqual(viewportWidth);
+ }
+ for (let i = 0; i < lanes.length; i++) {
+ for (let j = i + 1; j < lanes.length; j++) {
+ const a = lanes[i];
+ const b = lanes[j];
+ const overlapsX =
+ Math.min(a.right, b.right) - Math.max(a.left, b.left) > 1;
+ const overlapsY =
+ Math.min(a.bottom, b.bottom) - Math.max(a.top, b.top) > 1;
+ expect(overlapsX && overlapsY, `${a.text} / ${b.text}`).toBe(false);
+ }
+ }
+ });
+}
+
+/** The selected tab's indicator, its tab, and the toolbar row, as boxes. */
+async function readIndicator(page: Page) {
+ return page.evaluate(() => {
+ const toolbar = document.querySelector<HTMLElement>('[role="toolbar"]');
+ const indicator = [
+ ...document.querySelectorAll<HTMLElement>('.astryx-tab-indicator'),
+ ].find(element => getComputedStyle(element).opacity !== '0');
+ const tab = indicator?.closest<HTMLElement>('.astryx-tab');
+ if (toolbar == null || indicator == null || tab == null) {
+ throw new Error('No toolbar, tab, or visible indicator');
+ }
+ return {
+ indicatorBottom: indicator.getBoundingClientRect().bottom,
+ tabBottom: tab.getBoundingClientRect().bottom,
+ toolbarBottom: toolbar.getBoundingClientRect().bottom,
+ };
+ });
+}
+
+test('with a bottom divider the indicator sits on the rail while the lanes share one line', async ({
+ page,
+}) => {
+ await page.setViewportSize({width: 1024, height: 768});
+ await setDefaultFontSize(page, 16);
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=core-toolbar--with-center-tab-navigation&viewMode=story`,
+ );
+ await page.locator('[role="toolbar"]').waitFor();
+ const {indicatorBottom, tabBottom} = await readIndicator(page);
+ expect(indicatorBottom).toBeGreaterThan(tabBottom + 2);
+});
+
+test('with a bottom divider a wrapped row keeps the indicator on its tab', async ({
+ page,
+}) => {
+ await setDefaultFontSize(page, 16);
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=core-toolbar--with-center-tab-navigation&viewMode=story`,
+ );
+ await page.locator('[role="toolbar"]').waitFor();
+ await expect
+ .poll(async () => {
+ const {indicatorBottom, tabBottom} = await readIndicator(page);
+ return Math.abs(indicatorBottom - tabBottom) <= 2;
+ })
+ .toBe(true);
+});
+
+test('with a bottom divider and an empty start lane the indicator sits on the rail', async ({
+ page,
+}) => {
+ await page.setViewportSize({width: 1024, height: 768});
+ await setDefaultFontSize(page, 16);
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=core-toolbar--center-tab-navigation-end-only&viewMode=story`,
+ );
+ await page.locator('[role="toolbar"]').waitFor();
+ const {indicatorBottom, tabBottom} = await readIndicator(page);
+ expect(indicatorBottom).toBeGreaterThan(tabBottom + 2);
+});