Skip to content

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

TypeScript

fix(AppShell): a second shell on a page gets its own main id (#10199)

Cindy Zhang2151c883d59b
diff --git a/.changeset/appshell-unique-main-id.md b/.changeset/appshell-unique-main-id.md
new file mode 100644
index 0000000000..3d622a10e3
--- /dev/null
+++ b/.changeset/appshell-unique-main-id.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Two `AppShell`s on one page no longer share the main region's id. The first mounted shell keeps `id="astryx-app-shell-main"`, so single-shell pages, skip links and selectors that name it keep working. Each other shell's main region gets its own generated id, which its skip link targets.
+
+@cixzhang
diff --git a/docs/specs/components/AppShell/AppShell.spec.md b/docs/specs/components/AppShell/AppShell.spec.md
index 38cf691d86..d8389f9c47 100644
--- a/docs/specs/components/AppShell/AppShell.spec.md
+++ b/docs/specs/components/AppShell/AppShell.spec.md
@@ -174,8 +174,8 @@ the only component record in the AppShell root.
| FR1 | The root element carries `app-shell`, the forwarded `ref`, `data-testid`, and other DOM props, and contains, in order: the skip link, the Layout frame (header region, inline side region, content region), then any mobile drawer. | Current source and tests |
| FR2 | A slot is present when its value is renderable: not `null`, `undefined`, a boolean, or an empty string. A component that renders nothing still counts as present. | Current source and public types |
| FR3 | The header region renders only when `topNav` or `banner` is present; it carries `app-shell-header` and `role="banner"`, places `banner` above `topNav`, and is never inside another landmark. The sidenav-only mobile top bar (FR9) also carries `app-shell-header` and takes `role="banner"` only when no header region renders. AppShell renders at most one banner landmark. The header region pads its items by `env(safe-area-inset-top, 0px)` at the block start and the physical `env(safe-area-inset-left/right, 0px)` on its inline sides (swapped in right-to-left), while its background still reaches under the status bar and to the screen's sides; the sidenav-only mobile top bar takes the same insets when no header region renders, and only the side insets below one. In `auto`, the sidenav-only mobile top bar below a header region sticks at `env(safe-area-inset-top, 0px)`, not at the block start (FR6). | Current source and tests |
-| FR4 | `children` render in one region with `role="main"` and `id="astryx-app-shell-main"`, programmatically focusable so the skip link can move focus to it; programmatic focus on it draws no focus ring. Its padding is `contentPadding`, default `0`, and its block-end padding adds `env(safe-area-inset-bottom, 0px)`, in the page or in main's own scroller. The region stays border-box, and the inset it publishes to its descendants stays `contentPadding` alone, so a bleed child subtracts only `contentPadding` and the safe area survives below it. Whether it is a sequential tab stop is keyboard access to a scroll region (`spec:AST-025` FR12). Focus that Tab moves onto it while it is a stop draws the standard focus ring, inset, until focus leaves it; in `elevated` with both navs the region takes the surface's rounded top-start corner while that ring shows. | `architecture:container-padding`; current source and tests |
-| FR5 | The skip link is the first focusable element in the shell. It links to `#astryx-app-shell-main`, shows the translated `@astryx.appShell.skipToContent` text, is visually hidden until focused, and on activation moves focus to the main region. | WCAG 2.4.1; current source and tests |
+| FR4 | `children` render in one region with `role="main"` and an id: `astryx-app-shell-main` for the first mounted shell on the page, and a generated unique id for each other shell, so a page has no duplicate ids; programmatically focusable so the skip link can move focus to it; programmatic focus on it draws no focus ring. Its padding is `contentPadding`, default `0`, and its block-end padding adds `env(safe-area-inset-bottom, 0px)`, in the page or in main's own scroller. The region stays border-box, and the inset it publishes to its descendants stays `contentPadding` alone, so a bleed child subtracts only `contentPadding` and the safe area survives below it. Whether it is a sequential tab stop is keyboard access to a scroll region (`spec:AST-025` FR12). Focus that Tab moves onto it while it is a stop draws the standard focus ring, inset, until focus leaves it; in `elevated` with both navs the region takes the surface's rounded top-start corner while that ring shows. | `architecture:container-padding`; current source and tests |
+| FR5 | The skip link is the first focusable element in the shell. It links to its own main region's id (FR4), shows the translated `@astryx.appShell.skipToContent` text, is visually hidden until focused, and on activation moves focus to the main region. | WCAG 2.4.1; current source and tests |
| FR6 | `fill` sizes the root to `100dvh` and the inline side region and main region scroll on their own. `auto` gives the root a `100dvh` minimum, makes the header sticky at the block start, keeps the inline side region sticky below the measured height of a header present when the shell mounts in `auto`, with its own scrolling, and lets the page scroll. Header height is measured only in `auto`. | Current source and tests |
| FR7 | Variant backgrounds: `wash` paints body background on the frame, nav areas, and content; `surface` paints surface on all three; `section` paints surface on the frame and divides the nav areas from content, and in `auto` the header paints surface itself; `elevated` paints body background on the frame and nav areas and surface on content (FR16 for the corner). | Current source and tests |
| FR8 | The mobile layout follows `mobileNav.breakpoint` under `spec:AST-012` FR8 and `architecture:theme-application` INV10; the breakpoint defaults to `md`, and `defaultIsMobile` is ignored when it is `none`. | `spec:AST-012` FR8; tests |
diff --git a/packages/core/src/AppShell/AppShell.test.tsx b/packages/core/src/AppShell/AppShell.test.tsx
index 635d578804..92a9460765 100644
--- a/packages/core/src/AppShell/AppShell.test.tsx
+++ b/packages/core/src/AppShell/AppShell.test.tsx
@@ -238,6 +238,64 @@ describe('AppShell', () => {
expect(document.activeElement).toBe(main);
});
+ it('gives a second shell its own main id; the first keeps the fixed id', () => {
+ const view = render(
+ <div>
+ <AppShell key="first">
+ <div>First</div>
+ </AppShell>
+ <AppShell key="second">
+ <div>Second</div>
+ </AppShell>
+ </div>,
+ );
+ const [firstMain, secondMain] = screen.getAllByRole('main');
+ const [firstSkip, secondSkip] = screen.getAllByTestId('skip-to-content');
+ expect(firstMain).toHaveAttribute('id', 'astryx-app-shell-main');
+ expect(secondMain.id).not.toBe('astryx-app-shell-main');
+ expect(secondMain.id).not.toBe('');
+ expect(document.querySelectorAll(`[id="${secondMain.id}"]`)).toHaveLength(
+ 1,
+ );
+ expect(firstSkip).toHaveAttribute('href', '#astryx-app-shell-main');
+ expect(secondSkip).toHaveAttribute('href', `#${secondMain.id}`);
+
+ fireEvent.click(secondSkip);
+ expect(document.activeElement).toBe(secondMain);
+
+ // When the first shell leaves, the remaining shell takes the fixed id.
+ view.rerender(
+ <div>
+ <AppShell key="second">
+ <div>Second</div>
+ </AppShell>
+ </div>,
+ );
+ expect(screen.getByRole('main')).toHaveAttribute(
+ 'id',
+ 'astryx-app-shell-main',
+ );
+ });
+
+ it('keeps the fixed id on the page shell when another shell is nested in its content', () => {
+ render(
+ <AppShell data-testid="outer">
+ <AppShell data-testid="inner">
+ <div>Nested</div>
+ </AppShell>
+ </AppShell>,
+ );
+ const outerMain = screen
+ .getByTestId('outer')
+ .querySelector<HTMLElement>(':scope [role="main"]');
+ const innerMain = screen
+ .getByTestId('inner')
+ .querySelector<HTMLElement>('[role="main"]');
+ expect(outerMain).toHaveAttribute('id', 'astryx-app-shell-main');
+ expect(innerMain?.id).not.toBe('astryx-app-shell-main');
+ expect(innerMain?.id).not.toBe('');
+ });
+
it('skip link text comes from the i18n catalog', () => {
render(
<InternationalizationProvider
diff --git a/packages/core/src/AppShell/AppShell.tsx b/packages/core/src/AppShell/AppShell.tsx
index 9e76277431..2fbff087f5 100644
--- a/packages/core/src/AppShell/AppShell.tsx
+++ b/packages/core/src/AppShell/AppShell.tsx
@@ -69,6 +69,7 @@ import {
import {TopNavRenderContext} from '../TopNav/TopNavRenderContext';
import {TopNavMobileContentContext} from '../TopNav/TopNavMobileContentContext';
import {AppShellMobileContext} from './AppShellMobileContext';
+import {AppShellNestingContext, useAppShellMainId} from './useAppShellMainId';
import type {AppShellMobileContextValue} from './AppShellMobileContext';
import type {SpacingStep} from '../utils/types';
import type {BaseProps} from '../BaseProps';
@@ -112,8 +113,6 @@ const ActivityWrapper = HasActivity
// Constants
// =============================================================================
-const MAIN_CONTENT_ID = 'astryx-app-shell-main';
-
/**
* Extra time, on top of MobileNav's own worst-case close delay, that
* AppShell waits before flipping its `Activity` boundary to `'hidden'`.
@@ -680,12 +679,13 @@ export function AppShell({
[mobileNavIsControlled, mobileNavOnOpenChange],
);
+ const mainContentId = useAppShellMainId();
// Move focus to the main content container when the skip link is activated.
// Hash navigation alone doesn't reliably move focus in every browser, so
// focus the target explicitly (it's focusable via tabIndex={-1}).
const handleSkipLinkClick = useCallback(() => {
- document.getElementById(MAIN_CONTENT_ID)?.focus();
- }, []);
+ document.getElementById(mainContentId)?.focus();
+ }, [mainContentId]);
// Main draws its focus ring only for focus a Tab press moved onto it, and
// keeps it for as long as that focus stays, even once the content fits.
@@ -1215,7 +1215,7 @@ export function AppShell({
ref={mainRefs}
padding={contentPadding ?? 0}
role="main"
- id={MAIN_CONTENT_ID}
+ id={mainContentId}
// Focusable skip-link target (WCAG 2.4.1) — without tabIndex, several
// browsers won't move focus to the div when the skip link is activated.
// A keyboard stop only while it scrolls overflowing content.
@@ -1232,7 +1232,7 @@ export function AppShell({
: styles.mainFocusTarget,
styles.mainSafeAreaEnd,
]}>
- {children}
+ <AppShellNestingContext value={true}>{children}</AppShellNestingContext>
</LayoutContent>
);
@@ -1334,7 +1334,7 @@ export function AppShell({
<LayoutDividerContext value={null}>
{/* Skip-to-content link */}
<a
- href={`#${MAIN_CONTENT_ID}`}
+ href={`#${mainContentId}`}
onClick={handleSkipLinkClick}
{...focusOutlineProps.focusVisible(styles.skipLink)}
data-testid="skip-to-content">
diff --git a/packages/core/src/AppShell/useAppShellMainId.ts b/packages/core/src/AppShell/useAppShellMainId.ts
new file mode 100644
index 0000000000..2f48727fe3
--- /dev/null
+++ b/packages/core/src/AppShell/useAppShellMainId.ts
@@ -0,0 +1,77 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file useAppShellMainId.ts
+ * @input The mounted AppShell instances on the page
+ * @output The id each AppShell main region uses: the fixed
+ * `astryx-app-shell-main` for the first mounted outermost shell, a
+ * generated id for every other shell; AppShellNestingContext
+ * @position Private to AppShell; keeps main-region ids unique on a page
+ */
+
+import {createContext, use, useId, useState, useSyncExternalStore} from 'react';
+import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';
+
+/** The id of the first mounted shell's main region. Consumers link to it. */
+export const MAIN_CONTENT_ID = 'astryx-app-shell-main';
+
+/**
+ * True inside an AppShell. A shell nested in another shell's content never
+ * takes the fixed id: the page's own shell keeps it.
+ */
+export const AppShellNestingContext = createContext(false);
+AppShellNestingContext.displayName = 'AppShellNestingContext';
+
+const claims: object[] = [];
+const listeners = new Set<() => void>();
+
+function subscribe(listener: () => void): () => void {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+}
+
+function notify(): void {
+ for (const listener of listeners) {
+ listener();
+ }
+}
+
+/**
+ * The main-region id for one AppShell. The first mounted outermost shell
+ * keeps the fixed id, so skip links and selectors that name it keep working.
+ * A nested shell, or one that mounts while another holds the fixed id, takes
+ * a generated id, so the page has no duplicate ids. On the server and in its
+ * first commit, an outermost shell uses the fixed id. Any other outermost
+ * shell then changes to its own id.
+ */
+export function useAppShellMainId(): string {
+ const generatedId = useId();
+ const isNested = use(AppShellNestingContext);
+ const [claim] = useState(() => ({}));
+ const isFirst = useSyncExternalStore(
+ subscribe,
+ () => claims.length === 0 || claims[0] === claim,
+ () => true,
+ );
+
+ // Syncs this shell's claim in the page-wide claim list with its mount.
+ useIsomorphicLayoutEffect(() => {
+ if (isNested) {
+ return;
+ }
+ claims.push(claim);
+ notify();
+ return () => {
+ claims.splice(claims.indexOf(claim), 1);
+ notify();
+ };
+ }, [claim, isNested]);
+
+ return isFirst && !isNested
+ ? MAIN_CONTENT_ID
+ : `astryx-app-shell-main-${generatedId}`;
+}