An open source design system that's fully customizable and agent ready
TypeScript
Add the scrollable container system (#6262)
Cindy Zhang2ca486d78bfc
diff --git a/.changeset/scrollable-area-system.md b/.changeset/scrollable-area-system.mdnew file mode 100644index 0000000000..8d319118e2--- /dev/null+++ b/.changeset/scrollable-area-system.md@@ -0,0 +1,9 @@+---+'@astryxdesign/core': patch+---++[feature] Add ScrollableArea and useScrollableArea for accessible, logical-axis native scrolling with explicit overscroll policy.++Scrollable viewports now become keyboard reachable only while content effectively overflows, preserve logical edge state across writing modes, apply contained overscroll only on active axes, avoid capturing Sticky while fitting unless explicitly requested, expose standard container sizing props, and integrate optional content padding plus opt-in full bleed with the shared container geometry system.++@cixzhangdiff --git a/apps/storybook/rtl-audit/targets.json b/apps/storybook/rtl-audit/targets.jsonindex 597c3b9b7b..a71d95c7e2 100644--- a/apps/storybook/rtl-audit/targets.json+++ b/apps/storybook/rtl-audit/targets.json@@ -120,6 +120,17 @@"nextButton": "button[aria-label=\"Scroll right\"]"}},+ {+ "component": "ScrollableArea",+ "storyId": "core-scrollablearea--rtl-behavior-probe",+ "dims": [+ "D3"+ ],+ "selectors": {+ "scroller": "[data-rtl-scroll-probe]",+ "nextButton": "[data-rtl-scroll-button]"+ }+ },{"component": "Chat","storyId": "core-chat--mixed-content",diff --git a/apps/storybook/stories/ScrollableArea.stories.tsx b/apps/storybook/stories/ScrollableArea.stories.tsxnew file mode 100644index 0000000000..be3813afc8--- /dev/null+++ b/apps/storybook/stories/ScrollableArea.stories.tsx@@ -0,0 +1,742 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {useRef, useState} from 'react';+import type {Meta, StoryObj} from '@storybook/react';+import {expect, userEvent, waitFor} from 'storybook/test';+import * as stylex from '@stylexjs/stylex';+import {Button} from '@astryxdesign/core/Button';+import {HStack, VStack} from '@astryxdesign/core/Layout';+import {ScrollableArea} from '@astryxdesign/core/ScrollableArea';+import {Section} from '@astryxdesign/core/Section';+import {Text} from '@astryxdesign/core/Text';+import {+ colorVars,+ radiusVars,+ spacingVars,+ typographyVars,+} from '@astryxdesign/core/theme/tokens.stylex';++const styles = stylex.create({+ canvas: {+ padding: spacingVars['--spacing-4'],+ backgroundColor: colorVars['--color-background-body'],+ },+ viewport: {+ inlineSize: 340,+ blockSize: 180,+ borderWidth: 1,+ borderStyle: 'solid',+ borderColor: colorVars['--color-border-emphasized'],+ borderRadius: radiusVars['--radius-container'],+ backgroundColor: colorVars['--color-background-surface'],+ },+ viewportWide: {+ inlineSize: 460,+ },+ viewportCompact: {+ inlineSize: 260,+ blockSize: 140,+ },+ containerViewport: {+ blockSize: 180,+ },+ contentPadding: {+ padding: spacingVars['--spacing-3'],+ },+ copy: {+ margin: 0,+ fontFamily: typographyVars['--font-family-body'],+ color: colorVars['--color-text-primary'],+ },+ supportingCopy: {+ color: colorVars['--color-text-secondary'],+ },+ card: {+ inlineSize: 150,+ minBlockSize: 96,+ boxSizing: 'border-box',+ padding: spacingVars['--spacing-3'],+ borderRadius: radiusVars['--radius-element'],+ backgroundColor: colorVars['--color-background-muted'],+ flexShrink: 0,+ },+ horizontalRail: {+ display: 'flex',+ gap: spacingVars['--spacing-2'],+ inlineSize: 920,+ minBlockSize: 150,+ alignItems: 'stretch',+ padding: spacingVars['--spacing-2'],+ },+ verticalRail: {+ display: 'grid',+ gap: spacingVars['--spacing-2'],+ padding: spacingVars['--spacing-2'],+ },+ twoAxisCanvas: {+ position: 'relative',+ display: 'grid',+ gridTemplateColumns: 'repeat(4, 180px)',+ gridTemplateRows: 'repeat(4, 120px)',+ gap: spacingVars['--spacing-2'],+ inlineSize: 760,+ blockSize: 540,+ padding: spacingVars['--spacing-2'],+ },+ sticky: {+ position: 'sticky',+ zIndex: 1,+ alignSelf: 'start',+ padding: spacingVars['--spacing-2'],+ borderRadius: radiusVars['--radius-element'],+ backgroundColor: colorVars['--color-neutral'],+ fontFamily: typographyVars['--font-family-body'],+ color: colorVars['--color-text-primary'],+ containerType: {+ default: null,+ '@supports (container-type: scroll-state)': 'scroll-state',+ },+ },+ stickyInlineStart: {+ insetInlineStart: 0,+ },+ stickyInlineEnd: {+ insetInlineEnd: 0,+ },+ stickyBlockStart: {+ insetBlockStart: 0,+ },+ stickyBlockEnd: {+ insetBlockEnd: 0,+ alignSelf: 'end',+ },+ stickyStateInlineStart: {+ backgroundColor: {+ default: 'transparent',+ '@container scroll-state(stuck: inline-start)':+ colorVars['--color-accent-muted'],+ },+ },+ stickyStateInlineEnd: {+ backgroundColor: {+ default: 'transparent',+ '@container scroll-state(stuck: inline-end)':+ colorVars['--color-accent-muted'],+ },+ },+ stickyStateBlockStart: {+ backgroundColor: {+ default: 'transparent',+ '@container scroll-state(stuck: block-start)':+ colorVars['--color-accent-muted'],+ },+ },+ stickyStateBlockEnd: {+ backgroundColor: {+ default: 'transparent',+ '@container scroll-state(stuck: block-end)':+ colorVars['--color-accent-muted'],+ },+ },+ edgeStatus: {+ position: 'sticky',+ insetBlockStart: 0,+ opacity: 0.45,+ },+ edgeStatusInlineEnd: {+ opacity: {+ default: 0.45,+ '@container scroll-state(scrollable: inline-end)': 1,+ },+ },+ nestedViewport: {+ inlineSize: 280,+ blockSize: 140,+ borderWidth: 1,+ borderStyle: 'dashed',+ borderColor: colorVars['--color-border-emphasized'],+ borderRadius: radiusVars['--radius-element'],+ },+ nestedOuter: {+ inlineSize: 320,+ blockSize: 300,+ },+ stickyPassThroughOuter: {+ inlineSize: 360,+ blockSize: 220,+ },+ stickyPassThroughContent: {+ minBlockSize: 720,+ padding: spacingVars['--spacing-3'],+ },+ stickyPassThroughSpacer: {+ blockSize: 180,+ display: 'flex',+ alignItems: 'center',+ },+ stickyPassThroughInner: {+ blockSize: 140,+ borderWidth: 1,+ borderStyle: 'dashed',+ borderColor: colorVars['--color-border-emphasized'],+ borderRadius: radiusVars['--radius-element'],+ },+ stickyPassThroughInnerContent: {+ blockSize: 120,+ padding: spacingVars['--spacing-2'],+ },+ stickyPassThroughTail: {+ blockSize: 360,+ },+ verticalWriting: {+ writingMode: 'vertical-rl',+ inlineSize: 220,+ blockSize: 280,+ },+ rtl: {+ direction: 'rtl',+ },+ scrollbarThin: {+ scrollbarWidth: 'thin',+ },+ scrollbarStable: {+ scrollbarGutter: 'stable both-edges',+ },+ scrollbarNeutral: {+ scrollbarColor: `${colorVars['--color-neutral']} transparent`,+ },+ transformedHost: {+ inlineSize: 360,+ transform: 'perspective(700px) rotateY(0deg)',+ },+ clippedFrame: {+ overflow: 'clip',+ borderRadius: radiusVars['--radius-container'],+ borderWidth: 1,+ borderStyle: 'solid',+ borderColor: colorVars['--color-border-emphasized'],+ },+});++const meta = {+ title: 'Core/ScrollableArea',+ component: ScrollableArea,+ tags: ['autodocs'],+ args: {+ axis: 'block',+ label: 'Scrollable example',+ role: 'group',+ overscroll: 'allow',+ stickyContainment: 'whenScrollable',+ },+ argTypes: {+ axis: {control: 'select', options: ['inline', 'block', 'both']},+ role: {control: 'select', options: ['group', 'region']},+ overscroll: {control: 'select', options: ['allow', 'contain']},+ stickyContainment: {+ control: 'select',+ options: ['whenScrollable', 'always'],+ },+ },+} satisfies Meta<typeof ScrollableArea>;++export default meta;+type Story = StoryObj<typeof meta>;++function Cards({count}: {count: number}) {+ return (+ <div {...stylex.props(styles.horizontalRail)}>+ {Array.from({length: count}, (_, index) => (+ <div key={index} {...stylex.props(styles.card)}>+ <p {...stylex.props(styles.copy)}>Project {index + 1}</p>+ <p {...stylex.props(styles.copy, styles.supportingCopy)}>+ Native scrolling content+ </p>+ </div>+ ))}+ </div>+ );+}++function Rows({count}: {count: number}) {+ return (+ <div {...stylex.props(styles.verticalRail)}>+ {Array.from({length: count}, (_, index) => (+ <div key={index} {...stylex.props(styles.card)}>+ <p {...stylex.props(styles.copy)}>Activity {index + 1}</p>+ </div>+ ))}+ </div>+ );+}++export const Playground: Story = {+ render: args => (+ <div {...stylex.props(styles.canvas)}>+ <ScrollableArea {...args} xstyle={styles.viewport}>+ {args.axis === 'block' ? <Rows count={8} /> : <Cards count={8} />}+ </ScrollableArea>+ </div>+ ),+};++function ConditionalKeyboardDemo() {+ const [hasOverflow, setHasOverflow] = useState(false);+ return (+ <VStack gap={3} xstyle={styles.canvas}>+ <HStack gap={2} hAlign="start">+ <Button+ label={hasOverflow ? 'Make content fit' : 'Make content overflow'}+ onClick={() => setHasOverflow(current => !current)}>+ {hasOverflow ? 'Make content fit' : 'Make content overflow'}+ </Button>+ <Text type="supporting" color="secondary">+ Tab after toggling. The viewport is skipped when content fits and+ joins the tab order when content overflows.+ </Text>+ </HStack>+ <ScrollableArea+ axis="block"+ label="Conditional activity list"+ role="region"+ data-evidence="conditional-tabindex"+ xstyle={styles.viewportCompact}>+ <Rows count={hasOverflow ? 8 : 1} />+ </ScrollableArea>+ </VStack>+ );+}++export const ConditionalKeyboardAccess: Story = {+ render: () => <ConditionalKeyboardDemo />,+ play: async ({canvasElement}) => {+ const button = canvasElement.querySelector('button');+ const viewport = canvasElement.querySelector<HTMLElement>(+ '[data-evidence="conditional-tabindex"]',+ );+ expect(button).not.toBeNull();+ expect(viewport).not.toBeNull();+ if (button == null || viewport == null) {+ return;+ }++ await waitFor(() => {+ expect(getComputedStyle(viewport).overflowY).toBe('clip');+ expect(viewport).not.toHaveAttribute('tabindex');+ });+ await userEvent.click(button);+ await waitFor(() => {+ expect(getComputedStyle(viewport).overflowY).toBe('auto');+ expect(viewport).toHaveAttribute('tabindex', '0');+ });+ await userEvent.click(button);+ await waitFor(() => {+ expect(getComputedStyle(viewport).overflowY).toBe('clip');+ expect(viewport).not.toHaveAttribute('tabindex');+ });+ },+ parameters: {controls: {disable: true}},+};++function NestedChainingExample({policy}: {policy: 'allow' | 'contain'}) {+ return (+ <VStack gap={2}>+ <Text weight="semibold">{policy}</Text>+ <ScrollableArea+ axis="block"+ label={`${policy} outer activity`}+ overscroll="allow"+ xstyle={[styles.viewport, styles.nestedOuter]}>+ <VStack gap={3} xstyle={styles.contentPadding}>+ <Text>Scroll the nested areas, then continue at each edge.</Text>+ <ScrollableArea+ axis="block"+ label={`${policy} fitting nested area`}+ overscroll={policy}+ data-evidence={`${policy}-fitting-nested`}+ xstyle={styles.nestedViewport}>+ <Rows count={1} />+ </ScrollableArea>+ <ScrollableArea+ axis="block"+ label={`${policy} overflowing nested area`}+ overscroll={policy}+ data-evidence={`${policy}-overflowing-nested`}+ xstyle={styles.nestedViewport}>+ <Rows count={6} />+ </ScrollableArea>+ <Rows count={4} />+ </VStack>+ </ScrollableArea>+ </VStack>+ );+}++export const Overscroll: Story = {+ render: () => (+ <HStack gap={4} xstyle={styles.canvas}>+ <NestedChainingExample policy="allow" />+ <NestedChainingExample policy="contain" />+ </HStack>+ ),+ parameters: {controls: {disable: true}},+};++function StickyLabel({+ edge,+}: {+ edge: 'inline-start' | 'inline-end' | 'block-start' | 'block-end';+}) {+ const stateStyle =+ edge === 'inline-start'+ ? styles.stickyStateInlineStart+ : edge === 'inline-end'+ ? styles.stickyStateInlineEnd+ : edge === 'block-start'+ ? styles.stickyStateBlockStart+ : styles.stickyStateBlockEnd;+ return <span {...stylex.props(stateStyle)}>{edge}</span>;+}++export const StickyLogicalEdges: Story = {+ render: () => (+ <VStack gap={4} xstyle={styles.canvas}>+ <Text weight="semibold">Inline start and end</Text>+ <ScrollableArea+ axis="inline"+ label="Inline sticky examples"+ data-evidence="sticky-inline"+ xstyle={[styles.viewport, styles.viewportWide]}>+ <div {...stylex.props(styles.horizontalRail)}>+ <div {...stylex.props(styles.sticky, styles.stickyInlineStart)}>+ <StickyLabel edge="inline-start" />+ </div>+ <Cards count={4} />+ <div {...stylex.props(styles.sticky, styles.stickyInlineEnd)}>+ <StickyLabel edge="inline-end" />+ </div>+ </div>+ </ScrollableArea>++ <Text weight="semibold">Block start and end</Text>+ <ScrollableArea+ axis="block"+ label="Block sticky examples"+ data-evidence="sticky-block"+ xstyle={[styles.viewport, styles.viewportWide]}>+ <div {...stylex.props(styles.verticalRail)}>+ <div {...stylex.props(styles.sticky, styles.stickyBlockStart)}>+ <StickyLabel edge="block-start" />+ </div>+ <Rows count={5} />+ <div {...stylex.props(styles.sticky, styles.stickyBlockEnd)}>+ <StickyLabel edge="block-end" />+ </div>+ </div>+ </ScrollableArea>++ <Text weight="semibold">Both axes</Text>+ <ScrollableArea+ axis="both"+ label="Two-axis sticky examples"+ data-evidence="sticky-both"+ xstyle={[styles.viewport, styles.viewportWide]}>+ <div {...stylex.props(styles.twoAxisCanvas)}>+ <div+ {...stylex.props(+ styles.sticky,+ styles.stickyInlineStart,+ styles.stickyBlockStart,+ )}>+ <StickyLabel edge="inline-start" /> ·{' '}+ <StickyLabel edge="block-start" />+ </div>+ {Array.from({length: 14}, (_, index) => (+ <div key={index} {...stylex.props(styles.card)}>+ Cell {index + 1}+ </div>+ ))}+ <div+ {...stylex.props(+ styles.sticky,+ styles.stickyInlineEnd,+ styles.stickyBlockEnd,+ )}>+ <StickyLabel edge="inline-end" /> · <StickyLabel edge="block-end" />+ </div>+ </div>+ </ScrollableArea>+ </VStack>+ ),+ parameters: {controls: {disable: true}},+};++export const FittingStickyPassthrough: Story = {+ render: () => (+ <div {...stylex.props(styles.canvas)}>+ <ScrollableArea+ axis="block"+ label="Outer Sticky owner"+ data-sticky-outer="true"+ xstyle={[styles.viewport, styles.stickyPassThroughOuter]}>+ <div {...stylex.props(styles.stickyPassThroughContent)}>+ <div {...stylex.props(styles.stickyPassThroughSpacer)}>+ <Text>+ Scroll until the fitting inner area reaches the outer viewport.+ </Text>+ </div>+ <ScrollableArea+ axis="block"+ label="Fitting inner area"+ data-sticky-fitting-area="true"+ xstyle={styles.stickyPassThroughInner}>+ <div {...stylex.props(styles.stickyPassThroughInnerContent)}>+ <div+ data-sticky-passthrough="true"+ {...stylex.props(styles.sticky, styles.stickyBlockStart)}>+ Sticky passes through the fitting area+ </div>+ <Text type="supporting">+ This content fits, so the inner viewport uses clip and does not+ capture Sticky.+ </Text>+ </div>+ </ScrollableArea>+ <Text type="supporting">+ Explicit containment keeps the fitting viewport as a Sticky+ boundary.+ </Text>+ <ScrollableArea+ axis="block"+ label="Explicit fitting Sticky boundary"+ stickyContainment="always"+ data-sticky-contained-area="true"+ xstyle={styles.stickyPassThroughInner}>+ <div {...stylex.props(styles.stickyPassThroughInnerContent)}>+ <div {...stylex.props(styles.sticky, styles.stickyBlockStart)}>+ Sticky stays with this fitting area+ </div>+ </div>+ </ScrollableArea>+ <div {...stylex.props(styles.stickyPassThroughTail)} />+ </div>+ </ScrollableArea>+ </div>+ ),+ play: async ({canvasElement}) => {+ await document.fonts.ready;+ await new Promise<void>(resolve =>+ requestAnimationFrame(() => requestAnimationFrame(() => resolve())),+ );++ const outer = canvasElement.querySelector<HTMLElement>(+ '[data-sticky-outer="true"]',+ );+ const fittingArea = canvasElement.querySelector<HTMLElement>(+ '[data-sticky-fitting-area="true"]',+ );+ const containedArea = canvasElement.querySelector<HTMLElement>(+ '[data-sticky-contained-area="true"]',+ );+ const sticky = canvasElement.querySelector<HTMLElement>(+ '[data-sticky-passthrough="true"]',+ );+ expect(outer).not.toBeNull();+ expect(fittingArea).not.toBeNull();+ expect(containedArea).not.toBeNull();+ expect(sticky).not.toBeNull();+ if (+ outer == null ||+ fittingArea == null ||+ containedArea == null ||+ sticky == null+ ) {+ return;+ }++ expect(getComputedStyle(fittingArea).overflowX).toBe('clip');+ expect(getComputedStyle(fittingArea).overflowY).toBe('clip');+ expect(fittingArea).not.toHaveAttribute('tabindex');+ expect(getComputedStyle(containedArea).overflowX).toBe('hidden');+ expect(getComputedStyle(containedArea).overflowY).toBe('auto');+ expect(containedArea).not.toHaveAttribute('tabindex');++ outer.scrollTop = 200;+ outer.dispatchEvent(new Event('scroll'));+ await new Promise<void>(resolve =>+ requestAnimationFrame(() => requestAnimationFrame(() => resolve())),+ );+ expect(+ Math.abs(+ sticky.getBoundingClientRect().top - outer.getBoundingClientRect().top,+ ),+ ).toBeLessThanOrEqual(2);+ outer.dataset.stickyPassthroughVerified = 'true';+ },+ parameters: {controls: {disable: true}},+};++export const LogicalDirections: Story = {+ render: () => (+ <VStack gap={4} xstyle={styles.canvas}>+ <Text weight="semibold">LTR inline axis</Text>+ <ScrollableArea+ axis="inline"+ label="LTR projects"+ data-evidence="writing-ltr"+ xstyle={styles.viewport}>+ <Cards count={6} />+ </ScrollableArea>+ <Text weight="semibold">RTL inline axis</Text>+ <ScrollableArea+ axis="inline"+ label="RTL projects"+ dir="rtl"+ data-evidence="writing-rtl"+ xstyle={[styles.viewport, styles.rtl]}>+ <Cards count={6} />+ </ScrollableArea>+ <Text weight="semibold">vertical-rl inline axis</Text>+ <ScrollableArea+ axis="inline"+ label="Vertical projects"+ data-evidence="writing-vertical-rl"+ xstyle={styles.verticalWriting}>+ <Cards count={6} />+ </ScrollableArea>+ </VStack>+ ),+ parameters: {controls: {disable: true}},+};++function RTLBehaviorProbeStory() {+ const viewportRef = useRef<HTMLDivElement>(null);+ const scrollToInlineEnd = () => {+ const viewport = viewportRef.current;+ if (viewport == null) {+ return;+ }+ viewport.scrollLeft +=+ getComputedStyle(viewport).direction === 'rtl' ? -160 : 160;+ };++ return (+ <VStack gap={3} xstyle={styles.canvas}>+ <Button+ label="Scroll inline end"+ data-rtl-scroll-button="true"+ onClick={scrollToInlineEnd}>+ Scroll inline end+ </Button>+ <ScrollableArea+ ref={viewportRef}+ axis="inline"+ label="Logical direction probe"+ data-rtl-scroll-probe="true"+ xstyle={styles.viewport}>+ <Cards count={6} />+ </ScrollableArea>+ </VStack>+ );+}++export const RTLBehaviorProbe: Story = {+ render: () => <RTLBehaviorProbeStory />,+ parameters: {controls: {disable: true}},+};++function TransformedClipDemo() {+ const [activations, setActivations] = useState(0);+ return (+ <VStack gap={2} xstyle={styles.canvas}>+ <Text type="supporting" color="secondary">+ The native viewport remains clickable inside a perspective ancestor and+ a clipped rounded frame.+ </Text>+ <div {...stylex.props(styles.transformedHost)}>+ <div {...stylex.props(styles.clippedFrame)}>+ <ScrollableArea+ axis="block"+ label="Transformed clipped activity"+ data-evidence="transformed-clipped"+ xstyle={styles.viewportCompact}>+ <VStack gap={2} xstyle={styles.contentPadding}>+ <Button+ label="Activate clipped target"+ data-transform-hit-target="true"+ onClick={() => setActivations(value => value + 1)}>+ Activate clipped target+ </Button>+ <Text data-transform-hit-count="true">+ Activations: {activations}+ </Text>+ <Rows count={5} />+ </VStack>+ </ScrollableArea>+ </div>+ </div>+ </VStack>+ );+}++export const TransformedClippedAncestor: Story = {+ render: () => <TransformedClipDemo />,+ parameters: {controls: {disable: true}},+};++export const ContainerIntegration: Story = {+ render: () => (+ <div {...stylex.props(styles.canvas)}>+ <Section padding={4} width={340}>+ <ScrollableArea+ axis="block"+ label="Full-bleed activity"+ isFullBleed+ padding={3}+ data-evidence="container-integration"+ xstyle={styles.containerViewport}>+ <Rows count={6} />+ </ScrollableArea>+ </Section>+ </div>+ ),+ parameters: {controls: {disable: true}},+};++export const NativeScrollbarPresentation: Story = {+ render: () => (+ <VStack gap={4} xstyle={styles.canvas}>+ <Text weight="semibold">Platform default with neutral thumb</Text>+ <ScrollableArea+ axis="inline"+ label="Default native scrollbar"+ data-evidence="scrollbar-default"+ xstyle={styles.viewport}>+ <Cards count={6} />+ </ScrollableArea>+ <Text weight="semibold">Thin width and stable gutter</Text>+ <ScrollableArea+ axis="inline"+ label="Thin stable native scrollbar"+ data-evidence="scrollbar-thin-stable"+ xstyle={[+ styles.viewport,+ styles.scrollbarThin,+ styles.scrollbarStable,+ ]}>+ <Cards count={6} />+ </ScrollableArea>+ <Text weight="semibold">+ Consumer neutral override, transparent track+ </Text>+ <ScrollableArea+ axis="inline"+ label="Neutral native scrollbar"+ data-evidence="scrollbar-neutral"+ xstyle={[styles.viewport, styles.scrollbarNeutral]}>+ <Cards count={6} />+ </ScrollableArea>+ </VStack>+ ),+ parameters: {controls: {disable: true}},+};diff --git a/docs/architecture/container-padding.md b/docs/architecture/container-padding.mdindex 817d1a01c5..6fb9184357 100644--- a/docs/architecture/container-padding.md+++ b/docs/architecture/container-padding.md@@ -20,6 +20,7 @@ applies_to:packages/core/src/Lightbox/,packages/core/src/MobileNav/,packages/core/src/Section/,+ packages/core/src/ScrollableArea/,packages/core/src/Layout/,packages/core/src/Divider/,packages/core/src/Table/,@@ -29,12 +30,13 @@ applies_to:verified_by:[packages/core/src/Section/Section.test.tsx,+ packages/core/src/ScrollableArea/ScrollableArea.test.tsx,packages/core/src/Layout/Layout.test.tsx,packages/core/src/Layout/LayoutSlots.test.tsx,packages/core/src/Layout/overlayPaddingReset.test.tsx,packages/core/src/Layout/__tests__/edgeCompensation.test.tsx,]-deciding_specs: []+deciding_specs: [spec:AST-025/DEC-2]---# Container padding architecture@@ -46,8 +48,9 @@ each logical edge. Without it, a full-bleed child cannot cancel the padding itactually received, a nested region cannot preserve one content line, and anoverlay can inherit geometry from a visual box it no longer occupies.-This record describes the shipped internal protocol. It does not add a public-prop, CSS variable, theme capability, or new participant.+This record describes the shared internal protocol. It does not make its CSS+variables public API. `spec:AST-025/DEC-2` adds ScrollableArea as an explicit+participant with no padding and no bleed by default.## System model@@ -74,18 +77,20 @@ The protocol has four layers:### Shipped publishers and consumers-| Role | Current participants | Shipped responsibility |-| ------------------- | ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------- |-| Container publisher | Card, Section, Dialog | Resolve component padding and publish logical-edge and Layout inset variables through `container()` |-| Region publisher | LayoutHeader, LayoutContent, LayoutFooter, LayoutPanel | Publish baseline or explicit-padding geometry; automatic outer-edge publication has the conformance gap below |-| Bleed consumer | Section, Layout, Divider, Table | Subtract inherited inset on the edges each component is designed to escape |-| Alignment consumer | Toolbar and edge-compensating child components | Read the current inline inset to align visible content rather than stacked touch-target padding |-| Boundary owner | Layer surfaces and dialog-based overlay roots | Apply `overlayPaddingReset` before descendants read inherited page geometry |+| Role | Current participants | Shipped responsibility |+| ------------------- | ------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------- |+| Container publisher | Card, Section, Dialog, ScrollableArea | Resolve component padding or publish explicit content-box padding as logical-edge and Layout inset variables |+| Region publisher | LayoutHeader, LayoutContent, LayoutFooter, LayoutPanel | Publish baseline or explicit-padding geometry; automatic outer-edge publication has the conformance gap below |+| Bleed consumer | Section, ScrollableArea, Layout, Divider, Table | Subtract inherited inset on the edges each component is designed to escape; ScrollableArea does so only with `isFullBleed` |+| Alignment consumer | Toolbar and edge-compensating child components | Read the current inline inset to align visible content rather than stacked touch-target padding |+| Boundary owner | Layer surfaces and dialog-based overlay roots | Apply `overlayPaddingReset` before descendants read inherited page geometry |The participant list is the shared container system, not a Layout-owned family:-Section and Layout publish or redistribute insets, Table and Divider consume-bleed geometry, and Toolbar consumes alignment geometry. Participation here does-not by itself make Table or Divider a member of `family:layout-regions`.+Section and ScrollableArea publish content inset, Section and opt-in full-bleed+ScrollableArea instances consume inherited inset, Layout redistributes inset,+Table and Divider consume bleed geometry, and Toolbar consumes alignment geometry.+Participation here does not by itself make Table, Divider, or ScrollableArea a+member of `family:layout-regions`.`--_section-padding-propagated` is separate from the public`--astryx-section-padding` property. The private value carries one ancestor@@ -168,25 +173,26 @@ evidence, not part of this documentation stack.logical-edge setters, Section propagation, and the overlay reset.- `packages/core/src/Layout/edgeCompensation.stylex.ts` — owns the container-sidealignment adjustment for marked edge content.-- Card, Section, Dialog, and Layout region implementations — publish their- current geometry.-- Section, Layout, Divider, Table, and Toolbar implementations — consume the- current geometry for bleed or alignment.+- Card, Section, Dialog, ScrollableArea, and Layout region implementations —+ publish their current geometry.+- Section, ScrollableArea, Layout, Divider, Table, and Toolbar implementations —+ consume the current geometry for bleed or alignment.- Overlay roots — apply the reset at the visual boundary.## Deciding specs-None. This record names the already shipped protocol and its current ownership-boundaries.+- `spec:AST-025/DEC-2` — ScrollableArea publishes optional content padding and+ consumes inherited inset only through explicit full bleed.## Verification-| Invariant | Evidence | Failure signal |-| ---------- | ---------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |-| INV2, INV5 | `Section.test.tsx` per-edge and nested-propagation tests | A per-edge prop leaves a stale geometry variable, or nested Sections lose the shipped propagation order |-| INV4 | Layout source review plus `Layout.test.tsx` and `LayoutSlots.test.tsx` | Slot presence stops selecting the shipped applied outer/inner edge styles; exact republished geometry remains limited by the named conformance gap |-| INV6 | `overlayPaddingReset.test.tsx` | An overlay inherits page inset, loses its theme's Section padding, or lets ancestor Section propagation cross the boundary |-| INV3, INV7 | `Layout/__tests__/edgeCompensation.test.tsx` plus component tests | An unmarked child is compensated, or marked edge content loses direct-child discoverability |+| Invariant | Evidence | Failure signal |+| ---------------- | ---------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |+| INV2, INV5 | `Section.test.tsx` per-edge and nested-propagation tests | A per-edge prop leaves a stale geometry variable, or nested Sections lose the shipped propagation order |+| INV2, INV3, INV8 | `ScrollableArea.test.tsx` padding and full-bleed tests | The content box publishes inset different from its applied padding, or the viewport escapes inherited padding without explicit full bleed |+| INV4 | Layout source review plus `Layout.test.tsx` and `LayoutSlots.test.tsx` | Slot presence stops selecting the shipped applied outer/inner edge styles; exact republished geometry remains limited by the named conformance gap |+| INV6 | `overlayPaddingReset.test.tsx` | An overlay inherits page inset, loses its theme's Section padding, or lets ancestor Section propagation cross the boundary |+| INV3, INV7 | `Layout/__tests__/edgeCompensation.test.tsx` plus component tests | An unmarked child is compensated, or marked edge content loses direct-child discoverability |The current suite does not provide one browser matrix that compares computedpadding and bleed across every publisher and consumer. Component tests and thediff --git a/docs/specs/AST-025/spec.md b/docs/specs/AST-025/spec.mdindex 3ea9f83d80..e72c5dd4ce 100644--- a/docs/specs/AST-025/spec.md+++ b/docs/specs/AST-025/spec.md@@ -10,7 +10,8 @@ approved_by: cixzhangapproved_at: 2026-09-11phase: acceptedowners: [cixzhang]-affects_architecture: [architecture:public-component-api]+affects_architecture:+ [architecture:container-padding, architecture:public-component-api]affects_families: [family:layout-regions, family:layout-primitives]affects_contributing: []affects_consumer_docs:@@ -165,6 +166,18 @@ the behavior.separate public ScrollableArea component merely to participate. An arbitraryexternal wrapper cannot satisfy Table's internal ownership contract unless Tableexplicitly accepts and coordinates that owner.+- **FR20 — The reference component integrates container geometry.** ScrollableArea+ MUST publish the actual logical padding of its content box, using zero when no+ padding is requested. Its viewport MAY consume inherited padding only through an+ explicit full-bleed option; scrollability alone MUST NOT escape a parent container.+- **FR21 — Fitting scroll intent does not imply Sticky containment.** A participating+ viewport whose requested axes have no excess geometry MUST use `clip` on both+ physical axes. This prevents pre-measure paint overflow without creating a CSS+ scroll container, so native Sticky descendants can resolve to an outer effective+ owner. The viewport MUST switch to its requested `auto`/`hidden` pair when content+ exceeds the viewport, before the axis becomes an effective owner. A public+ `stickyContainment="always"` option MAY preserve that boundary while fitting, but+ containment MUST be explicit rather than an incidental result of scroll intent.### Delivery requirements@@ -213,10 +226,11 @@ interface ScrollAxisState {interface UseScrollableAreaOptions {axis: ScrollAxis;keyboardAccess: KeyboardAccess;- scrollChaining?: 'allow' | 'contain';+ overscroll?: 'allow' | 'contain';+ stickyContainment?: 'whenScrollable' | 'always';}-type ElementProps<E extends HTMLElement> = React.HTMLAttributes<E> &+type ElementProps<E extends HTMLElement> = BaseProps<E> &React.RefAttributes<E>;interface UseScrollableAreaResult {@@ -235,11 +249,12 @@ interface UseScrollableAreaResult {Each prop getter receives the adopter's already-resolved element props and publicref, composes them with the hook's behavior through the shared prop/ref utilities,-and returns one safe spread object. `getViewportProps` adds behavior-owned keyboard,-ARIA, event, data-state, overscroll, and registration behavior without choosing the-viewport's layout or paint. `getContentProps` composes content observation with an-existing content ref and props. Neither a loose prop bag nor a separate callback ref-makes spread order part of the contract.+and returns one safe spread object. `getViewportProps` consumes caller `xstyle` and+adds behavior-owned fitting clip, axis-specific active overflow, explicit Sticky+containment, keyboard, ARIA, event, data-state, overscroll, and registration behavior+without choosing viewport sizing or scrollbar presentation. `getContentProps`+composes content observation with an existing content ref and props. Neither a loose+prop bag nor a separate callback ref makes spread order part of the contract.Native scrollbar width, color, and gutter remain CSS on the viewport rather thanhook options. Optional custom presenters and scroll shadows consume the same@@ -342,16 +357,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 |+| 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 |## Decision log@@ -374,6 +391,40 @@ Rejected: making `ScrollableArea` the only entry point, because that would requiextra wrappers and turn a behavior component into the owner of component-specificstructure.+### DEC-2 — ScrollableArea is an explicit container-padding participant++**Reference:** `spec:AST-025/DEC-2`+**Decider:** `cixzhang`, `2026-09-11`++The reference component publishes its content box's logical padding, zero by+default, so nested bleed consumers receive the geometry actually applied.+Viewport bleed remains explicit rather than a side effect of becoming scrollable.+This aligns ScrollableArea with the shared container system without making the+behavior hook own padding or layout.++Rejected: automatic parent-padding escape, because adding scrolling must not+silently widen a container's visual boundary.++### DEC-3 — Fitting scroll intent does not silently contain Sticky++**Reference:** `spec:AST-025/DEC-3`+**Decider:** `cixzhang`, `2026-09-12`++The shared hook applies `clip` on both physical axes until requested content+exceeds its geometry. This avoids pre-measure paint overflow without creating a CSS+scroll container, so a fitting area does not silently intercept native Sticky from+an outer owner. Geometry-only overflow state activates the writing-mode-resolved+`auto`/`hidden` pair before effective ownership is measured.++`stickyContainment="always"` is the explicit opt-in for consumers that deliberately+want the fitting viewport to remain a Sticky boundary. Its camelCase enum follows+the public API conventions.++Rejected: retaining `auto`/`hidden` for every requested viewport, because scroll+intent alone would change Sticky behavior even when no scrolling can occur.+Rejected: no overflow declaration while fitting, because content could flash before+the first geometry measurement.+## Open questions- **OQ1 — How is the Layout `isScrollable` migration observed and sequenced?**diff --git a/internal/shadcn-registry/routes.lock.json b/internal/shadcn-registry/routes.lock.jsonindex 45a5f35ae0..a111568174 100644--- a/internal/shadcn-registry/routes.lock.json+++ b/internal/shadcn-registry/routes.lock.json@@ -791,6 +791,11 @@"path": "components/richtext/rich-text-editor","aliases": []},+ {+ "name": "component-scrollable-area",+ "path": "components/scrollable-area",+ "aliases": []+ },{"name": "component-section","path": "components/section",@@ -3685,6 +3690,11 @@"path": "hooks/use-scroll-overflow","aliases": []},+ {+ "name": "hook-use-scrollable-area",+ "path": "hooks/use-scrollable-area",+ "aliases": []+ },{"name": "hook-use-streaming-text","path": "hooks/use-streaming-text",diff --git a/packages/core/package.json b/packages/core/package.jsonindex 81c9e822fc..dbf81088f9 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -434,6 +434,11 @@"types": "./dist/Resizable/index.d.ts","default": "./dist/Resizable/index.js"},+ "./ScrollableArea": {+ "source": "./src/ScrollableArea/index.ts",+ "types": "./dist/ScrollableArea/index.d.ts",+ "default": "./dist/ScrollableArea/index.js"+ },"./Section": {"source": "./src/Section/index.ts","types": "./dist/Section/index.d.ts",diff --git a/packages/core/src/ScrollableArea/ScrollableArea.doc.mjs b/packages/core/src/ScrollableArea/ScrollableArea.doc.mjsnew file mode 100644index 0000000000..8c639db474--- /dev/null+++ b/packages/core/src/ScrollableArea/ScrollableArea.doc.mjs@@ -0,0 +1,100 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').ComponentDoc} */+export const docs = {+ name: 'ScrollableArea',+ displayName: 'Scrollable Area',+ category: 'Layout',+ keywords: ['scroll', 'overflow', 'viewport', 'logical axis', 'keyboard', 'overscroll', 'sticky', 'scrollbar', 'padding', 'full bleed'],+ usage: {+ description: 'Provides a native scroll viewport and a real observed content box. The viewport enters the tab order only while a requested logical axis is effectively scrollable, and containment applies only to effective axes.',+ bestPractices: [+ {guidance: true, description: 'Give every area a concise label that identifies the content keyboard users will scroll.'},+ {guidance: true, description: 'Choose `inline`, `block`, or `both` from content intent; the component maps the logical axes through writing mode and direction.'},+ {guidance: true, description: 'Keep the default `overscroll="allow"` for nested areas unless the interaction deliberately needs containment.'},+ {guidance: true, description: 'Use `useScrollableArea` instead when a component already owns both a viewport and a suitable content box, or when children must remain direct flex/grid items or retain a definite percentage block-size basis.'},+ {guidance: true, description: 'ScrollableArea owns one normal block content box with a 100% minimum size. Inline and both-axis modes use max-content inline sizing, so intrinsic inline layout is intentionally wider than the viewport.'},+ {guidance: true, description: 'Use logical padding props on the content box so nested full-bleed components receive the same inset geometry.'},+ {guidance: true, description: 'Set `isFullBleed` only when the viewport itself should reach an ancestor container edge; it is off by default.'},+ {guidance: true, description: 'Set `stickyContainment="always"` only when a fitting viewport should intentionally remain a Sticky boundary.'},+ {guidance: false, description: 'Hide the native scrollbar without another visible and operable overflow affordance.'},+ {guidance: false, description: 'Add another overflow wrapper around ScrollableArea; one native viewport should own scrolling.'},+ ],+ anatomy: [+ {name: 'Viewport', required: true, description: 'The root native scroll container, accessible name owner, focus target while effective, and `astryx-scrollable-area` theme target.'},+ {name: 'Content box', required: true, description: 'A real inner layout box observed together with the viewport. For inline scrolling it uses max-content inline sizing with a 100% minimum.'},+ ],+ },+ props: [+ {name: 'axis', type: "'inline' | 'block' | 'both'", description: 'Logical axis or axes where native scrolling is allowed.', default: "'block'"},+ {name: 'label', type: 'string', description: 'Accessible name for the viewport when it becomes keyboard scrollable.', required: true},+ {name: 'role', type: "'group' | 'region'", description: 'Semantics for the named viewport.', default: "'group'"},+ {name: 'overscroll', type: "'allow' | 'contain'", description: 'Whether effective axes continue scrolling an ancestor at their edge.', default: "'allow'"},+ {name: 'width', type: 'SizeValue', description: 'Width of the viewport; a number is interpreted as pixels, a string is used as-is.'},+ {name: 'height', type: 'SizeValue', description: 'Height of the viewport; a number is interpreted as pixels, a string is used as-is.'},+ {name: 'maxWidth', type: 'SizeValue', description: 'Maximum width of the viewport.'},+ {name: 'minHeight', type: 'SizeValue', description: 'Minimum height of the viewport.'},+ {name: 'stickyContainment', type: "'whenScrollable' | 'always'", description: 'Whether fitting content passes Sticky ownership to an outer container or deliberately keeps this viewport as the CSS Sticky boundary.', default: "'whenScrollable'"},+ {name: 'padding', type: '0 | 0.5 | 1 | 1.5 | 2 | 3 | 4 | 5 | 6 | 8 | 10', description: 'Content padding on every logical edge; publishes matching inset geometry.', default: '0'},+ {name: 'paddingInline', type: '0 | 0.5 | 1 | 1.5 | 2 | 3 | 4 | 5 | 6 | 8 | 10', description: 'Logical inline-axis content padding; overrides `padding` on that axis.'},+ {name: 'paddingInlineStart', type: '0 | 0.5 | 1 | 1.5 | 2 | 3 | 4 | 5 | 6 | 8 | 10', description: 'Logical inline-start content padding; overrides broader padding values.'},+ {name: 'paddingInlineEnd', type: '0 | 0.5 | 1 | 1.5 | 2 | 3 | 4 | 5 | 6 | 8 | 10', description: 'Logical inline-end content padding; overrides broader padding values.'},+ {name: 'paddingBlock', type: '0 | 0.5 | 1 | 1.5 | 2 | 3 | 4 | 5 | 6 | 8 | 10', description: 'Logical block-axis content padding; overrides `padding` on that axis.'},+ {name: 'paddingBlockStart', type: '0 | 0.5 | 1 | 1.5 | 2 | 3 | 4 | 5 | 6 | 8 | 10', description: 'Logical block-start content padding; overrides broader padding values.'},+ {name: 'paddingBlockEnd', type: '0 | 0.5 | 1 | 1.5 | 2 | 3 | 4 | 5 | 6 | 8 | 10', description: 'Logical block-end content padding; overrides broader padding values.'},+ {name: 'isFullBleed', type: 'boolean', description: 'Lets the viewport escape inherited container padding without changing content padding.', default: 'false'},+ {name: 'children', type: 'ReactNode', description: 'Content rendered inside the observed content box.'},+ {name: 'xstyle', type: 'StyleXStyles', description: 'StyleX sizing and native scrollbar presentation overrides for the viewport.'},+ ],+ playground: {+ defaults: {+ axis: 'block',+ label: 'Scrollable example',+ children: 'Add enough content to exceed a constrained viewport.',+ },+ },+ theming: {+ targets: [+ {className: 'astryx-scrollable-area', visualProps: ['axis']},+ ],+ },+};++/** @type {import('@astryxdesign/cli/authoring').ComponentTranslationDoc} */+export const docsDense = {+ description: 'native logical-axis scroll viewport with conditional keyboard access, live edge state, and observed content geometry',+ usage: {+ description: 'Use for a complete viewport/content composition; use useScrollableArea for existing structure.',+ bestPractices: [+ {guidance: true, description: 'Always provide a concise label.'},+ {guidance: true, description: 'Prefer overscroll allow; contain only deliberate nested interactions.'},+ {guidance: true, description: 'Use content padding props to publish inset; use isFullBleed only for viewport escape.'},+ {guidance: false, description: 'Nest another overflow wrapper around it.'},+ ],+ anatomy: [+ {name: 'Viewport', required: true, description: 'native scrolling, conditional tab stop, and theme target'},+ {name: 'Content box', required: true, description: 'real observed layout box'},+ ],+ },+ propDescriptions: {+ axis: "logical scroll intent: 'inline' | 'block' (default) | 'both'",+ label: 'required accessible viewport name',+ role: "named viewport semantics: 'group' (default) | 'region'",+ overscroll: "edge behavior: 'allow' (default) | 'contain' on effective axes only",+ width: 'viewport width',+ height: 'viewport height',+ maxWidth: 'viewport maximum width',+ minHeight: 'viewport minimum height',+ stickyContainment: "fitting Sticky ownership: 'whenScrollable' (default) | 'always'",+ padding: 'content inset on every edge; defaults to 0 and publishes geometry',+ paddingInline: 'logical inline-axis content inset',+ paddingInlineStart: 'logical inline-start content inset',+ paddingInlineEnd: 'logical inline-end content inset',+ paddingBlock: 'logical block-axis content inset',+ paddingBlockStart: 'logical block-start content inset',+ paddingBlockEnd: 'logical block-end content inset',+ isFullBleed: 'opt-in viewport escape from inherited container padding',+ children: 'content inside the observed box',+ xstyle: 'viewport sizing and native scrollbar presentation overrides',+ },+};diff --git a/packages/core/src/ScrollableArea/ScrollableArea.spec.md b/packages/core/src/ScrollableArea/ScrollableArea.spec.mdnew file mode 100644index 0000000000..761840e9f1--- /dev/null+++ b/packages/core/src/ScrollableArea/ScrollableArea.spec.md@@ -0,0 +1,189 @@+---+schema_version: 3+template_version: 4+kind: component+id: component:ScrollableArea+authority: current+archive_reason: null+superseded_by: null+approved_by: cixzhang+approved_at: 2026-09-11+owners: [cixzhang]+review_triggers: [public-api, behavior, layout, theming, accessibility]+verified_by:+ [+ packages/core/src/ScrollableArea/ScrollableArea.test.tsx,+ packages/core/src/hooks/useScrollableArea.test.tsx,+ apps/storybook/stories/ScrollableArea.stories.tsx,+ ]+modules: [module:ScrollableArea/useScrollableArea]+families: []+design_specs: []+architecture:+ [architecture:container-padding, architecture:public-component-api]+contributing: []+system_specs: [spec:AST-025/DEC-1]+---++# ScrollableArea component contract++## Intent++ScrollableArea gives builders a complete native scroll viewport and observable+content box without making them coordinate keyboard access, chaining, edge state,+and native scrollbar presentation. It is the reference composition over the+shared behavior hook, not the exclusive owner of that behavior.++## Compatibility and migration++- Released default preserved: not yet released+- Compatibility class: additive component and package exports+- Controlled/uncontrolled behavior: not applicable+- Migration decision: `spec:AST-025/DEC-1`++## Ownership boundary++**Owns**++- One root native viewport and one real observed inner content box.+- Conditional viewport keyboard access, accessible naming, logical-axis intent,+ overscroll policy, and native scrollbar defaults supplied by the shared hook.+- Optional logical content padding that publishes matching container inset, plus+ opt-in viewport bleed against inherited container padding.++**Does not own / non-goals**++- JavaScript-driven scrolling or custom scrollbar DOM.+- A general Sticky public API or fallback positioning algorithm.+- Existing component-owned viewport migrations such as Layout and Table.++## Public concepts++| Concept | Closed values or states | Meaning | Availability by variant/orientation/state | Default | Owner | Stability | Invalid-value behavior |+| ------------------ | ------------------------------------------ | ------------------------------------------- | ----------------------------------------- | ---------------- | -------------------------------- | --------- | ---------------------- |+| logical axis | `inline`, `block`, `both` | axes where native scrolling is allowed | all | `block` | `spec:AST-025` | stable | type error |+| overscroll | `allow`, `contain` | whether effective axes propagate at an edge | all | `allow` | `spec:AST-025` | stable | type error |+| viewport sizing | `width`, `height`, `maxWidth`, `minHeight` | standard container geometry on the viewport | all | auto | `component:ScrollableArea` | stable | type error |+| content padding | shared logical spacing-step ladder | content-box inset and published geometry | all | `0` | `architecture:container-padding` | stable | type error |+| full bleed | `false`, `true` | whether viewport escapes inherited inset | all | `false` | `architecture:container-padding` | stable | type error |+| Sticky containment | `whenScrollable`, `always` | whether fitting content captures Sticky | all | `whenScrollable` | `spec:AST-025` | stable | type error |+| viewport semantics | `group`, `region` plus required label | names a conditional keyboard scroll target | all | `group` | `component:ScrollableArea` | stable | type error |++## Behavioral and layout contract++| ID | Invariant | Basis | Acceptance and implementation state |+| --- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------- | ----------------------------------- |+| FR1 | The root MUST remain the one native viewport and receive the public ref, standard container sizing props, and styling inputs through StyleX. | `spec:AST-025` IR3–IR4 | implemented |+| FR2 | The inner content wrapper MUST be a real normal-flow block box observed with the viewport, use a 100% minimum size, and use max-content inline sizing only when inline scrolling is requested. Children participate in that box rather than the viewport's flex/grid formatting context, and the minimum block size does not create a definite percentage-height basis; structures that must preserve those semantics adopt the hook directly. | `spec:AST-025` FR5–FR6 | implemented |+| FR3 | Native scrollbar behavior MUST remain authoritative; the default thumb uses `--color-neutral`, the track is transparent, and forced colors restore platform presentation. | `spec:AST-025` FR15 | implemented |+| FR4 | Scroll-state container queries MAY enhance descendant stuck/edge presentation, but hook state MUST remain the cross-browser source of truth. | `spec:AST-025` platform support | implemented progressively |+| FR5 | The content box MUST apply and publish logical padding with edge-over-axis-over-uniform precedence, defaulting every published edge to zero. `isFullBleed` MUST let only the viewport consume inherited inset; nested content continues to read the content box's published values. | `architecture:container-padding` | implemented |+| FR6 | A fitting viewport MUST use `clip` on both physical axes so it prevents paint overflow without capturing native Sticky. Excess requested-axis geometry MUST activate the writing-mode-resolved `auto`/`hidden` pair. `stickyContainment="always"` MUST explicitly retain that pair while fitting. | `spec:AST-025` FR21 | implemented |++### Allowed variation++- **AV1 — Sizing and presentation.** Consumer `xstyle`, `className`, and `style`+ may size the viewport and adjust standards-based native scrollbar properties.+- **AV2 — Content.** Any flow content may render in the observed box; builders+ remain responsible for content semantics.++### Representative states++| State | Required invariant | Allowed variation |+| ------------------------------ | ------------------------------------------------------------------------------------------------------- | -------------------------- |+| fitting | `clip` on both axes; no tab stop; Sticky passes outward unless containment is `always`; both edges true | viewport size and content |+| overflowing | named tab stop; per-axis logical edge state | one or both requested axes |+| overflow removed while focused | remove future tab stop without moving focus | current focus remains |+| forced colors | native platform scrollbar presentation | platform rendering |++### Transformation and precedence order++- **ORD1 — Props.** Consumer DOM and styling props compose first; behavior-owned+ ref, accessibility, and active-axis chaining win documented conflicts.++### Performance and resources++- **PR1 — Shared, coalesced observation.** Viewport and content resize signals use+ the shared observer, and repeated invalidations publish at most once per frame.++## Accessibility contract++- **AR1 — Conditional access.** The viewport enters sequential navigation only+ while at least one requested axis is effective, with the supplied label and role.+- **AR2 — Focus continuity.** Losing overflow MUST NOT blur or move focus.++## Design relationships++| Anatomy or state | Design requirement | Representation authority | Hierarchy role | Component contract |+| ---------------- | ----------------------------------------------------------------- | ------------------------ | -------------- | ------------------ |+| Viewport | platform scrollbar with token-colored thumb and transparent track | `spec:AST-025` | supporting | FR1, FR3 |+| Content box | no independent paint by default | caller content | structural | FR2 |++### Theming anatomy++<!-- anatomy-theming:v1 -->++```json+{+ "Viewport": {"target": "scrollable-area"},+ "Content box": {+ "none": {+ "reason": "intentional: The content box is structural and paints no component-owned appearance."+ }+ }+}+```++## Family and system relationships++- `module:ScrollableArea/useScrollableArea` owns reusable measurement,+ overflow-boundary, Sticky-containment, accessibility, and registration behavior.+- `architecture:container-padding` owns optional content inset publication and+ opt-in viewport bleed.+- `spec:AST-025` owns shared effective-axis, observation, accessibility, overscroll,+ ownership, edge, and native presentation rules.++## Verification map++| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |+| ---------------- | ------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | ------------------------------- |+| FR1–FR6, AR1–AR2 | component/hook tests and Storybook browser probe | fit, overflow, focused loss, LTR/RTL/vertical, nested allow/contain, fitting Sticky passthrough/containment, native scrollbar, padding, full bleed | duplicate viewport, stale state, dead nested scroll zone, implicit Sticky containment, unconditional tab stop, or stale inset fails | `audit:ScrollableArea/behavior` |++## Decision log++### DEC-1 — The convenience component owns one explicit content box++**Reference:** `component:ScrollableArea/DEC-1`+**Decider:** cixzhang, 2026-09-11++A stable viewport/content structure gives the reference component dependable live+measurement while leaving structure-owning components free to adopt the hook directly.++### DEC-2 — ScrollableArea participates in the container-padding system++**Reference:** `component:ScrollableArea/DEC-2`+**Decider:** cixzhang, 2026-09-11++The content box publishes its actual logical padding, zero by default, so nested+bleed consumers never inherit stale inset. The viewport consumes ancestor inset+only when `isFullBleed` is explicit; scrolling alone does not silently escape its+parent container.++### DEC-3 — Fitting content passes Sticky ownership outward by default++**Reference:** `component:ScrollableArea/DEC-3`+**Decider:** cixzhang, 2026-09-12++A fitting viewport uses `clip` on both axes to prevent a pre-measure paint flash+without becoming a CSS scroll container. Excess requested-axis geometry activates+the writing-mode-resolved scroll boundary. `stickyContainment="always"` is the+explicit opt-in for retaining that boundary while fitting.++## Open questions++None.++## Content boundary++This file does not duplicate consumer examples, the shared hook algorithm, Sticky's+future public API, or migration plans for existing component-owned viewports.diff --git a/packages/core/src/ScrollableArea/ScrollableArea.test.tsx b/packages/core/src/ScrollableArea/ScrollableArea.test.tsxnew file mode 100644index 0000000000..82b7e543e9--- /dev/null+++ b/packages/core/src/ScrollableArea/ScrollableArea.test.tsx@@ -0,0 +1,299 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {readFileSync} from 'node:fs';+import {act, render, screen} from '@testing-library/react';+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';+import {ScrollableArea} from './ScrollableArea';++function setGeometry(+ element: HTMLElement,+ values: Partial<+ Pick<+ HTMLElement,+ 'clientWidth' | 'clientHeight' | 'scrollWidth' | 'scrollHeight'+ >+ >,+) {+ for (const [key, value] of Object.entries(values)) {+ Object.defineProperty(element, key, {+ configurable: true,+ value,+ writable: true,+ });+ }+}++describe('ScrollableArea', () => {+ let frames: FrameRequestCallback[];++ beforeEach(() => {+ frames = [];+ vi.stubGlobal(+ 'requestAnimationFrame',+ vi.fn((callback: FrameRequestCallback) => {+ frames.push(callback);+ return frames.length;+ }),+ );+ vi.stubGlobal('cancelAnimationFrame', vi.fn());+ vi.stubGlobal(+ 'ResizeObserver',+ vi.fn(function () {+ return {observe: vi.fn(), unobserve: vi.fn(), disconnect: vi.fn()};+ }),+ );+ });++ afterEach(() => vi.unstubAllGlobals());++ function flushFrame() {+ void act(() => {+ const pending = frames.splice(0);+ pending.forEach(callback => callback(performance.now()));+ });+ }++ it('renders one native viewport and one real content box', () => {+ render(+ <ScrollableArea label="Messages" data-testid="viewport">+ <p>Message history</p>+ </ScrollableArea>,+ );++ const viewport = screen.getByTestId('viewport');+ expect(viewport).toHaveAccessibleName('Messages');+ expect(viewport).toHaveAttribute('role', 'group');+ expect(viewport).toHaveAttribute('data-scroll-axis', 'block');+ expect(viewport).not.toHaveAttribute('tabindex');+ expect(viewport.children).toHaveLength(1);+ expect(viewport.firstElementChild).toHaveAttribute('data-scroll-content');+ expect(viewport).toHaveTextContent('Message history');+ });++ it('becomes keyboard reachable only when the requested axis is effective', () => {+ render(+ <ScrollableArea+ axis="block"+ label="Messages"+ data-testid="viewport"+ style={{height: 100}}>+ <p>Message history</p>+ </ScrollableArea>,+ );+ const viewport = screen.getByTestId('viewport');+ // jsdom does not resolve StyleX's dynamic CSS variables. Mirror the+ // generated class values so this integration test can exercise measurement.+ viewport.style.overflowX = 'hidden';+ viewport.style.overflowY = 'auto';+ setGeometry(viewport, {+ clientWidth: 100,+ clientHeight: 100,+ scrollWidth: 100,+ scrollHeight: 180,+ });++ void act(() => viewport.dispatchEvent(new Event('scroll')));+ flushFrame();+ expect(viewport).toHaveAttribute('tabindex', '0');+ expect(viewport).toHaveAttribute('data-scrollable-block', 'true');++ setGeometry(viewport, {scrollHeight: 100});+ viewport.focus();+ void act(() => viewport.dispatchEvent(new Event('scroll')));+ flushFrame();+ expect(viewport).toHaveAttribute('tabindex', '-1');+ expect(document.activeElement).toBe(viewport);+ });++ it('keeps viewport props, styles, class names, events, and refs', () => {+ const onClick = vi.fn();+ const ref = vi.fn();+ render(+ <ScrollableArea+ label="Results"+ role="region"+ ref={ref}+ onClick={onClick}+ className="consumer-class"+ style={{maxHeight: 200}}+ data-testid="viewport">+ Results+ </ScrollableArea>,+ );++ const viewport = screen.getByTestId('viewport');+ viewport.click();+ expect(onClick).toHaveBeenCalledTimes(1);+ expect(ref).toHaveBeenCalledWith(viewport);+ expect(viewport).toHaveClass('astryx-scrollable-area', 'consumer-class');+ expect(viewport.style.maxHeight).toBe('200px');+ expect(viewport).toHaveAttribute('role', 'region');+ });++ it('reflects logical axis and chaining intent without containing a fitting area', () => {+ render(+ <ScrollableArea+ axis="both"+ label="Canvas"+ overscroll="contain"+ data-testid="viewport">+ Canvas+ </ScrollableArea>,+ );+ const viewport = screen.getByTestId('viewport');+ expect(viewport).toHaveAttribute('data-axis', 'both');+ expect(viewport).toHaveAttribute('data-scroll-axis', 'both');+ expect(viewport.style.overscrollBehaviorX).toBe('auto');+ expect(viewport.style.overscrollBehaviorY).toBe('auto');+ });++ it('keeps logical overflow and content sizing for writing-mode changes', () => {+ const {rerender} = render(+ <ScrollableArea axis="inline" label="Timeline" data-testid="viewport">+ Timeline+ </ScrollableArea>,+ );+ const viewport = screen.getByTestId('viewport');+ const content = viewport.firstElementChild as HTMLElement;+ const inlineViewportClass = viewport.className;+ expect(viewport.style.overflowInline).toBe('');+ expect(viewport.style.overflowBlock).toBe('');+ const inlineContentClass = content.className;+ expect(content.style.inlineSize).toBe('');+ expect(content.style.minInlineSize).toBe('');++ rerender(+ <ScrollableArea axis="block" label="Timeline" data-testid="viewport">+ Timeline+ </ScrollableArea>,+ );+ expect(viewport.className).not.toBe(inlineViewportClass);+ expect(viewport.style.overflowInline).toBe('');+ expect(viewport.style.overflowBlock).toBe('');+ expect(content.className).not.toBe(inlineContentClass);+ expect(content.style.inlineSize).toBe('');+ const source = stylesSource();+ expect(source).not.toContain('dynamicStyles.overflow(');+ expect(source).not.toContain('logicalOverflowStyle');+ expect(hookSource()).toContain('styles.overflow(');+ expect(source).toContain("minInlineSize: '100%'");+ expect(source).toContain("inlineSize: 'max-content'");+ });++ it('uses clip while fitting and makes fitting Sticky containment explicit', () => {+ const {rerender} = render(+ <ScrollableArea label="Messages" data-testid="viewport">+ Messages+ </ScrollableArea>,+ );+ const viewport = screen.getByTestId('viewport');+ expect(viewport.getAttribute('style')).toContain('clip');+ expect(viewport).not.toHaveAttribute('tabindex');++ rerender(+ <ScrollableArea+ label="Messages"+ stickyContainment="always"+ data-testid="viewport">+ Messages+ </ScrollableArea>,+ );+ expect(viewport.getAttribute('style')).toContain('auto');+ expect(viewport.getAttribute('style')).toContain('hidden');+ expect(viewport).not.toHaveAttribute('tabindex');+ });++ it('accepts standard container sizing props on the viewport', () => {+ render(+ <ScrollableArea+ label="Messages"+ width={320}+ height="50vh"+ maxWidth="100%"+ minHeight={120}+ data-testid="viewport">+ Messages+ </ScrollableArea>,+ );++ expect(screen.getByTestId('viewport')).toBeInTheDocument();+ expect(stylesSource()).toContain('dynamicStyles.sizing(');+ });++ it('publishes content padding without changing the viewport default', () => {+ const {rerender} = render(+ <ScrollableArea label="Messages" data-testid="viewport">+ Messages+ </ScrollableArea>,+ );+ const viewport = screen.getByTestId('viewport');+ const content = viewport.firstElementChild as HTMLElement;+ const defaultViewportClass = viewport.className;+ const defaultContentClass = content.className;++ rerender(+ <ScrollableArea+ label="Messages"+ padding={4}+ paddingInlineEnd={2}+ data-testid="viewport">+ Messages+ </ScrollableArea>,+ );++ expect(viewport.className).toBe(defaultViewportClass);+ expect(content.className).not.toBe(defaultContentClass);+ const source = stylesSource();+ expect(source).toContain('containerPaddingInlineVarStyles[padding]');+ expect(source).toContain(+ 'containerPaddingInlineEndVarStyles[paddingInlineEnd]',+ );+ });++ it('keeps inherited container bleed opt-in on the viewport', () => {+ const {rerender} = render(+ <ScrollableArea label="Messages" data-testid="viewport">+ Messages+ </ScrollableArea>,+ );+ const viewport = screen.getByTestId('viewport');+ const containedClass = viewport.className;++ rerender(+ <ScrollableArea label="Messages" isFullBleed data-testid="viewport">+ Messages+ </ScrollableArea>,+ );++ expect(viewport.className).not.toBe(containedClass);+ const source = stylesSource();+ expect(source).toContain('var(--container-padding-inline-start, 0px)');+ expect(source).toContain('isFullBleed && styles.fullBleed');+ });++ it('uses the neutral token for native scrollbar color with a transparent track', () => {+ const source = stylesSource();+ expect(source).toContain("colorVars['--color-neutral']");+ expect(source).toContain('transparent');+ expect(source).toContain("'@media (forced-colors: active)': 'auto'");+ });++ it('guards scroll-state query containment as a progressive enhancement', () => {+ const source = stylesSource();+ expect(source).toContain("'@supports (container-type: scroll-state)'");+ expect(source).toContain("'scroll-state'");+ });+});++function hookSource(): string {+ return readFileSync('packages/core/src/hooks/useScrollableArea.ts', 'utf8');+}++function stylesSource(): string {+ // This focused source assertion complements the built-CSS browser probe: it+ // keeps the capability guard and token reference reviewable at unit-test speed.+ return readFileSync(+ 'packages/core/src/ScrollableArea/ScrollableArea.tsx',+ 'utf8',+ );+}diff --git a/packages/core/src/ScrollableArea/ScrollableArea.tsx b/packages/core/src/ScrollableArea/ScrollableArea.tsxnew file mode 100644index 0000000000..738c76f194--- /dev/null+++ b/packages/core/src/ScrollableArea/ScrollableArea.tsx@@ -0,0 +1,259 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file ScrollableArea.tsx+ * @input Logical scroll intent, accessible name, overscroll policy, viewport sizing, content padding, and content+ * @output Native scroll viewport with an observed real content box+ * @position Reference composition over useScrollableArea+ *+ * SYNC: When modified, update:+ * - /packages/core/src/ScrollableArea/ScrollableArea.test.tsx+ * - /packages/core/src/ScrollableArea/ScrollableArea.doc.mjs+ * - /apps/storybook/stories/ScrollableArea.stories.tsx+ */++import type {ReactNode} from 'react';+import * as stylex from '@stylexjs/stylex';+import type {BaseProps} from '../BaseProps';+import {+ paddingStyles,+ paddingInlineStyles,+ paddingInlineStartStyles,+ paddingInlineEndStyles,+ paddingBlockStyles,+ paddingBlockStartStyles,+ paddingBlockEndStyles,+ containerPaddingInlineVarStyles,+ containerPaddingInlineStartVarStyles,+ containerPaddingInlineEndVarStyles,+ containerPaddingBlockStartVarStyles,+ containerPaddingBlockEndVarStyles,+} from '../Layout/padding.stylex';+import type {SizeValue, SpacingStep} from '../utils/types';+import {+ useScrollableArea,+ type ScrollAxis,+ type ScrollOverscroll,+ type ScrollStickyContainment,+} from '../hooks/useScrollableArea';+import {colorVars} from '../theme/tokens.stylex';+import {focusOutlineStyles} from '../utils/focusOutline.stylex';+import {mergeProps} from '../utils/mergeProps';+import {themeProps} from '../utils/themeProps';++const styles = stylex.create({+ viewport: {+ boxSizing: 'border-box',+ maxInlineSize: '100%',+ maxBlockSize: '100%',+ WebkitOverflowScrolling: 'touch',+ scrollbarColor: {+ default: `${colorVars['--color-neutral']} transparent`,+ '@media (forced-colors: active)': 'auto',+ },+ scrollbarWidth: 'auto',+ scrollbarGutter: 'auto',+ // Chromium can resolve CSS-only stuck/edge presentation for descendants.+ // Unsupported engines keep the hook state as the behavior source of truth.+ containerType: {+ default: null,+ '@supports (container-type: scroll-state)': 'scroll-state',+ },+ },+ fullBleed: {+ marginInlineStart: 'calc(-1 * var(--container-padding-inline-start, 0px))',+ marginInlineEnd: 'calc(-1 * var(--container-padding-inline-end, 0px))',+ maxInlineSize:+ 'calc(100% + var(--container-padding-inline-start, 0px) + var(--container-padding-inline-end, 0px))',+ marginBlockStart: {+ default: null,+ ':first-child': 'calc(-1 * var(--container-padding-block-start, 0px))',+ },+ marginBlockEnd: {+ default: null,+ ':last-child': 'calc(-1 * var(--container-padding-block-end, 0px))',+ },+ },+ content: {+ boxSizing: 'border-box',+ minInlineSize: '100%',+ minBlockSize: '100%',+ },+ contentWithInlineOverflow: {+ inlineSize: 'max-content',+ },+});++const dynamicStyles = stylex.create({+ sizing: (+ width: SizeValue | null,+ height: SizeValue | null,+ maxWidth: SizeValue | null,+ minHeight: SizeValue | null,+ ) => ({width, height, maxWidth, minHeight}),+});++export type ScrollableAreaStickyContainment = ScrollStickyContainment;++export interface ScrollableAreaProps extends Omit<+ BaseProps<HTMLDivElement>,+ 'aria-label' | 'children' | 'role' | 'tabIndex'+> {+ /** Content rendered inside the observed content box. */+ children?: ReactNode;+ /** Logical axis or axes where scrolling is allowed. @default 'block' */+ axis?: ScrollAxis;+ /** Accessible name used when an effective viewport enters the tab order. */+ label: string;+ /** Semantics for the named scroll viewport. @default 'group' */+ role?: 'group' | 'region';+ /** Whether effective axes pass scroll gestures to ancestors at an edge. @default 'allow' */+ overscroll?: ScrollOverscroll;+ /** Width of the viewport; numbers are interpreted as pixels. */+ width?: SizeValue;+ /** Height of the viewport; numbers are interpreted as pixels. */+ height?: SizeValue;+ /** Maximum width of the viewport. */+ maxWidth?: SizeValue;+ /** Minimum height of the viewport. */+ minHeight?: SizeValue;+ /** Whether a fitting viewport deliberately remains a Sticky containing boundary. @default 'whenScrollable' */+ stickyContainment?: ScrollableAreaStickyContainment;+ /** Content padding using the shared spacing scale. @default 0 */+ padding?: SpacingStep;+ /** Logical inline-axis content padding; overrides `padding` on that axis. */+ paddingInline?: SpacingStep;+ /** Logical inline-start content padding; overrides broader padding values. */+ paddingInlineStart?: SpacingStep;+ /** Logical inline-end content padding; overrides broader padding values. */+ paddingInlineEnd?: SpacingStep;+ /** Logical block-axis content padding; overrides `padding` on that axis. */+ paddingBlock?: SpacingStep;+ /** Logical block-start content padding; overrides broader padding values. */+ paddingBlockStart?: SpacingStep;+ /** Logical block-end content padding; overrides broader padding values. */+ paddingBlockEnd?: SpacingStep;+ /** Let the viewport escape inherited container padding. @default false */+ isFullBleed?: boolean;+ /** Ref connected to the native scroll viewport. */+ ref?: React.Ref<HTMLDivElement>;+}++/**+ * A native scroll viewport with axis-aware accessibility and chaining.+ *+ * The root is the viewport. Its single child is a normal block content box with+ * a 100% minimum size; children participate in that box rather than directly in+ * viewport flex/grid layout. Inline scrolling gives the box max-content inline+ * sizing, and its minimum block size deliberately does not create a definite+ * percentage-height basis. Use the hook on owned structure when those formatting+ * semantics must stay unchanged. Native scrolling and platform scrollbars remain+ * authoritative.+ *+ * @example+ * ```+ * <ScrollableArea axis="block" label="Activity history">+ * <ActivityList />+ * </ScrollableArea>+ * ```+ */+export function ScrollableArea({+ children,+ axis = 'block',+ label,+ role = 'group',+ overscroll = 'allow',+ width,+ height,+ maxWidth,+ minHeight,+ stickyContainment = 'whenScrollable',+ padding = 0,+ paddingInline,+ paddingInlineStart,+ paddingInlineEnd,+ paddingBlock,+ paddingBlockStart,+ paddingBlockEnd,+ isFullBleed = false,+ ref,+ xstyle,+ className,+ style,+ ...props+}: ScrollableAreaProps) {+ const {getViewportProps, getContentProps} = useScrollableArea({+ axis,+ keyboardAccess: {owner: 'viewport', label, role},+ overscroll,+ stickyContainment,+ });++ const mergedViewportProps = mergeProps(+ themeProps('scrollable-area', {axis}),+ stylex.props(+ styles.viewport,+ isFullBleed && styles.fullBleed,+ focusOutlineStyles.focusVisible,+ dynamicStyles.sizing(+ width ?? null,+ height ?? null,+ maxWidth ?? null,+ minHeight ?? null,+ ),+ xstyle,+ ),+ className,+ style,+ );+ const viewportProps = getViewportProps<HTMLDivElement>({+ ...props,+ ref,+ ...mergedViewportProps,+ });++ return (+ <div {...viewportProps}>+ <div+ {...getContentProps<HTMLDivElement>({+ ...stylex.props(+ styles.content,+ axis !== 'block' && styles.contentWithInlineOverflow,+ paddingStyles[padding],+ containerPaddingInlineVarStyles[padding],+ containerPaddingBlockStartVarStyles[padding],+ containerPaddingBlockEndVarStyles[padding],+ paddingInline != null && paddingInlineStyles[paddingInline],+ paddingInline != null &&+ containerPaddingInlineVarStyles[paddingInline],+ paddingBlock != null && paddingBlockStyles[paddingBlock],+ paddingBlock != null &&+ containerPaddingBlockStartVarStyles[paddingBlock],+ paddingBlock != null &&+ containerPaddingBlockEndVarStyles[paddingBlock],+ paddingInlineStart != null &&+ paddingInlineStartStyles[paddingInlineStart],+ paddingInlineStart != null &&+ containerPaddingInlineStartVarStyles[paddingInlineStart],+ paddingInlineEnd != null &&+ paddingInlineEndStyles[paddingInlineEnd],+ paddingInlineEnd != null &&+ containerPaddingInlineEndVarStyles[paddingInlineEnd],+ paddingBlockStart != null &&+ paddingBlockStartStyles[paddingBlockStart],+ paddingBlockStart != null &&+ containerPaddingBlockStartVarStyles[paddingBlockStart],+ paddingBlockEnd != null && paddingBlockEndStyles[paddingBlockEnd],+ paddingBlockEnd != null &&+ containerPaddingBlockEndVarStyles[paddingBlockEnd],+ ),+ })}>+ {children}+ </div>+ </div>+ );+}++ScrollableArea.displayName = 'ScrollableArea';diff --git a/packages/core/src/ScrollableArea/index.ts b/packages/core/src/ScrollableArea/index.tsnew file mode 100644index 0000000000..9945871eda--- /dev/null+++ b/packages/core/src/ScrollableArea/index.ts@@ -0,0 +1,26 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file index.ts+ * @input ScrollableArea implementation and shared hook types+ * @output Public ScrollableArea package surface+ * @position Package entry point for ScrollableArea+ */++export {ScrollableArea} from './ScrollableArea';+export type {+ ScrollableAreaProps,+ ScrollableAreaStickyContainment,+} from './ScrollableArea';+export {useScrollableArea} from '../hooks/useScrollableArea';+export type {+ ScrollAxis,+ ScrollAxisState,+ ScrollOverscroll,+ ScrollStickyContainment,+ ScrollKeyboardAccess,+ ScrollableAreaState,+ ScrollableElementProps,+ UseScrollableAreaOptions,+ UseScrollableAreaResult,+} from '../hooks/useScrollableArea';diff --git a/packages/core/src/ScrollableArea/modules/useScrollableArea.spec.md b/packages/core/src/ScrollableArea/modules/useScrollableArea.spec.mdnew file mode 100644index 0000000000..bd15e9f8aa--- /dev/null+++ b/packages/core/src/ScrollableArea/modules/useScrollableArea.spec.md@@ -0,0 +1,121 @@+---+schema_version: 3+template_version: 1+kind: module+id: module:ScrollableArea/useScrollableArea+authority: current+archive_reason: null+superseded_by: null+approved_by: cixzhang+approved_at: 2026-09-11+owners: [cixzhang]+review_triggers: [public-api, behavior, accessibility]+verified_by: [packages/core/src/hooks/useScrollableArea.test.tsx]+parent_component: component:ScrollableArea+references: [architecture:public-component-api, spec:AST-025/DEC-1]+---++# useScrollableArea module contract++## Intent++useScrollableArea is the canonical reusable behavior core for components that+already own a viewport and content root. It provides safe prop/ref composition,+logical-axis measurement, live owner registration, edge state, keyboard access,+and scroll chaining without inserting structure.++## Compatibility and migration++- Released default preserved: not yet released+- Compatibility class: additive public hook and types+- Migration decision: `spec:AST-025/DEC-1`++## Ownership boundary++**Owns**++- Effective-axis measurement and stable logical-edge state.+- Observation, invalidation, DOM owner registration, conditional viewport access,+ and effective-axis chaining.+- Safe composition of caller viewport/content props and refs.++**Does not own / non-goals**++- Viewport layout, paint, overflow declarations, scrollbar presentation, or+ insertion of a content wrapper.+- Sticky positioning and public owner lookup.++## 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 |++## 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 |++### Transformation and precedence order++- **ORD1 — Effective state.** requested logical axis → computed physical axis →+ scroll-capable overflow → geometry tolerance → normalized logical edge.+- **ORD2 — Prop composition.** caller props and `xstyle` → behavior-owned+ fitting/active overflow style → stable composed ref → behavior-owned keyboard,+ state, and chaining outputs.++### Performance and resources++- **PR1 — Stable publication.** Equal effective/edge state reuses the prior object.+- **PR2 — Shared observation.** Both element boxes use the shared ResizeObserver;+ all secondary invalidation signals coalesce through one animation frame.++## 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.++## Design relationships++No visual representation is owned by this hook.++## Parent and system relationships++- `component:ScrollableArea` owns the reference viewport/content composition.+- `spec:AST-025` owns the shared behavior and adoption boundary.++## 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 |++## Decision log++### DEC-1 — Prop getters are the public composition seam++**Reference:** `module:ScrollableArea/useScrollableArea/DEC-1`+**Decider:** cixzhang, 2026-09-11++One returned prop object per owned element keeps refs, accessibility, handlers,+and behavior together without making consumer spread order part of correctness.++## Open questions++None.++## Content boundary++This file does not duplicate consumer signatures/examples, ScrollableArea's+structure/presentation, or Sticky's future API and positioning mechanism.diff --git a/packages/core/src/hooks/index.ts b/packages/core/src/hooks/index.tsindex 854886c307..6f2bcf51b1 100644--- a/packages/core/src/hooks/index.ts+++ b/packages/core/src/hooks/index.ts@@ -56,6 +56,19 @@ export type {UseOverflowOptions, UseOverflowReturn} from './useOverflow';export {useScrollOverflow} from './useScrollOverflow';export type {ScrollOverflowState} from './useScrollOverflow';+export {useScrollableArea} from './useScrollableArea';+export type {+ ScrollAxis,+ ScrollAxisState,+ ScrollOverscroll,+ ScrollStickyContainment,+ ScrollKeyboardAccess,+ ScrollableAreaState,+ ScrollableElementProps,+ UseScrollableAreaOptions,+ UseScrollableAreaResult,+} from './useScrollableArea';+export {useScrollLock} from './useScrollLock';export {useEntryAnimation} from './useEntryAnimation';diff --git a/packages/core/src/hooks/scrollGeometry.ts b/packages/core/src/hooks/scrollGeometry.tsnew file mode 100644index 0000000000..724f73a6e0--- /dev/null+++ b/packages/core/src/hooks/scrollGeometry.ts@@ -0,0 +1,155 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** Shared geometry primitives for logical-axis scroll ownership. */++export const SCROLL_OVERFLOW_TOLERANCE = 1;++export type LogicalScrollAxis = 'inline' | 'block';+export type PhysicalScrollAxis = 'x' | 'y';++export interface LogicalAxisMapping {+ inline: PhysicalScrollAxis;+ block: PhysicalScrollAxis;+ inlineReversed: boolean;+ blockReversed: boolean;+}++export interface MeasuredScrollAxisState {+ isScrollable: boolean;+ atStart: boolean;+ atEnd: boolean;+}++export interface LogicalOverflowGeometry {+ inline: boolean;+ block: boolean;+}++const INACTIVE_AXIS_STATE: MeasuredScrollAxisState = {+ isScrollable: false,+ atStart: true,+ atEnd: true,+};++export function getLogicalAxisMapping(+ writingMode: string,+ direction: string,+): LogicalAxisMapping {+ const mode = writingMode.toLowerCase();+ const isVertical = mode.startsWith('vertical') || mode.startsWith('sideways');+ const isRtl = direction === 'rtl';++ if (!isVertical) {+ return {+ inline: 'x',+ block: 'y',+ inlineReversed: isRtl,+ blockReversed: false,+ };+ }++ // sideways-lr runs its natural inline direction from bottom to top. The+ // other vertical/sideways modes run top to bottom; `direction` reverses each.+ const inlineReversed = mode === 'sideways-lr' ? !isRtl : isRtl;+ const blockReversed = mode.endsWith('-rl');++ return {+ inline: 'y',+ block: 'x',+ inlineReversed,+ blockReversed,+ };+}++export function isScrollCapableOverflow(value: string): boolean {+ return value === 'auto' || value === 'scroll' || value === 'overlay';+}++function physicalMetrics(+ element: HTMLElement,+ physicalAxis: PhysicalScrollAxis,+): {+ clientExtent: number;+ contentExtent: number;+ offset: number;+ overflow: string;+} {+ const computedStyle = getComputedStyle(element);+ if (physicalAxis === 'x') {+ return {+ clientExtent: element.clientWidth,+ contentExtent: element.scrollWidth,+ offset: element.scrollLeft,+ overflow: computedStyle.overflowX,+ };+ }+ return {+ clientExtent: element.clientHeight,+ contentExtent: element.scrollHeight,+ offset: element.scrollTop,+ overflow: computedStyle.overflowY,+ };+}++function isMeasurable(+ element: HTMLElement,+ computedStyle: CSSStyleDeclaration,+) {+ return (+ element.isConnected &&+ computedStyle.display !== 'none' &&+ element.clientWidth > 0 &&+ element.clientHeight > 0+ );+}++export function measureLogicalOverflowGeometry(+ element: HTMLElement,+ logicalAxis: LogicalScrollAxis,+ mapping: LogicalAxisMapping,+): boolean | null {+ const computedStyle = getComputedStyle(element);+ if (!isMeasurable(element, computedStyle)) {+ return null;+ }++ const physicalAxis = mapping[logicalAxis];+ const clientExtent =+ physicalAxis === 'x' ? element.clientWidth : element.clientHeight;+ const contentExtent =+ physicalAxis === 'x' ? element.scrollWidth : element.scrollHeight;+ return contentExtent - clientExtent > SCROLL_OVERFLOW_TOLERANCE;+}++export function measureLogicalScrollAxis(+ element: HTMLElement,+ logicalAxis: LogicalScrollAxis,+ mapping: LogicalAxisMapping,+): MeasuredScrollAxisState | null {+ const computedStyle = getComputedStyle(element);+ if (!isMeasurable(element, computedStyle)) {+ return null;+ }++ const physicalAxis = mapping[logicalAxis];+ const metrics = physicalMetrics(element, physicalAxis);+ const maxOffset = metrics.contentExtent - metrics.clientExtent;+ if (+ !isScrollCapableOverflow(metrics.overflow) ||+ maxOffset <= SCROLL_OVERFLOW_TOLERANCE+ ) {+ return INACTIVE_AXIS_STATE;+ }++ const isReversed = mapping[`${logicalAxis}Reversed`];+ const logicalOffset = Math.min(+ maxOffset,+ Math.max(0, isReversed ? Math.abs(metrics.offset) : metrics.offset),+ );++ return {+ isScrollable: true,+ atStart: logicalOffset <= SCROLL_OVERFLOW_TOLERANCE,+ atEnd: logicalOffset >= maxOffset - SCROLL_OVERFLOW_TOLERANCE,+ };+}diff --git a/packages/core/src/hooks/scrollOwnerRegistry.ts b/packages/core/src/hooks/scrollOwnerRegistry.tsnew file mode 100644index 0000000000..831116701c--- /dev/null+++ b/packages/core/src/hooks/scrollOwnerRegistry.ts@@ -0,0 +1,47 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** Private DOM registry used by future axis-aware Sticky consumers. */++export interface RegisteredScrollAxisState {+ isScrollable: boolean;+ atStart: boolean;+ atEnd: boolean;+}++export interface RegisteredScrollOwnerState {+ inline: RegisteredScrollAxisState;+ block: RegisteredScrollAxisState;+}++const owners = new WeakMap<HTMLElement, RegisteredScrollOwnerState>();++export function registerScrollOwner(+ element: HTMLElement,+ state: RegisteredScrollOwnerState,+): void {+ owners.set(element, state);+}++export function unregisterScrollOwner(element: HTMLElement): void {+ owners.delete(element);+}++export function getRegisteredScrollOwnerState(+ element: HTMLElement,+): RegisteredScrollOwnerState | undefined {+ return owners.get(element);+}++export function findNearestScrollOwner(+ element: Element,+ axis: 'inline' | 'block',+): HTMLElement | null {+ let candidate = element.parentElement;+ while (candidate != null) {+ if (owners.get(candidate)?.[axis].isScrollable === true) {+ return candidate;+ }+ candidate = candidate.parentElement;+ }+ return null;+}diff --git a/packages/core/src/hooks/useScrollableArea.doc.mjs b/packages/core/src/hooks/useScrollableArea.doc.mjsnew file mode 100644index 0000000000..ba0b9cdcb8--- /dev/null+++ b/packages/core/src/hooks/useScrollableArea.doc.mjs@@ -0,0 +1,108 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').HookDoc} */+export const docs = {+ name: 'useScrollableArea',+ displayName: 'useScrollableArea',+ keywords: [+ 'scroll',+ 'overflow',+ 'logical axis',+ 'keyboard',+ 'overscroll',+ 'sticky',+ 'resize',+ ],+ params: [+ {+ name: 'options',+ type: 'UseScrollableAreaOptions',+ description:+ 'Logical scroll intent, keyboard owner, overscroll policy, and fitting Sticky containment.',+ required: true,+ },+ ],+ returns: [+ {+ name: 'getViewportProps',+ type: '<E extends HTMLElement>(props?: ScrollableElementProps<E>) => ScrollableElementProps<E>',+ description:+ 'Consumes caller viewport props, xstyle, and refs; composes fitting/active overflow, Sticky containment, accessibility, chaining, and owner registration.',+ },+ {+ name: 'getContentProps',+ type: '<E extends HTMLElement>(props?: ScrollableElementProps<E>) => ScrollableElementProps<E>',+ description:+ 'Composes caller content-box props and refs with content observation.',+ },+ {+ name: 'state',+ type: 'ScrollableAreaState',+ description:+ 'Stable inline and block effective-scroll and logical-edge state.',+ },+ ],+ usage: {+ description:+ 'Adds canonical axis-aware scroll behavior to structure owned by the caller. An axis is effective only when its computed overflow is scroll-capable and geometry exceeds the shared 1px tolerance. Both viewport and content boxes are observed.',+ bestPractices: [+ {+ guidance: true,+ description:+ 'Pass already-resolved props and refs through both prop getters, then spread each returned object once.',+ },+ {+ guidance: true,+ description:+ 'Use viewport keyboard ownership only when the viewport itself should enter the tab order; provide a concise accessible label.',+ },+ {+ guidance: true,+ description:+ 'Use content keyboard ownership when an existing focusable descendant gives keyboard users access to all overflowed content.',+ },+ {+ guidance: true,+ description:+ 'Pass caller `xstyle` through `getViewportProps`; the getter composes it with fitting clip, active overflow, and Sticky containment.',+ },+ {+ guidance: false,+ description:+ 'Attach only the viewport getter. A real observed content box is required for live overflow changes.',+ },+ ],+ },+ relatedComponents: ['ScrollableArea'],+ relatedHooks: ['useScrollOverflow'],+ importPath: '@astryxdesign/core/hooks',+ category: 'layout',+};++/** @type {import('@astryxdesign/cli/authoring').HookTranslationDoc} */+export const docsDense = {+ description:+ '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.',+ },+ returnDescriptions: {+ getViewportProps:+ 'safe viewport prop/ref/xstyle composition with behavior-owned overflow, accessibility, and chaining.',+ getContentProps: 'safe observed content-box prop/ref composition.',+ state: 'inline/block isScrollable, atStart, and atEnd state.',+ },+ usage: {+ description:+ 'Use for existing structures that need ScrollableArea behavior without another wrapper.',+ bestPractices: [+ {+ guidance: true,+ description:+ 'Spread each prop getter result once on its owner element.',+ },+ {guidance: false, description: 'Skip the real content-box getter.'},+ ],+ },+};diff --git a/packages/core/src/hooks/useScrollableArea.test.tsx b/packages/core/src/hooks/useScrollableArea.test.tsxnew file mode 100644index 0000000000..1b16a4bf1a--- /dev/null+++ b/packages/core/src/hooks/useScrollableArea.test.tsx@@ -0,0 +1,437 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {act, render, screen} from '@testing-library/react';+import * as stylex from '@stylexjs/stylex';+import {useRef, type Ref} from 'react';+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';+import {+ useScrollableArea,+ type ScrollAxis,+ type ScrollOverscroll,+ type ScrollStickyContainment,+} from './useScrollableArea';+import {+ findNearestScrollOwner,+ getRegisteredScrollOwnerState,+} from './scrollOwnerRegistry';+import {getLogicalAxisMapping} from './scrollGeometry';++const testStyles = stylex.create({+ viewport: {borderWidth: 1, borderStyle: 'solid'},+});++interface FixtureProps {+ axis?: ScrollAxis;+ chaining?: ScrollOverscroll;+ stickyContainment?: ScrollStickyContainment;+ externalRef?: Ref<HTMLDivElement>;+ onScroll?: React.UIEventHandler<HTMLDivElement>;+}++function Fixture({+ axis = 'inline',+ chaining = 'allow',+ stickyContainment,+ externalRef,+ onScroll,+}: FixtureProps) {+ const {getViewportProps, getContentProps, state} = useScrollableArea({+ axis,+ keyboardAccess: {+ owner: 'viewport',+ label: 'Scrollable results',+ role: 'region',+ },+ overscroll: chaining,+ stickyContainment,+ });++ return (+ <>+ <div+ data-testid="viewport"+ {...getViewportProps({+ ref: externalRef,+ onScroll,+ xstyle: testStyles.viewport,+ style: {backgroundColor: 'red', overflowX: 'scroll'},+ })}>+ <div data-testid="content" {...getContentProps()}>+ <span data-testid="descendant">Content</span>+ </div>+ </div>+ <output data-testid="state">{JSON.stringify(state)}</output>+ </>+ );+}++function setGeometry(+ element: HTMLElement,+ values: Partial<+ Pick<+ HTMLElement,+ | 'clientWidth'+ | 'clientHeight'+ | 'scrollWidth'+ | 'scrollHeight'+ | 'scrollLeft'+ | 'scrollTop'+ >+ >,+) {+ for (const [key, value] of Object.entries(values)) {+ Object.defineProperty(element, key, {+ configurable: true,+ value,+ writable: true,+ });+ }+}++function state(): {+ inline: {isScrollable: boolean; atStart: boolean; atEnd: boolean};+ block: {isScrollable: boolean; atStart: boolean; atEnd: boolean};+} {+ return JSON.parse(screen.getByTestId('state').textContent ?? '{}');+}++function makeMeasurable(viewport: HTMLElement) {+ setGeometry(viewport, {+ clientWidth: 100,+ clientHeight: 100,+ scrollWidth: 100,+ scrollHeight: 100,+ scrollLeft: 0,+ scrollTop: 0,+ });+}++describe('useScrollableArea', () => {+ let frames: FrameRequestCallback[];++ beforeEach(() => {+ frames = [];+ vi.stubGlobal(+ 'requestAnimationFrame',+ vi.fn((callback: FrameRequestCallback) => {+ frames.push(callback);+ return frames.length;+ }),+ );+ vi.stubGlobal('cancelAnimationFrame', vi.fn());+ vi.stubGlobal(+ 'ResizeObserver',+ vi.fn(function () {+ return {observe: vi.fn(), unobserve: vi.fn(), disconnect: vi.fn()};+ }),+ );+ const nativeGetComputedStyle = window.getComputedStyle.bind(window);+ vi.spyOn(window, 'getComputedStyle').mockImplementation(element => {+ const computed = nativeGetComputedStyle(element);+ return new Proxy(computed, {+ // eslint-disable-next-line @typescript-eslint/promise-function-async -- Proxy traps must remain synchronous+ get(target, property) {+ if (element instanceof HTMLElement && property === 'overflowX') {+ return element.style.overflowX || 'auto';+ }+ if (element instanceof HTMLElement && property === 'overflowY') {+ return element.style.overflowY || 'auto';+ }+ return Reflect.get(target, property, target);+ },+ });+ });+ });++ afterEach(() => {+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+ });++ function flushFrame() {+ void act(() => {+ const pending = frames.splice(0);+ pending.forEach(callback => callback(performance.now()));+ });+ }++ it('starts inactive and fitting without creating a tab stop', () => {+ render(<Fixture />);+ const viewport = screen.getByTestId('viewport');++ expect(state()).toEqual({+ inline: {isScrollable: false, atStart: true, atEnd: true},+ block: {isScrollable: false, atStart: true, atEnd: true},+ });+ expect(viewport).not.toHaveAttribute('tabindex');+ expect(viewport).toHaveAttribute('role', 'region');+ expect(viewport).toHaveAccessibleName('Scrollable results');+ expect(viewport).not.toHaveAttribute('xstyle');+ expect(viewport.style.backgroundColor).toBe('red');+ expect(viewport.style.overflowX).toBe('');+ expect(viewport.getAttribute('style')).toContain('clip');+ });++ it('owns fitting and explicit Sticky overflow styling for direct adopters', () => {+ const {rerender} = render(<Fixture />);+ const viewport = screen.getByTestId('viewport');+ expect(viewport.getAttribute('style')).toContain('clip');++ rerender(<Fixture stickyContainment="always" />);+ expect(viewport.getAttribute('style')).toContain('auto');+ expect(viewport.getAttribute('style')).toContain('hidden');+ });++ it('activates only the overflowing physical axis when both are requested', () => {+ render(<Fixture axis="both" />);+ const viewport = screen.getByTestId('viewport');+ makeMeasurable(viewport);+ setGeometry(viewport, {scrollWidth: 180});++ void act(() => viewport.dispatchEvent(new Event('scroll')));+ flushFrame();+ expect(viewport.getAttribute('style')).toContain('--x-overflowX: auto');+ expect(viewport.getAttribute('style')).toContain('--x-overflowY: hidden');+ });++ it('requires scroll-capable computed overflow and more than 1px excess geometry', () => {+ render(<Fixture />);+ const viewport = screen.getByTestId('viewport');+ makeMeasurable(viewport);++ setGeometry(viewport, {scrollWidth: 101});+ void act(() => viewport.dispatchEvent(new Event('scroll')));+ flushFrame();+ expect(state().inline.isScrollable).toBe(false);++ viewport.style.overflowX = 'hidden';+ setGeometry(viewport, {scrollWidth: 140});+ void act(() => viewport.dispatchEvent(new Event('scroll')));+ flushFrame();+ expect(state().inline.isScrollable).toBe(false);++ viewport.style.overflowX = 'auto';+ void act(() => viewport.dispatchEvent(new Event('scroll')));+ flushFrame();+ expect(state().inline).toEqual({+ isScrollable: true,+ atStart: true,+ atEnd: false,+ });+ expect(viewport).toHaveAttribute('tabindex', '0');+ });++ it('publishes stable logical start, middle, and end edge state', () => {+ render(<Fixture />);+ const viewport = screen.getByTestId('viewport');+ makeMeasurable(viewport);+ setGeometry(viewport, {scrollWidth: 300});++ void act(() => viewport.dispatchEvent(new Event('scroll')));+ flushFrame();+ expect(state().inline).toEqual({+ isScrollable: true,+ atStart: true,+ atEnd: false,+ });++ setGeometry(viewport, {scrollLeft: 80});+ void act(() => viewport.dispatchEvent(new Event('scroll')));+ flushFrame();+ expect(state().inline).toEqual({+ isScrollable: true,+ atStart: false,+ atEnd: false,+ });++ setGeometry(viewport, {scrollLeft: 200});+ void act(() => viewport.dispatchEvent(new Event('scroll')));+ flushFrame();+ expect(state().inline).toEqual({+ isScrollable: true,+ atStart: false,+ atEnd: true,+ });+ });++ it('normalizes RTL inline offsets to logical edges', () => {+ render(<Fixture />);+ const viewport = screen.getByTestId('viewport');+ makeMeasurable(viewport);+ viewport.dir = 'rtl';+ setGeometry(viewport, {scrollWidth: 300, scrollLeft: -200});++ void act(() => viewport.dispatchEvent(new Event('scroll')));+ flushFrame();+ expect(state().inline).toEqual({+ isScrollable: true,+ atStart: false,+ atEnd: true,+ });+ });++ it('maps logical axes through vertical and sideways writing modes', () => {+ expect(getLogicalAxisMapping('vertical-rl', 'ltr')).toEqual({+ inline: 'y',+ block: 'x',+ inlineReversed: false,+ blockReversed: true,+ });+ expect(getLogicalAxisMapping('vertical-lr', 'rtl')).toEqual({+ inline: 'y',+ block: 'x',+ inlineReversed: true,+ blockReversed: false,+ });+ expect(getLogicalAxisMapping('sideways-lr', 'ltr')).toEqual({+ inline: 'y',+ block: 'x',+ inlineReversed: true,+ blockReversed: false,+ });+ });++ it('measures both requested axes independently in vertical writing mode', () => {+ render(<Fixture axis="both" />);+ const viewport = screen.getByTestId('viewport');+ makeMeasurable(viewport);+ viewport.style.writingMode = 'vertical-rl';+ setGeometry(viewport, {+ scrollWidth: 220,+ scrollHeight: 100,+ scrollLeft: -120,+ });++ void act(() => viewport.dispatchEvent(new Event('scroll')));+ flushFrame();+ expect(state()).toEqual({+ inline: {isScrollable: false, atStart: true, atEnd: true},+ block: {isScrollable: true, atStart: false, atEnd: true},+ });+ });++ it('contains only effective physical axes', () => {+ render(<Fixture axis="both" chaining="contain" />);+ const viewport = screen.getByTestId('viewport');+ makeMeasurable(viewport);+ setGeometry(viewport, {scrollWidth: 180, scrollHeight: 100});++ void act(() => viewport.dispatchEvent(new Event('scroll')));+ flushFrame();+ expect(viewport.style.overscrollBehaviorX).toBe('contain');+ expect(viewport.style.overscrollBehaviorY).toBe('auto');+ });++ it('preserves caller overscroll behavior on axes outside the requested intent', () => {+ function InlineOnly() {+ const area = useScrollableArea({+ axis: 'inline',+ keyboardAccess: {owner: 'content'},+ overscroll: 'contain',+ });+ return (+ <div+ data-testid="inline-only"+ {...area.getViewportProps({+ style: {overflowX: 'auto', overscrollBehaviorY: 'none'},+ })}>+ <div {...area.getContentProps()}>Content</div>+ </div>+ );+ }++ render(<InlineOnly />);+ const viewport = screen.getByTestId('inline-only');+ expect(viewport.style.overscrollBehaviorX).toBe('auto');+ expect(viewport.style.overscrollBehaviorY).toBe('none');+ });++ it('removes a lost tab stop without moving current focus', () => {+ render(<Fixture />);+ const viewport = screen.getByTestId('viewport');+ makeMeasurable(viewport);+ setGeometry(viewport, {scrollWidth: 180});+ void act(() => viewport.dispatchEvent(new Event('scroll')));+ flushFrame();++ viewport.focus();+ expect(document.activeElement).toBe(viewport);+ setGeometry(viewport, {scrollWidth: 100});+ void act(() => viewport.dispatchEvent(new Event('scroll')));+ flushFrame();++ expect(viewport).toHaveAttribute('tabindex', '-1');+ expect(document.activeElement).toBe(viewport);+ });++ it('composes caller refs and handlers without losing behavior', () => {+ const externalRef = vi.fn();+ const onScroll = vi.fn();+ const {rerender} = render(+ <Fixture externalRef={externalRef} onScroll={onScroll} />,+ );+ const viewport = screen.getByTestId('viewport');+ makeMeasurable(viewport);+ setGeometry(viewport, {scrollWidth: 180});++ void act(() =>+ viewport.dispatchEvent(new Event('scroll', {bubbles: true})),+ );+ flushFrame();+ expect(onScroll).toHaveBeenCalledTimes(1);+ expect(externalRef).toHaveBeenCalledWith(viewport);+ expect(state().inline.isScrollable).toBe(true);++ externalRef.mockClear();+ rerender(<Fixture externalRef={externalRef} onScroll={onScroll} />);+ expect(externalRef).not.toHaveBeenCalled();+ });++ it('registers effective owners by axis and skips inactive nested candidates', () => {+ function NestedFixture() {+ const outer = useScrollableArea({+ axis: 'block',+ keyboardAccess: {owner: 'content'},+ });+ const inner = useScrollableArea({+ axis: 'inline',+ keyboardAccess: {owner: 'content'},+ });+ const descendantRef = useRef<HTMLSpanElement>(null);+ return (+ <div+ data-testid="outer"+ {...outer.getViewportProps({style: {overflowY: 'auto'}})}>+ <div {...outer.getContentProps()}>+ <div+ data-testid="inner"+ {...inner.getViewportProps({style: {overflowX: 'auto'}})}>+ <div {...inner.getContentProps()}>+ <span ref={descendantRef} data-testid="nested-descendant" />+ </div>+ </div>+ </div>+ </div>+ );+ }++ render(<NestedFixture />);+ const outer = screen.getByTestId('outer');+ const inner = screen.getByTestId('inner');+ const descendant = screen.getByTestId('nested-descendant');+ makeMeasurable(outer);+ makeMeasurable(inner);+ setGeometry(outer, {scrollHeight: 240});+ setGeometry(inner, {scrollWidth: 100});++ void act(() => outer.dispatchEvent(new Event('scroll')));+ flushFrame();++ expect(getRegisteredScrollOwnerState(outer)?.block.isScrollable).toBe(true);+ expect(getRegisteredScrollOwnerState(inner)?.inline.isScrollable).toBe(+ false,+ );+ expect(findNearestScrollOwner(descendant, 'block')).toBe(outer);+ expect(findNearestScrollOwner(descendant, 'inline')).toBeNull();+ });+});diff --git a/packages/core/src/hooks/useScrollableArea.ts b/packages/core/src/hooks/useScrollableArea.tsnew file mode 100644index 0000000000..d0794b2260--- /dev/null+++ b/packages/core/src/hooks/useScrollableArea.ts@@ -0,0 +1,469 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @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+ * @position Canonical behavior core for ScrollableArea and structure-owning adopters+ *+ * SYNC: When modified, update:+ * - /packages/core/src/hooks/useScrollableArea.doc.mjs+ * - /packages/core/src/hooks/useScrollableArea.test.tsx+ * - /packages/core/src/hooks/index.ts+ */++import {+ useCallback,+ useMemo,+ useRef,+ useState,+ type CSSProperties,+ type Ref,+ type RefAttributes,+ type RefCallback,+} from 'react';+import * as stylex from '@stylexjs/stylex';+import type {BaseProps} from '../BaseProps';+import {useIsomorphicLayoutEffect} from './useIsomorphicLayoutEffect';+import {mergeProps} from '../utils/mergeProps';+import {mergeRefs} from '../utils/mergeRefs';+import {observeResize} from '../utils/sharedResizeObserver';+import {+ getLogicalAxisMapping,+ measureLogicalOverflowGeometry,+ measureLogicalScrollAxis,+ type LogicalAxisMapping,+ type LogicalOverflowGeometry,+} from './scrollGeometry';+import {+ registerScrollOwner,+ unregisterScrollOwner,+} from './scrollOwnerRegistry';++export type ScrollAxis = 'inline' | 'block' | 'both';+export type ScrollOverscroll = 'allow' | 'contain';+export type ScrollStickyContainment = 'whenScrollable' | 'always';++export type ScrollKeyboardAccess =+ | {owner: 'content'}+ | {owner: 'viewport'; label: string; role?: 'group' | 'region'};++export interface ScrollAxisState {+ isScrollable: boolean;+ atStart: boolean;+ atEnd: boolean;+}++export interface ScrollableAreaState {+ inline: ScrollAxisState;+ block: ScrollAxisState;+}++export interface UseScrollableAreaOptions {+ axis: ScrollAxis;+ keyboardAccess: ScrollKeyboardAccess;+ overscroll?: ScrollOverscroll;+ stickyContainment?: ScrollStickyContainment;+}++export type ScrollableElementProps<E extends HTMLElement> = BaseProps<E> &+ RefAttributes<E>;++export interface UseScrollableAreaResult {+ getViewportProps<E extends HTMLElement>(+ props?: ScrollableElementProps<E>,+ ): ScrollableElementProps<E>;+ getContentProps<E extends HTMLElement>(+ props?: ScrollableElementProps<E>,+ ): ScrollableElementProps<E>;+ state: ScrollableAreaState;+}++const INACTIVE_AXIS_STATE: ScrollAxisState = {+ isScrollable: false,+ atStart: true,+ atEnd: true,+};+const INITIAL_STATE: ScrollableAreaState = {+ inline: INACTIVE_AXIS_STATE,+ block: INACTIVE_AXIS_STATE,+};+const INITIAL_OVERFLOW: LogicalOverflowGeometry = {+ inline: false,+ block: false,+};+const INITIAL_MAPPING: LogicalAxisMapping = {+ inline: 'x',+ block: 'y',+ inlineReversed: false,+ blockReversed: false,+};++const styles = stylex.create({+ overflow: (+ overflowX: 'auto' | 'hidden' | 'clip',+ overflowY: 'auto' | 'hidden' | 'clip',+ ) => ({overflowX, overflowY}),+});++function axisIsRequested(requested: ScrollAxis, axis: 'inline' | 'block') {+ return requested === axis || requested === 'both';+}++function statesEqual(a: ScrollableAreaState, b: ScrollableAreaState): boolean {+ return (+ a.inline.isScrollable === b.inline.isScrollable &&+ a.inline.atStart === b.inline.atStart &&+ a.inline.atEnd === b.inline.atEnd &&+ a.block.isScrollable === b.block.isScrollable &&+ a.block.atStart === b.block.atStart &&+ a.block.atEnd === b.block.atEnd+ );+}++function overflowEqual(+ a: LogicalOverflowGeometry,+ b: LogicalOverflowGeometry,+): boolean {+ return a.inline === b.inline && a.block === b.block;+}++function mappingsEqual(a: LogicalAxisMapping, b: LogicalAxisMapping): boolean {+ return (+ a.inline === b.inline &&+ a.block === b.block &&+ a.inlineReversed === b.inlineReversed &&+ a.blockReversed === b.blockReversed+ );+}++function withoutOwnedOverflow(+ style: CSSProperties | undefined,+): CSSProperties | undefined {+ if (style == null) {+ return undefined;+ }+ const result = {...style};+ delete result.overflow;+ delete result.overflowX;+ delete result.overflowY;+ delete result.overflowInline;+ delete result.overflowBlock;+ return result;+}++function useStableComposedRef(+ internalRef: RefCallback<HTMLElement>,+): (externalRef: Ref<HTMLElement> | undefined) => RefCallback<HTMLElement> {+ const cachedExternalRef = useRef<Ref<HTMLElement> | undefined>(undefined);+ const cachedComposedRef = useRef<RefCallback<HTMLElement> | null>(null);+ return useCallback(+ (externalRef: Ref<HTMLElement> | undefined) => {+ if (+ cachedComposedRef.current != null &&+ Object.is(cachedExternalRef.current, externalRef)+ ) {+ return cachedComposedRef.current;+ }+ const composed = mergeRefs(externalRef, internalRef);+ cachedExternalRef.current = externalRef;+ cachedComposedRef.current = composed;+ return composed;+ },+ [internalRef],+ );+}++/**+ * Adds axis-aware scroll behavior to caller-owned viewport and content boxes.+ * The returned prop getters compose refs and preserve caller props, so spread+ * order cannot detach measurement or override behavior-owned accessibility.+ */+export function useScrollableArea({+ axis,+ keyboardAccess,+ overscroll = 'allow',+ stickyContainment = 'whenScrollable',+}: UseScrollableAreaOptions): UseScrollableAreaResult {+ const [viewport, setViewport] = useState<HTMLElement | null>(null);+ const [content, setContent] = useState<HTMLElement | null>(null);+ const [measured, setMeasured] = useState<ScrollableAreaState>(INITIAL_STATE);+ const [overflow, setOverflow] =+ useState<LogicalOverflowGeometry>(INITIAL_OVERFLOW);+ const [mapping, setMapping] = useState<LogicalAxisMapping>(INITIAL_MAPPING);+ const stateRef = useRef<ScrollableAreaState>(INITIAL_STATE);++ const viewportRef = useCallback((node: HTMLElement | null) => {+ setViewport(current => (current === node ? current : node));+ }, []);+ const contentRef = useCallback((node: HTMLElement | null) => {+ setContent(current => (current === node ? current : node));+ }, []);+ const getComposedViewportRef = useStableComposedRef(viewportRef);+ const getComposedContentRef = useStableComposedRef(contentRef);++ useIsomorphicLayoutEffect(() => {+ if (viewport == null || content == null) {+ return;+ }++ let frame: number | null = null;+ let isActive = true;++ const measure = () => {+ frame = null;+ const computedStyle = getComputedStyle(viewport);+ const nextMapping = getLogicalAxisMapping(+ computedStyle.writingMode,+ computedStyle.direction,+ );+ const inlineOverflow = axisIsRequested(axis, 'inline')+ ? measureLogicalOverflowGeometry(viewport, 'inline', nextMapping)+ : false;+ const blockOverflow = axisIsRequested(axis, 'block')+ ? measureLogicalOverflowGeometry(viewport, 'block', nextMapping)+ : false;+ const inline = axisIsRequested(axis, 'inline')+ ? measureLogicalScrollAxis(viewport, 'inline', nextMapping)+ : INACTIVE_AXIS_STATE;+ const block = axisIsRequested(axis, 'block')+ ? measureLogicalScrollAxis(viewport, 'block', nextMapping)+ : INACTIVE_AXIS_STATE;++ // Hidden, disconnected, and zero-size viewports are unknown rather than+ // fitting. Keep the last valid state until a bounded signal remeasures.+ if (+ inlineOverflow == null ||+ blockOverflow == null ||+ inline == null ||+ block == null+ ) {+ return;+ }++ const nextOverflow = {+ inline: inlineOverflow,+ block: blockOverflow,+ };+ const nextState = {inline, block};+ stateRef.current = nextState;+ registerScrollOwner(viewport, nextState);+ // eslint-disable-next-line @eslint-react/set-state-in-effect -- measured DOM geometry controls whether the viewport becomes a CSS scroll container+ setOverflow(current =>+ overflowEqual(current, nextOverflow) ? current : nextOverflow,+ );+ // eslint-disable-next-line @eslint-react/set-state-in-effect -- measured DOM state is the hook's output+ setMeasured(current =>+ statesEqual(current, nextState) ? current : nextState,+ );+ // eslint-disable-next-line @eslint-react/set-state-in-effect -- writing-mode changes remap behavior-owned physical CSS+ setMapping(current =>+ mappingsEqual(current, nextMapping) ? current : nextMapping,+ );+ };++ const scheduleMeasure = () => {+ if (!isActive || frame != null) {+ return;+ }+ frame = window.requestAnimationFrame(measure);+ };++ registerScrollOwner(viewport, stateRef.current);+ measure();+ const stopObservingViewport = observeResize(viewport, scheduleMeasure);+ const stopObservingContent = observeResize(content, scheduleMeasure);++ viewport.addEventListener('scroll', scheduleMeasure, {passive: true});+ window.addEventListener('resize', scheduleMeasure);+ window.visualViewport?.addEventListener('resize', scheduleMeasure);+ content.addEventListener('load', scheduleMeasure, true);+ viewport.addEventListener('transitionend', scheduleMeasure);+ viewport.addEventListener('animationend', scheduleMeasure);+ content.addEventListener('transitionend', scheduleMeasure);+ content.addEventListener('animationend', scheduleMeasure);++ const mutationObserver =+ typeof MutationObserver === 'undefined'+ ? null+ : new MutationObserver(scheduleMeasure);+ mutationObserver?.observe(viewport, {+ attributes: true,+ attributeFilter: ['class', 'dir', 'hidden', 'style'],+ });+ mutationObserver?.observe(content, {+ attributes: true,+ attributeFilter: ['class', 'dir', 'hidden', 'style'],+ characterData: true,+ childList: true,+ subtree: true,+ });+ let ancestor = viewport.parentElement;+ while (ancestor != null) {+ mutationObserver?.observe(ancestor, {+ attributes: true,+ attributeFilter: ['class', 'dir', 'hidden', 'style'],+ });+ ancestor = ancestor.parentElement;+ }++ const fonts = document.fonts;+ fonts?.addEventListener?.('loadingdone', scheduleMeasure);+ void fonts?.ready.then(scheduleMeasure);++ return () => {+ isActive = false;+ unregisterScrollOwner(viewport);+ stopObservingViewport();+ stopObservingContent();+ mutationObserver?.disconnect();+ viewport.removeEventListener('scroll', scheduleMeasure);+ window.removeEventListener('resize', scheduleMeasure);+ window.visualViewport?.removeEventListener('resize', scheduleMeasure);+ content.removeEventListener('load', scheduleMeasure, true);+ viewport.removeEventListener('transitionend', scheduleMeasure);+ viewport.removeEventListener('animationend', scheduleMeasure);+ content.removeEventListener('transitionend', scheduleMeasure);+ content.removeEventListener('animationend', scheduleMeasure);+ fonts?.removeEventListener?.('loadingdone', scheduleMeasure);+ if (frame != null) {+ window.cancelAnimationFrame(frame);+ }+ };+ }, [axis, content, viewport]);++ const state = useMemo<ScrollableAreaState>(+ () => ({+ inline: axisIsRequested(axis, 'inline')+ ? measured.inline+ : INACTIVE_AXIS_STATE,+ block: axisIsRequested(axis, 'block')+ ? measured.block+ : INACTIVE_AXIS_STATE,+ }),+ [axis, measured],+ );++ const getViewportProps = useCallback(+ <E extends HTMLElement>(+ props: ScrollableElementProps<E> = {},+ ): ScrollableElementProps<E> => {+ const hasEffectiveAxis =+ state.inline.isScrollable || state.block.isScrollable;+ const requestedX =+ (axisIsRequested(axis, 'inline') && mapping.inline === 'x') ||+ (axisIsRequested(axis, 'block') && mapping.block === 'x');+ const requestedY =+ (axisIsRequested(axis, 'inline') && mapping.inline === 'y') ||+ (axisIsRequested(axis, 'block') && mapping.block === 'y');+ const overflowingX =+ (overflow.inline && mapping.inline === 'x') ||+ (overflow.block && mapping.block === 'x');+ const overflowingY =+ (overflow.inline && mapping.inline === 'y') ||+ (overflow.block && mapping.block === 'y');+ const containsSticky =+ overflowingX || overflowingY || stickyContainment === 'always';+ const scrollsOnX =+ stickyContainment === 'always' ? requestedX : overflowingX;+ const scrollsOnY =+ stickyContainment === 'always' ? requestedY : overflowingY;+ const {xstyle, ...domProps} = props;+ const callerProps = {+ ...domProps,+ style: withoutOwnedOverflow(domProps.style),+ };+ const styledProps = mergeProps(+ callerProps,+ stylex.props(+ xstyle,+ styles.overflow(+ containsSticky ? (scrollsOnX ? 'auto' : 'hidden') : 'clip',+ containsSticky ? (scrollsOnY ? 'auto' : 'hidden') : 'clip',+ ),+ ),+ ) as ScrollableElementProps<E>;+ const keepsProgrammaticFocus =+ !hasEffectiveAxis &&+ viewport != null &&+ typeof document !== 'undefined' &&+ document.activeElement === viewport;+ const behaviorStyle: CSSProperties = {...styledProps.style};+ const containInline =+ overscroll === 'contain' && state.inline.isScrollable;+ const containBlock = overscroll === 'contain' && state.block.isScrollable;+ const inlinePhysical = mapping.inline;+ const blockPhysical = mapping.block;++ if (axisIsRequested(axis, 'inline')) {+ behaviorStyle[+ inlinePhysical === 'x' ? 'overscrollBehaviorX' : 'overscrollBehaviorY'+ ] = containInline ? 'contain' : 'auto';+ }+ if (axisIsRequested(axis, 'block')) {+ behaviorStyle[+ blockPhysical === 'x' ? 'overscrollBehaviorX' : 'overscrollBehaviorY'+ ] = containBlock ? 'contain' : 'auto';+ }++ const keyboardProps =+ keyboardAccess.owner === 'viewport'+ ? {+ role: keyboardAccess.role ?? 'group',+ 'aria-label': keyboardAccess.label,+ tabIndex: hasEffectiveAxis+ ? 0+ : keepsProgrammaticFocus+ ? -1+ : undefined,+ }+ : {};++ const result: ScrollableElementProps<E> = {+ ...styledProps,+ ...keyboardProps,+ ref: getComposedViewportRef(styledProps.ref),+ style: behaviorStyle,+ 'data-scroll-axis': axis,+ 'data-scrollable-inline': state.inline.isScrollable+ ? 'true'+ : undefined,+ 'data-scrollable-block': state.block.isScrollable ? 'true' : undefined,+ 'data-scroll-inline-start': state.inline.atStart ? 'true' : undefined,+ 'data-scroll-inline-end': state.inline.atEnd ? 'true' : undefined,+ 'data-scroll-block-start': state.block.atStart ? 'true' : undefined,+ 'data-scroll-block-end': state.block.atEnd ? 'true' : undefined,+ };+ return result;+ },+ [+ axis,+ getComposedViewportRef,+ keyboardAccess,+ mapping,+ overflow,+ overscroll,+ state,+ stickyContainment,+ viewport,+ ],+ );++ const getContentProps = useCallback(+ <E extends HTMLElement>(+ props: ScrollableElementProps<E> = {},+ ): ScrollableElementProps<E> => {+ const result: ScrollableElementProps<E> = {+ ...props,+ ref: getComposedContentRef(props.ref),+ 'data-scroll-content': '',+ };+ return result;+ },+ [getComposedContentRef],+ );++ return {getViewportProps, getContentProps, state};+}diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 22c2956f62..bd78d506a0 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -43,6 +43,7 @@ export * from './CheckboxList';export * from './Collapsible';export * from './RadioList';export * from './Resizable';+export * from './ScrollableArea';export * from './Divider';export * from './VisuallyHidden';export * from './EmptyState';