An open source design system that's fully customizable and agent ready
TypeScript
fix(useScrollableArea): a viewport is a tab stop from the first frame its content overflows (#8388)
Cindy Zhang3353ab581884
diff --git a/.changeset/scrollable-area-first-frame-tab-stop.md b/.changeset/scrollable-area-first-frame-tab-stop.mdnew file mode 100644index 0000000000..e7e91345cf--- /dev/null+++ b/.changeset/scrollable-area-first-frame-tab-stop.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] A scroll viewport that owns keyboard access (`ScrollableArea`, and the Table, CodeBlock, BottomSheet and Schedule viewports built on the same hook) is a tab stop from the first frame its content overflows. Content that arrived already overflowing, such as loaded data replacing a loading state, used to scroll for at least one animation frame, and longer on a busy page, before the viewport joined the tab order. During that time a keyboard user could not reach it and an accessibility audit reported `scrollable-region-focusable`.++@cixzhangdiff --git a/packages/core/src/hooks/useScrollableArea.test.tsx b/packages/core/src/hooks/useScrollableArea.test.tsxindex 0cf48a5767..df29307d7f 100644--- a/packages/core/src/hooks/useScrollableArea.test.tsx+++ b/packages/core/src/hooks/useScrollableArea.test.tsx@@ -113,6 +113,38 @@ function makeMeasurable(viewport: HTMLElement) {});}+/**+ * As in a browser, the computed overflow is the one the hook writes: an axis is+ * `clip` until the hook lets it scroll. `writingMode` reads the current mode.+ */+function mockOwnedComputedStyle(+ writingMode: () => string = () => 'horizontal-tb',+) {+ vi.mocked(window.getComputedStyle).mockImplementation(element => {+ const owned = (axis: 'X' | 'Y') =>+ element+ .getAttribute('style')+ ?.match(new RegExp(`--x-overflow${axis}:\\s*(\\w+)`))?.[1] ?? 'visible';+ return new Proxy({} as CSSStyleDeclaration, {+ get(_target, property) {+ if (property === 'overflowX') {+ return owned('X');+ }+ if (property === 'overflowY') {+ return owned('Y');+ }+ if (property === 'writingMode') {+ return writingMode();+ }+ if (property === 'direction') {+ return 'ltr';+ }+ return property === 'display' ? 'block' : '';+ },+ });+ });+}+describe('useScrollableArea', () => {let frames: FrameRequestCallback[];@@ -179,6 +211,133 @@ describe('useScrollableArea', () => {expect(viewport.getAttribute('style')).toContain('clip');});+ it('is a tab stop from the first frame its content overflows, before any animation frame (AST-025 FR12)', () => {+ mockOwnedComputedStyle();+ // Content that is already taller than the viewport when it mounts, such+ // as loaded data replacing a loading fallback.+ const extent = (value: number, scrolled: number) =>+ function (this: HTMLElement) {+ return this.dataset.testid === 'viewport' ? scrolled : value;+ };+ vi.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockImplementation(+ extent(100, 100),+ );+ vi.spyOn(HTMLElement.prototype, 'clientHeight', 'get').mockImplementation(+ extent(100, 100),+ );+ vi.spyOn(HTMLElement.prototype, 'scrollWidth', 'get').mockImplementation(+ extent(100, 100),+ );+ vi.spyOn(HTMLElement.prototype, 'scrollHeight', 'get').mockImplementation(+ extent(100, 180),+ );++ render(<Fixture axis="block" />);+ const viewport = screen.getByTestId('viewport');++ // No animation frame has run.+ expect(viewport.getAttribute('style')).toContain('--x-overflowY: auto');+ expect(viewport).toHaveAttribute('tabindex', '0');+ expect(state().block.isScrollable).toBe(true);+ });++ it('settles content that fits only once a scrollbar takes space, without looping in one commit (AST-025 FR7)', () => {+ mockOwnedComputedStyle();+ // Under `clip` the content is 105 tall and overflows; under `auto` its+ // scrollbar narrows it and it fits (a 16:9 child at full width).+ const viewportOverflowY = (element: HTMLElement) =>+ element.getAttribute('style')?.match(/--x-overflowY:\s*(\w+)/)?.[1];+ vi.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockReturnValue(100);+ vi.spyOn(HTMLElement.prototype, 'clientHeight', 'get').mockReturnValue(100);+ vi.spyOn(HTMLElement.prototype, 'scrollWidth', 'get').mockReturnValue(100);+ vi.spyOn(HTMLElement.prototype, 'scrollHeight', 'get').mockImplementation(+ function (this: HTMLElement) {+ return this.dataset.testid === 'viewport' &&+ viewportOverflowY(this) !== 'auto'+ ? 105+ : 100;+ },+ );++ expect(() => render(<Fixture axis="block" />)).not.toThrow();+ // At most one flip per animation frame, as before.+ expect(() => flushFrame()).not.toThrow();+ expect(() => flushFrame()).not.toThrow();+ });++ it('leaves one frame pending after an overflowing mount, and none after unmount (AST-025 FR7)', async () => {+ mockOwnedComputedStyle();+ const pending = new Set<number>();+ let nextId = 0;+ vi.stubGlobal(+ 'requestAnimationFrame',+ vi.fn(() => {+ nextId += 1;+ pending.add(nextId);+ return nextId;+ }),+ );+ vi.stubGlobal(+ 'cancelAnimationFrame',+ vi.fn((id: number) => pending.delete(id)),+ );+ const extent = (fits: number, viewport: number) =>+ function (this: HTMLElement) {+ return this.dataset.testid === 'viewport' ? viewport : fits;+ };+ vi.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockReturnValue(100);+ vi.spyOn(HTMLElement.prototype, 'clientHeight', 'get').mockReturnValue(100);+ vi.spyOn(HTMLElement.prototype, 'scrollWidth', 'get').mockReturnValue(100);+ vi.spyOn(HTMLElement.prototype, 'scrollHeight', 'get').mockImplementation(+ extent(100, 180),+ );++ const {unmount} = render(<Fixture axis="block" />);+ // Let the style change reach the MutationObserver.+ await act(async () => {});+ expect(screen.getByTestId('viewport')).toHaveAttribute('tabindex', '0');+ expect(pending.size).toBe(1);++ unmount();+ expect(pending.size).toBe(0);+ });++ it('keeps the tab stop through a writing-mode change that moves the overflowing axis', async () => {+ let isVertical = false;+ mockOwnedComputedStyle(() =>+ isVertical ? 'vertical-rl' : 'horizontal-tb',+ );+ // The content overflows the block axis in either mode: physical y while+ // horizontal, physical x once vertical.+ const viewportExtent = (axis: 'x' | 'y') =>+ function (this: HTMLElement) {+ if (this.dataset.testid !== 'viewport') {+ return 100;+ }+ return (axis === 'x') === isVertical ? 180 : 100;+ };+ vi.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockReturnValue(100);+ vi.spyOn(HTMLElement.prototype, 'clientHeight', 'get').mockReturnValue(100);+ vi.spyOn(HTMLElement.prototype, 'scrollWidth', 'get').mockImplementation(+ viewportExtent('x'),+ );+ vi.spyOn(HTMLElement.prototype, 'scrollHeight', 'get').mockImplementation(+ viewportExtent('y'),+ );++ render(<Fixture axis="block" />);+ const viewport = screen.getByTestId('viewport');+ expect(viewport).toHaveAttribute('tabindex', '0');++ isVertical = true;+ await act(async () => {+ viewport.parentElement!.setAttribute('dir', 'ltr');+ });+ flushFrame();+ expect(viewport.getAttribute('style')).toContain('--x-overflowX: auto');+ expect(viewport).toHaveAttribute('tabindex', '0');+ });+it('owns fitting and explicit Sticky overflow styling for direct adopters', () => {const {rerender} = render(<Fixture />);const viewport = screen.getByTestId('viewport');diff --git a/packages/core/src/hooks/useScrollableArea.ts b/packages/core/src/hooks/useScrollableArea.tsindex 1b4236ace6..e3803e8fc9 100644--- a/packages/core/src/hooks/useScrollableArea.ts+++ b/packages/core/src/hooks/useScrollableArea.ts@@ -200,6 +200,7 @@ export function useScrollableArea({useState<LogicalOverflowGeometry>(INITIAL_OVERFLOW);const [mapping, setMapping] = useState<LogicalAxisMapping>(INITIAL_MAPPING);const stateRef = useRef<ScrollableAreaState>(INITIAL_STATE);+ const measureRef = useRef<(() => void) | null>(null);const viewportRef = useCallback((node: HTMLElement | null) => {setViewport(current => (current === node ? current : node));@@ -218,8 +219,10 @@ export function useScrollableArea({let frame: number | null = null;let isActive = true;- const measure = () => {- frame = null;+ // Measures now; `measure` is the frame callback that also clears the+ // pending frame. The same-commit remeasure below calls this one, so a frame+ // already scheduled stays the only pending one.+ const measureNow = () => {const computedStyle = getComputedStyle(viewport);const nextMapping = getLogicalAxisMapping(computedStyle.writingMode,@@ -256,20 +259,26 @@ export function useScrollableArea({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+ // Measured DOM geometry decides 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+ // The 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+ // A writing-mode change remaps the behavior-owned physical CSS.setMapping(current =>mappingsEqual(current, nextMapping) ? current : nextMapping,);};+ const measure = () => {+ frame = null;+ measureNow();+ };+const scheduleMeasure = () => {if (!isActive || frame != null) {return;@@ -278,6 +287,7 @@ export function useScrollableArea({};registerScrollOwner(viewport, stateRef.current);+ measureRef.current = measureNow;measure();const stopObservingViewport = observeResize(viewport, scheduleMeasure);const stopObservingContent = observeResize(content, scheduleMeasure);@@ -323,6 +333,7 @@ export function useScrollableArea({return () => {isActive = false;+ measureRef.current = null;unregisterScrollOwner(viewport);stopObservingViewport();stopObservingContent();@@ -342,6 +353,29 @@ export function useScrollableArea({};}, [axis, content, viewport]);+ // The first measure reads the viewport before this hook has let an+ // overflowing axis scroll (it is `clip` until then), so it finds overflow+ // but no scrollable axis yet. Measure again in the same commit once an axis+ // has just gained overflow (or the axis mapping changed), so the viewport is+ // a tab stop from the first frame it scrolls, not an animation frame later+ // (`spec:AST-025` FR12). Only on a gain: content that fits only once a+ // scrollbar takes space would otherwise flip overflow back and forth inside+ // one commit; a loss waits for the next frame, as before.+ const previousOverflowRef = useRef<LogicalOverflowGeometry>(INITIAL_OVERFLOW);+ const previousMappingRef = useRef<LogicalAxisMapping>(INITIAL_MAPPING);+ useIsomorphicLayoutEffect(() => {+ const previous = previousOverflowRef.current;+ const hasGainedOverflow =+ (overflow.inline && !previous.inline) ||+ (overflow.block && !previous.block);+ const hasRemapped = mapping !== previousMappingRef.current;+ previousOverflowRef.current = overflow;+ previousMappingRef.current = mapping;+ if (hasGainedOverflow || hasRemapped) {+ measureRef.current?.();+ }+ }, [overflow, mapping]);+const state = useMemo<ScrollableAreaState>(() => ({inline: axisIsRequested(axis, 'inline')