Skip to content

[context menu] Fix right-click open is marked as instant - #5627

Closed
sai6855 wants to merge 6 commits into
mui:masterfrom
sai6855:context-menu-event-fix
Closed

sai6855 wants to merge 6 commits into
mui:masterfrom
sai6855:context-menu-event-fix

Conversation

@sai6855

@sai6855 sai6855 commented Sep 3, 2026 •

Copy link
Copy Markdown
Member

closes #5593

Right-click and touch long-press both produce detail === 0, so MenuRoot classified them as keyboard clicks and put data-instant="click" on the popup. Anyone using data-instant:transition-none lost the enter transition while the exit one still played.

ContextMenuTrigger now tags the event details with the gesture it actually handled instead of MenuRoot guessing from the event shape. Also covers the Android case where the native contextmenu and our long-press timer race to open the menu.

@pkg-pr-new

pkg-pr-new Bot commented Sep 3, 2026 •

Copy link
Copy Markdown

commit: c804b95

@code-infra-dashboard

code-infra-dashboard Bot commented Sep 3, 2026 •

Copy link
Copy Markdown

Bundle size

Bundle Parsed size Gzip size
@base-ui/react 🔺+441B(+0.10%) 🔺+123B(+0.08%)

Details of bundle changes

Performance

Total duration: 1,020.63 ms +19.33 ms(+1.9%) | Renders: 76 (+0) | Paint: 1,643.38 ms +35.31 ms(+2.2%)

Test Duration Renders
Mixed surface mount (app-like density) 74.23 ms 🔺+14.45 ms(+24.2%) 5 (+0)

14 tests within noise — details

Metric alarms

Test Metric Change
Mixed surface mount (app-like density) bench:paint 🔺 +19.55 ms

Check out the code infra dashboard for more information about this PR.

@sai6855

sai6855 commented Sep 3, 2026

Copy link
Copy Markdown
Member Author

@claude review

@github-actions

github-actions Bot commented Sep 3, 2026 •

Copy link
Copy Markdown

PR review

The fix is narrowly scoped, instantType is styling-only, and the two guards cover the cases the linked issue describes, so nothing here is merge-blocking. Two gaps are worth closing before merge: the new discriminator still classifies a touch-originated native contextmenu (Android long press) as a keyboard activation, and the ctrlKey half of the new condition has no test.

Bugs (1)

1. 🟠 Touch-originated contextmenu events are still treated as keyboard activations

Location: packages/react/src/menu/root/MenuRoot.tsx:380

const isPointerContextMenu =
  eventType === 'contextmenu' &&
  ((nativeEvent as MouseEvent).button !== 0 || (nativeEvent as MouseEvent).ctrlKey);
const isTouchPress = eventType != null && eventType.startsWith('touch');

isTouchPress only catches the touchstart event that ContextMenuTrigger's own 500 ms timer forwards (ContextMenuTrigger.tsx:141-143). It does not catch the native contextmenu that Chromium on Android dispatches for a long press: that event has button === 0 and no ctrlKey, so isPointerContextMenu is false, isTouchPress is false, detail === 0, and the popup is marked data-instant="click" — exactly the bug this PR fixes, for the touch path.

That path is reachable because ContextMenuTrigger.handleContextMenu (ContextMenuTrigger.tsx:76-82) is not touch-aware: it runs for any contextmenu, calls handleLongPress(..., event.nativeEvent) and opens the menu. Whether it or the 500 ms timer wins is a race between two ~500 ms deadlines, so this is intermittent rather than deterministic — but when the native event wins, the guard added here does not apply. (I could not exercise a real Android browser here, so treat the race outcome as plausible rather than measured; the classification gap itself is directly readable from the code.)

Failure scenario: On Android Chrome, long-pressing a ContextMenu.Trigger opens the popup with data-instant="click" on some presses and without it on others, so a consumer's enter animation flickers on/off between identical gestures.

Fix: Chromium dispatches contextmenu as a PointerEvent, so pointerType is available and is a stronger signal than button (Firefox, which dispatches a plain MouseEvent, still falls through to the button/ctrlKey check). Something like:

