An open source design system that's fully customizable and agent ready
TypeScript
fix(TopNav): the bar wraps instead of letting regions overlap at large text (#10571)
Cindy Zhang19981aa37506
diff --git a/.changeset/topnav-wraps-at-large-text.md b/.changeset/topnav-wraps-at-large-text.mdnew file mode 100644index 0000000000..da85fd468b--- /dev/null+++ b/.changeset/topnav-wraps-at-large-text.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] `TopNav` wraps its bar when its regions don't fit one row, as at a larger text size, instead of letting the end content (such as buttons) cover the navigation items. The end content moves to a second line. While the regions fit, the bar and its centered content look as before.++@cixzhangdiff --git a/docs/specs/components/TopNav/TopNav.spec.md b/docs/specs/components/TopNav/TopNav.spec.mdindex 6a2771c9b7..168523ad84 100644--- a/docs/specs/components/TopNav/TopNav.spec.md+++ b/docs/specs/components/TopNav/TopNav.spec.md@@ -14,6 +14,7 @@ verified_by:[packages/core/src/TopNav/TopNav.test.tsx,packages/core/src/TopNav/__tests__/TopNavMobileLongHeading.a11y.chromium.spec.ts,+ packages/core/src/TopNav/__tests__/TopNavTextSize.interaction.browser.spec.ts,packages/core/src/AppShell/AppShell.test.tsx,apps/storybook/stories/TopNav.stories.tsx,apps/storybook/rtl-audit/targets.json,@@ -38,7 +39,7 @@ system_specs: []| End-user impact | Screen-reader users get a named navigation landmark; phone-width users keep the product heading, end controls, and, while auto toggles are on, a drawer toggle in view while the navigation items move into the drawer. || Builder impact | None. Callers fill slots; `children` is accepted so nav items are not dropped. || Compatibility/readiness | Records shipped behavior; no prop, default, target, or export changes. Two implementation gaps (see Current-state impact). |-| Review checks | Reject dropping `children` when `startContent` is absent, dropping the three-column layout when `centerContent` is present, an unlabeled landmark, or a mobile bar that hides the toggle while drawer content exists and auto toggles are on (FR5). |+| Review checks | Reject dropping `children` when `startContent` is absent, dropping the three-region layout when `centerContent` is present, an unlabeled landmark, or a mobile bar that hides the toggle while drawer content exists and auto toggles are on (FR5). || Governing rules | `component:AppShell` FR9–FR10 select the render mode; MobileNav owns the drawer dialog; `architecture:component-theming-surface`. |This table is a review projection; the body below is authoritative.@@ -66,16 +67,15 @@ Consumer migration instructions belong in consumer docs and release notes.spread onto the `<nav>` after `role` and `aria-label`, so a caller `role` or`aria-label` replaces them. `architecture:public-component-api` INV5 keepscomponent-owned accessibility from being overwritten by accident.-- **Wide end content shifts the center.** The end column sets no minimum width- of zero, so end content wider than its share widens that column and moves the- center content toward the start.+- **Wide end content shifts the center.** End content wider than its share+ widens the end region and moves the center content toward the start.## Ownership boundary**Owns**- The navigation landmark and its default name (FR1, AR1).-- Slot resolution and the flex and three-column layouts (FR2–FR4).+- Slot resolution and the flex and three-region layouts (FR2–FR4).- The mobile-bar and drawer renderings of the bar itself (FR5, FR6).- The `<nav>`'s positioning and styling inputs (FR8, FR9).- The slot each descendant sits in, which TopNav menus read for popover@@ -106,8 +106,8 @@ Consumer migration instructions belong in consumer docs and release notes.| --- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------ || FR1 | In `default` and `mobile-bar` modes TopNav renders one `<nav role="navigation">` named by `label`, or by the translated `@astryx.topNav.landmarkLabel` ("Top navigation") when `label` is omitted. It carries `top-nav`, the forwarded `ref`, and other DOM props; `mobile-bar` adds `data-mode="mobile-bar"`. | Current source and tests || FR2 | `startContent` wins over `children`; `children` render as start content only when `startContent` is `null` or `undefined`. | Current source and tests |-| FR3 | Without `centerContent` the bar is a flex row: heading then start content at the inline start, end content pushed to the inline end. | Current source and tests |-| FR4 | With `centerContent` the bar is a three-column grid (`1fr auto 1fr`) that centers the center content while the start and end regions each fit their equal share. | Current source and tests |+| FR3 | Without `centerContent` the bar is a flex row: heading then start content at the inline start, end content pushed to the inline end. No region overlaps another; when the regions do not fit one row, the bar wraps and the end content moves to a second line, and a region wider than the whole bar wraps its own items (`spec:AST-102` FR4). | Current source and tests |+| FR4 | With `centerContent` the bar has three regions that center the center content while the start and end regions each fit their equal share of one row; when they do not fit one row, the bar wraps as FR3 describes. | Current source and tests || FR5 | `mobile-bar` mode renders the heading, then the end content and, when drawer content exists and auto toggles are on, the mobile nav toggle at the inline end. Start and center content do not render. The heading yields width first so end content and the toggle stay on screen. Drawer content exists when start or center content is present or AppShell passes side nav content. | Current source and tests || FR6 | `drawer` mode renders a MobileNav whose header is `heading` and whose body is start then center content in a vertical list, a divider when items and side nav content are both present, then any side nav content AppShell passes. With neither, TopNav renders nothing. | Current source and tests || FR7 | In `default` mode TopNav tells start, center, and end descendants which slot they are in. | Current source |@@ -122,13 +122,13 @@ Consumer migration instructions belong in consumer docs and release notes.### Representative states-| State | Required invariant | Allowed variation |-| --------------------------------- | ------------------------------------------------------------------------ | ------------------- |-| Heading and items, no center | Flex row; end content at the inline end. | Gaps and padding. |-| Center content present | Three-column grid; center centered while each side fits its share (FR4). | Column content. |-| Mobile bar with a long heading | With auto toggles on, toggle and end content stay inside the bar. | Heading truncation. |-| Mobile bar with no drawer content | No toggle. | — |-| Drawer with items and side nav | Items, divider, side nav content. | Item modes. |+| State | Required invariant | Allowed variation |+| --------------------------------- | -------------------------------------------------------------------- | ------------------- |+| Heading and items, no center | Flex row; end content at the inline end. | Gaps and padding. |+| Center content present | Three regions; center centered while each side fits its share (FR4). | Column content. |+| Mobile bar with a long heading | With auto toggles on, toggle and end content stay inside the bar. | Heading truncation. |+| Mobile bar with no drawer content | No toggle. | — |+| Drawer with items and side nav | Items, divider, side nav content. | Item modes. |### Transformation and precedence order@@ -168,15 +168,16 @@ component's record names its own target.## Verification map-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |-| ------------ | ------------------------------------------------------------------------------------------------ | ----------------------------------------------- | --------------------------------------------------------------------------- | ---------------------------- |-| FR1, AR1 | `TopNav.test.tsx` landmark tests | Default and mobile-bar; default and custom name | A missing role or name fails. | `audit:TopNav/accessibility` |-| FR2–FR4, FR8 | `TopNav.test.tsx` slot tests | Each slot; all slots; center without start/end | A dropped slot, wrong precedence, or positioned nav fails. | `audit:TopNav/layout` |-| FR5, FR6 | `AppShell.test.tsx` mobile suites | Heading-only; items; items with side nav | A missing toggle or duplicated items fails. | `audit:TopNav/behavior` |-| AR2 | `TopNavMobileLongHeading.a11y.chromium.spec.ts` | Long heading at phone width | The toggle or close button leaves the viewport. | `audit:TopNav/accessibility` |-| RTL relation | RTL audit curated D2 target (`apps/storybook/rtl-audit/targets.json`) on `TopNav / Full example` | Heading and first navigation item; LTR and RTL | A heading that is not at the inline start of the navigation items fails D2. | `audit:TopNav/i18n-rtl` |+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |+| ------------- | ------------------------------------------------------------------------------------------------- | ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------- | ---------------------------- |+| FR1, AR1 | `TopNav.test.tsx` landmark tests | Default and mobile-bar; default and custom name | A missing role or name fails. | `audit:TopNav/accessibility` |+| FR2–FR4, FR8 | `TopNav.test.tsx` slot tests | Each slot; all slots; center without start/end | A dropped slot, wrong precedence, or positioned nav fails. | `audit:TopNav/layout` |+| FR3, FR4 wrap | `TopNavTextSize.interaction.browser.spec.ts` at 1280 px and 100%, 200% and 250% default font size | Full Example; Centered With Start Content | A navigation item covered by another region, a page that scrolls sideways, or a changed layout at 100% fails. | `audit:TopNav/layout` |+| FR5, FR6 | `AppShell.test.tsx` mobile suites | Heading-only; items; items with side nav | A missing toggle or duplicated items fails. | `audit:TopNav/behavior` |+| AR2 | `TopNavMobileLongHeading.a11y.chromium.spec.ts` | Long heading at phone width | The toggle or close button leaves the viewport. | `audit:TopNav/accessibility` |+| RTL relation | RTL audit curated D2 target (`apps/storybook/rtl-audit/targets.json`) on `TopNav / Full example` | Heading and first navigation item; LTR and RTL | A heading that is not at the inline start of the navigation items fails D2. | `audit:TopNav/i18n-rtl` |-Read from source, with no focused test yet: the mobile bar's part order (FR5); the drawer's `heading` header (FR6); other DOM props reaching the `<nav>` (FR1); the auto-toggle condition (FR5); rendering nothing in `drawer` mode with no content (FR6); the `top-nav` target and its `mode` state (FR1); the flex and grid layout geometry (FR3, FR4); that start and center content do not render in the mobile bar (FR5); the drawer's content order and divider (FR6); FR7; and FR9.+Read from source, with no focused test yet: the mobile bar's part order (FR5); the drawer's `heading` header (FR6); other DOM props reaching the `<nav>` (FR1); the auto-toggle condition (FR5); rendering nothing in `drawer` mode with no content (FR6); the `top-nav` target and its `mode` state (FR1); the flex and three-region layout geometry at the default text size (FR3, FR4); that start and center content do not render in the mobile bar (FR5); the drawer's content order and divider (FR6); FR7; and FR9.## Decision logdiff --git a/packages/core/src/TopNav/TopNav.doc.mjs b/packages/core/src/TopNav/TopNav.doc.mjsindex f2d302fc46..2961c688f1 100644--- a/packages/core/src/TopNav/TopNav.doc.mjs+++ b/packages/core/src/TopNav/TopNav.doc.mjs@@ -73,7 +73,7 @@ export const docs = {{name: 'centerContent',type: 'ReactNode',- description: 'Center content slot (tabs, search bar, primary navigation): when provided, switches the layout to a three-column CSS grid for true horizontal centering.',+ description: 'Center content slot (tabs, search bar, primary navigation): when provided, switches the layout to three regions that keep it at the middle of the bar while they fit one row; the bar wraps when they do not.',slotElements: [{__element: 'Text',diff --git a/packages/core/src/TopNav/TopNav.tsx b/packages/core/src/TopNav/TopNav.tsxindex b1b8754833..a047a1cd6e 100644--- a/packages/core/src/TopNav/TopNav.tsx+++ b/packages/core/src/TopNav/TopNav.tsx@@ -48,21 +48,28 @@ const styles = stylex.create({padding: spacingVars['--spacing-2'],boxSizing: 'border-box',},- // Flex layout (default, used when no centerContent)+ // The bar wraps when its regions do not fit one row. The end region then+ // moves to a second line.baseFlex: {display: 'flex',+ flexWrap: 'wrap',},- // Grid layout (used when centerContent is present)- baseGrid: {- display: 'grid',- gridTemplateColumns: '1fr auto 1fr',+ // While the regions fit one row, the start and end regions share the free+ // width equally. This keeps the center at the bar's middle.+ baseThreeRegion: {+ display: 'flex',+ flexWrap: 'wrap',},+ // A region keeps its items on one line, so the bar wraps first. Only a+ // region wider than the bar wraps its own items. `fit-content` is the+ // region's full row, capped at the bar's width.leftSection: {display: 'flex',+ flexWrap: 'wrap',alignItems: 'center',gap: spacingVars['--spacing-4'],flex: '1 1 0%',- minWidth: 0,+ minWidth: stylex.firstThatWorks('fit-content', '-webkit-fit-content'),},heading: {display: 'flex',@@ -71,27 +78,43 @@ const styles = stylex.create({},startContent: {display: 'flex',+ flexWrap: 'wrap',alignItems: 'center',gap: spacingVars['--spacing-1'],},+ // The center claims its content's minimum width when the bar decides where+ // to wrap, then grows first, up to its content width. Only a center wider+ // than the whole bar, alone on its line, narrows below that minimum.centerContent: {display: 'flex',alignItems: 'center',justifyContent: 'center',gap: spacingVars['--spacing-1'],+ flexGrow: 1000,+ flexShrink: 1,+ flexBasis: 'min-content',+ minWidth: 0,+ maxWidth: 'max-content',},rightSection: {display: 'flex',+ flexWrap: 'wrap',alignItems: 'center',justifyContent: 'flex-end',gap: spacingVars['--spacing-1'],+ flex: '1 1 0%',+ minWidth: stylex.firstThatWorks('fit-content', '-webkit-fit-content'),},endContent: {display: 'flex',+ flexWrap: 'wrap',alignItems: 'center',+ justifyContent: 'flex-end',gap: spacingVars['--spacing-1'],flexShrink: 0,marginInlineStart: 'auto',+ minWidth: stylex.firstThatWorks('fit-content', '-webkit-fit-content'),+ maxWidth: '100%',},// Mobile bar mode — simplified top bar with heading + toggle + endContentmobileBar: {@@ -151,8 +174,8 @@ export interface TopNavProps extends BaseProps<HTMLElement> {/*** Center content slot - typically tabs, search bar, or primary navigation.* Positioned at the horizontal center of the nav bar.- * When provided, the layout switches to a three-column CSS grid to ensure- * true centering regardless of start/end content widths.+ * When provided, the layout switches to three regions that keep the center+ * at the bar's middle while they fit one row; the bar wraps when they do not.*/centerContent?: ReactNode;/**@@ -175,7 +198,7 @@ export interface TopNavProps extends BaseProps<HTMLElement> {* `endContent`. `children` are accepted as an alias for `startContent`* so navigation items do not silently disappear when using the common* React children pattern. When `centerContent` is provided, the layout switches- * to a three-column CSS grid to keep center content horizontally centered.+ * to three regions that keep center content horizontally centered.** @example* ```@@ -286,7 +309,7 @@ export function TopNav({themeProps('top-nav'),stylex.props(styles.base,- hasCenterContent ? styles.baseGrid : styles.baseFlex,+ hasCenterContent ? styles.baseThreeRegion : styles.baseFlex,xstyle,),className,diff --git a/packages/core/src/TopNav/__tests__/TopNavTextSize.interaction.browser.spec.ts b/packages/core/src/TopNav/__tests__/TopNavTextSize.interaction.browser.spec.tsnew file mode 100644index 0000000000..0e22ef710c--- /dev/null+++ b/packages/core/src/TopNav/__tests__/TopNavTextSize.interaction.browser.spec.ts@@ -0,0 +1,135 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file TopNavTextSize.interaction.browser.spec.ts+ * @input The built TopNav stories on a 1280 px desktop viewport, at+ * Chromium's default font size and at 200% and 250% of it+ * @output Real-browser evidence that no region covers another and the page+ * does not scroll sideways at a larger text size, and that the bar keeps+ * one row at the default text size+ * @position Browser proof of TopNav FR3 and FR4'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: 1280, height: 800},+ isMobile: false,+ hasTouch: false,+ deviceScaleFactor: 1,+});++/** 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)},+ });+}++/** Text boxes of the bar's links and buttons, and the page's width. */+async function readBar(page: Page) {+ return page.evaluate(() => {+ const nav = document.querySelector<HTMLElement>('nav[role="navigation"]');+ if (nav == null) {+ throw new Error('No TopNav');+ }+ const boxes = [...nav.querySelectorAll<HTMLElement>('a, button')]+ .filter(element => element.getBoundingClientRect().width > 0)+ .map(element => {+ const range = document.createRange();+ range.selectNodeContents(element);+ const box = range.getBoundingClientRect();+ return {+ element,+ name: (element.innerText || element.getAttribute('aria-label') || '')+ .trim()+ .slice(0, 24),+ left: box.left,+ right: box.right,+ top: box.top,+ bottom: box.bottom,+ };+ });+ const overlaps: string[] = [];+ for (let i = 0; i < boxes.length; i++) {+ for (let j = i + 1; j < boxes.length; j++) {+ const a = boxes[i];+ const b = boxes[j];+ if (a.element.contains(b.element) || b.element.contains(a.element)) {+ continue;+ }+ const x = Math.min(a.right, b.right) - Math.max(a.left, b.left);+ const y = Math.min(a.bottom, b.bottom) - Math.max(a.top, b.top);+ if (x > 2 && y > 2) {+ overlaps.push(`${a.name} / ${b.name}`);+ }+ }+ }+ return {+ overlaps,+ scrollWidth: document.documentElement.scrollWidth,+ viewportWidth: document.documentElement.clientWidth,+ // One row: every control's own box shares a vertical band with the+ // first one's.+ oneRow: boxes+ .map(({element}) => element.getBoundingClientRect())+ .every(+ (box, _, [first]) => box.top < first.bottom && box.bottom > first.top,+ ),+ };+ });+}++async function openStory(page: Page, story: string, px: number) {+ await setDefaultFontSize(page, px);+ await page.goto(+ `${storybook.origin}/iframe.html?id=core-topnav--${story}&viewMode=story`,+ );+ await page.locator('nav[role="navigation"]').waitFor();+}++test('at the default text size the full bar keeps one row', async ({page}) => {+ await openStory(page, 'full-example', 16);+ const {overlaps, oneRow} = await readBar(page);+ expect(overlaps).toEqual([]);+ expect(oneRow).toBe(true);+});++for (const story of ['full-example', 'centered-with-start-content']) {+ for (const [size, px] of [+ ['200%', 32],+ ['250%', 40],+ ] as const) {+ test(`at ${size} text size no region covers another: ${story}`, async ({+ page,+ }) => {+ await openStory(page, story, px);+ const {overlaps, scrollWidth, viewportWidth} = await readBar(page);+ expect(overlaps).toEqual([]);+ expect(scrollWidth).toBeLessThanOrEqual(viewportWidth);+ });+ }+}