An open source design system that's fully customizable and agent ready
TypeScript
fix(DropdownMenu): load the touch bottom sheet only when a menu shows it (#7709)
Joeye868278e05d5
diff --git a/.changeset/dropdown-menu-lazy-touch-sheet.md b/.changeset/dropdown-menu-lazy-touch-sheet.mdnew file mode 100644index 0000000000..549665b9c8--- /dev/null+++ b/.changeset/dropdown-menu-lazy-touch-sheet.md@@ -0,0 +1,9 @@+---+'@astryxdesign/core': patch+---++[fix] DropdownMenu: load the touch bottom sheet only when a menu shows it++`DropdownMenu` imported its touch sheet (BottomSheet, its gestures, and the touch action list) up front, so every page with a dropdown shipped it, even when the menu only ever opens as an anchored popover. The sheet now loads on demand, the way `ContextMenu` already loads it. A popover-only dropdown's own code drops by about a third (about 23 KB gzipped). Bottom-sheet and adaptive menus behave as before. The sheet starts loading when the trigger mounts, and a menu opened from the keyboard before it arrives still focuses its first action once it loads.++@josephfarinadiff --git a/packages/core/src/DropdownMenu/DropdownMenu.ssr.test.tsx b/packages/core/src/DropdownMenu/DropdownMenu.ssr.test.tsxnew file mode 100644index 0000000000..7d5ed33f4b--- /dev/null+++ b/packages/core/src/DropdownMenu/DropdownMenu.ssr.test.tsx@@ -0,0 +1,57 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file DropdownMenu.ssr.test.tsx+ * @input DropdownMenu server markup and React hydration+ * @output Proves a bottom-sheet DropdownMenu hydrates without a recoverable+ * error while its on-demand sheet has not loaded (spec:AST-013 FR9)+ * @position SSR acceptance test for DropdownMenu+ */++import {act} from 'react';+import {afterEach, describe, expect, it, vi} from 'vitest';+import {hydrateRoot} from 'react-dom/client';+import {renderToString} from 'react-dom/server';++afterEach(() => {+ vi.restoreAllMocks();+ document.body.replaceChildren();+});++async function serverRenderThenHydrate(): Promise<unknown[]> {+ // A fresh module graph is a fresh server process: the sheet has not loaded.+ vi.resetModules();+ const {DropdownMenu} = await import('./DropdownMenu');+ const tree = (+ <DropdownMenu+ button={{label: 'Actions'}}+ presentation="bottom-sheet"+ items={[{label: 'Edit project'}, {label: 'Delete'}]}+ />+ );+ const container = document.createElement('div');+ container.innerHTML = renderToString(tree);+ document.body.appendChild(container);++ vi.spyOn(console, 'error').mockImplementation(() => {});+ const recoverableErrors: unknown[] = [];+ let root!: ReturnType<typeof hydrateRoot>;+ await act(async () => {+ root = hydrateRoot(container, tree, {+ onRecoverableError: error => recoverableErrors.push(error),+ });+ });+ await act(async () => {+ root.unmount();+ });+ container.remove();+ return recoverableErrors;+}++describe('DropdownMenu — SSR', () => {+ it('hydrates a bottom-sheet menu cleanly on the first renders of a server process', async () => {+ expect(await serverRenderThenHydrate()).toEqual([]);+ expect(await serverRenderThenHydrate()).toEqual([]);+ expect(await serverRenderThenHydrate()).toEqual([]);+ }, 30000);+});diff --git a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx b/packages/core/src/DropdownMenu/DropdownMenu.test.tsxindex c3ff4e2ab4..2253b5d8ff 100644--- a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx+++ b/packages/core/src/DropdownMenu/DropdownMenu.test.tsx@@ -9,7 +9,15 @@* SYNC: When DropdownMenu.tsx changes, update tests to match new behavior*/-import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';+import {+ describe,+ it,+ expect,+ vi,+ beforeAll,+ beforeEach,+ afterEach,+} from 'vitest';import {readFileSync} from 'node:fs';import {render, screen, fireEvent, waitFor, act} from '@testing-library/react';import userEvent from '@testing-library/user-event';@@ -19,6 +27,7 @@ import {DropdownMenu, type DropdownMenuTriggerProps} from './DropdownMenu';import {DropdownMenuItem} from './DropdownMenuItem';import {DropdownMenuDivider} from './DropdownMenuDivider';import {DropdownMenuGroup} from './DropdownMenuGroup';+import {warmMenuBottomSheet} from './__tests__/warmMenuBottomSheet';import {DropdownMenuSubMenu} from './DropdownMenuSubMenu';import {Divider} from '../Divider';import {rtlStyles} from '../utils';@@ -74,6 +83,10 @@ beforeEach(() => {};});+// The touch sheet is loaded lazily; resolve it once so sheets below render+// synchronously.+beforeAll(warmMenuBottomSheet, 20000);+describe('DropdownMenu', () => {it('renders trigger button with label', () => {render(diff --git a/packages/core/src/DropdownMenu/DropdownMenu.tsx b/packages/core/src/DropdownMenu/DropdownMenu.tsxindex f937210990..afb803deb4 100644--- a/packages/core/src/DropdownMenu/DropdownMenu.tsx+++ b/packages/core/src/DropdownMenu/DropdownMenu.tsx@@ -4,7 +4,7 @@/*** @file DropdownMenu.tsx- * @input Uses React, StyleX, usePopover, MenuBottomSheet, Button, List,+ * @input Uses React, StyleX, usePopover, MenuBottomSheet (lazy), Button, List,* useListFocus, and the shared viewport-safe menu-width resolver* @output Exports DropdownMenu with caller-selected popover or bottom-sheet* presentation@@ -81,8 +81,11 @@ import {useAdaptivePresentation,type AdaptivePresentation,} from '../hooks/useAdaptivePresentation';-import {MenuBottomSheet} from './MenuBottomSheet';-import {MenuBottomSheetActionList} from './MenuBottomSheetActionList';+// Loaded on demand: only the bottom-sheet presentation renders the sheet.+import {+ MenuBottomSheet,+ MenuBottomSheetActionList,+} from './lazyMenuBottomSheet';import {layerAnimations} from '../Layer/layerAnimations.stylex';import type {LayerAlignment, LayerPlacement} from '../Layer/useLayer';import {@@ -759,12 +762,37 @@ function DropdownMenuBottomSheet({if (!isOpen || openModalityRef.current !== 'keyboard') {return;}- const frame = requestAnimationFrame(() => {- actionListRef.current- ?.querySelector<HTMLElement>('button:not(:disabled), a[href]')- ?.focus({preventScroll: true});+ const findFirstAction = () =>+ actionListRef.current?.querySelector<HTMLElement>(+ 'button:not(:disabled), a[href]',+ ) ?? null;+ let observer: MutationObserver | null = null;+ let frame = requestAnimationFrame(() => {+ const action = findFirstAction();+ if (action != null) {+ action.focus({preventScroll: true});+ return;+ }+ // The sheet loads on demand, so a keyboard open can arrive before its+ // rows exist. Wait for them, then focus a frame later so the sheet's+ // own open-focus has already run.+ observer = new MutationObserver(() => {+ const loaded = findFirstAction();+ if (loaded == null) {+ return;+ }+ observer?.disconnect();+ observer = null;+ frame = requestAnimationFrame(() => {+ loaded.focus({preventScroll: true});+ });+ });+ observer.observe(document.body, {childList: true, subtree: true});});- return () => cancelAnimationFrame(frame);+ return () => {+ cancelAnimationFrame(frame);+ observer?.disconnect();+ };}, [currentItems, isOpen]);useEffect(() => {diff --git a/packages/core/src/DropdownMenu/DropdownMenuLazySheet.test.tsx b/packages/core/src/DropdownMenu/DropdownMenuLazySheet.test.tsxnew file mode 100644index 0000000000..d9b8e39be1--- /dev/null+++ b/packages/core/src/DropdownMenu/DropdownMenuLazySheet.test.tsx@@ -0,0 +1,126 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file DropdownMenuLazySheet.test.tsx+ * @input Uses DropdownMenu, Testing Library, and a held module load+ * @output Tests DropdownMenu while its on-demand touch sheet is still loading+ * @position Test file for DropdownMenu+ *+ * This file never warms the sheet, and it checks that a popover menu never+ * requests it: each test holds the sheet modules until it+ * releases them, so it exercises the path a real page takes while the sheet's+ * code is still downloading.+ */++import {describe, it, expect, vi, beforeAll, beforeEach} from 'vitest';+import {render, screen, waitFor, act} from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import type {DropdownMenu as DropdownMenuComponent} from './DropdownMenu';++const sheetLoad = vi.hoisted(() => {+ let release: () => void = () => {};+ const gate = new Promise<void>(resolve => {+ release = resolve;+ });+ return {gate, release: () => release(), requested: [] as string[]};+});++vi.mock('./MenuBottomSheet', async importOriginal => {+ sheetLoad.requested.push('MenuBottomSheet');+ await sheetLoad.gate;+ return importOriginal();+});++vi.mock('./MenuBottomSheetActionList', async importOriginal => {+ sheetLoad.requested.push('MenuBottomSheetActionList');+ await sheetLoad.gate;+ return importOriginal();+});++let DropdownMenu: typeof DropdownMenuComponent;++// If any module the dropdown loads imported the sheet eagerly, this import+// would wait on the held sheet and the hook would time out.+beforeAll(async () => {+ ({DropdownMenu} = await import('./DropdownMenu'));+}, 10000);++beforeEach(() => {+ HTMLDialogElement.prototype.showModal = vi.fn(function (+ this: HTMLDialogElement,+ ) {+ this.setAttribute('open', '');+ });+ HTMLDialogElement.prototype.close = vi.fn(function (this: HTMLDialogElement) {+ this.removeAttribute('open');+ });+ vi.stubGlobal(+ 'matchMedia',+ vi.fn().mockImplementation((query: string) => ({+ matches: false,+ media: query,+ onchange: null,+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ addListener: vi.fn(),+ removeListener: vi.fn(),+ dispatchEvent: vi.fn(),+ })),+ );+});++describe('DropdownMenu touch sheet loaded on demand', () => {+ // Runs first: nothing in this file has rendered a sheet yet.+ it('never loads the sheet for a popover menu', async () => {+ const user = userEvent.setup();+ HTMLElement.prototype.showPopover = vi.fn();+ HTMLElement.prototype.hidePopover = vi.fn();+ render(+ <DropdownMenu+ button={{label: 'Actions'}}+ items={[{label: 'Edit project'}, {label: 'Delete'}]}+ />,+ );++ await user.click(screen.getByRole('button', {name: /Actions/}));+ await act(async () => {+ await new Promise(resolve => setTimeout(resolve, 50));+ });++ // Importing DropdownMenu and opening a popover menu requested neither+ // sheet module, so no other module the dropdown loads imports it eagerly.+ expect(sheetLoad.requested).toEqual([]);+ });++ it('focuses the first action when a keyboard open beats the sheet load', async () => {+ const user = userEvent.setup();+ render(+ <DropdownMenu+ button={{label: 'Actions'}}+ presentation="bottom-sheet"+ items={[{label: 'Edit project'}, {label: 'Delete'}]}+ />,+ );++ const trigger = screen.getByRole('button', {name: /Actions/});+ trigger.focus();+ await user.keyboard('{Enter}');+ // The open has committed, but the sheet's code has not arrived yet.+ await act(async () => {+ await new Promise(resolve => setTimeout(resolve, 50));+ });+ expect(screen.queryByRole('button', {name: 'Edit project'})).toBeNull();++ await act(async () => {+ sheetLoad.release();+ });++ await waitFor(+ () =>+ expect(+ screen.getByRole('button', {name: 'Edit project'}),+ ).toHaveFocus(),+ {timeout: 15000},+ );+ }, 20000);+});diff --git a/packages/core/src/DropdownMenu/__tests__/warmMenuBottomSheet.tsx b/packages/core/src/DropdownMenu/__tests__/warmMenuBottomSheet.tsxnew file mode 100644index 0000000000..03b381b78d--- /dev/null+++ b/packages/core/src/DropdownMenu/__tests__/warmMenuBottomSheet.tsx@@ -0,0 +1,43 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file warmMenuBottomSheet.tsx+ * @input Uses DropdownMenu and Testing Library+ * @output Exports warmMenuBottomSheet, a test helper that resolves the lazily+ * loaded touch sheet once+ * @position Test-only helper for suites that open a DropdownMenu bottom sheet+ *+ * DropdownMenu loads its touch sheet with React.lazy, so the first sheet+ * renders a tick after it opens. Opening one up front caches the resolved+ * modules on the lazy components, and every later sheet renders+ * synchronously. Call it from `beforeAll`.+ */++import {cleanup, render, screen} from '@testing-library/react';+import {DropdownMenu} from '../DropdownMenu';++export async function warmMenuBottomSheet(): Promise<void> {+ const {showModal, close} = HTMLDialogElement.prototype;+ HTMLDialogElement.prototype.showModal = function (this: HTMLDialogElement) {+ this.setAttribute('open', '');+ };+ HTMLDialogElement.prototype.close = function (this: HTMLDialogElement) {+ this.removeAttribute('open');+ };+ try {+ render(+ <DropdownMenu+ button={{label: 'Warm'}}+ presentation="bottom-sheet"+ isMenuOpen+ items={[{label: 'Warm item'}]}+ />,+ );+ // A cold import transforms the sheet's module graph; allow for it.+ await screen.findByText('Warm item', undefined, {timeout: 15000});+ } finally {+ cleanup();+ HTMLDialogElement.prototype.showModal = showModal;+ HTMLDialogElement.prototype.close = close;+ }+}diff --git a/packages/core/src/DropdownMenu/lazyMenuBottomSheet.ts b/packages/core/src/DropdownMenu/lazyMenuBottomSheet.tsnew file mode 100644index 0000000000..14f31a70e0--- /dev/null+++ b/packages/core/src/DropdownMenu/lazyMenuBottomSheet.ts@@ -0,0 +1,71 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file lazyMenuBottomSheet.ts+ * @input Uses React lazy and Suspense, useIsHydrating, MenuBottomSheet, and+ * MenuBottomSheetActionList+ * @output Exports MenuBottomSheet and MenuBottomSheetActionList wrappers that+ * load the touch sheet on first render+ * @position Internal to DropdownMenu+ *+ * The touch sheet (BottomSheet, its gestures, and the touch action list) only+ * renders for the bottom-sheet presentation. Loading it on demand keeps it out+ * of pages whose dropdowns only open as anchored popovers. Each wrapper keeps+ * the wrapped component's props and renders nothing until its module loads.+ *+ * Neither wrapper renders on the server or in the render that hydrates server+ * HTML (spec:AST-013 FR9): a lazy component that has not loaded yet would+ * leave server markup incomplete and abort hydration. The closed sheet has no+ * visible markup, so it first renders right after hydration.+ */++import {+ createElement,+ lazy,+ Suspense,+ type ComponentProps,+ type ReactElement,+} from 'react';+import {useIsHydrating} from '../hooks/useIsHydrating';+import type {MenuBottomSheet as EagerMenuBottomSheet} from './MenuBottomSheet';+import type {MenuBottomSheetActionList as EagerMenuBottomSheetActionList} from './MenuBottomSheetActionList';++const LazyMenuBottomSheet = lazy(async () =>+ import('./MenuBottomSheet').then(module => ({+ default: module.MenuBottomSheet,+ })),+);++const LazyMenuBottomSheetActionList = lazy(async () =>+ import('./MenuBottomSheetActionList').then(module => ({+ default: module.MenuBottomSheetActionList,+ })),+);++export function MenuBottomSheet(+ props: ComponentProps<typeof EagerMenuBottomSheet>,+): ReactElement | null {+ if (useIsHydrating()) {+ return null;+ }+ return createElement(+ Suspense,+ {fallback: null},+ createElement(LazyMenuBottomSheet, props),+ );+}++export function MenuBottomSheetActionList(+ props: ComponentProps<typeof EagerMenuBottomSheetActionList>,+): ReactElement | null {+ if (useIsHydrating()) {+ return null;+ }+ return createElement(+ Suspense,+ {fallback: null},+ createElement(LazyMenuBottomSheetActionList, props),+ );+}diff --git a/packages/core/src/MoreMenu/MoreMenu.test.tsx b/packages/core/src/MoreMenu/MoreMenu.test.tsxindex 6b25a43987..829ab539e4 100644--- a/packages/core/src/MoreMenu/MoreMenu.test.tsx+++ b/packages/core/src/MoreMenu/MoreMenu.test.tsx@@ -9,11 +9,15 @@* SYNC: When MoreMenu.tsx changes, update tests to match new behavior*/-import {describe, it, expect, vi, beforeEach} from 'vitest';+import {describe, it, expect, vi, beforeAll, beforeEach} from 'vitest';import {render, screen, fireEvent, waitFor} from '@testing-library/react';import userEvent from '@testing-library/user-event';import {MoreMenu} from './MoreMenu';import {DropdownMenu} from '../DropdownMenu/DropdownMenu';+import {warmMenuBottomSheet} from '../DropdownMenu/__tests__/warmMenuBottomSheet';++// DropdownMenu's touch sheet is loaded lazily; resolve it once up front.+beforeAll(warmMenuBottomSheet, 20000);// Mock showPopover and hidePopover methods since they're not implemented in jsdombeforeEach(() => {