An open source design system that's fully customizable and agent ready
TypeScript
fix(ContextMenu): position the menu relative to context for scroll-follow + auto-flip (#3866)
Cindy Zhang7019c3cbbec8
diff --git a/.changeset/contextmenu-context-anchor.md b/.changeset/contextmenu-context-anchor.mdnew file mode 100644index 0000000000..68c71964fb--- /dev/null+++ b/.changeset/contextmenu-context-anchor.md@@ -0,0 +1,6 @@+---+'@astryxdesign/core': patch+---++[fix] ContextMenu now anchors the menu to the right-click point relative to its context, so it follows the content on scroll and auto-flips at viewport edges instead of staying at a fixed screen position (#3465).+@cixzhangdiff --git a/packages/core/src/ContextMenu/ContextMenu.test.tsx b/packages/core/src/ContextMenu/ContextMenu.test.tsxindex 4553bfd7c7..aa3d78788d 100644--- a/packages/core/src/ContextMenu/ContextMenu.test.tsx+++ b/packages/core/src/ContextMenu/ContextMenu.test.tsx@@ -464,4 +464,76 @@ describe('ContextMenu compound mode', () => {).toBeInTheDocument();expect(screen.getByRole('separator', {hidden: true})).toBeInTheDocument();});++ describe('cursor anchor positioning (#3465)', () => {+ // The menu is anchored to a zero-size element placed at the cursor point+ // *inside the trigger*, so it is positioned relative to the trigger's+ // context (scroll-follow + auto-flip) rather than the viewport.+ function getCursorAnchor(trigger: HTMLElement): HTMLElement {+ const anchor = trigger.querySelector<HTMLElement>('[aria-hidden="true"]');+ if (!anchor) {+ throw new Error('cursor anchor not found');+ }+ return anchor;+ }++ it('renders a zero-size cursor anchor inside the trigger', () => {+ render(+ <ContextMenu items={[{label: 'Item 1'}]} data-testid="ctx">+ <div>Right-click me</div>+ </ContextMenu>,+ );+ const anchor = getCursorAnchor(screen.getByTestId('ctx'));+ expect(anchor.tagName).toBe('SPAN');+ // Carries an anchor-name so the menu can be anchored to it via CSS+ // anchor positioning (context mode), not fixed viewport coordinates.+ expect(anchor.style.anchorName).toMatch(/^--astryx-layer-/);+ });++ it('places the cursor anchor at the pointer position relative to the trigger', () => {+ render(+ <ContextMenu items={[{label: 'Item 1'}]} data-testid="ctx">+ <div>Right-click me</div>+ </ContextMenu>,+ );+ const trigger = screen.getByTestId('ctx');+ trigger.getBoundingClientRect = () =>+ ({+ left: 100,+ top: 50,+ right: 300,+ bottom: 150,+ width: 200,+ height: 100,+ }) as DOMRect;+ // Pointer at viewport (170, 90) -> local trigger offset (70, 40).+ fireEvent.contextMenu(trigger, {clientX: 170, clientY: 90, detail: 1});+ const anchor = getCursorAnchor(trigger);+ expect(anchor.style.left).toBe('70px');+ expect(anchor.style.top).toBe('40px');+ });++ it('anchors a keyboard-invoked menu to the trigger bottom-left', () => {+ render(+ <ContextMenu items={[{label: 'Item 1'}]} data-testid="ctx">+ <div>Right-click me</div>+ </ContextMenu>,+ );+ const trigger = screen.getByTestId('ctx');+ trigger.getBoundingClientRect = () =>+ ({+ left: 40,+ top: 10,+ right: 100,+ bottom: 30,+ width: 60,+ height: 20,+ }) as DOMRect;+ // Keyboard-initiated contextmenu: coords (0,0), detail 0 -> local (0, height).+ fireEvent.contextMenu(trigger, {clientX: 0, clientY: 0, detail: 0});+ const anchor = getCursorAnchor(trigger);+ expect(anchor.style.left).toBe('0px');+ expect(anchor.style.top).toBe('20px');+ });+ });});diff --git a/packages/core/src/ContextMenu/ContextMenu.tsx b/packages/core/src/ContextMenu/ContextMenu.tsxindex f917b7d8c6..94e5d38228 100644--- a/packages/core/src/ContextMenu/ContextMenu.tsx+++ b/packages/core/src/ContextMenu/ContextMenu.tsx@@ -3,11 +3,16 @@/*** @file ContextMenu.tsx- * @input Uses React, StyleX, useLayer (fixed mode), useListFocus+ * @input Uses React, StyleX, useLayer (context mode), useListFocus* @output Exports ContextMenu component* @position Core implementation; consumed by index.ts*- * Right-click context menu positioned at cursor coordinates.+ * Right-click context menu positioned at the cursor. The cursor point is+ * captured as an offset *inside the trigger* and materialized as a zero-size+ * anchor element, so the menu is positioned relative to the trigger's context+ * (via CSS anchor positioning) rather than the viewport. It therefore follows+ * the content on scroll and auto-flips at viewport edges, while still appearing+ * under the cursor.* Reuses DropdownMenu item rendering and keyboard navigation.** Supports two content modes with a single keyboard/focus path:@@ -53,7 +58,7 @@ import {easeVars,shadowVars,} from '../theme/tokens.stylex';-import {mergeProps} from '../utils';+import {mergeProps, mergeRefs} from '../utils';import type {BaseProps} from '../BaseProps';import type {StyleXStyles} from '../theme/types';import {themeProps} from '../utils/themeProps';@@ -67,9 +72,23 @@ import type {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',},+ // Zero-size 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.+ cursorAnchor: {+ position: 'absolute',+ width: 0,+ height: 0,+ pointerEvents: 'none',+ },menu: {boxSizing: 'border-box',display: 'flex',@@ -201,7 +220,13 @@ export function ContextMenu({const menuContent = 'menuContent' in props ? props.menuContent : undefined;const menuId = useId();+ // Cursor point in the trigger's local coordinate space (offset from the+ // trigger's top-left, in-flow). Stored here and written to the zero-size+ // 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});+ const cursorAnchorRef = useRef<HTMLSpanElement>(null);+ const triggerRef = useRef<HTMLDivElement>(null);// Element focused before the menu opened, restored when it closes so focus// does not fall to <body> after Escape or outside-click dismissal.const triggerFocusRef = useRef<HTMLElement | null>(null);@@ -209,7 +234,7 @@ export function ContextMenu({const [isOpen, setIsOpen] = useState(false);const layer = useLayer({- mode: 'fixed',+ mode: 'context',onHide: useCallback(() => {setIsOpen(false);onOpenChange?.(false);@@ -327,34 +352,53 @@ export function ContextMenu({[listNavKeyDown, typeahead],);+ // Place the zero-size cursor anchor at a point in the trigger's local+ // coordinate space and open the menu. Positioning the anchor inside the+ // trigger (rather than storing viewport coordinates on the menu itself) is+ // what makes the menu context-relative: it scrolls with the content and the+ // browser auto-flips it against the viewport edges via CSS anchor positioning.+ const openAtLocalPoint = useCallback(+ (localX: number, localY: number, focusEl: HTMLElement | null) => {+ positionRef.current = {x: localX, y: localY};+ const anchorEl = cursorAnchorRef.current;+ if (anchorEl) {+ anchorEl.style.left = `${localX}px`;+ anchorEl.style.top = `${localY}px`;+ }+ // Remember the element focused before opening so we can restore it on+ // close (Escape or outside-click), instead of dropping focus to <body>.+ triggerFocusRef.current =+ document.activeElement instanceof HTMLElement+ ? document.activeElement+ : focusEl;+ layer.show();+ requestAnimationFrame(() => focusFirst());+ },+ [layer, focusFirst],+ );+const handleContextMenu = useCallback((e: React.MouseEvent) => {if (isDisabled) {return;}e.preventDefault();+ const trigger = triggerRef.current;+ const rect = trigger?.getBoundingClientRect();// 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 box instead, so the- // menu is reachable without a pointer (menus-8).+ // 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;- if (isKeyboardInvoked && e.currentTarget instanceof HTMLElement) {- const rect = e.currentTarget.getBoundingClientRect();- positionRef.current = {x: rect.left, y: rect.bottom};- } else {- positionRef.current = {x: e.clientX, y: e.clientY};- }- // Remember the element focused before opening so we can restore it on- // close (Escape or outside-click), instead of dropping focus to <body>.- triggerFocusRef.current =- document.activeElement instanceof HTMLElement- ? document.activeElement- : (e.currentTarget as HTMLElement);- layer.show();- requestAnimationFrame(() => focusFirst());+ // Convert the viewport cursor point into the trigger's local space so+ // the anchor lives inside the (scrollable) trigger context.+ const localX = isKeyboardInvoked || !rect ? 0 : e.clientX - rect.left;+ const localY =+ isKeyboardInvoked || !rect ? (rect?.height ?? 0) : e.clientY - rect.top;+ openAtLocalPoint(localX, localY, e.currentTarget as HTMLElement);},- [isDisabled, layer, focusFirst],+ [isDisabled, openAtLocalPoint],);// Touch long-press invocation (menus-8). iOS Safari never synthesizes a@@ -365,11 +409,14 @@ export function ContextMenu({disabled: isDisabled,onLongPress: useCallback((point: {x: number; y: number}) => {- positionRef.current = {x: point.x, y: point.y};- layer.show();- requestAnimationFrame(() => focusFirst());+ const rect = triggerRef.current?.getBoundingClientRect();+ openAtLocalPoint(+ rect ? point.x - rect.left : point.x,+ rect ? point.y - rect.top : point.y,+ triggerRef.current,+ );},- [layer, focusFirst],+ [openAtLocalPoint],),});@@ -388,7 +435,7 @@ export function ContextMenu({return (<><div- ref={ref}+ ref={mergeRefs(ref, triggerRef)}onContextMenu={handleContextMenu}{...longPressHandlers}data-testid={testId}@@ -401,6 +448,16 @@ export function ContextMenu({: []),)}>{children}+ <span+ ref={mergeRefs(cursorAnchorRef, layer.ref)}+ aria-hidden="true"+ {...mergeProps(stylex.props(styles.cursorAnchor), {+ style: {+ left: `${positionRef.current.x}px`,+ top: `${positionRef.current.y}px`,+ },+ })}+ /></div>{layer.render(@@ -422,8 +479,8 @@ export function ContextMenu({</DropdownMenuContext></div>,{- x: positionRef.current.x,- y: positionRef.current.y,+ placement: 'below',+ alignment: 'start',xstyle: [popoverXstyle, layerAnimations.below],},)}