@barqjs/aria 0.0.0-stage → 0.2.0-next.0

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.
Files changed (76) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +293 -2
  3. package/package.json +347 -4
  4. package/src/breadcrumbs.tsx +296 -0
  5. package/src/button.tsx +342 -0
  6. package/src/calendar.tsx +1389 -0
  7. package/src/checkbox.tsx +570 -0
  8. package/src/collections.ts +976 -0
  9. package/src/color.ts +562 -0
  10. package/src/colorpicker.tsx +1478 -0
  11. package/src/combobox.tsx +2481 -0
  12. package/src/command.tsx +1184 -0
  13. package/src/date.ts +652 -0
  14. package/src/datefield.tsx +951 -0
  15. package/src/datepicker.tsx +556 -0
  16. package/src/dialog.tsx +890 -0
  17. package/src/disclosure.tsx +659 -0
  18. package/src/dom.ts +706 -0
  19. package/src/drawer.ts +674 -0
  20. package/src/focus.ts +1370 -0
  21. package/src/form.tsx +94 -0
  22. package/src/gridlist.tsx +563 -0
  23. package/src/i18n.ts +823 -0
  24. package/src/index.ts +1270 -0
  25. package/src/interactions/description.ts +73 -0
  26. package/src/interactions/flags.ts +35 -0
  27. package/src/interactions/focus-events.ts +218 -0
  28. package/src/interactions/focusable.ts +86 -0
  29. package/src/interactions/hover.ts +213 -0
  30. package/src/interactions/interact-outside.ts +123 -0
  31. package/src/interactions/keyboard.ts +105 -0
  32. package/src/interactions/listeners.ts +78 -0
  33. package/src/interactions/long-press.ts +160 -0
  34. package/src/interactions/modality.ts +416 -0
  35. package/src/interactions/move.ts +257 -0
  36. package/src/interactions/open-link.ts +193 -0
  37. package/src/interactions/press.ts +898 -0
  38. package/src/interactions/prevent-focus.ts +102 -0
  39. package/src/interactions/scroll-wheel.ts +43 -0
  40. package/src/interactions/text-selection.ts +77 -0
  41. package/src/interactions.ts +81 -0
  42. package/src/label.ts +128 -0
  43. package/src/link.tsx +381 -0
  44. package/src/listbox.tsx +721 -0
  45. package/src/live.ts +204 -0
  46. package/src/menu.tsx +2290 -0
  47. package/src/menubar.tsx +575 -0
  48. package/src/navigation.ts +735 -0
  49. package/src/numberfield.tsx +838 -0
  50. package/src/otp.ts +430 -0
  51. package/src/overlays.ts +1247 -0
  52. package/src/platform.ts +74 -0
  53. package/src/presence.ts +164 -0
  54. package/src/questionnaire.tsx +1712 -0
  55. package/src/radio.tsx +567 -0
  56. package/src/register-dom.ts +12 -0
  57. package/src/scroller.ts +1165 -0
  58. package/src/select.tsx +1665 -0
  59. package/src/selection.ts +1415 -0
  60. package/src/slider.tsx +1042 -0
  61. package/src/splitter.ts +1152 -0
  62. package/src/static-collection.ts +211 -0
  63. package/src/switch.tsx +186 -0
  64. package/src/table.tsx +0 -0
  65. package/src/tabs.tsx +1018 -0
  66. package/src/tag.tsx +452 -0
  67. package/src/textfield.tsx +417 -0
  68. package/src/toast.ts +658 -0
  69. package/src/toggle-input.tsx +48 -0
  70. package/src/toggle.ts +321 -0
  71. package/src/togglegroup.ts +365 -0
  72. package/src/toolbar.tsx +179 -0
  73. package/src/tooltip.tsx +657 -0
  74. package/src/utils.ts +758 -0
  75. package/src/validation.ts +447 -0
  76. package/src/virtualizer.tsx +674 -0