const isPointerContextMenu =
  eventType === 'contextmenu' &&
  ((nativeEvent as MouseEvent).button !== 0 ||
    (nativeEvent as MouseEvent).ctrlKey ||
    ((nativeEvent as PointerEvent).pointerType != null &&
      (nativeEvent as PointerEvent).pointerType !== ''));

Alternatively, make the trigger authoritative: handleContextMenu can consult touchPositionRef.current / longPressTimeout.isStarted() to know the gesture was touch-driven and tag the event details accordingly.

Tests (1)

1. 🟠 The ctrlKey branch of the new condition is untested

Location: packages/react/src/context-menu/root/ContextMenuRoot.test.tsx:287

The new condition has two independent clauses, button !== 0 and ctrlKey. Only the first is exercised ({ button: 2 }). Nothing in packages/react/src/context-menu or packages/react/src/menu passes ctrlKey in any test, so the macOS Ctrl+click case — the reason that clause exists, per the comment on MenuRoot.tsx:378 — can be deleted or inverted without a single failure. This file already mocks platform.os.mac: true at the top, so the case fits naturally here.

Failure scenario: Someone simplifies isPointerContextMenu down to button !== 0, the suite stays green, and Safari on macOS regresses to marking Ctrl+click-opened context menus as instant.

Fix: Add a third case alongside the two new ones:

fireEvent.contextMenu(screen.getByTestId('context-trigger'), {
  clientX: 10,
  clientY: 10,
  button: 0,
  ctrlKey: true,
});
expect(await screen.findByTestId('context-popup')).not.toHaveAttribute('data-instant');

Docs (1)

1. ℹ️ Test comment implies coordinates are part of the keyboard discriminator

Location: packages/react/src/context-menu/root/ContextMenuRoot.test.tsx:328

// Shift+F10 / the Menu key raise a `contextmenu` event with no pointer origin
// (`button === 0`, zeroed coordinates) — this is a genuine keyboard activation.

The implementation never reads clientX/clientY, and the claim is not generally true: Chromium sets a keyboard-invoked contextmenu's coordinates to the focused element's position, not 0,0. The comment reads as if the test is pinning a coordinate-based rule.

Fix: Drop the "zeroed coordinates" clause and keep the part that matches the code — button === 0 and no ctrlKey.

Verdict

Approve after nits - the guard is correct and low-risk for the cases it covers, but the touch-originated contextmenu path is left misclassified and the ctrlKey clause has no test.


🤖 Review generated with Claude Code · Opus 5 (High) · medium review depth · 34 turns · 5m31s · $1.99 · run

@sai6855 sai6855 added type: bug It doesn't behave as expected. component: context menu Changes related to the context menu component. labels Sep 3, 2026
@netlify

netlify Bot commented Sep 3, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for base-ui ready!

Built without sensitive environment variables

Name Link
🔨 Latest commit c804b95
🔍 Latest deploy log https://app.netlify.com/projects/base-ui/deploys/6aa27e2f0e62860008d6bfbe
😎 Deploy Preview https://deploy-preview-5627--base-ui.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
🤖 Make changes Run an agent on this branch

To edit notification comments on pull requests, go to your Netlify project configuration.

A mouse right-click and a touch long-press both produce a `contextmenu` /
`TouchEvent` with `detail === 0`, which the shared Menu logic classified as a
keyboard activation, adding `data-instant="click"` to the popup. Consumers of
`data-instant:transition-none` then skipped the enter transition while a later
mouse close still played the exit transition.

The trigger now classifies the gesture itself and passes an explicit `instantType`
on the event details (touch and pointer animate; a keyboard `contextmenu` stays
instant). A pending long-press recorded by `handleTouchStart` marks the Android
native `contextmenu` as pointer-driven, resolving the open-path race.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
@sai6855
sai6855 force-pushed the context-menu-event-fix branch from 3a90588 to 7accb92 Compare September 10, 2026 05:40
@sai6855

