diff --git a/.changeset/createcontextmenu-element-options-attaches-conte-k1sw.md b/.changeset/createcontextmenu-element-options-attaches-conte-k1sw.md new file mode 100644 index 0000000000000..8daf9928da83d --- /dev/null +++ b/.changeset/createcontextmenu-element-options-attaches-conte-k1sw.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[feat] `createContextMenu(element, options)` attaches ContextMenu's menu to any element, without wrapping it, and `useContextMenu(ref, options)` does the same from a component. A ListItem row passes its ref, so the list keeps `ul > li`, with no wrapper element, and its dividers. The menu opens on a long press, a right click, Shift+F10 or the context-menu key, and `destroy` removes every listener and node it added. + +@vjeux diff --git a/apps/storybook/stories/ContextMenu.stories.tsx b/apps/storybook/stories/ContextMenu.stories.tsx index 891b4ca1c4aa1..b868062e04bbb 100644 --- a/apps/storybook/stories/ContextMenu.stories.tsx +++ b/apps/storybook/stories/ContextMenu.stories.tsx @@ -1,14 +1,17 @@ // Copyright (c) Meta Platforms, Inc. and affiliates. import type {Meta, StoryObj} from '@storybook/react'; -import {useState} from 'react'; +import {useEffect, useRef, useState} from 'react'; import { ContextMenu, ContextMenuItem, ContextMenuCheckboxItem, ContextMenuRadioGroup, ContextMenuRadioItem, + createContextMenu, + useContextMenu, } from '@astryxdesign/core/ContextMenu'; import {Divider} from '@astryxdesign/core/Divider'; +import {List, ListItem} from '@astryxdesign/core/List'; import { PencilIcon, TrashIcon, @@ -647,3 +650,139 @@ export const BottomSheetSubmenu: Story = { } }, }; + +const headlessStyles = stylex.create({ + list: { + listStyle: 'none', + margin: 0, + padding: 0, + maxWidth: '320px', + }, + row: { + padding: '12px 16px', + borderBottomWidth: '1px', + borderBottomStyle: 'solid', + borderBottomColor: '#e5e7eb', + userSelect: 'none', + }, + listItems: { + maxWidth: '320px', + }, +}); + +/** + * Four rows of a list: the second carries a menu from the framework-agnostic + * createContextMenu, the third and fourth from useContextMenu. The list keeps + * only `li` children; the menus render outside it. The log below the list + * records what the page saw, for the interaction tests. + */ +function HeadlessRows() { + const plainRowRef = useRef(null); + const hookRowRef = useRef(null); + const contentRowRef = useRef(null); + const [log, setLog] = useState>([]); + const record = (entry: string) => setLog(entries => [...entries, entry]); + useEffect(() => { + const row = plainRowRef.current; + if (row == null) { + return; + } + const menu = createContextMenu(row, { + label: 'Inbox actions', + onOpenChange: isOpen => record(isOpen ? 'open' : 'close'), + items: [ + {label: 'Archive', onClick: () => record('archive')}, + {label: 'Delete', variant: 'destructive', onClick: () => {}}, + ], + }); + return () => menu.destroy(); + }, []); + useContextMenu(hookRowRef, { + label: 'Sent actions', + items: [{label: 'Forward', onClick: () => record('forward')}], + }); + useContextMenu(contentRowRef, { + label: 'Archive actions', + menuContent: ( + record('restore')} /> + ), + }); + return ( +
+
    +
  • + Drafts +
  • +
  • record('row-click')} + {...stylex.props(headlessStyles.row)}> + Inbox +
  • +
  • + Sent +
  • +
  • + Archive +
  • +
