An open source design system that's fully customizable and agent ready
TypeScript
fix(DropdownMenu): a menu's sheet renders nothing at rest and drops two wrappers (#8392)
Cindy Zhang7d489895638f
diff --git a/.changeset/menu-sheet-nothing-at-rest.md b/.changeset/menu-sheet-nothing-at-rest.mdnew file mode 100644index 0000000000..54d32c6ada--- /dev/null+++ b/.changeset/menu-sheet-nothing-at-rest.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] DropdownMenu, MoreMenu and ContextMenu: a menu presented as a bottom sheet (`presentation="bottom-sheet"`, or `"adaptive"` on a phone) no longer keeps its closed sheet and every item mounted while the menu is closed. The sheet mounts as it opens and unmounts after its exit, with focus still returning to the trigger. The open sheet also renders two fewer wrapper elements, with the same layout.++@cixzhangdiff --git a/packages/core/src/ContextMenu/ContextMenu.test.tsx b/packages/core/src/ContextMenu/ContextMenu.test.tsxindex 059b2bf9d4..d3d00b8417 100644--- a/packages/core/src/ContextMenu/ContextMenu.test.tsx+++ b/packages/core/src/ContextMenu/ContextMenu.test.tsx@@ -304,15 +304,42 @@ describe('ContextMenu', () => {);});- it('keeps only the top content padding in a menu BottomSheet', () => {- const source = readFileSync(- 'packages/core/src/DropdownMenu/MenuBottomSheet.tsx',- 'utf8',- );-- expect(source).toContain('paddingBlockStart={4}');- expect(source).toContain('paddingBlockEnd={0}');- });+ for (const mode of ['items', 'compound'] as const) {+ it(`insets a ${mode} menu sheet itself and publishes the inset to its rows`, async () => {+ render(+ mode === 'items' ? (+ <ContextMenu presentation="bottom-sheet" items={[{label: 'Edit'}]}>+ <div>Right-click me</div>+ </ContextMenu>+ ) : (+ <ContextMenu+ presentation="bottom-sheet"+ menuContent={<DropdownMenuItem label="Edit" />}>+ <div>Right-click me</div>+ </ContextMenu>+ ),+ );+ fireEvent.contextMenu(screen.getByText('Right-click me'));+ const content = await waitFor(() => {+ const element = document.querySelector<HTMLElement>(+ 'dialog .astryx-context-menu',+ );+ expect(element).not.toBeNull();+ return element as HTMLElement;+ });+ // No Section wrapper: the menu element keeps the sheet's 16px top and+ // 4px side inset plus its own 4px, and publishes the padding it applies.+ expect(content.parentElement?.closest('.astryx-section')).toBeNull();+ expect(content).toHaveStyle({+ paddingTop: 'calc(var(--spacing-4) + var(--spacing-1))',+ paddingInline: 'calc(var(--spacing-1) + var(--spacing-1))',+ '--container-padding-block-start':+ 'calc(var(--spacing-4) + var(--spacing-1))',+ '--container-padding-inline-start':+ 'calc(var(--spacing-1) + var(--spacing-1))',+ });+ });+ }it('uses the BottomSheet for adaptive presentation on compact touch', async () => {vi.stubGlobal(diff --git a/packages/core/src/ContextMenu/ContextMenu.tsx b/packages/core/src/ContextMenu/ContextMenu.tsxindex 2e257bb130..322a6c7c85 100644--- a/packages/core/src/ContextMenu/ContextMenu.tsx+++ b/packages/core/src/ContextMenu/ContextMenu.tsx@@ -54,6 +54,7 @@ import {LayerDepthProvider} from '../Layer/LayerDepthContext';import {useLayerDismissal} from '../Layer/useLayerDismissal';import {currentGesture} from '../Layer/gestureCounter';import {MenuBottomSheetActionList} from '../DropdownMenu/MenuBottomSheetActionList';+import {menuBottomSheetStyles} from '../DropdownMenu/menuBottomSheet.stylex';import {renderDropdownItems} from '../DropdownMenu/renderDropdownItems';import {DropdownMenuContext,@@ -176,6 +177,18 @@ const styles = stylex.create({outline: 'none',userSelect: 'none',},+ // The menu's own inset inside the sheet content box (menuBottomSheetStyles+ // .content): the 16px / 4px the sheet keeps plus the menu's 4px padding.+ sheetMenuInset: {+ paddingBlockStart: `calc(${spacingVars['--spacing-4']} + ${spacingVars['--spacing-1']})`,+ paddingBlockEnd: spacingVars['--spacing-1'],+ paddingInline: `calc(${spacingVars['--spacing-1']} + ${spacingVars['--spacing-1']})`,+ // Bleeding rows read the padding this element applies.+ '--container-padding-block-start': `calc(${spacingVars['--spacing-4']} + ${spacingVars['--spacing-1']})`,+ '--container-padding-block-end': spacingVars['--spacing-1'],+ '--container-padding-inline-start': `calc(${spacingVars['--spacing-1']} + ${spacingVars['--spacing-1']})`,+ '--container-padding-inline-end': `calc(${spacingVars['--spacing-1']} + ${spacingVars['--spacing-1']})`,+ },sheetHeader: {display: 'flex',flexDirection: 'row',@@ -728,7 +741,13 @@ export function ContextMenu({{...mergeProps(themeProps('context-menu'),stylex.props(- usesBottomSheet ? styles.sheetMenu : styles.menu,+ usesBottomSheet+ ? [+ styles.sheetMenu,+ menuBottomSheetStyles.content,+ styles.sheetMenuInset,+ ]+ : styles.menu,!usesBottomSheet &&(hasOverflow ? styles.touchPanYPinchZoom : styles.touchPinchZoom),xstyle,@@ -744,6 +763,24 @@ export function ContextMenu({</div>);+ // The root view's heading stands alone; a sub-menu's sits in a row with its+ // back button.+ const sheetViewHeading = (+ <Heading+ ref={setSheetHeadingRef}+ level={3}+ tabIndex={-1}+ xstyle={[+ styles.sheetViewHeading,+ submenuPath.length === 0 && [+ styles.sheetRootHeading,+ menuBottomSheetStyles.headingAlone,+ ],+ ]}>+ {currentTitle}+ </Heading>+ );+const renderedBottomSheetContent =itemsProp !== undefined ? (<div@@ -752,12 +789,17 @@ export function ContextMenu({tabIndex={0}{...mergeProps(themeProps('context-menu'),- stylex.props(styles.sheetMenu, xstyle),+ stylex.props(+ styles.sheetMenu,+ menuBottomSheetStyles.content,+ styles.sheetMenuInset,+ xstyle,+ ),className,style,)}>- <div {...stylex.props(styles.sheetHeader)}>- {submenuPath.length > 0 && (+ {submenuPath.length > 0 ? (+ <div {...stylex.props(styles.sheetHeader)}><Buttonlabel={backLabel}variant="ghost"@@ -768,18 +810,11 @@ export function ContextMenu({isIconOnlyonClick={() => setSubmenuPath(path => path.slice(0, -1))}/>- )}- <Heading- ref={setSheetHeadingRef}- level={3}- tabIndex={-1}- xstyle={[- styles.sheetViewHeading,- submenuPath.length === 0 && styles.sheetRootHeading,- ]}>- {currentTitle}- </Heading>- </div>+ {sheetViewHeading}+ </div>+ ) : (+ sheetViewHeading+ )}<MenuBottomSheetActionListitems={currentItems}onSelect={handleBottomSheetSelect}diff --git a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx b/packages/core/src/DropdownMenu/DropdownMenu.test.tsxindex 60c5d471b4..b154b7cfb6 100644--- a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx+++ b/packages/core/src/DropdownMenu/DropdownMenu.test.tsx@@ -176,10 +176,16 @@ describe('DropdownMenu', () => {const heading = screen.getByRole('heading', {name: 'Project actions'});expect(heading).toHaveStyle({marginInlineStart: 'var(--spacing-3)'});- expect(heading.closest('.astryx-section')).toHaveStyle({- paddingInlineStart: 'var(--spacing-1)',- paddingInlineEnd: 'var(--spacing-1)',+ // The menu's content element takes the sheet's content padding itself,+ // with no wrapper: 16px above the first row, 4px at the sides.+ const content = heading.closest('.astryx-dropdown-menu');+ expect(content?.parentElement?.closest('.astryx-section')).toBeNull();+ expect(content).toHaveStyle({+ paddingTop: 'var(--spacing-4)',+ paddingInline: 'var(--spacing-1)',});+ // The root heading stands alone, with no row wrapper.+ expect(heading.parentElement).toBe(content);expect(screen.getByRole('button', {name: 'Edit project'}).closest('li'),).toHaveStyle({@@ -188,6 +194,32 @@ describe('DropdownMenu', () => {});});+ it('renders nothing of the sheet at rest and keeps it through its exit', async () => {+ await warmMenuBottomSheet();+ const user = userEvent.setup();+ render(+ <DropdownMenu+ button={{label: 'Project actions'}}+ presentation="bottom-sheet"+ items={[{label: 'Edit project'}]}+ />,+ );+ expect(document.querySelector('dialog')).toBeNull();++ await user.click(screen.getByRole('button', {name: /Project actions/}));+ const dialog = document.querySelector('dialog');+ expect(dialog).not.toBeNull();++ await user.keyboard('{Escape}');+ // Closed, the sheet stays until its dialog has closed (its exit).+ expect(document.querySelector('dialog')).toBe(dialog);+ act(() => {+ dialog?.removeAttribute('open');+ dialog?.dispatchEvent(new Event('close'));+ });+ expect(document.querySelector('dialog')).toBeNull();+ });+it('keeps bottom-sheet section groups inside semantic list items', async () => {const user = userEvent.setup();diff --git a/packages/core/src/DropdownMenu/DropdownMenu.tsx b/packages/core/src/DropdownMenu/DropdownMenu.tsxindex 9127f0dfc2..55c9ed0164 100644--- a/packages/core/src/DropdownMenu/DropdownMenu.tsx+++ b/packages/core/src/DropdownMenu/DropdownMenu.tsx@@ -88,7 +88,9 @@ import {import {MenuBottomSheet,MenuBottomSheetActionList,+ preloadMenuBottomSheetActionList,} from './lazyMenuBottomSheet';+import {menuBottomSheetStyles} from './menuBottomSheet.stylex';import {layerAnimations} from '../Layer/layerAnimations.stylex';import type {LayerAlignment, LayerPlacement} from '../Layer/useLayer';import {@@ -653,6 +655,11 @@ function DropdownMenuBottomSheet({setSubmenuPath([]);}}+ // The closed sheet renders nothing, so load its rows at rest: the first+ // open shows the actions at once.+ useEffect(() => {+ preloadMenuBottomSheetActionList();+ }, []);const currentSubmenu = submenuPath.at(-1);const currentItems = currentSubmenu?.items ?? items;const currentTitle = currentSubmenu?.label ?? button.label;@@ -772,6 +779,23 @@ function DropdownMenuBottomSheet({setOpen(!isOpen);};+ // The root view's heading stands alone; a sub-menu's sits in a row with its+ // back button.+ const viewHeading = (+ <Heading+ ref={viewHeadingRef}+ level={3}+ tabIndex={-1}+ xstyle={[+ bottomSheetStyles.viewHeading,+ submenuPath.length === 0 && [+ bottomSheetStyles.rootHeading,+ menuBottomSheetStyles.headingAlone,+ ],+ ]}>+ {currentTitle}+ </Heading>+ );return (<>{renderTrigger != null ? (@@ -831,12 +855,16 @@ function DropdownMenuBottomSheet({{...rest}{...mergeProps(themeProps('dropdown-menu', {presentation: 'bottom-sheet'}),- stylex.props(bottomSheetStyles.content, xstyle),+ stylex.props(+ bottomSheetStyles.content,+ menuBottomSheetStyles.content,+ xstyle,+ ),className,style,)}>- <div {...stylex.props(bottomSheetStyles.header)}>- {submenuPath.length > 0 && (+ {submenuPath.length > 0 ? (+ <div {...stylex.props(bottomSheetStyles.header)}><Buttonlabel={backLabel}variant="ghost"@@ -851,18 +879,11 @@ function DropdownMenuBottomSheet({isIconOnlyonClick={() => setSubmenuPath(path => path.slice(0, -1))}/>- )}- <Heading- ref={viewHeadingRef}- level={3}- tabIndex={-1}- xstyle={[- bottomSheetStyles.viewHeading,- submenuPath.length === 0 && bottomSheetStyles.rootHeading,- ]}>- {currentTitle}- </Heading>- </div>+ {viewHeading}+ </div>+ ) : (+ viewHeading+ )}{isRenderable(header) && (<div {...stylex.props(bottomSheetStyles.region)}>{header}</div>)}diff --git a/packages/core/src/DropdownMenu/DropdownMenuSheetFirstOpen.test.tsx b/packages/core/src/DropdownMenu/DropdownMenuSheetFirstOpen.test.tsxnew file mode 100644index 0000000000..6b0e398f8d--- /dev/null+++ b/packages/core/src/DropdownMenu/DropdownMenuSheetFirstOpen.test.tsx@@ -0,0 +1,72 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file DropdownMenuSheetFirstOpen.test.tsx+ * @input vitest (jsdom), Testing Library, DropdownMenu, module mocks that+ * record when the lazily loaded sheet modules are requested and loaded+ * @output Checks that a bottom-sheet DropdownMenu loads its sheet and rows at+ * rest, so the first open renders the actions in the same commit, cold (no+ * warm-up)+ * @position Testing for DropdownMenu.tsx and lazyMenuBottomSheet.ts+ */++import {act, fireEvent, render, screen} from '@testing-library/react';+import {beforeEach, expect, it, vi} from 'vitest';+import {DropdownMenu} from './DropdownMenu';+import type * as MenuBottomSheetModule from './MenuBottomSheet';+import type * as ActionListModule from './MenuBottomSheetActionList';++const modules = vi.hoisted(() => ({+ requested: new Set<string>(),+ loaded: new Set<string>(),+}));++vi.mock('./MenuBottomSheet', async importOriginal => {+ modules.requested.add('sheet');+ const module = await importOriginal<typeof MenuBottomSheetModule>();+ modules.loaded.add('sheet');+ return module;+});++vi.mock('./MenuBottomSheetActionList', async importOriginal => {+ modules.requested.add('rows');+ const module = await importOriginal<typeof ActionListModule>();+ modules.loaded.add('rows');+ return module;+});++beforeEach(() => {+ HTMLDialogElement.prototype.showModal = vi.fn(function (+ this: HTMLDialogElement,+ ) {+ this.setAttribute('open', '');+ });+ HTMLDialogElement.prototype.close = vi.fn(function (this: HTMLDialogElement) {+ this.removeAttribute('open');+ });+});++it('loads the sheet and its rows at rest, so the first open renders the actions in the same commit', async () => {+ render(+ <DropdownMenu+ button={{label: 'Project actions'}}+ presentation="bottom-sheet"+ items={[{label: 'Edit project'}, {label: 'Archive'}]}+ />,+ );+ // Closed, the sheet renders nothing, yet both modules load.+ expect(document.querySelector('dialog')).toBeNull();+ await vi.waitFor(+ () => {+ expect([...modules.loaded].sort()).toEqual(['rows', 'sheet']);+ },+ {timeout: 15000},+ );++ // The rows render in the same commit as the opening: nothing suspends.+ act(() => {+ fireEvent.click(screen.getByRole('button', {name: /Project actions/}));+ });+ expect(screen.getByRole('button', {name: 'Edit project'})).toBeVisible();+ expect(screen.getByRole('button', {name: 'Archive'})).toBeVisible();+}, 20000);diff --git a/packages/core/src/DropdownMenu/MenuBottomSheet.tsx b/packages/core/src/DropdownMenu/MenuBottomSheet.tsxindex 9399dced90..d46c211fd8 100644--- a/packages/core/src/DropdownMenu/MenuBottomSheet.tsx+++ b/packages/core/src/DropdownMenu/MenuBottomSheet.tsx@@ -4,14 +4,19 @@/*** @file MenuBottomSheet.tsx- * @input Uses BottomSheet and Section- * @output Internal action-sheet host for menu content+ * @input Uses BottomSheet+ * @output Internal action-sheet host for menu content; nothing of the sheet renders while it is closed* @position Shared by DropdownMenu and ContextMenu adaptive presentations*/-import type {ReactNode, RefObject} from 'react';+import {+ useEffect,+ useRef,+ useState,+ type ReactNode,+ type RefObject,+} from 'react';import {BottomSheet} from '../BottomSheet/BottomSheet';-import {Section} from '../Section/Section';interface MenuBottomSheetProps {finalFocusRef?: RefObject<HTMLElement | null>;@@ -21,6 +26,13 @@ interface MenuBottomSheetProps {children: ReactNode;}+/**+ * The sheet renders nothing at rest (architecture:component-style-authoring+ * INV7): it mounts as it opens, and after it closes it stays only until its+ * dialog has closed, so the exit plays out and focus returns to the trigger.+ * The sheet has no content padding: callers inset their content with+ * menuBottomSheetStyles.content, so no wrapper sits between the sheet and it.+ */export function MenuBottomSheet({finalFocusRef,isOpen,@@ -28,17 +40,40 @@ export function MenuBottomSheet({label,children,}: MenuBottomSheetProps) {+ const [isMounted, setIsMounted] = useState(isOpen);+ if (isOpen && !isMounted) {+ setIsMounted(true);+ }+ const panelRef = useRef<HTMLDivElement | null>(null);+ useEffect(() => {+ if (isOpen || !isMounted) {+ return;+ }+ const dialog = panelRef.current?.closest('dialog');+ if (dialog == null || !dialog.open) {+ // eslint-disable-next-line @eslint-react/set-state-in-effect -- the native <dialog> has already closed, so the exit is over: unmount the sheet+ setIsMounted(false);+ return;+ }+ const handleClose = () => setIsMounted(false);+ dialog.addEventListener('close', handleClose);+ return () => dialog.removeEventListener('close', handleClose);+ }, [isMounted, isOpen]);++ if (!isMounted) {+ return null;+ }return (<BottomSheet+ ref={panelRef}finalFocusRef={finalFocusRef}isOpen={isOpen}onOpenChange={onOpenChange}label={label}height="hug"+ padding={0}purpose="info">- <Section paddingBlockStart={4} paddingBlockEnd={0} paddingInline={1}>- {children}- </Section>+ {children}</BottomSheet>);}diff --git a/packages/core/src/DropdownMenu/lazyMenuBottomSheet.ts b/packages/core/src/DropdownMenu/lazyMenuBottomSheet.tsindex 14f31a70e0..f8784d44d3 100644--- a/packages/core/src/DropdownMenu/lazyMenuBottomSheet.ts+++ b/packages/core/src/DropdownMenu/lazyMenuBottomSheet.ts@@ -25,12 +25,14 @@ import {createElement,lazy,Suspense,+ useState,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';+import type * as ActionListModule from './MenuBottomSheetActionList';const LazyMenuBottomSheet = lazy(async () =>import('./MenuBottomSheet').then(module => ({@@ -38,8 +40,27 @@ const LazyMenuBottomSheet = lazy(async () =>})),);+// The action list renders inside the sheet, which renders nothing while+// closed, so its first render is the first open. Once preloaded, it renders+// directly instead of through lazy(): a suspended render on open would hold+// the rows back (React delays revealing them for up to 300ms).+let actionListModule: typeof ActionListModule | null = null;+let actionListLoad: Promise<typeof ActionListModule> | null = null;+async function loadActionList(): Promise<typeof ActionListModule> {+ actionListLoad ??= import('./MenuBottomSheetActionList').then(module => {+ actionListModule = module;+ return module;+ });+ return actionListLoad;+}++/** Starts loading the action list; a sheet menu calls it at rest. */+export function preloadMenuBottomSheetActionList(): void {+ void loadActionList();+}+const LazyMenuBottomSheetActionList = lazy(async () =>- import('./MenuBottomSheetActionList').then(module => ({+ loadActionList().then(module => ({default: module.MenuBottomSheetActionList,})),);@@ -60,12 +81,17 @@ export function MenuBottomSheet(export function MenuBottomSheetActionList(props: ComponentProps<typeof EagerMenuBottomSheetActionList>,): ReactElement | null {+ // Chosen once per mount, so a module that arrives later never swaps the+ // rendered list (which would remount it and drop focus).+ const [LoadedActionList] = useState(+ () => actionListModule?.MenuBottomSheetActionList ?? null,+ );if (useIsHydrating()) {return null;}return createElement(Suspense,{fallback: null},- createElement(LazyMenuBottomSheetActionList, props),+ createElement(LoadedActionList ?? LazyMenuBottomSheetActionList, props),);}diff --git a/packages/core/src/DropdownMenu/menuBottomSheet.stylex.ts b/packages/core/src/DropdownMenu/menuBottomSheet.stylex.tsnew file mode 100644index 0000000000..1bdb8442d8--- /dev/null+++ b/packages/core/src/DropdownMenu/menuBottomSheet.stylex.ts@@ -0,0 +1,33 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file menuBottomSheet.stylex.ts+ * @input Uses StyleX and the spacing tokens+ * @output Exports menuBottomSheetStyles, the content box of a menu's sheet+ * @position Shared by DropdownMenu and ContextMenu sheet content+ */++import * as stylex from '@stylexjs/stylex';+import {spacingVars} from '../theme/tokens.stylex';++export const menuBottomSheetStyles = stylex.create({+ // The menu's own content element carries the inset a wrapper used to:+ // MenuBottomSheet gives the sheet no content padding, and this element+ // keeps 16px above the first row and 4px at the sides. The container+ // variables tell bleeding children the padding actually applied.+ content: {+ boxSizing: 'border-box',+ paddingBlockStart: spacingVars['--spacing-4'],+ paddingBlockEnd: 0,+ paddingInline: spacingVars['--spacing-1'],+ '--container-padding-inline-start': spacingVars['--spacing-1'],+ '--container-padding-inline-end': spacingVars['--spacing-1'],+ '--container-padding-block-start': spacingVars['--spacing-4'],+ '--container-padding-block-end': '0px',+ },+ // The heading alone, without a back button beside it, keeps the row's gap+ // to the actions.+ headingAlone: {+ marginBottom: spacingVars['--spacing-2'],+ },+});