@funstack/ui 0.1.0-alpha.0 → 0.1.0-alpha.1

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 (154) hide show
  1. package/README.md +1 -1
  2. package/dist/checkbox-group/checkbox-group-context.mjs +24 -0
  3. package/dist/checkbox-group/checkbox-group-context.mjs.map +1 -0
  4. package/dist/checkbox-group/checkbox-group-item.d.mts +55 -0
  5. package/dist/checkbox-group/checkbox-group-item.d.mts.map +1 -0
  6. package/dist/checkbox-group/checkbox-group-item.mjs +90 -0
  7. package/dist/checkbox-group/checkbox-group-item.mjs.map +1 -0
  8. package/dist/checkbox-group/checkbox-group-label.d.mts +21 -0
  9. package/dist/checkbox-group/checkbox-group-label.d.mts.map +1 -0
  10. package/dist/checkbox-group/checkbox-group-label.mjs +30 -0
  11. package/dist/checkbox-group/checkbox-group-label.mjs.map +1 -0
  12. package/dist/checkbox-group/checkbox-group-parent.d.mts +68 -0
  13. package/dist/checkbox-group/checkbox-group-parent.d.mts.map +1 -0
  14. package/dist/checkbox-group/checkbox-group-parent.mjs +145 -0
  15. package/dist/checkbox-group/checkbox-group-parent.mjs.map +1 -0
  16. package/dist/checkbox-group/checkbox-group-root.d.mts +100 -0
  17. package/dist/checkbox-group/checkbox-group-root.d.mts.map +1 -0
  18. package/dist/checkbox-group/checkbox-group-root.mjs +291 -0
  19. package/dist/checkbox-group/checkbox-group-root.mjs.map +1 -0
  20. package/dist/checkbox-group/index.d.mts +23 -0
  21. package/dist/checkbox-group/index.d.mts.map +1 -0
  22. package/dist/checkbox-group/index.mjs +23 -0
  23. package/dist/checkbox-group/index.mjs.map +1 -0
  24. package/dist/dialog/dialog-close.d.mts.map +1 -1
  25. package/dist/dialog/dialog-close.mjs +4 -4
  26. package/dist/dialog/dialog-close.mjs.map +1 -1
  27. package/dist/dialog/dialog-context.mjs.map +1 -1
  28. package/dist/dialog/dialog-popup.mjs +1 -0
  29. package/dist/dialog/dialog-popup.mjs.map +1 -1
  30. package/dist/dialog/dialog-root.mjs +9 -1
  31. package/dist/dialog/dialog-root.mjs.map +1 -1
  32. package/dist/index.d.mts +23 -1
  33. package/dist/index.mjs +4 -1
  34. package/dist/internal/anchor-position.d.mts +7 -0
  35. package/dist/internal/anchor-position.d.mts.map +1 -0
  36. package/dist/internal/anchor-position.mjs +16 -0
  37. package/dist/internal/anchor-position.mjs.map +1 -0
  38. package/dist/internal/platform-attributes.d.mts +6 -0
  39. package/dist/internal/platform-attributes.d.mts.map +1 -1
  40. package/dist/internal/sync-presence.mjs +19 -0
  41. package/dist/internal/sync-presence.mjs.map +1 -0
  42. package/dist/internal/use-action-trigger.mjs +58 -0
  43. package/dist/internal/use-action-trigger.mjs.map +1 -0
  44. package/dist/internal/use-delayed-pair.mjs +40 -0
  45. package/dist/internal/use-delayed-pair.mjs.map +1 -0
  46. package/dist/internal/use-exit-animation.mjs +55 -0
  47. package/dist/internal/use-exit-animation.mjs.map +1 -0
  48. package/dist/internal/use-native-group-reconciliation.mjs +2 -2
  49. package/dist/internal/use-native-group-reconciliation.mjs.map +1 -1
  50. package/dist/internal/use-popover-popup.mjs +274 -0
  51. package/dist/internal/use-popover-popup.mjs.map +1 -0
  52. package/dist/internal/use-popover-root.d.mts +2 -0
  53. package/dist/internal/use-popover-root.mjs +112 -0
  54. package/dist/internal/use-popover-root.mjs.map +1 -0
  55. package/dist/internal/use-popover-trigger.mjs +86 -0
  56. package/dist/internal/use-popover-trigger.mjs.map +1 -0
  57. package/dist/menu/index.d.mts +34 -0
  58. package/dist/menu/index.d.mts.map +1 -0
  59. package/dist/menu/index.mjs +34 -0
  60. package/dist/menu/index.mjs.map +1 -0
  61. package/dist/menu/menu-checkbox-item.d.mts +42 -0
  62. package/dist/menu/menu-checkbox-item.d.mts.map +1 -0
  63. package/dist/menu/menu-checkbox-item.mjs +71 -0
  64. package/dist/menu/menu-checkbox-item.mjs.map +1 -0
  65. package/dist/menu/menu-context.d.mts +1 -0
  66. package/dist/menu/menu-context.mjs +28 -0
  67. package/dist/menu/menu-context.mjs.map +1 -0
  68. package/dist/menu/menu-dom.mjs +37 -0
  69. package/dist/menu/menu-dom.mjs.map +1 -0
  70. package/dist/menu/menu-group.d.mts +48 -0
  71. package/dist/menu/menu-group.d.mts.map +1 -0
  72. package/dist/menu/menu-group.mjs +69 -0
  73. package/dist/menu/menu-group.mjs.map +1 -0
  74. package/dist/menu/menu-hover.mjs +29 -0
  75. package/dist/menu/menu-hover.mjs.map +1 -0
  76. package/dist/menu/menu-item.d.mts +45 -0
  77. package/dist/menu/menu-item.d.mts.map +1 -0
  78. package/dist/menu/menu-item.mjs +54 -0
  79. package/dist/menu/menu-item.mjs.map +1 -0
  80. package/dist/menu/menu-popup.d.mts +69 -0
  81. package/dist/menu/menu-popup.d.mts.map +1 -0
  82. package/dist/menu/menu-popup.mjs +207 -0
  83. package/dist/menu/menu-popup.mjs.map +1 -0
  84. package/dist/menu/menu-radio-group.d.mts +37 -0
  85. package/dist/menu/menu-radio-group.d.mts.map +1 -0
  86. package/dist/menu/menu-radio-group.mjs +72 -0
  87. package/dist/menu/menu-radio-group.mjs.map +1 -0
  88. package/dist/menu/menu-radio-item.d.mts +33 -0
  89. package/dist/menu/menu-radio-item.d.mts.map +1 -0
  90. package/dist/menu/menu-radio-item.mjs +62 -0
  91. package/dist/menu/menu-radio-item.mjs.map +1 -0
  92. package/dist/menu/menu-root.d.mts +54 -0
  93. package/dist/menu/menu-root.d.mts.map +1 -0
  94. package/dist/menu/menu-root.mjs +102 -0
  95. package/dist/menu/menu-root.mjs.map +1 -0
  96. package/dist/menu/menu-submenu-trigger.d.mts +31 -0
  97. package/dist/menu/menu-submenu-trigger.d.mts.map +1 -0
  98. package/dist/menu/menu-submenu-trigger.mjs +92 -0
  99. package/dist/menu/menu-submenu-trigger.mjs.map +1 -0
  100. package/dist/menu/menu-trigger.d.mts +36 -0
  101. package/dist/menu/menu-trigger.d.mts.map +1 -0
  102. package/dist/menu/menu-trigger.mjs +81 -0
  103. package/dist/menu/menu-trigger.mjs.map +1 -0
  104. package/dist/menu/use-menu-item.mjs +54 -0
  105. package/dist/menu/use-menu-item.mjs.map +1 -0
  106. package/dist/popover/index.d.mts +28 -0
  107. package/dist/popover/index.d.mts.map +1 -0
  108. package/dist/popover/index.mjs +28 -0
  109. package/dist/popover/index.mjs.map +1 -0
  110. package/dist/popover/popover-close.d.mts +41 -0
  111. package/dist/popover/popover-close.d.mts.map +1 -0
  112. package/dist/popover/popover-close.mjs +90 -0
  113. package/dist/popover/popover-close.mjs.map +1 -0
  114. package/dist/popover/popover-context.mjs +26 -0
  115. package/dist/popover/popover-context.mjs.map +1 -0
  116. package/dist/popover/popover-description.d.mts +22 -0
  117. package/dist/popover/popover-description.d.mts.map +1 -0
  118. package/dist/popover/popover-description.mjs +28 -0
  119. package/dist/popover/popover-description.mjs.map +1 -0
  120. package/dist/popover/popover-popup.d.mts +82 -0
  121. package/dist/popover/popover-popup.d.mts.map +1 -0
  122. package/dist/popover/popover-popup.mjs +93 -0
  123. package/dist/popover/popover-popup.mjs.map +1 -0
  124. package/dist/popover/popover-root.d.mts +64 -0
  125. package/dist/popover/popover-root.d.mts.map +1 -0
  126. package/dist/popover/popover-root.mjs +39 -0
  127. package/dist/popover/popover-root.mjs.map +1 -0
  128. package/dist/popover/popover-title.d.mts +23 -0
  129. package/dist/popover/popover-title.d.mts.map +1 -0
  130. package/dist/popover/popover-title.mjs +28 -0
  131. package/dist/popover/popover-title.mjs.map +1 -0
  132. package/dist/popover/popover-trigger.d.mts +37 -0
  133. package/dist/popover/popover-trigger.d.mts.map +1 -0
  134. package/dist/popover/popover-trigger.mjs +40 -0
  135. package/dist/popover/popover-trigger.mjs.map +1 -0
  136. package/dist/radio-group/radio-group-item.d.mts.map +1 -1
  137. package/dist/radio-group/radio-group-item.mjs +1 -6
  138. package/dist/radio-group/radio-group-item.mjs.map +1 -1
  139. package/dist/tabs/tabs-context.mjs +2 -1
  140. package/dist/tabs/tabs-context.mjs.map +1 -1
  141. package/dist/tabs/tabs-list.d.mts +1 -1
  142. package/dist/tabs/tabs-list.d.mts.map +1 -1
  143. package/dist/tabs/tabs-list.mjs +17 -9
  144. package/dist/tabs/tabs-list.mjs.map +1 -1
  145. package/dist/tabs/tabs-tab.d.mts +1 -1
  146. package/dist/tabs/tabs-tab.d.mts.map +1 -1
  147. package/dist/tabs/tabs-tab.mjs +6 -3
  148. package/dist/tabs/tabs-tab.mjs.map +1 -1
  149. package/dist/tooltip/tooltip-popup.d.mts.map +1 -1
  150. package/dist/tooltip/tooltip-popup.mjs +2 -7
  151. package/dist/tooltip/tooltip-popup.mjs.map +1 -1
  152. package/dist/tooltip/use-tooltip-interaction.mjs +5 -17
  153. package/dist/tooltip/use-tooltip-interaction.mjs.map +1 -1
  154. package/package.json +4 -1
