@funstack/ui 0.1.0-alpha.14 → 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 (88) 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 +1 -1
  17. package/dist/combobox/combobox-popup.d.mts.map +1 -1
  18. package/dist/combobox/combobox-popup.mjs +3 -15
  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 +10 -8
  24. package/dist/combobox/combobox-trigger.d.mts.map +1 -1
  25. package/dist/combobox/combobox-trigger.mjs +21 -17
  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 +2 -2
  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/announce.mjs +12 -7
  40. package/dist/internal/announce.mjs.map +1 -1
  41. package/dist/internal/focus-first-invalid.mjs +2 -11
  42. package/dist/internal/focus-first-invalid.mjs.map +1 -1
  43. package/dist/internal/focus-visible.mjs +26 -0
  44. package/dist/internal/focus-visible.mjs.map +1 -0
  45. package/dist/internal/{invoker-press.mjs → invokers.mjs} +22 -5
  46. package/dist/internal/invokers.mjs.map +1 -0
  47. package/dist/internal/platform-attributes.d.mts +1 -1
  48. package/dist/internal/pointer-capture.mjs +1 -1
  49. package/dist/internal/pointer-capture.mjs.map +1 -1
  50. package/dist/internal/trigger-ref.mjs +1 -1
  51. package/dist/internal/trigger-ref.mjs.map +1 -1
  52. package/dist/internal/use-interest-dismiss.mjs +84 -0
  53. package/dist/internal/use-interest-dismiss.mjs.map +1 -0
  54. package/dist/internal/use-overlay-root.mjs.map +1 -1
  55. package/dist/internal/use-popover-popup.mjs +43 -108
  56. package/dist/internal/use-popover-popup.mjs.map +1 -1
  57. package/dist/internal/use-popover-trigger.d.mts.map +1 -1
  58. package/dist/internal/use-popover-trigger.mjs +29 -10
  59. package/dist/internal/use-popover-trigger.mjs.map +1 -1
  60. package/dist/internal/use-value-set.mjs +20 -0
  61. package/dist/internal/use-value-set.mjs.map +1 -0
  62. package/dist/menu/menu-popup.d.mts +1 -1
  63. package/dist/menu/menu-popup.mjs +13 -27
  64. package/dist/menu/menu-popup.mjs.map +1 -1
  65. package/dist/menu/menu-submenu-trigger.d.mts +8 -8
  66. package/dist/menu/menu-submenu-trigger.mjs +9 -10
  67. package/dist/menu/menu-submenu-trigger.mjs.map +1 -1
  68. package/dist/menu/menu-trigger.d.mts +8 -7
  69. package/dist/menu/menu-trigger.d.mts.map +1 -1
  70. package/dist/menu/menu-trigger.mjs +6 -12
  71. package/dist/menu/menu-trigger.mjs.map +1 -1
  72. package/dist/number-field/number-field-root.mjs +1 -1
  73. package/dist/popover/popover-close.d.mts +3 -3
  74. package/dist/popover/popover-close.mjs +1 -1
  75. package/dist/popover/popover-close.mjs.map +1 -1
  76. package/dist/popover/popover-popup.mjs.map +1 -1
  77. package/dist/popover/popover-trigger.d.mts +9 -9
  78. package/dist/popover/popover-trigger.mjs +9 -9
  79. package/dist/popover/popover-trigger.mjs.map +1 -1
  80. package/dist/toast/toast-root.mjs.map +1 -1
  81. package/dist/toast/toast-viewport.d.mts.map +1 -1
  82. package/dist/toast/toast-viewport.mjs +4 -5
  83. package/dist/toast/toast-viewport.mjs.map +1 -1
  84. package/dist/toggle-group/toggle-group-root.d.mts.map +1 -1
  85. package/dist/toggle-group/toggle-group-root.mjs +4 -5
  86. package/dist/toggle-group/toggle-group-root.mjs.map +1 -1
  87. package/package.json +1 -1
  88. package/dist/internal/invoker-press.mjs.map +0 -1
@@ -1,4 +1,21 @@
1
- //#region src/internal/invoker-press.ts
1
+ //#region src/internal/invokers.ts
2
+ /**
3
+ * The `source` of a `ToggleEvent` (Chromium 140, Firefox 145, Safari 26.5), a `CommandEvent` or
4
+ * an `InterestEvent`: the invoker that caused it, `null` without one. Not in TypeScript's DOM lib
5
+ * for all three.
6
+ */
7
+ function eventSource(event) {
8
+ return event.source ?? null;
9
+ }
10
+ /**
11
+ * Whether the `ToggleEvent.source` of a close is a `popovertarget` invoker of `popup`. A
12
+ * `commandfor` or `interestfor` invoker sets `source` too (Chromium's lost-interest hide, a
13
+ * dismissal), and so names no `popovertarget` here.
14
+ */
15
+ function closedByPopoverTarget(event, popup) {
16
+ const source = eventSource(event);
17
+ return (source instanceof HTMLButtonElement || source instanceof HTMLInputElement) && source.popoverTargetElement === popup;
18
+ }
2
19
  /** The `<input>` types HTML counts as buttons: the ones `popovertarget` applies to. */
