An open source design system that's fully customizable and agent ready
TypeScript
feat(core): add focus-time scroll keyboard delegation (#6301)
Jiun Shinbfee8a4a306c
diff --git a/.changeset/bottom-sheet-keyboard-scroll.md b/.changeset/bottom-sheet-keyboard-scroll.mdnew file mode 100644index 0000000000..9aef2b68b7--- /dev/null+++ b/.changeset/bottom-sheet-keyboard-scroll.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] Make overflowing BottomSheet text keyboard reachable with a named scroll-body tab stop. Add shared focus-time keyboard delegation to `useScrollableArea`: forward Tab may enter the first native link/button directly, while inputs, composite widgets, and nested scroll owners retain the viewport stop. Reverse traversal skips the delegated viewport; pointer/programmatic focus and content changes never trigger delegation. Sheet scroll containment now applies only while content overflows and uses the shared `contain` policy, which permits native edge feedback.++@jiunshinndiff --git a/apps/storybook/stories/BottomSheet.stories.tsx b/apps/storybook/stories/BottomSheet.stories.tsxindex 72f5f4d009..9245f75f14 100644--- a/apps/storybook/stories/BottomSheet.stories.tsx+++ b/apps/storybook/stories/BottomSheet.stories.tsx@@ -1,8 +1,18 @@// Copyright (c) Meta Platforms, Inc. and affiliates.+/**+ * @file BottomSheet.stories.tsx+ * @input BottomSheet, content primitives, and controlled story state+ * @output BottomSheet examples and native keyboard delegation browser fixtures+ * @position Storybook coverage for BottomSheet presentation and interaction+ */+import type {Meta, StoryObj} from '@storybook/react';-import {useState} from 'react';+import * as stylex from '@stylexjs/stylex';+import {expect, waitFor, within} from 'storybook/test';+import {useState, type ComponentProps} from 'react';import {BottomSheet} from '@astryxdesign/core/BottomSheet';+import {ScrollableArea} from '@astryxdesign/core/ScrollableArea';import {Button} from '@astryxdesign/core/Button';import {Divider} from '@astryxdesign/core/Divider';import {Heading} from '@astryxdesign/core/Heading';@@ -40,6 +50,75 @@ const meta: Meta<typeof BottomSheet> = {export default meta;type Story = StoryObj<typeof BottomSheet>;+type StandaloneBottomSheetStoryProps = Extract<+ ComponentProps<typeof BottomSheet>,+ {sheetId?: never}+>;++/** Keep this sheet open so the accessibility audit inspects its scroll body. */+export const TextOnly: Story = {+ args: {+ isOpen: true,+ label: 'Reading details',+ height: 'capped',+ children: (+ <Section>+ <VStack gap={4}>+ <Heading level={2}>Reading details</Heading>+ {Array.from({length: 16}, (_, index) => (+ <Text key={index}>+ Paragraph {index + 1}. This sheet contains plain text. Use Tab to+ reach the scrolling area, then Arrow Down or Page Down to read the+ remaining content. Escape closes the sheet.+ </Text>+ ))}+ </VStack>+ </Section>+ ),+ },+ render: args => {+ const standaloneArgs = args as StandaloneBottomSheetStoryProps;+ const [isOpen, setIsOpen] = useState(true);+ return (+ <BottomSheet+ {...standaloneArgs}+ isOpen={isOpen}+ onOpenChange={setIsOpen}+ />+ );+ },+ play: async ({canvasElement}) => {+ const body = within(canvasElement).getByRole('group', {+ name: 'Reading details',+ });+ await waitFor(() => {+ expect(body).toHaveAttribute('data-scrollable-block', 'true');+ expect(body).toHaveAttribute('tabindex', '0');+ });+ },+};++export const TextOnlyFitting: Story = {+ ...TextOnly,+ args: {+ ...TextOnly.args,+ label: 'Short details',+ children: (+ <Section>+ <Text>This content fits without a separate keyboard scroll stop.</Text>+ </Section>+ ),+ },+ play: async ({canvasElement}) => {+ const body = within(canvasElement).getByRole('group', {+ name: 'Short details',+ });+ await waitFor(() => {+ expect(body).not.toHaveAttribute('data-scrollable-block');+ expect(body).not.toHaveAttribute('tabindex');+ });+ },+};interface CommentFormValues {title: string;@@ -495,3 +574,122 @@ export const MobileKeyboard: Story = {);},};++const keyboardFixtureStyles = stylex.create({+ nestedViewport: {overflow: 'auto', height: 100},+ nestedContent: {height: 200},+});++/** Native content variants deliberately exercise the hook's delegation boundary. */+export const KeyboardDelegation: Story = {+ render: () => {+ const [variant, setVariant] = useState('button');+ const [isOpen, setIsOpen] = useState(true);+ const [hasScrim, setHasScrim] = useState(false);+ const action = <Button label="First action" onClick={() => {}} />;+ let first;+ switch (variant) {+ case 'text':+ first = <Text>Read the details below.</Text>;+ break;+ case 'link':+ first = <Button label="First link" href="#reading-end" />;+ break;+ case 'input':+ first = <TextInput label="First input" value="" onChange={() => {}} />;+ break;+ case 'nested':+ first = (+ <ScrollableArea label="Nested reading" height={100}>+ {action}+ <div {...stylex.props(keyboardFixtureStyles.nestedContent)}>+ Nested content+ </div>+ </ScrollableArea>+ );+ break;+ case 'native-scroll':+ first = (+ <div {...stylex.props(keyboardFixtureStyles.nestedViewport)}>+ {action}+ <div {...stylex.props(keyboardFixtureStyles.nestedContent)}>+ Nested content+ </div>+ </div>+ );+ break;+ case 'disabled':+ first = <Button label="First action" isDisabled />;+ break;+ case 'button':+ first = action;+ break;+ default:+ first = <div role={variant}>{action}</div>;+ }+ return (+ <>+ <label>+ Content case+ <select+ value={variant}+ onChange={event => setVariant(event.target.value)}>+ {[+ 'button',+ 'link',+ 'text',+ 'input',+ 'disabled',+ 'nested',+ 'native-scroll',+ 'radiogroup',+ 'slider',+ 'combobox',+ 'listbox',+ 'menu',+ 'grid',+ 'tree',+ 'tablist',+ 'toolbar',+ ].map(value => (+ <option key={value} value={value}>+ {value}+ </option>+ ))}+ </select>+ </label>+ <Button label="Before sheet" onClick={() => setIsOpen(true)} />+ <Button+ label="Toggle modal"+ onClick={() => setHasScrim(value => !value)}+ />+ <BottomSheet+ key={hasScrim ? 'modal' : 'nonmodal'}+ label="Keyboard reading"+ isOpen={isOpen}+ onOpenChange={setIsOpen}+ hasScrim={hasScrim}+ height="capped">+ <Section>+ <VStack gap={4}>+ <Heading level={2}>Keyboard reading</Heading>+ {first}+ {Array.from({length: 24}, (_, index) => (+ <Text key={index}>+ Paragraph {index + 1}. Use Arrow or Page keys to read the full+ content. The sheet keeps native scrolling after keyboard+ entry.+ </Text>+ ))}+ {variant !== 'text' && variant !== 'disabled' && (+ <Button label="Last action" onClick={() => {}} />+ )}+ <Text id="reading-end">End of reading</Text>+ </VStack>+ </Section>+ </BottomSheet>+ <Button label="After sheet" onClick={() => {}} />+ </>+ );+ },+};diff --git a/docs/specs/AST-025/spec.md b/docs/specs/AST-025/spec.mdindex e72c5dd4ce..e56c16780f 100644--- a/docs/specs/AST-025/spec.md+++ b/docs/specs/AST-025/spec.md@@ -129,7 +129,18 @@ the behavior.while at least one applicable axis is effective, and MUST provide an appropriaterole and accessible name. An integration MAY instead rely on an existingfocusable descendant when that path gives keyboard users access to all overflowed- content. Overflow alone does not authorize an unexplained extra tab stop.+ content. In shared `contentOrViewport` mode the named viewport MUST retain+ `tabIndex=0` while effectively scrollable. On forward keyboard Tab entry the+ hook MUST inspect the first sequential descendant once and MAY delegate only+ to a native link or button that preserves native scroll keys. It MUST NOT skip+ an excluded first target to reach a later eligible one. Composite widgets,+ nested scroll owners, editable surfaces, and navigation-key-owning roles MUST+ retain the viewport stop. Reverse traversal from the delegated first child+ MUST skip the viewport without a loop. Pointer and programmatic focus MUST NOT+ delegate. Eligibility MUST be recalculated at each keyboard entry without+ persistent subtree or ancestor observation for keyboard eligibility; existing+ geometry observation remains governed by FR5–FR9. Both paths MUST retain clear+ accessible naming and native Arrow/Page access to the full scroll range.- **FR13 — Losing overflow does not move focus.** If a focused viewport stopsoverflowing, the system MAY remove it from future sequential navigation but MUSTNOT move or blur current focus solely because geometry changed.@@ -215,7 +226,12 @@ type ScrollAxis = 'inline' | 'block' | 'both';type KeyboardAccess =| {owner: 'content'}- | {owner: 'viewport'; label: string; role?: 'group' | 'region'};+ | {owner: 'viewport'; label: string; role?: 'group' | 'region'}+ | {+ owner: 'contentOrViewport';+ label: string;+ role?: 'group' | 'region';+ };interface ScrollAxisState {isScrollable: boolean;@@ -357,18 +373,18 @@ Representative public evidence:## Verification-| Contract | Verification | Representative states | Mutation or failure expectation |-| ---------------- | ---------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------ |-| FR1–FR4 | Unit geometry and computed-style tests plus browser matrix | inline, block, both; fitting, exact fit, >1px overflow; scroll-capable and non-scrollable computed values; horizontal, vertical, and sideways writing modes; LTR and RTL | A declaration or excess geometry alone becomes an owner, an effective axis is missed, or physical direction leaks into the contract |-| FR5–FR9 | Observer lifecycle and integration tests | viewport resize, content resize, async resource, hidden/show, reconnect, classic scrollbar | State remains stale, reports fitting while unmeasurable, loops, or publishes redundant updates |-| FR10, FR11, FR18 | Real-browser nested Sticky matrix | arbitrary flow position; each logical edge; orthogonal and same-axis owners; inactive inner candidate | Sticky binds to a non-effective or cross-axis owner, cannot appear mid-flow, or stacks against the wrong boundary |-| FR12, FR13 | Keyboard and accessibility-tree tests | no overflow, overflow, focusable descendants, named viewport, overflow removed while focused | Content is unreachable, a fitting area adds an unexplained stop, naming is absent, or focus moves on resize |-| FR14 | Wheel/touch/keyboard chaining browser tests | fitting child, active child, each edge, contain and chain | A fitting child creates a dead wheel zone or explicit containment leaks to an inactive axis |-| FR15, FR16 | Native/custom presentation and forced-colors tests | overlay/classic, thin/default, stable gutter, hidden/replacement, custom thumb | Presentation creates a second owner, masks state, loses platform fallback, or changes scrolling mechanics |-| FR17 | Type/API tests and browser fixtures | requested inline, block, both; attempted visible opposite axis | Public API admits a CSS combination the platform computes to different semantics |-| FR19 | Table browser integration | inline-only, bounded both-axis, sticky columns, sticky headers, intersection cell | Table plugins observe different owners or an external wrapper silently breaks sticky/accessibility behavior |-| FR20 | ScrollableArea component and container-padding tests | zero/default padding, uniform/edge overrides, nested bleed consumer, contained and full-bleed viewport | Content publishes stale inset, a nested bleed child compensates incorrectly, or scrolling escapes its parent without explicit intent |-| FR21 | Real-browser fitting/overflowing Sticky transition | fitting default, fitting `always`, content growth, content shrink, outer block Sticky owner | A fitting default viewport silently captures Sticky, explicit containment is lost, or overflow growth fails to activate scrolling |+| Contract | Verification | Representative states | Mutation or failure expectation |+| ---------------- | ---------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------- |+| FR1–FR4 | Unit geometry and computed-style tests plus browser matrix | inline, block, both; fitting, exact fit, >1px overflow; scroll-capable and non-scrollable computed values; horizontal, vertical, and sideways writing modes; LTR and RTL | A declaration or excess geometry alone becomes an owner, an effective axis is missed, or physical direction leaks into the contract |+| FR5–FR9 | Observer lifecycle and integration tests | viewport resize, content resize, async resource, hidden/show, reconnect, classic scrollbar | State remains stale, reports fitting while unmeasurable, loops, or publishes redundant updates |+| FR10, FR11, FR18 | Real-browser nested Sticky matrix | arbitrary flow position; each logical edge; orthogonal and same-axis owners; inactive inner candidate | Sticky binds to a non-effective or cross-axis owner, cannot appear mid-flow, or stacks against the wrong boundary |+| FR12, FR13 | Keyboard and accessibility-tree tests | fit/overflow, named viewport, native link/button delegation, excluded roles, nested owners, forward/reverse entry, pointer/programmatic focus, dynamic eligibility, full Arrow/Page range in Chromium/WebKit | Content is unreachable, a fitting area adds an unexplained stop, an existing path gains a duplicate stop, naming is absent, or focus moves on change |+| FR14 | Wheel/touch/keyboard chaining browser tests | fitting child, active child, each edge, contain and chain | A fitting child creates a dead wheel zone or explicit containment leaks to an inactive axis |+| FR15, FR16 | Native/custom presentation and forced-colors tests | overlay/classic, thin/default, stable gutter, hidden/replacement, custom thumb | Presentation creates a second owner, masks state, loses platform fallback, or changes scrolling mechanics |+| FR17 | Type/API tests and browser fixtures | requested inline, block, both; attempted visible opposite axis | Public API admits a CSS combination the platform computes to different semantics |+| FR19 | Table browser integration | inline-only, bounded both-axis, sticky columns, sticky headers, intersection cell | Table plugins observe different owners or an external wrapper silently breaks sticky/accessibility behavior |+| FR20 | ScrollableArea component and container-padding tests | zero/default padding, uniform/edge overrides, nested bleed consumer, contained and full-bleed viewport | Content publishes stale inset, a nested bleed child compensates incorrectly, or scrolling escapes its parent without explicit intent |+| FR21 | Real-browser fitting/overflowing Sticky transition | fitting default, fitting `always`, content growth, content shrink, outer block Sticky owner | A fitting default viewport silently captures Sticky, explicit containment is lost, or overflow growth fails to activate scrolling |## Decision log@@ -425,6 +441,29 @@ intent alone would change Sticky behavior even when no scrolling can occur.Rejected: no overflow declaration while fitting, because content could flash beforethe first geometry measurement.+### DEC-4 — Shared automatic keyboard ownership delegates at entry++**Reference:** `spec:AST-025/DEC-4`+**Decider:** `cixzhang`, `2026-09-13`++`keyboardAccess.owner="contentOrViewport"` owns the automatic keyboard path in+one shared hook. Components do not maintain parallel focusability detectors.+The initial continuous-eligibility approach is replaced by focus-time delegation:+the overflowing viewport remains a named stop, and forward Tab entry inspects the+first sequential descendant. The conservative delegation set is native links and+buttons outside composite widgets, editable surfaces, and nested scroll owners.+Positive-tabindex ordering and unproven interactive roles retain the viewport.++Native reverse traversal skips the viewport when returning from the delegated+first child. Pointer/programmatic focus stays on the viewport. Content changes+never move existing focus; eligibility is checked again on the next keyboard+entry. Native scrolling remains responsible for Arrow/Page keys and chaining.++Rejected: continuous keyboard-eligibility scans after subtree and ancestor+mutations, because shared infrastructure should not pay that cost while idle.+Geometry observation remains separate. Also rejected: forwarding past an excluded+first descendant, because that changes the consumer's sequential focus order.+## Open questions- **OQ1 — How is the Layout `isScrollable` migration observed and sequenced?**diff --git a/package.json b/package.jsonindex 12b05b2eb2..338946bfb9 100644--- a/package.json+++ b/package.json@@ -10,7 +10,7 @@"test": "vitest run","test:watch": "vitest","test:coverage": "vitest --coverage",- "test:a11y-contract": "playwright test --config playwright.config.ts",+ "test:a11y-contract": "playwright test --config playwright.config.ts --project chromium","check:package-boundaries": "node scripts/check-package-boundaries.js","check:repo": "pnpm check:sync && pnpm check:knowledge && pnpm check:package-boundaries && pnpm check:changesets && pnpm check:demo-media && pnpm check:executable-bits && pnpm check:cli-structure && pnpm check:use-client && pnpm check:portable-scripts && pnpm check:i18n-catalog && pnpm check:cldr-weekdays && pnpm check:fixtures && pnpm check:setup-contract","check:fixtures": "node internal/vibe-tests/scripts/fixture-suite.mjs verify",diff --git a/packages/core/src/BottomSheet/BottomSheet.doc.mjs b/packages/core/src/BottomSheet/BottomSheet.doc.mjsindex 86e6a59c5c..7aa3f82197 100644--- a/packages/core/src/BottomSheet/BottomSheet.doc.mjs+++ b/packages/core/src/BottomSheet/BottomSheet.doc.mjs@@ -1,5 +1,12 @@// Copyright (c) Meta Platforms, Inc. and affiliates.+/**+ * @file BottomSheet.doc.mjs+ * @input BottomSheet props, sheet anatomy, and focus-time keyboard scrolling behavior+ * @output Consumer documentation and examples for BottomSheet+ * @position CLI and rendered component documentation+ */+/** @type {import('@astryxdesign/cli/authoring').ComponentAnatomyElement[]} */const anatomy = [{@@ -130,7 +137,7 @@ export const docs = {name: 'children',type: 'ReactNode',description:- "Sheet content, rendered below the grab handle in a scrollable area. If it includes a text-entry control that can bring up the mobile keyboard, use height='tall' and keep the sheet fully expanded while editing.",+ "Sheet content in a scrollable area. The named body is keyboard reachable while overflowing. Forward Tab entry may move directly to the first native link or button; input controls, composite widgets, and nested scroll areas retain the body stop. Shift+Tab from a delegated first child skips the body. Fitting content adds no body stop. The internal observed content box preserves block flow and percentage heights. If it includes a text-entry control that can bring up the mobile keyboard, use height='tall' and keep the sheet fully expanded while editing.",required: true,},{diff --git a/packages/core/src/BottomSheet/BottomSheet.spec.md b/packages/core/src/BottomSheet/BottomSheet.spec.mdindex 01390ea318..fa0f0dbd44 100644--- a/packages/core/src/BottomSheet/BottomSheet.spec.md+++ b/packages/core/src/BottomSheet/BottomSheet.spec.md@@ -14,6 +14,9 @@ verified_by:[packages/core/src/BottomSheet/BottomSheet.test.tsx,packages/core/src/BottomSheet/BottomSheetPanel.test.tsx,+ packages/core/src/BottomSheet/BottomSheetKeyboard.test.tsx,+ packages/core/src/BottomSheet/__tests__/BottomSheetKeyboard.a11y.browser.spec.ts,+ apps/storybook/stories/BottomSheet.stories.tsx,scripts/check-knowledge.mjs,]modules: []@@ -22,7 +25,7 @@ design_specs: []architecture:[architecture:component-theming-surface, architecture:layer-runtime]contributing: []-system_specs: []+system_specs: [spec:AST-025]---# BottomSheet component contract@@ -30,14 +33,15 @@ system_specs: []## IntentBottomSheet presents caller-provided content in a panel that rises from the-bottom edge. This draft records current consumer anatomy and theming reachability-without changing runtime behavior, styling, targets, or public API.+bottom edge. This draft records current consumer anatomy, keyboard-reachable+scrolling, and theming reachability without changing public API.## Compatibility and migration- Released default preserved: `yes`-- Compatibility class: additive documentation only; runtime, DOM, styling,- targets, and public API remain unchanged+- Compatibility class: additive internal content box and shared scroll behavior;+ public props, defaults, targets, and caller child ordering inside the content box+ remain unchanged- Controlled/uncontrolled behavior: unchanged- Migration decision: none@@ -48,7 +52,8 @@ Consumer migration instructions belong in consumer docs and release notes.**Owns**- The visual Sheet panel and its current `bottom-sheet` target.-- The scrolling Content area and decorative Handle inside the panel.+- The scrolling Content area, its shared viewport/content-box integration, and+ automatic keyboard-path selection.- Standalone sheet presentation, including its optional native-dialog Scrim.**Does not own / non-goals**@@ -67,10 +72,11 @@ in `BottomSheet.doc.mjs`.## Behavioral and layout contract-| ID | Candidate invariant | Basis | Draft review state |-| --- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------- | -------------------------------------------------- |-| FR1 | The current presented sheet contains one Sheet panel, one scrolling Content area, and one decorative Handle; a Scrim is present only in scrim-backed presentation. | Current source, docs, and tests | Verified current behavior; no new behavior decided |-| FR2 | The Sheet panel carries `bottom-sheet`; Content area, Handle, and Scrim carry no BottomSheet public target. | Current source, docs, and tests | Verified current behavior; no target change |+| ID | Candidate invariant | Basis | Draft review state |+| --- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------- | -------------------------------------------------- |+| FR1 | The current presented sheet contains one Sheet panel, one scrolling Content area, and one decorative Handle; a Scrim is present only in scrim-backed presentation. | Current source, docs, and tests | Verified current behavior; no new behavior decided |+| FR2 | The Sheet panel carries `bottom-sheet`; Content area, Handle, and Scrim carry no BottomSheet public target. | Current source, docs, and tests | Verified current behavior; no target change |+| FR3 | Content renders in one real observed content box. Effective overflow, containment, and keyboard access come from `useScrollableArea`; the named overflowing body delegates forward Tab entry to a safe first sequential native link/button. | `spec:AST-025`; issue #5207; tests | Focus-time prototype for owner review |### Allowed variation@@ -96,8 +102,14 @@ in `BottomSheet.doc.mjs`.## Accessibility contract-This draft does not change or extend BottomSheet's existing dialog naming,-focus, Handle, keyboard, or dismissal behavior.+- **AR1 — Keyboard scroll path.** The named body is a tab stop while effectively+ overflowing. On forward Tab entry, the shared hook may delegate to the first+ sequential native link/button outside navigation-key-owning surfaces. It keeps+ the body stop for excluded content and skips the body on reverse traversal+ from the delegated first child.+- **AR2 — Focus continuity.** Content, overflow, or eligibility changes MUST NOT+ move focus. Pointer/programmatic body focus never delegates. A focused body+ losing overflow remains programmatically focusable.## Design relationships@@ -143,18 +155,20 @@ a decision that they must remain unthemeable.mapping, and factual `none` dispositions.- `architecture:layer-runtime` owns the current native-dialog host distinctionand records that sheets retain local scrim and swipe behavior.+- `spec:AST-025` owns effective scroll measurement, overflow and containment,+ automatic keyboard-owner selection, and focus continuity.- `family:overlay-dismissal` owns shared Escape and platform-close ordering andrecords BottomSheet's current local-only adoption gap. This anatomy backfilldoes not migrate that runtime behavior.## Verification map-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |-| ------------------- | ------------------------------------------------------------------------- | ---------------------------------------------- | ----------------------------------------------------------------------------------------------- | --------------------------- |-| FR1 | `BottomSheet.test.tsx` render, content, Handle, and scrim behavior suites | Modal, non-modal, and switcher presentations | Removing a documented part fails existing content, structure, or dismissal assertions. | `audit:BottomSheet/anatomy` |-| FR2 | Panel target assertion, source inspection, and theming target inventories | Sheet panel, Content area, Handle, and Scrim | Removing the panel target or documenting an unshipped child target fails evidence or inventory. | `audit:BottomSheet/theming` |-| Layout evidence | `BottomSheetPanel.test.tsx` | Floating Handle and scrolling Content area | Reordering or merging the stable parts fails existing panel structure and style assertions. | `audit:BottomSheet/anatomy` |-| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and current target inventory | Missing, extra, prefixed, stale, or multiply assigned mappings fail repository validation. | `audit:BottomSheet/theming` |+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |+| ------------------- | -------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------- | --------------------------------- |+| FR1 | `BottomSheet.test.tsx` render, content, Handle, and scrim behavior suites | Modal, non-modal, and switcher presentations | Removing a documented part fails existing content, structure, or dismissal assertions. | `audit:BottomSheet/anatomy` |+| FR2 | Panel target assertion, source inspection, and theming target inventories | Sheet panel, Content area, Handle, and Scrim | Removing the panel target or documenting an unshipped child target fails evidence or inventory. | `audit:BottomSheet/theming` |+| FR3, AR1–AR2 | `BottomSheetKeyboard.test.tsx`; `BottomSheetKeyboard.a11y.browser.spec.ts`; open Storybook stories | fitting/overflow, plain text, usable/unusable/dynamic descendants, focus | Missing/duplicate keyboard access, stale ownership, focus movement, or broken content-box layout fails. | `audit:BottomSheet/accessibility` | | Layout evidence | `BottomSheetPanel.test.tsx` | Floating Handle and scrolling Content area | Reordering or merging the stable parts fails existing panel structure and style assertions. | `audit:BottomSheet/anatomy` |+| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and current target inventory | Missing, extra, prefixed, stale, or multiply assigned mappings fail repository validation. | `audit:BottomSheet/theming` |Existing tests directly assert the Sheet panel target, Content area placement,Handle structure, and scrim behavior. Source and public target metadata confirm@@ -162,8 +176,20 @@ that the other three parts have no public target.## Decision log-None. This draft records current facts and introduces no component-local design,-API, theming, or layer-system decision.+### DEC-1 — BottomSheet adopts automatic shared keyboard ownership++**Reference:** `component:BottomSheet/DEC-1`+**Decider:** cixzhang, 2026-09-13++BottomSheet supplies its existing label to+`keyboardAccess.owner="contentOrViewport"`. The shared hook keeps the overflowing+body named and tabbable, delegating forward keyboard entry to a safe first native+link/button. Pointer/programmatic focus and excluded content keep the body path. BottomSheet retains `stickyContainment="always"` because the+body deliberately remains the sheet-local Sticky boundary.++A real flow-root content box supplies the hook's observation seam while preserving+representative margin, float, percentage-height, flex/grid-child, and hug-height+behavior.## Open questionsdiff --git a/packages/core/src/BottomSheet/BottomSheet.test.tsx b/packages/core/src/BottomSheet/BottomSheet.test.tsxindex c5cfd21c37..b0bc934e0a 100644--- a/packages/core/src/BottomSheet/BottomSheet.test.tsx+++ b/packages/core/src/BottomSheet/BottomSheet.test.tsx@@ -3,7 +3,7 @@/*** @file BottomSheet.test.tsx* @input Uses vitest, @testing-library/react, BottomSheet component- * @output Unit tests for BottomSheet component behavior+ * @output Unit tests for BottomSheet behavior and observed content anatomy* @position Core testing; validates BottomSheet.tsx implementation** SYNC: When BottomSheet.tsx changes, update tests to match new behavior@@ -290,7 +290,7 @@ describe('BottomSheet', () => {expect(onClick).toHaveBeenCalledTimes(1);});- it('keeps consumer content as the last scroll-body child', () => {+ it('keeps consumer content first and last inside the observed content box', () => {render(<BottomSheet isOpen onOpenChange={() => {}} label="Filters"><div data-testid="consumer-content">Sheet content</div>@@ -300,7 +300,10 @@ describe('BottomSheet', () => {const consumer = screen.getByTestId('consumer-content');expect(body.children).toHaveLength(1);- expect(body.lastElementChild).toBe(consumer);+ const content = body.lastElementChild;+ expect(content).toHaveAttribute('data-scroll-content');+ expect(content?.lastElementChild).toBe(consumer);+ expect(consumer.matches(':first-child')).toBe(true);expect(consumer.matches(':last-child')).toBe(true);});diff --git a/packages/core/src/BottomSheet/BottomSheet.tsx b/packages/core/src/BottomSheet/BottomSheet.tsxindex 69bb316da4..40cddbb32e 100644--- a/packages/core/src/BottomSheet/BottomSheet.tsx+++ b/packages/core/src/BottomSheet/BottomSheet.tsx@@ -4,7 +4,7 @@/*** @file BottomSheet.tsx- * @input Uses React, StyleX, core hooks/utils, BottomSheetPanel, BottomSheetSwitcherContext+ * @input Uses React, StyleX, core hooks/utils, named BottomSheetPanel, BottomSheetSwitcherContext* @output Exports BottomSheet component and BottomSheetProps* @position Public BottomSheet router plus private standalone/switcher hosts*@@ -379,6 +379,7 @@ function StandaloneBottomSheet({ref={ref}state={panelState}height={height}+ label={label}snapPoints={snapPoints}isSwipeDismissAllowed={purpose === 'info'}isPageScrollLocked={shouldPresent && hasScrim}@@ -537,6 +538,7 @@ function SwitcherBottomSheetItem({ref={ref}state={panelState}height={height}+ label={label}snapPoints={snapPoints}isSwipeDismissAllowed={purpose === 'info'}isPageScrollLocked={hasScrim}diff --git a/packages/core/src/BottomSheet/BottomSheetKeyboard.test.tsx b/packages/core/src/BottomSheet/BottomSheetKeyboard.test.tsxnew file mode 100644index 0000000000..1b0f4e67a2--- /dev/null+++ b/packages/core/src/BottomSheet/BottomSheetKeyboard.test.tsx@@ -0,0 +1,195 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file BottomSheetKeyboard.test.tsx+ * @input BottomSheetPanel, real shared scroll behavior, and explicit DOM geometry+ * @output Regression coverage for viewport access, entry-time eligibility, and focus continuity+ * @position BottomSheet integration tests; browser stories verify native key scrolling+ */++import {act, fireEvent, render, screen, waitFor} from '@testing-library/react';+import {useState, type ReactNode} from 'react';+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';+import {BottomSheetPanel} from './BottomSheetPanel';++function Fixture({children}: {children: ReactNode}) {+ return (+ <BottomSheetPanel+ label="Reading details"+ state={{kind: 'open', entering: false}}+ height="capped"+ onDismiss={() => {}}+ onScrimOpacity={() => {}}>+ {children}+ </BottomSheetPanel>+ );+}++function body() {+ return screen.getByRole('group', {name: 'Reading details'});+}++async function measure(scrollHeight: number, scrollWidth = 300) {+ const viewport = body();+ // jsdom does not resolve the shared hook's dynamic StyleX CSS variable.+ viewport.style.overflowY = 'auto';+ viewport.style.overflowX = 'auto';+ for (const [key, value] of Object.entries({+ clientHeight: 100,+ clientWidth: 300,+ scrollHeight,+ scrollWidth,+ })) {+ Object.defineProperty(viewport, key, {configurable: true, value});+ }+ fireEvent(window, new Event('resize'));+ await waitFor(() => {+ expect(viewport.dataset.scrollableBlock === 'true').toBe(+ scrollHeight > 101,+ );+ });+}++beforeEach(() => {+ // jsdom has no layout. Visibility-specific cases still use real computed+ // style/hidden/inert checks; native layout is covered in Storybook.+ vi.spyOn(HTMLElement.prototype, 'getClientRects').mockReturnValue([+ new DOMRect(0, 0, 20, 20),+ ] as unknown as DOMRectList);+});++afterEach(() => {+ vi.restoreAllMocks();+});++describe('BottomSheet keyboard scrolling', () => {+ it('adds a named body tab stop only while text-only content overflows', async () => {+ render(<Fixture>Reading details body</Fixture>);+ await measure(100);+ expect(body()).not.toHaveAttribute('tabindex');+ await measure(300);+ expect(body()).toHaveAttribute('tabindex', '0');+ expect(body()).toHaveStyle({overscrollBehaviorY: 'contain'});+ });++ it('preserves current body focus when overflow disappears', async () => {+ render(<Fixture>Reading details body</Fixture>);+ await measure(300);+ act(() => body().focus());+ await measure(100);+ expect(body()).toHaveFocus();+ expect(body()).toHaveAttribute('tabindex', '-1');+ expect(body()).toHaveStyle({overscrollBehaviorY: 'auto'});+ });++ it('retains keyboard access to content that overflows only horizontally', async () => {+ render(<Fixture>Wide reading content</Fixture>);+ await measure(100, 600);+ await waitFor(() =>+ expect(body()).toHaveAttribute('data-scrollable-inline', 'true'),+ );+ expect(body()).toHaveAttribute('tabindex', '0');+ });++ it('keeps the named viewport available alongside focusable content', async () => {+ render(+ <Fixture>+ <button type="button">Continue reading</button>+ </Fixture>,+ );+ await measure(300);+ expect(body()).toHaveAttribute('tabindex', '0');+ act(() => screen.getByRole('button').focus());+ expect(screen.getByRole('button')).toHaveFocus();+ });++ it.each([+ <button type="button" key="disabled" disabled>+ Unavailable+ </button>,+ <button type="button" key="hidden" hidden>+ Hidden+ </button>,+ <button type="button" key="negative" tabIndex={-2}>+ Programmatic only+ </button>,+ <button type="button" key="visibility" style={{visibility: 'hidden'}}>+ Hidden by CSS+ </button>,+ <div key="inert" inert>+ <button type="button">Inert</button>+ </div>,+ <fieldset key="fieldset" disabled>+ <button type="button">Disabled by fieldset</button>+ </fieldset>,+ ])(+ 'ignores a descendant that cannot supply sequential keyboard access (%#)',+ async child => {+ render(<Fixture>{child}</Fixture>);+ await measure(300);+ expect(body()).toHaveAttribute('tabindex', '0');+ },+ );++ it('does not move focus when a nested child changes', async () => {+ let setHasControl: (value: boolean) => void = () => {};+ function AsyncContent() {+ const [hasControl, update] = useState(false);+ setHasControl = update;+ return hasControl ? (+ <button type="button">Loaded action</button>+ ) : (+ <p>Loading text</p>+ );+ }+ render(+ <Fixture>+ <AsyncContent />+ </Fixture>,+ );+ await measure(300);+ act(() => body().focus());+ act(() => setHasControl(true));+ expect(body()).toHaveAttribute('tabindex', '0');+ expect(body()).toHaveFocus();+ act(() => setHasControl(false));+ await waitFor(() => expect(body()).toHaveAttribute('tabindex', '0'));+ });++ it('retains the viewport when an existing descendant becomes disabled', async () => {+ render(+ <Fixture>+ <button type="button">Continue reading</button>+ </Fixture>,+ );+ await measure(300);+ screen.getByRole('button').setAttribute('disabled', '');+ await waitFor(() => expect(body()).toHaveAttribute('tabindex', '0'));+ });++ it.each(['content', 'ancestor'])(+ 'retains the viewport when %s data attributes change child visibility',+ async target => {+ const {container} = render(+ <Fixture>+ <style>+ {'[data-actions="hidden"] button { visibility: hidden; }'}+ </style>+ <div data-testid="conditional-content">+ <button type="button">Conditional action</button>+ </div>+ </Fixture>,+ );+ await measure(300);+ expect(body()).toHaveAttribute('tabindex', '0');+ const owner =+ target === 'content'+ ? screen.getByTestId('conditional-content')+ : container;+ owner.setAttribute('data-actions', 'hidden');+ await waitFor(() => expect(body()).toHaveAttribute('tabindex', '0'));+ owner.removeAttribute('data-actions');+ expect(body()).toHaveAttribute('tabindex', '0');+ },+ );+});diff --git a/packages/core/src/BottomSheet/BottomSheetPanel.test.tsx b/packages/core/src/BottomSheet/BottomSheetPanel.test.tsxindex 555e49e60c..826c2910aa 100644--- a/packages/core/src/BottomSheet/BottomSheetPanel.test.tsx+++ b/packages/core/src/BottomSheet/BottomSheetPanel.test.tsx@@ -3,7 +3,7 @@/*** @file BottomSheetPanel.test.tsx* @input Uses vitest, Testing Library, BottomSheetPanel- * @output Tests the shared sheet surface motion contract+ * @output Tests the shared sheet surface motion and keyboard scroll contracts* @position Internal presentation tests shared by standalone and switcher modes*/@@ -50,6 +50,7 @@ function renderPanel() {return render(<BottomSheetPanel+ label="Sheet details"state={state}height="hug"style={panelTransitionStyle}@@ -92,6 +93,7 @@ describe('BottomSheetPanel', () => {const onMotionComplete = vi.fn();const {rerender} = render(<BottomSheetPanel+ label="Sheet details"state={{kind: 'retained', motion: 'covered', alignmentOffset: 0}}height="hug"style={panelTransitionStyle}@@ -104,6 +106,7 @@ describe('BottomSheetPanel', () => {rerender(<BottomSheetPanel+ label="Sheet details"state={{kind: 'open', entering: true}}height="hug"style={panelTransitionStyle}@@ -139,6 +142,7 @@ describe('BottomSheetPanel', () => {rerender(<BottomSheetPanel+ label="Sheet details"state={{kind: 'exiting'}}height="hug"style={panelTransitionStyle}@@ -166,6 +170,7 @@ describe('BottomSheetPanel', () => {const onMotionComplete = vi.fn();render(<BottomSheetPanel+ label="Sheet details"state={{kind: 'open', entering: true}}height="hug"onDismiss={() => {}}@@ -184,6 +189,7 @@ describe('BottomSheetPanel', () => {const onMotionComplete = vi.fn();render(<BottomSheetPanel+ label="Sheet details"state={{kind: 'open', entering: true}}height="hug"style={{@@ -211,6 +217,7 @@ describe('BottomSheetPanel', () => {const panelRef = vi.fn();const {rerender, unmount} = render(<BottomSheetPanel+ label="Sheet details"ref={panelRef}state={{kind: 'open', entering: false}}height="hug"@@ -223,6 +230,7 @@ describe('BottomSheetPanel', () => {expect(panelRef).toHaveBeenCalledTimes(1);rerender(<BottomSheetPanel+ label="Sheet details"ref={panelRef}state={{kind: 'open', entering: false}}height="hug"@@ -361,6 +369,7 @@ describe('BottomSheetPanel', () => {const {container: closing} = render(<BottomSheetPanel+ label="Sheet details"state={{kind: 'exiting'}}height="hug"onDismiss={() => {}}@@ -379,6 +388,7 @@ describe('BottomSheetPanel', () => {const {container: resting} = render(<BottomSheetPanel+ label="Sheet details"state={{kind: 'open', entering: false}}height="hug"onDismiss={() => {}}diff --git a/packages/core/src/BottomSheet/BottomSheetPanel.tsx b/packages/core/src/BottomSheet/BottomSheetPanel.tsxindex 836f72c7c5..5715bfb3db 100644--- a/packages/core/src/BottomSheet/BottomSheetPanel.tsx+++ b/packages/core/src/BottomSheet/BottomSheetPanel.tsx@@ -4,14 +4,14 @@/*** @file BottomSheetPanel.tsx- * @input Uses React, StyleX, theme tokens, useSheetGestures- * @output Internal BottomSheetPanel surface and motion-state types+ * @input Uses React, StyleX, theme tokens, sheet gestures, shared scroll behavior, and the host label+ * @output Internal BottomSheetPanel with a keyboard-reachable scrolling body and motion-state types* @position Shared presentation layer for standalone and switcher BottomSheets** This component owns everything intrinsic to a sheet surface: height budgets,* drag and snap gestures, the handle and scrolling body, motion styles, and- * transition completion. It deliberately does not own a dialog, focus, inert- * state, or switcher registration; those belong to the hosting controller.+ * transition completion. It owns the body's keyboard access; dialog focus+ * entry/return, inert state, and switcher registration belong to the host.** SYNC: When modified, update these files to stay in sync:* - /packages/core/src/BottomSheet/BottomSheet.tsx@@ -33,17 +33,20 @@ import {import * as stylex from '@stylexjs/stylex';import type {BaseProps} from '../BaseProps';import {useDevWarning} from '../hooks';+import {useScrollableArea} from '../hooks/useScrollableArea';import {borderVars,colorVars,durationVars,easeVars,+ focusVars,radiusVars,shadowVars,sizeVars,spacingVars,} from '../theme/tokens.stylex';import {mergeProps, themeProps} from '../utils';+import {focusOutlineStyles} from '../utils/focusOutline.stylex';import {overlayPaddingReset} from '../Layout/padding.stylex';import {isValidSnapPoint,@@ -211,9 +214,11 @@ const styles = stylex.create({flexGrow: 1,minHeight: 0,boxSizing: 'border-box',- overflowY: 'auto',- overscrollBehavior: 'none',touchAction: 'pan-y',+ outlineOffset: {+ default: 0,+ ':focus-visible': `calc(-1 * ${focusVars['--focus-outline-width']})`,+ },// The scrolling area paints the surface itself, covering the sheet's whole// inner box. Without it the sheet's edge is not uniform: a theme that packs// an inset ring into --shadow-high (the bundled themes all add one in dark@@ -229,6 +234,15 @@ const styles = stylex.create({// space a content wrapper's own top padding already provides.paddingBlockEnd: 0,},+ content: {+ // Preserve the body's block formatting (including margin/float isolation)+ // and its definite percentage-height basis. min-content lets this real+ // observed box grow with async content beyond a fixed-height viewport.+ display: 'flow-root',+ boxSizing: 'border-box',+ height: '100%',+ minHeight: 'min-content',+ },tallKeyboardBody: {scrollPaddingBlockEnd: MOBILE_KEYBOARD_BOTTOM_CLEARANCE,'::after': {@@ -265,6 +279,8 @@ interface BottomSheetPanelProps extends BaseProps<HTMLDivElement> {ref?: React.Ref<HTMLDivElement>;state: BottomSheetPanelState;height: BottomSheetHeight | number | string;+ /** Existing host name, reused for the keyboard scrolling group. */+ label: string;children: ReactNode;snapPoints?: ReadonlyArray<BottomSheetSnapPoint>;isSwipeDismissAllowed?: boolean;@@ -391,6 +407,7 @@ export function BottomSheetPanel({ref,state,height,+ label,children,snapPoints,className,@@ -490,6 +507,17 @@ export function BottomSheetPanel({onScrimOpacity,});+ const {getViewportProps, getContentProps} = useScrollableArea({+ // The previous overflow-y:auto also computed overflow-x:auto. Keep wide+ // content reachable instead of clipping that existing inline scroll path.+ axis: 'both',+ keyboardAccess: {owner: 'contentOrViewport', label},+ overscroll: 'contain',+ // The sheet body deliberately remains the boundary for sheet-local sticky+ // content while fitting, as it was before shared scroll adoption.+ stickyContainment: 'always',+ });+const setElement = useCallback((element: HTMLDivElement | null) => {sheetRef(element);@@ -656,17 +684,22 @@ export function BottomSheetPanel({<div {...stylex.props(styles.handlePill)} /></div><div- {...mergeProps(- stylex.props(- styles.body,- height === 'tall' && styles.tallKeyboardBody,+ {...getViewportProps<HTMLDivElement>({+ ...bodyProps,+ ...mergeProps(+ stylex.props(+ focusOutlineStyles.focusVisible,+ styles.body,+ height === 'tall' && styles.tallKeyboardBody,+ ),+ scrollPreservationInset > 0+ ? {style: {paddingBlockEnd: `${scrollPreservationInset}px`}}+ : {},),- scrollPreservationInset > 0- ? {style: {paddingBlockEnd: `${scrollPreservationInset}px`}}- : {},- )}- {...bodyProps}>- {children}+ })}>+ <div {...getContentProps<HTMLDivElement>(stylex.props(styles.content))}>+ {children}+ </div></div></div>);diff --git a/packages/core/src/BottomSheet/__tests__/BottomSheetKeyboard.a11y.browser.spec.ts b/packages/core/src/BottomSheet/__tests__/BottomSheetKeyboard.a11y.browser.spec.tsnew file mode 100644index 0000000000..c460f193cb--- /dev/null+++ b/packages/core/src/BottomSheet/__tests__/BottomSheetKeyboard.a11y.browser.spec.ts@@ -0,0 +1,344 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file BottomSheetKeyboard.a11y.browser.spec.ts+ * @input Built BottomSheet stories and real Chromium/WebKit keyboard input+ * @output Browser evidence for shared focus delegation, traversal, and native scrolling+ * @position Cross-browser proof for useScrollableArea's contentOrViewport policy+ */++import {expect, test, type Page, type Locator} 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();+});++// macOS WebKit defaults to text-field traversal. Option+Tab selects its native+// all-controls traversal, equivalent to enabling Safari's keyboard preference.+function tabKey(browserName: string, reverse = false): string {+ return `${browserName === 'webkit' && process.platform === 'darwin' ? 'Alt+' : ''}${reverse ? 'Shift+' : ''}Tab`;+}++async function mount(page: Page, browserName: string, variant = 'button') {+ await page.goto(+ `${storybook.origin}/iframe.html?id=core-bottomsheet--keyboard-delegation&viewMode=story`,+ );+ const viewport = page.getByRole('group', {+ name: 'Keyboard reading',+ exact: true,+ });+ await expect(viewport).toHaveAttribute('data-scrollable-block', 'true');+ await page.getByLabel('Content case').selectOption(variant);+ await expect(viewport).toHaveAttribute('tabindex', '0');+ // WebKit includes the non-modal dialog host in sequential navigation;+ // Chromium enters its descendants directly. Start immediately before the body.+ const before =+ browserName === 'webkit'+ ? page.getByRole('dialog', {name: 'Keyboard reading', exact: true})+ : page.getByRole('button', {name: 'Toggle modal', exact: true});+ await before.focus();+ return {viewport, before};+}++for (const variant of ['button', 'link']) {+ test(`${variant}: forward entry delegates once and reverse traversal exits`, async ({+ page,+ browserName,+ }) => {+ const {viewport, before} = await mount(page, browserName, variant);+ const first = page.getByRole(variant === 'button' ? 'button' : 'link', {+ name: variant === 'button' ? 'First action' : 'First link',+ exact: true,+ });+ await page.keyboard.press(tabKey(browserName));+ await expect(first).toBeFocused();+ await expect(viewport).toHaveAttribute('tabindex', '0');+ await expect(viewport).toHaveAccessibleName('Keyboard reading');+ await expect(first).toHaveAccessibleName(+ variant === 'button' ? 'First action' : 'First link',+ );+ await page.keyboard.press(tabKey(browserName));+ await expect(page.getByRole('button', {name: 'Last action'})).toBeFocused();+ await page.keyboard.press(tabKey(browserName, true));+ await expect(first).toBeFocused();+ await page.keyboard.press(tabKey(browserName, true));+ await expect(before).toBeFocused();+ await expect(viewport).toHaveAttribute('tabindex', '0');+ await page.keyboard.press(tabKey(browserName));+ await expect(first).toBeFocused();+ });+}++for (const variant of [+ 'text',+ 'input',+ 'disabled',+ 'nested',+ 'native-scroll',+ 'radiogroup',+ 'slider',+ 'combobox',+ 'listbox',+ 'menu',+ 'grid',+ 'tree',+ 'tablist',+ 'toolbar',+]) {+ test(`${variant}: retains a named viewport stop`, async ({+ page,+ browserName,+ }) => {+ const {viewport, before} = await mount(page, browserName, variant);+ await page.keyboard.press(tabKey(browserName));+ await expect(viewport).toBeFocused();+ await expect(viewport).toHaveAccessibleName('Keyboard reading');+ await page.keyboard.press(tabKey(browserName, true));+ await expect(before).toBeFocused();+ });+}++async function scrollRange(viewport: Locator) {+ return viewport.evaluate(element => ({+ position: element.scrollTop,+ max: element.scrollHeight - element.clientHeight,+ }));+}++for (const key of ['PageDown', 'ArrowDown']) {+ test(`${key}: reaches both scroll edges after delegation`, async ({+ page,+ browserName,+ }) => {+ const {viewport} = await mount(page, browserName);+ await page.keyboard.press(tabKey(browserName));+ const first = page.getByRole('button', {name: 'First action', exact: true});+ await expect(first).toBeFocused();+ for (let count = 0; count < 300; count++) {+ const {position, max} = await scrollRange(viewport);+ if (position >= max - 1) {+ break;+ }+ await page.keyboard.press(key, {delay: key === 'ArrowDown' ? 50 : 25});+ }+ await expect+ .poll(async () => {+ const {position, max} = await scrollRange(viewport);+ // WebKit can overshoot a native edge while showing rubber-band feedback.+ return max - position;+ })+ .toBeLessThanOrEqual(1);+ for (let count = 0; count < 300; count++) {+ if ((await scrollRange(viewport)).position <= 1) {+ break;+ }+ await page.keyboard.press(key === 'PageDown' ? 'PageUp' : 'ArrowUp', {+ delay: key === 'ArrowDown' ? 50 : 25,+ });+ }+ await expect+ .poll(async () => (await scrollRange(viewport)).position)+ .toBeLessThanOrEqual(1);+ await expect(first).toBeFocused();+ });+}++test('pointer and programmatic focus stay on the viewport, including during keydown', async ({+ page,+ browserName,+}) => {+ const {viewport, before} = await mount(page, browserName);+ await viewport.focus();+ await expect(viewport).toBeFocused();+ await before.focus();+ await viewport.click({position: {x: 4, y: 40}});+ await expect(viewport).toBeFocused();+ await before.focus();+ await before.evaluate(element => {+ element.addEventListener('keydown', event => {+ if (event instanceof KeyboardEvent && event.key === 'Tab') {+ event.preventDefault();+ document+ .querySelector<HTMLElement>(+ '[role="group"][aria-label="Keyboard reading"]',+ )+ ?.focus();+ }+ });+ });+ await page.keyboard.press(tabKey(browserName));+ await expect(viewport).toBeFocused();+});++test('dynamic eligibility is checked at the next entry without mutation observation', async ({+ page,+ browserName,+}) => {+ await page.addInitScript(() => {+ const Original = window.MutationObserver;+ const observers: MutationObserver[] = [];+ window.MutationObserver = class extends Original {+ constructor(callback: MutationCallback) {+ super(callback);+ observers.push(this);+ }+ };+ Object.assign(window, {+ stopMutationObservers: () =>+ observers.forEach(observer => observer.disconnect()),+ });+ });+ const {viewport, before} = await mount(page, browserName);+ await page.evaluate(() => {+ (+ window as unknown as {stopMutationObservers: () => void}+ ).stopMutationObservers();+ });+ await viewport.focus();+ const first = page.getByRole('button', {name: 'First action', exact: true});+ await first.evaluate(element => element.setAttribute('disabled', ''));+ await expect(viewport).toBeFocused();+ await before.focus();+ await page.keyboard.press(tabKey(browserName));+ await expect(page.getByRole('button', {name: 'Last action'})).toBeFocused();+ await before.focus();+ await first.evaluate(element => element.removeAttribute('disabled'));+ await page.keyboard.press(tabKey(browserName));+ await expect(first).toBeFocused();+ await before.focus();+ await viewport.locator('[data-scroll-content]').evaluate(element => {+ const input = document.createElement('input');+ input.setAttribute('aria-label', 'Inserted input');+ element.prepend(input);+ });+ await page.keyboard.press(tabKey(browserName));+ await expect(viewport).toBeFocused();+ await page.getByLabel('Inserted input').evaluate(element => element.remove());+ await expect(viewport).toBeFocused();+ await before.focus();+ await page.keyboard.press(tabKey(browserName));+ await expect(first).toBeFocused();+ await before.focus();+ await first.evaluate(element => element.setAttribute('role', 'combobox'));+ await page.keyboard.press(tabKey(browserName));+ await expect(viewport).toBeFocused();+});++test('modal BottomSheet keeps native focus containment without cycling through the viewport', async ({+ page,+ browserName,+}) => {+ await mount(page, browserName);+ await page.getByRole('button', {name: 'Toggle modal', exact: true}).click();+ const dialog = page.getByRole('dialog', {+ name: 'Keyboard reading',+ exact: true,+ });+ await expect+ .poll(async () => dialog.evaluate(element => element.matches(':modal')))+ .toBe(true);+ const viewport = page.getByRole('group', {+ name: 'Keyboard reading',+ exact: true,+ });+ await expect(viewport).toHaveAttribute('data-scrollable-block', 'true');+ const panel = dialog.locator('.astryx-bottom-sheet');+ await panel.focus();+ await page.keyboard.press(tabKey(browserName));+ const first = page.getByRole('button', {name: 'First action', exact: true});+ await expect(first).toBeFocused();+ await page.keyboard.press(tabKey(browserName, true));+ await expect(viewport).not.toBeFocused();+ await expect(first).not.toBeFocused();+ // Native dialog traversal may wrap to another sheet target or browser chrome;+ // it must never focus the inert background or create a viewport/child loop.+ await expect(+ page.getByRole('button', {name: 'Before sheet', includeHidden: true}),+ ).not.toBeFocused();+ await expect(viewport).toHaveAttribute('tabindex', '0');+});++test('fitting text removes the viewport stop while preserving current focus', async ({+ page,+ browserName,+}) => {+ const {viewport} = await mount(page, browserName, 'text');+ await viewport.focus();+ await viewport.locator('[data-scroll-content]').evaluate(element => {+ element.textContent = 'Short reading content';+ });+ await expect(viewport).not.toHaveAttribute('data-scrollable-block', 'true');+ await expect(viewport).toHaveAttribute('tabindex', '-1');+ await expect(viewport).toBeFocused();+});++test('horizontal overflow remains keyboard scrollable after delegation', async ({+ page,+ browserName,+}) => {+ const {viewport, before} = await mount(page, browserName);+ await viewport.evaluate(element => {+ const content = element.querySelector<HTMLElement>('[data-scroll-content]');+ if (content != null) {+ content.style.width = `${element.clientWidth + 320}px`;+ }+ });+ await expect(viewport).toHaveAttribute('data-scrollable-inline', 'true');+ await before.focus();+ await page.keyboard.press(tabKey(browserName));+ await expect(+ page.getByRole('button', {name: 'First action', exact: true}),+ ).toBeFocused();+ for (const key of ['ArrowRight', 'ArrowLeft']) {+ for (let count = 0; count < 100; count++) {+ const atEdge = await viewport.evaluate(+ (element, forward) =>+ forward+ ? element.scrollLeft >=+ element.scrollWidth - element.clientWidth - 1+ : element.scrollLeft <= 1,+ key === 'ArrowRight',+ );+ if (atEdge) {+ break;+ }+ await page.keyboard.press(key, {delay: 50});+ }+ await expect+ .poll(async () =>+ viewport.evaluate(+ (element, forward) =>+ forward+ ? element.scrollWidth - element.clientWidth - element.scrollLeft+ : element.scrollLeft,+ key === 'ArrowRight',+ ),+ )+ .toBeLessThanOrEqual(1);+ }+});++test('does not skip an aria-hidden first tab stop to delegate to a later action', async ({+ page,+ browserName,+}) => {+ const {viewport} = await mount(page, browserName);+ await page+ .getByRole('button', {name: 'First action', exact: true})+ .evaluate(element => {+ element.setAttribute('aria-hidden', 'true');+ });+ await page.keyboard.press(tabKey(browserName));+ await expect(viewport).toBeFocused();+});diff --git a/packages/core/src/ScrollableArea/modules/useScrollableArea.spec.md b/packages/core/src/ScrollableArea/modules/useScrollableArea.spec.mdindex bd15e9f8aa..41c5ac6a5d 100644--- a/packages/core/src/ScrollableArea/modules/useScrollableArea.spec.md+++ b/packages/core/src/ScrollableArea/modules/useScrollableArea.spec.md@@ -10,7 +10,12 @@ approved_by: cixzhangapproved_at: 2026-09-11owners: [cixzhang]review_triggers: [public-api, behavior, accessibility]-verified_by: [packages/core/src/hooks/useScrollableArea.test.tsx]+verified_by:+ [+ packages/core/src/hooks/useScrollableArea.test.tsx,+ packages/core/src/hooks/scrollKeyboardDelegation.test.ts,+ packages/core/src/BottomSheet/__tests__/BottomSheetKeyboard.a11y.browser.spec.ts,+ ]parent_component: component:ScrollableAreareferences: [architecture:public-component-api, spec:AST-025/DEC-1]---@@ -47,24 +52,25 @@ and scroll chaining without inserting structure.## Public API and concepts-| Concept | Closed values or states | Meaning | Default | Owner | Stability |-| -------------- | ---------------------------------- | ------------------------------------- | ------------------------- | ----------------------------------------- | --------- |-| axis | `inline`, `block`, `both` | requested logical scroll intent | required | `spec:AST-025` | stable |-| keyboard owner | `content`, named `viewport` | where keyboard scrolling is reached | required | `spec:AST-025` | stable |-| overscroll | `allow`, `contain` | edge propagation on effective axes | `allow` | `spec:AST-025` | stable |-| axis state | `isScrollable`, `atStart`, `atEnd` | effective ownership and logical edges | inactive, both edges true | `module:ScrollableArea/useScrollableArea` | stable |+| Concept | Closed values or states | Meaning | Default | Owner | Stability |+| -------------- | ------------------------------------------------------ | --------------------------------------- | ------------------------- | ----------------------------------------- | --------- |+| axis | `inline`, `block`, `both` | requested logical scroll intent | required | `spec:AST-025` | stable |+| keyboard owner | `content`, named `viewport`, named `contentOrViewport` | fixed or automatic keyboard scroll path | required | `spec:AST-025` | stable |+| overscroll | `allow`, `contain` | edge propagation on effective axes | `allow` | `spec:AST-025` | stable |+| axis state | `isScrollable`, `atStart`, `atEnd` | effective ownership and logical edges | inactive, both edges true | `module:ScrollableArea/useScrollableArea` | stable |## Behavioral contract-| ID | Invariant | Basis | Acceptance and implementation state |-| --- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------- | --------------------------------------- |-| FR1 | An axis MUST be effective only when requested, computed overflow is scroll-capable, and geometry exceeds 1px. | `spec:AST-025` FR1–FR4 | implemented |-| FR2 | Viewport and content geometry MUST be observed; invalidations MUST coalesce and preserve the last valid state while unmeasurable. | `spec:AST-025` FR5–FR9 | implemented |-| FR3 | Logical edges and behavior-owned physical overflow MUST map through direction and horizontal, vertical, or sideways writing modes without requiring adopters to recreate the mapping. | `spec:AST-025` FR1, FR3–FR4 | implemented |-| FR4 | The nearest registered effective owner MUST win independently by axis. | `spec:AST-025` FR10, FR18 | implemented privately for future Sticky |-| FR5 | Viewport keyboard props and overscroll containment MUST appear only while applicable requested axes are effective. | `spec:AST-025` FR12–FR14 | implemented |-| FR6 | Prop getters MUST compose refs and preserve caller handlers/classes/styles/ARIA while behavior-owned accessibility and non-cancellable behavior win conflicts. | `spec:AST-025` IR4 | implemented |-| FR7 | The viewport prop getter MUST consume caller `xstyle` and internally compose geometry-driven `clip`/`auto`/`hidden` overflow plus explicit fitting Sticky containment. | `spec:AST-025` FR21 | implemented |+| ID | Invariant | Basis | Acceptance and implementation state |+| --- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------- | --------------------------------------- |+| FR1 | An axis MUST be effective only when requested, computed overflow is scroll-capable, and geometry exceeds 1px. | `spec:AST-025` FR1–FR4 | implemented |+| FR2 | Viewport and content geometry MUST be observed; invalidations MUST coalesce and preserve the last valid state while unmeasurable. | `spec:AST-025` FR5–FR9 | implemented |+| FR3 | Logical edges and behavior-owned physical overflow MUST map through direction and horizontal, vertical, or sideways writing modes without requiring adopters to recreate the mapping. | `spec:AST-025` FR1, FR3–FR4 | implemented |+| FR4 | The nearest registered effective owner MUST win independently by axis. | `spec:AST-025` FR10, FR18 | implemented privately for future Sticky |+| FR5 | Viewport keyboard props and overscroll containment MUST appear only while applicable requested axes are effective. | `spec:AST-025` FR12–FR14 | implemented |+| FR6 | Prop getters MUST compose refs and preserve caller handlers/classes/styles/ARIA while behavior-owned accessibility and non-cancellable behavior win conflicts. | `spec:AST-025` IR4 | implemented |+| FR7 | The viewport prop getter MUST consume caller `xstyle` and internally compose geometry-driven `clip`/`auto`/`hidden` overflow plus explicit fitting Sticky containment. | `spec:AST-025` FR21 | implemented |+| FR8 | `contentOrViewport` MUST retain the named overflowing viewport, inspect the first sequential descendant on forward Tab entry, and delegate only to a native link/button outside navigation-key-owning surfaces. Reverse traversal from the delegated first child skips the viewport. Pointer/programmatic focus never delegates; eligibility is checked again on the next entry. | `spec:AST-025` FR12–FR13 | implemented |### Transformation and precedence order@@ -82,9 +88,20 @@ and scroll chaining without inserting structure.## Accessibility contract-- **AR1 — Named viewport owner.** Viewport-owned access requires a label and adds- the viewport to the tab order only while an applicable axis is effective.-- **AR2 — Focus continuity.** State changes never move or blur focus.+- **AR1 — Named viewport owner.** Fixed viewport and automatic access require a+ label and retain `tabIndex=0` while effectively scrollable. Automatic access+ delegates only on forward keyboard entry; the descendant retains its own name+ inside the named viewport group/region.+- **AR2 — Focus continuity.** Content, eligibility, and geometry changes never+ move or blur focus. A viewport losing overflow while focused remains+ programmatically focusable. Reverse traversal from the delegated first child+ skips the viewport, including after visiting later descendants.+- **AR3 — Conservative eligibility.** Inspect the first sequential target; do not+ search past an excluded one for a link/button. Composite roles, editable+ surfaces, native or registered nested scroll owners, positive tab ordering,+ popup triggers, and unproven interactive roles retain the viewport path.+- **AR4 — Native scrolling.** Delegation MUST preserve Arrow/Page access to both+ scroll edges without implementing JavaScript scrolling.## Design relationships@@ -97,9 +114,9 @@ No visual representation is owned by this hook.## Verification map-| Contract | Verification | Representative states | Mutation or failure expectation |-| ---------------- | -------------------------------------------------------------- | ------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- |-| FR1–FR6, AR1–AR2 | `useScrollableArea.test.tsx` plus real-browser Storybook probe | horizontal/vertical/sideways, LTR/RTL, fit/overflow/edge, nested owners, focused loss | style-only or geometry-only ownership, physical-edge leakage, stale state, ref loss, or dead containment fails |+| Contract | Verification | Representative states | Mutation or failure expectation |+| ---------------- | ---------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------- |+| FR1–FR8, AR1–AR4 | `useScrollableArea.test.tsx`, `scrollKeyboardDelegation.test.ts`, and `BottomSheetKeyboard.a11y.browser.spec.ts` | horizontal/vertical/sideways, LTR/RTL, fit/overflow/edge, fixed/automatic keyboard owners, dynamic descendant eligibility, nested owners, focused loss | style-only or geometry-only ownership, physical-edge leakage, duplicate/missing keyboard path, stale state, ref loss, or dead containment fails |## Decision log@@ -111,6 +128,17 @@ No visual representation is owned by this hook.One returned prop object per owned element keeps refs, accessibility, handlers,and behavior together without making consumer spread order part of correctness.+### DEC-2 — Automatic ownership is shared behavior++**Reference:** `module:ScrollableArea/useScrollableArea/DEC-2`+**Decider:** cixzhang, 2026-09-13++`contentOrViewport` retains the named overflowing viewport and delegates only on+forward Tab entry to a safe first sequential native link/button. This replaces+continuous keyboard-eligibility observation. Geometry observation is unchanged;+keyboard eligibility adds no subtree or ancestor observers and is inspected anew+at each entry. BottomSheet is a proving composition of this shared behavior.+## Open questionsNone.diff --git a/packages/core/src/hooks/scrollKeyboardDelegation.test.ts b/packages/core/src/hooks/scrollKeyboardDelegation.test.tsnew file mode 100644index 0000000000..c2f345911e--- /dev/null+++ b/packages/core/src/hooks/scrollKeyboardDelegation.test.ts@@ -0,0 +1,155 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file scrollKeyboardDelegation.test.ts+ * @input Private delegation behavior, explicit visibility, and focus event sequences+ * @output Eligibility, keyboard intent, observer cost, and cleanup regressions+ * @position DOM-level policy proof; browser tests own native Tab and scroll evidence+ */++import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';+import {attachScrollKeyboardDelegation} from './scrollKeyboardDelegation';+import {FOCUSABLE_SELECTOR} from './focusableSelector';++let detach: (() => void) | undefined;+let before: HTMLButtonElement;+let viewport: HTMLDivElement;+let content: HTMLDivElement;++beforeEach(() => {+ vi.spyOn(HTMLElement.prototype, 'getClientRects').mockReturnValue([+ new DOMRect(0, 0, 20, 20),+ ] as unknown as DOMRectList);+ before = document.createElement('button');+ viewport = document.createElement('div');+ viewport.tabIndex = 0;+ content = document.createElement('div');+ viewport.append(content);+ // The pinned jsdom selector engine orders this comma-separated selector by+ // selector group. Browsers return document order; normalize only the emulator.+ const query = content.querySelectorAll.bind(content);+ vi.spyOn(content, '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;+ });+ document.body.append(before, viewport);+ detach = attachScrollKeyboardDelegation(viewport, content);+});++afterEach(() => {+ detach?.();+ before.remove();+ viewport.remove();+ vi.restoreAllMocks();+});++// jsdom supplies no Tab default action. Complete dispatch before focusing to+// model the browser's event boundary; real traversal is tested in both engines.+function enter() {+ before.focus();+ before.dispatchEvent(+ new KeyboardEvent('keydown', {key: 'Tab', bubbles: true}),+ );+ viewport.focus();+}++describe('scroll keyboard delegation', () => {+ it('inspects content only on keyboard entry and leaves mutation observation untouched', () => {+ content.innerHTML = '<button>Action</button>';+ const scan = vi.spyOn(content, 'querySelectorAll');+ const observe = vi.spyOn(MutationObserver.prototype, 'observe');+ viewport.focus();+ content.firstElementChild?.setAttribute('data-state', 'changed');+ viewport.dispatchEvent(new Event('scroll'));+ expect(scan).not.toHaveBeenCalled();+ expect(observe).not.toHaveBeenCalled();+ enter();+ expect(scan).toHaveBeenCalledTimes(1);+ expect(document.activeElement).toBe(content.firstElementChild);+ expect(viewport.tabIndex).toBe(0);+ });++ it.each([+ '<input aria-label="Input"><button>Later action</button>',+ '<button role="radio">Radio</button><button>Later action</button>',+ '<div role="toolbar"><button>Toolbar action</button></div>',+ '<div contenteditable="true"><button>Editor action</button></div>',+ '<button aria-haspopup="menu">Open menu</button>',+ '<button aria-disabled="true">Unavailable</button>',+ '<button aria-hidden="true">Hidden from AT</button><button>Later action</button>',+ '<button>Zero</button><button tabindex="1">Earlier positive stop</button>',+ '<div tabindex="0">Custom target</div><button>Later action</button>',+ ])('does not skip an excluded first target: %s', markup => {+ content.innerHTML = markup;+ enter();+ expect(document.activeElement).toBe(viewport);+ });++ it.each(['disabled', 'hidden', 'tabindex="-2"', 'style="visibility:hidden"'])(+ 'skips a nonsequential target (%s)',+ attributes => {+ content.innerHTML = `<button ${attributes}>Skipped</button><button>Action</button>`;+ enter();+ expect(document.activeElement).toBe(content.lastElementChild);+ },+ );++ it('rechecks ancestor eligibility on the next entry', () => {+ content.innerHTML = '<div><button>Action</button></div>';+ enter();+ expect(document.activeElement).toBe(content.querySelector('button'));+ content.firstElementChild?.setAttribute('role', 'menu');+ enter();+ expect(document.activeElement).toBe(viewport);+ });++ it('retains programmatic focus during a Tab handler even without preventDefault', () => {+ content.innerHTML = '<button>Action</button>';+ before.addEventListener('keydown', () => viewport.focus(), {once: true});+ before.focus();+ before.dispatchEvent(+ new KeyboardEvent('keydown', {key: 'Tab', bubbles: true}),+ );+ expect(document.activeElement).toBe(viewport);+ });++ it('does not retain canceled keyboard intent', () => {+ content.innerHTML = '<button>Action</button>';+ before.addEventListener('keydown', event => event.preventDefault(), {+ once: true,+ });+ before.focus();+ before.dispatchEvent(+ new KeyboardEvent('keydown', {+ key: 'Tab',+ bubbles: true,+ cancelable: true,+ }),+ );+ viewport.focus();+ expect(document.activeElement).toBe(viewport);+ });++ it('restores the skipped viewport on cancellation and cleans up pending work', () => {+ content.innerHTML = '<button>Action</button><button>Last</button>';+ enter();+ const first = content.firstElementChild as HTMLElement;+ (content.lastElementChild as HTMLElement).focus();+ first.focus();+ first.dispatchEvent(+ new KeyboardEvent('keydown', {key: 'Tab', shiftKey: true, bubbles: true}),+ );+ expect(viewport.tabIndex).toBe(-1);+ detach?.();+ detach = undefined;+ expect(viewport.tabIndex).toBe(0);+ enter();+ expect(document.activeElement).toBe(viewport);+ });+});diff --git a/packages/core/src/hooks/scrollKeyboardDelegation.ts b/packages/core/src/hooks/scrollKeyboardDelegation.tsnew file mode 100644index 0000000000..1052ee80f5--- /dev/null+++ b/packages/core/src/hooks/scrollKeyboardDelegation.ts@@ -0,0 +1,233 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file scrollKeyboardDelegation.ts+ * @input A named, overflowing viewport and its real content box+ * @output Focus-time delegation with native forward and reverse Tab traversal+ * @position Private useScrollableArea keyboard behavior; no DOM observers or scrolling+ */++import {FOCUSABLE_SELECTOR} from './focusableSelector';+import {getRegisteredScrollOwnerState} from './scrollOwnerRegistry';++// Structural roles may contain ordinary links/buttons. Unknown or interactive+// roles are deliberately excluded until their navigation contract is proven.+const PASSIVE_ROLES = new Set([+ 'article',+ 'banner',+ 'complementary',+ 'contentinfo',+ 'definition',+ 'directory',+ 'document',+ 'figure',+ 'form',+ 'generic',+ 'group',+ 'heading',+ 'list',+ 'listitem',+ 'main',+ 'navigation',+ 'none',+ 'note',+ 'paragraph',+ 'presentation',+ 'region',+ 'section',+ 'status',+ 'table',+ 'term',+]);++function isSequential(element: HTMLElement): boolean {+ if (+ element.tabIndex < 0 ||+ element.matches(':disabled') ||+ element.closest('[inert], [hidden]') != null ||+ element.getClientRects().length === 0+ ) {+ return false;+ }+ const visibility = getComputedStyle(element).visibility;+ return visibility !== 'hidden' && visibility !== 'collapse';+}++function firstDelegationTarget(+ viewport: HTMLElement,+ content: HTMLElement,+): HTMLElement | null {+ const candidates = content.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR);+ let first =+ content.matches(FOCUSABLE_SELECTOR) && isSequential(content)+ ? content+ : null;+ for (const candidate of candidates) {+ // After finding the first target, only positive tabindex can precede it.+ // Ordinary trailing controls need no visibility or layout reads.+ if (first != null && candidate.tabIndex <= 0) {+ continue;+ }+ if (!isSequential(candidate)) {+ continue;+ }+ // Positive tabindex participates before the zero-index viewport. Do not+ // revisit it or skip its ordering by delegating to a later zero-index child.+ if (candidate.tabIndex > 0) {+ return null;+ }+ first ??= candidate;+ }+ if (+ first == null ||+ first.tabIndex !== 0 ||+ !first.matches('a[href], button') ||+ first.closest('[aria-hidden="true"]') != null ||+ first.matches(+ '[aria-disabled="true"], [aria-haspopup]:not([aria-haspopup="false"])',+ )+ ) {+ return null;+ }++ let ancestor: HTMLElement | null = first;+ while (ancestor != null && ancestor !== viewport) {+ const role: string | undefined = ancestor+ .getAttribute('role')+ ?.trim()+ .toLowerCase();+ const nativeRole: boolean =+ ancestor === first &&+ ((role === 'button' && first.localName === 'button') ||+ (role === 'link' && first.localName === 'a'));+ if (+ (role != null &&+ role !== '' &&+ !nativeRole &&+ !PASSIVE_ROLES.has(role)) ||+ (ancestor === first && role != null && role !== '' && !nativeRole) ||+ ancestor.hasAttribute('aria-activedescendant') ||+ ancestor.isContentEditable ||+ ancestor.matches('[contenteditable]:not([contenteditable="false"])') ||+ getRegisteredScrollOwnerState(ancestor) != null+ ) {+ return null;+ }+ // Also respect native scroll owners that have not adopted the shared hook.+ const style = getComputedStyle(ancestor);+ if (+ (/^(auto|scroll|overlay)$/.test(style.overflowX) &&+ ancestor.scrollWidth > ancestor.clientWidth + 1) ||+ (/^(auto|scroll|overlay)$/.test(style.overflowY) &&+ ancestor.scrollHeight > ancestor.clientHeight + 1)+ ) {+ return null;+ }+ ancestor = ancestor.parentElement;+ }+ return ancestor === viewport ? first : null;+}++/** Attach only while automatic ownership has an effective scroll axis. */+export function attachScrollKeyboardDelegation(+ viewport: HTMLElement,+ content: HTMLElement,+): () => void {+ const document = viewport.ownerDocument;+ const window = document.defaultView;+ if (window == null) {+ return () => {};+ }+ let entry: KeyboardEvent | null = null;+ let origin: EventTarget | null = null;+ let delegated: HTMLElement | null = null;+ let timer: number | undefined;+ let restoreTabStop: (() => void) | undefined;++ const reset = () => {+ entry = null;+ origin = null;+ window.clearTimeout(timer);+ restoreTabStop?.();+ restoreTabStop = undefined;+ };++ const onKeyDown = (event: KeyboardEvent) => {+ reset();+ if (event.key !== 'Tab' || event.ctrlKey || event.metaKey) {+ return;+ }+ // Keep the actual event: focus() during keydown is programmatic (nonzero+ // eventPhase), whereas native Tab focus follows completed event dispatch.+ entry = event;+ origin = event.target;+ if (+ event.shiftKey &&+ delegated != null &&+ document.activeElement === delegated &&+ viewport.contains(delegated)+ ) {+ const tabIndex = viewport.getAttribute('tabindex');+ viewport.tabIndex = -1;+ restoreTabStop = () => {+ if (viewport.getAttribute('tabindex') === '-1') {+ if (tabIndex == null) {+ viewport.removeAttribute('tabindex');+ } else {+ viewport.setAttribute('tabindex', tabIndex);+ }+ }+ };+ }+ // A canceled Tab, focus leaving the document, or a held key must not leave+ // stale keyboard intent for a later pointer/programmatic focus operation.+ timer = window.setTimeout(reset, 0);+ };++ const onFocusIn = (event: FocusEvent) => {+ const keyboardEntry = entry;+ const previous = origin;+ reset();+ if (event.target !== viewport) {+ if (!viewport.contains(event.target as Node | null)) {+ delegated = null;+ }+ return;+ }+ delegated = null;+ if (+ keyboardEntry == null ||+ keyboardEntry.shiftKey ||+ keyboardEntry.defaultPrevented ||+ keyboardEntry.eventPhase !== 0 ||+ (event.relatedTarget != null && event.relatedTarget !== previous)+ ) {+ return;+ }+ const target = firstDelegationTarget(viewport, content);+ if (target == null) {+ return;+ }+ delegated = target;+ // Let native focus reveal the action. Arrow/Page scrolling remains entirely+ // browser-owned, including scroll chaining and the full viewport range.+ target.focus();+ if (document.activeElement !== target) {+ delegated = null;+ }+ };++ document.addEventListener('keydown', onKeyDown, true);+ document.addEventListener('keyup', reset, true);+ document.addEventListener('pointerdown', reset, true);+ document.addEventListener('focusin', onFocusIn, true);+ window.addEventListener('blur', reset);+ return () => {+ reset();+ document.removeEventListener('keydown', onKeyDown, true);+ document.removeEventListener('keyup', reset, true);+ document.removeEventListener('pointerdown', reset, true);+ document.removeEventListener('focusin', onFocusIn, true);+ window.removeEventListener('blur', reset);+ };+}diff --git a/packages/core/src/hooks/useScrollableArea.doc.mjs b/packages/core/src/hooks/useScrollableArea.doc.mjsindex ba0b9cdcb8..8115983dc6 100644--- a/packages/core/src/hooks/useScrollableArea.doc.mjs+++ b/packages/core/src/hooks/useScrollableArea.doc.mjs@@ -1,5 +1,12 @@// Copyright (c) Meta Platforms, Inc. and affiliates.+/**+ * @file useScrollableArea.doc.mjs+ * @input Shared scroll hook's fixed and entry-time keyboard policies+ * @output Consumer guidance for named viewports and safe focus delegation+ * @position Hook documentation consumed by the CLI and docsite+ */+/** @type {import('@astryxdesign/cli/authoring').HookDoc} */export const docs = {name: 'useScrollableArea',@@ -18,7 +25,7 @@ export const docs = {name: 'options',type: 'UseScrollableAreaOptions',description:- 'Logical scroll intent, keyboard owner, overscroll policy, and fitting Sticky containment.',+ 'Logical scroll intent, fixed or automatic keyboard owner, overscroll policy, and fitting Sticky containment.',required: true,},],@@ -59,7 +66,12 @@ export const docs = {{guidance: true,description:- 'Use content keyboard ownership when an existing focusable descendant gives keyboard users access to all overflowed content.',+ 'Use contentOrViewport to delegate forward Tab entry to the first sequential native link or button when it preserves native scroll keys. Inputs, composite widgets, and nested scroll areas retain the named viewport stop. Shift+Tab from the delegated first child skips the viewport; pointer and programmatic focus stay on it.',+ },+ {+ guidance: true,+ description:+ 'Use content keyboard ownership when your integration already supplies keyboard access to the full scroll range. Automatic delegation checks current content at each keyboard entry without continuously tracking its focusability.',},{guidance: true,@@ -85,7 +97,7 @@ export const docsDense = {'Composes logical-axis scrolling into caller-owned viewport/content elements with stable effective-axis and edge state.',paramDescriptions: {options:- 'axis, keyboard owner, allow/contain overscroll policy, and fitting Sticky containment.',+ 'axis, fixed/automatic keyboard owner, allow/contain overscroll policy, and fitting Sticky containment.',},returnDescriptions: {getViewportProps:diff --git a/packages/core/src/hooks/useScrollableArea.test.tsx b/packages/core/src/hooks/useScrollableArea.test.tsxindex 1b16a4bf1a..0cf48a5767 100644--- a/packages/core/src/hooks/useScrollableArea.test.tsx+++ b/packages/core/src/hooks/useScrollableArea.test.tsx@@ -1,8 +1,15 @@// Copyright (c) Meta Platforms, Inc. and affiliates.+/**+ * @file useScrollableArea.test.tsx+ * @input Shared scroll hook, mocked geometry, and observed DOM changes+ * @output Regression coverage for measurement, composition, and stable viewport access+ * @position DOM-level hook contract; native traversal is verified in browser tests+ */+import {act, render, screen} from '@testing-library/react';import * as stylex from '@stylexjs/stylex';-import {useRef, type Ref} from 'react';+import {useRef, type ReactNode, type Ref} from 'react';import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';import {useScrollableArea,@@ -194,6 +201,57 @@ describe('useScrollableArea', () => {expect(viewport.getAttribute('style')).toContain('--x-overflowY: hidden');});+ it('keeps the named viewport available while content eligibility changes', () => {+ function AdaptiveFixture({children}: {children?: ReactNode}) {+ const area = useScrollableArea({+ axis: 'block',+ keyboardAccess: {+ owner: 'contentOrViewport',+ label: 'Adaptive results',+ role: 'region',+ },+ });+ return (+ <div data-testid="adaptive-viewport" {...area.getViewportProps()}>+ <div data-testid="adaptive-content" {...area.getContentProps()}>+ {children}+ </div>+ </div>+ );+ }++ vi.spyOn(HTMLElement.prototype, 'getClientRects').mockReturnValue([+ new DOMRect(0, 0, 20, 20),+ ] as unknown as DOMRectList);+ const {rerender} = render(<AdaptiveFixture>Plain text</AdaptiveFixture>);+ const viewport = screen.getByTestId('adaptive-viewport');+ const content = screen.getByTestId('adaptive-content');+ makeMeasurable(viewport);+ setGeometry(viewport, {scrollHeight: 180});++ void act(() => viewport.dispatchEvent(new Event('scroll')));+ flushFrame();+ expect(viewport).toHaveAttribute('role', 'region');+ expect(viewport).toHaveAccessibleName('Adaptive results');+ expect(viewport).toHaveAttribute('tabindex', '0');++ viewport.focus();+ rerender(+ <AdaptiveFixture>+ <button type="button">Use existing action</button>+ </AdaptiveFixture>,+ );+ void act(() => content.dispatchEvent(new Event('transitionend')));+ flushFrame();+ expect(viewport).toHaveAttribute('tabindex', '0');+ expect(viewport).toHaveFocus();++ rerender(<AdaptiveFixture>Plain text again</AdaptiveFixture>);+ void act(() => content.dispatchEvent(new Event('transitionend')));+ flushFrame();+ expect(viewport).toHaveAttribute('tabindex', '0');+ });+it('requires scroll-capable computed overflow and more than 1px excess geometry', () => {render(<Fixture />);const viewport = screen.getByTestId('viewport');diff --git a/packages/core/src/hooks/useScrollableArea.ts b/packages/core/src/hooks/useScrollableArea.tsindex d0794b2260..1b4236ace6 100644--- a/packages/core/src/hooks/useScrollableArea.ts+++ b/packages/core/src/hooks/useScrollableArea.ts@@ -4,8 +4,8 @@/*** @file useScrollableArea.ts- * @input Logical scroll intent, keyboard ownership, caller-owned viewport/content props- * @output Safe prop getters and stable per-axis effective scroll state+ * @input Logical scroll intent, focus-time keyboard delegation, caller-owned viewport/content props+ * @output Safe prop getters, native keyboard entry, and stable per-axis effective scroll state* @position Canonical behavior core for ScrollableArea and structure-owning adopters** SYNC: When modified, update:@@ -26,6 +26,7 @@ import {} from 'react';import * as stylex from '@stylexjs/stylex';import type {BaseProps} from '../BaseProps';+import {attachScrollKeyboardDelegation} from './scrollKeyboardDelegation';import {useIsomorphicLayoutEffect} from './useIsomorphicLayoutEffect';import {mergeProps} from '../utils/mergeProps';import {mergeRefs} from '../utils/mergeRefs';@@ -48,7 +49,12 @@ export type ScrollStickyContainment = 'whenScrollable' | 'always';export type ScrollKeyboardAccess =| {owner: 'content'}- | {owner: 'viewport'; label: string; role?: 'group' | 'region'};+ | {owner: 'viewport'; label: string; role?: 'group' | 'region'}+ | {+ owner: 'contentOrViewport';+ label: string;+ role?: 'group' | 'region';+ };export interface ScrollAxisState {isScrollable: boolean;@@ -285,6 +291,8 @@ export function useScrollableArea({content.addEventListener('transitionend', scheduleMeasure);content.addEventListener('animationend', scheduleMeasure);+ // Geometry invalidation is independent of keyboard eligibility. The latter+ // is inspected only on native keyboard entry, never by these observers.const mutationObserver =typeof MutationObserver === 'undefined'? null@@ -346,6 +354,20 @@ export function useScrollableArea({[axis, measured],);+ const hasEffectiveAxis =+ state.inline.isScrollable || state.block.isScrollable;+ useIsomorphicLayoutEffect(() => {+ if (+ keyboardAccess.owner !== 'contentOrViewport' ||+ !hasEffectiveAxis ||+ viewport == null ||+ content == null+ ) {+ return;+ }+ return attachScrollKeyboardDelegation(viewport, content);+ }, [content, hasEffectiveAxis, keyboardAccess.owner, viewport]);+const getViewportProps = useCallback(<E extends HTMLElement>(props: ScrollableElementProps<E> = {},@@ -385,8 +407,9 @@ export function useScrollableArea({),),) as ScrollableElementProps<E>;+ const viewportIsKeyboardOwner = keyboardAccess.owner !== 'content';const keepsProgrammaticFocus =- !hasEffectiveAxis &&+ (!viewportIsKeyboardOwner || !hasEffectiveAxis) &&viewport != null &&typeof document !== 'undefined' &&document.activeElement === viewport;@@ -409,15 +432,16 @@ export function useScrollableArea({}const keyboardProps =- keyboardAccess.owner === 'viewport'+ keyboardAccess.owner !== 'content'? {role: keyboardAccess.role ?? 'group','aria-label': keyboardAccess.label,- tabIndex: hasEffectiveAxis- ? 0- : keepsProgrammaticFocus- ? -1- : undefined,+ tabIndex:+ viewportIsKeyboardOwner && hasEffectiveAxis+ ? 0+ : keepsProgrammaticFocus+ ? -1+ : undefined,}: {};diff --git a/playwright.config.ts b/playwright.config.tsindex a83c7675a9..a3d1d9ea67 100644--- a/playwright.config.ts+++ b/playwright.config.ts@@ -3,7 +3,7 @@/*** @file playwright.config.ts* @input Uses @playwright/test- * @output The real-Chromium lane for the accessibility spec-test contracts.+ * @output Chromium accessibility contracts and Chromium/WebKit keyboard proofs.* @position Run with `pnpm test:a11y-contract`. Deliberately separate from* `pnpm test`: the Vitest projects must stay runnable from a cold clone with* no browser installed, and the accessibility-tree and real-browser evidence@@ -18,8 +18,12 @@* artifact every other Chromium check in this repository uses. Build it first:** pnpm storybook:build- * npx playwright install chromium+ * pnpm exec playwright install chromium webkit* pnpm test:a11y-contract+ * pnpm exec playwright test BottomSheetKeyboard.a11y.browser.spec.ts+ *+ * Cross-browser specs use `.a11y.browser.spec.ts`; Chromium-only contracts keep+ * `.a11y.chromium.spec.ts`. The WebKit project runs only the former.** SYNC: When a package gains an accessibility binding, add its spec glob here.*/@@ -37,6 +41,7 @@ export default defineConfig({'internal/a11y-spec/src/**/*.chromium.spec.ts',// Component bindings.'packages/*/src/**/*.a11y.chromium.spec.ts',+ 'packages/*/src/**/*.a11y.browser.spec.ts',],// The contract mounts, focuses, and types into one page at a time; parallel// workers would race over real keyboard focus.@@ -48,5 +53,12 @@ export default defineConfig({// `use.reducedMotion` nor Chromium's `--force-prefers-reduced-motion` reaches// `matchMedia` in this Playwright version — both were measured returning// false. The specs call `holdMotionStill(page)` instead, which does work.- projects: [{name: 'chromium', use: {...devices['Desktop Chrome']}}],+ projects: [+ {name: 'chromium', use: {...devices['Desktop Chrome']}},+ {+ name: 'webkit',+ testMatch: ['packages/*/src/**/*.a11y.browser.spec.ts'],+ use: {...devices['Desktop Safari']},+ },+ ],});