@funstack/ui 0.1.0-alpha.20 → 0.1.0-alpha.22
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/dist/alert-dialog/alert-dialog-root.mjs +2 -1
- package/dist/alert-dialog/alert-dialog-root.mjs.map +1 -1
- package/dist/avatar/avatar-context.mjs +24 -0
- package/dist/avatar/avatar-context.mjs.map +1 -0
- package/dist/avatar/avatar-fallback.d.mts +32 -0
- package/dist/avatar/avatar-fallback.d.mts.map +1 -0
- package/dist/avatar/avatar-fallback.mjs +31 -0
- package/dist/avatar/avatar-fallback.mjs.map +1 -0
- package/dist/avatar/avatar-image.d.mts +37 -0
- package/dist/avatar/avatar-image.d.mts.map +1 -0
- package/dist/avatar/avatar-image.mjs +91 -0
- package/dist/avatar/avatar-image.mjs.map +1 -0
- package/dist/avatar/avatar-root.d.mts +48 -0
- package/dist/avatar/avatar-root.d.mts.map +1 -0
- package/dist/avatar/avatar-root.mjs +81 -0
- package/dist/avatar/avatar-root.mjs.map +1 -0
- package/dist/avatar/index.d.mts +24 -0
- package/dist/avatar/index.d.mts.map +1 -0
- package/dist/avatar/index.mjs +24 -0
- package/dist/avatar/index.mjs.map +1 -0
- package/dist/dialog/dialog-close.d.mts.map +1 -1
- package/dist/dialog/dialog-close.mjs +14 -3
- package/dist/dialog/dialog-close.mjs.map +1 -1
- package/dist/dialog/dialog-context.mjs +7 -1
- package/dist/dialog/dialog-context.mjs.map +1 -1
- package/dist/dialog/dialog-popup.d.mts +1 -0
- package/dist/dialog/dialog-popup.d.mts.map +1 -1
- package/dist/dialog/dialog-popup.mjs +20 -2
- package/dist/dialog/dialog-popup.mjs.map +1 -1
- package/dist/dialog/dialog-root.mjs +6 -4
- package/dist/dialog/dialog-root.mjs.map +1 -1
- package/dist/docs/components/avatar.md +354 -0
- package/dist/docs/components/drawer.md +622 -0
- package/dist/docs/components/menu.md +1 -1
- package/dist/docs/components/menubar.md +309 -0
- package/dist/docs/components/meter.md +1 -1
- package/dist/docs/components/navigation-menu.md +501 -0
- package/dist/docs/components/number-field.md +2 -2
- package/dist/docs/components/otp-field.md +508 -0
- package/dist/docs/components/progress.md +1 -1
- package/dist/docs/components/radio-group.md +1 -1
- package/dist/docs/components/scroll-area.md +294 -0
- package/dist/docs/components/slider.md +1 -1
- package/dist/docs/concepts/direction-and-locales.md +106 -0
- package/dist/docs/index.md +8 -1
- package/dist/docs/roadmap.md +13 -0
- package/dist/drawer/drawer-close.d.mts +26 -0
- package/dist/drawer/drawer-close.d.mts.map +1 -0
- package/dist/drawer/drawer-close.mjs +19 -0
- package/dist/drawer/drawer-close.mjs.map +1 -0
- package/dist/drawer/drawer-description.d.mts +23 -0
- package/dist/drawer/drawer-description.d.mts.map +1 -0
- package/dist/drawer/drawer-description.mjs +18 -0
- package/dist/drawer/drawer-description.mjs.map +1 -0
- package/dist/drawer/drawer-form.d.mts +24 -0
- package/dist/drawer/drawer-form.d.mts.map +1 -0
- package/dist/drawer/drawer-form.mjs +19 -0
- package/dist/drawer/drawer-form.mjs.map +1 -0
- package/dist/drawer/drawer-popup.d.mts +77 -0
- package/dist/drawer/drawer-popup.d.mts.map +1 -0
- package/dist/drawer/drawer-popup.mjs +124 -0
- package/dist/drawer/drawer-popup.mjs.map +1 -0
- package/dist/drawer/drawer-root.d.mts +31 -0
- package/dist/drawer/drawer-root.d.mts.map +1 -0
- package/dist/drawer/drawer-root.mjs +23 -0
- package/dist/drawer/drawer-root.mjs.map +1 -0
- package/dist/drawer/drawer-swipe.d.mts +5 -0
- package/dist/drawer/drawer-swipe.d.mts.map +1 -0
- package/dist/drawer/drawer-swipe.mjs +193 -0
- package/dist/drawer/drawer-swipe.mjs.map +1 -0
- package/dist/drawer/drawer-title.d.mts +23 -0
- package/dist/drawer/drawer-title.d.mts.map +1 -0
- package/dist/drawer/drawer-title.mjs +18 -0
- package/dist/drawer/drawer-title.mjs.map +1 -0
- package/dist/drawer/drawer-trigger.d.mts +23 -0
- package/dist/drawer/drawer-trigger.d.mts.map +1 -0
- package/dist/drawer/drawer-trigger.mjs +18 -0
- package/dist/drawer/drawer-trigger.mjs.map +1 -0
- package/dist/drawer/index.d.mts +34 -0
- package/dist/drawer/index.d.mts.map +1 -0
- package/dist/drawer/index.mjs +33 -0
- package/dist/drawer/index.mjs.map +1 -0
- package/dist/index.d.mts +29 -2
- package/dist/index.mjs +6 -1
- package/dist/internal/menubar-context.mjs +12 -0
- package/dist/internal/menubar-context.mjs.map +1 -0
- package/dist/internal/overlay/trigger-ref.mjs +1 -1
- package/dist/internal/overlay/trigger-ref.mjs.map +1 -1
- package/dist/internal/overlay/use-overlay-root.mjs +3 -2
- package/dist/internal/overlay/use-overlay-root.mjs.map +1 -1
- package/dist/internal/overlay/use-popover-trigger.mjs +2 -2
- package/dist/internal/overlay/use-popover-trigger.mjs.map +1 -1
- package/dist/internal/range-value.mjs +5 -3
- package/dist/internal/range-value.mjs.map +1 -1
- package/dist/internal/swipe-arithmetic.mjs +75 -0
- package/dist/internal/swipe-arithmetic.mjs.map +1 -0
- package/dist/internal/swipe.mjs +169 -0
- package/dist/internal/swipe.mjs.map +1 -0
- package/dist/menu/menu-context-trigger.mjs +1 -1
- package/dist/menu/menu-popup.d.mts.map +1 -1
- package/dist/menu/menu-popup.mjs +34 -7
- package/dist/menu/menu-popup.mjs.map +1 -1
- package/dist/menu/menu-trigger.d.mts +10 -3
- package/dist/menu/menu-trigger.d.mts.map +1 -1
- package/dist/menu/menu-trigger.mjs +53 -5
- package/dist/menu/menu-trigger.mjs.map +1 -1
- package/dist/menubar/index.d.mts +3 -0
- package/dist/menubar/index.mjs +1 -0
- package/dist/menubar/menubar.d.mts +49 -0
- package/dist/menubar/menubar.d.mts.map +1 -0
- package/dist/menubar/menubar.mjs +147 -0
- package/dist/menubar/menubar.mjs.map +1 -0
- package/dist/meter/meter-root.d.mts +3 -2
- package/dist/meter/meter-root.d.mts.map +1 -1
- package/dist/meter/meter-root.mjs.map +1 -1
- package/dist/multi-select/multi-select-root.mjs +1 -1
- package/dist/multi-select/multi-select-trigger.mjs +1 -1
- package/dist/navigation-menu/index.d.mts +32 -0
- package/dist/navigation-menu/index.d.mts.map +1 -0
- package/dist/navigation-menu/index.mjs +32 -0
- package/dist/navigation-menu/index.mjs.map +1 -0
- package/dist/navigation-menu/navigation-menu-context.mjs +19 -0
- package/dist/navigation-menu/navigation-menu-context.mjs.map +1 -0
- package/dist/navigation-menu/navigation-menu-item.d.mts +79 -0
- package/dist/navigation-menu/navigation-menu-item.d.mts.map +1 -0
- package/dist/navigation-menu/navigation-menu-item.mjs +80 -0
- package/dist/navigation-menu/navigation-menu-item.mjs.map +1 -0
- package/dist/navigation-menu/navigation-menu-link.d.mts +48 -0
- package/dist/navigation-menu/navigation-menu-link.d.mts.map +1 -0
- package/dist/navigation-menu/navigation-menu-link.mjs +66 -0
- package/dist/navigation-menu/navigation-menu-link.mjs.map +1 -0
- package/dist/navigation-menu/navigation-menu-list.d.mts +33 -0
- package/dist/navigation-menu/navigation-menu-list.d.mts.map +1 -0
- package/dist/navigation-menu/navigation-menu-list.mjs +30 -0
- package/dist/navigation-menu/navigation-menu-list.mjs.map +1 -0
- package/dist/navigation-menu/navigation-menu-popup.d.mts +102 -0
- package/dist/navigation-menu/navigation-menu-popup.d.mts.map +1 -0
- package/dist/navigation-menu/navigation-menu-popup.mjs +93 -0
- package/dist/navigation-menu/navigation-menu-popup.mjs.map +1 -0
- package/dist/navigation-menu/navigation-menu-root.d.mts +33 -0
- package/dist/navigation-menu/navigation-menu-root.d.mts.map +1 -0
- package/dist/navigation-menu/navigation-menu-root.mjs +27 -0
- package/dist/navigation-menu/navigation-menu-root.mjs.map +1 -0
- package/dist/navigation-menu/navigation-menu-trigger.d.mts +32 -0
- package/dist/navigation-menu/navigation-menu-trigger.d.mts.map +1 -0
- package/dist/navigation-menu/navigation-menu-trigger.mjs +42 -0
- package/dist/navigation-menu/navigation-menu-trigger.mjs.map +1 -0
- package/dist/otp-field/index.d.mts +23 -0
- package/dist/otp-field/index.d.mts.map +1 -0
- package/dist/otp-field/index.mjs +23 -0
- package/dist/otp-field/index.mjs.map +1 -0
- package/dist/otp-field/otp-field-context.mjs +13 -0
- package/dist/otp-field/otp-field-context.mjs.map +1 -0
- package/dist/otp-field/otp-field-filter.d.mts +5 -0
- package/dist/otp-field/otp-field-filter.d.mts.map +1 -0
- package/dist/otp-field/otp-field-filter.mjs +135 -0
- package/dist/otp-field/otp-field-filter.mjs.map +1 -0
- package/dist/otp-field/otp-field-input.d.mts +41 -0
- package/dist/otp-field/otp-field-input.d.mts.map +1 -0
- package/dist/otp-field/otp-field-input.mjs +177 -0
- package/dist/otp-field/otp-field-input.mjs.map +1 -0
- package/dist/otp-field/otp-field-root.d.mts +152 -0
- package/dist/otp-field/otp-field-root.d.mts.map +1 -0
- package/dist/otp-field/otp-field-root.mjs +400 -0
- package/dist/otp-field/otp-field-root.mjs.map +1 -0
- package/dist/otp-field/otp-field-slot.d.mts +52 -0
- package/dist/otp-field/otp-field-slot.d.mts.map +1 -0
- package/dist/otp-field/otp-field-slot.mjs +67 -0
- package/dist/otp-field/otp-field-slot.mjs.map +1 -0
- package/dist/popover/index.d.mts +1 -1
- package/dist/popover/popover-trigger.mjs +1 -1
- package/dist/progress/progress-root.d.mts +3 -2
- package/dist/progress/progress-root.d.mts.map +1 -1
- package/dist/progress/progress-root.mjs.map +1 -1
- package/package.json +7 -1
- package/skills/funstack-ui-knowledge/SKILL.md +8 -1
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/** A release at least this fraction of the extent toward the edge dismisses. */
|
|
2
|
+
const SWIPE_DISMISS_FRACTION = .25;
|
|
3
|
+
/** A release at least this fast toward the edge dismisses, in px/ms. */
|
|
4
|
+
const SWIPE_FLICK_VELOCITY = .5;
|
|
5
|
+
/** The unit vector of a direction. */
|
|
6
|
+
function swipeVector(direction) {
|
|
7
|
+
switch (direction) {
|
|
8
|
+
case "up": return [0, -1];
|
|
9
|
+
case "down": return [0, 1];
|
|
10
|
+
case "left": return [-1, 0];
|
|
11
|
+
case "right": return [1, 0];
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* The signed distance a movement `(dx, dy)` covers toward the edge: positive toward it,
|
|
16
|
+
* negative away from it.
|
|
17
|
+
*/
|
|
18
|
+
function towardEdge(dx, dy, direction) {
|
|
19
|
+
const [x, y] = swipeVector(direction);
|
|
20
|
+
return dx * x + dy * y;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* What a press that has moved `(dx, dy)` from where it went down is: `"wait"` while it is
|
|
24
|
+
* within the slop; once past it, `"start"` when it moved more along the axis than across it
|
|
25
|
+
* and toward the edge, else `"drop"` (the first move in another direction drops the press for
|
|
26
|
+
* good).
|
|
27
|
+
*/
|
|
28
|
+
function classifyPress(dx, dy, direction) {
|
|
29
|
+
if (Math.hypot(dx, dy) < 6) return "wait";
|
|
30
|
+
const along = towardEdge(dx, dy, direction);
|
|
31
|
+
const [x] = swipeVector(direction);
|
|
32
|
+
return along > 0 && along > (x === 0 ? Math.abs(dx) : Math.abs(dy)) ? "start" : "drop";
|
|
33
|
+
}
|
|
34
|
+
/** The offset written while dragging: the distance toward the edge, never below 0. */
|
|
35
|
+
function swipeOffset(toward) {
|
|
36
|
+
return Math.max(0, toward);
|
|
37
|
+
}
|
|
38
|
+
/** The offset as a physical vector in px (`--drawer-swipe-x` / `-y`). */
|
|
39
|
+
function swipeTranslation(offset, direction) {
|
|
40
|
+
const [x, y] = swipeVector(direction);
|
|
41
|
+
return [offset * x + 0, offset * y + 0];
|
|
42
|
+
}
|
|
43
|
+
/** `offset / extent`, clamped to [0, 1]; 0 for an empty extent. */
|
|
44
|
+
function swipeProgress(offset, extent) {
|
|
45
|
+
if (!(extent > 0)) return 0;
|
|
46
|
+
return Math.min(1, Math.max(0, offset / extent));
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* The velocity toward the edge at the release (px/ms, negative when moving back): from the
|
|
50
|
+
* oldest sample within `SWIPE_VELOCITY_WINDOW` of the last one to the last one. 0 when the
|
|
51
|
+
* pointer did not move in that window (held still before the release) or there is one sample.
|
|
52
|
+
*/
|
|
53
|
+
function releaseVelocity(samples) {
|
|
54
|
+
const last = samples.at(-1);
|
|
55
|
+
if (last === void 0) return 0;
|
|
56
|
+
const first = samples.find((sample) => last.time - sample.time <= 100);
|
|
57
|
+
if (first === void 0 || first === last) return 0;
|
|
58
|
+
const elapsed = last.time - first.time;
|
|
59
|
+
if (elapsed <= 0) return 0;
|
|
60
|
+
return (last.toward - first.toward) / elapsed;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* The decision at the release: `"dismiss"` when the offset is at least a quarter of the extent
|
|
64
|
+
* or the release is a flick toward the edge, **but** `"return"` when the pointer was moving
|
|
65
|
+
* back; otherwise `"return"`.
|
|
66
|
+
*/
|
|
67
|
+
function releaseOutcome(offset, extent, velocity) {
|
|
68
|
+
if (velocity < -.1) return "return";
|
|
69
|
+
if (velocity >= .5) return "dismiss";
|
|
70
|
+
return extent > 0 && offset >= extent * .25 ? "dismiss" : "return";
|
|
71
|
+
}
|
|
72
|
+
//#endregion
|
|
73
|
+
export { SWIPE_DISMISS_FRACTION, SWIPE_FLICK_VELOCITY, classifyPress, releaseOutcome, releaseVelocity, swipeOffset, swipeProgress, swipeTranslation, swipeVector, towardEdge };
|
|
74
|
+
|
|
75
|
+
//# sourceMappingURL=swipe-arithmetic.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"swipe-arithmetic.mjs","names":[],"sources":["../../src/internal/swipe-arithmetic.ts"],"sourcesContent":["// The arithmetic of a swipe toward an edge (design/components/drawer.md 4.1): when a press\n// becomes a drag, how far it has gone toward the edge, its release velocity and the dismiss /\n// return decision. Pure functions, no DOM; the tracker (`swipe.ts`) feeds them. No directive\n// (conventions 7.1).\n\n/** The physical direction a swipe dismisses toward. */\nexport type SwipeDirection = \"up\" | \"down\" | \"left\" | \"right\";\n\n/** How far a press must move before it is a drag or is dropped, in px. */\nexport const SWIPE_SLOP = 6;\n/** A release at least this fraction of the extent toward the edge dismisses. */\nexport const SWIPE_DISMISS_FRACTION = 0.25;\n/** A release at least this fast toward the edge dismisses, in px/ms. */\nexport const SWIPE_FLICK_VELOCITY = 0.5;\n/** A release moving back faster than this (away from the edge) returns, in px/ms. */\nexport const SWIPE_REVERSAL_VELOCITY = 0.1;\n/** The release velocity is measured over this much of the gesture's end, in ms. */\nexport const SWIPE_VELOCITY_WINDOW = 100;\n\n/** The unit vector of a direction. */\nexport function swipeVector(direction: SwipeDirection): readonly [x: number, y: number] {\n switch (direction) {\n case \"up\":\n return [0, -1];\n case \"down\":\n return [0, 1];\n case \"left\":\n return [-1, 0];\n case \"right\":\n return [1, 0];\n }\n}\n\n/**\n * The signed distance a movement `(dx, dy)` covers toward the edge: positive toward it,\n * negative away from it.\n */\nexport function towardEdge(dx: number, dy: number, direction: SwipeDirection): number {\n const [x, y] = swipeVector(direction);\n return dx * x + dy * y;\n}\n\n/**\n * What a press that has moved `(dx, dy)` from where it went down is: `\"wait\"` while it is\n * within the slop; once past it, `\"start\"` when it moved more along the axis than across it\n * and toward the edge, else `\"drop\"` (the first move in another direction drops the press for\n * good).\n */\nexport function classifyPress(\n dx: number,\n dy: number,\n direction: SwipeDirection,\n): \"wait\" | \"start\" | \"drop\" {\n if (Math.hypot(dx, dy) < SWIPE_SLOP) return \"wait\";\n const along = towardEdge(dx, dy, direction);\n const [x] = swipeVector(direction);\n const across = x === 0 ? Math.abs(dx) : Math.abs(dy);\n return along > 0 && along > across ? \"start\" : \"drop\";\n}\n\n/** The offset written while dragging: the distance toward the edge, never below 0. */\nexport function swipeOffset(toward: number): number {\n return Math.max(0, toward);\n}\n\n/** The offset as a physical vector in px (`--drawer-swipe-x` / `-y`). */\nexport function swipeTranslation(\n offset: number,\n direction: SwipeDirection,\n): readonly [x: number, y: number] {\n const [x, y] = swipeVector(direction);\n // `+ 0` turns a `-0` into `0`.\n return [offset * x + 0, offset * y + 0];\n}\n\n/** `offset / extent`, clamped to [0, 1]; 0 for an empty extent. */\nexport function swipeProgress(offset: number, extent: number): number {\n if (!(extent > 0)) return 0;\n return Math.min(1, Math.max(0, offset / extent));\n}\n\n/** One point of the gesture: a time (ms) and the signed distance toward the edge. */\nexport interface SwipeSample {\n readonly time: number;\n readonly toward: number;\n}\n\n/**\n * The velocity toward the edge at the release (px/ms, negative when moving back): from the\n * oldest sample within `SWIPE_VELOCITY_WINDOW` of the last one to the last one. 0 when the\n * pointer did not move in that window (held still before the release) or there is one sample.\n */\nexport function releaseVelocity(samples: readonly SwipeSample[]): number {\n const last = samples.at(-1);\n if (last === undefined) return 0;\n const first = samples.find((sample) => last.time - sample.time <= SWIPE_VELOCITY_WINDOW);\n if (first === undefined || first === last) return 0;\n const elapsed = last.time - first.time;\n if (elapsed <= 0) return 0;\n return (last.toward - first.toward) / elapsed;\n}\n\n/**\n * The decision at the release: `\"dismiss\"` when the offset is at least a quarter of the extent\n * or the release is a flick toward the edge, **but** `\"return\"` when the pointer was moving\n * back; otherwise `\"return\"`.\n */\nexport function releaseOutcome(\n offset: number,\n extent: number,\n velocity: number,\n): \"dismiss\" | \"return\" {\n if (velocity < -SWIPE_REVERSAL_VELOCITY) return \"return\";\n if (velocity >= SWIPE_FLICK_VELOCITY) return \"dismiss\";\n return extent > 0 && offset >= extent * SWIPE_DISMISS_FRACTION ? \"dismiss\" : \"return\";\n}\n"],"mappings":";AAWA,MAAa,yBAAyB;;AAEtC,MAAa,uBAAuB;;AAOpC,SAAgB,YAAY,WAA4D;CACtF,QAAQ,WAAR;EACE,KAAK,MACH,OAAO,CAAC,GAAG,EAAE;EACf,KAAK,QACH,OAAO,CAAC,GAAG,CAAC;EACd,KAAK,QACH,OAAO,CAAC,IAAI,CAAC;EACf,KAAK,SACH,OAAO,CAAC,GAAG,CAAC;CAChB;AACF;;;;;AAMA,SAAgB,WAAW,IAAY,IAAY,WAAmC;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@@
|
|
|
1
|
+
import { classifyPress, releaseOutcome, releaseVelocity, swipeOffset, swipeProgress, towardEdge } from "./swipe-arithmetic.mjs";
|
|
2
|
+
import { capturePointer } from "./pointer-capture.mjs";
|
|
3
|
+
//#region src/internal/swipe.ts
|
|
4
|
+
/** The document's selection when it is not collapsed, else `null`. */
|
|
5
|
+
function selectionOf(doc) {
|
|
6
|
+
const selection = doc.getSelection();
|
|
7
|
+
if (selection === null || selection.isCollapsed) return null;
|
|
8
|
+
const { anchorNode, anchorOffset, focusNode, focusOffset } = selection;
|
|
9
|
+
return {
|
|
10
|
+
anchorNode,
|
|
11
|
+
anchorOffset,
|
|
12
|
+
focusNode,
|
|
13
|
+
focusOffset
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
/** Whether the press made a text selection: one exists now and it is not the one it found. */
|
|
17
|
+
function selectedSincePress(doc, before) {
|
|
18
|
+
const now = selectionOf(doc);
|
|
19
|
+
if (now === null) return false;
|
|
20
|
+
return before === null || now.anchorNode !== before.anchorNode || now.anchorOffset !== before.anchorOffset || now.focusNode !== before.focusNode || now.focusOffset !== before.focusOffset;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Tracks swipes on `element`. A primary press the caller accepts is only recorded: no capture,
|
|
24
|
+
* no `preventDefault()`, so a tap, a click and a text selection are untouched. When it has
|
|
25
|
+
* moved `SWIPE_SLOP` px, more along the axis than across and toward the edge, it becomes a drag
|
|
26
|
+
* (the pointer is captured on `element`) unless the press's `pointerdown` was
|
|
27
|
+
* `defaultPrevented` (read then, so a handler that ran after the capture-phase listener
|
|
28
|
+
* counts), another element took the pointer's capture, or a mouse press made a text selection.
|
|
29
|
+
* A first move in another direction drops the press.
|
|
30
|
+
*/
|
|
31
|
+
function trackSwipe(element, options) {
|
|
32
|
+
const doc = element.ownerDocument;
|
|
33
|
+
let press = null;
|
|
34
|
+
const detachPress = () => {
|
|
35
|
+
doc.removeEventListener("pointermove", onMove, true);
|
|
36
|
+
doc.removeEventListener("pointerup", onUp, true);
|
|
37
|
+
doc.removeEventListener("pointercancel", onCancel, true);
|
|
38
|
+
doc.removeEventListener("gotpointercapture", onGotCapture, true);
|
|
39
|
+
element.removeEventListener("lostpointercapture", onLostCapture);
|
|
40
|
+
};
|
|
41
|
+
/** Forget the press; release the capture of a drag that did not end with the button. */
|
|
42
|
+
const clear = () => {
|
|
43
|
+
const current = press;
|
|
44
|
+
press = null;
|
|
45
|
+
detachPress();
|
|
46
|
+
if (current?.dragging) {
|
|
47
|
+
const id = current.event.pointerId;
|
|
48
|
+
try {
|
|
49
|
+
if (element.hasPointerCapture(id)) element.releasePointerCapture(id);
|
|
50
|
+
} catch {}
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
const finish = (outcome, event) => {
|
|
54
|
+
const current = press;
|
|
55
|
+
if (current === null || !current.dragging) {
|
|
56
|
+
clear();
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
const { offset, extent } = current;
|
|
60
|
+
clear();
|
|
61
|
+
options.end({
|
|
62
|
+
outcome,
|
|
63
|
+
event,
|
|
64
|
+
offset,
|
|
65
|
+
extent
|
|
66
|
+
});
|
|
67
|
+
};
|
|
68
|
+
const onDown = (event) => {
|
|
69
|
+
if (press !== null) {
|
|
70
|
+
if (event.isPrimary && event.pointerId !== press.event.pointerId) finish("cancel", event);
|
|
71
|
+
else return;
|
|
72
|
+
}
|
|
73
|
+
if (!event.isPrimary || event.button !== 0) return;
|
|
74
|
+
const direction = options.press(event);
|
|
75
|
+
if (direction === null) return;
|
|
76
|
+
press = {
|
|
77
|
+
event,
|
|
78
|
+
direction,
|
|
79
|
+
selection: event.pointerType === "mouse" ? selectionOf(doc) : null,
|
|
80
|
+
capturedElsewhere: false,
|
|
81
|
+
dragging: false,
|
|
82
|
+
extent: 0,
|
|
83
|
+
offset: 0,
|
|
84
|
+
samples: [{
|
|
85
|
+
time: event.timeStamp,
|
|
86
|
+
toward: 0
|
|
87
|
+
}]
|
|
88
|
+
};
|
|
89
|
+
doc.addEventListener("pointermove", onMove, true);
|
|
90
|
+
doc.addEventListener("pointerup", onUp, true);
|
|
91
|
+
doc.addEventListener("pointercancel", onCancel, true);
|
|
92
|
+
doc.addEventListener("gotpointercapture", onGotCapture, true);
|
|
93
|
+
};
|
|
94
|
+
const onGotCapture = (event) => {
|
|
95
|
+
const current = press;
|
|
96
|
+
if (current === null || current.dragging) return;
|
|
97
|
+
if (event.pointerId !== current.event.pointerId) return;
|
|
98
|
+
const target = event.target;
|
|
99
|
+
if (target === element) return;
|
|
100
|
+
if (current.event.pointerType !== "mouse" && target === current.event.target) return;
|
|
101
|
+
current.capturedElsewhere = true;
|
|
102
|
+
};
|
|
103
|
+
/** The press becomes a drag, or is dropped (`false`). */
|
|
104
|
+
const tryStart = (current, event) => {
|
|
105
|
+
if (current.event.defaultPrevented || current.capturedElsewhere) return false;
|
|
106
|
+
if (current.event.pointerType === "mouse" && selectedSincePress(doc, current.selection)) return false;
|
|
107
|
+
if (!capturePointer(element, current.event.pointerId)) return false;
|
|
108
|
+
current.dragging = true;
|
|
109
|
+
current.extent = options.extent();
|
|
110
|
+
element.addEventListener("lostpointercapture", onLostCapture);
|
|
111
|
+
options.start(event);
|
|
112
|
+
return true;
|
|
113
|
+
};
|
|
114
|
+
const follow = (current, event) => {
|
|
115
|
+
const toward = towardEdge(event.clientX - current.event.clientX, event.clientY - current.event.clientY, current.direction);
|
|
116
|
+
current.samples.push({
|
|
117
|
+
time: event.timeStamp,
|
|
118
|
+
toward
|
|
119
|
+
});
|
|
120
|
+
current.offset = swipeOffset(toward);
|
|
121
|
+
if (current.event.pointerType === "mouse" && selectedSincePress(doc, current.selection)) doc.getSelection()?.removeAllRanges();
|
|
122
|
+
options.move(current.offset, swipeProgress(current.offset, current.extent), event);
|
|
123
|
+
};
|
|
124
|
+
const onMove = (event) => {
|
|
125
|
+
const current = press;
|
|
126
|
+
if (current === null || event.pointerId !== current.event.pointerId) return;
|
|
127
|
+
if (!current.dragging) {
|
|
128
|
+
const verdict = classifyPress(event.clientX - current.event.clientX, event.clientY - current.event.clientY, current.direction);
|
|
129
|
+
if (verdict === "wait") return;
|
|
130
|
+
if (verdict === "drop" || !tryStart(current, event)) {
|
|
131
|
+
clear();
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
follow(current, event);
|
|
136
|
+
};
|
|
137
|
+
const onUp = (event) => {
|
|
138
|
+
const current = press;
|
|
139
|
+
if (current === null || event.pointerId !== current.event.pointerId) return;
|
|
140
|
+
if (!current.dragging) {
|
|
141
|
+
clear();
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
follow(current, event);
|
|
145
|
+
const velocity = releaseVelocity(current.samples);
|
|
146
|
+
finish(releaseOutcome(current.offset, current.extent, velocity), event);
|
|
147
|
+
};
|
|
148
|
+
const onCancel = (event) => {
|
|
149
|
+
if (press === null || event.pointerId !== press.event.pointerId) return;
|
|
150
|
+
finish("cancel", event);
|
|
151
|
+
};
|
|
152
|
+
const onLostCapture = (event) => {
|
|
153
|
+
if (press === null || event.pointerId !== press.event.pointerId) return;
|
|
154
|
+
finish("cancel", event);
|
|
155
|
+
};
|
|
156
|
+
element.addEventListener("pointerdown", onDown, true);
|
|
157
|
+
return {
|
|
158
|
+
dragging: () => press?.dragging ?? false,
|
|
159
|
+
cancel: clear,
|
|
160
|
+
dispose: () => {
|
|
161
|
+
clear();
|
|
162
|
+
element.removeEventListener("pointerdown", onDown, true);
|
|
163
|
+
}
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
//#endregion
|
|
167
|
+
export { trackSwipe };
|
|
168
|
+
|
|
169
|
+
//# sourceMappingURL=swipe.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"swipe.mjs","names":[],"sources":["../../src/internal/swipe.ts"],"sourcesContent":["// The swipe tracker (design/components/drawer.md 4.1, 9): Pointer Events bookkeeping for a drag\n// of an element toward one of its edges, for mouse, pen and touch alike. It knows nothing of\n// dialogs: the caller says which presses are candidates, which way the edge is and how far it\n// is, and gets `start`, `move(offset)` and `end` callbacks. Drawer uses it; Toast's reserved\n// swipe (toast.md 9.2) is meant to. No directive: DOM listeners only (conventions 7.1).\nimport { capturePointer } from \"./pointer-capture.js\";\nimport {\n classifyPress,\n releaseOutcome,\n releaseVelocity,\n swipeOffset,\n swipeProgress,\n towardEdge,\n} from \"./swipe-arithmetic.js\";\nimport type { SwipeDirection, SwipeSample } from \"./swipe-arithmetic.js\";\n\n/** How a gesture that started ended. */\nexport interface SwipeEnd {\n /**\n * `\"dismiss\"`: released past the threshold or with a flick toward the edge. `\"return\"`:\n * released short of it, or moving back. `\"cancel\"`: the browser took the pointer\n * (`pointercancel`), the capture was lost, or another primary press came.\n */\n readonly outcome: \"dismiss\" | \"return\" | \"cancel\";\n /** The `pointerup`, the `pointercancel` or `lostpointercapture`, or the new press. */\n readonly event: Event;\n /** The offset reached, px. */\n readonly offset: number;\n /** The extent measured at the start, px. */\n readonly extent: number;\n}\n\nexport interface SwipeTrackerOptions {\n /**\n * Whether a primary-button press can become a swipe, at the `pointerdown` (capture phase on\n * the element). Return the direction of the edge, or `null` for a press that is not a\n * candidate.\n */\n readonly press: (event: PointerEvent) => SwipeDirection | null;\n /**\n * The distance (px) that takes the element fully off its edge, measured once when the drag\n * starts, before the first `move`.\n */\n readonly extent: () => number;\n /** The drag started (the pointer is captured); `move` follows at once with the first offset. */\n readonly start: (event: PointerEvent) => void;\n /** The offset toward the edge (px, never below 0) and its fraction of the extent. */\n readonly move: (offset: number, progress: number, event: PointerEvent) => void;\n /** The drag ended. Not called for `cancel()` or `dispose()`. */\n readonly end: (end: SwipeEnd) => void;\n}\n\nexport interface SwipeTracker {\n /** Whether a drag is in progress (between `start` and `end`). */\n readonly dragging: () => boolean;\n /** Drop the press or the drag without calling `end` (the caller ends it its own way). */\n readonly cancel: () => void;\n /** Remove every listener. */\n readonly dispose: () => void;\n}\n\ninterface Press {\n readonly event: PointerEvent;\n readonly direction: SwipeDirection;\n readonly selection: SelectionSnapshot | null;\n /** Another element took the pointer's capture after the press (a slider thumb, a map). */\n capturedElsewhere: boolean;\n dragging: boolean;\n extent: number;\n offset: number;\n samples: SwipeSample[];\n}\n\ninterface SelectionSnapshot {\n readonly anchorNode: Node | null;\n readonly anchorOffset: number;\n readonly focusNode: Node | null;\n readonly focusOffset: number;\n}\n\n/** The document's selection when it is not collapsed, else `null`. */\nfunction selectionOf(doc: Document): SelectionSnapshot | null {\n const selection = doc.getSelection();\n if (selection === null || selection.isCollapsed) return null;\n const { anchorNode, anchorOffset, focusNode, focusOffset } = selection;\n return { anchorNode, anchorOffset, focusNode, focusOffset };\n}\n\n/** Whether the press made a text selection: one exists now and it is not the one it found. */\nfunction selectedSincePress(doc: Document, before: SelectionSnapshot | null): boolean {\n const now = selectionOf(doc);\n if (now === null) return false;\n return (\n before === null ||\n now.anchorNode !== before.anchorNode ||\n now.anchorOffset !== before.anchorOffset ||\n now.focusNode !== before.focusNode ||\n now.focusOffset !== before.focusOffset\n );\n}\n\n/**\n * Tracks swipes on `element`. A primary press the caller accepts is only recorded: no capture,\n * no `preventDefault()`, so a tap, a click and a text selection are untouched. When it has\n * moved `SWIPE_SLOP` px, more along the axis than across and toward the edge, it becomes a drag\n * (the pointer is captured on `element`) unless the press's `pointerdown` was\n * `defaultPrevented` (read then, so a handler that ran after the capture-phase listener\n * counts), another element took the pointer's capture, or a mouse press made a text selection.\n * A first move in another direction drops the press.\n */\nexport function trackSwipe(element: HTMLElement, options: SwipeTrackerOptions): SwipeTracker {\n const doc = element.ownerDocument;\n let press: Press | null = null;\n\n const detachPress = (): void => {\n doc.removeEventListener(\"pointermove\", onMove, true);\n doc.removeEventListener(\"pointerup\", onUp, true);\n doc.removeEventListener(\"pointercancel\", onCancel, true);\n doc.removeEventListener(\"gotpointercapture\", onGotCapture, true);\n element.removeEventListener(\"lostpointercapture\", onLostCapture);\n };\n\n /** Forget the press; release the capture of a drag that did not end with the button. */\n const clear = (): void => {\n const current = press;\n press = null;\n detachPress();\n if (current?.dragging) {\n const id = current.event.pointerId;\n try {\n if (element.hasPointerCapture(id)) element.releasePointerCapture(id);\n } catch {\n // Not an active pointer any more.\n }\n }\n };\n\n const finish = (outcome: SwipeEnd[\"outcome\"], event: Event): void => {\n const current = press;\n if (current === null || !current.dragging) {\n clear();\n return;\n }\n const { offset, extent } = current;\n clear();\n options.end({ outcome, event, offset, extent });\n };\n\n const onDown = (event: PointerEvent): void => {\n if (press !== null) {\n // A second primary press (another pointer type) ends what the first one did.\n if (event.isPrimary && event.pointerId !== press.event.pointerId) finish(\"cancel\", event);\n else return;\n }\n if (!event.isPrimary || event.button !== 0) return;\n const direction = options.press(event);\n if (direction === null) return;\n press = {\n event,\n direction,\n selection: event.pointerType === \"mouse\" ? selectionOf(doc) : null,\n capturedElsewhere: false,\n dragging: false,\n extent: 0,\n offset: 0,\n // The motion starts at the press: an engine may coalesce a flick's moves into the one\n // `pointermove` that starts the drag, and the velocity must still see the whole flick.\n samples: [{ time: event.timeStamp, toward: 0 }],\n };\n doc.addEventListener(\"pointermove\", onMove, true);\n doc.addEventListener(\"pointerup\", onUp, true);\n doc.addEventListener(\"pointercancel\", onCancel, true);\n doc.addEventListener(\"gotpointercapture\", onGotCapture, true);\n };\n\n const onGotCapture = (event: Event): void => {\n const current = press;\n if (current === null || current.dragging) return;\n if ((event as PointerEvent).pointerId !== current.event.pointerId) return;\n const target = event.target;\n if (target === element) return;\n // Touch and pen capture the pointer to the pressed element implicitly (Pointer Events 3).\n if (current.event.pointerType !== \"mouse\" && target === current.event.target) return;\n current.capturedElsewhere = true;\n };\n\n /** The press becomes a drag, or is dropped (`false`). */\n const tryStart = (current: Press, event: PointerEvent): boolean => {\n if (current.event.defaultPrevented || current.capturedElsewhere) return false;\n if (current.event.pointerType === \"mouse\" && selectedSincePress(doc, current.selection)) {\n return false;\n }\n if (!capturePointer(element, current.event.pointerId)) return false;\n current.dragging = true;\n current.extent = options.extent();\n element.addEventListener(\"lostpointercapture\", onLostCapture);\n options.start(event);\n return true;\n };\n\n const follow = (current: Press, event: PointerEvent): void => {\n const toward = towardEdge(\n event.clientX - current.event.clientX,\n event.clientY - current.event.clientY,\n current.direction,\n );\n current.samples.push({ time: event.timeStamp, toward });\n current.offset = swipeOffset(toward);\n // Firefox keeps extending the text selection of the press under pointer capture: a drag\n // moves, it does not select (Chromium selects nothing once captured).\n if (current.event.pointerType === \"mouse\" && selectedSincePress(doc, current.selection)) {\n doc.getSelection()?.removeAllRanges();\n }\n options.move(current.offset, swipeProgress(current.offset, current.extent), event);\n };\n\n const onMove = (event: PointerEvent): void => {\n const current = press;\n if (current === null || event.pointerId !== current.event.pointerId) return;\n if (!current.dragging) {\n const verdict = classifyPress(\n event.clientX - current.event.clientX,\n event.clientY - current.event.clientY,\n current.direction,\n );\n if (verdict === \"wait\") return;\n if (verdict === \"drop\" || !tryStart(current, event)) {\n clear();\n return;\n }\n }\n follow(current, event);\n };\n\n const onUp = (event: PointerEvent): void => {\n const current = press;\n if (current === null || event.pointerId !== current.event.pointerId) return;\n if (!current.dragging) {\n clear();\n return;\n }\n // The release position is the gesture's last (an engine may coalesce the final move into\n // the `pointerup`).\n follow(current, event);\n const velocity = releaseVelocity(current.samples);\n finish(releaseOutcome(current.offset, current.extent, velocity), event);\n };\n\n const onCancel = (event: PointerEvent): void => {\n if (press === null || event.pointerId !== press.event.pointerId) return;\n finish(\"cancel\", event);\n };\n\n const onLostCapture = (event: PointerEvent): void => {\n if (press === null || event.pointerId !== press.event.pointerId) return;\n // The `pointerup` comes first (it releases the capture after its dispatch), so this is a\n // capture taken away mid-drag.\n finish(\"cancel\", event);\n };\n\n element.addEventListener(\"pointerdown\", onDown, true);\n\n return {\n dragging: () => press?.dragging ?? false,\n cancel: clear,\n dispose: () => {\n clear();\n element.removeEventListener(\"pointerdown\", onDown, true);\n },\n };\n}\n"],"mappings":";;;;AAiFA,SAAS,YAAY,KAAyC;CAC5D,MAAM,YAAY,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AAe,QAAQ,IAAI;CAEpD,OAAO;EACL,gBAAgB,OAAO,YAAY;EACnC,QAAQ;EACR,eAAe;GACb,MAAM;GACN,QAAQ,oBAAoB,eAAe,QAAQ,IAAI;EACzD;CACF;AACF"}
|
|
@@ -3,9 +3,9 @@ import { dataAttr } from "../internal/data-attr.mjs";
|
|
|
3
3
|
import { useDevWarning } from "../internal/use-dev-warning.mjs";
|
|
4
4
|
import { resolveStateValue } from "../internal/render-element.mjs";
|
|
5
5
|
import { useRender } from "../internal/use-render.mjs";
|
|
6
|
+
import { capturePointer } from "../internal/pointer-capture.mjs";
|
|
6
7
|
import { MenuRegionContext, claimPress, isPressClaimed, markHandled, useMenuContext } from "./menu-context.mjs";
|
|
7
8
|
import { isEditableTarget } from "./menu-dom.mjs";
|
|
8
|
-
import { capturePointer } from "../internal/pointer-capture.mjs";
|
|
9
9
|
import { armClickSwallow, guardTouch, isTouchLike, startDrag } from "./menu-gestures.mjs";
|
|
10
10
|
import { useCallback, useEffect, useRef } from "react";
|
|
11
11
|
import { jsx } from "react/jsx-runtime";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"menu-popup.d.mts","names":[],"sources":["../../src/menu/menu-popup.tsx"],"mappings":";;;;;
|
|
1
|
+
{"version":3,"file":"menu-popup.d.mts","names":[],"sources":["../../src/menu/menu-popup.tsx"],"mappings":";;;;;YAwCY,WAAW;;;;;YAKX,YAAY;;;;;iBAMP;;WAEN;;;;;;WAMA,MAAM;;WAEN,OAAO;;WAEP;;;;;WAKA;;;;;;;iBAQM,uBAAuB,KACtC;;;;;;;;;;;;;EA8BA,OAAO;;;;;;;EAOP,QAAQ;;;;;;;;EAQR;;;;;;;;;EASA;;;;;;;;;;EAUA,aAAa;;EAEb,YAAY,+BAA+B;;EAE3C,QAAQ,WAAW,2BAA2B;;EAE9C,WAAW,WAAW,WAAW;;EAEjC,SAAS,WAAW,8BAA8B;;;;;;;;;;;;;;;;;;;;;;;;;;wBAmCpC,YACd,MAAM,UACN,OACA,aACA,yBACA,YACA,WACA,OACA,UACA,WACG,QACF,iBAAc;yBAXD"}
|
package/dist/menu/menu-popup.mjs
CHANGED
|
@@ -12,9 +12,10 @@ import { CSPContext } from "../internal/csp-context.mjs";
|
|
|
12
12
|
import { FSUI_PRECEDENCE } from "../internal/shipped-styles.mjs";
|
|
13
13
|
import { listenInvokerPresses } from "../internal/overlay/invokers.mjs";
|
|
14
14
|
import { usePopoverPopup } from "../internal/overlay/use-popover-popup.mjs";
|
|
15
|
-
import { MenuListContext, claimPress, useMenuContext } from "./menu-context.mjs";
|
|
16
|
-
import { edgeItem } from "./menu-dom.mjs";
|
|
17
15
|
import { capturePointer } from "../internal/pointer-capture.mjs";
|
|
16
|
+
import { MenuListContext, claimPress, useMenuContext } from "./menu-context.mjs";
|
|
17
|
+
import { edgeItem, hasModifier } from "./menu-dom.mjs";
|
|
18
|
+
import { MenubarContext, useMenubarContext } from "../internal/menubar-context.mjs";
|
|
18
19
|
import { scheduleHoverClose } from "./menu-hover.mjs";
|
|
19
20
|
import { listenOutside } from "./menu-outside.mjs";
|
|
20
21
|
import { MENU_POINT_HREF, MENU_POINT_RULES, pointStyle } from "./menu-point.mjs";
|
|
@@ -67,7 +68,27 @@ function MenuPopup({ side: sideProp, align = "start", keepMounted, experimental_
|
|
|
67
68
|
});
|
|
68
69
|
const { side, align: resolvedAlign, ref: placementRef } = placement;
|
|
69
70
|
const nativeFocusgroup = useNativeFocusgroup(experimental_focusgroup);
|
|
70
|
-
const { onKeyDown, typingAhead } = useMenuKeyboard(menu, nativeFocusgroup);
|
|
71
|
+
const { onKeyDown: onMenuKeyDown, typingAhead } = useMenuKeyboard(menu, nativeFocusgroup);
|
|
72
|
+
const bar = useMenubarContext();
|
|
73
|
+
const onKeyDown = (event) => {
|
|
74
|
+
onMenuKeyDown(event);
|
|
75
|
+
if (bar === null || event.defaultPrevented || hasModifier(event)) return;
|
|
76
|
+
const popup = event.currentTarget;
|
|
77
|
+
const target = event.target;
|
|
78
|
+
if (!target.matches("[role=\"menuitem\"], [role=\"menuitemcheckbox\"], [role=\"menuitemradio\"]") || !popup.contains(target)) return;
|
|
79
|
+
const rtl = bar.rtl();
|
|
80
|
+
let delta;
|
|
81
|
+
if (event.key === (rtl ? "ArrowLeft" : "ArrowRight")) {
|
|
82
|
+
if (target.hasAttribute("aria-haspopup")) return;
|
|
83
|
+
delta = 1;
|
|
84
|
+
} else if (event.key === (rtl ? "ArrowRight" : "ArrowLeft")) {
|
|
85
|
+
if (target.closest("[role=\"menu\"]") !== popup) return;
|
|
86
|
+
delta = -1;
|
|
87
|
+
} else return;
|
|
88
|
+
const trigger = popover.triggerRef.current;
|
|
89
|
+
if (trigger === null) return;
|
|
90
|
+
if (bar.step(trigger, delta, event.nativeEvent)) event.preventDefault();
|
|
91
|
+
};
|
|
71
92
|
const { setElement, visible, renderContent, reshow } = usePopoverPopup(popover, {
|
|
72
93
|
part: "Menu.Popup",
|
|
73
94
|
initialFocus: (popup) => {
|
|
@@ -170,10 +191,16 @@ function MenuPopup({ side: sideProp, align = "start", keepMounted, experimental_
|
|
|
170
191
|
nonce: csp?.nonce,
|
|
171
192
|
children: MENU_POINT_RULES
|
|
172
193
|
}) : null;
|
|
173
|
-
const content = (s) =>
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
194
|
+
const content = (s) => {
|
|
195
|
+
const list = /* @__PURE__ */ jsxs(MenuListContext, {
|
|
196
|
+
value: listContext,
|
|
197
|
+
children: [pointRules, renderContent(() => resolveStateValue(children, s))]
|
|
198
|
+
});
|
|
199
|
+
return bar === null ? list : /* @__PURE__ */ jsx(MenubarContext, {
|
|
200
|
+
value: null,
|
|
201
|
+
children: list
|
|
202
|
+
});
|
|
203
|
+
};
|
|
177
204
|
const element = useRender({
|
|
178
205
|
defaultElement: "div",
|
|
179
206
|
render,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"menu-popup.mjs","names":[],"sources":["../../src/menu/menu-popup.tsx"],"sourcesContent":["\"use client\";\nimport { use, useCallback, useLayoutEffect, useMemo, useRef } from \"react\";\nimport type {\n ComponentPropsWithRef,\n CSSProperties,\n FocusEvent,\n MouseEvent,\n PointerEvent,\n ReactNode,\n ViewTransitionClass,\n} from \"react\";\nimport type { AnchorAlign, AnchorSide } from \"../internal/overlay/anchor-position.js\";\nimport { CSPContext } from \"../internal/csp-context.js\";\nimport { listenInvokerPresses } from \"../internal/overlay/invokers.js\";\nimport { isPopoverOpen } from \"../internal/overlay/popover-open.js\";\nimport { capturePointer } from \"../internal/pointer-capture.js\";\nimport { FSUI_PRECEDENCE } from \"../internal/shipped-styles.js\";\nimport { useTransitionBoundary } from \"../internal/transition-boundary.js\";\nimport type { RenderProp, StateValue } from \"../internal/types.js\";\nimport { useElementCheck } from \"../internal/use-element-check.js\";\nimport { useLatest } from \"../internal/use-latest.js\";\nimport { useMergedRefs } from \"../internal/use-merged-refs.js\";\nimport { useNativeFocusgroup } from \"../internal/use-native-focusgroup.js\";\nimport { usePopoverPopup } from \"../internal/overlay/use-popover-popup.js\";\nimport { useAnchoredPlacement } from \"../internal/overlay/use-resolved-placement.js\";\nimport { resolveStateValue, useRender } from \"../internal/use-render.js\";\nimport type { DataAttributes } from \"../internal/use-render.js\";\nimport { claimPress, MenuListContext, useMenuContext } from \"./menu-context.js\";\nimport type { MenuListContextValue } from \"./menu-context.js\";\nimport { edgeItem } from \"./menu-dom.js\";\nimport { scheduleHoverClose } from \"./menu-hover.js\";\nimport { listenOutside } from \"./menu-outside.js\";\nimport { MENU_POINT_HREF, MENU_POINT_RULES, pointStyle } from \"./menu-point.js\";\nimport { useMenuKeyboard } from \"./use-menu-keyboard.js\";\n\nconst isDev = process.env.NODE_ENV !== \"production\";\n\n/** `inline-start` / `inline-end` follow the popup's `direction` (conventions 13.1). */\nexport type MenuSide = AnchorSide;\n/**\n * Alignment of the Popup along its side: inline-relative on a top / bottom side, the top / bottom\n * edges on the others.\n */\nexport type MenuAlign = AnchorAlign;\n\n/**\n * State of `Menu.Popup`, passed to the function forms of `className`, `style`, `children` and\n * `render`.\n */\nexport interface MenuPopupState {\n /** Committed open state. Read `:popover-open` for the DOM truth. */\n readonly open: boolean;\n /**\n * While shown: the physical side the browser placed the popup on (after any fallback flip;\n * conventions 13.2). Otherwise the `side` prop. `null` with `side={null}`, and while the menu\n * is placed at a point (`context`).\n */\n readonly side: MenuSide | null;\n /** While shown: the resolved alignment; otherwise the `align` prop. */\n readonly align: MenuAlign;\n /** This popup belongs to a submenu. */\n readonly submenu: boolean;\n /**\n * The current open came from a `Menu.ContextTrigger`: the popup is placed at the pointer, with\n * `--menu-point-x` / `--menu-point-y` set inline (`data-context`).\n */\n readonly context: boolean;\n}\n\n/**\n * Props of `Menu.Popup`.\n *\n * @see https://ui.funstack.work/components/menu\n */\nexport interface MenuPopupProps extends Omit<\n ComponentPropsWithRef<\"div\">,\n | \"id\"\n | \"popover\"\n | \"role\"\n | \"aria-labelledby\"\n | \"onKeyDown\"\n | \"onFocus\"\n | \"onBlur\"\n | \"onMouseDown\"\n | \"onContextMenu\"\n | \"onPointerEnter\"\n | \"onPointerLeave\"\n | \"onToggle\"\n | \"onBeforeToggle\"\n | \"className\"\n | \"style\"\n | \"children\"\n> {\n /**\n * Placement against the Trigger through inline `position-area`, with `position-try-fallbacks`\n * flipping it when it does not fit. A submenu's `\"inline-end\"` is the right of the item in LTR,\n * its left in RTL; its fallback is `flip-inline` only. `\"left\"` / `\"right\"` stay physical.\n * `null` emits no inline positioning (and no `data-side` / `data-align`): the stylesheet owns\n * placement. Ignored for an open from a\n * `Menu.ContextTrigger`, which is placed at the pointer; there `null` also opts out of the\n * inline point placement and the library's `@position-try` rules, leaving only\n * `--menu-point-x` / `--menu-point-y`.\n *\n * @defaultValue `\"bottom\"` for a top-level menu, `\"inline-end\"` for a submenu\n */\n side?: MenuSide | null;\n /**\n * Alignment along the side: inline-relative on a top / bottom side (mirrored under\n * `direction: rtl`), the top edges on the others. Ignored when `side` is `null`.\n *\n * @defaultValue `\"start\"` (both levels)\n */\n align?: MenuAlign;\n /**\n * `false` (default): the items are not rendered while the menu is closed; mounting them is part\n * of the opening transition, so items that suspend hold the open (and the Trigger pending)\n * until they are ready. `true`: they stay mounted inside `<Activity mode=\"hidden\">`.\n *\n * @defaultValue `false`\n */\n keepMounted?: boolean;\n /**\n * Experimental (Chromium 150+). Renders `focusgroup=\"menu wrap|nowrap\"` and, where the engine\n * implements `focusGroup`, lets the browser handle ArrowUp / ArrowDown / Home / End: items then\n * render no `tabindex` and the library's arrow-key handling steps aside. Typeahead, activation,\n * submenu keys and Tab stay in JS. No effect in other engines.\n *\n * @defaultValue `false`\n */\n experimental_focusgroup?: boolean;\n /**\n * Forwarded to the `<ViewTransition default>` around the popup element. Animates the opening\n * commit and every library-driven close (an item's activation, the Trigger, ArrowLeft, hover\n * leaving a submenu, controlled `open={false}`) in all engines; dismissals (Escape, a click\n * outside, Tab) animate with CSS only. Without it the part renders no `<ViewTransition>`.\n * While a view transition runs, the popup's CSS transitions are turned off for the moment of the\n * library's own show or hide (an inline `transition: none !important`, restored right after),\n * so that show or hide runs no CSS transition (a `@keyframes` animation is not cut).\n */\n transition?: ViewTransitionClass;\n /** Class name, or a function of the part's state that returns one. */\n className?: StateValue<string | undefined, MenuPopupState>;\n /** Inline style, or a function of the part's state that returns one. */\n style?: StateValue<CSSProperties | undefined, MenuPopupState>;\n /** Content, or a function of the part's state. */\n children?: StateValue<ReactNode, MenuPopupState>;\n /** Should render a `<div>`; a `<dialog>` would run the dialog focusing steps. */\n render?: RenderProp<ComponentPropsWithRef<\"div\">, MenuPopupState>;\n}\n\n/**\n * What a press may focus inside a popup: items, the popup itself, the consumer's controls.\n * Differs from the roving and Tooltip selectors on purpose: it asks \"does a press focus\n * something\", so any `input` counts (a hidden one is never pressed).\n */\nconst FOCUSABLE_SELECTOR =\n 'a[href], button, input, select, textarea, summary, [tabindex], [contenteditable]:not([contenteditable=\"false\"])';\n\n/**\n * The menu itself: `<div popover=\"auto\" role=\"menu\" aria-labelledby={trigger} tabindex=\"-1\">`,\n * placed against its Trigger with CSS Anchor Positioning. Owns the keyboard model (design 5):\n * ArrowUp / ArrowDown / Home / End move focus between items (or the browser does, with\n * `experimental_focusgroup` where supported), printable characters run typeahead, ArrowLeft\n * closes a submenu. The top-level popup closes the whole menu at once when focus leaves it (Tab);\n * a press on a button of the consumer's that names it (`popovertarget`, `commandfor`) moves no\n * focus, so that button's click closes the menu as `\"activate\"`.\n * Style it with `:popover-open`; it emits `data-side` / `data-align` but no `data-open`. While\n * shown, those are where the browser placed it (conventions 13.2), otherwise the requested\n * values.\n *\n * Owned keys (conventions 1.2): `id`, `popover`, `role`, `aria-labelledby` (token-merged),\n * `tabIndex`, `focusgroup` (with the flag), `onKeyDown`, `onBlur`, `onMouseDown` (a press on\n * non-item space keeps focus on the current item), `onContextMenu` (no native menu over this\n * one), `onPointerEnter` / `onPointerLeave`, `data-side` / `data-align` unless `side` is `null`\n * or the menu is placed at a point, and `data-context` for an open from a `Menu.ContextTrigger`.\n * Such an open is placed at the pointer: `--menu-point-x` / `--menu-point-y` inline and, unless\n * `side` is `null`, `top` and `left` (`right` for an RTL popup) at the point with the library's\n * `@position-try` fallbacks, whose rules it renders as a hoisted `<style>`. A top-level menu\n * closes at once on a right- or middle-click outside it.\n *\n * @see https://ui.funstack.work/components/menu\n */\nexport function MenuPopup({\n side: sideProp,\n align = \"start\",\n keepMounted,\n experimental_focusgroup = false,\n transition,\n className,\n style,\n children,\n render,\n ...rest\n}: MenuPopupProps) {\n const menu = useMenuContext(\"Menu.Popup\");\n const { popover, submenu, loop } = menu;\n const csp = use(CSPContext);\n // The listeners installed at the open read the placement of the latest commit (4.8).\n const latestPlacement = useLatest(menu.placement);\n // A submenu opens on the inline-end side of its item: the side ArrowRight (ArrowLeft in RTL)\n // points to.\n const sideOption = sideProp === undefined ? (submenu ? \"inline-end\" : \"bottom\") : sideProp;\n // A ContextTrigger's open is placed at the point; nothing is anchored (context-menu.md 3.3).\n const point = menu.placement.kind === \"point\" ? menu.placement : null;\n const requestedSide = point !== null ? null : sideOption;\n // Resolved while shown (conventions 13.2); idle for a point open, which has no side.\n const placement = useAnchoredPlacement({\n side: requestedSide,\n align,\n fallbacks: submenu ? \"flip-inline\" : undefined,\n });\n const { side, align: resolvedAlign, ref: placementRef } = placement;\n\n const nativeFocusgroup = useNativeFocusgroup(experimental_focusgroup);\n const { onKeyDown, typingAhead } = useMenuKeyboard(menu, nativeFocusgroup);\n\n const { setElement, visible, renderContent, reshow } = usePopoverPopup(popover, {\n part: \"Menu.Popup\",\n // Design 6.1: the first (or last) enabled item by open cause, nothing for a hover open, the\n // popup itself when there are no items.\n // A pointer open focuses without the focus ring where the engine can be told so.\n initialFocus: (popup) => {\n const { cause, pointer } = menu.takeOpenCause();\n if (cause === \"none\") return null;\n const element = edgeItem(popup, cause) ?? popup;\n return pointer ? { element, focusVisible: false } : element;\n },\n keepMounted,\n transition,\n // A point open nests through the region that opened it (context-menu.md 3.1).\n source: () => (point !== null ? point.source : popover.triggerRef.current),\n // The outside right- / middle-click listeners and the foreign invoker press guard of a\n // top-level menu.\n whileShown: submenu\n ? undefined\n : (element) => {\n const stopListening = listenOutside(element, menu, () => latestPlacement.current);\n const stopPresses = listenInvokerPresses(element);\n return () => {\n stopListening();\n stopPresses();\n };\n },\n });\n\n // A move (context-menu.md 4.3): the popup is shown and the placement changed since it was\n // shown (a new point, or a right-click in the region while a Trigger open is shown). Re-show\n // it so the respelled fallbacks place it afresh, the source is the region and the first item\n // is focused again; then capture the still-pressed pointer again, against the Firefox / WebKit\n // `pointerup` light dismiss. Runs after the hook's apply effect (declared after it).\n // Once the popup is not visible (hidden, exit animation over) and no open is intended or in\n // flight, a point placement goes back to anchored for the next open that is not a\n // ContextTrigger's: after a point open that was shown and closed, and after one that was\n // rejected or refused.\n const shownKey = useRef<number | \"anchor\" | null>(null);\n useLayoutEffect(() => {\n const element = popover.popupRef.current;\n if (element === null) return;\n const key = point !== null ? point.generation : \"anchor\";\n if (isPopoverOpen(element)) {\n if (shownKey.current !== null && shownKey.current !== key && reshow()) {\n capturePointer(element, point?.pointerId);\n }\n shownKey.current = key;\n } else {\n shownKey.current = null;\n if (!visible && point !== null && !popover.pending && !popover.intended()) {\n menu.resetPlacement(point.generation);\n }\n }\n });\n\n const checkElement = useElementCheck(\n isDev &&\n ((element) =>\n element.tagName === \"DIALOG\"\n ? \"Menu.Popup: rendered a <dialog>. Render a <div>: a <dialog popover> runs the dialog \" +\n \"focusing steps, which fight the menu's item focus.\"\n : null),\n );\n const pressRef = useCallback(\n (element: HTMLElement) => {\n checkElement?.(element);\n // A press inside a menu is never a long-press of a Menu.ContextTrigger around it.\n // Native, so it runs before React's root listener dispatches to the region.\n const onPointerDown = (event: Event) => claimPress(event);\n element.addEventListener(\"pointerdown\", onPointerDown);\n return () => element.removeEventListener(\"pointerdown\", onPointerDown);\n },\n [checkElement],\n );\n const ref = useMergedRefs(setElement, pressRef, placementRef);\n\n const listContext = useMemo<MenuListContextValue>(\n () => ({ menu, nativeFocusgroup, typingAhead }),\n [menu, nativeFocusgroup, typingAhead],\n );\n\n const state: MenuPopupState = {\n open: popover.committed,\n side,\n align: resolvedAlign,\n submenu,\n context: point !== null,\n };\n\n // Tab / Shift+Tab or any focus move out of the tree closes the whole stack at once (design\n // 2.2): submenus are DOM descendants of the top-level popup, the Trigger is outside on purpose.\n // A null `relatedTarget` (window blur, a removed element) closes nothing.\n const onBlur = (event: FocusEvent<HTMLElement>) => {\n if (submenu) return;\n const popup = event.currentTarget;\n const next = event.relatedTarget;\n if (!(next instanceof Node) || popup.contains(next)) return;\n if (isPopoverOpen(popup)) popup.hidePopover();\n };\n\n // A press on non-item space (padding, a Separator, a GroupLabel) would focus the popup itself\n // (`tabindex=\"-1\"`) and take focus off the current item; keep it where it is (the\n // pointer-focus model of design 6.2). Focusable content of the consumer's (a text field) still\n // takes focus.\n const onMouseDown = (event: MouseEvent<HTMLElement>) => {\n if (event.button !== 0) return;\n const target = event.target as Element;\n const focusable = target.closest(FOCUSABLE_SELECTOR);\n if (focusable === null || focusable.getAttribute(\"role\") === \"menu\") event.preventDefault();\n };\n\n const libraryProps: ComponentPropsWithRef<\"div\"> & DataAttributes = {\n id: popover.ids.popup,\n popover: \"auto\",\n role: \"menu\",\n \"aria-labelledby\": menu.triggerId,\n // The popup itself takes focus as the last resort when a menu has no items.\n tabIndex: -1,\n ...(experimental_focusgroup && { focusgroup: `menu ${loop ? \"wrap\" : \"nowrap\"}` }),\n onKeyDown,\n onBlur,\n onMouseDown,\n // No native menu over the custom one. The popup is a sibling of any ContextTrigger, so this\n // event never reaches a region as a move; an outer region sees it prevented and stays quiet.\n onContextMenu: (event: MouseEvent<HTMLElement>) => {\n event.preventDefault();\n },\n ...(submenu && {\n onPointerEnter: (event: PointerEvent<HTMLElement>) => {\n if (event.pointerType !== \"touch\") menu.timers.cancelClose();\n },\n onPointerLeave: (event: PointerEvent<HTMLElement>) => {\n if (event.pointerType !== \"touch\") scheduleHoverClose(menu, event.nativeEvent);\n },\n }),\n ...placement.dataAttributes,\n \"data-context\": point !== null ? \"\" : undefined,\n };\n\n // The shipped `@position-try` rules (conventions 12): hoisted into <head> and deduplicated by\n // React, rendered only by a point open that does not opt out with `side={null}`, with the\n // `<CSPProvider>` nonce for a nonce-based `style-src`.\n const pointRules =\n point !== null && sideOption !== null ? (\n <style href={MENU_POINT_HREF} precedence={FSUI_PRECEDENCE} nonce={csp?.nonce}>\n {MENU_POINT_RULES}\n </style>\n ) : null;\n\n const content = (s: MenuPopupState): ReactNode => (\n <MenuListContext value={listContext}>\n {pointRules}\n {renderContent(() => resolveStateValue(children, s))}\n </MenuListContext>\n );\n\n const element = useRender<ComponentPropsWithRef<\"div\">, MenuPopupState>({\n defaultElement: \"div\",\n render,\n state,\n className,\n // The inline placement sits under the consumer's style: the consumer wins.\n style:\n point !== null\n ? (s) => ({ ...pointStyle(point, sideOption === null), ...resolveStateValue(style, s) })\n : placement.style(style),\n children: content,\n props: rest,\n libraryProps,\n ref,\n });\n\n return useTransitionBoundary(\"Menu.Popup\", transition, element);\n}\n\nMenuPopup.displayName = \"MenuPopup\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAmCA,MAAM,QAAQ,QAAQ,IAAI,aAAa;;;;;;AAwHvC,MAAM,qBACJ;;;;;;;;;;;;;;;;;;;;;;;;;AA0BF,SAAgB,UAAU,EACxB,MAAM,UACN,QAAQ,SACR,aACA,0BAA0B,OAC1B,YACA,WACA,OACA,UACA,QACA,GAAG,QACc;CACjB,MAAM,OAAO,eAAe,YAAY;CACxC,MAAM,EAAE,SAAS,SAAS,SAAS;CACnC,MAAM,MAAM,IAAI,UAAU;CAE1B,MAAM,kBAAkB,UAAU,KAAK,SAAS;CAGhD,MAAM,aAAa,aAAa,KAAA,IAAa,UAAU,eAAe,WAAY;CAElF,MAAM,QAAQ,KAAK,UAAU,SAAS,UAAU,KAAK,YAAY;CAGjE,MAAM,YAAY,qBAAqB;EACrC,MAHoB,UAAU,OAAO,OAAO;EAI5C;EACA,WAAW,UAAU,gBAAgB,KAAA;CACvC,CAAC;CACD,MAAM,EAAE,MAAM,OAAO,eAAe,KAAK,iBAAiB;CAE1D,MAAM,mBAAmB,oBAAoB,uBAAuB;CACpE,MAAM,EAAE,WAAW,gBAAgB,gBAAgB,MAAM,gBAAgB;CAEzE,MAAM,EAAE,YAAY,SAAS,eAAe,WAAW,gBAAgB,SAAS;EAC9E,MAAM;EAIN,eAAe,UAAU;GACvB,MAAM,EAAE,OAAO,YAAY,KAAK,cAAc;GAC9C,IAAI,UAAU,QAAQ,OAAO;GAC7B,MAAM,UAAU,SAAS,OAAO,KAAK,KAAK;GAC1C,OAAO,UAAU;IAAE;IAAS,cAAc;GAAM,IAAI;EACtD;EACA;EACA;EAEA,cAAe,UAAU,OAAO,MAAM,SAAS,QAAQ,WAAW;EAGlE,YAAY,UACR,KAAA,KACC,YAAY;GACX,MAAM,gBAAgB,cAAc,SAAS,YAA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I,MAAM,WAAW,GAAG;EAExB,MAAM,YADS,MAAM,OACI,QAAQ,kBAAkB;EACnD,IAAI,cAAc,QAAQ,UAAU,aAAa,MAAM,MAAM,QAAQ,MAAM,eAAe;CAC5F;CAEA,MAAM,eAA8D;EAClE,IAAI,QAAQ,IAAI;EAChB,SAAS;EACT,MAAM;EACN,mBAAmB,KAAK;EAExB,UAAU;EACV,GAAI,2BAA2B,EAAE,YAAY,QAAQ,OAAO,SAAS,WAAW;EAChF;EACA;EACA;EAGA,gBAAgB,UAAmC;GACjD,MAAM,eAAe;EACvB;EACA,GAAI,WAAW;GACb,iBAAiB,UAAqC;IACpD,IAAI,MAAM,gBAAgB,SAAS,KAAK,OAAO,YAAY;GAC7D;GACA,iBAAiB,UAAqC;IACpD,IAAI,MAAM,gBAAgB,SAAS,mBAAmB,MAAM,MAAM,WAAW;GAC/E;EACF;EACA,GAAG,UAAU;EACb,gBAAgB,UAAU,OAAO,KAAK,KAAA;CACxC;CAKA,MAAM,aACJ,UAAU,QAAQ,eAAe,OAC/B,oBAAC,SAAD;EAAO,MAAM;EAAiB,YAAY;EAAiB,OAAO,KAAK;EACpE,UAAA;CACI,CAAA,IACL;CAEN,MAAM,WAAW,MACf,qBAAC,iBAAD;EAAiB,OAAO;EAAxB,UAAA,CACG,YACA,oBAAoB,kBAAkB,UAAU,CAAC,CAAC,CACpC;;CAGnB,MAAM,UAAU,UAAwD;EACtE,gBAAgB;EAChB;EACA;EACA;EAEA,OACE,UAAU,QACL,OAAO;GAAE,GAAG,WAAW,OAAO,eAAe,IAAI;GAAG,GAAG,kBAAkB,OAAO,CAAC;EAAE,KACpF,UAAU,MAAM,KAAK;EAC3B,UAAU;EACV,OAAO;EACP;EACA;CACF,CAAC;CAED,OAAO,sBAAsB,cAAc,YAAY,OAAO;AAChE;AAEA,UAAU,cAAc"}
|
|
1
|
+
{"version":3,"file":"menu-popup.mjs","names":[],"sources":["../../src/menu/menu-popup.tsx"],"sourcesContent":["\"use client\";\nimport { use, useCallback, useLayoutEffect, useMemo, useRef } from \"react\";\nimport type {\n ComponentPropsWithRef,\n CSSProperties,\n FocusEvent,\n KeyboardEvent,\n MouseEvent,\n PointerEvent,\n ReactNode,\n ViewTransitionClass,\n} from \"react\";\nimport type { AnchorAlign, AnchorSide } from \"../internal/overlay/anchor-position.js\";\nimport { CSPContext } from \"../internal/csp-context.js\";\nimport { MenubarContext, useMenubarContext } from \"../internal/menubar-context.js\";\nimport { listenInvokerPresses } from \"../internal/overlay/invokers.js\";\nimport { isPopoverOpen } from \"../internal/overlay/popover-open.js\";\nimport { capturePointer } from \"../internal/pointer-capture.js\";\nimport { FSUI_PRECEDENCE } from \"../internal/shipped-styles.js\";\nimport { useTransitionBoundary } from \"../internal/transition-boundary.js\";\nimport type { RenderProp, StateValue } from \"../internal/types.js\";\nimport { useElementCheck } from \"../internal/use-element-check.js\";\nimport { useLatest } from \"../internal/use-latest.js\";\nimport { useMergedRefs } from \"../internal/use-merged-refs.js\";\nimport { useNativeFocusgroup } from \"../internal/use-native-focusgroup.js\";\nimport { usePopoverPopup } from \"../internal/overlay/use-popover-popup.js\";\nimport { useAnchoredPlacement } from \"../internal/overlay/use-resolved-placement.js\";\nimport { resolveStateValue, useRender } from \"../internal/use-render.js\";\nimport type { DataAttributes } from \"../internal/use-render.js\";\nimport { claimPress, MenuListContext, useMenuContext } from \"./menu-context.js\";\nimport type { MenuListContextValue } from \"./menu-context.js\";\nimport { edgeItem, hasModifier, ITEM_SELECTOR } from \"./menu-dom.js\";\nimport { scheduleHoverClose } from \"./menu-hover.js\";\nimport { listenOutside } from \"./menu-outside.js\";\nimport { MENU_POINT_HREF, MENU_POINT_RULES, pointStyle } from \"./menu-point.js\";\nimport { useMenuKeyboard } from \"./use-menu-keyboard.js\";\n\nconst isDev = process.env.NODE_ENV !== \"production\";\n\n/** `inline-start` / `inline-end` follow the popup's `direction` (conventions 13.1). */\nexport type MenuSide = AnchorSide;\n/**\n * Alignment of the Popup along its side: inline-relative on a top / bottom side, the top / bottom\n * edges on the others.\n */\nexport type MenuAlign = AnchorAlign;\n\n/**\n * State of `Menu.Popup`, passed to the function forms of `className`, `style`, `children` and\n * `render`.\n */\nexport interface MenuPopupState {\n /** Committed open state. Read `:popover-open` for the DOM truth. */\n readonly open: boolean;\n /**\n * While shown: the physical side the browser placed the popup on (after any fallback flip;\n * conventions 13.2). Otherwise the `side` prop. `null` with `side={null}`, and while the menu\n * is placed at a point (`context`).\n */\n readonly side: MenuSide | null;\n /** While shown: the resolved alignment; otherwise the `align` prop. */\n readonly align: MenuAlign;\n /** This popup belongs to a submenu. */\n readonly submenu: boolean;\n /**\n * The current open came from a `Menu.ContextTrigger`: the popup is placed at the pointer, with\n * `--menu-point-x` / `--menu-point-y` set inline (`data-context`).\n */\n readonly context: boolean;\n}\n\n/**\n * Props of `Menu.Popup`.\n *\n * @see https://ui.funstack.work/components/menu\n */\nexport interface MenuPopupProps extends Omit<\n ComponentPropsWithRef<\"div\">,\n | \"id\"\n | \"popover\"\n | \"role\"\n | \"aria-labelledby\"\n | \"onKeyDown\"\n | \"onFocus\"\n | \"onBlur\"\n | \"onMouseDown\"\n | \"onContextMenu\"\n | \"onPointerEnter\"\n | \"onPointerLeave\"\n | \"onToggle\"\n | \"onBeforeToggle\"\n | \"className\"\n | \"style\"\n | \"children\"\n> {\n /**\n * Placement against the Trigger through inline `position-area`, with `position-try-fallbacks`\n * flipping it when it does not fit. A submenu's `\"inline-end\"` is the right of the item in LTR,\n * its left in RTL; its fallback is `flip-inline` only. `\"left\"` / `\"right\"` stay physical.\n * `null` emits no inline positioning (and no `data-side` / `data-align`): the stylesheet owns\n * placement. Ignored for an open from a\n * `Menu.ContextTrigger`, which is placed at the pointer; there `null` also opts out of the\n * inline point placement and the library's `@position-try` rules, leaving only\n * `--menu-point-x` / `--menu-point-y`.\n *\n * @defaultValue `\"bottom\"` for a top-level menu, `\"inline-end\"` for a submenu\n */\n side?: MenuSide | null;\n /**\n * Alignment along the side: inline-relative on a top / bottom side (mirrored under\n * `direction: rtl`), the top edges on the others. Ignored when `side` is `null`.\n *\n * @defaultValue `\"start\"` (both levels)\n */\n align?: MenuAlign;\n /**\n * `false` (default): the items are not rendered while the menu is closed; mounting them is part\n * of the opening transition, so items that suspend hold the open (and the Trigger pending)\n * until they are ready. `true`: they stay mounted inside `<Activity mode=\"hidden\">`.\n *\n * @defaultValue `false`\n */\n keepMounted?: boolean;\n /**\n * Experimental (Chromium 150+). Renders `focusgroup=\"menu wrap|nowrap\"` and, where the engine\n * implements `focusGroup`, lets the browser handle ArrowUp / ArrowDown / Home / End: items then\n * render no `tabindex` and the library's arrow-key handling steps aside. Typeahead, activation,\n * submenu keys and Tab stay in JS. No effect in other engines.\n *\n * @defaultValue `false`\n */\n experimental_focusgroup?: boolean;\n /**\n * Forwarded to the `<ViewTransition default>` around the popup element. Animates the opening\n * commit and every library-driven close (an item's activation, the Trigger, ArrowLeft, hover\n * leaving a submenu, controlled `open={false}`) in all engines; dismissals (Escape, a click\n * outside, Tab) animate with CSS only. Without it the part renders no `<ViewTransition>`.\n * While a view transition runs, the popup's CSS transitions are turned off for the moment of the\n * library's own show or hide (an inline `transition: none !important`, restored right after),\n * so that show or hide runs no CSS transition (a `@keyframes` animation is not cut).\n */\n transition?: ViewTransitionClass;\n /** Class name, or a function of the part's state that returns one. */\n className?: StateValue<string | undefined, MenuPopupState>;\n /** Inline style, or a function of the part's state that returns one. */\n style?: StateValue<CSSProperties | undefined, MenuPopupState>;\n /** Content, or a function of the part's state. */\n children?: StateValue<ReactNode, MenuPopupState>;\n /** Should render a `<div>`; a `<dialog>` would run the dialog focusing steps. */\n render?: RenderProp<ComponentPropsWithRef<\"div\">, MenuPopupState>;\n}\n\n/**\n * What a press may focus inside a popup: items, the popup itself, the consumer's controls.\n * Differs from the roving and Tooltip selectors on purpose: it asks \"does a press focus\n * something\", so any `input` counts (a hidden one is never pressed).\n */\nconst FOCUSABLE_SELECTOR =\n 'a[href], button, input, select, textarea, summary, [tabindex], [contenteditable]:not([contenteditable=\"false\"])';\n\n/**\n * The menu itself: `<div popover=\"auto\" role=\"menu\" aria-labelledby={trigger} tabindex=\"-1\">`,\n * placed against its Trigger with CSS Anchor Positioning. Owns the keyboard model (design 5):\n * ArrowUp / ArrowDown / Home / End move focus between items (or the browser does, with\n * `experimental_focusgroup` where supported), printable characters run typeahead, ArrowLeft\n * closes a submenu. The top-level popup closes the whole menu at once when focus leaves it (Tab);\n * a press on a button of the consumer's that names it (`popovertarget`, `commandfor`) moves no\n * focus, so that button's click closes the menu as `\"activate\"`.\n * Style it with `:popover-open`; it emits `data-side` / `data-align` but no `data-open`. While\n * shown, those are where the browser placed it (conventions 13.2), otherwise the requested\n * values.\n *\n * Owned keys (conventions 1.2): `id`, `popover`, `role`, `aria-labelledby` (token-merged),\n * `tabIndex`, `focusgroup` (with the flag), `onKeyDown`, `onBlur`, `onMouseDown` (a press on\n * non-item space keeps focus on the current item), `onContextMenu` (no native menu over this\n * one), `onPointerEnter` / `onPointerLeave`, `data-side` / `data-align` unless `side` is `null`\n * or the menu is placed at a point, and `data-context` for an open from a `Menu.ContextTrigger`.\n * Such an open is placed at the pointer: `--menu-point-x` / `--menu-point-y` inline and, unless\n * `side` is `null`, `top` and `left` (`right` for an RTL popup) at the point with the library's\n * `@position-try` fallbacks, whose rules it renders as a hoisted `<style>`. A top-level menu\n * closes at once on a right- or middle-click outside it.\n *\n * @see https://ui.funstack.work/components/menu\n */\nexport function MenuPopup({\n side: sideProp,\n align = \"start\",\n keepMounted,\n experimental_focusgroup = false,\n transition,\n className,\n style,\n children,\n render,\n ...rest\n}: MenuPopupProps) {\n const menu = useMenuContext(\"Menu.Popup\");\n const { popover, submenu, loop } = menu;\n const csp = use(CSPContext);\n // The listeners installed at the open read the placement of the latest commit (4.8).\n const latestPlacement = useLatest(menu.placement);\n // A submenu opens on the inline-end side of its item: the side ArrowRight (ArrowLeft in RTL)\n // points to.\n const sideOption = sideProp === undefined ? (submenu ? \"inline-end\" : \"bottom\") : sideProp;\n // A ContextTrigger's open is placed at the point; nothing is anchored (context-menu.md 3.3).\n const point = menu.placement.kind === \"point\" ? menu.placement : null;\n const requestedSide = point !== null ? null : sideOption;\n // Resolved while shown (conventions 13.2); idle for a point open, which has no side.\n const placement = useAnchoredPlacement({\n side: requestedSide,\n align,\n fallbacks: submenu ? \"flip-inline\" : undefined,\n });\n const { side, align: resolvedAlign, ref: placementRef } = placement;\n\n const nativeFocusgroup = useNativeFocusgroup(experimental_focusgroup);\n const { onKeyDown: onMenuKeyDown, typingAhead } = useMenuKeyboard(menu, nativeFocusgroup);\n // A menu of a Menubar (design/components/menubar.md 2.3). `null` in a submenu: this Popup ends\n // the bar's context for its content.\n const bar = useMenubarContext();\n const onKeyDown = (event: KeyboardEvent<HTMLElement>) => {\n onMenuKeyDown(event);\n if (bar === null || event.defaultPrevented || hasModifier(event)) return;\n const popup = event.currentTarget;\n const target = event.target as Element;\n // An item at any depth: submenus are DOM descendants of this popup. A SubmenuTrigger keeps\n // its forward arrow (it opens the submenu; a disabled one does nothing).\n if (!target.matches(ITEM_SELECTOR) || !popup.contains(target)) return;\n const rtl = bar.rtl();\n let delta: 1 | -1;\n if (event.key === (rtl ? \"ArrowLeft\" : \"ArrowRight\")) {\n if (target.hasAttribute(\"aria-haspopup\")) return;\n delta = 1;\n } else if (event.key === (rtl ? \"ArrowRight\" : \"ArrowLeft\")) {\n // Only from the top level: in a submenu the backward arrow closes the submenu.\n if (target.closest('[role=\"menu\"]') !== popup) return;\n delta = -1;\n } else {\n return;\n }\n const trigger = popover.triggerRef.current;\n if (trigger === null) return;\n if (bar.step(trigger, delta, event.nativeEvent)) event.preventDefault();\n };\n\n const { setElement, visible, renderContent, reshow } = usePopoverPopup(popover, {\n part: \"Menu.Popup\",\n // Design 6.1: the first (or last) enabled item by open cause, nothing for a hover open, the\n // popup itself when there are no items.\n // A pointer open focuses without the focus ring where the engine can be told so.\n initialFocus: (popup) => {\n const { cause, pointer } = menu.takeOpenCause();\n if (cause === \"none\") return null;\n const element = edgeItem(popup, cause) ?? popup;\n return pointer ? { element, focusVisible: false } : element;\n },\n keepMounted,\n transition,\n // A point open nests through the region that opened it (context-menu.md 3.1).\n source: () => (point !== null ? point.source : popover.triggerRef.current),\n // The outside right- / middle-click listeners and the foreign invoker press guard of a\n // top-level menu.\n whileShown: submenu\n ? undefined\n : (element) => {\n const stopListening = listenOutside(element, menu, () => latestPlacement.current);\n const stopPresses = listenInvokerPresses(element);\n return () => {\n stopListening();\n stopPresses();\n };\n },\n });\n\n // A move (context-menu.md 4.3): the popup is shown and the placement changed since it was\n // shown (a new point, or a right-click in the region while a Trigger open is shown). Re-show\n // it so the respelled fallbacks place it afresh, the source is the region and the first item\n // is focused again; then capture the still-pressed pointer again, against the Firefox / WebKit\n // `pointerup` light dismiss. Runs after the hook's apply effect (declared after it).\n // Once the popup is not visible (hidden, exit animation over) and no open is intended or in\n // flight, a point placement goes back to anchored for the next open that is not a\n // ContextTrigger's: after a point open that was shown and closed, and after one that was\n // rejected or refused.\n const shownKey = useRef<number | \"anchor\" | null>(null);\n useLayoutEffect(() => {\n const element = popover.popupRef.current;\n if (element === null) return;\n const key = point !== null ? point.generation : \"anchor\";\n if (isPopoverOpen(element)) {\n if (shownKey.current !== null && shownKey.current !== key && reshow()) {\n capturePointer(element, point?.pointerId);\n }\n shownKey.current = key;\n } else {\n shownKey.current = null;\n if (!visible && point !== null && !popover.pending && !popover.intended()) {\n menu.resetPlacement(point.generation);\n }\n }\n });\n\n const checkElement = useElementCheck(\n isDev &&\n ((element) =>\n element.tagName === \"DIALOG\"\n ? \"Menu.Popup: rendered a <dialog>. Render a <div>: a <dialog popover> runs the dialog \" +\n \"focusing steps, which fight the menu's item focus.\"\n : null),\n );\n const pressRef = useCallback(\n (element: HTMLElement) => {\n checkElement?.(element);\n // A press inside a menu is never a long-press of a Menu.ContextTrigger around it.\n // Native, so it runs before React's root listener dispatches to the region.\n const onPointerDown = (event: Event) => claimPress(event);\n element.addEventListener(\"pointerdown\", onPointerDown);\n return () => element.removeEventListener(\"pointerdown\", onPointerDown);\n },\n [checkElement],\n );\n const ref = useMergedRefs(setElement, pressRef, placementRef);\n\n const listContext = useMemo<MenuListContextValue>(\n () => ({ menu, nativeFocusgroup, typingAhead }),\n [menu, nativeFocusgroup, typingAhead],\n );\n\n const state: MenuPopupState = {\n open: popover.committed,\n side,\n align: resolvedAlign,\n submenu,\n context: point !== null,\n };\n\n // Tab / Shift+Tab or any focus move out of the tree closes the whole stack at once (design\n // 2.2): submenus are DOM descendants of the top-level popup, the Trigger is outside on purpose.\n // A null `relatedTarget` (window blur, a removed element) closes nothing.\n const onBlur = (event: FocusEvent<HTMLElement>) => {\n if (submenu) return;\n const popup = event.currentTarget;\n const next = event.relatedTarget;\n if (!(next instanceof Node) || popup.contains(next)) return;\n if (isPopoverOpen(popup)) popup.hidePopover();\n };\n\n // A press on non-item space (padding, a Separator, a GroupLabel) would focus the popup itself\n // (`tabindex=\"-1\"`) and take focus off the current item; keep it where it is (the\n // pointer-focus model of design 6.2). Focusable content of the consumer's (a text field) still\n // takes focus.\n const onMouseDown = (event: MouseEvent<HTMLElement>) => {\n if (event.button !== 0) return;\n const target = event.target as Element;\n const focusable = target.closest(FOCUSABLE_SELECTOR);\n if (focusable === null || focusable.getAttribute(\"role\") === \"menu\") event.preventDefault();\n };\n\n const libraryProps: ComponentPropsWithRef<\"div\"> & DataAttributes = {\n id: popover.ids.popup,\n popover: \"auto\",\n role: \"menu\",\n \"aria-labelledby\": menu.triggerId,\n // The popup itself takes focus as the last resort when a menu has no items.\n tabIndex: -1,\n ...(experimental_focusgroup && { focusgroup: `menu ${loop ? \"wrap\" : \"nowrap\"}` }),\n onKeyDown,\n onBlur,\n onMouseDown,\n // No native menu over the custom one. The popup is a sibling of any ContextTrigger, so this\n // event never reaches a region as a move; an outer region sees it prevented and stays quiet.\n onContextMenu: (event: MouseEvent<HTMLElement>) => {\n event.preventDefault();\n },\n ...(submenu && {\n onPointerEnter: (event: PointerEvent<HTMLElement>) => {\n if (event.pointerType !== \"touch\") menu.timers.cancelClose();\n },\n onPointerLeave: (event: PointerEvent<HTMLElement>) => {\n if (event.pointerType !== \"touch\") scheduleHoverClose(menu, event.nativeEvent);\n },\n }),\n ...placement.dataAttributes,\n \"data-context\": point !== null ? \"\" : undefined,\n };\n\n // The shipped `@position-try` rules (conventions 12): hoisted into <head> and deduplicated by\n // React, rendered only by a point open that does not opt out with `side={null}`, with the\n // `<CSPProvider>` nonce for a nonce-based `style-src`.\n const pointRules =\n point !== null && sideOption !== null ? (\n <style href={MENU_POINT_HREF} precedence={FSUI_PRECEDENCE} nonce={csp?.nonce}>\n {MENU_POINT_RULES}\n </style>\n ) : null;\n\n const content = (s: MenuPopupState): ReactNode => {\n const list = (\n <MenuListContext value={listContext}>\n {pointRules}\n {renderContent(() => resolveStateValue(children, s))}\n </MenuListContext>\n );\n // The bar's context ends here: a Root inside is a submenu, not a menu of the bar.\n return bar === null ? list : <MenubarContext value={null}>{list}</MenubarContext>;\n };\n\n const element = useRender<ComponentPropsWithRef<\"div\">, MenuPopupState>({\n defaultElement: \"div\",\n render,\n state,\n className,\n // The inline placement sits under the consumer's style: the consumer wins.\n style:\n point !== null\n ? (s) => ({ ...pointStyle(point, sideOption === null), ...resolveStateValue(style, s) })\n : placement.style(style),\n children: content,\n props: rest,\n libraryProps,\n ref,\n });\n\n return useTransitionBoundary(\"Menu.Popup\", transition, element);\n}\n\nMenuPopup.displayName = \"MenuPopup\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,MAAM,QAAQ,QAAQ,IAAI,aAAa;;;;;;AAwHvC,MAAM,qBACJ;;;;;;;;;;;;;;;;;;;;;;;;;AA0BF,SAAgB,UAAU,EACxB,MAAM,UACN,QAAQ,SACR,aACA,0BAA0B,OAC1B,YACA,WACA,OACA,UACA,QACA,GAAG,QACc;CACjB,MAAM,OAAO,eAAe,YAAY;CACxC,MAAM,EAAE,SAAS,SAAS,SAAS;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;EAChB;EACA;EACA;EAEA,OACE,UAAU,QACL,OAAO;GAAE,GAAG,WAAW,OAAO,eAAe,IAAI;GAAG,GAAG,kBAAkB,OAAO,CAAC;EAAE,KACpF,UAAU,MAAM,KAAK;EAC3B,UAAU;EACV,OAAO;EACP;EACA;CACF,CAAC;CAED,OAAO,sBAAsB,cAAc,YAAY,OAAO;AAChE;AAEA,UAAU,cAAc"}
|
|
@@ -42,10 +42,17 @@ export interface MenuTriggerProps extends Omit<ComponentPropsWithRef<"button">,
|
|
|
42
42
|
* first / last item focused (inside a vertical `Toolbar.Root`: the inline-end arrow, with the
|
|
43
43
|
* first item focused).
|
|
44
44
|
*
|
|
45
|
+
* Inside a `Menubar` it is an item of the bar (design/components/menubar.md): `role="menuitem"`,
|
|
46
|
+
* no rendered `tabindex` (the bar writes it), and `disabled` as `aria-disabled="true"` (it stays
|
|
47
|
+
* focusable and never opens). Moving the pointer onto it while another menu of the bar is open
|
|
48
|
+
* switches to its menu.
|
|
49
|
+
*
|
|
45
50
|
* Owned keys (conventions 1.2): `type` (on a `<button>` only), `id`, `disabled`, `aria-disabled`
|
|
46
|
-
* (link or component `render
|
|
47
|
-
* `onKeyDown`, `onMouseDown`, `data-open`, `data-pending`,
|
|
48
|
-
* `
|
|
51
|
+
* (link or component `render`, and in a Menubar), `popoverTarget`, `aria-haspopup`,
|
|
52
|
+
* `aria-expanded`, `onClick`, `onKeyDown`, `onMouseDown`, `data-open`, `data-pending`,
|
|
53
|
+
* `data-disabled`, and in a Menubar `role`; `commandfor`, `command` and `popoverTargetAction`
|
|
54
|
+
* (never written; omitted from the props type). In a Menubar the hover switch is an
|
|
55
|
+
* `onPointerMove` handler merged with the consumer's (theirs runs first).
|
|
49
56
|
*
|
|
50
57
|
* @see https://ui.funstack.work/components/menu
|
|
51
58
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"menu-trigger.d.mts","names":[],"sources":["../../src/menu/menu-trigger.tsx"],"mappings":";;;;;;;;;
|
|
1
|
+
{"version":3,"file":"menu-trigger.d.mts","names":[],"sources":["../../src/menu/menu-trigger.tsx"],"mappings":";;;;;;;;;YA+BY,mBAAmB;;;;;;iBAOd,yBAAyB,KACxC;;;;;;;EAoBA;;EAEA,YAAY,+BAA+B;;EAE3C,QAAQ,WAAW,2BAA2B;;EAE9C,WAAW,WAAW,WAAW;;;;;;EAMjC,SAAS,WAAW,iCAAiC;;;;;;;;;;;;;;;;;;;;;;;;wBAkEvC,cACd,UACA,WACA,OACA,UACA,WACG,QACF,mBAAgB;yBAPH"}
|
|
@@ -2,10 +2,14 @@
|
|
|
2
2
|
import { useToolbarContext } from "../internal/toolbar-context.mjs";
|
|
3
3
|
import { useDevWarning } from "../internal/use-dev-warning.mjs";
|
|
4
4
|
import { useRender } from "../internal/use-render.mjs";
|
|
5
|
+
import { useLatest } from "../internal/use-latest.mjs";
|
|
6
|
+
import { useMergedRefs } from "../internal/use-merged-refs.mjs";
|
|
5
7
|
import { isPopoverOpen } from "../internal/overlay/popover-open.mjs";
|
|
6
8
|
import { toggleFromTrigger, usePopoverTrigger } from "../internal/overlay/use-popover-trigger.mjs";
|
|
7
9
|
import { useMenuContext } from "./menu-context.mjs";
|
|
8
10
|
import { edgeItem, focusItem, hasModifier, isRtl } from "./menu-dom.mjs";
|
|
11
|
+
import { useMenubarContext } from "../internal/menubar-context.mjs";
|
|
12
|
+
import { useCallback } from "react";
|
|
9
13
|
//#region src/menu/menu-trigger.tsx
|
|
10
14
|
const isDev = process.env.NODE_ENV !== "production";
|
|
11
15
|
/**
|
|
@@ -30,6 +34,19 @@ function isPointerClick(event) {
|
|
|
30
34
|
return event.type === "click" && event.detail > 0;
|
|
31
35
|
}
|
|
32
36
|
/**
|
|
37
|
+
* A switch's open (design/components/menubar.md 2.2 step 3): the first item focused when the menu
|
|
38
|
+
* shows (or at once, when it is already shown), or focus left on the Trigger.
|
|
39
|
+
*/
|
|
40
|
+
function openFromBar(menu, event, focus) {
|
|
41
|
+
if (focus === "first") {
|
|
42
|
+
openMenuWithFocus(menu, event, "first");
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
if (menu.popover.intended()) return;
|
|
46
|
+
menu.setOpenCause("none");
|
|
47
|
+
menu.popover.requestOpen(event, "activate");
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
33
50
|
* The menu button: `<button type="button" popovertarget aria-haspopup="menu">`, with no
|
|
34
51
|
* `aria-expanded` (the browser exposes the menu's state on its invoker; a link or other non-button
|
|
35
52
|
* element, or a disabled component `render`, renders it from the shown menu). A click (Enter,
|
|
@@ -37,21 +54,30 @@ function isPointerClick(event) {
|
|
|
37
54
|
* first / last item focused (inside a vertical `Toolbar.Root`: the inline-end arrow, with the
|
|
38
55
|
* first item focused).
|
|
39
56
|
*
|
|
57
|
+
* Inside a `Menubar` it is an item of the bar (design/components/menubar.md): `role="menuitem"`,
|
|
58
|
+
* no rendered `tabindex` (the bar writes it), and `disabled` as `aria-disabled="true"` (it stays
|
|
59
|
+
* focusable and never opens). Moving the pointer onto it while another menu of the bar is open
|
|
60
|
+
* switches to its menu.
|
|
61
|
+
*
|
|
40
62
|
* Owned keys (conventions 1.2): `type` (on a `<button>` only), `id`, `disabled`, `aria-disabled`
|
|
41
|
-
* (link or component `render
|
|
42
|
-
* `onKeyDown`, `onMouseDown`, `data-open`, `data-pending`,
|
|
43
|
-
* `
|
|
63
|
+
* (link or component `render`, and in a Menubar), `popoverTarget`, `aria-haspopup`,
|
|
64
|
+
* `aria-expanded`, `onClick`, `onKeyDown`, `onMouseDown`, `data-open`, `data-pending`,
|
|
65
|
+
* `data-disabled`, and in a Menubar `role`; `commandfor`, `command` and `popoverTargetAction`
|
|
66
|
+
* (never written; omitted from the props type). In a Menubar the hover switch is an
|
|
67
|
+
* `onPointerMove` handler merged with the consumer's (theirs runs first).
|
|
44
68
|
*
|
|
45
69
|
* @see https://ui.funstack.work/components/menu
|
|
46
70
|
*/
|
|
47
71
|
function MenuTrigger({ disabled = false, className, style, children, render, ...rest }) {
|
|
48
72
|
const menu = useMenuContext("Menu.Trigger");
|
|
49
73
|
useDevWarning(menu.submenu, isDev && "Menu.Trigger: rendered in a submenu. Use Menu.SubmenuTrigger, which is also an item of the parent menu.");
|
|
74
|
+
const bar = useMenubarContext();
|
|
75
|
+
const inBar = bar !== null;
|
|
50
76
|
const toolbar = useToolbarContext();
|
|
51
77
|
const onKeyDown = (event) => {
|
|
52
78
|
if (disabled || hasModifier(event)) return;
|
|
53
79
|
let which;
|
|
54
|
-
if (toolbar?.orientation === "vertical") {
|
|
80
|
+
if (!inBar && toolbar?.orientation === "vertical") {
|
|
55
81
|
const openKey = isRtl(event.currentTarget) ? "ArrowLeft" : "ArrowRight";
|
|
56
82
|
if (event.key !== openKey) return;
|
|
57
83
|
which = "first";
|
|
@@ -62,18 +88,39 @@ function MenuTrigger({ disabled = false, className, style, children, render, ...
|
|
|
62
88
|
event.preventDefault();
|
|
63
89
|
openMenuWithFocus(menu, event.nativeEvent, which);
|
|
64
90
|
};
|
|
65
|
-
const
|
|
91
|
+
const latest = useLatest({
|
|
92
|
+
menu,
|
|
93
|
+
disabled
|
|
94
|
+
});
|
|
95
|
+
const barRef = useCallback((element) => bar?.register(element, {
|
|
96
|
+
disabled: () => latest.current.disabled,
|
|
97
|
+
intended: () => latest.current.menu.popover.intended(),
|
|
98
|
+
hiddenBeforeToggle: () => latest.current.menu.popover.hiddenBeforeToggle(),
|
|
99
|
+
popup: () => latest.current.menu.popover.popupRef.current,
|
|
100
|
+
open: (event, focus) => openFromBar(latest.current.menu, event, focus),
|
|
101
|
+
supersede: (event) => latest.current.menu.popover.requestClose(event, "dismiss")
|
|
102
|
+
}), [bar, latest]);
|
|
103
|
+
const onPointerMove = bar === null ? void 0 : (event) => {
|
|
104
|
+
if (event.pointerType === "touch" || disabled || menu.popover.intended()) return;
|
|
105
|
+
const element = event.currentTarget;
|
|
106
|
+
if (!bar.otherIntended(element)) return;
|
|
107
|
+
bar.switchTo(element, "none", event.nativeEvent, true);
|
|
108
|
+
};
|
|
109
|
+
const { state, libraryProps, ref: triggerRef } = usePopoverTrigger(menu.popover, {
|
|
66
110
|
part: "Menu.Trigger",
|
|
67
111
|
disabled,
|
|
68
112
|
render,
|
|
113
|
+
alwaysFocusable: inBar,
|
|
69
114
|
handlers: {
|
|
70
115
|
onKeyDown,
|
|
116
|
+
...onPointerMove !== void 0 && { onPointerMove },
|
|
71
117
|
onMouseDown: (event) => {
|
|
72
118
|
if (event.button === 0 && menu.popover.intended()) event.preventDefault();
|
|
73
119
|
}
|
|
74
120
|
},
|
|
75
121
|
onActivate: (event) => toggleFromTrigger(menu.popover, event.nativeEvent, () => menu.setOpenCause("first", isPointerClick(event.nativeEvent)))
|
|
76
122
|
});
|
|
123
|
+
const ref = useMergedRefs(triggerRef, barRef);
|
|
77
124
|
return useRender({
|
|
78
125
|
defaultElement: "button",
|
|
79
126
|
render,
|
|
@@ -84,6 +131,7 @@ function MenuTrigger({ disabled = false, className, style, children, render, ...
|
|
|
84
131
|
props: rest,
|
|
85
132
|
libraryProps: {
|
|
86
133
|
...libraryProps,
|
|
134
|
+
...inBar && { role: "menuitem" },
|
|
87
135
|
id: menu.triggerId,
|
|
88
136
|
"aria-haspopup": "menu"
|
|
89
137
|
},
|