3
20
  const INPUT_BUTTON_TYPES = /* @__PURE__ */ new Set([
4
21
  "submit",
@@ -11,7 +28,7 @@ const INPUT_BUTTON_TYPES = /* @__PURE__ */ new Set([
11
28
  * `<button>`, or an `<input>` of a button type) is outside the popup and names it through
12
29
  * `popovertarget`, or (a `<button>`) through `commandfor` with a popover command
13
30
  * (`toggle-popover`, `show-popover`, `hide-popover`). HTML's invoker relationship, the one light
14
- * dismiss exempts (conventions 3.5, #126): a disabled button and a submit button with a form owner
31
+ * dismiss exempts (conventions 3.5): a disabled button and a submit button with a form owner
15
32
  * invoke nothing. Read through the IDL, so an engine without it has no such invoker.
16
33
  */
17
34
  function isPopoverInvoker(target, popup) {
@@ -28,7 +45,7 @@ function isPopoverInvoker(target, popup) {
28
45
  }
29
46
  /**
30
47
  * While a popup that closes on focus leaving is shown: a primary-button `mousedown` on a foreign
31
- * invoker of it moves no focus (conventions 3.5, #126). Chromium and Firefox focus a button on
48
+ * invoker of it moves no focus (conventions 3.5). Chromium and Firefox focus a button on
32
49
  * press, which would close the popup at the `focusout` before the click's own toggle (as
33
50
  * `"dismiss"`, and the toggle then re-showed it). Returns the cleanup.
34
51
  */
@@ -41,6 +58,6 @@ function listenInvokerPresses(popup) {
41
58
  return () => doc.removeEventListener("mousedown", onMouseDown, true);
42
59
  }
43
60
  //#endregion
44
- export { isPopoverInvoker, listenInvokerPresses };
61
+ export { closedByPopoverTarget, eventSource, isPopoverInvoker, listenInvokerPresses };
45
62
 
46
- //# sourceMappingURL=invoker-press.mjs.map
63
+ //# sourceMappingURL=invokers.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"invokers.mjs","names":[],"sources":["../../src/internal/invokers.ts"],"sourcesContent":["// No directive: DOM reads and listeners only (conventions 7.1). The platform's invoker\n// relationship between a button and a popover, as the overlays read it.\n\n/** An invoker button's IDL; absent where the engine lacks the Popover API or Invoker Commands. */\ninterface InvokerButton {\n readonly popoverTargetElement?: Element | null;\n readonly commandForElement?: Element | null;\n readonly command?: string;\n}\n\n/**\n * The `source` of a `ToggleEvent` (Chromium 140, Firefox 145, Safari 26.5), a `CommandEvent` or\n * an `InterestEvent`: the invoker that caused it, `null` without one. Not in TypeScript's DOM lib\n * for all three.\n */\nexport function eventSource(event: Event): Element | null {\n return (event as Event & { readonly source?: Element | null }).source ?? null;\n}\n\n/**\n * Whether the `ToggleEvent.source` of a close is a `popovertarget` invoker of `popup`. A\n * `commandfor` or `interestfor` invoker sets `source` too (Chromium's lost-interest hide, a\n * dismissal), and so names no `popovertarget` here.\n */\nexport function closedByPopoverTarget(event: ToggleEvent, popup: HTMLElement): boolean {\n const source = eventSource(event);\n return (\n (source instanceof HTMLButtonElement || source instanceof HTMLInputElement) &&\n source.popoverTargetElement === popup\n );\n}\n\n/** The `<input>` types HTML counts as buttons: the ones `popovertarget` applies to. */\nconst INPUT_BUTTON_TYPES = new Set([\"submit\", \"image\", \"reset\", \"button\"]);\n\n/**\n * Whether a press on `target` is a press on a foreign invoker of `popup`: its closest button (a\n * `<button>`, or an `<input>` of a button type) is outside the popup and names it through\n * `popovertarget`, or (a `<button>`) through `commandfor` with a popover command\n * (`toggle-popover`, `show-popover`, `hide-popover`). HTML's invoker relationship, the one light\n * dismiss exempts (conventions 3.5): a disabled button and a submit button with a form owner\n * invoke nothing. Read through the IDL, so an engine without it has no such invoker.\n */\nexport function isPopoverInvoker(target: EventTarget | null, popup: Element): boolean {\n if (!(target instanceof Element)) return false;\n const button = target.closest<HTMLButtonElement | HTMLInputElement>(\"button, input\");\n if (button === null || popup.contains(button)) return false;\n const isInput = button.tagName === \"INPUT\";\n if (isInput && !INPUT_BUTTON_TYPES.has(button.type)) return false;\n if (button.disabled) return false;\n if (button.form !== null && (button.type === \"submit\" || button.type === \"image\")) return false;\n const invoker = button as InvokerButton;\n if (invoker.popoverTargetElement === popup) return true;\n return !isInput && invoker.commandForElement === popup && /-popover$/.test(invoker.command ?? \"\");\n}\n\n/**\n * While a popup that closes on focus leaving is shown: a primary-button `mousedown` on a foreign\n * invoker of it moves no focus (conventions 3.5). Chromium and Firefox focus a button on\n * press, which would close the popup at the `focusout` before the click's own toggle (as\n * `\"dismiss\"`, and the toggle then re-showed it). Returns the cleanup.\n */\nexport function listenInvokerPresses(popup: HTMLElement): () => void {\n const doc = popup.ownerDocument;\n const onMouseDown = (event: MouseEvent) => {\n if (event.button === 0 && isPopoverInvoker(event.target, popup)) event.preventDefault();\n };\n doc.addEventListener(\"mousedown\", onMouseDown, true);\n return () => doc.removeEventListener(\"mousedown\", onMouseDown, true);\n}\n"],"mappings":";;;;;;AAeA,SAAgB,YAAY,OAA8B;CACxD,OAAQ,MAAuD,UAAU;AAC3E;;;;;;AAOA,SAAgB,sBAAsB,OAAoB,OAA6B;CACrF,MAAM,SAAS,YAAY,KAAK;CAChC,QACG,kBAAkB,qBAAqB,kBAAkB,qBAC1D,OAAO,yBAAyB;AAEpC;;AAGA,MAAM,qCAAqB,IAAI,IAAI;CAAC;CAAU;CAAS;CAAS;AAAQ,CAAC;;;;;;;;;AAUzE,SAAgB,iBAAiB,QAA4B,OAAyB;CACpF,IAAI,EAAE,kBAAkB,UAAU,OAAO;CACzC,MAAM,SAAS,OAAO,QAA8C,eAAe;CACnF,IAAI,WAAW,QAAQ,MAAM,SAAS,MAAM,GAAG,OAAO;CACtD,MAAM,UAAU,OAAO,YAAY;CACnC,IAAI,WAAW,CAAC,mBAAmB,IAAI,OAAO,IAAI,GAAG,OAAO;CAC5D,IAAI,OAAO,UAAU,OAAO;CAC5B,IAAI,OAAO,SAAS,SAAS,OAAO,SAAS,YAAY,OAAO,SAAS,UAAU,OAAO;CAC1F,MAAM,UAAU;CAChB,IAAI,QAAQ,yBAAyB,OAAO,OAAO;CACnD,OAAO,CAAC,WAAW,QAAQ,sBAAsB,SAAS,YAAY,KAAK,QAAQ,WAAW,EAAE;AAClG;;;;;;;AAQA,SAAgB,qBAAqB,OAAgC;CACnE,MAAM,MAAM,MAAM;CAClB,MAAM,eAAe,UAAsB;EACzC,IAAI,MAAM,WAAW,KAAK,iBAAiB,MAAM,QAAQ,KAAK,GAAG,MAAM,eAAe;CACxF;CACA,IAAI,iBAAiB,aAAa,aAAa,IAAI;CACnD,aAAa,IAAI,oBAAoB,aAAa,aAAa,IAAI;AACrE"}
@@ -25,7 +25,7 @@ declare module "react" {
25
25
  /**
26
26
  * `commandfor` (Invoker Commands): id of the element the button's `command` acts on.
27
27
  * Not in `@types/react` 19.3.0 (DefinitelyTyped #74664). Rendered by `Popover.Close`, the
28
- * Dialog parts and `Button`; the overlay Triggers use `popovertarget` (#121).
28
+ * Dialog parts and `Button`; the overlay Triggers use `popovertarget`.
29
29
  */
30
30
  commandfor?: string | undefined;
31
31
  /**
@@ -3,7 +3,7 @@
3
3
  * `setPointerCapture`, which throws `NotFoundError` for a pointer the engine no longer tracks
4
4
  * (context-menu.md 2.1). A silent no-op when no button is down. `true` when the capture was
5
5
  * taken (the Menu's press-drag-release gesture runs only then, 2.6). The Combobox Input uses it
6
- * to keep a press on the field from light-dismissing the listbox (combobox.md 5.4, #123).
6
+ * to keep a press on the field from light-dismissing the listbox (combobox.md 5.4).
7
7
  */
8
8
  function capturePointer(element, pointerId) {
9
9
  if (element === null || pointerId === void 0) return false;
@@ -1 +1 @@
1
- {"version":3,"file":"pointer-capture.mjs","names":[],"sources":["../../src/internal/pointer-capture.ts"],"sourcesContent":["// No directive: a pure DOM call (conventions 7.1).\n\n/**\n * `setPointerCapture`, which throws `NotFoundError` for a pointer the engine no longer tracks\n * (context-menu.md 2.1). A silent no-op when no button is down. `true` when the capture was\n * taken (the Menu's press-drag-release gesture runs only then, 2.6). The Combobox Input uses it\n * to keep a press on the field from light-dismissing the listbox (combobox.md 5.4, #123).\n */\nexport function capturePointer(element: Element | null, pointerId: number | undefined): boolean {\n if (element === null || pointerId === undefined) return false;\n try {\n element.setPointerCapture(pointerId);\n return true;\n } catch {\n // Not an active pointer (a synthetic event, a released button): nothing to capture.\n return false;\n }\n}\n"],"mappings":";;;;;;;AAQA,SAAgB,eAAe,SAAyB,WAAwC;CAC9F,IAAI,YAAY,QAAQ,cAAc,KAAA,GAAW,OAAO;CACxD,IAAI;EACF,QAAQ,kBAAkB,SAAS;EACnC,OAAO;CACT,QAAQ;EAEN,OAAO;CACT;AACF"}
1
+ {"version":3,"file":"pointer-capture.mjs","names":[],"sources":["../../src/internal/pointer-capture.ts"],"sourcesContent":["// No directive: a pure DOM call (conventions 7.1).\n\n/**\n * `setPointerCapture`, which throws `NotFoundError` for a pointer the engine no longer tracks\n * (context-menu.md 2.1). A silent no-op when no button is down. `true` when the capture was\n * taken (the Menu's press-drag-release gesture runs only then, 2.6). The Combobox Input uses it\n * to keep a press on the field from light-dismissing the listbox (combobox.md 5.4).\n */\nexport function capturePointer(element: Element | null, pointerId: number | undefined): boolean {\n if (element === null || pointerId === undefined) return false;\n try {\n element.setPointerCapture(pointerId);\n return true;\n } catch {\n // Not an active pointer (a synthetic event, a released button): nothing to capture.\n return false;\n }\n}\n"],"mappings":";;;;;;;AAQA,SAAgB,eAAe,SAAyB,WAAwC;CAC9F,IAAI,YAAY,QAAQ,cAAc,KAAA,GAAW,OAAO;CACxD,IAAI;EACF,QAAQ,kBAAkB,SAAS;EACnC,OAAO;CACT,QAAQ;EAEN,OAAO;CACT;AACF"}
@@ -5,7 +5,7 @@ const warned = /* @__PURE__ */ new WeakSet();
5
5
  /**
6
6
  * Registers `element` as the Root's one Trigger (`triggerRef`, last mounted wins) and returns
7
7
  * the ref cleanup. In development, a second Trigger mounting while another is registered
8
- * warns once per Root (#113 API3): only the registered one is the popup's `source` (anchor,
8
+ * warns once per Root (popover.md 14.2): only the registered one is the popup's `source` (anchor,
9
9
  * focus return) and, in JS-free mode, the one whose `data-open` is kept current.
10
10
  */
11
11
  function registerTrigger(triggerRef, element, part) {
@@ -1 +1 @@
1
- {"version":3,"file":"trigger-ref.mjs","names":[],"sources":["../../src/internal/trigger-ref.ts"],"sourcesContent":["import type { RefObject } from \"react\";\n\nconst isDev = process.env.NODE_ENV !== \"production\";\n\n/** The Roots that already warned about a second Trigger, keyed by their `triggerRef`. */\nconst warned = new WeakSet<RefObject<HTMLElement | null>>();\n\n/**\n * Registers `element` as the Root's one Trigger (`triggerRef`, last mounted wins) and returns\n * the ref cleanup. In development, a second Trigger mounting while another is registered\n * warns once per Root (#113 API3): only the registered one is the popup's `source` (anchor,\n * focus return) and, in JS-free mode, the one whose `data-open` is kept current.\n */\nexport function registerTrigger(\n triggerRef: RefObject<HTMLElement | null>,\n element: HTMLElement,\n part: string,\n): () => void {\n // A Trigger's own cleanup clears the ref first (a remount, StrictMode, a ref change), so a\n // registered element here is another, still mounted Trigger.\n if (isDev && triggerRef.current !== null) {\n if (!warned.has(triggerRef)) {\n warned.add(triggerRef);\n console.error(\n `${part}: a second ${part} mounted in the same Root. A Root supports one ${part}: ` +\n \"the popup only follows the last one mounted (its anchor, focus return and, \" +\n `without an action, data-open). Render one ${part} per Root.`,\n );\n }\n }\n triggerRef.current = element;\n return () => {\n if (triggerRef.current === element) triggerRef.current = null;\n };\n}\n"],"mappings":";AAEA,MAAM,QAAQ,QAAQ,IAAI,aAAa;;AAGvC,MAAM,yBAAS,IAAI,QAAuC;;;;;;;AAQ1D,SAAgB,gBACd,YACA,SACA,MACY;CAGZ,IAAI,SAAS,WAAW,YAAY,MAC9B;MAAA,CAAC,OAAO,IAAI,UAAU,GAAG;GAC3B,OAAO,IAAI,UAAU;GACrB,QAAQ,MACN,GAAG,KAAK,aAAa,KAAK,iDAAiD,KAAK,yHAEjC,KAAK,WACtD;EACF;;CAEF,WAAW,UAAU;CACrB,aAAa;EACX,IAAI,WAAW,YAAY,SAAS,WAAW,UAAU;CAC3D;AACF"}
1
+ {"version":3,"file":"trigger-ref.mjs","names":[],"sources":["../../src/internal/trigger-ref.ts"],"sourcesContent":["import type { RefObject } from \"react\";\n\nconst isDev = process.env.NODE_ENV !== \"production\";\n\n/** The Roots that already warned about a second Trigger, keyed by their `triggerRef`. */\nconst warned = new WeakSet<RefObject<HTMLElement | null>>();\n\n/**\n * Registers `element` as the Root's one Trigger (`triggerRef`, last mounted wins) and returns\n * the ref cleanup. In development, a second Trigger mounting while another is registered\n * warns once per Root (popover.md 14.2): only the registered one is the popup's `source` (anchor,\n * focus return) and, in JS-free mode, the one whose `data-open` is kept current.\n */\nexport function registerTrigger(\n triggerRef: RefObject<HTMLElement | null>,\n element: HTMLElement,\n part: string,\n): () => void {\n // A Trigger's own cleanup clears the ref first (a remount, StrictMode, a ref change), so a\n // registered element here is another, still mounted Trigger.\n if (isDev && triggerRef.current !== null) {\n if (!warned.has(triggerRef)) {\n warned.add(triggerRef);\n console.error(\n `${part}: a second ${part} mounted in the same Root. A Root supports one ${part}: ` +\n \"the popup only follows the last one mounted (its anchor, focus return and, \" +\n `without an action, data-open). Render one ${part} per Root.`,\n );\n }\n }\n triggerRef.current = element;\n return () => {\n if (triggerRef.current === element) triggerRef.current = null;\n };\n}\n"],"mappings":";AAEA,MAAM,QAAQ,QAAQ,IAAI,aAAa;;AAGvC,MAAM,yBAAS,IAAI,QAAuC;;;;;;;AAQ1D,SAAgB,gBACd,YACA,SACA,MACY;CAGZ,IAAI,SAAS,WAAW,YAAY,MAC9B;MAAA,CAAC,OAAO,IAAI,UAAU,GAAG;GAC3B,OAAO,IAAI,UAAU;GACrB,QAAQ,MACN,GAAG,KAAK,aAAa,KAAK,iDAAiD,KAAK,yHAEjC,KAAK,WACtD;EACF;;CAEF,WAAW,UAAU;CACrB,aAAa;EACX,IAAI,WAAW,YAAY,SAAS,WAAW,UAAU;CAC3D;AACF"}
@@ -0,0 +1,84 @@
1
+ "use client";
2
+ import { isPopoverOpen } from "./popover-open.mjs";
3
+ import { eventSource } from "./invokers.mjs";
4
+ import { useCallback, useRef } from "react";
5
+ //#region src/internal/use-interest-dismiss.ts
6
+ /**
7
+ * Lost interest of an `interestfor` button naming the popup (library mode; Chromium; popover.md
8
+ * lost-interest amendment), for `usePopoverPopup`. The platform hides only a popover its own
9
+ * interest show opened (`invokedVia == kInterest`), and the library cancels that show and
10
+ * re-shows with `showPopover({ source })`, so the platform never hides: the library does, as a
11
+ * dismissal. Chromium also fires `loseinterest` from inside every hide of the popup while the
12
+ * button has interest (Escape, script, the library's own close), before the state flips, and a
13
+ * `hidePopover()` called from there re-enters the hide and loses its `toggle`: the hide waits one
14
+ * task and runs only if the popup is still shown and still meant to be open, and returns no focus
15
+ * to the Trigger. A pending interest open is cancelled instead.
16
+ */
17
+ function useInterestDismiss(ctx) {
18
+ const isLibrary = ctx.mode === "library";
19
+ const { popupRef } = ctx;
20
+ const interestInvoker = useRef(null);
21
+ const interestOpen = useRef(false);
22
+ const interestHideTask = useRef(void 0);
23
+ const interestHide = useRef(false);
24
+ const onInterest = (event) => {
25
+ const element = popupRef.current;
26
+ if (!isLibrary || element === null || event.target !== element) return;
27
+ interestInvoker.current = eventSource(event);
28
+ };
29
+ const onLoseInterest = (event) => {
30
+ const element = popupRef.current;
31
+ if (!isLibrary || element === null || event.target !== element) return;
32
+ const source = eventSource(event);
33
+ if (source === null || source !== interestInvoker.current) return;
34
+ interestInvoker.current = null;
35
+ if (!interestOpen.current) return;
36
+ if (isPopoverOpen(element)) {
37
+ clearTimeout(interestHideTask.current);
38
+ interestHideTask.current = setTimeout(() => {
39
+ interestHideTask.current = void 0;
40
+ if (!isPopoverOpen(element) || !ctx.intended()) return;
41
+ if (interestInvoker.current !== null) return;
42
+ ctx.recordCloseIntent({
43
+ reason: "dismiss",
44
+ event
45
+ });
46
+ interestHide.current = true;
47
+ element.hidePopover();
48
+ }, 0);
49
+ } else if (ctx.intended()) {
50
+ interestOpen.current = false;
51
+ ctx.requestClose(event, "dismiss");
52
+ }
53
+ };
54
+ const noteOpen = (event) => {
55
+ const source = eventSource(event);
56
+ interestOpen.current = source !== null && source === interestInvoker.current;
57
+ };
58
+ const noteClosed = () => {
59
+ interestOpen.current = false;
60
+ };
61
+ const takeLostInterest = () => {
62
+ const lostInterest = interestHide.current;
63
+ interestHide.current = false;
64
+ return lostInterest;
65
+ };
66
+ return {
67
+ onInterest,
68
+ onLoseInterest,
69
+ noteOpen,
70
+ noteClosed,
71
+ takeLostInterest,
72
+ reset: useCallback(() => {
73
+ clearTimeout(interestHideTask.current);
74
+ interestHideTask.current = void 0;
75
+ interestHide.current = false;
76
+ interestInvoker.current = null;
77
+ interestOpen.current = false;
78
+ }, [])
79
+ };
80
+ }
81
+ //#endregion
82
+ export { useInterestDismiss };
83
+
84
+ //# sourceMappingURL=use-interest-dismiss.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-interest-dismiss.mjs","names":[],"sources":["../../src/internal/use-interest-dismiss.ts"],"sourcesContent":["\"use client\";\nimport { useCallback, useRef } from \"react\";\nimport { eventSource } from \"./invokers.js\";\nimport { isPopoverOpen } from \"./popover-open.js\";\nimport type { PopoverRootValue } from \"./use-overlay-root.js\";\n\nexport interface InterestDismiss {\n /** `interest` at the popup: remembers the button that has interest in it. */\n onInterest(event: Event): void;\n /** `loseinterest` at the popup: the lost-interest hide (see `useInterestDismiss`). */\n onLoseInterest(event: Event): void;\n /** The opening `beforetoggle` the Root routes: whether it is the interest invoker's open. */\n noteOpen(event: ToggleEvent): void;\n /** The popup's `toggle` reported it hidden: the interest open is over. */\n noteClosed(): void;\n /** Whether the hide whose `toggle` arrived was the lost-interest hide; clears it. */\n takeLostInterest(): boolean;\n /** The popup element detached: cancels a pending hide and forgets everything. Stable. */\n reset(): void;\n}\n\n/**\n * Lost interest of an `interestfor` button naming the popup (library mode; Chromium; popover.md\n * lost-interest amendment), for `usePopoverPopup`. The platform hides only a popover its own\n * interest show opened (`invokedVia == kInterest`), and the library cancels that show and\n * re-shows with `showPopover({ source })`, so the platform never hides: the library does, as a\n * dismissal. Chromium also fires `loseinterest` from inside every hide of the popup while the\n * button has interest (Escape, script, the library's own close), before the state flips, and a\n * `hidePopover()` called from there re-enters the hide and loses its `toggle`: the hide waits one\n * task and runs only if the popup is still shown and still meant to be open, and returns no focus\n * to the Trigger. A pending interest open is cancelled instead.\n */\nexport function useInterestDismiss(ctx: PopoverRootValue): InterestDismiss {\n const isLibrary = ctx.mode === \"library\";\n const { popupRef } = ctx;\n // The button that has interest in the popup (`InterestEvent.source`), whether the current open\n // was that button's interest open, the task that hides the popup on its lost interest, and\n // whether the hide in flight is that one.\n const interestInvoker = useRef<Element | null>(null);\n const interestOpen = useRef(false);\n const interestHideTask = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);\n const interestHide = useRef(false);\n\n const onInterest = (event: Event): void => {\n const element = popupRef.current;\n if (!isLibrary || element === null || event.target !== element) return;\n interestInvoker.current = eventSource(event);\n };\n\n const onLoseInterest = (event: Event): void => {\n const element = popupRef.current;\n if (!isLibrary || element === null || event.target !== element) return;\n const source = eventSource(event);\n if (source === null || source !== interestInvoker.current) return;\n interestInvoker.current = null;\n if (!interestOpen.current) return;\n if (isPopoverOpen(element)) {\n clearTimeout(interestHideTask.current);\n interestHideTask.current = setTimeout(() => {\n interestHideTask.current = undefined;\n if (!isPopoverOpen(element) || !ctx.intended()) return;\n // Interest regained meanwhile (the pointer came back): the popup stays.\n if (interestInvoker.current !== null) return;\n // Recorded right before the hide, so its one-task clear cannot run first.\n ctx.recordCloseIntent({ reason: \"dismiss\", event });\n interestHide.current = true;\n element.hidePopover();\n }, 0);\n } else if (ctx.intended()) {\n interestOpen.current = false;\n ctx.requestClose(event, \"dismiss\");\n }\n };\n\n const noteOpen = (event: ToggleEvent): void => {\n // Chromium dispatches `interest` and then the interest show in one step, so a show whose\n // `source` is the remembered interest invoker is that button's interest open.\n const source = eventSource(event);\n interestOpen.current = source !== null && source === interestInvoker.current;\n };\n\n const noteClosed = (): void => {\n interestOpen.current = false;\n };\n\n const takeLostInterest = (): boolean => {\n const lostInterest = interestHide.current;\n interestHide.current = false;\n return lostInterest;\n };\n\n const reset = useCallback((): void => {\n clearTimeout(interestHideTask.current);\n interestHideTask.current = undefined;\n interestHide.current = false;\n interestInvoker.current = null;\n interestOpen.current = false;\n }, []);\n\n return { onInterest, onLoseInterest, noteOpen, noteClosed, takeLostInterest, reset };\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAgCA,SAAgB,mBAAmB,KAAwC;CACzE,MAAM,YAAY,IAAI,SAAS;CAC/B,MAAM,EAAE,aAAa;CAIrB,MAAM,kBAAkB,OAAuB,IAAI;CACnD,MAAM,eAAe,OAAO,KAAK;CACjC,MAAM,mBAAmB,OAAkD,KAAA,CAAS;CACpF,MAAM,eAAe,OAAO,KAAK;CAEjC,MAAM,cAAc,UAAuB;EACzC,MAAM,UAAU,SAAS;EACzB,IAAI,CAAC,aAAa,YAAY,QAAQ,MAAM,WAAW,SAAS;EAChE,gBAAgB,UAAU,YAAY,KAAK;CAC7C;CAEA,MAAM,kBAAkB,UAAuB;EAC7C,MAAM,UAAU,SAAS;EACzB,IAAI,CAAC,aAAa,YAAY,QAAQ,MAAM,WAAW,SAAS;EAChE,MAAM,SAAS,YAAY,KAAK;EAChC,IAAI,WAAW,QAAQ,WAAW,gBAAgB,SAAS;EAC3D,gBAAgB,UAAU;EAC1B,IAAI,CAAC,aAAa,SAAS;EAC3B,IAAI,cAAc,OAAO,GAAG;GAC1B,aAAa,iBAAiB,OAAO;GACrC,iBAAiB,UAAU,iBAAiB;IAC1C,iBAAiB,UAAU,KAAA;IAC3B,IAAI,CAAC,cAAc,OAAO,KAAK,CAAC,IAAI,SAAS,GAAG;IAEhD,IAAI,gBAAgB,YAAY,MAAM;IAEtC,IAAI,kBAAkB;KAAE,QAAQ;KAAW;IAAM,CAAC;IAClD,aAAa,UAAU;IACvB,QAAQ,YAAY;GACtB,GAAG,CAAC;EACN,OAAO,IAAI,IAAI,SAAS,GAAG;GACzB,aAAa,UAAU;GACvB,IAAI,aAAa,OAAO,SAAS;EACnC;CACF;CAEA,MAAM,YAAY,UAA6B;EAG7C,MAAM,SAAS,YAAY,KAAK;EAChC,aAAa,UAAU,WAAW,QAAQ,WAAW,gBAAgB;CACvE;CAEA,MAAM,mBAAyB;EAC7B,aAAa,UAAU;CACzB;CAEA,MAAM,yBAAkC;EACtC,MAAM,eAAe,aAAa;EAClC,aAAa,UAAU;EACvB,OAAO;CACT;CAUA,OAAO;EAAE;EAAY;EAAgB;EAAU;EAAY;EAAkB,OAR/D,kBAAwB;GACpC,aAAa,iBAAiB,OAAO;GACrC,iBAAiB,UAAU,KAAA;GAC3B,aAAa,UAAU;GACvB,gBAAgB,UAAU;GAC1B,aAAa,UAAU;EACzB,GAAG,CAAC,CAE6E;CAAE;AACrF"}
@@ -1 +1 @@
1
- {"version":3,"file":"use-overlay-root.mjs","names":[],"sources":["../../src/internal/use-overlay-root.ts"],"sourcesContent":["\"use client\";\nimport { useCallback, useId, useMemo, useRef, useState } from \"react\";\nimport type { RefObject } from \"react\";\nimport { createActionDetails } from \"./action-details.js\";\nimport { isPopoverOpen } from \"./popover-open.js\";\nimport { transitionTypes } from \"./transition-types.js\";\nimport type { ActionDetails, ChangeAction, ChangeReason } from \"./types.js\";\nimport { useControllableAction } from \"./use-controllable-action.js\";\nimport { useDevWarning } from \"./use-dev-warning.js\";\nimport { useLatest } from \"./use-latest.js\";\n\nconst isDev = process.env.NODE_ENV !== \"production\";\n\n/**\n * \"static\": JS-free mode, the browser owns open and close through Invoker Commands. \"library\":\n * opening and part-initiated closing are library-owned (transitions keyed on committed state);\n * dismissals are the browser's and notified (design/components/popover.md section 2).\n */\nexport type OverlayMode = \"static\" | \"library\";\n\n/**\n * What caused the next close, recorded just before it happens (design 2.3). The `toggle` event\n * names no cause beyond its invoker (`ToggleEvent.source`: a `popovertarget`, `commandfor` or\n * `interestfor` button, #125); without an intent a close is a `\"dismiss\"`.\n */\nexport interface OverlayCloseIntent {\n readonly reason: ChangeReason;\n readonly event: Event | undefined;\n}\n\n/** The `details` every overlay `openChangeAction` receives (Dialog's adds `returnValue`). */\nexport interface OverlayDetails extends ActionDetails {\n readonly reason: ChangeReason;\n}\n\n/**\n * The Root's state and machinery, shared by Popover, Menu, Combobox (design 14) and Dialog. The\n * component puts it in its own context; `usePopoverTrigger` and `usePopoverPopup` take it as their\n * first argument. `Popup` is the popup element's type; `CloseArgs` are the extra arguments of a\n * close (Dialog's `returnValue`), passed on to the `details` builder.\n */\nexport interface OverlayRootValue<Popup extends HTMLElement, CloseArgs extends unknown[]> {\n readonly mode: OverlayMode;\n /** `useId`-based ids: the popup, its Title and its Description. */\n readonly ids: { readonly popup: string; readonly title: string; readonly description: string };\n /** Committed open state (library mode); `false` in JS-free mode. */\n readonly committed: boolean;\n /** Optimistic open state (library mode); `false` in JS-free mode. */\n readonly optimistic: boolean;\n /**\n * The popup is in the top layer, mirrored from its `toggle` (urgent, conventions 3.5): what\n * `aria-expanded` renders on a non-button Trigger and the Combobox Input (#118; a `<button>`\n * Trigger renders none, #121). Written by a popover Popup in library mode; Dialog does not\n * maintain it.\n */\n readonly shown: boolean;\n /** Writes `shown` from the DOM (`:popover-open`); the Popup's `toggle`, ref attach and detach. */\n readonly setShown: (shown: boolean) => void;\n /** The Root's transition is pending (library mode). */\n readonly pending: boolean;\n /**\n * What the user already intends: the latest in-flight dispatch's `next`, else the optimistic\n * value of the last commit. Safe to call from handlers and effects (layout effects included,\n * also in the commit that changed it), and after an `await`. Not during render.\n */\n readonly intended: () => boolean;\n /**\n * A counter that grows with every open (a requested open, or the popup being shown). A part\n * whose close runs after an `await` records it first and drops the close when it changed: the\n * user dismissed and re-opened meanwhile (Popover.Close, design 3.4). Handlers only.\n */\n readonly openGeneration: () => number;\n /** Advance `openGeneration` (the Popup's `beforetoggle` for an open). */\n readonly nextOpenGeneration: () => void;\n /**\n * Open through the Root's transition (library mode): a Trigger click, a foreign open caught at\n * `beforetoggle`, or mount reconciliation. A no-op when `true` is already intended.\n */\n readonly requestOpen: (event: Event | undefined, reason: ChangeReason) => void;\n /**\n * A library-owned close (library mode): a Trigger click while open, a Close part, Menu's item\n * activation. `openChangeAction(false)` is awaited and the popup hides in the commit. A no-op\n * when `false` is already intended.\n */\n readonly requestClose: (\n event: Event | undefined,\n reason: ChangeReason,\n ...args: CloseArgs\n ) => void;\n /**\n * The browser hid the popup (a dismissal or a foreign invoker): dispatch the `false`\n * notification unless `false` is already intended (the library's own echo, or a dismissal\n * during a pending part-initiated close).\n */\n readonly notifyClosed: (\n event: Event | undefined,\n reason: ChangeReason,\n ...args: CloseArgs\n ) => void;\n /** From `useControllableAction`: the latest in-flight intent, or `null`. */\n readonly latestInFlight: () => { readonly next: boolean } | null;\n /** The registered Trigger: `showPopover({ source })` and the focus-return fallback. */\n readonly triggerRef: RefObject<HTMLElement | null>;\n /** The popup element, set by the Popup's ref; how Close reaches `hidePopover()` / `close()`. */\n readonly popupRef: RefObject<Popup | null>;\n /**\n * Record what causes the next close. Cleared after a task if the popover did not close.\n * `unlessRecorded`: keep an intent already recorded for this close (the `command` listener runs\n * before the `beforetoggle` of the same click, #125).\n */\n readonly recordCloseIntent: (\n intent: OverlayCloseIntent | undefined,\n options?: { readonly unlessRecorded?: boolean },\n ) => void;\n /** Read and clear the recorded intent (the Popup's `toggle` listener). */\n readonly takeCloseIntent: () => OverlayCloseIntent | undefined;\n}\n\n/** The root value of the popover-like components (Popover, Menu, Combobox). */\nexport type PopoverRootValue = OverlayRootValue<HTMLElement, []>;\n\nexport interface UseOverlayRootOptions<\n Details extends ActionDetails,\n Popup extends HTMLElement = HTMLElement,\n CloseArgs extends unknown[] = [],\n> {\n /** Transition types and messages: `\"popover\"` gives `fsui-popover`, `fsui-popover-open`, … */\n readonly component: string;\n /** Public name of the Root part for development warnings (`\"Popover.Root\"`). */\n readonly part: string;\n readonly open: boolean | undefined;\n readonly defaultOpen: boolean | undefined;\n readonly openChangeAction: ChangeAction<boolean, Details> | undefined;\n /**\n * `\"library\"` forces library mode whatever the props (Menu, which has no JS-free mode). Default:\n * detected from `open` / `defaultOpen` / `openChangeAction` on the first render.\n */\n readonly mode?: \"library\";\n /**\n * Called synchronously for every dispatch, before the action runs (Menu: cancel hover timers,\n * read the open cause).\n */\n readonly onDispatch?: (next: boolean, details: Details) => void;\n /** Builds the `details` of a dispatch (`popoverDetails`: `{ reason }`); an open passes no args. */\n readonly details: (\n event: Event | undefined,\n reason: ChangeReason,\n ...args: CloseArgs | []\n ) => Details;\n /** Whether the popup is shown, for a stale close intent. Default: `:popover-open`. */\n readonly isShown?: (popup: Popup) => boolean;\n}\n\n/** How long a recorded close intent survives when the popup did not close (design 2.3). */\nfunction clearLater<Popup extends HTMLElement>(\n intentRef: { current: OverlayCloseIntent | undefined },\n intent: OverlayCloseIntent,\n popupRef: { current: Popup | null },\n isShown: (popup: Popup) => boolean,\n): void {\n setTimeout(() => {\n // Closed: its `toggle` / `close` event (queued as a task) consumes the intent. Still open: the\n // close was cancelled or invalid, so the intent is stale.\n const popup = popupRef.current;\n if (intentRef.current === intent && popup !== null && isShown(popup)) {\n intentRef.current = undefined;\n }\n }, 0);\n}\n\n/** The `details` of a popover-like component: `{ reason }` (and `event`). */\nexport const popoverDetails = (event: Event | undefined, reason: ChangeReason): OverlayDetails =>\n createActionDetails(event, { reason });\n\n/**\n * The Root of an overlay without its public props: mode detection (once, from the first\n * render), `useControllableAction<boolean>`, ids, refs, close intents, the open generation and\n * the intent-aware `requestOpen` / `requestClose` / `notifyClosed`.\n */\nexport function useOverlayRoot<\n Details extends ActionDetails,\n Popup extends HTMLElement = HTMLElement,\n CloseArgs extends unknown[] = [],\n>(options: UseOverlayRootOptions<Details, Popup, CloseArgs>): OverlayRootValue<Popup, CloseArgs> {\n const { component, part, open, defaultOpen, openChangeAction, details, onDispatch } = options;\n\n // Mode is decided once, from the first render's props (design 2).\n const isLibraryNow =\n options.mode === \"library\" ||\n open !== undefined ||\n defaultOpen !== undefined ||\n openChangeAction !== undefined;\n const [mode] = useState<OverlayMode>(isLibraryNow ? \"library\" : \"static\");\n const isLibrary = mode === \"library\";\n useDevWarning(\n isLibrary !== isLibraryNow,\n isDev &&\n `${part}: the mode changed after mount (\\`open\\`, \\`defaultOpen\\` and \\`openChangeAction\\` ` +\n \"were all absent on one render and present on another). Switching between JS-free and \" +\n \"library mode is not supported.\",\n );\n\n // Hooks cannot be conditional: JS-free mode calls the hook too and never dispatches.\n const { committed, optimistic, pending, dispatch, latestInFlight } = useControllableAction<\n boolean,\n Details\n >({\n controlled: isLibrary ? open : undefined,\n defaultValue: isLibrary ? defaultOpen : undefined,\n initialValue: false,\n action: isLibrary ? openChangeAction : undefined,\n transitionTypes: (next) => transitionTypes(component, next ? \"open\" : \"close\"),\n warn: { component: part, prop: \"open\" },\n });\n\n const id = useId();\n const triggerRef = useRef<HTMLElement | null>(null);\n const popupRef = useRef<Popup | null>(null);\n const closeIntent = useRef<OverlayCloseIntent | undefined>(undefined);\n\n // The optimistic value of the last commit, for callers that run after an `await` (a Close\n // action's continuation) and would otherwise read the value of the render they were created in.\n // An insertion effect runs in the mutation phase, before any layout effect of the same commit\n // (a child's included), so `intended()` is current there too.\n const committedOptimistic = useLatest(optimistic);\n // `details`, `onDispatch` and `isShown` are usually inline functions: read the committed render's\n // through a ref so that the functions below, and with them the returned value, stay stable.\n const callbacks = useLatest({ details, onDispatch, isShown: options.isShown });\n const generation = useRef(0);\n const openGeneration = useCallback(() => generation.current, []);\n const nextOpenGeneration = useCallback(() => {\n generation.current++;\n }, []);\n\n const recordCloseIntent = useCallback(\n (intent: OverlayCloseIntent | undefined, options?: { readonly unlessRecorded?: boolean }) => {\n if (options?.unlessRecorded === true && closeIntent.current !== undefined) return;\n closeIntent.current = intent;\n if (intent !== undefined) {\n clearLater(closeIntent, intent, popupRef, callbacks.current.isShown ?? isPopoverOpen);\n }\n },\n [callbacks],\n );\n const takeCloseIntent = useCallback(() => {\n const intent = closeIntent.current;\n closeIntent.current = undefined;\n return intent;\n }, []);\n\n // Conventions 3.8 rule 1: judge no-ops against what the user already intends. That also\n // deduplicates the StrictMode re-run of the mount reconciliation and recognises the library's\n // own `hidePopover()` echoing back through `toggle`.\n const intended = useCallback(\n (): boolean => latestInFlight()?.next ?? committedOptimistic.current,\n [latestInFlight, committedOptimistic],\n );\n\n const send = useCallback(\n (next: boolean, event: Event | undefined, reason: ChangeReason, args: CloseArgs | []): void => {\n const { details, onDispatch } = callbacks.current;\n const built = details(event, reason, ...args);\n if (next) nextOpenGeneration();\n onDispatch?.(next, built);\n dispatch(next, built);\n },\n [callbacks, nextOpenGeneration, dispatch],\n );\n\n const requestOpen = useCallback(\n (event: Event | undefined, reason: ChangeReason): void => {\n if (!isLibrary || intended()) return;\n send(true, event, reason, []);\n },\n [isLibrary, intended, send],\n );\n\n const requestClose = useCallback(\n (event: Event | undefined, reason: ChangeReason, ...args: CloseArgs): void => {\n if (!isLibrary || !intended()) return;\n send(false, event, reason, args);\n },\n [isLibrary, intended, send],\n );\n\n const [shown, setShown] = useState(false);\n\n const ids = useMemo(\n () => ({ popup: id, title: `${id}-title`, description: `${id}-description` }),\n [id],\n );\n\n // Memoised: every function above is stable, so the value changes only with the open state and\n // pending, and the components' context values built on it are reused otherwise.\n return useMemo(\n () => ({\n mode,\n ids,\n committed: isLibrary && committed,\n optimistic: isLibrary && optimistic,\n shown,\n setShown,\n pending: isLibrary && pending,\n intended,\n openGeneration,\n nextOpenGeneration,\n requestOpen,\n requestClose,\n // The same function as `requestClose`; a separate name because the callers mean different\n // things (a part asks to close; the platform already closed).\n notifyClosed: requestClose,\n latestInFlight,\n triggerRef,\n popupRef,\n recordCloseIntent,\n takeCloseIntent,\n }),\n [\n mode,\n ids,\n isLibrary,\n committed,\n optimistic,\n shown,\n pending,\n intended,\n openGeneration,\n nextOpenGeneration,\n requestOpen,\n requestClose,\n latestInFlight,\n recordCloseIntent,\n takeCloseIntent,\n ],\n );\n}\n"],"mappings":";;;;;;;;;AAWA,MAAM,QAAQ,QAAQ,IAAI,aAAa;;AA+IvC,SAAS,WACP,WACA,QACA,UACA,SACM;CACN,iBAAiB;EAGf,MAAM,QAAQ,SAAS;EACvB,IAAI,UAAU,YAAY,UAAU,UAAU,QAAQ,QAAQ,KAAK,GACjE,UAAU,UAAU,KAAA;CAExB,GAAG,CAAC;AACN;;AAGA,MAAa,kBAAkB,OAA0B,WACvD,oBAAoB,OAAO,EAAE,OAAO,CAAC;;;;;;AAOvC,SAAgB,eAId,SAA+F;CAC/F,MAAM,EAAE,WAAW,MAAM,MAAM,aAAa,kBAAkB,SAAS,eAAe;CAGtF,MAAM,eACJ,QAAQ,SAAS,aACjB,SAAS,KAAA,KACT,gBAAgB,KAAA,KAChB,qBAAqB,KAAA;CACvB,MAAM,CAAC,QAAQ,SAAsB,eAAe,YAAY,QAAQ;CACxE,MAAM,YAAY,SAAS;CAC3B,cACE,cAAc,cACd,SACE,GAAG,KAAK,uMAGZ;CAGA,MAAM,EAAE,WAAW,YAAY,SAAS,UAAU,mBAAmB,sBAGnE;EACA,YAAY,YAAY,OAAO,KAAA;EAC/B,cAAc,YAAY,cAAc,KAAA;EACxC,cAAc;EACd,QAAQ,YAAY,mBAAmB,KAAA;EACvC,kBAAkB,SAAS,gBAAgB,WAAW,OAAO,SAAS,OAAO;EAC7E,MAAM;GAAE,WAAW;GAAM,MAAM;EAAO;CACxC,CAAC;CAED,MAAM,KAAK,MAAM;CACjB,MAAM,aAAa,OAA2B,IAAI;CAClD,MAAM,WAAW,OAAqB,IAAI;CAC1C,MAAM,cAAc,OAAuC,KAAA,CAAS;CAMpE,MAAM,sBAAsB,UAAU,UAAU;CAGhD,MAAM,YAAY,UAAU;EAAE;EAAS;EAAY,SAAS,QAAQ;CAAQ,CAAC;CAC7E,MAAM,aAAa,OAAO,CAAC;CAC3B,MAAM,iBAAiB,kBAAkB,WAAW,SAAS,CAAC,CAAC;CAC/D,MAAM,qBAAqB,kBAAkB;EAC3C,WAAW;CACb,GAAG,CAAC,CAAC;CAEL,MAAM,oBAAoB,aACvB,QAAwC,YAAoD;EAC3F,IAAI,SAAS,mBAAmB,QAAQ,YAAY,YAAY,KAAA,GAAW;EAC3E,YAAY,UAAU;EACtB,IAAI,WAAW,KAAA,GACb,WAAW,aAAa,QAAQ,UAAU,UAAU,QAAQ,WAAW,aAAa;CAExF,GACA,CAAC,SAAS,CACZ;CACA,MAAM,kBAAkB,kBAAkB;EACxC,MAAM,SAAS,YAAY;EAC3B,YAAY,UAAU,KAAA;EACtB,OAAO;CACT,GAAG,CAAC,CAAC;CAKL,MAAM,WAAW,kBACA,eAAe,CAAC,EAAE,QAAQ,oBAAoB,SAC7D,CAAC,gBAAgB,mBAAmB,CACtC;CAEA,MAAM,OAAO,aACV,MAAe,OAA0B,QAAsB,SAA+B;EAC7F,MAAM,EAAE,SAAS,eAAe,UAAU;EAC1C,MAAM,QAAQ,QAAQ,OAAO,QAAQ,GAAG,IAAI;EAC5C,IAAI,MAAM,mBAAmB;EAC7B,aAAa,MAAM,KAAK;EACxB,SAAS,MAAM,KAAK;CACtB,GACA;EAAC;EAAW;EAAoB;CAAQ,CAC1C;CAEA,MAAM,cAAc,aACjB,OAA0B,WAA+B;EACxD,IAAI,CAAC,aAAa,SAAS,GAAG;EAC9B,KAAK,MAAM,OAAO,QAAQ,CAAC,CAAC;CAC9B,GACA;EAAC;EAAW;EAAU;CAAI,CAC5B;CAEA,MAAM,eAAe,aAClB,OAA0B,QAAsB,GAAG,SAA0B;EAC5E,IAAI,CAAC,aAAa,CAAC,SAAS,GAAG;EAC/B,KAAK,OAAO,OAAO,QAAQ,IAAI;CACjC,GACA;EAAC;EAAW;EAAU;CAAI,CAC5B;CAEA,MAAM,CAAC,OAAO,YAAY,SAAS,KAAK;CAExC,MAAM,MAAM,eACH;EAAE,OAAO;EAAI,OAAO,GAAG,GAAG;EAAS,aAAa,GAAG,GAAG;CAAc,IAC3E,CAAC,EAAE,CACL;CAIA,OAAO,eACE;EACL;EACA;EACA,WAAW,aAAa;EACxB,YAAY,aAAa;EACzB;EACA;EACA,SAAS,aAAa;EACtB;EACA;EACA;EACA;EACA;EAGA,cAAc;EACd;EACA;EACA;EACA;EACA;CACF,IACA;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CACF;AACF"}
1
+ {"version":3,"file":"use-overlay-root.mjs","names":[],"sources":["../../src/internal/use-overlay-root.ts"],"sourcesContent":["\"use client\";\nimport { useCallback, useId, useMemo, useRef, useState } from \"react\";\nimport type { RefObject } from \"react\";\nimport { createActionDetails } from \"./action-details.js\";\nimport { isPopoverOpen } from \"./popover-open.js\";\nimport { transitionTypes } from \"./transition-types.js\";\nimport type { ActionDetails, ChangeAction, ChangeReason } from \"./types.js\";\nimport { useControllableAction } from \"./use-controllable-action.js\";\nimport { useDevWarning } from \"./use-dev-warning.js\";\nimport { useLatest } from \"./use-latest.js\";\n\nconst isDev = process.env.NODE_ENV !== \"production\";\n\n/**\n * \"static\": JS-free mode, the browser owns open and close through Invoker Commands. \"library\":\n * opening and part-initiated closing are library-owned (transitions keyed on committed state);\n * dismissals are the browser's and notified (design/components/popover.md section 2).\n */\nexport type OverlayMode = \"static\" | \"library\";\n\n/**\n * What caused the next close, recorded just before it happens (design 2.3). The `toggle` event\n * names no cause beyond its invoker (`ToggleEvent.source`: a `popovertarget`, `commandfor` or\n * `interestfor` button); without an intent a close is a `\"dismiss\"`.\n */\nexport interface OverlayCloseIntent {\n readonly reason: ChangeReason;\n readonly event: Event | undefined;\n}\n\n/** The `details` every overlay `openChangeAction` receives (Dialog's adds `returnValue`). */\nexport interface OverlayDetails extends ActionDetails {\n readonly reason: ChangeReason;\n}\n\n/**\n * The Root's state and machinery, shared by Popover, Menu, Combobox (design 14) and Dialog. The\n * component puts it in its own context; `usePopoverTrigger` and `usePopoverPopup` take it as their\n * first argument. `Popup` is the popup element's type; `CloseArgs` are the extra arguments of a\n * close (Dialog's `returnValue`), passed on to the `details` builder.\n */\nexport interface OverlayRootValue<Popup extends HTMLElement, CloseArgs extends unknown[]> {\n readonly mode: OverlayMode;\n /** `useId`-based ids: the popup, its Title and its Description. */\n readonly ids: { readonly popup: string; readonly title: string; readonly description: string };\n /** Committed open state (library mode); `false` in JS-free mode. */\n readonly committed: boolean;\n /** Optimistic open state (library mode); `false` in JS-free mode. */\n readonly optimistic: boolean;\n /**\n * The popup is in the top layer, mirrored from its `toggle` (urgent, conventions 3.5): what\n * `aria-expanded` renders on a non-button Trigger and the Combobox Input (a `<button>`\n * Trigger renders none). Written by a popover Popup in library mode; Dialog does not\n * maintain it, and its context omits it.\n */\n readonly shown: boolean;\n /** Writes `shown` from the DOM (`:popover-open`); the Popup's `toggle`, ref attach and detach. */\n readonly setShown: (shown: boolean) => void;\n /** The Root's transition is pending (library mode). */\n readonly pending: boolean;\n /**\n * What the user already intends: the latest in-flight dispatch's `next`, else the optimistic\n * value of the last commit. Safe to call from handlers and effects (layout effects included,\n * also in the commit that changed it), and after an `await`. Not during render.\n */\n readonly intended: () => boolean;\n /**\n * A counter that grows with every open (a requested open, or the popup being shown). A part\n * whose close runs after an `await` records it first and drops the close when it changed: the\n * user dismissed and re-opened meanwhile (Popover.Close, design 3.4). Handlers only.\n */\n readonly openGeneration: () => number;\n /** Advance `openGeneration` (the Popup's `beforetoggle` for an open). */\n readonly nextOpenGeneration: () => void;\n /**\n * Open through the Root's transition (library mode): a Trigger click, a foreign open caught at\n * `beforetoggle`, or mount reconciliation. A no-op when `true` is already intended.\n */\n readonly requestOpen: (event: Event | undefined, reason: ChangeReason) => void;\n /**\n * A library-owned close (library mode): a Trigger click while open, a Close part, Menu's item\n * activation. `openChangeAction(false)` is awaited and the popup hides in the commit. A no-op\n * when `false` is already intended.\n */\n readonly requestClose: (\n event: Event | undefined,\n reason: ChangeReason,\n ...args: CloseArgs\n ) => void;\n /**\n * The browser hid the popup (a dismissal or a foreign invoker): dispatch the `false`\n * notification unless `false` is already intended (the library's own echo, or a dismissal\n * during a pending part-initiated close).\n */\n readonly notifyClosed: (\n event: Event | undefined,\n reason: ChangeReason,\n ...args: CloseArgs\n ) => void;\n /** From `useControllableAction`: the latest in-flight intent, or `null`. */\n readonly latestInFlight: () => { readonly next: boolean } | null;\n /** The registered Trigger: `showPopover({ source })` and the focus-return fallback. */\n readonly triggerRef: RefObject<HTMLElement | null>;\n /** The popup element, set by the Popup's ref; how Close reaches `hidePopover()` / `close()`. */\n readonly popupRef: RefObject<Popup | null>;\n /**\n * Record what causes the next close. Cleared after a task if the popover did not close.\n * `unlessRecorded`: keep an intent already recorded for this close (the `command` listener runs\n * before the `beforetoggle` of the same click).\n */\n readonly recordCloseIntent: (\n intent: OverlayCloseIntent | undefined,\n options?: { readonly unlessRecorded?: boolean },\n ) => void;\n /** Read and clear the recorded intent (the Popup's `toggle` listener). */\n readonly takeCloseIntent: () => OverlayCloseIntent | undefined;\n}\n\n/** The root value of the popover-like components (Popover, Menu, Combobox). */\nexport type PopoverRootValue = OverlayRootValue<HTMLElement, []>;\n\nexport interface UseOverlayRootOptions<\n Details extends ActionDetails,\n Popup extends HTMLElement = HTMLElement,\n CloseArgs extends unknown[] = [],\n> {\n /** Transition types and messages: `\"popover\"` gives `fsui-popover`, `fsui-popover-open`, … */\n readonly component: string;\n /** Public name of the Root part for development warnings (`\"Popover.Root\"`). */\n readonly part: string;\n readonly open: boolean | undefined;\n readonly defaultOpen: boolean | undefined;\n readonly openChangeAction: ChangeAction<boolean, Details> | undefined;\n /**\n * `\"library\"` forces library mode whatever the props (Menu, which has no JS-free mode). Default:\n * detected from `open` / `defaultOpen` / `openChangeAction` on the first render.\n */\n readonly mode?: \"library\";\n /**\n * Called synchronously for every dispatch, before the action runs (Menu: cancel hover timers,\n * read the open cause).\n */\n readonly onDispatch?: (next: boolean, details: Details) => void;\n /** Builds the `details` of a dispatch (`popoverDetails`: `{ reason }`); an open passes no args. */\n readonly details: (\n event: Event | undefined,\n reason: ChangeReason,\n ...args: CloseArgs | []\n ) => Details;\n /** Whether the popup is shown, for a stale close intent. Default: `:popover-open`. */\n readonly isShown?: (popup: Popup) => boolean;\n}\n\n/** How long a recorded close intent survives when the popup did not close (design 2.3). */\nfunction clearLater<Popup extends HTMLElement>(\n intentRef: { current: OverlayCloseIntent | undefined },\n intent: OverlayCloseIntent,\n popupRef: { current: Popup | null },\n isShown: (popup: Popup) => boolean,\n): void {\n setTimeout(() => {\n // Closed: its `toggle` / `close` event (queued as a task) consumes the intent. Still open: the\n // close was cancelled or invalid, so the intent is stale.\n const popup = popupRef.current;\n if (intentRef.current === intent && popup !== null && isShown(popup)) {\n intentRef.current = undefined;\n }\n }, 0);\n}\n\n/** The `details` of a popover-like component: `{ reason }` (and `event`). */\nexport const popoverDetails = (event: Event | undefined, reason: ChangeReason): OverlayDetails =>\n createActionDetails(event, { reason });\n\n/**\n * The Root of an overlay without its public props: mode detection (once, from the first\n * render), `useControllableAction<boolean>`, ids, refs, close intents, the open generation and\n * the intent-aware `requestOpen` / `requestClose` / `notifyClosed`.\n */\nexport function useOverlayRoot<\n Details extends ActionDetails,\n Popup extends HTMLElement = HTMLElement,\n CloseArgs extends unknown[] = [],\n>(options: UseOverlayRootOptions<Details, Popup, CloseArgs>): OverlayRootValue<Popup, CloseArgs> {\n const { component, part, open, defaultOpen, openChangeAction, details, onDispatch } = options;\n\n // Mode is decided once, from the first render's props (design 2).\n const isLibraryNow =\n options.mode === \"library\" ||\n open !== undefined ||\n defaultOpen !== undefined ||\n openChangeAction !== undefined;\n const [mode] = useState<OverlayMode>(isLibraryNow ? \"library\" : \"static\");\n const isLibrary = mode === \"library\";\n useDevWarning(\n isLibrary !== isLibraryNow,\n isDev &&\n `${part}: the mode changed after mount (\\`open\\`, \\`defaultOpen\\` and \\`openChangeAction\\` ` +\n \"were all absent on one render and present on another). Switching between JS-free and \" +\n \"library mode is not supported.\",\n );\n\n // Hooks cannot be conditional: JS-free mode calls the hook too and never dispatches.\n const { committed, optimistic, pending, dispatch, latestInFlight } = useControllableAction<\n boolean,\n Details\n >({\n controlled: isLibrary ? open : undefined,\n defaultValue: isLibrary ? defaultOpen : undefined,\n initialValue: false,\n action: isLibrary ? openChangeAction : undefined,\n transitionTypes: (next) => transitionTypes(component, next ? \"open\" : \"close\"),\n warn: { component: part, prop: \"open\" },\n });\n\n const id = useId();\n const triggerRef = useRef<HTMLElement | null>(null);\n const popupRef = useRef<Popup | null>(null);\n const closeIntent = useRef<OverlayCloseIntent | undefined>(undefined);\n\n // The optimistic value of the last commit, for callers that run after an `await` (a Close\n // action's continuation) and would otherwise read the value of the render they were created in.\n // An insertion effect runs in the mutation phase, before any layout effect of the same commit\n // (a child's included), so `intended()` is current there too.\n const committedOptimistic = useLatest(optimistic);\n // `details`, `onDispatch` and `isShown` are usually inline functions: read the committed render's\n // through a ref so that the functions below, and with them the returned value, stay stable.\n const callbacks = useLatest({ details, onDispatch, isShown: options.isShown });\n const generation = useRef(0);\n const openGeneration = useCallback(() => generation.current, []);\n const nextOpenGeneration = useCallback(() => {\n generation.current++;\n }, []);\n\n const recordCloseIntent = useCallback(\n (intent: OverlayCloseIntent | undefined, options?: { readonly unlessRecorded?: boolean }) => {\n if (options?.unlessRecorded === true && closeIntent.current !== undefined) return;\n closeIntent.current = intent;\n if (intent !== undefined) {\n clearLater(closeIntent, intent, popupRef, callbacks.current.isShown ?? isPopoverOpen);\n }\n },\n [callbacks],\n );\n const takeCloseIntent = useCallback(() => {\n const intent = closeIntent.current;\n closeIntent.current = undefined;\n return intent;\n }, []);\n\n // Conventions 3.8 rule 1: judge no-ops against what the user already intends. That also\n // deduplicates the StrictMode re-run of the mount reconciliation and recognises the library's\n // own `hidePopover()` echoing back through `toggle`.\n const intended = useCallback(\n (): boolean => latestInFlight()?.next ?? committedOptimistic.current,\n [latestInFlight, committedOptimistic],\n );\n\n const send = useCallback(\n (next: boolean, event: Event | undefined, reason: ChangeReason, args: CloseArgs | []): void => {\n const { details, onDispatch } = callbacks.current;\n const built = details(event, reason, ...args);\n if (next) nextOpenGeneration();\n onDispatch?.(next, built);\n dispatch(next, built);\n },\n [callbacks, nextOpenGeneration, dispatch],\n );\n\n const requestOpen = useCallback(\n (event: Event | undefined, reason: ChangeReason): void => {\n if (!isLibrary || intended()) return;\n send(true, event, reason, []);\n },\n [isLibrary, intended, send],\n );\n\n const requestClose = useCallback(\n (event: Event | undefined, reason: ChangeReason, ...args: CloseArgs): void => {\n if (!isLibrary || !intended()) return;\n send(false, event, reason, args);\n },\n [isLibrary, intended, send],\n );\n\n const [shown, setShown] = useState(false);\n\n const ids = useMemo(\n () => ({ popup: id, title: `${id}-title`, description: `${id}-description` }),\n [id],\n );\n\n // Memoised: every function above is stable, so the value changes only with the open state and\n // pending, and the components' context values built on it are reused otherwise.\n return useMemo(\n () => ({\n mode,\n ids,\n committed: isLibrary && committed,\n optimistic: isLibrary && optimistic,\n shown,\n setShown,\n pending: isLibrary && pending,\n intended,\n openGeneration,\n nextOpenGeneration,\n requestOpen,\n requestClose,\n // The same function as `requestClose`; a separate name because the callers mean different\n // things (a part asks to close; the platform already closed).\n notifyClosed: requestClose,\n latestInFlight,\n triggerRef,\n popupRef,\n recordCloseIntent,\n takeCloseIntent,\n }),\n [\n mode,\n ids,\n isLibrary,\n committed,\n optimistic,\n shown,\n pending,\n intended,\n openGeneration,\n nextOpenGeneration,\n requestOpen,\n requestClose,\n latestInFlight,\n recordCloseIntent,\n takeCloseIntent,\n ],\n );\n}\n"],"mappings":"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"}
@@ -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,37 +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
- /**
38
- * Whether the `ToggleEvent.source` of a close (Chromium 140, Firefox 145, Safari 26.5; not in
39
- * TypeScript's DOM lib) is a `popovertarget` invoker of `popup`. A `commandfor` or `interestfor`
40
- * invoker sets `source` too (Chromium's lost-interest hide, a dismissal), and so names no
41
- * `popovertarget` here.
42
- */
43
- function closedByPopoverTarget(event, popup) {
44
- const source = event.source;
45
- return (source instanceof HTMLButtonElement || source instanceof HTMLInputElement) && source.popoverTargetElement === popup;
46
- }
47
19
  /** Whether `element` sits inside a popover that is not shown (an outer popup that closed). */
48
20
  function insideHiddenPopover(element) {
49
21
  for (let node = element.parentElement; node !== null; node = node.parentElement) if (node.hasAttribute("popover") && !isPopoverOpen(node)) return true;
@@ -52,13 +24,12 @@ function insideHiddenPopover(element) {
52
24
  /**
53
25
  * Everything in a popover-like Popup except rendering (design/components/popover.md 14.2): mount
54
26
  * reconciliation, the apply effect, the native `beforetoggle` / `toggle` / `command` listeners
55
- * (and `interest` / `loseinterest`, #127), close intents, the focus-return fallback, the JS-free
27
+ * (and `interest` / `loseinterest`), close intents, the focus-return fallback, the JS-free
56
28
  * `data-open` sync, the deferred unmount while a hide animates, and `initialFocus`. Shared by
57
- * Popover and Menu.
29
+ * Popover, Menu and Combobox.
58
30
  */
59
31
  function usePopoverPopup(ctx, options) {
60
- const { part, initialFocus, transition, onBeforeToggle: onBeforeToggleOption } = options;
61
- const onToggleOption = options.onToggle;
32
+ const { part, initialFocus, transition } = options;
62
33
  const isLibrary = ctx.mode === "library";
63
34
  const { popupRef, triggerRef, setShown } = ctx;
64
35
  const opening = useRef(false);
@@ -66,10 +37,12 @@ function usePopoverPopup(ctx, options) {
66
37
  const awaitingClose = useRef(false);
67
38
  const focusWasInside = useRef(false);
68
39
  const initialFocusTarget = useInitialFocusTarget(part, "popup");
69
- const interestInvoker = useRef(null);
70
- const interestOpen = useRef(false);
71
- const interestHideTask = useRef(void 0);
72
- const interestHide = useRef(false);
40
+ const interest = useInterestDismiss(ctx);
41
+ const stopWhileShown = useRef(null);
42
+ const stopListeningWhileShown = () => {
43
+ stopWhileShown.current?.();
44
+ stopWhileShown.current = null;
45
+ };
73
46
  const exit = useCloseHold(ctx.committed, isLibrary, transition);
74
47
  const contentProbe = useContentFocusProbe(popupRef);
75
48
  const { wrapContent } = contentProbe;
@@ -82,36 +55,40 @@ function usePopoverPopup(ctx, options) {
82
55
  const resolved = options.resolveInitialFocus(element);
83
56
  if (resolved === null) return null;
84
57
  const target = resolved instanceof HTMLElement ? resolved : resolved.element;
85
- 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
+ };
86
63
  }
87
- return initialFocusTarget(element, initialFocus);
64
+ const target = initialFocusTarget(element, initialFocus);
65
+ return target === null ? null : {
66
+ target,
67
+ quiet: false
68
+ };
88
69
  };
89
70
  const showPopup = (element) => {
90
- const resolved = resolveFocusTarget(element);
91
- const target = resolved === null || resolved instanceof HTMLElement ? resolved : resolved.element;
92
- const quiet = target !== null && !(resolved instanceof HTMLElement) && supportsFocusVisibleOption(element.ownerDocument);
93
- const added = target !== null && !quiet && !target.hasAttribute("autofocus");
94
- 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", "");
95
74
  opening.current = true;
96
75
  try {
97
76
  const source = options.source !== void 0 ? options.source() : triggerRef.current;
98
77
  element.showPopover(source != null && source.isConnected ? { source } : void 0);
99
78
  } finally {
100
79
  opening.current = false;
101
- if (added) target.removeAttribute("autofocus");
80
+ autofocused?.removeAttribute("autofocus");
102
81
  }
103
- 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 });
104
83
  };
105
84
  const reshow = () => {
106
85
  const element = popupRef.current;
107
86
  if (!isLibrary || element === null || !isPopoverOpen(element)) return false;
108
- opening.current = true;
109
87
  reshowing.current = true;
110
88
  try {
111
89
  element.hidePopover();
112
90
  showPopup(element);
113
91
  } finally {
114
- opening.current = false;
115
92
  reshowing.current = false;
116
93
  }
117
94
  awaitingClose.current = false;
@@ -154,8 +131,7 @@ function usePopoverPopup(ctx, options) {
154
131
  if (toggle.newState === "open") {
155
132
  if (isLibrary && !opening.current) {
156
133
  event.preventDefault();
157
- const source = toggle.source;
158
- interestOpen.current = source != null && source === interestInvoker.current;
134
+ interest.noteOpen(toggle);
159
135
  ctx.requestOpen(event, "activate");
160
136
  } else if (!reshowing.current) ctx.nextOpenGeneration();
161
137
  contentProbe.forget();
@@ -170,18 +146,16 @@ function usePopoverPopup(ctx, options) {
170
146
  focusWasInside.current = active !== null && element.contains(active) || contentProbe.hadFocus();
171
147
  contentProbe.forget();
172
148
  }
173
- onBeforeToggleOption?.(toggle);
174
149
  };
175
150
  const onToggle = (event) => {
176
151
  const element = popupRef.current;
177
152
  if (element === null || event.target !== element) return;
178
153
  awaitingClose.current = false;
179
- const lostInterest = interestHide.current;
180
- interestHide.current = false;
154
+ const lostInterest = interest.takeLostInterest();
181
155
  if (isLibrary) setShown(isPopoverOpen(element));
182
156
  else syncOpen(element);
183
157
  if (!isPopoverOpen(element)) {
184
- interestOpen.current = false;
158
+ interest.noteClosed();
185
159
  const wasInside = focusWasInside.current;
186
160
  focusWasInside.current = false;
187
161
  if (wasInside && !lostInterest) returnFocus(element);
@@ -191,7 +165,9 @@ function usePopoverPopup(ctx, options) {
191
165
  ctx.notifyClosed(intent?.event ?? event, intent?.reason ?? "dismiss");
192
166
  }
193
167
  }
194
- onToggleOption?.(event);
168
+ const { newState } = event;
169
+ if (newState === "open" && isPopoverOpen(element)) stopWhileShown.current ??= options.whileShown?.(element) ?? null;
170
+ else if (newState === "closed") stopListeningWhileShown();
195
171
  };
196
172
  const onCommand = (event) => {
197
173
  const element = popupRef.current;
@@ -202,57 +178,16 @@ function usePopoverPopup(ctx, options) {
202
178
  event
203
179
  });
204
180
  };
205
- /** The `source` of an `interest` / `loseinterest` event (`InterestEvent`, not in the DOM lib). */
206
- const interestSource = (event) => event.source ?? null;
207
- const onInterest = (event) => {
208
- const element = popupRef.current;
209
- if (!isLibrary || element === null || event.target !== element) return;
210
- interestInvoker.current = interestSource(event);
211
- };
212
- /**
213
- * Lost interest of an `interestfor` button naming the popup (Chromium; amendment #127). The
214
- * platform hides only a popover its own interest show opened (`invokedVia == kInterest`), and
215
- * the library cancels that show and re-shows with `showPopover({ source })`, so the platform
216
- * never hides: the library does, as a dismissal. Chromium also fires `loseinterest` from
217
- * inside every hide of the popup while the button has interest (Escape, script, the library's
218
- * own close), before the state flips, and a `hidePopover()` called from there re-enters the
219
- * hide and loses its `toggle`: the hide waits one task and runs only if the popup is still
220
- * shown and still meant to be open, and returns no focus to the Trigger. A pending interest
221
- * open is cancelled instead.
222
- */
223
- const onLoseInterest = (event) => {
224
- const element = popupRef.current;
225
- if (!isLibrary || element === null || event.target !== element) return;
226
- const source = interestSource(event);
227
- if (source === null || source !== interestInvoker.current) return;
228
- interestInvoker.current = null;
229
- if (!interestOpen.current) return;
230
- if (isPopoverOpen(element)) {
231
- clearTimeout(interestHideTask.current);
232
- interestHideTask.current = setTimeout(() => {
233
- interestHideTask.current = void 0;
234
- if (!isPopoverOpen(element) || !ctx.intended()) return;
235
- if (interestInvoker.current !== null) return;
236
- ctx.recordCloseIntent({
237
- reason: "dismiss",
238
- event
239
- });
240
- interestHide.current = true;
241
- element.hidePopover();
242
- }, 0);
243
- } else if (ctx.intended()) {
244
- interestOpen.current = false;
245
- ctx.requestClose(event, "dismiss");
246
- }
247
- };
248
181
  const handlers = useLatest({
249
182
  onBeforeToggle,
250
183
  onToggle,
251
184
  onCommand,
252
- onInterest,
253
- onLoseInterest
185
+ onInterest: interest.onInterest,
186
+ onLoseInterest: interest.onLoseInterest
254
187
  });
188
+ const latestWhileShown = useLatest(options.whileShown);
255
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;
256
191
  const setElement = useCallback((element) => {
257
192
  checkElement?.(element);
258
193
  popupRef.current = element;
@@ -265,6 +200,7 @@ function usePopoverPopup(ctx, options) {
265
200
  ];
266
201
  for (const [type, listener] of listeners) element.addEventListener(type, listener);
267
202
  if (isLibrary) setShown(isPopoverOpen(element));
203
+ if (isPopoverOpen(element)) stopWhileShown.current ??= latestWhileShown.current?.(element) ?? null;
268
204
  let autofocused = null;
269
205
  if (!isLibrary && initialFocus !== void 0) {
270
206
  const target = resolveInitialFocus(element, initialFocus);
@@ -275,11 +211,8 @@ function usePopoverPopup(ctx, options) {
275
211
  }
276
212
  return () => {
277
213
  for (const [type, listener] of listeners) element.removeEventListener(type, listener);
278
- clearTimeout(interestHideTask.current);
279
- interestHideTask.current = void 0;
280
- interestHide.current = false;
281
- interestInvoker.current = null;
282
- interestOpen.current = false;
214
+ resetInterest();
215
+ stopListeningWhileShown();
283
216
  if (isLibrary) setShown(false);
284
217
  autofocused?.removeAttribute("autofocus");
285
218
  if (popupRef.current === element) popupRef.current = null;
@@ -289,8 +222,10 @@ function usePopoverPopup(ctx, options) {
289
222
  popupRef,
290
223
  setShown,
291
224
  handlers,
225
+ latestWhileShown,
292
226
  isLibrary,
293
- initialFocus
227
+ initialFocus,
228
+ resetInterest
294
229
  ]);
295
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);
296
231
  const visible = ctx.committed || exit.held;