Skip to content

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

TypeScript

fix(ScrollableArea): complete hardening audit (#6314)

AKff7e096bab6d
diff --git a/.changeset/scrollable-area-hardening.md b/.changeset/scrollable-area-hardening.md
new file mode 100644
index 0000000000..7c8eea165a
--- /dev/null
+++ b/.changeset/scrollable-area-hardening.md
@@ -0,0 +1,9 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] `getContentProps` from `useScrollableArea` now applies a caller's `xstyle` instead of leaking it to the DOM. (#6314)
+
+A viewport that lost overflow while focused drops its leftover `tabindex` as soon as it is blurred, and a focused viewport in another document keeps focus when it loses overflow. `ScrollableArea`'s viewport also sheds the obsolete `-webkit-overflow-scrolling` and initial-value scrollbar declarations.
+
+@AKnassa
diff --git a/apps/storybook/stories/ScrollableArea.stories.tsx b/apps/storybook/stories/ScrollableArea.stories.tsx
index be3813afc8..2a07bbb731 100644
--- a/apps/storybook/stories/ScrollableArea.stories.tsx
+++ b/apps/storybook/stories/ScrollableArea.stories.tsx
@@ -40,6 +40,17 @@ const styles = stylex.create({
containerViewport: {
blockSize: 180,
},
+ narrowHost: {
+ inlineSize: 280,
+ padding: spacingVars['--spacing-2'],
+ borderWidth: 1,
+ borderStyle: 'dashed',
+ borderColor: colorVars['--color-border-emphasized'],
+ },
+ narrowViewport: {
+ inlineSize: '100%',
+ blockSize: 140,
+ },
contentPadding: {
padding: spacingVars['--spacing-3'],
},
@@ -329,9 +340,31 @@ export const ConditionalKeyboardAccess: Story = {
expect(getComputedStyle(viewport).overflowY).toBe('auto');
expect(viewport).toHaveAttribute('tabindex', '0');
});
- await userEvent.click(button);
+
+ // A focused native scroll container is the keyboard-scrolling contract.
+ // Synthetic key events cannot drive native scrolling, so a programmatic
+ // scroll proves the live scroll machinery here; trusted arrow and PageDown
+ // keys belong to a real-browser spec (AST-009 FR7).
+ viewport.focus();
+ expect(document.activeElement).toBe(viewport);
+ expect(viewport).toHaveAttribute('data-scroll-block-start', 'true');
+ viewport.scrollTop = 40;
+ await waitFor(() => {
+ expect(viewport).not.toHaveAttribute('data-scroll-block-start');
+ });
+
+ // Losing overflow while focused keeps focus without a future tab stop
+ // (button.click() is programmatic, so the viewport stays focused).
+ button.click();
await waitFor(() => {
expect(getComputedStyle(viewport).overflowY).toBe('clip');
+ expect(viewport).toHaveAttribute('tabindex', '-1');
+ });
+ expect(document.activeElement).toBe(viewport);
+
+ // Blurring the fitting viewport removes the leftover tabindex.
+ viewport.blur();
+ await waitFor(() => {
expect(viewport).not.toHaveAttribute('tabindex');
});
},
@@ -642,6 +675,28 @@ function RTLBehaviorProbeStory() {
export const RTLBehaviorProbe: Story = {
render: () => <RTLBehaviorProbeStory />,
+ play: async ({canvasElement}) => {
+ const button = canvasElement.querySelector<HTMLButtonElement>(
+ '[data-rtl-scroll-button="true"]',
+ );
+ const viewport = canvasElement.querySelector<HTMLElement>(
+ '[data-rtl-scroll-probe="true"]',
+ );
+ expect(button).not.toBeNull();
+ expect(viewport).not.toBeNull();
+ if (button == null || viewport == null) {
+ return;
+ }
+
+ await waitFor(() => {
+ expect(viewport).toHaveAttribute('data-scrollable-inline', 'true');
+ expect(viewport).toHaveAttribute('data-scroll-inline-start', 'true');
+ });
+ await userEvent.click(button);
+ await waitFor(() => {
+ expect(viewport).not.toHaveAttribute('data-scroll-inline-start');
+ });
+ },
parameters: {controls: {disable: true}},
};
@@ -684,6 +739,32 @@ export const TransformedClippedAncestor: Story = {
parameters: {controls: {disable: true}},
};
+export const NarrowContainer: Story = {
+ render: () => (
+ <div {...stylex.props(styles.canvas)}>
+ <div {...stylex.props(styles.narrowHost)}>
+ <ScrollableArea
+ axis="block"
+ label="Narrow activity"
+ data-evidence="narrow-container"
+ xstyle={[styles.viewport, styles.narrowViewport]}>
+ <VStack gap={2} xstyle={styles.contentPadding}>
+ <Text>
+ Percentage-width viewport inside a 280px container, with a long
+ unbroken token below.
+ </Text>
+ <p {...stylex.props(styles.copy)}>
+ LongUnbrokenIdentifier_0123456789_ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz
+ </p>
+ <Rows count={6} />
+ </VStack>
+ </ScrollableArea>
+ </div>
+ </div>
+ ),
+ parameters: {controls: {disable: true}},
+};
+
export const ContainerIntegration: Story = {
render: () => (
<div {...stylex.props(styles.canvas)}>
diff --git a/packages/core/src/ScrollableArea/ScrollableArea.doc.mjs b/packages/core/src/ScrollableArea/ScrollableArea.doc.mjs
index 65b366f519..eb4da4b2fb 100644
--- a/packages/core/src/ScrollableArea/ScrollableArea.doc.mjs
+++ b/packages/core/src/ScrollableArea/ScrollableArea.doc.mjs
@@ -10,6 +10,7 @@ export const docs = {
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: 'Leave `role` unset (it renders `group`) for ordinary scroll containers. Choose `role="region"` only when the area is significant enough to appear in screen-reader landmark navigation; every `region` adds an entry to that list.'},
{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.'},
@@ -28,7 +29,7 @@ export const docs = {
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: 'role', type: "'group' | 'region'", description: 'Semantics for the named viewport; use `region` only for areas that belong in landmark navigation.', 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.'},
@@ -44,7 +45,7 @@ export const docs = {
{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.'},
+ {name: 'xstyle', type: 'StyleXStyles', description: 'StyleX sizing and native scrollbar presentation overrides for the viewport. Must be a `stylex.create()` value, not an inline style object.'},
],
playground: {
defaults: {
@@ -79,7 +80,7 @@ export const docsDense = {
propDescriptions: {
axis: "logical scroll intent: 'inline' | 'block' (default) | 'both'",
label: 'required accessible viewport name',
- role: "named viewport semantics: 'group' (default) | 'region'",
+ role: "named viewport semantics: 'group' (default) | 'region' (landmark-navigation entries only)",
overscroll: "edge behavior: 'allow' (default) | 'contain' on effective axes only",
width: 'viewport width',
height: 'viewport height',
diff --git a/packages/core/src/ScrollableArea/ScrollableArea.test.tsx b/packages/core/src/ScrollableArea/ScrollableArea.test.tsx
index 3f75946b1c..d792d72102 100644
--- a/packages/core/src/ScrollableArea/ScrollableArea.test.tsx
+++ b/packages/core/src/ScrollableArea/ScrollableArea.test.tsx
@@ -2,9 +2,42 @@
import {readFileSync} from 'node:fs';
import {act, render, screen} from '@testing-library/react';
+import * as stylex from '@stylexjs/stylex';
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import type {StyleXStyles} from '@stylexjs/stylex';
+import {getAllInjectedCss} from '../__tests__/forcedColors';
+import {
+ containerPaddingBlockEndVarStyles,
+ containerPaddingBlockStartVarStyles,
+ containerPaddingInlineEndVarStyles,
+ containerPaddingInlineStartVarStyles,
+ paddingBlockEndStyles,
+ paddingBlockStartStyles,
+ paddingInlineEndStyles,
+ paddingInlineStartStyles,
+} from '../Layout/padding.stylex';
import {ScrollableArea} from './ScrollableArea';
+/**
+ * Atomic (hashed) class names for a style, excluding dev-mode debug names —
+ * two style maps declaring the same property/value share the hash atom, so
+ * these tokens are comparable across maps while debug names are not. Accepts
+ * the custom-property var styles, whose entries are not typed as StyleXStyles.
+ */
+function classTokens(style: object): string[] {
+ return (stylex.props(style as StyleXStyles).className ?? '')
+ .split(' ')
+ .filter(token => token && !token.includes('__'));
+}
+
+/** Each logical edge's applied padding atom and published inset variable. */
+const PADDING_EDGES = [
+ [paddingInlineStartStyles, containerPaddingInlineStartVarStyles],
+ [paddingInlineEndStyles, containerPaddingInlineEndVarStyles],
+ [paddingBlockStartStyles, containerPaddingBlockStartVarStyles],
+ [paddingBlockEndStyles, containerPaddingBlockEndVarStyles],
+] as const;
+
function setGeometry(
element: HTMLElement,
values: Partial<
@@ -98,7 +131,7 @@ describe('ScrollableArea', () => {
expect(viewport).toHaveAttribute('data-scrollable-block', 'true');
setGeometry(viewport, {scrollHeight: 100});
- viewport.focus();
+ void act(() => viewport.focus());
void act(() => viewport.dispatchEvent(new Event('scroll')));
flushFrame();
expect(viewport).toHaveAttribute('tabindex', '-1');
@@ -198,8 +231,8 @@ describe('ScrollableArea', () => {
Messages
</ScrollableArea>,
);
- expect(viewport.getAttribute('style')).toContain('auto');
- expect(viewport.getAttribute('style')).toContain('hidden');
+ expect(viewport.getAttribute('style')).toContain('--x-overflowX: hidden');
+ expect(viewport.getAttribute('style')).toContain('--x-overflowY: auto');
expect(viewport).not.toHaveAttribute('tabindex');
});
@@ -250,6 +283,63 @@ describe('ScrollableArea', () => {
);
});
+ it.each([
+ {name: 'zero on every edge by default', props: {}, edges: [0, 0, 0, 0]},
+ {
+ name: 'uniform padding on every edge',
+ props: {padding: 4},
+ edges: [4, 4, 4, 4],
+ },
+ {
+ name: 'zero axis values over uniform',
+ props: {padding: 4, paddingInline: 0, paddingBlock: 0},
+ edges: [0, 0, 0, 0],
+ },
+ {
+ name: 'start edges over axis over uniform',
+ props: {
+ padding: 4,
+ paddingInline: 3,
+ paddingBlock: 2,
+ paddingInlineStart: 0,
+ paddingBlockStart: 0,
+ },
+ edges: [0, 3, 0, 2],
+ },
+ {
+ name: 'end edges over axis over uniform',
+ props: {
+ padding: 4,
+ paddingInline: 3,
+ paddingBlock: 2,
+ paddingInlineEnd: 0,
+ paddingBlockEnd: 0,
+ },
+ edges: [3, 0, 2, 0],
+ },
+ ] as const)('applies and publishes $name', ({props, edges}) => {
+ render(
+ <ScrollableArea label="Messages" data-testid="viewport" {...props}>
+ Messages
+ </ScrollableArea>,
+ );
+ const content = screen.getByTestId('viewport')
+ .firstElementChild as HTMLElement;
+ const contentClasses = new Set(content.className.split(' '));
+
+ // StyleX keeps one atom per property, so the winning atom being present
+ // means every overridden one was dropped.
+ PADDING_EDGES.forEach(([atoms, inset], index) => {
+ for (const style of [atoms[edges[index]], inset[edges[index]]]) {
+ const tokens = classTokens(style);
+ expect(tokens.length).toBeGreaterThan(0);
+ for (const token of tokens) {
+ expect(contentClasses).toContain(token);
+ }
+ }
+ });
+ });
+
it('keeps inherited container bleed opt-in on the viewport', () => {
const {rerender} = render(
<ScrollableArea label="Messages" data-testid="viewport">
@@ -272,10 +362,32 @@ describe('ScrollableArea', () => {
});
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'");
+ render(
+ <ScrollableArea label="Messages" data-testid="viewport">
+ Messages
+ </ScrollableArea>,
+ );
+ const viewport = screen.getByTestId('viewport');
+ const css = getAllInjectedCss();
+ // Anchor every assertion to a class the rendered viewport carries --
+ // runtime injection emits rules for unused styles too, so an unanchored
+ // match would pass even if the viewport stopped composing these styles.
+ const thumbRules = [
+ ...css.matchAll(/\.([\w-]+)[^{]*\{[^{}]*scrollbar-color:([^;{}]*);/g),
+ ].filter(match => viewport.classList.contains(match[1]));
+ expect(
+ thumbRules.some(
+ match => match[2].trim() === 'var(--color-neutral) transparent',
+ ),
+ ).toBe(true);
+ const forcedRules = [
+ ...css.matchAll(
+ /@media \(forced-colors:\s*active\)\s*\{\s*\.([\w-]+)[^{]*\{[^{}]*scrollbar-color:\s*auto/g,
+ ),
+ ];
+ expect(
+ forcedRules.some(match => viewport.classList.contains(match[1])),
+ ).toBe(true);
});
it("keeps the platform's own scroll indicator on touch screens", () => {
@@ -284,9 +396,25 @@ describe('ScrollableArea', () => {
});
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'");
+ render(
+ <ScrollableArea label="Messages" data-testid="viewport">
+ Messages
+ </ScrollableArea>,
+ );
+ const viewport = screen.getByTestId('viewport');
+ const css = getAllInjectedCss();
+ // The guarded rule must declare `container-type: scroll-state` INSIDE the
+ // @supports block (a mutated declaration keeps the condition text), on a
+ // class the rendered viewport actually carries (runtime injection emits
+ // rules for unused styles too).
+ const guarded = [
+ ...css.matchAll(
+ /@supports \(container-type:\s*scroll-state\)\s*\{\s*\.([\w-]+)[^{]*\{[^{}]*container-type:\s*scroll-state\s*;/g,
+ ),
+ ];
+ expect(guarded.some(match => viewport.classList.contains(match[1]))).toBe(
+ true,
+ );
});
});
diff --git a/packages/core/src/ScrollableArea/ScrollableArea.tsx b/packages/core/src/ScrollableArea/ScrollableArea.tsx
index 8ec4355b37..fc8b55f381 100644
--- a/packages/core/src/ScrollableArea/ScrollableArea.tsx
+++ b/packages/core/src/ScrollableArea/ScrollableArea.tsx
@@ -49,7 +49,6 @@ const styles = stylex.create({
boxSizing: 'border-box',
maxInlineSize: '100%',
maxBlockSize: '100%',
- WebkitOverflowScrolling: 'touch',
scrollbarColor: {
default: `${colorVars['--color-neutral']} transparent`,
// Touch screens keep the platform's own scroll indicator, which iOS
@@ -58,8 +57,6 @@ const styles = stylex.create({
'@media (pointer: coarse)': 'auto',
'@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: {
diff --git a/packages/core/src/hooks/useScrollableArea.doc.mjs b/packages/core/src/hooks/useScrollableArea.doc.mjs
index 8115983dc6..582171b31e 100644
--- a/packages/core/src/hooks/useScrollableArea.doc.mjs
+++ b/packages/core/src/hooks/useScrollableArea.doc.mjs
@@ -40,7 +40,7 @@ export const docs = {
name: 'getContentProps',
type: '<E extends HTMLElement>(props?: ScrollableElementProps<E>) => ScrollableElementProps<E>',
description:
- 'Composes caller content-box props and refs with content observation.',
+ 'Composes caller content-box props, xstyle, and refs with content observation.',
},
{
name: 'state',
@@ -78,11 +78,21 @@ export const docs = {
description:
'Pass caller `xstyle` through `getViewportProps`; the getter composes it with fitting clip, active overflow, and Sticky containment.',
},
+ {
+ guidance: true,
+ description:
+ 'Give a viewport-owned tab stop a visible focus indicator; compose `focusOutlineStyles.focusVisible` (or an equivalent) into the viewport `xstyle`, as ScrollableArea does.',
+ },
{
guidance: false,
description:
'Attach only the viewport getter. A real observed content box is required for live overflow changes.',
},
+ {
+ guidance: false,
+ description:
+ 'Declare overflow through caller props on the viewport; the getter owns overflow declarations and strips conflicting inline values.',
+ },
],
},
relatedComponents: ['ScrollableArea'],
@@ -102,7 +112,7 @@ export const docsDense = {
returnDescriptions: {
getViewportProps:
'safe viewport prop/ref/xstyle composition with behavior-owned overflow, accessibility, and chaining.',
- getContentProps: 'safe observed content-box prop/ref composition.',
+ getContentProps: 'safe observed content-box prop/ref/xstyle composition.',
state: 'inline/block isScrollable, atStart, and atEnd state.',
},
usage: {
diff --git a/packages/core/src/hooks/useScrollableArea.test.tsx b/packages/core/src/hooks/useScrollableArea.test.tsx
index e0b06a8e44..a8d04705c4 100644
--- a/packages/core/src/hooks/useScrollableArea.test.tsx
+++ b/packages/core/src/hooks/useScrollableArea.test.tsx
@@ -9,7 +9,14 @@
import {act, render, screen} from '@testing-library/react';
import * as stylex from '@stylexjs/stylex';
-import {useRef, type ReactNode, type Ref} from 'react';
+import {
+ Profiler,
+ StrictMode,
+ useRef,
+ type FocusEvent,
+ type ReactNode,
+ type Ref,
+} from 'react';
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {
useScrollableArea,
@@ -26,11 +33,13 @@ import {subscribeScrollGeometry} from './scrollGeometrySubscriptions';
const testStyles = stylex.create({
viewport: {borderWidth: 1, borderStyle: 'solid'},
+ contentMinWidth: (minWidth: string) => ({minWidth}),
});
interface FixtureProps {
axis?: ScrollAxis;
chaining?: ScrollOverscroll;
+ keyboardOwner?: 'viewport' | 'contentOrViewport';
stickyContainment?: ScrollStickyContainment;
externalRef?: Ref<HTMLDivElement>;
onScroll?: React.UIEventHandler<HTMLDivElement>;
@@ -39,6 +48,7 @@ interface FixtureProps {
function Fixture({
axis = 'inline',
chaining = 'allow',
+ keyboardOwner = 'viewport',
stickyContainment,
externalRef,
onScroll,
@@ -46,7 +56,7 @@ function Fixture({
const {getViewportProps, getContentProps, state} = useScrollableArea({
axis,
keyboardAccess: {
- owner: 'viewport',
+ owner: keyboardOwner,
label: 'Scrollable results',
role: 'region',
},
@@ -205,6 +215,36 @@ describe('useScrollableArea', () => {
});
}
+ function setInlineOverflow(viewport: HTMLElement, isOverflowing: boolean) {
+ setGeometry(viewport, {scrollWidth: isOverflowing ? 180 : 100});
+ void act(() => viewport.dispatchEvent(new Event('scroll')));
+ flushFrame();
+ }
+
+ /** Focus listener changes in call order, as `add focusin <test id>`. */
+ function recordFocusListeners() {
+ const add = vi.spyOn(EventTarget.prototype, 'addEventListener');
+ const remove = vi.spyOn(EventTarget.prototype, 'removeEventListener');
+ const changes = (verb: string, spy: typeof add | typeof remove) =>
+ spy.mock.calls.flatMap(([type], index) => {
+ const target = spy.mock.contexts[index];
+ return target instanceof HTMLElement &&
+ target.dataset.testid != null &&
+ (type === 'focusin' || type === 'focusout')
+ ? [
+ {
+ order: spy.mock.invocationCallOrder[index],
+ change: `${verb} ${type} ${target.dataset.testid}`,
+ },
+ ]
+ : [];
+ });
+ return () =>
+ [...changes('add', add), ...changes('remove', remove)]
+ .sort((a, b) => a.order - b.order)
+ .map(({change}) => change);
+ }
+
it('reports a change below the content root as content only and an outer change as layout', async () => {
render(<Fixture />);
const viewport = screen.getByTestId('viewport');
@@ -428,8 +468,8 @@ describe('useScrollableArea', () => {
expect(viewport.getAttribute('style')).toContain('clip');
rerender(<Fixture stickyContainment="always" />);
- expect(viewport.getAttribute('style')).toContain('auto');
- expect(viewport.getAttribute('style')).toContain('hidden');
+ expect(viewport.getAttribute('style')).toContain('--x-overflowX: auto');
+ expect(viewport.getAttribute('style')).toContain('--x-overflowY: hidden');
});
it('activates only the overflowing physical axis when both are requested', () => {
@@ -478,7 +518,7 @@ describe('useScrollableArea', () => {
expect(viewport).toHaveAccessibleName('Adaptive results');
expect(viewport).toHaveAttribute('tabindex', '0');
- viewport.focus();
+ void act(() => viewport.focus());
rerender(
<AdaptiveFixture>
<button type="button">Use existing action</button>
@@ -766,6 +806,52 @@ describe('useScrollableArea', () => {
inlineReversed: true,
blockReversed: false,
});
+ expect(getLogicalAxisMapping('sideways-lr', 'rtl')).toEqual({
+ inline: 'y',
+ block: 'x',
+ inlineReversed: false,
+ blockReversed: false,
+ });
+ expect(getLogicalAxisMapping('sideways-rl', 'ltr')).toEqual({
+ inline: 'y',
+ block: 'x',
+ inlineReversed: false,
+ blockReversed: true,
+ });
+ expect(getLogicalAxisMapping('sideways-rl', 'rtl')).toEqual({
+ inline: 'y',
+ block: 'x',
+ inlineReversed: true,
+ blockReversed: true,
+ });
+ expect(getLogicalAxisMapping('vertical-rl', 'rtl')).toEqual({
+ inline: 'y',
+ block: 'x',
+ inlineReversed: true,
+ blockReversed: true,
+ });
+ expect(getLogicalAxisMapping('horizontal-tb', 'rtl')).toEqual({
+ inline: 'x',
+ block: 'y',
+ inlineReversed: true,
+ blockReversed: false,
+ });
+ });
+
+ it('normalizes reversed inline offsets in sideways writing modes', () => {
+ render(<Fixture />);
+ const viewport = screen.getByTestId('viewport');
+ makeMeasurable(viewport);
+ viewport.style.writingMode = 'sideways-lr';
+ setGeometry(viewport, {scrollHeight: 300, scrollTop: -200});
+
+ void act(() => viewport.dispatchEvent(new Event('scroll')));
+ flushFrame();
+ expect(state().inline).toEqual({
+ isScrollable: true,
+ atStart: false,
+ atEnd: true,
+ });
});
it('measures both requested axes independently in vertical writing mode', () => {
@@ -831,7 +917,7 @@ describe('useScrollableArea', () => {
void act(() => viewport.dispatchEvent(new Event('scroll')));
flushFrame();
- viewport.focus();
+ void act(() => viewport.focus());
expect(document.activeElement).toBe(viewport);
setGeometry(viewport, {scrollWidth: 100});
void act(() => viewport.dispatchEvent(new Event('scroll')));
@@ -841,6 +927,402 @@ describe('useScrollableArea', () => {
expect(document.activeElement).toBe(viewport);
});
+ it.each(['viewport', 'contentOrViewport'] as const)(
+ 'removes the leftover tabindex once a fitting viewport is blurred (%s owner)',
+ keyboardOwner => {
+ render(<Fixture keyboardOwner={keyboardOwner} />);
+ const viewport = screen.getByTestId('viewport');
+ makeMeasurable(viewport);
+ setGeometry(viewport, {scrollWidth: 180});
+ void act(() => viewport.dispatchEvent(new Event('scroll')));
+ flushFrame();
+
+ void act(() => viewport.focus());
+ setGeometry(viewport, {scrollWidth: 100});
+ void act(() => viewport.dispatchEvent(new Event('scroll')));
+ flushFrame();
+ expect(viewport).toHaveAttribute('tabindex', '-1');
+ expect(document.activeElement).toBe(viewport);
+
+ void act(() => viewport.blur());
+ expect(viewport).not.toHaveAttribute('tabindex');
+ },
+ );
+
+ it('keeps a focused viewport in another document programmatically focusable when it loses overflow', () => {
+ const frame = document.createElement('iframe');
+ document.body.append(frame);
+ const frameDocument = frame.contentDocument as Document;
+ const container = frameDocument.createElement('div');
+ frameDocument.body.append(container);
+
+ const {getByTestId, rerender, unmount} = render(
+ <Fixture externalRef={() => {}} />,
+ {container},
+ );
+ try {
+ const viewport = getByTestId('viewport');
+ makeMeasurable(viewport);
+ viewport.style.overflowX = 'auto';
+ setInlineOverflow(viewport, true);
+ expect(viewport).toHaveAttribute('tabindex', '0');
+
+ void act(() => viewport.focus());
+ expect(frameDocument.activeElement).toBe(viewport);
+ setInlineOverflow(viewport, false);
+
+ expect(viewport).toHaveAttribute('tabindex', '-1');
+ expect(frameDocument.activeElement).toBe(viewport);
+
+ // Reattaching reads focus again, from the same document.
+ rerender(<Fixture externalRef={() => {}} />);
+ expect(viewport).toHaveAttribute('tabindex', '-1');
+ } finally {
+ unmount();
+ frame.remove();
+ }
+ });
+
+ it('ignores focus on a descendant of a viewport that loses overflow', () => {
+ render(<Fixture />);
+ const viewport = screen.getByTestId('viewport');
+ const descendant = screen.getByTestId('descendant');
+ descendant.tabIndex = -1;
+ makeMeasurable(viewport);
+ setInlineOverflow(viewport, true);
+
+ void act(() => descendant.focus());
+ setInlineOverflow(viewport, false);
+
+ expect(document.activeElement).toBe(descendant);
+ expect(viewport).not.toHaveAttribute('tabindex');
+ });
+
+ it('removes the leftover tabindex when focus moves from the viewport to a descendant', () => {
+ render(<Fixture />);
+ const viewport = screen.getByTestId('viewport');
+ const descendant = screen.getByTestId('descendant');
+ descendant.tabIndex = -1;
+ makeMeasurable(viewport);
+ setInlineOverflow(viewport, true);
+ void act(() => viewport.focus());
+ setInlineOverflow(viewport, false);
+ expect(viewport).toHaveAttribute('tabindex', '-1');
+
+ void act(() => descendant.focus());
+
+ expect(document.activeElement).toBe(descendant);
+ expect(viewport).not.toHaveAttribute('tabindex');
+ });
+
+ it('keeps the tabindex when focusout fires while the viewport is still the active element', () => {
+ render(<Fixture />);
+ const viewport = screen.getByTestId('viewport');
+ makeMeasurable(viewport);
+ setInlineOverflow(viewport, true);
+ void act(() => viewport.focus());
+ setInlineOverflow(viewport, false);
+
+ // A window blur fires focusout but leaves the element active.
+ void act(() =>
+ viewport.dispatchEvent(new FocusEvent('focusout', {bubbles: true})),
+ );
+
+ expect(document.activeElement).toBe(viewport);
+ expect(viewport).toHaveAttribute('tabindex', '-1');
+ });
+
+ it('keeps the tabindex when focus leaves and returns in one task', () => {
+ render(<Fixture />);
+ const viewport = screen.getByTestId('viewport');
+ makeMeasurable(viewport);
+ setInlineOverflow(viewport, true);
+ void act(() => viewport.focus());
+ setInlineOverflow(viewport, false);
+
+ void act(() => {
+ viewport.blur();
+ viewport.focus();
+ });
+
+ expect(document.activeElement).toBe(viewport);
+ expect(viewport).toHaveAttribute('tabindex', '-1');
+ });
+
+ it('reads focus from the document when focus events never reach the viewport', () => {
+ const stopFocusEvent = (event: FocusEvent<HTMLDivElement>) =>
+ event.stopPropagation();
+ render(
+ <div onFocusCapture={stopFocusEvent} onBlurCapture={stopFocusEvent}>
+ <Fixture />
+ </div>,
+ );
+ const viewport = screen.getByTestId('viewport');
+ makeMeasurable(viewport);
+ setInlineOverflow(viewport, true);
+
+ void act(() => viewport.focus());
+ setInlineOverflow(viewport, false);
+ expect(viewport).toHaveAttribute('tabindex', '-1');
+ expect(document.activeElement).toBe(viewport);
+
+ // No focusout arrives either, so only the next measurement can notice.
+ void act(() => viewport.blur());
+ expect(viewport).toHaveAttribute('tabindex', '-1');
+ void act(() => window.dispatchEvent(new Event('resize')));
+ flushFrame();
+ expect(viewport).not.toHaveAttribute('tabindex');
+ });
+
+ it.each([
+ ['inline', {scrollWidth: 180}],
+ ['block', {scrollHeight: 180}],
+ ] as const)(
+ 'does not commit for a focus change or the next measurement while the %s axis scrolls',
+ (axis, overflowingGeometry) => {
+ const onCommit = vi.fn();
+ function CountedFixture() {
+ const area = useScrollableArea({
+ axis,
+ keyboardAccess: {owner: 'viewport', label: 'Counted results'},
+ });
+ return (
+ <div data-testid="counted" {...area.getViewportProps()}>
+ <div {...area.getContentProps()} />
+ </div>
+ );
+ }
+
+ render(
+ <Profiler id="counted" onRender={onCommit}>
+ <CountedFixture />
+ </Profiler>,
+ );
+ const viewport = screen.getByTestId('counted');
+ makeMeasurable(viewport);
+ setGeometry(viewport, overflowingGeometry);
+ void act(() => viewport.dispatchEvent(new Event('scroll')));
+ flushFrame();
+ expect(viewport).toHaveAttribute('tabindex', '0');
+ const remeasure = () => {
+ void act(() => window.dispatchEvent(new Event('resize')));
+ flushFrame();
+ };
+ remeasure();
+ onCommit.mockClear();
+
+ void act(() => viewport.focus());
+ expect(document.activeElement).toBe(viewport);
+ remeasure();
+ void act(() => viewport.blur());
+ remeasure();
+ expect(onCommit).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each([
+ ['inline', 'block', {scrollWidth: 180}],
+ ['block', 'inline', {scrollHeight: 180}],
+ ] as const)(
+ 'keeps the tabindex of a focused viewport when its scrolling %s axis is dropped',
+ (_scrollingAxis, nextAxis, overflowingGeometry) => {
+ const {rerender} = render(<Fixture axis="both" />);
+ const viewport = screen.getByTestId('viewport');
+ makeMeasurable(viewport);
+ setGeometry(viewport, overflowingGeometry);
+ void act(() => viewport.dispatchEvent(new Event('scroll')));
+ flushFrame();
+ expect(viewport).toHaveAttribute('tabindex', '0');
+ void act(() => viewport.focus());
+ const removeAttribute = vi.spyOn(viewport, 'removeAttribute');
+
+ // The first commit renders before the new axis is measured. Dropping
+ // the tabindex there blurs the viewport in Chromium.
+ rerender(<Fixture axis={nextAxis} />);
+
+ expect(removeAttribute).not.toHaveBeenCalledWith('tabindex');
+ expect(viewport).toHaveAttribute('tabindex', '-1');
+ expect(document.activeElement).toBe(viewport);
+ },
+ );
+
+ it('drops the tabindex of an unfocused viewport after an axis change', () => {
+ const {rerender} = render(<Fixture axis="both" />);
+ const viewport = screen.getByTestId('viewport');
+ makeMeasurable(viewport);
+ setInlineOverflow(viewport, true);
+ expect(viewport).toHaveAttribute('tabindex', '0');
+
+ rerender(<Fixture axis="block" />);
+
+ expect(viewport).not.toHaveAttribute('tabindex');
+ });
+
+ it('keeps tracking focus when the caller passes a fresh ref every render', () => {
+ const {rerender} = render(<Fixture externalRef={() => {}} />);
+ const viewport = screen.getByTestId('viewport');
+ makeMeasurable(viewport);
+ setGeometry(viewport, {scrollWidth: 180});
+ void act(() => viewport.dispatchEvent(new Event('scroll')));
+ flushFrame();
+
+ void act(() => viewport.focus());
+ setGeometry(viewport, {scrollWidth: 100});
+ void act(() => viewport.dispatchEvent(new Event('scroll')));
+ flushFrame();
+ expect(viewport).toHaveAttribute('tabindex', '-1');
+
+ const removeListener = vi.spyOn(viewport, 'removeEventListener');
+ rerender(<Fixture externalRef={() => {}} />);
+ expect(viewport).toHaveAttribute('tabindex', '-1');
+ // Reattaching releases the previous listeners so they cannot pile up.
+ expect(removeListener).toHaveBeenCalledWith(
+ 'focusin',
+ expect.any(Function),
+ );
+ expect(removeListener).toHaveBeenCalledWith(
+ 'focusout',
+ expect.any(Function),
+ );
+
+ void act(() => viewport.blur());
+ expect(viewport).not.toHaveAttribute('tabindex');
+ });
+
+ it('keeps one focus listener pair and working tracking through StrictMode replay', () => {
+ const focusListeners = recordFocusListeners();
+ const {unmount} = render(
+ <StrictMode>
+ <Fixture />
+ </StrictMode>,
+ );
+ const viewport = screen.getByTestId('viewport');
+ expect(focusListeners()).toEqual([
+ 'add focusin viewport',
+ 'add focusout viewport',
+ 'remove focusin viewport',
+ 'remove focusout viewport',
+ 'add focusin viewport',
+ 'add focusout viewport',
+ ]);
+
+ makeMeasurable(viewport);
+ setInlineOverflow(viewport, true);
+ void act(() => viewport.focus());
+ setInlineOverflow(viewport, false);
+ expect(viewport).toHaveAttribute('tabindex', '-1');
+ void act(() => viewport.blur());
+ expect(viewport).not.toHaveAttribute('tabindex');
+
+ unmount();
+ expect(focusListeners().slice(-2)).toEqual([
+ 'remove focusin viewport',
+ 'remove focusout viewport',
+ ]);
+ });
+
+ it('cleans up the old node before attaching the new one when the viewport is replaced in one commit', () => {
+ function KeyedFixture({nodeKey}: {nodeKey: string}) {
+ const area = useScrollableArea({
+ axis: 'inline',
+ keyboardAccess: {owner: 'viewport', label: 'Keyed results'},
+ });
+ return (
+ <>
+ <div
+ key={nodeKey}
+ data-testid={nodeKey}
+ {...area.getViewportProps()}
+ />
+ {/* Outside the viewport, so it survives the replacement. */}
+ <div {...area.getContentProps()} />
+ <output data-testid="retained-tab-index">
+ {String(area.getViewportProps().tabIndex)}
+ </output>
+ </>
+ );
+ }
+
+ const {rerender} = render(<KeyedFixture nodeKey="old" />);
+ const viewport = screen.getByTestId('old');
+ makeMeasurable(viewport);
+ setInlineOverflow(viewport, true);
+ void act(() => viewport.focus());
+ setInlineOverflow(viewport, false);
+ expect(screen.getByTestId('retained-tab-index')).toHaveTextContent('-1');
+
+ const focusListeners = recordFocusListeners();
+ rerender(<KeyedFixture nodeKey="new" />);
+
+ expect(focusListeners()).toEqual([
+ 'remove focusin old',
+ 'remove focusout old',
+ 'add focusin new',
+ 'add focusout new',
+ ]);
+ expect(screen.getByTestId('retained-tab-index')).toHaveTextContent(
+ 'undefined',
+ );
+ expect(getRegisteredScrollOwnerState(viewport)).toBeUndefined();
+ expect(
+ getRegisteredScrollOwnerState(screen.getByTestId('new')),
+ ).toBeDefined();
+ });
+
+ it('stops tracking a viewport that detaches while the hook stays mounted', () => {
+ function DetachableFixture({isAttached}: {isAttached: boolean}) {
+ const area = useScrollableArea({
+ axis: 'inline',
+ keyboardAccess: {owner: 'viewport', label: 'Detachable results'},
+ });
+ return (
+ <>
+ {isAttached ? (
+ <div data-testid="detachable" {...area.getViewportProps()} />
+ ) : null}
+ {/* Outside the viewport, so only its own detach can clear the state. */}
+ <div {...area.getContentProps()} />
+ <output data-testid="retained-tab-index">
+ {String(area.getViewportProps().tabIndex)}
+ </output>
+ </>
+ );
+ }
+
+ const {rerender} = render(<DetachableFixture isAttached />);
+ const viewport = screen.getByTestId('detachable');
+ const retainedTabIndex = screen.getByTestId('retained-tab-index');
+ makeMeasurable(viewport);
+ setGeometry(viewport, {scrollWidth: 180});
+ void act(() => viewport.dispatchEvent(new Event('scroll')));
+ flushFrame();
+ void act(() => viewport.focus());
+ setGeometry(viewport, {scrollWidth: 100});
+ void act(() => viewport.dispatchEvent(new Event('scroll')));
+ flushFrame();
+ expect(retainedTabIndex).toHaveTextContent('-1');
+ expect(getRegisteredScrollOwnerState(viewport)).toBeDefined();
+
+ rerender(<DetachableFixture isAttached={false} />);
+ expect(getRegisteredScrollOwnerState(viewport)).toBeUndefined();
+ expect(retainedTabIndex).toHaveTextContent('undefined');
+
+ // The old node's listeners are gone, so focusing it again changes nothing.
+ document.body.append(viewport);
+ try {
+ void act(() => viewport.focus());
+ expect(retainedTabIndex).toHaveTextContent('undefined');
+ } finally {
+ viewport.remove();
+ }
+
+ rerender(<DetachableFixture isAttached />);
+ const replacement = screen.getByTestId('detachable');
+ expect(replacement).not.toBe(viewport);
+ expect(getRegisteredScrollOwnerState(replacement)).toBeDefined();
+ expect(getRegisteredScrollOwnerState(viewport)).toBeUndefined();
+ });
+
it('composes caller refs and handlers without losing behavior', () => {
const externalRef = vi.fn();
const onScroll = vi.fn();
@@ -911,4 +1393,173 @@ describe('useScrollableArea', () => {
expect(findNearestScrollOwner(descendant, 'block')).toBe(outer);
expect(findNearestScrollOwner(descendant, 'inline')).toBeNull();
});
+
+ it('resolves the nearest of two nested block owners and unregisters both on unmount', () => {
+ function DoubleBlockFixture() {
+ const outer = useScrollableArea({
+ axis: 'block',
+ keyboardAccess: {owner: 'content'},
+ });
+ const inner = useScrollableArea({
+ axis: 'block',
+ keyboardAccess: {owner: 'content'},
+ });
+ return (
+ <div
+ data-testid="outer-owner"
+ {...outer.getViewportProps({style: {overflowY: 'auto'}})}>
+ <div {...outer.getContentProps()}>
+ <div
+ data-testid="inner-owner"
+ {...inner.getViewportProps({style: {overflowY: 'auto'}})}>
+ <div {...inner.getContentProps()}>
+ <span data-testid="deep-descendant" />
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+ }
+
+ const {unmount} = render(<DoubleBlockFixture />);
+ const outer = screen.getByTestId('outer-owner');
+ const inner = screen.getByTestId('inner-owner');
+ const descendant = screen.getByTestId('deep-descendant');
+ makeMeasurable(outer);
+ makeMeasurable(inner);
+ setGeometry(outer, {scrollHeight: 240});
+ setGeometry(inner, {scrollHeight: 300});
+
+ void act(() => {
+ outer.dispatchEvent(new Event('scroll'));
+ inner.dispatchEvent(new Event('scroll'));
+ });
+ flushFrame();
+
+ expect(findNearestScrollOwner(descendant, 'block')).toBe(inner);
+
+ unmount();
+ expect(getRegisteredScrollOwnerState(inner)).toBeUndefined();
+ expect(getRegisteredScrollOwnerState(outer)).toBeUndefined();
+ });
+
+ it('composes caller content props and consumes content xstyle', () => {
+ const contentRef = vi.fn();
+ const onClick = vi.fn();
+ function ContentFixture() {
+ const area = useScrollableArea({
+ axis: 'inline',
+ keyboardAccess: {owner: 'content'},
+ });
+ return (
+ <div {...area.getViewportProps({style: {overflowX: 'auto'}})}>
+ <div
+ data-testid="styled-content"
+ {...area.getContentProps<HTMLDivElement>({
+ ref: contentRef,
+ onClick,
+ className: 'consumer-content',
+ style: {color: 'red'},
+ xstyle: [
+ testStyles.viewport,
+ testStyles.contentMinWidth('120px'),
+ ],
+ })}>
+ Content
+ </div>
+ </div>
+ );
+ }
+
+ render(<ContentFixture />);
+ const content = screen.getByTestId('styled-content');
+ expect(content).not.toHaveAttribute('xstyle');
+ expect(content).toHaveClass('consumer-content');
+ const expectedClasses = (stylex.props(testStyles.viewport).className ?? '')
+ .split(' ')
+ .filter(Boolean);
+ expect(expectedClasses.length).toBeGreaterThan(0);
+ for (const token of expectedClasses) {
+ expect(content).toHaveClass(token);
+ }
+ expect(content.style.color).toBe('red');
+ expect(content.getAttribute('style')).toContain('120px');
+ expect(content).toHaveAttribute('data-scroll-content');
+ content.click();
+ expect(onClick).toHaveBeenCalledTimes(1);
+ expect(contentRef).toHaveBeenCalledWith(content);
+ });
+
+ it('preserves the last valid state through a full measurement while the viewport has no box', () => {
+ render(<Fixture />);
+ const viewport = screen.getByTestId('viewport');
+ makeMeasurable(viewport);
+ setGeometry(viewport, {scrollWidth: 180, scrollLeft: 40});
+ void act(() => viewport.dispatchEvent(new Event('scroll')));
+ flushFrame();
+ expect(state().inline).toEqual({
+ isScrollable: true,
+ atStart: false,
+ atEnd: false,
+ });
+
+ // A display:none box reads zero for every metric and fires no scroll; the
+ // full measurement must keep the last valid state rather than publish
+ // fitting.
+ setGeometry(viewport, {
+ clientWidth: 0,
+ clientHeight: 0,
+ scrollWidth: 0,
+ scrollHeight: 0,
+ scrollLeft: 0,
+ });
+ void act(() => window.dispatchEvent(new Event('resize')));
+ expect(frames).toHaveLength(1);
+ flushFrame();
+ expect(state().inline).toEqual({
+ isScrollable: true,
+ atStart: false,
+ atEnd: false,
+ });
+ });
+
+ it('coalesces repeated invalidations into one animation frame', () => {
+ render(<Fixture />);
+ const viewport = screen.getByTestId('viewport');
+ makeMeasurable(viewport);
+ setGeometry(viewport, {scrollWidth: 180});
+
+ void act(() => {
+ viewport.dispatchEvent(new Event('scroll'));
+ viewport.dispatchEvent(new Event('scroll'));
+ window.dispatchEvent(new Event('resize'));
+ });
+ expect(frames).toHaveLength(1);
+ });
+
+ it('keeps behavior-owned accessibility over conflicting caller props', () => {
+ function ConflictFixture() {
+ const area = useScrollableArea({
+ axis: 'inline',
+ keyboardAccess: {owner: 'viewport', label: 'Owned name'},
+ });
+ return (
+ <div
+ data-testid="conflict-viewport"
+ {...area.getViewportProps<HTMLDivElement>({
+ role: 'list',
+ 'aria-label': 'Caller name',
+ tabIndex: 5,
+ })}>
+ <div {...area.getContentProps()}>Content</div>
+ </div>
+ );
+ }
+
+ render(<ConflictFixture />);
+ const viewport = screen.getByTestId('conflict-viewport');
+ expect(viewport).toHaveAttribute('role', 'group');
+ expect(viewport).toHaveAccessibleName('Owned name');
+ expect(viewport).not.toHaveAttribute('tabindex');
+ });
});
diff --git a/packages/core/src/hooks/useScrollableArea.ts b/packages/core/src/hooks/useScrollableArea.ts
index 5f047fea2a..7e54dadb35 100644
--- a/packages/core/src/hooks/useScrollableArea.ts
+++ b/packages/core/src/hooks/useScrollableArea.ts
@@ -48,10 +48,17 @@ import {
unregisterScrollOwner,
} from './scrollOwnerRegistry';
+/** Logical axis or axes where native scrolling is requested. */
export type ScrollAxis = 'inline' | 'block' | 'both';
+/** Whether effective axes pass scroll gestures to ancestors at an edge. */
export type ScrollOverscroll = 'allow' | 'contain';
+/** Whether a fitting viewport deliberately remains a Sticky containing boundary. */
export type ScrollStickyContainment = 'whenScrollable' | 'always';
+/**
+ * Where keyboard scrolling is reached: caller-owned content, a named viewport,
+ * or a named viewport that delegates forward Tab entry into its content.
+ */
export type ScrollKeyboardAccess =
| {owner: 'content'}
| {owner: 'viewport'; label: string; role?: 'group' | 'region'}
@@ -61,21 +68,27 @@ export type ScrollKeyboardAccess =
role?: 'group' | 'region';
};
+/** Effective ownership and logical edge state for one requested axis. */
export interface ScrollAxisState {
isScrollable: boolean;
atStart: boolean;
atEnd: boolean;
}
+/** Per-axis effective scroll state published by the hook. */
export interface ScrollableAreaState {
inline: ScrollAxisState;
block: ScrollAxisState;
}
export interface UseScrollableAreaOptions {
+ /** Logical axis or axes where scrolling is allowed. */
axis: ScrollAxis;
+ /** Keyboard reachability owner; a named viewport joins the tab order while effective. */
keyboardAccess: ScrollKeyboardAccess;
+ /** Edge propagation on effective axes. @default 'allow' */
overscroll?: ScrollOverscroll;
+ /** Sticky containment while fitting. @default 'whenScrollable' */
stickyContainment?: ScrollStickyContainment;
}
@@ -238,6 +251,19 @@ function useStableComposedRef(
* 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.
+ *
+ * @example
+ * ```
+ * const {getViewportProps, getContentProps, state} = useScrollableArea({
+ * axis: 'block',
+ * keyboardAccess: {owner: 'viewport', label: 'Activity history'},
+ * });
+ * return (
+ * <div {...getViewportProps({xstyle: styles.viewport})}>
+ * <div {...getContentProps()}>{children}</div>
+ * </div>
+ * );
+ * ```
*/
export function useScrollableArea({
axis,
@@ -251,11 +277,36 @@ export function useScrollableArea({
const [overflow, setOverflow] =
useState<LogicalOverflowGeometry>(INITIAL_OVERFLOW);
const [mapping, setMapping] = useState<LogicalAxisMapping>(INITIAL_MAPPING);
+ const [isViewportFocused, setViewportFocused] = useState(false);
const stateRef = useRef<ScrollableAreaState>(INITIAL_STATE);
const measureRef = useRef<(() => void) | null>(null);
const viewportRef = useCallback((node: HTMLElement | null) => {
setViewport(current => (current === node ? current : node));
+ if (node == null) {
+ return;
+ }
+ const syncFocus = () => {
+ // Only a viewport with no scrollable axis reads this state, and the
+ // measurement that ends its scrolling reads focus again, so a scrollable
+ // one can skip the render.
+ const {inline, block} = stateRef.current;
+ if (inline.isScrollable || block.isScrollable) {
+ return;
+ }
+ setViewportFocused(node.ownerDocument.activeElement === node);
+ };
+ syncFocus();
+ node.addEventListener('focusin', syncFocus);
+ node.addEventListener('focusout', syncFocus);
+ // React runs this cleanup instead of calling the ref with null, so the
+ // viewport state has to clear here as well.
+ return () => {
+ node.removeEventListener('focusin', syncFocus);
+ node.removeEventListener('focusout', syncFocus);
+ setViewportFocused(false);
+ setViewport(null);
+ };
}, []);
const contentRef = useCallback((node: HTMLElement | null) => {
setContent(current => (current === node ? current : node));
@@ -320,6 +371,13 @@ export function useScrollableArea({
return;
}
+ // Focus events do not always reach the viewport (Chromium fires none
+ // while the page lacks system focus), and this commit may drop the tab
+ // stop that keeps focus here. A scrollable viewport never reads it.
+ if (!inline.isScrollable && !block.isScrollable) {
+ setViewportFocused(viewport.ownerDocument.activeElement === viewport);
+ }
+
const nextOverflow = {
inline: inlineOverflow,
block: blockOverflow,
@@ -623,12 +681,13 @@ export function useScrollableArea({
),
),
) as ScrollableElementProps<E>;
- const viewportIsKeyboardOwner = keyboardAccess.owner !== 'content';
- const keepsProgrammaticFocus =
- (!viewportIsKeyboardOwner || !hasEffectiveAxis) &&
- viewport != null &&
- typeof document !== 'undefined' &&
- document.activeElement === viewport;
+ // Focus state is stale while an axis scrolls, so until an axis change is
+ // measured, the last measured scrolling keeps a focused viewport's
+ // tabindex. Dropping it there blurs the viewport in Chromium.
+ const mayHoldFocus =
+ isViewportFocused ||
+ measured.inline.isScrollable ||
+ measured.block.isScrollable;
const behaviorStyle: CSSProperties = {...styledProps.style};
const containInline =
overscroll === 'contain' && state.inline.isScrollable;
@@ -652,12 +711,7 @@ export function useScrollableArea({
? {
role: keyboardAccess.role ?? 'group',
'aria-label': keyboardAccess.label,
- tabIndex:
- viewportIsKeyboardOwner && hasEffectiveAxis
- ? 0
- : keepsProgrammaticFocus
- ? -1
- : undefined,
+ tabIndex: hasEffectiveAxis ? 0 : mayHoldFocus ? -1 : undefined,
}
: {};
@@ -681,13 +735,14 @@ export function useScrollableArea({
[
axis,
getComposedViewportRef,
+ isViewportFocused,
keyboardAccess,
mapping,
+ measured,
overflow,
overscroll,
state,
stickyContainment,
- viewport,
],
);
@@ -695,9 +750,14 @@ export function useScrollableArea({
<E extends HTMLElement>(
props: ScrollableElementProps<E> = {},
): ScrollableElementProps<E> => {
+ const {xstyle, ...domProps} = props;
+ const styledProps = mergeProps(
+ domProps,
+ stylex.props(xstyle),
+ ) as ScrollableElementProps<E>;
const result: ScrollableElementProps<E> = {
- ...props,
- ref: getComposedContentRef(props.ref),
+ ...styledProps,
+ ref: getComposedContentRef(styledProps.ref),
'data-scroll-content': '',
};
return result;