sai6855 commented Sep 10, 2026

Copy link
Copy Markdown
Member Author

@claude review

@github-actions

github-actions Bot commented Sep 10, 2026 •

Copy link
Copy Markdown

PR review

The fix is well-targeted — right-click and long-press opens no longer inherit the detail === 0 keyboard heuristic — and the touchPositionRef guard for Android's native long-press contextmenu is a nice catch. Nothing here is merge-blocking. The main concerns are that the non-Chromium fallback in isKeyboardContextMenu rests on an unverified assumption about keyboard contextmenu coordinates, that the branch every Chrome user actually hits (pointerType) is never exercised by the new tests, and that the instantType channel into MenuRoot is detected by property sniffing and leaks onto public event details.

Bugs (1)

1. 🟠 The non-Chromium keyboard fallback assumes zeroed coordinates, which Firefox/Safari likely do not provide

Location: packages/react/src/context-menu/trigger/ContextMenuTrigger.tsx:24

function isKeyboardContextMenu(event: MouseEvent): boolean {
  const { pointerType } = event as PointerEvent;
  if (pointerType != null) {
    return pointerType === '';
  }
  return event.button === 0 && event.clientX === 0 && event.clientY === 0;
}

The Chromium branch is sound. The fallback — used by Firefox and Safari, which still dispatch contextmenu as a plain MouseEvent — requires clientX === 0 && clientY === 0. Gecko and WebKit need real coordinates to position the native menu for a keyboard-invoked contextmenu, and dispatch the event at the focused element's box rather than at the viewport origin. If that holds, keyboard activation in those browsers falls through as "pointer-driven" and the popup animates in where it previously opened instantly. Note that the same assumption is asserted as fact in the JSDoc above the function ("a keyboard activation reports the primary button and no coordinates") without any test covering a non-zero-coordinate keyboard event, so nothing in CI would catch it being wrong.

This repo already has a cross-browser answer to exactly this problem, and the header comment on it names the same two browsers:

// packages/utils/src/useEnhancedClickHandler.ts
// Safari and Firefox do not provide the PointerEvent to the click handler (they use MouseEvent) yet.
lastClickInteractionTypeRef.current = event.pointerType as InteractionType;

Failure scenario: A user focuses a ContextMenu.Trigger subtree in Firefox and presses Shift+F10 or the Menu key. The event arrives as a MouseEvent with button === 0 but clientX/clientY at the focused element, so isKeyboardContextMenu returns false, instantType is undefined, and the popup plays its enter transition instead of appearing instantly — the behavior the PR explicitly intends to keep.

Fix: Track the last pointerdown pointerType on the trigger (the useEnhancedClickHandler pattern) and treat a contextmenu with no preceding pointer gesture as keyboard, instead of inferring it from geometry. That also subsumes the touchPositionRef.current == null special case in handleContextMenu, since a touch long press always records a pointerdown first. If you prefer to keep the geometry heuristic, at minimum add Gecko's reliable signal ((event as MouseEvent & { mozInputSource?: number }).mozInputSource === 6) before falling back to coordinates.

Tests (1)

1. 🟠 No test exercises the pointerType branch that runs in every real Chromium session

Location: packages/react/src/context-menu/root/ContextMenuRoot.test.tsx:302

fireEvent.contextMenu(screen.getByTestId('context-trigger'), {
  clientX: 10,
  clientY: 10,
  button: 2,
});

fireEvent.contextMenu constructs a MouseEvent, in the browser runner as well as in jsdom, so pointerType is undefined and all four new tests take the button/coordinate fallback. The pointerType === '' branch — the only branch that runs for real users in Chromium, for both right-click and Shift+F10 — has zero coverage. Inverting it to pointerType !== '' would keep the whole suite green while making every Chrome right-click instant again and every Chrome keyboard open animated, i.e. reintroducing #5593.

Failure scenario: A future refactor of isKeyboardContextMenu breaks the Chromium path; CI passes because the tests only ever construct MouseEvents, and the regression ships.

