diff --git a/.changeset/table-cell-lazy-context-menu.md b/.changeset/table-cell-lazy-context-menu.md new file mode 100644 index 0000000000000..015f4276ae863 --- /dev/null +++ b/.changeset/table-cell-lazy-context-menu.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[perf] TableCell and TableHeaderCell load their right-click context menu only when the cell has `contextMenuActions`. A table without context menus no longer ships ContextMenu, DropdownMenu's menu code and the touch sheet: a page that renders Table, Text and Button loads about 23 to 25 KB less JavaScript (gzip) on first load in Vite, Rolldown and webpack. A cell with actions renders its content at once and starts loading its menu on its first client render; the content keeps its DOM node, focus and state when the menu attaches. A right-click, Shift+F10 or long press that arrives before then is held and opens the cell's menu when it loads, unless another press or key comes first, so the browser's own menu does not appear. If the menu code fails to load, the table stays and the browser's own menu returns; a later mount, or a later right-click or touch on that cell, asks the module loader again. A test that expects the menu synchronously right after render has to wait for it to load. `resolveContextActions` keeps its export and no longer pulls the menu in. + +@rhagigi @cixzhang diff --git a/docs/architecture/component-import-boundaries.md b/docs/architecture/component-import-boundaries.md index ce8d680ce5ae0..8d8f0b2133e23 100644 --- a/docs/architecture/component-import-boundaries.md +++ b/docs/architecture/component-import-boundaries.md @@ -84,7 +84,9 @@ one allowlist row. A module that an `import()` targets is a surface module. Some modules in a surface or capability folder are base code: the trigger contract a surface folder keeps for base imports -(`Tooltip/tooltipPresentInterest`, `Layer/layerScopedContext`), and a +(`Tooltip/tooltipPresentInterest`, `Layer/layerScopedContext`, +`ContextMenu/ContextMenuTrigger`, and `Layer/gestureCounter`, which a trigger +reads to drop a held intent at a later press or key), and a capability's own import (a Table plugin's folder index and the modules it re-exports, and `SnapPaging/SnapPaging`). INV7's wiring lives in base code: the component's own modules or the capability's own import. A wiring module @@ -221,20 +223,20 @@ one pending load per module, caches a success, and resets after a failure. ### Allowlist -| Crossing (base module → module it imports statically) | Entries that reach it | Cost, gzip | Invariant | Row leaves when | -| ----------------------------------------------------------------- | ---------------------------------------------- | ---------------------- | ---------- | ------------------------------------------------------------------------------------------------------ | -| `Text/TruncationTooltip` → `Layer/gestureCounter` | Text, Heading, Button, IconButton, Link, Table | 1.7 KB (Text, Heading) | INV1, INV8 | the truncation tooltip's eager code carries no touch tap recognizer; the row moves with the recognizer | -| `Button/Button` → `Tooltip/useTooltip` | Button, IconButton | 19.5 KB | INV1 | Button's tooltip layer code is lazy | -| `Link/Link` → `Tooltip` | Link | 21.6 KB | INV1 | Link's tooltip layer code is lazy | -| `Table/tableContextMenu` → `ContextMenu` | Table | 88.5 KB | INV1 | cells without actions reach no menu module | -| `Table/BaseTable` → `Table/plugins/virtualization/useTableWindow` | Table | 3.6 KB | INV7 | a Table that never windows reaches neither the controller nor its engine | +| Crossing (base module → module it imports statically) | Entries that reach it | Cost, gzip | Invariant | Row leaves when | +| ----------------------------------------------------------------- | ---------------------------------------------- | ---------------------- | ---------- | ---------------------------------------------------------------------------------------------------------------------------------- | +| `Text/TruncationTooltip` → `Layer/gestureCounter` | Text, Heading, Button, IconButton, Link, Table | 1.7 KB (Text, Heading) | INV1, INV8 | the truncation tooltip's eager code carries no touch tap recognizer; the row moves with the recognizer | +| `Button/Button` → `Tooltip/useTooltip` | Button, IconButton | 19.7 KB | INV1 | Button's tooltip layer code is lazy | +| `Link/Link` → `Tooltip` | Link | 21.7 KB | INV1 | Link's tooltip layer code is lazy | +| `Table/TableCellContextMenu` → `Layer/gestureCounter` | Table | 0.0 KB | INV8 | a cell's menu wrapper reads the gesture identity from a module without the touch tap recognizer; the row moves with the recognizer | +| `Table/BaseTable` → `Table/plugins/virtualization/useTableWindow` | Table | 3.5 KB | INV7 | a Table that never windows reaches neither the controller nor its engine | Costs are the check's own printout in CI: each crossing's removal from the entry with every other crossing kept, in the entry build above. A local run on another platform or Node version can print gzip sizes a few tenths of a KB apart. Rows share modules, so they do not add up. The truncation tooltip's touch code costs Button, IconButton, Link, and Table nothing on its own, because another of their -crossings brings the same module. Table carries 134.5 KB eager. +crossings brings the same module. Table carries 50.5 KB eager. ### Must not reach @@ -268,16 +270,13 @@ an allowlist row does. `Popover`, and `ContextMenu` are not in INV9's entry list, and `DropdownMenu` is an entry whose crossings are not checked. - INV1 gap: Button's and IconButton's imports reach the tooltip hook and the - layer runtime, 19.5 KB gzip, with or without a `tooltip` prop. Through + layer runtime, 19.7 KB gzip, with or without a `tooltip` prop. Through Button, Link, or their own code, 32 of Core's 95 component imports that are not surfaces carry 17–24 KB of tooltip code, and 52 carry at least 1 KB. - INV1 gap: Link's import reaches the Tooltip component and the layer - runtime, 21.6 KB gzip, with or without a `tooltip` prop. -- INV1 gap: Table's import reaches the cell context menu, 88.5 KB gzip, for - cells with no actions, while `component:TableCell` PR1 loads a menu only - when actions are given. + runtime, 21.7 KB gzip, with or without a `tooltip` prop. - INV7 gap: Table's import reaches the window controller and the shared - windowing module, 3.6 KB gzip, for a Table that never windows. + windowing module, 3.5 KB gzip, for a Table that never windows. - INV3 gap: no record says how a tooltip's description reaches assistive technology before its surface loads, for the triggers whose tooltip is their description. diff --git a/docs/specs/components/ContextMenu/ContextMenu.spec.md b/docs/specs/components/ContextMenu/ContextMenu.spec.md index af08cfd78df09..d4d387965ebdb 100644 --- a/docs/specs/components/ContextMenu/ContextMenu.spec.md +++ b/docs/specs/components/ContextMenu/ContextMenu.spec.md @@ -78,6 +78,14 @@ 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). +- `ContextMenuTrigger`, the internal module that renders the Trigger area's + wrapper and its cursor anchor. ContextMenu renders it, and a table cell + renders it before its menu code loads, so the cell's content keeps its node + when the menu attaches. It imports no menu code, so a base import can carry + it (`architecture:component-import-boundaries` INV1). +- `ContextMenuForTrigger`, the internal mode that opens the same menu around a + trigger the caller already renders (a table cell), since `ContextMenu` + renders its own trigger. No public entry exports either module. **Does not own / non-goals** @@ -112,7 +120,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: no headless context menu ships; ContextMenu owns its invocation, open state, outside-press listener, and cleanup itself. Table cells open the same menu through the internal `ContextMenuForTrigger` mode, around a trigger the cell renders. The cell holds an invocation that arrives before the menu loads. | `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 @@ -270,7 +278,10 @@ anchor is positioning infrastructure rather than consumer anatomy. - **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. + `spec:AST-107` FR8. Table cells open the same menu through the internal + `ContextMenuForTrigger` mode, around a trigger the cell renders, and the cell + holds an invocation that arrives before the menu loads. Both are part of + this gap. - **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/Table/TableCell.spec.md b/docs/specs/components/Table/TableCell.spec.md index 7997fb4e54a86..6fcbb116cb665 100644 --- a/docs/specs/components/Table/TableCell.spec.md +++ b/docs/specs/components/Table/TableCell.spec.md @@ -14,6 +14,12 @@ verified_by: [ packages/core/src/Table/Table.test.tsx, packages/core/src/Table/tableContextMenu.test.tsx, + packages/core/src/Table/TableCellContextMenu.test.tsx, + packages/core/src/Table/TableCellContextMenu.touch.test.tsx, + packages/core/src/Table/TableCellContextMenu.modality.test.tsx, + packages/core/src/Table/TableCellContextMenu.ssr.test.tsx, + packages/core/src/Table/TableCellContextMenu.loadFailure.test.tsx, + packages/core/src/Table/__tests__/TableCellMenuLoad.a11y.chromium.spec.ts, packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.test.tsx, packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.glide.test.tsx, packages/core/src/Table/__tests__/TableRowGlide.a11y.browser.spec.ts, @@ -131,7 +137,11 @@ Consumer migration instructions belong in consumer docs and release notes. ### Performance and resources - **PR1 — No resources.** TableCell reads the Table's appearance; a context - menu loads only when actions are given. + menu loads only when actions are given. A cell with actions starts the + menu load at its first client render after the hydrating render, before + any intent (`architecture:component-import-boundaries` INV2). A + right-click, Shift+F10, or long press made before the menu arrives is held + and replayed once, as that record's INV4 states. ## Accessibility contract @@ -156,15 +166,15 @@ its own, so no anatomy-theming block is declared here. ## Verification map -| Contract | Verification | Representative states | Mutation or failure expectation | Audit section | -| ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------- | -| FR1, AR1 | `Table.test.tsx` children-mode and density-reflection tests; `themingTargets.test.ts` | Children mode; each density | A missing cell, a lost target, or a missing `data-density` fails. `themingTargets.test.ts` catches only a renamed or undocumented target. | `audit:TableCell/anatomy` | -| FR2 | `Table.test.tsx` density, overflow, divider, and vertical-alignment tests; `TableRowGlide.a11y.browser.spec.ts`; `useTableRowExpansion.glide.test.tsx` | Densities; wrap and truncate; dividers; mid-glide, pinned cells, themed and overridden dividers | A mid-glide divider that does not move with its row, or the line on the wrong cell, fails in the glide checks. A truncating Table whose data-mode cells lose their truncating text wrapper, or a cell without the requested `vertical-align`, fails. Gap: the density and divider tests assert only that the table renders, and no test covers the cell's own truncation. | `audit:TableCell/layout` | -| FR3 | Source review | Inside Card, Section, Layout | Gap: no test covers edge cells aligning to the container inset. | `audit:TableCell/layout` | -| FR4 | `tableContextMenu.test.tsx` body-cell row-actions and full-cell tests; `useTableRowExpansion.test.tsx` context-menu action test | Body cell with a list; body cell with a getter (expandable rows); full-cell trigger | A body cell that ignores its action list or getter fails. Gap: the full-cell test checks only that the trigger has a class, so a trigger that does not fill the cell passes; no test covers an empty list or the edge-cell padding outside the trigger. | `audit:TableCell/behavior` | -| FR5, ORD1 | `Table.test.tsx` TableCell ref, `colSpan`, and `rowSpan` tests | `ref`; `colSpan`, `rowSpan` | A ref off the `td` or a dropped `colSpan` or `rowSpan` fails. Gap: no TableCell test covers event props, `xstyle`, `className`, `style`, or the order in which caller styles follow the Table's treatment. | `audit:TableCell/api` | -| PR1 | Source review | Every state | Gap: no automated check covers lazy context-menu loading. | `audit:TableCell/behavior` | -| RTL relation | RTL audit curated D2 and D8 targets (`apps/storybook/rtl-audit/targets.json`) on the `In Card` story | A Card with `padding={0}`, where the first column's logical inline-start padding differs from its inline-end padding; LTR and RTL | A first column not at the inline start, or an edge padding that stays on the same physical side in RTL, fails D2 or D8. | `audit:TableCell/i18n-rtl` | +| Contract | Verification | Representative states | Mutation or failure expectation | Audit section | +| ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------- | +| FR1, AR1 | `Table.test.tsx` children-mode and density-reflection tests; `themingTargets.test.ts` | Children mode; each density | A missing cell, a lost target, or a missing `data-density` fails. `themingTargets.test.ts` catches only a renamed or undocumented target. | `audit:TableCell/anatomy` | +| FR2 | `Table.test.tsx` density, overflow, divider, and vertical-alignment tests; `TableRowGlide.a11y.browser.spec.ts`; `useTableRowExpansion.glide.test.tsx` | Densities; wrap and truncate; dividers; mid-glide, pinned cells, themed and overridden dividers | A mid-glide divider that does not move with its row, or the line on the wrong cell, fails in the glide checks. A truncating Table whose data-mode cells lose their truncating text wrapper, or a cell without the requested `vertical-align`, fails. Gap: the density and divider tests assert only that the table renders, and no test covers the cell's own truncation. | `audit:TableCell/layout` | +| FR3 | Source review | Inside Card, Section, Layout | Gap: no test covers edge cells aligning to the container inset. | `audit:TableCell/layout` | +| FR4 | `tableContextMenu.test.tsx` body-cell row-actions and full-cell tests; `useTableRowExpansion.test.tsx` context-menu action test | Body cell with a list; body cell with a getter (expandable rows); full-cell trigger | A body cell that ignores its action list or getter fails. Gap: the full-cell test checks only that the trigger has a class, so a trigger that does not fill the cell passes; no test covers an empty list or the edge-cell padding outside the trigger. | `audit:TableCell/behavior` | +| FR5, ORD1 | `Table.test.tsx` TableCell ref, `colSpan`, and `rowSpan` tests | `ref`; `colSpan`, `rowSpan` | A ref off the `td` or a dropped `colSpan` or `rowSpan` fails. Gap: no TableCell test covers event props, `xstyle`, `className`, `style`, or the order in which caller styles follow the Table's treatment. | `audit:TableCell/api` | +| PR1 | `TableCellContextMenu.test.tsx` no-load and loaded-cell tests; the menu-load scenario tests; `TableCellContextMenu` touch, modality, SSR and load-failure tests; `TableCellMenuLoad.a11y.chromium.spec.ts` | No actions; actions before and after the menu loads; early right-click, Shift+F10 and long press; server render and hydration; a failed menu load | A cell without actions that loads the menu fails. Content that remounts or loses focus or state when the menu loads fails. An early invocation that is lost, doubled or replayed after a later press fails. A hydration error, or a failed load that unmounts the table or never retries, fails. | `audit:TableCell/behavior` | +| RTL relation | RTL audit curated D2 and D8 targets (`apps/storybook/rtl-audit/targets.json`) on the `In Card` story | A Card with `padding={0}`, where the first column's logical inline-start padding differs from its inline-end padding; LTR and RTL | A first column not at the inline start, or an edge padding that stays on the same physical side in RTL, fails D2 or D8. | `audit:TableCell/i18n-rtl` | ## Decision log diff --git a/docs/specs/components/Table/TableHeaderCell.spec.md b/docs/specs/components/Table/TableHeaderCell.spec.md index cb2a9f35bec72..477eab0087ce0 100644 --- a/docs/specs/components/Table/TableHeaderCell.spec.md +++ b/docs/specs/components/Table/TableHeaderCell.spec.md @@ -126,10 +126,14 @@ Consumer migration instructions belong in consumer docs and release notes. ### Performance and resources -- **PR1 — Few resources.** TableHeaderCell reads the Table's appearance. Its - only state is FR2's cut-heading tooltip: the heading it measured on - keyboard focus. It measures nothing and mounts no tooltip at rest; the - Tooltip module loads after the first render, as tooltip code does. +- **PR1 — Resources.** TableHeaderCell reads the Table's appearance. Its only + state is FR2's cut-heading tooltip: the heading it measured on keyboard + focus. It measures nothing and mounts no tooltip at rest; the Tooltip module + loads after the first render, as tooltip code does. A header cell with + actions starts the menu load at its first client render after the hydrating + render, before any intent (`architecture:component-import-boundaries` INV2), + as `component:TableCell` PR1 does; a right-click, Shift+F10 or long press + made before the menu arrives is held and replayed once (INV4). ## Accessibility contract @@ -157,15 +161,15 @@ block is declared here. ## Verification map -| Contract | Verification | Representative states | Mutation or failure expectation | Audit section | -| ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------- | -| FR1, AR1 | `TableHeaderCell.test.tsx` element, scope, and outside-Table tests; `Table.test.tsx` density-reflection test; `themingTargets.test.ts` | Default; `scope`; standalone; densities | A non-`th` element, an unrequested or missing `scope`, styling outside a Table, or a missing target or `data-density` fails. `themingTargets.test.ts` catches only a renamed or undocumented target. | `audit:TableHeaderCell/anatomy` | -| FR2 | `TableHeaderCell.test.tsx` density, weight and color, bottom divider, and column divider tests | Three densities; dividers off, rows, columns, grid | Wrong density padding, weight, or color, a missing bottom divider, or a wrong column divider fails. Gap: truncation and edge alignment have no check. | `audit:TableHeaderCell/layout` | -| FR2 tooltip | `TableHeaderCell.truncationTooltip.test.tsx` (cut heading on keyboard focus of a sortable header, no `aria-describedby`; blur closes; hover shows nothing; fitting heading; select-all cell; nothing measured at rest); real-browser focus and hover | Plain and sortable header cells, cut and fitting headings | A cut heading without a tooltip, a fitting one with one, a duplicate description, or a layout read at rest. | `audit:TableHeaderCell/layout` | -| FR3 | `tableContextMenu.test.tsx` header context-menu tests | Header cell with actions | A header cell with actions that does not open its menu, or one without actions that does, fails. | `audit:TableHeaderCell/behavior` | -| FR4, ORD1 | `TableHeaderCell.test.tsx` xstyle, array xstyle, ref, attribute, and className and style tests | Caller inputs | A ref off the `th`, a dropped attribute, context styling that beats `xstyle`, or a lost caller class or style fails. | `audit:TableHeaderCell/api` | -| PR1 | Source review | Every state | Gap: no automated check fails if TableHeaderCell adds state beyond FR2's tooltip. | `audit:TableHeaderCell/behavior` | -| RTL relation | RTL audit curated D2 and D8 targets (`apps/storybook/rtl-audit/targets.json`) on the `In Card` story | A Card with `padding={0}`, where the first column's logical inline-start padding differs from its inline-end padding; LTR and RTL | A first column not at the inline start, or an edge padding that stays on the same physical side in RTL, fails D2 or D8. | `audit:TableHeaderCell/i18n-rtl` | +| Contract | Verification | Representative states | Mutation or failure expectation | Audit section | +| ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------- | +| FR1, AR1 | `TableHeaderCell.test.tsx` element, scope, and outside-Table tests; `Table.test.tsx` density-reflection test; `themingTargets.test.ts` | Default; `scope`; standalone; densities | A non-`th` element, an unrequested or missing `scope`, styling outside a Table, or a missing target or `data-density` fails. `themingTargets.test.ts` catches only a renamed or undocumented target. | `audit:TableHeaderCell/anatomy` | +| FR2 | `TableHeaderCell.test.tsx` density, weight and color, bottom divider, and column divider tests | Three densities; dividers off, rows, columns, grid | Wrong density padding, weight, or color, a missing bottom divider, or a wrong column divider fails. Gap: truncation and edge alignment have no check. | `audit:TableHeaderCell/layout` | +| FR2 tooltip | `TableHeaderCell.truncationTooltip.test.tsx` (cut heading on keyboard focus of a sortable header, no `aria-describedby`; blur closes; hover shows nothing; fitting heading; select-all cell; nothing measured at rest); real-browser focus and hover | Plain and sortable header cells, cut and fitting headings | A cut heading without a tooltip, a fitting one with one, a duplicate description, or a layout read at rest. | `audit:TableHeaderCell/layout` | +| FR3 | `tableContextMenu.test.tsx` header context-menu tests | Header cell with actions | A header cell with actions that does not open its menu, or one without actions that does, fails. | `audit:TableHeaderCell/behavior` | +| FR4, ORD1 | `TableHeaderCell.test.tsx` xstyle, array xstyle, ref, attribute, and className and style tests | Caller inputs | A ref off the `th`, a dropped attribute, context styling that beats `xstyle`, or a lost caller class or style fails. | `audit:TableHeaderCell/api` | +| PR1 | Source review (no state beyond FR2's tooltip); `TableHeaderCellContextMenu.test.tsx` early Shift+F10 case | Every state; a sortable header cell with actions before and after the menu loads | Gap: no automated check fails if TableHeaderCell adds state beyond FR2's tooltip. A held Shift+F10 that is lost, doubled, or remounts the focused header control fails. Gap: no header-cell test asserts the load starts after the hydrating render, or covers an early right-click or long press on a header cell; the `component:TableCell` PR1 cases cover the shared menu wrapper. | `audit:TableHeaderCell/behavior` | +| RTL relation | RTL audit curated D2 and D8 targets (`apps/storybook/rtl-audit/targets.json`) on the `In Card` story | A Card with `padding={0}`, where the first column's logical inline-start padding differs from its inline-end padding; LTR and RTL | A first column not at the inline start, or an edge padding that stays on the same physical side in RTL, fails D2 or D8. | `audit:TableHeaderCell/i18n-rtl` | ## Decision log diff --git a/packages/core/src/ContextMenu/ContextMenu.test.tsx b/packages/core/src/ContextMenu/ContextMenu.test.tsx index ab315cfd9611a..4c70da1a9f18a 100644 --- a/packages/core/src/ContextMenu/ContextMenu.test.tsx +++ b/packages/core/src/ContextMenu/ContextMenu.test.tsx @@ -745,7 +745,7 @@ describe('ContextMenu', () => { it('suppresses native text selection on the long-press trigger', () => { const source = readFileSync( - 'packages/core/src/ContextMenu/ContextMenu.tsx', + 'packages/core/src/ContextMenu/ContextMenuTrigger.tsx', 'utf8', ); diff --git a/packages/core/src/ContextMenu/ContextMenu.tsx b/packages/core/src/ContextMenu/ContextMenu.tsx index a9f98961c0fed..7b949014238ef 100644 --- a/packages/core/src/ContextMenu/ContextMenu.tsx +++ b/packages/core/src/ContextMenu/ContextMenu.tsx @@ -32,6 +32,8 @@ * The trigger wrapper is a `div` by default; `triggerAs` makes it an inline * `span`, so a reference inside prose can own a context menu without * breaking the text flow. + * `ContextMenuForTrigger` runs this menu on a trigger its caller renders. + * Table cells use it to load the menu after their content. * * SYNC: When modified, update these files to stay in sync: * - /packages/core/src/ContextMenu/ContextMenu.doc.mjs @@ -39,6 +41,7 @@ * - /packages/core/src/ContextMenu/index.ts * - /apps/storybook/stories/ContextMenu.stories.tsx * - /packages/cli/assets/templates/blocks/components/ContextMenu/ (showcase blocks) + * - /packages/core/src/ContextMenu/ContextMenuTrigger.tsx (trigger and anchor) */ import React, { @@ -51,9 +54,9 @@ import React, { } from 'react'; import type {ReactNode} from 'react'; import * as stylex from '@stylexjs/stylex'; -import {Button} from '../Button'; -import {Heading} from '../Heading'; -import {Icon} from '../Icon'; +import {Button} from '../Button/Button'; +import {Heading} from '../Heading/Heading'; +import {Icon} from '../Icon/Icon'; import {useLayerInternal} from '../Layer/useLayer'; import {LayerDepthProvider} from '../Layer/LayerDepthContext'; import {useLayerDismissal} from '../Layer/useLayerDismissal'; @@ -95,7 +98,8 @@ import { easeVars, shadowVars, } from '../theme/tokens.stylex'; -import {mergeProps, rtlStyles} from '../utils'; +import {mergeProps} from '../utils/mergeProps'; +import {rtlStyles} from '../utils/rtlStyles'; import type {BaseProps} from '../BaseProps'; import type {StyleXStyles} from '../theme/types'; import {themeProps} from '../utils/themeProps'; @@ -107,6 +111,14 @@ import type { } from '../DropdownMenu/DropdownMenu'; import {useMergedRefs} from '../hooks/useMergedRefs'; +import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect'; +import { + ContextMenuTrigger, + anchorBase, + contextMenuPoint, + longPressPoint, + type TriggerPoint, +} from './ContextMenuTrigger'; import { useAdaptivePresentation, type AdaptivePresentation, @@ -120,29 +132,6 @@ import english from '../i18n/generated-english/ContextMenu/ContextMenu.generated registerEnglishFallback(english); const styles = stylex.create({ - // Trigger wrapper: suppress the iOS long-press callout/selection so the - // long-press opens our context menu instead of the native text/callout UI. - // `position: relative` establishes the containing block for the absolutely - // positioned cursor anchor below, so the anchor point tracks the trigger - // (and scrolls with it) instead of the page. - trigger: { - position: 'relative', - WebkitTouchCallout: 'none', - WebkitUserSelect: 'none', - userSelect: 'none', - }, - // 1px anchor placed at the cursor point within the trigger. The menu is - // anchored to this element, so it sits under the cursor yet is positioned - // relative to the trigger's context — it follows the content on scroll and - // the browser can auto-flip it against the viewport edges. It owns a box - // because WebKit counts an empty anchor box as clipped, and the default - // `position-visibility: anchors-visible` then hides the menu. - cursorAnchor: { - position: 'absolute', - width: '1px', - height: '1px', - pointerEvents: 'none', - }, menu: { boxSizing: 'border-box', display: 'flex', @@ -323,6 +312,40 @@ interface ContextMenuCompoundProps extends ContextMenuBaseProps { export type ContextMenuProps = ContextMenuDataProps | ContextMenuCompoundProps; +/** + * The trigger's event handlers, published by `ContextMenuForTrigger` for the + * trigger element its caller renders. + */ +export interface ContextMenuTriggerHandlers { + onContextMenu: (event: React.MouseEvent) => void; + /** Opens the menu as a long press at this viewport point does. */ + openFromLongPress: (point: {x: number; y: number}) => void; + /** Opens the menu for an invocation held at this point in the trigger. */ + openAtTriggerPoint: (point: TriggerPoint) => void; + onTouchStart: (event: React.TouchEvent) => void; + onTouchMove: (event: React.TouchEvent) => void; + onTouchEnd: (event: React.TouchEvent) => void; + onTouchCancel: (event: React.TouchEvent) => void; +} + +/** + * A trigger that the caller renders. It has the right-click target and the + * 1px cursor anchor inside it. Its callback receives the trigger's handlers + * while the menu is mounted, and `null` after the menu unmounts. + */ +export interface ContextMenuExternalTrigger { + triggerRef: React.RefObject; + anchorRef: React.RefObject; + onHandlersChange: (handlers: ContextMenuTriggerHandlers | null) => void; +} + +export type ContextMenuForTriggerProps = Omit< + ContextMenuDataProps, + 'children' | 'ref' | 'triggerAs' | 'triggerXstyle' +> & { + trigger: ContextMenuExternalTrigger; +}; + // ============================================================================= // ContextMenu // ============================================================================= @@ -350,28 +373,51 @@ export type ContextMenuProps = ContextMenuDataProps | ContextMenuCompoundProps; * * ``` */ -export function ContextMenu({ - children, - menuWidth, - size = 'md', - label: labelFromProps, - isDisabled = false, - onOpenChange, - presentation = 'popover', - triggerAs = 'div', - ref, - className, - style, - xstyle, - triggerXstyle, - onContextMenu: onContextMenuProp, - onTouchStart: onTouchStartProp, - onTouchMove: onTouchMoveProp, - onTouchEnd: onTouchEndProp, - onTouchCancel: onTouchCancelProp, - 'data-testid': testId, - ...rest -}: ContextMenuProps) { +export function ContextMenu(props: ContextMenuProps): ReactNode { + return useContextMenuElement(props, null); +} + +ContextMenu.displayName = 'ContextMenu'; + +/** + * Internal. `ContextMenu` without its own trigger. The menu opens from the + * trigger and cursor anchor in `trigger`. The caller renders them and keeps + * them mounted, so its content survives while this component loads lazily. + * Until it mounts, the trigger has no handlers. The caller decides what an + * early invocation does. + */ +export function ContextMenuForTrigger({ + trigger, + ...props +}: ContextMenuForTriggerProps): ReactNode { + return useContextMenuElement({...props, children: null}, trigger); +} + +function useContextMenuElement( + { + children, + menuWidth, + size = 'md', + label: labelFromProps, + isDisabled = false, + onOpenChange, + presentation = 'popover', + triggerAs = 'div', + ref, + className, + style, + xstyle, + triggerXstyle, + onContextMenu: onContextMenuProp, + onTouchStart: onTouchStartProp, + onTouchMove: onTouchMoveProp, + onTouchEnd: onTouchEndProp, + onTouchCancel: onTouchCancelProp, + 'data-testid': testId, + ...rest + }: ContextMenuProps, + externalTrigger: ContextMenuExternalTrigger | null, +): ReactNode { const t = useComponentTranslator(); const label = labelFromProps ?? t('@astryx.contextMenu.label'); const backLabel = t('@astryx.dropdownMenu.back'); @@ -407,6 +453,8 @@ export function ContextMenu({ // anchor element so the menu is positioned relative to the trigger context // — it scrolls with the content instead of sitting at a fixed viewport point. const positionRef = useRef({x: 0, y: 0}); + // With an external trigger these mirror its elements (see the layout effect + // below the handlers). const cursorAnchorRef = useRef(null); const triggerRef = useRef(null); // Element focused before the menu opened, restored when it closes so focus @@ -627,12 +675,14 @@ export function ContextMenu({ // The box the cursor anchor's offsets are measured from: its containing // block. That is the trigger, unless a caller's triggerXstyle leaves the // trigger unpositioned so that another box holds the anchor. - const getAnchorBaseRect = useCallback((): DOMRect | undefined => { - const base = cursorAnchorRef.current?.offsetParent; - return ( - base instanceof HTMLElement ? base : triggerRef.current - )?.getBoundingClientRect(); - }, []); + const getAnchorBaseRect = useCallback( + (): DOMRect | undefined => + anchorBase( + triggerRef.current, + cursorAnchorRef.current, + )?.getBoundingClientRect(), + [], + ); // Place the 1px cursor anchor at a point in the trigger's local // coordinate space and open the menu. Positioning the anchor inside the @@ -675,36 +725,34 @@ export function ContextMenu({ return; } e.preventDefault(); - const rect = getAnchorBaseRect(); - // A keyboard-initiated contextmenu (Shift+F10 / the Menu key) fires a - // `contextmenu` event whose coordinates are (0, 0) in several browsers. - // Detect that and anchor the menu to the trigger's bottom-left instead, - // so the menu is reachable without a pointer (menus-8). - const isKeyboardInvoked = - e.clientX === 0 && e.clientY === 0 && e.detail === 0; - // Convert the viewport cursor point into the trigger's local space so - // the anchor lives inside the (scrollable) trigger context. - const trigger = triggerRef.current?.getBoundingClientRect(); - let localX = 0; - let localY = rect?.height ?? 0; - if (rect && isKeyboardInvoked && trigger) { - localX = trigger.left - rect.left; - localY = trigger.bottom - rect.top; - } else if (rect && !isKeyboardInvoked) { - localX = e.clientX - rect.left; - localY = e.clientY - rect.top; - } + // The anchor lives inside the trigger, so it scrolls with the trigger. + const point = contextMenuPoint( + e, + triggerRef.current, + cursorAnchorRef.current, + ); // A finger's long press reaches here as a pointer `contextmenu` where // the browser sends one (Chromium); its compatibility mousedown then // belongs to the opening press. A mouse or the keyboard opens without // one, so every later mousedown is a press outside. - openingGestureRef.current = - (e.nativeEvent as Partial).pointerType === 'touch' - ? currentGesture() - : null; - openAtLocalPoint(localX, localY, e.currentTarget as HTMLElement); + openingGestureRef.current = point.isTouch ? currentGesture() : null; + openAtLocalPoint(point.x, point.y, e.currentTarget as HTMLElement); }, - [isDisabled, openAtLocalPoint, getAnchorBaseRect], + [isDisabled, openAtLocalPoint], + ); + + // An invocation that a caller's trigger held, at the point in the trigger + // where it arrived. The trigger is the focus element, because the held + // event no longer has a current target. + const openAtTriggerPoint = useCallback( + (point: TriggerPoint) => { + if (isDisabled) { + return; + } + openingGestureRef.current = point.isTouch ? currentGesture() : null; + openAtLocalPoint(point.x, point.y, triggerRef.current); + }, + [isDisabled, openAtLocalPoint], ); // Touch long-press invocation (menus-8). iOS Safari never synthesizes a @@ -713,6 +761,15 @@ export function ContextMenu({ // held long enough (see useLongPress for timer/move-cancel/cleanup logic). // The hook also returns the imperative start/moveTo/cancel API the menu press // model drives; only its four touch handlers belong on the trigger element. + const openFromLongPress = useCallback( + (point: {x: number; y: number}) => + // The finger is still down: the compatibility mousedown iOS sends + // mid-hold, or Chromium as it lifts, belongs to this press. + openAtTriggerPoint( + longPressPoint(point, triggerRef.current, cursorAnchorRef.current), + ), + [openAtTriggerPoint], + ); const { onTouchStart: handleLongPressTouchStart, onTouchMove: handleLongPressTouchMove, @@ -720,20 +777,7 @@ export function ContextMenu({ onTouchCancel: handleLongPressTouchCancel, } = useLongPress({ disabled: isDisabled, - onLongPress: useCallback( - (point: {x: number; y: number}) => { - const rect = getAnchorBaseRect(); - // The finger is still down: the compatibility mousedown iOS sends - // mid-hold, or Chromium as it lifts, belongs to this press. - openingGestureRef.current = currentGesture(); - openAtLocalPoint( - rect ? point.x - rect.left : point.x, - rect ? point.y - rect.top : point.y, - triggerRef.current, - ); - }, - [openAtLocalPoint, getAnchorBaseRect], - ), + onLongPress: openFromLongPress, }); // ContextMenu owns invocation and long-press cleanup. Consumer handlers are @@ -905,61 +949,100 @@ export function ContextMenu({ renderedMenu ); - // An inline trigger (`span`) lets prose own a context menu without - // breaking its flow. - const TriggerElement = triggerAs === 'div' ? 'div' : 'span'; + const mergedTriggerRef = useMergedRefs(ref, triggerRef); + const mergedAnchorRef = useMergedRefs(cursorAnchorRef, layer.ref); + + const triggerHandlers = useMemo( + () => ({ + onContextMenu: handleTriggerContextMenu, + openFromLongPress, + openAtTriggerPoint, + onTouchStart: handleTriggerTouchStart, + onTouchMove: handleTriggerTouchMove, + onTouchEnd: handleTriggerTouchEnd, + onTouchCancel: handleTriggerTouchCancel, + }), + [ + handleTriggerContextMenu, + openFromLongPress, + openAtTriggerPoint, + handleTriggerTouchStart, + handleTriggerTouchMove, + handleTriggerTouchEnd, + handleTriggerTouchCancel, + ], + ); + const layerAnchorRef = layer.ref; + // Syncs the menu's popover anchoring with the caller's DOM: the layer + // anchors to the caller's cursor anchor, and the open handlers measure the + // caller's trigger. It runs before the next Effect publishes the handlers, + // so a trigger that replays a held invocation finds both in place. + useIsomorphicLayoutEffect(() => { + if (externalTrigger == null) { + return; + } + triggerRef.current = externalTrigger.triggerRef.current; + cursorAnchorRef.current = externalTrigger.anchorRef.current; + layerAnchorRef(externalTrigger.anchorRef.current); + return () => { + layerAnchorRef(null); + triggerRef.current = null; + cursorAnchorRef.current = null; + }; + }, [externalTrigger, layerAnchorRef]); + // Syncs the caller's trigger element with this menu: it receives the + // trigger handlers while the menu is mounted, and none after unmount. + useIsomorphicLayoutEffect(() => { + if (externalTrigger == null) { + return; + } + const {onHandlersChange} = externalTrigger; + onHandlersChange(triggerHandlers); + return () => { + onHandlersChange(null); + }; + }, [externalTrigger, triggerHandlers]); + const SheetForContent = usesSheetActionList ? MenuBottomSheet : MenuBottomSheetWithoutActionList; + const menuSurface = usesBottomSheet ? ( + + {renderedBottomSheetContent} + + ) : ( + layer.render({renderedMenu}, { + placement: 'below', + alignment: 'start', + xstyle: [popoverXstyle, layerAnimations.below], + }) + ); + + if (externalTrigger != null) { + return menuSurface; + } return ( <> - + data-testid={testId}> {children} - - - {usesBottomSheet ? ( - - {renderedBottomSheetContent} - - ) : ( - layer.render({renderedMenu}, { - placement: 'below', - alignment: 'start', - xstyle: [popoverXstyle, layerAnimations.below], - }) - )} + + {menuSurface} ); } - -ContextMenu.displayName = 'ContextMenu'; diff --git a/packages/core/src/ContextMenu/ContextMenuCheckboxItem.ts b/packages/core/src/ContextMenu/ContextMenuCheckboxItem.ts new file mode 100644 index 0000000000000..08e7638bad2bf --- /dev/null +++ b/packages/core/src/ContextMenu/ContextMenuCheckboxItem.ts @@ -0,0 +1,15 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file ContextMenuCheckboxItem.ts + * @input DropdownMenuCheckboxItem + * @output ContextMenuCheckboxItem and ContextMenuCheckboxItemProps: + * DropdownMenuCheckboxItem under the ContextMenu name + * @position Re-exported by the ContextMenu index. A module of its own, so an + * app that imports only this name does not reach ContextMenu itself. + */ + +export { + DropdownMenuCheckboxItem as ContextMenuCheckboxItem, + type DropdownMenuCheckboxItemProps as ContextMenuCheckboxItemProps, +} from '../DropdownMenu/DropdownMenuCheckboxItem'; diff --git a/packages/core/src/ContextMenu/ContextMenuDivider.ts b/packages/core/src/ContextMenu/ContextMenuDivider.ts new file mode 100644 index 0000000000000..18b9d35cef789 --- /dev/null +++ b/packages/core/src/ContextMenu/ContextMenuDivider.ts @@ -0,0 +1,15 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file ContextMenuDivider.ts + * @input DropdownMenuDivider + * @output ContextMenuDivider and ContextMenuDividerProps: + * DropdownMenuDivider under the ContextMenu name + * @position Re-exported by the ContextMenu index. A module of its own, so an + * app that imports only this name does not reach ContextMenu itself. + */ + +export { + DropdownMenuDivider as ContextMenuDivider, + type DropdownMenuDividerProps as ContextMenuDividerProps, +} from '../DropdownMenu/DropdownMenuDivider'; diff --git a/packages/core/src/ContextMenu/ContextMenuGroup.ts b/packages/core/src/ContextMenu/ContextMenuGroup.ts new file mode 100644 index 0000000000000..188015ca78b5b --- /dev/null +++ b/packages/core/src/ContextMenu/ContextMenuGroup.ts @@ -0,0 +1,15 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file ContextMenuGroup.ts + * @input DropdownMenuGroup + * @output ContextMenuGroup and ContextMenuGroupProps: + * DropdownMenuGroup under the ContextMenu name + * @position Re-exported by the ContextMenu index. A module of its own, so an + * app that imports only this name does not reach ContextMenu itself. + */ + +export { + DropdownMenuGroup as ContextMenuGroup, + type DropdownMenuGroupProps as ContextMenuGroupProps, +} from '../DropdownMenu/DropdownMenuGroup'; diff --git a/packages/core/src/ContextMenu/ContextMenuItem.ts b/packages/core/src/ContextMenu/ContextMenuItem.ts new file mode 100644 index 0000000000000..68e4c273ebc1b --- /dev/null +++ b/packages/core/src/ContextMenu/ContextMenuItem.ts @@ -0,0 +1,15 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file ContextMenuItem.ts + * @input DropdownMenuItem + * @output ContextMenuItem and ContextMenuItemProps: + * DropdownMenuItem under the ContextMenu name + * @position Re-exported by the ContextMenu index. A module of its own, so an + * app that imports only this name does not reach ContextMenu itself. + */ + +export { + DropdownMenuItem as ContextMenuItem, + type DropdownMenuItemProps as ContextMenuItemProps, +} from '../DropdownMenu/DropdownMenuItem'; diff --git a/packages/core/src/ContextMenu/ContextMenuRadioGroup.ts b/packages/core/src/ContextMenu/ContextMenuRadioGroup.ts new file mode 100644 index 0000000000000..1bb0c14a406dc --- /dev/null +++ b/packages/core/src/ContextMenu/ContextMenuRadioGroup.ts @@ -0,0 +1,15 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file ContextMenuRadioGroup.ts + * @input DropdownMenuRadioGroup + * @output ContextMenuRadioGroup and ContextMenuRadioGroupProps: + * DropdownMenuRadioGroup under the ContextMenu name + * @position Re-exported by the ContextMenu index. A module of its own, so an + * app that imports only this name does not reach ContextMenu itself. + */ + +export { + DropdownMenuRadioGroup as ContextMenuRadioGroup, + type DropdownMenuRadioGroupProps as ContextMenuRadioGroupProps, +} from '../DropdownMenu/DropdownMenuRadioGroup'; diff --git a/packages/core/src/ContextMenu/ContextMenuRadioItem.ts b/packages/core/src/ContextMenu/ContextMenuRadioItem.ts new file mode 100644 index 0000000000000..6e138ffc18fa0 --- /dev/null +++ b/packages/core/src/ContextMenu/ContextMenuRadioItem.ts @@ -0,0 +1,15 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file ContextMenuRadioItem.ts + * @input DropdownMenuRadioItem + * @output ContextMenuRadioItem and ContextMenuRadioItemProps: + * DropdownMenuRadioItem under the ContextMenu name + * @position Re-exported by the ContextMenu index. A module of its own, so an + * app that imports only this name does not reach ContextMenu itself. + */ + +export { + DropdownMenuRadioItem as ContextMenuRadioItem, + type DropdownMenuRadioItemProps as ContextMenuRadioItemProps, +} from '../DropdownMenu/DropdownMenuRadioItem'; diff --git a/packages/core/src/ContextMenu/ContextMenuSubMenu.ts b/packages/core/src/ContextMenu/ContextMenuSubMenu.ts new file mode 100644 index 0000000000000..ebc439ca5e967 --- /dev/null +++ b/packages/core/src/ContextMenu/ContextMenuSubMenu.ts @@ -0,0 +1,15 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file ContextMenuSubMenu.ts + * @input DropdownMenuSubMenu + * @output ContextMenuSubMenu and ContextMenuSubMenuProps: + * DropdownMenuSubMenu under the ContextMenu name + * @position Re-exported by the ContextMenu index. A module of its own, so an + * app that imports only this name does not reach ContextMenu itself. + */ + +export { + DropdownMenuSubMenu as ContextMenuSubMenu, + type DropdownMenuSubMenuProps as ContextMenuSubMenuProps, +} from '../DropdownMenu/DropdownMenuSubMenu'; diff --git a/packages/core/src/ContextMenu/ContextMenuTrigger.tsx b/packages/core/src/ContextMenu/ContextMenuTrigger.tsx new file mode 100644 index 0000000000000..f92da447db399 --- /dev/null +++ b/packages/core/src/ContextMenu/ContextMenuTrigger.tsx @@ -0,0 +1,160 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file ContextMenuTrigger.tsx + * @input React, StyleX, mergeProps + * @output ContextMenuTrigger, the right-click target and its 1px cursor anchor, + * and contextMenuPoint and longPressPoint, where a right-click or a long + * press opens the menu in the trigger + * @position ContextMenu renders it around its children; Table cells render it + * before their lazily loaded menu arrives. It imports no menu code. + */ + +import type { + ComponentPropsWithoutRef, + MouseEvent as ReactMouseEvent, + ReactNode, + Ref, +} from 'react'; +import * as stylex from '@stylexjs/stylex'; +import type {StyleXStyles} from '../theme/types'; +import {mergeProps} from '../utils/mergeProps'; + +const styles = stylex.create({ + // The trigger suppresses the iOS long-press callout and text selection, so + // a long press opens the menu. `position: relative` makes it the containing + // block of the cursor anchor, so the anchor scrolls with the trigger. + trigger: { + position: 'relative', + WebkitTouchCallout: 'none', + WebkitUserSelect: 'none', + userSelect: 'none', + }, + // The menu anchors to this 1px box at the cursor point. So it follows + // the content on scroll and flips at viewport edges. + // It owns a box because WebKit counts an empty anchor box as clipped, and + // the default `position-visibility: anchors-visible` then hides the menu. + cursorAnchor: { + position: 'absolute', + width: '1px', + height: '1px', + pointerEvents: 'none', + }, +}); + +const ORIGIN = {x: 0, y: 0}; + +/** A point in the trigger's own box where the menu opens. */ +export interface TriggerPoint { + x: number; + y: number; + /** The invocation came from a finger, so its press belongs to the open. */ + isTouch: boolean; +} + +/** The point in `trigger`'s box where a long press at this viewport point opens the menu. */ +export function longPressPoint( + point: {x: number; y: number}, + trigger: Element | null, + anchor: HTMLElement | null = null, +): TriggerPoint { + const rect = anchorBase(trigger, anchor)?.getBoundingClientRect(); + return { + x: rect ? point.x - rect.left : point.x, + y: rect ? point.y - rect.top : point.y, + isTouch: true, + }; +} + +/** + * The box the cursor anchor's offsets are measured from: its containing + * block. That is the trigger, unless the caller's trigger style leaves the + * trigger unpositioned so that another box holds the anchor. + */ +export function anchorBase( + trigger: Element | null, + anchor: HTMLElement | null, +): Element | null { + const base = anchor?.offsetParent; + return base instanceof HTMLElement ? base : trigger; +} + +/** + * The point in the anchor's base box where a `contextmenu` event opens the + * menu. A keyboard `contextmenu` (Shift+F10, the Menu key) has coordinates + * (0, 0) in several browsers. Then the menu opens at the trigger's + * bottom-left corner, so it is reachable without a pointer. + */ +export function contextMenuPoint( + event: ReactMouseEvent, + trigger: Element | null, + anchor: HTMLElement | null = null, +): TriggerPoint { + const rect = anchorBase(trigger, anchor)?.getBoundingClientRect(); + const isKeyboard = + event.clientX === 0 && event.clientY === 0 && event.detail === 0; + let x = 0; + let y = rect?.height ?? 0; + const box = isKeyboard ? trigger?.getBoundingClientRect() : undefined; + if (rect && box) { + x = box.left - rect.left; + y = box.bottom - rect.top; + } else if (rect && !isKeyboard) { + x = event.clientX - rect.left; + y = event.clientY - rect.top; + } + return { + x, + y, + isTouch: + (event.nativeEvent as Partial).pointerType === 'touch', + }; +} + +type TriggerDOMProps = Omit< + ComponentPropsWithoutRef<'div'>, + 'children' | 'className' | 'style' +>; + +export interface ContextMenuTriggerProps extends TriggerDOMProps { + /** `div` is a block; `span` keeps an inline reference in the text flow. */ + as?: 'div' | 'span'; + ref?: Ref; + anchorRef?: Ref; + /** The cursor anchor's offset inside the trigger. */ + anchorPoint?: {x: number; y: number}; + xstyle?: StyleXStyles | StyleXStyles[]; + children: ReactNode; +} + +export function ContextMenuTrigger({ + as = 'div', + ref, + anchorRef, + anchorPoint = ORIGIN, + xstyle, + children, + ...domProps +}: ContextMenuTriggerProps): ReactNode { + const Element = as === 'div' ? 'div' : 'span'; + return ( + } + {...domProps} + {...stylex.props( + styles.trigger, + ...(xstyle ? (Array.isArray(xstyle) ? xstyle : [xstyle]) : []), + )}> + {children} + + ); +} diff --git a/packages/core/src/ContextMenu/index.ts b/packages/core/src/ContextMenu/index.ts index 48f49e2331524..31dd694909092 100644 --- a/packages/core/src/ContextMenu/index.ts +++ b/packages/core/src/ContextMenu/index.ts @@ -15,35 +15,14 @@ export { } from './ContextMenu'; export type {AdaptivePresentation as MenuPresentation} from '../hooks/useAdaptivePresentation'; -export { - DropdownMenuItem as ContextMenuItem, - type DropdownMenuItemProps as ContextMenuItemProps, -} from '../DropdownMenu/DropdownMenuItem'; -export { - DropdownMenuDivider as ContextMenuDivider, - type DropdownMenuDividerProps as ContextMenuDividerProps, -} from '../DropdownMenu/DropdownMenuDivider'; -export { - DropdownMenuGroup as ContextMenuGroup, - type DropdownMenuGroupProps as ContextMenuGroupProps, -} from '../DropdownMenu/DropdownMenuGroup'; +export * from './ContextMenuItem'; +export * from './ContextMenuDivider'; +export * from './ContextMenuGroup'; // Selectable items work inside a ContextMenu too — re-exported under the // ContextMenu name for a coherent API. -export { - DropdownMenuCheckboxItem as ContextMenuCheckboxItem, - type DropdownMenuCheckboxItemProps as ContextMenuCheckboxItemProps, -} from '../DropdownMenu/DropdownMenuCheckboxItem'; -export { - DropdownMenuRadioGroup as ContextMenuRadioGroup, - type DropdownMenuRadioGroupProps as ContextMenuRadioGroupProps, -} from '../DropdownMenu/DropdownMenuRadioGroup'; -export { - DropdownMenuRadioItem as ContextMenuRadioItem, - type DropdownMenuRadioItemProps as ContextMenuRadioItemProps, -} from '../DropdownMenu/DropdownMenuRadioItem'; +export * from './ContextMenuCheckboxItem'; +export * from './ContextMenuRadioGroup'; +export * from './ContextMenuRadioItem'; // Submenus work inside a ContextMenu too (nested flyout of items). -export { - DropdownMenuSubMenu as ContextMenuSubMenu, - type DropdownMenuSubMenuProps as ContextMenuSubMenuProps, -} from '../DropdownMenu/DropdownMenuSubMenu'; +export * from './ContextMenuSubMenu'; diff --git a/packages/core/src/DropdownMenu/DropdownMenuDivider.tsx b/packages/core/src/DropdownMenu/DropdownMenuDivider.tsx index b8dbdeedc3a15..51717ef5c2328 100644 --- a/packages/core/src/DropdownMenu/DropdownMenuDivider.tsx +++ b/packages/core/src/DropdownMenu/DropdownMenuDivider.tsx @@ -24,7 +24,7 @@ */ import * as stylex from '@stylexjs/stylex'; -import {Divider} from '../Divider'; +import {Divider} from '../Divider/Divider'; import {spacingVars} from '../theme/tokens.stylex'; import type {BaseProps} from '../BaseProps'; import {themeProps} from '../utils/themeProps'; diff --git a/packages/core/src/DropdownMenu/DropdownMenuItem.tsx b/packages/core/src/DropdownMenu/DropdownMenuItem.tsx index b071ec0715694..f81b260a0eb9e 100644 --- a/packages/core/src/DropdownMenu/DropdownMenuItem.tsx +++ b/packages/core/src/DropdownMenu/DropdownMenuItem.tsx @@ -35,8 +35,8 @@ import { type ReactNode, } from 'react'; import * as stylex from '@stylexjs/stylex'; -import {renderIconSlot, type IconType} from '../Icon'; -import {Item} from '../Item'; +import {renderIconSlot, type IconType} from '../Icon/Icon'; +import {Item} from '../Item/Item'; import {useLinkComponent} from '../Link/useLinkComponent'; import { colorVars, @@ -45,7 +45,8 @@ import { typeScaleVars, focusVars, } from '../theme/tokens.stylex'; -import {composeEventHandlers, mergeProps} from '../utils'; +import {composeEventHandlers} from '../utils/composeEventHandlers'; +import {mergeProps} from '../utils/mergeProps'; import type {BaseProps} from '../BaseProps'; import {useDropdownMenuContext} from './DropdownMenuContext'; import {focusOutlineStyles} from '../utils/focusOutline.stylex'; diff --git a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx index e303c2585051b..152328f38e1e4 100644 --- a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx +++ b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx @@ -61,10 +61,10 @@ import React, { } from 'react'; import {createPortal} from 'react-dom'; import * as stylex from '@stylexjs/stylex'; -import {Icon, renderIconSlot, type IconType} from '../Icon'; -import {Spinner} from '../Spinner'; +import {Icon, renderIconSlot, type IconType} from '../Icon/Icon'; +import {Spinner} from '../Spinner/Spinner'; import {moveRegionsTab} from './menuRegionStops'; -import {Item} from '../Item'; +import {Item} from '../Item/Item'; import {useLayer} from '../Layer/useLayer'; import {layerAnimations} from '../Layer/layerAnimations.stylex'; import {useInternalListFocus} from '../hooks/useListFocus'; @@ -90,13 +90,11 @@ import { typeScaleVars, focusVars, } from '../theme/tokens.stylex'; -import { - composeEventHandlers, - isImeKeyEvent, - isRenderable, - mergeProps, - rtlStyles, -} from '../utils'; +import {composeEventHandlers} from '../utils/composeEventHandlers'; +import {isImeKeyEvent} from '../utils/ime'; +import {isRenderable} from '../utils/isRenderable'; +import {mergeProps} from '../utils/mergeProps'; +import {rtlStyles} from '../utils/rtlStyles'; import {visibleText} from '../utils/accessibleName'; import {focusOutlineStyles} from '../utils/focusOutline.stylex'; import {menuPressLitRowStyle} from '../privateAttributes/menuPressLit.stylex'; diff --git a/packages/core/src/DropdownMenu/renderDropdownItems.tsx b/packages/core/src/DropdownMenu/renderDropdownItems.tsx index c56f3f36c3fca..d06f86d4aa50e 100644 --- a/packages/core/src/DropdownMenu/renderDropdownItems.tsx +++ b/packages/core/src/DropdownMenu/renderDropdownItems.tsx @@ -17,7 +17,8 @@ import { typeScaleVars, colorVars, } from '../theme/tokens.stylex'; -import {mergeProps, themeProps} from '../utils'; +import {mergeProps} from '../utils/mergeProps'; +import {themeProps} from '../utils/themeProps'; import type { DropdownMenuItemData, DropdownMenuOption, diff --git a/packages/core/src/Table/TableCell.tsx b/packages/core/src/Table/TableCell.tsx index 22485214073b2..8afa582bf371e 100644 --- a/packages/core/src/Table/TableCell.tsx +++ b/packages/core/src/Table/TableCell.tsx @@ -25,10 +25,8 @@ import { } from '../theme/tokens.stylex'; import type {StyleXStyles} from '../theme/types'; import type {TableContextActions} from './types'; -import { - hasTableContextActions, - wrapInTableContextMenu, -} from './tableContextMenu'; +import {TableCellContextMenu} from './TableCellContextMenu'; +import {hasContextActions} from './tableContextActions'; import { overflowStyles, wrapStyles, @@ -222,7 +220,7 @@ export function TableCell({ }: TableCellProps) { const ctx = useTableContext(); - const hasContextMenu = hasTableContextActions(contextMenuActions); + const hasContextMenu = hasContextActions(contextMenuActions); // When the cell owns a context menu, its density padding is relocated onto // the right-click trigger wrapper (see `content` below) so the entire cell — @@ -256,10 +254,12 @@ export function TableCell({ : hasContextMenu ? triggerFillStyles.fill : undefined; - const content = wrapInTableContextMenu( - children, - contextMenuActions, - triggerXstyle, + const content = ( + + {children} + ); return ( diff --git a/packages/core/src/Table/TableCellContextMenu.loadFailure.test.tsx b/packages/core/src/Table/TableCellContextMenu.loadFailure.test.tsx new file mode 100644 index 0000000000000..8a03c61bc2b2d --- /dev/null +++ b/packages/core/src/Table/TableCellContextMenu.loadFailure.test.tsx @@ -0,0 +1,174 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file TableCellContextMenu.loadFailure.test.tsx + * @output Tests that a failed load of the table context menu keeps the table + * mounted, drops the held invocation and any early long press, returns the + * browser's own menu, and lets a later render or invocation load it again, + * including a first invocation after another cell loaded it + * @position Validates TableCellContextMenu's load-failure path. Each test + * starts from a fresh module registry and a fresh mock of the menu module. + */ + +import {describe, it, expect, vi, beforeEach} from 'vitest'; +import {act, fireEvent, render, screen, waitFor} from '@testing-library/react'; +import {mockPopover, scenarioActions} from './__tests__/menuLoadScenario'; + +const loader = {calls: 0, failures: 0}; + +beforeEach(() => { + mockPopover(); + vi.resetModules(); + vi.doUnmock('./tableContextMenu'); + loader.calls = 0; + vi.doMock('./tableContextMenu', async importOriginal => { + loader.calls += 1; + if (loader.calls <= loader.failures) { + throw new Error('Failed to fetch dynamically imported module'); + } + return importOriginal(); + }); +}); + +async function renderTable(label: string) { + const [{Table}, {TableBody}, {TableRow}, {TableCell}] = await Promise.all([ + import('./Table'), + import('./TableBody'), + import('./TableRow'), + import('./TableCell'), + ]); + return render( +
+

