An open source design system that's fully customizable and agent ready
TypeScript
fix(TopNav): let the heading shrink so a long heading truncates inside its column (#9551)
David Billiotaba928398848
diff --git a/.changeset/topnav-heading-shrink.md b/.changeset/topnav-heading-shrink.mdnew file mode 100644index 0000000000..f796c71e8f--- /dev/null+++ b/.changeset/topnav-heading-shrink.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] TopNav's heading can now shrink, so a heading wider than the whole bar ends in an ellipsis instead of running off the bar and scrolling the page sideways (#9530). `TopNavHeading` keeps its logo whole, and independently linked lines wrap and keep their longest word; a plain line beside them still keeps its full width.++@WeAreResiliencediff --git a/apps/storybook/stories/TopNav.stories.tsx b/apps/storybook/stories/TopNav.stories.tsxindex 9b9f5034b9..3bfe435fca 100644--- a/apps/storybook/stories/TopNav.stories.tsx+++ b/apps/storybook/stories/TopNav.stories.tsx@@ -133,6 +133,41 @@ export const WithHeadingMenu: Story = {},};+/**+ * A heading whose superheading and heading are separate links, beside a full+ * set of nav items. In a narrow window the start region is crowded.+ */+export const IndependentHeadingLinks: Story = {+ args: {+ label: 'Main navigation',+ heading: (+ <TopNavHeading+ superheading="Northwind workspace"+ superheadingHref="#"+ heading="Operations overview"+ headingHref="#"+ logo={<NavIcon icon={<CubeIcon style={{width: 16, height: 16}} />} />}+ />+ ),+ startContent: (+ <>+ <TopNavItem label="Dashboard" href="#" isSelected />+ <TopNavItem label="Reports" href="#" />+ <TopNavItem label="Analytics" href="#" />+ <TopNavItem label="Settings" href="#" />+ </>+ ),+ endContent: (+ <Button+ label="Profile"+ variant="ghost"+ icon={<UserCircleIcon style={{width: 16, height: 16}} />}+ isIconOnly+ />+ ),+ },+};+export const TitleOnly: Story = {args: {label: 'Main navigation',diff --git a/docs/specs/components/TopNav/TopNavHeading.spec.md b/docs/specs/components/TopNav/TopNavHeading.spec.mdindex 535cb6fc09..6258af6ce9 100644--- a/docs/specs/components/TopNav/TopNavHeading.spec.md+++ b/docs/specs/components/TopNav/TopNavHeading.spec.md@@ -128,7 +128,7 @@ Consumer migration instructions belong in consumer docs and release notes.| ID | Invariant | Basis || ---- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------ |-| FR1 | The root carries `top-nav-heading` and shows, in order: the logo, a text column (superheading, a heading row, subheading; plain-text lines and the menu-configuration heading link stay on one line with ellipsis, while lines rendered through the Link component wrap), and `headerEndContent` at the inline end. With `menu`, the heading row holds the heading then the chevron button; without `menu` there is no chevron. | Current source and tests |+| FR1 | The root carries `top-nav-heading` and shows, in order: the logo, a text column (superheading, a heading row, subheading; plain-text lines and the menu-configuration heading link stay on one line with ellipsis, while lines rendered through the Link component wrap), and `headerEndContent` at the inline end. With `menu`, the heading row holds the heading then the chevron button; without `menu` there is no chevron. When the start region is crowded, a heading text column holding independent links keeps its longest word and wraps, and the row wraps before any link is clipped; a heading with no links still truncates first. The logo never shrinks. | Current source and tests || FR2 | Configuration: no `heading` and no `menu` → logo only, a link named by `logoLabel` when `headingHref` is set, else a `div`; `headingHref` alone without `menu` → the whole block is one link; other `*Href` props without `menu` → each line with an href is its own link and a linked logo is named by `logoLabel`, else `heading`; `menu` without any href → the whole block opens the menu; `menu` with hrefs → the links stay independent, and the chevron button and the rest of the block open the menu; otherwise a plain `div`. | Current source and tests || FR3 | The logo link, the whole-heading link, the logo-only link, and the menu-configuration heading link use the `as` component, else the `LinkProvider` link, else `<a>`. Supporting lines, and the heading line in the independent-links configuration, use the Link component, which does not receive `as`. | Current source and tests || FR4 | In both menu configurations, the chevron is a button named by the translated `@astryx.topNav.heading.openMenu` that toggles the menu; it is at least 28 by 28 px. | Current source and tests |diff --git a/packages/core/src/TopNav/TopNav.test.tsx b/packages/core/src/TopNav/TopNav.test.tsxindex b95a6aabf9..1898b83cdf 100644--- a/packages/core/src/TopNav/TopNav.test.tsx+++ b/packages/core/src/TopNav/TopNav.test.tsx@@ -212,6 +212,18 @@ describe('TopNav', () => {// positioning context for the mega menu panel.expect(nav).not.toHaveStyle({position: 'relative'});});++ it('lets the heading column shrink so a long heading can truncate', () => {+ render(+ <TopNav+ label="Main navigation"+ heading={<span>A very long product name</span>}+ endContent={<span>End</span>}+ />,+ );+ const column = screen.getByText('A very long product name').parentElement!;+ expect(getComputedStyle(column).flexShrink).toBe('1');+ });});describe('TopNavHeading', () => {@@ -236,6 +248,93 @@ describe('TopNavHeading', () => {expect(screen.getByTestId('logo')).toBeInTheDocument();});+ // jsdom does not place grid items, so this locks the track that puts+ // headerEndContent at the inline end when the root is wider than its parts.+ it('gives the text track the free space so header end content sits at the inline end', () => {+ const {rerender} = render(+ <TopNavHeading+ logo={<span>Logo</span>}+ heading="Product"+ headerEndContent={<span>End</span>}+ />,+ );+ const withLogo = screen+ .getByText('Product')+ .closest('.astryx-top-nav-heading');+ expect(withLogo).not.toBeNull();+ expect(getComputedStyle(withLogo!).gridTemplateColumns).toBe(+ 'auto minmax(0,1fr)',+ );++ rerender(+ <TopNavHeading heading="Product" headerEndContent={<span>End</span>} />,+ );+ const textOnly = screen+ .getByText('Product')+ .closest('.astryx-top-nav-heading');+ expect(getComputedStyle(textOnly!).gridTemplateColumns).toBe(+ 'minmax(0,1fr)',+ );+ });++ it('clips each linked line inside its column and leaves the column overflow visible', () => {+ render(+ <TopNavHeading+ superheading="Suite"+ superheadingHref="/suite"+ heading="Product"+ headingHref="/product"+ subheading="Account"+ subheadingHref="/account"+ />,+ );+ for (const name of ['Suite', 'Product', 'Account']) {+ const link = screen.getByRole('link', {name});+ const style = getComputedStyle(link);+ expect(style.overflow).toBe('hidden');+ expect(style.minWidth).toBe('0');+ expect(style.maxWidth).toBe('100%');+ }+ // The column itself is not a clip, so the link's own focus ring can paint.+ const column = screen.getByRole('link', {name: 'Product'}).parentElement;+ expect(getComputedStyle(column!).overflow).toBe('');+ });++ it('counts the chevron row in the text track when the heading has a menu', () => {+ const {rerender} = render(+ <TopNavHeading+ logo={<span>Logo</span>}+ heading="Product"+ menu={<div>Menu</div>}+ />,+ );+ const withLogo = document.querySelector('.astryx-top-nav-heading');+ expect(getComputedStyle(withLogo!).gridTemplateColumns).toBe(+ 'auto minmax(calc(var(--spacing-7) + var(--spacing-1)),1fr)',+ );++ rerender(<TopNavHeading heading="Product" menu={<div>Menu</div>} />);+ const textOnly = document.querySelector('.astryx-top-nav-heading');+ expect(getComputedStyle(textOnly!).gridTemplateColumns).toBe(+ 'minmax(calc(var(--spacing-7) + var(--spacing-1)),1fr)',+ );+ });++ it('gives a logo-only heading a single track', () => {+ render(+ <TopNavHeading+ logo={<span>Logo</span>}+ headingHref="/home"+ logoLabel="Home"+ />,+ );+ const root = screen.getByRole('link', {name: 'Home'});+ expect(root).toHaveClass('astryx-top-nav-heading');+ expect(getComputedStyle(root).display).toBe('grid');+ expect(getComputedStyle(root).gridTemplateColumns).toBe('');+ expect(root.childElementCount).toBe(1);+ });+describe('logo link accessible name', () => {const logo = <img src="/logo.png" alt="" />;diff --git a/packages/core/src/TopNav/TopNav.tsx b/packages/core/src/TopNav/TopNav.tsxindex a047a1cd6e..d401d81e28 100644--- a/packages/core/src/TopNav/TopNav.tsx+++ b/packages/core/src/TopNav/TopNav.tsx@@ -71,10 +71,12 @@ const styles = stylex.create({flex: '1 1 0%',minWidth: stylex.firstThatWorks('fit-content', '-webkit-fit-content'),},+ // The heading shrinks only to its own narrowest width. TopNavHeading keeps+ // its logo there.heading: {display: 'flex',alignItems: 'center',- flexShrink: 0,+ flexShrink: 1,},startContent: {display: 'flex',diff --git a/packages/core/src/TopNav/TopNavHeading.tsx b/packages/core/src/TopNav/TopNavHeading.tsxindex bf530d6a7e..609ec6d1ce 100644--- a/packages/core/src/TopNav/TopNavHeading.tsx+++ b/packages/core/src/TopNav/TopNavHeading.tsx@@ -58,8 +58,12 @@ registerEnglishFallback(english);// =============================================================================const styles = stylex.create({+ // The text track can shrink to zero. The logo and the chevron row keep+ // their width.root: {- display: 'flex',+ display: 'grid',+ gridAutoFlow: 'column',+ justifyContent: 'start',alignItems: 'center',gap: spacingVars['--spacing-2'],minHeight: spacingVars['--spacing-8'],@@ -75,6 +79,29 @@ const styles = stylex.create({color: colorVars['--color-text-primary'],cursor: 'default',},+ // The text track takes the free space, so end content sits at the inline end.+ columnsWithLogo: {+ gridTemplateColumns: 'auto minmax(0, 1fr)',+ },+ columnsText: {+ gridTemplateColumns: 'minmax(0, 1fr)',+ },+ // Linked lines wrap, so the text track keeps its longest word: a link is+ // never clipped to nothing, and no hidden words grow the bar.+ columnsWithLogoAndLinks: {+ gridTemplateColumns: 'auto minmax(min-content, 1fr)',+ },+ columnsWithLinks: {+ gridTemplateColumns: 'minmax(min-content, 1fr)',+ },+ // The chevron box plus the gap before it. The track stops there, so a+ // crowded bar cannot cover the chevron.+ columnsWithLogoAndMenu: {+ gridTemplateColumns: `auto minmax(calc(${spacingVars['--spacing-7']} + ${spacingVars['--spacing-1']}), 1fr)`,+ },+ columnsWithMenu: {+ gridTemplateColumns: `minmax(calc(${spacingVars['--spacing-7']} + ${spacingVars['--spacing-1']}), 1fr)`,+ },interactive: {cursor: {default: 'pointer',@@ -159,6 +186,13 @@ const styles = stylex.create({textOverflow: 'ellipsis',whiteSpace: 'nowrap',},+ // Clip the link itself. The column stays overflow visible, so the link's+ // own focus ring is not cut off.+ linkedLine: {+ minWidth: 0,+ maxWidth: '100%',+ overflow: 'hidden',+ },chevron: {flexShrink: 0,display: 'flex',@@ -406,6 +440,18 @@ export function TopNavHeading({const showChevron = !!menu;const hasAnyHref = !!(headingHref || superheadingHref || subheadingHref);+ // Logo-only has no text column. An empty second track would add the column+ // gap and widen the heading.+ const rootColumns =+ !heading && !menu+ ? null+ : isRenderable(logo)+ ? menu+ ? styles.columnsWithLogoAndMenu+ : styles.columnsWithLogo+ : menu+ ? styles.columnsWithMenu+ : styles.columnsText;// Determine interaction modeconst isWholeHeadingTrigger = !!menu && !hasAnyHref;@@ -421,7 +467,8 @@ export function TopNavHeading({href={superheadingHref}onClick={(e: React.MouseEvent) => e.stopPropagation()}color="secondary"- size="xsm">+ size="xsm"+ xstyle={styles.linkedLine}>{superheading}</Link>) : (@@ -446,7 +493,8 @@ export function TopNavHeading({href={subheadingHref}onClick={(e: React.MouseEvent) => e.stopPropagation()}color="secondary"- size="xsm">+ size="xsm"+ xstyle={styles.linkedLine}>{subheading}</Link>) : (@@ -501,6 +549,7 @@ export function TopNavHeading({themeProps('top-nav-heading'),stylex.props(styles.root,+ rootColumns,!!headingHref && styles.menuTrigger,xstyle,),@@ -524,7 +573,7 @@ export function TopNavHeading({data-testid={testId}{...mergeProps(themeProps('top-nav-heading'),- stylex.props(styles.root, styles.menuTrigger, xstyle),+ stylex.props(styles.root, rootColumns, styles.menuTrigger, xstyle),className,style,)}@@ -549,7 +598,7 @@ export function TopNavHeading({{...triggerProps}{...mergeProps(themeProps('top-nav-heading'),- stylex.props(styles.root, styles.menuTrigger, xstyle),+ stylex.props(styles.root, rootColumns, styles.menuTrigger, xstyle),className,style,)}>@@ -623,7 +672,7 @@ export function TopNavHeading({{...triggerProps}{...mergeProps(themeProps('top-nav-heading'),- stylex.props(styles.root, xstyle),+ stylex.props(styles.root, rootColumns, xstyle),className,style,)}>@@ -701,13 +750,16 @@ export function TopNavHeading({// Static heading with independent links (no menu)if (hasAnyHref && !isWholeHeadingLink) {+ const linkColumns = isRenderable(logo)+ ? styles.columnsWithLogoAndLinks+ : styles.columnsWithLinks;return (<divref={ref as React.Ref<HTMLDivElement>}data-testid={testId}{...mergeProps(themeProps('top-nav-heading'),- stylex.props(styles.root, xstyle),+ stylex.props(styles.root, linkColumns, xstyle),className,style,)}@@ -726,14 +778,22 @@ export function TopNavHeading({<span {...stylex.props(styles.textContainer)}>{superheading &&(superheadingHref ? (- <Link href={superheadingHref} color="secondary" size="xsm">+ <Link+ href={superheadingHref}+ color="secondary"+ size="xsm"+ xstyle={styles.linkedLine}>{superheading}</Link>) : (<span {...stylex.props(styles.superheading)}>{superheading}</span>))}{headingHref ? (- <Link href={headingHref} color="primary" weight="semibold">+ <Link+ href={headingHref}+ color="primary"+ weight="semibold"+ xstyle={styles.linkedLine}>{heading}</Link>) : (@@ -741,7 +801,11 @@ export function TopNavHeading({)}{subheading &&(subheadingHref ? (- <Link href={subheadingHref} color="secondary" size="xsm">+ <Link+ href={subheadingHref}+ color="secondary"+ size="xsm"+ xstyle={styles.linkedLine}>{subheading}</Link>) : (@@ -761,7 +825,7 @@ export function TopNavHeading({data-testid={testId}{...mergeProps(themeProps('top-nav-heading'),- stylex.props(styles.root, xstyle),+ stylex.props(styles.root, rootColumns, xstyle),className,style,)}diff --git a/packages/core/src/TopNav/__tests__/TopNavCrowdedHeading.a11y.chromium.spec.ts b/packages/core/src/TopNav/__tests__/TopNavCrowdedHeading.a11y.chromium.spec.tsnew file mode 100644index 0000000000..8f76915957--- /dev/null+++ b/packages/core/src/TopNav/__tests__/TopNavCrowdedHeading.a11y.chromium.spec.ts@@ -0,0 +1,165 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+// @pr-a11y scope core/TopNav++/**+ * @file TopNavCrowdedHeading.a11y.chromium.spec.ts+ * @input The `Core/TopNav` FullExample, TitleOnly and IndependentHeadingLinks+ * stories in a built Storybook, in real Chromium at narrow widths.+ * @output Real-engine proof that a crowded bar keeps the heading's logo whole+ * and its box clear of every other control, that a heading wider than the+ * whole bar truncates instead of scrolling the page sideways, and that+ * independently linked lines keep their words visible instead of clipping+ * to nothing (component:TopNavHeading FR1).+ * @position Run with `pnpm test:a11y-contract`.+ */++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();+});++async function openStory(page: Page, id: string): Promise<void> {+ await page.goto(`${storybook.origin}/iframe.html?id=${id}&viewMode=story`);+ await expect(page.locator('.astryx-top-nav-heading').first()).toBeVisible();+}++/**+ * The heading's box, its logo, the controls outside it that its box overlaps,+ * and whether the page scrolls sideways.+ */+async function measure(page: Page) {+ return page.evaluate(() => {+ const heading = document.querySelector<HTMLElement>(+ '.astryx-top-nav-heading',+ );+ const bar = heading?.closest('nav') ?? heading?.closest('header');+ if (heading == null || bar == null) {+ throw new Error('the story has no heading inside a bar');+ }+ const box = heading.getBoundingClientRect();+ const overlaps = [...bar.querySelectorAll<HTMLElement>('a, button')]+ .filter(control => !heading.contains(control))+ .filter(control => {+ const other = control.getBoundingClientRect();+ const width =+ Math.min(box.right, other.right) - Math.max(box.left, other.left);+ const height =+ Math.min(box.bottom, other.bottom) - Math.max(box.top, other.top);+ return width > 1 && height > 1;+ })+ .map(control => control.textContent?.trim() ?? '');+ const logo = heading.querySelector('svg, img');+ return {+ logoWidth: logo?.getBoundingClientRect().width ?? null,+ headingRight: box.right,+ overlaps,+ pageScrolls: document.documentElement.scrollWidth > innerWidth,+ };+ });+}++for (const width of [700, 600, 390]) {+ test(`at ${width} px a crowded bar keeps the heading's logo whole and its box clear of every other control`, async ({+ page,+ }) => {+ await page.setViewportSize({width, height: 320});+ await openStory(page, 'core-topnav--full-example');+ const box = await measure(page);+ expect(box.logoWidth).toBeGreaterThan(0);+ expect(box.overlaps).toEqual([]);+ expect(box.pageScrolls).toBe(false);+ });+}++test('a heading wider than the whole bar truncates instead of scrolling the page sideways', async ({+ page,+}) => {+ await page.setViewportSize({width: 320, height: 320});+ await openStory(page, 'core-topnav--title-only');+ const truncated = await page.evaluate(() => {+ const heading = document.querySelector<HTMLElement>(+ '.astryx-top-nav-heading',+ );+ const text = [...(heading?.querySelectorAll<HTMLElement>('*') ?? [])].find(+ el =>+ el.childNodes.length === 1 &&+ el.childNodes[0].nodeType === Node.TEXT_NODE &&+ el.textContent === 'Simple App',+ );+ if (text == null) {+ throw new Error('the story has no heading text');+ }+ text.textContent =+ 'Northwind Traders International Holdings Operations Workspace';+ return text.scrollWidth > text.clientWidth;+ });+ const box = await measure(page);+ expect(truncated).toBe(true);+ expect(box.headingRight).toBeLessThanOrEqual(320);+ expect(box.overlaps).toEqual([]);+ expect(box.pageScrolls).toBe(false);+});++for (const width of [1280, 560, 480]) {+ test(`at ${width} px independently linked lines keep their words, and Tab lands on a visible link`, async ({+ page,+ }) => {+ await page.setViewportSize({width, height: 320});+ await openStory(page, 'core-topnav--independent-heading-links');+ const links = await page.evaluate(() =>+ [+ ...document.querySelectorAll<HTMLAnchorElement>(+ '.astryx-top-nav-heading a',+ ),+ ]+ .filter(link => (link.textContent ?? '').trim() !== '')+ .map(link => ({+ width: link.getBoundingClientRect().width,+ clipped:+ link.scrollWidth > link.clientWidth + 1 ||+ link.scrollHeight > link.clientHeight + 1,+ })),+ );+ expect(links).toHaveLength(2);+ for (const link of links) {+ expect(link.width).toBeGreaterThan(0);+ expect(link.clipped).toBe(false);+ }+ const box = await measure(page);+ expect(box.overlaps).toEqual([]);+ expect(box.pageScrolls).toBe(false);++ // Tab from the top of the page until the superheading link holds focus.+ let focused = {text: '', width: 0, isFocusVisible: false};+ for (+ let step = 0;+ step < 6 && focused.text !== 'Northwind workspace';+ step+++ ) {+ await page.keyboard.press('Tab');+ focused = await page.evaluate(() => {+ const link = document.activeElement;+ return {+ text: link?.textContent?.trim() ?? '',+ width: link?.getBoundingClientRect().width ?? 0,+ isFocusVisible: link?.matches(':focus-visible') ?? false,+ };+ });+ }+ expect(focused.text).toBe('Northwind workspace');+ expect(focused.width).toBeGreaterThan(0);+ expect(focused.isFocusVisible).toBe(true);+ });+}