Fix: Add cases that dispatch real pointer events, e.g. trigger.dispatchEvent(new PointerEvent('contextmenu', { bubbles: true, cancelable: true, pointerType: 'mouse', button: 2 })) expecting no data-instant, and the same with pointerType: '', button: 0 and non-zero clientX/clientY expecting data-instant="click". The latter is the case that pins the Chromium behavior independently of the coordinate fallback.

Simplifications (2)

1. 🟡 Property sniffing with in plus a cast, and an accidental public property on onOpenChange details

Location: packages/react/src/menu/root/MenuRoot.tsx:379

const hasExplicitInstantType = 'instantType' in eventDetails;
const explicitInstantType = hasExplicitInstantType
  ? (eventDetails as { instantType: MenuStoreState<Payload>['instantType'] }).instantType
  : undefined;
const isKeyboardClick =
  !hasExplicitInstantType &&
  (reason === REASONS.triggerPress || reason === REASONS.itemPress) &&
  (nativeEvent as MouseEvent).detail === 0;

Three things pile up here:

  • The signal is a key whose presence matters while its value is legitimately undefined, so it can only be detected with in and read through an untyped cast. That is invisible to the type system: a future caller that spreads the property conditionally (...(x && { instantType: 'click' })) silently changes behavior.
  • !hasExplicitInstantType on isKeyboardClick is dead — isKeyboardClick is only read in the else if chain below, after if (hasExplicitInstantType) has already returned. Likewise explicitInstantType's ternary is only read inside that same branch, so the hasExplicitInstantType ? guard is redundant.
  • createChangeEventDetails spreads custom properties straight onto the object handed to the user's onOpenChange, so ContextMenu.Root consumers now receive an undocumented, untyped details.instantType at runtime.

Failure scenario: A maintainer adds a second trigger that wants to force an instant open, writes instantType: someCondition ? 'click' : undefined in one place and a conditional spread in another, and gets two different behaviors from code that reads identically — while MenuRoot's else if (isDismissClose) branch is silently skipped for any details object that carries the key at all.

Fix: Use a value-carrying, self-describing custom property instead of key presence — e.g. activation: 'keyboard' | 'pointer' — and read it with an optional cast: const activation = (eventDetails as { activation?: 'keyboard' | 'pointer' }).activation; then isKeyboardClick = activation != null ? activation === 'keyboard' : (reason === … && detail === 0). Drop explicitInstantType and the !hasExplicitInstantType guard, and keep the reason-based else if chain intact so a future close path still gets 'dismiss'.

2. 🟡 !isTouchEvent in the instantType expression is unreachable

Location: packages/react/src/context-menu/trigger/ContextMenuTrigger.tsx:93

instantType: !isTouchEvent && keyboardActivation ? 'click' : undefined,

keyboardActivation is only ever true from handleContextMenu, which passes a contextmenu MouseEvent/PointerEvent, so isTouchEvent is false there. The long-press timer path passes a TouchEvent and never supplies the fourth argument, leaving keyboardActivation at its false default. The !isTouchEvent && conjunct can never flip the result.

Failure scenario: A reader has to reconstruct both call sites to convince themselves the guard isn't load-bearing, and the redundant term suggests a "touch + keyboard" combination exists that never can.

Fix: instantType: keyboardActivation ? 'click' : undefined.

Verdict

Approve after nits — the Chromium path is correct and the touch/long-press regression is genuinely fixed; the Firefox/Safari fallback and its missing pointer-event coverage are worth tightening before merge, but neither breaks the primary flow.


🤖 Review generated with Claude Code · Opus 5 (High) · medium review depth · 24 turns · 5m30s · $1.48 · run

sai6855 and others added 4 commits September 10, 2026 11:47
…vent shape

Chromium dispatches `contextmenu` as a `PointerEvent`, so `pointerType` answers
whether a pointer opened the menu. Firefox and Safari still dispatch a plain
`MouseEvent`, and the previous fallback inferred keyboard activation from zeroed
coordinates -- but Gecko and WebKit position a keyboard-invoked native menu
against the focused element, so those coordinates are real and a Shift+F10 open
would have been misread as pointer-driven.