@@ -1 +1 @@
1
- {"version":3,"file":"use-native-group-reconciliation.mjs","names":[],"sources":["../../src/internal/use-native-group-reconciliation.ts"],"sourcesContent":["\"use client\";\nimport { useCallback, useEffectEvent, useLayoutEffect, useRef } from \"react\";\nimport type { RefObject } from \"react\";\nimport { useFormReset } from \"./use-form-reset.js\";\n\nexport interface UseNativeGroupReconciliationOptions<T> {\n /** The group's form-associated container (`RadioGroup.Root`'s `<fieldset>`). */\n readonly element: RefObject<HTMLFieldSetElement | null>;\n /** The group's value as the DOM shows it now (`checked` of the members). */\n readonly readCurrent: () => T;\n /** The value the browser resets the group to (`defaultChecked` of the members, rule 5). */\n readonly readDefault: () => T;\n /**\n * What the user intends (rule 1): the latest in-flight dispatch's `next`, else the optimistic\n * value. Use an explicit null check, `const f = latestInFlight(); return f === null ?\n * optimistic : f.next;`, not `?.next ?? optimistic`, which drops an in-flight dispatch of a\n * nullish value (a pending reset to \"nothing checked\").\n */\n readonly base: () => T;\n /**\n * The browser changed the group's value on a residual path and it differs from `base()`.\n * `event` is the `reset` event, or `undefined` for mount reconciliation (the Root's mount, or a\n * member mounting later). The Root dispatches once for the whole group with\n * `reason: \"platform\"`.\n */\n readonly onPlatformChange: (next: T, event: Event | undefined) => void;\n}\n\nexport interface UseNativeGroupReconciliationResult {\n /**\n * Stable. Pass it to every member, which hands it to\n * `useNativeChecked({ group: true, onItemMounted })`; the hook calls it from the member's mount\n * layout effect. A member that mounts after the Root's own mount reconciliation (inside a\n * Suspense boundary that hydrates later, selective hydration, or a member added on the client)\n * makes the adapter reconcile the group again: `readCurrent()` vs `base()`, in a microtask, once\n * for all members mounted in the same commit. Members mounting in the Root's own commit are\n * covered by the Root's mount reconciliation (their effects run before the Root's) and are\n * ignored.\n *\n * RadioGroup wiring: `const { onItemMounted } = useNativeGroupReconciliation(...)` in the Root,\n * put `onItemMounted` in the group context, and in each Item\n * `useNativeChecked({ type: \"radio\", group: true, onItemMounted: ctx.onItemMounted, ... })`.\n * The member's element argument is not used here; the Root may use it (dev warnings).\n */\n readonly onItemMounted: (element?: Element | null) => void;\n}\n\n/**\n * Group adapter of the native-input machinery (conventions 3.8): one dispatch per group for the\n * residual browser paths, from the Root rather than once per member.\n *\n * - Mount reconciliation, once, in a layout effect: `readCurrent()` vs `base()`. The members'\n * `useNativeChecked({ group: true })` leaves `checked` alone in their mount commit, so this\n * effect, which runs after the members' (children first), still reads the hydrated DOM.\n * - Late members: a member mounting in a later commit (a Suspense boundary that hydrates after the\n * Root, where a click before hydration changed the DOM) reports through `onItemMounted`, and the\n * group is reconciled again the same way (see `UseNativeGroupReconciliationResult`).\n * - Form reset through `useFormReset` on the container: in a microtask after the reset,\n * `readDefault()` vs `base()`.\n *\n * Values are compared with `Object.is`.\n */\nexport function useNativeGroupReconciliation<T>(\n options: UseNativeGroupReconciliationOptions<T>,\n): UseNativeGroupReconciliationResult {\n const { element } = options;\n\n // The latest committed options, for the late reconciliation, which runs in a microtask outside\n // any effect (so it cannot go through an Effect Event).\n const latest = useRef(options);\n useLayoutEffect(() => {\n latest.current = options;\n });\n\n /** The Root's own mount reconciliation has run (reset by its cleanup, StrictMode included). */\n const rootReconciled = useRef(false);\n /** A late reconciliation is queued; members mounting in the same commit share it. */\n const lateQueued = useRef(false);\n\n const reconcileMount = useEffectEvent(() => {\n if (element.current === null) return;\n reconcile(options, options.readCurrent());\n });\n useLayoutEffect(() => {\n reconcileMount();\n rootReconciled.current = true;\n return () => {\n rootReconciled.current = false;\n };\n }, []);\n\n const onItemMounted = useCallback(() => {\n if (!rootReconciled.current || lateQueued.current) return;\n lateQueued.current = true;\n queueMicrotask(() => {\n lateQueued.current = false;\n if (!rootReconciled.current) return;\n const current = latest.current;\n if (current.element.current === null) return;\n reconcile(current, current.readCurrent());\n });\n }, []);\n\n useFormReset(element, (event) => {\n if (element.current === null) return;\n reconcile(options, options.readDefault(), event);\n });\n\n return { onItemMounted };\n}\n\nfunction reconcile<T>(options: UseNativeGroupReconciliationOptions<T>, next: T, event?: Event) {\n if (!Object.is(next, options.base())) options.onPlatformChange(next, event);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA8DA,SAAgB,6BACd,SACoC;CACpC,MAAM,EAAE,YAAY;CAIpB,MAAM,SAAS,OAAO,OAAO;CAC7B,sBAAsB;EACpB,OAAO,UAAU;CACnB,CAAC;;CAGD,MAAM,iBAAiB,OAAO,KAAK;;CAEnC,MAAM,aAAa,OAAO,KAAK;CAE/B,MAAM,iBAAiB,qBAAqB;EAC1C,IAAI,QAAQ,YAAY,MAAM;EAC9B,UAAU,SAAS,QAAQ,YAAY,CAAC;CAC1C,CAAC;CACD,sBAAsB;EACpB,eAAe;EACf,eAAe,UAAU;EACzB,aAAa;GACX,eAAe,UAAU;EAC3B;CACF,GAAG,CAAC,CAAC;CAEL,MAAM,gBAAgB,kBAAkB;EACtC,IAAI,CAAC,eAAe,WAAW,WAAW,SAAS;EACnD,WAAW,UAAU;EACrB,qBAAqB;GACnB,WAAW,UAAU;GACrB,IAAI,CAAC,eAAe,SAAS;GAC7B,MAAM,UAAU,OAAO;GACvB,IAAI,QAAQ,QAAQ,YAAY,MAAM;GACtC,UAAU,SAAS,QAAQ,YAAY,CAAC;EAC1C,CAAC;CACH,GAAG,CAAC,CAAC;CAEL,aAAa,UAAU,UAAU;EAC/B,IAAI,QAAQ,YAAY,MAAM;EAC9B,UAAU,SAAS,QAAQ,YAAY,GAAG,KAAK;CACjD,CAAC;CAED,OAAO,EAAE,cAAc;AACzB;AAEA,SAAS,UAAa,SAAiD,MAAS,OAAe;CAC7F,IAAI,CAAC,OAAO,GAAG,MAAM,QAAQ,KAAK,CAAC,GAAG,QAAQ,iBAAiB,MAAM,KAAK;AAC5E"}
1
+ {"version":3,"file":"use-native-group-reconciliation.mjs","names":[],"sources":["../../src/internal/use-native-group-reconciliation.ts"],"sourcesContent":["\"use client\";\nimport { useCallback, useEffectEvent, useLayoutEffect, useRef } from \"react\";\nimport type { RefObject } from \"react\";\nimport { useFormReset } from \"./use-form-reset.js\";\n\nexport interface UseNativeGroupReconciliationOptions<T> {\n /** The group's form-associated container (`RadioGroup.Root`'s `<fieldset>`). */\n readonly element: RefObject<HTMLFieldSetElement | null>;\n /** The group's value as the DOM shows it now (`checked` of the members). */\n readonly readCurrent: () => T;\n /** The value the browser resets the group to (`defaultChecked` of the members, rule 5). */\n readonly readDefault: () => T;\n /**\n * What the user intends (rule 1): the latest in-flight dispatch's `next`, else the optimistic\n * value. Use an explicit null check, `const f = latestInFlight(); return f === null ?\n * optimistic : f.next;`, not `?.next ?? optimistic`, which drops an in-flight dispatch of a\n * nullish value (a pending reset to \"nothing checked\").\n */\n readonly base: () => T;\n /**\n * The browser changed the group's value on a residual path and it differs from `base()`.\n * `event` is the `reset` event, or `undefined` for mount reconciliation (the Root's mount, or a\n * member mounting later). The Root dispatches once for the whole group with\n * `reason: \"platform\"`.\n */\n readonly onPlatformChange: (next: T, event: Event | undefined) => void;\n /**\n * Equality between a read value and `base()`. Default `Object.is`, right for a primitive value\n * (RadioGroup's `string | null`); a group with a collection value (CheckboxGroup's\n * `ReadonlySet<string>`) passes structural equality, since every read builds a new object.\n */\n readonly equals?: ((a: T, b: T) => boolean) | undefined;\n}\n\nexport interface UseNativeGroupReconciliationResult {\n /**\n * Stable. Pass it to every member, which hands it to\n * `useNativeChecked({ group: true, onItemMounted })`; the hook calls it from the member's mount\n * layout effect. A member that mounts after the Root's own mount reconciliation (inside a\n * Suspense boundary that hydrates later, selective hydration, or a member added on the client)\n * makes the adapter reconcile the group again: `readCurrent()` vs `base()`, in a microtask, once\n * for all members mounted in the same commit. Members mounting in the Root's own commit are\n * covered by the Root's mount reconciliation (their effects run before the Root's) and are\n * ignored.\n *\n * RadioGroup wiring: `const { onItemMounted } = useNativeGroupReconciliation(...)` in the Root,\n * put `onItemMounted` in the group context, and in each Item\n * `useNativeChecked({ type: \"radio\", group: true, onItemMounted: ctx.onItemMounted, ... })`.\n * The member's element argument is not used here; the Root may use it (dev warnings).\n */\n readonly onItemMounted: (element?: Element | null) => void;\n}\n\n/**\n * Group adapter of the native-input machinery (conventions 3.8): one dispatch per group for the\n * residual browser paths, from the Root rather than once per member.\n *\n * - Mount reconciliation, once, in a layout effect: `readCurrent()` vs `base()`. The members'\n * `useNativeChecked({ group: true })` leaves `checked` alone in their mount commit, so this\n * effect, which runs after the members' (children first), still reads the hydrated DOM.\n * - Late members: a member mounting in a later commit (a Suspense boundary that hydrates after the\n * Root, where a click before hydration changed the DOM) reports through `onItemMounted`, and the\n * group is reconciled again the same way (see `UseNativeGroupReconciliationResult`).\n * - Form reset through `useFormReset` on the container: in a microtask after the reset,\n * `readDefault()` vs `base()`.\n *\n * Values are compared with `equals` (default `Object.is`).\n */\nexport function useNativeGroupReconciliation<T>(\n options: UseNativeGroupReconciliationOptions<T>,\n): UseNativeGroupReconciliationResult {\n const { element } = options;\n\n // The latest committed options, for the late reconciliation, which runs in a microtask outside\n // any effect (so it cannot go through an Effect Event).\n const latest = useRef(options);\n useLayoutEffect(() => {\n latest.current = options;\n });\n\n /** The Root's own mount reconciliation has run (reset by its cleanup, StrictMode included). */\n const rootReconciled = useRef(false);\n /** A late reconciliation is queued; members mounting in the same commit share it. */\n const lateQueued = useRef(false);\n\n const reconcileMount = useEffectEvent(() => {\n if (element.current === null) return;\n reconcile(options, options.readCurrent());\n });\n useLayoutEffect(() => {\n reconcileMount();\n rootReconciled.current = true;\n return () => {\n rootReconciled.current = false;\n };\n }, []);\n\n const onItemMounted = useCallback(() => {\n if (!rootReconciled.current || lateQueued.current) return;\n lateQueued.current = true;\n queueMicrotask(() => {\n lateQueued.current = false;\n if (!rootReconciled.current) return;\n const current = latest.current;\n if (current.element.current === null) return;\n reconcile(current, current.readCurrent());\n });\n }, []);\n\n useFormReset(element, (event) => {\n if (element.current === null) return;\n reconcile(options, options.readDefault(), event);\n });\n\n return { onItemMounted };\n}\n\nfunction reconcile<T>(options: UseNativeGroupReconciliationOptions<T>, next: T, event?: Event) {\n const equals = options.equals ?? Object.is;\n if (!equals(next, options.base())) options.onPlatformChange(next, event);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAoEA,SAAgB,6BACd,SACoC;CACpC,MAAM,EAAE,YAAY;CAIpB,MAAM,SAAS,OAAO,OAAO;CAC7B,sBAAsB;EACpB,OAAO,UAAU;CACnB,CAAC;;CAGD,MAAM,iBAAiB,OAAO,KAAK;;CAEnC,MAAM,aAAa,OAAO,KAAK;CAE/B,MAAM,iBAAiB,qBAAqB;EAC1C,IAAI,QAAQ,YAAY,MAAM;EAC9B,UAAU,SAAS,QAAQ,YAAY,CAAC;CAC1C,CAAC;CACD,sBAAsB;EACpB,eAAe;EACf,eAAe,UAAU;EACzB,aAAa;GACX,eAAe,UAAU;EAC3B;CACF,GAAG,CAAC,CAAC;CAEL,MAAM,gBAAgB,kBAAkB;EACtC,IAAI,CAAC,eAAe,WAAW,WAAW,SAAS;EACnD,WAAW,UAAU;EACrB,qBAAqB;GACnB,WAAW,UAAU;GACrB,IAAI,CAAC,eAAe,SAAS;GAC7B,MAAM,UAAU,OAAO;GACvB,IAAI,QAAQ,QAAQ,YAAY,MAAM;GACtC,UAAU,SAAS,QAAQ,YAAY,CAAC;EAC1C,CAAC;CACH,GAAG,CAAC,CAAC;CAEL,aAAa,UAAU,UAAU;EAC/B,IAAI,QAAQ,YAAY,MAAM;EAC9B,UAAU,SAAS,QAAQ,YAAY,GAAG,KAAK;CACjD,CAAC;CAED,OAAO,EAAE,cAAc;AACzB;AAEA,SAAS,UAAa,SAAiD,MAAS,OAAe;CAE7F,IAAI,EADW,QAAQ,UAAU,OAAO,GAAA,CAC5B,MAAM,QAAQ,KAAK,CAAC,GAAG,QAAQ,iBAAiB,MAAM,KAAK;AACzE"}
@@ -0,0 +1,274 @@
1
+ "use client";
2
+ import { exitAnimations, useExitAnimation } from "./use-exit-animation.mjs";
3
+ import { createElement, useCallback, useEffect, useEffectEvent, useInsertionEffect, useLayoutEffect, useRef, useState } from "react";
4
+ //#region src/internal/use-popover-popup.ts
5
+ const isDev = process.env.NODE_ENV !== "production";
6
+ function isPopoverOpen(element) {
7
+ try {
8
+ return element.matches(":popover-open");
9
+ } catch {
10
+ return false;
11
+ }
12
+ }
13
+ let focusVisibleOption;
14
+ /**
15
+ * The engine reads the `focusVisible` member of `focus()`'s options (Chromium 145, Firefox 104,
16
+ * Safari 18.4). Detected once through a getter: the bindings convert the dictionary before the
17
+ * method runs, so a detached element is enough and nothing is focused.
18
+ */
19
+ function supportsFocusVisibleOption(doc) {
20
+ if (focusVisibleOption === void 0) {
21
+ let read = false;
22
+ try {
23
+ doc.createElement("div").focus({ get focusVisible() {
24
+ read = true;
25
+ return false;
26
+ } });
27
+ } catch {
28
+ read = false;
29
+ }
30
+ focusVisibleOption = read;
31
+ }
32
+ return focusVisibleOption;
33
+ }
34
+ /** Resolves `initialFocus` against the popup (a ref, or a selector inside the popup). */
35
+ function resolveInitialFocus(popup, initialFocus) {
36
+ if (typeof initialFocus === "string") return popup.querySelector(initialFocus);
37
+ return initialFocus.current;
38
+ }
39
+ /** Whether `element` sits inside a popover that is not shown (an outer popup that closed). */
40
+ function insideHiddenPopover(element) {
41
+ for (let node = element.parentElement; node !== null; node = node.parentElement) if (node.hasAttribute("popover") && !isPopoverOpen(node)) return true;
42
+ return false;
43
+ }
44
+ /**
45
+ * Records, from its layout-effect cleanup, whether focus is inside the popup when the content
46
+ * goes away: React runs a deleted component's layout cleanups before it detaches the host nodes,
47
+ * so `document.activeElement` still names the focused element there.
48
+ */
49
+ function ContentFocusProbe({ onDetach, children }) {
50
+ useLayoutEffect(() => onDetach, [onDetach]);
51
+ return children;
52
+ }
53
+ /**
54
+ * Everything in a popover-like Popup except rendering (design/components/popover.md 14.2): mount
55
+ * reconciliation, the apply effect, the native `beforetoggle` / `toggle` / `command` listeners,
56
+ * close intents, the focus-return fallback, the JS-free `aria-expanded` sync, the deferred
57
+ * unmount while a hide animates, and `initialFocus`. Shared by Popover and Menu.
58
+ */
59
+ function usePopoverPopup(ctx, options) {
60
+ const { part, initialFocus, transition, onBeforeToggle: onBeforeToggleOption } = options;
61
+ const onToggleOption = options.onToggle;
62
+ const isLibrary = ctx.mode === "library";
63
+ const { popupRef, triggerRef } = ctx;
64
+ const opening = useRef(false);
65
+ const awaitingClose = useRef(false);
66
+ const focusWasInside = useRef(false);
67
+ const contentHadFocus = useRef(false);
68
+ const warnedFocus = useRef(false);
69
+ const exit = useExitAnimation();
70
+ const [prevCommitted, setPrevCommitted] = useState(ctx.committed);
71
+ if (prevCommitted !== ctx.committed) {
72
+ setPrevCommitted(ctx.committed);
73
+ if (isLibrary && prevCommitted && transition === void 0) exit.holdDuringRender();
74
+ }
75
+ const recordContentFocus = useCallback(() => {
76
+ const element = popupRef.current;
77
+ if (element === null) return;
78
+ const active = element.ownerDocument.activeElement;
79
+ if (active !== null && active !== element && element.contains(active)) contentHadFocus.current = true;
80
+ }, [popupRef]);
81
+ const wrapContent = useCallback((children) => createElement(ContentFocusProbe, { onDetach: recordContentFocus }, children), [recordContentFocus]);
82
+ const syncExpanded = (element) => {
83
+ triggerRef.current?.setAttribute("aria-expanded", String(isPopoverOpen(element)));
84
+ };
85
+ /**
86
+ * Design 6.2 rule 2, for a close that began with focus inside: when focus is now on `<body>`
87
+ * or still inside the hidden popup, focus the Trigger (connected, not inside a hidden
88
+ * popover), else blur what holds focus.
89
+ */
90
+ const returnFocus = (element) => {
91
+ const doc = element.ownerDocument;
92
+ const active = doc.activeElement;
93
+ if (active !== null && active !== doc.body && !element.contains(active)) return;
94
+ const trigger = triggerRef.current;
95
+ if (trigger !== null && trigger.isConnected && !insideHiddenPopover(trigger)) trigger.focus();
96
+ else if (active instanceof HTMLElement && active !== doc.body) active.blur();
97
+ };
98
+ const resolveFocusTarget = (element) => {
99
+ if (options.resolveInitialFocus !== void 0) {
100
+ const resolved = options.resolveInitialFocus(element);
101
+ if (resolved === null) return null;
102
+ const target = resolved instanceof HTMLElement ? resolved : resolved.element;
103
+ return element.contains(target) ? resolved : null;
104
+ }
105
+ if (initialFocus === void 0) return null;
106
+ const target = resolveInitialFocus(element, initialFocus);
107
+ if (target !== null && element.contains(target)) return target;
108
+ if (isDev && !warnedFocus.current) {
109
+ warnedFocus.current = true;
110
+ console.error(target === null ? `${part}: \`initialFocus\` resolved to no element; the platform picks the focus target.` : `${part}: \`initialFocus\` is outside the popup; the platform picks the focus target.`);
111
+ }
112
+ return null;
113
+ };
114
+ const showPopup = (element) => {
115
+ const resolved = resolveFocusTarget(element);
116
+ const target = resolved === null || resolved instanceof HTMLElement ? resolved : resolved.element;
117
+ const quiet = target !== null && !(resolved instanceof HTMLElement) && supportsFocusVisibleOption(element.ownerDocument);
118
+ const added = target !== null && !quiet && !target.hasAttribute("autofocus");
119
+ if (added) target.setAttribute("autofocus", "");
120
+ opening.current = true;
121
+ try {
122
+ const source = triggerRef.current;
123
+ element.showPopover(source !== null && source.isConnected ? { source } : void 0);
124
+ } finally {
125
+ opening.current = false;
126
+ if (added) target.removeAttribute("autofocus");
127
+ }
128
+ if (quiet && isPopoverOpen(element) && element.contains(target)) target.focus({ focusVisible: false });
129
+ };
130
+ const reconcileOnMount = useEffectEvent(() => {
131
+ const element = popupRef.current;
132
+ if (element === null) return;
133
+ if (!isLibrary) {
134
+ syncExpanded(element);
135
+ return;
136
+ }
137
+ if (isPopoverOpen(element)) ctx.requestOpen(void 0, "platform");
138
+ });
139
+ useLayoutEffect(() => {
140
+ reconcileOnMount();
141
+ }, []);
142
+ useLayoutEffect(() => {
143
+ if (!isLibrary) return;
144
+ const element = popupRef.current;
145
+ if (element === null || !element.isConnected) return;
146
+ if (!ctx.pending && ctx.latestInFlight() === null) {
147
+ const shown = isPopoverOpen(element);
148
+ if (ctx.committed && !shown) {
149
+ if (!awaitingClose.current) showPopup(element);
150
+ } else if (!ctx.committed && shown) {
151
+ ctx.recordCloseIntent(void 0);
152
+ element.hidePopover();
153
+ if (focusWasInside.current) returnFocus(element);
154
+ }
155
+ }
156
+ if (ctx.committed && isPopoverOpen(element)) contentHadFocus.current = false;
157
+ if (exit.held && !ctx.committed && !exit.waiting() && !awaitingClose.current && !isPopoverOpen(element)) exit.release();
158
+ });
159
+ const onBeforeToggle = (event) => {
160
+ const element = popupRef.current;
161
+ if (element === null || event.target !== element) return;
162
+ const toggle = event;
163
+ if (toggle.newState === "open") {
164
+ if (isLibrary && !opening.current) {
165
+ event.preventDefault();
166
+ ctx.requestOpen(event, "activate");
167
+ } else ctx.nextOpenGeneration();
168
+ contentHadFocus.current = false;
169
+ } else {
170
+ awaitingClose.current = true;
171
+ const active = element.ownerDocument.activeElement;
172
+ focusWasInside.current = active !== null && element.contains(active) || contentHadFocus.current;
173
+ contentHadFocus.current = false;
174
+ }
175
+ onBeforeToggleOption?.(toggle);
176
+ };
177
+ const onToggle = (event) => {
178
+ const element = popupRef.current;
179
+ if (element === null || event.target !== element) return;
180
+ awaitingClose.current = false;
181
+ if (!isLibrary) syncExpanded(element);
182
+ if (!isPopoverOpen(element)) {
183
+ const wasInside = focusWasInside.current;
184
+ focusWasInside.current = false;
185
+ if (wasInside) returnFocus(element);
186
+ const intent = ctx.takeCloseIntent();
187
+ if (isLibrary) {
188
+ if (!!ctx.intended() || transition === void 0) {
189
+ const animations = exitAnimations(element);
190
+ if (animations.length > 0) exit.holdUntil(animations);
191
+ else exit.release();
192
+ }
193
+ ctx.notifyClosed(intent?.event ?? event, intent?.reason ?? "dismiss");
194
+ }
195
+ }
196
+ onToggleOption?.(event);
197
+ };
198
+ const onCommand = (event) => {
199
+ const element = popupRef.current;
200
+ if (element === null || event.target !== element || event.defaultPrevented) return;
201
+ const command = String(event.command ?? "").toLowerCase();
202
+ if (command === "hide-popover" || command === "toggle-popover" && isPopoverOpen(element)) ctx.recordCloseIntent({
203
+ reason: "activate",
204
+ event
205
+ });
206
+ };
207
+ const handlers = useRef({
208
+ onBeforeToggle,
209
+ onToggle,
210
+ onCommand
211
+ });
212
+ useInsertionEffect(() => {
213
+ handlers.current = {
214
+ onBeforeToggle,
215
+ onToggle,
216
+ onCommand
217
+ };
218
+ });
219
+ const setElement = useCallback((element) => {
220
+ if (isDev && element.tagName !== "DIALOG" && element.tagName !== "DIV") console.error(`${part}: expected to render a <dialog> or a <div> but got <${element.tagName.toLowerCase()}>.`);
221
+ popupRef.current = element;
222
+ const listeners = [
223
+ ["beforetoggle", (event) => handlers.current.onBeforeToggle(event)],
224
+ ["toggle", (event) => handlers.current.onToggle(event)],
225
+ ["command", (event) => handlers.current.onCommand(event)]
226
+ ];
227
+ for (const [type, listener] of listeners) element.addEventListener(type, listener);
228
+ let autofocused = null;
229
+ if (!isLibrary && initialFocus !== void 0) {
230
+ const target = resolveInitialFocus(element, initialFocus);
231
+ if (target !== null && element.contains(target) && !target.hasAttribute("autofocus")) {
232
+ target.setAttribute("autofocus", "");
233
+ autofocused = target;
234
+ }
235
+ }
236
+ return () => {
237
+ for (const [type, listener] of listeners) element.removeEventListener(type, listener);
238
+ autofocused?.removeAttribute("autofocus");
239
+ if (popupRef.current === element) popupRef.current = null;
240
+ };
241
+ }, [
242
+ part,
243
+ popupRef,
244
+ isLibrary,
245
+ initialFocus
246
+ ]);
247
+ const shown = !isLibrary || ctx.committed;
248
+ const warnedName = useRef(false);
249
+ useEffect(() => {
250
+ const element = popupRef.current;
251
+ if (!isDev || element === null || !shown || warnedName.current) return;
252
+ if (element.hasAttribute("aria-label")) return;
253
+ const labelledBy = (element.getAttribute("aria-labelledby") ?? "").split(/\s+/);
254
+ const doc = element.ownerDocument;
255
+ if (labelledBy.some((id) => id !== "" && doc.getElementById(id) !== null)) return;
256
+ const role = element.getAttribute("role");
257
+ if (role !== "dialog" && role !== "alertdialog" && role !== "menu") return;
258
+ warnedName.current = true;
259
+ console.error(`${part}: the popup has no accessible name. Render a Title, or give the Popup an \`aria-label\`.`);
260
+ }, [
261
+ popupRef,
262
+ shown,
263
+ part
264
+ ]);
265
+ return {
266
+ setElement,
267
+ visible: ctx.committed || exit.held,
268
+ wrapContent
269
+ };
270
+ }
271
+ //#endregion
272
+ export { usePopoverPopup };
273
+
274
+ //# sourceMappingURL=use-popover-popup.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-popover-popup.mjs","names":[],"sources":["../../src/internal/use-popover-popup.ts"],"sourcesContent":["\"use client\";\nimport {\n createElement,\n useCallback,\n useEffect,\n useEffectEvent,\n useInsertionEffect,\n useLayoutEffect,\n useRef,\n useState,\n} from \"react\";\nimport type { ReactNode, RefObject, ViewTransitionClass } from \"react\";\nimport { exitAnimations, useExitAnimation } from \"./use-exit-animation.js\";\nimport type { PopoverRootValue } from \"./use-popover-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 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: close the stack on Tab-out). */\n readonly onToggle?: (event: ToggleEvent) => void;\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; review H1).\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 * Wraps the library-mode content: call it only while `visible` (`visible ? wrapContent(x) :\n * null`), or inside the `<Activity>` for `keepMounted`. When a close commit unmounts the\n * content while it holds focus (a library-driven close with `transition`, where the focused\n * element is gone before `hidePopover()` runs and the platform restores nothing), the hide\n * that follows returns focus to the Trigger (design 6.2).\n */\n readonly wrapContent: (children: ReactNode) => ReactNode;\n}\n\nconst isDev = process.env.NODE_ENV !== \"production\";\n\nfunction isPopoverOpen(element: Element): boolean {\n try {\n return element.matches(\":popover-open\");\n } catch {\n return false;\n }\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/** Resolves `initialFocus` against the popup (a ref, or a selector inside the popup). */\nfunction resolveInitialFocus(\n popup: HTMLElement,\n initialFocus: RefObject<HTMLElement | null> | string,\n): HTMLElement | null {\n if (typeof initialFocus === \"string\") return popup.querySelector<HTMLElement>(initialFocus);\n return initialFocus.current;\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 * Records, from its layout-effect cleanup, whether focus is inside the popup when the content\n * goes away: React runs a deleted component's layout cleanups before it detaches the host nodes,\n * so `document.activeElement` still names the focused element there.\n */\nfunction ContentFocusProbe({\n onDetach,\n children,\n}: {\n onDetach: () => void;\n children?: ReactNode;\n}): ReactNode {\n useLayoutEffect(() => onDetach, [onDetach]);\n return children;\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 } = ctx;\n\n // The opening `beforetoggle` lets this one through: the library's own `showPopover()`.\n const opening = 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 // Whether the content unmounted while holding focus since the popup was last shown (H1).\n const contentHadFocus = useRef(false);\n const warnedFocus = useRef(false);\n\n // --- `held`: children stay mounted while the hide animates (design 4.4) -------------------\n\n const exit = useExitAnimation();\n\n // A library-driven close commits `false` first and hides in the layout effect, so without\n // `transition` the children are held through the close commit (\"previous value in state\").\n // With `transition` the close commit unmounts them inside the view transition, whose old\n // snapshot carries the content out.\n const [prevCommitted, setPrevCommitted] = useState(ctx.committed);\n if (prevCommitted !== ctx.committed) {\n setPrevCommitted(ctx.committed);\n if (isLibrary && prevCommitted && transition === undefined) exit.holdDuringRender();\n }\n\n const recordContentFocus = useCallback(() => {\n const element = popupRef.current;\n if (element === null) return;\n const active = element.ownerDocument.activeElement;\n if (active !== null && active !== element && element.contains(active)) {\n contentHadFocus.current = true;\n }\n }, [popupRef]);\n\n const wrapContent = useCallback(\n (children: ReactNode): ReactNode =>\n createElement(ContentFocusProbe, { onDetach: recordContentFocus }, children),\n [recordContentFocus],\n );\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 /**\n * Design 6.2 rule 2, for a close that began with focus inside: when focus is now on `<body>`\n * or still inside the hidden popup, focus the Trigger (connected, not inside a hidden\n * popover), else blur what holds focus.\n */\n const returnFocus = (element: HTMLElement): void => {\n const doc = element.ownerDocument;\n const active = doc.activeElement;\n if (active !== null && active !== doc.body && !element.contains(active)) return;\n const trigger = triggerRef.current;\n if (trigger !== null && trigger.isConnected && !insideHiddenPopover(trigger)) {\n trigger.focus();\n } else if (active instanceof HTMLElement && active !== doc.body) {\n active.blur();\n }\n };\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 if (initialFocus === undefined) return null;\n const target = resolveInitialFocus(element, initialFocus);\n if (target !== null && element.contains(target)) return target;\n if (isDev && !warnedFocus.current) {\n warnedFocus.current = true;\n console.error(\n target === null\n ? `${part}: \\`initialFocus\\` resolved to no element; the platform picks the focus target.`\n : `${part}: \\`initialFocus\\` is outside the popup; the platform picks the focus target.`,\n );\n }\n return null;\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 = 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 // 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, once nothing is in flight, the DOM\n // follows committed state. One effect covers the normal open, `defaultOpen`, a controlled open\n // or close, a library-driven close after `openChangeAction(false)` settled, the re-open of a\n // refused dismissal, and the close after a refused or failed pre-hydration open.\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 (H1): 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)) contentHadFocus.current = false;\n // A hold the close commit set (or a dismissal's notification commit) that no hide animation\n // is going to release: the popup is already hidden and its `toggle` has been handled.\n if (\n exit.held &&\n !ctx.committed &&\n !exit.waiting() &&\n !awaitingClose.current &&\n !isPopoverOpen(element)\n ) {\n exit.release();\n }\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 {\n // A Close action that resolves after this open must not close it (design 3.4).\n ctx.nextOpenGeneration();\n }\n contentHadFocus.current = false;\n } else {\n awaitingClose.current = true;\n const active = element.ownerDocument.activeElement;\n focusWasInside.current =\n (active !== null && element.contains(active)) || contentHadFocus.current;\n contentHadFocus.current = false;\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 if (!isLibrary) 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 // `false` already intended: the library's own hide (or a dismissal during a pending\n // part-initiated close). With `transition` such a close needs no hold (4.4).\n const echo = !ctx.intended();\n if (!echo || transition === undefined) {\n const animations = exitAnimations(element);\n if (animations.length > 0) {\n // Before the notification, so its commit keeps the children (urgent, internal).\n exit.holdUntil(animations);\n } else {\n // Nothing animates (Firefox, or no CSS exit): release a hold now; the commit is\n // invisible, the popup is already `display: none`.\n exit.release();\n }\n }\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 = String((event as Event & { command?: string }).command ?? \"\").toLowerCase();\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 = useRef({ onBeforeToggle, onToggle, onCommand });\n useInsertionEffect(() => {\n handlers.current = { onBeforeToggle, onToggle, onCommand };\n });\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 setElement = useCallback(\n (element: HTMLElement) => {\n if (isDev && element.tagName !== \"DIALOG\" && element.tagName !== \"DIV\") {\n console.error(\n `${part}: expected to render a <dialog> or a <div> but got ` +\n `<${element.tagName.toLowerCase()}>.`,\n );\n }\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\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 autofocused?.removeAttribute(\"autofocus\");\n if (popupRef.current === element) popupRef.current = null;\n };\n },\n [part, popupRef, isLibrary, initialFocus],\n );\n\n // Development check (design 9): `role=\"dialog\"` needs a name once the popup is (or can be)\n // shown.\n const shown = !isLibrary || ctx.committed;\n const warnedName = useRef(false);\n useEffect(() => {\n const element = popupRef.current;\n if (!isDev || element === null || !shown || warnedName.current) return;\n if (element.hasAttribute(\"aria-label\")) return;\n const labelledBy = (element.getAttribute(\"aria-labelledby\") ?? \"\").split(/\\s+/);\n const doc = element.ownerDocument;\n if (labelledBy.some((id) => id !== \"\" && doc.getElementById(id) !== null)) return;\n const role = element.getAttribute(\"role\");\n if (role !== \"dialog\" && role !== \"alertdialog\" && role !== \"menu\") return;\n warnedName.current = true;\n console.error(\n `${part}: the popup has no accessible name. Render a Title, or give the Popup an ` +\n \"`aria-label`.\",\n );\n }, [popupRef, shown, part]);\n\n return { setElement, visible: ctx.committed || exit.held, wrapContent };\n}\n"],"mappings":";;;;AAgEA,MAAM,QAAQ,QAAQ,IAAI,aAAa;AAEvC,SAAS,cAAc,SAA2B;CAChD,IAAI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oBAAoB,MAAM,QAAQ;GACpF,aAAa,gBAAgB,WAAW;GACxC,IAAI,SAAS,YAAY,SAAS,SAAS,UAAU;EACvD;CACF,GACA;EAAC;EAAM;EAAU;EAAW;CAAY,CAC1C;CAIA,MAAM,QAAQ,CAAC,aAAa,IAAI;CAChC,MAAM,aAAa,OAAO,KAAK;CAC/B,gBAAgB;EACd,MAAM,UAAU,SAAS;EACzB,IAAI,CAAC,SAAS,YAAY,QAAQ,CAAC,SAAS,WAAW,SAAS;EAChE,IAAI,QAAQ,aAAa,YAAY,GAAG;EACxC,MAAM,cAAc,QAAQ,aAAa,iBAAiB,KAAK,GAAA,CAAI,MAAM,KAAK;EAC9E,MAAM,MAAM,QAAQ;EACpB,IAAI,WAAW,MAAM,OAAO,OAAO,MAAM,IAAI,eAAe,EAAE,MAAM,IAAI,GAAG;EAC3E,MAAM,OAAO,QAAQ,aAAa,MAAM;EACxC,IAAI,SAAS,YAAY,SAAS,iBAAiB,SAAS,QAAQ;EACpE,WAAW,UAAU;EACrB,QAAQ,MACN,GAAG,KAAK,yFAEV;CACF,GAAG;EAAC;EAAU;EAAO;CAAI,CAAC;CAE1B,OAAO;EAAE;EAAY,SAAS,IAAI,aAAa,KAAK;EAAM;CAAY;AACxE"}
@@ -0,0 +1,2 @@
1
+ import "./types.mjs";
2
+ import { RefObject } from "react";
@@ -0,0 +1,112 @@
1
+ "use client";
2
+ import { createActionDetails } from "./action-details.mjs";
3
+ import { transitionTypes } from "./transition-types.mjs";
4
+ import { useControllableAction } from "./use-controllable-action.mjs";
5
+ import { useDevWarning } from "./use-dev-warning.mjs";
6
+ import { useCallback, useId, useInsertionEffect, useRef, useState } from "react";
7
+ //#region src/internal/use-popover-root.ts
8
+ function isPopoverOpen(element) {
9
+ if (element === null) return false;
10
+ try {
11
+ return element.matches(":popover-open");
12
+ } catch {
13
+ return false;
14
+ }
15
+ }
16
+ /** How long a recorded close intent survives when the popover did not close (design 2.3). */
17
+ function clearLater(intentRef, intent, popupRef) {
18
+ setTimeout(() => {
19
+ if (intentRef.current === intent && isPopoverOpen(popupRef.current)) intentRef.current = void 0;
20
+ }, 0);
21
+ }
22
+ /**
23
+ * The Root of a popover-like component without its public props (design 14.1): mode detection
24
+ * (once, from the first render), `useControllableAction<boolean>`, ids, refs, close intents and
25
+ * the intent-aware `requestOpen` / `requestClose` / `notifyClosed`.
26
+ */
27
+ function usePopoverRoot(options) {
28
+ const { component, part, open, defaultOpen, openChangeAction, details, onDispatch } = options;
29
+ const isLibraryNow = options.mode === "library" || open !== void 0 || defaultOpen !== void 0 || openChangeAction !== void 0;
30
+ const [mode] = useState(isLibraryNow ? "library" : "static");
31
+ const isLibrary = mode === "library";
32
+ useDevWarning(isLibrary !== isLibraryNow, `${part}: the mode changed after mount (\`open\`, \`defaultOpen\` and \`openChangeAction\` were all absent on one render and present on another). Switching between JS-free and library mode is not supported.`);
33
+ const { committed, optimistic, pending, dispatch, latestInFlight } = useControllableAction({
34
+ controlled: isLibrary ? open : void 0,
35
+ defaultValue: isLibrary ? defaultOpen : void 0,
36
+ initialValue: false,
37
+ action: isLibrary ? openChangeAction : void 0,
38
+ transitionTypes: (next) => transitionTypes(component, next ? "open" : "close"),
39
+ warn: {
40
+ component: part,
41
+ prop: "open"
42
+ }
43
+ });
44
+ const id = useId();
45
+ const triggerRef = useRef(null);
46
+ const popupRef = useRef(null);
47
+ const closeIntent = useRef(void 0);
48
+ const committedOptimistic = useRef(optimistic);
49
+ useInsertionEffect(() => {
50
+ committedOptimistic.current = optimistic;
51
+ });
52
+ const generation = useRef(0);
53
+ const openGeneration = useCallback(() => generation.current, []);
54
+ const nextOpenGeneration = useCallback(() => {
55
+ generation.current++;
56
+ }, []);
57
+ const recordCloseIntent = useCallback((intent) => {
58
+ closeIntent.current = intent;
59
+ if (intent !== void 0) clearLater(closeIntent, intent, popupRef);
60
+ }, []);
61
+ const takeCloseIntent = useCallback(() => {
62
+ const intent = closeIntent.current;
63
+ closeIntent.current = void 0;
64
+ return intent;
65
+ }, []);
66
+ const intended = () => latestInFlight()?.next ?? committedOptimistic.current;
67
+ const buildDetails = (event, reason) => details !== void 0 ? details(event, reason) : createActionDetails(event, { reason });
68
+ const send = (next, event, reason) => {
69
+ const built = buildDetails(event, reason);
70
+ if (next) nextOpenGeneration();
71
+ onDispatch?.(next, built);
72
+ dispatch(next, built);
73
+ };
74
+ const requestOpen = (event, reason) => {
75
+ if (!isLibrary || intended()) return;
76
+ send(true, event, reason);
77
+ };
78
+ const requestClose = (event, reason) => {
79
+ if (!isLibrary || !intended()) return;
80
+ send(false, event, reason);
81
+ };
82
+ const notifyClosed = (event, reason) => {
83
+ if (!isLibrary || !intended()) return;
84
+ send(false, event, reason);
85
+ };
86
+ return {
87
+ mode,
88
+ ids: {
89
+ popup: id,
90
+ title: `${id}-title`,
91
+ description: `${id}-description`
92
+ },
93
+ committed: isLibrary && committed,
94
+ optimistic: isLibrary && optimistic,
95
+ pending: isLibrary && pending,
96
+ intended,
97
+ openGeneration,
98
+ nextOpenGeneration,
99
+ requestOpen,
100
+ requestClose,
101
+ notifyClosed,
102
+ latestInFlight,
103
+ triggerRef,
104
+ popupRef,
105
+ recordCloseIntent,
106
+ takeCloseIntent
107
+ };
108
+ }
109
+ //#endregion
110
+ export { usePopoverRoot };
111
+
112
+ //# sourceMappingURL=use-popover-root.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-popover-root.mjs","names":[],"sources":["../../src/internal/use-popover-root.ts"],"sourcesContent":["\"use client\";\nimport { useCallback, useId, useInsertionEffect, useRef, useState } from \"react\";\nimport type { RefObject } from \"react\";\nimport { createActionDetails } from \"./action-details.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\";\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 PopoverMode = \"static\" | \"library\";\n\n/**\n * What caused the next close, recorded just before it happens (design 2.3). The `toggle` event\n * carries no source; without an intent a close is a `\"dismiss\"`.\n */\nexport interface PopoverCloseIntent {\n readonly reason: ChangeReason;\n readonly event: Event | undefined;\n}\n\n/** The `details` every popover-like `openChangeAction` receives. */\nexport interface PopoverLikeDetails extends ActionDetails {\n readonly reason: ChangeReason;\n}\n\n/**\n * The Root's state and machinery, shared by Popover and Menu (design 14). The component puts it\n * in its own context; `usePopoverTrigger` and `usePopoverPopup` take it as their first argument.\n */\nexport interface PopoverRootValue {\n readonly mode: PopoverMode;\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 /** 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: (event: Event | undefined, reason: ChangeReason) => 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: (event: Event | undefined, reason: ChangeReason) => 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()`. */\n readonly popupRef: RefObject<HTMLElement | null>;\n /** Record what causes the next close. Cleared after a task if the popover did not close. */\n readonly recordCloseIntent: (intent: PopoverCloseIntent | undefined) => void;\n /** Read and clear the recorded intent (the Popup's `toggle` listener). */\n readonly takeCloseIntent: () => PopoverCloseIntent | undefined;\n}\n\nexport interface UsePopoverRootOptions<Details extends PopoverLikeDetails> {\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 * Builds the `details` of a dispatch. Default: `createActionDetails(event, { reason })`. A\n * component with more fields (Menu) passes its own.\n */\n readonly details?: (event: Event | undefined, reason: ChangeReason) => Details;\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}\n\nfunction isPopoverOpen(element: Element | null): boolean {\n if (element === null) return false;\n try {\n return element.matches(\":popover-open\");\n } catch {\n return false;\n }\n}\n\n/** How long a recorded close intent survives when the popover did not close (design 2.3). */\nfunction clearLater(\n intentRef: { current: PopoverCloseIntent | undefined },\n intent: PopoverCloseIntent,\n popupRef: { current: HTMLElement | null },\n): void {\n setTimeout(() => {\n // Closed: its `toggle` event (queued as a task) consumes the intent. Still open: the close\n // was cancelled or invalid, so the intent is stale.\n if (intentRef.current === intent && isPopoverOpen(popupRef.current)) {\n intentRef.current = undefined;\n }\n }, 0);\n}\n\n/**\n * The Root of a popover-like component without its public props (design 14.1): mode detection\n * (once, from the first render), `useControllableAction<boolean>`, ids, refs, close intents and\n * the intent-aware `requestOpen` / `requestClose` / `notifyClosed`.\n */\nexport function usePopoverRoot<Details extends PopoverLikeDetails>(\n options: UsePopoverRootOptions<Details>,\n): PopoverRootValue {\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<PopoverMode>(isLibraryNow ? \"library\" : \"static\");\n const isLibrary = mode === \"library\";\n useDevWarning(\n isLibrary !== isLibraryNow,\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<HTMLElement | null>(null);\n const closeIntent = useRef<PopoverCloseIntent | 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 = useRef(optimistic);\n useInsertionEffect(() => {\n committedOptimistic.current = optimistic;\n });\n const generation = useRef(0);\n const openGeneration = useCallback(() => generation.current, []);\n const nextOpenGeneration = useCallback(() => {\n generation.current++;\n }, []);\n\n const recordCloseIntent = useCallback((intent: PopoverCloseIntent | undefined) => {\n closeIntent.current = intent;\n if (intent !== undefined) clearLater(closeIntent, intent, popupRef);\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 = (): boolean => latestInFlight()?.next ?? committedOptimistic.current;\n\n const buildDetails = (event: Event | undefined, reason: ChangeReason): Details =>\n details !== undefined\n ? details(event, reason)\n : (createActionDetails(event, { reason }) as unknown as Details);\n\n const send = (next: boolean, event: Event | undefined, reason: ChangeReason): void => {\n const built = buildDetails(event, reason);\n if (next) nextOpenGeneration();\n onDispatch?.(next, built);\n dispatch(next, built);\n };\n\n const requestOpen = (event: Event | undefined, reason: ChangeReason): void => {\n if (!isLibrary || intended()) return;\n send(true, event, reason);\n };\n\n const requestClose = (event: Event | undefined, reason: ChangeReason): void => {\n if (!isLibrary || !intended()) return;\n send(false, event, reason);\n };\n\n // Same guard as `requestClose`; a separate name because the callers mean different things.\n const notifyClosed = (event: Event | undefined, reason: ChangeReason): void => {\n if (!isLibrary || !intended()) return;\n send(false, event, reason);\n };\n\n // Not memoised: `dispatch` is a new function on every render (as Dialog), so parts re-render\n // with the Root, which they do anyway when its state changes.\n return {\n mode,\n ids: { popup: id, title: `${id}-title`, description: `${id}-description` },\n committed: isLibrary && committed,\n optimistic: isLibrary && optimistic,\n pending: isLibrary && pending,\n intended,\n openGeneration,\n nextOpenGeneration,\n requestOpen,\n requestClose,\n notifyCl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r.mjs";
3
+ import { rendersButton } from "./use-render.mjs";
4
+ import { useCallback } from "react";
5
+ //#region src/internal/use-popover-trigger.ts
6
+ const isDev = process.env.NODE_ENV !== "production";
7
+ function isPopoverOpen(element) {
8
+ if (element === null) return false;
9
+ try {
10
+ return element.matches(":popover-open");
11
+ } catch {
12
+ return false;
13
+ }
14
+ }
15
+ /**
16
+ * The Trigger of a popover-like component (design/components/popover.md 14.3):
17
+ * `button[commandfor][command="toggle-popover"]` with `aria-expanded`. In JS-free mode the
18
+ * browser runs the command and the Popup keeps `aria-expanded` current on the element. In library
19
+ * mode the click is cancelled (so the command does not run) and toggles against what the user
20
+ * already intends: an open through `requestOpen`, a library-owned close through `requestClose`.
21
+ *
22
+ * Menu adds `aria-haspopup="menu"` and its own key handling on top.
23
+ */
24
+ function usePopoverTrigger(ctx, options) {
25
+ const { part, disabled, render, handlers, activate, disabledAs = "native" } = options;
26
+ const isLibrary = ctx.mode === "library";
27
+ const { ids, triggerRef, popupRef } = ctx;
28
+ const state = {
29
+ open: ctx.optimistic,
30
+ pending: ctx.pending,
31
+ disabled
32
+ };
33
+ const ref = useCallback((element) => {
34
+ if (isDev && !isLibrary && element.tagName !== "BUTTON") console.error(`${part}: rendered a <${element.tagName.toLowerCase()}> 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}\`).`);
35
+ triggerRef.current = element;
36
+ if (!isLibrary && popupRef.current !== null) element.setAttribute("aria-expanded", String(isPopoverOpen(popupRef.current)));
37
+ return () => {
38
+ if (triggerRef.current === element) triggerRef.current = null;
39
+ };
40
+ }, [
41
+ isLibrary,
42
+ part,
43
+ triggerRef,
44
+ popupRef
45
+ ]);
46
+ const onClick = (event) => {
47
+ event.preventDefault();
48
+ if (disabled) return;
49
+ if (activate !== void 0) {
50
+ activate(event);
51
+ return;
52
+ }
53
+ const native = event.nativeEvent;
54
+ if (ctx.intended()) ctx.requestClose(native, "activate");
55
+ else ctx.requestOpen(native, "activate");
56
+ };
57
+ const merged = { ...handlers };
58
+ if (isLibrary) {
59
+ const extra = handlers?.onClick;
60
+ merged.onClick = extra === void 0 ? onClick : (event) => {
61
+ extra(event);
62
+ onClick(event);
63
+ };
64
+ }
65
+ const ariaDisabled = disabledAs === "aria";
66
+ return {
67
+ state,
68
+ libraryProps: {
69
+ ...rendersButton(render) && { type: "button" },
70
+ disabled: ariaDisabled ? void 0 : disabled,
71
+ ...ariaDisabled && { "aria-disabled": disabled ? true : void 0 },
72
+ commandfor: ids.popup,
73
+ command: "toggle-popover",
74
+ "aria-expanded": isLibrary ? state.open : false,
75
+ ...merged,
76
+ "data-open": dataAttr(state.open),
77
+ "data-pending": dataAttr(state.pending),
78
+ "data-disabled": dataAttr((isLibrary || ariaDisabled) && disabled)
79
+ },
80
+ ref
81
+ };
82
+ }
83
+ //#endregion
84
+ export { usePopoverTrigger };
85
+
86
+ //# sourceMappingURL=use-popover-trigger.mjs.map
@@ -0,0 +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 type { RenderProp } from \"./types.js\";\nimport { rendersButton } from \"./use-render.js\";\nimport type { DataAttributes } from \"./use-render.js\";\nimport type { PopoverRootValue } from \"./use-popover-root.js\";\n\nexport interface PopoverTriggerHookState {\n /** Optimistic open state (library mode); `false` in JS-free mode. */\n readonly open: boolean;\n /** The Root's transition is pending (an open, a part-initiated close or a 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\" | \"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 * How `disabled` is rendered. `\"native\"` (default): the `disabled` attribute, so the button is\n * no invoker at all. `\"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\nconst isDev = process.env.NODE_ENV !== \"production\";\n\nfunction isPopoverOpen(element: Element | null): boolean {\n if (element === null) return false;\n try {\n return element.matches(\":popover-open\");\n } catch {\n return false;\n }\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 *\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, 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 ref = useCallback(\n (element: HTMLElement) => {\n if (isDev && !isLibrary && element.tagName !== \"BUTTON\") {\n console.error(\n `${part}: rendered a <${element.tagName.toLowerCase()}> in JS-free mode. Only a ` +\n '<button> runs `command=\"toggle-popover\"`; this trigger will not open the popover. ' +\n \"Render a <button>, or put the component in library mode (`defaultOpen={false}`).\",\n );\n }\n triggerRef.current = element;\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 () => {\n if (triggerRef.current === element) triggerRef.current = null;\n };\n },\n [isLibrary, part, triggerRef, popupRef],\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 const ariaDisabled = disabledAs === \"aria\";\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). With `disabledAs: \"aria\"` it is owned as absent.\n disabled: ariaDisabled ? undefined : disabled,\n ...(ariaDisabled && { \"aria-disabled\": disabled ? true : undefined }),\n commandfor: ids.popup,\n command: \"toggle-popover\",\n // Library mode: optimistic. JS-free mode: \"false\" in React; the Popup's `toggle` listener\n // writes the DOM value, and React never rewrites an unchanged prop.\n \"aria-expanded\": isLibrary ? state.open : false,\n ...merged,\n \"data-open\": dataAttr(state.open),\n \"data-pending\": dataAttr(state.pending),\n \"data-disabled\": dataAttr((isLibrary || ariaDisabled) && disabled),\n };\n\n return { state, libraryProps, ref };\n}\n"],"mappings":";;;;;AAuDA,MAAM,QAAQ,QAAQ,IAAI,aAAa;AAEvC,SAAS,cAAc,SAAkC;CACvD,IAAI,YAAY,MAAM,OAAO;CAC7B,IAAI;EACF,OAAO,QAAQ,QAAQ,eAAe;CACxC,QAAQ;EACN,OAAO;CACT;AACF;;;;;;;;;;AAWA,SAAgB,kBACd,KACA,SACoB;CACpB,MAAM,EAAE,MAAM,UAAU,QAAQ,UAAU,UAAU,aAAa,aAAa;CAC9E,MAAM,YAAY,IAAI,SAAS;CAC/B,MAAM,EAAE,KAAK,YAAY,aAAa;CAEtC,MAAM,QAAiC;EACrC,MAAM,IAAI;EAEV,SAAS,IAAI;EACb;CACF;CAEA,MAAM,MAAM,aACT,YAAyB;EACxB,IAAI,SAAS,CAAC,aAAa,QAAQ,YAAY,UAC7C,QAAQ,MACN,GAAG,KAAK,gBAAgB,QAAQ,QAAQ,YAAY,EAAE,iMAGxD;EAEF,WAAW,UAAU;EAGrB,IAAI,CAAC,aAAa,SAAS,YAAY,MACrC,QAAQ,aAAa,iBAAiB,OAAO,cAAc,SAAS,OAAO,CAAC,CAAC;EAE/E,aAAa;GACX,IAAI,WAAW,YAAY,SAAS,WAAW,UAAU;EAC3D;CACF,GACA;EAAC;EAAW;EAAM;EAAY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