Skip to content

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

TypeScript

feat(AppShell): keep the header's items and the content's end inside the device's safe area (#8150)

Christopher Chedeau36f8ea10e636
diff --git a/.changeset/appshell-safe-area.md b/.changeset/appshell-safe-area.md
new file mode 100644
index 0000000000..e09ea4e9e3
--- /dev/null
+++ b/.changeset/appshell-safe-area.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] AppShell keeps its header items and the end of its content inside the device's safe area on a phone page that opts into the full screen (`viewport-fit=cover`). A header region or the phone top bar reaches under the status bar and out to the screen's sides while its items stay clear of the status bar, the Dynamic Island and a landscape notch. In `height="auto"`, a phone top bar below a banner sticks under the top inset instead of at the top edge, so its items stay clear when the page scrolls. The main content ends clear of the home indicator (its block-end padding is `contentPadding` plus the bottom inset, so a child that fills it ends above the indicator), in the page or in the main region's own scroller. A shell with no header region or phone top bar takes no top inset, so its content keeps its own top padding there. In landscape only the header is inset, not an inline SideNav or the content's sides. Without `viewport-fit=cover` the insets are zero and nothing moves. The AppShell docs say how a page and an installed web app opt in.
+
+@vjeux
diff --git a/apps/storybook/stories/AppShell.stories.tsx b/apps/storybook/stories/AppShell.stories.tsx
index aa959c5b41..56f40cdf94 100644
--- a/apps/storybook/stories/AppShell.stories.tsx
+++ b/apps/storybook/stories/AppShell.stories.tsx
@@ -845,6 +845,30 @@ export const WithBanner: Story = {
),
};
+/**
+ * Auto height with a banner and a side nav but no top nav. Below the mobile
+ * breakpoint, the side nav shows as the phone top bar under the banner. Both
+ * stick to the top as the page scrolls.
+ */
+export const AutoHeightSideNavBanner: Story = {
+ render: () => (
+ <AppShell
+ contentPadding={6}
+ sideNav={<SideNavWithHeader />}
+ height="auto"
+ banner={
+ <Banner
+ status="info"
+ container="section"
+ title="System maintenance scheduled"
+ description="The system will undergo maintenance tonight at 10pm UTC."
+ />
+ }>
+ <MockContent paragraphs={20} />
+ </AppShell>
+ ),
+};
+
/**
* A layout root (FR18): a With Banner shell at the page root (`host: root`)
* or placed in a padded Card that clips overflow, as a docs example card
diff --git a/docs/specs/components/AppShell/AppShell.spec.md b/docs/specs/components/AppShell/AppShell.spec.md
index c0e0c23a21..e4de333ec2 100644
--- a/docs/specs/components/AppShell/AppShell.spec.md
+++ b/docs/specs/components/AppShell/AppShell.spec.md
@@ -13,6 +13,7 @@ review_triggers: [public-api, behavior, layout, theming, accessibility]
verified_by:
[
packages/core/src/AppShell/AppShell.test.tsx,
+ packages/core/src/AppShell/AppShellSafeArea.test.tsx,
packages/core/src/MobileNav/MobileNavCloseEdgeCases.test.tsx,
apps/storybook/stories/AppShell.stories.tsx,
scripts/check-knowledge.mjs,
@@ -30,15 +31,15 @@ system_specs: [spec:AST-012, spec:AST-027]
## Contract at a glance
-| Area | Contract |
-| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
-| Public contract | `AppShell` with `topNav`, `sideNav`, `banner`, `children`, `mobileNav` (`false`, a config object, or a node), `height` (`fill`, `auto`), `variant` (`wash`, `surface`, `section`, `elevated`), and `contentPadding`; targets `app-shell`, `app-shell-header`, `app-shell-sidenav`. |
-| Behavior | One page frame: skip link, then a header region, an inline side region, and one `main` region. Below the mobile breakpoint the side nav leaves the page and AppShell composes a mobile drawer from the nav slots, unless `mobileNav` disables or replaces it. AppShell is a layout root: layout values from its ancestors stop at its root (FR18). |
-| End-user impact | Keyboard users get a skip link to the main region; screen-reader users get one banner and one main landmark; phone-width users reach the side nav through a toggle and drawer while page content, its input values, and focus survive the layout switch. When the side nav collapses or expands, the content's old and new wrap swap on the rail's clock instead of re-wrapping in one frame (FR17). |
-| Builder impact | None. Callers fill slots and choose height, variant, content padding, and mobile behavior. |
-| Compatibility/readiness | Records shipped behavior; no prop, default, or export changes. Four current-state gaps, listed under Current-state impact: page-level stacking values, a banner pinned against its docs, an unmeasured late header, and a raw `content` drawer the toggle cannot reach. |
-| Review checks | Reject a second `main` or banner landmark from AppShell, a skip link that is not the first focusable element or does not move focus to `main`, a breakpoint that treats equality as mobile, or remounting page content when the breakpoint changes. Also reject a content area that animates its width during a side nav collapse or expand (FR17), and a shell whose regions move, clip, or change inset because of a Layout, Card, Section, or other layout host around it (FR18). |
-| Governing rules | `spec:AST-012` FR8 (width points), `family:layout-regions` FR9, `architecture:theme-application` INV10, `spec:AST-027` FR1–FR5 (local stacking), `architecture:component-theming-surface`; `component:SideNav` FR6 and `spec:AST-105` FR8 (the content swap); `architecture:container-padding` and `component:Layout` FR2 and FR5 (the layout root, FR18). |
+| Area | Contract |
+| ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Public contract | `AppShell` with `topNav`, `sideNav`, `banner`, `children`, `mobileNav` (`false`, a config object, or a node), `height` (`fill`, `auto`), `variant` (`wash`, `surface`, `section`, `elevated`), and `contentPadding`; targets `app-shell`, `app-shell-header`, `app-shell-sidenav`. |
+| Behavior | One page frame: skip link, then a header region, an inline side region, and one `main` region. Below the mobile breakpoint the side nav leaves the page and AppShell composes a mobile drawer from the nav slots, unless `mobileNav` disables or replaces it. AppShell is a layout root: layout values from its ancestors stop at its root (FR18). |
+| End-user impact | Keyboard users get a skip link to the main region; screen-reader users get one banner and one main landmark; phone-width users reach the side nav through a toggle and drawer while page content, its input values, and focus survive the layout switch. When the side nav collapses or expands, the content's old and new wrap swap on the rail's clock instead of re-wrapping in one frame (FR17). |
+| Builder impact | None. Callers fill slots and choose height, variant, content padding, and mobile behavior. |
+| Compatibility/readiness | Records shipped behavior and adds the FR3 and FR4 safe area for pages that set `viewport-fit=cover`; no prop, default, or export changes. Six current-state gaps, listed under Current-state impact: page-level stacking values, a banner pinned against its docs, an unmeasured late header, a raw `content` drawer the toggle cannot reach, landscape side insets that reach neither the content's sides nor an inline SideNav, and no top inset in a shell with no header region or phone top bar. |
+| Review checks | Reject a second `main` or banner landmark from AppShell, a skip link that is not the first focusable element or does not move focus to `main`, a breakpoint that treats equality as mobile, or remounting page content when the breakpoint changes. Also reject a content area that animates its width during a side nav collapse or expand (FR17), and a shell whose regions move, clip, or change inset because of a Layout, Card, Section, or other layout host around it (FR18). |
+| Governing rules | `spec:AST-012` FR8 (width points), `family:layout-regions` FR9, `architecture:theme-application` INV10, `spec:AST-027` FR1–FR5 (local stacking), `architecture:component-theming-surface`; `component:SideNav` FR6 and `spec:AST-105` FR8 (the content swap); `architecture:container-padding` and `component:Layout` FR2 and FR5 (the layout root, FR18). |
This table is a review projection; the body below is authoritative.
@@ -54,12 +55,17 @@ at a theme-resolved width point. Consumer usage lives in `AppShell.doc.mjs`.
- Released default preserved: `yes`, except FR17: `no`, since every AppShell with
an inline collapsible SideNav swaps its content wrap on a collapse or expand,
- with no prop to keep the earlier instant re-wrap; and FR18: `no`, since an
+ with no prop to keep the earlier instant re-wrap; FR18: `no`, since an
AppShell inside a padded container or a Layout lays out as it does at the
- page root instead of escaping the host's padding and taking its layout values
+ page root instead of escaping the host's padding and taking its layout values;
+ and FR3 and FR4: `no` on a page that sets `viewport-fit=cover`, since the
+ header region pads its items by the device's safe-area insets and main adds
+ the bottom inset to its block end, with no prop to keep the earlier placement
- Compatibility class: records shipped behavior, including FR17, a nonbreaking
- motion addition, and FR18, a layout correction for a shell placed inside a
- layout host; no public prop, default, target, or export changes
+ motion addition, FR18, a layout correction for a shell placed inside a
+ layout host, and FR3 and FR4, a nonbreaking safe-area layout addition for
+ pages that set `viewport-fit=cover`; no public prop, default, target, or
+ export changes
- Controlled/uncontrolled behavior: the mobile drawer's open state is
uncontrolled by default and controlled when `mobileNav.isOpen` is defined
(FR11)
@@ -89,6 +95,18 @@ Consumer migration instructions belong in consumer docs and release notes.
the auto toggle still renders, so its `aria-controls` names no element and its
presses open nothing. WCAG 4.1.2 requires a control's relationships and state
to be programmatically correct.
+- **In landscape the side insets reach neither the content's sides nor an
+ inline SideNav.** Under `viewport-fit=cover`, only the header region and the
+ sidenav-only mobile top bar take the side safe-area insets (FR3), so in
+ landscape a notch or a rounded screen corner can cover the edge of the
+ content and of an inline side nav.
+- **A shell with no header region or phone top bar takes no top inset.** Under
+ `viewport-fit=cover`, only the header region and the sidenav-only mobile top
+ bar take the top safe-area inset (FR3), so in a shell with neither the first
+ line of the content sits under the status bar. That is content only, or a
+ side nav with no top nav or banner while the phone top bar does not render:
+ above the mobile breakpoint, with `mobileNav={false}`, or with
+ `mobileNav={{hasToggle: false}}`.
## Ownership boundary
@@ -153,8 +171,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. | 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`. 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. | Current source and tests |
+| 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 |
| 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 |
@@ -284,6 +302,7 @@ reachability, not a decision that it must stay unthemeable.
| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
| ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------ |
| FR1–FR4, AR1 | `AppShell.test.tsx` slot, landmark, banner, and ref suites; `AppShellMainKeyboard.a11y.browser.spec.ts` for main as a tab stop and its focus ring | Content only; each slot; mobile top bar with banner; Tab, Shift+Tab, click and skip link onto an overflowing main | A missing or duplicate landmark, or a nested banner, fails role queries. | `audit:AppShell/anatomy` |
+| FR3, FR4 safe area | `AppShellSafeArea.test.tsx` declared insets for the header region, the sidenav-only mobile top bar, and main; `AppShellSafeArea.a11y.chromium.spec.ts` with the device's insets emulated | Portrait and landscape insets; right to left with a notch on one side; the sidenav-only top bar alone and below a banner, at rest and scrolled in `auto`; no insets; a child that fills main | Items under the status bar or a side inset, sides that follow the text direction instead of the device, a block-end padding other than `contentPadding` plus the bottom inset, a published inset that includes the safe area, or anything moving without insets fails. | `audit:AppShell/behavior` |
| FR5, AR2 | `AppShell.test.tsx` skip-link and keyboard suites | First Tab; Enter; click; translated text | Losing the href, the focus move, or tab order fails. | `audit:AppShell/accessibility` |
| FR6, PR1 | `AppShell.test.tsx` height-mode and main keyboard access suites; `observeMainOverflow.test.ts` | `fill`, `auto`, section header in `auto`; main fitting and overflowing in `fill` | Dropping the header's sticky placement, measuring the header in `fill`, or not measuring main, fails. | `audit:AppShell/behavior` |
| FR8 | `AppShell.test.tsx` breakpoint suites | `lg`, `xl`, `2xl`, explicit `md`, `none`; nearest, root, and built themes; SSR hint | Wrong map, inclusive edge, or `none` entering mobile fails. | `audit:AppShell/behavior` |
diff --git a/packages/core/src/AppShell/AppShell.doc.mjs b/packages/core/src/AppShell/AppShell.doc.mjs
index 410922fb9c..377f25e173 100644
--- a/packages/core/src/AppShell/AppShell.doc.mjs
+++ b/packages/core/src/AppShell/AppShell.doc.mjs
@@ -45,6 +45,11 @@ export const docs = {
description:
'Start the page heading inside `children`. AppShell owns the skip link, the banner landmark and the main landmark, but it renders no heading, so the first heading in the content area is the page h1.',
},
+ {
+ guidance: true,
+ description:
+ 'On phones, opt the page into the full screen with `viewport-fit=cover` in the viewport meta tag (`width=device-width, initial-scale=1, viewport-fit=cover`). AppShell then extends its header under the status bar and out to the screen sides, and keeps the header\'s items and the end of the content inside the device\'s safe area. An installed web app can also draw under the status bar with `<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">`. In landscape only the header is inset: an inline SideNav and the content\'s sides still reach under a notch, so keep content padding there. A shell with no header region or phone top bar keeps no top inset; keep top padding there.',
+ },
{
guidance: false,
description:
@@ -343,6 +348,11 @@ export const docsDense = {
description:
'Give every nav slot an accessible name: TopNav and SideNav are separate navigation landmarks, so pass `label` to each.',
},
+ {
+ guidance: true,
+ description:
+ 'Phones: add `viewport-fit=cover` to the viewport meta; the header then reaches under the status bar while its items and the content end stay in the safe area. Landscape: only the header is inset (not an inline SideNav or the content sides). No header region or phone top bar: no top inset, so keep top padding. Installed web apps: `apple-mobile-web-app-status-bar-style` `black-translucent`.',
+ },
{
guidance: true,
description:
diff --git a/packages/core/src/AppShell/AppShell.tsx b/packages/core/src/AppShell/AppShell.tsx
index ccce8fdff3..313d3fa2b9 100644
--- a/packages/core/src/AppShell/AppShell.tsx
+++ b/packages/core/src/AppShell/AppShell.tsx
@@ -471,6 +471,38 @@ const styles = stylex.create({
top: 0,
zIndex: 1,
},
+ // The insets are zero unless the page sets `viewport-fit=cover`. The header
+ // background goes under the status bar and to the screen sides, as a UIKit
+ // bar does.
+ headerSafeAreaTop: {
+ paddingBlockStart: 'env(safe-area-inset-top, 0px)',
+ },
+ // The insets are physical sides, so a right-to-left context swaps them on
+ // the inline sides.
+ headerSafeAreaSides: {
+ paddingInlineStart: {
+ default: 'env(safe-area-inset-left, 0px)',
+ ':is([dir="rtl"] *)': 'env(safe-area-inset-right, 0px)',
+ },
+ paddingInlineEnd: {
+ default: 'env(safe-area-inset-right, 0px)',
+ ':is([dir="rtl"] *)': 'env(safe-area-inset-left, 0px)',
+ },
+ },
+ // In `auto`, the banner's wrapper and the phone top bar both stick. Below a
+ // banner, the bar sticks under the top inset, so its items stay clear of the
+ // status bar.
+ headerStickyBelowTopInset: {
+ top: 'env(safe-area-inset-top, 0px)',
+ },
+ // Main adds the bottom inset to the padding that LayoutContent publishes for
+ // `contentPadding`. The published value excludes the inset, so a bleed child
+ // subtracts only `contentPadding`. Main is border-box, so a child that fills
+ // it ends above the inset.
+ mainSafeAreaEnd: {
+ paddingBlockEnd:
+ 'calc(var(--container-padding-block-end, 0px) + env(safe-area-inset-bottom, 0px))',
+ },
// Sticky sideNav for auto height mode — sticks within the wrapper.
// This div replaces the panel as the direct flex child of the middle
// (horizontal) container, so it needs the same flex properties that
@@ -891,7 +923,12 @@ export function AppShell({
role="banner"
{...mergeProps(
themeProps('app-shell-header', {variant}),
- stylex.props(headerAreaStyle, isAuto && styles.headerSticky),
+ stylex.props(
+ headerAreaStyle,
+ isAuto && styles.headerSticky,
+ styles.headerSafeAreaTop,
+ styles.headerSafeAreaSides,
+ ),
)}>
{headerInner}
</div>
@@ -1184,6 +1221,7 @@ export function AppShell({
drawsMainFocusRing
? [focusOutlineStyles.focusVisible, styles.mainScrollRegionInset]
: styles.mainFocusTarget,
+ styles.mainSafeAreaEnd,
]}>
{children}
</LayoutContent>
@@ -1230,7 +1268,15 @@ export function AppShell({
role={headerContent == null ? 'banner' : undefined}
{...mergeProps(
themeProps('app-shell-header', {variant}),
- stylex.props(headerAreaStyle, isAuto && styles.headerSticky),
+ stylex.props(
+ headerAreaStyle,
+ isAuto && styles.headerSticky,
+ styles.headerSafeAreaSides,
+ // Under a banner, the banner's wrapper pads the top inset. This top
+ // bar takes only the side insets.
+ headerContent == null && styles.headerSafeAreaTop,
+ isAuto && headerContent != null && styles.headerStickyBelowTopInset,
+ ),
)}>
<LayoutHeader padding={0} hasDivider={navHasDividers}>
<div
diff --git a/packages/core/src/AppShell/AppShellSafeArea.test.tsx b/packages/core/src/AppShell/AppShellSafeArea.test.tsx
new file mode 100644
index 0000000000..248ef82919
--- /dev/null
+++ b/packages/core/src/AppShell/AppShellSafeArea.test.tsx
@@ -0,0 +1,249 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file AppShellSafeArea.test.tsx
+ * @input vitest (jsdom), React Testing Library, AppShell, and the CSS rules
+ * that StyleX injects.
+ * @output Checks the safe-area declarations. The header and the sidenav-only
+ * top bar pad their items by the top and side insets. Under a banner, the
+ * top bar takes only the sides. Main's block end is `contentPadding` plus
+ * the bottom inset.
+ * @position Testing for AppShell.tsx. jsdom drops `env()` values, so the test
+ * reads the rules that StyleX passes to `insertRule`.
+ */
+
+import {render, screen} from '@testing-library/react';
+import {beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
+import type {AppShell as AppShellComponent} from './AppShell';
+import type {
+ SideNav as SideNavComponent,
+ SideNavItem as SideNavItemComponent,
+ SideNavSection as SideNavSectionComponent,
+} from '../SideNav';
+
+/** Every rule StyleX inserted, as the raw text it handed to `insertRule`. */
+const rawRules: string[] = [];
+let AppShell: typeof AppShellComponent;
+let SideNav: typeof SideNavComponent;
+let SideNavItem: typeof SideNavItemComponent;
+let SideNavSection: typeof SideNavSectionComponent;
+
+beforeAll(async () => {
+ const insertRule = CSSStyleSheet.prototype.insertRule;
+ CSSStyleSheet.prototype.insertRule = function (
+ this: CSSStyleSheet,
+ rule: string,
+ index?: number,
+ ) {
+ rawRules.push(rule);
+ return insertRule.call(this, rule, index);
+ };
+ // StyleX injects when the styles are created: load AppShell after the
+ // recorder is in place.
+ vi.resetModules();
+ ({AppShell} = await import('./AppShell'));
+ ({SideNav, SideNavItem, SideNavSection} = await import('../SideNav'));
+});
+
+function stubMatchMedia(matches: boolean) {
+ vi.stubGlobal(
+ 'matchMedia',
+ vi.fn((query: string) => ({
+ matches,
+ media: query,
+ onchange: null,
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
+ addListener: vi.fn(),
+ removeListener: vi.fn(),
+ dispatchEvent: vi.fn(),
+ })),
+ );
+}
+
+beforeEach(() => {
+ stubMatchMedia(false);
+});
+
+/** The declarations `el`'s classes make, from the raw rules, by property. */
+function rawDeclarations(el: Element, pseudo = ''): Map<string, string> {
+ const declarations = new Map<string, string>();
+ for (const className of Array.from(el.classList)) {
+ for (const rule of rawRules) {
+ const match = new RegExp(
+ `^\\.${className}(?::not\\(#\\\\#\\))*${pseudo}\\{([^}]*)\\}$`,
+ ).exec(rule);
+ if (match == null) {
+ continue;
+ }
+ for (const declaration of match[1].split(';')) {
+ const colon = declaration.indexOf(':');
+ if (colon > 0) {
+ // StyleX minifies values: compare without whitespace.
+ declarations.set(
+ declaration.slice(0, colon).trim(),
+ declaration.slice(colon + 1).replace(/\s+/g, ''),
+ );
+ }
+ }
+ }
+ }
+ return declarations;
+}
+
+describe('AppShell safe area', () => {
+ it('pads the header by the top and side insets', () => {
+ render(
+ <AppShell topNav={<div>Nav</div>}>
+ <div>Content</div>
+ </AppShell>,
+ );
+ const declarations = rawDeclarations(screen.getByRole('banner'));
+ expect(declarations.get('padding-top')).toBe(
+ 'env(safe-area-inset-top,0px)',
+ );
+ // Left-to-right here; a right-to-left context swaps the sides.
+ expect(declarations.get('padding-inline-start')).toBe(
+ 'env(safe-area-inset-left,0px)',
+ );
+ expect(declarations.get('padding-inline-end')).toBe(
+ 'env(safe-area-inset-right,0px)',
+ );
+ });
+
+ it('pads the sidenav-only phone top bar the same way', () => {
+ stubMatchMedia(true);
+ render(
+ <AppShell
+ sideNav={
+ <SideNav>
+ <SideNavSection title="Main" isHeaderHidden>
+ <SideNavItem label="Home" />
+ </SideNavSection>
+ </SideNav>
+ }>
+ <div>Content</div>
+ </AppShell>,
+ );
+ const bar = screen.getByRole('banner');
+ expect(rawDeclarations(bar).get('padding-top')).toBe(
+ 'env(safe-area-inset-top,0px)',
+ );
+ });
+
+ it('pads a sidenav-only phone top bar under a banner by the sides only', () => {
+ stubMatchMedia(true);
+ render(
+ <AppShell
+ banner={<div>Banner</div>}
+ sideNav={
+ <SideNav>
+ <SideNavSection title="Main" isHeaderHidden>
+ <SideNavItem label="Home" />
+ </SideNavSection>
+ </SideNav>
+ }>
+ <div>Content</div>
+ </AppShell>,
+ );
+ // The banner's wrapper pads the top inset once; the top bar below it
+ // would otherwise add a second band of the same height.
+ const banner = screen.getByRole('banner');
+ expect(rawDeclarations(banner).get('padding-top')).toBe(
+ 'env(safe-area-inset-top,0px)',
+ );
+ const topBar = screen
+ .getAllByRole('navigation')
+ .map(nav => nav.closest('.astryx-app-shell-header'))
+ .find(el => el != null && el !== banner) as HTMLElement;
+ expect(topBar).toBeTruthy();
+ const declarations = rawDeclarations(topBar);
+ expect(declarations.has('padding-top')).toBe(false);
+ expect(declarations.get('padding-inline-start')).toBe(
+ 'env(safe-area-inset-left,0px)',
+ );
+ });
+
+ it('sticks a phone top bar under a banner below the top inset in auto', () => {
+ stubMatchMedia(true);
+ const sideNav = (
+ <SideNav>
+ <SideNavSection title="Main" isHeaderHidden>
+ <SideNavItem label="Home" />
+ </SideNavSection>
+ </SideNav>
+ );
+ const withBanner = render(
+ <AppShell height="auto" banner={<div>Banner</div>} sideNav={sideNav}>
+ <div>Content</div>
+ </AppShell>,
+ );
+ const banner = screen.getByRole('banner');
+ const topBar = screen
+ .getAllByRole('navigation')
+ .map(nav => nav.closest('.astryx-app-shell-header'))
+ .find(el => el != null && el !== banner) as HTMLElement;
+ expect(topBar).toBeTruthy();
+ expect(rawDeclarations(topBar).get('position')).toBe('sticky');
+ expect(rawDeclarations(topBar).get('top')).toBe(
+ 'env(safe-area-inset-top,0px)',
+ );
+ withBanner.unmount();
+ // With no banner, the top bar is the header itself. It pads the top inset
+ // and sticks at the top edge.
+ render(
+ <AppShell height="auto" sideNav={sideNav}>
+ <div>Content</div>
+ </AppShell>,
+ );
+ const bar = screen.getByRole('banner');
+ expect(rawDeclarations(bar).get('padding-top')).toBe(
+ 'env(safe-area-inset-top,0px)',
+ );
+ const top = rawDeclarations(bar).get('top');
+ expect(top).toBeDefined();
+ expect(top).not.toContain('env(');
+ });
+
+ // Main's block-end padding: the inset it publishes for `contentPadding`
+ // plus the bottom safe-area inset (FR4).
+ const MAIN_END =
+ 'calc(var(--container-padding-block-end,0px)+env(safe-area-inset-bottom,0px))';
+
+ it('grows the main region’s block-end padding by the bottom inset', () => {
+ render(
+ <AppShell topNav={<div>Nav</div>}>
+ <div>Content</div>
+ </AppShell>,
+ );
+ const main = screen.getByRole('main');
+ const declarations = rawDeclarations(main);
+ // No content padding: the published inset is the block-start padding's
+ // zero, so the block-end padding is the bottom inset alone.
+ const published = declarations.get('--container-padding-block-end');
+ expect(published).toBeTruthy();
+ expect(published).toBe(declarations.get('padding-top'));
+ expect(published).not.toContain('env(');
+ expect(declarations.get('padding-bottom')).toBe(MAIN_END);
+ // Padding, not a spacer: main is border-box, so a child that fills it
+ // ends above the inset instead of overflowing it.
+ expect(declarations.get('box-sizing')).toBe('border-box');
+ expect(rawDeclarations(main, '::after').has('height')).toBe(false);
+ });
+
+ it('adds the bottom inset to the content padding, and publishes the content padding alone', () => {
+ render(
+ <AppShell topNav={<div>Nav</div>} contentPadding={6}>
+ <div>Content</div>
+ </AppShell>,
+ );
+ const declarations = rawDeclarations(screen.getByRole('main'));
+ expect(declarations.get('padding-bottom')).toBe(MAIN_END);
+ // The published inset is `contentPadding` alone, the block-start
+ // padding's value, so a bleed child subtracts only `contentPadding`.
+ const published = declarations.get('--container-padding-block-end');
+ expect(published).toBeTruthy();
+ expect(published).toBe(declarations.get('padding-top'));
+ expect(published).not.toContain('env(');
+ });
+});
diff --git a/packages/core/src/AppShell/__tests__/AppShellSafeArea.a11y.chromium.spec.ts b/packages/core/src/AppShell/__tests__/AppShellSafeArea.a11y.chromium.spec.ts
new file mode 100644
index 0000000000..aeeae538ba
--- /dev/null
+++ b/packages/core/src/AppShell/__tests__/AppShellSafeArea.a11y.chromium.spec.ts
@@ -0,0 +1,352 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+// @pr-a11y scope ^packages/core/src/AppShell/ ^apps/storybook/stories/AppShell
+
+/**
+ * @file AppShellSafeArea.a11y.chromium.spec.ts
+ * @input The built AppShell stories on the phone profile. The Chromium
+ * protocol emulates the device's safe-area insets (iPhone 17 Pro, iOS 26.2).
+ * @output Proves the safe-area geometry. The header background starts at the
+ * top edge, and its items start inside the insets. Main's block-end padding
+ * is `contentPadding` plus the bottom inset. With no insets, nothing moves.
+ * @position Browser proof for AppShell.tsx, run by `pnpm test:a11y-contract`
+ * and in pr-a11y. Chromium only: WebKit under Playwright cannot emulate
+ * insets.
+ */
+
+import {expect, test, type CDPSession, type Page} from '@playwright/test';
+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();
+});
+
+// The phone: an iPhone 17 Pro page in Safari, portrait.
+test.use({
+ viewport: {width: 402, height: 714},
+ deviceScaleFactor: 3,
+ isMobile: true,
+ hasTouch: true,
+});
+
+async function openStory(page: Page, id: string, globals = ''): Promise<void> {
+ const query = globals === '' ? '' : `&globals=${globals}`;
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=${id}&viewMode=story${query}`,
+ );
+ await page.locator('[role="banner"]').first().waitFor();
+ await page.evaluate(async () => document.fonts.ready);
+}
+
+interface Insets {
+ top: number;
+ bottom: number;
+ left: number;
+ right: number;
+}
+
+/** iPhone 17 Pro, UIKit lab, iOS 26.2 simulator. */
+const PORTRAIT: Insets = {top: 62, bottom: 34, left: 0, right: 0};
+const LANDSCAPE: Insets = {top: 0, bottom: 21, left: 62, right: 62};
+const NONE: Insets = {top: 0, bottom: 0, left: 0, right: 0};
+
+// One protocol session per page, so each override replaces the one before it.
+const sessions = new WeakMap<Page, CDPSession>();
+
+async function emulateInsets(page: Page, insets: Insets): Promise<CDPSession> {
+ let session = sessions.get(page);
+ if (session == null) {
+ session = await page.context().newCDPSession(page);
+ sessions.set(page, session);
+ }
+ await session.send('Emulation.setSafeAreaInsetsOverride', {
+ insets: {
+ top: insets.top,
+ topMax: insets.top,
+ bottom: insets.bottom,
+ bottomMax: insets.bottom,
+ left: insets.left,
+ leftMax: insets.left,
+ right: insets.right,
+ rightMax: insets.right,
+ },
+ });
+ return session;
+}
+
+/** Main's block-end padding with no insets: the content padding alone. */
+async function endPaddingWithoutInsets(
+ page: Page,
+ story: string,
+): Promise<number> {
+ await emulateInsets(page, NONE);
+ await openStory(page, story);
+ return page.evaluate(
+ () =>
+ parseFloat(
+ getComputedStyle(document.querySelector('[role="main"]') as HTMLElement)
+ .paddingBottom,
+ ) || 0,
+ );
+}
+
+interface Geometry {
+ shellTop: number;
+ shellLeft: number;
+ shellRight: number;
+ bannerTop: number;
+ padding: {top: number; left: number; right: number};
+ /** The banner's first item (TopNav's or the top bar's content). */
+ item: {top: number; left: number; right: number};
+ /** Main's block-end padding: its content padding plus the bottom inset. */
+ spacer: number;
+ /** Main's block-start padding: its content padding alone. */
+ contentPadding: number;
+ /** The inset main publishes to its children, resolved to px. */
+ published: number;
+ boxSizing: string;
+}
+
+async function geometry(page: Page): Promise<Geometry> {
+ return page.evaluate(() => {
+ const shell = document.querySelector('[role="banner"]')?.parentElement;
+ const root = document.querySelector('.astryx-app-shell');
+ const banner = document.querySelector('[role="banner"]') as HTMLElement;
+ const main = document.querySelector('[role="main"]') as HTMLElement;
+ const style = getComputedStyle(banner);
+ // The banner's content box: what its items lay out in.
+ const first = banner.firstElementChild as HTMLElement;
+ const items = first.getBoundingClientRect();
+ const box = (root ?? shell ?? banner).getBoundingClientRect();
+ const mainStyle = getComputedStyle(main);
+ // What a bleed child subtracts: the published inset, resolved to px.
+ const probe = document.createElement('div');
+ probe.style.cssText =
+ 'position:absolute;visibility:hidden;width:var(--container-padding-block-end)';
+ main.append(probe);
+ const published = probe.getBoundingClientRect().width;
+ probe.remove();
+ return {
+ shellTop: box.top,
+ shellLeft: box.left,
+ shellRight: box.right,
+ bannerTop: banner.getBoundingClientRect().top,
+ padding: {
+ top: parseFloat(style.paddingTop),
+ left: parseFloat(style.paddingLeft),
+ right: parseFloat(style.paddingRight),
+ },
+ item: {top: items.top, left: items.left, right: items.right},
+ spacer: parseFloat(mainStyle.paddingBottom) || 0,
+ contentPadding: parseFloat(mainStyle.paddingTop) || 0,
+ published,
+ boxSizing: mainStyle.boxSizing,
+ };
+ });
+}
+
+for (const story of [
+ 'core-appshell--top-nav-only',
+ 'core-appshell--auto-height',
+]) {
+ test(`${story}: in portrait the header reaches under the status bar and the content clears the home indicator`, async ({
+ page,
+ }) => {
+ const base = await endPaddingWithoutInsets(page, story);
+ await emulateInsets(page, PORTRAIT);
+ await openStory(page, story);
+ const g = await geometry(page);
+ test
+ .info()
+ .annotations.push({type: 'geometry', description: JSON.stringify(g)});
+ // The background starts at the shell's top edge…
+ expect(g.bannerTop).toBeCloseTo(g.shellTop, 1);
+ // …and the items start below the inset.
+ expect(g.padding.top).toBe(PORTRAIT.top);
+ expect(g.item.top - g.bannerTop).toBeGreaterThanOrEqual(PORTRAIT.top - 0.5);
+ // Main's block-end padding is its content padding without insets, and
+ // its content padding plus exactly the bottom inset with them.
+ expect(g.contentPadding).toBeGreaterThan(0);
+ expect(base).toBe(g.contentPadding);
+ expect(g.spacer).toBe(g.contentPadding + PORTRAIT.bottom);
+ // The inset main publishes to its children stays its content padding
+ // alone, and main stays border-box.
+ expect(g.published).toBe(g.contentPadding);
+ expect(g.boxSizing).toBe('border-box');
+ });
+}
+
+test('a child that fills main ends above the home indicator, without an outer scroll', async ({
+ page,
+}) => {
+ await emulateInsets(page, PORTRAIT);
+ await openStory(page, 'core-appshell--top-nav-only');
+ const g = await page.evaluate(() => {
+ // A child that fills main, as `Layout height="fill"` does.
+ const main = document.querySelector('[role="main"]') as HTMLElement;
+ const contentPadding = parseFloat(getComputedStyle(main).paddingTop) || 0;
+ const child = document.createElement('div');
+ child.style.height = '100%';
+ main.replaceChildren(child);
+ const box = main.getBoundingClientRect();
+ return {
+ contentPadding,
+ overflow: main.scrollHeight - main.clientHeight,
+ gap: box.bottom - child.getBoundingClientRect().bottom,
+ };
+ });
+ test
+ .info()
+ .annotations.push({type: 'geometry', description: JSON.stringify(g)});
+ expect(g.overflow).toBeLessThanOrEqual(0);
+ expect(g.gap).toBeCloseTo(g.contentPadding + PORTRAIT.bottom, 0);
+});
+
+test('in landscape the header items stay inside the side insets', async ({
+ page,
+}) => {
+ await page.setViewportSize({width: 874, height: 402});
+ const base = await endPaddingWithoutInsets(
+ page,
+ 'core-appshell--top-nav-only',
+ );
+ await emulateInsets(page, LANDSCAPE);
+ await openStory(page, 'core-appshell--top-nav-only');
+ const g = await geometry(page);
+ test
+ .info()
+ .annotations.push({type: 'geometry', description: JSON.stringify(g)});
+ expect(g.padding.left).toBe(LANDSCAPE.left);
+ expect(g.padding.right).toBe(LANDSCAPE.right);
+ expect(g.item.left - g.shellLeft).toBeGreaterThanOrEqual(
+ LANDSCAPE.left - 0.5,
+ );
+ expect(g.shellRight - g.item.right).toBeGreaterThanOrEqual(
+ LANDSCAPE.right - 0.5,
+ );
+ expect(g.padding.top).toBe(0);
+ expect(base).toBe(g.contentPadding);
+ expect(g.spacer).toBe(g.contentPadding + LANDSCAPE.bottom);
+});
+
+test('in right to left the physical side insets stay on their sides', async ({
+ page,
+}) => {
+ await page.setViewportSize({width: 874, height: 402});
+ // A notch on the left only: the inset follows the device, not the text
+ // direction, so it stays on the left in both directions.
+ const uneven: Insets = {top: 0, bottom: 21, left: 62, right: 0};
+ for (const direction of ['ltr', 'rtl']) {
+ await emulateInsets(page, uneven);
+ await openStory(
+ page,
+ 'core-appshell--top-nav-only',
+ `direction:${direction}`,
+ );
+ const g = await geometry(page);
+ const applied = await page.evaluate(
+ () =>
+ getComputedStyle(document.querySelector('[role="banner"]') as Element)
+ .direction,
+ );
+ test.info().annotations.push({
+ type: `geometry ${direction}`,
+ description: JSON.stringify(g),
+ });
+ expect(applied).toBe(direction);
+ expect(g.padding.left).toBe(uneven.left);
+ expect(g.padding.right).toBe(uneven.right);
+ expect(g.item.left - g.shellLeft).toBeGreaterThanOrEqual(uneven.left - 0.5);
+ }
+});
+
+test('the sidenav-only phone top bar keeps to the safe area too', async ({
+ page,
+}) => {
+ await emulateInsets(page, PORTRAIT);
+ await openStory(page, 'core-appshell--side-nav-only');
+ const g = await geometry(page);
+ test
+ .info()
+ .annotations.push({type: 'geometry', description: JSON.stringify(g)});
+ expect(g.padding.top).toBe(PORTRAIT.top);
+ expect(g.item.top - g.bannerTop).toBeGreaterThanOrEqual(PORTRAIT.top - 0.5);
+});
+
+/** The banner and the phone top bar below it, and the bar's menu button. */
+async function stuckBar(page: Page) {
+ return page.evaluate(() => {
+ const banner = document.querySelector('[role="banner"]') as HTMLElement;
+ const bar = [...document.querySelectorAll('.astryx-app-shell-header')].find(
+ el => el !== banner,
+ ) as HTMLElement;
+ const button = bar.querySelector('button') as HTMLElement;
+ const box = (el: HTMLElement) => el.getBoundingClientRect();
+ return {
+ scrollY: window.scrollY,
+ bannerBottom: box(banner).bottom,
+ barTop: box(bar).top,
+ barHeight: box(bar).height,
+ buttonTop: box(button).top,
+ buttonHeight: box(button).height,
+ };
+ });
+}
+
+async function scrollPage(page: Page, y: number) {
+ await page.evaluate(async top => {
+ window.scrollTo(0, top);
+ await new Promise<void>(resolve => {
+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()));
+ });
+ }, y);
+}
+
+// In `auto`, the banner's wrapper and the phone top bar below it both stick.
+// Scrolled, the bar must stick under the top inset, so its menu button stays
+// clear of the status bar.
+test('in auto, the phone top bar below a banner sticks under the top inset', async ({
+ page,
+}) => {
+ await emulateInsets(page, PORTRAIT);
+ await openStory(page, 'core-appshell--auto-height-side-nav-banner');
+ const rest = await stuckBar(page);
+ expect(rest.barHeight).toBeGreaterThan(0);
+ expect(rest.buttonHeight).toBeGreaterThan(0);
+ expect(rest.barTop).toBeGreaterThanOrEqual(rest.bannerBottom - 0.5);
+ await scrollPage(page, 600);
+ const scrolled = await stuckBar(page);
+ test.info().annotations.push({
+ type: 'geometry',
+ description: JSON.stringify(scrolled),
+ });
+ expect(scrolled.scrollY).toBeGreaterThan(rest.bannerBottom);
+ expect(scrolled.barTop).toBeCloseTo(PORTRAIT.top, 0);
+ expect(scrolled.buttonTop).toBeGreaterThanOrEqual(PORTRAIT.top - 0.5);
+ // With no insets, the bar sticks at the top edge.
+ await emulateInsets(page, NONE);
+ await openStory(page, 'core-appshell--auto-height-side-nav-banner');
+ await scrollPage(page, 600);
+ expect((await stuckBar(page)).barTop).toBeCloseTo(0, 0);
+});
+
+test('with no insets nothing moves', async ({page}) => {
+ await emulateInsets(page, NONE);
+ await openStory(page, 'core-appshell--top-nav-only');
+ const g = await geometry(page);
+ expect(g.padding).toEqual({top: 0, left: 0, right: 0});
+ expect(g.item.top).toBeCloseTo(g.bannerTop, 1);
+ // Main keeps its content padding on every side, and publishes it.
+ expect(g.contentPadding).toBeGreaterThan(0);
+ expect(g.spacer).toBe(g.contentPadding);
+ expect(g.published).toBe(g.contentPadding);
+});
diff --git a/packages/core/src/Layer/layerViewportInset.test.ts b/packages/core/src/Layer/layerViewportInset.test.ts
index ccd25d7a48..7627ff8a45 100644
--- a/packages/core/src/Layer/layerViewportInset.test.ts
+++ b/packages/core/src/Layer/layerViewportInset.test.ts
@@ -16,9 +16,12 @@ import {clampInlineSize, isIntrinsicInlineSize} from './clampInlineSize';
const EDGES = ['block-start', 'block-end', 'inline-start', 'inline-end'];
// Surfaces that keep the same gutter by convention but are not anchor-mode
-// layers (spec:AST-059 non-goals), plus the module itself.
+// layers (spec:AST-059 non-goals), plus the module itself. AppShell reads the
+// device's insets for the page shell itself (its header and the end of its
+// content), not as a layer gutter.
const GUTTER_OWNERS = new Set([
'Layer/layerViewportInset.stylex.ts',
+ 'AppShell/AppShell.tsx',
'Dialog/Dialog.tsx',
'Toast/ToastViewport.tsx',
'BottomSheet/BottomSheetPanel.tsx',