@funstack/ui 0.1.0-alpha.13 → 0.1.0-alpha.15

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 (106) hide show
  1. package/dist/accordion/accordion-root.d.mts.map +1 -1
  2. package/dist/accordion/accordion-root.mjs +5 -4
  3. package/dist/accordion/accordion-root.mjs.map +1 -1
  4. package/dist/checkbox-group/checkbox-group-root.d.mts.map +1 -1
  5. package/dist/checkbox-group/checkbox-group-root.mjs +4 -5
  6. package/dist/checkbox-group/checkbox-group-root.mjs.map +1 -1
  7. package/dist/combobox/combobox-context.mjs.map +1 -1
  8. package/dist/combobox/combobox-input.d.mts +7 -6
  9. package/dist/combobox/combobox-input.d.mts.map +1 -1
  10. package/dist/combobox/combobox-input.mjs +6 -5
  11. package/dist/combobox/combobox-input.mjs.map +1 -1
  12. package/dist/combobox/combobox-label.d.mts +2 -1
  13. package/dist/combobox/combobox-label.d.mts.map +1 -1
  14. package/dist/combobox/combobox-label.mjs +2 -1
  15. package/dist/combobox/combobox-label.mjs.map +1 -1
  16. package/dist/combobox/combobox-popup.d.mts +4 -2
  17. package/dist/combobox/combobox-popup.d.mts.map +1 -1
  18. package/dist/combobox/combobox-popup.mjs +7 -3
  19. package/dist/combobox/combobox-popup.mjs.map +1 -1
  20. package/dist/combobox/combobox-root.d.mts.map +1 -1
  21. package/dist/combobox/combobox-root.mjs +9 -80
  22. package/dist/combobox/combobox-root.mjs.map +1 -1
  23. package/dist/combobox/combobox-trigger.d.mts +15 -10
  24. package/dist/combobox/combobox-trigger.d.mts.map +1 -1
  25. package/dist/combobox/combobox-trigger.mjs +28 -19
  26. package/dist/combobox/combobox-trigger.mjs.map +1 -1
  27. package/dist/combobox/index.d.mts +2 -2
  28. package/dist/combobox/index.mjs +2 -2
  29. package/dist/combobox/index.mjs.map +1 -1
  30. package/dist/combobox/use-deferred-leave.mjs +105 -0
  31. package/dist/combobox/use-deferred-leave.mjs.map +1 -0
  32. package/dist/dialog/dialog-context.mjs.map +1 -1
  33. package/dist/dialog/dialog-popup.d.mts.map +1 -1
  34. package/dist/dialog/dialog-popup.mjs +5 -4
  35. package/dist/dialog/dialog-popup.mjs.map +1 -1
  36. package/dist/dialog/dialog-trigger.mjs.map +1 -1
  37. package/dist/form/form-root.mjs +1 -1
  38. package/dist/form/form-root.mjs.map +1 -1
  39. package/dist/internal/anchor-position.mjs.map +1 -1
  40. package/dist/internal/announce.mjs +12 -7
  41. package/dist/internal/announce.mjs.map +1 -1
  42. package/dist/internal/focus-first-invalid.mjs +2 -11
  43. package/dist/internal/focus-first-invalid.mjs.map +1 -1
  44. package/dist/internal/focus-visible.mjs +26 -0
  45. package/dist/internal/focus-visible.mjs.map +1 -0
  46. package/dist/internal/invokers.mjs +63 -0
  47. package/dist/internal/invokers.mjs.map +1 -0
  48. package/dist/internal/platform-attributes.d.mts +2 -1
  49. package/dist/internal/platform-attributes.d.mts.map +1 -1
  50. package/dist/internal/pointer-capture.mjs +1 -1
  51. package/dist/internal/pointer-capture.mjs.map +1 -1
  52. package/dist/internal/render-element.mjs.map +1 -1
  53. package/dist/internal/trigger-ref.mjs +3 -3
  54. package/dist/internal/trigger-ref.mjs.map +1 -1
  55. package/dist/internal/use-interest-dismiss.mjs +84 -0
  56. package/dist/internal/use-interest-dismiss.mjs.map +1 -0
  57. package/dist/internal/use-overlay-root.mjs +2 -1
  58. package/dist/internal/use-overlay-root.mjs.map +1 -1
  59. package/dist/internal/use-popover-popup.mjs +59 -48
  60. package/dist/internal/use-popover-popup.mjs.map +1 -1
  61. package/dist/internal/use-popover-trigger.d.mts.map +1 -1
  62. package/dist/internal/use-popover-trigger.mjs +37 -15
  63. package/dist/internal/use-popover-trigger.mjs.map +1 -1
  64. package/dist/internal/use-resolved-placement.mjs +1 -1
  65. package/dist/internal/use-resolved-placement.mjs.map +1 -1
  66. package/dist/internal/use-value-set.mjs +20 -0
  67. package/dist/internal/use-value-set.mjs.map +1 -0
  68. package/dist/menu/menu-context.mjs.map +1 -1
  69. package/dist/menu/menu-popup.d.mts +3 -1
  70. package/dist/menu/menu-popup.d.mts.map +1 -1
  71. package/dist/menu/menu-popup.mjs +15 -18
  72. package/dist/menu/menu-popup.mjs.map +1 -1
  73. package/dist/menu/menu-submenu-trigger.d.mts +11 -9
  74. package/dist/menu/menu-submenu-trigger.d.mts.map +1 -1
  75. package/dist/menu/menu-submenu-trigger.mjs +11 -10
  76. package/dist/menu/menu-submenu-trigger.mjs.map +1 -1
  77. package/dist/menu/menu-trigger.d.mts +13 -10
  78. package/dist/menu/menu-trigger.d.mts.map +1 -1
  79. package/dist/menu/menu-trigger.mjs +10 -14
  80. package/dist/menu/menu-trigger.mjs.map +1 -1
  81. package/dist/number-field/number-field-root.mjs +1 -1
  82. package/dist/popover/index.d.mts +1 -1
  83. package/dist/popover/index.mjs +1 -1
  84. package/dist/popover/index.mjs.map +1 -1
  85. package/dist/popover/popover-close.d.mts +5 -3
  86. package/dist/popover/popover-close.d.mts.map +1 -1
  87. package/dist/popover/popover-close.mjs +3 -1
  88. package/dist/popover/popover-close.mjs.map +1 -1
  89. package/dist/popover/popover-popup.d.mts +1 -1
  90. package/dist/popover/popover-popup.mjs +1 -1
  91. package/dist/popover/popover-popup.mjs.map +1 -1
  92. package/dist/popover/popover-root.d.mts +1 -1
  93. package/dist/popover/popover-root.mjs +1 -1
  94. package/dist/popover/popover-root.mjs.map +1 -1
  95. package/dist/popover/popover-trigger.d.mts +10 -9
  96. package/dist/popover/popover-trigger.d.mts.map +1 -1
  97. package/dist/popover/popover-trigger.mjs +9 -8
  98. package/dist/popover/popover-trigger.mjs.map +1 -1
  99. package/dist/toast/toast-root.mjs.map +1 -1
  100. package/dist/toast/toast-viewport.d.mts.map +1 -1
  101. package/dist/toast/toast-viewport.mjs +4 -5
  102. package/dist/toast/toast-viewport.mjs.map +1 -1
  103. package/dist/toggle-group/toggle-group-root.d.mts.map +1 -1
  104. package/dist/toggle-group/toggle-group-root.mjs +4 -5
  105. package/dist/toggle-group/toggle-group-root.mjs.map +1 -1
  106. package/package.json +1 -1
@@ -4,7 +4,10 @@ import { useElementCheck } from "./use-element-check.mjs";
4
4
  import { isPopoverOpen } from "./popover-open.mjs";
5
5
  import { useContentFocusProbe } from "./content-focus-probe.mjs";
6
6
  import { commandOf, renderOverlayContent, resolveInitialFocus, returnFocusToTrigger, useCloseHold, useInitialFocusTarget } from "./overlay-popup.mjs";
7
+ import { closedByPopoverTarget } from "./invokers.mjs";
7
8
  import { useShownNameWarning } from "./use-name-warning.mjs";
9
+ import { supportsFocusVisibleOption } from "./focus-visible.mjs";
10
+ import { useInterestDismiss } from "./use-interest-dismiss.mjs";
8
11
  import { useCallback, useEffectEvent, useLayoutEffect, useRef } from "react";
9
12
  //#region src/internal/use-popover-popup.ts
10
13
  const isDev = process.env.NODE_ENV !== "production";
@@ -13,27 +16,6 @@ function needsName(element) {
13
16
  const role = element.getAttribute("role");
14
17
  return role === "dialog" || role === "alertdialog" || role === "menu";
15
18
  }
16
- let focusVisibleOption;
17
- /**
18
- * The engine reads the `focusVisible` member of `focus()`'s options (Chromium 145, Firefox 104,
19
- * Safari 18.4). Detected once through a getter: the bindings convert the dictionary before the
20
- * method runs, so a detached element is enough and nothing is focused.
21
- */
22
- function supportsFocusVisibleOption(doc) {
23
- if (focusVisibleOption === void 0) {
24
- let read = false;
25
- try {
26
- doc.createElement("div").focus({ get focusVisible() {
27
- read = true;
28
- return false;
29
- } });
30
- } catch {
31
- read = false;
32
- }
33
- focusVisibleOption = read;
34
- }
35
- return focusVisibleOption;
36
- }
37
19
  /** Whether `element` sits inside a popover that is not shown (an outer popup that closed). */