+ {log.join(',')} +
+ ); +} + +export const HeadlessOnAListRow: Story = { + name: 'Headless / createContextMenu on a list row', + parameters: { + docs: { + description: { + story: + 'createContextMenu attaches ContextMenu to an element that is already on the page, here a list row, without React; useContextMenu does the same from a component. A held finger, a right click, Shift+F10 or the context-menu key opens it.', + }, + }, + }, + render: () => , +}; + +/** A ListItem whose row menu attaches to its own `li`. */ +function RowWithMenu({label}: {label: string}) { + const rowRef = useRef(null); + useContextMenu(rowRef, { + label: `Actions for ${label}`, + items: [ + {label: 'Archive', onClick: () => {}}, + {label: 'Delete', variant: 'destructive', onClick: () => {}}, + ], + }); + return ; +} + +export const HeadlessOnListItems: Story = { + name: 'Headless / useContextMenu on ListItem rows', + parameters: { + docs: { + description: { + story: + 'Each ListItem passes its ref to useContextMenu, so the menu attaches to the row itself: the list keeps `ul > li`, with no wrapper element, and its dividers. A ContextMenu around a ListItem would put a wrapper between the list and its row.', + }, + }, + }, + render: () => ( + + + + + + + ), +}; diff --git a/docs/specs/components/ContextMenu/ContextMenu.spec.md b/docs/specs/components/ContextMenu/ContextMenu.spec.md index af08cfd78df09..7046df4a48655 100644 --- a/docs/specs/components/ContextMenu/ContextMenu.spec.md +++ b/docs/specs/components/ContextMenu/ContextMenu.spec.md @@ -78,6 +78,9 @@ Consumer migration instructions belong in consumer docs and release notes. `context-menu` target. - Cursor-anchor placement across the two presentation paths, and open state (FR10). +- The menu root in `ContextMenu.tsx` that ContextMenu and `createContextMenu` + both render: the menu, its open state, outside press, and focus return. + Only `ContextMenu.tsx` and `createContextMenu.tsx` use it. **Does not own / non-goals** @@ -112,7 +115,7 @@ Consumer props, content modes, and presentation policy remain documented in | FR7 | Sub-menu rows follow `component:DropdownMenu` FR11 inside the pointer menu: ContextMenu mounts the same drill-in view stack, named after its `label`, so a sub-menu drills in on a phone here too. A sub-menu with a header or footer shows its rows alone here (`component:DropdownMenu` FR20). | `component:DropdownMenu/DEC-4` | | FR8 | In the pointer menu ArrowDown on the last row wraps to the first and ArrowUp on the first to the last; PageDown and PageUp page as in `component:DropdownMenu` FR12; a held key's auto-repeat does not activate; typeahead matches the row's label element alone. A disabled row is reached by these keys and by typeahead and stays inert, as `component:DropdownMenu` FR17 states. | Current source and tests | | FR9 | While the Pointer menu surface is open, it participates in `family:overlay-dismissal` through the shared stack and provides descendant depth. One Escape press affects only the top-most present nested surface; ContextMenu closes only when it is that surface. | `family:overlay-dismissal` FR1–FR6; `ContextMenu.test.tsx` nested-layer case | -| FR10 | ContextMenu MUST be built on the public headless context menu (`spec:AST-107` FR8), with its invocation, open state, and cleanup the factory's and no behavior of its own beside the factory's. Implementation gap: no headless context menu ships; ContextMenu owns its invocation, open state, outside-press listener, and cleanup itself. | `spec:AST-107` FR8 | +| FR10 | ContextMenu MUST be built on the public headless context menu (`spec:AST-107` FR8), with its invocation, open state, and cleanup the factory's and no behavior of its own beside the factory's. Implementation gap: ContextMenu and `createContextMenu` share one menu, open state, outside-press listener, and cleanup, but ContextMenu takes its invocation on its own wrapper element instead of through the factory. | `spec:AST-107` FR8 | | FR11 | Tab or Shift+Tab on a row of the pointer menu, its own or an open sub-menu flyout's at any depth, closes every open level and the menu and calls `onOpenChange(false)` once, as `component:DropdownMenu` FR23 states for its menu. | WAI-ARIA Menu Button pattern; current tests | ### Allowed variation @@ -268,9 +271,10 @@ anchor is positioning infrastructure rather than consumer anatomy. ## Current-state impact -- **No headless factory (FR10).** No headless context menu ships, so ContextMenu - owns its invocation, open state, and outside-press listener itself, against - `spec:AST-107` FR8. +- **ContextMenu beside the factory (FR10).** `createContextMenu` and + `useContextMenu` share ContextMenu's menu, open state, and outside-press + listener, but ContextMenu takes its invocation on its own wrapper element + instead of through the factory, against `spec:AST-107` FR8. - **Touch grow, pan dismissal, handoff, and lift (FR5).** A touch-opened menu keeps the layer's own entrance and exit instead of growing from the finger, a scroll that starts outside leaves it open, the held finger that diff --git a/docs/specs/components/List/List.spec.md b/docs/specs/components/List/List.spec.md index 4018fad06fcc2..2a8205f86d5b6 100644 --- a/docs/specs/components/List/List.spec.md +++ b/docs/specs/components/List/List.spec.md @@ -54,15 +54,15 @@ system_specs: ## Contract at a glance -| Area | Contract | -| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| Public contract | Optional `edge?: 'padded' \| 'flush' \| 'outset' \| 'bleed'`, default `'padded'`. Deprecated `edgeCompensation?: 'inline'` resolves to `'outset'`. Optional `reorderable` takes the object `createReorderable` returns, and ListItem's `itemKey` identifies each row (`spec:AST-103`). Optional `animatedLayout` takes the handle `useAnimatedLayout` returns (`spec:AST-105`). | -| Behavior | One edge treatment applies to every ListItem row and decides where row content and row paint sit relative to the list's edges and the host's padding. With `reorderable`, rows reorder by dragging a handle or through reorder mode (`spec:AST-103` FR3, FR4). Under a coarse pointer a row's press follows the cell profile (`spec:AST-094` FR11); with `animatedLayout`, row updates animate (`spec:AST-105`). A row menu opens from the row's own `
  • ` on the context request (FR13). | -| End-user impact | Row text can share the line of the list header and a heading above, with row paint stopping at the text, reaching into the host padding, or reaching the host edges. Touch users get a 44 px row target (FR10) and the cell press (FR11), and every pointer keeps a highlighted row's dividers visible (FR11); with `animatedLayout`, row updates animate for every pointer (FR12). A row with a menu opens it by a long press, a right click, or Shift+F10, or through its More actions button (FR13). | -| Builder impact | One `edge` choice per list. `flush` works anywhere; `outset` and `bleed` act only inside a host that publishes container padding. Passing an `animatedLayout` handle is one new choice, and a row menu is the other: the caller passes a ListItem's ref to `useContextMenu` (FR13), and who draws a plain row's More actions button is open (OQ2); and rows animate only with an `itemKey`; the touch target and press need none. | -| Compatibility/readiness | Additive; omission keeps current geometry; `edgeCompensation` keeps working with a codemod to `edge`. `reorderable` is stable; `spec:AST-103` FR1 gap: `createReorderable` takes no `labels` or `positions`. FR12 gap: with a handle, rows keyed by `itemKey` report inserts, removals and moves, but a change to a row's start or end content does not animate. The touch target (FR10) and the press's compositor release (FR11) apply under coarse primary pointers, and neither changes anything under a fine pointer. FR11's divider rule applies to every pointer. Row menus (FR13) are additive; FR13 gap: a long press, a right click, or Shift+F10 on a ListItem row opens no row menu. | -| Review checks | Reject header movement, row paint past the host's padding edge, duplicated padding values, physical-edge logic, automatic opt-in, a ListItem-level edge prop, or a second prop that can contradict `edge`. | -| Governing rules | `architecture:container-padding/INV3`, `INV9–INV11`; `spec:AST-002/DEC-1–DEC-2`; `spec:AST-017/FR4`; `spec:AST-057/FR9`. `spec:AST-103`. `spec:AST-094` FR4, FR5, FR11, FR13; `spec:AST-105` FR1–FR5, FR8. `spec:AST-107` FR8 (row menus). | +| Area | Contract | +| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| Public contract | Optional `edge?: 'padded' \| 'flush' \| 'outset' \| 'bleed'`, default `'padded'`. Deprecated `edgeCompensation?: 'inline'` resolves to `'outset'`. Optional `reorderable` takes the object `createReorderable` returns, and ListItem's `itemKey` identifies each row (`spec:AST-103`). Optional `animatedLayout` takes the handle `useAnimatedLayout` returns (`spec:AST-105`). | +| Behavior | One edge treatment applies to every ListItem row and decides where row content and row paint sit relative to the list's edges and the host's padding. With `reorderable`, rows reorder by dragging a handle or through reorder mode (`spec:AST-103` FR3, FR4). Under a coarse pointer a row's press follows the cell profile (`spec:AST-094` FR11); with `animatedLayout`, row updates animate (`spec:AST-105`). A row menu opens from the row's own `
  • ` on the context request (FR13). | +| End-user impact | Row text can share the line of the list header and a heading above, with row paint stopping at the text, reaching into the host padding, or reaching the host edges. Touch users get a 44 px row target (FR10) and the cell press (FR11), and every pointer keeps a highlighted row's dividers visible (FR11); with `animatedLayout`, row updates animate for every pointer (FR12). A row with a menu opens it by a long press, a right click, or Shift+F10, or through its More actions button (FR13). | +| Builder impact | One `edge` choice per list. `flush` works anywhere; `outset` and `bleed` act only inside a host that publishes container padding. Passing an `animatedLayout` handle is one new choice, and a row menu is the other: the caller passes a ListItem's ref to `useContextMenu` (FR13), and who draws a plain row's More actions button is open (OQ2); and rows animate only with an `itemKey`; the touch target and press need none. | +| Compatibility/readiness | Additive; omission keeps current geometry; `edgeCompensation` keeps working with a codemod to `edge`. `reorderable` is stable; `spec:AST-103` FR1 gap: `createReorderable` takes no `labels` or `positions`. FR12 gap: with a handle, rows keyed by `itemKey` report inserts, removals and moves, but a change to a row's start or end content does not animate. The touch target (FR10) and the press's compositor release (FR11) apply under coarse primary pointers, and neither changes anything under a fine pointer. FR11's divider rule applies to every pointer. Row menus (FR13) attach to the row's own `
  • ` and open on a long press, a right click, or Shift+F10. FR13 gap: a row does not lift under a finger. The More actions button and the focus target are open (OQ2). | +| Review checks | Reject header movement, row paint past the host's padding edge, duplicated padding values, physical-edge logic, automatic opt-in, a ListItem-level edge prop, or a second prop that can contradict `edge`. | +| Governing rules | `architecture:container-padding/INV3`, `INV9–INV11`; `spec:AST-002/DEC-1–DEC-2`; `spec:AST-017/FR4`; `spec:AST-057/FR9`. `spec:AST-103`. `spec:AST-094` FR4, FR5, FR11, FR13; `spec:AST-105` FR1–FR5, FR8. `spec:AST-107` FR8 (row menus). | This table is a review projection; the body below is authoritative. diff --git a/internal/shadcn-registry/routes.lock.json b/internal/shadcn-registry/routes.lock.json index 60ce1aa074a1f..0378c6b6ff9b7 100644 --- a/internal/shadcn-registry/routes.lock.json +++ b/internal/shadcn-registry/routes.lock.json @@ -4208,6 +4208,11 @@ "path": "hooks/create-animator", "aliases": [] }, + { + "name": "hook-create-context-menu", + "path": "hooks/create-context-menu", + "aliases": [] + }, { "name": "hook-create-drag-to-snap-points", "path": "hooks/create-drag-to-snap-points", @@ -4313,6 +4318,11 @@ "path": "hooks/use-container-reveal", "aliases": [] }, + { + "name": "hook-use-context-menu", + "path": "hooks/use-context-menu", + "aliases": [] + }, { "name": "hook-use-dev-warning", "path": "hooks/use-dev-warning", diff --git a/packages/cli/foundation/doc-compiler/inputs.test.mjs b/packages/cli/foundation/doc-compiler/inputs.test.mjs index 98014c6c40f27..a5462b7777b34 100644 --- a/packages/cli/foundation/doc-compiler/inputs.test.mjs +++ b/packages/cli/foundation/doc-compiler/inputs.test.mjs @@ -124,6 +124,7 @@ describe('collectDocInputs over what this repo ships', () => { 'Resizable', 'SyntaxTheme', 'createAnimator', + 'createContextMenu', 'createDragToSnapPoints', 'createPanGesture', ]); diff --git a/packages/core/src/ContextMenu/ContextMenu.doc.mjs b/packages/core/src/ContextMenu/ContextMenu.doc.mjs index 7a4d71c712e73..2bed7a75aeace 100644 --- a/packages/core/src/ContextMenu/ContextMenu.doc.mjs +++ b/packages/core/src/ContextMenu/ContextMenu.doc.mjs @@ -201,6 +201,11 @@ export const docs = { description: 'Place more than 10–12 items in a single menu without grouping them into sections.', }, + { + guidance: false, + description: + 'Wrap a ListItem in a ContextMenu: the wrapper sits between the list and its row. Pass the row\u2019s ref to `useContextMenu` instead, which attaches the same menu to the row itself.', + }, ], }, playground: { diff --git a/packages/core/src/ContextMenu/ContextMenu.tsx b/packages/core/src/ContextMenu/ContextMenu.tsx index d1ecf61136901..f78758f818890 100644 --- a/packages/core/src/ContextMenu/ContextMenu.tsx +++ b/packages/core/src/ContextMenu/ContextMenu.tsx @@ -6,8 +6,10 @@ * @input Uses React, StyleX, useLayer, shared layer dismissal, the lazily * loaded menu sheet (DropdownMenu/lazyMenuBottomSheet), useListFocus, and the * shared menu-presentation resolver - * @output Exports ContextMenu with cursor-popover and touch-sheet presentations - * @position Core implementation; consumed by index.ts + * @output Exports ContextMenu with cursor-popover and touch-sheet presentations, + * and ContextMenuAttached, the same menu for the element createContextMenu + * attaches it to (internal) + * @position Core implementation; consumed by index.ts and createContextMenu.tsx * * Right-click context menu positioned at the cursor. The cursor point is * captured as an offset *inside the trigger* and materialized as a 1px @@ -36,6 +38,7 @@ * SYNC: When modified, update these files to stay in sync: * - /packages/core/src/ContextMenu/ContextMenu.doc.mjs * - /packages/core/src/ContextMenu/ContextMenu.test.tsx + * - /packages/core/src/ContextMenu/createContextMenu.tsx (ContextMenuAttached) * - /packages/core/src/ContextMenu/index.ts * - /apps/storybook/stories/ContextMenu.stories.tsx * - /packages/cli/assets/templates/blocks/components/ContextMenu/ (showcase blocks) @@ -45,6 +48,7 @@ import React, { useCallback, useEffect, useId, + useImperativeHandle, useMemo, useRef, useState, @@ -145,6 +149,12 @@ const styles = stylex.create({ height: '1px', pointerEvents: 'none', }, + // The headless context menu's anchor: it lives in the factory's own + // container, outside the element, at a client point + // (createContextMenu.tsx). + cursorAnchorAttached: { + position: 'fixed', + }, menu: { boxSizing: 'border-box', display: 'flex', @@ -259,6 +269,38 @@ function keepAnchorInside(offset: number, size: number): number { return offset > size - 1 && offset <= size ? Math.max(size - 1, 0) : offset; } +/** The client point of an element's bottom-left corner, where a request without a point opens. */ +function bottomLeftOf(element: HTMLElement): {x: number; y: number} { + const box = element.getBoundingClientRect(); + return {x: box.left, y: box.bottom}; +} + +/** + * The `left` and `top` that put a fixed box's corner at a client point. A + * fixed box's containing block is the viewport unless an ancestor sets one + * up (a transform, a filter, `contain: paint`), as a Drawer's dialog does + * while it is open. The box's drawn rect at its current inline offsets, which + * its render always sets, gives the block's origin, and its drawn size + * against its layout size gives the block's scale. It only reads, so the + * caller's one measurement pass comes before its one write. + */ +function fixedOffsetOfClientPoint( + box: HTMLElement, + point: {x: number; y: number}, +): {x: number; y: number} { + const drawn = box.getBoundingClientRect(); + const width = box.offsetWidth; + const height = box.offsetHeight; + const scaleX = width > 0 ? drawn.width / width || 1 : 1; + const scaleY = height > 0 ? drawn.height / height || 1 : 1; + const left = Number.parseFloat(box.style.left) || 0; + const top = Number.parseFloat(box.style.top) || 0; + return { + x: left + (point.x - drawn.left) / scaleX, + y: top + (point.y - drawn.top) / scaleY, + }; +} + // ============================================================================= // Types // ============================================================================= @@ -333,6 +375,45 @@ interface ContextMenuCompoundProps extends ContextMenuBaseProps { export type ContextMenuProps = ContextMenuDataProps | ContextMenuCompoundProps; +/** + * @internal A request the headless context menu forwards to the menu + * (createContextMenu.tsx): what made it, and its client point, none for a + * key or for `open()` without one. + */ +export interface ContextMenuAttachedRequest { + readonly kind: 'hold' | 'pointer' | 'keyboard' | 'open'; + readonly point: {readonly x: number; readonly y: number} | null; +} + +/** @internal How the headless context menu opens and closes the menu. */ +export interface ContextMenuAttachedHandle { + open(request: ContextMenuAttachedRequest): void; + close(): void; +} + +/** + * @internal The element the headless context menu attaches the menu to, + * which is the trigger, and the handle its own open() and close() reach the + * menu through. + */ +export interface ContextMenuAttachment { + readonly element: HTMLElement; + readonly handleRef: React.Ref; +} + +/** @internal The menu createContextMenu renders for its element. */ +export type ContextMenuAttachedProps = Pick< + ContextMenuBaseProps, + 'label' | 'isDisabled' | 'onOpenChange' | 'presentation' +> & {attachment: ContextMenuAttachment} & ( + | {items: ContextMenuOption[]; menuContent?: undefined} + | {items?: undefined; menuContent: ReactNode} + ); + +type ContextMenuRootProps = ContextMenuProps & { + attachment?: ContextMenuAttachment | null; +}; + // ============================================================================= // ContextMenu // ============================================================================= @@ -360,7 +441,17 @@ export type ContextMenuProps = ContextMenuDataProps | ContextMenuCompoundProps; * * ``` */ -export function ContextMenu({ +export function ContextMenu(props: ContextMenuProps) { + return ; +} + +/** + * ContextMenu's menu and its trigger, or, given an `attachment`, the menu + * alone for the element the headless context menu attaches it to + * (createContextMenu.tsx): that element is the trigger, and the factory's + * requests reach the menu through the attachment's handle. + */ +function ContextMenuRoot({ children, menuWidth, size = 'md', @@ -380,8 +471,9 @@ export function ContextMenu({ onTouchEnd: onTouchEndProp, onTouchCancel: onTouchCancelProp, 'data-testid': testId, + attachment = null, ...rest -}: ContextMenuProps) { +}: ContextMenuRootProps) { const t = useComponentTranslator(); const label = labelFromProps ?? t('@astryx.contextMenu.label'); const backLabel = t('@astryx.dropdownMenu.back'); @@ -467,13 +559,20 @@ export function ContextMenu({ onHide: useCallback(() => { setIsOpen(false); onOpenChange?.(false); - // Restore focus to the element that was focused before opening. + // Restore focus to the element that was focused before opening. An + // attached element can sit in a shadow root, which `document.contains` + // does not see into. const toRestore = triggerFocusRef.current; triggerFocusRef.current = null; - if (toRestore && document.contains(toRestore)) { + if ( + toRestore && + (attachment != null + ? toRestore.isConnected + : document.contains(toRestore)) + ) { toRestore.focus(); } - }, [onOpenChange]), + }, [onOpenChange, attachment]), onShow: useCallback(() => { setIsOpen(true); onOpenChange?.(true); @@ -688,6 +787,48 @@ export function ContextMenu({ [getAnchorBaseRect, layer, updateOpenState, usesBottomSheet], ); + // The headless context menu's open (createContextMenu.tsx). Its anchor is + // a fixed box in the factory's own container, at the request's client + // point. A key's request, and open() without a point, open at the + // element's bottom-left corner, as the trigger's keyboard path does. + // Focus returns to the element on close. + const openAttached = useCallback( + (request: ContextMenuAttachedRequest) => { + if (attachment == null || isDisabled) { + return; + } + const {element} = attachment; + const anchorEl = cursorAnchorRef.current; + // One measurement pass per open, before the one write: the element's + // box, then the anchor's drawn box where it is now. + const point = request.point ?? bottomLeftOf(element); + const offset = + anchorEl != null ? fixedOffsetOfClientPoint(anchorEl, point) : point; + positionRef.current = offset; + if (anchorEl != null) { + anchorEl.style.left = `${offset.x}px`; + anchorEl.style.top = `${offset.y}px`; + } + // A held finger is still down: its compatibility mousedown belongs to + // the press that opened the menu. + openingGestureRef.current = + request.kind === 'hold' ? currentGesture() : null; + triggerFocusRef.current = element; + if (usesBottomSheet) { + updateOpenState(true); + } else { + focusOnShowRef.current = true; + layer.show(); + } + }, + [attachment, isDisabled, layer, updateOpenState, usesBottomSheet], + ); + useImperativeHandle( + attachment?.handleRef, + () => ({open: openAttached, close: () => closeMenu()}), + [openAttached, closeMenu], + ); + const handleContextMenu = useCallback( (e: React.MouseEvent) => { if (isDisabled) { @@ -944,11 +1085,57 @@ export function ContextMenu({ const SheetForContent = usesSheetActionList ? MenuBottomSheet : MenuBottomSheetWithoutActionList; + const triggerElementRef = useMergedRefs(ref, triggerRef); + const cursorAnchorElementRef = useMergedRefs(cursorAnchorRef, layer.ref); + + const cursorAnchor = ( +
  • + {label} +
  • + ); + } + render( +
      + {['Inbox', 'Sent', 'Drafts', 'Spam', 'Trash'].map(label => ( + + ))} +
    , + ); + expect(renders).toBe(0); + rightClick(screen.getByText('Inbox')); + expect(isOpen()).toBe(true); + expect(renders).toBe(1); + act(() => { + menus[0].close(); + }); + rightClick(screen.getByText('Inbox')); + expect(isOpen()).toBe(true); + expect(renders).toBe(1); + }); + + it('hands the public createContextMenu a `render` for menuContent, and nothing else (spec:AST-107 FR8, FR6)', () => { + vi.mocked(createContextMenu).mockClear(); + render( + + Custom + + } + />, + ); + expect(vi.mocked(createContextMenu)).toHaveBeenCalledTimes(1); + const [element, options] = vi.mocked(createContextMenu).mock.calls[0] ?? []; + expect(element).toBe(screen.getByText('Inbox')); + expect( + Object.keys(options ?? {}).filter(key => !FACTORY_OPTIONS.has(key)), + ).toEqual([]); + expect(typeof options?.render).toBe('function'); + expect(options?.items).toBeUndefined(); + expect(options?.label).toBe('Inbox actions'); + }); + + it('passes `presentation` to the factory, as ContextMenu does', () => { + vi.mocked(createContextMenu).mockClear(); + render(); + expect(vi.mocked(createContextMenu).mock.calls[0]?.[1]).toMatchObject({ + presentation: 'popover', + }); + }); + + it("a DropdownMenuItem in menuContent keeps the menu's behavior: choosing it closes the menu", async () => { + const onArchive = vi.fn(); + render( + } + />, + ); + rightClick(screen.getByText('Inbox')); + expect(isOpen()).toBe(true); + await waitFor(() => + expect(document.activeElement).toBe( + screen.getByRole('menuitem', {name: 'Archive', hidden: true}), + ), + ); + // A key chooses the row: jsdom's pointer click lands on a row the close + // has already taken out of the page, which no browser does (the browser + // check is the interaction spec's). + await userEvent.setup().keyboard('{Enter}'); + expect(onArchive).toHaveBeenCalledTimes(1); + await waitFor(() => expect(isOpen()).toBe(false)); + }); + + it('a layer inside menuContent takes Escape before the menu, as in ContextMenu', () => { + const onNestedDismiss = vi.fn(); + render( + } + />, + ); + rightClick(screen.getByText('Inbox')); + expect(isOpen()).toBe(true); + const nested = screen.getByRole('button', { + name: 'Nested layer', + hidden: true, + }); + nested.focus(); + fireEvent.keyDown(nested, {key: 'Escape'}); + expect(onNestedDismiss).toHaveBeenCalledOnce(); + expect(isOpen()).toBe(true); + fireEvent.keyDown(document, {key: 'Escape'}); + expect(isOpen()).toBe(false); + }); + + it('open() and close() drive the menu', () => { + const onOpenChange = vi.fn(); + render(); + act(() => { + controls.open({x: 10, y: 10}); + }); + expect(isOpen()).toBe(true); + act(() => { + controls.close(); + }); + expect(isOpen()).toBe(false); + expect(onOpenChange.mock.calls).toEqual([[true], [false]]); + }); + + it('follows isDisabled: the browser keeps its menu while disabled', () => { + const view = render(); + expect(rightClick(screen.getByText('Inbox')).defaultPrevented).toBe(false); + expect(isOpen()).toBe(false); + view.rerender(); + expect(rightClick(screen.getByText('Inbox')).defaultPrevented).toBe(true); + expect(isOpen()).toBe(true); + }); + + it('unmounting removes the menu and everything it added', () => { + const view = render(); + const element = screen.getByText('Inbox'); + rightClick(element); + view.unmount(); + expect(isOpen()).toBe(false); + expect(document.querySelector('[role="menu"]')).toBeNull(); + expect(rightClick(element).defaultPrevented).toBe(false); + }); +}); + +describe('useContextMenu: its element and its React roots', () => { + it('is exported from the hooks entry point, as AST-107 imports it (spec:AST-107 FR6)', () => { + expect(hooks.useContextMenu).toBe(useContextMenu); + }); + + it('attaches to the element its ref points at now, when that element changes', () => { + function Switching({which}: {which: 'a' | 'b'}) { + const ref = useRef(null); + useContextMenu(ref, {items: [{label: 'Rename'}], label: 'Row actions'}); + return ( +
      + {which === 'a' ? ( +
    • + A +
    • + ) : ( +
    • + B +
    • + )} +
    + ); + } + const view = render(); + view.rerender(); + const request = rightClick(screen.getByTestId('row-b')); + expect(request.defaultPrevented).toBe(true); + expect(isOpen()).toBe(true); + }); + + it('unmounting leaves React no root to unmount during its own commit, so it logs no error', () => { + const errors = vi.spyOn(console, 'error'); + try { + const view = render( + } + />, + ); + rightClick(screen.getByText('Inbox')); + expect(isOpen()).toBe(true); + view.unmount(); + const messages = errors.mock.calls.map(call => String(call[0])); + expect( + messages.filter(message => + message.includes('synchronously unmount a root'), + ), + ).toEqual([]); + } finally { + errors.mockRestore(); + } + }); +}); diff --git a/packages/core/src/ContextMenu/useContextMenu.tsx b/packages/core/src/ContextMenu/useContextMenu.tsx new file mode 100644 index 0000000000000..c95765ec8c28e --- /dev/null +++ b/packages/core/src/ContextMenu/useContextMenu.tsx @@ -0,0 +1,258 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file useContextMenu.tsx + * @input A ref to the element, and createContextMenu's options with a + * ReactNode `menuContent` + * @output useContextMenu: the React wrapper over createContextMenu, + * returning `{open, close}`; exported from the hooks entry point + * (@astryxdesign/core/hooks) and from ContextMenu's + * @position Public hook over the public factory: it hands createContextMenu + * a `render` that portals `menuContent` into the menu's container, carries + * the caller's Core providers (theme, layer, link, i18n) into the menu, and + * passes later options through updateContextMenu. `menuContent` renders + * at the menu's first open, as the factory fills the menu, in a root the + * hook owns, into a host the menu's container adopts (contextMenuRows.tsx), + * and stays rendered after; its rows read the menu's own row context, open + * state, layer and layer depth + */ + +import { + useCallback, + useEffect, + useLayoutEffect, + useMemo, + useRef, + type ReactNode, + type RefObject, +} from 'react'; +import {createPortal} from 'react-dom'; +import {createRoot} from 'react-dom/client'; +import type {AdaptivePresentation} from '../hooks/useAdaptivePresentation'; +import {useCommittedRef} from '../hooks/useCommittedRef'; +import type {ContextMenuOption} from './ContextMenu'; +import { + createMenuRowsSlot, + MenuRows, + useCoreBridge, + type CoreBridge, +} from './contextMenuRows'; +import { + bridgeContextMenu, + destroyContextMenuFromReact, + createContextMenu, + updateContextMenu, + type ContextMenuController, + type ContextMenuPoint, + type CreateContextMenuOptions, +} from './createContextMenu'; + +interface UseContextMenuSharedOptions { + /** Names the menu for assistive technology. */ + label?: string; + /** While true, the element makes no context request and keeps the browser's own menu. */ + isDisabled?: boolean; + /** Called with true when the menu opens and false when it closes. */ + onOpenChange?: (isOpen: boolean) => void; + /** Where the menu appears, as ContextMenu's `presentation`. */ + presentation?: AdaptivePresentation; +} + +export type UseContextMenuOptions = UseContextMenuSharedOptions & + ( + | {items: ReadonlyArray; menuContent?: undefined} + | {items?: undefined; menuContent: ReactNode} + ); + +/** What useContextMenu returns. */ +export interface UseContextMenuResult { + /** Opens the menu at `at`, client coordinates; at the element without it. */ + open: (at?: ContextMenuPoint) => void; + /** Closes the menu. */ + close: () => void; +} + +/** + * `menuContent`, rendered in a root the hook owns, into its slot, from the + * menu's first open on. + */ +interface MenuContentPortal { + /** + * The factory's `render`, which runs at the menu's first open: the + * container adopts the slot's host, and the content renders there. + */ + readonly render: (container: HTMLElement) => () => void; + /** Keeps `content` with the caller's providers, and renders it once drawn. */ + draw(content: ReactNode, wrap: CoreBridge): void; + unmount(): void; +} + +function createMenuContentPortal(doc: Document): MenuContentPortal { + const slot = createMenuRowsSlot(doc); + const root = createRoot(doc.createElement('div')); + // A menu that never opens renders nothing: a list with a menu on every row + // draws one row's content only when that row's menu opens. + let latest: {content: ReactNode; wrap: CoreBridge} | null = null; + let isDrawn = false; + const paint = () => { + if (latest == null) { + return; + } + root.render( + createPortal( + latest.wrap({latest.content}), + slot.host, + ), + ); + }; + return { + render(container) { + const cleanup = slot.render(container); + if (!isDrawn) { + isDrawn = true; + paint(); + } + return cleanup; + }, + draw(content, wrap) { + latest = {content, wrap}; + if (isDrawn) { + paint(); + } + }, + unmount() { + slot.host.remove(); + // Called from an effect's cleanup: React cannot unmount a root while + // it commits another, so this one renders nothing instead, an update + // React takes in its own time, and is dropped with its node. + root.render(null); + }, + }; +} + +function factoryOptions( + options: UseContextMenuOptions, + onOpenChange: (isOpen: boolean) => void, + portal: MenuContentPortal | null, +): CreateContextMenuOptions { + const shared = { + label: options.label, + isDisabled: options.isDisabled, + onOpenChange, + presentation: options.presentation, + }; + return portal != null + ? {...shared, render: portal.render} + : {...shared, items: options.items ?? []}; +} + +/** The element the hook's menu is attached to, and how to detach it. */ +interface Attached { + element: HTMLElement; + hasContent: boolean; + detach: () => void; +} + +/** + * Attaches a context menu to the element `ref` points at: + * it opens on that element's context request, and unmounting removes it. + * When the ref moves to another element, the menu moves with it. + */ +export function useContextMenu( + ref: RefObject, + options: UseContextMenuOptions, +): UseContextMenuResult { + const wrap = useCoreBridge(); + const hasContent = options.menuContent !== undefined; + const latestRef = useCommittedRef({options, wrap}); + const controllerRef = useRef(null); + const portalRef = useRef(null); + const attachedRef = useRef(null); + const handleOpenChange = useCallback( + (isOpen: boolean) => { + latestRef.current.options.onOpenChange?.(isOpen); + }, + [latestRef], + ); + + // Syncs the factory's menu with this render's options, the caller's + // providers and `menuContent`. + useLayoutEffect(() => { + const controller = controllerRef.current; + if (controller == null) { + return; + } + const portal = portalRef.current; + updateContextMenu( + controller, + factoryOptions(options, handleOpenChange, portal), + ); + bridgeContextMenu(controller, wrap); + if (portal != null) { + portal.draw(options.menuContent, wrap); + } + }); + + // Every commit checks the element the ref points at now: a ref moved to + // another element moves the menu with it. + useEffect(() => { + const element = ref.current; + const attached = attachedRef.current; + if ( + attached != null && + attached.element === element && + attached.hasContent === hasContent + ) { + return; + } + attached?.detach(); + attachedRef.current = null; + if (element == null) { + return; + } + const latest = latestRef.current; + const portal = hasContent + ? createMenuContentPortal(element.ownerDocument) + : null; + portal?.draw(latest.options.menuContent, latest.wrap); + const controller = createContextMenu( + element, + factoryOptions(latest.options, handleOpenChange, portal), + ); + bridgeContextMenu(controller, latest.wrap); + controllerRef.current = controller; + portalRef.current = portal; + attachedRef.current = { + element, + hasContent, + detach: () => { + destroyContextMenuFromReact(controller); + portal?.unmount(); + if (controllerRef.current === controller) { + controllerRef.current = null; + portalRef.current = null; + } + }, + }; + }); + + // Syncs the factory's menu with this component's life: unmounting destroys + // the menu and everything it added. + useEffect( + () => () => { + attachedRef.current?.detach(); + attachedRef.current = null; + }, + [], + ); + + return useMemo( + () => ({ + open: (at?: ContextMenuPoint) => controllerRef.current?.open(at), + close: () => controllerRef.current?.close(), + }), + [], + ); +} diff --git a/packages/core/src/List/__tests__/ListItemContextMenu.test.tsx b/packages/core/src/List/__tests__/ListItemContextMenu.test.tsx new file mode 100644 index 0000000000000..3a3b8fe78d08d --- /dev/null +++ b/packages/core/src/List/__tests__/ListItemContextMenu.test.tsx @@ -0,0 +1,145 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file ListItemContextMenu.test.tsx + * @input vitest (jsdom), a List whose rows pass their ref to useContextMenu, + * and the same List with ContextMenu around each row + * @output Checks a row menu on a ListItem: it attaches to the row's own `li`, + * so the list keeps `ul > li` with no wrapper, each row keeps the classes + * it draws its divider with, and a right click opens the row's menu. The + * ContextMenu wrapper's `ul > div > li` is the control that shows the + * check finds a wrapper. + * @position Testing for List.tsx and ListItem.tsx with useContextMenu + */ + +import {act, render} from '@testing-library/react'; +import {useRef} from 'react'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import {ContextMenu} from '../../ContextMenu/ContextMenu'; +import {useContextMenu} from '../../ContextMenu/useContextMenu'; +import {List} from '../List'; +import {ListItem} from '../ListItem'; + +const LABELS = ['Inbox', 'Sent', 'Drafts', 'Archive']; + +beforeEach(() => { + HTMLElement.prototype.showPopover = vi.fn(function (this: HTMLElement) { + this.setAttribute('popover-open', ''); + }); + HTMLElement.prototype.hidePopover = vi.fn(function (this: HTMLElement) { + this.removeAttribute('popover-open'); + }); +}); + +afterEach(() => { + vi.restoreAllMocks(); +}); + +function RowWithMenu({label}: {label: string}) { + const rowRef = useRef(null); + useContextMenu(rowRef, { + label: `Actions for ${label}`, + items: [{label: 'Archive'}, {label: 'Delete'}], + }); + return ; +} + +function listOf(container: HTMLElement): HTMLUListElement { + const list = container.querySelector('ul'); + if (list == null) { + throw new Error('no list'); + } + return list; +} + +describe('a row menu on a ListItem (useContextMenu)', () => { + it('attaches to the row\u2019s own li: the list keeps ul > li with no wrapper', () => { + const {container} = render( + + {LABELS.map(label => ( + + ))} + , + ); + const list = listOf(container); + expect(Array.from(list.children, child => child.tagName)).toEqual( + LABELS.map(() => 'LI'), + ); + expect(Array.from(list.children, child => child.textContent)).toEqual( + LABELS, + ); + // The menus render outside the list. + expect(list.querySelector('[role="menu"]')).toBeNull(); + }); + + it('keeps each row\u2019s divider classes: the rows draw what rows without a menu draw', () => { + const withMenus = render( + + {LABELS.map(label => ( + + ))} + , + ); + const classesWithMenus = Array.from( + listOf(withMenus.container).children, + row => row.className, + ); + withMenus.unmount(); + const withoutMenus = render( + + {LABELS.map(label => ( + + ))} + , + ); + expect( + Array.from(listOf(withoutMenus.container).children, row => row.className), + ).toEqual(classesWithMenus); + }); + + it('a right click on a row opens its menu, named for that row', () => { + const {container} = render( + + {LABELS.map(label => ( + + ))} + , + ); + const sent = listOf(container).children[1]; + act(() => { + sent.dispatchEvent( + new MouseEvent('contextmenu', { + bubbles: true, + cancelable: true, + clientX: 40, + clientY: 50, + button: 2, + }), + ); + }); + const menu = document.querySelector( + '[role="menu"][aria-label="Actions for Sent"]', + ); + expect(menu?.closest('[popover]')?.hasAttribute('popover-open')).toBe(true); + }); + + it('control: ContextMenu around a ListItem puts a wrapper between the list and its row', () => { + const {container} = render( + + {LABELS.map(label => ( + + + + ))} + , + ); + const list = listOf(container); + expect( + Array.from(list.children).filter(child => child.tagName !== 'LI'), + ).not.toHaveLength(0); + expect(list.querySelectorAll(':scope > li')).toHaveLength(0); + expect(list.querySelectorAll(':scope > div > li')).toHaveLength( + LABELS.length, + ); + }); +}); diff --git a/packages/core/src/hooks/index.ts b/packages/core/src/hooks/index.ts index 1e338cb75a9ef..43e79927751b9 100644 --- a/packages/core/src/hooks/index.ts +++ b/packages/core/src/hooks/index.ts @@ -143,6 +143,14 @@ export type { export {useLongPress} from './useLongPress'; export type {UseLongPressOptions, UseLongPressHandlers} from './useLongPress'; +// Lives beside ContextMenu, which shares its menu, and is exported here with +// the other public gesture hooks. +export {useContextMenu} from '../ContextMenu/useContextMenu'; +export type { + UseContextMenuOptions, + UseContextMenuResult, +} from '../ContextMenu/useContextMenu'; + export {usePressFeedback} from './usePressFeedback'; export {useDevWarning} from './useDevWarning'; diff --git a/scripts/touch-support-bundle.test.mjs b/scripts/touch-support-bundle.test.mjs index 461085606560a..866c216df82b2 100644 --- a/scripts/touch-support-bundle.test.mjs +++ b/scripts/touch-support-bundle.test.mjs @@ -351,6 +351,9 @@ const GESTURE_USERS = new Set([ 'hooks: usePanGesture', // The snap-point drag, which moves an element on that pan. 'hooks: useDragToSnapPoints', + // The headless context menu: its element opens on a held finger's long + // press. + 'hooks: useContextMenu', // Snap paging: the pager, under a finger and on a trackpad swipe. Carousel // imports none of it. 'SnapPaging',