An open source design system that's fully customizable and agent ready
TypeScript
fix(Collapsible): focus inside closing content moves to the trigger (#9250)
Cindy Zhang8c8f0dac6629
diff --git a/.changeset/collapsible-close-keeps-focus.md b/.changeset/collapsible-close-keeps-focus.mdnew file mode 100644index 0000000000..1ff0a4c541--- /dev/null+++ b/.changeset/collapsible-close-keeps-focus.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] When a `Collapsible` closes while keyboard focus is inside its content, for example from an owner-set `isOpen` or a group's value, focus moves to its trigger. Before, focus fell to the page, so a keyboard or screen-reader user lost their place (WCAG 2.2 SC 2.4.3). Focus anywhere else is not moved.++@cixzhang @duytbpdiff --git a/apps/storybook/stories/Collapsible.stories.tsx b/apps/storybook/stories/Collapsible.stories.tsxindex a272fbf767..3593d98cbd 100644--- a/apps/storybook/stories/Collapsible.stories.tsx+++ b/apps/storybook/stories/Collapsible.stories.tsx@@ -1,9 +1,10 @@// Copyright (c) Meta Platforms, Inc. and affiliates.-import {useState} from 'react';+import {useEffect, useState} from 'react';import type {Meta, StoryObj} from '@storybook/react';import * as stylex from '@stylexjs/stylex';import {Collapsible, CollapsibleGroup} from '@astryxdesign/core/Collapsible';+import {Button} from '@astryxdesign/core/Button';import {Card} from '@astryxdesign/core/Card';import {VStack} from '@astryxdesign/core/Layout';import {@@ -373,3 +374,38 @@ export const PressedState: Story = {</VStack>),};++// =============================================================================+// Close with focus inside (AR4)+// =============================================================================++/**+ * The app closes the Collapsible from a keyboard shortcut (`[`), which leaves+ * focus where it was. Focus on "Inside" moves to the trigger; focus elsewhere+ * stays put.+ */+function CloseFocusDemo() {+ const [isOpen, setIsOpen] = useState(true);+ useEffect(() => {+ const onKeyDown = (event: KeyboardEvent) => {+ if (event.key === '[') {+ setIsOpen(open => !open);+ }+ };+ document.addEventListener('keydown', onKeyDown);+ return () => document.removeEventListener('keydown', onKeyDown);+ }, []);+ return (+ <VStack gap={2}>+ <Collapsible trigger="Details" isOpen={isOpen} onOpenChange={setIsOpen}>+ <Button label="Inside" variant="secondary" />+ </Collapsible>+ <Button label="Elsewhere" variant="secondary" />+ </VStack>+ );+}++export const CloseFocus: Story = {+ name: 'Close Focus',+ render: () => <CloseFocusDemo />,+};diff --git a/docs/specs/components/Collapsible/Collapsible.spec.md b/docs/specs/components/Collapsible/Collapsible.spec.mdindex b374bebdb7..3d76cbacaf 100644--- a/docs/specs/components/Collapsible/Collapsible.spec.md+++ b/docs/specs/components/Collapsible/Collapsible.spec.md@@ -146,6 +146,11 @@ not parallel public names for this axis.- **AR3 — Direction remains understandable.** The collapsed leading cue MUST pointtoward the content in both LTR and RTL; it MUST NOT retain an LTR physicaldirection under RTL.+- **AR4 — Focus leaves closing content.** When the Collapsible closes while+ focus is inside its content, however it closes (an owner-set `isOpen`, a+ group's value), focus moves to its trigger, including while the content+ plays its exit (FR10). Focus anywhere else is not moved (WCAG 2.2 SC+ 2.4.3).## Design relationships@@ -198,14 +203,15 @@ to the Group container anatomy here.## Verification map-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |-| ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------- |-| FR1–FR5 | Collapsible prop/type, DOM-order, glyph/direction, and no-extra-values tests | omitted/end/start; collapsed/expanded; LTR/RTL | default changes, `start` follows the label, collapsed leading cue points outward, or an unsupported cue value is admitted | audit:Collapsible/public-api |-| FR6 | composed trigger layout and geometry tests | plain text; composed label with trailing content; start/end | label becomes shrink-wrapped/stranded or composed content cannot use remaining row | audit:Collapsible/layout |-| FR7–FR8, ORD1 | group inheritance, item override, and nested reset tests | group start/end; item override; nested omission | group value is ignored, item cannot override, or position leaks into nested content | audit:Collapsible/behavior |-| FR9, AR1–AR3, ORD2 | disclosure semantics via `DISCLOSURE_PATTERN`, plus component-owned chevron and real RTL rendering | collapsed/expanded; controlled/uncontrolled; enabled/disabled; start/end; LTR/RTL | position changes state behavior, the trigger loses its controlled-content relationship, content visibility diverges from state, accessible output duplicates, or leading direction fails to mirror | audit:Collapsible/accessibility |-| FR10 | `animatedLayoutAdopters.test.tsx` (with and without a handle; an owner-set `isOpen` and a group's controlled value glide; one measurement in StrictMode and none for a refused change; the exit kept inert until it ends) and `animatedLayoutAdopters.interaction.browser.spec.ts` (the `Core/Animated layout` story through a ScrollableArea ref, opening and closing) | no handle; a handle; click, owner-set, and group-driven changes; opening and closing | the content after it jumps with a handle, an owner-set change lands at once, closing content vanishes before its exit or stays reachable during it, or anything changes without a handle | audit:Collapsible/behavior |-| Theming anatomy | focused target-reflection assertions plus `themingTargets.test.ts` | standalone/grouped; open/closed; enabled/disabled; start/end; divided/density | a style-driving axis or state disappears from its owning target, a target loses its anatomy owner, or the chevron stops delegating to Icon | audit:Collapsible/theming |+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |+| ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------- |+| FR1–FR5 | Collapsible prop/type, DOM-order, glyph/direction, and no-extra-values tests | omitted/end/start; collapsed/expanded; LTR/RTL | default changes, `start` follows the label, collapsed leading cue points outward, or an unsupported cue value is admitted | audit:Collapsible/public-api |+| FR6 | composed trigger layout and geometry tests | plain text; composed label with trailing content; start/end | label becomes shrink-wrapped/stranded or composed content cannot use remaining row | audit:Collapsible/layout |+| FR7–FR8, ORD1 | group inheritance, item override, and nested reset tests | group start/end; item override; nested omission | group value is ignored, item cannot override, or position leaks into nested content | audit:Collapsible/behavior |+| FR9, AR1–AR3, ORD2 | disclosure semantics via `DISCLOSURE_PATTERN`, plus component-owned chevron and real RTL rendering | collapsed/expanded; controlled/uncontrolled; enabled/disabled; start/end; LTR/RTL | position changes state behavior, the trigger loses its controlled-content relationship, content visibility diverges from state, accessible output duplicates, or leading direction fails to mirror | audit:Collapsible/accessibility |+| FR10 | `animatedLayoutAdopters.test.tsx` (with and without a handle; an owner-set `isOpen` and a group's controlled value glide; one measurement in StrictMode and none for a refused change; the exit kept inert until it ends) and `animatedLayoutAdopters.interaction.browser.spec.ts` (the `Core/Animated layout` story through a ScrollableArea ref, opening and closing) | no handle; a handle; click, owner-set, and group-driven changes; opening and closing | the content after it jumps with a handle, an owner-set change lands at once, closing content vanishes before its exit or stays reachable during it, or anything changes without a handle | audit:Collapsible/behavior |+| AR4 | `Collapsible.test.tsx` close-focus suite; `animatedLayoutAdopters.test.tsx` close with focus inside during the exit; `CollapsibleCloseFocus.a11y.chromium.spec.ts` | Focus inside the content, owner-set close, with and without a handle; focus outside; the trigger closing it; opening | Focus left inside the hidden or inert content, on the page body, or moved when it was not inside the content fails. | `audit:Collapsible/accessibility` |+| Theming anatomy | focused target-reflection assertions plus `themingTargets.test.ts` | standalone/grouped; open/closed; enabled/disabled; start/end; divided/density | a style-driving axis or state disappears from its owning target, a target loses its anatomy owner, or the chevron stops delegating to Icon | audit:Collapsible/theming |## Decision logdiff --git a/packages/core/src/Collapsible/Collapsible.test.tsx b/packages/core/src/Collapsible/Collapsible.test.tsxindex 2426a0b88d..4d6e4745c7 100644--- a/packages/core/src/Collapsible/Collapsible.test.tsx+++ b/packages/core/src/Collapsible/Collapsible.test.tsx@@ -618,3 +618,52 @@ describe('pressed state', () => {expect(hasPressedArm(screen.getByRole('button'))).toBe(false);});});++describe('Collapsible close focus (AR4)', () => {+ function Example({isOpen}: {isOpen: boolean}) {+ return (+ <>+ <Collapsible trigger="Details" isOpen={isOpen} onOpenChange={() => {}}>+ <button type="button">Inside</button>+ </Collapsible>+ <button type="button">Elsewhere</button>+ </>+ );+ }++ it('moves focus inside the content to the trigger when it closes', () => {+ const {rerender} = render(<Example isOpen />);+ screen.getByRole('button', {name: 'Inside'}).focus();+ rerender(<Example isOpen={false} />);+ expect(screen.getByRole('button', {name: 'Details'})).toHaveFocus();+ });++ it('moves no focus that is outside the content', () => {+ const {rerender} = render(<Example isOpen />);+ const elsewhere = screen.getByRole('button', {name: 'Elsewhere'});+ elsewhere.focus();+ rerender(<Example isOpen={false} />);+ expect(elsewhere).toHaveFocus();+ });++ it('keeps focus on the trigger when the trigger closes it', async () => {+ const user = userEvent.setup();+ render(+ <Collapsible trigger="Details">+ <button type="button">Inside</button>+ </Collapsible>,+ );+ const trigger = screen.getByRole('button', {name: 'Details'});+ await user.click(trigger);+ expect(trigger).toHaveAttribute('aria-expanded', 'false');+ expect(trigger).toHaveFocus();+ });++ it('moves no focus when it opens', () => {+ const {rerender} = render(<Example isOpen={false} />);+ const elsewhere = screen.getByRole('button', {name: 'Elsewhere'});+ elsewhere.focus();+ rerender(<Example isOpen />);+ expect(elsewhere).toHaveFocus();+ });+});diff --git a/packages/core/src/Collapsible/Collapsible.tsx b/packages/core/src/Collapsible/Collapsible.tsxindex 411a414f10..ce2300bb91 100644--- a/packages/core/src/Collapsible/Collapsible.tsx+++ b/packages/core/src/Collapsible/Collapsible.tsx@@ -51,6 +51,14 @@ import {import {useCollapsible} from './useCollapsible';import {LayoutChangeSnapshot} from '../motion/LayoutChangeSnapshot';+import {+ moveFocusLeftBehind,+ noteFocusWithin,+ type FocusWithin,+} from '../utils/focusReturn';+import {useInteractionModalityTracking} from '../utils/interactionModality';+import {useFocusLeavingChange} from '../utils/useFocusLeavingChange';+import {useMergedRefs} from '../hooks/useMergedRefs';import {applyLayoutChangeTransition,holdLayoutExit,@@ -449,6 +457,29 @@ export function Collapsible({}}, [isOpen, isExiting]);+ // Focus inside the content when it closes would be lost to the page once+ // the content hides. It moves to the trigger that closes it (AR4); focus+ // anywhere else is not moved. The shared sequence notes it in the commit+ // before the DOM changes and moves it once the close has committed.+ // The trigger's own document's last input decides the moved focus's ring.+ const {ref: modalityRef} = useInteractionModalityTracking();+ const mergedTriggerRef = useMergedRefs(triggerRef, modalityRef);+ const noteClosingFocus = useFocusLeavingChange(+ isOpen,+ (wasOpen: boolean) =>+ wasOpen ? noteFocusWithin(contentRef.current) : null,+ (focus: FocusWithin) =>+ moveFocusLeftBehind(focus, triggerRef.current, contentRef.current),+ );+ const beforeOpenChange = useCallback(+ (wasOpen: boolean) => {+ noteClosingFocus(wasOpen);+ if (animatedLayout != null) {+ measureChange();+ }+ },+ [animatedLayout, measureChange, noteClosingFocus],+ );// Activation is blocked by this guard rather than the native `disabled`// attribute, so the trigger keeps `aria-disabled` semantics and stays// discoverable. A native `disabled` button would silently swallow events@@ -513,7 +544,7 @@ export function Collapsible({)}{...props}><button- ref={triggerRef}+ ref={mergedTriggerRef}type="button"onClick={handleToggle}aria-disabled={isDisabled || undefined}@@ -547,9 +578,7 @@ export function Collapsible({<span {...stylex.props(styles.triggerLabel)}>{trigger}</span>{!isChevronAtStart && chevron}</button>- {animatedLayout != null && (- <LayoutChangeSnapshot value={isOpen} onBeforeChange={measureChange} />- )}+ <LayoutChangeSnapshot value={isOpen} onBeforeChange={beforeOpenChange} /><divref={contentRef}id={contentId}diff --git a/packages/core/src/Collapsible/__tests__/CollapsibleCloseFocus.a11y.chromium.spec.ts b/packages/core/src/Collapsible/__tests__/CollapsibleCloseFocus.a11y.chromium.spec.tsnew file mode 100644index 0000000000..305bd008b7--- /dev/null+++ b/packages/core/src/Collapsible/__tests__/CollapsibleCloseFocus.a11y.chromium.spec.ts@@ -0,0 +1,63 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file CollapsibleCloseFocus.a11y.chromium.spec.ts+ * @input The built Storybook's `Core/Collapsible` "Close Focus" story: a+ * Collapsible its app closes from a `[` shortcut, with a button inside its+ * content and one outside it+ * @output Real-Chromium proof of `component:Collapsible` AR4: focus inside the+ * content when it closes moves to the trigger; focus elsewhere is not moved+ * @position Testing; the unit cases are in Collapsible.test.tsx and+ * motion/animatedLayoutAdopters.test.tsx+ *+ * SYNC: When modified, update the AR4 Verification row in Collapsible.spec.md.+ */++import {expect, test, type Page} from '@playwright/test';+import {+ DEFAULT_STORYBOOK_DIR,+ serveStorybook,+ type StaticServer,+} from '@astryxdesign/a11y-spec/storybook';++let storybook: StaticServer;++test.beforeAll(async () => {+ storybook = await serveStorybook(DEFAULT_STORYBOOK_DIR);+});++test.afterAll(async () => {+ await storybook?.close();+});++async function openStory(page: Page): Promise<void> {+ await page.goto(+ `${storybook.origin}/iframe.html?id=core-collapsible--close-focus&viewMode=story`,+ );+ await page.getByRole('button', {name: 'Inside'}).waitFor();+}++test('focus inside the content moves to the trigger when it closes', async ({+ page,+}) => {+ await openStory(page);+ await page.getByRole('button', {name: 'Inside'}).focus();+ await page.keyboard.press('[');++ const trigger = page.getByRole('button', {name: 'Details'});+ await expect(trigger).toHaveAttribute('aria-expanded', 'false');+ await expect(trigger).toBeFocused();+});++test('focus outside the content is not moved', async ({page}) => {+ await openStory(page);+ const elsewhere = page.getByRole('button', {name: 'Elsewhere'});+ await elsewhere.focus();+ await page.keyboard.press('[');++ await expect(page.getByRole('button', {name: 'Details'})).toHaveAttribute(+ 'aria-expanded',+ 'false',+ );+ await expect(elsewhere).toBeFocused();+});diff --git a/packages/core/src/SideNav/SideNav.tsx b/packages/core/src/SideNav/SideNav.tsxindex 31cb77302b..2eccebe216 100644--- a/packages/core/src/SideNav/SideNav.tsx+++ b/packages/core/src/SideNav/SideNav.tsx@@ -57,6 +57,7 @@ import {useTranslator} from '../i18n';import {useMergedRefs} from '../hooks/useMergedRefs';import {LayoutChangeSnapshot} from '../motion/LayoutChangeSnapshot';import {getFocusableElements} from '../hooks/useFocusTrap';+import {useFocusLeavingChange} from '../utils/useFocusLeavingChange';import {readAccessibleName} from '../utils/accessibleName';import {moveFocusLeftBehind,@@ -417,6 +418,19 @@ export interface SideNavProps extends BaseProps<HTMLElement> {// Component// =============================================================================+/** Where focus was before a collapse, as the move after it needs it. */+interface PendingRailFocus {+ focus: FocusWithin;+ /** Whether the rail keeps the row that held focus. */+ isRowKept: boolean;+ /** Kept rows before the row that held focus. */+ keptBefore: number;+ /** The name of the control outside the rows that held focus. */+ outside: {name: string} | null;+ /** Whether focus was on the collapse toggle. */+ wasOnToggle: boolean;+}+/*** Sidebar navigation container for application pages.*@@ -598,86 +612,77 @@ export function SideNav({[],);const resizeWrapperRef = useRef<HTMLDivElement>(null);- const pendingFocusRef = useRef<{- focus: FocusWithin;- /** Whether the rail keeps the row that held focus. */- isRowKept: boolean;- /** Kept rows before the row that held focus. */- keptBefore: number;- /** The name of the control outside the rows that held focus. */- outside: {name: string} | null;- /** Whether focus was on the collapse toggle. */- wasOnToggle: boolean;- } | null>(null);- const noteRailFocus = useCallback((wasCollapsed: boolean) => {- pendingFocusRef.current = null;- const nav = navRef.current;- // The resize handle sits beside the nav, in the resize wrapper, and goes- // with a collapse its Enter starts.- const focus = wasCollapsed- ? null- : (noteFocusWithin(nav) ?? noteFocusWithin(resizeWrapperRef.current));- if (focus == null || nav == null) {- return;- }- const rows = railRows(nav, rowsRef.current);- // The innermost row holding focus, the last in document order: a nested- // row's parent holds it too.- let index = -1;- rows.forEach((row, at) => {- if (row.contains(focus.element)) {- index = at;+ const noteRailFocus = useFocusLeavingChange(+ collapsed,+ (wasCollapsed: boolean): PendingRailFocus | null => {+ const nav = navRef.current;+ // The resize handle sits beside the nav, in the resize wrapper, and goes+ // with a collapse its Enter starts.+ const focus = wasCollapsed+ ? null+ : (noteFocusWithin(nav) ?? noteFocusWithin(resizeWrapperRef.current));+ if (focus == null || nav == null) {+ return null;}- });- let outside = null;- if (index < 0) {- const controls = controlsOutsideRows(nav, rows);- const at = controls.findIndex(control => control.contains(focus.element));- outside = at < 0 ? null : {name: controlName(controls[at])};- }- pendingFocusRef.current = {- focus,- outside,- wasOnToggle: [...togglesRef.current].some(toggle =>- toggle.contains(focus.element),- ),- isRowKept: index >= 0 && rowsRef.current.get(rows[index]) === true,- keptBefore: rows- .slice(0, Math.max(index, 0))- .filter(row => rowsRef.current.get(row) === true).length,- };- }, []);- useLayoutEffect(() => {- const pending = pendingFocusRef.current;- pendingFocusRef.current = null;- const nav = navRef.current;- if (pending == null || !collapsed || nav == null) {- return;- }- // Collapsed, every row the nav renders is one the rail keeps, in order.- const kept = railRows(nav, rowsRef.current);- const controlOf = (row: HTMLElement | undefined) =>- row == null ? undefined : getFocusableElements(row)[0];- const toggle = [...togglesRef.current].find(element =>- nav.contains(element),- );- let sameOutside: HTMLElement | undefined;- if (pending.wasOnToggle) {- sameOutside = toggle;- } else if (pending.outside != null) {- const controls = controlsOutsideRows(nav, kept);- sameOutside = controls.find(- control => controlName(control) === pending.outside?.name,+ const rows = railRows(nav, rowsRef.current);+ // The innermost row holding focus, the last in document order: a nested+ // row's parent holds it too.+ let index = -1;+ rows.forEach((row, at) => {+ if (row.contains(focus.element)) {+ index = at;+ }+ });+ let outside = null;+ if (index < 0) {+ const controls = controlsOutsideRows(nav, rows);+ const at = controls.findIndex(control =>+ control.contains(focus.element),+ );+ outside = at < 0 ? null : {name: controlName(controls[at])};+ }+ return {+ focus,+ outside,+ wasOnToggle: [...togglesRef.current].some(toggle =>+ toggle.contains(focus.element),+ ),+ isRowKept: index >= 0 && rowsRef.current.get(rows[index]) === true,+ keptBefore: rows+ .slice(0, Math.max(index, 0))+ .filter(row => rowsRef.current.get(row) === true).length,+ };+ },+ (pending: PendingRailFocus, isCollapsed: boolean) => {+ const nav = navRef.current;+ if (!isCollapsed || nav == null) {+ return;+ }+ // Collapsed, every row the nav renders is one the rail keeps, in order.+ const kept = railRows(nav, rowsRef.current);+ const controlOf = (row: HTMLElement | undefined) =>+ row == null ? undefined : getFocusableElements(row)[0];+ const toggle = [...togglesRef.current].find(element =>+ nav.contains(element),);- }- const target = pending.isRowKept- ? controlOf(kept[pending.keptBefore])- : (sameOutside ??- toggle ??- controlOf(kept[pending.keptBefore - 1]) ??- controlOf(kept[pending.keptBefore]));- moveFocusLeftBehind(pending.focus, target);- }, [collapsed]);+ let sameOutside: HTMLElement | undefined;+ if (pending.wasOnToggle) {+ sameOutside = toggle;+ } else if (pending.outside != null) {+ const controls = controlsOutsideRows(nav, kept);+ sameOutside = controls.find(+ control => controlName(control) === pending.outside?.name,+ );+ }+ const target = pending.isRowKept+ ? controlOf(kept[pending.keptBefore])+ : (sameOutside ??+ toggle ??+ controlOf(kept[pending.keptBefore - 1]) ??+ controlOf(kept[pending.keptBefore]));+ moveFocusLeftBehind(pending.focus, target);+ },+ );const beforeRailChange = useCallback((wasCollapsed: boolean) => {noteRailFocus(wasCollapsed);diff --git a/packages/core/src/motion/animatedLayoutAdopters.test.tsx b/packages/core/src/motion/animatedLayoutAdopters.test.tsxindex 8d2617c6a6..1a2a4f4314 100644--- a/packages/core/src/motion/animatedLayoutAdopters.test.tsx+++ b/packages/core/src/motion/animatedLayoutAdopters.test.tsx@@ -352,6 +352,37 @@ describe("a close plays the content's exit (spec:AST-105 FR4)", () => {expect(content.style.getPropertyValue('margin-block-end')).toBe('');});+ it('moves focus inside a closing Collapsible to its trigger while the content plays its exit (component:Collapsible AR4)', async () => {+ const example = (isOpen: boolean) => (+ <Area withHandle>+ {layout => (+ <Collapsible+ trigger="Details"+ isOpen={isOpen}+ onOpenChange={() => {}}+ animatedLayout={layout}>+ <button type="button">Inside</button>+ </Collapsible>+ )}+ </Area>+ );+ const {rerender} = render(example(true));+ stubGeometry();+ const trigger = screen.getByRole('button', {name: 'Details'});+ const content = document.getElementById(+ trigger.getAttribute('aria-controls') ?? '',+ ) as HTMLElement;+ vi.spyOn(content, 'getBoundingClientRect').mockReturnValue(+ new DOMRect(0, 40, 400, 40),+ );+ screen.getByRole('button', {name: 'Inside'}).focus();+ rerender(example(false));+ await flush();+ // Still on screen for the exit, and inert, so focus left it.+ expect(content).toHaveAttribute('inert');+ expect(trigger).toHaveFocus();+ });+it("keeps a collapsing TreeList row's child group until its exit ends, out of the keyboard order", async () => {const user = userEvent.setup();render(diff --git a/packages/core/src/utils/useFocusLeavingChange.ts b/packages/core/src/utils/useFocusLeavingChange.tsnew file mode 100644index 0000000000..1db3d801cf--- /dev/null+++ b/packages/core/src/utils/useFocusLeavingChange.ts@@ -0,0 +1,53 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file useFocusLeavingChange.ts+ * @input A state whose change can remove or hide focused content, how to note+ * the focus before the change, and how to move it after+ * @output A before-change callback for `LayoutChangeSnapshot`, and the move,+ * run from a layout effect of the same commit+ * @position Internal hook, not exported from the package: the one sequence a+ * disclosure runs so focus leaves content its change takes away+ * (`component:SideNav` AR3, `component:Collapsible` AR4). It pairs with+ * `noteFocusWithin` and `moveFocusLeftBehind` in `focusReturn.ts`, which+ * stays free of React so `isFocusDetached` remains server-safe.+ */++import {useCallback, useLayoutEffect, useRef} from 'react';++/**+ * Notes focus in the commit before `value`'s change touches the DOM, and+ * moves it from a layout effect of the same commit.+ *+ * Pass the returned callback as `LayoutChangeSnapshot`'s `onBeforeChange`+ * (with `value` as its `value`). `note` receives the value being left and+ * returns what `move` needs, or `null` when there is nothing to move; `move`+ * receives that and the new value once the change has committed. `move` is+ * the latest render's. `note` runs before this commit's effects, so it is the+ * previous committed render's: read refs or the DOM in it, not props.+ */+export function useFocusLeavingChange<V, N>(+ value: V,+ note: (previous: V) => N | null,+ move: (noted: N, value: V) => void,+): (previous: V) => void {+ const noteRef = useRef(note);+ const moveRef = useRef(move);+ const pendingRef = useRef<N | null>(null);+ useLayoutEffect(() => {+ noteRef.current = note;+ moveRef.current = move;+ });+ useLayoutEffect(() => {+ const noted = pendingRef.current;+ pendingRef.current = null;+ if (noted != null) {+ moveRef.current(noted, value);+ }+ }, [value]);+ return useCallback((previous: V) => {+ pendingRef.current = noteRef.current(previous);+ }, []);+}