38
20
  function insideHiddenPopover(element) {
39
21
  for (let node = element.parentElement; node !== null; node = node.parentElement) if (node.hasAttribute("popover") && !isPopoverOpen(node)) return true;
@@ -41,13 +23,13 @@ function insideHiddenPopover(element) {
41
23
  }
42
24
  /**
43
25
  * Everything in a popover-like Popup except rendering (design/components/popover.md 14.2): mount
44
- * reconciliation, the apply effect, the native `beforetoggle` / `toggle` / `command` listeners,
45
- * close intents, the focus-return fallback, the JS-free `aria-expanded` sync, the deferred
46
- * unmount while a hide animates, and `initialFocus`. Shared by Popover and Menu.
26
+ * reconciliation, the apply effect, the native `beforetoggle` / `toggle` / `command` listeners
27
+ * (and `interest` / `loseinterest`), close intents, the focus-return fallback, the JS-free
28
+ * `data-open` sync, the deferred unmount while a hide animates, and `initialFocus`. Shared by
29
+ * Popover, Menu and Combobox.
47
30
  */
48
31
  function usePopoverPopup(ctx, options) {
49
- const { part, initialFocus, transition, onBeforeToggle: onBeforeToggleOption } = options;
50
- const onToggleOption = options.onToggle;
32
+ const { part, initialFocus, transition } = options;
51
33
  const isLibrary = ctx.mode === "library";
52
34
  const { popupRef, triggerRef, setShown } = ctx;
53
35
  const opening = useRef(false);
@@ -55,11 +37,17 @@ function usePopoverPopup(ctx, options) {
55
37
  const awaitingClose = useRef(false);
56
38
  const focusWasInside = useRef(false);
57
39
  const initialFocusTarget = useInitialFocusTarget(part, "popup");
40
+ const interest = useInterestDismiss(ctx);
41
+ const stopWhileShown = useRef(null);
42
+ const stopListeningWhileShown = () => {
43
+ stopWhileShown.current?.();
44
+ stopWhileShown.current = null;
45
+ };
58
46
  const exit = useCloseHold(ctx.committed, isLibrary, transition);
59
47
  const contentProbe = useContentFocusProbe(popupRef);
60
48
  const { wrapContent } = contentProbe;
61
- const syncExpanded = (element) => {
62
- triggerRef.current?.setAttribute("aria-expanded", String(isPopoverOpen(element)));
49
+ const syncOpen = (element) => {
50
+ triggerRef.current?.toggleAttribute("data-open", isPopoverOpen(element));
63
51
  };
64
52
  const returnFocus = (element) => returnFocusToTrigger(element, triggerRef.current, (trigger) => !insideHiddenPopover(trigger));
65
53
  const resolveFocusTarget = (element) => {
@@ -67,36 +55,40 @@ function usePopoverPopup(ctx, options) {
67
55
  const resolved = options.resolveInitialFocus(element);
68
56
  if (resolved === null) return null;
69
57
  const target = resolved instanceof HTMLElement ? resolved : resolved.element;
70
- return element.contains(target) ? resolved : null;
58
+ if (!element.contains(target)) return null;
59
+ return {
60
+ target,
61
+ quiet: !(resolved instanceof HTMLElement) && supportsFocusVisibleOption(element.ownerDocument)
62
+ };
71
63
  }
72
- return initialFocusTarget(element, initialFocus);
64
+ const target = initialFocusTarget(element, initialFocus);
65
+ return target === null ? null : {
66
+ target,
67
+ quiet: false
68
+ };
73
69
  };
74
70
  const showPopup = (element) => {
75
- const resolved = resolveFocusTarget(element);
76
- const target = resolved === null || resolved instanceof HTMLElement ? resolved : resolved.element;
77
- const quiet = target !== null && !(resolved instanceof HTMLElement) && supportsFocusVisibleOption(element.ownerDocument);
78
- const added = target !== null && !quiet && !target.hasAttribute("autofocus");
79
- if (added) target.setAttribute("autofocus", "");
71
+ const focus = resolveFocusTarget(element);
72
+ const autofocused = focus !== null && !focus.quiet && !focus.target.hasAttribute("autofocus") ? focus.target : null;
73
+ autofocused?.setAttribute("autofocus", "");
80
74
  opening.current = true;
81
75
  try {
82
76
  const source = options.source !== void 0 ? options.source() : triggerRef.current;
83
77
  element.showPopover(source != null && source.isConnected ? { source } : void 0);
84
78
  } finally {
85
79
  opening.current = false;
86
- if (added) target.removeAttribute("autofocus");
80
+ autofocused?.removeAttribute("autofocus");
87
81
  }
88
- if (quiet && isPopoverOpen(element) && element.contains(target)) target.focus({ focusVisible: false });
82
+ if (focus?.quiet === true && isPopoverOpen(element) && element.contains(focus.target)) focus.target.focus({ focusVisible: false });
89
83
  };
90
84
  const reshow = () => {
91
85
  const element = popupRef.current;
92
86
  if (!isLibrary || element === null || !isPopoverOpen(element)) return false;
93
- opening.current = true;
94
87
  reshowing.current = true;
95
88
  try {
96
89
  element.hidePopover();
97
90
  showPopup(element);
98
91
  } finally {
99
- opening.current = false;
100
92
  reshowing.current = false;
101
93
  }
102
94
  awaitingClose.current = false;
@@ -107,7 +99,7 @@ function usePopoverPopup(ctx, options) {
107
99
  const element = popupRef.current;
108
100
  if (element === null) return;
109
101
  if (!isLibrary) {
110
- syncExpanded(element);
102
+ syncOpen(element);
111
103
  return;
112
104
  }
113
105
  if (isPopoverOpen(element)) ctx.requestOpen(void 0, "platform");
@@ -139,41 +131,49 @@ function usePopoverPopup(ctx, options) {
139
131
  if (toggle.newState === "open") {
140
132
  if (isLibrary && !opening.current) {
141
133
  event.preventDefault();
134
+ interest.noteOpen(toggle);
142
135
  ctx.requestOpen(event, "activate");
143
136
  } else if (!reshowing.current) ctx.nextOpenGeneration();
144
137
  contentProbe.forget();
145
138
  } else {
139
+ if (isLibrary && closedByPopoverTarget(toggle, element)) ctx.recordCloseIntent({
140
+ reason: "activate",
141
+ event
142
+ }, { unlessRecorded: true });
146
143
  awaitingClose.current = true;
147
144
  exit.recordBaseline(element);
148
145
  const active = element.ownerDocument.activeElement;
149
146
  focusWasInside.current = active !== null && element.contains(active) || contentProbe.hadFocus();
150
147
  contentProbe.forget();
151
148
  }
152
- onBeforeToggleOption?.(toggle);
153
149
  };
154
150
  const onToggle = (event) => {
155
151
  const element = popupRef.current;
156
152
  if (element === null || event.target !== element) return;
157
153
  awaitingClose.current = false;
154
+ const lostInterest = interest.takeLostInterest();
158
155
  if (isLibrary) setShown(isPopoverOpen(element));
159
- else syncExpanded(element);
156
+ else syncOpen(element);
160
157
  if (!isPopoverOpen(element)) {
158
+ interest.noteClosed();
161
159
  const wasInside = focusWasInside.current;
162
160
  focusWasInside.current = false;
163
- if (wasInside) returnFocus(element);
161
+ if (wasInside && !lostInterest) returnFocus(element);
164
162
  const intent = ctx.takeCloseIntent();
165
163
  if (isLibrary) {
166
164
  exit.afterClose(element, !ctx.intended());
167
165
  ctx.notifyClosed(intent?.event ?? event, intent?.reason ?? "dismiss");
168
166
  }
169
167
  }
170
- onToggleOption?.(event);
168
+ const { newState } = event;
169
+ if (newState === "open" && isPopoverOpen(element)) stopWhileShown.current ??= options.whileShown?.(element) ?? null;
170
+ else if (newState === "closed") stopListeningWhileShown();
171
171
  };
172
172
  const onCommand = (event) => {
173
173
  const element = popupRef.current;
174
174
  if (element === null || event.target !== element || event.defaultPrevented) return;
175
175
  const command = commandOf(event);
176
- if (command === "hide-popover" || command === "toggle-popover" && isPopoverOpen(element)) ctx.recordCloseIntent({
176
+ if ((command === "hide-popover" || command === "toggle-popover") && isPopoverOpen(element)) ctx.recordCloseIntent({
177
177
  reason: "activate",
178
178
  event
179
179
  });
@@ -181,19 +181,26 @@ function usePopoverPopup(ctx, options) {
181
181
  const handlers = useLatest({
182
182
  onBeforeToggle,
183
183
  onToggle,
184
- onCommand
184
+ onCommand,
185
+ onInterest: interest.onInterest,
186
+ onLoseInterest: interest.onLoseInterest
185
187
  });
188
+ const latestWhileShown = useLatest(options.whileShown);
186
189
  const checkElement = useElementCheck(isDev && ((element) => element.tagName !== "DIALOG" && element.tagName !== "DIV" ? `${part}: expected to render a <dialog> or a <div> but got <${element.tagName.toLowerCase()}>.` : null));
190
+ const resetInterest = interest.reset;
187
191
  const setElement = useCallback((element) => {
188
192
  checkElement?.(element);
189
193
  popupRef.current = element;
190
194
  const listeners = [
191
195
  ["beforetoggle", (event) => handlers.current.onBeforeToggle(event)],
192
196
  ["toggle", (event) => handlers.current.onToggle(event)],
193
- ["command", (event) => handlers.current.onCommand(event)]
197
+ ["command", (event) => handlers.current.onCommand(event)],
198
+ ["interest", (event) => handlers.current.onInterest(event)],
199
+ ["loseinterest", (event) => handlers.current.onLoseInterest(event)]
194
200
  ];
195
201
  for (const [type, listener] of listeners) element.addEventListener(type, listener);
196
202
  if (isLibrary) setShown(isPopoverOpen(element));
203
+ if (isPopoverOpen(element)) stopWhileShown.current ??= latestWhileShown.current?.(element) ?? null;
197
204
  let autofocused = null;
198
205
  if (!isLibrary && initialFocus !== void 0) {
199
206
  const target = resolveInitialFocus(element, initialFocus);
@@ -204,6 +211,8 @@ function usePopoverPopup(ctx, options) {
204
211
  }
205
212
  return () => {
206
213
  for (const [type, listener] of listeners) element.removeEventListener(type, listener);
214
+ resetInterest();
215
+ stopListeningWhileShown();
207
216
  if (isLibrary) setShown(false);
208
217
  autofocused?.removeAttribute("autofocus");
209
218
  if (popupRef.current === element) popupRef.current = null;
@@ -213,8 +222,10 @@ function usePopoverPopup(ctx, options) {
213
222
  popupRef,
214
223
  setShown,
215
224
  handlers,
225
+ latestWhileShown,
216
226
  isLibrary,
217
- initialFocus
227
+ initialFocus,
228
+ resetInterest
218
229
  ]);
219
230
  useShownNameWarning(popupRef, !isLibrary || ctx.committed, isDev && `${part}: the popup has no accessible name. Render a Title, or give the Popup an \`aria-label\`.`, needsName);
220
231
  const visible = ctx.committed || exit.held;
@@ -1 +1 @@
1
- {"version":3,"file":"use-popover-popup.mjs","names":[],"sources":["../../src/internal/use-popover-popup.ts"],"sourcesContent":["\"use client\";\nimport { useCallback, useEffectEvent, useLayoutEffect, useRef } from \"react\";\nimport type { ReactNode, RefObject, ViewTransitionClass } from \"react\";\nimport { useContentFocusProbe } from \"./content-focus-probe.js\";\nimport {\n commandOf,\n renderOverlayContent,\n resolveInitialFocus,\n returnFocusToTrigger,\n useCloseHold,\n useInitialFocusTarget,\n} from \"./overlay-popup.js\";\nimport { isPopoverOpen } from \"./popover-open.js\";\nimport { useElementCheck } from \"./use-element-check.js\";\nimport { useLatest } from \"./use-latest.js\";\nimport { useShownNameWarning } from \"./use-name-warning.js\";\nimport type { PopoverRootValue } from \"./use-overlay-root.js\";\n\nexport interface UsePopoverPopupOptions {\n /** Public name of the part for development warnings (`\"Popover.Popup\"`). */\n readonly part: string;\n /** Element to focus on open: a ref, or a selector resolved inside the popup (design 6.1). */\n readonly initialFocus?: RefObject<HTMLElement | null> | string | undefined;\n /**\n * Replaces `initialFocus` with a function called right before each library open (Menu: the\n * first or last item by open cause). `null` leaves the choice to the platform. A\n * `QuietFocusTarget` asks for focus without the focus ring (a pointer-opened menu).\n */\n readonly resolveInitialFocus?: (popup: HTMLElement) => HTMLElement | QuietFocusTarget | null;\n /** The consumer's `keepMounted`: `renderContent` keeps the children in an `<Activity>`. */\n readonly keepMounted?: boolean | undefined;\n /** The consumer's `transition`; decides how a library-driven close keeps its content (4.4). */\n readonly transition: ViewTransitionClass | undefined;\n /** Runs after the library's own `beforetoggle` handling (Menu: focus bookkeeping). */\n readonly onBeforeToggle?: (event: ToggleEvent) => void;\n /** Runs after the library's own `toggle` handling (Menu: the outside right-click listeners). */\n readonly onToggle?: (event: ToggleEvent) => void;\n /**\n * The `source` of each library `showPopover({ source })`, read right before the call. Default:\n * the registered Trigger. Menu passes the ContextTrigger region for a point open\n * (design/components/context-menu.md 14).\n */\n readonly source?: () => HTMLElement | null;\n}\n\n/**\n * An initial focus target opened by a pointer: where the engine reads `focus({ focusVisible })`,\n * the library focuses it with `focusVisible: false` right after `showPopover()` instead of\n * writing `autofocus` (WebKit shows the ring for an `autofocus` target after a click).\n * Elsewhere it is an ordinary target.\n */\nexport interface QuietFocusTarget {\n readonly element: HTMLElement;\n readonly focusVisible: false;\n}\n\nexport interface PopoverPopupHook {\n /** Callback ref for the popup element; pass as `useRender`'s `ref`. */\n readonly setElement: (element: HTMLElement) => () => void;\n /**\n * Whether the children are shown: committed open, or held while the hide animates (4.4).\n * Library mode only; JS-free mode always renders them.\n */\n readonly visible: boolean;\n /**\n * The popup's children by mode, `visible` and `keepMounted` (`renderOverlayContent`), inside\n * the focus probe: when a close commit unmounts the content while it holds focus (a\n * library-driven close with `transition`), the hide that follows returns focus to the Trigger\n * (design 6.2).\n */\n readonly renderContent: (children: () => ReactNode) => ReactNode;\n /**\n * Re-shows a shown popup in place (`hidePopover()` + `showPopover({ source })` under the\n * opening flag, initial focus resolved again): Menu's move to a new point\n * (design/components/context-menu.md 4.3). The platform coalesces the two toggles into one\n * `toggle` (`open` to `open`), so nothing is dispatched. No-op (`false`) when the popup is not\n * shown.\n */\n readonly reshow: () => boolean;\n}\n\nconst isDev = process.env.NODE_ENV !== \"production\";\n\n/** The popup roles that require a name (a listbox's name is checked on the List). */\nfunction needsName(element: Element): boolean {\n const role = element.getAttribute(\"role\");\n return role === \"dialog\" || role === \"alertdialog\" || role === \"menu\";\n}\n\nlet focusVisibleOption: boolean | undefined;\n\n/**\n * The engine reads the `focusVisible` member of `focus()`'s options (Chromium 145, Firefox 104,\n * Safari 18.4). Detected once through a getter: the bindings convert the dictionary before the\n * method runs, so a detached element is enough and nothing is focused.\n */\nfunction supportsFocusVisibleOption(doc: Document): boolean {\n if (focusVisibleOption === undefined) {\n let read = false;\n try {\n doc.createElement(\"div\").focus({\n get focusVisible() {\n read = true;\n return false;\n },\n } as FocusOptions);\n } catch {\n read = false;\n }\n focusVisibleOption = read;\n }\n return focusVisibleOption;\n}\n\n/** Tests only: forget the detection, so the next pointer open detects the option again. */\nexport function resetFocusVisibleOption(): void {\n focusVisibleOption = undefined;\n}\n\n/** Whether `element` sits inside a popover that is not shown (an outer popup that closed). */\nfunction insideHiddenPopover(element: Element): boolean {\n for (let node = element.parentElement; node !== null; node = node.parentElement) {\n if (node.hasAttribute(\"popover\") && !isPopoverOpen(node)) return true;\n }\n return false;\n}\n\n/**\n * Everything in a popover-like Popup except rendering (design/components/popover.md 14.2): mount\n * reconciliation, the apply effect, the native `beforetoggle` / `toggle` / `command` listeners,\n * close intents, the focus-return fallback, the JS-free `aria-expanded` sync, the deferred\n * unmount while a hide animates, and `initialFocus`. Shared by Popover and Menu.\n */\nexport function usePopoverPopup(\n ctx: PopoverRootValue,\n options: UsePopoverPopupOptions,\n): PopoverPopupHook {\n const { part, initialFocus, transition, onBeforeToggle: onBeforeToggleOption } = options;\n const onToggleOption = options.onToggle;\n const isLibrary = ctx.mode === \"library\";\n const { popupRef, triggerRef, setShown } = ctx;\n\n // The opening `beforetoggle` lets this one through: the library's own `showPopover()`.\n const opening = useRef(false);\n // Set across `reshow()`: the show is not a new open.\n const reshowing = useRef(false);\n // Set by the synchronous `beforetoggle` of a close, cleared by `toggle` a task later: the\n // popup is hidden but its `toggle` has not arrived, so the apply effect must not re-open it\n // from a commit that lands in between (design 2.5).\n const awaitingClose = useRef(false);\n // Whether focus was inside the popup when its last close began (design 6.2 rule 1).\n const focusWasInside = useRef(false);\n const initialFocusTarget = useInitialFocusTarget(part, \"popup\");\n\n // `held`: children stay mounted while the hide animates (design 4.4).\n const exit = useCloseHold(ctx.committed, isLibrary, transition);\n\n // Whether the content unmounted while holding focus since the popup was last shown.\n const contentProbe = useContentFocusProbe(popupRef);\n const { wrapContent } = contentProbe;\n\n const syncExpanded = (element: HTMLElement): void => {\n // JS-free mode only (design 9): read the DOM, not `newState`, so a stale task cannot lie.\n triggerRef.current?.setAttribute(\"aria-expanded\", String(isPopoverOpen(element)));\n };\n\n // Design 6.2 rule 2, for a close that began with focus inside; not to a Trigger inside a\n // hidden popover.\n const returnFocus = (element: HTMLElement): void =>\n returnFocusToTrigger(element, triggerRef.current, (trigger) => !insideHiddenPopover(trigger));\n\n // --- Opening ------------------------------------------------------------------------------\n\n const resolveFocusTarget = (element: HTMLElement): HTMLElement | QuietFocusTarget | null => {\n if (options.resolveInitialFocus !== undefined) {\n const resolved = options.resolveInitialFocus(element);\n if (resolved === null) return null;\n const target = resolved instanceof HTMLElement ? resolved : resolved.element;\n return element.contains(target) ? resolved : null;\n }\n return initialFocusTarget(element, initialFocus);\n };\n\n const showPopup = (element: HTMLElement): void => {\n const resolved = resolveFocusTarget(element);\n const target =\n resolved === null || resolved instanceof HTMLElement ? resolved : resolved.element;\n // A pointer open asks for no focus ring: `focus({ focusVisible: false })` after the show,\n // where the engine reads that option (QuietFocusTarget).\n const quiet =\n target !== null &&\n !(resolved instanceof HTMLElement) &&\n supportsFocusVisibleOption(element.ownerDocument);\n // Otherwise the popover focusing steps honour `autofocus` (and run the dialog focusing steps\n // for a <dialog>, in every engine); React drops `autoFocus` on client-rendered content.\n // Never `.focus()` (6.1) except for the quiet target above.\n const added = target !== null && !quiet && !target.hasAttribute(\"autofocus\");\n if (added) target.setAttribute(\"autofocus\", \"\");\n opening.current = true;\n try {\n const source = options.source !== undefined ? options.source() : triggerRef.current;\n element.showPopover(source != null && source.isConnected ? { source } : undefined);\n } finally {\n opening.current = false;\n if (added) target.removeAttribute(\"autofocus\");\n }\n if (quiet && isPopoverOpen(element) && element.contains(target)) {\n target.focus({ focusVisible: false } as FocusOptions);\n }\n };\n\n const reshow = (): boolean => {\n const element = popupRef.current;\n if (!isLibrary || element === null || !isPopoverOpen(element)) return false;\n // The hide half's `beforetoggle` records `awaitingClose` / `focusWasInside`; the coalesced\n // `toggle` finds the popup open again, so it clears `awaitingClose`, returns no focus and\n // notifies nothing. The opening flag covers both halves (conventions 3.5, the move).\n opening.current = true;\n reshowing.current = true;\n try {\n element.hidePopover();\n showPopup(element);\n } finally {\n opening.current = false;\n reshowing.current = false;\n }\n // Whether or not the engine fires the coalesced `toggle`, the close bookkeeping of the hide\n // half is void: the popup is open again.\n awaitingClose.current = false;\n focusWasInside.current = false;\n return isPopoverOpen(element);\n };\n\n // Mount reconciliation (design 2.4): a click before hydration opened the popover natively.\n // Runs before the apply effect; the dispatch makes the apply effect wait for it.\n const reconcileOnMount = useEffectEvent(() => {\n const element = popupRef.current;\n if (element === null) return;\n if (!isLibrary) {\n syncExpanded(element);\n return;\n }\n if (isPopoverOpen(element)) ctx.requestOpen(undefined, \"platform\");\n });\n useLayoutEffect(() => {\n reconcileOnMount();\n }, []);\n\n // The apply effect (design 2.5): after every commit that re-renders the Popup, once nothing is\n // in flight, the DOM follows committed state. One effect covers the normal open, `defaultOpen`,\n // a controlled open or close, a library-driven close after `openChangeAction(false)` settled,\n // the re-open of a refused dismissal, and the close after a refused or failed pre-hydration\n // open. The Root's value is memoised, so an unrelated Root render does not re-render the Popup\n // and does not run this; every path that makes the DOM diverge from state goes through a\n // dispatch, whose `pending` flips do. Do not rely on an unrelated render to re-apply state.\n useLayoutEffect(() => {\n if (!isLibrary) return;\n const element = popupRef.current;\n if (element === null || !element.isConnected) return;\n if (!ctx.pending && ctx.latestInFlight() === null) {\n const shown = isPopoverOpen(element);\n if (ctx.committed && !shown) {\n if (!awaitingClose.current) showPopup(element);\n } else if (!ctx.committed && shown) {\n // An echo: the `toggle` listener finds `false` intended and skips the dispatch.\n ctx.recordCloseIntent(undefined);\n element.hidePopover();\n // The close commit may have unmounted the focused content before the hide: the\n // platform restores focus only from inside the popover, so do it now.\n if (focusWasInside.current) returnFocus(element);\n }\n }\n // Content that unmounted while the popup stays open (not a close): forget it.\n if (ctx.committed && isPopoverOpen(element)) contentProbe.forget();\n exit.releaseIfIdle(ctx.committed, awaitingClose.current, isPopoverOpen(element));\n });\n\n // --- Native listeners (conventions 7.4; filtered on target: React 19.3.1 emulates bubbling\n // of `toggle`, and a nested popover's events reach this element through the real DOM too) ---\n\n const onBeforeToggle = (event: Event): void => {\n const element = popupRef.current;\n if (element === null || event.target !== element) return;\n const toggle = event as ToggleEvent;\n if (toggle.newState === \"open\") {\n // Every open the library did not start itself is routed through the Root (design 2.2):\n // a foreign `show-popover` / `toggle-popover` invoker, a script `showPopover()`.\n if (isLibrary && !opening.current) {\n event.preventDefault();\n ctx.requestOpen(event, \"activate\");\n } else if (!reshowing.current) {\n // A Close action that resolves after this open must not close it (design 3.4). A re-show\n // (Menu's move) is the same open: an item action pending across it still closes.\n ctx.nextOpenGeneration();\n }\n contentProbe.forget();\n } else {\n awaitingClose.current = true;\n exit.recordBaseline(element);\n const active = element.ownerDocument.activeElement;\n focusWasInside.current =\n (active !== null && element.contains(active)) || contentProbe.hadFocus();\n contentProbe.forget();\n }\n onBeforeToggleOption?.(toggle);\n };\n\n const onToggle = (event: Event): void => {\n const element = popupRef.current;\n if (element === null || event.target !== element) return;\n awaitingClose.current = false;\n // `aria-expanded`: JS-free mode writes the DOM, library mode mirrors into the Root (#118).\n if (isLibrary) setShown(isPopoverOpen(element));\n else syncExpanded(element);\n\n if (!isPopoverOpen(element)) {\n // Focus return for what the platform leaves out (design 6.2): a nested popover restores\n // nothing, and an opener that is gone leaves focus inside the hidden popup.\n const wasInside = focusWasInside.current;\n focusWasInside.current = false;\n if (wasInside) returnFocus(element);\n\n const intent = ctx.takeCloseIntent();\n if (isLibrary) {\n // An echo: `false` already intended (the library's own hide, or a dismissal during a\n // pending part-initiated close).\n exit.afterClose(element, !ctx.intended());\n ctx.notifyClosed(intent?.event ?? event, intent?.reason ?? \"dismiss\");\n }\n }\n onToggleOption?.(event as ToggleEvent);\n };\n\n const onCommand = (event: Event): void => {\n const element = popupRef.current;\n if (element === null || event.target !== element || event.defaultPrevented) return;\n const command = commandOf(event);\n // A foreign invoker closing the popup (design 2.3). Opens are caught at `beforetoggle`.\n if (command === \"hide-popover\" || (command === \"toggle-popover\" && isPopoverOpen(element))) {\n ctx.recordCloseIntent({ reason: \"activate\", event });\n }\n };\n\n // The listeners the callback ref attaches call the latest render's handlers. An insertion\n // effect publishes them before refs attach and before any layout effect (whose\n // `hidePopover()` dispatches `beforetoggle` synchronously).\n const handlers = useLatest({ onBeforeToggle, onToggle, onCommand });\n\n // --- Element ------------------------------------------------------------------------------\n\n // The listeners attach in the callback ref, so they are in place from the commit that mounts\n // the element (no passive-effect window, no extra render). JS-free mode: there is no \"right\n // before showPopover()\" (the browser runs the command), so the `autofocus` attribute stays on\n // the `initialFocus` target while it is mounted (as Dialog).\n const checkElement = useElementCheck(\n isDev &&\n ((element) =>\n element.tagName !== \"DIALOG\" && element.tagName !== \"DIV\"\n ? `${part}: expected to render a <dialog> or a <div> but got ` +\n `<${element.tagName.toLowerCase()}>.`\n : null),\n );\n const setElement = useCallback(\n (element: HTMLElement) => {\n checkElement?.(element);\n popupRef.current = element;\n const listeners: [string, EventListener][] = [\n [\"beforetoggle\", (event) => handlers.current.onBeforeToggle(event)],\n [\"toggle\", (event) => handlers.current.onToggle(event)],\n [\"command\", (event) => handlers.current.onCommand(event)],\n ];\n for (const [type, listener] of listeners) element.addEventListener(type, listener);\n // A pre-hydration open is shown from the first commit; a popup removed while open fires no\n // `toggle`, so the detach clears the mirror (#118).\n if (isLibrary) setShown(isPopoverOpen(element));\n\n let autofocused: HTMLElement | null = null;\n if (!isLibrary && initialFocus !== undefined) {\n const target = resolveInitialFocus(element, initialFocus);\n if (target !== null && element.contains(target) && !target.hasAttribute(\"autofocus\")) {\n target.setAttribute(\"autofocus\", \"\");\n autofocused = target;\n }\n }\n\n return () => {\n for (const [type, listener] of listeners) element.removeEventListener(type, listener);\n if (isLibrary) setShown(false);\n autofocused?.removeAttribute(\"autofocus\");\n if (popupRef.current === element) popupRef.current = null;\n };\n },\n [checkElement, popupRef, setShown, handlers, isLibrary, initialFocus],\n );\n\n // Development check (design 9): `role=\"dialog\"` needs a name once the popup is (or can be)\n // shown.\n useShownNameWarning(\n popupRef,\n !isLibrary || ctx.committed,\n isDev &&\n `${part}: the popup has no accessible name. Render a Title, or give the Popup an ` +\n \"`aria-label`.\",\n needsName,\n );\n\n const visible = ctx.committed || exit.held;\n const renderContent = (children: () => ReactNode): ReactNode =>\n renderOverlayContent(\n { isLibrary, keepMounted: options.keepMounted, visible, wrapContent },\n children,\n );\n return { setElement, visible, renderContent, reshow };\n}\n"],"mappings":";;;;;;;;;AAiFA,MAAM,QAAQ,QAAQ,IAAI,aAAa;;AAGvC,SAAS,UAAU,SAA2B;CAC5C,MAAM,OAAO,QAAQ,aAAa,MAAM;CACxC,OAAO,SAAS,YAAY,SAAS,iBAAiB,SAAS;AACjE;AAEA,IAAI;;;;;;AAOJ,SAAS,2BAA2B,KAAwB;CAC1D,IAAI,uBAAuB,KAAA,GAAW;EACpC,IAAI,OAAO;EACX,IAAI;GACF,IAAI,cAAc,KAAK,CAAC,CAAC,MAAM,EAC7B,IAAI,eAAe;IACjB,OAAO;IACP,OAAO;GACT,EACF,CAAiB;EACnB,QAAQ;GACN,OAAO;EACT;EACA,qBAAqB;CACvB;CACA,OAAO;AACT;;AAQA,SAAS,oBAAoB,SAA2B;CACtD,KAAK,IAAI,OAAO,QAAQ,eAAe,SAAS,MAAM,OAAO,KAAK,eAChE,IAAI,KAAK,aAAa,SAAS,KAAK,CAAC,cAAc,IAAI,GAAG,OAAO;CAEnE,OAAO;AACT;;;;;;;AAQA,SAAgB,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AW;CAAY,CACtE;CAIA,oBACE,UACA,CAAC,aAAa,IAAI,WAClB,SACE,GAAG,KAAK,2FAEV,SACF;CAEA,MAAM,UAAU,IAAI,aAAa,KAAK;CACtC,MAAM,iBAAiB,aACrB,qBACE;EAAE;EAAW,aAAa,QAAQ;EAAa;EAAS;CAAY,GACpE,QACF;CACF,OAAO;EAAE;EAAY;EAAS;EAAe;CAAO;AACtD"}
1
+ {"version":3,"file":"use-popover-popup.mjs","names":[],"sources":["../../src/internal/use-popover-popup.ts"],"sourcesContent":["\"use client\";\nimport { useCallback, useEffectEvent, useLayoutEffect, useRef } from \"react\";\nimport type { ReactNode, RefObject, ViewTransitionClass } from \"react\";\nimport { useContentFocusProbe } from \"./content-focus-probe.js\";\nimport { closedByPopoverTarget } from \"./invokers.js\";\nimport { supportsFocusVisibleOption } from \"./focus-visible.js\";\nimport type { QuietFocusTarget } from \"./focus-visible.js\";\nimport {\n commandOf,\n renderOverlayContent,\n resolveInitialFocus,\n returnFocusToTrigger,\n useCloseHold,\n useInitialFocusTarget,\n} from \"./overlay-popup.js\";\nimport { isPopoverOpen } from \"./popover-open.js\";\nimport { useElementCheck } from \"./use-element-check.js\";\nimport { useInterestDismiss } from \"./use-interest-dismiss.js\";\nimport { useLatest } from \"./use-latest.js\";\nimport { useShownNameWarning } from \"./use-name-warning.js\";\nimport type { PopoverRootValue } from \"./use-overlay-root.js\";\n\nexport interface UsePopoverPopupOptions {\n /** Public name of the part for development warnings (`\"Popover.Popup\"`). */\n readonly part: string;\n /** Element to focus on open: a ref, or a selector resolved inside the popup (design 6.1). */\n readonly initialFocus?: RefObject<HTMLElement | null> | string | undefined;\n /**\n * Replaces `initialFocus` with a function called right before each library open (Menu: the\n * first or last item by open cause). `null` leaves the choice to the platform. A\n * `QuietFocusTarget` asks for focus without the focus ring (a pointer-opened menu).\n */\n readonly resolveInitialFocus?: (popup: HTMLElement) => HTMLElement | QuietFocusTarget | null;\n /** The consumer's `keepMounted`: `renderContent` keeps the children in an `<Activity>`. */\n readonly keepMounted?: boolean | undefined;\n /** The consumer's `transition`; decides how a library-driven close keeps its content (4.4). */\n readonly transition: ViewTransitionClass | undefined;\n /**\n * Installs listeners that live while the popup is shown (Menu: the outside right-click\n * listeners; Menu and Combobox: the foreign invoker press guard) and returns their cleanup.\n * Called at the `toggle` that finds the popup shown, and again when the ref attaches to a\n * shown popup; the cleanup runs at the `toggle` of the close and when the element detaches.\n */\n readonly whileShown?: ((popup: HTMLElement) => () => void) | undefined;\n /**\n * The `source` of each library `showPopover({ source })`, read right before the call. Default:\n * the registered Trigger. Menu passes the ContextTrigger region for a point open\n * (design/components/context-menu.md 14).\n */\n readonly source?: () => HTMLElement | null;\n}\n\nexport interface PopoverPopupHook {\n /** Callback ref for the popup element; pass as `useRender`'s `ref`. */\n readonly setElement: (element: HTMLElement) => () => void;\n /**\n * Whether the children are shown: committed open, or held while the hide animates (4.4).\n * Library mode only; JS-free mode always renders them.\n */\n readonly visible: boolean;\n /**\n * The popup's children by mode, `visible` and `keepMounted` (`renderOverlayContent`), inside\n * the focus probe: when a close commit unmounts the content while it holds focus (a\n * library-driven close with `transition`), the hide that follows returns focus to the Trigger\n * (design 6.2).\n */\n readonly renderContent: (children: () => ReactNode) => ReactNode;\n /**\n * Re-shows a shown popup in place (`hidePopover()` + `showPopover({ source })` under the\n * opening flag, initial focus resolved again): Menu's move to a new point\n * (design/components/context-menu.md 4.3). The platform coalesces the two toggles into one\n * `toggle` (`open` to `open`), so nothing is dispatched. No-op (`false`) when the popup is not\n * shown.\n */\n readonly reshow: () => boolean;\n}\n\nconst isDev = process.env.NODE_ENV !== \"production\";\n\n/** The popup roles that require a name (a listbox's name is checked on the List). */\nfunction needsName(element: Element): boolean {\n const role = element.getAttribute(\"role\");\n return role === \"dialog\" || role === \"alertdialog\" || role === \"menu\";\n}\n\n/** Whether `element` sits inside a popover that is not shown (an outer popup that closed). */\nfunction insideHiddenPopover(element: Element): boolean {\n for (let node = element.parentElement; node !== null; node = node.parentElement) {\n if (node.hasAttribute(\"popover\") && !isPopoverOpen(node)) return true;\n }\n return false;\n}\n\n/**\n * Everything in a popover-like Popup except rendering (design/components/popover.md 14.2): mount\n * reconciliation, the apply effect, the native `beforetoggle` / `toggle` / `command` listeners\n * (and `interest` / `loseinterest`), close intents, the focus-return fallback, the JS-free\n * `data-open` sync, the deferred unmount while a hide animates, and `initialFocus`. Shared by\n * Popover, Menu and Combobox.\n */\nexport function usePopoverPopup(\n ctx: PopoverRootValue,\n options: UsePopoverPopupOptions,\n): PopoverPopupHook {\n const { part, initialFocus, transition } = options;\n const isLibrary = ctx.mode === \"library\";\n const { popupRef, triggerRef, setShown } = ctx;\n\n // The opening `beforetoggle` lets this one through: the library's own `showPopover()`.\n const opening = useRef(false);\n // Set across `reshow()`: the show is not a new open.\n const reshowing = useRef(false);\n // Set by the synchronous `beforetoggle` of a close, cleared by `toggle` a task later: the\n // popup is hidden but its `toggle` has not arrived, so the apply effect must not re-open it\n // from a commit that lands in between (design 2.5).\n const awaitingClose = useRef(false);\n // Whether focus was inside the popup when its last close began (design 6.2 rule 1).\n const focusWasInside = useRef(false);\n const initialFocusTarget = useInitialFocusTarget(part, \"popup\");\n // `interestfor` (library mode, popover.md lost-interest amendment).\n const interest = useInterestDismiss(ctx);\n // The cleanup of `whileShown` while the popup is shown.\n const stopWhileShown = useRef<(() => void) | null>(null);\n const stopListeningWhileShown = (): void => {\n stopWhileShown.current?.();\n stopWhileShown.current = null;\n };\n\n // `held`: children stay mounted while the hide animates (design 4.4).\n const exit = useCloseHold(ctx.committed, isLibrary, transition);\n\n // Whether the content unmounted while holding focus since the popup was last shown.\n const contentProbe = useContentFocusProbe(popupRef);\n const { wrapContent } = contentProbe;\n\n const syncOpen = (element: HTMLElement): void => {\n // JS-free mode only (design 9): read the DOM, not `newState`, so a stale task cannot\n // lie.\n triggerRef.current?.toggleAttribute(\"data-open\", isPopoverOpen(element));\n };\n\n // Design 6.2 rule 2, for a close that began with focus inside; not to a Trigger inside a\n // hidden popover.\n const returnFocus = (element: HTMLElement): void =>\n returnFocusToTrigger(element, triggerRef.current, (trigger) => !insideHiddenPopover(trigger));\n\n // --- Opening ------------------------------------------------------------------------------\n\n // The initial focus target inside the popup, and whether it is focused without the focus ring.\n const resolveFocusTarget = (\n element: HTMLElement,\n ): { readonly target: HTMLElement; readonly quiet: boolean } | null => {\n if (options.resolveInitialFocus !== undefined) {\n const resolved = options.resolveInitialFocus(element);\n if (resolved === null) return null;\n const target = resolved instanceof HTMLElement ? resolved : resolved.element;\n if (!element.contains(target)) return null;\n // A pointer open asks for no focus ring: `focus({ focusVisible: false })` after the show,\n // where the engine reads that option (QuietFocusTarget).\n const quiet =\n !(resolved instanceof HTMLElement) && supportsFocusVisibleOption(element.ownerDocument);\n return { target, quiet };\n }\n const target = initialFocusTarget(element, initialFocus);\n return target === null ? null : { target, quiet: false };\n };\n\n const showPopup = (element: HTMLElement): void => {\n const focus = resolveFocusTarget(element);\n // Otherwise the popover focusing steps honour `autofocus` (and run the dialog focusing steps\n // for a <dialog>, in every engine); React drops `autoFocus` on client-rendered content.\n // Never `.focus()` (6.1) except for the quiet target above.\n const autofocused =\n focus !== null && !focus.quiet && !focus.target.hasAttribute(\"autofocus\")\n ? focus.target\n : null;\n autofocused?.setAttribute(\"autofocus\", \"\");\n opening.current = true;\n try {\n const source = options.source !== undefined ? options.source() : triggerRef.current;\n element.showPopover(source != null && source.isConnected ? { source } : undefined);\n } finally {\n opening.current = false;\n autofocused?.removeAttribute(\"autofocus\");\n }\n if (focus?.quiet === true && isPopoverOpen(element) && element.contains(focus.target)) {\n focus.target.focus({ focusVisible: false } as FocusOptions);\n }\n };\n\n const reshow = (): boolean => {\n const element = popupRef.current;\n if (!isLibrary || element === null || !isPopoverOpen(element)) return false;\n // The hide half's `beforetoggle` records `awaitingClose` / `focusWasInside`; the coalesced\n // `toggle` finds the popup open again, so it clears `awaitingClose`, returns no focus and\n // notifies nothing. The show half runs under `showPopup`'s opening flag (conventions 3.5, the\n // move); the hide half needs none, only an opening `beforetoggle` reads it.\n reshowing.current = true;\n try {\n element.hidePopover();\n showPopup(element);\n } finally {\n reshowing.current = false;\n }\n // Whether or not the engine fires the coalesced `toggle`, the close bookkeeping of the hide\n // half is void: the popup is open again.\n awaitingClose.current = false;\n focusWasInside.current = false;\n return isPopoverOpen(element);\n };\n\n // Mount reconciliation (design 2.4): a click before hydration opened the popover natively.\n // Runs before the apply effect; the dispatch makes the apply effect wait for it.\n const reconcileOnMount = useEffectEvent(() => {\n const element = popupRef.current;\n if (element === null) return;\n if (!isLibrary) {\n syncOpen(element);\n return;\n }\n if (isPopoverOpen(element)) ctx.requestOpen(undefined, \"platform\");\n });\n useLayoutEffect(() => {\n reconcileOnMount();\n }, []);\n\n // The apply effect (design 2.5): after every commit that re-renders the Popup, once nothing is\n // in flight, the DOM follows committed state. One effect covers the normal open, `defaultOpen`,\n // a controlled open or close, a library-driven close after `openChangeAction(false)` settled,\n // the re-open of a refused dismissal, and the close after a refused or failed pre-hydration\n // open. The Root's value is memoised, so an unrelated Root render does not re-render the Popup\n // and does not run this; every path that makes the DOM diverge from state goes through a\n // dispatch, whose `pending` flips do. Do not rely on an unrelated render to re-apply state.\n useLayoutEffect(() => {\n if (!isLibrary) return;\n const element = popupRef.current;\n if (element === null || !element.isConnected) return;\n if (!ctx.pending && ctx.latestInFlight() === null) {\n const shown = isPopoverOpen(element);\n if (ctx.committed && !shown) {\n if (!awaitingClose.current) showPopup(element);\n } else if (!ctx.committed && shown) {\n // An echo: the `toggle` listener finds `false` intended and skips the dispatch.\n ctx.recordCloseIntent(undefined);\n element.hidePopover();\n // The close commit may have unmounted the focused content before the hide: the\n // platform restores focus only from inside the popover, so do it now.\n if (focusWasInside.current) returnFocus(element);\n }\n }\n // Content that unmounted while the popup stays open (not a close): forget it.\n if (ctx.committed && isPopoverOpen(element)) contentProbe.forget();\n exit.releaseIfIdle(ctx.committed, awaitingClose.current, isPopoverOpen(element));\n });\n\n // --- Native listeners (conventions 7.4; filtered on target: React 19.3.1 emulates bubbling\n // of `toggle`, and a nested popover's events reach this element through the real DOM too) ---\n\n const onBeforeToggle = (event: Event): void => {\n const element = popupRef.current;\n if (element === null || event.target !== element) return;\n const toggle = event as ToggleEvent;\n if (toggle.newState === \"open\") {\n // Every open the library did not start itself is routed through the Root (design 2.2):\n // a foreign `show-popover` / `toggle-popover` invoker, a script `showPopover()`.\n if (isLibrary && !opening.current) {\n event.preventDefault();\n interest.noteOpen(toggle);\n ctx.requestOpen(event, \"activate\");\n } else if (!reshowing.current) {\n // A Close action that resolves after this open must not close it (design 3.4). A re-show\n // (Menu's move) is the same open: an item action pending across it still closes.\n ctx.nextOpenGeneration();\n }\n contentProbe.forget();\n } else {\n // A foreign `popovertarget` invoker closing the popup (design 2.3): `source` is the\n // button, and `null` for Escape, light dismiss and script. The library's own parts never\n // get here with a source (their clicks are cancelled; their closes are `hidePopover()`). A\n // button with `commandfor` as well runs its command, whose intent comes first and stays.\n if (isLibrary && closedByPopoverTarget(toggle, element)) {\n ctx.recordCloseIntent({ reason: \"activate\", event }, { unlessRecorded: true });\n }\n awaitingClose.current = true;\n exit.recordBaseline(element);\n const active = element.ownerDocument.activeElement;\n focusWasInside.current =\n (active !== null && element.contains(active)) || contentProbe.hadFocus();\n contentProbe.forget();\n }\n };\n\n const onToggle = (event: Event): void => {\n const element = popupRef.current;\n if (element === null || event.target !== element) return;\n awaitingClose.current = false;\n const lostInterest = interest.takeLostInterest();\n // JS-free mode writes the Trigger's `data-open`; library mode mirrors into the Root, which\n // non-button Triggers and the Combobox Input render as `aria-expanded`.\n if (isLibrary) setShown(isPopoverOpen(element));\n else syncOpen(element);\n\n if (!isPopoverOpen(element)) {\n interest.noteClosed();\n // Focus return for what the platform leaves out (design 6.2): a nested popover restores\n // nothing, and an opener that is gone leaves focus inside the hidden popup. Not after a\n // lost-interest hide: the platform never focuses the invoker there, and focusing a Trigger\n // with `interestfor` would give it interest again and re-open the popup.\n const wasInside = focusWasInside.current;\n focusWasInside.current = false;\n if (wasInside && !lostInterest) returnFocus(element);\n\n const intent = ctx.takeCloseIntent();\n if (isLibrary) {\n // An echo: `false` already intended (the library's own hide, or a dismissal during a\n // pending part-initiated close).\n exit.afterClose(element, !ctx.intended());\n ctx.notifyClosed(intent?.event ?? event, intent?.reason ?? \"dismiss\");\n }\n }\n const { newState } = event as ToggleEvent;\n if (newState === \"open\" && isPopoverOpen(element)) {\n stopWhileShown.current ??= options.whileShown?.(element) ?? null;\n } else if (newState === \"closed\") {\n stopListeningWhileShown();\n }\n };\n\n const onCommand = (event: Event): void => {\n const element = popupRef.current;\n if (element === null || event.target !== element || event.defaultPrevented) return;\n const command = commandOf(event);\n // A foreign `commandfor` invoker closing the popup (design 2.3). Opens are caught at\n // `beforetoggle`.\n // The `command` event fires whatever the popover's state (HTML): a `hide-popover` at a\n // hidden popup closes nothing and must leave no intent for a later close.\n if ((command === \"hide-popover\" || command === \"toggle-popover\") && isPopoverOpen(element)) {\n ctx.recordCloseIntent({ reason: \"activate\", event });\n }\n };\n\n // The listeners the callback ref attaches call the latest render's handlers. An insertion\n // effect publishes them before refs attach and before any layout effect (whose\n // `hidePopover()` dispatches `beforetoggle` synchronously).\n const handlers = useLatest({\n onBeforeToggle,\n onToggle,\n onCommand,\n onInterest: interest.onInterest,\n onLoseInterest: interest.onLoseInterest,\n });\n const latestWhileShown = useLatest(options.whileShown);\n\n // --- Element ------------------------------------------------------------------------------\n\n // The listeners attach in the callback ref, so they are in place from the commit that mounts\n // the element (no passive-effect window, no extra render). JS-free mode: there is no \"right\n // before showPopover()\" (the browser runs the command), so the `autofocus` attribute stays on\n // the `initialFocus` target while it is mounted (as Dialog).\n const checkElement = useElementCheck(\n isDev &&\n ((element) =>\n element.tagName !== \"DIALOG\" && element.tagName !== \"DIV\"\n ? `${part}: expected to render a <dialog> or a <div> but got ` +\n `<${element.tagName.toLowerCase()}>.`\n : null),\n );\n const resetInterest = interest.reset;\n const setElement = useCallback(\n (element: HTMLElement) => {\n checkElement?.(element);\n popupRef.current = element;\n const listeners: [string, EventListener][] = [\n [\"beforetoggle\", (event) => handlers.current.onBeforeToggle(event)],\n [\"toggle\", (event) => handlers.current.onToggle(event)],\n [\"command\", (event) => handlers.current.onCommand(event)],\n // Fired only where `interestfor` exists (Chromium).\n [\"interest\", (event) => handlers.current.onInterest(event)],\n [\"loseinterest\", (event) => handlers.current.onLoseInterest(event)],\n ];\n for (const [type, listener] of listeners) element.addEventListener(type, listener);\n // A pre-hydration open is shown from the first commit; a popup removed while open fires no\n // `toggle`, so the detach clears the mirror.\n if (isLibrary) setShown(isPopoverOpen(element));\n // The ref re-runs whenever the merged ref changes (an inline consumer `ref`), and its detach\n // stopped the listeners: a popup that is still shown gets them back, as no `toggle` comes.\n if (isPopoverOpen(element)) {\n stopWhileShown.current ??= latestWhileShown.current?.(element) ?? null;\n }\n\n let autofocused: HTMLElement | null = null;\n if (!isLibrary && initialFocus !== undefined) {\n const target = resolveInitialFocus(element, initialFocus);\n if (target !== null && element.contains(target) && !target.hasAttribute(\"autofocus\")) {\n target.setAttribute(\"autofocus\", \"\");\n autofocused = target;\n }\n }\n\n return () => {\n for (const [type, listener] of listeners) element.removeEventListener(type, listener);\n resetInterest();\n stopListeningWhileShown();\n if (isLibrary) setShown(false);\n autofocused?.removeAttribute(\"autofocus\");\n if (popupRef.current === element) popupRef.current = null;\n };\n },\n [\n checkElement,\n popupRef,\n setShown,\n handlers,\n latestWhileShown,\n isLibrary,\n initialFocus,\n resetInterest,\n ],\n );\n\n // Development check (design 9): a `dialog`, `alertdialog` or `menu` role needs a name once the\n // popup is (or can be) shown.\n useShownNameWarning(\n popupRef,\n !isLibrary || ctx.committed,\n isDev &&\n `${part}: the popup has no accessible name. Render a Title, or give the Popup an ` +\n \"`aria-label`.\",\n needsName,\n );\n\n const visible = ctx.committed || exit.held;\n const renderContent = (children: () => ReactNode): ReactNode =>\n renderOverlayContent(\n { isLibrary, keepMounted: options.keepMounted, visible, wrapContent },\n children,\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AiB,aACrB,qBACE;EAAE;EAAW,aAAa,QAAQ;EAAa;EAAS;CAAY,GACpE,QACF;CACF,OAAO;EAAE;EAAY;EAAS;EAAe;CAAO;AACtD"}
@@ -1 +1 @@
1
- {"version":3,"file":"use-popover-trigger.d.mts","names":[],"sources":["../../src/internal/use-popover-trigger.ts"],"mappings":";;;;;;iBAeiB;;WAEN;;WAEA;WACA"}
1
+ {"version":3,"file":"use-popover-trigger.d.mts","names":[],"sources":["../../src/internal/use-popover-trigger.ts"],"mappings":";;;;;;iBA6CiB;;WAEN;;WAEA;WACA"}
@@ -8,18 +8,37 @@ import { useCallback } from "react";
8
8
  //#region src/internal/use-popover-trigger.ts
9
9
  const isDev = process.env.NODE_ENV !== "production";
10
10
  /**
11
+ * Owned and never written on an overlay Trigger (Popover, Menu, Combobox): the default
12
+ * `popovertarget` action, which a render element must not change, and an Invoker Command, which
13
+ * would take precedence over `popovertarget` and act on another element.
14
+ */
15
+ const RESERVED_INVOKER_KEYS = {
16
+ popoverTargetAction: void 0,
17
+ commandfor: void 0,
18
+ command: void 0
19
+ };
20
+ /**
21
+ * The library-mode dev warning for a Trigger rendered as another element than a `<button>`: only
22
+ * an invoker button is spared by the popover's light dismiss, so a press while the popup is open
23
+ * hides it before the click. `popover` and `popup` are the nouns the text uses for it.
24
+ */
25
+ function nonInvokerMessage(part, tag, popover, popup) {
26
+ return `${part}: rendered a <${tag}>. Only a <button> is the ${popover}'s invoker: a press on this element while the ${popup} is open closes it through light dismiss before the click, so the close is not awaited, openChangeAction(false) cannot veto it and there is no exit transition. Render a <button>.`;
27
+ }
28
+ /**
11
29
  * The Trigger of a popover-like component (design/components/popover.md 14.3):
12
- * `button[commandfor][command="toggle-popover"]` with `aria-expanded`. In JS-free mode the
13
- * browser runs the command and the Popup keeps `aria-expanded` current on the element. In library
14
- * mode the click is cancelled (so the command does not run) and toggles against what the user
15
- * already intends: an open through `requestOpen`, a library-owned close through `requestClose`.
16
- * There `aria-expanded` renders whether the popup is shown (in the top layer); `data-open` and `state.open` are
17
- * optimistic (#118).
30
+ * `button[popoverTarget]`, with no `aria-expanded` on an invoker: every engine exposes the
31
+ * popover's shown state from the invoker relationship. In JS-free mode the browser toggles
32
+ * the popover and the Popup keeps `data-open` current on the element. In library mode the click
33
+ * is cancelled (so the activation does not run) and toggles against what the user already
34
+ * intends: an open through `requestOpen`, a library-owned close through `requestClose`. There
35
+ * `data-open` and `state.open` are optimistic; a non-button `render` (no invoker) renders
36
+ * `aria-expanded` from whether the popup is shown (in the top layer).
18
37
  *
19
38
  * Menu adds `aria-haspopup="menu"` and its own key handling on top.
20
39
  */
21
40
  function usePopoverTrigger(ctx, options) {
22
- const { part, disabled, render, handlers, activate, opensOnly = false, disabledAs = "native" } = options;
41
+ const { part, disabled, render, handlers, activate, beforeOpen, disabledAs = "native" } = options;
23
42
  const isLibrary = ctx.mode === "library";
24
43
  const { ids, triggerRef, popupRef } = ctx;
25
44
  const state = {
@@ -30,13 +49,13 @@ function usePopoverTrigger(ctx, options) {
30
49
  const checkElement = useElementCheck(isDev && ((element) => {
31
50
  if (element.tagName === "BUTTON") return null;
32
51
  const tag = element.tagName.toLowerCase();
33
- if (isLibrary && opensOnly) return `${part}: rendered a <${tag}>. Only a <button> is the popover's invoker: a press on this element while its popup is open dismisses the popup through light dismiss instead of moving focus into it. Render a <button>.`;
34
- return isLibrary ? `${part}: rendered a <${tag}>. Only a <button> is the popover's invoker: a press on this element while the popup is open closes it through light dismiss before the click, so the close is not awaited, openChangeAction(false) cannot veto it and there is no exit transition. Render a <button>.` : `${part}: rendered a <${tag}> in JS-free mode. Only a <button> runs \`command="toggle-popover"\`; this trigger will not open the popover. Render a <button>, or put the component in library mode (\`defaultOpen={false}\`).`;
52
+ if (isLibrary && activate !== void 0) return `${part}: rendered a <${tag}>. Only a <button> is the popover's invoker: a press on this element while its popup is open dismisses the popup through light dismiss instead of moving focus into it. Render a <button>.`;
53
+ return isLibrary ? nonInvokerMessage(part, tag, "popover", "popup") : `${part}: rendered a <${tag}> in JS-free mode. Only a <button> is a \`popovertarget\` invoker; this trigger will not open the popover. Render a <button>, or put the component in library mode (\`defaultOpen={false}\`).`;
35
54
  }));
36
55
  const ref = useCallback((element) => {
37
56
  checkElement?.(element);
38
57
  const unregister = registerTrigger(triggerRef, element, part);
39
- if (!isLibrary && popupRef.current !== null) element.setAttribute("aria-expanded", String(isPopoverOpen(popupRef.current)));
58
+ if (!isLibrary && popupRef.current !== null) element.toggleAttribute("data-open", isPopoverOpen(popupRef.current));
40
59
  return unregister;
41
60
  }, [
42
61
  isLibrary,
@@ -54,7 +73,10 @@ function usePopoverTrigger(ctx, options) {
54
73
  }
55
74
  const native = event.nativeEvent;
56
75
  if (ctx.intended()) ctx.requestClose(native, "activate");
57
- else ctx.requestOpen(native, "activate");
76
+ else {
77
+ beforeOpen?.(event);
78
+ ctx.requestOpen(native, "activate");
79
+ }
58
80
  };
59
81
  const merged = { ...handlers };
60
82
  if (isLibrary) {
@@ -74,9 +96,9 @@ function usePopoverTrigger(ctx, options) {
74
96
  libraryProps: {
75
97
  ...rendersButton(render) && { type: "button" },
76
98
  ...disabledProps.props,
77
- commandfor: invoker ? ids.popup : void 0,
78
- command: invoker ? "toggle-popover" : void 0,
79
- "aria-expanded": isLibrary ? ctx.shown : false,
99
+ popoverTarget: invoker ? ids.popup : void 0,
100
+ ...RESERVED_INVOKER_KEYS,
101
+ "aria-expanded": invoker ? void 0 : isLibrary ? ctx.shown : false,
80
102
  ...merged,
81
103
  "data-open": dataAttr(state.open),
82
104
  "data-pending": dataAttr(state.pending),
@@ -86,6 +108,6 @@ function usePopoverTrigger(ctx, options) {
86
108
  };
87
109
  }
88
110
  //#endregion
89
- export { usePopoverTrigger };
111
+ export { RESERVED_INVOKER_KEYS, nonInvokerMessage, usePopoverTrigger };
90
112
 
91
113
  //# sourceMappingURL=use-popover-trigger.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"use-popover-trigger.mjs","names":[],"sources":["../../src/internal/use-popover-trigger.ts"],"sourcesContent":["\"use client\";\nimport { useCallback } from \"react\";\nimport type { ComponentPropsWithRef, DOMAttributes, MouseEvent } from \"react\";\nimport { dataAttr } from \"./data-attr.js\";\nimport { isPopoverOpen } from \"./popover-open.js\";\nimport { registerTrigger } from \"./trigger-ref.js\";\nimport type { RenderProp } from \"./types.js\";\nimport { useElementCheck } from \"./use-element-check.js\";\nimport { disabledButton, rendersButton } from \"./use-render.js\";\nimport type { DataAttributes } from \"./use-render.js\";\nimport type { PopoverRootValue } from \"./use-overlay-root.js\";\n\nconst isDev = process.env.NODE_ENV !== \"production\";\n\n/** The state of an overlay Trigger (Popover.Trigger, Menu.Trigger and its siblings). */\nexport interface PopoverTriggerHookState {\n /** Optimistic open state. A Popover in JS-free mode (the browser owns it) reports `false`. */\n readonly open: boolean;\n /** The Root's transition is pending (an open, a part-initiated close or a dismissal notification). */\n readonly pending: boolean;\n readonly disabled: boolean;\n}\n\n/** Event handlers a component layers onto the Trigger's own (Menu's keys and hover intent). */\nexport type PopoverTriggerHandlers = Pick<\n DOMAttributes<HTMLButtonElement>,\n \"onClick\" | \"onKeyDown\" | \"onMouseDown\" | \"onPointerMove\" | \"onPointerEnter\" | \"onPointerLeave\"\n>;\n\nexport interface UsePopoverTriggerOptions<State> {\n /** Public name of the part for development warnings (`\"Popover.Trigger\"`). */\n readonly part: string;\n readonly disabled: boolean;\n readonly render: RenderProp<ComponentPropsWithRef<\"button\">, State> | undefined;\n /**\n * Extra handlers, merged in front of the Trigger's own: for a key both define, the extra one\n * runs first (the consumer's pass-through handler still runs before both, conventions 1.2).\n */\n readonly handlers?: PopoverTriggerHandlers;\n /**\n * What a click does in library mode, after the command has been cancelled and `disabled`\n * checked. Default: toggle against `intended()` (`requestOpen` / `requestClose`). Menu's\n * SubmenuTrigger opens, or moves focus into an already open submenu, and never closes.\n */\n readonly activate?: (event: MouseEvent<HTMLElement>) => void;\n /**\n * The click never closes (Menu's SubmenuTrigger): only picks the library-mode non-button\n * warning's text, since there a press while open dismisses the popup instead of moving focus\n * into it. (Not `activate !== undefined`: Menu.Trigger has an `activate` that closes.)\n */\n readonly opensOnly?: boolean;\n /**\n * How `disabled` is rendered. `\"native\"` (default): the `disabled` attribute, so the button is\n * no invoker at all; in library mode a link or component `render` still gets the `\"aria\"`\n * branch, because native `disabled` means nothing on a link and the installed click handler is\n * what refuses. `\"aria\"`: `aria-disabled=\"true\"` and no `disabled` (a menu item stays\n * focusable); the click handler still refuses.\n */\n readonly disabledAs?: \"native\" | \"aria\";\n}\n\nexport interface PopoverTriggerHook {\n readonly state: PopoverTriggerHookState;\n /** Owned props (conventions 1.2) for `useRender`'s `libraryProps`. */\n readonly libraryProps: ComponentPropsWithRef<\"button\"> & DataAttributes;\n /** Registers the element as the Root's Trigger; pass as `useRender`'s `ref`. */\n readonly ref: (element: HTMLElement) => () => void;\n}\n\n/**\n * The Trigger of a popover-like component (design/components/popover.md 14.3):\n * `button[commandfor][command=\"toggle-popover\"]` with `aria-expanded`. In JS-free mode the\n * browser runs the command and the Popup keeps `aria-expanded` current on the element. In library\n * mode the click is cancelled (so the command does not run) and toggles against what the user\n * already intends: an open through `requestOpen`, a library-owned close through `requestClose`.\n * There `aria-expanded` renders whether the popup is shown (in the top layer); `data-open` and `state.open` are\n * optimistic (#118).\n *\n * Menu adds `aria-haspopup=\"menu\"` and its own key handling on top.\n */\nexport function usePopoverTrigger<State>(\n ctx: PopoverRootValue,\n options: UsePopoverTriggerOptions<State>,\n): PopoverTriggerHook {\n const {\n part,\n disabled,\n render,\n handlers,\n activate,\n opensOnly = false,\n disabledAs = \"native\",\n } = options;\n const isLibrary = ctx.mode === \"library\";\n const { ids, triggerRef, popupRef } = ctx;\n\n const state: PopoverTriggerHookState = {\n open: ctx.optimistic,\n // Opens, part-initiated closes and dismissal notifications all belong to the Trigger (4.2).\n pending: ctx.pending,\n disabled,\n };\n\n const checkElement = useElementCheck(\n isDev &&\n ((element) => {\n if (element.tagName === \"BUTTON\") return null;\n const tag = element.tagName.toLowerCase();\n // Library mode: the click handler works, but only an invoker button is spared by the\n // popover's light dismiss, so a press while open hides the popup before the click (#115).\n if (isLibrary && opensOnly) {\n return (\n `${part}: rendered a <${tag}>. Only a <button> is the popover's invoker: a press on ` +\n \"this element while its popup is open dismisses the popup through light dismiss \" +\n \"instead of moving focus into it. Render a <button>.\"\n );\n }\n return isLibrary\n ? `${part}: rendered a <${tag}>. Only a <button> is the popover's invoker: a press on ` +\n \"this element while the popup is open closes it through light dismiss before the \" +\n \"click, so the close is not awaited, openChangeAction(false) cannot veto it and \" +\n \"there is no exit transition. Render a <button>.\"\n : `${part}: rendered a <${tag}> in JS-free mode. Only a <button> runs ` +\n '`command=\"toggle-popover\"`; this trigger will not open the popover. Render a ' +\n \"<button>, or put the component in library mode (`defaultOpen={false}`).\";\n }),\n );\n const ref = useCallback(\n (element: HTMLElement) => {\n checkElement?.(element);\n const unregister = registerTrigger(triggerRef, element, part);\n // JS-free mode: the DOM owns `aria-expanded` (design 9). A Trigger that mounts after the\n // Popup (or is re-created) picks up the current state here.\n if (!isLibrary && popupRef.current !== null) {\n element.setAttribute(\"aria-expanded\", String(isPopoverOpen(popupRef.current)));\n }\n return unregister;\n },\n [isLibrary, checkElement, triggerRef, popupRef, part],\n );\n\n const onClick = (event: MouseEvent<HTMLElement>) => {\n // Cancelling the click cancels the command (it runs as the button's activation behaviour,\n // only if the click was not cancelled). Enter and Space synthesise the same click.\n event.preventDefault();\n if (disabled) return;\n if (activate !== undefined) {\n activate(event);\n return;\n }\n const native = event.nativeEvent;\n if (ctx.intended()) ctx.requestClose(native, \"activate\");\n else ctx.requestOpen(native, \"activate\");\n };\n\n // The component's handlers first, then the Trigger's (design/components/menu.md 14). The click\n // handler is only owned when installed, so a render element keeps its own `onClick` in JS-free\n // mode.\n const merged: PopoverTriggerHandlers = { ...handlers };\n if (isLibrary) {\n const extra = handlers?.onClick;\n merged.onClick =\n extra === undefined\n ? onClick\n : (event) => {\n extra(event);\n onClick(event);\n };\n }\n // The click handler is installed in library mode only; in JS-free mode the command needs\n // native `disabled` to stop it.\n const disabledProps = disabledButton(render, disabled, {\n handlesClick: isLibrary,\n alwaysFocusable: disabledAs === \"aria\",\n });\n\n const invoker = disabledProps.invoker && rendersButton(render);\n\n const libraryProps: ComponentPropsWithRef<\"button\"> & DataAttributes = {\n // `type` only applies to a <button>; on any other element the key is not owned.\n ...(rendersButton(render) && { type: \"button\" as const }),\n // Owned: a render element must not re-enable a disabled Trigger (in JS-free mode the browser\n // would run its command).\n ...disabledProps.props,\n // Only on a button (or a component, assumed to render one): another element is no invoker,\n // and the attributes would claim otherwise (#115).\n commandfor: invoker ? ids.popup : undefined,\n command: invoker ? \"toggle-popover\" : undefined,\n // Library mode: shown (the popup is in the top layer); `data-open` is the optimistic one.\n // Chromium and WebKit compute an invoker's state from the popover, so this is the one value\n // every engine agrees on (#118). JS-free mode: \"false\" in React; the Popup's `toggle`\n // listener writes the DOM value, and React never rewrites an unchanged prop.\n \"aria-expanded\": isLibrary ? ctx.shown : false,\n ...merged,\n \"data-open\": dataAttr(state.open),\n \"data-pending\": dataAttr(state.pending),\n // Every mode: the styling hook agrees with the rendered `disabled` / `aria-disabled`\n // (conventions 1.2).\n \"data-disabled\": dataAttr(disabled),\n };\n\n return { state, libraryProps, ref };\n}\n"],"mappings":";;;;;;;;AAYA,MAAM,QAAQ,QAAQ,IAAI,aAAa;;;;;;;;;;;;AAoEvC,SAAgB,kBACd,KACA,SACoB;CACpB,MAAM,EACJ,MACA,UACA,QACA,UACA,UACA,YAAY,OACZ,aAAa,aACX;CACJ,MAAM,YAAY,IAAI,SAAS;CAC/B,MAAM,EAAE,KAAK,YAAY,aAAa;CAEtC,MAAM,QAAiC;EACrC,MAAM,IAAI;EAEV,SAAS,IAAI;EACb;CACF;CAEA,MAAM,eAAe,gBACnB,WACI,YAAY;EACZ,IAAI,QAAQ,YAAY,UAAU,OAAO;EACzC,MAAM,MAAM,QAAQ,QAAQ,YAAY;EAGxC,IAAI,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GT;EAAG;CAAI;AACpC"}
1
+ {"version":3,"file":"use-popover-trigger.mjs","names":[],"sources":["../../src/internal/use-popover-trigger.ts"],"sourcesContent":["\"use client\";\nimport { useCallback } from \"react\";\nimport type { ComponentPropsWithRef, DOMAttributes, MouseEvent } from \"react\";\nimport { dataAttr } from \"./data-attr.js\";\nimport { isPopoverOpen } from \"./popover-open.js\";\nimport { registerTrigger } from \"./trigger-ref.js\";\nimport type { RenderProp } from \"./types.js\";\nimport { useElementCheck } from \"./use-element-check.js\";\nimport { disabledButton, rendersButton } from \"./use-render.js\";\nimport type { DataAttributes } from \"./use-render.js\";\nimport type { PopoverRootValue } from \"./use-overlay-root.js\";\n\nconst isDev = process.env.NODE_ENV !== \"production\";\n\n/**\n * Owned and never written on an overlay Trigger (Popover, Menu, Combobox): the default\n * `popovertarget` action, which a render element must not change, and an Invoker Command, which\n * would take precedence over `popovertarget` and act on another element.\n */\nexport const RESERVED_INVOKER_KEYS = {\n popoverTargetAction: undefined,\n commandfor: undefined,\n command: undefined,\n} as const;\n\n/**\n * The library-mode dev warning for a Trigger rendered as another element than a `<button>`: only\n * an invoker button is spared by the popover's light dismiss, so a press while the popup is open\n * hides it before the click. `popover` and `popup` are the nouns the text uses for it.\n */\nexport function nonInvokerMessage(\n part: string,\n tag: string,\n popover: string,\n popup: string,\n): string {\n return (\n `${part}: rendered a <${tag}>. Only a <button> is the ${popover}'s invoker: a press on ` +\n `this element while the ${popup} is open closes it through light dismiss before the ` +\n \"click, so the close is not awaited, openChangeAction(false) cannot veto it and \" +\n \"there is no exit transition. Render a <button>.\"\n );\n}\n\n/** The state of an overlay Trigger (Popover.Trigger, Menu.Trigger and its siblings). */\nexport interface PopoverTriggerHookState {\n /** Optimistic open state. A Popover in JS-free mode (the browser owns it) reports `false`. */\n readonly open: boolean;\n /** The Root's transition is pending (an open, a part-initiated close or a dismissal notification). */\n readonly pending: boolean;\n readonly disabled: boolean;\n}\n\n/** Event handlers a component layers onto the Trigger's own (Menu's keys and hover intent). */\nexport type PopoverTriggerHandlers = Pick<\n DOMAttributes<HTMLButtonElement>,\n \"onClick\" | \"onKeyDown\" | \"onMouseDown\" | \"onPointerMove\" | \"onPointerEnter\" | \"onPointerLeave\"\n>;\n\nexport interface UsePopoverTriggerOptions<State> {\n /** Public name of the part for development warnings (`\"Popover.Trigger\"`). */\n readonly part: string;\n readonly disabled: boolean;\n readonly render: RenderProp<ComponentPropsWithRef<\"button\">, State> | undefined;\n /**\n * Extra handlers, merged in front of the Trigger's own: for a key both define, the extra one\n * runs first (the consumer's pass-through handler still runs before both, conventions 1.2).\n */\n readonly handlers?: PopoverTriggerHandlers;\n /**\n * What a click does in library mode, after the command has been cancelled and `disabled`\n * checked, replacing the default toggle against `intended()` (`requestOpen` / `requestClose`).\n * Menu's SubmenuTrigger opens, or moves focus into an already open submenu, and never closes;\n * so with `activate` the library-mode non-button warning says a press while open dismisses the\n * popup instead of moving focus into it.\n */\n readonly activate?: (event: MouseEvent<HTMLElement>) => void;\n /** Runs right before the default toggle's `requestOpen` (Menu.Trigger: the open cause). */\n readonly beforeOpen?: (event: MouseEvent<HTMLElement>) => void;\n /**\n * How `disabled` is rendered. `\"native\"` (default): the `disabled` attribute, so the button is\n * no invoker at all; in library mode a link or component `render` still gets the `\"aria\"`\n * branch, because native `disabled` means nothing on a link and the installed click handler is\n * what refuses. `\"aria\"`: `aria-disabled=\"true\"` and no `disabled` (a menu item stays\n * focusable); the click handler still refuses.\n */\n readonly disabledAs?: \"native\" | \"aria\";\n}\n\nexport interface PopoverTriggerHook {\n readonly state: PopoverTriggerHookState;\n /** Owned props (conventions 1.2) for `useRender`'s `libraryProps`. */\n readonly libraryProps: ComponentPropsWithRef<\"button\"> & DataAttributes;\n /** Registers the element as the Root's Trigger; pass as `useRender`'s `ref`. */\n readonly ref: (element: HTMLElement) => () => void;\n}\n\n/**\n * The Trigger of a popover-like component (design/components/popover.md 14.3):\n * `button[popoverTarget]`, with no `aria-expanded` on an invoker: every engine exposes the\n * popover's shown state from the invoker relationship. In JS-free mode the browser toggles\n * the popover and the Popup keeps `data-open` current on the element. In library mode the click\n * is cancelled (so the activation does not run) and toggles against what the user already\n * intends: an open through `requestOpen`, a library-owned close through `requestClose`. There\n * `data-open` and `state.open` are optimistic; a non-button `render` (no invoker) renders\n * `aria-expanded` from whether the popup is shown (in the top layer).\n *\n * Menu adds `aria-haspopup=\"menu\"` and its own key handling on top.\n */\nexport function usePopoverTrigger<State>(\n ctx: PopoverRootValue,\n options: UsePopoverTriggerOptions<State>,\n): PopoverTriggerHook {\n const { part, disabled, render, handlers, activate, beforeOpen, disabledAs = \"native\" } = options;\n const isLibrary = ctx.mode === \"library\";\n const { ids, triggerRef, popupRef } = ctx;\n\n const state: PopoverTriggerHookState = {\n open: ctx.optimistic,\n // Opens, part-initiated closes and dismissal notifications all belong to the Trigger (4.2).\n pending: ctx.pending,\n disabled,\n };\n\n const checkElement = useElementCheck(\n isDev &&\n ((element) => {\n if (element.tagName === \"BUTTON\") return null;\n const tag = element.tagName.toLowerCase();\n // Library mode: the click handler works, but only an invoker button is spared by the\n // popover's light dismiss, so a press while open hides the popup before the click.\n if (isLibrary && activate !== undefined) {\n return (\n `${part}: rendered a <${tag}>. Only a <button> is the popover's invoker: a press on ` +\n \"this element while its popup is open dismisses the popup through light dismiss \" +\n \"instead of moving focus into it. Render a <button>.\"\n );\n }\n return isLibrary\n ? nonInvokerMessage(part, tag, \"popover\", \"popup\")\n : `${part}: rendered a <${tag}> in JS-free mode. Only a <button> is a ` +\n \"`popovertarget` invoker; this trigger will not open the popover. Render a \" +\n \"<button>, or put the component in library mode (`defaultOpen={false}`).\";\n }),\n );\n const ref = useCallback(\n (element: HTMLElement) => {\n checkElement?.(element);\n const unregister = registerTrigger(triggerRef, element, part);\n // JS-free mode: the DOM owns `data-open` (design 9). A Trigger that mounts after the\n // Popup (or is re-created) picks up the current state here.\n if (!isLibrary && popupRef.current !== null) {\n element.toggleAttribute(\"data-open\", isPopoverOpen(popupRef.current));\n }\n return unregister;\n },\n [isLibrary, checkElement, triggerRef, popupRef, part],\n );\n\n const onClick = (event: MouseEvent<HTMLElement>) => {\n // Cancelling the click cancels the popover toggle (it runs as the button's activation\n // behaviour, only if the click was not cancelled). Enter and Space synthesise the same click.\n event.preventDefault();\n if (disabled) return;\n if (activate !== undefined) {\n activate(event);\n return;\n }\n const native = event.nativeEvent;\n if (ctx.intended()) {\n ctx.requestClose(native, \"activate\");\n } else {\n // First: what it records (Menu's open cause) must be in place before anything can show the\n // popup. Today the show waits for the apply effect, so the order is not observable.\n beforeOpen?.(event);\n ctx.requestOpen(native, \"activate\");\n }\n };\n\n // The component's handlers first, then the Trigger's (design/components/menu.md 14). The click\n // handler is only owned when installed, so a render element keeps its own `onClick` in JS-free\n // mode.\n const merged: PopoverTriggerHandlers = { ...handlers };\n if (isLibrary) {\n const extra = handlers?.onClick;\n merged.onClick =\n extra === undefined\n ? onClick\n : (event) => {\n extra(event);\n onClick(event);\n };\n }\n // The click handler is installed in library mode only; in JS-free mode the activation needs\n // native `disabled` to stop it.\n const disabledProps = disabledButton(render, disabled, {\n handlesClick: isLibrary,\n alwaysFocusable: disabledAs === \"aria\",\n });\n\n const invoker = disabledProps.invoker && rendersButton(render);\n\n const libraryProps: ComponentPropsWithRef<\"button\"> & DataAttributes = {\n // `type` only applies to a <button>; on any other element the key is not owned.\n ...(rendersButton(render) && { type: \"button\" as const }),\n // Owned: a render element must not re-enable a disabled Trigger (in JS-free mode the browser\n // would toggle the popover).\n ...disabledProps.props,\n // Only on a button (or a component, assumed to render one): another element is no invoker,\n // and the attribute would claim otherwise.\n popoverTarget: invoker ? ids.popup : undefined,\n ...RESERVED_INVOKER_KEYS,\n // No `aria-expanded` on an invoker: every engine exposes the popover's shown state from\n // `popovertarget`, and ARIA in HTML forbids the attribute there. Otherwise nothing else\n // exposes the state: library mode renders shown (the popup is in the top layer; `data-open`\n // is the optimistic one), JS-free mode cannot know it and renders \"false\".\n \"aria-expanded\": invoker ? undefined : isLibrary ? ctx.shown : false,\n ...merged,\n \"data-open\": dataAttr(state.open),\n \"data-pending\": dataAttr(state.pending),\n // Every mode: the styling hook agrees with the rendered `disabled` / `aria-disabled`\n // (conventions 1.2).\n \"data-disabled\": dataAttr(disabled),\n };\n\n return { state, libraryProps, ref };\n}\n"],"mappings":";;;;;;;;AAYA,MAAM,QAAQ,QAAQ,IAAI,aAAa;;;;;;AAOvC,MAAa,wBAAwB;CACnC,qBAAqB,KAAA;CACrB,YAAY,KAAA;CACZ,SAAS,KAAA;AACX;;;;;;AAOA,SAAgB,kBACd,MACA,KACA,SACA,OACQ;CACR,OACE,GAAG,KAAK,gBAAgB,IAAI,4BAA4B,QAAQ,gDACtC,MAAM;AAIpC;;;;;;;;;;;;;AAmEA,SAAgB,kBACd,KACA,SACoB;CACpB,MAAM,EAAE,MAAM,UAAU,QAAQ,UAAU,UAAU,YAAY,aAAa,aAAa;CAC1F,MAAM,YAAY,IAAI,SAAS;CAC/B,MAAM,EAAE,KAAK,YAAY,aAAa;CAEtC,MAAM,QAAiC;EACrC,MAAM,IAAI;EAEV,SAAS,IAAI;EACb;CACF;CAEA,MAAM,eAAe,gBACnB,WACI,YAAY;EACZ,IAAI,QAAQ,YAAY,UAAU,OAAO;EACzC,MAAM,MAAM,QAAQ,QAAQ,YAAY;EAGxC,IAAI,aAAa,aAAa,KAAA,GAC5B,OACE,GAAG,KAAK,gBAAgB,IAAI;EAKhC,OAAO,YACH,kBAAkB,MAAM,KAAK,WAAW,OAAO,IAC/C,GAAG,KAAK,gBAAgB,IAAI;CAGlC,EACJ;CACA,MAAM,MAAM,aACT,YAAyB;EACxB,eAAe,OAAO;EACtB,MAAM,aAAa,gBAAgB,YAAY,SAAS,IAAI;EAG5D,IAAI,CAAC,aAAa,SAAS,YAAY,MACrC,QAAQ,gBAAgB,aAAa,cAAc,SAAS,OAAO,CAAC;EAEtE,OAAO;CACT,GACA;EAAC;EAAW;EAAc;EAAY;EAAU;CAAI,CACtD;CAEA,MAAM,WAAW,UAAmC;EAGlD,MAAM,eAAe;EACrB,IAAI,UAAU;EACd,IAAI,aAAa,KAAA,GAAW;GAC1B,SAAS,KAAK;GACd;EACF;EACA,MAAM,SAAS,MAAM;EACrB,IAAI,IAAI,SAAS,GACf,IAAI,aAAa,QAAQ,UAAU;OAC9B;GAGL,aAAa,KAAK;GAClB,IAAI,YAAY,QAAQ,UAAU;EACpC;CACF;CAKA,MAAM,SAAiC,EAAE,GAAG,SAAS;CACrD,IAAI,WAAW;EACb,MAAM,QAAQ,UAAU;EACxB,OAAO,UACL,UAAU,KAAA,IACN,WACC,UAAU;GACT,MAAM,KAAK;GACX,QAAQ,KAAK;EACf;CACR;CAGA,MAAM,gBAAgB,eAAe,QAAQ,UAAU;EACrD,cAAc;EACd,iBAAiB,eAAe;CAClC,CAAC;CAED,MAAM,UAAU,cAAc,WAAW,cAAc,MAAM;CAyB7D,OAAO;EAAE;EAAO,cAAA;GArBd,GAAI,cAAc,MAAM,KAAK,EAAE,MAAM,SAAkB;GAGvD,GAAG,cAAc;GAGjB,eAAe,UAAU,IAAI,QAAQ,KAAA;GACrC,GAAG;GAKH,iBAAiB,UAAU,KAAA,IAAY,YAAY,IAAI,QAAQ;GAC/D,GAAG;GACH,aAAa,SAAS,MAAM,IAAI;GAChC,gBAAgB,SAAS,MAAM,OAAO;GAGtC,iBAAiB,SAAS,QAAQ;EAGT;EAAG;CAAI;AACpC"}
@@ -9,7 +9,7 @@ const toDirection = (value) => value === "rtl" ? "rtl" : "ltr";
9
9
  /**
10
10
  * Where the browser actually placed an anchored popup (design/conventions.md 13.2): the
11
11
  * `position-try-fallbacks` option it applied, read from the computed `position-area` while the
12
- * popup is shown. Observation only; runs whatever opened the popup (`interestfor` and
12
+ * popup is shown. Observation only; runs whatever opened the popup (`interestfor`, `popovertarget` and
13
13
  * `commandfor` included). Read on a `ResizeObserver` (hidden to shown is a resize, delivered
14
14
  * before paint), `toggle`, and while shown document `scroll` and window `resize` plus the next
15
15
  * two frames. Written urgently (`flushSync`), and only when the rendered pair changes: an open
@@ -1 +1 @@
1
- {"version":3,"file":"use-resolved-placement.mjs","names":[],"sources":["../../src/internal/use-resolved-placement.ts"],"sourcesContent":["\"use client\";\nimport { useCallback, useLayoutEffect, useRef, useState } from \"react\";\nimport type { CSSProperties, RefCallback } from \"react\";\nimport { flushSync } from \"react-dom\";\nimport { parsePositionArea, POSITION_TRY_FALLBACKS, positionArea } from \"./anchor-position.js\";\nimport type {\n AnchorAlign,\n AnchorSide,\n Direction,\n PhysicalSide,\n ResolvedPlacement,\n} from \"./anchor-position.js\";\nimport { isPopoverOpen } from \"./popover-open.js\";\nimport { resolveStateValue } from \"./render-element.js\";\nimport type { DataAttributes } from \"./render-element.js\";\nimport type { StateValue } from \"./types.js\";\n\nexport interface PlacementRequest<Side extends AnchorSide> {\n /** The requested side; `null` when the stylesheet owns placement (the hook is idle). */\n readonly side: Side | null;\n readonly align: AnchorAlign;\n}\n\nexport interface PlacementResult<Side extends AnchorSide> {\n /** The resolved physical side while the popup is shown, else the requested side. */\n readonly side: Side | PhysicalSide | null;\n /** The resolved alignment while shown, else the requested one. */\n readonly align: AnchorAlign;\n /** Merge into the popup element's ref. Stable. */\n readonly ref: RefCallback<HTMLElement>;\n}\n\nconst toDirection = (value: string): Direction => (value === \"rtl\" ? \"rtl\" : \"ltr\");\n\n/**\n * Where the browser actually placed an anchored popup (design/conventions.md 13.2): the\n * `position-try-fallbacks` option it applied, read from the computed `position-area` while the\n * popup is shown. Observation only; runs whatever opened the popup (`interestfor` and\n * `commandfor` included). Read on a `ResizeObserver` (hidden to shown is a resize, delivered\n * before paint), `toggle`, and while shown document `scroll` and window `resize` plus the next\n * two frames. Written urgently (`flushSync`), and only when the rendered pair changes: an open\n * where it was asked costs no render. Hidden again, it resets once the popup no longer renders\n * (an exit animation keeps the resolved side). Idle with `side: null`.\n */\nexport function useResolvedPlacement<Side extends AnchorSide>(\n request: PlacementRequest<Side>,\n): PlacementResult<Side> {\n const { side, align } = request;\n const [resolved, setResolved] = useState<ResolvedPlacement | null>(null);\n // What the state holds (or is about to hold), so an unchanged read schedules nothing.\n const written = useRef<ResolvedPlacement | null>(null);\n // The request the element is rendered with (kept by the layout effect below).\n const requested = useRef<PlacementRequest<Side>>(request);\n // The mounted element's read, for the layout effect below.\n const sync = useRef<((urgent: boolean) => void) | null>(null);\n\n const ref = useCallback((element: HTMLElement | null) => {\n if (element === null) return;\n const doc = element.ownerDocument;\n const win = doc.defaultView ?? window;\n\n const write = (value: ResolvedPlacement | null, urgent: boolean) => {\n // Where it was asked to be: the requested values say so already, no state needed.\n const next =\n value !== null &&\n value.side === requested.current.side &&\n value.align === requested.current.align\n ? null\n : value;\n const previous = written.current;\n if (\n previous === next ||\n (previous !== null &&\n next !== null &&\n previous.side === next.side &&\n previous.align === next.align)\n ) {\n return;\n }\n written.current = next;\n if (urgent) flushSync(() => setResolved(next));\n else setResolved(next);\n };\n\n let listening = false;\n const listen = (on: boolean) => {\n if (on === listening) return;\n listening = on;\n if (on) {\n doc.addEventListener(\"scroll\", onMove, { capture: true, passive: true });\n win.addEventListener(\"resize\", onMove);\n } else {\n doc.removeEventListener(\"scroll\", onMove, { capture: true });\n win.removeEventListener(\"resize\", onMove);\n cancelFrames();\n }\n };\n\n // Both engines (Chromium 156, Firefox 157) apply the scroll-dependent anchoring state, the\n // option and the scroll-compensated geometry alike, in the layout of the frame after the\n // `scroll` event: a read in the handler, or in a rAF registered from it (which runs before\n // that layout), sees the old option even after a forced layout. The timing is unspecified\n // (css-anchor-position-1 §3.3 issue), so read again in the next two frames; a scroll that\n // arrives while that is pending restarts it at the end, so the last scroll is always followed.\n // Separately, Chromium 156 keeps an overflowing option for a top-layer popover once the first\n // frames after the show have passed (a bug, §6.5; upstream item #92): then no frame reads a\n // new option, and `data-side` correctly keeps reporting the applied one. Do not drop the\n // frame reads \"because Chromium does not re-choose\": when it does, it lags like Firefox.\n let frame = 0;\n let again = false;\n const cancelFrames = () => {\n if (frame !== 0) win.cancelAnimationFrame(frame);\n frame = 0;\n again = false;\n };\n const readLater = () => {\n if (frame !== 0) {\n again = true;\n return;\n }\n frame = win.requestAnimationFrame(() => {\n read(true);\n // The popup was found hidden (or `side` turned null): `listen(false)` ended the pair.\n if (!listening) return;\n frame = win.requestAnimationFrame(() => {\n frame = 0;\n read(true);\n if (again && listening) {\n again = false;\n readLater();\n }\n });\n });\n };\n\n const read = (urgent: boolean) => {\n if (requested.current.side === null) {\n listen(false);\n write(null, urgent);\n return;\n }\n if (element.isConnected && isPopoverOpen(element)) {\n listen(true);\n const style = getComputedStyle(element);\n const placement = parsePositionArea(\n style.positionArea,\n toDirection(style.direction),\n () => toDirection(getComputedStyle(doc.documentElement).direction),\n style.writingMode || \"horizontal-tb\",\n );\n write(placement, urgent);\n return;\n }\n listen(false);\n // Hidden, but still rendered while an exit animation runs: keep the resolved side to the\n // end of it. The ResizeObserver sees the box go and resets then.\n // Nothing written, nothing to reset: skip the forced layout (every mount and request change\n // of a hidden popup comes through here).\n if (\n written.current !== null &&\n (!element.isConnected || element.getClientRects().length === 0)\n ) {\n write(null, urgent);\n }\n };\n\n function onEvent() {\n read(true);\n }\n function onMove() {\n // In every Chromium 156 / Firefox 157 probe this read still saw the old option (see the\n // frame reads above); kept as cover for WebKit, which was not probed, at the cost of one\n // style read per scroll event.\n read(true);\n if (listening) readLater();\n }\n\n sync.current = read;\n const observer = typeof ResizeObserver === \"function\" ? new ResizeObserver(onEvent) : null;\n observer?.observe(element);\n element.addEventListener(\"toggle\", onEvent);\n return () => {\n observer?.disconnect();\n element.removeEventListener(\"toggle\", onEvent);\n listen(false);\n if (sync.current === read) sync.current = null;\n };\n }, []);\n\n // A changed request while shown places the popup differently: read again (a layout effect, so\n // the corrected attribute is in the same frame). Also how `side={null}` turns the hook off.\n useLayoutEffect(() => {\n requested.current = { side, align };\n sync.current?.(false);\n }, [side, align]);\n\n if (side === null) return { side: null, align, ref };\n return resolved === null ? { side, align, ref } : { ...resolved, ref };\n}\n\nexport interface AnchoredPlacementRequest<Side extends AnchorSide> extends PlacementRequest<Side> {\n /** `position-try-fallbacks`. Default: flip on both axes. */\n readonly fallbacks?: string;\n}\n\nexport interface AnchoredPlacement<Side extends AnchorSide> extends PlacementResult<Side> {\n /** `data-side` / `data-align` (resolved); no keys when the side is `null` (not owned then). */\n readonly dataAttributes: DataAttributes;\n /**\n * The popup's `style`: the requested inline placement (the browser keeps choosing from it)\n * under the consumer's style, so the consumer wins. The consumer's style alone for `side: null`.\n */\n readonly style: <State>(\n consumer: StateValue<CSSProperties | undefined, State>,\n ) => StateValue<CSSProperties | undefined, State>;\n}\n\n/**\n * An anchored popup's placement (Popover, Tooltip and Menu Popup): `useResolvedPlacement` plus\n * the data attributes and the inline `position-area` / `position-try-fallbacks` it renders.\n */\nexport function useAnchoredPlacement<Side extends AnchorSide>(\n request: AnchoredPlacementRequest<Side>,\n): AnchoredPlacement<Side> {\n const {\n side: requestedSide,\n align: requestedAlign,\n fallbacks = POSITION_TRY_FALLBACKS,\n } = request;\n const placement = useResolvedPlacement({ side: requestedSide, align: requestedAlign });\n const { side, align } = placement;\n const dataAttributes: DataAttributes =\n side !== null ? { \"data-side\": side, \"data-align\": align } : {};\n const style = <State>(\n consumer: StateValue<CSSProperties | undefined, State>,\n ): StateValue<CSSProperties | undefined, State> =>\n requestedSide === null\n ? consumer\n : (s: State) => ({\n positionArea: positionArea(requestedSide, requestedAlign),\n positionTryFallbacks: fallbacks,\n ...resolveStateValue(consumer, s),\n });\n return { ...placement, dataAttributes, style };\n}\n"],"mappings":";;;;;;;AAgCA,MAAM,eAAe,UAA8B,UAAU,QAAQ,QAAQ;;;;;;;;;;;AAY7E,SAAgB,qBACd,SACuB;CACvB,MAAM,EAAE,MAAM,UAAU;CACxB,MAAM,CAAC,UAAU,eAAe,SAAmC,IAAI;CAEvE,MAAM,UAAU,OAAiC,IAAI;CAErD,MAAM,YAAY,OAA+B,OAAO;CAExD,MAAM,OAAO,OAA2C,IAAI;CAE5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AAO;CAAe,CAAC;CACrF,MAAM,EAAE,MAAM,UAAU;CACxB,MAAM,iBACJ,SAAS,OAAO;EAAE,aAAa;EAAM,cAAc;CAAM,IAAI,CAAC;CAChE,MAAM,SACJ,aAEA,kBAAkB,OACd,YACC,OAAc;EACb,cAAc,aAAa,eAAe,cAAc;EACxD,sBAAsB;EACtB,GAAG,kBAAkB,UAAU,CAAC;CAClC;CACN,OAAO;EAAE,GAAG;EAAW;EAAgB;CAAM;AAC/C"}
1
+ {"version":3,"file":"use-resolved-placement.mjs","names":[],"sources":["../../src/internal/use-resolved-placement.ts"],"sourcesContent":["\"use client\";\nimport { useCallback, useLayoutEffect, useRef, useState } from \"react\";\nimport type { CSSProperties, RefCallback } from \"react\";\nimport { flushSync } from \"react-dom\";\nimport { parsePositionArea, POSITION_TRY_FALLBACKS, positionArea } from \"./anchor-position.js\";\nimport type {\n AnchorAlign,\n AnchorSide,\n Direction,\n PhysicalSide,\n ResolvedPlacement,\n} from \"./anchor-position.js\";\nimport { isPopoverOpen } from \"./popover-open.js\";\nimport { resolveStateValue } from \"./render-element.js\";\nimport type { DataAttributes } from \"./render-element.js\";\nimport type { StateValue } from \"./types.js\";\n\nexport interface PlacementRequest<Side extends AnchorSide> {\n /** The requested side; `null` when the stylesheet owns placement (the hook is idle). */\n readonly side: Side | null;\n readonly align: AnchorAlign;\n}\n\nexport interface PlacementResult<Side extends AnchorSide> {\n /** The resolved physical side while the popup is shown, else the requested side. */\n readonly side: Side | PhysicalSide | null;\n /** The resolved alignment while shown, else the requested one. */\n readonly align: AnchorAlign;\n /** Merge into the popup element's ref. Stable. */\n readonly ref: RefCallback<HTMLElement>;\n}\n\nconst toDirection = (value: string): Direction => (value === \"rtl\" ? \"rtl\" : \"ltr\");\n\n/**\n * Where the browser actually placed an anchored popup (design/conventions.md 13.2): the\n * `position-try-fallbacks` option it applied, read from the computed `position-area` while the\n * popup is shown. Observation only; runs whatever opened the popup (`interestfor`, `popovertarget` and\n * `commandfor` included). Read on a `ResizeObserver` (hidden to shown is a resize, delivered\n * before paint), `toggle`, and while shown document `scroll` and window `resize` plus the next\n * two frames. Written urgently (`flushSync`), and only when the rendered pair changes: an open\n * where it was asked costs no render. Hidden again, it resets once the popup no longer renders\n * (an exit animation keeps the resolved side). Idle with `side: null`.\n */\nexport function useResolvedPlacement<Side extends AnchorSide>(\n request: PlacementRequest<Side>,\n): PlacementResult<Side> {\n const { side, align } = request;\n const [resolved, setResolved] = useState<ResolvedPlacement | null>(null);\n // What the state holds (or is about to hold), so an unchanged read schedules nothing.\n const written = useRef<ResolvedPlacement | null>(null);\n // The request the element is rendered with (kept by the layout effect below).\n const requested = useRef<PlacementRequest<Side>>(request);\n // The mounted element's read, for the layout effect below.\n const sync = useRef<((urgent: boolean) => void) | null>(null);\n\n const ref = useCallback((element: HTMLElement | null) => {\n if (element === null) return;\n const doc = element.ownerDocument;\n const win = doc.defaultView ?? window;\n\n const write = (value: ResolvedPlacement | null, urgent: boolean) => {\n // Where it was asked to be: the requested values say so already, no state needed.\n const next =\n value !== null &&\n value.side === requested.current.side &&\n value.align === requested.current.align\n ? null\n : value;\n const previous = written.current;\n if (\n previous === next ||\n (previous !== null &&\n next !== null &&\n previous.side === next.side &&\n previous.align === next.align)\n ) {\n return;\n }\n written.current = next;\n if (urgent) flushSync(() => setResolved(next));\n else setResolved(next);\n };\n\n let listening = false;\n const listen = (on: boolean) => {\n if (on === listening) return;\n listening = on;\n if (on) {\n doc.addEventListener(\"scroll\", onMove, { capture: true, passive: true });\n win.addEventListener(\"resize\", onMove);\n } else {\n doc.removeEventListener(\"scroll\", onMove, { capture: true });\n win.removeEventListener(\"resize\", onMove);\n cancelFrames();\n }\n };\n\n // Both engines (Chromium 156, Firefox 157) apply the scroll-dependent anchoring state, the\n // option and the scroll-compensated geometry alike, in the layout of the frame after the\n // `scroll` event: a read in the handler, or in a rAF registered from it (which runs before\n // that layout), sees the old option even after a forced layout. The timing is unspecified\n // (css-anchor-position-1 §3.3 issue), so read again in the next two frames; a scroll that\n // arrives while that is pending restarts it at the end, so the last scroll is always followed.\n // Separately, Chromium 156 keeps an overflowing option for a top-layer popover once the first\n // frames after the show have passed (a bug, §6.5; upstream item #92): then no frame reads a\n // new option, and `data-side` correctly keeps reporting the applied one. Do not drop the\n // frame reads \"because Chromium does not re-choose\": when it does, it lags like Firefox.\n let frame = 0;\n let again = false;\n const cancelFrames = () => {\n if (frame !== 0) win.cancelAnimationFrame(frame);\n frame = 0;\n again = false;\n };\n const readLater = () => {\n if (frame !== 0) {\n again = true;\n return;\n }\n frame = win.requestAnimationFrame(() => {\n read(true);\n // The popup was found hidden (or `side` turned null): `listen(false)` ended the pair.\n if (!listening) return;\n frame = win.requestAnimationFrame(() => {\n frame = 0;\n read(true);\n if (again && listening) {\n again = false;\n readLater();\n }\n });\n });\n };\n\n const read = (urgent: boolean) => {\n if (requested.current.side === null) {\n listen(false);\n write(null, urgent);\n return;\n }\n if (element.isConnected && isPopoverOpen(element)) {\n listen(true);\n const style = getComputedStyle(element);\n const placement = parsePositionArea(\n style.positionArea,\n toDirection(style.direction),\n () => toDirection(getComputedStyle(doc.documentElement).direction),\n style.writingMode || \"horizontal-tb\",\n );\n write(placement, urgent);\n return;\n }\n listen(false);\n // Hidden, but still rendered while an exit animation runs: keep the resolved side to the\n // end of it. The ResizeObserver sees the box go and resets then.\n // Nothing written, nothing to reset: skip the forced layout (every mount and request change\n // of a hidden popup comes through here).\n if (\n written.current !== null &&\n (!element.isConnected || element.getClientRects().length === 0)\n ) {\n write(null, urgent);\n }\n };\n\n function onEvent() {\n read(true);\n }\n function onMove() {\n // In every Chromium 156 / Firefox 157 probe this read still saw the old option (see the\n // frame reads above); kept as cover for WebKit, which was not probed, at the cost of one\n // style read per scroll event.\n read(true);\n if (listening) readLater();\n }\n\n sync.current = read;\n const observer = typeof ResizeObserver === \"function\" ? new ResizeObserver(onEvent) : null;\n observer?.observe(element);\n element.addEventListener(\"toggle\", onEvent);\n return () => {\n observer?.disconnect();\n element.removeEventListener(\"toggle\", onEvent);\n listen(false);\n if (sync.current === read) sync.current = null;\n };\n }, []);\n\n // A changed request while shown places the popup differently: read again (a layout effect, so\n // the corrected attribute is in the same frame). Also how `side={null}` turns the hook off.\n useLayoutEffect(() => {\n requested.current = { side, align };\n sync.current?.(false);\n }, [side, align]);\n\n if (side === null) return { side: null, align, ref };\n return resolved === null ? { side, align, ref } : { ...resolved, ref };\n}\n\nexport interface AnchoredPlacementRequest<Side extends AnchorSide> extends PlacementRequest<Side> {\n /** `position-try-fallbacks`. Default: flip on both axes. */\n readonly fallbacks?: string;\n}\n\nexport interface AnchoredPlacement<Side extends AnchorSide> extends PlacementResult<Side> {\n /** `data-side` / `data-align` (resolved); no keys when the side is `null` (not owned then). */\n readonly dataAttributes: DataAttributes;\n /**\n * The popup's `style`: the requested inline placement (the browser keeps choosing from it)\n * under the consumer's style, so the consumer wins. The consumer's style alone for `side: null`.\n */\n readonly style: <State>(\n consumer: StateValue<CSSProperties | undefined, State>,\n ) => StateValue<CSSProperties | undefined, State>;\n}\n\n/**\n * An anchored popup's placement (Popover, Tooltip and Menu Popup): `useResolvedPlacement` plus\n * the data attributes and the inline `position-area` / `position-try-fallbacks` it renders.\n */\nexport function useAnchoredPlacement<Side extends AnchorSide>(\n request: AnchoredPlacementRequest<Side>,\n): AnchoredPlacement<Side> {\n const {\n side: requestedSide,\n align: requestedAlign,\n fallbacks = POSITION_TRY_FALLBACKS,\n } = request;\n const placement = useResolvedPlacement({ side: requestedSide, align: requestedAlign });\n const { side, align } = placement;\n const dataAttributes: DataAttributes =\n side !== null ? { \"data-side\": side, \"data-align\": align } : {};\n const style = <State>(\n consumer: StateValue<CSSProperties | undefined, State>,\n ): StateValue<CSSProperties | undefined, State> =>\n requestedSide === null\n ? consumer\n : (s: State) => ({\n positionArea: positionArea(requestedSide, requestedAlign),\n positionTryFallbacks: fallbacks,\n ...resolveStateValue(consumer, s),\n });\n return { ...placement, dataAttributes, style };\n}\n"],"mappings":";;;;;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