Page heading

+ + + + {label} + Plain cell + + +
+
, + ); +} + +async function settle() { + await act(async () => { + await new Promise(resolve => setTimeout(resolve, 20)); + }); +} + +/** + * Waits until the loader has run `count` times, then lets the result land. A + * loaded machine can run the mocked import later than one fixed wait. + */ +async function afterLoads(count: number) { + for (let tries = 0; loader.calls < count && tries < 100; tries += 1) { + await settle(); + } + await settle(); + expect(loader.calls).toBe(count); +} + +describe('TableCellContextMenu menu load failure', () => { + it('keeps the table, drops the held right-click and returns the browser menu when the menu fails to load', async () => { + loader.failures = 1; + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const {container} = await renderTable('Alice'); + const cell = screen.getByText('Alice'); + // Held while the menu loads, so the browser's menu does not open. + expect(fireEvent.contextMenu(cell)).toBe(false); + + await afterLoads(1); + // Development builds warn once, whichever path saw the failure first. + expect( + warn.mock.calls.filter(([message]) => + String(message).includes('cell context menu failed to load'), + ), + ).toHaveLength(1); + warn.mockRestore(); + + expect(container.textContent).toBe('Page headingAlicePlain cell'); + expect(screen.getByText('Alice')).toBe(cell); + expect(screen.queryByRole('menu', {hidden: true})).toBeNull(); + // No menu can open, so a right-click reaches the browser's own menu. + expect(fireEvent.contextMenu(cell)).toBe(true); + await settle(); + expect(screen.queryByRole('menu', {hidden: true})).toBeNull(); + }); + + it('loads the menu again in a later render after a failed load', async () => { + loader.failures = 1; + const first = await renderTable('Alice'); + await afterLoads(1); + expect(first.container.textContent).toBe('Page headingAlicePlain cell'); + + await renderTable('Bob'); + const {loadTableContextMenu} = await import('./TableCellContextMenu'); + await act(async () => { + await loadTableContextMenu(); + }); + await settle(); + + expect(loader.calls).toBe(2); + expect(fireEvent.contextMenu(screen.getByText('Bob'))).toBe(false); + await waitFor(() => { + expect( + screen.getByRole('menuitem', {name: 'Copy', hidden: true}), + ).toBeTruthy(); + }); + }); + it('opens the menu on the first right-click after another cell loaded it', async () => { + loader.failures = 1; + await renderTable('Alice'); + await afterLoads(1); + + // A second table loads the menu module after Alice's load failed. + await renderTable('Bob'); + const {loadTableContextMenu} = await import('./TableCellContextMenu'); + await act(async () => { + await loadTableContextMenu(); + }); + await settle(); + expect(loader.calls).toBe(2); + + // Alice's first right-click since then is held and opens her menu. + expect(fireEvent.contextMenu(screen.getByText('Alice'))).toBe(false); + await waitFor(() => { + expect( + screen.getByRole('menuitem', {name: 'Copy', hidden: true}), + ).toBeTruthy(); + }); + }); + + it('ends an early long press when the menu fails to load before its deadline', async () => { + loader.failures = 1; + await renderTable('Alice'); + const cell = screen.getByText('Alice'); + fireEvent.touchStart(cell, {touches: [{clientX: 10, clientY: 10}]}); + await settle(); + // Past the long-press deadline, then lifted: nothing may be held. + await act(async () => { + await new Promise(resolve => setTimeout(resolve, 650)); + }); + fireEvent.touchEnd(cell, {touches: []}); + + // A right-click retries the load; a held long press would open on attach. + expect(fireEvent.contextMenu(cell)).toBe(true); + const {loadTableContextMenu} = await import('./TableCellContextMenu'); + await act(async () => { + await loadTableContextMenu(); + }); + await settle(); + expect(loader.calls).toBe(2); + expect(screen.queryByRole('menu', {hidden: true})).toBeNull(); + + // The retried menu works for the next right-click. + expect(fireEvent.contextMenu(cell)).toBe(false); + await waitFor(() => { + expect( + screen.getByRole('menuitem', {name: 'Copy', hidden: true}), + ).toBeTruthy(); + }); + }); +}); diff --git a/packages/core/src/Table/TableCellContextMenu.modality.test.tsx b/packages/core/src/Table/TableCellContextMenu.modality.test.tsx new file mode 100644 index 0000000000000..ae890a9d91e9c --- /dev/null +++ b/packages/core/src/Table/TableCellContextMenu.modality.test.tsx @@ -0,0 +1,68 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file TableCellContextMenu.modality.test.tsx + * @output Tests that a mouse right-click held before the menu loads opens the + * menu without the keyboard focus ring + * @position Validates interaction-modality tracking for an early invocation. + * Its own file, so no earlier menu in this document has started the + * tracking. + */ + +import {describe, it, expect, vi, beforeEach} from 'vitest'; +import {act, fireEvent, render, screen, waitFor} from '@testing-library/react'; +import {mockPopover, scenarioActions} from './__tests__/menuLoadScenario'; + +const gate = {release: () => {}}; + +beforeEach(() => { + mockPopover(); + vi.resetModules(); + vi.doUnmock('./tableContextMenu'); + const opened = new Promise(resolve => { + gate.release = resolve; + }); + vi.doMock('./tableContextMenu', async importOriginal => { + await opened; + return importOriginal(); + }); +}); + +describe('TableCellContextMenu early invocation modality', () => { + it('focuses the first row without the keyboard ring after an early mouse right-click', async () => { + const [{Table}, {TableBody}, {TableRow}, {TableCell}, menu] = + await Promise.all([ + import('./Table'), + import('./TableBody'), + import('./TableRow'), + import('./TableCell'), + import('./TableCellContextMenu'), + ]); + render( + + + + Name + + +
, + ); + const focus = vi.spyOn(HTMLElement.prototype, 'focus'); + const trigger = screen.getByText('Name'); + fireEvent.pointerDown(trigger, {pointerType: 'mouse', button: 2}); + expect(fireEvent.contextMenu(trigger)).toBe(false); + + gate.release(); + await act(async () => { + await menu.loadTableContextMenu(); + }); + + await waitFor(() => + expect(focus).toHaveBeenCalledWith( + expect.objectContaining({focusVisible: false}), + ), + ); + expect(focus.mock.contexts.at(-1)).toHaveTextContent('Copy'); + focus.mockRestore(); + }); +}); diff --git a/packages/core/src/Table/TableCellContextMenu.ssr.test.tsx b/packages/core/src/Table/TableCellContextMenu.ssr.test.tsx new file mode 100644 index 0000000000000..3239d741754be --- /dev/null +++ b/packages/core/src/Table/TableCellContextMenu.ssr.test.tsx @@ -0,0 +1,98 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file TableCellContextMenu.ssr.test.tsx + * @input Table cell server markup and React hydration + * @output Proves body and header cells with context actions hydrate without a + * recoverable error or a console error while the menu has not loaded + * @position SSR acceptance test for TableCellContextMenu; it waits for the + * menu module each hydration starts, so none loads after teardown + */ + +import {act} from 'react'; +import {afterEach, describe, expect, it, vi} from 'vitest'; +import {hydrateRoot} from 'react-dom/client'; +import {renderToString} from 'react-dom/server'; +// Vitest loads these while it collects this file, which is untimed. Each +// fresh module graph below runs these modules again without that cost. +import './Table'; +import './tableContextMenu'; +import type {TableContextAction} from './types'; + +const actions: TableContextAction[] = [ + {id: 'copy', label: 'Copy', onSelect: () => {}}, +]; + +afterEach(() => { + vi.restoreAllMocks(); + document.body.replaceChildren(); +}); + +interface Hydration { + recoverableErrors: unknown[]; + consoleErrors: unknown[][]; +} + +async function serverRenderThenHydrate(): Promise { + // A fresh module graph is a fresh server process: the menu has not loaded. + vi.resetModules(); + const [{Table}, {TableHeader}, {TableBody}, {TableRow}, cells] = + await Promise.all([ + import('./Table'), + import('./TableHeader'), + import('./TableBody'), + import('./TableRow'), + Promise.all([import('./TableCell'), import('./TableHeaderCell')]), + ]); + const [{TableCell}, {TableHeaderCell}] = cells; + const tree = ( + + + + Name + + + + + Alice + + +
+ ); + const container = document.createElement('div'); + container.innerHTML = renderToString(tree); + document.body.appendChild(container); + + // Watched, not muted: React reports some mismatches only on the console. + const logged = vi.spyOn(console, 'error'); + const recoverableErrors: unknown[] = []; + let root!: ReturnType; + await act(async () => { + root = hydrateRoot(container, tree, { + onRecoverableError: error => recoverableErrors.push(error), + }); + }); + // Right after hydration the cells start loading the menu. Finish that load + // before the test ends, or it resolves after the environment is torn down. + await act(async () => { + await import('./tableContextMenu'); + }); + await act(async () => { + root.unmount(); + }); + container.remove(); + const consoleErrors = [...logged.mock.calls]; + logged.mockRestore(); + return {recoverableErrors, consoleErrors}; +} + +describe('TableCellContextMenu — SSR', () => { + it('hydrates body and header cells with actions cleanly on the first renders of a server process', async () => { + for (let render = 0; render < 3; render++) { + expect(await serverRenderThenHydrate()).toEqual({ + recoverableErrors: [], + consoleErrors: [], + }); + } + }, 30000); +}); diff --git a/packages/core/src/Table/TableCellContextMenu.test.tsx b/packages/core/src/Table/TableCellContextMenu.test.tsx new file mode 100644 index 0000000000000..92d70f75d017a --- /dev/null +++ b/packages/core/src/Table/TableCellContextMenu.test.tsx @@ -0,0 +1,75 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file TableCellContextMenu.test.tsx + * @output Tests that body cells load the context menu only when they have + * actions, and that loading it leaves the cell's content in place + * @position Validates the lazy boundary in TableCellContextMenu + */ + +import {describe, it, expect, vi, beforeEach} from 'vitest'; +import {act, fireEvent, render, screen} from '@testing-library/react'; +import {Table} from './Table'; +import {TableBody} from './TableBody'; +import {TableRow} from './TableRow'; +import {TableCell} from './TableCell'; +import type {TableContextAction} from './types'; +import { + StatefulContent, + expectContentSurvivesMenuLoad, + mockPopover, + scenarioActions, +} from './__tests__/menuLoadScenario'; + +const loads = vi.hoisted(() => ({count: 0})); +vi.mock('./tableContextMenu', async importOriginal => { + loads.count += 1; + return importOriginal(); +}); + +beforeEach(mockPopover); + +function bodyCell( + contextMenuActions: TableContextAction[] | undefined, + children: React.ReactNode, +) { + return ( + + + + + {children} + + + +
+ ); +} + +// Order matters: the module registry is per file, so the first two tests see +// the menu before anything has loaded it. +describe('TableCellContextMenu', () => { + it('does not load the context menu for cells without actions', async () => { + render(bodyCell(undefined, 'Cell')); + render(bodyCell([], 'Cell')); + await act(async () => { + await new Promise(resolve => setTimeout(resolve, 50)); + }); + expect(screen.getAllByText('Cell')).toHaveLength(2); + expect(loads.count).toBe(0); + }); + + it('keeps a body cell editor’s node, value, focus and state while the menu loads', async () => { + await expectContentSurvivesMenuLoad( + bodyCell(scenarioActions, ), + 'input', + 'after-load', + ); + expect(loads.count).toBe(1); + }); + + it('renders a cell with actions synchronously once the menu has loaded', () => { + render(bodyCell(scenarioActions, 'Loaded cell')); + expect(fireEvent.contextMenu(screen.getByText('Loaded cell'))).toBe(false); + }); +}); diff --git a/packages/core/src/Table/TableCellContextMenu.touch.test.tsx b/packages/core/src/Table/TableCellContextMenu.touch.test.tsx new file mode 100644 index 0000000000000..7ff4c537487a6 --- /dev/null +++ b/packages/core/src/Table/TableCellContextMenu.touch.test.tsx @@ -0,0 +1,355 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file TableCellContextMenu.touch.test.tsx + * @output Tests what an invocation before the menu loads does once it loads: + * a long press opens the menu, timed and recognized by the loaded menu from + * the held touch, a tap or a moved press does not, only the last held cell + * opens, a later press or key drops the hold, the held point stays in the + * cell across a scroll, focus returns to the cell, and an unmounted cell + * drops only its own hold + * @position Validates early invocations in TableCellContextMenu. Each test + * starts from a fresh module registry and a fresh mock. The mock holds the + * menu module until the test releases it. + */ + +import {describe, it, expect, vi, beforeEach} from 'vitest'; +import {act, fireEvent, render, screen} from '@testing-library/react'; +import type {ReactNode} from 'react'; +import type {TableContextAction} from './types'; +import type * as LongPressDetectorModule from '../hooks/longPressDetector'; +import {mockPopover, scenarioActions} from './__tests__/menuLoadScenario'; + +const gate = { + release: () => {}, + factoryRuns: 0, +}; + +beforeEach(() => { + mockPopover(); + // A fresh registry and a fresh mock per test: the gated factory runs again, + // so each test's menu import waits for that test's own release. + vi.resetModules(); + vi.doUnmock('./tableContextMenu'); + const opened = new Promise(resolve => { + gate.release = resolve; + }); + vi.doMock('./tableContextMenu', async importOriginal => { + gate.factoryRuns += 1; + await opened; + return importOriginal(); + }); +}); + +type ColdCell = {label: string; actions?: TableContextAction[]}; + +/** + * Renders one row of cells from a fresh module registry. The menu module stays + * held until `loadMenu` releases it. + */ +async function renderColdCells( + cells: ColdCell[], + content?: (label: string) => ReactNode, +): Promise<{ + triggers: HTMLElement[]; + loadMenu: () => Promise; + unmount: () => void; +}> { + const [{Table}, {TableBody}, {TableRow}, {TableCell}, menu] = + await Promise.all([ + import('./Table'), + import('./TableBody'), + import('./TableRow'), + import('./TableCell'), + import('./TableCellContextMenu'), + ]); + const table: ReactNode = ( + + + + {cells.map(cell => ( + + {content ? content(cell.label) : cell.label} + + ))} + + +
+ ); + const {unmount} = render(table); + return { + unmount, + triggers: cells.map( + cell => + screen.getByText(cell.label).closest('td') + ?.firstElementChild as HTMLElement, + ), + loadMenu: async () => { + gate.release(); + await act(async () => { + await menu.loadTableContextMenu(); + }); + await wait(0); + }, + }; +} + +async function renderColdCell(label: string): Promise<{ + trigger: HTMLElement; + loadMenu: () => Promise; +}> { + const {triggers, loadMenu} = await renderColdCells([{label}]); + return {trigger: triggers[0], loadMenu}; +} + +async function wait(ms: number) { + await act(async () => { + await new Promise(resolve => setTimeout(resolve, ms)); + }); +} + +describe('TableCellContextMenu early invocation', () => { + it('opens the menu for a press held past the deadline and lifted before the menu loads', async () => { + const runsBefore = gate.factoryRuns; + const {trigger, loadMenu} = await renderColdCell('Hold me'); + fireEvent.touchStart(trigger, {touches: [{clientX: 10, clientY: 10}]}); + // A move inside the movement tolerance keeps the press. + fireEvent.touchMove(trigger, {touches: [{clientX: 14, clientY: 12}]}); + await wait(650); + fireEvent.touchEnd(trigger, {touches: []}); + expect(screen.queryByRole('menu', {hidden: true})).toBeNull(); + + await loadMenu(); + + expect( + screen.getByRole('menuitem', {name: 'Copy', hidden: true}), + ).toBeTruthy(); + expect(gate.factoryRuns).toBe(runsBefore + 1); + }); + + it('does not open the menu for a tap before the menu loads', async () => { + const runsBefore = gate.factoryRuns; + const {trigger, loadMenu} = await renderColdCell('Tap me'); + fireEvent.touchStart(trigger, {touches: [{clientX: 10, clientY: 10}]}); + fireEvent.touchEnd(trigger, {touches: []}); + expect(screen.queryByRole('menu', {hidden: true})).toBeNull(); + + await loadMenu(); + await wait(600); + + expect(screen.queryByRole('menu', {hidden: true})).toBeNull(); + // The menu module loaded through this test's own gated factory. + expect(gate.factoryRuns).toBe(runsBefore + 1); + }); + it('recognizes no gesture before the menu loads: the loaded menu reads the held touch', async () => { + const detectorsMade = {count: 0}; + vi.doMock('../hooks/longPressDetector', async importOriginal => { + const original = await importOriginal(); + return { + ...original, + createLongPressDetector: ( + ...args: Parameters + ) => { + detectorsMade.count += 1; + return original.createLongPressDetector(...args); + }, + }; + }); + const {trigger, loadMenu} = await renderColdCell('Hold me'); + fireEvent.touchStart(trigger, {touches: [{clientX: 10, clientY: 10}]}); + await wait(650); + fireEvent.touchEnd(trigger, {touches: []}); + expect(detectorsMade.count).toBe(0); + + await loadMenu(); + + expect( + screen.getByRole('menuitem', {name: 'Copy', hidden: true}), + ).toBeTruthy(); + vi.doUnmock('../hooks/longPressDetector'); + }); + + it('opens the menu at the deadline counted from the touch start for a press still held when the menu loads', async () => { + const {trigger, loadMenu} = await renderColdCell('Hold me'); + fireEvent.touchStart(trigger, {touches: [{clientX: 10, clientY: 10}]}); + await wait(200); + + await loadMenu(); + expect(screen.queryByRole('menu', {hidden: true})).toBeNull(); + await wait(400); + + expect( + screen.getByRole('menuitem', {name: 'Copy', hidden: true}), + ).toBeTruthy(); + fireEvent.touchEnd(trigger, {touches: []}); + }); + + it('does not open the menu for a press that moved past the tolerance before the menu loads', async () => { + const {trigger, loadMenu} = await renderColdCell('Scroll me'); + fireEvent.touchStart(trigger, {touches: [{clientX: 10, clientY: 10}]}); + fireEvent.touchMove(trigger, {touches: [{clientX: 10, clientY: 60}]}); + await wait(650); + fireEvent.touchEnd(trigger, {touches: []}); + + await loadMenu(); + await wait(600); + + expect(screen.queryByRole('menu', {hidden: true})).toBeNull(); + }); + + it('does not open the menu for a press that strayed past the tolerance and came back before the menu loads', async () => { + const {trigger, loadMenu} = await renderColdCell('Stray'); + fireEvent.touchStart(trigger, {touches: [{clientX: 10, clientY: 10}]}); + fireEvent.touchMove(trigger, {touches: [{clientX: 10, clientY: 60}]}); + fireEvent.touchMove(trigger, {touches: [{clientX: 10, clientY: 12}]}); + await wait(650); + fireEvent.touchEnd(trigger, {touches: []}); + + await loadMenu(); + await wait(600); + + // A loaded cell cancels this press at the stray move, so it opens nothing. + expect(screen.queryByRole('menu', {hidden: true})).toBeNull(); + }); + + it('drops a held touch once a press elsewhere comes before the menu loads', async () => { + const {trigger, loadMenu} = await renderColdCell('Hold me'); + fireEvent.touchStart(trigger, {touches: [{clientX: 10, clientY: 10}]}); + await wait(650); + fireEvent.touchEnd(trigger, {touches: []}); + fireEvent.pointerDown(document.body); + + await loadMenu(); + await wait(600); + + expect(screen.queryByRole('menu', {hidden: true})).toBeNull(); + }); + + it('opens only the last of two cells right-clicked before the menu loads', async () => { + const {triggers, loadMenu} = await renderColdCells([ + {label: 'Name', actions: [{id: 'a', label: 'Alpha', onSelect: () => {}}]}, + {label: 'Email', actions: [{id: 'b', label: 'Beta', onSelect: () => {}}]}, + ]); + expect(fireEvent.contextMenu(triggers[0])).toBe(false); + expect(fireEvent.contextMenu(triggers[1])).toBe(false); + + await loadMenu(); + + expect( + screen.getByRole('menuitem', {name: 'Beta', hidden: true}), + ).toBeTruthy(); + expect( + screen.queryByRole('menuitem', {name: 'Alpha', hidden: true}), + ).toBeNull(); + }); + + it('drops a held right-click once a press elsewhere comes before the menu loads', async () => { + const {trigger, loadMenu} = await renderColdCell('Name'); + expect(fireEvent.contextMenu(trigger)).toBe(false); + fireEvent.pointerDown(document.body); + + await loadMenu(); + + expect(screen.queryByRole('menu', {hidden: true})).toBeNull(); + }); + + it('drops a held right-click once a key comes before the menu loads', async () => { + const {trigger, loadMenu} = await renderColdCell('Name'); + expect(fireEvent.contextMenu(trigger)).toBe(false); + fireEvent.keyDown(document, {key: 'Escape'}); + + await loadMenu(); + + expect(screen.queryByRole('menu', {hidden: true})).toBeNull(); + }); + it('keeps a held right-click at its point in the cell when the page scrolls during the load', async () => { + const {triggers, loadMenu} = await renderColdCells([{label: 'Name'}]); + const trigger = triggers[0]; + let top = 200; + trigger.getBoundingClientRect = () => + ({ + left: 100, + top, + width: 200, + height: 40, + right: 300, + bottom: top + 40, + }) as DOMRect; + expect( + fireEvent.contextMenu(trigger, {clientX: 130, clientY: 215, detail: 1}), + ).toBe(false); + // The page scrolls 150px while the menu loads. + top = 50; + + await loadMenu(); + + expect( + screen.getByRole('menuitem', {name: 'Copy', hidden: true}), + ).toBeTruthy(); + const anchor = trigger.querySelector( + 'span[aria-hidden="true"]', + ); + expect(anchor?.style.left).toBe('30px'); + expect(anchor?.style.top).toBe('15px'); + }); + + it('restores focus to the cell on close when the focused element before a held right-click was not an HTML element', async () => { + const {triggers, loadMenu} = await renderColdCells( + [{label: 'Name'}], + label => ( + <> + {label} + + + ), + ); + const trigger = triggers[0]; + const mark = screen.getByLabelText('Mark'); + mark.focus(); + expect(document.activeElement).toBe(mark); + expect(fireEvent.contextMenu(trigger)).toBe(false); + const focusTrigger = vi.spyOn(trigger, 'focus'); + + await loadMenu(); + expect(screen.getByRole('menu', {hidden: true})).toBeTruthy(); + fireEvent.keyDown(document, {key: 'Escape'}); + + // The menu restores focus to the cell's trigger, as a direct right-click + // on the cell does. + expect(focusTrigger).toHaveBeenCalled(); + }); + + it('drops the hold of a cell that unmounts before the menu loads', async () => { + const hold = () => + (globalThis as unknown as Record)[ + Symbol.for('@astryxdesign/core/table/context-menu-hold/v1') + ]; + const first = await renderColdCells([{label: 'Name'}]); + expect(fireEvent.contextMenu(first.triggers[0])).toBe(false); + expect(hold().current).not.toBeNull(); + + first.unmount(); + + expect(hold().current).toBeNull(); + await first.loadMenu(); + expect(screen.queryByRole('menu', {hidden: true})).toBeNull(); + }); + + it("keeps another cell's hold when a cell unmounts before the menu loads", async () => { + const first = await renderColdCells([{label: 'Name'}]); + const second = await renderColdCells([ + {label: 'Email', actions: [{id: 'b', label: 'Beta', onSelect: () => {}}]}, + ]); + expect(fireEvent.contextMenu(first.triggers[0])).toBe(false); + expect(fireEvent.contextMenu(second.triggers[0])).toBe(false); + + first.unmount(); + await second.loadMenu(); + + expect( + screen.getByRole('menuitem', {name: 'Beta', hidden: true}), + ).toBeTruthy(); + }); +}); diff --git a/packages/core/src/Table/TableCellContextMenu.tsx b/packages/core/src/Table/TableCellContextMenu.tsx new file mode 100644 index 0000000000000..cc1dcde768d2f --- /dev/null +++ b/packages/core/src/Table/TableCellContextMenu.tsx @@ -0,0 +1,391 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file TableCellContextMenu.tsx + * @input React (lazy, Suspense), createModuleLoader, ContextMenuTrigger, + * useIsHydrating, useInteractionModalityTracking + * @output TableCellContextMenu, loadTableContextMenu + * @position Renders a cell's `contextMenuActions` for TableCell and + * TableHeaderCell. The menu code loads only for cells that have actions. The + * cell renders the trigger, and the menu loads beside it, so the content + * keeps its node, focus and state. The cell holds an invocation that comes + * before the load and replays it when the menu arrives. It recognizes no + * gesture itself: the loaded menu reads a held touch's events. + */ + +import { + lazy, + Suspense, + useEffect, + useRef, + useState, + type ComponentProps, + type ComponentType, + type ReactNode, + type TouchEvent as ReactTouchEvent, +} from 'react'; +import type { + ContextMenuExternalTrigger, + ContextMenuTriggerHandlers, +} from '../ContextMenu/ContextMenu'; +import { + ContextMenuTrigger, + contextMenuPoint, + type TriggerPoint, +} from '../ContextMenu/ContextMenuTrigger'; +import {useIsHydrating} from '../hooks/useIsHydrating'; +import {useMergedRefs} from '../hooks/useMergedRefs'; +import {currentGesture} from '../Layer/gestureCounter'; +import {useInteractionModalityTracking} from '../utils/interactionModality'; +import {createModuleLoader} from '../utils/moduleLoader'; +import {realmValue, sharedKey} from '../utils/sharedRealm'; +import type {StyleXStyles} from '../theme/types'; +import type {TableContextActions} from './types'; +import type {TableContextMenuForTrigger} from './tableContextMenu'; +import {hasContextActions} from './tableContextActions'; +import {warnOnce} from '../utils/devWarning'; + +interface TableContextMenuModule { + TableContextMenuForTrigger: typeof TableContextMenuForTrigger; +} + +const tableContextMenu = createModuleLoader( + async () => import('./tableContextMenu'), +); + +/** + * Starts loading the table context menu, once. The returned promise settles + * when the module has loaded; a cell with actions renders its menu a tick + * later. A failed load (a dropped connection, a removed chunk) is not kept, + * so the next call asks the module loader again. + */ +export const loadTableContextMenu = tableContextMenu.load; + +/** Development builds warn once when the menu code fails to load. */ +function warnMenuUnavailable(error: unknown): void { + warnOnce( + 'table-context-menu-load', + 'Table', + 'The cell context menu failed to load. Cells show the browser menu until a later invocation loads it.', + error, + ); +} + +/** Starts the load for an early invocation. */ +function preloadTableContextMenu(): void { + loadTableContextMenu().catch(warnMenuUnavailable); +} + +type LazyMenuProps = ComponentProps & { + onUnavailable: () => void; +}; + +/** Renders in place of the menu when it failed to load. */ +function MenuUnavailable({onUnavailable}: LazyMenuProps): ReactNode { + // Syncs the cell with the failed load: it drops its held invocation and + // stops holding, so the browser's own menu returns. + useEffect(onUnavailable, [onUnavailable]); + return null; +} + +// React.lazy keeps a rejection. A failed load resolves to MenuUnavailable +// instead of throwing. A cell mounted later gets a new lazy that loads again. +function createLazyTableContextMenu() { + return lazy(async () => { + try { + const mod = await loadTableContextMenu(); + return {default: mod.TableContextMenuForTrigger}; + } catch (error) { + warnMenuUnavailable(error); + LazyTableContextMenu = createLazyTableContextMenu(); + return {default: MenuUnavailable}; + } + }); +} + +let LazyTableContextMenu: ComponentType = + createLazyTableContextMenu(); + +/** + * An invocation that arrived before the menu, replayed when it attaches. Its + * point is in the trigger's own box, so a scroll during the load keeps it on + * the content. + */ +type HeldInvocation = { + owner: object; + gesture: number; + point: TriggerPoint; +}; + +// One hold serves all cells, in every copy of Core on the page. A later +// invocation replaces it, as a second press closes the first menu after the +// load. +const hold = realmValue(sharedKey('table/context-menu-hold', 1), () => ({ + current: null as HeldInvocation | null, +})); + +function holdInvocation(held: HeldInvocation): void { + hold.current = held; +} + +function dropHeldInvocation(owner: object): void { + if (hold.current?.owner === owner) { + hold.current = null; + } +} + +function takeHeldInvocation(owner: object): HeldInvocation | null { + const held = hold.current; + if (held?.owner !== owner) { + return null; + } + hold.current = null; + return held; +} + +type TouchPhase = 'start' | 'move' | 'end' | 'cancel'; + +/** + * The touch events of a press that starts before the menu attaches. The menu + * gets them in order when it attaches. Its long press then times the press + * from the touch's own start, and tells a long press from a tap. + */ +type HeldTouch = { + gesture: number; + events: {phase: TouchPhase; event: ReactTouchEvent}[]; +}; + +/** + * Adds a touch event to a held press. Every move is kept. A press that + * strays past the move tolerance and comes back cancels the long press on + * replay, as on a loaded cell. + */ +function holdTouchEvent( + held: HeldTouch | null, + phase: TouchPhase, + event: ReactTouchEvent, +): HeldTouch | null { + if (phase === 'start' && event.touches.length === 1) { + return {gesture: currentGesture(), events: [{phase, event}]}; + } + if (held == null) { + return null; + } + const last = held.events.at(-1); + if (last?.phase === 'end' || last?.phase === 'cancel') { + return held; + } + return {...held, events: [...held.events, {phase, event}]}; +} + +function replayTouch( + held: HeldTouch, + handlers: ContextMenuTriggerHandlers, +): void { + for (const {phase, event} of held.events) { + if (phase === 'start') { + handlers.onTouchStart(event); + } else if (phase === 'move') { + handlers.onTouchMove(event); + } else if (phase === 'end') { + handlers.onTouchEnd(event); + } else { + handlers.onTouchCancel(event); + } + } +} + +/** + * A cell's content, wrapped in a right-click context menu when `actions` can + * open one. Without actions it returns the content untouched, so the native + * browser menu passes through and the menu code never loads. + */ +export function TableCellContextMenu({ + children, + actions, + triggerXstyle, +}: { + children: ReactNode; + actions: TableContextActions | undefined; + triggerXstyle?: StyleXStyles | StyleXStyles[]; +}): ReactNode { + if (actions === undefined || !hasContextActions(actions)) { + return children; + } + return ( + + {children} + + ); +} + +function CellTrigger({ + children, + actions, + triggerXstyle, +}: { + children: ReactNode; + actions: TableContextActions; + triggerXstyle?: StyleXStyles | StyleXStyles[]; +}): ReactNode { + const triggerRef = useRef(null); + const anchorRef = useRef(null); + const handlersRef = useRef(null); + const heldTouchRef = useRef(null); + // True after this cell's menu failed to load, until a later load succeeds. + const [isMenuUnavailable, setMenuUnavailable] = useState(false); + const retryMenu = () => { + loadTableContextMenu().then( + () => setMenuUnavailable(false), + warnMenuUnavailable, + ); + }; + + const triggerHandle = useRef({ + triggerRef, + anchorRef, + onHandlersChange: handlers => { + handlersRef.current = handlers; + if (handlers == null) { + return; + } + const held = takeHeldInvocation(triggerRef); + const heldTouch = heldTouchRef.current; + heldTouchRef.current = null; + if (held == null && heldTouch == null) { + return; + } + // Replay after the commit that attached the menu, so the menu anchors its + // layer before it opens. A press or key since the hold drops it. + queueMicrotask(() => { + if (handlersRef.current !== handlers) { + return; + } + if (heldTouch != null && currentGesture() === heldTouch.gesture) { + replayTouch(heldTouch, handlers); + } + if (held != null && currentGesture() === held.gesture) { + handlers.openAtTriggerPoint(held.point); + } + }); + }, + }).current; + + // The menu is not in server markup or the hydrating render: a lazy + // component that has not loaded would abort hydration. The trigger holds + // an invocation until the menu renders right after hydration. + const isHydrating = useIsHydrating(); + // The menu reads the last input type when it opens. The cell starts + // tracking here, so the tracker records a press before the menu mounts. + const {ref: modalityRef} = useInteractionModalityTracking(); + const mergedTriggerRef = useMergedRefs(triggerRef, modalityRef); + + // Syncs the shared hold with this cell's lifetime: a cell that unmounts + // before its menu loads drops its own hold, and keeps another cell's. + useEffect(() => () => dropHeldInvocation(triggerRef), []); + + // A failed load drops this cell's held touch and invocation, so no later + // menu opens for them. + const onMenuUnavailable = useRef(() => { + heldTouchRef.current = null; + dropHeldInvocation(triggerRef); + setMenuUnavailable(true); + }).current; + + // Before the menu attaches, a touch only starts the load and is held. + const holdTouch = ( + phase: TouchPhase, + event: ReactTouchEvent, + ): void => { + heldTouchRef.current = holdTouchEvent(heldTouchRef.current, phase, event); + }; + + return ( + <> + { + const handlers = handlersRef.current; + if (handlers != null) { + handlers.onContextMenu(event); + return; + } + if (isMenuUnavailable) { + retryMenu(); + // Another cell may have loaded the menu since this cell's load + // failed. Then this invocation waits for this cell's menu. + if (tableContextMenu.loaded() == null) { + return; + } + } + // Hold the invocation until the menu loads. Then the browser's own + // menu does not open. + event.preventDefault(); + holdInvocation({ + owner: triggerRef, + gesture: currentGesture(), + point: contextMenuPoint( + event, + triggerRef.current, + anchorRef.current, + ), + }); + preloadTableContextMenu(); + }} + onTouchStart={event => { + const handlers = handlersRef.current; + if (handlers != null) { + handlers.onTouchStart(event); + return; + } + if (isMenuUnavailable) { + retryMenu(); + if (tableContextMenu.loaded() == null) { + return; + } + } + holdTouch('start', event); + preloadTableContextMenu(); + }} + onTouchMove={event => { + const handlers = handlersRef.current; + if (handlers != null) { + handlers.onTouchMove(event); + } else { + holdTouch('move', event); + } + }} + onTouchEnd={event => { + const handlers = handlersRef.current; + if (handlers != null) { + handlers.onTouchEnd(event); + } else { + holdTouch('end', event); + } + }} + onTouchCancel={event => { + const handlers = handlersRef.current; + if (handlers != null) { + handlers.onTouchCancel(event); + } else { + holdTouch('cancel', event); + } + }}> + {children} + + {isHydrating || isMenuUnavailable ? null : ( + + + + )} + + ); +} diff --git a/packages/core/src/Table/TableHeaderCell.tsx b/packages/core/src/Table/TableHeaderCell.tsx index 2556cd115b5d4..c4af60ea146be 100644 --- a/packages/core/src/Table/TableHeaderCell.tsx +++ b/packages/core/src/Table/TableHeaderCell.tsx @@ -28,10 +28,8 @@ import type {StyleXStyles} from '../theme/types'; import type {TableContextActions} from './types'; import {overflowStyles, containerEdgeStyles} from './table.stylex'; import {useTableContext, mergeXStyle} from './useTableCellStyles'; -import { - hasTableContextActions, - wrapInTableContextMenu, -} from './tableContextMenu'; +import {TableCellContextMenu} from './TableCellContextMenu'; +import {hasContextActions} from './tableContextActions'; import {mergeProps} from '../utils'; import {themeProps} from '../utils/themeProps'; import {useMergedRefs} from '../hooks/useMergedRefs'; @@ -178,7 +176,7 @@ export function TableHeaderCell({ // Header cells always get the bottom divider (separates header from body). // When used standalone (no table context) the cell renders plain, with no // density/divider styles. - const hasContextMenu = hasTableContextActions(contextMenuActions); + const hasContextMenu = hasContextActions(contextMenuActions); const cellStyles: StyleXStyles[] = []; if (ctx) { cellStyles.push( @@ -201,10 +199,14 @@ export function TableHeaderCell({ // interacts with its padding / content. No-op when no actions. Inside a // Table the wrapper stays unpositioned, so a header plugin's overlay, such // as a resize boundary, positions against the cell and sits on its edge. - const content = wrapInTableContextMenu( - children, - contextMenuActions, - ctx && hasContextMenu ? headerTriggerStyles.unpositioned : undefined, + const content = ( + + {children} + ); return ( diff --git a/packages/core/src/Table/TableHeaderCellContextMenu.test.tsx b/packages/core/src/Table/TableHeaderCellContextMenu.test.tsx new file mode 100644 index 0000000000000..9aa8508cb581d --- /dev/null +++ b/packages/core/src/Table/TableHeaderCellContextMenu.test.tsx @@ -0,0 +1,41 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file TableHeaderCellContextMenu.test.tsx + * @output Tests that loading a header cell's context menu leaves the cell's + * content in place + * @position Validates the lazy boundary in TableCellContextMenu for + * TableHeaderCell; its own file so the menu starts unloaded + */ + +import {describe, it, beforeEach} from 'vitest'; +import {Table} from './Table'; +import {TableHeader} from './TableHeader'; +import {TableRow} from './TableRow'; +import {TableHeaderCell} from './TableHeaderCell'; +import { + StatefulContent, + expectContentSurvivesMenuLoad, + mockPopover, + scenarioActions, +} from './__tests__/menuLoadScenario'; + +beforeEach(mockPopover); + +describe('TableHeaderCell context menu loading', () => { + it('holds a Shift+F10 sent before the menu loads, opens the menu, and keeps the focused header control’s node and state', async () => { + await expectContentSurvivesMenuLoad( + + + + + + + + +
, + 'button', + 'before-load', + ); + }); +}); diff --git a/packages/core/src/Table/TableMenuWindowFocus.test.tsx b/packages/core/src/Table/TableMenuWindowFocus.test.tsx index 85f7c547e29ab..844f11356eda0 100644 --- a/packages/core/src/Table/TableMenuWindowFocus.test.tsx +++ b/packages/core/src/Table/TableMenuWindowFocus.test.tsx @@ -9,8 +9,11 @@ import { } from '@testing-library/react'; import {afterEach, describe, it, expect, vi} from 'vitest'; import {warmMenuBottomSheet} from '../DropdownMenu/__tests__/warmMenuBottomSheet'; +import {warmTableContextMenu} from './__tests__/warmTableContextMenu'; import {beforeAll} from 'vitest'; beforeAll(warmMenuBottomSheet, 20000); +// A cell's menu loads on its first use; load it once, before the tests. +beforeAll(warmTableContextMenu, 20000); import {Table} from './Table'; import type {BodyCellRenderProps, BodyRowRenderProps} from './types'; import {useTableRowsVirtualization} from './plugins/virtualization/useTableRowsVirtualization'; diff --git a/packages/core/src/Table/__tests__/TableCellMenuLoad.a11y.chromium.spec.ts b/packages/core/src/Table/__tests__/TableCellMenuLoad.a11y.chromium.spec.ts new file mode 100644 index 0000000000000..69a4a77a6ce9e --- /dev/null +++ b/packages/core/src/Table/__tests__/TableCellMenuLoad.a11y.chromium.spec.ts @@ -0,0 +1,368 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. +// @pr-a11y scope ^packages/core/src/Table/ ^packages/core/src/ContextMenu/ ^packages/core/src/hooks/(useLongPress|longPressDetector) + +/** + * @file TableCellMenuLoad.a11y.chromium.spec.ts + * @input The TableCellMenuLoad fixture built from source with Vite (a client + * build and a server build), React's server renderer and hydrateRoot, and + * native Chromium mouse, keyboard and touch + * @output Browser evidence for an invocation that reaches a table cell while + * its menu code still loads: the server-rendered table hydrates without a + * recoverable error, the browser's own menu stays shut, the held invocation + * opens the cell's menu once when the code arrives, focus lands on the first + * row (with no keyboard ring after a mouse open), and Escape hands it back. + * With no invocation, the load changes no box and no axe result + * @position Real-browser layer for TableCellContextMenu's early invocations. + * The fixture server holds the menu chunk until the test releases it. + */ + +import {once} from 'node:events'; +import AxeBuilder from '@axe-core/playwright'; +import fs from 'node:fs'; +import {createServer, type Server, type ServerResponse} from 'node:http'; +import path from 'node:path'; +import {pathToFileURL} from 'node:url'; +import {expect, test, type Page} from '@astryxdesign/a11y-spec/playwright'; +import {tap, touchDriver} from '@astryxdesign/interaction-harness'; +import {build} from 'vite'; + +const CONFIG = path.resolve( + 'packages/core/src/Table/__tests__/TableCellMenuLoad.vite.mjs', +); +const SERVER_ENTRY = path.resolve( + 'packages/core/src/Table/__tests__/TableCellMenuLoad.server.tsx', +); + +let server: Server; +let origin: string; +let menuChunkFile: string; + +/** The fixture server holds the menu chunk until a test releases it. */ +const gate = { + released: false, + requests: 0, + waiting: [] as (() => void)[], +}; + +function release() { + gate.released = true; + for (const send of gate.waiting.splice(0)) { + send(); + } +} + +const TYPES: Record = { + '.js': 'text/javascript', + '.css': 'text/css', + '.html': 'text/html', +}; + +test.beforeAll(async () => { + // A folder per worker, so parallel workers never share a build. + const out = path.resolve( + `test-results/table-cell-menu-load-${test.info().parallelIndex}`, + ); + const clientDir = path.join(out, 'client'); + const serverDir = path.join(out, 'server'); + await build({ + configFile: CONFIG, + logLevel: 'warn', + build: {outDir: clientDir, emptyOutDir: true}, + }); + await build({ + configFile: CONFIG, + logLevel: 'warn', + build: { + outDir: serverDir, + emptyOutDir: true, + ssr: SERVER_ENTRY, + manifest: false, + rollupOptions: { + input: SERVER_ENTRY, + external: [/^react(?:-dom)?(?:\/|$)/], + output: {entryFileNames: '[name].mjs'}, + }, + }, + }); + const {renderHtml} = (await import( + pathToFileURL(path.join(serverDir, 'TableCellMenuLoad.server.mjs')).href + )) as {renderHtml: () => string}; + const manifest = JSON.parse( + fs.readFileSync(path.join(clientDir, '.vite/manifest.json'), 'utf8'), + ) as Record; + const menuChunk = Object.values(manifest).find(chunk => + chunk.src?.endsWith('tableContextMenu.tsx'), + )?.file; + if (menuChunk == null) { + throw new Error('the build has no lazy table menu chunk'); + } + menuChunkFile = menuChunk; + const page = fs + .readFileSync(path.join(clientDir, 'TableCellMenuLoad.html'), 'utf8') + .replace('', renderHtml()); + const send = (response: ServerResponse, type: string, body: Uint8Array) => { + response.writeHead(200, { + 'Content-Type': type, + 'Cache-Control': 'no-store', + }); + response.end(body); + }; + server = createServer((request, response) => { + const name = (request.url ?? '/').split('?')[0].slice(1); + if (name === '') { + send(response, 'text/html', Buffer.from(page)); + return; + } + const file = path.join(clientDir, name); + if (!file.startsWith(clientDir) || !fs.existsSync(file)) { + response.writeHead(404); + response.end(); + return; + } + const type = TYPES[path.extname(file)] ?? 'application/octet-stream'; + const body = fs.readFileSync(file); + if (name === menuChunk) { + gate.requests += 1; + if (!gate.released) { + gate.waiting.push(() => send(response, type, body)); + return; + } + } + send(response, type, body); + }); + server.listen(0, '127.0.0.1'); + await once(server, 'listening'); + const address = server.address(); + if (!address || typeof address === 'string') { + throw new Error('the fixture server has no address'); + } + origin = `http://127.0.0.1:${address.port}`; +}); + +test.afterAll(async () => { + release(); + if (server) { + await new Promise((resolve, reject) => + server.close(error => (error ? reject(error) : resolve())), + ); + } +}); + +type PageState = { + __shows: number; + __contextmenus: boolean[]; + __recoverable: string[]; +}; + +const errors = new WeakMap(); + +test.beforeEach(async ({page}) => { + gate.released = false; + gate.requests = 0; + const pageErrors: string[] = []; + errors.set(page, pageErrors); + page.on('pageerror', error => pageErrors.push(error.message)); + page.on('console', message => { + if (message.type() === 'error') { + pageErrors.push(message.text()); + } + }); + // Counts menu opens, and records whether each contextmenu event reached + // the window with its default prevented, so the browser's menu stayed shut. + await page.addInitScript(() => { + const state = window as unknown as PageState; + state.__shows = 0; + state.__contextmenus = []; + const show = HTMLElement.prototype.showPopover; + HTMLElement.prototype.showPopover = function ( + this: HTMLElement, + ...args: Parameters + ) { + state.__shows += 1; + return show.apply(this, args); + }; + window.addEventListener('contextmenu', event => { + state.__contextmenus.push(event.defaultPrevented); + }); + }); + await page.goto(origin); + await expect(page.locator('html')).toHaveAttribute('data-hydrated', 'true'); + // The server markup hydrated as is, and the menu code is still held. + expect( + await page.evaluate(() => (window as unknown as PageState).__recoverable), + ).toEqual([]); + expect(gate.requests).toBeLessThanOrEqual(1); + await expect(page.getByRole('menu')).toHaveCount(0); +}); + +test.afterEach(async ({page}) => { + expect(errors.get(page)).toEqual([]); +}); + +const state = async (page: Page) => + page.evaluate(() => { + const {__shows, __contextmenus} = window as unknown as PageState; + return { + shows: __shows, + contextmenus: __contextmenus, + focusVisible: document.activeElement?.matches(':focus-visible') ?? false, + }; + }); + +const cell = (page: Page) => page.getByRole('cell', {name: /Alice/}); + +async function cellPoint(page: Page) { + const box = await cell(page).boundingBox(); + if (box == null) { + throw new Error('the cell has no rendered bounds'); + } + return {x: Math.round(box.x) + 12, y: Math.round(box.y) + 10}; +} + +/** Lets a second open, if one were coming, arrive before the count. */ +async function settle(page: Page) { + await page.waitForTimeout(300); +} + +const AXE_DISABLED_RULES = [ + // The fixture is a fragment, not a page. + 'landmark-one-main', + 'page-has-heading-one', + 'region', +]; + +async function axeViolations(page: Page): Promise { + const results = await new AxeBuilder({page}) + .disableRules(AXE_DISABLED_RULES) + .analyze(); + return results.violations.map( + violation => + `${violation.id}: ${violation.nodes.map(node => node.target.join(' ')).join(', ')}`, + ); +} + +/** The boxes of the cell, its menu trigger and its button. */ +async function cellBoxes(page: Page) { + return { + cell: await cell(page).boundingBox(), + trigger: await cell(page).locator('> *').first().boundingBox(), + button: await page.getByRole('button', {name: 'Edit'}).boundingBox(), + }; +} + +test('the menu load changes no box in the cell and no axe result', async ({ + page, +}) => { + const before = await cellBoxes(page); + expect(await axeViolations(page)).toEqual([]); + + release(); + // The browser received the menu code. + await page.waitForFunction( + file => + performance + .getEntriesByType('resource') + .some(entry => entry.name.endsWith(file)), + menuChunkFile, + ); + await settle(page); + + expect(await cellBoxes(page)).toEqual(before); + expect(await axeViolations(page)).toEqual([]); + await expect(page.getByRole('menu')).toHaveCount(0); + expect((await state(page)).shows).toBe(0); + + // The loaded menu opens on the first right-click. + const point = await cellPoint(page); + await page.mouse.click(point.x, point.y, {button: 'right'}); + await expect(page.getByRole('menuitem', {name: 'Copy'})).toBeFocused(); + expect((await state(page)).contextmenus).toEqual([true]); +}); + +test('a right-click before the menu code arrives keeps the browser menu shut and opens the cell menu once, focused without a ring', async ({ + page, +}) => { + const point = await cellPoint(page); + await page.mouse.click(point.x, point.y, {button: 'right'}); + expect((await state(page)).contextmenus).toEqual([true]); + await expect(page.getByRole('menu')).toHaveCount(0); + // The invocation asked for the menu code, which the server still holds. + expect(gate.requests).toBe(1); + + release(); + + const first = page.getByRole('menuitem', {name: 'Copy'}); + await expect(first).toBeFocused(); + await settle(page); + expect(await state(page)).toMatchObject({shows: 1, focusVisible: false}); + // The menu opened at the pointer. + const anchor = await cell(page) + .locator('span[aria-hidden="true"][style*="anchor-name"]') + .boundingBox(); + expect(Math.abs((anchor?.x ?? 0) - point.x)).toBeLessThanOrEqual(1); + expect(Math.abs((anchor?.y ?? 0) - point.y)).toBeLessThanOrEqual(1); + + await page.keyboard.press('Escape'); + await expect(page.getByRole('menu')).toBeHidden(); + // Focus was on the page before the right-click, and goes back there. + expect( + await page.evaluate(() => document.activeElement === document.body), + ).toBe(true); +}); + +test('Shift+F10 before the menu code arrives opens the cell menu once, and Escape hands focus back', async ({ + page, +}) => { + const edit = page.getByRole('button', {name: 'Edit'}); + await edit.focus(); + await page.keyboard.press('Shift+F10'); + expect((await state(page)).contextmenus).toEqual([true]); + await expect(page.getByRole('menu')).toHaveCount(0); + // The invocation asked for the menu code, which the server still holds. + expect(gate.requests).toBe(1); + + release(); + + await expect(page.getByRole('menuitem', {name: 'Copy'})).toBeFocused(); + await settle(page); + expect((await state(page)).shows).toBe(1); + + await page.keyboard.press('Escape'); + await expect(page.getByRole('menu')).toBeHidden(); + await expect(edit).toBeFocused(); +}); + +test.describe('on a touch screen', () => { + test.use({hasTouch: true}); + + test('a long press lifted before the menu code arrives opens the cell menu once at the finger, and Escape hands focus back', async ({ + page, + }) => { + const point = await cellPoint(page); + const driver = await touchDriver(page); + await driver.play(tap(point, {holdMs: 800})); + await expect(page.getByRole('menu')).toHaveCount(0); + // The browser's own menu stayed shut for any contextmenu the press sent. + expect((await state(page)).contextmenus.every(Boolean)).toBe(true); + expect(gate.requests).toBe(1); + + release(); + + await expect(page.getByRole('menuitem', {name: 'Copy'})).toBeFocused(); + await settle(page); + expect((await state(page)).shows).toBe(1); + // The menu opened at the finger. + const anchor = await cell(page) + .locator('span[aria-hidden="true"][style*="anchor-name"]') + .boundingBox(); + expect(Math.abs((anchor?.x ?? 0) - point.x)).toBeLessThanOrEqual(1); + expect(Math.abs((anchor?.y ?? 0) - point.y)).toBeLessThanOrEqual(1); + + await page.keyboard.press('Escape'); + await expect(page.getByRole('menu')).toBeHidden(); + // Focus was on the page before the press, and goes back there. + expect( + await page.evaluate(() => document.activeElement === document.body), + ).toBe(true); + }); +}); diff --git a/packages/core/src/Table/__tests__/TableCellMenuLoad.client.tsx b/packages/core/src/Table/__tests__/TableCellMenuLoad.client.tsx new file mode 100644 index 0000000000000..3a4c4cddc3399 --- /dev/null +++ b/packages/core/src/Table/__tests__/TableCellMenuLoad.client.tsx @@ -0,0 +1,15 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. +/** + * @file TableCellMenuLoad.client.tsx + * @input The fixture's Root and the server-rendered markup in #root + * @output Hydrates the markup and records recoverable hydration errors + * @position Browser entry of the TableCellMenuLoad fixture + */ +import {hydrateRoot} from 'react-dom/client'; +import {Root} from './TableCellMenuLoad.fixture'; + +const state = window as unknown as {__recoverable: string[]}; +state.__recoverable = []; +hydrateRoot(document.getElementById('root') as HTMLElement, , { + onRecoverableError: error => state.__recoverable.push(String(error)), +}); diff --git a/packages/core/src/Table/__tests__/TableCellMenuLoad.fixture.tsx b/packages/core/src/Table/__tests__/TableCellMenuLoad.fixture.tsx new file mode 100644 index 0000000000000..b03ef4fea58b1 --- /dev/null +++ b/packages/core/src/Table/__tests__/TableCellMenuLoad.fixture.tsx @@ -0,0 +1,48 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. +'use client'; +/** + * @file TableCellMenuLoad.fixture.tsx + * @input Table, TableBody, TableRow and TableCell from source + * @output Root: one row with a context-menu cell and a plain cell, which marks + * the document once it has hydrated + * @position Test-only fixture for TableCellMenuLoad.a11y.chromium.spec.ts, + * rendered on the server and hydrated in the browser + */ +import {useEffect, type ReactNode} from 'react'; +import {Table} from '../Table'; +import {TableBody} from '../TableBody'; +import {TableRow} from '../TableRow'; +import {TableCell} from '../TableCell'; +import type {TableContextAction} from '../types'; +import '../../reset.css'; + +const actions: TableContextAction[] = [ + {id: 'copy', label: 'Copy', onSelect: () => {}}, + {id: 'paste', label: 'Paste', onSelect: () => {}}, +]; + +function Hydrated(): null { + // Syncs the document with hydration: the spec waits for this mark. + useEffect(() => { + document.documentElement.dataset.hydrated = 'true'; + }, []); + return null; +} + +export function Root(): ReactNode { + return ( + <> + + + + + Alice + + Plain cell + + +
+ + + ); +} diff --git a/packages/core/src/Table/__tests__/TableCellMenuLoad.html b/packages/core/src/Table/__tests__/TableCellMenuLoad.html new file mode 100644 index 0000000000000..79e0735bce33c --- /dev/null +++ b/packages/core/src/Table/__tests__/TableCellMenuLoad.html @@ -0,0 +1,13 @@ + + + + + + + Table cell menu load + + +
+ + + diff --git a/packages/core/src/Table/__tests__/TableCellMenuLoad.server.tsx b/packages/core/src/Table/__tests__/TableCellMenuLoad.server.tsx new file mode 100644 index 0000000000000..773612348c73b --- /dev/null +++ b/packages/core/src/Table/__tests__/TableCellMenuLoad.server.tsx @@ -0,0 +1,13 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. +/** + * @file TableCellMenuLoad.server.tsx + * @input The fixture's Root + * @output renderHtml, the fixture's server markup + * @position Server entry of the TableCellMenuLoad fixture + */ +import {renderToString} from 'react-dom/server'; +import {Root} from './TableCellMenuLoad.fixture'; + +export function renderHtml(): string { + return renderToString(); +} diff --git a/packages/core/src/Table/__tests__/TableCellMenuLoad.vite.mjs b/packages/core/src/Table/__tests__/TableCellMenuLoad.vite.mjs new file mode 100644 index 0000000000000..cc253547be2d0 --- /dev/null +++ b/packages/core/src/Table/__tests__/TableCellMenuLoad.vite.mjs @@ -0,0 +1,39 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. +/** Test-only build of the cell-menu load fixture, compiled from source. */ +import {defineConfig} from 'vite'; +import react from '@vitejs/plugin-react'; +import path from 'node:path'; +import {astryxStylex} from '../../../../build/src/vite'; +import resolution from '../../../../../scripts/stylex-module-resolution.cjs'; +const root = process.cwd(); +// The server build emits no stylesheet, so it skips the CSS layer split; its +// class names come from the same StyleX compile as the client build's. +export default defineConfig(({isSsrBuild}) => ({ + root: path.join(root, 'packages/core/src/Table/__tests__'), + plugins: [ + ...astryxStylex({ + libraryPattern: 'packages/', + stylexOptions: { + dev: false, + styleResolution: 'application-order', + unstable_moduleResolution: resolution.stylexModuleResolution, + }, + }).filter( + plugin => !isSsrBuild || plugin.name !== 'astryx-build-layer-split', + ), + react(), + ], + // The server build lands outside Core's folder, where only React resolves, + // so it bundles every other dependency. + ssr: {noExternal: true}, + build: { + target: 'chrome123', + manifest: true, + rollupOptions: { + input: path.join( + root, + 'packages/core/src/Table/__tests__/TableCellMenuLoad.html', + ), + }, + }, +})); diff --git a/packages/core/src/Table/__tests__/menuLoadScenario.tsx b/packages/core/src/Table/__tests__/menuLoadScenario.tsx new file mode 100644 index 0000000000000..775a253bbf368 --- /dev/null +++ b/packages/core/src/Table/__tests__/menuLoadScenario.tsx @@ -0,0 +1,127 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file menuLoadScenario.tsx + * @input Uses Testing Library and TableCellContextMenu's loader + * @output Exports expectContentSurvivesMenuLoad, a test scenario for a cell + * whose context menu loads after its content + * @position Test-only helper shared by the body-cell and header-cell suites, + * which each run it in their own module registry so the menu starts cold + */ + +import {act, fireEvent, render, screen, waitFor} from '@testing-library/react'; +import {useEffect, useState, type ReactNode} from 'react'; +import {expect, vi} from 'vitest'; +import {loadTableContextMenu} from '../TableCellContextMenu'; +import type {TableContextAction} from '../types'; + +export const scenarioActions: TableContextAction[] = [ + {id: 'copy', label: 'Copy', onSelect: () => {}}, + {id: 'paste', label: 'Paste', onSelect: () => {}}, +]; + +const mounts = {count: 0}; + +/** Cell content with its own state, a mount effect and two focusable parts. */ +export function StatefulContent(): ReactNode { + const [count, setCount] = useState(0); + const [text, setText] = useState(''); + useEffect(() => { + mounts.count += 1; + }, []); + return ( + <> + + setText(event.target.value)} + /> + + ); +} + +/** jsdom has no Popover API; mirror the ContextMenu tests' mock. */ +export function mockPopover(): void { + HTMLElement.prototype.showPopover = vi.fn(function (this: HTMLElement) { + this.setAttribute('popover-open', ''); + const event = new Event('toggle', {bubbles: false}); + Object.defineProperty(event, 'newState', {value: 'open'}); + this.dispatchEvent(event); + }); + HTMLElement.prototype.hidePopover = vi.fn(function (this: HTMLElement) { + this.removeAttribute('popover-open'); + const event = new Event('toggle', {bubbles: false}); + Object.defineProperty(event, 'newState', {value: 'closed'}); + this.dispatchEvent(event); + }); +} + +/** + * Renders `cell` while the menu module is still loading. `cell` is a table + * with one cell that has `scenarioActions` around ``. The + * scenario edits and focuses the content, then lets the menu load. It checks + * that the content kept its nodes, state and single mount. It then checks + * that the menu opens from the keyboard (Shift+F10), navigates, and returns + * focus on Escape. + * + * With `invoke: 'before-load'`, the Shift+F10 arrives before the menu loads. + * The cell holds it, so the browser's menu does not open. The cell's menu + * opens after the load. + */ +export async function expectContentSurvivesMenuLoad( + cell: ReactNode, + focus: 'button' | 'input', + invoke: 'before-load' | 'after-load', +): Promise { + mounts.count = 0; + render(cell); + const button = screen.getByRole('button', {name: 'Count 0'}); + const input = screen.getByRole('textbox', {name: 'Edit'}); + fireEvent.click(button); + fireEvent.change(input, {target: {value: 'draft'}}); + const focused = focus === 'button' ? button : input; + focused.focus(); + // Shift+F10 / the Menu key: a contextmenu at (0, 0) with no click count. + const openFromKeyboard = () => + fireEvent.contextMenu(focused, {clientX: 0, clientY: 0, detail: 0}); + + if (invoke === 'before-load') { + expect(openFromKeyboard()).toBe(false); + expect(screen.queryByRole('menu', {hidden: true})).toBeNull(); + } + + await act(async () => { + await loadTableContextMenu(); + }); + await act(async () => { + await new Promise(resolve => setTimeout(resolve, 0)); + }); + + expect(screen.getByRole('button', {name: 'Count 1'})).toBe(button); + expect(screen.getByRole('textbox', {name: 'Edit'})).toBe(input); + expect(input).toHaveValue('draft'); + expect(mounts.count).toBe(1); + + if (invoke === 'after-load') { + expect(focused).toHaveFocus(); + expect(openFromKeyboard()).toBe(false); + } + await waitFor(() => { + expect( + screen.getByRole('menuitem', {name: 'Copy', hidden: true}), + ).toHaveFocus(); + }); + fireEvent.keyDown(screen.getByRole('menu', {hidden: true}), { + key: 'ArrowDown', + }); + expect( + screen.getByRole('menuitem', {name: 'Paste', hidden: true}), + ).toHaveFocus(); + fireEvent.keyDown(document, {key: 'Escape'}); + expect(focused).toHaveFocus(); +} diff --git a/packages/core/src/Table/__tests__/warmTableContextMenu.tsx b/packages/core/src/Table/__tests__/warmTableContextMenu.tsx new file mode 100644 index 0000000000000..4de540a84b81e --- /dev/null +++ b/packages/core/src/Table/__tests__/warmTableContextMenu.tsx @@ -0,0 +1,43 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file warmTableContextMenu.tsx + * @input Uses TableCellContextMenu and Testing Library + * @output Exports warmTableContextMenu, a test helper that resolves the lazily + * loaded table context menu once + * @position Test-only helper for suites that right-click table cells + * + * TableCell and TableHeaderCell load their context menu with React.lazy, so a + * cell's menu is ready a tick after the cell first renders. Rendering one up + * front caches the resolved module on the lazy component, and every later + * cell renders its menu synchronously. Call it from `beforeAll`. + */ + +import {act, cleanup, render} from '@testing-library/react'; +import { + TableCellContextMenu, + loadTableContextMenu, +} from '../TableCellContextMenu'; + +export async function warmTableContextMenu(): Promise { + try { + await act(async () => { + render( + {}}]}> + Warm cell + , + ); + }); + // A cold import transforms the menu's module graph; once it settles, the + // lazy component resolves on the next tick. + await act(async () => { + await loadTableContextMenu(); + }); + await act(async () => { + await new Promise(resolve => setTimeout(resolve, 0)); + }); + } finally { + cleanup(); + } +} diff --git a/packages/core/src/Table/index.ts b/packages/core/src/Table/index.ts index 53fc798eeb684..734a71ef63c58 100644 --- a/packages/core/src/Table/index.ts +++ b/packages/core/src/Table/index.ts @@ -60,7 +60,7 @@ export {useTableInfiniteScroll} from './plugins/infiniteScroll'; export {useTableRowStatus} from './plugins/rowStatus'; export {useTableRowExpansion} from './plugins/rowExpansion'; export {useTableTreeData, useTableTreeState} from './plugins/tree'; -export {resolveContextActions} from './tableContextMenu'; +export {resolveContextActions} from './tableContextActions'; export { useTableFiltering, useTableFilterState, diff --git a/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.test.tsx b/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.test.tsx index 46fcacab530f7..1c68b6441cb63 100644 --- a/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.test.tsx +++ b/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.test.tsx @@ -1,6 +1,6 @@ // Copyright (c) Meta Platforms, Inc. and affiliates. -import {describe, it, expect, vi, beforeEach} from 'vitest'; +import {describe, it, expect, vi, beforeAll, beforeEach} from 'vitest'; import {render, screen, fireEvent, act} from '@testing-library/react'; import {useState} from 'react'; import {Table} from '../../Table'; @@ -10,6 +10,11 @@ import {InternationalizationProvider} from '../../../i18n'; import type {ComponentIconMap} from '../../../Icon/index'; import {defineTheme} from '../../../theme/defineTheme'; import {Theme} from '../../../theme/Theme'; +import {warmTableContextMenu} from '../../__tests__/warmTableContextMenu'; + +// Cells load their context menu lazily; resolve it once so menus open +// synchronously below. +beforeAll(warmTableContextMenu); // popover mock for context-menu tests beforeEach(() => { diff --git a/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.tsx b/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.tsx index 6e99347a02743..672fba9ec6b7e 100644 --- a/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.tsx +++ b/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.tsx @@ -43,7 +43,7 @@ import {Icon} from '../../../Icon'; import {ComponentIcon} from '../../../Icon/ComponentIcon'; import {iconBoxSizeStyles} from '../../../Icon/IconSize.stylex'; import {VisuallyHidden} from '../../../VisuallyHidden'; -import {resolveContextActions} from '../../tableContextMenu'; +import {resolveContextActions} from '../../tableContextActions'; import {useTableContext} from '../../useTableCellStyles'; import {rtlStyles} from '../../../utils'; import { diff --git a/packages/core/src/Table/plugins/sortable/useTableSortable.test.tsx b/packages/core/src/Table/plugins/sortable/useTableSortable.test.tsx index d6c6b3d3bb493..fdf5150359bc0 100644 --- a/packages/core/src/Table/plugins/sortable/useTableSortable.test.tsx +++ b/packages/core/src/Table/plugins/sortable/useTableSortable.test.tsx @@ -7,7 +7,7 @@ * @position Testing; validates sortable plugin implementation */ -import {describe, it, expect, vi, beforeEach} from 'vitest'; +import {describe, it, expect, vi, beforeAll, beforeEach} from 'vitest'; import {render, screen, fireEvent} from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import {useState} from 'react'; @@ -18,6 +18,11 @@ import {useTableSortable, type TableSortState} from './useTableSortable'; import type {ComponentIconMap} from '../../../Icon/index'; import {defineTheme} from '../../../theme/defineTheme'; import {Theme} from '../../../theme/Theme'; +import {warmTableContextMenu} from '../../__tests__/warmTableContextMenu'; + +// Cells load their context menu lazily; resolve it once so menus open +// synchronously below. +beforeAll(warmTableContextMenu); // ============================================================================= // Test Data diff --git a/packages/core/src/Table/plugins/sortable/useTableSortable.tsx b/packages/core/src/Table/plugins/sortable/useTableSortable.tsx index f81358c776258..5b082ff59ebb7 100644 --- a/packages/core/src/Table/plugins/sortable/useTableSortable.tsx +++ b/packages/core/src/Table/plugins/sortable/useTableSortable.tsx @@ -20,7 +20,7 @@ import {colorVars, spacingVars, radiusVars} from '../../../theme/tokens.stylex'; import {focusOutlineProps} from '../../../utils/focusOutline.stylex'; import {Icon} from '../../../Icon'; import {ComponentIcon} from '../../../Icon/ComponentIcon'; -import {resolveContextActions} from '../../tableContextMenu'; +import {resolveContextActions} from '../../tableContextActions'; import type { TablePlugin, HeaderCellRenderProps, diff --git a/packages/core/src/Table/tableContextActions.ts b/packages/core/src/Table/tableContextActions.ts new file mode 100644 index 0000000000000..df2576510ff60 --- /dev/null +++ b/packages/core/src/Table/tableContextActions.ts @@ -0,0 +1,48 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file tableContextActions.ts + * @input types + * @output resolveContextActions, hasContextActions + * @position Dependency-free helpers for `contextMenuActions`, shared by cells + * and plugins, so reading actions never pulls in the context menu itself. + * + * SYNC: When modified, update these files to stay in sync: + * - /packages/core/src/Table/types.ts (TableContextAction) + */ + +import type {TableContextAction, TableContextActions} from './types'; + +/** + * Resolve a `contextMenuActions` value (array or getter) to a plain array. + * Use this when composing actions from a prior plugin's render props so you + * don't have to branch on the array-vs-getter form: + * + * ``` + * contextMenuActions: () => [ + * ...resolveContextActions(props.contextMenuActions), + * ...myActions, + * ] + * ``` + */ +export function resolveContextActions( + actions: TableContextActions | undefined, +): TableContextAction[] { + if (typeof actions === 'function') { + return actions(); + } + return actions ?? []; +} + +/** + * Whether a `contextMenuActions` value can open a menu: a getter (resolved on + * open) or a non-empty array. + */ +export function hasContextActions( + actions: TableContextActions | undefined, +): boolean { + return ( + typeof actions === 'function' || + (Array.isArray(actions) && actions.length > 0) + ); +} diff --git a/packages/core/src/Table/tableContextMenu.test.tsx b/packages/core/src/Table/tableContextMenu.test.tsx index 006e1b3466299..653c67e98393d 100644 --- a/packages/core/src/Table/tableContextMenu.test.tsx +++ b/packages/core/src/Table/tableContextMenu.test.tsx @@ -6,11 +6,16 @@ * @position Validates contextMenuActions aggregation + header context menus */ -import {describe, it, expect, vi, beforeEach} from 'vitest'; +import {describe, it, expect, vi, beforeAll, beforeEach} from 'vitest'; import {render, screen, fireEvent} from '@testing-library/react'; import {Table} from './Table'; import type {TablePlugin, TableColumn} from './types'; -import {resolveContextActions} from './tableContextMenu'; +import {resolveContextActions} from './tableContextActions'; +import {warmTableContextMenu} from './__tests__/warmTableContextMenu'; + +// Cells load their context menu lazily; resolve it once so menus open +// synchronously below. +beforeAll(warmTableContextMenu); // jsdom doesn't implement the Popover API; mirror the ContextMenu test's mock // so the menu can "open" and its items become queryable (as hidden). diff --git a/packages/core/src/Table/tableContextMenu.tsx b/packages/core/src/Table/tableContextMenu.tsx index 4a648c45521b6..23e59575e0c53 100644 --- a/packages/core/src/Table/tableContextMenu.tsx +++ b/packages/core/src/Table/tableContextMenu.tsx @@ -5,41 +5,25 @@ /** * @file tableContextMenu.tsx * @input React, ContextMenu, Icon, types - * @output wrapInTableContextMenu helper - * @position Renders the aggregated `contextMenuActions` for a header cell / row + * @output TableContextMenuForTrigger + * @position The lazily loaded context menu for a body or header cell with + * `contextMenuActions` * * SYNC: When modified, update these files to stay in sync: - * - /packages/core/src/Table/BaseTable.tsx (call sites) + * - /packages/core/src/Table/TableCellContextMenu.tsx (lazy loader) + * - /packages/core/src/Table/tableContextActions.ts (resolveContextActions) * - /packages/core/src/Table/types.ts (TableContextAction) */ import {useState, type ReactNode} from 'react'; -import {ContextMenu, type ContextMenuOption} from '../ContextMenu'; -import {Icon} from '../Icon'; -import type {StyleXStyles} from '../theme/types'; +import { + ContextMenuForTrigger, + type ContextMenuExternalTrigger, + type ContextMenuOption, +} from '../ContextMenu/ContextMenu'; +import {Icon} from '../Icon/Icon'; import type {TableContextAction, TableContextActions} from './types'; -/** - * Resolve a `contextMenuActions` value (array or getter) to a plain array. - * Use this when composing actions from a prior plugin's render props so you - * don't have to branch on the array-vs-getter form: - * - * ``` - * contextMenuActions: () => [ - * ...resolveContextActions(props.contextMenuActions), - * ...myActions, - * ] - * ``` - */ -export function resolveContextActions( - actions: TableContextActions | undefined, -): TableContextAction[] { - if (typeof actions === 'function') { - return actions(); - } - return actions ?? []; -} - /** * Convert the flat action list into ContextMenu options, inserting a divider * between groups (first-seen group order). Ungrouped actions form a trailing @@ -87,89 +71,36 @@ function toContextMenuOptions( } /** - * Wrap a table element (a header cell's content or a row) in a right-click - * context menu rendering the aggregated `actions`. When no plugin contributes - * actions the element is returned untouched so the native browser menu passes - * through. - */ -/** - * A context menu whose actions are resolved lazily — only when the user opens - * the menu (right-click). Deferring the work means plugins that pass a getter - * don't build an action array (with its closures) for every cell on every - * render; it's computed on demand and memoized until the menu closes. + * The menu for a cell whose trigger TableCellContextMenu renders. It loads + * lazily beside the cell's content, so the content never remounts. A getter + * resolves when the menu opens and stays memoized until the menu closes. So + * a plugin that passes a getter builds no action array on each cell render. */ -function LazyTableContextMenu({ - element, - getActions, - triggerXstyle, +export function TableContextMenuForTrigger({ + actions, + trigger, }: { - element: ReactNode; - getActions: () => TableContextAction[]; - triggerXstyle?: StyleXStyles | StyleXStyles[]; + actions: TableContextActions; + trigger: ContextMenuExternalTrigger; }): ReactNode { - const [options, setOptions] = useState(null); - return ( - { - // Resolve actions when opening; clear on close so state derived later - // (e.g. current sort direction) is always fresh next open. - setOptions(open ? toContextMenuOptions(getActions()) : null); - }}> - {element} - - ); -} - -/** - * Whether `actions` give a cell a context menu: a getter, or a non-empty array. - * Cells read it to style the menu's trigger, and `wrapInTableContextMenu` to - * decide whether to wrap, so the two always agree. - */ -export function hasTableContextActions( - actions: TableContextActions | undefined, -): actions is NonNullable { - return ( - typeof actions === 'function' || - (Array.isArray(actions) && actions.length > 0) + const [lazyOptions, setLazyOptions] = useState( + null, ); -} - -/** - * Wrap a table element (a header cell's content or a body cell) in a right-click - * context menu rendering the aggregated `actions`. Accepts a static array or a - * getter (resolved lazily on open). When there are no actions the element is - * returned untouched so the native browser menu passes through. - * - * `triggerXstyle` styles the right-click target wrapper. Cells pass a fill + - * padding style so the entire cell (padding included) opens the menu. - */ -export function wrapInTableContextMenu( - element: ReactNode, - actions: TableContextActions | undefined, - triggerXstyle?: StyleXStyles | StyleXStyles[], -): ReactNode { - // Getter form → resolve lazily on open. if (typeof actions === 'function') { return ( - { + setLazyOptions(open ? toContextMenuOptions(actions()) : null); + }} /> ); } - if (!hasTableContextActions(actions)) { - return element; - } - // item (it looked like "ascending" was always selected). Focus moves only - // when the user arrow-keys into the menu. return ( - - {element} - + /> ); } diff --git a/scripts/check-component-import-boundaries.mjs b/scripts/check-component-import-boundaries.mjs index c6110fbfb77b8..385615aa34377 100644 --- a/scripts/check-component-import-boundaries.mjs +++ b/scripts/check-component-import-boundaries.mjs @@ -120,8 +120,12 @@ export const CORE_BOUNDARIES = { // Trigger contract and context plumbing that live in a surface folder. A // truncated Text hands its held intent to the tooltip through // `tooltipPresentInterest`; every scoped context uses `layerScopedContext`. + // A table cell renders `ContextMenuTrigger` before its menu loads, and reads + // `gestureCounter` to drop a held invocation at a later press or key. baseModulesInSurfaceFolders: [ 'Tooltip/tooltipPresentInterest', + 'ContextMenu/ContextMenuTrigger', + 'Layer/gestureCounter', 'Layer/layerScopedContext', ], // The shared internal touch modules, the layer's touch trigger, and the diff --git a/scripts/check-component-import-boundaries.test.mjs b/scripts/check-component-import-boundaries.test.mjs index b34770f4fae1d..dbcff494ad462 100644 --- a/scripts/check-component-import-boundaries.test.mjs +++ b/scripts/check-component-import-boundaries.test.mjs @@ -401,7 +401,11 @@ describe('the allowlist', () => { entries: ['Button', 'IconButton'], }, {from: 'Link/Link', to: 'Tooltip', entries: ['Link']}, - {from: 'Table/tableContextMenu', to: 'ContextMenu', entries: ['Table']}, + { + from: 'Table/TableCellContextMenu', + to: 'Layer/gestureCounter', + entries: ['Table'], + }, { from: 'Table/BaseTable', to: 'Table/plugins/virtualization/useTableWindow', diff --git a/scripts/core-single-bundle.test.mjs b/scripts/core-single-bundle.test.mjs index ea618855169e4..2b09239ddcdbb 100644 --- a/scripts/core-single-bundle.test.mjs +++ b/scripts/core-single-bundle.test.mjs @@ -159,8 +159,9 @@ describe('Core in esbuild bundles', () => { metafile: true, }); const {outputs} = result.metafile; - const entry = Object.keys(outputs).find( - file => outputs[file].entryPoint != null, + // Core's lazy modules are entry points too, so pick the app's own. + const entry = Object.keys(outputs).find(file => + outputs[file].entryPoint?.endsWith('main.jsx'), ); const startup = new Set([entry]); const queue = [entry]; diff --git a/scripts/shared-identity.baseline.json b/scripts/shared-identity.baseline.json index acaeb5e67449a..ae62a839db1bb 100644 --- a/scripts/shared-identity.baseline.json +++ b/scripts/shared-identity.baseline.json @@ -161,6 +161,10 @@ "status": "allowed", "reason": "The attach and the scroll calls run in the same copy; the paging value is shared." }, + "packages/core/src/Table/TableCellContextMenu.tsx:LazyTableContextMenu": { + "status": "allowed", + "reason": "Each copy's lazy loads that copy's menu module, which reads that copy's contexts; a shared lazy would render one copy's menu in another copy's cell." + }, "packages/core/src/Table/glidingDivider.ts:inlineColorOf": { "status": "allowed", "reason": "Keyed by rows of one table; only that table's row-expansion plugin marks them, so its overlapping glides share one copy's maps."