Follow the gesture that produced the event instead: a pointer-driven
`contextmenu` always begins with `pointerdown` on the trigger, while a keyboard
one is always generated by the keypress whose `keydown` fires first and clears
the recorded gesture. This also subsumes the Android long-press special case,
since a long press records a `touch` pointerdown before the native `contextmenu`.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Address review feedback on the gesture-classification approach:

- Move the trigger's classification off the public event details and onto the
  Context Menu root context. `createChangeEventDetails` spreads custom properties
  onto the object passed to `onOpenChange`, so `instantType` was reaching
  consumers as an undocumented key, with producer and consumer agreeing only via
  a string literal and a cast. It is now a typed ref on `ContextMenuRootContext`,
  alongside the other trigger-to-root refs, and `MenuRoot` reads it only for a
  `triggerPress` open whose parent is a context menu.
- Treat the secondary button on the `contextmenu` as a positive pointer signal.
  The recorded gesture is best-effort, and a right-click whose `pointerdown`
  never reached the trigger was falling through to the keyboard branch.
- Record the gesture in the capture phase so a descendant that stops
  `pointerdown` propagation (drag handles, editor widgets) cannot hide it.
- Drop the unreachable `!isTouchEvent` guard: `keyboardActivation` is only ever
  true on the `contextmenu` path.

Tests cover a right-click with no preceding `pointerdown`, a Ctrl+click whose
`pointerdown` a descendant swallows, and a pointer gesture following a key press;
each fails without the specific mechanism it pins. The pointer helpers drop
`firePointer`, whose `timeStamp` precondition nothing here reads.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The previous code claimed Chromium reports an empty `pointerType` for a keyboard
`contextmenu`. Measured on Chromium 151, it does not -- Shift+F10 and the Menu
key both report `pointerType: 'mouse'`, the same value a right-click reports:

  shift+F10        PointerEvent  pointerType="mouse"  button=-1  detail=0
  ContextMenu key  PointerEvent  pointerType="mouse"  button=-1  detail=0
  right-click      PointerEvent  pointerType="mouse"  button= 2  detail=0

So that branch classified every keyboard open in Chrome and Edge as a pointer
open, dropping `data-instant` and animating a popup that should have appeared
instantly. The coordinates are no better: a keyboard activation carries the
focused element's box, in Chromium as well as Gecko and WebKit.

Drop the branch. What is left is engine-agnostic and holds by measurement:
the secondary button is a positive pointer signal, and otherwise the answer is
whether a pointer gesture is in flight. The ordering that supports it:

  shift+F10    -> keydown -> contextmenu(button=-1)
  right-click  -> pointerdown -> contextmenu(button=2)
  ctrl+click   -> keydown(Control) -> pointerdown -> contextmenu

Ctrl+click records its gesture after the modifier's key press clears it, so it
still classifies as a pointer.

The two browser-only tests now reproduce the measured Chromium event shape
rather than one Chromium never emits; the keyboard case fails against the old
branch. `MenuRoot` also consumes the ref it reads, so a stale value cannot
suppress a later open that never wrote one.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The gesture-classification comments had grown into multi-paragraph blocks with
bullet lists, which nothing else in these files does -- the neighbouring
comments are one or two plain lines explaining a single non-obvious "why", and
the sibling context fields carry none at all. Keep the facts that are not
recoverable from the code (that the event's own shape cannot identify a keyboard
`contextmenu`, and that the recording is taken in the capture phase) and drop
the narrative around them. Comments only; no behaviour change.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@sai6855

sai6855 commented Sep 10, 2026

Copy link
Copy Markdown
Member Author

@claude review

@github-actions

github-actions Bot commented Sep 10, 2026 •

Copy link
Copy Markdown

PR review