package/src/menu.tsx ADDED
@@ -0,0 +1,2290 @@
1
+ /**
2
+ * Menus: a list of actions, opened from a trigger.
3
+ *
4
+ * A menu looks like a listbox and behaves differently in three ways that all
5
+ * come from the same fact — it closes when you choose something.
6
+ *
7
+ * - Selection happens on pointer UP, not down. The press that opened the menu
8
+ * ends over the item that is now underneath it, and selecting on down would
9
+ * let one gesture open the menu and choose its first item.
10
+ * - Escape closes the menu rather than clearing the selection. A menu whose
11
+ * Escape cleared checkboxes and left itself open would strand a keyboard
12
+ * user with no way out.
13
+ * - Enter closes even a multi-select menu, where a click does not: keyboard
14
+ * users have Space for "check this and stay", so Enter is free to mean
15
+ * "this one, done".
16
+ *
17
+ * The role of an item is decided by the menu's selection mode, not by the
18
+ * item: `menuitemradio` under single selection, `menuitemcheckbox` under
19
+ * multiple, `menuitem` when there is nothing to select. Writing
20
+ * `aria-checked` on a plain `menuitem` says every item is unchecked rather
21
+ * than that checking is not the point.
22
+ */
23
+
24
+ import {
25
+ type Accessor,
26
+ type Child,
27
+ For,
28
+ createContext,
29
+ createEffect,
30
+ createUniqueId,
31
+ getContext,
32
+ getOwner,
33
+ type Incoming,
34
+ install,
35
+ onCleanup,
36
+ provide,
37
+ createSignal,
38
+ } from "@barqjs/core";
39
+ import { isServer } from "@barqjs/web";
40
+ import { tryCleanup } from "@barqjs/primitives/utils";
41
+ import { ref as makeRef, mergeRefs, type RefTarget } from "@barqjs/primitives/refs";
42
+ import type {
43
+ FocusStrategy,
44
+ ItemAccessors,
45
+ Key,
46
+ ListStateOptions,
47
+ Node,
48
+ SelectionMode,
49
+ } from "./collections.ts";
50
+ import { listState, type ListState } from "./collections.ts";
51
+ import {
52
+ contains,
53
+ focusWithoutScrolling,
54
+ ownerDocument,
55
+ ownerWindow,
56
+ targetElement,
57
+ } from "./dom.ts";
58
+ import { Popover, popoverStateProps } from "./dialog.tsx";
59
+ import { focusRing } from "./focus.ts";
60
+ import { hover } from "./interactions/hover.ts";
61
+ import { getInteractionModality, isFocusVisible } from "./interactions/modality.ts";
62
+ import { keyboard, type BaseEvent } from "./interactions/keyboard.ts";
63
+ import { globalListeners, type GlobalListeners } from "./interactions/listeners.ts";
64
+ import { longPressHandlers } from "./interactions/long-press.ts";
65
+ import { isOpeningLink } from "./interactions/flags.ts";
66
+ import { router } from "./interactions/open-link.ts";
67
+ import type { ElementRef, PressEvent } from "./interactions/press.ts";
68
+ import { button, toggleState, type ButtonOptions } from "./button.tsx";
69
+ import {
70
+ overlayTrigger,
71
+ overlayTriggerState,
72
+ type AnchorRect,
73
+ type OverlayTriggerState,
74
+ type OverlayTriggerStateOptions,
75
+ type Placement,
76
+ } from "./overlays.ts";
77
+ import { useLocale } from "./i18n.ts";
78
+ import { idFragment } from "./listbox.tsx";
79
+ import { selectableItem, selectableList, type KeyboardDelegate } from "./selection.ts";
80
+ import {
81
+ staticAccessors,
82
+ staticCollection,
83
+ staticItem,
84
+ type StaticCollection,
85
+ } from "./static-collection.ts";
86
+ import {
87
+ access,
88
+ controllable,
89
+ type DOMProps,
90
+ filterDOMProps,
91
+ fromProps,
92
+ id,
93
+ type MaybeAccessor,
94
+ mergeProps,
95
+ type StyleProps,
96
+ styleProps,
97
+ } from "./utils.ts";
98
+
99
+ // ---------------------------------------------------------------------------
100
+ // The menu
101
+ // ---------------------------------------------------------------------------
102
+
103
+ export interface MenuOptions {
104
+ ref: ElementRef;
105
+ /** @default true */
106
+ shouldFocusWrap?: MaybeAccessor<boolean | undefined>;
107
+ autoFocus?: MaybeAccessor<boolean | "first" | "last" | undefined>;
108
+ /** Track focus with `aria-activedescendant`, for an autocomplete. */
109
+ shouldUseVirtualFocus?: MaybeAccessor<boolean | undefined>;
110
+ disallowTypeAhead?: MaybeAccessor<boolean | undefined>;
111
+ isVirtualized?: MaybeAccessor<boolean | undefined>;
112
+ keyboardDelegate?: KeyboardDelegate;
113
+ /** The menu's own id, which every item id is derived from. */
114
+ baseId?: MaybeAccessor<string | undefined>;
115
+ "aria-label"?: MaybeAccessor<string | undefined>;
116
+ "aria-labelledby"?: MaybeAccessor<string | undefined>;
117
+ /** Called when an item is chosen and the menu should go away. */
118
+ onClose?: () => void;
119
+ onAction?: (key: Key) => void;
120
+ /**
121
+ * Chained BEFORE the collection's own key handling.
122
+ *
123
+ * A SUBMENU needs it: the key that closes it — the arrow pointing back at
124
+ * its trigger, or Escape — is pressed inside the submenu and belongs to the
125
+ * trigger, which is in the menu above.
126
+ */
127
+ onKeyDown?: (event: KeyboardEvent) => void;
128
+ }
129
+
130
+ export interface MenuResult {
131
+ menuProps: DOMProps;
132
+ /** The base every item id is derived from, shared with the items. */
133
+ baseId: Accessor<string>;
134
+ }
135
+
136
+ export function menu(options: MenuOptions, state: ListState<unknown>): MenuResult {
137
+ const baseId = id(options.baseId);
138
+
139
+ const { listProps } = selectableList({
140
+ ...options,
141
+ selectionManager: state.selectionManager,
142
+ collection: state.collection,
143
+ disabledKeys: state.disabledKeys,
144
+ shouldFocusWrap: () => access(options.shouldFocusWrap) ?? true,
145
+ // The overlay's Escape is the one that matters; clearing the selection
146
+ // first would consume the key and leave the menu open.
147
+ escapeKeyBehavior: "none",
148
+ // Following a link is the item's job, timed with the close.
149
+ linkBehavior: "override",
150
+ });
151
+
152
+ return {
153
+ baseId,
154
+ menuProps: mergeProps(
155
+ { onKeyDown: options.onKeyDown },
156
+ filterDOMProps(options, { labelable: true }),
157
+ listProps,
158
+ {
159
+ role: "menu",
160
+ // Under virtual focus the menu never has DOM focus, so the item that
161
+ // does is named here instead.
162
+ "aria-activedescendant": () => {
163
+ if (access(options.shouldUseVirtualFocus) !== true) return undefined;
164
+ const focused = state.selectionManager().focusedKey;
165
+ return focused === null ? undefined : menuItemIdFor(baseId(), focused);
166
+ },
167
+ },
168
+ ),
169
+ };
170
+ }
171
+
172
+ // ---------------------------------------------------------------------------
173
+ // An item
174
+ // ---------------------------------------------------------------------------
175
+
176
+ /**
177
+ * The id an item renders under.
178
+ *
179
+ * `aria-activedescendant` names it before the item exists, so the id is
180
+ * DERIVED from the key rather than generated per element. It is derived from
181
+ * the menu's own id as well, because two menus offering the same key would
182
+ * otherwise write the same id twice — the same shape `optionIdFor` uses in
183
+ * `listbox.tsx`.
184
+ */
185
+ export function menuItemIdFor(baseId: string, key: Key): string {
186
+ return `${baseId}-item-${idFragment(key)}`;
187
+ }
188
+
189
+ export interface MenuItemOptions {
190
+ key: Key;
191
+ ref: ElementRef;
192
+ /** The menu's own id, which the item's is derived from. */
193
+ baseId: MaybeAccessor<string>;
194
+ isDisabled?: MaybeAccessor<boolean | undefined>;
195
+ isVirtualized?: MaybeAccessor<boolean | undefined>;
196
+ shouldUseVirtualFocus?: MaybeAccessor<boolean | undefined>;
197
+ /** Override when the menu closes. By default Enter and a single choice do. */
198
+ shouldCloseOnSelect?: MaybeAccessor<boolean | undefined>;
199
+ /**
200
+ * Interaction handling on top of the item's own, chained after it.
201
+ *
202
+ * A submenu trigger IS a menu item, and opening on hover, on a virtual press
203
+ * and on touch is three behaviours layered over the item's own rather than
204
+ * instead of it. A second `press` or `hover` on the same element would be
205
+ * two pressed states racing over one gesture.
206
+ */
207
+ onPressStart?: (event: PressEvent) => void;
208
+ onPress?: (event: PressEvent) => void;
209
+ onHoverChange?: (isHovered: boolean) => void;
210
+ /** Chained BEFORE the collection's own, so a trigger's arrow key wins. */
211
+ onKeyDown?: (event: KeyboardEvent) => void;
212
+ "aria-label"?: MaybeAccessor<string | undefined>;
213
+ "aria-describedby"?: MaybeAccessor<string | undefined>;
214
+ /** What this item opens, when it is a submenu trigger. */
215
+ "aria-haspopup"?: MaybeAccessor<"menu" | "dialog" | undefined>;
216
+ "aria-expanded"?: MaybeAccessor<boolean | undefined>;
217
+ "aria-controls"?: MaybeAccessor<string | undefined>;
218
+ /**
219
+ * What this item is, when it says so itself.
220
+ *
221
+ * A menu rendered from data takes one selection mode for all of its items. A
222
+ * menu WRITTEN as children mixes them: a tick beside "Show toolbar", three
223
+ * radios under it and a plain "Print" at the bottom. Each item then carries
224
+ * its own kind and its own state, and the menu's selection is not consulted.
225
+ *
226
+ * @default decided by the menu's selection mode
227
+ */
228
+ type?: MaybeAccessor<MenuItemType | undefined>;
229
+ /** Whether a `checkbox` or `radio` item is on. */
230
+ isSelected?: MaybeAccessor<boolean | undefined>;
231
+ /** Turn a `checkbox` item over, or a `radio` item on. */
232
+ onToggle?: () => void;
233
+ /** Called when the item is chosen, before the menu closes; preventing it keeps the menu open. */
234
+ onSelect?: (event: MenuSelectEvent) => void;
235
+ onAction?: (key: Key) => void;
236
+ onClose?: () => void;
237
+ }
238
+
239
+ export type MenuItemType = "item" | "checkbox" | "radio";
240
+
241
+ /**
242
+ * What an item's `onSelect` receives.
243
+ *
244
+ * Choosing an item closes the menu, and the one thing a caller needs to say
245
+ * about that is "not this time": a "Select all" that should leave the list up,
246
+ * or an item that opens a dialog and wants to hand focus over itself.
247
+ */
248
+ export interface MenuSelectEvent {
249
+ readonly key: Key;
250
+ readonly defaultPrevented: boolean;
251
+ preventDefault: () => void;
252
+ }
253
+
254
+ export interface MenuItemResult {
255
+ menuItemProps: DOMProps;
256
+ /**
257
+ * For an item whose name is one element among several.
258
+ *
259
+ * Nothing references these ids until the caller says so with
260
+ * `aria-labelledby` and `aria-describedby`: an item that is just its text
261
+ * is named by that text, and a reference to an element the caller never
262
+ * rendered leaves it with no name at all.
263
+ */
264
+ labelProps: DOMProps;
265
+ descriptionProps: DOMProps;
266
+ /** For the element showing the item's keyboard shortcut, if any. */
267
+ keyboardShortcutProps: DOMProps;
268
+ isSelected: Accessor<boolean>;
269
+ isFocused: Accessor<boolean>;
270
+ isPressed: Accessor<boolean>;
271
+ isDisabled: Accessor<boolean>;
272
+ }
273
+
274
+ export function menuItem(options: MenuItemOptions, state: ListState<unknown>): MenuItemResult {
275
+ const labelId = id();
276
+ const descriptionId = id();
277
+ const keyboardId = id();
278
+
279
+ const manager = () => state.selectionManager();
280
+ const navigate = router();
281
+ const isTrigger = (): boolean => access(options["aria-haspopup"]) !== undefined;
282
+ const node = (): Node<unknown> | null => state.collection().getItem(options.key);
283
+ const kind = (): MenuItemType | undefined => access(options.type);
284
+ const checks = (): boolean => kind() === "checkbox" || kind() === "radio";
285
+
286
+ /**
287
+ * Whether choosing this item takes the menu away.
288
+ *
289
+ * From the keyboard, Enter means "this one" and closes whatever the mode;
290
+ * Space is the one that checks an item and stays. From a pointer, only a
291
+ * multi-select menu stays open, because there is no second gesture that
292
+ * means "and I am done".
293
+ */
294
+ const shouldClose = (event: PressEvent): boolean => {
295
+ const declared = access(options.shouldCloseOnSelect);
296
+ if (declared !== undefined) return declared;
297
+ if (manager().isLink(options.key)) return true;
298
+ // An item that says what it is closes on any pointer choice: there is no
299
+ // menu-wide mode to read "and I am not done" from, and a caller who wants
300
+ // the list left up says so through `onSelect`.
301
+ if (kind() !== undefined) {
302
+ return event.pointerType !== "keyboard" || event.key === "Enter" || !checks();
303
+ }
304
+ if (event.pointerType === "keyboard") {
305
+ return event.key === "Enter" || manager().selectionMode === "none";
306
+ }
307
+ return manager().selectionMode !== "multiple";
308
+ };
309
+
310
+ /**
311
+ * `shouldSelectOnPressUp` with `allowsDifferentPressOrigin` is what makes
312
+ * this a menu rather than a listbox: the press may begin on the trigger and
313
+ * end here. `linkBehavior: "none"` leaves a link alone so the close and the
314
+ * navigation happen in that order rather than racing.
315
+ */
316
+ const item = selectableItem({
317
+ key: options.key,
318
+ ref: options.ref,
319
+ id: () => menuItemIdFor(access(options.baseId), options.key),
320
+ selectionManager: state.selectionManager,
321
+ isDisabled: options.isDisabled,
322
+ shouldUseVirtualFocus: options.shouldUseVirtualFocus,
323
+ shouldSelectOnPressUp: true,
324
+ allowsDifferentPressOrigin: true,
325
+ linkBehavior: "none",
326
+ onPressStart: options.onPressStart,
327
+ onPress: (event) => {
328
+ options.onPress?.(event);
329
+ if (isTrigger() || item.isDisabled()) return;
330
+ if (checks()) options.onToggle?.();
331
+
332
+ let prevented = false;
333
+ options.onSelect?.({
334
+ key: options.key,
335
+ get defaultPrevented() {
336
+ return prevented;
337
+ },
338
+ preventDefault: () => {
339
+ prevented = true;
340
+ },
341
+ });
342
+
343
+ const itemAction = node()?.props?.onAction;
344
+ if (typeof itemAction === "function") (itemAction as () => void)();
345
+ options.onAction?.(options.key);
346
+
347
+ const closes = !prevented && shouldClose(event);
348
+ // Followed here rather than by the collection, which was told to leave
349
+ // links alone: the menu is still up, so the anchor is still in the
350
+ // document for the browser to follow.
351
+ const element = access(options.ref) as Element | null;
352
+ const href = node()?.props?.href;
353
+ if (typeof href === "string" && element !== null) navigate.open(element, event, href);
354
+ if (closes) options.onClose?.();
355
+ },
356
+ });
357
+
358
+ const { hoverProps } = hover({
359
+ isDisabled: item.isDisabled,
360
+ // Pointing at an item makes it the focused one, so arrowing on from where
361
+ // the mouse left off continues rather than jumping back. Not while the
362
+ // focus ring is showing: a mouse crossing the menu must not move a
363
+ // keyboard user's place.
364
+ onHoverStart: () => {
365
+ if (isFocusVisible()) return;
366
+ manager().setFocused(true);
367
+ manager().setFocusedKey(options.key);
368
+ },
369
+ onHoverChange: options.onHoverChange,
370
+ });
371
+
372
+ const isSelected = (): boolean =>
373
+ kind() === undefined ? item.isSelected() : checks() && access(options.isSelected) === true;
374
+
375
+ const role = (): string => {
376
+ if (isTrigger()) return "menuitem";
377
+ const own = kind();
378
+ if (own === "checkbox") return "menuitemcheckbox";
379
+ if (own === "radio") return "menuitemradio";
380
+ if (own === "item") return "menuitem";
381
+ const mode = manager().selectionMode;
382
+ if (mode === "single") return "menuitemradio";
383
+ if (mode === "multiple") return "menuitemcheckbox";
384
+ return "menuitem";
385
+ };
386
+
387
+ return {
388
+ isSelected,
389
+ isFocused: item.isFocused,
390
+ isPressed: item.isPressed,
391
+ isDisabled: item.isDisabled,
392
+ labelProps: { id: labelId },
393
+ descriptionProps: { id: descriptionId },
394
+ keyboardShortcutProps: { id: keyboardId },
395
+ menuItemProps: mergeProps({ onKeyDown: options.onKeyDown }, item.itemProps, hoverProps, {
396
+ role,
397
+ "aria-disabled": () => item.isDisabled() || undefined,
398
+ "aria-label": () => access(options["aria-label"]) ?? node()?.["aria-label"],
399
+ "aria-describedby": () => access(options["aria-describedby"]),
400
+ "aria-checked": () => {
401
+ if (isTrigger()) return undefined;
402
+ if (kind() !== undefined) return checks() ? isSelected() : undefined;
403
+ return manager().selectionMode !== "none" ? item.isSelected() : undefined;
404
+ },
405
+ "aria-haspopup": () => access(options["aria-haspopup"]),
406
+ "aria-expanded": () => access(options["aria-expanded"]),
407
+ "aria-controls": () => access(options["aria-controls"]),
408
+ "aria-posinset": () =>
409
+ access(options.isVirtualized) === true ? (node()?.index ?? 0) + 1 : undefined,
410
+ "aria-setsize": () =>
411
+ access(options.isVirtualized) === true ? state.collection().size : undefined,
412
+ }),
413
+ };
414
+ }
415
+
416
+ // ---------------------------------------------------------------------------
417
+ // A section
418
+ // ---------------------------------------------------------------------------
419
+
420
+ export interface MenuSectionOptions {
421
+ heading?: MaybeAccessor<unknown>;
422
+ "aria-label"?: MaybeAccessor<string | undefined>;
423
+ }
424
+
425
+ export interface MenuSectionResult {
426
+ itemProps: DOMProps;
427
+ headingProps: DOMProps;
428
+ groupProps: DOMProps;
429
+ }
430
+
431
+ /**
432
+ * A group of items with a heading.
433
+ *
434
+ * ARIA has no heading inside a menu, so the heading is `role="presentation"`
435
+ * and exists only to name the group. Left as a real heading it would be an
436
+ * entry in the screen reader's heading list pointing at nothing navigable.
437
+ */
438
+ export function menuSection(options: MenuSectionOptions): MenuSectionResult {
439
+ const headingId = id();
440
+ const hasHeading = (): boolean => {
441
+ const heading = access(options.heading);
442
+ return heading !== undefined && heading !== null && heading !== "";
443
+ };
444
+
445
+ return {
446
+ itemProps: { role: "presentation" },
447
+ headingProps: {
448
+ id: () => (hasHeading() ? headingId() : undefined),
449
+ role: "presentation",
450
+ },
451
+ groupProps: {
452
+ role: "group",
453
+ "aria-label": () => access(options["aria-label"]),
454
+ "aria-labelledby": () => (hasHeading() ? headingId() : undefined),
455
+ },
456
+ };
457
+ }
458
+
459
+ // ---------------------------------------------------------------------------
460
+ // The trigger
461
+ // ---------------------------------------------------------------------------
462
+
463
+ export type MenuTriggerType = "press" | "longPress";
464
+
465
+ export interface MenuTriggerStateOptions extends OverlayTriggerStateOptions {}
466
+
467
+ export interface MenuTriggerState extends OverlayTriggerState {
468
+ /** Which end the menu opens focused at, when it was opened from the keyboard. */
469
+ focusStrategy: Accessor<FocusStrategy | null>;
470
+ open: (focusStrategy?: FocusStrategy | null) => void;
471
+ toggle: (focusStrategy?: FocusStrategy | null) => void;
472
+ }
473
+
474
+ /**
475
+ * The state at the ROOT of a menu tree, which owns the submenu stack.
476
+ *
477
+ * Separate from {@link MenuTriggerState} because `menuTrigger` needs only the
478
+ * opening and closing, and a `SelectState` — which is a menu trigger for a
479
+ * listbox — has no submenus at all.
480
+ */
481
+ export interface RootMenuTriggerState extends MenuTriggerState {
482
+ /**
483
+ * The trigger key of the open submenu at each level, outermost first.
484
+ *
485
+ * A STACK rather than a flag per trigger: only one submenu can be open at a
486
+ * given depth, and opening one at depth 1 has to close whatever was open at
487
+ * depth 2 and below. Holding that in the root state is what lets a trigger
488
+ * three levels down know it has been closed by something it cannot see.
489
+ */
490
+ expandedKeys: Accessor<Key[]>;
491
+ openSubmenu: (triggerKey: Key, level: number) => void;
492
+ closeSubmenu: (triggerKey: Key, level: number) => void;
493
+ }
494
+
495
+ /** Whether the menu is open, and where focus lands when it opens. */
496
+ export function menuTriggerState(options: MenuTriggerStateOptions = {}): RootMenuTriggerState {
497
+ const overlay = overlayTriggerState(options);
498
+ const [strategy, setStrategy] = createSignal<FocusStrategy | null>(null);
499
+ const [expanded, setExpanded] = createSignal<Key[]>([]);
500
+
501
+ const close = (): void => {
502
+ setExpanded([]);
503
+ overlay.close();
504
+ };
505
+
506
+ return {
507
+ ...overlay,
508
+ close,
509
+ focusStrategy: strategy,
510
+ expandedKeys: expanded,
511
+ openSubmenu: (triggerKey, level) => {
512
+ if (level > expanded().length) return;
513
+ setExpanded((prev) => [...prev.slice(0, level), triggerKey]);
514
+ },
515
+ closeSubmenu: (triggerKey, level) => {
516
+ if (expanded()[level] !== triggerKey) return;
517
+ setExpanded((prev) => prev.slice(0, level));
518
+ },
519
+ open(focusStrategy: FocusStrategy | null = null) {
520
+ setStrategy(focusStrategy);
521
+ overlay.open();
522
+ },
523
+ toggle(focusStrategy: FocusStrategy | null = null) {
524
+ setStrategy(focusStrategy);
525
+ if (overlay.isOpen()) close();
526
+ else overlay.open();
527
+ },
528
+ };
529
+ }
530
+
531
+ // ---------------------------------------------------------------------------
532
+ // A submenu
533
+ // ---------------------------------------------------------------------------
534
+
535
+ export interface SubmenuTriggerStateOptions {
536
+ /** The key of the item that opens this submenu. */
537
+ triggerKey: Key;
538
+ }
539
+
540
+ export interface SubmenuTriggerState {
541
+ isOpen: Accessor<boolean>;
542
+ focusStrategy: Accessor<FocusStrategy | null>;
543
+ /** How deep this submenu sits: 0 for one opened from the root menu. */
544
+ level: number;
545
+ open: (focusStrategy?: FocusStrategy | null) => void;
546
+ close: () => void;
547
+ toggle: (focusStrategy?: FocusStrategy | null) => void;
548
+ /** Close the whole tree, root included. */
549
+ closeAll: () => void;
550
+ }
551
+
552
+ /**
553
+ * One submenu's share of the root menu's stack.
554
+ *
555
+ * The level is read ONCE, at construction: it is how deep this trigger sits in
556
+ * the markup, which does not change, whereas `expandedKeys` moves under it
557
+ * constantly. Reading it live would make a trigger's level jump as its own
558
+ * submenu opened.
559
+ */
560
+ export function submenuTriggerState(
561
+ options: SubmenuTriggerStateOptions,
562
+ root: RootMenuTriggerState,
563
+ ): SubmenuTriggerState {
564
+ const level = root.expandedKeys().length;
565
+ const [strategy, setStrategy] = createSignal<FocusStrategy | null>(null);
566
+ const isOpen = (): boolean => root.expandedKeys()[level] === options.triggerKey;
567
+
568
+ const open = (focusStrategy: FocusStrategy | null = null): void => {
569
+ setStrategy(focusStrategy);
570
+ root.openSubmenu(options.triggerKey, level);
571
+ };
572
+
573
+ const close = (): void => {
574
+ setStrategy(null);
575
+ root.closeSubmenu(options.triggerKey, level);
576
+ };
577
+
578
+ return {
579
+ isOpen,
580
+ focusStrategy: strategy,
581
+ level,
582
+ open,
583
+ close,
584
+ closeAll: root.close,
585
+ toggle: (focusStrategy: FocusStrategy | null = null) => {
586
+ if (isOpen()) close();
587
+ else open(focusStrategy);
588
+ },
589
+ };
590
+ }
591
+
592
+ export interface MenuTriggerOptions {
593
+ /** @default "menu" */
594
+ type?: MaybeAccessor<"menu" | "listbox" | undefined>;
595
+ /** @default "press" */
596
+ trigger?: MaybeAccessor<MenuTriggerType | undefined>;
597
+ isDisabled?: MaybeAccessor<boolean | undefined>;
598
+ }
599
+
600
+ export interface MenuTriggerResult {
601
+ /** Options for {@link button}, not props for an element. */
602
+ menuTriggerProps: DOMProps;
603
+ /** The props the menu itself needs: its id, its name, and where to focus. */
604
+ menuProps: DOMProps;
605
+ }
606
+
607
+ /**
608
+ * A button that opens a menu.
609
+ *
610
+ * The menu opens on pointer DOWN and closes on the press that follows over an
611
+ * item, which is what every native menu does and what makes click-drag-release
612
+ * work as one gesture. Touch is the exception: it opens on release, because a
613
+ * menu appearing under a finger that is still down would immediately receive
614
+ * that finger's move as a drag.
615
+ */
616
+ export function menuTrigger(
617
+ options: MenuTriggerOptions,
618
+ state: MenuTriggerState,
619
+ ): MenuTriggerResult {
620
+ const triggerId = id();
621
+ const trigger = (): MenuTriggerType => access(options.trigger) ?? "press";
622
+ const isDisabled = (): boolean => access(options.isDisabled) === true;
623
+
624
+ const { triggerProps, overlayProps } = overlayTrigger(
625
+ { type: access(options.type) ?? "menu" },
626
+ state,
627
+ );
628
+ // The press handling below replaces it: a menu opens on down, not on press.
629
+ delete triggerProps.onPress;
630
+
631
+ const openWithKey = (
632
+ event: KeyboardEvent,
633
+ strategy: FocusStrategy,
634
+ forLongPress: boolean,
635
+ ): boolean => {
636
+ if (isDisabled()) return false;
637
+ if (forLongPress !== (trigger() === "longPress")) return false;
638
+ if (event.defaultPrevented) return false;
639
+ state.toggle(strategy);
640
+ return true;
641
+ };
642
+
643
+ const { keyboardProps } = keyboard({
644
+ isDisabled: options.isDisabled,
645
+ onKeyDown: (event) => {
646
+ const alt = event.altKey;
647
+ let handled = false;
648
+
649
+ switch (event.key) {
650
+ case "Enter":
651
+ case " ":
652
+ handled = openWithKey(event, "first", alt);
653
+ break;
654
+ case "ArrowDown":
655
+ // Alt+Arrow opens a long-press menu too: it is the only key that
656
+ // does, since the plain arrows there belong to whatever is behind.
657
+ handled = alt
658
+ ? openWithKey(event, "first", true) || openWithKey(event, "first", false)
659
+ : openWithKey(event, "first", false);
660
+ break;
661
+ case "ArrowUp":
662
+ handled = alt
663
+ ? openWithKey(event, "last", true) || openWithKey(event, "last", false)
664
+ : openWithKey(event, "last", false);
665
+ break;
666
+ default:
667
+ break;
668
+ }
669
+
670
+ if (handled) event.preventDefault();
671
+ else event.continuePropagation();
672
+ },
673
+ });
674
+
675
+ const held = longPressHandlers({
676
+ isDisabled: () => isDisabled() || trigger() !== "longPress",
677
+ accessibilityDescription: "Long press to open the menu",
678
+ onLongPressStart: () => state.close(),
679
+ onLongPress: () => state.open("first"),
680
+ });
681
+
682
+ const interactionProps: DOMProps =
683
+ trigger() === "longPress"
684
+ ? { ...held.describedProps, onPressStart: held.onPressStart, onPressEnd: held.onPressEnd }
685
+ : {
686
+ preventFocusOnPress: true,
687
+ onPressStart: (event: PressEvent) => {
688
+ if (isDisabled() || event.pointerType === "touch" || event.pointerType === "keyboard") {
689
+ return;
690
+ }
691
+ // Focus has to be on the trigger before the menu opens, or the
692
+ // focus scope has nowhere to put it back when the menu closes.
693
+ focusWithoutScrolling(event.target as HTMLElement);
694
+ // A screen reader's activation has no pointer to follow, so the
695
+ // first item is focused rather than the menu itself.
696
+ state.open(event.pointerType === "virtual" ? "first" : null);
697
+ },
698
+ onPress: (event: PressEvent) => {
699
+ if (isDisabled() || event.pointerType !== "touch") return;
700
+ focusWithoutScrolling(event.target as HTMLElement);
701
+ state.toggle();
702
+ },
703
+ };
704
+
705
+ return {
706
+ menuTriggerProps: mergeProps(triggerProps, interactionProps, keyboardProps, {
707
+ id: triggerId,
708
+ "data-state": () => (state.isOpen() ? "open" : "closed"),
709
+ }),
710
+ menuProps: {
711
+ ...overlayProps,
712
+ "aria-labelledby": triggerId,
713
+ autoFocus: () => {
714
+ return state.focusStrategy() ?? true;
715
+ },
716
+ onClose: state.close,
717
+ },
718
+ };
719
+ }
720
+
721
+ // ---------------------------------------------------------------------------
722
+ // A menu at the pointer
723
+ // ---------------------------------------------------------------------------
724
+
725
+ export interface ContextMenuTriggerOptions {
726
+ isDisabled?: MaybeAccessor<boolean | undefined>;
727
+ /** How long a touch must be held before the menu opens. @default 500 */
728
+ longPressThreshold?: MaybeAccessor<number | undefined>;
729
+ }
730
+
731
+ export interface ContextMenuTriggerResult {
732
+ /** Props for the region the menu is opened over. */
733
+ contextMenuTriggerProps: DOMProps;
734
+ /** The props the menu itself needs: its id, and where to focus. */
735
+ menuProps: DOMProps;
736
+ /** The point the menu is anchored to, as a zero-size box. */
737
+ anchorRect: Accessor<AnchorRect | null>;
738
+ }
739
+
740
+ const TOUCH_HOLD = 500;
741
+
742
+ /** How far a held touch may wander before it is a scroll rather than a hold. */
743
+ const TOUCH_SLOP = 10;
744
+
745
+ /** How long a click is waited for after a hold that opened the menu. */
746
+ const SWALLOW_WINDOW = 300;
747
+
748
+ /**
749
+ * Whether a `contextmenu` event came from the keyboard.
750
+ *
751
+ * It decides where focus lands: a menu opened with Shift+F10 or the Menu key
752
+ * has to arrive on its first item, and one opened with the pointer arrives
753
+ * with nothing highlighted. Where the browser dispatches `contextmenu` as a
754
+ * `PointerEvent` it answers this itself, with an empty `pointerType`; where it
755
+ * does not, the fallback is that no button was pressed and none is held, which
756
+ * both a right-click and a macOS Control-click fail.
757
+ */
758
+ function isKeyboardContextMenu(event: MouseEvent): boolean {
759
+ const pointerType = (event as PointerEvent).pointerType;
760
+ if (typeof pointerType === "string" && pointerType !== "") return false;
761
+ return event.button === 0 && event.buttons === 0;
762
+ }
763
+
764
+ /**
765
+ * A menu opened over a region rather than from a control.
766
+ *
767
+ * The anchor is a POINT, so the menu goes just below and to the right of the
768
+ * pointer the way every platform's own context menu does, and flips at the
769
+ * edge of the screen the way any other overlay does.
770
+ *
771
+ * Touch has no second button, so a held touch opens it. That is done with the
772
+ * pointer events directly rather than with `press`, because a press over a
773
+ * region of arbitrary content would disable text selection inside it and take
774
+ * Enter and Space from the children the keystrokes belong to.
775
+ */
776
+ export function contextMenuTrigger(
777
+ options: ContextMenuTriggerOptions,
778
+ state: MenuTriggerState,
779
+ ): ContextMenuTriggerResult {
780
+ const menuId = id();
781
+ const [anchor, setAnchor] = createSignal<AnchorRect | null>(null);
782
+ const listeners = globalListeners();
783
+ const isDisabled = (): boolean => access(options.isDisabled) === true;
784
+
785
+ let held: ReturnType<typeof setTimeout> | undefined;
786
+ let from: { x: number; y: number } | null = null;
787
+
788
+ const cancelHold = (): void => {
789
+ if (held !== undefined) clearTimeout(held);
790
+ held = undefined;
791
+ from = null;
792
+ };
793
+
794
+ const openAt = (x: number, y: number, strategy: FocusStrategy | null): void => {
795
+ setAnchor({ top: y, left: x, width: 0, height: 0 });
796
+ state.open(strategy);
797
+ };
798
+
799
+ const onContextMenu = (event: MouseEvent): void => {
800
+ // Disabled hands the page back the browser's own menu, which is what it
801
+ // had before this was wrapped around it.
802
+ if (isDisabled()) return;
803
+ cancelHold();
804
+ event.preventDefault();
805
+ openAt(event.clientX, event.clientY, isKeyboardContextMenu(event) ? "first" : null);
806
+ };
807
+
808
+ const onKeyDown = (event: KeyboardEvent): void => {
809
+ if (isDisabled()) return;
810
+ if (event.key !== "ContextMenu" && !(event.key === "F10" && event.shiftKey)) return;
811
+ // Under the element that HAS focus, not at the region's own corner: the
812
+ // region can be a page of content, and the menu is about whatever the
813
+ // keyboard is on.
814
+ const target = (targetElement(event) ?? event.currentTarget) as Element | null;
815
+ if (target === null) return;
816
+ event.preventDefault();
817
+ const box = target.getBoundingClientRect();
818
+ openAt(box.left, box.bottom, "first");
819
+ };
820
+
821
+ const onPointerDown = (event: PointerEvent): void => {
822
+ if (isDisabled()) return;
823
+ if (event.pointerType !== "touch" && event.pointerType !== "pen") return;
824
+ cancelHold();
825
+ from = { x: event.clientX, y: event.clientY };
826
+ const region = event.currentTarget as Element | null;
827
+ const { clientX, clientY } = event;
828
+ held = setTimeout(
829
+ () => {
830
+ held = undefined;
831
+ if (region !== null) swallowNextClick(listeners, region);
832
+ openAt(clientX, clientY, null);
833
+ },
834
+ access(options.longPressThreshold) ?? TOUCH_HOLD,
835
+ );
836
+ };
837
+
838
+ const onPointerMove = (event: PointerEvent): void => {
839
+ if (held === undefined || from === null) return;
840
+ const moved =
841
+ Math.abs(event.clientX - from.x) > TOUCH_SLOP ||
842
+ Math.abs(event.clientY - from.y) > TOUCH_SLOP;
843
+ if (moved) cancelHold();
844
+ };
845
+
846
+ return {
847
+ contextMenuTriggerProps: {
848
+ onContextMenu,
849
+ onKeyDown,
850
+ onPointerDown,
851
+ onPointerMove,
852
+ onPointerUp: cancelHold,
853
+ onPointerCancel: cancelHold,
854
+ // iOS puts its own callout over a held element, on top of this menu.
855
+ style: { "-webkit-touch-callout": "none" },
856
+ "data-open": () => state.isOpen(),
857
+ "data-state": () => (state.isOpen() ? "open" : "closed"),
858
+ "data-disabled": () => isDisabled(),
859
+ },
860
+ menuProps: {
861
+ id: menuId,
862
+ autoFocus: () => state.focusStrategy() ?? true,
863
+ onClose: state.close,
864
+ },
865
+ anchorRect: anchor,
866
+ };
867
+ }
868
+
869
+ /**
870
+ * Eat the click that ends a hold.
871
+ *
872
+ * The finger is still down when the menu opens, so the click that follows
873
+ * would land on whatever the menu is now covering. Most platforms send no
874
+ * click after a long press at all, so the listener comes off on a timer as
875
+ * well, or the next ordinary click is eaten instead.
876
+ */
877
+ function swallowNextClick(listeners: GlobalListeners, region: Element): void {
878
+ const doc = ownerDocument(region);
879
+ const swallow = (click: Event): void => {
880
+ click.preventDefault();
881
+ click.stopPropagation();
882
+ };
883
+ listeners.add(doc, "click", swallow, { once: true, capture: true });
884
+ setTimeout(() => listeners.remove(doc, "click", swallow, true), SWALLOW_WINDOW);
885
+ }
886
+
887
+ // ---------------------------------------------------------------------------
888
+ // Moving the pointer to a submenu without losing it
889
+ // ---------------------------------------------------------------------------
890
+
891
+ export interface SafelyMouseToSubmenuOptions {
892
+ /** The menu the trigger is in. */
893
+ menuRef: ElementRef;
894
+ submenuRef: ElementRef;
895
+ isOpen: MaybeAccessor<boolean>;
896
+ isDisabled?: MaybeAccessor<boolean | undefined>;
897
+ }
898
+
899
+ /** How many moves away from the submenu are forgiven before giving up. */
900
+ const ALLOWED_INVALID_MOVEMENTS = 2;
901
+ const THROTTLE_TIME = 50;
902
+ const GIVE_UP_TIME = 1000;
903
+ /** 15°, so a hand that wobbles on the way still counts as heading there. */
904
+ const ANGLE_PADDING = Math.PI / 12;
905
+
906
+ /**
907
+ * Let the pointer travel from a trigger to its submenu without closing it.
908
+ *
909
+ * The submenu is BESIDE the trigger, not under it, so the direct route to it
910
+ * crosses other items of the parent menu — each of which would take the hover
911
+ * and close the submenu the user was reaching for. The fix is to notice that
912
+ * the pointer is heading INTO the submenu's rectangle and, while it is, turn
913
+ * off pointer events on the parent menu so nothing it crosses reacts.
914
+ *
915
+ * "Heading into" is an angle test: the angle from the last pointer position to
916
+ * the current one, against the angles to the submenu's top and bottom corners.
917
+ * Two consecutive moves that fail it give up, because a user who has changed
918
+ * their mind should not have to wait.
919
+ */
920
+ export function safelyMouseToSubmenu(options: SafelyMouseToSubmenuOptions): void {
921
+ if (isServer) return;
922
+
923
+ let previous: { x: number; y: number } | null = null;
924
+ let rect: DOMRect | null = null;
925
+ let lastProcessed = 0;
926
+ let side: "left" | "right" | null = null;
927
+ let towards = ALLOWED_INVALID_MOVEMENTS;
928
+ let giveUp: ReturnType<typeof setTimeout> | undefined;
929
+ const [blocked, setBlocked] = createSignal(false);
930
+
931
+ const reset = (): void => {
932
+ setBlocked(false);
933
+ towards = ALLOWED_INVALID_MOVEMENTS;
934
+ previous = null;
935
+ side = null;
936
+ };
937
+
938
+ // The parent menu stops answering the pointer while the user is on their way
939
+ // across it. Restored on the way out, and on close, by the same effect.
940
+ createEffect(
941
+ () => [access(options.menuRef) as HTMLElement | null, blocked()] as const,
942
+ ([menu_, isBlocked]) => {
943
+ if (menu_ === null) return undefined;
944
+ menu_.style.pointerEvents = isBlocked ? "none" : "";
945
+ return () => {
946
+ menu_.style.pointerEvents = "";
947
+ };
948
+ },
949
+ );
950
+
951
+ createEffect(
952
+ () => {
953
+ const submenu = access(options.submenuRef) as HTMLElement | null;
954
+ const parent = access(options.menuRef) as HTMLElement | null;
955
+ if (
956
+ access(options.isDisabled) === true ||
957
+ submenu === null ||
958
+ parent === null ||
959
+ !access(options.isOpen) ||
960
+ getInteractionModality() !== "pointer"
961
+ ) {
962
+ return null;
963
+ }
964
+ return [submenu, parent] as const;
965
+ },
966
+ (elements) => {
967
+ if (elements === null) {
968
+ reset();
969
+ return undefined;
970
+ }
971
+ const [submenu, parent] = elements;
972
+
973
+ rect = submenu.getBoundingClientRect();
974
+
975
+ const onPointerMove = (event: PointerEvent): void => {
976
+ if (event.pointerType === "touch" || event.pointerType === "pen") return;
977
+
978
+ const now = Date.now();
979
+ if (now - lastProcessed < THROTTLE_TIME) return;
980
+ clearTimeout(giveUp);
981
+
982
+ const x = event.clientX;
983
+ const y = event.clientY;
984
+
985
+ if (previous === null) {
986
+ previous = { x, y };
987
+ return;
988
+ }
989
+ if (rect === null) return;
990
+
991
+ side ??= x > rect.right ? "left" : "right";
992
+
993
+ const bounds = parent.getBoundingClientRect();
994
+ if (x < bounds.left || x > bounds.right || y < bounds.top || y > bounds.bottom) {
995
+ reset();
996
+ return;
997
+ }
998
+
999
+ const toSubmenu = side === "right" ? rect.left - previous.x : previous.x - rect.right;
1000
+ const angleTop = Math.atan2(previous.y - rect.top, toSubmenu) + ANGLE_PADDING;
1001
+ const angleBottom = Math.atan2(previous.y - rect.bottom, toSubmenu) - ANGLE_PADDING;
1002
+ const angle = Math.atan2(previous.y - y, side === "left" ? previous.x - x : x - previous.x);
1003
+ const heading = angle < angleTop && angle > angleBottom;
1004
+
1005
+ towards = heading
1006
+ ? Math.min(towards + 1, ALLOWED_INVALID_MOVEMENTS)
1007
+ : Math.max(towards - 1, 0);
1008
+ setBlocked(towards >= ALLOWED_INVALID_MOVEMENTS);
1009
+
1010
+ lastProcessed = now;
1011
+ previous = { x, y };
1012
+
1013
+ // Heading there but no longer moving: the user has stopped somewhere in
1014
+ // the middle, and the item under them should take the hover after all.
1015
+ if (heading) {
1016
+ giveUp = setTimeout(() => {
1017
+ reset();
1018
+ setTimeout(() => {
1019
+ const under = document.elementFromPoint(x, y);
1020
+ if (under !== null && contains(parent, under)) {
1021
+ under.dispatchEvent(new PointerEvent("pointerover", { bubbles: true }));
1022
+ }
1023
+ }, 100);
1024
+ }, GIVE_UP_TIME);
1025
+ }
1026
+ };
1027
+
1028
+ const view = ownerWindow(parent);
1029
+ view.addEventListener("pointermove", onPointerMove as EventListener);
1030
+
1031
+ return () => {
1032
+ view.removeEventListener("pointermove", onPointerMove as EventListener);
1033
+ clearTimeout(giveUp);
1034
+ towards = ALLOWED_INVALID_MOVEMENTS;
1035
+ };
1036
+ },
1037
+ );
1038
+ }
1039
+
1040
+ export interface SubmenuTriggerOptions {
1041
+ /** The menu the trigger item is in. */
1042
+ parentMenuRef: ElementRef;
1043
+ submenuRef: ElementRef;
1044
+ /**
1045
+ * The id the trigger ITEM already renders under.
1046
+ *
1047
+ * Not generated here: a menu item's id is derived from its key so that
1048
+ * `aria-activedescendant` can name it before it exists, and a second id
1049
+ * generated for the same element would leave `aria-labelledby` on the
1050
+ * submenu pointing at nothing.
1051
+ */
1052
+ triggerId: MaybeAccessor<string>;
1053
+ /** @default "menu" */
1054
+ type?: MaybeAccessor<"menu" | "dialog" | undefined>;
1055
+ /**
1056
+ * Escape inside the submenu closes every menu up to the root, and focus goes
1057
+ * back to what opened the root, as Radix does. Otherwise it closes this
1058
+ * submenu alone and focus goes back to its trigger item. @default false
1059
+ */
1060
+ shouldCloseAllOnEscape?: MaybeAccessor<boolean | undefined>;
1061
+ isDisabled?: MaybeAccessor<boolean | undefined>;
1062
+ /** How long a hover must last before the submenu opens. @default 200 */
1063
+ delay?: MaybeAccessor<number | undefined>;
1064
+ shouldUseVirtualFocus?: MaybeAccessor<boolean | undefined>;
1065
+ }
1066
+
1067
+ export interface SubmenuTriggerResult {
1068
+ /** Options for {@link menuItem}, not props for an element. */
1069
+ submenuTriggerProps: DOMProps;
1070
+ /** Options for the submenu's own {@link menu}. */
1071
+ submenuProps: DOMProps;
1072
+ /** Options for the {@link Popover} the submenu is rendered in. */
1073
+ popoverProps: DOMProps;
1074
+ }
1075
+
1076
+ /**
1077
+ * An item that opens a menu beside itself.
1078
+ *
1079
+ * The direction keys are mirrored for RTL, and the one that OPENS is the one
1080
+ * pointing at where the submenu will appear. Escape and the closing arrow both
1081
+ * put focus back on the trigger, because a submenu that closes leaving focus
1082
+ * nowhere strands a keyboard user.
1083
+ */
1084
+ export function submenuTrigger(
1085
+ options: SubmenuTriggerOptions,
1086
+ state: SubmenuTriggerState,
1087
+ ref: ElementRef,
1088
+ ): SubmenuTriggerResult {
1089
+ const overlayId = id();
1090
+ const locale = useLocale();
1091
+ const type = (): "menu" | "dialog" => access(options.type) ?? "menu";
1092
+ const isDisabled = (): boolean => access(options.isDisabled) === true;
1093
+
1094
+ let opening: ReturnType<typeof setTimeout> | undefined;
1095
+ const cancelOpen = (): void => {
1096
+ clearTimeout(opening);
1097
+ opening = undefined;
1098
+ };
1099
+
1100
+ const openNow = (focusStrategy: FocusStrategy | null = null): void => {
1101
+ cancelOpen();
1102
+ state.open(focusStrategy);
1103
+ };
1104
+
1105
+ const closeNow = (): void => {
1106
+ cancelOpen();
1107
+ state.close();
1108
+ };
1109
+
1110
+ /**
1111
+ * Put focus back on the trigger, AFTER the submenu has gone.
1112
+ *
1113
+ * Not in the same turn as the close: the submenu's focus scope is still
1114
+ * containing focus at that instant and pulls it straight back onto the item
1115
+ * the user was standing on. A frame later the scope is disposed and the
1116
+ * trigger is the right place for focus to be.
1117
+ */
1118
+ const restoreFocus = (): void => {
1119
+ if (access(options.shouldUseVirtualFocus) === true) return;
1120
+ const element = access(ref) as HTMLElement | null;
1121
+ if (element === null) return;
1122
+ requestAnimationFrame(() => {
1123
+ if (element.isConnected) focusWithoutScrolling(element);
1124
+ });
1125
+ };
1126
+
1127
+ tryCleanup(cancelOpen);
1128
+
1129
+ /** The key that opens the submenu, which is the one pointing at it. */
1130
+ const openKey = (): string => (locale().direction === "rtl" ? "ArrowLeft" : "ArrowRight");
1131
+ const closeKey = (): string => (locale().direction === "rtl" ? "ArrowRight" : "ArrowLeft");
1132
+
1133
+ // On the SUBMENU, for getting back out of it.
1134
+ const onSubmenuKeyDown = (event: BaseEvent<KeyboardEvent>): void => {
1135
+ if (event.key !== closeKey() && event.key !== "Escape") {
1136
+ event.continuePropagation();
1137
+ return;
1138
+ }
1139
+ const submenu = access(options.submenuRef) as Element | null;
1140
+ const target = targetElement(event);
1141
+ if (submenu === null || target === null || !contains(submenu, target)) {
1142
+ event.continuePropagation();
1143
+ return;
1144
+ }
1145
+ if (event.key === "Escape" && access(options.shouldCloseAllOnEscape) === true) {
1146
+ cancelOpen();
1147
+ state.closeAll();
1148
+ return;
1149
+ }
1150
+ closeNow();
1151
+ restoreFocus();
1152
+ };
1153
+
1154
+ // On the TRIGGER, for getting into it.
1155
+ const onTriggerKeyDown = (event: BaseEvent<KeyboardEvent>): void => {
1156
+ if (isDisabled()) {
1157
+ event.continuePropagation();
1158
+ return;
1159
+ }
1160
+ if (event.key === openKey()) {
1161
+ if (!state.isOpen()) openNow("first");
1162
+ return;
1163
+ }
1164
+ if (event.key === closeKey() && state.isOpen()) {
1165
+ closeNow();
1166
+ restoreFocus();
1167
+ return;
1168
+ }
1169
+ event.continuePropagation();
1170
+ };
1171
+
1172
+ const { keyboardProps: triggerKeyboardProps } = keyboard({ onKeyDown: onTriggerKeyDown });
1173
+ const { keyboardProps: submenuKeyboardProps } = keyboard({ onKeyDown: onSubmenuKeyDown });
1174
+
1175
+ safelyMouseToSubmenu({
1176
+ menuRef: options.parentMenuRef,
1177
+ submenuRef: options.submenuRef,
1178
+ isOpen: state.isOpen,
1179
+ isDisabled: options.isDisabled,
1180
+ });
1181
+
1182
+ // Focus landing on a DIFFERENT item of the parent menu closes this submenu.
1183
+ // Without it, arrowing past an open trigger leaves its submenu behind.
1184
+ //
1185
+ // The submenu itself is EXCLUDED, and not as a nicety: it renders inside the
1186
+ // trigger item, so it is a DOM descendant of the parent menu, and its own
1187
+ // autofocus would otherwise close it the moment it opened.
1188
+ createEffect(
1189
+ () => access(options.parentMenuRef) as Element | null,
1190
+ (parent) => {
1191
+ if (parent === null) return undefined;
1192
+
1193
+ const onFocusIn = (event: FocusEvent): void => {
1194
+ if (!state.isOpen()) return;
1195
+ const target = targetElement(event);
1196
+ if (target === null || target === access(ref)) return;
1197
+ const submenu = access(options.submenuRef) as Element | null;
1198
+ if (submenu !== null && contains(submenu, target)) return;
1199
+ if (contains(parent, target)) closeNow();
1200
+ };
1201
+
1202
+ parent.addEventListener("focusin", onFocusIn as EventListener);
1203
+ return () => parent.removeEventListener("focusin", onFocusIn as EventListener);
1204
+ },
1205
+ );
1206
+
1207
+ return {
1208
+ submenuTriggerProps: mergeProps(triggerKeyboardProps, {
1209
+ "aria-haspopup": () => (isDisabled() ? undefined : type()),
1210
+ "aria-expanded": () => state.isOpen(),
1211
+ "aria-controls": () => (state.isOpen() ? overlayId() : undefined),
1212
+ onPressStart: (event: PressEvent) => {
1213
+ // A screen reader or a keyboard has no pointer to follow, so the first
1214
+ // item is focused rather than the submenu itself.
1215
+ if (isDisabled()) return;
1216
+ if (event.pointerType === "virtual" || event.pointerType === "keyboard") openNow("first");
1217
+ },
1218
+ onPress: (event: PressEvent) => {
1219
+ if (isDisabled()) return;
1220
+ if (event.pointerType === "touch" || event.pointerType === "mouse") openNow();
1221
+ },
1222
+ onHoverChange: (isHovered: boolean) => {
1223
+ if (isDisabled()) return;
1224
+ if (!isHovered) {
1225
+ cancelOpen();
1226
+ return;
1227
+ }
1228
+ if (state.isOpen() || opening !== undefined) return;
1229
+ opening = setTimeout(
1230
+ () => {
1231
+ opening = undefined;
1232
+ state.open();
1233
+ },
1234
+ access(options.delay) ?? 200,
1235
+ );
1236
+ },
1237
+ }),
1238
+ submenuProps: mergeProps(type() === "menu" ? submenuKeyboardProps : {}, {
1239
+ id: overlayId,
1240
+ "aria-labelledby": () => access(options.triggerId),
1241
+ ...(type() === "menu"
1242
+ ? { onClose: state.closeAll, autoFocus: () => state.focusStrategy() ?? undefined }
1243
+ : {}),
1244
+ }),
1245
+ popoverProps: {
1246
+ // A submenu does not hide the page from assistive technology: the menu
1247
+ // behind it is still the thing the user is in.
1248
+ isModal: false,
1249
+ placement: () => (locale().direction === "rtl" ? "left start" : "right start"),
1250
+ },
1251
+ };
1252
+ }
1253
+
1254
+ // ---------------------------------------------------------------------------
1255
+ // Components
1256
+ // ---------------------------------------------------------------------------
1257
+
1258
+ interface MenuContextValue {
1259
+ state: ListState<unknown>;
1260
+ /** The menu's own id, which every item id is derived from. */
1261
+ baseId: Accessor<string>;
1262
+ /** The `<ul>`, for a submenu's safe triangle and its focus watching. */
1263
+ menuRef: ElementRef;
1264
+ /**
1265
+ * The state at the ROOT of this menu tree, shared by every level.
1266
+ *
1267
+ * A submenu three deep is opened and closed through the same stack as one
1268
+ * beside the trigger, so the root is threaded down rather than re-derived.
1269
+ */
1270
+ root: RootMenuTriggerState;
1271
+ shouldUseVirtualFocus: Accessor<boolean | undefined>;
1272
+ onAction: Accessor<((key: Key) => void) | undefined>;
1273
+ onClose: Accessor<(() => void) | undefined>;
1274
+ /**
1275
+ * Where a `<MenuItem>` written as a child registers itself.
1276
+ *
1277
+ * Present when the menu was given no `items`: the items that render ARE the
1278
+ * collection, and each one says what it is rather than reading a node.
1279
+ */
1280
+ staticItems?: StaticCollection | undefined;
1281
+ }
1282
+
1283
+ const MenuContext = createContext<MenuContextValue | null>(null);
1284
+ const MenuNodeContext = createContext<Node<unknown> | null>(null);
1285
+
1286
+ export function useMenu(): MenuContextValue {
1287
+ const value = getContext(MenuContext);
1288
+ if (value === null || value === undefined) {
1289
+ throw new Error("A MenuItem must be rendered inside a Menu.");
1290
+ }
1291
+ return value;
1292
+ }
1293
+
1294
+ /** The enclosing menu, or `null` when this is the outermost one. */
1295
+ function useEnclosingMenu(): MenuContextValue | null {
1296
+ return getContext(MenuContext) ?? null;
1297
+ }
1298
+
1299
+ /** The collection node the row being built is for. */
1300
+ export function provideMenuNode(node: Node<unknown>): void {
1301
+ const owner = getOwner();
1302
+ if (owner !== null) install(owner, MenuNodeContext, () => node);
1303
+ }
1304
+
1305
+ /** The collection node the enclosing row is for. */
1306
+ export function useMenuNode(): Node<unknown> {
1307
+ const node = getContext(MenuNodeContext);
1308
+ if (node === null || node === undefined) {
1309
+ throw new Error("A MenuItem must be rendered inside its Menu's item callback.");
1310
+ }
1311
+ return node;
1312
+ }
1313
+
1314
+ export interface MenuTriggerValue {
1315
+ state: RootMenuTriggerState;
1316
+ triggerRef: ReturnType<typeof makeRef<HTMLElement>>;
1317
+ menuTriggerProps: DOMProps;
1318
+ menuProps: DOMProps;
1319
+ /**
1320
+ * The box the menu is placed against, when it is not the trigger's own.
1321
+ *
1322
+ * A context menu is anchored to the point the pointer was at. `null` for a
1323
+ * trigger the menu hangs off, which is every other one.
1324
+ */
1325
+ anchorRect: Accessor<AnchorRect | null>;
1326
+ /** Where the menu goes when it is not told. */
1327
+ placement: Placement;
1328
+ /** How far from the anchor the menu sits when it is not told. */
1329
+ offset: number;
1330
+ /**
1331
+ * Key handling for every menu in this trigger's tree, after the menu's own.
1332
+ *
1333
+ * A menubar needs it: the arrow that leaves one menu for its neighbour is
1334
+ * pressed on an ITEM, three submenus deep or none, and belongs to the bar.
1335
+ * `isSubmenu` says which level heard it, since the arrow pointing back at a
1336
+ * submenu's trigger closes that submenu and is not the bar's to take.
1337
+ */
1338
+ onMenuKeyDown?: (event: KeyboardEvent, isSubmenu: boolean) => void;
1339
+ }
1340
+
1341
+ const MenuTriggerContext = createContext<MenuTriggerValue | null>(null);
1342
+
1343
+ /**
1344
+ * Build `children` as the contents of a trigger this module did not make.
1345
+ *
1346
+ * A menubar's menu is a menu trigger whose open state belongs to the bar, so
1347
+ * it builds the value itself and the `<Menu>` inside finds it the usual way.
1348
+ */
1349
+ export function provideMenuTrigger(value: MenuTriggerValue, children: () => unknown): unknown {
1350
+ return provide(MenuTriggerContext, () => value, children);
1351
+ }
1352
+
1353
+ /** The enclosing {@link MenuTrigger}, if there is one. */
1354
+ export function useMenuTrigger(): MenuTriggerValue | null {
1355
+ return getContext(MenuTriggerContext) ?? null;
1356
+ }
1357
+
1358
+ export interface SubmenuTriggerValue {
1359
+ state: SubmenuTriggerState;
1360
+ /**
1361
+ * The `baseId` of the menu the TRIGGER is in.
1362
+ *
1363
+ * Everything inside a `<SubmenuTrigger>` sees this context, the submenu's own
1364
+ * items included, and without this every one of them would think it was the
1365
+ * trigger: `aria-haspopup` on all of them, and a press that opens rather than
1366
+ * chooses. Identity of the accessor is enough, since each menu makes one.
1367
+ */
1368
+ parentBaseId: Accessor<string>;
1369
+ /** The key of the item that opens the submenu. */
1370
+ triggerKey: Key;
1371
+ /** Written by the `<MenuItem>` inside, read by the safe triangle. */
1372
+ triggerRef: ReturnType<typeof makeRef<HTMLLIElement>>;
1373
+ /** Written by the `<Menu>` inside. */
1374
+ submenuRef: ReturnType<typeof makeRef<HTMLUListElement>>;
1375
+ /** Options for {@link menuItem}, not props for an element. */
1376
+ submenuTriggerProps: DOMProps;
1377
+ /** Options for the submenu's own {@link menu}. */
1378
+ submenuProps: DOMProps;
1379
+ popoverProps: DOMProps;
1380
+ }
1381
+
1382
+ const SubmenuTriggerContext = createContext<SubmenuTriggerValue | null>(null);
1383
+
1384
+ /** The enclosing {@link SubmenuTrigger}, if there is one. */
1385
+ export function useSubmenuTrigger(): SubmenuTriggerValue | null {
1386
+ return getContext(SubmenuTriggerContext) ?? null;
1387
+ }
1388
+
1389
+ export interface SubmenuTriggerComponentProps {
1390
+ /** A `<MenuItem>` and the `<Menu>` it opens, in that order. */
1391
+ children?: Child;
1392
+ isDisabled?: boolean;
1393
+ /** How long a hover must last before the submenu opens. @default 200 */
1394
+ delay?: number;
1395
+ /** Escape closes the whole menu rather than this submenu alone. @default false */
1396
+ shouldCloseAllOnEscape?: boolean;
1397
+ }
1398
+
1399
+ /**
1400
+ * A menu item and the menu it opens beside itself.
1401
+ *
1402
+ * ```tsx
1403
+ * <Menu items={actions()}>
1404
+ * {(action) =>
1405
+ * action.children === undefined ? (
1406
+ * <MenuItem>{action.name}</MenuItem>
1407
+ * ) : (
1408
+ * <SubmenuTrigger>
1409
+ * <MenuItem>{action.name}</MenuItem>
1410
+ * <Menu items={action.children}>{(child) => <MenuItem>{child.name}</MenuItem>}</Menu>
1411
+ * </SubmenuTrigger>
1412
+ * )
1413
+ * }
1414
+ * </Menu>
1415
+ * ```
1416
+ *
1417
+ * The two children find each other through this component's context rather
1418
+ * than by position, so the `<MenuItem>` can be wrapped or decorated without
1419
+ * the submenu losing its trigger.
1420
+ */
1421
+ export function SubmenuTrigger(props: Incoming<SubmenuTriggerComponentProps>) {
1422
+ const triggerRef = makeRef<HTMLLIElement>();
1423
+ const submenuRef = makeRef<HTMLUListElement>();
1424
+ const list = useMenu();
1425
+ // In a menu written as children there is no node to read: the trigger item
1426
+ // inside registers under the key made here, which is how the two find each
1427
+ // other.
1428
+ const node: Pick<Node<unknown>, "key" | "props"> = list.staticItems === undefined
1429
+ ? useMenuNode()
1430
+ : { key: createUniqueId(), props: {} };
1431
+
1432
+ const state = submenuTriggerState({ triggerKey: node.key }, list.root);
1433
+
1434
+ const { submenuTriggerProps, submenuProps, popoverProps } = submenuTrigger(
1435
+ {
1436
+ parentMenuRef: list.menuRef,
1437
+ submenuRef,
1438
+ triggerId: () => menuItemIdFor(list.baseId(), node.key),
1439
+ isDisabled: () =>
1440
+ props.isDisabled?.() === true ||
1441
+ node.props?.isDisabled === true ||
1442
+ list.state.collection().getItem(node.key)?.props?.isDisabled === true,
1443
+ delay: () => props.delay?.(),
1444
+ shouldUseVirtualFocus: list.shouldUseVirtualFocus,
1445
+ shouldCloseAllOnEscape: () => props.shouldCloseAllOnEscape?.(),
1446
+ },
1447
+ state,
1448
+ triggerRef,
1449
+ );
1450
+
1451
+ const value: SubmenuTriggerValue = {
1452
+ state,
1453
+ parentBaseId: list.baseId,
1454
+ triggerKey: node.key,
1455
+ triggerRef,
1456
+ submenuRef,
1457
+ submenuTriggerProps,
1458
+ submenuProps,
1459
+ popoverProps,
1460
+ };
1461
+
1462
+ // `provide`, not `install`, for the reason `MenuTrigger` gives: two submenu
1463
+ // triggers in one menu both run their bodies before either one's children
1464
+ // are built.
1465
+ return provide(
1466
+ SubmenuTriggerContext,
1467
+ () => value,
1468
+ () => props.children as unknown,
1469
+ );
1470
+ }
1471
+
1472
+ export interface MenuTriggerComponentProps {
1473
+ children?: Child;
1474
+ isOpen?: boolean;
1475
+ defaultOpen?: boolean;
1476
+ /** @default "press" */
1477
+ trigger?: MenuTriggerType;
1478
+ isDisabled?: boolean;
1479
+ onOpenChange?: (isOpen: boolean) => void;
1480
+ }
1481
+
1482
+ /**
1483
+ * A trigger and its menu, sharing one piece of state.
1484
+ *
1485
+ * ```tsx
1486
+ * <MenuTrigger>
1487
+ * <MenuButton>Actions</MenuButton>
1488
+ * <Menu items={actions()} onAction={(key) => run(key)}>
1489
+ * {(action) => <MenuItem>{action.name}</MenuItem>}
1490
+ * </Menu>
1491
+ * </MenuTrigger>
1492
+ * ```
1493
+ *
1494
+ * The `<Menu>` inside puts itself in a popover anchored to the button and
1495
+ * renders only while open, so neither has to be told about the other.
1496
+ */
1497
+ export function MenuTrigger(props: Incoming<MenuTriggerComponentProps>) {
1498
+ const triggerRef = makeRef<HTMLElement>();
1499
+ const options = fromProps(props);
1500
+ const state = menuTriggerState(options);
1501
+
1502
+ const { menuTriggerProps, menuProps } = menuTrigger(options, state);
1503
+
1504
+ const value: MenuTriggerValue = {
1505
+ state,
1506
+ triggerRef,
1507
+ menuTriggerProps,
1508
+ menuProps,
1509
+ anchorRect: () => null,
1510
+ placement: "bottom start",
1511
+ offset: 8,
1512
+ };
1513
+ const owner = getOwner();
1514
+ if (owner === null) return <>{props.children}</>;
1515
+
1516
+ // `provide`, not `install`: a component gets no scope of its own, so
1517
+ // installing on the ambient owner writes where its SIBLINGS read. Two menu
1518
+ // triggers beside each other both run their bodies before either one's
1519
+ // children are built, and every child of both then sees the second one.
1520
+ return provide(
1521
+ MenuTriggerContext,
1522
+ () => value,
1523
+ () => props.children as unknown,
1524
+ );
1525
+ }
1526
+
1527
+ export interface MenuButtonComponentProps extends StyleProps {
1528
+ children?: Child;
1529
+ isDisabled?: boolean;
1530
+ "aria-label"?: string;
1531
+ ref?: RefTarget<HTMLButtonElement>;
1532
+ }
1533
+
1534
+ /** The button an enclosing {@link MenuTrigger} opens its menu from. */
1535
+ export function MenuButton(props: Incoming<MenuButtonComponentProps>) {
1536
+ const menuTriggerValue = useMenuTrigger();
1537
+ if (menuTriggerValue === null) {
1538
+ throw new Error("A MenuButton must be rendered inside a MenuTrigger.");
1539
+ }
1540
+
1541
+ const options = fromProps(props);
1542
+ const { buttonProps, isPressed } = button(
1543
+ { ...(options as ButtonOptions), ...menuTriggerValue.menuTriggerProps },
1544
+ menuTriggerValue.triggerRef,
1545
+ );
1546
+
1547
+ const { hoverProps, isHovered } = hover({ isDisabled: options.isDisabled });
1548
+ const { focusProps, isFocused, isFocusVisible: showsRing } = focusRing();
1549
+
1550
+ const elementProps = mergeProps(
1551
+ buttonProps,
1552
+ { id: menuTriggerValue.menuTriggerProps.id },
1553
+ hoverProps,
1554
+ focusProps,
1555
+ filterDOMProps(options, { global: true }),
1556
+ styleProps(props),
1557
+ {
1558
+ "data-pressed": isPressed,
1559
+ "data-hovered": isHovered,
1560
+ "data-focused": isFocused,
1561
+ "data-focus-visible": showsRing,
1562
+ "data-disabled": () => props.isDisabled?.() === true,
1563
+ "data-state": () => (menuTriggerValue.state.isOpen() ? "open" : "closed"),
1564
+ "data-testid": () => props["data-testid"]?.(),
1565
+ },
1566
+ );
1567
+
1568
+ return (
1569
+ <button {...elementProps} ref={mergeRefs(menuTriggerValue.triggerRef.set, props.ref?.())}>
1570
+ {props.children}
1571
+ </button>
1572
+ );
1573
+ }
1574
+
1575
+ export interface ContextMenuComponentProps {
1576
+ /** A `<ContextMenuTrigger>` and the `<Menu>` it opens, in that order. */
1577
+ children?: Child;
1578
+ isOpen?: boolean;
1579
+ defaultOpen?: boolean;
1580
+ /** Leave the browser's own menu in place. */
1581
+ isDisabled?: boolean;
1582
+ /** How long a touch must be held before the menu opens. @default 500 */
1583
+ longPressThreshold?: number;
1584
+ onOpenChange?: (isOpen: boolean) => void;
1585
+ }
1586
+
1587
+ /**
1588
+ * A region and the menu a right-click over it opens.
1589
+ *
1590
+ * ```tsx
1591
+ * <ContextMenu>
1592
+ * <ContextMenuTrigger>Right-click anywhere in here</ContextMenuTrigger>
1593
+ * <Menu items={actions()} aria-label="Actions" onAction={(key) => run(key)}>
1594
+ * {(action) => <MenuItem>{action.name}</MenuItem>}
1595
+ * </Menu>
1596
+ * </ContextMenu>
1597
+ * ```
1598
+ *
1599
+ * Give the menu an `aria-label`. Every other menu here is named by the control
1600
+ * that opens it, and this one's trigger is a region of content whose whole text
1601
+ * would otherwise be read out as the menu's name.
1602
+ */
1603
+ export function ContextMenu(props: Incoming<ContextMenuComponentProps>) {
1604
+ const triggerRef = makeRef<HTMLElement>();
1605
+ const options = fromProps(props);
1606
+ const state = menuTriggerState(options);
1607
+
1608
+ const { contextMenuTriggerProps, menuProps, anchorRect } = contextMenuTrigger(options, state);
1609
+
1610
+ const value: MenuTriggerValue = {
1611
+ state,
1612
+ triggerRef,
1613
+ menuTriggerProps: contextMenuTriggerProps,
1614
+ menuProps,
1615
+ anchorRect,
1616
+ // A point has no side to hang off, so the menu goes down and to the right
1617
+ // of it, which is where every platform's own context menu goes.
1618
+ placement: "right top",
1619
+ offset: 2,
1620
+ };
1621
+
1622
+ // `provide`, not `install`, for the reason `MenuTrigger` gives.
1623
+ return provide(
1624
+ MenuTriggerContext,
1625
+ () => value,
1626
+ () => props.children as unknown,
1627
+ );
1628
+ }
1629
+
1630
+ export interface ContextMenuTriggerComponentProps extends StyleProps {
1631
+ children?: Child;
1632
+ ref?: RefTarget<HTMLElement>;
1633
+ }
1634
+
1635
+ /**
1636
+ * The region an enclosing {@link ContextMenu} belongs to.
1637
+ *
1638
+ * The only trigger here that renders an element of its own, and it has to:
1639
+ * there is no control for the pointer to land on, only an area.
1640
+ *
1641
+ * Shift+F10 and the Menu key open the menu from wherever the keyboard is
1642
+ * inside the region, so a region whose content is not focusable needs a
1643
+ * `tabIndex` of its own or there is no keyboard route to the menu at all.
1644
+ */
1645
+ export function ContextMenuTrigger(props: Incoming<ContextMenuTriggerComponentProps>) {
1646
+ const trigger = useMenuTrigger();
1647
+ if (trigger === null) {
1648
+ throw new Error("A ContextMenuTrigger must be rendered inside a ContextMenu.");
1649
+ }
1650
+
1651
+ const options = fromProps(props);
1652
+ const elementProps = mergeProps(
1653
+ trigger.menuTriggerProps,
1654
+ filterDOMProps(options, { global: true, labelable: true }),
1655
+ styleProps(props),
1656
+ { "data-testid": () => props["data-testid"]?.() },
1657
+ );
1658
+
1659
+ return (
1660
+ <div {...elementProps} ref={mergeRefs(trigger.triggerRef.set, props.ref?.())}>
1661
+ {props.children}
1662
+ </div>
1663
+ );
1664
+ }
1665
+
1666
+ export interface MenuComponentProps<T> extends StyleProps, ItemAccessors<T> {
1667
+ /**
1668
+ * The values to render, in order.
1669
+ *
1670
+ * Leave it out and the `<MenuItem>`s written as children are the collection:
1671
+ * each one says what it is and what choosing it does.
1672
+ */
1673
+ items?: Iterable<T>;
1674
+ /** How one value renders, returning a `<MenuItem>` or a `<MenuSection>`; or the items themselves. */
1675
+ children: ((item: T) => Child) | Child;
1676
+ /** @default "none" */
1677
+ selectionMode?: SelectionMode;
1678
+ selectedKeys?: "all" | Iterable<Key>;
1679
+ defaultSelectedKeys?: "all" | Iterable<Key>;
1680
+ disabledKeys?: Iterable<Key>;
1681
+ disallowEmptySelection?: boolean;
1682
+ /** @default true */
1683
+ shouldFocusWrap?: boolean;
1684
+ autoFocus?: boolean | "first" | "last";
1685
+ "aria-label"?: string;
1686
+ "aria-labelledby"?: string;
1687
+ /** Where the popover goes, when inside a {@link MenuTrigger}. @default "bottom start" */
1688
+ placement?: Placement;
1689
+ offset?: number;
1690
+ /** Distance along the trigger's edge, from where `placement` aligns it. @default 0 */
1691
+ crossOffset?: number;
1692
+ ref?: RefTarget<HTMLUListElement>;
1693
+ onSelectionChange?: (keys: "all" | Set<Key>) => void;
1694
+ onAction?: (key: Key) => void;
1695
+ onClose?: () => void;
1696
+ }
1697
+
1698
+ /**
1699
+ * ```tsx
1700
+ * <Menu items={actions()} onAction={(key) => run(key)}>
1701
+ * {(action) => <MenuItem>{action.name}</MenuItem>}
1702
+ * </Menu>
1703
+ * ```
1704
+ *
1705
+ * The items are DATA, as they are for a listbox: a component whose body runs
1706
+ * once has no reason to render them twice, once to discover them and once to
1707
+ * show them.
1708
+ */
1709
+ export function Menu<T>(props: Incoming<MenuComponentProps<T>>) {
1710
+ const enclosing = useSubmenuTrigger();
1711
+ const parent = useEnclosingMenu();
1712
+ // The submenu of the trigger this menu sits in, rather than of a trigger
1713
+ // further up: a menu nested inside a submenu's own items is not it.
1714
+ const submenu =
1715
+ enclosing !== null && parent !== null && enclosing.parentBaseId === parent.baseId
1716
+ ? enclosing
1717
+ : null;
1718
+
1719
+ // A submenu is anchored to its trigger ITEM and sits beside it, and it is
1720
+ // checked first: a submenu is also inside the root `<MenuTrigger>`, whose
1721
+ // popover is already open and holding the menu this one opens from.
1722
+ if (submenu !== null) {
1723
+ return (
1724
+ <Popover
1725
+ triggerRef={submenu.triggerRef}
1726
+ isOpen={submenu.state.isOpen()}
1727
+ onOpenChange={(isOpen: boolean) => {
1728
+ if (!isOpen) submenu.state.close();
1729
+ }}
1730
+ placement={
1731
+ props.placement?.() ?? access(submenu.popoverProps.placement as MaybeAccessor<Placement>)
1732
+ }
1733
+ offset={props.offset?.() ?? 0}
1734
+ crossOffset={props.crossOffset?.()}
1735
+ isNested
1736
+ >
1737
+ <MenuList of={props} trigger={null} />
1738
+ </Popover>
1739
+ );
1740
+ }
1741
+
1742
+ const trigger = useMenuTrigger();
1743
+
1744
+ if (trigger === null) return <MenuList of={props} trigger={null} />;
1745
+
1746
+ // The list is written inside the popover rather than built and handed to it,
1747
+ // so it is a Block: nothing is constructed until the menu opens, and the
1748
+ // autofocus reads the focus strategy the opening keypress set.
1749
+ return (
1750
+ <Popover
1751
+ triggerRef={trigger.triggerRef}
1752
+ triggerRect={trigger.anchorRect()}
1753
+ isOpen={trigger.state.isOpen()}
1754
+ onOpenChange={trigger.state.setOpen}
1755
+ placement={props.placement?.() ?? trigger.placement}
1756
+ offset={props.offset?.() ?? trigger.offset}
1757
+ crossOffset={props.crossOffset?.()}
1758
+ >
1759
+ <MenuList of={props} trigger={trigger} />
1760
+ </Popover>
1761
+ );
1762
+ }
1763
+
1764
+ interface MenuListProps<T> {
1765
+ /** The `<Menu>`'s own props, still as Cells. */
1766
+ of: Incoming<MenuComponentProps<T>>;
1767
+ trigger: MenuTriggerValue | null;
1768
+ }
1769
+
1770
+ function MenuList<T>(listProps: Incoming<MenuListProps<T>>) {
1771
+ const domRef = makeRef<HTMLUListElement>();
1772
+ const props = listProps.of();
1773
+ const options = fromProps(props as unknown as Incoming<Record<string, unknown>>);
1774
+ const trigger = listProps.trigger();
1775
+ const enclosing = useEnclosingMenu();
1776
+ const trigger_ = useSubmenuTrigger();
1777
+ // The same guard `<Menu>` applies: a menu nested inside a submenu's items is
1778
+ // not that submenu.
1779
+ const submenu =
1780
+ trigger_ !== null && enclosing !== null && trigger_.parentBaseId === enclosing.baseId
1781
+ ? trigger_
1782
+ : null;
1783
+
1784
+ // One root for the whole tree. A menu with no trigger above it is its own
1785
+ // root, so a submenu still works inside a menu rendered inline.
1786
+ const root = enclosing?.root ?? trigger?.state ?? menuTriggerState();
1787
+ const written = props.items === undefined ? staticCollection() : null;
1788
+ // The trigger at the top of the tree, which a submenu is not handed.
1789
+ const treeKeyDown = useMenuTrigger()?.onMenuKeyDown;
1790
+
1791
+ const state = listState<T>({
1792
+ ...(options as ListStateOptions<T>),
1793
+ ...(written === null
1794
+ ? {}
1795
+ : ({ items: written.entries, ...staticAccessors } as unknown as ListStateOptions<T>)),
1796
+ onSelectionChange: (keys) => props.onSelectionChange?.()?.(keys),
1797
+ });
1798
+
1799
+ const close = (): void => {
1800
+ props.onClose?.()?.();
1801
+ if (submenu !== null) submenu.state.closeAll();
1802
+ trigger?.state.close();
1803
+ };
1804
+
1805
+ const { menuProps, baseId } = menu(
1806
+ {
1807
+ ...(options as unknown as MenuOptions),
1808
+ ...(submenu === null ? {} : (submenu.submenuProps as Record<string, never>)),
1809
+ ...(treeKeyDown === undefined
1810
+ ? {}
1811
+ : {
1812
+ onKeyDown: (event: KeyboardEvent): void => {
1813
+ (submenu?.submenuProps.onKeyDown as ((event: KeyboardEvent) => void) | undefined)?.(
1814
+ event,
1815
+ );
1816
+ treeKeyDown(event, submenu !== null);
1817
+ },
1818
+ }),
1819
+ ref: domRef,
1820
+ // A submenu with no label of its own is named by the ITEM that opens it,
1821
+ // which is what a screen reader announces on the way in.
1822
+ "aria-labelledby": () =>
1823
+ props["aria-labelledby"]?.() ??
1824
+ (props["aria-label"]?.() !== undefined
1825
+ ? undefined
1826
+ : (access(
1827
+ (submenu?.submenuProps["aria-labelledby"] ??
1828
+ trigger?.menuProps["aria-labelledby"]) as MaybeAccessor<string | undefined>,
1829
+ ) ?? undefined)),
1830
+ autoFocus: () =>
1831
+ props.autoFocus?.() ??
1832
+ (submenu === null
1833
+ ? trigger === null
1834
+ ? undefined
1835
+ : access(trigger.menuProps.autoFocus as MaybeAccessor<boolean | "first" | "last">)
1836
+ : (submenu.state.focusStrategy() ?? undefined)),
1837
+ onClose: close,
1838
+ },
1839
+ state,
1840
+ );
1841
+
1842
+ const owner = getOwner();
1843
+ if (owner !== null) {
1844
+ const value: MenuContextValue = {
1845
+ state: state,
1846
+ baseId,
1847
+ menuRef: domRef,
1848
+ root,
1849
+ shouldUseVirtualFocus: () => undefined,
1850
+ onAction: () => props.onAction?.(),
1851
+ onClose: () => close,
1852
+ staticItems: written ?? undefined,
1853
+ };
1854
+ install(owner, MenuContext, () => value);
1855
+ }
1856
+
1857
+ const elementProps = mergeProps(
1858
+ menuProps,
1859
+ filterDOMProps(options, { global: true }),
1860
+ styleProps(props),
1861
+ {
1862
+ id: () =>
1863
+ access(
1864
+ (submenu?.submenuProps.id ?? trigger?.menuProps.id) as MaybeAccessor<string | undefined>,
1865
+ ),
1866
+ "data-testid": () => props["data-testid"]?.(),
1867
+ "data-empty": () => state.collection().size === 0,
1868
+ },
1869
+ // The popover's own element is the positioner; this is the one a design
1870
+ // system names, so the side and the state are repeated on it.
1871
+ popoverStateProps(),
1872
+ );
1873
+
1874
+ if (written !== null) {
1875
+ return (
1876
+ <ul {...elementProps} ref={mergeRefs(domRef.set, submenu?.submenuRef.set, props.ref?.())}>
1877
+ {props.children}
1878
+ </ul>
1879
+ );
1880
+ }
1881
+
1882
+ const render = props.children;
1883
+
1884
+ return (
1885
+ <ul {...elementProps} ref={mergeRefs(domRef.set, submenu?.submenuRef.set, props.ref?.())}>
1886
+ <For each={() => [...state.collection()]}>
1887
+ {(node: Node<T>) => {
1888
+ provideMenuNode(node);
1889
+ return render(node.value as T);
1890
+ }}
1891
+ </For>
1892
+ </ul>
1893
+ );
1894
+ }
1895
+
1896
+ export interface MenuItemComponentProps extends StyleProps {
1897
+ children?: Child;
1898
+ "aria-label"?: string;
1899
+ /** Override when the menu closes on this item. */
1900
+ shouldCloseOnSelect?: boolean;
1901
+ ref?: RefTarget<HTMLLIElement>;
1902
+ /**
1903
+ * The item's key, when it is written as a child of a menu with no `items`:
1904
+ * what the menu's `onAction` reports. Generated when left out, and never the
1905
+ * element's own `id`, which is derived from it.
1906
+ */
1907
+ id?: string;
1908
+ /** What a typeahead matches, for a written item. @default its own text */
1909
+ textValue?: string;
1910
+ /** For a written item; one rendered from data reads its item's. */
1911
+ isDisabled?: boolean;
1912
+ /**
1913
+ * Makes a written item a link; one rendered from data reads its item's
1914
+ * `href`. See {@link MenuItem} for what that renders.
1915
+ */
1916
+ href?: string;
1917
+ target?: string;
1918
+ rel?: string;
1919
+ download?: boolean | string;
1920
+ /**
1921
+ * What a written item is. A `radio` inside a {@link MenuRadioGroup} and a
1922
+ * `checkbox` given `isSelected`, `defaultSelected` or `onChange` are both
1923
+ * recognised without it.
1924
+ */
1925
+ type?: MenuItemType;
1926
+ /** Whether a written checkbox item is ticked. */
1927
+ isSelected?: boolean;
1928
+ defaultSelected?: boolean;
1929
+ /** Called when a written checkbox item is turned over. */
1930
+ onChange?: (isSelected: boolean) => void;
1931
+ /** What a written radio item stands for in its {@link MenuRadioGroup}. */
1932
+ value?: string;
1933
+ /** Called when a written item is chosen. */
1934
+ onAction?: () => void;
1935
+ /** Called when the item is chosen, before the menu closes; preventing it keeps the menu open. */
1936
+ onSelect?: (event: MenuSelectEvent) => void;
1937
+ }
1938
+
1939
+ /**
1940
+ * One item. Rendered from data, its key, value and disabled state come from the
1941
+ * collection node the enclosing {@link Menu} is rendering, so nothing is
1942
+ * repeated here; written as a child, it says those things itself.
1943
+ *
1944
+ * An item with an `href` is a real `<a role="menuitem">` inside a
1945
+ * presentational `<li>`, so a middle click and "copy link address" mean what
1946
+ * they mean on any link. Choosing it is followed through the router with the
1947
+ * modifiers the press carried, which is what keeps a Control-click a new tab
1948
+ * and lets the menu close in the same gesture. A disabled one has no `href`.
1949
+ */
1950
+ export function MenuItem(props: Incoming<MenuItemComponentProps>) {
1951
+ const domRef = makeRef<HTMLElement>();
1952
+ const list = useMenu();
1953
+ const enclosing = useSubmenuTrigger();
1954
+ const registry = list.staticItems;
1955
+ // Written, the only item of THIS menu inside a `<SubmenuTrigger>` is the
1956
+ // trigger: the submenu's own items belong to the menu it opens.
1957
+ const opensWritten =
1958
+ registry !== undefined && enclosing !== null && enclosing.parentBaseId === list.baseId
1959
+ ? enclosing
1960
+ : null;
1961
+ const group = registry === undefined ? null : (getContext(MenuRadioGroupContext) ?? null);
1962
+ const ownType = (): MenuItemType | undefined => {
1963
+ if (registry === undefined) return undefined;
1964
+ const declared = props.type?.();
1965
+ if (declared !== undefined) return declared;
1966
+ if (group !== null && props.value !== undefined) return "radio";
1967
+ return props.isSelected !== undefined ||
1968
+ props.defaultSelected !== undefined ||
1969
+ props.onChange !== undefined
1970
+ ? "checkbox"
1971
+ : "item";
1972
+ };
1973
+ const ticked =
1974
+ registry === undefined
1975
+ ? null
1976
+ : toggleState({
1977
+ isSelected: () => props.isSelected?.(),
1978
+ defaultSelected: () => props.defaultSelected?.(),
1979
+ onChange: (isSelected) => props.onChange?.()?.(isSelected),
1980
+ });
1981
+
1982
+ const written =
1983
+ registry === undefined
1984
+ ? null
1985
+ : staticItem(registry, {
1986
+ key: opensWritten?.triggerKey ?? props.id?.(),
1987
+ textValue: () => props.textValue?.(),
1988
+ props: () => ({
1989
+ isDisabled: props.isDisabled?.() === true,
1990
+ href: props.href?.(),
1991
+ target: props.target?.(),
1992
+ rel: props.rel?.(),
1993
+ download: props.download?.(),
1994
+ onAction: props.onAction?.(),
1995
+ }),
1996
+ });
1997
+ const node: Pick<Node<unknown>, "key" | "props"> = written === null
1998
+ ? useMenuNode()
1999
+ : { key: written.key, props: {} };
2000
+ // Inside a `<SubmenuTrigger>` this item IS the trigger, and takes its
2001
+ // handlers and its `aria-haspopup` on top of an ordinary item's. The
2002
+ // submenu's OWN items are inside that same context and are not.
2003
+ const submenu =
2004
+ enclosing !== null &&
2005
+ enclosing.parentBaseId === list.baseId &&
2006
+ enclosing.triggerKey === node.key
2007
+ ? enclosing
2008
+ : null;
2009
+ const opens = submenu?.submenuTriggerProps ?? {};
2010
+
2011
+ const { menuItemProps, isSelected, isFocused, isPressed, isDisabled } = menuItem(
2012
+ {
2013
+ key: node.key,
2014
+ ref: domRef,
2015
+ baseId: list.baseId,
2016
+ "aria-label": () => props["aria-label"]?.(),
2017
+ isDisabled: () => props.isDisabled?.() === true || node.props?.isDisabled === true,
2018
+ shouldCloseOnSelect: () => props.shouldCloseOnSelect?.(),
2019
+ shouldUseVirtualFocus: list.shouldUseVirtualFocus,
2020
+ type: ownType,
2021
+ isSelected: () =>
2022
+ ownType() === "radio" ? group?.value() === props.value?.() : ticked?.isSelected(),
2023
+ onToggle: () => {
2024
+ const value = props.value?.();
2025
+ if (ownType() === "radio") {
2026
+ if (value !== undefined) group?.setValue(value);
2027
+ } else ticked?.toggle();
2028
+ },
2029
+ onSelect: (event) => props.onSelect?.()?.(event),
2030
+ onAction: (key) => list.onAction()?.(key),
2031
+ onClose: () => list.onClose()?.(),
2032
+ ...(opens as unknown as Record<string, never>),
2033
+ },
2034
+ list.state,
2035
+ );
2036
+
2037
+ const { hoverProps, isHovered } = hover({ isDisabled });
2038
+ const { focusProps, isFocusVisible: showsRing } = focusRing();
2039
+
2040
+ const toHref = router().href;
2041
+ const linked = (name: "href" | "target" | "rel" | "download"): unknown =>
2042
+ props[name]?.() ?? node.props?.[name];
2043
+ const href = (): string | undefined => {
2044
+ const to = linked("href");
2045
+ return typeof to === "string" ? to : undefined;
2046
+ };
2047
+ const isLink = href() !== undefined;
2048
+ const checks = (): boolean => {
2049
+ const role = access(menuItemProps.role as MaybeAccessor<string>);
2050
+ return submenu === null && (role === "menuitemcheckbox" || role === "menuitemradio");
2051
+ };
2052
+
2053
+ const elementProps = mergeProps(
2054
+ menuItemProps,
2055
+ hoverProps,
2056
+ focusProps,
2057
+ // A written item's `id` is its key; the element's id is derived from it.
2058
+ filterDOMProps(fromProps(props), { global: true, labelable: true, id: written === null }),
2059
+ styleProps(props),
2060
+ {
2061
+ "data-selected": isSelected,
2062
+ "data-focused": isFocused,
2063
+ // Radix's name for the same thing, so a rule written for it applies.
2064
+ "data-highlighted": isFocused,
2065
+ "data-focus-visible": showsRing,
2066
+ "data-pressed": isPressed,
2067
+ "data-hovered": isHovered,
2068
+ "data-disabled": isDisabled,
2069
+ "data-state": () => {
2070
+ if (submenu !== null) return submenu.state.isOpen() ? "open" : "closed";
2071
+ if (!checks()) return undefined;
2072
+ return isSelected() ? "checked" : "unchecked";
2073
+ },
2074
+ "data-testid": () => props["data-testid"]?.(),
2075
+ },
2076
+ );
2077
+
2078
+ if (isLink) {
2079
+ const linkProps = mergeProps(elementProps, {
2080
+ href: () => {
2081
+ const to = href();
2082
+ return to === undefined || isDisabled() ? undefined : toHref(to);
2083
+ },
2084
+ target: () => linked("target"),
2085
+ rel: () => linked("rel"),
2086
+ download: () => linked("download"),
2087
+ // The press follows the link, so no other click may: not the one that
2088
+ // carried the press, and not the one `press` makes for a key the browser
2089
+ // would ignore. The click the router dispatches is let through.
2090
+ onClick: (event: MouseEvent) => {
2091
+ if (!isOpeningLink()) event.preventDefault();
2092
+ },
2093
+ });
2094
+ const anchorRef = (element: HTMLAnchorElement | null): void => {
2095
+ domRef.set(element);
2096
+ written?.ref(element);
2097
+ };
2098
+
2099
+ return (
2100
+ <li role="none">
2101
+ <a {...linkProps} ref={anchorRef}>
2102
+ {props.children}
2103
+ </a>
2104
+ </li>
2105
+ );
2106
+ }
2107
+
2108
+ return (
2109
+ <li
2110
+ {...elementProps}
2111
+ ref={mergeRefs(domRef.set, submenu?.triggerRef.set, written?.ref, props.ref?.())}
2112
+ >
2113
+ {props.children}
2114
+ </li>
2115
+ );
2116
+ }
2117
+
2118
+ interface MenuRadioGroupValue {
2119
+ value: Accessor<string | undefined>;
2120
+ setValue: (value: string) => void;
2121
+ }
2122
+
2123
+ const MenuRadioGroupContext = createContext<MenuRadioGroupValue | null>(null);
2124
+
2125
+ interface MenuGroupHeading {
2126
+ id: Accessor<string>;
2127
+ readonly name: (has: boolean) => void;
2128
+ }
2129
+
2130
+ const MenuGroupHeadingContext = createContext<MenuGroupHeading | null>(null);
2131
+
2132
+ /**
2133
+ * The id the enclosing group's heading must carry, for a heading written as
2134
+ * one of the group's children.
2135
+ *
2136
+ * Calling it is what makes the group point at the heading, and leaving undoes
2137
+ * that, so a group never names an element that is not there.
2138
+ */
2139
+ export function useMenuGroupHeading(): Accessor<string> | null {
2140
+ const heading = getContext(MenuGroupHeadingContext);
2141
+ if (heading === null || heading === undefined) return null;
2142
+ heading.name(true);
2143
+ onCleanup(() => heading.name(false));
2144
+ return heading.id;
2145
+ }
2146
+
2147
+ interface WrittenGroupProps extends StyleProps {
2148
+ heading?: Child;
2149
+ "aria-label"?: string;
2150
+ "aria-labelledby"?: string;
2151
+ children?: Child;
2152
+ }
2153
+
2154
+ /**
2155
+ * A `role="group"` around items written as children.
2156
+ *
2157
+ * It registers nothing: the items inside are the menu's own, in document
2158
+ * order, so the arrows cross the boundary without the group taking part.
2159
+ */
2160
+ function WrittenGroup(groupProps: Incoming<{ of: Incoming<WrittenGroupProps> }>) {
2161
+ const props = groupProps.of();
2162
+ const headingId = id();
2163
+ const [isNamed, setNamed] = createSignal(false, { ownedWrite: true });
2164
+ const hasHeading = (): boolean => props.heading?.() !== undefined;
2165
+ const heading: MenuGroupHeading = { id: headingId, name: setNamed };
2166
+
2167
+ return (
2168
+ <li role="presentation">
2169
+ {props.heading === undefined ? null : (
2170
+ <span role="presentation" id={headingId()}>
2171
+ {props.heading}
2172
+ </span>
2173
+ )}
2174
+ <ul
2175
+ {...mergeProps(filterDOMProps(fromProps(props), { global: true }), styleProps(props), {
2176
+ "data-testid": () => props["data-testid"]?.(),
2177
+ })}
2178
+ role="group"
2179
+ aria-label={props["aria-label"]?.()}
2180
+ aria-labelledby={
2181
+ props["aria-labelledby"]?.() ?? (hasHeading() || isNamed() ? headingId() : undefined)
2182
+ }
2183
+ >
2184
+ {provide(
2185
+ MenuGroupHeadingContext,
2186
+ () => heading,
2187
+ () => props.children as unknown,
2188
+ )}
2189
+ </ul>
2190
+ </li>
2191
+ );
2192
+ }
2193
+
2194
+ export interface MenuRadioGroupComponentProps extends StyleProps {
2195
+ /** The `value` of the radio item that is on. */
2196
+ value?: string;
2197
+ defaultValue?: string;
2198
+ onValueChange?: (value: string) => void;
2199
+ heading?: Child;
2200
+ "aria-label"?: string;
2201
+ "aria-labelledby"?: string;
2202
+ children?: Child;
2203
+ }
2204
+
2205
+ /**
2206
+ * A set of written radio items of which one is on.
2207
+ *
2208
+ * ```tsx
2209
+ * <Menu aria-label="View">
2210
+ * <MenuRadioGroup value={density()} onValueChange={setDensity} aria-label="Density">
2211
+ * <MenuItem value="compact">Compact</MenuItem>
2212
+ * <MenuItem value="comfortable">Comfortable</MenuItem>
2213
+ * </MenuRadioGroup>
2214
+ * </Menu>
2215
+ * ```
2216
+ *
2217
+ * The group owns the value rather than the menu, because a written menu can
2218
+ * hold two of these beside a checkbox and a plain item.
2219
+ */
2220
+ export function MenuRadioGroup(props: Incoming<MenuRadioGroupComponentProps>) {
2221
+ const [value, setValue] = controllable<string | undefined>(
2222
+ () => props.value?.(),
2223
+ () => props.defaultValue?.(),
2224
+ (next) => {
2225
+ if (next !== undefined) props.onValueChange?.()?.(next);
2226
+ },
2227
+ );
2228
+ const group: MenuRadioGroupValue = { value, setValue };
2229
+
2230
+ return provide(
2231
+ MenuRadioGroupContext,
2232
+ () => group,
2233
+ () => <WrittenGroup of={props} />,
2234
+ );
2235
+ }
2236
+
2237
+ export interface MenuSectionComponentProps<T> extends StyleProps {
2238
+ heading?: Child;
2239
+ "aria-label"?: string;
2240
+ "aria-labelledby"?: string;
2241
+ /** How one child of this section renders; or, in a written menu, its items. */
2242
+ children: ((item: T) => Child) | Child;
2243
+ }
2244
+
2245
+ /**
2246
+ * A group of items inside a menu, taken from the section node the enclosing
2247
+ * {@link Menu} is rendering.
2248
+ *
2249
+ * ```tsx
2250
+ * <Menu items={grouped()}>
2251
+ * {(entry) =>
2252
+ * entry.children === undefined ? (
2253
+ * <MenuItem>{entry.name}</MenuItem>
2254
+ * ) : (
2255
+ * <MenuSection heading={entry.name}>
2256
+ * {(child) => <MenuItem>{child.name}</MenuItem>}
2257
+ * </MenuSection>
2258
+ * )
2259
+ * }
2260
+ * </Menu>
2261
+ * ```
2262
+ */
2263
+ export function MenuSection<T>(props: Incoming<MenuSectionComponentProps<T>>) {
2264
+ if (useMenu().staticItems !== undefined) {
2265
+ return <WrittenGroup of={props} />;
2266
+ }
2267
+
2268
+ const node = useMenuNode();
2269
+
2270
+ const { itemProps, headingProps, groupProps } = menuSection({
2271
+ heading: () => props.heading?.(),
2272
+ "aria-label": () => props["aria-label"]?.(),
2273
+ });
2274
+
2275
+ const render = props.children;
2276
+
2277
+ return (
2278
+ <li {...itemProps}>
2279
+ <span {...headingProps}>{props.heading}</span>
2280
+ <ul {...mergeProps(groupProps, styleProps(props))}>
2281
+ <For each={() => [...node.childNodes]}>
2282
+ {(child: Node<unknown>) => {
2283
+ provideMenuNode(child);
2284
+ return render(child.value as T);
2285
+ }}
2286
+ </For>
2287
+ </ul>
2288
+ </li>
2289
+ );
2290
+ }