An open source design system that's fully customizable and agent ready
TypeScript
fix(AppShell): with fill height, keyboard users can scroll an overflowing main region (#8111)
Christopher Chedeau00507ba075d0
diff --git a/.changeset/appshell-main-keyboard-scroll.md b/.changeset/appshell-main-keyboard-scroll.mdnew file mode 100644index 0000000000..5e42c2123e--- /dev/null+++ b/.changeset/appshell-main-keyboard-scroll.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] With `height="fill"`, AppShell's main region can be scrolled from the keyboard when its content overflows and has nothing focusable (WCAG 2.1.1 Keyboard). Before, main was only the skip link's target (`tabIndex={-1}`): Tab passed it by, so long text, a report or a read-only page could not be scrolled without a pointer. Now, while main scrolls overflowing content, it is a stop in the tab order and keyboard focus on it draws the standard focus ring, inset; in an elevated shell with a top nav and an inline side nav, main then takes the surface's rounded top-start corner so the ring follows it. Tab entry moves on when the first focusable element inside main is a plain link or button; otherwise main is one stop before it. A main region that fits, and `height="auto"` (where the page scrolls), are unchanged.++@vjeuxdiff --git a/apps/storybook/stories/AppShell.stories.tsx b/apps/storybook/stories/AppShell.stories.tsxindex a23e6fa117..8d91eaaabc 100644--- a/apps/storybook/stories/AppShell.stories.tsx+++ b/apps/storybook/stories/AppShell.stories.tsx@@ -509,6 +509,23 @@ export const AutoHeight: Story = {),};+/**+ * The default fill height with more content than fits and nothing focusable+ * in it. The main region scrolls inside the viewport-high shell; while it+ * overflows it is a stop in the tab order, so the arrow keys and Page Up/Down+ * can scroll it.+ */+export const LongContent: Story = {+ render: () => (+ <AppShell+ contentPadding={6}+ topNav={<AppTopNav />}+ sideNav={<SideNavWithoutHeader />}>+ <MockContent paragraphs={20} />+ </AppShell>+ ),+};+/*** Auto height mode with Field-based inputs. Scroll the inputs under the* sticky header — the header must stay above the input surfaces. Fielddiff --git a/packages/core/src/AppShell/AppShell.doc.mjs b/packages/core/src/AppShell/AppShell.doc.mjsindex 2a5b592458..410922fb9c 100644--- a/packages/core/src/AppShell/AppShell.doc.mjs+++ b/packages/core/src/AppShell/AppShell.doc.mjs@@ -96,7 +96,7 @@ export const docs = {name: 'Main content',required: true,description:- 'children, rendered in the main landmark. Scrolls internally when height is fill, and with the page when it is auto.',+ 'children, rendered in the main landmark. Scrolls internally when height is fill, and with the page when it is auto. While it scrolls content that overflows, it is a stop in the tab order; Tab entry moves on when its first focusable element is a plain link or button, and otherwise main is one stop before it.',},{name: 'Mobile nav drawer',diff --git a/packages/core/src/AppShell/AppShell.spec.md b/packages/core/src/AppShell/AppShell.spec.mdindex df2cb20dd4..1a656ad11f 100644--- a/packages/core/src/AppShell/AppShell.spec.md+++ b/packages/core/src/AppShell/AppShell.spec.md@@ -36,7 +36,7 @@ system_specs: [spec:AST-012, spec:AST-027]| 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. || 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. Five 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, and a fill-height main region that is not a tab stop. |+| 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). || 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). |@@ -86,11 +86,6 @@ Consumer migration instructions belong in consumer docs and release notes.the auto toggle still renders, so its `aria-controls` names no element and itspresses open nothing. WCAG 4.1.2 requires a control's relationships and stateto be programmatically correct.-- **The fill-height main region is not a tab stop while it overflows.** In- `height="fill"` the main region is a scroll container, but it is never a- sequential tab stop, so keyboard users reach overflowing content only through- the skip link or focusable content inside it. `spec:AST-025` FR12 requires- effective scroll content to stay keyboard reachable.## Ownership boundary@@ -155,7 +150,7 @@ 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). | 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 || 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 |@@ -202,8 +197,10 @@ the only component record in the AppShell root.### Performance and resources-- **PR1 — Header measurement.** AppShell observes the header's size only in- `auto` and observes nothing in `fill`.+- **PR1 — Measurement.** AppShell observes the header's size only in `auto`.+ In `fill` it observes only whether the main region overflows (main's size,+ its direct children's sizes, and its content), which decides whether main is+ a sequential tab stop (FR4).- **PR2 — One media query.** The breakpoint switch uses one media querysubscription per shell.@@ -280,9 +277,9 @@ 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 | Content only; each slot; mobile top bar with banner | A missing or duplicate landmark, or a nested banner, fails role queries. | `audit:AppShell/anatomy` |+| 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` || 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 suites | `fill`, `auto`, section header in `auto` | Dropping the header's sticky placement or measuring in `fill` fails. | `audit:AppShell/behavior` |+| 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` || FR9–FR12 | `AppShell.test.tsx` mobile suites; `MobileNavCloseEdgeCases.test.tsx` AppShell drawer suites | Sidenav only; both navs; heading-only TopNav; custom node | A missing toggle, duplicated items, a stale drawer, or an early hide fails. | `audit:AppShell/behavior` || FR13, AR3 | `AppShell.test.tsx` keyboard drawer and `useAppShellMobile` suites | Outside a shell; inside, closed and open | A wrong id link or stale state fails. | `audit:AppShell/accessibility` |@@ -298,7 +295,7 @@ Read from source, with no focused test or baseline yet:- FR2: `null`, `true`, `false`, and `''` slots counting as absent, and a slot that rendersnothing counting as present.- FR3: `banner` above `topNav`, and no header region with only `sideNav`.-- FR4: the `contentPadding` value and its `0` default, and no focus ring on main.+- FR4: the `contentPadding` value and its `0` default.- FR5: the skip link's visual hiding until focus; AR2: its shared focus outline.- FR6: root sizing and region scrolling in each height mode, and the sticky sideregion in `auto`.diff --git a/packages/core/src/AppShell/AppShell.test.tsx b/packages/core/src/AppShell/AppShell.test.tsxindex 7f01171167..ac92df125e 100644--- a/packages/core/src/AppShell/AppShell.test.tsx+++ b/packages/core/src/AppShell/AppShell.test.tsx@@ -860,7 +860,7 @@ describe('AppShell', () => {expect(observeSpy).toHaveBeenCalled();});- it('does not set up ResizeObserver in fill mode', () => {+ it('does not observe the header in fill mode', () => {const observeSpy = vi.fn();vi.stubGlobal('ResizeObserver',@@ -878,7 +878,13 @@ describe('AppShell', () => {</AppShell>,);- expect(observeSpy).not.toHaveBeenCalled();+ // Only the header offset needs measuring for sticky positioning, which+ // fill mode does not use. (Main is measured for keyboard access.)+ const observed = new Set<unknown>();+ for (const call of observeSpy.mock.calls) {+ observed.add(call[0]);+ }+ expect(observed.has(screen.getByRole('banner'))).toBe(false);});// ===========================================================================@@ -1146,3 +1152,159 @@ describe('AppShell', () => {).toBe(true);});});++describe('AppShell main keyboard access', () => {+ let frames: FrameRequestCallback[];++ beforeEach(() => {+ frames = [];+ vi.stubGlobal(+ 'requestAnimationFrame',+ vi.fn((callback: FrameRequestCallback) => {+ frames.push(callback);+ return frames.length;+ }),+ );+ vi.stubGlobal('cancelAnimationFrame', vi.fn());+ // jsdom does not expand LayoutContent's `overflow` into its longhands.+ const nativeGetComputedStyle = window.getComputedStyle.bind(window);+ vi.spyOn(window, 'getComputedStyle').mockImplementation(+ (element, pseudo) => {+ const computed = nativeGetComputedStyle(element, pseudo);+ return new Proxy(computed, {+ // eslint-disable-next-line @typescript-eslint/promise-function-async -- Proxy traps must remain synchronous+ get(target, property) {+ if (property === 'overflowX' || property === 'overflowY') {+ return target.overflow || 'visible';+ }+ return Reflect.get(target, property, target);+ },+ });+ },+ );+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ vi.stubGlobal('ResizeObserver', MockResizeObserver);+ });++ function setMainGeometry(main: HTMLElement, scrollHeight: number) {+ for (const [key, value] of [+ ['clientWidth', 800],+ ['scrollWidth', 800],+ ['clientHeight', 300],+ ['scrollHeight', scrollHeight],+ ['scrollTop', 0],+ ['scrollLeft', 0],+ ] as const) {+ Object.defineProperty(main, key, {+ configurable: true,+ value,+ writable: true,+ });+ }+ }++ function remeasure() {+ act(() => {+ window.dispatchEvent(new Event('resize'));+ });+ act(() => {+ const pending = frames.splice(0);+ pending.forEach(callback => callback(performance.now()));+ });+ }++ it('makes main a keyboard stop while it scrolls overflowing content, and a skip target again once it fits', () => {+ render(+ <AppShell topNav={<div>Nav</div>}>+ <p>Long content</p>+ </AppShell>,+ );+ const main = screen.getByRole('main');+ expect(main).toHaveAttribute('tabindex', '-1');++ setMainGeometry(main, 1200);+ remeasure();+ expect(main).toHaveAttribute('tabindex', '0');++ setMainGeometry(main, 300);+ remeasure();+ expect(main).toHaveAttribute('tabindex', '-1');+ });++ it('observes main only with fill, where it can become a keyboard stop', () => {+ const observed: Element[] = [];+ vi.stubGlobal(+ 'ResizeObserver',+ class {+ constructor(public callback: ResizeObserverCallback) {}+ observe(target: Element) {+ observed.push(target);+ }+ unobserve() {}+ disconnect() {}+ },+ );+ const inMain = (main: HTMLElement) =>+ observed.filter(target => target === main || main.contains(target));++ const {unmount} = render(+ <AppShell height="auto" topNav={<div>Nav</div>}>+ <p>Long content</p>+ </AppShell>,+ );+ expect(inMain(screen.getByRole('main'))).toEqual([]);+ unmount();++ render(+ <AppShell topNav={<div>Nav</div>}>+ <p>Long content</p>+ </AppShell>,+ );+ expect(inMain(screen.getByRole('main')).length).toBeGreaterThan(0);+ });++ it('stops observing main when the shell switches to auto, and measures it again back in fill', () => {+ const {rerender} = render(+ <AppShell topNav={<div>Nav</div>}>+ <p>Long content</p>+ </AppShell>,+ );+ const main = screen.getByRole('main');+ setMainGeometry(main, 1200);+ remeasure();+ expect(main).toHaveAttribute('tabindex', '0');++ rerender(+ <AppShell height="auto" topNav={<div>Nav</div>}>+ <p>Long content</p>+ </AppShell>,+ );+ expect(screen.getByRole('main')).toHaveAttribute('tabindex', '-1');+ remeasure();+ expect(screen.getByRole('main')).toHaveAttribute('tabindex', '-1');++ // Back in fill, main is measured as it attaches, with no other signal.+ rerender(+ <AppShell topNav={<div>Nav</div>}>+ <p>Long content</p>+ </AppShell>,+ );+ expect(screen.getByRole('main')).toHaveAttribute('tabindex', '0');+ });++ it('never makes main a keyboard stop when the page scrolls instead (auto)', () => {+ render(+ <AppShell height="auto" topNav={<div>Nav</div>}>+ <p>Long content</p>+ </AppShell>,+ );+ const main = screen.getByRole('main');++ setMainGeometry(main, 1200);+ remeasure();+ expect(main).toHaveAttribute('tabindex', '-1');+ });+});diff --git a/packages/core/src/AppShell/AppShell.tsx b/packages/core/src/AppShell/AppShell.tsxindex 592d399bd9..e8f9438a1a 100644--- a/packages/core/src/AppShell/AppShell.tsx+++ b/packages/core/src/AppShell/AppShell.tsx@@ -33,6 +33,7 @@ import {import * as stylex from '@stylexjs/stylex';import {colorVars,+ focusVars,fontWeightVars,radiusVars,spacingVars,@@ -64,7 +65,10 @@ import type {AppShellMobileContextValue} from './AppShellMobileContext';import type {SpacingStep} from '../utils/types';import type {BaseProps} from '../BaseProps';import {mergeProps, isRenderable} from '../utils';-import {focusOutlineProps} from '../utils/focusOutline.stylex';+import {+ focusOutlineProps,+ focusOutlineStyles,+} from '../utils/focusOutline.stylex';import {useMediaQuery} from '../hooks/useMediaQuery';import {observeResize} from '../utils/sharedResizeObserver';import {themeProps} from '../utils/themeProps';@@ -77,6 +81,8 @@ import {import type {AppShellVariantMap} from './index';import {useMergedRefs} from '../hooks/useMergedRefs';+import {attachScrollKeyboardDelegation} from '../hooks/scrollKeyboardDelegation';+import {observeMainOverflow} from './observeMainOverflow';const HasActivity = typeof React.Activity !== 'undefined';const ActivityWrapper = HasActivity? ({@@ -370,7 +376,7 @@ const styles = stylex.create({fontWeight: fontWeightVars['--font-weight-semibold'],fontSize: typeScaleVars['--text-body-size'],},- // Programmatic focus target for the skip link. The main container is only+ // Programmatic focus target for the skip link. While main fits, it is only// focusable via tabIndex={-1} (never tabbable), so a focus ring around the// entire content area would be noise rather than guidance — suppress it.mainFocusTarget: {@@ -379,6 +385,24 @@ const styles = stylex.create({':focus': 'none',},},+ // While main's focus ring shows, main follows the elevated surface's+ // rounded top-start corner, so the ring keeps the surface's shape instead of+ // drawing a square corner. Otherwise main keeps its corner and clips nothing.+ mainElevatedCorner: {+ borderStartStartRadius: {+ default: null,+ ':focus-visible': radiusVars['--radius-page'],+ },+ },+ // While main scrolls its overflowing content it is a keyboard stop, and+ // keyboard focus on it draws the standard ring, inset so the shell's own+ // clipping cannot hide it.+ mainScrollRegionInset: {+ outlineOffset: {+ default: '0',+ ':focus-visible': `calc(-1 * ${focusVars['--focus-outline-width']})`,+ },+ },elevatedBackdrop: {position: 'absolute',@@ -615,9 +639,105 @@ export function AppShell({document.getElementById(MAIN_CONTENT_ID)?.focus();}, []);+ // 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.+ // Programmatic focus (the skip link, a script's focus() on a route change)+ // draws none (FR4), even after keyboard input, where :focus-visible alone+ // would match. See the effect below for how a Tab move is told apart.+ const [isTabFocus, setIsTabFocus] = useState(false);+ // A window or tab switch blurs main without moving focus off it: main stays+ // the document's active element, and focus comes back to it with no Tab+ // press. The ring holds across that round trip; any real focus move ends it.+ const isMainAwayRef = useRef(false);+ const handleMainBlur = useCallback(+ (event: React.FocusEvent<HTMLDivElement>) => {+ if (event.target !== event.currentTarget) {+ return;+ }+ if (document.activeElement === event.currentTarget) {+ isMainAwayRef.current = true;+ return;+ }+ isMainAwayRef.current = false;+ setIsTabFocus(false);+ },+ [],+ );+const isFill = height === 'fill';const isAuto = height === 'auto';+ // With `fill`, main is the page's scroller. While its content overflows it+ // must be reachable from the keyboard even when nothing inside it is+ // focusable (AST-025 FR12): it joins the tab order, and Tab entry moves on+ // to its first link or button when it has one. Only `fill` observes main+ // (PR1); LayoutContent keeps owning main's overflow and styles.+ const [isMainOverflowing, setIsMainOverflowing] = useState(false);+ const isMainScrollRegion = isFill && isMainOverflowing;+ // Main's node is owned through a ref, never React state. Under `fill` its+ // overflow is observed while the node is attached, and while main is a+ // scroll region the keyboard delegation is attached to it. The ref callback+ // changes with `fill`, so switching modes detaches and re-attaches main in+ // the same commit; a detached or replaced node releases both before the new+ // node takes over.+ const mainNodeRef = useRef<HTMLDivElement | null>(null);+ const mainOverflowRef = useRef<{+ node: HTMLDivElement;+ stop: () => void;+ } | null>(null);+ const mainDelegationRef = useRef<{+ node: HTMLDivElement;+ release: () => void;+ } | null>(null);+ const isMainScrollRegionRef = useRef(isMainScrollRegion);+ const syncMainDelegation = useCallback(() => {+ const node = isMainScrollRegionRef.current ? mainNodeRef.current : null;+ const current = mainDelegationRef.current;+ if (current?.node === node) {+ return;+ }+ current?.release();+ mainDelegationRef.current =+ node == null+ ? null+ : {node, release: attachScrollKeyboardDelegation(node, node)};+ }, []);+ const setMainNode = useCallback(+ (node: HTMLDivElement | null) => {+ mainNodeRef.current = node;+ const observed = isFill ? node : null;+ const current = mainOverflowRef.current;+ if (current?.node !== observed) {+ current?.stop();+ mainOverflowRef.current =+ observed == null+ ? null+ : {+ node: observed,+ stop: observeMainOverflow(observed, setIsMainOverflowing),+ };+ if (observed == null) {+ setIsMainOverflowing(false);+ }+ }+ syncMainDelegation();+ },+ [isFill, syncMainDelegation],+ );+ useEffect(() => {+ isMainScrollRegionRef.current = isMainScrollRegion;+ syncMainDelegation();+ }, [isMainScrollRegion, syncMainDelegation]);+ useEffect(+ () => () => {+ mainOverflowRef.current?.stop();+ mainOverflowRef.current = null;+ mainDelegationRef.current?.release();+ mainDelegationRef.current = null;+ },+ [],+ );+// Nav style derived valuesconst hasBanner = isRenderable(banner);const hasTopNav = isRenderable(topNav);@@ -781,6 +901,9 @@ export function AppShell({// (`component:SideNav` FR6).const railRef = useRef<HTMLDivElement>(null);const mainRef = useRef<HTMLDivElement>(null);+ // Main's node goes to the glide above and to the overflow observation+ // that, under `fill`, makes main a keyboard stop.+ const mainRefs = useMergedRefs(mainRef, setMainNode);const backdropRef = useRef<HTMLDivElement>(null);const contentLayout = useAnimatedLayout({containerRef: shellRef});const pendingContentRef = useRef<{@@ -949,18 +1072,115 @@ export function AppShell({// Build main content// =========================================================================const shouldElevateWithCorner = isElevated && hasTopNav && showSideNavInline;+ // While main is a keyboard stop, a Tab keydown anywhere in the document+ // (capture, so Shift+Tab from the page start counts too) marks the next+ // focus move, and so does the window's focus event for keyboard focus that+ // enters the document from outside (Tab or Shift+Tab from the page+ // embedding this one), where the browser's own `:focus-visible` then tells+ // a key from a pointer. A mark counts only once its event's dispatch has+ // finished uncancelled (`eventPhase === 0`): the browser's own focus move+ // follows that dispatch in the same task, while a focus() a page's handler+ // calls during it is programmatic and draws no ring (FR4). The marks expire+ // on a zero-delay timer, so a cancelled Tab, a Tab out of the document or a+ // window focus with nothing focused leaves nothing for a later focus().+ useEffect(() => {+ if (!isMainScrollRegion) {+ return;+ }+ let tabKeydown: KeyboardEvent | null = null;+ let windowFocus: FocusEvent | null = null;+ let expiry: ReturnType<typeof setTimeout> | undefined;+ const expireMarks = () => {+ clearTimeout(expiry);+ expiry = setTimeout(() => {+ tabKeydown = null;+ windowFocus = null;+ }, 0);+ };+ const onKeyDown = (event: KeyboardEvent) => {+ tabKeydown = event.key === 'Tab' ? event : null;+ windowFocus = null;+ expireMarks();+ };+ const onPointerDown = () => {+ tabKeydown = null;+ windowFocus = null;+ };+ const onWindowFocus = (event: FocusEvent) => {+ windowFocus = event;+ expireMarks();+ };+ const onFocusIn = (event: FocusEvent) => {+ // Still dispatching: this focus move is a handler's focus(), so it+ // reads no mark and leaves the mark for the browser's own move.+ const tabDone = tabKeydown != null && tabKeydown.eventPhase === 0;+ const focusDone = windowFocus != null && windowFocus.eventPhase === 0;+ const arrivedByTab = tabDone && tabKeydown?.defaultPrevented === false;+ const enteredDocument = focusDone;+ if (tabDone) {+ tabKeydown = null;+ }+ if (focusDone) {+ windowFocus = null;+ }+ const main = mainNodeRef.current;+ const isMain = event.target != null && event.target === main;+ if (isMainAwayRef.current) {+ // Focus comes back after a window or tab switch (main keeps the ring+ // it had), or lands elsewhere (main's ring is over).+ isMainAwayRef.current = false;+ if (isMain && !arrivedByTab) {+ return;+ }+ if (!isMain) {+ setIsTabFocus(false);+ return;+ }+ }+ if (isMain) {+ setIsTabFocus(+ arrivedByTab || (enteredDocument && main.matches(':focus-visible')),+ );+ }+ };+ document.addEventListener('keydown', onKeyDown, true);+ document.addEventListener('pointerdown', onPointerDown, true);+ document.addEventListener('focusin', onFocusIn, true);+ window.addEventListener('focus', onWindowFocus);+ return () => {+ document.removeEventListener('keydown', onKeyDown, true);+ document.removeEventListener('pointerdown', onPointerDown, true);+ document.removeEventListener('focusin', onFocusIn, true);+ window.removeEventListener('focus', onWindowFocus);+ clearTimeout(expiry);+ };+ }, [isMainScrollRegion]);++ // Tab focus on main draws the ring until main loses focus; programmatic+ // focus never does (FR4).+ const drawsMainFocusRing = isTabFocus;const mainInner = (<LayoutContent- ref={mainRef}+ ref={mainRefs}padding={contentPadding ?? 0}role="main"id={MAIN_CONTENT_ID}// 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.- tabIndex={-1}+ // A keyboard stop only while it scrolls overflowing content.+ tabIndex={isMainScrollRegion ? 0 : -1}isScrollable={isFill}- xstyle={[contentAreaStyle, styles.mainFocusTarget]}>+ onBlur={handleMainBlur}+ xstyle={[+ contentAreaStyle,+ drawsMainFocusRing &&+ shouldElevateWithCorner &&+ styles.mainElevatedCorner,+ drawsMainFocusRing+ ? [focusOutlineStyles.focusVisible, styles.mainScrollRegionInset]+ : styles.mainFocusTarget,+ ]}>{children}</LayoutContent>);diff --git a/packages/core/src/AppShell/__tests__/AppShellMainKeyboard.a11y.browser.spec.ts b/packages/core/src/AppShell/__tests__/AppShellMainKeyboard.a11y.browser.spec.tsnew file mode 100644index 0000000000..e5e6740116--- /dev/null+++ b/packages/core/src/AppShell/__tests__/AppShellMainKeyboard.a11y.browser.spec.ts@@ -0,0 +1,534 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file AppShellMainKeyboard.a11y.browser.spec.ts+ * @input The `Core/AppShell` stories in a built Storybook, and real Chromium+ * and WebKit keyboard input.+ * @output Browser evidence that the main region of a `fill` shell is reachable+ * from the keyboard while it scrolls overflowing content (AST-025 FR12): Tab+ * reaches it when nothing inside is focusable and Page Down then scrolls it,+ * and the stop it reaches is exposed as the main landmark (its role names it);+ * Tab entry moves on to its first link when there is one; keyboard focus+ * draws the focus ring inset, following the elevated surface's rounded+ * corner (also after Shift+Tab from the page start, and for as long as that+ * focus stays when the content shrinks to fit), and pointer focus, the skip+ * link's focus move and a script's focus() draw none; an+ * overflowing main rounds its corner only while its ring shows; a main+ * region that fits stays out of the tab order and keeps its square corner.+ * @position Cross-browser proof; jsdom has no layout, so AppShell.test.tsx can+ * only assert the tab stop against mocked geometry.+ */++import {chromium, expect, test, 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();+});++test.use({viewport: {width: 1280, height: 720}});++async function openStory(page: Page, story: string) {+ await page.goto(+ `${storybook.origin}/iframe.html?id=core-appshell--${story}&viewMode=story`,+ );+ await expect(page.getByRole('main')).toBeVisible();+}++/**+ * Presses Tab from the top of a freshly opened story until focus reaches+ * `isTarget`, or gives up after `limit` presses. Returns how many presses it+ * took, or -1.+ */+async function tabUntil(+ page: Page,+ isTarget: () => boolean,+ limit = 60,+): Promise<number> {+ for (let presses = 1; presses <= limit; presses += 1) {+ await page.keyboard.press('Tab');+ if (await page.evaluate(isTarget)) {+ return presses;+ }+ }+ return -1;+}++test('Tab reaches an overflowing main region with nothing focusable in it, and Page Down scrolls it', async ({+ page,+}) => {+ await openStory(page, 'long-content');+ const main = page.getByRole('main');+ await expect(main).toHaveAttribute('tabindex', '0');++ const presses = await tabUntil(+ page,+ () => document.activeElement?.getAttribute('role') === 'main',+ );+ expect(presses).toBeGreaterThan(0);++ await page.keyboard.press('PageDown');+ await expect+ .poll(async () => main.evaluate(element => element.scrollTop))+ .toBeGreaterThan(100);+});++test('Tab onto an overflowing main with no name of its own exposes the main landmark', async ({+ page,+ browserName,+}) => {+ await openStory(page, 'long-content');+ const presses = await tabUntil(+ page,+ () => document.activeElement?.getAttribute('role') === 'main',+ );+ expect(presses).toBeGreaterThan(0);++ // The stop has no name of its own: its role, the main landmark, is what a+ // screen reader announces (AST-025 FR12 lets the single main rely on it).+ const focused = page.locator(':focus');+ await expect(focused).toHaveRole('main');+ await expect(focused).toHaveAccessibleName('');+ if (browserName !== 'chromium') {+ return;+ }+ // Chromium's own accessibility tree, the one screen readers read: the+ // focused element's node is the main landmark, exposed rather than ignored.+ const cdp = await page.context().newCDPSession(page);+ await cdp.send('Accessibility.enable');+ const {result} = await cdp.send('Runtime.evaluate', {+ expression: 'document.activeElement',+ });+ const {node} = await cdp.send('DOM.describeNode', {+ objectId: result.objectId,+ });+ const {nodes} = await cdp.send('Accessibility.getPartialAXTree', {+ backendNodeId: node.backendNodeId,+ fetchRelatives: false,+ });+ await cdp.detach();+ expect(+ nodes.map(axNode => ({+ role: axNode.role?.value,+ name: axNode.name?.value ?? '',+ ignored: axNode.ignored,+ focused: axNode.properties?.some(+ property =>+ property.name === 'focused' && property.value.value === true,+ ),+ })),+ ).toEqual([{role: 'main', name: '', ignored: false, focused: true}]);+});++test('Tab entry moves on to the first link of an overflowing main region, and Shift+Tab skips the region', async ({+ page,+}) => {+ await openStory(page, 'long-content');+ const toMain = await tabUntil(+ page,+ () => document.activeElement?.getAttribute('role') === 'main',+ );+ expect(toMain).toBeGreaterThan(0);++ // A fresh load, so Tab starts from the top again.+ await openStory(page, 'long-content');+ await page.getByRole('main').evaluate(main => {+ const link = document.createElement('a');+ link.href = '#details';+ link.textContent = 'Details';+ main.prepend(link);+ });+ // The press that entered main now lands on its first link: no extra stop.+ const toLink = await tabUntil(+ page,+ () => document.activeElement?.textContent === 'Details',+ );+ expect(toLink).toBe(toMain);++ await page.keyboard.press('Shift+Tab');+ expect(+ await page.evaluate(() => document.activeElement?.getAttribute('role')),+ ).not.toBe('main');+});++test('keyboard focus draws the focus ring inside the overflowing main region, and pointer focus draws none', async ({+ page,+}) => {+ await openStory(page, 'long-content');+ const main = page.getByRole('main');+ const presses = await tabUntil(+ page,+ () => document.activeElement?.getAttribute('role') === 'main',+ );+ expect(presses).toBeGreaterThan(0);+ const ring = await main.evaluate(element => {+ const style = getComputedStyle(element);+ return {+ style: style.outlineStyle,+ width: Number.parseFloat(style.outlineWidth),+ offset: Number.parseFloat(style.outlineOffset),+ };+ });+ expect(ring.style).not.toBe('none');+ expect(ring.width).toBeGreaterThan(0);+ // Inset by its own width, so the shell's clipping around main cannot cut it.+ expect(ring.offset).toBeCloseTo(-ring.width, 1);+ // The ring follows the shape of the surface main sits on: with a top nav+ // and an inline side nav, the elevated surface rounds its top-start corner.+ const corners = await main.evaluate(element => {+ const surface = element.parentElement?.firstElementChild;+ if (surface == null || surface === element) {+ throw new Error('no elevated surface behind main');+ }+ return {+ main: getComputedStyle(element).borderTopLeftRadius,+ surface: getComputedStyle(surface).borderTopLeftRadius,+ };+ });+ expect(Number.parseFloat(corners.surface)).toBeGreaterThan(0);+ expect(corners.main).toBe(corners.surface);++ // A pointer press inside main focuses it too, without a ring.+ await openStory(page, 'long-content');+ const box = await main.boundingBox();+ if (box == null) {+ throw new Error('no main box');+ }+ await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2);+ expect(+ await page.evaluate(() => document.activeElement?.getAttribute('role')),+ ).toBe('main');+ expect(+ await main.evaluate(element => getComputedStyle(element).outlineStyle),+ ).toBe('none');+});++test('the skip link moves focus to an overflowing main without drawing the ring', async ({+ page,+}) => {+ await openStory(page, 'long-content');+ const main = page.getByRole('main');+ const presses = await tabUntil(+ page,+ () =>+ document.activeElement?.getAttribute('data-testid') === 'skip-to-content',+ );+ expect(presses).toBeGreaterThan(0);++ await page.keyboard.press('Enter');+ expect(+ await page.evaluate(() => document.activeElement?.getAttribute('role')),+ ).toBe('main');+ expect(+ await main.evaluate(element => getComputedStyle(element).outlineStyle),+ ).toBe('none');+});++test("a script's focus on an overflowing main after keyboard input draws no ring", async ({+ page,+}) => {+ await openStory(page, 'long-content');+ const main = page.getByRole('main');+ await page.keyboard.press('Tab');+ await main.evaluate(element => element.focus());++ expect(+ await page.evaluate(() => document.activeElement?.getAttribute('role')),+ ).toBe('main');+ expect(+ await main.evaluate(element => getComputedStyle(element).outlineStyle),+ ).toBe('none');+ expect(+ await main.evaluate(+ element => getComputedStyle(element).borderTopLeftRadius,+ ),+ ).toBe('0px');+});++test('Shift+Tab from the start of the page reaches an overflowing main with its ring', async ({+ page,+}) => {+ await openStory(page, 'long-content');+ const main = page.getByRole('main');+ let presses = -1;+ for (let press = 1; press <= 60; press += 1) {+ await page.keyboard.press('Shift+Tab');+ if (+ await page.evaluate(+ () => document.activeElement?.getAttribute('role') === 'main',+ )+ ) {+ presses = press;+ break;+ }+ }+ expect(presses).toBeGreaterThan(0);+ expect(+ await main.evaluate(element => getComputedStyle(element).outlineStyle),+ ).toBe('solid');+});++test('a Tab-focused main keeps its ring when its content shrinks to fit', async ({+ page,+}) => {+ await openStory(page, 'long-content');+ const main = page.getByRole('main');+ const presses = await tabUntil(+ page,+ () => document.activeElement?.getAttribute('role') === 'main',+ );+ expect(presses).toBeGreaterThan(0);+ expect(+ await main.evaluate(element => getComputedStyle(element).outlineStyle),+ ).toBe('solid');++ await main.evaluate(element => {+ for (const child of element.children) {+ (child as HTMLElement).style.display = 'none';+ }+ });+ await expect(main).toHaveAttribute('tabindex', '-1');+ expect(+ await page.evaluate(() => document.activeElement?.getAttribute('role')),+ ).toBe('main');+ expect(+ await main.evaluate(element => getComputedStyle(element).outlineStyle),+ ).toBe('solid');+});++test('keyboard focus entering from the embedding page draws the ring on main', async ({+ page,+}) => {+ // Shift+Tab from a control after the frame: the key goes to the embedding+ // page, so main's document sees focus arrive with no Tab keydown of its own.+ await page.setContent(+ `<iframe title="App" style="width: 1280px; height: 720px; border: 0" src="${storybook.origin}/iframe.html?id=core-appshell--long-content&viewMode=story"></iframe><button>After the frame</button>`,+ );+ const frame = page.frameLocator('iframe');+ const main = frame.getByRole('main');+ await expect(main).toBeVisible();+ await expect(main).toHaveAttribute('tabindex', '0');++ await page.getByRole('button', {name: 'After the frame'}).focus();+ await page.keyboard.press('Shift+Tab');++ await expect+ .poll(async () =>+ main.evaluate(element => element.ownerDocument.activeElement === element),+ )+ .toBe(true);+ expect(+ await main.evaluate(element => getComputedStyle(element).outlineStyle),+ ).toBe('solid');+});++test("a script's focus on main after the embedding page focuses the frame draws no ring", async ({+ page,+}) => {+ // The window gains focus with nothing focused in it; a later focus() is+ // programmatic (FR4), not the focus move that entered the document.+ await page.setContent(+ `<button>Before the frame</button><iframe title="App" style="width: 1280px; height: 720px; border: 0" src="${storybook.origin}/iframe.html?id=core-appshell--long-content&viewMode=story"></iframe>`,+ );+ const main = page.frameLocator('iframe').getByRole('main');+ await expect(main).toHaveAttribute('tabindex', '0');+ await page.getByRole('button', {name: 'Before the frame'}).focus();+ await page.evaluate(() => {+ document.querySelector('iframe')?.contentWindow?.focus();+ });+ await page.waitForTimeout(50);++ await main.evaluate(element => (element as HTMLElement).focus());++ await expect+ .poll(async () =>+ main.evaluate(element => element.ownerDocument.activeElement === element),+ )+ .toBe(true);+ expect(+ await main.evaluate(element => getComputedStyle(element).outlineStyle),+ ).not.toBe('solid');+});++test("a script's focus on main inside a Tab keydown handler draws no ring", async ({+ page,+}) => {+ await openStory(page, 'long-content');+ const main = page.getByRole('main');+ await expect(main).toHaveAttribute('tabindex', '0');+ // A page's own Tab handler moves focus itself: programmatic focus (FR4),+ // even though a Tab key is down.+ await page.evaluate(() => {+ document.addEventListener('keydown', event => {+ if (event.key === 'Tab') {+ event.preventDefault();+ document.querySelector<HTMLElement>('[role="main"]')?.focus();+ }+ });+ });++ await page.keyboard.press('Tab');++ await expect+ .poll(async () =>+ page.evaluate(() => document.activeElement?.getAttribute('role')),+ )+ .toBe('main');+ expect(+ await main.evaluate(element => getComputedStyle(element).outlineStyle),+ ).not.toBe('solid');+});++test("a script's focus on main inside the frame window's own focus handler draws no ring", async ({+ page,+}) => {+ await page.setContent(+ `<button>Before the frame</button><iframe title="App" style="width: 1280px; height: 720px; border: 0" src="${storybook.origin}/iframe.html?id=core-appshell--long-content&viewMode=story"></iframe>`,+ );+ const main = page.frameLocator('iframe').getByRole('main');+ await expect(main).toHaveAttribute('tabindex', '0');+ const frame = page.frame({url: /iframe\.html/});+ expect(frame).not.toBeNull();+ await frame?.evaluate(() => {+ window.addEventListener('focus', () => {+ document.querySelector<HTMLElement>('[role="main"]')?.focus();+ });+ });+ await page.getByRole('button', {name: 'Before the frame'}).focus();++ await page.evaluate(() => {+ document.querySelector('iframe')?.contentWindow?.focus();+ });++ await expect+ .poll(async () =>+ main.evaluate(element => element.ownerDocument.activeElement === element),+ )+ .toBe(true);+ expect(+ await main.evaluate(element => getComputedStyle(element).outlineStyle),+ ).not.toBe('solid');+});++test('pointer focus entering from the embedding page draws no ring on main', async ({+ page,+}) => {+ await page.setContent(+ `<button>Before the frame</button><iframe title="App" style="width: 1280px; height: 720px; border: 0" src="${storybook.origin}/iframe.html?id=core-appshell--long-content&viewMode=story"></iframe>`,+ );+ const main = page.frameLocator('iframe').getByRole('main');+ await expect(main).toHaveAttribute('tabindex', '0');+ await page.getByRole('button', {name: 'Before the frame'}).focus();++ await main.click({position: {x: 40, y: 40}});++ await expect+ .poll(async () =>+ main.evaluate(element => element.ownerDocument.activeElement === element),+ )+ .toBe(true);+ expect(+ await main.evaluate(element => getComputedStyle(element).outlineStyle),+ ).not.toBe('solid');+});++test('a Tab-focused main keeps its ring after a window or tab switch', async ({+ browserName,+}) => {+ test.skip(+ browserName !== 'chromium',+ 'a real window switch needs full Chromium (launched below)',+ );+ // The headless shell never takes focus away from a page; full Chromium in+ // its headless mode does once focus emulation is off, firing what a real+ // switch fires: blur and focusout on main while main stays the active+ // element, then focus and focusin on return.+ const browser = await chromium.launch({channel: 'chromium'});+ try {+ const context = await browser.newContext({+ viewport: {width: 1280, height: 720},+ });+ const page = await context.newPage();+ await openStory(page, 'long-content');+ const main = page.getByRole('main');+ const presses = await tabUntil(+ page,+ () => document.activeElement?.getAttribute('role') === 'main',+ );+ expect(presses).toBeGreaterThan(0);+ expect(+ await main.evaluate(element => getComputedStyle(element).outlineStyle),+ ).toBe('solid');++ const cdp = await context.newCDPSession(page);+ await cdp.send('Emulation.setFocusEmulationEnabled', {enabled: false});+ const other = await context.newPage();+ await other.bringToFront();+ await expect+ .poll(async () => page.evaluate(() => document.hasFocus()))+ .toBe(false);+ await page.bringToFront();+ await expect+ .poll(async () => page.evaluate(() => document.hasFocus()))+ .toBe(true);++ expect(+ await page.evaluate(() => document.activeElement?.getAttribute('role')),+ ).toBe('main');+ expect(+ await main.evaluate(element => getComputedStyle(element).outlineStyle),+ ).toBe('solid');++ // A real focus move still ends the ring.+ await page.keyboard.press('Shift+Tab');+ expect(+ await main.evaluate(element => getComputedStyle(element).outlineStyle),+ ).not.toBe('solid');+ } finally {+ await browser.close();+ }+});++test('an overflowing main rounds its corner only while its ring shows', async ({+ page,+}) => {+ await openStory(page, 'long-content');+ const main = page.getByRole('main');+ await expect(main).toHaveAttribute('tabindex', '0');+ expect(+ await main.evaluate(+ element => getComputedStyle(element).borderTopLeftRadius,+ ),+ ).toBe('0px');+});++test('a main region that fits stays out of the tab order and keeps its square corner', async ({+ page,+}) => {+ await openStory(page, 'playground');+ const main = page.getByRole('main');+ await expect(main).toHaveAttribute('tabindex', '-1');+ // The rounded corner only shapes the ring of a main that is a stop.+ expect(+ await main.evaluate(+ element => getComputedStyle(element).borderTopLeftRadius,+ ),+ ).toBe('0px');++ const presses = await tabUntil(+ page,+ () => document.activeElement?.getAttribute('role') === 'main',+ 40,+ );+ expect(presses).toBe(-1);+});diff --git a/packages/core/src/AppShell/observeMainOverflow.test.ts b/packages/core/src/AppShell/observeMainOverflow.test.tsnew file mode 100644index 0000000000..f25fe6a1cc--- /dev/null+++ b/packages/core/src/AppShell/observeMainOverflow.test.ts@@ -0,0 +1,173 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file observeMainOverflow.test.ts+ * @input observeMainOverflow on a main element with mocked geometry, a+ * recorded resize observer, and frames run by hand+ * @output Regression coverage for measuring a scroll container that holds its+ * content as direct children: the children's sizes, the children coming and+ * going, unknown geometry, and stopping+ * @position Unit contract of AppShell's internal overflow observer;+ * AppShell.test.tsx covers main becoming a keyboard stop+ */++import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';+import {observeMainOverflow} from './observeMainOverflow';++const observed = vi.hoisted(+ () => new Map<Element, {callback: () => void; stopped: boolean}>(),+);++vi.mock('../utils/sharedResizeObserver', () => ({+ observeResize: (element: Element, callback: () => void) => {+ const entry = {callback, stopped: false};+ observed.set(element, entry);+ return () => {+ entry.stopped = true;+ };+ },+}));++function setGeometry(element: HTMLElement, client: number, scroll: number) {+ for (const [key, value] of [+ ['clientWidth', 800],+ ['scrollWidth', 800],+ ['clientHeight', client],+ ['scrollHeight', scroll],+ ['scrollTop', 0],+ ['scrollLeft', 0],+ ] as const) {+ Object.defineProperty(element, key, {+ configurable: true,+ value,+ writable: true,+ });+ }+}++describe('observeMainOverflow', () => {+ let frames: FrameRequestCallback[];+ let main: HTMLElement;+ let stop: (() => void) | null;++ beforeEach(() => {+ observed.clear();+ frames = [];+ stop = null;+ vi.stubGlobal(+ 'requestAnimationFrame',+ vi.fn((callback: FrameRequestCallback) => {+ frames.push(callback);+ return frames.length;+ }),+ );+ vi.stubGlobal('cancelAnimationFrame', vi.fn());+ // jsdom computes no overflow longhands; main scrolls (`overflow: auto`).+ const nativeGetComputedStyle = window.getComputedStyle.bind(window);+ vi.spyOn(window, 'getComputedStyle').mockImplementation(element => {+ const computed = nativeGetComputedStyle(element);+ return new Proxy(computed, {+ // eslint-disable-next-line @typescript-eslint/promise-function-async -- Proxy traps must remain synchronous+ get(target, property) {+ if (property === 'overflowX' || property === 'overflowY') {+ return 'auto';+ }+ return Reflect.get(target, property, target);+ },+ });+ });+ main = document.createElement('div');+ main.innerHTML = '<p id="first">First</p><p id="second">Second</p>';+ document.body.append(main);+ setGeometry(main, 300, 300);+ });++ afterEach(() => {+ stop?.();+ main.remove();+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+ });++ function runFrames() {+ const pending = frames.splice(0);+ pending.forEach(callback => callback(performance.now()));+ }++ it('reports the first measurement at once, then only changes', () => {+ const onChange = vi.fn();+ stop = observeMainOverflow(main, onChange);+ expect(onChange.mock.calls).toEqual([[false]]);++ window.dispatchEvent(new Event('resize'));+ runFrames();+ expect(onChange.mock.calls).toEqual([[false]]);++ setGeometry(main, 300, 1200);+ window.dispatchEvent(new Event('resize'));+ runFrames();+ expect(onChange.mock.calls).toEqual([[false], [true]]);+ });++ it('watches each direct child, so content growing inside main is measured', () => {+ const onChange = vi.fn();+ stop = observeMainOverflow(main, onChange);+ const second = main.querySelector('#second');+ expect(observed.has(main)).toBe(true);+ expect(observed.has(main.querySelector('#first') as Element)).toBe(true);+ expect(second != null && observed.has(second)).toBe(true);++ // The child grows; main keeps its own size.+ setGeometry(main, 300, 1200);+ observed.get(second as Element)?.callback();+ runFrames();++ expect(onChange).toHaveBeenLastCalledWith(true);+ });++ it('follows the children as they come and go', async () => {+ stop = observeMainOverflow(main, vi.fn());+ const first = main.querySelector('#first') as Element;++ const replacement = document.createElement('section');+ first.replaceWith(replacement);+ // The mutation observer reports the change asynchronously.+ await Promise.resolve();++ expect(observed.get(first)?.stopped).toBe(true);+ expect(observed.has(replacement)).toBe(true);+ });++ it('keeps the last answer while main cannot be measured', () => {+ const onChange = vi.fn();+ setGeometry(main, 300, 1200);+ stop = observeMainOverflow(main, onChange);+ expect(onChange.mock.calls).toEqual([[true]]);++ // A hidden or zero-size main is unknown, not fitting.+ setGeometry(main, 0, 0);+ window.dispatchEvent(new Event('resize'));+ runFrames();+ expect(onChange.mock.calls).toEqual([[true]]);+ });++ it('stops every observer and listener, and measures nothing after', () => {+ const onChange = vi.fn();+ stop = observeMainOverflow(main, onChange);+ const children = Array.from(main.children);+ window.dispatchEvent(new Event('resize'));+ stop();+ stop = null;++ expect(cancelAnimationFrame).toHaveBeenCalled();+ expect(observed.get(main)?.stopped).toBe(true);+ for (const child of children) {+ expect(observed.get(child)?.stopped).toBe(true);+ }+ setGeometry(main, 300, 1200);+ window.dispatchEvent(new Event('resize'));+ runFrames();+ expect(frames).toEqual([]);+ expect(onChange.mock.calls).toEqual([[false]]);+ });+});diff --git a/packages/core/src/AppShell/observeMainOverflow.ts b/packages/core/src/AppShell/observeMainOverflow.tsnew file mode 100644index 0000000000..97ed467044--- /dev/null+++ b/packages/core/src/AppShell/observeMainOverflow.ts@@ -0,0 +1,143 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file observeMainOverflow.ts+ * @input AppShell's main region under `height="fill"`: its own scroll+ * container, holding its content as direct children with no wrapper+ * @output observeMainOverflow(main, onChange): reports whether main's content+ * overflows it on either axis, once at the start and on every change, and+ * returns the function that stops observing+ * @position Internal to AppShell and never exported. AppShell makes main a+ * keyboard stop only while it overflows (`spec:AST-025` FR12,+ * `component:AppShell` FR4 and PR1). Main has no inner content box, so its+ * content grows inside it without resizing it: its direct children's sizes+ * are watched instead.+ *+ * SYNC: When modified, update:+ * - /packages/core/src/AppShell/AppShell.tsx+ * - /packages/core/src/AppShell/observeMainOverflow.test.ts+ */++import {+ getLogicalAxisMapping,+ measureLogicalScrollAxis,+} from '../hooks/scrollGeometry';+import {observeMutations} from '../utils/sharedMutationObserver';+import {observeResize} from '../utils/sharedResizeObserver';++/**+ * Main's content: layout attributes, text and children, all the way down.+ * One shared observer serves every registration with these options.+ */+const CONTENT_MUTATIONS: MutationObserverInit = {+ attributes: true,+ attributeFilter: ['class', 'dir', 'hidden', 'style'],+ characterData: true,+ childList: true,+ subtree: true,+};++/**+ * Calls `onChange` with whether `main`'s content overflows it on either axis:+ * once with the first measurement, then whenever the answer changes. Signals+ * coalesce into one measurement per frame. A hidden, disconnected or+ * zero-size main is unknown rather than fitting: the last answer stands until+ * a later signal measures it.+ */+export function observeMainOverflow(+ main: HTMLElement,+ onChange: (overflows: boolean) => void,+): () => void {+ let isActive = true;+ let frame: number | null = null;+ let overflows: boolean | null = null;++ const measure = () => {+ frame = null;+ if (!isActive) {+ return;+ }+ const computedStyle = getComputedStyle(main);+ const mapping = getLogicalAxisMapping(+ computedStyle.writingMode,+ computedStyle.direction,+ );+ const inline = measureLogicalScrollAxis(main, 'inline', mapping);+ const block = measureLogicalScrollAxis(main, 'block', mapping);+ if (inline == null || block == null) {+ return;+ }+ const next = inline.isScrollable || block.isScrollable;+ if (next !== overflows) {+ overflows = next;+ onChange(next);+ }+ };++ const scheduleMeasure = () => {+ if (isActive && frame == null) {+ frame = window.requestAnimationFrame(measure);+ }+ };++ // Main keeps its size while its content grows; its children do not. Each+ // direct child's size is watched, following the children as they change.+ const childObservers = new Map<Element, () => void>();+ const syncChildObservers = () => {+ const children = new Set(Array.from(main.children));+ for (const [child, stop] of childObservers) {+ if (!children.has(child)) {+ stop();+ childObservers.delete(child);+ }+ }+ for (const child of children) {+ if (!childObservers.has(child)) {+ childObservers.set(child, observeResize(child, scheduleMeasure));+ }+ }+ };+ const onContentChange = () => {+ syncChildObservers();+ scheduleMeasure();+ };++ measure();+ syncChildObservers();+ const stopObservingMain = observeResize(main, scheduleMeasure);+ const stopObservingContent = observeMutations(+ main,+ CONTENT_MUTATIONS,+ onContentChange,+ );+ window.addEventListener('resize', scheduleMeasure);+ window.visualViewport?.addEventListener('resize', scheduleMeasure);+ main.addEventListener('load', scheduleMeasure, true);+ main.addEventListener('transitionend', scheduleMeasure);+ main.addEventListener('animationend', scheduleMeasure);+ const fonts = document.fonts;+ fonts?.addEventListener?.('loadingdone', scheduleMeasure);+ void fonts?.ready.then(scheduleMeasure);++ return () => {+ isActive = false;+ if (frame != null) {+ window.cancelAnimationFrame(frame);+ frame = null;+ }+ stopObservingMain();+ stopObservingContent();+ for (const stop of childObservers.values()) {+ stop();+ }+ childObservers.clear();+ window.removeEventListener('resize', scheduleMeasure);+ window.visualViewport?.removeEventListener('resize', scheduleMeasure);+ main.removeEventListener('load', scheduleMeasure, true);+ main.removeEventListener('transitionend', scheduleMeasure);+ main.removeEventListener('animationend', scheduleMeasure);+ fonts?.removeEventListener?.('loadingdone', scheduleMeasure);+ };+}diff --git a/packages/core/src/hooks/scrollKeyboardDelegation.test.ts b/packages/core/src/hooks/scrollKeyboardDelegation.test.tsindex c2f345911e..f55149433e 100644--- a/packages/core/src/hooks/scrollKeyboardDelegation.test.ts+++ b/packages/core/src/hooks/scrollKeyboardDelegation.test.ts@@ -153,3 +153,36 @@ describe('scroll keyboard delegation', () => {expect(document.activeElement).toBe(viewport);});});++describe('a viewport that is its own content box', () => {+ function attachToItself(markup: string) {+ detach?.();+ viewport.innerHTML = markup;+ const query = viewport.querySelectorAll.bind(viewport);+ vi.spyOn(viewport, 'querySelectorAll').mockImplementation(selector => {+ const result = query(selector);+ return selector === FOCUSABLE_SELECTOR+ ? ([...result].sort((a, b) =>+ a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING+ ? -1+ : 1,+ ) as unknown as NodeListOf<Element>)+ : result;+ });+ detach = attachScrollKeyboardDelegation(viewport, viewport);+ }++ it('delegates Tab entry to its first link or button, never to itself', () => {+ attachToItself(+ '<p>Text</p><a href="#first">First link</a><button>Later</button>',+ );+ enter();+ expect(document.activeElement).toBe(viewport.querySelector('a'));+ });++ it('keeps the stop on itself when nothing inside is focusable', () => {+ attachToItself('<p>Only text</p>');+ enter();+ expect(document.activeElement).toBe(viewport);+ });+});diff --git a/packages/core/src/hooks/scrollKeyboardDelegation.ts b/packages/core/src/hooks/scrollKeyboardDelegation.tsindex 1052ee80f5..cb31bc5f49 100644--- a/packages/core/src/hooks/scrollKeyboardDelegation.ts+++ b/packages/core/src/hooks/scrollKeyboardDelegation.ts@@ -2,9 +2,11 @@/*** @file scrollKeyboardDelegation.ts- * @input A named, overflowing viewport and its real content box+ * @input A named, overflowing viewport and its real content box (the viewport+ * itself when it has no separate content box)* @output Focus-time delegation with native forward and reverse Tab traversal- * @position Private useScrollableArea keyboard behavior; no DOM observers or scrolling+ * @position Private keyboard behavior of useScrollableArea and of AppShell's main+ * region; no DOM observers or scrolling*/import {FOCUSABLE_SELECTOR} from './focusableSelector';@@ -58,8 +60,12 @@ function firstDelegationTarget(content: HTMLElement,): HTMLElement | null {const candidates = content.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR);+ // A viewport that is its own content box is the stop being entered, never+ // the target it delegates to.let first =- content.matches(FOCUSABLE_SELECTOR) && isSequential(content)+ content !== viewport &&+ content.matches(FOCUSABLE_SELECTOR) &&+ isSequential(content)? content: null;for (const candidate of candidates) {diff --git a/packages/core/src/utils/sharedMutationObserver.test.ts b/packages/core/src/utils/sharedMutationObserver.test.tsindex 9f8a4748d8..9809db2ad2 100644--- a/packages/core/src/utils/sharedMutationObserver.test.ts+++ b/packages/core/src/utils/sharedMutationObserver.test.ts@@ -1,7 +1,7 @@// Copyright (c) Meta Platforms, Inc. and affiliates.import {describe, it, expect, vi} from 'vitest';-import {observeContent} from './sharedMutationObserver';+import {observeContent, observeMutations} from './sharedMutationObserver';const flush = async () => new Promise(resolve => setTimeout(resolve, 0));@@ -51,3 +51,56 @@ describe('observeContent', () => {unsubscribeLive();});});++describe('observeMutations', () => {+ it('shares one observer across registrations with the same options', async () => {+ const Native = globalThis.MutationObserver;+ let constructed = 0;+ vi.stubGlobal(+ 'MutationObserver',+ class extends Native {+ constructor(callback: MutationCallback) {+ super(callback);+ constructed += 1;+ }+ },+ );+ const options = {attributes: true, attributeFilter: ['dir']};+ const first = document.createElement('div');+ const second = document.createElement('div');+ const firstCallback = vi.fn();+ const secondCallback = vi.fn();+ const stops = [+ observeMutations(first, options, firstCallback),+ observeMutations(second, {...options}, secondCallback),+ ];++ first.dir = 'rtl';+ await flush();++ expect(constructed).toBe(1);+ expect(firstCallback).toHaveBeenCalledTimes(1);+ expect(secondCallback).not.toHaveBeenCalled();+ stops.forEach(stop => stop());+ vi.unstubAllGlobals();+ });++ it('reports a descendant only to a subtree registration', async () => {+ const outer = document.createElement('div');+ const inner = document.createElement('span');+ outer.append(inner);+ const self = vi.fn();+ const subtree = vi.fn();+ const stops = [+ observeMutations(outer, {attributes: true}, self),+ observeMutations(outer, {attributes: true, subtree: true}, subtree),+ ];++ inner.className = 'changed';+ await flush();++ expect(self).not.toHaveBeenCalled();+ expect(subtree).toHaveBeenCalledTimes(1);+ stops.forEach(stop => stop());+ });+});diff --git a/packages/core/src/utils/sharedMutationObserver.ts b/packages/core/src/utils/sharedMutationObserver.tsindex c8a9555a50..90163384d0 100644--- a/packages/core/src/utils/sharedMutationObserver.ts+++ b/packages/core/src/utils/sharedMutationObserver.ts@@ -5,58 +5,105 @@/*** @file sharedMutationObserver.ts* @input MutationObserver API- * @output Exports observeContent for shared content-change observation- * @position Internal utility; consumed by useTruncation. The content-change- * counterpart of sharedResizeObserver: one observer for every element, so a- * repeated cell or row path does not create one observer per instance.+ * @output Exports observeMutations (one shared observer per set of options)+ * and observeContent, its text-and-children form+ * @position Internal utility; consumed by useTruncation, hitArea and AppShell's+ * main-overflow observer. The mutation counterpart of sharedResizeObserver:+ * one observer for every element observed with the same options, so a+ * repeated cell, row or region does not create one observer per instance.*/-type ContentCallback = () => void;+type MutationCallback = () => void;-const OPTIONS: MutationObserverInit = {+const CONTENT_OPTIONS: MutationObserverInit = {characterData: true,childList: true,subtree: true,};-let observer: MutationObserver | null = null;-const callbacks = new Map<Node, Set<ContentCallback>>();+interface SharedObserver {+ readonly observer: MutationObserver;+ readonly callbacks: Map<Node, Set<MutationCallback>>;+}++/**+ * One observer per distinct set of options: an observer holds one set of+ * options per node, so registrations that need different options cannot+ * share one.+ */+const observers = new Map<string, SharedObserver>();++function optionsKey(options: MutationObserverInit): string {+ return JSON.stringify([+ options.attributes === true,+ options.attributeFilter == null+ ? null+ : [...options.attributeFilter].sort(),+ options.characterData === true,+ options.childList === true,+ options.subtree === true,+ ]);+}-function dispatch(records: MutationRecord[]): void {- // One call per callback per batch, however many records it received. A- // record's target can be any descendant, so walk up to the observed roots.- const pending = new Set<ContentCallback>();- for (const record of records) {- for (let node: Node | null = record.target; node; node = node.parentNode) {- callbacks.get(node)?.forEach(callback => pending.add(callback));+function createSharedObserver(options: MutationObserverInit): SharedObserver {+ const callbacks = new Map<Node, Set<MutationCallback>>();+ const isSubtree = options.subtree === true;+ const observer = new MutationObserver(records => {+ // One call per callback per batch, however many records it received.+ // With `subtree`, a record's target can be any descendant, so walk up to+ // the observed roots; without it, the target is the observed node.+ const pending = new Set<MutationCallback>();+ for (const record of records) {+ if (!isSubtree) {+ callbacks+ .get(record.target)+ ?.forEach(callback => pending.add(callback));+ continue;+ }+ for (+ let node: Node | null = record.target;+ node;+ node = node.parentNode+ ) {+ callbacks.get(node)?.forEach(callback => pending.add(callback));+ }}- }- pending.forEach(callback => callback());+ pending.forEach(callback => callback());+ });+ return {observer, callbacks};}/**- * Call `callback` when the element's text or children change (including- * descendants). Returns an unsubscribe that removes only this registration.+ * Call `callback` for mutations of `element` matching `options`, through the+ * one observer shared by every registration with the same options. Returns an+ * unsubscribe that removes only this registration.** MutationObserver has no per-target unobserve, so a released element stays- * registered with the shared observer until no element remains; its records- * match no callback and are ignored. The observer disconnects and is released- * when the last registration goes.+ * registered with its shared observer until no element remains; its records+ * match no callback and are ignored. An observer disconnects and is released+ * when its last registration goes.*/-export function observeContent(- element: Element,- callback: ContentCallback,+export function observeMutations(+ element: Node,+ options: MutationObserverInit,+ callback: MutationCallback,): () => void {if (typeof MutationObserver === 'undefined') {return () => {};}- observer ??= new MutationObserver(dispatch);+ const key = optionsKey(options);+ let shared = observers.get(key);+ if (shared == null) {+ shared = createSharedObserver(options);+ observers.set(key, shared);+ }+ const {observer, callbacks} = shared;const existing = callbacks.get(element);if (existing) {existing.add(callback);} else {callbacks.set(element, new Set([callback]));- observer.observe(element, OPTIONS);+ observer.observe(element, options);}let isSubscribed = true;@@ -70,9 +117,20 @@ export function observeContent(if (targetCallbacks?.size === 0) {callbacks.delete(element);}- if (callbacks.size === 0 && observer) {+ if (callbacks.size === 0 && observers.get(key)?.observer === observer) {observer.disconnect();- observer = null;+ observers.delete(key);}};}++/**+ * Call `callback` when the element's text or children change (including+ * descendants). Returns an unsubscribe that removes only this registration.+ */+export function observeContent(+ element: Element,+ callback: MutationCallback,+): () => void {+ return observeMutations(element, CONTENT_OPTIONS, callback);+}