The fix is sound in shape — moving gesture classification into ContextMenuTrigger instead of guessing from detail === 0 is the right call, and the mouse/keyboard paths are correctly discriminated. The main gap is that the trigger records the gesture only from pointerdown, so a touch long-press whose pointerdown never reaches the trigger still gets classified as a keyboard activation — the same bug this PR fixes, just on touch. Nothing here is merge-blocking, but the touch gap and one inert test assertion are worth fixing first.

Bugs (1)

1. 🟠 A touch long press with no pointerdown on the trigger is classified as a keyboard context menu

Location: packages/react/src/context-menu/trigger/ContextMenuTrigger.tsx:24

function isKeyboardContextMenu(event: MouseEvent, lastPointerType: InteractionType): boolean {
  if (event.button === SECONDARY_BUTTON) {
    return false;
  }
  return lastPointerType === '';
}

lastPointerTypeRef is written only from onPointerDownCapture. handleTouchStart — the trigger's own record that a touch gesture is in flight — never writes it, and '' doubles as both "keyboard" and "nothing recorded yet". So a native contextmenu with button === 0 arriving after a touch, but without a pointerdown having reached the trigger, takes the keyboard branch and sets openInstantTypeRef.current = 'click'.

This is not hypothetical in the PR's own test suite: the Android test at ContextMenuTrigger.test.tsx:425 only passes because it explicitly fires fireEvent.pointerDown(trigger, { pointerType: 'touch' }) at line 439. Delete that one call and the assertion at line 454 flips to data-instant="click". Environments where this happens for real: iOS Safari's hit-slop, where a tap just outside an element's bounds fires mousedown but not pointerdown (already documented in packages/react/src/utils/useOpenInteractionType.ts:19-22), and WebViews/embedders that deliver touch events without Pointer Events.

Failure scenario: A user long-presses the context menu surface on a touch device where the pointerdown lands slightly off the trigger; the native contextmenu opens the menu with data-instant="click", so a consumer using data-instant:transition-none sees the popup snap in while the exit transition still plays — exactly the reported bug.

Fix: Record the gesture from touch as well, so the ref reflects every pointer gesture the trigger observes:

function handleTouchStart(event: React.TouchEvent) {
  lastPointerTypeRef.current = 'touch';
  if (disabled) {
    cancelLongPress();
    return;
  }
  // ...
}

(Setting it before the disabled early-return keeps the record accurate even when the trigger is disabled and the native menu is allowed through.) Add a regression test that fires touchstart + contextmenu with no pointerdown.

Tests (2)

1. 🟡 The Chromium keyboard test does not exercise the mechanism its comment describes

Location: packages/react/src/context-menu/root/ContextMenuRoot.test.tsx:481

// `pointerType` is `'mouse'` here as well, so only the preceding `keydown` marks it keyboard.
fireEvent.keyDown(focusable, { key: 'F10', shiftKey: true });
await dispatchChromiumContextMenu(screen.getByTestId('context-trigger'), -1);

No pointerdown is fired first, so lastPointerTypeRef is still at its initial '' when the contextmenu arrives. The keyDown line is inert — the test passes identically if handleKeyDown and the onKeyDownCapture wiring are deleted entirely. The same is true of marks the popup as instant when opened from the keyboard (line 379); only marks the popup as instant when a key press follows an earlier pointer gesture (line 411) actually pins the reset.

Failure scenario: Someone removes onKeyDownCapture from the trigger's prop list in a later refactor; the Chromium keyboard test stays green while real Shift+F10 after a right-click on the same surface silently stops being instant.

Fix: Fire fireEvent.pointerDown(focusable, { pointerType: 'mouse', button: 2 }) before the keyDown so the assertion depends on the reset, and adjust the comment accordingly.

2. 🟡 No coverage for openInstantTypeRef reuse across successive opens

Location: packages/react/src/menu/root/MenuRoot.tsx:383

if (isContextMenuOpen) {
  // Consumed here so a stale value cannot suppress a later open that never wrote one.
  contextMenuInstantType = contextMenuOpenInstantTypeRef.current;
  contextMenuOpenInstantTypeRef.current = undefined;
}

