@delacour/react-native-ui 0.1.0-alpha.20261009010458 → 0.1.0-alpha.20261009010834

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@delacour/react-native-ui",
3
- "version": "0.1.0-alpha.20261009010458",
3
+ "version": "0.1.0-alpha.20261009010834",
4
4
  "description": "React Native UI components — Uniwind, Reanimated, Gesture Handler",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -45,6 +45,7 @@
45
45
  "./checkbox": "./src/components/checkbox/index.ts",
46
46
  "./chip": "./src/components/chip/index.ts",
47
47
  "./collapsible": "./src/components/collapsible/index.ts",
48
+ "./context-menu": "./src/components/context-menu/index.ts",
48
49
  "./dialog": "./src/components/dialog/index.ts",
49
50
  "./drawer": "./src/components/drawer/index.ts",
50
51
  "./empty-state": "./src/components/empty-state/index.ts",
@@ -111,8 +112,8 @@
111
112
  },
112
113
  "peerDependencies": {
113
114
  "@central-icons-react-native/round-outlined-radius-1-stroke-1.5": "^1.1",
114
- "@delacour/react-native-bottom-sheet": "0.1.0-alpha.20261009010458",
115
- "@delacour/react-native-charts": "0.1.0-alpha.20261009010458",
115
+ "@delacour/react-native-bottom-sheet": "0.1.0-alpha.20261009010834",
116
+ "@delacour/react-native-charts": "0.1.0-alpha.20261009010834",
116
117
  "@legendapp/list": ">=3.3",
117
118
  "expo-linear-gradient": ">=15",
118
119
  "expo-router": ">=57",
@@ -0,0 +1,103 @@
1
+ # ContextMenu
2
+
3
+ The actions that belong to a piece of **content** — a message bubble, a card, a
4
+ row — reached by holding the content itself. A [Menu](../menu/AGENTS.md) hangs
5
+ off a control that exists to be opened; a context menu has no such control,
6
+ because the target is the content. Compound root plus `ContextMenu.Trigger`,
7
+ `ContextMenu.Content`, `ContextMenu.Preview` and `ContextMenu.Item`, with Menu's
8
+ `Label`, `Separator`, `CheckboxItem`, `RadioGroup`, `RadioItem`, `Sub`,
9
+ `SubTrigger`, `SubContent` and `Background` re-exported outright.
10
+
11
+ `import { ContextMenu } from "@delacour/react-native-ui/context-menu";`
12
+
13
+ ## Files
14
+
15
+ | File | What it holds |
16
+ | --- | --- |
17
+ | `index.ts` | → `@delacour/react-native-ui/context-menu` |
18
+ | `context-menu.tsx` | Root — Menu's `useMenuRootValue` into `MenuRootProvider`, plus this folder's provider; the `Object.assign` |
19
+ | `context-menu-trigger.tsx` | `ContextMenu.Trigger` — the wrapper, the hold-vs-tap gesture, the measurement, the accessibility actions |
20
+ | `context-menu-content.tsx` | `ContextMenu.Content` — `Menu.Content` with the context defaults; lifts a `Preview` out by type |
21
+ | `context-menu-preview.tsx` | `ContextMenu.Preview` — the lifted copy at the trigger's window rect |
22
+ | `context-menu-item.tsx` | `ContextMenu.Item` — `Menu.Item` with a trailing icon and a taller row |
23
+ | `context-menu.context.tsx` | The invocation, the registered trigger children, `useContextMenuTarget` |
24
+ | `context-menu.variants.ts` | The slotted `tv()`, the constants and the pure resolvers — no RN imports |
25
+ | `context-menu.variants.test.ts` | Anchor, hold, accessibility, the content defaults against Menu's resolvers, tokens |
26
+
27
+ ## Design
28
+
29
+ - **The rows and the panel are Menu's, imported from its leaves.** `Menu.Content`,
30
+ `Menu.Item` and the other rows come from `../menu/<leaf>`, never from `../menu`
31
+ — the folder index would pull Menu's root and could close a cycle (rule 3).
32
+ A restyled copy would be a second press fill and a second placement that drift.
33
+ - **One recogniser decides up front.** `Gesture.Exclusive(longPress, tap)`, with
34
+ `LongPress().minDuration(delay).maxDistance(slop)`: the tap waits for the hold
35
+ to fail, so a hold that opens the menu never also fires `onPress`. That is why
36
+ `onPress` is the trigger's prop — a pressable inside it would race the hold
37
+ instead of being arbitrated against it. Without `onPress` the tap is not
38
+ installed at all, so an inner control keeps its own taps.
39
+ - **A scroll that starts on the trigger still scrolls.** The hold fails once the
40
+ finger drifts past `slop` (12pt), and the scroller takes the touch. The tap's
41
+ `maxDuration` is at least the hold's delay, so a long `delay` never leaves a
42
+ dead window where neither fires.
43
+ - **The delay has a 150ms floor.** `resolveHoldConfig` clamps it: anything
44
+ shorter is a tap, and a menu that opens on a tap swallows `onPress`.
45
+ - **The content is not cloned or altered**, and need not be pressable. The
46
+ wrapper is a plain `View` that lays out like one — it does not shrink to its
47
+ child — with `collapsable={false}` so Android keeps a node to measure.
48
+ - **`point` anchors at the finger, `target` at the wrapper.** The hold's
49
+ `absoluteX/absoluteY` become a zero-size rect, which Menu's
50
+ `resolveMenuPlacement` handles with no special case; `target` is the wrapper's
51
+ `measureInWindow`. Both go to Menu through its reuse contract: `open(rect)`
52
+ on the shared `MenuRootProvider`, and `anchor` on `Menu.Content`.
53
+ - **A preview, or a screen reader, forces the target.** With a preview the panel
54
+ must open beside the lifted copy, never across it; a screen-reader open has no
55
+ pointer coordinate. `resolveContextAnchor` is the one place this is decided.
56
+ - **A stale invocation is detected by identity.** The trigger records the rect it
57
+ handed to `open()`; Menu keeps that object as its anchor. A parent flipping
58
+ `isOpen` makes Menu measure the trigger itself, the identities differ, and
59
+ Content and Preview fall back to Menu's measured rect rather than last visit's.
60
+ - **The preview is drawn through Menu's `backdrop`.** A `Modal` covers everything,
61
+ so a copy above the scrim has to live inside it. `ContextMenu.Preview` is lifted
62
+ out of the rows by type and handed to `Menu.Content`'s `backdrop`: over the
63
+ scrim, behind the panel, fading with both, taking no touches. That prop is the
64
+ one change this component needed from Menu.
65
+ - **The preview is a second instance.** It renders the trigger's children again
66
+ (registered in context from an effect), so their local state starts fresh;
67
+ pass `ContextMenu.Preview` children of its own when that matters. It grows
68
+ 1 → 1.03 over Menu's 160ms enter and casts `shadow-lg`. The 8pt offset clears
69
+ that growth for any target under ~530pt tall, and a test pins the arithmetic.
70
+ Under reduced motion it does not grow — it still appears.
71
+ - **The scrim is on by default.** `hasScrim` is Menu's; ContextMenu defaults it
72
+ to `true` — the content behind is not the menu's control, and the dim says
73
+ where the action now is. A tap on it (or the preview) closes; Android back
74
+ closes through the `Modal`.
75
+ - **Defaults differ from Menu's**: below, start-aligned, 8pt offset, 280 wide at
76
+ least — a point anchor has no width to inherit, and Menu's 200 floor is too
77
+ narrow for a trailing icon and a label. `CONTEXT_MENU_CONTENT_DEFAULTS`.
78
+ - **Rows are taller and icons trail.** `ContextMenu.Item` is `Menu.Item` with
79
+ `iconPlacement="trailing"` and `min-h-12` merged over the row's `min-h-11`.
80
+ The other row kinds are re-exported unchanged.
81
+ - **The haptic fires at hold acceptance**, in the long-press `onStart` on the UI
82
+ thread, before the open crosses to JS. The root's `haptic` is Menu's: played
83
+ when a row is chosen. Both are off by default.
84
+
85
+ ## Accessibility
86
+
87
+ - The trigger is **one** element (`accessible`): `accessibilityRole="button"` with
88
+ `onPress`, `"none"` without, `accessibilityState={{ disabled, expanded }}`.
89
+ - `accessibilityActions`: `activate` and `longpress` labelled "Show menu".
90
+ `activate` runs `onPress`, or opens when there is none; `longpress` opens
91
+ against the target rect. `resolveContextMenuAccessibility` holds the matrix.
92
+ - Disabled: announced, and neither the gesture nor either action does anything.
93
+ - The panel is Menu's: `menu` / `menuitem` roles and modal containment. The
94
+ preview is hidden from the accessibility tree.
95
+
96
+ ## Out of scope
97
+
98
+ - **`presentation="bottom-sheet"`** — the same reason as Menu: it would force the
99
+ optional sheet engine on every consumer.
100
+ - **Hardware keyboard** — Shift+F10 and the Context Menu key.
101
+ - **Gesture Handler's absolute coordinates** are relative to the root view; in an
102
+ app whose root is not the window (a modal screen with an offset), `point` mode
103
+ can land a few points off. Use `anchor="target"` there.
@@ -0,0 +1,64 @@
1
+ import { Children, isValidElement, type ReactElement, type ReactNode, useMemo } from "react";
2
+ import { MenuContent, type MenuContentProps } from "../menu/menu-content";
3
+ import { useContextMenuTarget } from "./context-menu.context";
4
+ import { CONTEXT_MENU_CONTENT_DEFAULTS } from "./context-menu.variants";
5
+ import { ContextMenuPreview } from "./context-menu-preview";
6
+
7
+ export type ContextMenuContentProps = Omit<MenuContentProps, "hasScrim" | "anchor" | "backdrop"> & {
8
+ /** Tint the screen behind the panel. Default `true`. */
9
+ hasScrim?: boolean;
10
+ };
11
+
12
+ /**
13
+ * The panel: `Menu.Content` itself, with the defaults a held menu wants —
14
+ * below, start-aligned, 8pt from the anchor, at least 280 wide, over a scrim.
15
+ *
16
+ * The anchor is this visit's: a zero-size point at the finger, or the trigger's
17
+ * rect — forced to the rect when a `ContextMenu.Preview` is among the children.
18
+ * The preview is lifted out by type and drawn through Menu's `backdrop`, over
19
+ * the scrim and behind the panel.
20
+ */
21
+ export function ContextMenuContent({
22
+ children,
23
+ placement = CONTEXT_MENU_CONTENT_DEFAULTS.placement,
24
+ align = CONTEXT_MENU_CONTENT_DEFAULTS.align,
25
+ offset = CONTEXT_MENU_CONTENT_DEFAULTS.offset,
26
+ minWidth = CONTEXT_MENU_CONTENT_DEFAULTS.minWidth,
27
+ hasScrim = CONTEXT_MENU_CONTENT_DEFAULTS.hasScrim,
28
+ ...props
29
+ }: ContextMenuContentProps): ReactElement {
30
+ const { preview, rows } = useMemo(() => splitPreview(children), [children]);
31
+ const { anchor } = useContextMenuTarget("ContextMenu.Content", preview !== null);
32
+
33
+ return (
34
+ <MenuContent
35
+ align={align}
36
+ anchor={anchor ?? undefined}
37
+ backdrop={preview}
38
+ hasScrim={hasScrim}
39
+ minWidth={minWidth}
40
+ offset={offset}
41
+ placement={placement}
42
+ {...props}
43
+ >
44
+ {rows}
45
+ </MenuContent>
46
+ );
47
+ }
48
+ ContextMenuContent.displayName = "DelacourUI.ContextMenu.Content";
49
+
50
+ /** Lifts a `ContextMenu.Preview` out of the rows, so it is drawn behind the panel instead of in it. */
51
+ function splitPreview(children: ReactNode): { preview: ReactElement | null; rows: ReactNode[] } {
52
+ let preview: ReactElement | null = null;
53
+ const rows: ReactNode[] = [];
54
+
55
+ for (const child of Children.toArray(children)) {
56
+ if (isValidElement(child) && child.type === ContextMenuPreview) {
57
+ preview = child;
58
+ continue;
59
+ }
60
+ rows.push(child);
61
+ }
62
+
63
+ return { preview, rows };
64
+ }
@@ -0,0 +1,22 @@
1
+ import type { ReactElement } from "react";
2
+ import type { MenuItemProps } from "../menu/menu.types";
3
+ import { MenuItem } from "../menu/menu-item";
4
+ import { contextMenuVariants } from "./context-menu.variants";
5
+
6
+ export type ContextMenuItemProps = MenuItemProps;
7
+
8
+ /**
9
+ * A verb: `Menu.Item` itself, with its icon at the trailing edge by default
10
+ * and a taller row. The same row, so the two menus cannot drift.
11
+ *
12
+ * @example
13
+ * <ContextMenu.Item icon={IconShare} onSelect={share}>Share</ContextMenu.Item>
14
+ */
15
+ export function ContextMenuItem({
16
+ className,
17
+ iconPlacement = "trailing",
18
+ ...props
19
+ }: ContextMenuItemProps): ReactElement {
20
+ return <MenuItem className={contextMenuVariants().item({ className })} iconPlacement={iconPlacement} {...props} />;
21
+ }
22
+ ContextMenuItem.displayName = "DelacourUI.ContextMenu.Item";
@@ -0,0 +1,60 @@
1
+ import { type ReactElement, type ReactNode, useEffect } from "react";
2
+ import type { ViewProps } from "react-native";
3
+ import Animated, { useAnimatedStyle, useReducedMotion, useSharedValue, withTiming } from "react-native-reanimated";
4
+ import { useContextMenuPart, useContextMenuTarget } from "./context-menu.context";
5
+ import { CONTEXT_MENU_PREVIEW_MS, CONTEXT_MENU_PREVIEW_SCALE, contextMenuVariants } from "./context-menu.variants";
6
+
7
+ export type ContextMenuPreviewProps = Omit<ViewProps, "children"> & {
8
+ /** What to lift. Default: the trigger's own children, rendered again. */
9
+ children?: ReactNode;
10
+ className?: string;
11
+ };
12
+
13
+ /**
14
+ * The held content, lifted over the scrim while the menu is open.
15
+ *
16
+ * Placed among `ContextMenu.Content`'s rows, and lifted out of them by type: it
17
+ * is drawn through Menu's `backdrop`, absolutely at the trigger's measured
18
+ * window rect, grows 1 → 1.03 and casts a shadow. It takes no touches — a tap
19
+ * on it is an outside tap.
20
+ *
21
+ * It renders the trigger's children **again**, as a second instance, so any
22
+ * local state inside them starts fresh. Pass children of your own when that
23
+ * matters. With a preview present, the panel anchors to the trigger's rect
24
+ * rather than the press point, so it opens beside the copy, never across it.
25
+ *
26
+ * Under reduced motion it does not grow; it still appears, with the scrim.
27
+ */
28
+ export function ContextMenuPreview({
29
+ children,
30
+ className,
31
+ style,
32
+ ...props
33
+ }: ContextMenuPreviewProps): ReactElement | null {
34
+ const { content } = useContextMenuPart("ContextMenu.Preview");
35
+ const { targetRect } = useContextMenuTarget("ContextMenu.Preview", true);
36
+ const isReducedMotion = useReducedMotion();
37
+
38
+ const lift = useSharedValue(1);
39
+ useEffect(() => {
40
+ if (isReducedMotion) return;
41
+ lift.value = withTiming(CONTEXT_MENU_PREVIEW_SCALE, { duration: CONTEXT_MENU_PREVIEW_MS });
42
+ }, [isReducedMotion, lift]);
43
+ const liftStyle = useAnimatedStyle(() => ({ transform: [{ scale: lift.value }] }));
44
+
45
+ if (!targetRect) return null;
46
+
47
+ const frame = { height: targetRect.height, left: targetRect.x, top: targetRect.y, width: targetRect.width };
48
+
49
+ return (
50
+ <Animated.View
51
+ className={contextMenuVariants().preview({ className })}
52
+ pointerEvents="none"
53
+ style={[frame, liftStyle, style]}
54
+ {...props}
55
+ >
56
+ {children ?? content}
57
+ </Animated.View>
58
+ );
59
+ }
60
+ ContextMenuPreview.displayName = "DelacourUI.ContextMenu.Preview";
@@ -0,0 +1,160 @@
1
+ import { type ReactElement, type ReactNode, useCallback, useEffect, useMemo, useRef } from "react";
2
+ import { type AccessibilityActionEvent, View, type ViewProps } from "react-native";
3
+ import { Gesture, GestureDetector } from "react-native-gesture-handler";
4
+ import { scheduleOnRN } from "react-native-worklets";
5
+ import { type MenuMeasurable, useMenuPart } from "../menu/menu.context";
6
+ import { type HapticFeedback, playHaptic } from "../pressable/pressable";
7
+ import { useContextMenuPart } from "./context-menu.context";
8
+ import {
9
+ CONTEXT_MENU_ACCESSIBILITY_ACTIONS,
10
+ type ContextMenuAnchor,
11
+ type ContextMenuInvoker,
12
+ type ContextMenuPoint,
13
+ contextMenuVariants,
14
+ resolveContextAnchor,
15
+ resolveContextMenuAccessibility,
16
+ resolveHoldConfig,
17
+ } from "./context-menu.variants";
18
+
19
+ export type ContextMenuTriggerProps = Omit<ViewProps, "children"> & {
20
+ /** The content that is held. Not cloned or altered, and it need not be pressable. */
21
+ children: ReactNode;
22
+ /** Lays out like a `View`; the wrapper does not shrink to its child. */
23
+ className?: string;
24
+ /** Open at the finger (`point`, default) or against the whole trigger (`target`). */
25
+ anchor?: ContextMenuAnchor;
26
+ /** How long the hold lasts before it opens, in ms. Default 350, at least 150. */
27
+ delay?: number;
28
+ /** How far the finger may drift during the hold, in pt. Default 12. */
29
+ slop?: number;
30
+ /** A short press. Arbitrated against the hold, so the two never both fire. */
31
+ onPress?: () => void;
32
+ /** Played the moment the hold is accepted. Off by default. */
33
+ haptic?: false | HapticFeedback;
34
+ /** Neither the hold nor `onPress` fires, and the trigger announces disabled. */
35
+ isDisabled?: boolean;
36
+ };
37
+
38
+ /**
39
+ * The content that is held: a message bubble, a card, a row.
40
+ *
41
+ * **One recogniser decides up front.** `Gesture.Exclusive(longPress, tap)`: the
42
+ * tap waits for the hold to fail, so a hold that opens the menu never also
43
+ * counts as a tap. That is why `onPress` belongs here, on the trigger, and not
44
+ * on a pressable inside it — an inner press would race the hold instead.
45
+ *
46
+ * **A scroll that starts here still scrolls.** The hold fails once the finger
47
+ * drifts past `slop`, and the scroller takes the touch.
48
+ *
49
+ * The haptic plays on the UI thread in the hold's `onStart`; the open crosses
50
+ * to JS, measures the wrapper with `measureInWindow`, and anchors the panel at
51
+ * the press point or against that rect.
52
+ *
53
+ * For a screen reader it is one element with two actions: `activate` runs
54
+ * `onPress` (or opens, without one) and `longpress`, "Show menu", opens against
55
+ * the trigger — there is no pointer coordinate to open at.
56
+ */
57
+ export function ContextMenuTrigger({
58
+ children,
59
+ className,
60
+ anchor = "point",
61
+ delay,
62
+ slop,
63
+ onPress,
64
+ haptic = false,
65
+ isDisabled = false,
66
+ ...props
67
+ }: ContextMenuTriggerProps): ReactElement {
68
+ const { isOpen, open, triggerRef } = useMenuPart("ContextMenu.Trigger");
69
+ const { invoke, registerContent } = useContextMenuPart("ContextMenu.Trigger");
70
+ const hold = resolveHoldConfig({ delay, slop });
71
+ const hasPress = onPress !== undefined;
72
+ const a11y = resolveContextMenuAccessibility({ hasPress, isDisabled, isOpen });
73
+
74
+ useEffect(() => {
75
+ registerContent(children);
76
+ }, [children, registerContent]);
77
+
78
+ const nodeRef = useRef<View | null>(null);
79
+ const setNode = useCallback(
80
+ (node: View | null) => {
81
+ nodeRef.current = node;
82
+ triggerRef.current = node as MenuMeasurable | null;
83
+ },
84
+ [triggerRef]
85
+ );
86
+
87
+ const openFrom = useCallback(
88
+ (invokedBy: ContextMenuInvoker, point: ContextMenuPoint | null) => {
89
+ const node = nodeRef.current;
90
+ if (!node) return;
91
+ node.measureInWindow((x, y, width, height) => {
92
+ const targetRect = { height, width, x, y };
93
+ const opened = resolveContextAnchor({ hasPreview: false, invokedBy, mode: anchor, point, targetRect });
94
+ invoke({ invokedBy, mode: anchor, opened, point, targetRect });
95
+ open(opened);
96
+ });
97
+ },
98
+ [anchor, invoke, open]
99
+ );
100
+
101
+ const openAtPoint = useCallback((x: number, y: number) => openFrom("pointer", { x, y }), [openFrom]);
102
+
103
+ const pressRef = useRef(onPress);
104
+ pressRef.current = onPress;
105
+ const handlePress = useCallback(() => pressRef.current?.(), []);
106
+
107
+ const gesture = useMemo(() => {
108
+ const longPress = Gesture.LongPress()
109
+ .enabled(!isDisabled)
110
+ .minDuration(hold.delay)
111
+ .maxDistance(hold.slop)
112
+ .onStart((event) => {
113
+ "worklet";
114
+ if (haptic) playHaptic(haptic);
115
+ scheduleOnRN(openAtPoint, event.absoluteX, event.absoluteY);
116
+ });
117
+
118
+ if (!hasPress) return longPress;
119
+
120
+ const tap = Gesture.Tap()
121
+ .enabled(!isDisabled)
122
+ .maxDistance(hold.slop)
123
+ .maxDuration(Math.max(500, hold.delay))
124
+ .shouldCancelWhenOutside(true)
125
+ .onEnd((_event, isSuccess) => {
126
+ "worklet";
127
+ if (isSuccess) scheduleOnRN(handlePress);
128
+ });
129
+
130
+ return Gesture.Exclusive(longPress, tap);
131
+ }, [handlePress, hasPress, haptic, hold.delay, hold.slop, isDisabled, openAtPoint]);
132
+
133
+ const handleAccessibilityAction = useCallback(
134
+ (event: AccessibilityActionEvent) => {
135
+ const outcome = a11y.onAction(event.nativeEvent.actionName);
136
+ if (outcome === "press") handlePress();
137
+ else if (outcome === "open") openFrom("accessibility", null);
138
+ },
139
+ [a11y, handlePress, openFrom]
140
+ );
141
+
142
+ return (
143
+ <GestureDetector gesture={gesture}>
144
+ <View
145
+ accessibilityActions={CONTEXT_MENU_ACCESSIBILITY_ACTIONS}
146
+ accessibilityRole={a11y.role}
147
+ accessibilityState={a11y.state}
148
+ accessible
149
+ className={contextMenuVariants().trigger({ className })}
150
+ collapsable={false}
151
+ onAccessibilityAction={handleAccessibilityAction}
152
+ ref={setNode}
153
+ {...props}
154
+ >
155
+ {children}
156
+ </View>
157
+ </GestureDetector>
158
+ );
159
+ }
160
+ ContextMenuTrigger.displayName = "DelacourUI.ContextMenu.Trigger";
@@ -0,0 +1,91 @@
1
+ import { createContext, type ReactElement, type ReactNode, use, useCallback, useMemo, useState } from "react";
2
+ import { useMenuPart } from "../menu/menu.context";
3
+ import type { MenuAnchorRect } from "../menu/menu.variants";
4
+ import {
5
+ type ContextMenuAnchor,
6
+ type ContextMenuInvoker,
7
+ type ContextMenuPoint,
8
+ resolveContextAnchor,
9
+ } from "./context-menu.variants";
10
+
11
+ /** One hold (or screen-reader action) that opened the menu, as the trigger saw it. */
12
+ export type ContextMenuInvocation = {
13
+ mode: ContextMenuAnchor;
14
+ point: ContextMenuPoint | null;
15
+ targetRect: MenuAnchorRect;
16
+ invokedBy: ContextMenuInvoker;
17
+ /**
18
+ * The very rect handed to Menu's `open()`. Menu keeps it by identity, so a
19
+ * mismatch means the menu was opened some other way — a parent flipping
20
+ * `isOpen` — and this invocation is stale.
21
+ */
22
+ opened: MenuAnchorRect;
23
+ };
24
+
25
+ export type ContextMenuContextValue = {
26
+ invocation: ContextMenuInvocation | null;
27
+ invoke: (invocation: ContextMenuInvocation) => void;
28
+ /** The trigger's children, which a bare `ContextMenu.Preview` lifts. */
29
+ content: ReactNode;
30
+ registerContent: (content: ReactNode) => void;
31
+ };
32
+
33
+ const ContextMenuContext = createContext<ContextMenuContextValue | null>(null);
34
+
35
+ export function ContextMenuProvider({
36
+ value,
37
+ children,
38
+ }: {
39
+ value: ContextMenuContextValue;
40
+ children: ReactNode;
41
+ }): ReactElement {
42
+ return <ContextMenuContext value={value}>{children}</ContextMenuContext>;
43
+ }
44
+ ContextMenuProvider.displayName = "DelacourUI.ContextMenu.Provider";
45
+
46
+ /** The context-menu context, for its own parts. Throws with the part's name outside a `ContextMenu`. */
47
+ export function useContextMenuPart(part: string): ContextMenuContextValue {
48
+ const context = use(ContextMenuContext);
49
+ if (!context) throw new Error(`${part} must be used inside a <ContextMenu>.`);
50
+ return context;
51
+ }
52
+
53
+ /** The root's state: the last invocation and the trigger's registered children. */
54
+ export function useContextMenuRootValue(): ContextMenuContextValue {
55
+ const [invocation, setInvocation] = useState<ContextMenuInvocation | null>(null);
56
+ const [content, setContent] = useState<ReactNode>(null);
57
+ const invoke = useCallback((next: ContextMenuInvocation) => setInvocation(next), []);
58
+ const registerContent = useCallback((next: ReactNode) => setContent(next), []);
59
+ return useMemo(
60
+ () => ({ content, invocation, invoke, registerContent }),
61
+ [content, invocation, invoke, registerContent]
62
+ );
63
+ }
64
+
65
+ /**
66
+ * Where the panel anchors and where the lifted preview sits, for this visit.
67
+ *
68
+ * Read by both `ContextMenu.Content` and `ContextMenu.Preview`, so the two can
69
+ * never disagree. A current invocation runs through `resolveContextAnchor`;
70
+ * without one (a controlled open) both fall back to the trigger rect Menu
71
+ * measured itself.
72
+ */
73
+ export function useContextMenuTarget(
74
+ part: string,
75
+ hasPreview: boolean
76
+ ): { anchor: MenuAnchorRect | null; targetRect: MenuAnchorRect | null } {
77
+ const { anchor: menuAnchor } = useMenuPart(part);
78
+ const { invocation } = useContextMenuPart(part);
79
+ const current = invocation !== null && invocation.opened === menuAnchor ? invocation : null;
80
+ if (!current) return { anchor: menuAnchor, targetRect: menuAnchor };
81
+ return {
82
+ anchor: resolveContextAnchor({
83
+ hasPreview,
84
+ invokedBy: current.invokedBy,
85
+ mode: current.mode,
86
+ point: current.point,
87
+ targetRect: current.targetRect,
88
+ }),
89
+ targetRect: current.targetRect,
90
+ };
91
+ }
@@ -0,0 +1,90 @@
1
+ import type { ReactElement } from "react";
2
+ import type { MenuProps } from "../menu/menu";
3
+ import { MenuRootProvider, useMenuRootValue } from "../menu/menu.context";
4
+ import { MenuBackground } from "../menu/menu-background";
5
+ import { MenuCheckboxItem } from "../menu/menu-checkbox-item";
6
+ import { MenuLabel } from "../menu/menu-label";
7
+ import { MenuRadioGroup } from "../menu/menu-radio-group";
8
+ import { MenuRadioItem } from "../menu/menu-radio-item";
9
+ import { MenuSeparator } from "../menu/menu-separator";
10
+ import { MenuSub } from "../menu/menu-sub";
11
+ import { MenuSubContent } from "../menu/menu-sub-content";
12
+ import { MenuSubTrigger } from "../menu/menu-sub-trigger";
13
+ import { ContextMenuProvider, useContextMenuRootValue } from "./context-menu.context";
14
+ import { ContextMenuContent } from "./context-menu-content";
15
+ import { ContextMenuItem } from "./context-menu-item";
16
+ import { ContextMenuPreview } from "./context-menu-preview";
17
+ import { ContextMenuTrigger } from "./context-menu-trigger";
18
+
19
+ /** Menu's own root props: the open state, and the haptic played when a row is chosen. */
20
+ export type ContextMenuProps = MenuProps;
21
+
22
+ function ContextMenuRoot({ children, isOpen, defaultOpen, onOpenChange, haptic }: ContextMenuProps): ReactElement {
23
+ const menu = useMenuRootValue({ defaultOpen, haptic, isOpen, onOpenChange });
24
+ const context = useContextMenuRootValue();
25
+ return (
26
+ <MenuRootProvider value={menu}>
27
+ <ContextMenuProvider value={context}>{children}</ContextMenuProvider>
28
+ </MenuRootProvider>
29
+ );
30
+ }
31
+
32
+ /**
33
+ * The actions that belong to a piece of content — a message, a card, a row —
34
+ * reached by holding the content itself.
35
+ *
36
+ * A `Menu` hangs off a control that exists to open it; a context menu has no
37
+ * such control, because the target is the content. Hold it for 350ms and the
38
+ * panel opens at the finger (or against the whole trigger with
39
+ * `anchor="target"`); a short press runs the trigger's `onPress`, and never both.
40
+ *
41
+ * **The rows and the panel are Menu's.** `ContextMenu.Content` is
42
+ * `Menu.Content` with a scrim and wider defaults, `ContextMenu.Item` is
43
+ * `Menu.Item` with a trailing icon and a taller row, and every other row kind is
44
+ * Menu's own component, so the two entry points cannot drift.
45
+ *
46
+ * `ContextMenu.Preview`, among the rows, lifts a copy of the held content over
47
+ * the scrim, and the panel opens beside it.
48
+ *
49
+ * @example
50
+ * <ContextMenu>
51
+ * <ContextMenu.Trigger haptic="medium" onPress={openThread}>
52
+ * <Card>…</Card>
53
+ * </ContextMenu.Trigger>
54
+ * <ContextMenu.Content>
55
+ * <ContextMenu.Preview />
56
+ * <ContextMenu.Item icon={IconShare} onSelect={share}>Share</ContextMenu.Item>
57
+ * <ContextMenu.Separator />
58
+ * <ContextMenu.Item icon={IconTrashCan} variant="destructive" onSelect={remove}>Delete</ContextMenu.Item>
59
+ * </ContextMenu.Content>
60
+ * </ContextMenu>
61
+ */
62
+ export const ContextMenu = Object.assign(ContextMenuRoot, {
63
+ /** The content that is held. `onPress` is its short press, arbitrated against the hold. */
64
+ Trigger: ContextMenuTrigger,
65
+ /** The panel — `Menu.Content` over a scrim. */
66
+ Content: ContextMenuContent,
67
+ /** The held content, lifted over the scrim. Place it among the rows. */
68
+ Preview: ContextMenuPreview,
69
+ /** A verb: runs `onSelect` and closes. Icon trailing, row taller. */
70
+ Item: ContextMenuItem,
71
+ /** The panel's surface. Pass one as a `ContextMenu.Content` child to repaint it. */
72
+ Background: MenuBackground,
73
+ /** A section heading. */
74
+ Label: MenuLabel,
75
+ /** A row that toggles a setting. Stays open. */
76
+ CheckboxItem: MenuCheckboxItem,
77
+ /** Holds the value for a set of radio rows. */
78
+ RadioGroup: MenuRadioGroup,
79
+ /** One option in a radio group. Closes. */
80
+ RadioItem: MenuRadioItem,
81
+ /** A rule between groups of rows. */
82
+ Separator: MenuSeparator,
83
+ /** Nested rows that expand in place. */
84
+ Sub: MenuSub,
85
+ /** The row that expands a `ContextMenu.Sub`. */
86
+ SubTrigger: MenuSubTrigger,
87
+ /** The rows a `ContextMenu.Sub` discloses. */
88
+ SubContent: MenuSubContent,
89
+ displayName: "DelacourUI.ContextMenu",
90
+ });
@@ -0,0 +1,266 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { declaredTokens } from "../../styles/theme-tokens.test";
3
+ import { MENU_DEFAULT_MIN_WIDTH, resolveMenuPlacement, resolveMenuWidth } from "../menu/menu.variants";
4
+ import {
5
+ CONTEXT_MENU_ACCESSIBILITY_ACTIONS,
6
+ CONTEXT_MENU_CONTENT_DEFAULTS,
7
+ CONTEXT_MENU_HOLD,
8
+ CONTEXT_MENU_PREVIEW_SCALE,
9
+ contextMenuVariants,
10
+ resolveContextAnchor,
11
+ resolveContextMenuAccessibility,
12
+ resolveHoldConfig,
13
+ } from "./context-menu.variants";
14
+
15
+ const TARGET = { height: 120, width: 300, x: 24, y: 200 };
16
+ const POINT = { x: 140, y: 260 };
17
+
18
+ describe("resolveContextAnchor", () => {
19
+ test("point mode, by the finger, is a zero-size rect at the press", () => {
20
+ expect(
21
+ resolveContextAnchor({
22
+ hasPreview: false,
23
+ invokedBy: "pointer",
24
+ mode: "point",
25
+ point: POINT,
26
+ targetRect: TARGET,
27
+ })
28
+ ).toEqual({ height: 0, width: 0, x: 140, y: 260 });
29
+ });
30
+
31
+ test("target mode anchors to the measured wrapper", () => {
32
+ expect(
33
+ resolveContextAnchor({
34
+ hasPreview: false,
35
+ invokedBy: "pointer",
36
+ mode: "target",
37
+ point: POINT,
38
+ targetRect: TARGET,
39
+ })
40
+ ).toEqual(TARGET);
41
+ });
42
+
43
+ test("a preview forces the target, so the panel opens outside the lifted copy", () => {
44
+ expect(
45
+ resolveContextAnchor({
46
+ hasPreview: true,
47
+ invokedBy: "pointer",
48
+ mode: "point",
49
+ point: POINT,
50
+ targetRect: TARGET,
51
+ })
52
+ ).toEqual(TARGET);
53
+ });
54
+
55
+ test("a screen-reader open forces the target — there is no pointer coordinate", () => {
56
+ expect(
57
+ resolveContextAnchor({
58
+ hasPreview: false,
59
+ invokedBy: "accessibility",
60
+ mode: "point",
61
+ point: null,
62
+ targetRect: TARGET,
63
+ })
64
+ ).toEqual(TARGET);
65
+ });
66
+
67
+ test("point mode without a point falls back to the target", () => {
68
+ expect(
69
+ resolveContextAnchor({
70
+ hasPreview: false,
71
+ invokedBy: "pointer",
72
+ mode: "point",
73
+ point: null,
74
+ targetRect: TARGET,
75
+ })
76
+ ).toEqual(TARGET);
77
+ });
78
+
79
+ test("returns a fresh rect, never the caller's object", () => {
80
+ const result = resolveContextAnchor({
81
+ hasPreview: false,
82
+ invokedBy: "pointer",
83
+ mode: "target",
84
+ point: null,
85
+ targetRect: TARGET,
86
+ });
87
+ expect(result).not.toBe(TARGET);
88
+ });
89
+ });
90
+
91
+ describe("resolveHoldConfig", () => {
92
+ test("defaults to a 350ms hold and 12pt of drift", () => {
93
+ expect(resolveHoldConfig({})).toEqual({ delay: 350, slop: 12 });
94
+ expect(CONTEXT_MENU_HOLD).toEqual({ delay: 350, minDelay: 150, slop: 12 });
95
+ });
96
+
97
+ test("keeps values above the floors", () => {
98
+ expect(resolveHoldConfig({ delay: 600, slop: 20 })).toEqual({ delay: 600, slop: 20 });
99
+ });
100
+
101
+ test("floors the delay at 150ms, so a tap cannot open the menu", () => {
102
+ expect(resolveHoldConfig({ delay: 40 }).delay).toBe(150);
103
+ });
104
+
105
+ test("floors the slop at zero", () => {
106
+ expect(resolveHoldConfig({ slop: -5 }).slop).toBe(0);
107
+ });
108
+
109
+ test("a non-finite value takes the default", () => {
110
+ expect(resolveHoldConfig({ delay: Number.NaN, slop: Number.POSITIVE_INFINITY })).toEqual({
111
+ delay: 350,
112
+ slop: 12,
113
+ });
114
+ });
115
+ });
116
+
117
+ describe("resolveContextMenuAccessibility", () => {
118
+ test("a trigger with onPress is a button", () => {
119
+ expect(resolveContextMenuAccessibility({ hasPress: true, isDisabled: false, isOpen: false }).role).toBe("button");
120
+ });
121
+
122
+ test("a trigger without onPress claims no role", () => {
123
+ expect(resolveContextMenuAccessibility({ hasPress: false, isDisabled: false, isOpen: false }).role).toBe("none");
124
+ });
125
+
126
+ test("offers activate and a labelled long-press", () => {
127
+ expect(CONTEXT_MENU_ACCESSIBILITY_ACTIONS).toEqual([
128
+ { name: "activate" },
129
+ { label: "Show menu", name: "longpress" },
130
+ ]);
131
+ });
132
+
133
+ test("announces disabled and expanded", () => {
134
+ expect(resolveContextMenuAccessibility({ hasPress: true, isDisabled: true, isOpen: true }).state).toEqual({
135
+ disabled: true,
136
+ expanded: true,
137
+ });
138
+ });
139
+
140
+ test("activate runs onPress when there is one, else opens", () => {
141
+ const withPress = resolveContextMenuAccessibility({ hasPress: true, isDisabled: false, isOpen: false });
142
+ const without = resolveContextMenuAccessibility({ hasPress: false, isDisabled: false, isOpen: false });
143
+ expect(withPress.onAction("activate")).toBe("press");
144
+ expect(without.onAction("activate")).toBe("open");
145
+ });
146
+
147
+ test("longpress opens", () => {
148
+ const a11y = resolveContextMenuAccessibility({ hasPress: true, isDisabled: false, isOpen: false });
149
+ expect(a11y.onAction("longpress")).toBe("open");
150
+ });
151
+
152
+ test("disabled does nothing, for either action", () => {
153
+ const a11y = resolveContextMenuAccessibility({ hasPress: true, isDisabled: true, isOpen: false });
154
+ expect(a11y.onAction("activate")).toBe("none");
155
+ expect(a11y.onAction("longpress")).toBe("none");
156
+ });
157
+
158
+ test("an unknown action does nothing", () => {
159
+ const a11y = resolveContextMenuAccessibility({ hasPress: true, isDisabled: false, isOpen: false });
160
+ expect(a11y.onAction("magicTap")).toBe("none");
161
+ });
162
+ });
163
+
164
+ describe("content defaults", () => {
165
+ test("differ from Menu's: bottom, start, 8pt, at least 280 wide, with a scrim", () => {
166
+ expect(CONTEXT_MENU_CONTENT_DEFAULTS).toEqual({
167
+ align: "start",
168
+ hasScrim: true,
169
+ minWidth: 280,
170
+ offset: 8,
171
+ placement: "bottom",
172
+ });
173
+ });
174
+
175
+ test("a point anchor resolves to the 280 floor, not Menu's 200", () => {
176
+ const width = resolveMenuWidth({ minWidth: CONTEXT_MENU_CONTENT_DEFAULTS.minWidth, triggerWidth: 0 });
177
+ expect(width).toBe(280);
178
+ expect(width).toBeGreaterThan(MENU_DEFAULT_MIN_WIDTH);
179
+ });
180
+
181
+ test("a wide target keeps its own width", () => {
182
+ expect(resolveMenuWidth({ minWidth: CONTEXT_MENU_CONTENT_DEFAULTS.minWidth, triggerWidth: 340 })).toBe(340);
183
+ });
184
+
185
+ test("the panel sits 8pt below a point", () => {
186
+ const result = resolveMenuPlacement({
187
+ align: CONTEXT_MENU_CONTENT_DEFAULTS.align,
188
+ anchor: { height: 0, width: 0, x: 140, y: 260 },
189
+ content: { height: 200, width: 280 },
190
+ insets: { bottom: 34, left: 0, right: 0, top: 47 },
191
+ isRTL: false,
192
+ offset: CONTEXT_MENU_CONTENT_DEFAULTS.offset,
193
+ placement: CONTEXT_MENU_CONTENT_DEFAULTS.placement,
194
+ window: { height: 800, width: 400 },
195
+ });
196
+ expect(result.placement).toBe("bottom");
197
+ expect(result.top).toBe(268);
198
+ });
199
+
200
+ test("a panel under a tall target flips above it, clear of the target", () => {
201
+ const target = { height: 300, width: 360, x: 20, y: 420 };
202
+ const result = resolveMenuPlacement({
203
+ align: CONTEXT_MENU_CONTENT_DEFAULTS.align,
204
+ anchor: target,
205
+ content: { height: 200, width: 360 },
206
+ insets: { bottom: 34, left: 0, right: 0, top: 47 },
207
+ isRTL: false,
208
+ offset: CONTEXT_MENU_CONTENT_DEFAULTS.offset,
209
+ placement: CONTEXT_MENU_CONTENT_DEFAULTS.placement,
210
+ window: { height: 800, width: 400 },
211
+ });
212
+ expect(result.placement).toBe("top");
213
+ expect(result.top + 200).toBeLessThanOrEqual(target.y - CONTEXT_MENU_CONTENT_DEFAULTS.offset);
214
+ });
215
+ });
216
+
217
+ describe("preview", () => {
218
+ test("lifts by 3%, which the 8pt offset clears for any target under ~530pt tall", () => {
219
+ expect(CONTEXT_MENU_PREVIEW_SCALE).toBe(1.03);
220
+ const grow = ((CONTEXT_MENU_PREVIEW_SCALE - 1) * 530) / 2;
221
+ expect(grow).toBeLessThan(CONTEXT_MENU_CONTENT_DEFAULTS.offset);
222
+ });
223
+ });
224
+
225
+ describe("contextMenuVariants", () => {
226
+ test("rows are taller than Menu's", () => {
227
+ expect(contextMenuVariants().item()).toContain("min-h-12");
228
+ });
229
+
230
+ test("the trigger does not shrink to its child", () => {
231
+ expect(contextMenuVariants().trigger()).not.toMatch(/self-start|items-start/);
232
+ });
233
+
234
+ test("the preview is absolute and casts a shadow", () => {
235
+ const preview = contextMenuVariants().preview();
236
+ expect(preview).toContain("absolute");
237
+ expect(preview).toMatch(/shadow-/);
238
+ });
239
+
240
+ test("merges a caller's class", () => {
241
+ expect(contextMenuVariants().trigger({ className: "rounded-lg" })).toContain("rounded-lg");
242
+ });
243
+
244
+ test("no slot carries a text colour", () => {
245
+ const slots = contextMenuVariants();
246
+ for (const name of ["trigger", "preview", "item"] as const) {
247
+ expect(slots[name]()).not.toMatch(/\btext-/);
248
+ }
249
+ });
250
+ });
251
+
252
+ describe("context menu colour tokens", () => {
253
+ const LIGHT = declaredTokens("light");
254
+ const DARK = declaredTokens("dark");
255
+
256
+ test("every token is declared in both themes", () => {
257
+ const slots = contextMenuVariants();
258
+ for (const name of ["trigger", "preview", "item"] as const) {
259
+ for (const [, token] of slots[name]().matchAll(/\b(?:bg|border)-([a-z][\w-]*)/g)) {
260
+ if (token === undefined) continue;
261
+ expect({ inLight: LIGHT.has(token), token }).toEqual({ inLight: true, token });
262
+ expect({ inDark: DARK.has(token), token }).toEqual({ inDark: true, token });
263
+ }
264
+ }
265
+ });
266
+ });
@@ -0,0 +1,147 @@
1
+ import type { VariantProps } from "tailwind-variants";
2
+ import { tv } from "../../lib/tv";
3
+ import type { MenuAlign, MenuAnchorRect, MenuPlacement } from "../menu/menu.variants";
4
+
5
+ export const CONTEXT_MENU_ANCHORS = ["point", "target"] as const;
6
+
7
+ /** What the panel hangs off: the finger's press point, or the held content's rect. */
8
+ export type ContextMenuAnchor = (typeof CONTEXT_MENU_ANCHORS)[number];
9
+
10
+ /** How the menu was asked for. A screen reader has no pointer coordinate. */
11
+ export type ContextMenuInvoker = "pointer" | "accessibility";
12
+
13
+ /** A press point in window coordinates. */
14
+ export type ContextMenuPoint = { x: number; y: number };
15
+
16
+ /**
17
+ * The hold: `delay` ms before it is accepted, `slop` pt the finger may drift
18
+ * meanwhile. `minDelay` is the floor — anything shorter is a tap.
19
+ */
20
+ export const CONTEXT_MENU_HOLD = { delay: 350, minDelay: 150, slop: 12 } as const;
21
+
22
+ /**
23
+ * `ContextMenu.Content`'s defaults, where they differ from `Menu.Content`'s: a
24
+ * wider floor (a point anchor has no width to inherit), a little more gap from
25
+ * the finger, and a scrim — the content behind is not the menu's control.
26
+ */
27
+ export const CONTEXT_MENU_CONTENT_DEFAULTS: {
28
+ placement: MenuPlacement;
29
+ align: MenuAlign;
30
+ offset: number;
31
+ minWidth: number;
32
+ hasScrim: boolean;
33
+ } = { align: "start", hasScrim: true, minWidth: 280, offset: 8, placement: "bottom" };
34
+
35
+ /** How far the lifted preview grows, 1 → this. */
36
+ export const CONTEXT_MENU_PREVIEW_SCALE = 1.03;
37
+
38
+ /** How long the preview takes to lift, in ms — Menu's enter, so the two arrive together. */
39
+ export const CONTEXT_MENU_PREVIEW_MS = 160;
40
+
41
+ /** The label a screen reader reads for the long-press action. */
42
+ export const CONTEXT_MENU_SHOW_LABEL = "Show menu";
43
+
44
+ export const CONTEXT_MENU_ACCESSIBILITY_ACTIONS: ReadonlyArray<{ name: string; label?: string }> = [
45
+ { name: "activate" },
46
+ { label: CONTEXT_MENU_SHOW_LABEL, name: "longpress" },
47
+ ];
48
+
49
+ export type ContextAnchorInput = {
50
+ mode: ContextMenuAnchor;
51
+ /** The press point, or `null` when there was none — a screen-reader open. */
52
+ point: ContextMenuPoint | null;
53
+ /** The trigger's measured window rect. */
54
+ targetRect: MenuAnchorRect;
55
+ hasPreview: boolean;
56
+ invokedBy: ContextMenuInvoker;
57
+ };
58
+
59
+ /**
60
+ * The rect the panel is placed against.
61
+ *
62
+ * `point` mode gives a zero-size rect at the press, which Menu's placement
63
+ * resolver handles with no special case. Three things force the target instead:
64
+ * `target` mode; a `ContextMenu.Preview`, so the panel opens outside the lifted
65
+ * copy rather than across it; and a screen-reader open, which has no point.
66
+ */
67
+ export function resolveContextAnchor({
68
+ mode,
69
+ point,
70
+ targetRect,
71
+ hasPreview,
72
+ invokedBy,
73
+ }: ContextAnchorInput): MenuAnchorRect {
74
+ const isTarget = mode === "target" || hasPreview || invokedBy === "accessibility" || point === null;
75
+ if (isTarget) return { height: targetRect.height, width: targetRect.width, x: targetRect.x, y: targetRect.y };
76
+ return { height: 0, width: 0, x: point.x, y: point.y };
77
+ }
78
+
79
+ /**
80
+ * The hold's timing: defaults of 350ms and 12pt, a 150ms floor on the delay so
81
+ * a tap can never open the menu, and a zero floor on the slop. A non-finite
82
+ * value takes the default.
83
+ */
84
+ export function resolveHoldConfig({ delay, slop }: { delay?: number; slop?: number }): {
85
+ delay: number;
86
+ slop: number;
87
+ } {
88
+ const d = delay !== undefined && Number.isFinite(delay) ? delay : CONTEXT_MENU_HOLD.delay;
89
+ const s = slop !== undefined && Number.isFinite(slop) ? slop : CONTEXT_MENU_HOLD.slop;
90
+ return { delay: Math.max(CONTEXT_MENU_HOLD.minDelay, d), slop: Math.max(0, s) };
91
+ }
92
+
93
+ /** What an accessibility action resolves to. */
94
+ export type ContextMenuActionOutcome = "press" | "open" | "none";
95
+
96
+ /**
97
+ * The trigger's accessibility: a `button` when it has `onPress` (activating it
98
+ * does something of its own), otherwise no role — the content inside speaks for
99
+ * itself. `activate` runs `onPress`, or opens when there is none; `longpress`
100
+ * ("Show menu") opens. Disabled, neither does anything.
101
+ */
102
+ export function resolveContextMenuAccessibility({
103
+ hasPress,
104
+ isDisabled,
105
+ isOpen,
106
+ }: {
107
+ hasPress: boolean;
108
+ isDisabled: boolean;
109
+ isOpen: boolean;
110
+ }): {
111
+ role: "button" | "none";
112
+ state: { disabled: boolean; expanded: boolean };
113
+ onAction: (name: string) => ContextMenuActionOutcome;
114
+ } {
115
+ return {
116
+ onAction: (name) => {
117
+ if (isDisabled) return "none";
118
+ if (name === "activate") return hasPress ? "press" : "open";
119
+ if (name === "longpress") return "open";
120
+ return "none";
121
+ },
122
+ role: hasPress ? "button" : "none",
123
+ state: { disabled: isDisabled, expanded: isOpen },
124
+ };
125
+ }
126
+
127
+ /**
128
+ * Styling for ContextMenu's own parts. The rows and the panel are Menu's, and
129
+ * wear `menuVariants`; this holds only what differs.
130
+ *
131
+ * - `trigger` lays out like a plain `View` — it neither shrinks to its child nor
132
+ * adds anything to it.
133
+ * - `preview` is the lifted copy, absolutely placed at the trigger's window rect.
134
+ * - `item` makes a row taller: content menus are reached by a held finger, and a
135
+ * 48pt row is easier to land after the lift.
136
+ *
137
+ * Free of React Native imports so it stays reachable from `bun test`.
138
+ */
139
+ export const contextMenuVariants = tv({
140
+ slots: {
141
+ trigger: "relative",
142
+ preview: "absolute shadow-lg",
143
+ item: "min-h-12",
144
+ },
145
+ });
146
+
147
+ export type ContextMenuVariantProps = VariantProps<typeof contextMenuVariants>;
@@ -0,0 +1,18 @@
1
+ export { ContextMenu, type ContextMenuProps } from "./context-menu";
2
+ export {
3
+ CONTEXT_MENU_ANCHORS,
4
+ CONTEXT_MENU_CONTENT_DEFAULTS,
5
+ CONTEXT_MENU_HOLD,
6
+ type ContextAnchorInput,
7
+ type ContextMenuAnchor,
8
+ type ContextMenuInvoker,
9
+ type ContextMenuPoint,
10
+ type ContextMenuVariantProps,
11
+ contextMenuVariants,
12
+ resolveContextAnchor,
13
+ resolveHoldConfig,
14
+ } from "./context-menu.variants";
15
+ export type { ContextMenuContentProps } from "./context-menu-content";
16
+ export type { ContextMenuItemProps } from "./context-menu-item";
17
+ export type { ContextMenuPreviewProps } from "./context-menu-preview";
18
+ export type { ContextMenuTriggerProps } from "./context-menu-trigger";
@@ -162,6 +162,10 @@ ContextMenu renders this component's rows and panel rather than a copy:
162
162
  `anchor` straight to `Menu.Content`.
163
163
  - **`hasScrim`** tints the screen behind the panel; **`iconPlacement="trailing"`**
164
164
  puts a row's icon at its end.
165
+ - **`backdrop`** draws a node inside the `Modal`, over the scrim and behind the
166
+ panel, fading with them and taking no touches. A `Modal` covers everything,
167
+ so anything meant to show above the scrim — ContextMenu's lifted preview — has
168
+ to be inside it; outside, it would sit under the tint.
165
169
 
166
170
  ## Out of scope
167
171
 
@@ -52,6 +52,12 @@ export type MenuContentProps = Omit<ViewProps, "children"> & {
52
52
  hasScrim?: boolean;
53
53
  /** Anchor to this rect instead of the trigger. A zero-size rect is a point. */
54
54
  anchor?: MenuAnchorRect;
55
+ /**
56
+ * Drawn inside the `Modal`, over the scrim and behind the panel, fading with
57
+ * them. It takes no touches — a tap on it is an outside tap. ContextMenu's
58
+ * lifted preview is the reason it exists.
59
+ */
60
+ backdrop?: ReactNode;
55
61
  };
56
62
 
57
63
  /**
@@ -88,6 +94,7 @@ export function MenuContent({
88
94
  isScrollable = true,
89
95
  hasScrim = false,
90
96
  anchor: anchorProp,
97
+ backdrop,
91
98
  ...props
92
99
  }: MenuContentProps): ReactElement | null {
93
100
  const { anchor: contextAnchor, close, isOpen } = useMenuPart("Menu.Content");
@@ -201,6 +208,16 @@ export function MenuContent({
201
208
  >
202
209
  {hasScrim ? <Animated.View className={slots.scrim()} style={scrimStyle} /> : null}
203
210
  </Pressable>
211
+ {backdrop ? (
212
+ <Animated.View
213
+ className={slots.backdrop()}
214
+ importantForAccessibility="no-hide-descendants"
215
+ pointerEvents="none"
216
+ style={scrimStyle}
217
+ >
218
+ {backdrop}
219
+ </Animated.View>
220
+ ) : null}
204
221
  <Animated.View
205
222
  accessibilityRole="menu"
206
223
  accessibilityViewIsModal
@@ -315,6 +315,13 @@ describe("menuVariants", () => {
315
315
  expect(menuVariants().scrim()).toContain("bg-overlay");
316
316
  });
317
317
 
318
+ test("the backdrop layer fills the screen and paints nothing of its own", () => {
319
+ const backdrop = menuVariants().backdrop();
320
+ expect(backdrop).toContain("absolute");
321
+ expect(backdrop).toContain("inset-0");
322
+ expect(backdrop).not.toMatch(/\b(bg|text)-/);
323
+ });
324
+
318
325
  test("a row is at least a touch target tall", () => {
319
326
  expect(menuVariants().item()).toContain("min-h-11");
320
327
  });
@@ -338,7 +345,7 @@ describe("menuVariants", () => {
338
345
 
339
346
  test("no slot worn by a View carries a text colour", () => {
340
347
  const slots = menuVariants({ variant: "destructive" });
341
- for (const name of ["content", "background", "item", "itemFill", "subContent", "scrim"] as const) {
348
+ for (const name of ["content", "background", "item", "itemFill", "subContent", "scrim", "backdrop"] as const) {
342
349
  expect(slots[name]()).not.toMatch(/\btext-/);
343
350
  }
344
351
  });
@@ -296,6 +296,8 @@ export const menuVariants = tv({
296
296
  background: "absolute inset-0 bg-popover",
297
297
  /** The full-screen tint behind the panel, when `hasScrim`. */
298
298
  scrim: "absolute inset-0 bg-overlay",
299
+ /** What `backdrop` is drawn in — full-screen, over the scrim, behind the panel. */
300
+ backdrop: "absolute inset-0",
299
301
  /** The scroller's padding, around the rows. */
300
302
  scroll: "p-1",
301
303
  /** One row. */