An open source design system that's fully customizable and agent ready
TypeScript
fix(AppShell): defer hiding the mobile nav Activity boundary until close finishes (#6319)
Ojas Mutreja3c9b4ef2fbae
diff --git a/.changeset/appshell-mobilenav-close-animation.md b/.changeset/appshell-mobilenav-close-animation.mdnew file mode 100644index 0000000000..93f025beef--- /dev/null+++ b/.changeset/appshell-mobilenav-close-animation.md@@ -0,0 +1,13 @@+---+'@astryxdesign/core': patch+---++[fix] AppShell: defer hiding the mobile nav's Activity boundary until its close animation finishes (#5701)++`AppShell` mounts the mobile nav drawer inside a `React.Activity` boundary that flipped to `mode="hidden"` in the same commit as the drawer closing. React's `Activity` hides its subtree with `display: none !important` synchronously and re-runs the cleanup of every effect inside it, which cut off `MobileNav`'s own slide-out CSS transition and cancelled its delayed `dialog.close()` before either could run. The drawer still closed correctly (a safety-net effect force-closed the native dialog on that same cleanup), just with the close animation skipped entirely.++`AppShell` now holds the `Activity` boundary visible for a beat after the drawer closes, strictly longer than `MobileNav`'s own worst-case close delay, so `MobileNav`'s normal close effect gets a real chance to run its transition and its own timed `dialog.close()` before `Activity` ever hides the subtree.++`MobileNav` also keeps its dialog rendered from the commit that closes it until its delayed `close()` has run, instead of relying on the dialog's discrete `display` transition to do so. A browser that does not hold that transition (WebKit) dropped the dialog to `display: none` at once while it was still an open modal, so for about 200ms nothing was visible and the page stayed inert. The slide-out itself is unchanged.++@HelloOjasMutrejadiff --git a/packages/core/src/AppShell/AppShell.tsx b/packages/core/src/AppShell/AppShell.tsxindex 5b6c33177f..04fbb2808a 100644--- a/packages/core/src/AppShell/AppShell.tsx+++ b/packages/core/src/AppShell/AppShell.tsx@@ -43,6 +43,7 @@ import {LayoutHeader} from '../Layout/LayoutHeader';import {LayoutPanel} from '../Layout/LayoutPanel';import {LayoutContent} from '../Layout/LayoutContent';import {MobileNavToggle} from '../MobileNav/MobileNavToggle';+import {MAX_CLOSE_DELAY_MS as MOBILE_NAV_MAX_CLOSE_DELAY_MS} from '../MobileNav/MobileNav';import {SideNavRenderContext} from '../SideNav/SideNavRenderContext';import {TopNavRenderContext} from '../TopNav/TopNavRenderContext';import {TopNavMobileContentContext} from '../TopNav/TopNavMobileContentContext';@@ -81,6 +82,20 @@ const ActivityWrapper = HasActivityconst MAIN_CONTENT_ID = 'astryx-app-shell-main';+/**+ * Extra time, on top of MobileNav's own worst-case close delay, that+ * AppShell waits before flipping its `Activity` boundary to `'hidden'`.+ *+ * React's `Activity` hides its subtree with `display: none !important`+ * synchronously in the same commit as the mode flip, and re-runs the+ * cleanup of every effect inside it — which would otherwise clear+ * MobileNav's own scheduled `dialog.close()` before it fires, or cut off+ * its slide-out CSS transition before it plays (#5701). Waiting strictly+ * longer than MobileNav's own cap, rather than the same duration, means+ * this never turns into a race decided by browser timer-firing order.+ */+const ACTIVITY_HIDE_BUFFER_MS = 50;+// =============================================================================// Types// =============================================================================@@ -525,6 +540,34 @@ export function AppShell({const [uncontrolledMobileOpen, setUncontrolledMobileOpen] = useState(false);const isMobileNavOpen = mobileNavConfig?.isOpen ?? uncontrolledMobileOpen;+ // Holds the mobile nav's `Activity` boundary visible for a beat after a+ // close, so MobileNav's own close effect gets a real chance to run its+ // slide-out transition and schedule its delayed `dialog.close()` before+ // Activity hides the subtree (#5701). Only the CLOSE is deferred: opening+ // reads `isMobileNavOpen` directly below, so a controlled open is visible in+ // the commit that carries it instead of one effect later.+ const [isMobileNavCloseHeld, setIsMobileNavCloseHeld] =+ useState(isMobileNavOpen);+ // Arm the hold during render, from the open state itself, so no Effect has+ // to copy props into state; the Effect below only owns the release timer.+ if (isMobileNavOpen && !isMobileNavCloseHeld) {+ setIsMobileNavCloseHeld(true);+ }+ useEffect(() => {+ if (!HasActivity || isMobileNavOpen) {+ return;+ }+ const delayMs = window.matchMedia('(prefers-reduced-motion: reduce)')+ .matches+ ? 0+ : MOBILE_NAV_MAX_CLOSE_DELAY_MS + ACTIVITY_HIDE_BUFFER_MS;+ const timeout = setTimeout(() => {+ setIsMobileNavCloseHeld(false);+ }, delayMs);+ return () => clearTimeout(timeout);+ }, [isMobileNavOpen]);+ const isMobileNavActivityVisible = isMobileNavOpen || isMobileNavCloseHeld;+const mobileNavOnOpenChange = mobileNavConfig?.onOpenChange;const setMobileNavOpen = useCallback((open: boolean) => {@@ -864,7 +907,8 @@ export function AppShell({!mobileNavDisabled &&mobileNavReactNode == null &&!mobileNavConfigContent && (- <ActivityWrapper mode={isMobileNavOpen ? 'visible' : 'hidden'}>+ <ActivityWrapper+ mode={isMobileNavActivityVisible ? 'visible' : 'hidden'}>{/* SideNav drawer — always mounted so presence detection works.Hidden when TopNav owns the drawer (combined mode passessideNav via TopNav's mobile content context instead). */}diff --git a/packages/core/src/MobileNav/MobileNav.tsx b/packages/core/src/MobileNav/MobileNav.tsxindex 1ffcbf6d24..f5736fb099 100644--- a/packages/core/src/MobileNav/MobileNav.tsx+++ b/packages/core/src/MobileNav/MobileNav.tsx@@ -260,8 +260,15 @@ const dynamicStyles = stylex.create({// Close timing// =============================================================================-/** Longest the drawer will wait before closing, however long the hold is. */-const MAX_CLOSE_DELAY_MS = 250;+/**+ * Longest the drawer will wait before closing, however long the hold is.+ *+ * Exported so `AppShell` can defer hiding this drawer's `Activity` boundary+ * by at least this long too (`ACTIVITY_HIDE_BUFFER_MS` in AppShell.tsx) —+ * otherwise Activity's `display: none !important` lands before this delay's+ * own scheduled `dialog.close()` has a chance to run (#5701).+ */+export const MAX_CLOSE_DELAY_MS = 250;/** Fraction of the hold to close at, so the close never lands on its boundary. */const CLOSE_WITHIN_HOLD = 0.6;@@ -488,6 +495,21 @@ export function MobileNav({// Element that was focused when the drawer opened; focus goes back to it// once the native dialog has closed (see closeAndRestoreFocus).const triggerElementRef = useRef<HTMLElement | null>(null);++ // Keeps the dialog rendered from the commit that closes it until the delayed+ // `close()` below has run. The `display` transition on the dialog is meant to+ // do this, but a browser that does not hold a discrete `display` transition+ // (WebKit) drops the dialog to `display: none` at once while it is still an+ // open modal: nothing is visible, yet the whole page stays inert until the+ // timer fires. Set during render, so it is already true in the commit that+ // closes. The drawer's transform and the backdrop stay keyed to `isOpen`, so+ // the slide-out is unchanged.+ const [isCloseHeld, setIsCloseHeld] = useState(false);+ const [wasOpen, setWasOpen] = useState(isOpen);+ if (wasOpen !== isOpen) {+ setWasOpen(isOpen);+ setIsCloseHeld(!isOpen);+ }const gutterRef = useRef<ScrollbarGutterHold | null>(null);// Gives back the gutter held open in place of the hidden scrollbar.@@ -563,7 +585,12 @@ export function MobileNav({closeTimeoutRef.current = setTimeout(() => {closeAndRestoreFocus(dialog, triggerElementRef);+ setIsCloseHeld(false);}, resolveCloseDelay(dialog));+ } else {+ // Nothing is open, so there is no close to hold the dialog for, and no+ // close timer is left to release the hold.+ setIsCloseHeld(false);}return () => {@@ -647,7 +674,7 @@ export function MobileNav({layerStructureReset.reset,styles.dialog,overlayPaddingReset.reset,- isOpen && styles.open,+ (isOpen || isCloseHeld) && styles.open,styles.backdrop,isOpen && styles.backdropOpen,xstyle,diff --git a/packages/core/src/MobileNav/MobileNavCloseEdgeCases.test.tsx b/packages/core/src/MobileNav/MobileNavCloseEdgeCases.test.tsxindex 7e261cbeb0..8cb76ad8c7 100644--- a/packages/core/src/MobileNav/MobileNavCloseEdgeCases.test.tsx+++ b/packages/core/src/MobileNav/MobileNavCloseEdgeCases.test.tsx@@ -26,7 +26,7 @@ import {beforeEach,afterEach,} from 'vitest';-import {StrictMode} from 'react';+import {StrictMode, useLayoutEffect} from 'react';import {render, screen, fireEvent, act} from '@testing-library/react';import {MobileNav} from './MobileNav';import {AppShell} from '../AppShell/AppShell';@@ -136,6 +136,42 @@ describe('MobileNav close path edge cases', () => {}});+ // A browser that does not hold a discrete `display` transition (WebKit)+ // drops the dialog to `display: none` the moment the open styling goes, while+ // it is still an open modal: nothing is visible, yet the page stays inert+ // until the close timer fires. So the dialog's own open styling has to be+ // held by the component, not left to that transition. jsdom applies no+ // StyleX styles, so this reads the readable class names StyleX emits in+ // tests: the `open` class (display) is held through the closing commit, the+ // `backdropOpen` class is not, and the hold ends when the dialog closes.+ it('keeps the dialog rendered until its delayed close has run', () => {+ vi.useFakeTimers();+ try {+ const {rerender} = render(<Drawer isOpen />);+ const dialog = screen.getByTestId('mobile-nav');+ expect(dialog.className).toMatch(/styles\.open/);+ expect(dialog.className).toMatch(/styles\.backdropOpen/);++ act(() => {+ rerender(<Drawer isOpen={false} />);+ });+ // Still an open modal, so still rendered; only the backdrop's open+ // styling (the fade-out) has gone.+ expect(dialog).toHaveAttribute('open');+ expect(dialog.className).toMatch(/styles\.open/);+ expect(dialog.className).not.toMatch(/styles\.backdropOpen/);++ act(() => {+ vi.advanceTimersByTime(300);+ });+ // Closed: the hold is released along with the dialog.+ expect(dialog).not.toHaveAttribute('open');+ expect(dialog.className).not.toMatch(/styles\.open/);+ } finally {+ vi.useRealTimers();+ }+ });+it('closes the dialog when unmounted while fully open', () => {const {unmount} = render(<Drawer isOpen />);const dialog = screen.getByTestId('mobile-nav');@@ -401,26 +437,148 @@ describe('MobileNav close path edge cases', () => {});it('closes the AppShell drawer when dismissed with Escape', () => {- render(<TestShell />);- fireEvent.click(screen.getByRole('button', {name: /open navigation/i}));- const dialog = screen.getAllByRole('dialog', {hidden: true})[0];- expect(dialog).toHaveAttribute('open');+ // Fake timers: AppShell now defers hiding this drawer's Activity boundary+ // (#5701) so MobileNav's own close effect gets a real chance to run —+ // the dialog closes via its normal deferred setTimeout, not synchronously.+ vi.useFakeTimers();+ try {+ render(<TestShell />);+ act(() => {+ fireEvent.click(screen.getByRole('button', {name: /open navigation/i}));+ });+ const dialog = screen.getAllByRole('dialog', {hidden: true})[0];+ expect(dialog).toHaveAttribute('open');- fireEvent(dialog, new Event('cancel', {cancelable: true, bubbles: false}));+ act(() => {+ fireEvent(+ dialog,+ new Event('cancel', {cancelable: true, bubbles: false}),+ );+ });+ act(() => {+ vi.advanceTimersByTime(300);+ });- expect(dialog).not.toHaveAttribute('open');+ expect(dialog).not.toHaveAttribute('open');+ } finally {+ vi.useRealTimers();+ }});it('closes the AppShell drawer when the backdrop is clicked', () => {- render(<TestShell />);- fireEvent.click(screen.getByRole('button', {name: /open navigation/i}));- const dialog = screen.getAllByRole('dialog', {hidden: true})[0];- expect(dialog).toHaveAttribute('open');+ vi.useFakeTimers();+ try {+ render(<TestShell />);+ act(() => {+ fireEvent.click(screen.getByRole('button', {name: /open navigation/i}));+ });+ const dialog = screen.getAllByRole('dialog', {hidden: true})[0];+ expect(dialog).toHaveAttribute('open');- // A click landing on the dialog itself, not the drawer panel, is a- // backdrop dismiss.- fireEvent.click(dialog);+ // A click landing on the dialog itself, not the drawer panel, is a+ // backdrop dismiss.+ act(() => {+ fireEvent.click(dialog);+ });+ act(() => {+ vi.advanceTimersByTime(300);+ });- expect(dialog).not.toHaveAttribute('open');+ expect(dialog).not.toHaveAttribute('open');+ } finally {+ vi.useRealTimers();+ }+ });++ // #5701: AppShell mounts the drawer inside a React.Activity boundary that+ // used to flip to mode="hidden" in the SAME commit as the close, which+ // forced this file's own unmount-only safety-net effect to call+ // dialog.close() synchronously — closing correctly, but skipping the+ // slide-out transition entirely, because Activity's display:none landed+ // before any transition could run. AppShell now defers that flip, so the+ // dialog should still be open (and rendered) for a beat after closing,+ // not synchronously cut off.+ it('keeps the drawer open long enough for its close transition to run (#5701)', () => {+ vi.useFakeTimers();+ try {+ render(<TestShell />);+ act(() => {+ fireEvent.click(screen.getByRole('button', {name: /open navigation/i}));+ });+ const dialog = screen.getAllByRole('dialog', {hidden: true})[0];+ expect(dialog).toHaveAttribute('open');++ act(() => {+ fireEvent.click(+ screen.getByRole('button', {name: /close navigation/i}),+ );+ });++ // Immediately after closing, with no timers advanced: the old+ // synchronous-hide bug closed the dialog on this exact tick. The fix+ // means it must still be open here — Activity hasn't hidden the+ // subtree yet, so MobileNav's own deferred close effect is still the+ // one in control.+ expect(dialog).toHaveAttribute('open');++ // MobileNav's own close delay (capped at 250ms) runs first: about+ // 260ms after the click the dialog has closed on its own timing while+ // AppShell's Activity boundary (held for 250ms + 50ms) still shows the+ // subtree. Hiding first would cut off that close (#5701).+ act(() => {+ vi.advanceTimersByTime(260);+ });+ expect(dialog).not.toHaveAttribute('open');+ // Activity hides its subtree with an inline `display: none`; a closed+ // dialog's own UA style does not count here.+ expect(dialog.style.display).not.toBe('none');++ // After the hold, Activity hides the subtree.+ act(() => {+ vi.advanceTimersByTime(60);+ });+ expect(dialog.style.display).toBe('none');+ } finally {+ vi.useRealTimers();+ }+ });+ // A controlled open must be visible in the commit that carries it. The+ // Activity boundary only defers the CLOSE; if opening waited for an effect+ // to copy the open state, the drawer would render hidden for one commit+ // with `isOpen` already true.+ it('shows a controlled open in the same commit, not one effect later', () => {+ const commits: {isOpen: boolean; isHidden: boolean}[] = [];+ function Probe({isOpen}: {isOpen: boolean}) {+ useLayoutEffect(() => {+ const drawer = document.querySelector('dialog');+ commits.push({+ isOpen,+ isHidden:+ drawer != null && getComputedStyle(drawer).display === 'none',+ });+ });+ return null;+ }+ const shell = (isOpen: boolean) => (+ <AppShell+ sideNav={+ <SideNav>+ <SideNavSection title="Test" isHeaderHidden>+ <SideNavItem label="Home" />+ </SideNavSection>+ </SideNav>+ }+ mobileNav={{breakpoint: 'md', isOpen, onOpenChange: () => {}}}>+ <Probe isOpen={isOpen} />+ <div>Content</div>+ </AppShell>+ );++ const {rerender} = render(shell(false));+ rerender(shell(true));++ const openCommits = commits.filter(commit => commit.isOpen);+ expect(openCommits.length).toBeGreaterThan(0);+ expect(openCommits.every(commit => !commit.isHidden)).toBe(true);});});