The design's principal risk is cross-open leakage through a ref that lives on the root context and is written on one side and cleared on the other — notably when onOpenChange cancels the open (MenuRoot.tsx:344-346 returns before the consume runs). Every new test opens the menu exactly once, so nothing verifies that a keyboard open followed by a mouse right-click (or the reverse, or a canceled open in between) classifies correctly the second time.

Failure scenario: A future change moves the ref write out of handleLongPress (or adds a second triggerPress open path that doesn't write it); a keyboard open leaks 'click' into the next right-click open and the whole suite stays green.

Fix: Add one test that opens from the keyboard, closes with Escape, then opens with a mouse right-click and asserts data-instant is absent — plus the mirror case.

Simplifications (2)

1. 🟡 The != null guard and the temp local in MenuRoot can collapse

Location: packages/react/src/menu/root/MenuRoot.tsx:378

const contextMenuOpenInstantTypeRef =
  parent.type === 'context-menu' ? parent.context.openInstantTypeRef : undefined;
const isContextMenuOpen =
  nextOpen && reason === REASONS.triggerPress && contextMenuOpenInstantTypeRef != null;
let contextMenuInstantType: MenuStoreState<Payload>['instantType'];
if (isContextMenuOpen) {
  contextMenuInstantType = contextMenuOpenInstantTypeRef.current;
  contextMenuOpenInstantTypeRef.current = undefined;
}

contextMenuOpenInstantTypeRef != null is always true when parent.type === 'context-menu' — it tests the ref object, not .current. As written the condition is just nextOpen && reason === triggerPress && parent.type === 'context-menu', but the indirection reads like it was meant to be .current != null (which would be a behavior change, since undefined is the meaningful "not instant" value). The temp local exists only to survive from the read site to line 409.

Also, the adjacent comment — "Consumed here so a stale value cannot suppress a later open that never wrote one" — doesn't match the invariant documented on the context field ("Written by the trigger before every open it drives"): if every trigger-driven open writes the ref, no stale value can be read, and a stale 'click' would cause instant, not suppress it.

Failure scenario: A maintainer reading contextMenuOpenInstantTypeRef != null reasonably "fixes" it to .current != null, which makes isContextMenuOpen false for every pointer-driven open and hands control straight back to the detail === 0 heuristic — silently reverting this PR.

Fix: Drop the temp and the null check:

const isContextMenuOpen =
  nextOpen && reason === REASONS.triggerPress && parent.type === 'context-menu';
// ...
if (isContextMenuOpen) {
  popupOpenState.instantType = parent.context.openInstantTypeRef.current;
}

and reword the comment to state the actual invariant (or keep the reset with a comment saying it is purely defensive against a canceled open).

2. ℹ️ lastPointerTypeRef stores more than it needs, and duplicates the store's openMethod

Location: packages/react/src/context-menu/trigger/ContextMenuTrigger.tsx:67

const lastPointerTypeRef = React.useRef<InteractionType>('');

The only question ever asked of this ref is "was a pointer gesture the last thing we saw?". Typing it as InteractionType imports a type whose 'keyboard' member is never produced here, requires event.pointerType as InteractionType at line 156, and overloads '' to mean both "keyboard" and "nothing yet" (the root of finding Bugs #1). A React.useRef(false) named pointerGestureSeenRef is smaller and says exactly what it means.

Separately: MenuRoot already tracks this via useOpenInteractionType (MenuRoot.tsx:185), but openMethod is permanently null for Context Menu because ContextMenuTrigger never consumes store.state.triggerProps. That also leaves openMethod === 'touch' in MenuPositioner.tsx:272 and openInteractionType={openMethod} in MenuPopup.tsx:125 inert for context menus. Wiring the trigger into the existing mechanism instead of adding a parallel one would fix all three — larger than this PR, but worth a follow-up rather than cementing a second tracker.

Failure scenario: Two independent pointer-type trackers on the same component drift apart; a later fix to openMethod doesn't reach data-instant, and vice versa.

Fix: Narrow the ref to a boolean here, and file a follow-up to feed store.state.triggerProps (or a Context Menu-specific setOpenMethod call) from ContextMenuTrigger.

Verdict

Approve after nits — the classification logic is correct for mouse and keyboard, but the touch path still depends on a pointerdown the trigger may never receive, and one keyboard test asserts nothing about the mechanism it names.


🤖 Review generated with Claude Code · Opus 5 (High) · medium review depth · 29 turns · 6m30s · $1.75 · run

@sai6855
sai6855 marked this pull request as ready for review September 10, 2026 10:28
@sai6855
sai6855 requested a review from atomiks as a code owner September 10, 2026 10:28
Copilot AI lite review requested due to automatic review settings September 10, 2026 10:28

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Two moderate gesture-tracking issues remain unresolved in ContextMenuTrigger.

Pull request overview

Fixes incorrect data-instant="click" behavior for pointer- and touch-driven context-menu openings.

Changes:

  • Tracks context-menu gesture metadata.
  • Updates MenuRoot to use the recorded gesture.
  • Adds interaction-specific regression tests.
File summaries
File Summary
packages/react/src/menu/root/MenuRoot.tsx Consumes context-menu gesture metadata when setting instantType.
packages/react/src/context-menu/trigger/ContextMenuTrigger.tsx Classifies pointer, touch, and keyboard context-menu gestures.
packages/react/src/context-menu/trigger/ContextMenuTrigger.test.tsx Tests long-press behavior.
packages/react/src/context-menu/root/ContextMenuRootContext.ts Exposes gesture metadata through context.
packages/react/src/context-menu/root/ContextMenuRoot.tsx Initializes and provides the metadata ref.
packages/react/src/context-menu/root/ContextMenuRoot.test.tsx Tests gesture classification across platforms.
Review details

Suppressed comments (2)

packages/react/src/context-menu/trigger/ContextMenuTrigger.tsx:242

  • The trigger also supports the TouchEvent path, but lastPointerTypeRef is only populated by onPointerDownCapture. On a browser that delivers touchstart/native contextmenu without Pointer Events, the native menu event can arrive before the 500 ms timer, leaving this ref empty and causing isKeyboardContextMenu to classify the touch open as keyboard (data-instant="click"). Record the touch gesture when a single touch starts so the native-contextmenu race is covered on that path too.
        onPointerDownCapture: handlePointerDown,
        onKeyDownCapture: handleKeyDown,

packages/react/src/context-menu/trigger/ContextMenuTrigger.tsx:110

  • lastPointerTypeRef is never consumed or reset after this classification. After any pointer-driven context menu, a later keyboard or assistive-technology contextmenu that does not dispatch a keydown will reuse the stale 'mouse'/'touch' value and incorrectly omit data-instant="click". Clear the recorded gesture after computing the activation type (and cover this sequence with a regression test).
    handleLongPress(
      event.clientX,
      event.clientY,
      event.nativeEvent,
      isKeyboardContextMenu(event.nativeEvent, lastPointerTypeRef.current),
  • Files reviewed: 6/6 changed files
  • Comments generated: 0
  • Review effort level: Lite

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@github-actions github-actions Bot added the PR: out-of-date The pull request has merge conflicts and can't be merged. label Sep 21, 2026
@github-actions

Copy link
Copy Markdown

This pull request has been inactive for 30 days. Please remove the stale label or leave a comment to keep it open. Otherwise, it will be closed in 15 days.

@github-actions github-actions Bot added the stale Inactive for 7 days (issues) or 30 days (PRs); closed after 5 or 15 more days if no update. label Oct 26, 2026
@sai6855 sai6855 closed this Nov 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

component: context menu Changes related to the context menu component. PR: out-of-date The pull request has merge conflicts and can't be merged. stale Inactive for 7 days (issues) or 30 days (PRs); closed after 5 or 15 more days if no update. type: bug It doesn't behave as expected.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[context menu] Right-click open is marked as instant

2 participants