An open source design system that's fully customizable and agent ready
TypeScript
fix(a11y): name a scrolling LayoutContent, LayoutPanel or StackItem (#9985)
Christopher Chedeaucb2a34a62159
diff --git a/.changeset/scroll-region-name.md b/.changeset/scroll-region-name.mdnew file mode 100644index 0000000000..be8d6f546e--- /dev/null+++ b/.changeset/scroll-region-name.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] LayoutContent, LayoutPanel and a scrollable `div` or `span` StackItem name their region while it scrolls. Before, a scrolling region was a nameless element that Chromium could make a Tab stop, so a screen reader announced nothing about it. It is now a group named by the caller's label, or by a translated "Content" (accessibility target: LayoutContent AR3, LayoutPanel AR3 and Stack AR2). A caller's role stays with only the caller's name, and Tab behavior stays the browser's.++@vjeuxdiff --git a/apps/storybook/stories/ScrollRegionA11y.stories.tsx b/apps/storybook/stories/ScrollRegionA11y.stories.tsxnew file mode 100644index 0000000000..79a56f0550--- /dev/null+++ b/apps/storybook/stories/ScrollRegionA11y.stories.tsx@@ -0,0 +1,137 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** Storybook fixtures for the accessible name of a scrolling region. */++import type {Meta, StoryObj} from '@storybook/react';+import type {ReactNode} from 'react';+import * as stylex from '@stylexjs/stylex';+import {+ Layout,+ LayoutContent,+ LayoutPanel,+ StackItem,+ VStack,+} from '@astryxdesign/core/Layout';++const styles = stylex.create({+ frame: {+ height: 240,+ },+});++const LINES = Array.from({length: 40}, (_, index) => `Line ${index + 1}`);++function Lines() {+ return LINES.map(line => <p key={line}>{line}</p>);+}++function Frame({children}: {children: ReactNode}) {+ return <div {...stylex.props(styles.frame)}>{children}</div>;+}++const meta: Meta = {+ title: 'a11y/Scroll region name',+ tags: ['no-visual'],+ parameters: {layout: 'padded'},+};++export default meta;++export const ContentScrolls: StoryObj = {+ render: () => (+ <Frame>+ <Layout+ content={+ <LayoutContent data-scroll-region>+ <Lines />+ </LayoutContent>+ }+ />+ </Frame>+ ),+};++export const ContentFits: StoryObj = {+ render: () => (+ <Frame>+ <Layout+ content={<LayoutContent data-scroll-region>Line 1</LayoutContent>}+ />+ </Frame>+ ),+};++export const ContentLabelled: StoryObj = {+ render: () => (+ <Frame>+ <Layout+ content={+ <LayoutContent data-scroll-region label="Messages">+ <Lines />+ </LayoutContent>+ }+ />+ </Frame>+ ),+};++export const ContentMain: StoryObj = {+ render: () => (+ <Frame>+ <Layout+ content={+ <LayoutContent data-scroll-region role="main">+ <Lines />+ </LayoutContent>+ }+ />+ </Frame>+ ),+};++export const PanelScrolls: StoryObj = {+ render: () => (+ <Frame>+ <Layout+ start={+ <LayoutPanel data-scroll-region hasDivider>+ <Lines />+ </LayoutPanel>+ }+ content={<LayoutContent>Line 1</LayoutContent>}+ />+ </Frame>+ ),+};++export const StackItemScrolls: StoryObj = {+ render: () => (+ <VStack height={240}>+ <StackItem data-scroll-region isScrollable size="fill">+ <Lines />+ </StackItem>+ </VStack>+ ),+};++export const StackItemListScrolls: StoryObj = {+ render: () => (+ <VStack height={240}>+ <StackItem as="ul" data-scroll-region isScrollable size="fill">+ {LINES.map(line => (+ <li key={line}>{line}</li>+ ))}+ </StackItem>+ </VStack>+ ),+};++export const StackItemStatic: StoryObj = {+ render: () => (+ <VStack height={240}>+ <StackItem data-scroll-region size="fill">+ <Lines />+ </StackItem>+ </VStack>+ ),+};diff --git a/docs/specs/components/Layout/LayoutContent.spec.md b/docs/specs/components/Layout/LayoutContent.spec.mdindex 0c1e4eb8f1..eabedf103f 100644--- a/docs/specs/components/Layout/LayoutContent.spec.md+++ b/docs/specs/components/Layout/LayoutContent.spec.md@@ -16,6 +16,8 @@ verified_by:packages/core/src/Layout/__tests__/contentWidth.test.tsx,packages/core/src/Layout/__tests__/Layout.a11y.test.tsx,packages/core/src/Layout/__tests__/Layout.a11y.chromium.spec.ts,+ packages/core/src/hooks/useScrollRegionProps.test.tsx,+ packages/core/src/hooks/__tests__/scrollRegionName.a11y.chromium.spec.ts,.github/visual-baseline/manifest.json,scripts/check-knowledge.mjs,apps/storybook/rtl-audit/targets.json,@@ -42,8 +44,8 @@ system_specs: [spec:AST-038]| Public contract | `children`, `isScrollable`, `padding`, `label`, `role`, root `BaseProps`, and a root `ref`. || Behavior | The main content region fills the Layout's middle area, scrolls by default, and insets its children from neighbouring regions and open edges. || End-user impact | People scroll the main content while headers, footers, and panels stay put, with the scrollbar at the content area's open edge. |-| Builder impact | None; the record describes shipped behavior. |-| Compatibility/readiness | Released behavior recorded as current; no API, default, or output changes. Three implementation gaps are listed under Current-state impact. |+| Builder impact | None: no API change; a scrolling region gains a role and a name with no code change (AR3). |+| Compatibility/readiness | No API or default changes; the scrolling-region role and name (AR3) are a patch `[fix]`. Three gaps are listed under Current-state impact. || Review checks | Reject an inner wrapper around the children, a scrollbar moved off the open edge, an inferred landmark, or a further publication mismatch. || Governing rules | `family:layout-regions` FR1, FR3, FR4, FR7, FR8, FR12; `architecture:container-padding`; `architecture:public-component-api` INV5–INV8. |@@ -61,8 +63,10 @@ Consumer syntax and examples belong in `LayoutContent.doc.mjs`.- Released default preserved: `yes` — scrollable, automatic inset, nolandmark role.-- Compatibility class: records shipped behavior; no public prop, default, DOM,- target, or styling output changes.+- Compatibility class: patch. No public prop, default, target, or styling+ output changes. While it scrolls, a region with no caller `role` gains+ `role="group"` and an `aria-label` (DOM; AR3, `[fix]` under+ `spec:AST-017` FR53).- Controlled/uncontrolled behavior: not applicable- Migration decision: none@@ -121,7 +125,7 @@ Consumer migration instructions belong in consumer docs and release notes.| FR1 | LayoutContent renders one `div` carrying the `layout-content` target that fills the middle area's height and remaining width and holds the children directly. It scrolls overflow by default; `isScrollable={false}` clips it. | Current source and tests; `family:layout-regions` FR7 || FR2 | Without `padding`, each edge that faces another region (a panel, header, or footer) has the inner inset, and each open edge has the Layout-edge inset, where the Layout-edge inset comes from the Layout's `padding`, else the nearest padding container, and the inner inset from the nearest padding container (Card, Section, Dialog, Drawer, or BottomSheet), each spacing step 4 otherwise; a block edge beside a header or footer without a divider collapses to zero. A `padding` step replaces all four edges, and `0` removes them. The region publishes container-padding values equal to the padding it applies, excluding the content-width alignment gutter of FR3, which is applied but not published. Implementation gaps: with only a start panel the open inline-end edge applies the inner inset; the published values differ from the applied padding with only an end panel and beside a header or footer without a divider; and a nested Layout inherits an outer header's or footer's collapse, so its content sits flush against its own divider (Current-state impact). | Current source; `family:layout-regions` FR4, FR6; `architecture:container-padding` || FR3 | When the Layout sets a content width, the region keeps its own box and scrollbar where `component:Layout` FR6 places them and aligns its children to that width through its inline padding, never less than its inset. With `padding={0}` it stays full bleed. | Current source and tests; `family:layout-regions` FR12 |-| FR4 | `role` and `label` set the root's `role` and `aria-label`; LayoutContent adds no role of its own. | Current source and tests; `family:layout-regions` FR8 |+| FR4 | `role` and `label` set the root's `role` and `aria-label`; LayoutContent adds a role and a name of its own only while it scrolls (AR3). | Current source and tests; `family:layout-regions` FR8 || FR5 | `ref` reaches the root. Supported DOM, data, ARIA, and event props reach the root after the component's own attributes; `xstyle`, `className`, and `style` compose after component styles. | Current source and tests; `architecture:public-component-api` INV5–INV8 |### Allowed variation@@ -149,7 +153,8 @@ Consumer migration instructions belong in consumer docs and release notes.### Performance and resources- **PR1 — No external lifecycle.** LayoutContent reads which slots its Layout- fills and adds no listener, observer, timer, or measurement.+ fills. It adds no listener, observer, timer, or measurement, except the+ overflow observation of AR3 while it may scroll.## Accessibility contract@@ -159,6 +164,13 @@ Consumer migration instructions belong in consumer docs and release notes.- **AR2 — Keyboard scrolling.** A scrolling region is a browser scrollcontainer, so its overflow scrolls with the keyboard once focus is insideit or on it.+- **AR3 — A scrolling region is named.** While the region scrolls, its+ scrolling element has `role="group"` (unless the caller sets a `role`) and+ an accessible name (the caller's `label`, or a translated "Content"), so a+ screen reader that reaches it, including as a browser-made Tab stop,+ announces it; Tab behavior is the browser's (owner decision, 2026-11-04).+ A caller's `role` takes only the caller's `label` (AR1), so a single main+ landmark relies on its role (`spec:AST-025` FR12).## Design relationships@@ -189,7 +201,8 @@ anatomy of its own, so no anatomy-theming block is declared here.| FR3 | `contentWidth.test.tsx`; stable visual baseline `core-layout--content-width-scrollbar-placement` | No panels, one panel, both; zero padding | A content region that is not full width without panels, children not aligned, or a lost full bleed fails; a scrollbar moved off its edge comes back changed for review. | `audit:LayoutContent/layout` || FR4, AR1 | `LayoutSlots.test.tsx` landmark test; `Layout.a11y.test.tsx` and `Layout.a11y.chromium.spec.ts` `content-main` state | Caller `main` role and label | A lost role or name fails, including at the accessibility tree. Gap: no test asserts that a region without `role` exposes none. | `audit:LayoutContent/accessibility` || FR5 | `LayoutSlots.test.tsx` ref and className/style tests | Ref; caller class and style | A ref on another element, or a dropped class or style, fails. Gap: no test covers DOM, data, or event props, or the `xstyle` merge order. | `audit:LayoutContent/api` |-| AR2, PR1 | Source review | Scrolling region | Gap: no automated check covers keyboard scrolling or fails if LayoutContent adds a listener or measurement. | `audit:LayoutContent/behavior` |+| AR2, PR1 | Source review | Scrolling region | Gap: no automated check covers keyboard scrolling or fails if LayoutContent adds a listener or measurement beyond AR3's. | `audit:LayoutContent/behavior` |+| AR3 | `useScrollRegionProps.test.tsx` LayoutContent tests; `scrollRegionName.a11y.chromium.spec.ts` | Scrolling, fitting, labelled, `main`, not scrollable | A group role or name missing while it overflows, or present while it fits or cannot scroll, fails, in Chromium's accessibility tree too; a lost caller role or label, a default landmark name, or a tab index fails. | `audit:LayoutContent/accessibility` || RTL relation | RTL audit curated D8 target (`apps/storybook/rtl-audit/targets.json`) on the `Content width with start panel` story | Start panel with a centered content width (logical padding 16px start, 144px end); LTR and RTL | A logical start/end padding pair that does not swap physical sides in RTL fails D8. | `audit:LayoutContent/i18n-rtl` |## Decision logdiff --git a/docs/specs/components/Layout/LayoutPanel.spec.md b/docs/specs/components/Layout/LayoutPanel.spec.mdindex 596829f4bb..46994b60a3 100644--- a/docs/specs/components/Layout/LayoutPanel.spec.md+++ b/docs/specs/components/Layout/LayoutPanel.spec.md@@ -15,6 +15,8 @@ verified_by:packages/core/src/Layout/LayoutSlots.test.tsx,packages/core/src/Layout/__tests__/Layout.a11y.test.tsx,packages/core/src/Layout/__tests__/Layout.a11y.chromium.spec.ts,+ packages/core/src/hooks/useScrollRegionProps.test.tsx,+ packages/core/src/hooks/__tests__/scrollRegionName.a11y.chromium.spec.ts,scripts/check-knowledge.mjs,apps/storybook/rtl-audit/targets.json,]@@ -40,8 +42,8 @@ system_specs: [spec:AST-105]| Public contract | `children`, `width`, `resizable`, `hasDivider`, `isScrollable`, `padding`, `label`, `role`, root `BaseProps`, and a root `ref`. || Behavior | A fixed-width side region at logical start or end that scrolls by default, with an optional divider on its content-facing edge. || End-user impact | People see a side panel that keeps its width, scrolls on its own, and mirrors to the other side in right-to-left. |-| Builder impact | None: no API change; a collapsing resizable panel slides with no code change. |-| Compatibility/readiness | No API or default changes; a collapsing resizable panel slides (FR7) and moves focus out, then becomes inert (AR2): patch, `[feat]` slide and `[fix]` focus. Implementation gaps are listed under Current-state impact. |+| Builder impact | None: no API change; a collapsing resizable panel slides, and a scrolling panel gains a role and a name, with no code change. |+| Compatibility/readiness | No API or default changes; a collapsing resizable panel slides (FR7) and moves focus out, then becomes inert (AR2), and a scrolling panel is named, as a group (AR3): patch, `[feat]` slide and `[fix]` focus and name. || Review checks | Reject a divider on the outer edge, a panel that shrinks, an inferred landmark, `width` beating `resizable`, or a further publication mismatch. || Governing rules | `family:layout-regions` FR1, FR2, FR4–FR8, FR10; `architecture:container-padding`; `architecture:public-component-api` INV5–INV8. |@@ -63,7 +65,9 @@ Consumer syntax and examples belong in `LayoutPanel.doc.mjs`.output changes. A collapsing resizable panel now slides (FR7, `[feat]`,visual-only under `spec:AST-017/DEC-17`), and focus inside it moves to theadjacent ResizeHandle while the collapsed panel becomes inert (DOM: `inert`- and `aria-hidden`; AR2, `[fix]` under `spec:AST-017` FR53).+ and `aria-hidden`; AR2, `[fix]` under `spec:AST-017` FR53). While it+ scrolls, a panel with no caller `role` gains `role="group"` and an+ `aria-label` (DOM; AR3, `[fix]` under `spec:AST-017` FR53).- Controlled/uncontrolled behavior: not applicable- Migration decision: none@@ -120,7 +124,7 @@ Consumer migration instructions belong in consumer docs and release notes.| FR2 | In the `start` slot the panel's content-facing edge is its inline end; in the `end` slot it is its inline start; both follow writing direction. | Current source and tests; `family:layout-regions` FR2 || FR3 | Without `padding`, the panel's outer inline edge has the Layout-edge inset, a block edge with no header or footer beside it has the Layout-edge inset, and other edges have the inner inset, where the Layout-edge inset comes from the Layout's `padding`, else the nearest padding container, and the inner inset from the nearest padding container (Card, Section, Dialog, Drawer, or BottomSheet), each spacing step 4 otherwise. A `padding` step replaces all four edges, and `0` removes them. The panel publishes container-padding values equal to the padding it applies. Implementation gap: on the automatic path it publishes the inner inset on every edge (Current-state impact). | Current source; `family:layout-regions` FR4; `architecture:container-padding` || FR4 | `hasDivider` draws a 1px solid `--color-border` line on the content-facing edge; LayoutPanel does not read a Layout divider default. Without a divider and with the automatic inset, the panel overlaps the content area by the inner inset so the two share one gap. One boundary has one divider owner (`family:layout-regions` FR5). Implementation gap: nothing prevents a panel divider and an adjacent ResizeHandle line from both painting (Current-state impact). | Current source and docs; `family:layout-regions` FR5, FR6 |-| FR5 | `role` and `label` set the root's `role` and `aria-label`; LayoutPanel adds no role of its own. | Current source and tests; `family:layout-regions` FR8 |+| FR5 | `role` and `label` set the root's `role` and `aria-label`; LayoutPanel adds a role and a name of its own only while it scrolls (AR3). | Current source and tests; `family:layout-regions` FR8 || FR6 | `ref` reaches the root. Supported DOM, data, ARIA, and event props reach the root after the component's own attributes; `xstyle`, `className`, and `style` compose after component styles. | Current source and tests; `architecture:public-component-api` INV5–INV8 || FR7 | A LayoutPanel whose size comes from a resize controller lends its element to the controller of the ResizeHandle on its content-facing edge through an internal channel, so the panel slides closed and open by `spec:AST-105` FR9's edge reveal when its region collapses or opens: its content-facing edge (FR2) moves, and the content on that edge's side moves on the same motion (`component:Resizable` FR8). A panel given the configuration-object form, a hand-built `ResizableProps` object that `useResizable` did not return passed through `resizable`, and a panel with no resize controller, never slide; `useResizable`'s own `props` passed through `resizable` do slide. LayoutPanel adds no prop. Implementation gap: no panel slides yet (Current-state impact). | `spec:AST-105` FR9; `component:Resizable` FR8 |@@ -148,8 +152,9 @@ Consumer migration instructions belong in consumer docs and release notes.### Performance and resources- **PR1 — No external lifecycle.** LayoutPanel reads its slot and which slots- its Layout fills, and adds no listener, observer, timer, or measurement of- its own; the slide's measurement is the resize controller's (FR7).+ its Layout fills. It adds no listener, observer, timer, or measurement of+ its own, except the overflow observation of AR3 while it may scroll; the+ slide's measurement is the resize controller's (FR7).## Accessibility contract@@ -166,6 +171,12 @@ Consumer migration instructions belong in consumer docs and release notes.where it is. Only the slide (FR7) excludes the configuration-object form.Implementation gap: focus stays in a collapsed panel, which stays reachable(Current-state impact).+- **AR3 — A scrolling panel is named.** While the panel scrolls, its+ scrolling element has `role="group"` (unless the caller sets a `role`) and+ an accessible name (the caller's `label`, or a translated "Content"), so a+ screen reader that reaches it, including as a browser-made Tab stop,+ announces it; Tab behavior is the browser's (owner decision, 2026-11-04).+ A caller's `role` takes only the caller's `label` (AR1).## Design relationships@@ -200,6 +211,7 @@ of its own, so no anatomy-theming block is declared here.| FR5, AR1 | `LayoutSlots.test.tsx` landmark test; `Layout.a11y.test.tsx` and `Layout.a11y.chromium.spec.ts` `start-end-navigation-rtl` and `nested-panel-region` states | Caller `navigation` and `region` roles and labels | A lost role or name fails, including at the accessibility tree. Gap: no test asserts that a panel without `role` exposes none. | `audit:LayoutPanel/accessibility` || FR6 | `LayoutSlots.test.tsx` ref and className tests | Ref; caller class | A ref on another element or a dropped class fails. Gap: no test covers `style`, DOM, data, or event props, or the `xstyle` merge order. | `audit:LayoutPanel/api` || FR7, AR2 | Real-browser frame capture of a start and an end panel collapsing and opening, with focus inside, with the hook's `props` and with a hand-built object (pending) | Start and end; toggle, Enter and a drag past the threshold; configuration-object form; Reduce Motion | A jump instead of a slide, a gap beside the moving edge, a slide under the configuration-object form, focus left in a collapsed panel, a collapsed panel reachable by Tab or exposed to assistive technology, or a new prop fails. | `audit:LayoutPanel/behavior` |+| AR3 | `useScrollRegionProps.test.tsx` LayoutPanel tests; `scrollRegionName.a11y.chromium.spec.ts` `panel-scrolls` | Scrolling panel; caller `navigation` role and label | A group role or name missing while the panel overflows fails, at Chromium's accessibility tree too; a caller's role or label lost fails. | `audit:LayoutPanel/accessibility` || PR1 | Source review | Every state | Gap: no automated check fails if LayoutPanel adds a listener, timer, or measurement. | `audit:LayoutPanel/behavior` || RTL relation | RTL audit curated D2 target (`apps/storybook/rtl-audit/targets.json`) on the `Content width with start panel` story | Start panel beside the content; LTR and RTL | A start panel that is not at the inline start of the content in both directions fails D2. | `audit:LayoutPanel/i18n-rtl` |diff --git a/docs/specs/components/Stack/Stack.spec.md b/docs/specs/components/Stack/Stack.spec.mdindex e3667534d6..41a2b1c226 100644--- a/docs/specs/components/Stack/Stack.spec.md+++ b/docs/specs/components/Stack/Stack.spec.md@@ -16,6 +16,8 @@ verified_by:.github/visual-baseline/manifest.json,packages/core/src/Stack/Stack.test.tsx,packages/core/src/Stack/StackItem.test.tsx,+ packages/core/src/hooks/useScrollRegionProps.test.tsx,+ packages/core/src/hooks/__tests__/scrollRegionName.a11y.chromium.spec.ts,packages/core/src/HStack/HStack.test.tsx,packages/core/src/VStack/VStack.test.tsx,packages/core/src/theme/themingTargets.test.ts,@@ -47,8 +49,8 @@ system_specs: []| Public contract | Stack arranges children on one flex axis with `direction`, alignment, `gap`, per-edge `padding`, sizing, `wrap`, `isScrollable`, and `as`. HStack and VStack fix the direction; StackItem controls one child's participation. || Behavior | Alignment props resolve to the main or cross axis from the direction; padding resolves per logical edge; padding stays local and publishes no container inset. || End-user impact | Readers see consistent spacing and alignment that follows the writing direction. |-| Builder impact | None; the record describes shipped behavior. |-| Compatibility/readiness | Released behavior recorded as current; no API, default, or output changes. |+| Builder impact | None: no API change; a scrolling `div` or `span` StackItem gains a role and a name with no code change (AR2). |+| Compatibility/readiness | No API or default changes; the role and name of a scrolling `div` or `span` StackItem (AR2) are a patch `[fix]`. || Review checks | Reject physical left/right padding, an alias that wins over an explicit alignment, padding that publishes container inset, or a StackItem without the flex minimum reset. || Governing rules | `family:layout-primitives/FR1–FR6,FR8`; `architecture:container-padding/INV8`; `architecture:public-component-api/INV5,INV6,INV8`. |@@ -64,8 +66,10 @@ inside it.## Compatibility and migration- Released default preserved: `yes`-- Compatibility class: records shipped behavior; no public prop, default, DOM,- or styling output changes+- Compatibility class: patch. No public prop, default, or styling output+ changes. While it scrolls, a scrollable `div` or `span` StackItem with no+ caller `role` gains `role="group"` and an `aria-label` (DOM; AR2, `[fix]`+ under `spec:AST-017` FR53)- Controlled/uncontrolled behavior: not applicable- Migration decision: none@@ -139,12 +143,21 @@ Consumer migration instructions belong in consumer docs and release notes.### Performance and resources- **PR1 — Static render.** Stack, HStack, VStack, and StackItem hold no state and- use no hooks.+ use no hooks. The one exception is a scrollable `div` or `span` StackItem:+ it renders through a client island that observes its overflow for AR2.## Accessibility contract- **AR1 — No semantics added.** Stack and StackItem add no role, name, or tab- stop of their own; their semantics are those of the `as` element.+ stop of their own; their semantics are those of the `as` element. The one+ exception is the name of a scrolling StackItem (AR2).+- **AR2 — A scrolling StackItem is named.** While a scrollable `div` or+ `span` StackItem scrolls, its element has `role="group"` (unless the+ caller sets a `role`) and an accessible name (the caller's `aria-label`, or+ a translated "Content"), so a screen reader that reaches it, including as+ a browser-made Tab stop, announces it; Tab behavior is the browser's (owner+ decision, 2026-11-04). A caller's `role` takes only the caller's+ `aria-label`, and another element keeps its own role and name.## Design relationships@@ -191,6 +204,7 @@ Consumer migration instructions belong in consumer docs and release notes.| FR4 | Source review against `architecture:container-padding` | Padded stack | Gap: no automated check fails if Stack publishes container-padding variables. | `audit:Stack/layout` || Theming anatomy map | `scripts/check-knowledge.mjs` | Consumer anatomy and current targets | Missing, extra, or stale mappings fail repository validation. | `audit:Stack/theming` || AR1, PR1 | `serverSafeComponents.test.ts`; `HStack.test.tsx` no-role test; `HStackAudit` frames; source review | Every form | A client API (state, an effect, a context read) added without a client directive fails `serverSafeComponents.test.ts`. `HStack.test.tsx` and the `HStackAudit` frames fail if Stack adds a role or tab stop on its horizontal path. Gap: a client API added together with a client directive passes, and no automated check fails if Stack adds a role or tab stop on its vertical path, or StackItem adds either. | `audit:Stack/behavior` |+| AR2 | `useScrollRegionProps.test.tsx` StackItem tests; `scrollRegionName.a11y.chromium.spec.ts` `stack-item-scrolls` and `stack-item-static` | Scrolling item; caller `region` role and `aria-label`; item that is not scrollable | A group role or name missing while the item overflows, or present on an item that is not scrollable, fails, at Chromium's accessibility tree too; a caller's role or `aria-label` lost fails. | `audit:Stack/behavior` || RTL relation | RTL audit curated targets (`apps/storybook/rtl-audit/targets.json`): Stack and StackItem D2 on `Stack / Horizontal` and `Stack / StackItem fill size`, HStack D2 on `AspectRatio / Height driven` and `HStack / Alignment Matrix`, VStack D4 on `Spinner / Narrow flex host` | Horizontal stacks, static and fill items, and a start-aligned vertical stack; LTR and RTL | A horizontal stack whose first child is not at the inline start, or a start-aligned vertical stack child that does not move to the mirrored side, fails D2 or D4. | `audit:Stack/i18n-rtl` |## Decision logdiff --git a/packages/core/locales/en.json b/packages/core/locales/en.jsonindex 63d5c996ee..a43e611e5a 100644--- a/packages/core/locales/en.json+++ b/packages/core/locales/en.json@@ -1323,6 +1323,10 @@"defaultMessage": "Loading","description": "Screen-reader-only default name for a standalone Spinner's role=\"status\" element, used when the consumer supplies neither `aria-label` nor a visible string label; also announced once when a busy input or selector starts loading, in place of its decorative Spinner. Present-progressive form. Kept separate from `button.loading` and `typeahead.loading` — translations may diverge."},+ "@astryx.scrollRegion.label": {+ "defaultMessage": "Content",+ "description": "Accessible name of a scrolling content region (LayoutContent, LayoutPanel or StackItem) when the caller gives none. A screen reader announces it with the region's group role while the region scrolls."+ },"@astryx.chatComposerDrawer.expand": {"defaultMessage": "Expand {label}","description": "Screen-reader-only label on the ChatComposerDrawer toggle when the drawer is collapsed. `{label}` is the drawer's visible name — example: `Expand Attachments`. Pairs with `collapse`."diff --git a/packages/core/src/AppShell/observeMainOverflow.ts b/packages/core/src/AppShell/observeMainOverflow.tsindex 97ed467044..8f47e735f8 100644--- a/packages/core/src/AppShell/observeMainOverflow.ts+++ b/packages/core/src/AppShell/observeMainOverflow.ts@@ -4,20 +4,23 @@/*** @file observeMainOverflow.ts- * @input AppShell's main region under `height="fill"`: its own scroll- * container, holding its content as direct children with no wrapper+ * @input A scroll container that holds its content as direct children with+ * no wrapper: AppShell's main region under `height="fill"`, or a scrolling+ * LayoutContent, LayoutPanel or StackItem* @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+ * @position Internal 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.+ * `component:AppShell` FR4 and PR1). useScrollRegionProps names a+ * scrolling region only while it overflows. 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+ * - /packages/core/src/hooks/useScrollRegionProps.ts*/import {diff --git a/packages/core/src/Layout/LayoutContent.doc.mjs b/packages/core/src/Layout/LayoutContent.doc.mjsindex 8a962abaf8..bb19a14ea2 100644--- a/packages/core/src/Layout/LayoutContent.doc.mjs+++ b/packages/core/src/Layout/LayoutContent.doc.mjs@@ -30,7 +30,8 @@ export const docs = {{name: 'label',type: 'string',- description: 'Accessible label for the landmark element.',+ description:+ 'Accessible label for the landmark element. While the region scrolls, it also names the scrolling region, which otherwise takes a translated "Content".',},{name: 'role',@@ -66,7 +67,8 @@ export const docsZh = {{name: 'label',type: 'string',- description: '地标元素的无障碍标签。',+ description:+ '地标元素的无障碍标签。区域滚动时,它也为滚动区域命名;未提供时使用已翻译的“Content”(内容)。',},{name: 'role',@@ -86,7 +88,8 @@ export const docsDense = {padding: 'Internal padding on spacing scale. Overrides layout container default.',isScrollable:'Enable scrollable overflow. With arithmetic contentWidth values, the scrollport reaches open sides while context-aware insets align children.',- label: 'Accessible label for landmark element.',+ label:+ 'Accessible label for landmark element; also names the region while it scrolls (default "Content").',role: 'ARIA landmark role.',},};diff --git a/packages/core/src/Layout/LayoutContent.tsx b/packages/core/src/Layout/LayoutContent.tsxindex 3321205dae..51699c2b57 100644--- a/packages/core/src/Layout/LayoutContent.tsx+++ b/packages/core/src/Layout/LayoutContent.tsx@@ -4,7 +4,7 @@/*** @file LayoutContent.tsx- * @input Uses React StyleX, LayoutSlotsContext+ * @input Uses React StyleX, LayoutSlotsContext, useScrollRegionProps* @output Exports LayoutContent component and LayoutContentProps* @position Scrollable main content area for Layout. Wraps the primary body content* with automatic scroll containment and context-aware padding.@@ -21,6 +21,8 @@ import {use} from 'react';import * as stylex from '@stylexjs/stylex';import {spacingVars} from '../theme/tokens.stylex';import {LayoutSlotsContext} from './LayoutSlotsContext';+import {useMergedRefs} from '../hooks/useMergedRefs';+import {useScrollRegionProps} from '../hooks/useScrollRegionProps';import {mergeProps} from '../utils/mergeProps';import type {SpacingStep} from '../utils/types';import {themeProps} from '../utils/themeProps';@@ -132,6 +134,8 @@ export interface LayoutContentProps extends BaseProps<HTMLDivElement> {/*** Accessible label for the landmark.* Required when role is set and multiple landmarks of the same type exist.+ * While the content scrolls, it also names the scrolling region, which+ * otherwise takes a translated "Content".*/label?: string;@@ -192,12 +196,14 @@ export function LayoutContent({const {hasHeader, hasFooter, hasStart, hasEnd} = use(LayoutSlotsContext);const isZeroPadding = padding === 0;+ const region = useScrollRegionProps({isScrollable, role, label});+ const mergedRef = useMergedRefs(ref, region.ref);return (<div- ref={ref}- role={role}- aria-label={label}+ ref={mergedRef}+ role={region.role}+ aria-label={region['aria-label']}{...mergeProps(themeProps('layout-content'),stylex.props(diff --git a/packages/core/src/Layout/LayoutPanel.doc.mjs b/packages/core/src/Layout/LayoutPanel.doc.mjsindex 6047f49b97..9b269f4e15 100644--- a/packages/core/src/Layout/LayoutPanel.doc.mjs+++ b/packages/core/src/Layout/LayoutPanel.doc.mjs@@ -53,7 +53,8 @@ export const docs = {{name: 'label',type: 'string',- description: 'Accessible label for the landmark element.',+ description:+ 'Accessible label for the landmark element. While the region scrolls, it also names the scrolling region, which otherwise takes a translated "Content".',},{name: 'role',@@ -106,7 +107,8 @@ export const docsZh = {{name: 'label',type: 'string',- description: '地标元素的无障碍标签。',+ description:+ '地标元素的无障碍标签。区域滚动时,它也为滚动区域命名;未提供时使用已翻译的“Content”(内容)。',},{name: 'role',@@ -139,7 +141,8 @@ export const docsDense = {padding:'Internal padding on spacing scale. Overrides layout container default.',isScrollable: 'Enable scrollable overflow.',- label: 'Accessible label for landmark element.',+ label:+ 'Accessible label for landmark element; also names the region while it scrolls (default "Content").',role: 'ARIA landmark role.',width:'Panel width. Numbers = pixels, strings as-is. Ignored when resizable provided; hook controls width.',diff --git a/packages/core/src/Layout/LayoutPanel.tsx b/packages/core/src/Layout/LayoutPanel.tsxindex d21b3aa079..89373b6201 100644--- a/packages/core/src/Layout/LayoutPanel.tsx+++ b/packages/core/src/Layout/LayoutPanel.tsx@@ -4,7 +4,8 @@/*** @file LayoutPanel.tsx- * @input Uses React StyleX, LayoutAreaContext, LayoutSlotsContext+ * @input Uses React StyleX, LayoutAreaContext, LayoutSlotsContext,+ * useScrollRegionProps* @output Exports LayoutPanel component and LayoutPanelProps* @position Sidebar panel for Layout start/end slots. Use for navigation panels,* settings sidebars, detail panels, or any fixed-width side content.@@ -22,6 +23,8 @@ import * as stylex from '@stylexjs/stylex';import {colorVars, spacingVars} from '../theme/tokens.stylex';import {LayoutAreaContext} from './LayoutAreaContext';import {LayoutSlotsContext} from './LayoutSlotsContext';+import {useMergedRefs} from '../hooks/useMergedRefs';+import {useScrollRegionProps} from '../hooks/useScrollRegionProps';import {mergeProps} from '../utils';import type {SizeValue, SpacingStep} from '../utils/types';import type {ResizableProps} from '../Resizable/useResizable';@@ -144,6 +147,8 @@ export interface LayoutPanelProps extends BaseProps<HTMLDivElement> {/*** Accessible label for the landmark.* Required when role is set and multiple landmarks of the same type exist.+ * While the panel scrolls, it also names the scrolling region, which+ * otherwise takes a translated "Content".*/label?: string;@@ -235,6 +240,8 @@ export function LayoutPanel({// When no divider, collapse spacing for seamless visual flowconst shouldCollapseSpacing =!hasDivider && !isZeroPadding && padding == null;+ const region = useScrollRegionProps({isScrollable, role, label});+ const mergedRef = useMergedRefs(ref, region.ref);// Select divider style based on positionconst dividerStyle = isStartPanel@@ -252,9 +259,9 @@ export function LayoutPanel({return (<div- ref={ref}- role={role}- aria-label={label}+ ref={mergedRef}+ role={region.role}+ aria-label={region['aria-label']}{...mergeProps(themeProps('layout-panel'),stylex.props(diff --git a/packages/core/src/Stack/Stack.doc.mjs b/packages/core/src/Stack/Stack.doc.mjsindex 05d1c0e3b3..693dd96792 100644--- a/packages/core/src/Stack/Stack.doc.mjs+++ b/packages/core/src/Stack/Stack.doc.mjs@@ -524,7 +524,7 @@ export const docs = {name: 'isScrollable',type: 'boolean',description:- 'Enables scrollable overflow (overflow: auto). StackItem already applies the flex min-height/min-width reset, so <StackItem size="fill" isScrollable> is a complete scroll region. Matches isScrollable on LayoutContent and LayoutPanel.',+ 'Enables scrollable overflow (overflow: auto). StackItem already applies the flex min-height/min-width reset, so <StackItem size="fill" isScrollable> is a complete scroll region. Matches isScrollable on LayoutContent and LayoutPanel. While its content overflows, a div or span item is a group named by aria-label, or by a translated "Content"; another element keeps its own role.',default: 'false',},{diff --git a/packages/core/src/Stack/StackItem.tsx b/packages/core/src/Stack/StackItem.tsxindex a2d85516fa..adf09881d7 100644--- a/packages/core/src/Stack/StackItem.tsx+++ b/packages/core/src/Stack/StackItem.tsx@@ -2,9 +2,11 @@/*** @file StackItem.tsx- * @input Uses React, ElementType, stackItem utility+ * @input Uses React, ElementType, stackItem utility, StackItemScrollRegion* @output Exports StackItem polymorphic component and StackItemProps- * @position Layout/Stack component; uses stackItem.stylex.ts+ * @position Layout/Stack component; uses stackItem.stylex.ts. A scrollable+ * `div` or `span` item renders through StackItemScrollRegion, which names+ * it while it scrolls.** SYNC: When modified, update these files to stay in sync:* - /packages/core/src/Stack/Stack.doc.mjs@@ -21,6 +23,7 @@ import {} from './stackItem.stylex';import {mergeProps} from '../utils/mergeProps';import {themeProps} from '../utils/themeProps';+import {StackItemScrollRegion} from '../hooks/StackItemScrollRegion';const overflowStyles = stylex.create({scrollable: {@@ -53,7 +56,9 @@ export interface StackItemProps extends BaseProps<HTMLElement> {* reset, so `<StackItem size="fill" isScrollable>` is a complete scroll* region — it grows to fill the stack and scrolls its own overflow with* no extra style plumbing. Matches `isScrollable` on `LayoutContent`- * and `LayoutPanel`.+ * and `LayoutPanel`. While its content overflows, a `div` or `span` item+ * is a group named by the caller's `aria-label`, or by a translated+ * "Content". Another element keeps its own role.* @default false*/isScrollable?: boolean;@@ -102,18 +107,27 @@ export function StackItem({xstyle,);+ const elementProps = {+ ...mergeProps(+ themeProps('stack-item', {size}),+ stylexProps,+ className,+ style,+ ),+ ...props,+ };++ if (isScrollable && (element === 'div' || element === 'span')) {+ return createElement(+ StackItemScrollRegion,+ {as: element, ref, elementProps},+ children,+ );+ }+return createElement(element,- {- ref: ref as Ref<Element>,- ...mergeProps(- themeProps('stack-item', {size}),- stylexProps,- className,- style,- ),- ...props,- },+ {ref: ref as Ref<Element>, ...elementProps},children,);}diff --git a/packages/core/src/hooks/StackItemScrollRegion.tsx b/packages/core/src/hooks/StackItemScrollRegion.tsxnew file mode 100644index 0000000000..878fdf540a--- /dev/null+++ b/packages/core/src/hooks/StackItemScrollRegion.tsx@@ -0,0 +1,57 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file StackItemScrollRegion.tsx+ * @input A scrollable `div` or `span` StackItem's props, ref and children+ * @output StackItemScrollRegion (internal; not re-exported from+ * hooks/index.ts), which renders that element and names it as a group+ * while its content overflows+ * @position Internal client island for StackItem, which itself stays a+ * static render. Only a scrollable `div` or `span` item measures its+ * overflow, on the client; another element keeps its own role.+ *+ * SYNC: When modified, update:+ * - /packages/core/src/Stack/StackItem.tsx+ * - /packages/core/src/serverSafeComponents.test.ts+ */++import {createElement, type AriaRole, type ReactNode, type Ref} from 'react';+import {useMergedRefs} from './useMergedRefs';+import {useScrollRegionProps} from './useScrollRegionProps';++export interface StackItemScrollRegionProps {+ as: 'div' | 'span';+ ref?: Ref<HTMLElement>;+ elementProps: {+ role?: AriaRole;+ 'aria-label'?: string;+ [prop: string]: unknown;+ };+ children?: ReactNode;+}++export function StackItemScrollRegion({+ as: element,+ ref,+ elementProps,+ children,+}: StackItemScrollRegionProps) {+ const region = useScrollRegionProps({+ isScrollable: true,+ role: elementProps.role,+ label: elementProps['aria-label'],+ });+ const mergedRef = useMergedRefs(ref, region.ref);+ return createElement(+ element,+ {+ ...elementProps,+ ref: mergedRef,+ role: region.role,+ 'aria-label': region['aria-label'],+ },+ children,+ );+}diff --git a/packages/core/src/hooks/__tests__/scrollRegionName.a11y.chromium.spec.ts b/packages/core/src/hooks/__tests__/scrollRegionName.a11y.chromium.spec.tsnew file mode 100644index 0000000000..b680090657--- /dev/null+++ b/packages/core/src/hooks/__tests__/scrollRegionName.a11y.chromium.spec.ts@@ -0,0 +1,123 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+// @pr-a11y scope ^(packages/core/src/(Layout/Layout(Content|Panel)|Stack/StackItem|hooks/useScrollRegionProps|AppShell/observeMainOverflow)|apps/storybook/stories/ScrollRegionA11y)+/**+ * Chromium's accessibility tree for a scrolling region: while it scrolls,+ * a screen reader that reaches it announces a named group.+ */+import {+ expect,+ test,+ type CDPSession,+ type Page,+} from '@astryxdesign/a11y-spec/playwright';+import {+ DEFAULT_STORYBOOK_DIR,+ serveStorybook,+ type StaticServer,+} from '@astryxdesign/a11y-spec/storybook';++const REGION = '[data-scroll-region]';++let storybook: StaticServer;++test.beforeAll(async () => {+ storybook = await serveStorybook(+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,+ );+});++test.afterAll(async () => storybook?.close());++async function open(page: Page, story: string): Promise<void> {+ await page.goto(+ `${storybook.origin}/iframe.html?id=a11y-scroll-region-name--${story}&viewMode=story`,+ {waitUntil: 'load'},+ );+}++/** Chromium's computed role and name for the region, as a screen reader reads them. */+async function announced(+ cdp: CDPSession,+): Promise<{role: string; name: string}> {+ const {root} = await cdp.send('DOM.getDocument', {depth: -1});+ const {nodeId} = await cdp.send('DOM.querySelector', {+ nodeId: root.nodeId,+ selector: REGION,+ });+ const {nodes} = await cdp.send('Accessibility.getPartialAXTree', {+ nodeId,+ fetchRelatives: false,+ });+ const node = nodes[0];+ return {+ role: String(node?.role?.value ?? ''),+ name: String(node?.name?.value ?? ''),+ };+}++/** The region is on screen with a real box, and whether it overflows. */+async function presentAndOverflowing(page: Page): Promise<boolean> {+ const region = page.locator(REGION);+ await expect(region).toHaveCount(1);+ const box = await region.boundingBox();+ expect(box?.width ?? 0).toBeGreaterThan(0);+ expect(box?.height ?? 0).toBeGreaterThan(0);+ return region.evaluate(+ element =>+ element.scrollHeight > element.clientHeight + 1 ||+ element.scrollWidth > element.clientWidth + 1,+ );+}++async function settle(page: Page): Promise<void> {+ await page.evaluate(async () => {+ await new Promise<void>(resolve => {+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()));+ });+ });+}++const SCROLLING = [+ {story: 'content-scrolls', role: 'group', name: 'Content'},+ {story: 'content-labelled', role: 'group', name: 'Messages'},+ // A caller's landmark keeps its role, named only by the caller.+ {story: 'content-main', role: 'main', name: ''},+ {story: 'panel-scrolls', role: 'group', name: 'Content'},+ {story: 'stack-item-scrolls', role: 'group', name: 'Content'},+ // Another element keeps its own role.+ {story: 'stack-item-list-scrolls', role: 'list', name: ''},+] as const;++for (const {story, role, name} of SCROLLING) {+ test(`a scrolling region is announced [${story}]: ${role} "${name}"`, async ({+ page,+ }) => {+ await open(page, story);+ expect(await presentAndOverflowing(page)).toBe(true);+ const cdp = await page.context().newCDPSession(page);+ await expect.poll(async () => announced(cdp)).toEqual({role, name});+ // Tab behavior stays the browser's: no tab index is set.+ expect(await page.locator(REGION).getAttribute('tabindex')).toBeNull();+ });+}++const QUIET = [+ {story: 'content-fits', overflows: false},+ {story: 'stack-item-static', overflows: true},+] as const;++for (const {story, overflows} of QUIET) {+ test(`a region that does not scroll adds no role or name [${story}]`, async ({+ page,+ }) => {+ await open(page, story);+ expect(await presentAndOverflowing(page)).toBe(overflows);+ await settle(page);+ const cdp = await page.context().newCDPSession(page);+ // A plain element: Chromium exposes it as generic, or leaves it out of+ // the tree.+ const {role, name} = await announced(cdp);+ expect(['generic', 'none']).toContain(role);+ expect(name).toBe('');+ });+}diff --git a/packages/core/src/hooks/useScrollRegionProps.test.tsx b/packages/core/src/hooks/useScrollRegionProps.test.tsxnew file mode 100644index 0000000000..79f410b138--- /dev/null+++ b/packages/core/src/hooks/useScrollRegionProps.test.tsx@@ -0,0 +1,230 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file useScrollRegionProps.test.tsx+ * @input LayoutContent, LayoutPanel and StackItem, with the overflow observer+ * replaced by one the test drives+ * @output Regression coverage for naming a scrolling region: only while it+ * scrolls, the caller's role and label first, a translated default, and the+ * observer stopping+ * @position Unit contract of useScrollRegionProps through its three callers;+ * the Chromium spec in __tests__ reads the real accessibility tree+ */++import {act, render, screen} from '@testing-library/react';+import {createRef} from 'react';+import {afterEach, describe, expect, it, vi} from 'vitest';+import {InternationalizationProvider} from '../i18n/InternationalizationProvider';+import {LayoutContent} from '../Layout/LayoutContent';+import {LayoutPanel} from '../Layout/LayoutPanel';+import {StackItem} from '../Stack/StackItem';++const observers = vi.hoisted(+ () =>+ new Map<+ Element,+ {onChange: (overflows: boolean) => void; stopped: boolean}+ >(),+);++vi.mock('../AppShell/observeMainOverflow', () => ({+ observeMainOverflow: (+ element: Element,+ onChange: (overflows: boolean) => void,+ ) => {+ const entry = {onChange, stopped: false};+ observers.set(element, entry);+ return () => {+ entry.stopped = true;+ };+ },+}));++function setOverflow(element: Element, overflows: boolean) {+ const entry = observers.get(element);+ if (entry == null) {+ throw new Error('the region is not observed');+ }+ act(() => entry.onChange(overflows));+}++afterEach(() => {+ observers.clear();+});++describe('a scrolling LayoutContent', () => {+ it('is a group named "Content" only while it overflows', () => {+ render(<LayoutContent data-testid="region">Body</LayoutContent>);+ const region = screen.getByTestId('region');+ expect(region).not.toHaveAttribute('role');+ expect(region).not.toHaveAttribute('aria-label');++ setOverflow(region, true);+ expect(region).toHaveAttribute('role', 'group');+ expect(region).toHaveAttribute('aria-label', 'Content');++ setOverflow(region, false);+ expect(region).not.toHaveAttribute('role');+ expect(region).not.toHaveAttribute('aria-label');+ });++ it("takes the caller's label, which also names it while it fits", () => {+ render(+ <LayoutContent data-testid="region" label="Messages">+ Body+ </LayoutContent>,+ );+ const region = screen.getByTestId('region');+ expect(region).toHaveAttribute('aria-label', 'Messages');+ expect(region).not.toHaveAttribute('role');++ setOverflow(region, true);+ expect(region).toHaveAttribute('role', 'group');+ expect(region).toHaveAttribute('aria-label', 'Messages');+ });++ it("keeps a caller's landmark role with only the caller's name, and does not observe it", () => {+ render(+ <LayoutContent data-testid="region" role="main">+ Body+ </LayoutContent>,+ );+ const region = screen.getByTestId('region');+ expect(observers.has(region)).toBe(false);+ expect(region).toHaveAttribute('role', 'main');+ expect(region).not.toHaveAttribute('aria-label');+ });++ it('reads the name from the catalog', () => {+ render(+ <InternationalizationProvider+ locale="en"+ overrides={{en: {'@astryx.scrollRegion.label': 'Body text'}}}>+ <LayoutContent data-testid="region">Body</LayoutContent>+ </InternationalizationProvider>,+ );+ const region = screen.getByTestId('region');+ setOverflow(region, true);+ expect(region).toHaveAttribute('aria-label', 'Body text');+ });++ it('is never observed or named when it cannot scroll', () => {+ render(+ <LayoutContent data-testid="region" isScrollable={false}>+ Body+ </LayoutContent>,+ );+ const region = screen.getByTestId('region');+ expect(observers.has(region)).toBe(false);+ expect(region).not.toHaveAttribute('role');+ expect(region).not.toHaveAttribute('aria-label');+ });++ it('leaves the tab index to the browser', () => {+ render(<LayoutContent data-testid="region">Body</LayoutContent>);+ const region = screen.getByTestId('region');+ setOverflow(region, true);+ expect(region).not.toHaveAttribute('tabindex');+ });++ it("still gives the caller's ref the root, and stops observing on unmount", () => {+ const ref = createRef<HTMLDivElement>();+ const {unmount} = render(+ <LayoutContent data-testid="region" ref={ref}>+ Body+ </LayoutContent>,+ );+ const region = screen.getByTestId('region');+ expect(ref.current).toBe(region);+ const entry = observers.get(region);+ expect(entry?.stopped).toBe(false);++ unmount();+ expect(entry?.stopped).toBe(true);+ expect(ref.current).toBeNull();+ });+});++describe('a scrolling LayoutPanel', () => {+ it('is a group named "Content" only while it overflows', () => {+ render(<LayoutPanel data-testid="region">Sections</LayoutPanel>);+ const region = screen.getByTestId('region');+ expect(region).not.toHaveAttribute('role');++ setOverflow(region, true);+ expect(region).toHaveAttribute('role', 'group');+ expect(region).toHaveAttribute('aria-label', 'Content');+ });++ it("keeps the caller's role and label, and does not observe it", () => {+ render(+ <LayoutPanel data-testid="region" label="Sections" role="navigation">+ Sections+ </LayoutPanel>,+ );+ const region = screen.getByTestId('region');+ expect(observers.has(region)).toBe(false);+ expect(region).toHaveAttribute('role', 'navigation');+ expect(region).toHaveAttribute('aria-label', 'Sections');+ });+});++describe('a scrollable StackItem', () => {+ it('is a group named "Content" only while it overflows', () => {+ render(+ <StackItem data-testid="region" isScrollable>+ Items+ </StackItem>,+ );+ const region = screen.getByTestId('region');+ expect(region).not.toHaveAttribute('role');++ setOverflow(region, true);+ expect(region).toHaveAttribute('role', 'group');+ expect(region).toHaveAttribute('aria-label', 'Content');++ setOverflow(region, false);+ expect(region).not.toHaveAttribute('role');+ expect(region).not.toHaveAttribute('aria-label');+ });++ it("keeps the caller's role and aria-label, and its ref", () => {+ const ref = createRef<HTMLElement>();+ render(+ <StackItem+ aria-label="Results"+ data-testid="region"+ isScrollable+ ref={ref}+ role="region">+ Items+ </StackItem>,+ );+ const region = screen.getByTestId('region');+ expect(ref.current).toBe(region);+ expect(observers.has(region)).toBe(false);+ expect(region).toHaveAttribute('role', 'region');+ expect(region).toHaveAttribute('aria-label', 'Results');+ });++ it('keeps the own role of another element, such as a list, and does not observe it', () => {+ render(+ <StackItem as="ul" data-testid="region" isScrollable>+ <li>Item</li>+ </StackItem>,+ );+ const region = screen.getByTestId('region');+ expect(region.tagName).toBe('UL');+ expect(observers.has(region)).toBe(false);+ expect(region).not.toHaveAttribute('role');+ expect(region).not.toHaveAttribute('aria-label');+ });++ it('is never observed or named when it is not scrollable', () => {+ render(<StackItem data-testid="region">Items</StackItem>);+ const region = screen.getByTestId('region');+ expect(observers.has(region)).toBe(false);+ expect(region).not.toHaveAttribute('role');+ expect(region).not.toHaveAttribute('aria-label');+ });+});diff --git a/packages/core/src/hooks/useScrollRegionProps.ts b/packages/core/src/hooks/useScrollRegionProps.tsnew file mode 100644index 0000000000..73e05fdbda--- /dev/null+++ b/packages/core/src/hooks/useScrollRegionProps.ts@@ -0,0 +1,76 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file useScrollRegionProps.ts+ * @input Whether a region may scroll, and the caller's role and label+ * @output useScrollRegionProps: a ref for the region, and the role and+ * accessible name that the region carries while its content overflows+ * @position Internal hook for LayoutContent, LayoutPanel and StackItem.+ *+ * SYNC: When modified, update:+ * - /packages/core/src/hooks/useScrollRegionProps.test.tsx+ * - /packages/core/src/AppShell/observeMainOverflow.ts+ */++import {useCallback, useState, type AriaRole, type RefCallback} from 'react';+import {+ registerEnglishFallback,+ useComponentTranslator,+} from '../i18n/useComponentTranslator';+import english from '../i18n/generated-english/hooks/useScrollRegionProps.generated';+import {observeMainOverflow} from '../AppShell/observeMainOverflow';++registerEnglishFallback(english);++export interface ScrollRegionOptions {+ /** Whether the region may scroll at all (`overflow: auto`). */+ isScrollable: boolean;+ /** The caller's role. It always wins, and takes no default name. */+ role?: AriaRole;+ /** The caller's accessible name. It always wins. */+ label?: string;+}++export interface ScrollRegionProps {+ ref: RefCallback<HTMLElement>;+ role: AriaRole | undefined;+ 'aria-label': string | undefined;+}++/**+ * The region's ref, role and accessible name. While the region may scroll+ * and its content overflows, it is a group named by the caller's `label`, or+ * by the translated "Content". A caller's `role` is kept with only the+ * caller's `label`: a single main landmark relies on its role alone. When+ * the region does not scroll, the caller's own `role` and `label` pass+ * through unchanged.+ */+export function useScrollRegionProps({+ isScrollable,+ role,+ label,+}: ScrollRegionOptions): ScrollRegionProps {+ const t = useComponentTranslator();+ const [overflows, setOverflows] = useState(false);+ // A caller's role takes no default name, so its region is not observed.+ const hasRole = role != null;+ const ref = useCallback(+ (element: HTMLElement | null) => {+ if (element == null || !isScrollable || hasRole) {+ setOverflows(false);+ return undefined;+ }+ return observeMainOverflow(element, setOverflows);+ },+ [hasRole, isScrollable],+ );+ const isGroup = !hasRole && isScrollable && overflows;+ return {+ ref,+ role: role ?? (isGroup ? 'group' : undefined),+ 'aria-label':+ label ?? (isGroup ? t('@astryx.scrollRegion.label') : undefined),+ };+}diff --git a/packages/core/src/serverSafeComponents.test.ts b/packages/core/src/serverSafeComponents.test.tsindex 9ec19bc0ff..937805d514 100644--- a/packages/core/src/serverSafeComponents.test.ts+++ b/packages/core/src/serverSafeComponents.test.ts@@ -76,7 +76,10 @@ const EXTENSIONS = ['.tsx', '.ts', '.mjs', '.js', '.jsx'];* island: each does nothing on the server, so the component's server output* is unchanged. The walk stops at them.*/-const CLIENT_ISLANDS = new Set(['hooks/AnnounceRenderedText.tsx']);+const CLIENT_ISLANDS = new Set([+ 'hooks/AnnounceRenderedText.tsx',+ 'hooks/StackItemScrollRegion.tsx',+]);const isSourceFile = (name: string) =>/\.[jt]sx?$/.test(name) &&