@bigbinary/neeto-atoms 1.0.97 → 1.0.99

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 (331) hide show
  1. package/dist/{Alert-CQ7lMpGp.js → Alert-CydF7eEs.js} +9 -31
  2. package/dist/Alert-CydF7eEs.js.map +1 -0
  3. package/dist/{Combobox-CKR_H-QS.js → Combobox-DriZMj4f.js} +300 -5017
  4. package/dist/Combobox-DriZMj4f.js.map +1 -0
  5. package/dist/{Dialog-BOcBeB8v.js → Dialog-D8C0-nEo.js} +10 -31
  6. package/dist/Dialog-D8C0-nEo.js.map +1 -0
  7. package/dist/DialogTrigger-a3diAOif.js +992 -0
  8. package/dist/DialogTrigger-a3diAOif.js.map +1 -0
  9. package/dist/{Select-Bc0D3byr.js → Select-Dng-cXLj.js} +2 -2
  10. package/dist/{Select-Bc0D3byr.js.map → Select-Dng-cXLj.js.map} +1 -1
  11. package/dist/{Sheet-Bw8GVQPS.js → Sheet-D1MWtg1q.js} +9 -33
  12. package/dist/Sheet-D1MWtg1q.js.map +1 -0
  13. package/dist/{button-CrEMzWKw.js → button-CePY5zne.js} +2 -2
  14. package/dist/button-CePY5zne.js.map +1 -0
  15. package/dist/cjs/{Alert-CxctOMOk.js → Alert-BdZVGiON.js} +9 -31
  16. package/dist/cjs/Alert-BdZVGiON.js.map +1 -0
  17. package/dist/cjs/Combobox-BE8LT4yq.js +5501 -0
  18. package/dist/cjs/Combobox-BE8LT4yq.js.map +1 -0
  19. package/dist/cjs/{Dialog-CBSuKeu_.js → Dialog-DNv7j7ts.js} +10 -31
  20. package/dist/cjs/Dialog-DNv7j7ts.js.map +1 -0
  21. package/dist/cjs/DialogTrigger-B0Q6yIrx.js +1026 -0
  22. package/dist/cjs/DialogTrigger-B0Q6yIrx.js.map +1 -0
  23. package/dist/cjs/{Select-DVDECeJb.js → Select-gItId3pj.js} +2 -2
  24. package/dist/cjs/{Select-DVDECeJb.js.map → Select-gItId3pj.js.map} +1 -1
  25. package/dist/cjs/{Sheet-By1W1pFD.js → Sheet-D-NWMprq.js} +9 -33
  26. package/dist/cjs/Sheet-D-NWMprq.js.map +1 -0
  27. package/dist/cjs/{button-CMl9rLXi.js → button-CSBhDSDJ.js} +2 -2
  28. package/dist/cjs/button-CSBhDSDJ.js.map +1 -0
  29. package/dist/cjs/components/Alert.js +22 -18
  30. package/dist/cjs/components/Alert.js.map +1 -1
  31. package/dist/cjs/components/Avatar.js +4 -3
  32. package/dist/cjs/components/Avatar.js.map +1 -1
  33. package/dist/cjs/components/Button.js +5 -4
  34. package/dist/cjs/components/Button.js.map +1 -1
  35. package/dist/cjs/components/Checkbox.js +5 -4
  36. package/dist/cjs/components/Checkbox.js.map +1 -1
  37. package/dist/cjs/components/ColorPicker.js +4 -3
  38. package/dist/cjs/components/ColorPicker.js.map +1 -1
  39. package/dist/cjs/components/DataTable.js +6 -5
  40. package/dist/cjs/components/DataTable.js.map +1 -1
  41. package/dist/cjs/components/DatePicker.js +5 -4
  42. package/dist/cjs/components/DatePicker.js.map +1 -1
  43. package/dist/cjs/components/Dialog.js +10 -16
  44. package/dist/cjs/components/Dialog.js.map +1 -1
  45. package/dist/cjs/components/DropdownMenu.js +6 -5
  46. package/dist/cjs/components/DropdownMenu.js.map +1 -1
  47. package/dist/cjs/components/Empty.js +5 -4
  48. package/dist/cjs/components/Empty.js.map +1 -1
  49. package/dist/cjs/components/Input.js +6 -5
  50. package/dist/cjs/components/Input.js.map +1 -1
  51. package/dist/cjs/components/Kbd.js +4 -3
  52. package/dist/cjs/components/Kbd.js.map +1 -1
  53. package/dist/cjs/components/Label.js +5 -4
  54. package/dist/cjs/components/Label.js.map +1 -1
  55. package/dist/cjs/components/MultiEmailInput.js +5 -4
  56. package/dist/cjs/components/MultiEmailInput.js.map +1 -1
  57. package/dist/cjs/components/Pagination.js +1 -1
  58. package/dist/cjs/components/Popover.js +3 -2
  59. package/dist/cjs/components/Popover.js.map +1 -1
  60. package/dist/cjs/components/RadioGroup.js +5 -4
  61. package/dist/cjs/components/RadioGroup.js.map +1 -1
  62. package/dist/cjs/components/Select.js +9 -7
  63. package/dist/cjs/components/Select.js.map +1 -1
  64. package/dist/cjs/components/Sheet.js +10 -16
  65. package/dist/cjs/components/Sheet.js.map +1 -1
  66. package/dist/cjs/components/Slider.js +5 -4
  67. package/dist/cjs/components/Slider.js.map +1 -1
  68. package/dist/cjs/components/Switch.js +5 -4
  69. package/dist/cjs/components/Switch.js.map +1 -1
  70. package/dist/cjs/components/Textarea.js +5 -4
  71. package/dist/cjs/components/Textarea.js.map +1 -1
  72. package/dist/cjs/components/TimePicker.js +5 -4
  73. package/dist/cjs/components/TimePicker.js.map +1 -1
  74. package/dist/cjs/components/Tooltip.js +4 -3
  75. package/dist/cjs/components/Tooltip.js.map +1 -1
  76. package/dist/cjs/components/TreeSelect.js +5 -4
  77. package/dist/cjs/components/TreeSelect.js.map +1 -1
  78. package/dist/cjs/components/index.js +18 -16
  79. package/dist/cjs/components/index.js.map +1 -1
  80. package/dist/cjs/{dialog-Cs1qH5xA.js → dialog-CGblgaX5.js} +34 -40
  81. package/dist/cjs/dialog-CGblgaX5.js.map +1 -0
  82. package/dist/cjs/{floating-ui.react-dom-B4Aw6O7R.js → floating-ui.react-dom--alWUjS1.js} +147 -463
  83. package/dist/cjs/floating-ui.react-dom--alWUjS1.js.map +1 -0
  84. package/dist/cjs/floating-ui.utils.dom-BGEmL7pd.js +339 -0
  85. package/dist/cjs/floating-ui.utils.dom-BGEmL7pd.js.map +1 -0
  86. package/dist/cjs/formik/ActionBlock.js +5 -4
  87. package/dist/cjs/formik/ActionBlock.js.map +1 -1
  88. package/dist/cjs/formik/BlockNavigation.js +23 -19
  89. package/dist/cjs/formik/BlockNavigation.js.map +1 -1
  90. package/dist/cjs/formik/Button.js +5 -4
  91. package/dist/cjs/formik/Button.js.map +1 -1
  92. package/dist/cjs/formik/Checkbox.js +5 -4
  93. package/dist/cjs/formik/Checkbox.js.map +1 -1
  94. package/dist/cjs/formik/Input.js +6 -5
  95. package/dist/cjs/formik/Input.js.map +1 -1
  96. package/dist/cjs/formik/MultiEmailInput.js +5 -4
  97. package/dist/cjs/formik/MultiEmailInput.js.map +1 -1
  98. package/dist/cjs/formik/RadioGroup.js +5 -4
  99. package/dist/cjs/formik/RadioGroup.js.map +1 -1
  100. package/dist/cjs/formik/Select.js +9 -7
  101. package/dist/cjs/formik/Select.js.map +1 -1
  102. package/dist/cjs/formik/Slider.js +5 -4
  103. package/dist/cjs/formik/Slider.js.map +1 -1
  104. package/dist/cjs/formik/Switch.js +5 -4
  105. package/dist/cjs/formik/Switch.js.map +1 -1
  106. package/dist/cjs/formik/Textarea.js +5 -4
  107. package/dist/cjs/formik/Textarea.js.map +1 -1
  108. package/dist/cjs/formik/TreeSelect.js +5 -4
  109. package/dist/cjs/formik/TreeSelect.js.map +1 -1
  110. package/dist/cjs/formik/index.js +12 -10
  111. package/dist/cjs/formik/index.js.map +1 -1
  112. package/dist/cjs/{index-DbA93GP3.js → index-CMFCdiR6.js} +2 -2
  113. package/dist/cjs/{index-DbA93GP3.js.map → index-CMFCdiR6.js.map} +1 -1
  114. package/dist/cjs/{index-BTsnrFFc.js → index-DdQaz0iQ.js} +31 -33
  115. package/dist/cjs/{index-BTsnrFFc.js.map → index-DdQaz0iQ.js.map} +1 -1
  116. package/dist/cjs/{index-C9ICrOhM.js → index-owSUsE-n.js} +2 -2
  117. package/dist/cjs/{index-C9ICrOhM.js.map → index-owSUsE-n.js.map} +1 -1
  118. package/dist/cjs/index.js +18 -16
  119. package/dist/cjs/index.js.map +1 -1
  120. package/dist/cjs/{input-group-BdQoKm0i.js → input-group-DZ-c2jRZ.js} +2 -2
  121. package/dist/cjs/{input-group-BdQoKm0i.js.map → input-group-DZ-c2jRZ.js.map} +1 -1
  122. package/dist/cjs/primitives/AlertDialog.js +112 -188
  123. package/dist/cjs/primitives/AlertDialog.js.map +1 -1
  124. package/dist/cjs/primitives/Button.js +1 -2
  125. package/dist/cjs/primitives/Button.js.map +1 -1
  126. package/dist/cjs/primitives/Calendar.js +1 -1
  127. package/dist/cjs/primitives/Carousel.js +1 -1
  128. package/dist/cjs/primitives/Combobox.js +6 -4
  129. package/dist/cjs/primitives/Combobox.js.map +1 -1
  130. package/dist/cjs/primitives/Command.js +19 -5
  131. package/dist/cjs/primitives/Command.js.map +1 -1
  132. package/dist/cjs/primitives/ContextMenu.js +4 -3
  133. package/dist/cjs/primitives/ContextMenu.js.map +1 -1
  134. package/dist/cjs/primitives/Dialog.js +48 -44
  135. package/dist/cjs/primitives/Dialog.js.map +1 -1
  136. package/dist/cjs/primitives/Drawer.js +2 -2
  137. package/dist/cjs/primitives/Drawer.js.map +1 -1
  138. package/dist/cjs/primitives/DropdownMenu.js +20 -13
  139. package/dist/cjs/primitives/DropdownMenu.js.map +1 -1
  140. package/dist/cjs/primitives/Field.js +5 -4
  141. package/dist/cjs/primitives/Field.js.map +1 -1
  142. package/dist/cjs/primitives/HoverCard.js +3 -2
  143. package/dist/cjs/primitives/HoverCard.js.map +1 -1
  144. package/dist/cjs/primitives/InputGroup.js +2 -2
  145. package/dist/cjs/primitives/Menubar.js +4 -3
  146. package/dist/cjs/primitives/Menubar.js.map +1 -1
  147. package/dist/cjs/primitives/Pagination.js +1 -1
  148. package/dist/cjs/primitives/Popover.js +3 -2
  149. package/dist/cjs/primitives/Popover.js.map +1 -1
  150. package/dist/cjs/primitives/Select.js +3 -2
  151. package/dist/cjs/primitives/Select.js.map +1 -1
  152. package/dist/cjs/primitives/Sheet.js +68 -62
  153. package/dist/cjs/primitives/Sheet.js.map +1 -1
  154. package/dist/cjs/primitives/Sidebar.js +15 -11
  155. package/dist/cjs/primitives/Sidebar.js.map +1 -1
  156. package/dist/cjs/primitives/Tooltip.js +4 -3
  157. package/dist/cjs/primitives/Tooltip.js.map +1 -1
  158. package/dist/cjs/primitives/index.js +18 -15
  159. package/dist/cjs/primitives/index.js.map +1 -1
  160. package/dist/cjs/sheet-BMQ9juND.js +138 -0
  161. package/dist/cjs/sheet-BMQ9juND.js.map +1 -0
  162. package/dist/cjs/{tooltip-BYCcUMZn.js → tooltip-hM8gc5L8.js} +2 -2
  163. package/dist/cjs/{tooltip-BYCcUMZn.js.map → tooltip-hM8gc5L8.js.map} +1 -1
  164. package/dist/cjs/useOpenInteractionType-D4z6FTrA.js +4877 -0
  165. package/dist/cjs/useOpenInteractionType-D4z6FTrA.js.map +1 -0
  166. package/dist/components/Alert.js +22 -18
  167. package/dist/components/Alert.js.map +1 -1
  168. package/dist/components/Avatar.js +4 -3
  169. package/dist/components/Avatar.js.map +1 -1
  170. package/dist/components/Button.js +5 -4
  171. package/dist/components/Button.js.map +1 -1
  172. package/dist/components/Checkbox.js +5 -4
  173. package/dist/components/Checkbox.js.map +1 -1
  174. package/dist/components/ColorPicker.js +4 -3
  175. package/dist/components/ColorPicker.js.map +1 -1
  176. package/dist/components/DataTable.js +6 -5
  177. package/dist/components/DataTable.js.map +1 -1
  178. package/dist/components/DatePicker.js +5 -4
  179. package/dist/components/DatePicker.js.map +1 -1
  180. package/dist/components/Dialog/Dialog.d.ts +1 -1
  181. package/dist/components/Dialog.js +10 -16
  182. package/dist/components/Dialog.js.map +1 -1
  183. package/dist/components/DropdownMenu.js +6 -5
  184. package/dist/components/DropdownMenu.js.map +1 -1
  185. package/dist/components/Empty.js +5 -4
  186. package/dist/components/Empty.js.map +1 -1
  187. package/dist/components/Input.js +6 -5
  188. package/dist/components/Input.js.map +1 -1
  189. package/dist/components/Kbd.js +4 -3
  190. package/dist/components/Kbd.js.map +1 -1
  191. package/dist/components/Label.js +5 -4
  192. package/dist/components/Label.js.map +1 -1
  193. package/dist/components/MultiEmailInput.js +5 -4
  194. package/dist/components/MultiEmailInput.js.map +1 -1
  195. package/dist/components/Pagination.js +1 -1
  196. package/dist/components/Popover.js +3 -2
  197. package/dist/components/Popover.js.map +1 -1
  198. package/dist/components/RadioGroup.js +5 -4
  199. package/dist/components/RadioGroup.js.map +1 -1
  200. package/dist/components/Select.js +9 -7
  201. package/dist/components/Select.js.map +1 -1
  202. package/dist/components/Sheet/Sheet.d.ts +2 -2
  203. package/dist/components/Sheet.js +10 -16
  204. package/dist/components/Sheet.js.map +1 -1
  205. package/dist/components/Slider.js +5 -4
  206. package/dist/components/Slider.js.map +1 -1
  207. package/dist/components/Switch.js +5 -4
  208. package/dist/components/Switch.js.map +1 -1
  209. package/dist/components/Textarea.js +5 -4
  210. package/dist/components/Textarea.js.map +1 -1
  211. package/dist/components/TimePicker.js +5 -4
  212. package/dist/components/TimePicker.js.map +1 -1
  213. package/dist/components/Tooltip.js +4 -3
  214. package/dist/components/Tooltip.js.map +1 -1
  215. package/dist/components/TreeSelect.js +5 -4
  216. package/dist/components/TreeSelect.js.map +1 -1
  217. package/dist/components/index.js +18 -16
  218. package/dist/components/index.js.map +1 -1
  219. package/dist/{dialog-BVHqPY9y.js → dialog-CqXuhXNS.js} +34 -40
  220. package/dist/dialog-CqXuhXNS.js.map +1 -0
  221. package/dist/{floating-ui.react-dom-D8_f_WWh.js → floating-ui.react-dom-BtFUJRfb.js} +3 -299
  222. package/dist/floating-ui.react-dom-BtFUJRfb.js.map +1 -0
  223. package/dist/floating-ui.utils.dom-Bw_Rc4bg.js +299 -0
  224. package/dist/floating-ui.utils.dom-Bw_Rc4bg.js.map +1 -0
  225. package/dist/formik/ActionBlock.js +5 -4
  226. package/dist/formik/ActionBlock.js.map +1 -1
  227. package/dist/formik/BlockNavigation.js +23 -19
  228. package/dist/formik/BlockNavigation.js.map +1 -1
  229. package/dist/formik/Button.js +5 -4
  230. package/dist/formik/Button.js.map +1 -1
  231. package/dist/formik/Checkbox.js +5 -4
  232. package/dist/formik/Checkbox.js.map +1 -1
  233. package/dist/formik/Input.js +6 -5
  234. package/dist/formik/Input.js.map +1 -1
  235. package/dist/formik/MultiEmailInput.js +5 -4
  236. package/dist/formik/MultiEmailInput.js.map +1 -1
  237. package/dist/formik/RadioGroup.js +5 -4
  238. package/dist/formik/RadioGroup.js.map +1 -1
  239. package/dist/formik/Select.js +9 -7
  240. package/dist/formik/Select.js.map +1 -1
  241. package/dist/formik/Slider.js +5 -4
  242. package/dist/formik/Slider.js.map +1 -1
  243. package/dist/formik/Switch.js +5 -4
  244. package/dist/formik/Switch.js.map +1 -1
  245. package/dist/formik/Textarea.js +5 -4
  246. package/dist/formik/Textarea.js.map +1 -1
  247. package/dist/formik/TreeSelect.js +5 -4
  248. package/dist/formik/TreeSelect.js.map +1 -1
  249. package/dist/formik/index.js +12 -10
  250. package/dist/formik/index.js.map +1 -1
  251. package/dist/{index-DnD7-4_R.js → index-BQtGUR27.js} +2 -2
  252. package/dist/{index-DnD7-4_R.js.map → index-BQtGUR27.js.map} +1 -1
  253. package/dist/{index-GJ3FauH8.js → index-CLV7U7i7.js} +4 -4
  254. package/dist/{index-GJ3FauH8.js.map → index-CLV7U7i7.js.map} +1 -1
  255. package/dist/{index-C3hByjk3.js → index-XvwNqU74.js} +2 -2
  256. package/dist/{index-C3hByjk3.js.map → index-XvwNqU74.js.map} +1 -1
  257. package/dist/index.js +18 -16
  258. package/dist/index.js.map +1 -1
  259. package/dist/{input-group-DDwp2ozP.js → input-group-DuITGkyB.js} +2 -2
  260. package/dist/{input-group-DDwp2ozP.js.map → input-group-DuITGkyB.js.map} +1 -1
  261. package/dist/primitives/AlertDialog.js +113 -189
  262. package/dist/primitives/AlertDialog.js.map +1 -1
  263. package/dist/primitives/Button.js +2 -3
  264. package/dist/primitives/Button.js.map +1 -1
  265. package/dist/primitives/Calendar.js +1 -1
  266. package/dist/primitives/Carousel.js +1 -1
  267. package/dist/primitives/Combobox.js +6 -4
  268. package/dist/primitives/Combobox.js.map +1 -1
  269. package/dist/primitives/Command.js +19 -5
  270. package/dist/primitives/Command.js.map +1 -1
  271. package/dist/primitives/ContextMenu.js +4 -3
  272. package/dist/primitives/ContextMenu.js.map +1 -1
  273. package/dist/primitives/Dialog.d.ts +6 -4
  274. package/dist/primitives/Dialog.js +49 -45
  275. package/dist/primitives/Dialog.js.map +1 -1
  276. package/dist/primitives/Drawer.js +2 -2
  277. package/dist/primitives/Drawer.js.map +1 -1
  278. package/dist/primitives/DropdownMenu.js +20 -13
  279. package/dist/primitives/DropdownMenu.js.map +1 -1
  280. package/dist/primitives/Field.js +5 -4
  281. package/dist/primitives/Field.js.map +1 -1
  282. package/dist/primitives/HoverCard.js +3 -2
  283. package/dist/primitives/HoverCard.js.map +1 -1
  284. package/dist/primitives/InputGroup.js +2 -2
  285. package/dist/primitives/Menubar.js +4 -3
  286. package/dist/primitives/Menubar.js.map +1 -1
  287. package/dist/primitives/Pagination.js +1 -1
  288. package/dist/primitives/Popover.js +3 -2
  289. package/dist/primitives/Popover.js.map +1 -1
  290. package/dist/primitives/Select.js +3 -2
  291. package/dist/primitives/Select.js.map +1 -1
  292. package/dist/primitives/Sheet.d.ts +5 -4
  293. package/dist/primitives/Sheet.js +68 -62
  294. package/dist/primitives/Sheet.js.map +1 -1
  295. package/dist/primitives/Sidebar.js +15 -11
  296. package/dist/primitives/Sidebar.js.map +1 -1
  297. package/dist/primitives/Tooltip.js +4 -3
  298. package/dist/primitives/Tooltip.js.map +1 -1
  299. package/dist/primitives/index.js +18 -15
  300. package/dist/primitives/index.js.map +1 -1
  301. package/dist/shadcn/components/alert-dialog.d.ts +8 -8
  302. package/dist/shadcn/components/command.d.ts +3 -1
  303. package/dist/shadcn/components/dialog.d.ts +10 -9
  304. package/dist/shadcn/components/dropdown-menu.d.ts +1 -1
  305. package/dist/shadcn/components/sheet.d.ts +7 -7
  306. package/dist/sheet-B9oDGvvX.js +129 -0
  307. package/dist/sheet-B9oDGvvX.js.map +1 -0
  308. package/dist/{tooltip-ChQ9xD1j.js → tooltip-0DecQ06t.js} +2 -2
  309. package/dist/{tooltip-ChQ9xD1j.js.map → tooltip-0DecQ06t.js.map} +1 -1
  310. package/dist/useOpenInteractionType-CVfxIsuz.js +4766 -0
  311. package/dist/useOpenInteractionType-CVfxIsuz.js.map +1 -0
  312. package/package.json +1 -1
  313. package/dist/Alert-CQ7lMpGp.js.map +0 -1
  314. package/dist/Combobox-CKR_H-QS.js.map +0 -1
  315. package/dist/Dialog-BOcBeB8v.js.map +0 -1
  316. package/dist/Sheet-Bw8GVQPS.js.map +0 -1
  317. package/dist/button-CrEMzWKw.js.map +0 -1
  318. package/dist/cjs/Alert-CxctOMOk.js.map +0 -1
  319. package/dist/cjs/Combobox-Dd2m0qal.js +0 -10218
  320. package/dist/cjs/Combobox-Dd2m0qal.js.map +0 -1
  321. package/dist/cjs/Dialog-CBSuKeu_.js.map +0 -1
  322. package/dist/cjs/Sheet-By1W1pFD.js.map +0 -1
  323. package/dist/cjs/button-CMl9rLXi.js.map +0 -1
  324. package/dist/cjs/dialog-Cs1qH5xA.js.map +0 -1
  325. package/dist/cjs/floating-ui.react-dom-B4Aw6O7R.js.map +0 -1
  326. package/dist/cjs/sheet-G6ismmAK.js +0 -147
  327. package/dist/cjs/sheet-G6ismmAK.js.map +0 -1
  328. package/dist/dialog-BVHqPY9y.js.map +0 -1
  329. package/dist/floating-ui.react-dom-D8_f_WWh.js.map +0 -1
  330. package/dist/sheet-DNANcGkk.js +0 -138
  331. package/dist/sheet-DNANcGkk.js.map +0 -1
@@ -0,0 +1,4877 @@
1
+ 'use strict';
2
+
3
+ var React = require('react');
4
+ var floatingUi_utils_dom = require('./floating-ui.utils.dom-BGEmL7pd.js');
5
+ var jsxRuntime = require('react/jsx-runtime');
6
+ var ReactDOM = require('react-dom');
7
+ var index = require('./index-DnKJmaCq.js');
8
+ var withSelector = require('./with-selector-DeKHbQY7.js');
9
+
10
+ function _interopNamespace(e) {
11
+ if (e && e.__esModule) return e;
12
+ var n = Object.create(null);
13
+ if (e) {
14
+ Object.keys(e).forEach(function (k) {
15
+ if (k !== 'default') {
16
+ var d = Object.getOwnPropertyDescriptor(e, k);
17
+ Object.defineProperty(n, k, d.get ? d : {
18
+ enumerable: true,
19
+ get: function () { return e[k]; }
20
+ });
21
+ }
22
+ });
23
+ }
24
+ n.default = e;
25
+ return Object.freeze(n);
26
+ }
27
+
28
+ var React__namespace = /*#__PURE__*/_interopNamespace(React);
29
+ var ReactDOM__namespace = /*#__PURE__*/_interopNamespace(ReactDOM);
30
+
31
+ /**
32
+ * Creates a formatErrorMessage function with a custom URL and prefix.
33
+ * @param baseUrl - The base URL for the error page (e.g., 'https://base-ui.com/production-error')
34
+ * @param prefix - The prefix for the error message (e.g., 'Base UI')
35
+ * @returns A function that formats error messages with the given URL and prefix
36
+ */
37
+ function createFormatErrorMessage(baseUrl, prefix) {
38
+ return function formatErrorMessage(code, ...args) {
39
+ const url = new URL(baseUrl);
40
+ url.searchParams.set('code', code.toString());
41
+ args.forEach(arg => url.searchParams.append('args[]', arg));
42
+ return `${prefix} error #${code}; visit ${url} for the full message.`;
43
+ };
44
+ }
45
+
46
+ /**
47
+ * WARNING: Don't import this directly. It's imported by the code generated by
48
+ * `@mui/internal-babel-plugin-minify-errors`. Make sure to always use string literals in `Error`
49
+ * constructors to ensure the plugin works as expected. Supported patterns include:
50
+ * throw new Error('My message');
51
+ * throw new Error(`My message: ${foo}`);
52
+ * throw new Error(`My message: ${foo}` + 'another string');
53
+ * ...
54
+ */
55
+ const formatErrorMessage = createFormatErrorMessage('https://base-ui.com/production-error', 'Base UI');
56
+
57
+ const UNINITIALIZED = {};
58
+
59
+ /**
60
+ * A React.useRef() that is initialized with a function. Note that it accepts an optional
61
+ * initialization argument, so the initialization function doesn't need to be an inline closure.
62
+ *
63
+ * @usage
64
+ * const ref = useRefWithInit(sortColumns, columns)
65
+ */
66
+
67
+ function useRefWithInit(init, initArg) {
68
+ const ref = React__namespace.useRef(UNINITIALIZED);
69
+ if (ref.current === UNINITIALIZED) {
70
+ ref.current = init(initArg);
71
+ }
72
+ return ref;
73
+ }
74
+
75
+ /**
76
+ * Merges refs into a single memoized callback ref or `null`.
77
+ * This makes sure multiple refs are updated together and have the same value.
78
+ *
79
+ * This function accepts up to four refs. If you need to merge more, or have an unspecified number of refs to merge,
80
+ * use `useMergedRefsN` instead.
81
+ */
82
+
83
+ function useMergedRefs(a, b, c, d) {
84
+ const forkRef = useRefWithInit(createForkRef).current;
85
+ if (didChange(forkRef, a, b, c, d)) {
86
+ update(forkRef, [a, b, c, d]);
87
+ }
88
+ return forkRef.callback;
89
+ }
90
+
91
+ /**
92
+ * Merges an array of refs into a single memoized callback ref or `null`.
93
+ *
94
+ * If you need to merge a fixed number (up to four) of refs, use `useMergedRefs` instead for better performance.
95
+ */
96
+ function useMergedRefsN(refs) {
97
+ const forkRef = useRefWithInit(createForkRef).current;
98
+ if (didChangeN(forkRef, refs)) {
99
+ update(forkRef, refs);
100
+ }
101
+ return forkRef.callback;
102
+ }
103
+ function createForkRef() {
104
+ return {
105
+ callback: null,
106
+ cleanup: null,
107
+ refs: []
108
+ };
109
+ }
110
+ function didChange(forkRef, a, b, c, d) {
111
+ // prettier-ignore
112
+ return forkRef.refs[0] !== a || forkRef.refs[1] !== b || forkRef.refs[2] !== c || forkRef.refs[3] !== d;
113
+ }
114
+ function didChangeN(forkRef, newRefs) {
115
+ return forkRef.refs.length !== newRefs.length || forkRef.refs.some((ref, index) => ref !== newRefs[index]);
116
+ }
117
+ function update(forkRef, refs) {
118
+ forkRef.refs = refs;
119
+ if (refs.every(ref => ref == null)) {
120
+ forkRef.callback = null;
121
+ return;
122
+ }
123
+ forkRef.callback = instance => {
124
+ if (forkRef.cleanup) {
125
+ forkRef.cleanup();
126
+ forkRef.cleanup = null;
127
+ }
128
+ if (instance != null) {
129
+ const cleanupCallbacks = Array(refs.length).fill(null);
130
+ for (let i = 0; i < refs.length; i += 1) {
131
+ const ref = refs[i];
132
+ if (ref == null) {
133
+ continue;
134
+ }
135
+ switch (typeof ref) {
136
+ case 'function':
137
+ {
138
+ const refCleanup = ref(instance);
139
+ if (typeof refCleanup === 'function') {
140
+ cleanupCallbacks[i] = refCleanup;
141
+ }
142
+ break;
143
+ }
144
+ case 'object':
145
+ {
146
+ ref.current = instance;
147
+ break;
148
+ }
149
+ }
150
+ }
151
+ forkRef.cleanup = () => {
152
+ for (let i = 0; i < refs.length; i += 1) {
153
+ const ref = refs[i];
154
+ if (ref == null) {
155
+ continue;
156
+ }
157
+ switch (typeof ref) {
158
+ case 'function':
159
+ {
160
+ const cleanupCallback = cleanupCallbacks[i];
161
+ if (typeof cleanupCallback === 'function') {
162
+ cleanupCallback();
163
+ } else {
164
+ ref(null);
165
+ }
166
+ break;
167
+ }
168
+ case 'object':
169
+ {
170
+ ref.current = null;
171
+ break;
172
+ }
173
+ }
174
+ }
175
+ };
176
+ }
177
+ };
178
+ }
179
+
180
+ const majorVersion = parseInt(React__namespace.version, 10);
181
+ function isReactVersionAtLeast(reactVersionToCheck) {
182
+ return majorVersion >= reactVersionToCheck;
183
+ }
184
+
185
+ /**
186
+ * Extracts the `ref` from a React element, handling different React versions.
187
+ */
188
+ function getReactElementRef(element) {
189
+ if (! /*#__PURE__*/React__namespace.isValidElement(element)) {
190
+ return null;
191
+ }
192
+ const reactElement = element;
193
+ const propsWithRef = reactElement.props;
194
+ return (isReactVersionAtLeast(19) ? propsWithRef?.ref : reactElement.ref) ?? null;
195
+ }
196
+
197
+ function mergeObjects(a, b) {
198
+ if (a && !b) {
199
+ return a;
200
+ }
201
+ if (!a && b) {
202
+ return b;
203
+ }
204
+ if (a || b) {
205
+ return {
206
+ ...a,
207
+ ...b
208
+ };
209
+ }
210
+ return undefined;
211
+ }
212
+
213
+ function getStateAttributesProps(state, customMapping) {
214
+ const props = {};
215
+
216
+ /* eslint-disable-next-line guard-for-in */
217
+ for (const key in state) {
218
+ const value = state[key];
219
+ if (customMapping?.hasOwnProperty(key)) {
220
+ const customProps = customMapping[key](value);
221
+ if (customProps != null) {
222
+ Object.assign(props, customProps);
223
+ }
224
+ continue;
225
+ }
226
+ if (value === true) {
227
+ props[`data-${key.toLowerCase()}`] = '';
228
+ } else if (value) {
229
+ props[`data-${key.toLowerCase()}`] = value.toString();
230
+ }
231
+ }
232
+ return props;
233
+ }
234
+
235
+ /**
236
+ * If the provided className is a string, it will be returned as is.
237
+ * Otherwise, the function will call the className function with the state as the first argument.
238
+ *
239
+ * @param className
240
+ * @param state
241
+ */
242
+ function resolveClassName(className, state) {
243
+ return typeof className === 'function' ? className(state) : className;
244
+ }
245
+
246
+ /**
247
+ * If the provided style is an object, it will be returned as is.
248
+ * Otherwise, the function will call the style function with the state as the first argument.
249
+ *
250
+ * @param style
251
+ * @param state
252
+ */
253
+ function resolveStyle(style, state) {
254
+ return typeof style === 'function' ? style(state) : style;
255
+ }
256
+
257
+ const EMPTY_PROPS = {};
258
+
259
+ /* eslint-disable id-denylist */
260
+ /**
261
+ * Merges multiple sets of React props. It follows the Object.assign pattern where the rightmost object's fields overwrite
262
+ * the conflicting ones from others. This doesn't apply to event handlers, `className` and `style` props.
263
+ *
264
+ * Event handlers are merged and called in right-to-left order (rightmost handler executes first, leftmost last).
265
+ * For React synthetic events, the rightmost handler can prevent prior (left-positioned) handlers from executing
266
+ * by calling `event.preventBaseUIHandler()`. For non-synthetic events (custom events with primitive/object values),
267
+ * all handlers always execute without prevention capability.
268
+ *
269
+ * The `className` prop is merged by concatenating classes in right-to-left order (rightmost class appears first in the string).
270
+ * The `style` prop is merged with rightmost styles overwriting the prior ones.
271
+ *
272
+ * Props can either be provided as objects or as functions that take the previous props as an argument.
273
+ * The function will receive the merged props up to that point (going from left to right):
274
+ * so in the case of `(obj1, obj2, fn, obj3)`, `fn` will receive the merged props of `obj1` and `obj2`.
275
+ * The function is responsible for chaining event handlers if needed (that is, we don't run the merge logic).
276
+ *
277
+ * Event handlers returned by the functions are not automatically prevented when `preventBaseUIHandler` is called.
278
+ * They must check `event.baseUIHandlerPrevented` themselves and bail out if it's true.
279
+ *
280
+ * @important **`ref` is not merged.**
281
+ * @param a Props object to merge.
282
+ * @param b Props object to merge. The function will overwrite conflicting props from `a`.
283
+ * @param c Props object to merge. The function will overwrite conflicting props from previous parameters.
284
+ * @param d Props object to merge. The function will overwrite conflicting props from previous parameters.
285
+ * @param e Props object to merge. The function will overwrite conflicting props from previous parameters.
286
+ * @returns The merged props.
287
+ * @public
288
+ */
289
+
290
+ function mergeProps$1(a, b, c, d, e) {
291
+ if (!c && !d && true && !a) {
292
+ return createInitialMergedProps(b);
293
+ }
294
+
295
+ // We need to mutably own `merged`.
296
+ let merged = createInitialMergedProps(a);
297
+ if (b) {
298
+ merged = mergeInto(merged, b);
299
+ }
300
+ if (c) {
301
+ merged = mergeInto(merged, c);
302
+ }
303
+ if (d) {
304
+ merged = mergeInto(merged, d);
305
+ }
306
+ return merged;
307
+ }
308
+ /* eslint-enable id-denylist */
309
+
310
+ /**
311
+ * Merges an arbitrary number of React props using the same logic as {@link mergeProps}.
312
+ * This function accepts an array of props instead of individual arguments.
313
+ *
314
+ * This has slightly lower performance than {@link mergeProps} due to accepting an array
315
+ * instead of a fixed number of arguments. Prefer {@link mergeProps} when merging 5 or
316
+ * fewer prop sets for better performance.
317
+ *
318
+ * @param props Array of props to merge.
319
+ * @returns The merged props.
320
+ * @see mergeProps
321
+ * @public
322
+ */
323
+ function mergePropsN(props) {
324
+ if (props.length === 0) {
325
+ return EMPTY_PROPS;
326
+ }
327
+ if (props.length === 1) {
328
+ return createInitialMergedProps(props[0]);
329
+ }
330
+
331
+ // We need to mutably own `merged`.
332
+ let merged = createInitialMergedProps(props[0]);
333
+ for (let i = 1; i < props.length; i += 1) {
334
+ merged = mergeInto(merged, props[i]);
335
+ }
336
+ return merged;
337
+ }
338
+ function createInitialMergedProps(inputProps) {
339
+ if (isPropsGetter(inputProps)) {
340
+ // Getter-returned handlers intentionally keep their existing semantics.
341
+ return {
342
+ ...resolvePropsGetter(inputProps, EMPTY_PROPS)
343
+ };
344
+ }
345
+ return copyInitialProps(inputProps);
346
+ }
347
+ function mergeInto(merged, inputProps) {
348
+ if (isPropsGetter(inputProps)) {
349
+ return resolvePropsGetter(inputProps, merged);
350
+ }
351
+ return mutablyMergeInto(merged, inputProps);
352
+ }
353
+ function copyInitialProps(inputProps) {
354
+ const copiedProps = {
355
+ ...inputProps
356
+ };
357
+
358
+ // `copiedProps` is our fresh own-object copy, so iterating with `for...in` is safe here.
359
+ // eslint-disable-next-line guard-for-in
360
+ for (const propName in copiedProps) {
361
+ const propValue = copiedProps[propName];
362
+ if (isEventHandler(propName, propValue)) {
363
+ copiedProps[propName] = wrapEventHandler(propValue);
364
+ }
365
+ }
366
+ return copiedProps;
367
+ }
368
+
369
+ /**
370
+ * Merges two sets of props. In case of conflicts, the external props take precedence.
371
+ */
372
+ function mutablyMergeInto(mergedProps, externalProps) {
373
+ if (!externalProps) {
374
+ return mergedProps;
375
+ }
376
+
377
+ // eslint-disable-next-line guard-for-in
378
+ for (const propName in externalProps) {
379
+ const externalPropValue = externalProps[propName];
380
+ switch (propName) {
381
+ case 'style':
382
+ {
383
+ mergedProps[propName] = mergeObjects(mergedProps.style, externalPropValue);
384
+ break;
385
+ }
386
+ case 'className':
387
+ {
388
+ mergedProps[propName] = mergeClassNames(mergedProps.className, externalPropValue);
389
+ break;
390
+ }
391
+ default:
392
+ {
393
+ if (isEventHandler(propName, externalPropValue)) {
394
+ mergedProps[propName] = mergeEventHandlers(mergedProps[propName], externalPropValue);
395
+ } else {
396
+ mergedProps[propName] = externalPropValue;
397
+ }
398
+ }
399
+ }
400
+ }
401
+ return mergedProps;
402
+ }
403
+ function isEventHandler(key, value) {
404
+ // This approach is more efficient than using a regex.
405
+ const code0 = key.charCodeAt(0);
406
+ const code1 = key.charCodeAt(1);
407
+ const code2 = key.charCodeAt(2);
408
+ return code0 === 111 /* o */ && code1 === 110 /* n */ && code2 >= 65 /* A */ && code2 <= 90 /* Z */ && (typeof value === 'function' || typeof value === 'undefined');
409
+ }
410
+ function isPropsGetter(inputProps) {
411
+ return typeof inputProps === 'function';
412
+ }
413
+ function resolvePropsGetter(inputProps, previousProps) {
414
+ if (isPropsGetter(inputProps)) {
415
+ return inputProps(previousProps);
416
+ }
417
+ return inputProps ?? EMPTY_PROPS;
418
+ }
419
+ function mergeEventHandlers(ourHandler, theirHandler) {
420
+ if (!theirHandler) {
421
+ return ourHandler;
422
+ }
423
+ if (!ourHandler) {
424
+ return wrapEventHandler(theirHandler);
425
+ }
426
+ return event => {
427
+ if (isSyntheticEvent(event)) {
428
+ const baseUIEvent = event;
429
+ makeEventPreventable(baseUIEvent);
430
+ const result = theirHandler(baseUIEvent);
431
+ if (!baseUIEvent.baseUIHandlerPrevented) {
432
+ ourHandler?.(baseUIEvent);
433
+ }
434
+ return result;
435
+ }
436
+ const result = theirHandler(event);
437
+ ourHandler?.(event);
438
+ return result;
439
+ };
440
+ }
441
+ function wrapEventHandler(handler) {
442
+ if (!handler) {
443
+ return handler;
444
+ }
445
+ return event => {
446
+ if (isSyntheticEvent(event)) {
447
+ makeEventPreventable(event);
448
+ }
449
+ return handler(event);
450
+ };
451
+ }
452
+ function makeEventPreventable(event) {
453
+ event.preventBaseUIHandler = () => {
454
+ event.baseUIHandlerPrevented = true;
455
+ };
456
+ return event;
457
+ }
458
+ function mergeClassNames(ourClassName, theirClassName) {
459
+ if (theirClassName) {
460
+ if (ourClassName) {
461
+ // eslint-disable-next-line prefer-template
462
+ return theirClassName + ' ' + ourClassName;
463
+ }
464
+ return theirClassName;
465
+ }
466
+ return ourClassName;
467
+ }
468
+ function isSyntheticEvent(event) {
469
+ return event != null && typeof event === 'object' && 'nativeEvent' in event;
470
+ }
471
+
472
+ function NOOP() {}
473
+ const EMPTY_ARRAY = Object.freeze([]);
474
+ const EMPTY_OBJECT = Object.freeze({});
475
+
476
+ const DISABLED_TRANSITIONS_STYLE = {
477
+ style: {
478
+ transition: 'none'
479
+ }
480
+ };
481
+ const CLICK_TRIGGER_IDENTIFIER = 'data-base-ui-click-trigger';
482
+
483
+ /**
484
+ * Used for dropdowns that usually strictly prefer top/bottom placements and
485
+ * use `var(--available-height)` to limit their height.
486
+ */
487
+ const DROPDOWN_COLLISION_AVOIDANCE = {
488
+ fallbackAxisSide: 'none'
489
+ };
490
+
491
+ /**
492
+ * Special visually hidden styles for the aria-owns owner element to ensure owned element
493
+ * accessibility in iOS/Safari/VoiceControl.
494
+ * The owner element is an empty span, so most of the common visually hidden styles are not needed.
495
+ * @see https://github.com/floating-ui/floating-ui/issues/3403
496
+ */
497
+ const ownerVisuallyHidden = {
498
+ clipPath: 'inset(50%)',
499
+ position: 'fixed',
500
+ top: 0,
501
+ left: 0
502
+ };
503
+
504
+ /**
505
+ * Renders a Base UI element.
506
+ *
507
+ * @param element The default HTML element to render. Can be overridden by the `render` prop.
508
+ * @param componentProps An object containing the `render` and `className` props to be used for element customization. Other props are ignored.
509
+ * @param params Additional parameters for rendering the element.
510
+ */
511
+ function useRenderElement(element, componentProps, params = {}) {
512
+ const renderProp = componentProps.render;
513
+ const outProps = useRenderElementProps(componentProps, params);
514
+ if (params.enabled === false) {
515
+ return null;
516
+ }
517
+ const state = params.state ?? EMPTY_OBJECT;
518
+ return evaluateRenderProp(element, renderProp, outProps, state);
519
+ }
520
+
521
+ /**
522
+ * Computes render element final props.
523
+ */
524
+ function useRenderElementProps(componentProps, params = {}) {
525
+ const {
526
+ className: classNameProp,
527
+ style: styleProp,
528
+ render: renderProp
529
+ } = componentProps;
530
+ const {
531
+ state = EMPTY_OBJECT,
532
+ ref,
533
+ props,
534
+ stateAttributesMapping,
535
+ enabled = true
536
+ } = params;
537
+ const className = enabled ? resolveClassName(classNameProp, state) : undefined;
538
+ const style = enabled ? resolveStyle(styleProp, state) : undefined;
539
+ const stateProps = enabled ? getStateAttributesProps(state, stateAttributesMapping) : EMPTY_OBJECT;
540
+ const resolvedProps = enabled && props ? resolveRenderFunctionProps(props) : undefined;
541
+
542
+ // Ensure outProps is always a new mutable object when enabled, never EMPTY_OBJECT.
543
+ // This prevents potential TypeError when setting ref, className, or style properties,
544
+ // since EMPTY_OBJECT is frozen and mutations would fail in strict mode.
545
+ const outProps = enabled ? mergeObjects(stateProps, resolvedProps) ?? {} : EMPTY_OBJECT;
546
+
547
+ // SAFETY: The `useMergedRefs` functions use a single hook to store the same value,
548
+ // switching between them at runtime is safe. If this assertion fails, React will
549
+ // throw at runtime anyway.
550
+ // This also skips the `useMergedRefs` call on the server, which is fine because
551
+ // refs are not used on the server side.
552
+ /* eslint-disable react-hooks/rules-of-hooks */
553
+ if (typeof document !== 'undefined') {
554
+ if (!enabled) {
555
+ useMergedRefs(null, null);
556
+ } else if (Array.isArray(ref)) {
557
+ outProps.ref = useMergedRefsN([outProps.ref, getReactElementRef(renderProp), ...ref]);
558
+ } else {
559
+ outProps.ref = useMergedRefs(outProps.ref, getReactElementRef(renderProp), ref);
560
+ }
561
+ }
562
+ if (!enabled) {
563
+ return EMPTY_OBJECT;
564
+ }
565
+ if (className !== undefined) {
566
+ outProps.className = mergeClassNames(outProps.className, className);
567
+ }
568
+ if (style !== undefined) {
569
+ outProps.style = mergeObjects(outProps.style, style);
570
+ }
571
+ return outProps;
572
+ }
573
+ function resolveRenderFunctionProps(props) {
574
+ if (Array.isArray(props)) {
575
+ return mergePropsN(props);
576
+ }
577
+ return mergeProps$1(undefined, props);
578
+ }
579
+
580
+ // The symbol React uses internally for lazy components
581
+ // https://github.com/facebook/react/blob/a0566250b210499b4c5677f5ac2eedbd71d51a1b/packages/shared/ReactSymbols.js#L31
582
+ //
583
+ // TODO delete once https://github.com/facebook/react/issues/32392 is fixed
584
+ const REACT_LAZY_TYPE = Symbol.for('react.lazy');
585
+ function evaluateRenderProp(element, render, props, state) {
586
+ if (render) {
587
+ if (typeof render === 'function') {
588
+ return render(props, state);
589
+ }
590
+ const mergedProps = mergeProps$1(props, render.props);
591
+ mergedProps.ref = props.ref;
592
+ let newElement = render;
593
+
594
+ // Workaround for https://github.com/facebook/react/issues/32392
595
+ // This works because the toArray() logic unwrap lazy element type in
596
+ // https://github.com/facebook/react/blob/a0566250b210499b4c5677f5ac2eedbd71d51a1b/packages/react/src/ReactChildren.js#L186
597
+ if (newElement?.$$typeof === REACT_LAZY_TYPE) {
598
+ const children = React__namespace.Children.toArray(render);
599
+ newElement = children[0];
600
+ }
601
+ return /*#__PURE__*/React__namespace.cloneElement(newElement, mergedProps);
602
+ }
603
+ if (element) {
604
+ if (typeof element === 'string') {
605
+ return renderTag(element, props);
606
+ }
607
+ }
608
+ // Unreachable, but the typings on `useRenderElement` need to be reworked
609
+ // to annotate it correctly.
610
+ throw new Error(formatErrorMessage(8));
611
+ }
612
+ function renderTag(Tag, props) {
613
+ if (Tag === 'button') {
614
+ return /*#__PURE__*/React.createElement("button", {
615
+ type: "button",
616
+ ...props,
617
+ key: props.key
618
+ });
619
+ }
620
+ if (Tag === 'img') {
621
+ return /*#__PURE__*/React.createElement("img", {
622
+ alt: "",
623
+ ...props,
624
+ key: props.key
625
+ });
626
+ }
627
+ return /*#__PURE__*/React__namespace.createElement(Tag, props);
628
+ }
629
+
630
+ let TransitionStatusDataAttributes = /*#__PURE__*/function (TransitionStatusDataAttributes) {
631
+ /**
632
+ * Present when the component is animating in.
633
+ */
634
+ TransitionStatusDataAttributes["startingStyle"] = "data-starting-style";
635
+ /**
636
+ * Present when the component is animating out.
637
+ */
638
+ TransitionStatusDataAttributes["endingStyle"] = "data-ending-style";
639
+ return TransitionStatusDataAttributes;
640
+ }({});
641
+ const STARTING_HOOK = {
642
+ [TransitionStatusDataAttributes.startingStyle]: ''
643
+ };
644
+ const ENDING_HOOK = {
645
+ [TransitionStatusDataAttributes.endingStyle]: ''
646
+ };
647
+ const transitionStatusMapping = {
648
+ transitionStatus(value) {
649
+ if (value === 'starting') {
650
+ return STARTING_HOOK;
651
+ }
652
+ if (value === 'ending') {
653
+ return ENDING_HOOK;
654
+ }
655
+ return null;
656
+ }
657
+ };
658
+
659
+ let CommonPopupDataAttributes = function (CommonPopupDataAttributes) {
660
+ /**
661
+ * Present when the popup is open.
662
+ */
663
+ CommonPopupDataAttributes["open"] = "data-open";
664
+ /**
665
+ * Present when the popup is closed.
666
+ */
667
+ CommonPopupDataAttributes["closed"] = "data-closed";
668
+ /**
669
+ * Present when the popup is animating in.
670
+ */
671
+ CommonPopupDataAttributes[CommonPopupDataAttributes["startingStyle"] = TransitionStatusDataAttributes.startingStyle] = "startingStyle";
672
+ /**
673
+ * Present when the popup is animating out.
674
+ */
675
+ CommonPopupDataAttributes[CommonPopupDataAttributes["endingStyle"] = TransitionStatusDataAttributes.endingStyle] = "endingStyle";
676
+ /**
677
+ * Present when the anchor is hidden.
678
+ */
679
+ CommonPopupDataAttributes["anchorHidden"] = "data-anchor-hidden";
680
+ /**
681
+ * Indicates which side the popup is positioned relative to the trigger.
682
+ * @type { 'top' | 'bottom' | 'left' | 'right' | 'inline-end' | 'inline-start'}
683
+ */
684
+ CommonPopupDataAttributes["side"] = "data-side";
685
+ /**
686
+ * Indicates how the popup is aligned relative to specified side.
687
+ * @type {'start' | 'center' | 'end'}
688
+ */
689
+ CommonPopupDataAttributes["align"] = "data-align";
690
+ return CommonPopupDataAttributes;
691
+ }({});
692
+ let CommonTriggerDataAttributes = /*#__PURE__*/function (CommonTriggerDataAttributes) {
693
+ /**
694
+ * Present when the popup is open.
695
+ */
696
+ CommonTriggerDataAttributes["popupOpen"] = "data-popup-open";
697
+ /**
698
+ * Present when a pressable trigger is pressed.
699
+ */
700
+ CommonTriggerDataAttributes["pressed"] = "data-pressed";
701
+ return CommonTriggerDataAttributes;
702
+ }({});
703
+ const TRIGGER_HOOK = {
704
+ [CommonTriggerDataAttributes.popupOpen]: ''
705
+ };
706
+ const PRESSABLE_TRIGGER_HOOK = {
707
+ [CommonTriggerDataAttributes.popupOpen]: '',
708
+ [CommonTriggerDataAttributes.pressed]: ''
709
+ };
710
+ const POPUP_OPEN_HOOK = {
711
+ [CommonPopupDataAttributes.open]: ''
712
+ };
713
+ const POPUP_CLOSED_HOOK = {
714
+ [CommonPopupDataAttributes.closed]: ''
715
+ };
716
+ const ANCHOR_HIDDEN_HOOK = {
717
+ [CommonPopupDataAttributes.anchorHidden]: ''
718
+ };
719
+ const triggerOpenStateMapping = {
720
+ open(value) {
721
+ if (value) {
722
+ return TRIGGER_HOOK;
723
+ }
724
+ return null;
725
+ }
726
+ };
727
+ const pressableTriggerOpenStateMapping = {
728
+ open(value) {
729
+ if (value) {
730
+ return PRESSABLE_TRIGGER_HOOK;
731
+ }
732
+ return null;
733
+ }
734
+ };
735
+ const popupStateMapping = {
736
+ open(value) {
737
+ if (value) {
738
+ return POPUP_OPEN_HOOK;
739
+ }
740
+ return POPUP_CLOSED_HOOK;
741
+ },
742
+ anchorHidden(value) {
743
+ if (value) {
744
+ return ANCHOR_HIDDEN_HOOK;
745
+ }
746
+ return null;
747
+ }
748
+ };
749
+
750
+ // https://github.com/mui/material-ui/issues/41190#issuecomment-2040873379
751
+ const useInsertionEffect = React__namespace[`useInsertionEffect${Math.random().toFixed(1)}`.slice(0, -3)];
752
+ const useSafeInsertionEffect =
753
+ // React 17 doesn't have useInsertionEffect.
754
+ useInsertionEffect &&
755
+ // Preact replaces useInsertionEffect with useLayoutEffect and fires too late.
756
+ useInsertionEffect !== React__namespace.useLayoutEffect ? useInsertionEffect : fn => fn();
757
+ /**
758
+ * Stabilizes the function passed so it's always the same between renders.
759
+ *
760
+ * The function becomes non-reactive to any values it captures.
761
+ * It can safely be passed as a dependency of `React.useMemo` and `React.useEffect` without re-triggering them if its captured values change.
762
+ *
763
+ * The function must only be called inside effects and event handlers, never during render (which throws an error).
764
+ *
765
+ * This hook is a more permissive version of React 19.2's `React.useEffectEvent` in that it can be passed through contexts and called in event handler props, not just effects.
766
+ */
767
+ function useStableCallback(callback) {
768
+ const stable = useRefWithInit(createStableCallback).current;
769
+ stable.next = callback;
770
+ useSafeInsertionEffect(stable.effect);
771
+ return stable.trampoline;
772
+ }
773
+ function createStableCallback() {
774
+ const stable = {
775
+ next: undefined,
776
+ callback: assertNotCalled,
777
+ trampoline: (...args) => stable.callback?.(...args),
778
+ effect: () => {
779
+ stable.callback = stable.next;
780
+ }
781
+ };
782
+ return stable;
783
+ }
784
+ function assertNotCalled() {
785
+ }
786
+
787
+ // https://github.com/mui/material-ui/issues/41190#issuecomment-2040873379
788
+ const SafeReact = {
789
+ ...React__namespace
790
+ };
791
+
792
+ const noop = () => {};
793
+ const useIsoLayoutEffect = typeof document !== 'undefined' ? React__namespace.useLayoutEffect : noop;
794
+
795
+ const CompositeRootContext = /*#__PURE__*/React__namespace.createContext(undefined);
796
+ function useCompositeRootContext(optional = false) {
797
+ const context = React__namespace.useContext(CompositeRootContext);
798
+ if (context === undefined && !optional) {
799
+ throw new Error(formatErrorMessage(16));
800
+ }
801
+ return context;
802
+ }
803
+
804
+ function useFocusableWhenDisabled(parameters) {
805
+ const {
806
+ focusableWhenDisabled,
807
+ disabled,
808
+ composite = false,
809
+ tabIndex: tabIndexProp = 0,
810
+ isNativeButton
811
+ } = parameters;
812
+ const isFocusableComposite = composite && focusableWhenDisabled !== false;
813
+ const isNonFocusableComposite = composite && focusableWhenDisabled === false;
814
+
815
+ // we can't explicitly assign `undefined` to any of these props because it
816
+ // would otherwise prevent subsequently merged props from setting them
817
+ const props = React__namespace.useMemo(() => {
818
+ const additionalProps = {
819
+ // allow Tabbing away from focusableWhenDisabled elements
820
+ onKeyDown(event) {
821
+ if (disabled && focusableWhenDisabled && event.key !== 'Tab') {
822
+ event.preventDefault();
823
+ }
824
+ }
825
+ };
826
+ if (!composite) {
827
+ additionalProps.tabIndex = tabIndexProp;
828
+ if (!isNativeButton && disabled) {
829
+ additionalProps.tabIndex = focusableWhenDisabled ? tabIndexProp : -1;
830
+ }
831
+ }
832
+ if (isNativeButton && (focusableWhenDisabled || isFocusableComposite) || !isNativeButton && disabled) {
833
+ additionalProps['aria-disabled'] = disabled;
834
+ }
835
+ if (isNativeButton && (!focusableWhenDisabled || isNonFocusableComposite)) {
836
+ additionalProps.disabled = disabled;
837
+ }
838
+ return additionalProps;
839
+ }, [composite, disabled, focusableWhenDisabled, isFocusableComposite, isNonFocusableComposite, isNativeButton, tabIndexProp]);
840
+ return {
841
+ props
842
+ };
843
+ }
844
+
845
+ function useButton(parameters = {}) {
846
+ const {
847
+ disabled = false,
848
+ focusableWhenDisabled,
849
+ tabIndex = 0,
850
+ native: isNativeButton = true,
851
+ composite: compositeProp
852
+ } = parameters;
853
+ const elementRef = React__namespace.useRef(null);
854
+ const compositeRootContext = useCompositeRootContext(true);
855
+ const isCompositeItem = compositeProp ?? compositeRootContext !== undefined;
856
+ const {
857
+ props: focusableWhenDisabledProps
858
+ } = useFocusableWhenDisabled({
859
+ focusableWhenDisabled,
860
+ disabled,
861
+ composite: isCompositeItem,
862
+ tabIndex,
863
+ isNativeButton
864
+ });
865
+
866
+ // handles a disabled composite button rendering another button, e.g.
867
+ // <Toolbar.Button disabled render={<Menu.Trigger />} />
868
+ // the `disabled` prop needs to pass through 2 `useButton`s then finally
869
+ // delete the `disabled` attribute from DOM
870
+ const updateDisabled = React__namespace.useCallback(() => {
871
+ const element = elementRef.current;
872
+ if (!isButtonElement(element)) {
873
+ return;
874
+ }
875
+ if (isCompositeItem && disabled && focusableWhenDisabledProps.disabled === undefined && element.disabled) {
876
+ element.disabled = false;
877
+ }
878
+ }, [disabled, focusableWhenDisabledProps.disabled, isCompositeItem]);
879
+ useIsoLayoutEffect(updateDisabled, [updateDisabled]);
880
+ const getButtonProps = React__namespace.useCallback((externalProps = {}) => {
881
+ const {
882
+ onClick: externalOnClick,
883
+ onMouseDown: externalOnMouseDown,
884
+ onKeyUp: externalOnKeyUp,
885
+ onKeyDown: externalOnKeyDown,
886
+ onPointerDown: externalOnPointerDown,
887
+ ...otherExternalProps
888
+ } = externalProps;
889
+ const type = isNativeButton ? 'button' : undefined;
890
+ return mergeProps$1({
891
+ type,
892
+ onClick(event) {
893
+ if (disabled) {
894
+ event.preventDefault();
895
+ return;
896
+ }
897
+ externalOnClick?.(event);
898
+ },
899
+ onMouseDown(event) {
900
+ if (!disabled) {
901
+ externalOnMouseDown?.(event);
902
+ }
903
+ },
904
+ onKeyDown(event) {
905
+ if (disabled) {
906
+ return;
907
+ }
908
+ makeEventPreventable(event);
909
+ externalOnKeyDown?.(event);
910
+ if (event.baseUIHandlerPrevented) {
911
+ return;
912
+ }
913
+ const isCurrentTarget = event.target === event.currentTarget;
914
+ const currentTarget = event.currentTarget;
915
+ const isButton = isButtonElement(currentTarget);
916
+ const isLink = !isNativeButton && isValidLinkElement(currentTarget);
917
+ const shouldClick = isCurrentTarget && (isNativeButton ? isButton : !isLink);
918
+ const isEnterKey = event.key === 'Enter';
919
+ const isSpaceKey = event.key === ' ';
920
+ const role = currentTarget.getAttribute('role');
921
+ const isTextNavigationRole = role?.startsWith('menuitem') || role === 'option' || role === 'gridcell';
922
+ if (isCurrentTarget && isCompositeItem && isSpaceKey) {
923
+ if (event.defaultPrevented && isTextNavigationRole) {
924
+ return;
925
+ }
926
+ event.preventDefault();
927
+ if (isLink || isNativeButton && isButton) {
928
+ currentTarget.click();
929
+ event.preventBaseUIHandler();
930
+ } else if (shouldClick) {
931
+ externalOnClick?.(event);
932
+ event.preventBaseUIHandler();
933
+ }
934
+ return;
935
+ }
936
+
937
+ // Keyboard accessibility for native and non-native elements.
938
+ if (shouldClick) {
939
+ if (!isNativeButton && (isSpaceKey || isEnterKey)) {
940
+ event.preventDefault();
941
+ }
942
+ if (!isNativeButton && isEnterKey) {
943
+ externalOnClick?.(event);
944
+ }
945
+ }
946
+ },
947
+ onKeyUp(event) {
948
+ if (disabled) {
949
+ return;
950
+ }
951
+
952
+ // calling preventDefault in keyUp on a <button> will not dispatch a click event if Space is pressed
953
+ // https://codesandbox.io/p/sandbox/button-keyup-preventdefault-dn7f0
954
+ makeEventPreventable(event);
955
+ externalOnKeyUp?.(event);
956
+ if (event.target === event.currentTarget && isNativeButton && isCompositeItem && isButtonElement(event.currentTarget) && event.key === ' ') {
957
+ event.preventDefault();
958
+ return;
959
+ }
960
+ if (event.baseUIHandlerPrevented) {
961
+ return;
962
+ }
963
+
964
+ // Keyboard accessibility for non interactive elements
965
+ if (event.target === event.currentTarget && !isNativeButton && !isCompositeItem && event.key === ' ') {
966
+ externalOnClick?.(event);
967
+ }
968
+ },
969
+ onPointerDown(event) {
970
+ if (disabled) {
971
+ event.preventDefault();
972
+ return;
973
+ }
974
+ externalOnPointerDown?.(event);
975
+ }
976
+ }, !isNativeButton ? {
977
+ role: 'button'
978
+ } : undefined, focusableWhenDisabledProps, otherExternalProps);
979
+ }, [disabled, focusableWhenDisabledProps, isCompositeItem, isNativeButton]);
980
+ const buttonRef = useStableCallback(element => {
981
+ elementRef.current = element;
982
+ updateDisabled();
983
+ });
984
+ return {
985
+ getButtonProps,
986
+ buttonRef
987
+ };
988
+ }
989
+ function isButtonElement(elem) {
990
+ return floatingUi_utils_dom.isHTMLElement(elem) && elem.tagName === 'BUTTON';
991
+ }
992
+ function isValidLinkElement(elem) {
993
+ return Boolean(elem?.tagName === 'A' && elem?.href);
994
+ }
995
+
996
+ const none = 'none';
997
+ const triggerPress = 'trigger-press';
998
+ const triggerHover = 'trigger-hover';
999
+ const outsidePress = 'outside-press';
1000
+ const itemPress = 'item-press';
1001
+ const closePress = 'close-press';
1002
+ const clearPress = 'clear-press';
1003
+ const chipRemovePress = 'chip-remove-press';
1004
+ const inputChange = 'input-change';
1005
+ const inputClear = 'input-clear';
1006
+ const inputPress = 'input-press';
1007
+ const focusOut = 'focus-out';
1008
+ const escapeKey = 'escape-key';
1009
+ const listNavigation = 'list-navigation';
1010
+ const imperativeAction = 'imperative-action';
1011
+
1012
+ /**
1013
+ * Maps a change `reason` string to the corresponding native event type.
1014
+ */
1015
+
1016
+ /**
1017
+ * Details of custom change events emitted by Base UI components.
1018
+ */
1019
+
1020
+ /**
1021
+ * Details of custom generic events emitted by Base UI components.
1022
+ */
1023
+
1024
+ /**
1025
+ * Creates a Base UI event details object with the given reason and utilities
1026
+ * for preventing Base UI's internal event handling.
1027
+ */
1028
+ function createChangeEventDetails(reason, event, trigger, customProperties) {
1029
+ let canceled = false;
1030
+ let allowPropagation = false;
1031
+ const custom = EMPTY_OBJECT;
1032
+ const details = {
1033
+ reason,
1034
+ event: event ?? new Event('base-ui'),
1035
+ cancel() {
1036
+ canceled = true;
1037
+ },
1038
+ allowPropagation() {
1039
+ allowPropagation = true;
1040
+ },
1041
+ get isCanceled() {
1042
+ return canceled;
1043
+ },
1044
+ get isPropagationAllowed() {
1045
+ return allowPropagation;
1046
+ },
1047
+ trigger,
1048
+ ...custom
1049
+ };
1050
+ return details;
1051
+ }
1052
+ function createGenericEventDetails(reason, event, customProperties) {
1053
+ const custom = customProperties ?? EMPTY_OBJECT;
1054
+ const details = {
1055
+ reason,
1056
+ event: event ?? new Event('base-ui'),
1057
+ ...custom
1058
+ };
1059
+ return details;
1060
+ }
1061
+
1062
+ let globalId = 0;
1063
+
1064
+ // TODO React 17: Remove `useGlobalId` once React 17 support is removed
1065
+ function useGlobalId(idOverride, prefix = 'mui') {
1066
+ const [defaultId, setDefaultId] = React__namespace.useState(idOverride);
1067
+ const id = idOverride || defaultId;
1068
+ React__namespace.useEffect(() => {
1069
+ if (defaultId == null) {
1070
+ // Fallback to this default id when possible.
1071
+ // Use the incrementing value for client-side rendering only.
1072
+ // We can't use it server-side.
1073
+ // If you want to use random values please consider the Birthday Problem: https://en.wikipedia.org/wiki/Birthday_problem
1074
+ globalId += 1;
1075
+ setDefaultId(`${prefix}-${globalId}`);
1076
+ }
1077
+ }, [defaultId, prefix]);
1078
+ return id;
1079
+ }
1080
+ const maybeReactUseId = SafeReact.useId;
1081
+
1082
+ /**
1083
+ *
1084
+ * @example <div id={useId()} />
1085
+ * @param idOverride
1086
+ * @returns {string}
1087
+ */
1088
+ function useId(idOverride, prefix) {
1089
+ // React.useId() is only available from React 17.0.0.
1090
+ if (maybeReactUseId !== undefined) {
1091
+ const reactId = maybeReactUseId();
1092
+ return idOverride ?? (prefix ? `${prefix}-${reactId}` : reactId);
1093
+ }
1094
+
1095
+ // TODO: uncomment once we enable eslint-plugin-react-compiler // eslint-disable-next-line react-compiler/react-compiler
1096
+ // eslint-disable-next-line react-hooks/rules-of-hooks -- `React.useId` is invariant at runtime.
1097
+ return useGlobalId(idOverride, prefix);
1098
+ }
1099
+
1100
+ /**
1101
+ * Wraps `useId` and prefixes generated `id`s with `base-ui-`
1102
+ * @param {string | undefined} idOverride overrides the generated id when provided
1103
+ * @returns {string | undefined}
1104
+ */
1105
+ function useBaseUiId(idOverride) {
1106
+ return useId(idOverride, 'base-ui');
1107
+ }
1108
+
1109
+ const EMPTY$2 = [];
1110
+
1111
+ /**
1112
+ * A React.useEffect equivalent that runs once, when the component is mounted.
1113
+ */
1114
+ function useOnMount(fn) {
1115
+ // TODO: uncomment once we enable eslint-plugin-react-compiler // eslint-disable-next-line react-compiler/react-compiler -- no need to put `fn` in the dependency array
1116
+ /* eslint-disable react-hooks/exhaustive-deps */
1117
+ React__namespace.useEffect(fn, EMPTY$2);
1118
+ /* eslint-enable react-hooks/exhaustive-deps */
1119
+ }
1120
+
1121
+ const EMPTY$1 = 0;
1122
+ class Timeout {
1123
+ static create() {
1124
+ return new Timeout();
1125
+ }
1126
+ currentId = EMPTY$1;
1127
+
1128
+ /**
1129
+ * Executes `fn` after `delay`, clearing any previously scheduled call.
1130
+ */
1131
+ start(delay, fn) {
1132
+ this.clear();
1133
+ this.currentId = setTimeout(() => {
1134
+ this.currentId = EMPTY$1;
1135
+ fn();
1136
+ }, delay); /* Node.js types are enabled in development */
1137
+ }
1138
+ isStarted() {
1139
+ return this.currentId !== EMPTY$1;
1140
+ }
1141
+ clear = () => {
1142
+ if (this.currentId !== EMPTY$1) {
1143
+ clearTimeout(this.currentId);
1144
+ this.currentId = EMPTY$1;
1145
+ }
1146
+ };
1147
+ disposeEffect = () => {
1148
+ return this.clear;
1149
+ };
1150
+ }
1151
+
1152
+ /**
1153
+ * A `setTimeout` with automatic cleanup and guard.
1154
+ */
1155
+ function useTimeout() {
1156
+ const timeout = useRefWithInit(Timeout.create).current;
1157
+ useOnMount(timeout.disposeEffect);
1158
+ return timeout;
1159
+ }
1160
+
1161
+ const hasNavigator = typeof navigator !== 'undefined';
1162
+ const nav = getNavigatorData();
1163
+ const platform = getPlatform();
1164
+ const userAgent = getUserAgent();
1165
+ const isWebKit = typeof CSS === 'undefined' || !CSS.supports ? false : CSS.supports('-webkit-backdrop-filter:none');
1166
+ const isIOS =
1167
+ // iPads can claim to be MacIntel
1168
+ nav.platform === 'MacIntel' && nav.maxTouchPoints > 1 ? true : /iP(hone|ad|od)|iOS/.test(nav.platform);
1169
+ const isFirefox = hasNavigator && /firefox/i.test(userAgent);
1170
+ const isSafari = hasNavigator && /apple/i.test(navigator.vendor);
1171
+ const isAndroid = hasNavigator && /android/i.test(platform) || /android/i.test(userAgent);
1172
+ hasNavigator && platform.toLowerCase().startsWith('mac') && !navigator.maxTouchPoints;
1173
+ const isJSDOM = userAgent.includes('jsdom/');
1174
+
1175
+ // Avoid Chrome DevTools blue warning.
1176
+ function getNavigatorData() {
1177
+ if (!hasNavigator) {
1178
+ return {
1179
+ platform: '',
1180
+ maxTouchPoints: -1
1181
+ };
1182
+ }
1183
+ const uaData = navigator.userAgentData;
1184
+ if (uaData?.platform) {
1185
+ return {
1186
+ platform: uaData.platform,
1187
+ maxTouchPoints: navigator.maxTouchPoints
1188
+ };
1189
+ }
1190
+ return {
1191
+ platform: navigator.platform ?? '',
1192
+ maxTouchPoints: navigator.maxTouchPoints ?? -1
1193
+ };
1194
+ }
1195
+ function getUserAgent() {
1196
+ if (!hasNavigator) {
1197
+ return '';
1198
+ }
1199
+ const uaData = navigator.userAgentData;
1200
+ if (uaData && Array.isArray(uaData.brands)) {
1201
+ return uaData.brands.map(({
1202
+ brand,
1203
+ version
1204
+ }) => `${brand}/${version}`).join(' ');
1205
+ }
1206
+ return navigator.userAgent;
1207
+ }
1208
+ function getPlatform() {
1209
+ if (!hasNavigator) {
1210
+ return '';
1211
+ }
1212
+ const uaData = navigator.userAgentData;
1213
+ if (uaData?.platform) {
1214
+ return uaData.platform;
1215
+ }
1216
+ return navigator.platform ?? '';
1217
+ }
1218
+
1219
+ function stopEvent(event) {
1220
+ event.preventDefault();
1221
+ event.stopPropagation();
1222
+ }
1223
+ function isReactEvent(event) {
1224
+ return 'nativeEvent' in event;
1225
+ }
1226
+
1227
+ // License: https://github.com/adobe/react-spectrum/blob/main/packages/@react-aria/utils/src/isVirtualEvent.ts
1228
+ function isVirtualClick(event) {
1229
+ if (event.pointerType === '' && event.isTrusted) {
1230
+ return true;
1231
+ }
1232
+ if (isAndroid && event.pointerType) {
1233
+ return event.type === 'click' && event.buttons === 1;
1234
+ }
1235
+ return event.detail === 0 && !event.pointerType;
1236
+ }
1237
+ function isVirtualPointerEvent(event) {
1238
+ if (isJSDOM) {
1239
+ return false;
1240
+ }
1241
+ return !isAndroid && event.width === 0 && event.height === 0 || isAndroid && event.width === 1 && event.height === 1 && event.pressure === 0 && event.detail === 0 && event.pointerType === 'mouse' ||
1242
+ // iOS VoiceOver returns 0.333• for width/height.
1243
+ event.width < 1 && event.height < 1 && event.pressure === 0 && event.detail === 0 && event.pointerType === 'touch';
1244
+ }
1245
+ function isMouseLikePointerType(pointerType, strict) {
1246
+ // On some Linux machines with Chromium, mouse inputs return a `pointerType`
1247
+ // of "pen": https://github.com/floating-ui/floating-ui/issues/2015
1248
+ const values = ['mouse', 'pen'];
1249
+ return values.includes(pointerType);
1250
+ }
1251
+ function isClickLikeEvent(event) {
1252
+ const type = event.type;
1253
+ return type === 'click' || type === 'mousedown' || type === 'keydown' || type === 'keyup';
1254
+ }
1255
+
1256
+ /**
1257
+ * Adds an event listener and returns a cleanup function to remove it.
1258
+ */
1259
+
1260
+ function addEventListener(target, type, listener, options) {
1261
+ target.addEventListener(type, listener, options);
1262
+ return () => {
1263
+ target.removeEventListener(type, listener, options);
1264
+ };
1265
+ }
1266
+
1267
+ /**
1268
+ * Combines multiple cleanup functions into a single cleanup function.
1269
+ */
1270
+ function mergeCleanups(...cleanups) {
1271
+ return () => {
1272
+ for (let i = 0; i < cleanups.length; i += 1) {
1273
+ const cleanup = cleanups[i];
1274
+ if (cleanup) {
1275
+ cleanup();
1276
+ }
1277
+ }
1278
+ };
1279
+ }
1280
+
1281
+ /**
1282
+ * Untracks the provided value by turning it into a ref to remove its reactivity.
1283
+ *
1284
+ * Used to access the passed value inside `React.useEffect` without causing the effect to re-run when the value changes.
1285
+ */
1286
+ function useValueAsRef(value) {
1287
+ const latest = useRefWithInit(createLatestRef, value).current;
1288
+ latest.next = value;
1289
+
1290
+ // eslint-disable-next-line react-hooks/exhaustive-deps
1291
+ useIsoLayoutEffect(latest.effect);
1292
+ return latest;
1293
+ }
1294
+ function createLatestRef(value) {
1295
+ const latest = {
1296
+ current: value,
1297
+ next: value,
1298
+ effect: () => {
1299
+ latest.current = latest.next;
1300
+ }
1301
+ };
1302
+ return latest;
1303
+ }
1304
+
1305
+ /** Unlike `setTimeout`, rAF doesn't guarantee a positive integer return value, so we can't have
1306
+ * a monomorphic `uint` type with `0` meaning empty.
1307
+ * See warning note at:
1308
+ * https://developer.mozilla.org/en-US/docs/Web/API/Window/requestAnimationFrame#return_value */
1309
+ const EMPTY = null;
1310
+ class Scheduler {
1311
+ /* This implementation uses an array as a backing data-structure for frame callbacks.
1312
+ * It allows `O(1)` callback cancelling by inserting a `null` in the array, though it
1313
+ * never calls the native `cancelAnimationFrame` if there are no frames left. This can
1314
+ * be much more efficient if there is a call pattern that alterns as
1315
+ * "request-cancel-request-cancel-…".
1316
+ * But in the case of "request-request-…-cancel-cancel-…", it leaves the final animation
1317
+ * frame to run anyway. We turn that frame into a `O(1)` no-op via `callbacksCount`. */
1318
+
1319
+ callbacks = [];
1320
+ callbacksCount = 0;
1321
+ nextId = 1;
1322
+ startId = 1;
1323
+ isScheduled = false;
1324
+ tick = timestamp => {
1325
+ this.isScheduled = false;
1326
+ const currentCallbacks = this.callbacks;
1327
+ const currentCallbacksCount = this.callbacksCount;
1328
+
1329
+ // Update these before iterating, callbacks could call `requestAnimationFrame` again.
1330
+ this.callbacks = [];
1331
+ this.callbacksCount = 0;
1332
+ this.startId = this.nextId;
1333
+ if (currentCallbacksCount > 0) {
1334
+ for (let i = 0; i < currentCallbacks.length; i += 1) {
1335
+ currentCallbacks[i]?.(timestamp);
1336
+ }
1337
+ }
1338
+ };
1339
+ request(fn) {
1340
+ const id = this.nextId;
1341
+ this.nextId += 1;
1342
+ this.callbacks.push(fn);
1343
+ this.callbacksCount += 1;
1344
+
1345
+ /* In a test environment with fake timers, a fake `requestAnimationFrame` can be called
1346
+ * but there's no guarantee that the animation frame will actually run before the fake
1347
+ * timers are teared, which leaves `isScheduled` set, but won't run our `tick()`. */
1348
+ const didRAFChange = "production" !== 'production';
1349
+ if (!this.isScheduled || didRAFChange) {
1350
+ requestAnimationFrame(this.tick);
1351
+ this.isScheduled = true;
1352
+ }
1353
+ return id;
1354
+ }
1355
+ cancel(id) {
1356
+ const index = id - this.startId;
1357
+ if (index < 0 || index >= this.callbacks.length) {
1358
+ return;
1359
+ }
1360
+ this.callbacks[index] = null;
1361
+ this.callbacksCount -= 1;
1362
+ }
1363
+ }
1364
+ const scheduler = new Scheduler();
1365
+ class AnimationFrame {
1366
+ static create() {
1367
+ return new AnimationFrame();
1368
+ }
1369
+ static request(fn) {
1370
+ return scheduler.request(fn);
1371
+ }
1372
+ static cancel(id) {
1373
+ return scheduler.cancel(id);
1374
+ }
1375
+ currentId = EMPTY;
1376
+
1377
+ /**
1378
+ * Executes `fn` after `delay`, clearing any previously scheduled call.
1379
+ */
1380
+ request(fn) {
1381
+ this.cancel();
1382
+ this.currentId = scheduler.request(() => {
1383
+ this.currentId = EMPTY;
1384
+ fn();
1385
+ });
1386
+ }
1387
+ cancel = () => {
1388
+ if (this.currentId !== EMPTY) {
1389
+ scheduler.cancel(this.currentId);
1390
+ this.currentId = EMPTY;
1391
+ }
1392
+ };
1393
+ disposeEffect = () => {
1394
+ return this.cancel;
1395
+ };
1396
+ }
1397
+
1398
+ /**
1399
+ * A `requestAnimationFrame` with automatic cleanup and guard.
1400
+ */
1401
+ function useAnimationFrame() {
1402
+ const timeout = useRefWithInit(AnimationFrame.create).current;
1403
+ useOnMount(timeout.disposeEffect);
1404
+ return timeout;
1405
+ }
1406
+
1407
+ function ownerDocument(node) {
1408
+ return node?.ownerDocument || document;
1409
+ }
1410
+
1411
+ const visuallyHiddenBase = {
1412
+ clipPath: 'inset(50%)',
1413
+ overflow: 'hidden',
1414
+ whiteSpace: 'nowrap',
1415
+ border: 0,
1416
+ padding: 0,
1417
+ width: 1,
1418
+ height: 1,
1419
+ margin: -1
1420
+ };
1421
+ const visuallyHidden = {
1422
+ ...visuallyHiddenBase,
1423
+ position: 'fixed',
1424
+ top: 0,
1425
+ left: 0
1426
+ };
1427
+ const visuallyHiddenInput = {
1428
+ ...visuallyHiddenBase,
1429
+ position: 'absolute'
1430
+ };
1431
+
1432
+ const FocusGuard = /*#__PURE__*/React__namespace.forwardRef(function FocusGuard(props, ref) {
1433
+ const [role, setRole] = React__namespace.useState();
1434
+ useIsoLayoutEffect(() => {
1435
+ if (isSafari) {
1436
+ // Unlike other screen readers such as NVDA and JAWS, the virtual cursor
1437
+ // on VoiceOver does trigger the onFocus event, so we can use the focus
1438
+ // trap element. On Safari, only buttons trigger the onFocus event.
1439
+ setRole('button');
1440
+ }
1441
+ }, []);
1442
+ const restProps = {
1443
+ tabIndex: 0,
1444
+ // Role is only for VoiceOver
1445
+ role
1446
+ };
1447
+ return /*#__PURE__*/jsxRuntime.jsx("span", {
1448
+ ...props,
1449
+ ref: ref,
1450
+ style: visuallyHidden,
1451
+ "aria-hidden": role ? undefined : true,
1452
+ ...restProps,
1453
+ "data-base-ui-focus-guard": ""
1454
+ });
1455
+ });
1456
+
1457
+ const FOCUSABLE_ATTRIBUTE = 'data-base-ui-focusable';
1458
+ const ACTIVE_KEY = 'active';
1459
+ const SELECTED_KEY = 'selected';
1460
+ const TYPEABLE_SELECTOR = "input:not([type='hidden']):not([disabled])," + "[contenteditable]:not([contenteditable='false']),textarea:not([disabled])";
1461
+ const ARROW_LEFT = 'ArrowLeft';
1462
+ const ARROW_RIGHT = 'ArrowRight';
1463
+ const ARROW_UP = 'ArrowUp';
1464
+ const ARROW_DOWN = 'ArrowDown';
1465
+
1466
+ function activeElement(doc) {
1467
+ let element = doc.activeElement;
1468
+ while (element?.shadowRoot?.activeElement != null) {
1469
+ element = element.shadowRoot.activeElement;
1470
+ }
1471
+ return element;
1472
+ }
1473
+ function contains(parent, child) {
1474
+ if (!parent || !child) {
1475
+ return false;
1476
+ }
1477
+ const rootNode = child.getRootNode?.();
1478
+
1479
+ // First, attempt with the faster native method.
1480
+ if (parent.contains(child)) {
1481
+ return true;
1482
+ }
1483
+
1484
+ // Then fall back to traversing out of shadow roots when needed.
1485
+ if (rootNode && floatingUi_utils_dom.isShadowRoot(rootNode)) {
1486
+ let next = child;
1487
+ while (next) {
1488
+ if (parent === next) {
1489
+ return true;
1490
+ }
1491
+ next = next.parentNode || next.host;
1492
+ }
1493
+ }
1494
+ return false;
1495
+ }
1496
+ function getTarget(event) {
1497
+ if ('composedPath' in event) {
1498
+ return event.composedPath()[0];
1499
+ }
1500
+
1501
+ // TS assumes `composedPath()` always exists, but older browsers without
1502
+ // shadow DOM support still fall back to `target`.
1503
+ return event.target;
1504
+ }
1505
+
1506
+ function isEventTargetWithin(event, node) {
1507
+ if (node == null) {
1508
+ return false;
1509
+ }
1510
+ if ('composedPath' in event) {
1511
+ return event.composedPath().includes(node);
1512
+ }
1513
+
1514
+ // TS thinks `event` is of type never as it assumes all browsers support composedPath, but browsers without shadow dom don't
1515
+ const eventAgain = event;
1516
+ return eventAgain.target != null && node.contains(eventAgain.target);
1517
+ }
1518
+ function isRootElement(element) {
1519
+ return element.matches('html,body');
1520
+ }
1521
+ function isTypeableElement(element) {
1522
+ return floatingUi_utils_dom.isHTMLElement(element) && element.matches(TYPEABLE_SELECTOR);
1523
+ }
1524
+ function isInteractiveElement(element) {
1525
+ return element?.closest(`button,a[href],[role="button"],select,[tabindex]:not([tabindex="-1"]),${TYPEABLE_SELECTOR}`) != null;
1526
+ }
1527
+ function isTypeableCombobox(element) {
1528
+ if (!element) {
1529
+ return false;
1530
+ }
1531
+ return element.getAttribute('role') === 'combobox' && isTypeableElement(element);
1532
+ }
1533
+ function getFloatingFocusElement(floatingElement) {
1534
+ if (!floatingElement) {
1535
+ return null;
1536
+ }
1537
+ // Try to find the element that has `{...getFloatingProps()}` spread on it.
1538
+ // This indicates the floating element is acting as a positioning wrapper, and
1539
+ // so focus should be managed on the child element with the event handlers and
1540
+ // aria props.
1541
+ return floatingElement.hasAttribute(FOCUSABLE_ATTRIBUTE) ? floatingElement : floatingElement.querySelector(`[${FOCUSABLE_ATTRIBUTE}]`) || floatingElement;
1542
+ }
1543
+
1544
+ function isDifferentGridRow(index, cols, prevRow) {
1545
+ return Math.floor(index / cols) !== prevRow;
1546
+ }
1547
+ function isIndexOutOfListBounds(list, index) {
1548
+ return index < 0 || index >= list.length;
1549
+ }
1550
+ function getMinListIndex(listRef, disabledIndices) {
1551
+ return findNonDisabledListIndex(listRef.current, {
1552
+ disabledIndices
1553
+ });
1554
+ }
1555
+ function getMaxListIndex(listRef, disabledIndices) {
1556
+ return findNonDisabledListIndex(listRef.current, {
1557
+ decrement: true,
1558
+ startingIndex: listRef.current.length,
1559
+ disabledIndices
1560
+ });
1561
+ }
1562
+ function findNonDisabledListIndex(list, {
1563
+ startingIndex = -1,
1564
+ decrement = false,
1565
+ disabledIndices,
1566
+ amount = 1
1567
+ } = {}) {
1568
+ let index = startingIndex;
1569
+ do {
1570
+ index += decrement ? -amount : amount;
1571
+ } while (index >= 0 && index <= list.length - 1 && isListIndexDisabled(list, index, disabledIndices));
1572
+ return index;
1573
+ }
1574
+ function getGridNavigatedIndex(list, {
1575
+ event,
1576
+ orientation,
1577
+ loopFocus,
1578
+ onLoop,
1579
+ rtl,
1580
+ cols,
1581
+ disabledIndices,
1582
+ minIndex,
1583
+ maxIndex,
1584
+ prevIndex,
1585
+ stopEvent: stop = false
1586
+ }) {
1587
+ let nextIndex = prevIndex;
1588
+ let verticalDirection;
1589
+ if (event.key === ARROW_UP) {
1590
+ verticalDirection = 'up';
1591
+ } else if (event.key === ARROW_DOWN) {
1592
+ verticalDirection = 'down';
1593
+ }
1594
+ if (verticalDirection) {
1595
+ // -------------------------------------------------------------------------
1596
+ // Detect row structure only when handling vertical navigation. This keeps
1597
+ // the non-vertical key paths free from row inference work.
1598
+ // -------------------------------------------------------------------------
1599
+ const rows = [];
1600
+ const rowIndexMap = [];
1601
+ let hasRoleRow = false;
1602
+ let visibleItemCount = 0;
1603
+ {
1604
+ let currentRowEl = null;
1605
+ let currentRowIndex = -1;
1606
+ list.forEach((el, idx) => {
1607
+ if (el == null) {
1608
+ return;
1609
+ }
1610
+ visibleItemCount += 1;
1611
+ const rowEl = el.closest('[role="row"]');
1612
+ if (rowEl) {
1613
+ hasRoleRow = true;
1614
+ }
1615
+ if (rowEl !== currentRowEl || currentRowIndex === -1) {
1616
+ currentRowEl = rowEl;
1617
+ currentRowIndex += 1;
1618
+ rows[currentRowIndex] = [];
1619
+ }
1620
+ rows[currentRowIndex].push(idx);
1621
+ rowIndexMap[idx] = currentRowIndex;
1622
+ });
1623
+ }
1624
+ let hasDomRows = false;
1625
+ let inferredDomCols = 0;
1626
+ if (hasRoleRow) {
1627
+ for (const row of rows) {
1628
+ const rowLength = row.length;
1629
+ if (rowLength > inferredDomCols) {
1630
+ inferredDomCols = rowLength;
1631
+ }
1632
+ if (rowLength !== cols) {
1633
+ hasDomRows = true;
1634
+ }
1635
+ }
1636
+ }
1637
+ const hasVirtualizedGaps = hasDomRows && visibleItemCount < list.length;
1638
+ const verticalCols = inferredDomCols || cols;
1639
+ const navigateVertically = direction => {
1640
+ if (!hasDomRows || prevIndex === -1) {
1641
+ return undefined;
1642
+ }
1643
+ const currentRow = rowIndexMap[prevIndex];
1644
+ if (currentRow == null) {
1645
+ return undefined;
1646
+ }
1647
+ const colInRow = rows[currentRow].indexOf(prevIndex);
1648
+ const step = direction === 'up' ? -1 : 1;
1649
+ for (let nextRow = currentRow + step, i = 0; i < rows.length; i += 1, nextRow += step) {
1650
+ if (nextRow < 0 || nextRow >= rows.length) {
1651
+ if (!loopFocus || hasVirtualizedGaps) {
1652
+ return undefined;
1653
+ }
1654
+ nextRow = nextRow < 0 ? rows.length - 1 : 0;
1655
+ if (onLoop) {
1656
+ const clampedCol = Math.min(colInRow, rows[nextRow].length - 1);
1657
+ const targetItemIndex = rows[nextRow][clampedCol] ?? rows[nextRow][0];
1658
+ const returnedItemIndex = onLoop(event, prevIndex, targetItemIndex);
1659
+ nextRow = rowIndexMap[returnedItemIndex] ?? nextRow;
1660
+ }
1661
+ }
1662
+ const targetRow = rows[nextRow];
1663
+ for (let col = Math.min(colInRow, targetRow.length - 1); col >= 0; col -= 1) {
1664
+ const candidate = targetRow[col];
1665
+ if (!isListIndexDisabled(list, candidate, disabledIndices)) {
1666
+ return candidate;
1667
+ }
1668
+ }
1669
+ }
1670
+ return undefined;
1671
+ };
1672
+ const navigateVerticallyWithInferredRows = direction => {
1673
+ if (!hasVirtualizedGaps || prevIndex === -1) {
1674
+ return undefined;
1675
+ }
1676
+ const colInRow = prevIndex % verticalCols;
1677
+ const rowStep = direction === 'up' ? -verticalCols : verticalCols;
1678
+ const lastRowStart = maxIndex - maxIndex % verticalCols;
1679
+ const rowCount = floatingUi_utils_dom.floor(maxIndex / verticalCols) + 1;
1680
+ for (let rowStart = prevIndex - colInRow + rowStep, i = 0; i < rowCount; i += 1, rowStart += rowStep) {
1681
+ if (rowStart < 0 || rowStart > maxIndex) {
1682
+ if (!loopFocus) {
1683
+ return undefined;
1684
+ }
1685
+ rowStart = rowStart < 0 ? lastRowStart : 0;
1686
+ }
1687
+ const rowEnd = Math.min(rowStart + verticalCols - 1, maxIndex);
1688
+ for (let candidate = Math.min(rowStart + colInRow, rowEnd); candidate >= rowStart; candidate -= 1) {
1689
+ if (!isListIndexDisabled(list, candidate, disabledIndices)) {
1690
+ return candidate;
1691
+ }
1692
+ }
1693
+ }
1694
+ return undefined;
1695
+ };
1696
+ if (stop) {
1697
+ stopEvent(event);
1698
+ }
1699
+ const verticalCandidate = navigateVertically(verticalDirection) ?? navigateVerticallyWithInferredRows(verticalDirection);
1700
+ if (verticalCandidate !== undefined) {
1701
+ nextIndex = verticalCandidate;
1702
+ } else if (prevIndex === -1) {
1703
+ nextIndex = verticalDirection === 'up' ? maxIndex : minIndex;
1704
+ } else {
1705
+ nextIndex = findNonDisabledListIndex(list, {
1706
+ startingIndex: prevIndex,
1707
+ amount: verticalCols,
1708
+ decrement: verticalDirection === 'up',
1709
+ disabledIndices
1710
+ });
1711
+ if (loopFocus) {
1712
+ if (verticalDirection === 'up' && (prevIndex - verticalCols < minIndex || nextIndex < 0)) {
1713
+ const col = prevIndex % verticalCols;
1714
+ const maxCol = maxIndex % verticalCols;
1715
+ const offset = maxIndex - (maxCol - col);
1716
+ if (maxCol === col) {
1717
+ nextIndex = maxIndex;
1718
+ } else {
1719
+ nextIndex = maxCol > col ? offset : offset - verticalCols;
1720
+ }
1721
+ if (onLoop) {
1722
+ nextIndex = onLoop(event, prevIndex, nextIndex);
1723
+ }
1724
+ }
1725
+ if (verticalDirection === 'down' && prevIndex + verticalCols > maxIndex) {
1726
+ nextIndex = findNonDisabledListIndex(list, {
1727
+ startingIndex: prevIndex % verticalCols - verticalCols,
1728
+ amount: verticalCols,
1729
+ disabledIndices
1730
+ });
1731
+ if (onLoop) {
1732
+ nextIndex = onLoop(event, prevIndex, nextIndex);
1733
+ }
1734
+ }
1735
+ }
1736
+ }
1737
+ if (isIndexOutOfListBounds(list, nextIndex)) {
1738
+ nextIndex = prevIndex;
1739
+ }
1740
+ }
1741
+
1742
+ // Remains on the same row/column.
1743
+ if (orientation === 'both') {
1744
+ const prevRow = floatingUi_utils_dom.floor(prevIndex / cols);
1745
+ if (event.key === (rtl ? ARROW_LEFT : ARROW_RIGHT)) {
1746
+ if (stop) {
1747
+ stopEvent(event);
1748
+ }
1749
+ if (prevIndex % cols !== cols - 1) {
1750
+ nextIndex = findNonDisabledListIndex(list, {
1751
+ startingIndex: prevIndex,
1752
+ disabledIndices
1753
+ });
1754
+ if (loopFocus && isDifferentGridRow(nextIndex, cols, prevRow)) {
1755
+ nextIndex = findNonDisabledListIndex(list, {
1756
+ startingIndex: prevIndex - prevIndex % cols - 1,
1757
+ disabledIndices
1758
+ });
1759
+ if (onLoop) {
1760
+ nextIndex = onLoop(event, prevIndex, nextIndex);
1761
+ }
1762
+ }
1763
+ } else if (loopFocus) {
1764
+ nextIndex = findNonDisabledListIndex(list, {
1765
+ startingIndex: prevIndex - prevIndex % cols - 1,
1766
+ disabledIndices
1767
+ });
1768
+ if (onLoop) {
1769
+ nextIndex = onLoop(event, prevIndex, nextIndex);
1770
+ }
1771
+ }
1772
+ if (isDifferentGridRow(nextIndex, cols, prevRow)) {
1773
+ nextIndex = prevIndex;
1774
+ }
1775
+ }
1776
+ if (event.key === (rtl ? ARROW_RIGHT : ARROW_LEFT)) {
1777
+ if (stop) {
1778
+ stopEvent(event);
1779
+ }
1780
+ if (prevIndex % cols !== 0) {
1781
+ nextIndex = findNonDisabledListIndex(list, {
1782
+ startingIndex: prevIndex,
1783
+ decrement: true,
1784
+ disabledIndices
1785
+ });
1786
+ if (loopFocus && isDifferentGridRow(nextIndex, cols, prevRow)) {
1787
+ nextIndex = findNonDisabledListIndex(list, {
1788
+ startingIndex: prevIndex + (cols - prevIndex % cols),
1789
+ decrement: true,
1790
+ disabledIndices
1791
+ });
1792
+ if (onLoop) {
1793
+ nextIndex = onLoop(event, prevIndex, nextIndex);
1794
+ }
1795
+ }
1796
+ } else if (loopFocus) {
1797
+ nextIndex = findNonDisabledListIndex(list, {
1798
+ startingIndex: prevIndex + (cols - prevIndex % cols),
1799
+ decrement: true,
1800
+ disabledIndices
1801
+ });
1802
+ if (onLoop) {
1803
+ nextIndex = onLoop(event, prevIndex, nextIndex);
1804
+ }
1805
+ }
1806
+ if (isDifferentGridRow(nextIndex, cols, prevRow)) {
1807
+ nextIndex = prevIndex;
1808
+ }
1809
+ }
1810
+ const lastRow = floatingUi_utils_dom.floor(maxIndex / cols) === prevRow;
1811
+ if (isIndexOutOfListBounds(list, nextIndex)) {
1812
+ if (loopFocus && lastRow) {
1813
+ nextIndex = event.key === (rtl ? ARROW_RIGHT : ARROW_LEFT) ? maxIndex : findNonDisabledListIndex(list, {
1814
+ startingIndex: prevIndex - prevIndex % cols - 1,
1815
+ disabledIndices
1816
+ });
1817
+ if (onLoop) {
1818
+ nextIndex = onLoop(event, prevIndex, nextIndex);
1819
+ }
1820
+ } else {
1821
+ nextIndex = prevIndex;
1822
+ }
1823
+ }
1824
+ }
1825
+ return nextIndex;
1826
+ }
1827
+
1828
+ /** For each cell index, gets the item index that occupies that cell */
1829
+ function createGridCellMap(sizes, cols, dense) {
1830
+ const cellMap = [];
1831
+ let startIndex = 0;
1832
+ sizes.forEach(({
1833
+ width,
1834
+ height
1835
+ }, index) => {
1836
+ let itemPlaced = false;
1837
+ while (!itemPlaced) {
1838
+ const targetCells = [];
1839
+ for (let i = 0; i < width; i += 1) {
1840
+ for (let j = 0; j < height; j += 1) {
1841
+ targetCells.push(startIndex + i + j * cols);
1842
+ }
1843
+ }
1844
+ if (startIndex % cols + width <= cols && targetCells.every(cell => cellMap[cell] == null)) {
1845
+ targetCells.forEach(cell => {
1846
+ cellMap[cell] = index;
1847
+ });
1848
+ itemPlaced = true;
1849
+ } else {
1850
+ startIndex += 1;
1851
+ }
1852
+ }
1853
+ });
1854
+
1855
+ // convert into a non-sparse array
1856
+ return [...cellMap];
1857
+ }
1858
+
1859
+ /** Gets cell index of an item's corner or -1 when index is -1. */
1860
+ function getGridCellIndexOfCorner(index, sizes, cellMap, cols, corner) {
1861
+ if (index === -1) {
1862
+ return -1;
1863
+ }
1864
+ const firstCellIndex = cellMap.indexOf(index);
1865
+ const sizeItem = sizes[index];
1866
+ switch (corner) {
1867
+ case 'tl':
1868
+ return firstCellIndex;
1869
+ case 'tr':
1870
+ if (!sizeItem) {
1871
+ return firstCellIndex;
1872
+ }
1873
+ return firstCellIndex + sizeItem.width - 1;
1874
+ case 'bl':
1875
+ if (!sizeItem) {
1876
+ return firstCellIndex;
1877
+ }
1878
+ return firstCellIndex + (sizeItem.height - 1) * cols;
1879
+ case 'br':
1880
+ return cellMap.lastIndexOf(index);
1881
+ default:
1882
+ return -1;
1883
+ }
1884
+ }
1885
+
1886
+ /** Gets all cell indices that correspond to the specified indices */
1887
+ function getGridCellIndices(indices, cellMap) {
1888
+ return cellMap.flatMap((index, cellIndex) => indices.includes(index) ? [cellIndex] : []);
1889
+ }
1890
+ function isListIndexDisabled(list, index, disabledIndices) {
1891
+ const isExplicitlyDisabled = typeof disabledIndices === 'function' ? disabledIndices(index) : disabledIndices?.includes(index) ?? false;
1892
+ if (isExplicitlyDisabled) {
1893
+ return true;
1894
+ }
1895
+ const element = list[index];
1896
+ if (!element) {
1897
+ return false;
1898
+ }
1899
+ if (!isElementVisible(element)) {
1900
+ return true;
1901
+ }
1902
+ return !disabledIndices && (element.hasAttribute('disabled') || element.getAttribute('aria-disabled') === 'true');
1903
+ }
1904
+ function isElementVisible(element) {
1905
+ if (typeof element.checkVisibility === 'function') {
1906
+ return element.checkVisibility();
1907
+ }
1908
+ return floatingUi_utils_dom.getComputedStyle(element).display !== 'none';
1909
+ }
1910
+
1911
+ const CANDIDATE_SELECTOR = 'a[href],button,input,select,textarea,summary,details,iframe,object,embed,[tabindex],[contenteditable]:not([contenteditable="false"]),audio[controls],video[controls]';
1912
+ function getParentElement(element) {
1913
+ const assignedSlot = element.assignedSlot;
1914
+ if (assignedSlot) {
1915
+ return assignedSlot;
1916
+ }
1917
+ if (element.parentElement) {
1918
+ return element.parentElement;
1919
+ }
1920
+ const rootNode = element.getRootNode();
1921
+ return floatingUi_utils_dom.isShadowRoot(rootNode) ? rootNode.host : null;
1922
+ }
1923
+ function getDetailsSummary(details) {
1924
+ for (const child of Array.from(details.children)) {
1925
+ if (floatingUi_utils_dom.getNodeName(child) === 'summary') {
1926
+ return child;
1927
+ }
1928
+ }
1929
+ return null;
1930
+ }
1931
+ function isWithinOpenDetailsSummary(element, details) {
1932
+ const summary = getDetailsSummary(details);
1933
+ return !!summary && (element === summary || contains(summary, element));
1934
+ }
1935
+ function isFocusableCandidate(element) {
1936
+ const nodeName = element ? floatingUi_utils_dom.getNodeName(element) : '';
1937
+ return element != null && element.matches(CANDIDATE_SELECTOR) && (nodeName !== 'summary' || element.parentElement != null && floatingUi_utils_dom.getNodeName(element.parentElement) === 'details' && getDetailsSummary(element.parentElement) === element) && (nodeName !== 'details' || getDetailsSummary(element) == null) && (nodeName !== 'input' || element.type !== 'hidden');
1938
+ }
1939
+ function isFocusableElement(element) {
1940
+ if (!isFocusableCandidate(element) || !element.isConnected || element.matches(':disabled')) {
1941
+ return false;
1942
+ }
1943
+ for (let current = element; current; current = getParentElement(current)) {
1944
+ const isSlot = floatingUi_utils_dom.getNodeName(current) === 'slot';
1945
+ if (current.hasAttribute('inert')) {
1946
+ return false;
1947
+ }
1948
+ if (current !== element && floatingUi_utils_dom.getNodeName(current) === 'details' && !current.open && !isWithinOpenDetailsSummary(element, current) || current.hasAttribute('hidden') || !isSlot && !isElementVisible(current)) {
1949
+ return false;
1950
+ }
1951
+ }
1952
+ return true;
1953
+ }
1954
+ function getTabIndex(element) {
1955
+ const tabIndex = element.tabIndex;
1956
+ if (tabIndex < 0) {
1957
+ const nodeName = floatingUi_utils_dom.getNodeName(element);
1958
+ if (nodeName === 'details' || nodeName === 'audio' || nodeName === 'video' || floatingUi_utils_dom.isHTMLElement(element) && element.isContentEditable) {
1959
+ return 0;
1960
+ }
1961
+ }
1962
+ return tabIndex;
1963
+ }
1964
+ function getNamedRadioInput(element) {
1965
+ if (floatingUi_utils_dom.getNodeName(element) !== 'input') {
1966
+ return null;
1967
+ }
1968
+ const input = element;
1969
+ return input.type === 'radio' && input.name !== '' ? input : null;
1970
+ }
1971
+ function isTabbableRadio(element, candidates) {
1972
+ const input = getNamedRadioInput(element);
1973
+ if (!input) {
1974
+ return true;
1975
+ }
1976
+ const checkedRadio = candidates.find(candidate => {
1977
+ const radio = getNamedRadioInput(candidate);
1978
+ return radio?.name === input.name && radio.form === input.form && radio.checked;
1979
+ });
1980
+ if (checkedRadio) {
1981
+ return checkedRadio === input;
1982
+ }
1983
+ return candidates.find(candidate => {
1984
+ const radio = getNamedRadioInput(candidate);
1985
+ return radio?.name === input.name && radio.form === input.form;
1986
+ }) === input;
1987
+ }
1988
+ function getComposedChildren(container) {
1989
+ if (floatingUi_utils_dom.isHTMLElement(container) && floatingUi_utils_dom.getNodeName(container) === 'slot') {
1990
+ const assignedElements = container.assignedElements({
1991
+ flatten: true
1992
+ });
1993
+ if (assignedElements.length > 0) {
1994
+ return assignedElements;
1995
+ }
1996
+ }
1997
+ if (floatingUi_utils_dom.isHTMLElement(container) && container.shadowRoot) {
1998
+ return Array.from(container.shadowRoot.children);
1999
+ }
2000
+ return Array.from(container.children);
2001
+ }
2002
+ function appendCandidates(container, list) {
2003
+ getComposedChildren(container).forEach(child => {
2004
+ if (isFocusableCandidate(child)) {
2005
+ list.push(child);
2006
+ }
2007
+ appendCandidates(child, list);
2008
+ });
2009
+ }
2010
+ function appendMatchingElements(container, selector, list) {
2011
+ getComposedChildren(container).forEach(child => {
2012
+ if (floatingUi_utils_dom.isHTMLElement(child) && child.matches(selector)) {
2013
+ list.push(child);
2014
+ }
2015
+ appendMatchingElements(child, selector, list);
2016
+ });
2017
+ }
2018
+ function isTabbable(element) {
2019
+ return isFocusableElement(element) && getTabIndex(element) >= 0;
2020
+ }
2021
+ function focusable(container) {
2022
+ const candidates = [];
2023
+ appendCandidates(container, candidates);
2024
+ return candidates.filter(isFocusableElement);
2025
+ }
2026
+ function tabbable(container) {
2027
+ const candidates = focusable(container);
2028
+ return candidates.filter(element => getTabIndex(element) >= 0 && isTabbableRadio(element, candidates));
2029
+ }
2030
+ function getTabbableIn(container, dir) {
2031
+ const list = tabbable(container);
2032
+ const len = list.length;
2033
+ if (len === 0) {
2034
+ return undefined;
2035
+ }
2036
+ const active = activeElement(ownerDocument(container));
2037
+ const index = list.indexOf(active);
2038
+ // eslint-disable-next-line no-nested-ternary
2039
+ const nextIndex = index === -1 ? dir === 1 ? 0 : len - 1 : index + dir;
2040
+ return list[nextIndex];
2041
+ }
2042
+ function getNextTabbable(referenceElement) {
2043
+ return getTabbableIn(ownerDocument(referenceElement).body, 1) || referenceElement;
2044
+ }
2045
+ function getPreviousTabbable(referenceElement) {
2046
+ return getTabbableIn(ownerDocument(referenceElement).body, -1) || referenceElement;
2047
+ }
2048
+ function isOutsideEvent(event, container) {
2049
+ const containerElement = container || event.currentTarget;
2050
+ const relatedTarget = event.relatedTarget;
2051
+ return !relatedTarget || !contains(containerElement, relatedTarget);
2052
+ }
2053
+ function disableFocusInside(container) {
2054
+ const tabbableElements = tabbable(container);
2055
+ tabbableElements.forEach(element => {
2056
+ element.dataset.tabindex = element.getAttribute('tabindex') || '';
2057
+ element.setAttribute('tabindex', '-1');
2058
+ });
2059
+ }
2060
+ function enableFocusInside(container) {
2061
+ const elements = [];
2062
+ appendMatchingElements(container, '[data-tabindex]', elements);
2063
+ elements.forEach(element => {
2064
+ const tabindex = element.dataset.tabindex;
2065
+ delete element.dataset.tabindex;
2066
+ if (tabindex) {
2067
+ element.setAttribute('tabindex', tabindex);
2068
+ } else {
2069
+ element.removeAttribute('tabindex');
2070
+ }
2071
+ });
2072
+ }
2073
+
2074
+ /* eslint-disable @typescript-eslint/no-loop-func */
2075
+
2076
+ function getNodeChildren(nodes, id, onlyOpenChildren = true) {
2077
+ const directChildren = nodes.filter(node => node.parentId === id);
2078
+ return directChildren.flatMap(child => [...(!onlyOpenChildren || child.context?.open ? [child] : []), ...getNodeChildren(nodes, child.id, onlyOpenChildren)]);
2079
+ }
2080
+ function getNodeAncestors(nodes, id) {
2081
+ let allAncestors = [];
2082
+ let currentParentId = nodes.find(node => node.id === id)?.parentId;
2083
+ while (currentParentId) {
2084
+ const currentNode = nodes.find(node => node.id === currentParentId);
2085
+ currentParentId = currentNode?.parentId;
2086
+ if (currentNode) {
2087
+ allAncestors = allAncestors.concat(currentNode);
2088
+ }
2089
+ }
2090
+ return allAncestors;
2091
+ }
2092
+
2093
+ function createAttribute(name) {
2094
+ return `data-base-ui-${name}`;
2095
+ }
2096
+
2097
+ let rafId = 0;
2098
+ function enqueueFocus(el, options = {}) {
2099
+ const {
2100
+ preventScroll = false,
2101
+ cancelPrevious = true,
2102
+ sync = false
2103
+ } = options;
2104
+ if (cancelPrevious) {
2105
+ cancelAnimationFrame(rafId);
2106
+ }
2107
+ const exec = () => el?.focus({
2108
+ preventScroll
2109
+ });
2110
+ if (sync) {
2111
+ exec();
2112
+ return NOOP;
2113
+ }
2114
+ const currentRafId = requestAnimationFrame(exec);
2115
+ rafId = currentRafId;
2116
+ return () => {
2117
+ if (rafId === currentRafId) {
2118
+ cancelAnimationFrame(currentRafId);
2119
+ rafId = 0;
2120
+ }
2121
+ };
2122
+ }
2123
+
2124
+ // Modified to add conditional `aria-hidden` support:
2125
+ // https://github.com/theKashey/aria-hidden/blob/9220c8f4a4fd35f63bee5510a9f41a37264382d4/src/index.ts
2126
+ const counters = {
2127
+ inert: new WeakMap(),
2128
+ 'aria-hidden': new WeakMap()
2129
+ };
2130
+ const markerName = 'data-base-ui-inert';
2131
+ const uncontrolledElementsSets = {
2132
+ inert: new WeakSet(),
2133
+ 'aria-hidden': new WeakSet()
2134
+ };
2135
+ let markerCounterMap = new WeakMap();
2136
+ let lockCount = 0;
2137
+ function getUncontrolledElementsSet(controlAttribute) {
2138
+ return uncontrolledElementsSets[controlAttribute];
2139
+ }
2140
+ function unwrapHost(node) {
2141
+ if (!node) {
2142
+ return null;
2143
+ }
2144
+ return floatingUi_utils_dom.isShadowRoot(node) ? node.host : unwrapHost(node.parentNode);
2145
+ }
2146
+ const correctElements = (parent, targets) => targets.map(target => {
2147
+ if (parent.contains(target)) {
2148
+ return target;
2149
+ }
2150
+ const correctedTarget = unwrapHost(target);
2151
+ if (parent.contains(correctedTarget)) {
2152
+ return correctedTarget;
2153
+ }
2154
+ return null;
2155
+ }).filter(x => x != null);
2156
+ const buildKeepSet = targets => {
2157
+ const keep = new Set();
2158
+ targets.forEach(target => {
2159
+ let node = target;
2160
+ while (node && !keep.has(node)) {
2161
+ keep.add(node);
2162
+ node = node.parentNode;
2163
+ }
2164
+ });
2165
+ return keep;
2166
+ };
2167
+ const collectOutsideElements = (root, keepElements, stopElements) => {
2168
+ const outside = [];
2169
+ const walk = parent => {
2170
+ if (!parent || stopElements.has(parent)) {
2171
+ return;
2172
+ }
2173
+ Array.from(parent.children).forEach(node => {
2174
+ if (floatingUi_utils_dom.getNodeName(node) === 'script') {
2175
+ return;
2176
+ }
2177
+ if (keepElements.has(node)) {
2178
+ walk(node);
2179
+ } else {
2180
+ outside.push(node);
2181
+ }
2182
+ });
2183
+ };
2184
+ walk(root);
2185
+ return outside;
2186
+ };
2187
+ function applyAttributeToOthers(uncorrectedAvoidElements, body, ariaHidden, inert, {
2188
+ mark = true,
2189
+ markerIgnoreElements = []
2190
+ }) {
2191
+ // eslint-disable-next-line no-nested-ternary
2192
+ const controlAttribute = inert ? 'inert' : ariaHidden ? 'aria-hidden' : null;
2193
+ let counterMap = null;
2194
+ let uncontrolledElementsSet = null;
2195
+ const avoidElements = correctElements(body, uncorrectedAvoidElements);
2196
+ const markerIgnoreTargets = mark ? correctElements(body, markerIgnoreElements) : [];
2197
+ const markerIgnoreSet = new Set(markerIgnoreTargets);
2198
+ const markerTargets = mark ? collectOutsideElements(body, buildKeepSet(avoidElements), new Set(avoidElements)).filter(target => !markerIgnoreSet.has(target)) : [];
2199
+ const hiddenElements = [];
2200
+ const markedElements = [];
2201
+ if (controlAttribute) {
2202
+ const map = counters[controlAttribute];
2203
+ const currentUncontrolledElementsSet = getUncontrolledElementsSet(controlAttribute);
2204
+ uncontrolledElementsSet = currentUncontrolledElementsSet;
2205
+ counterMap = map;
2206
+ const ariaLiveElements = correctElements(body, Array.from(body.querySelectorAll('[aria-live]')));
2207
+ const controlElements = avoidElements.concat(ariaLiveElements);
2208
+ const controlTargets = collectOutsideElements(body, buildKeepSet(controlElements), new Set(controlElements));
2209
+ controlTargets.forEach(node => {
2210
+ const attr = node.getAttribute(controlAttribute);
2211
+ const alreadyHidden = attr !== null && attr !== 'false';
2212
+ const counterValue = (map.get(node) || 0) + 1;
2213
+ map.set(node, counterValue);
2214
+ hiddenElements.push(node);
2215
+ if (counterValue === 1 && alreadyHidden) {
2216
+ currentUncontrolledElementsSet.add(node);
2217
+ }
2218
+ if (!alreadyHidden) {
2219
+ node.setAttribute(controlAttribute, controlAttribute === 'inert' ? '' : 'true');
2220
+ }
2221
+ });
2222
+ }
2223
+ if (mark) {
2224
+ markerTargets.forEach(node => {
2225
+ const markerValue = (markerCounterMap.get(node) || 0) + 1;
2226
+ markerCounterMap.set(node, markerValue);
2227
+ markedElements.push(node);
2228
+ if (markerValue === 1) {
2229
+ node.setAttribute(markerName, '');
2230
+ }
2231
+ });
2232
+ }
2233
+ lockCount += 1;
2234
+ return () => {
2235
+ if (counterMap) {
2236
+ hiddenElements.forEach(element => {
2237
+ const currentCounterValue = counterMap.get(element) || 0;
2238
+ const counterValue = currentCounterValue - 1;
2239
+ counterMap.set(element, counterValue);
2240
+ if (!counterValue) {
2241
+ if (!uncontrolledElementsSet?.has(element) && controlAttribute) {
2242
+ element.removeAttribute(controlAttribute);
2243
+ }
2244
+ uncontrolledElementsSet?.delete(element);
2245
+ }
2246
+ });
2247
+ }
2248
+ if (mark) {
2249
+ markedElements.forEach(element => {
2250
+ const markerValue = (markerCounterMap.get(element) || 0) - 1;
2251
+ markerCounterMap.set(element, markerValue);
2252
+ if (!markerValue) {
2253
+ element.removeAttribute(markerName);
2254
+ }
2255
+ });
2256
+ }
2257
+ lockCount -= 1;
2258
+ if (!lockCount) {
2259
+ counters.inert = new WeakMap();
2260
+ counters['aria-hidden'] = new WeakMap();
2261
+ uncontrolledElementsSets.inert = new WeakSet();
2262
+ uncontrolledElementsSets['aria-hidden'] = new WeakSet();
2263
+ markerCounterMap = new WeakMap();
2264
+ }
2265
+ };
2266
+ }
2267
+ function markOthers(avoidElements, options = {}) {
2268
+ const {
2269
+ ariaHidden = false,
2270
+ inert = false,
2271
+ mark = true,
2272
+ markerIgnoreElements = []
2273
+ } = options;
2274
+ const body = ownerDocument(avoidElements[0]).body;
2275
+ return applyAttributeToOthers(avoidElements, body, ariaHidden, inert, {
2276
+ mark,
2277
+ markerIgnoreElements
2278
+ });
2279
+ }
2280
+
2281
+ const PortalContext = /*#__PURE__*/React__namespace.createContext(null);
2282
+ const usePortalContext = () => React__namespace.useContext(PortalContext);
2283
+ const attr = createAttribute('portal');
2284
+ function useFloatingPortalNode(props = {}) {
2285
+ const {
2286
+ ref,
2287
+ container: containerProp,
2288
+ componentProps = EMPTY_OBJECT,
2289
+ elementProps
2290
+ } = props;
2291
+ const uniqueId = useId();
2292
+ const portalContext = usePortalContext();
2293
+ const parentPortalNode = portalContext?.portalNode;
2294
+ const [containerElement, setContainerElement] = React__namespace.useState(null);
2295
+ const [portalNode, setPortalNode] = React__namespace.useState(null);
2296
+ const setPortalNodeRef = useStableCallback(node => {
2297
+ if (node !== null) {
2298
+ // the useIsoLayoutEffect below watching containerProp / parentPortalNode
2299
+ // sets setPortalNode(null) when the container becomes null or changes.
2300
+ // So even though the ref callback now ignores null, the portal node still gets cleared.
2301
+ setPortalNode(node);
2302
+ }
2303
+ });
2304
+ const containerRef = React__namespace.useRef(null);
2305
+ useIsoLayoutEffect(() => {
2306
+ // Wait for the container to be resolved if explicitly `null`.
2307
+ if (containerProp === null) {
2308
+ if (containerRef.current) {
2309
+ containerRef.current = null;
2310
+ setPortalNode(null);
2311
+ setContainerElement(null);
2312
+ }
2313
+ return;
2314
+ }
2315
+
2316
+ // React 17 does not use React.useId().
2317
+ if (uniqueId == null) {
2318
+ return;
2319
+ }
2320
+ const resolvedContainer = (containerProp && (floatingUi_utils_dom.isNode(containerProp) ? containerProp : containerProp.current)) ?? parentPortalNode ?? document.body;
2321
+ if (resolvedContainer == null) {
2322
+ if (containerRef.current) {
2323
+ containerRef.current = null;
2324
+ setPortalNode(null);
2325
+ setContainerElement(null);
2326
+ }
2327
+ return;
2328
+ }
2329
+ if (containerRef.current !== resolvedContainer) {
2330
+ containerRef.current = resolvedContainer;
2331
+ setPortalNode(null);
2332
+ setContainerElement(resolvedContainer);
2333
+ }
2334
+ }, [containerProp, parentPortalNode, uniqueId]);
2335
+ const portalElement = useRenderElement('div', componentProps, {
2336
+ ref: [ref, setPortalNodeRef],
2337
+ props: [{
2338
+ id: uniqueId,
2339
+ [attr]: ''
2340
+ }, elementProps]
2341
+ });
2342
+
2343
+ // This `createPortal` call injects `portalElement` into the `container`.
2344
+ // Another call inside `FloatingPortal`/`FloatingPortalLite` then injects the children into `portalElement`.
2345
+ const portalSubtree = containerElement && portalElement ? /*#__PURE__*/ReactDOM__namespace.createPortal(portalElement, containerElement) : null;
2346
+ return {
2347
+ portalNode,
2348
+ portalSubtree
2349
+ };
2350
+ }
2351
+
2352
+ /**
2353
+ * Portals the floating element into a given container element — by default,
2354
+ * outside of the app root and into the body.
2355
+ * This is necessary to ensure the floating element can appear outside any
2356
+ * potential parent containers that cause clipping (such as `overflow: hidden`),
2357
+ * while retaining its location in the React tree.
2358
+ * @see https://floating-ui.com/docs/FloatingPortal
2359
+ * @internal
2360
+ */
2361
+ const FloatingPortal = /*#__PURE__*/React__namespace.forwardRef(function FloatingPortal(componentProps, forwardedRef) {
2362
+ const {
2363
+ children,
2364
+ container,
2365
+ className,
2366
+ render,
2367
+ renderGuards,
2368
+ style,
2369
+ ...elementProps
2370
+ } = componentProps;
2371
+ const {
2372
+ portalNode,
2373
+ portalSubtree
2374
+ } = useFloatingPortalNode({
2375
+ container,
2376
+ ref: forwardedRef,
2377
+ componentProps,
2378
+ elementProps
2379
+ });
2380
+ const beforeOutsideRef = React__namespace.useRef(null);
2381
+ const afterOutsideRef = React__namespace.useRef(null);
2382
+ const beforeInsideRef = React__namespace.useRef(null);
2383
+ const afterInsideRef = React__namespace.useRef(null);
2384
+ const [focusManagerState, setFocusManagerState] = React__namespace.useState(null);
2385
+ const focusInsideDisabledRef = React__namespace.useRef(false);
2386
+ const modal = focusManagerState?.modal;
2387
+ const open = focusManagerState?.open;
2388
+ const shouldRenderGuards = typeof renderGuards === 'boolean' ? renderGuards : !!focusManagerState && !focusManagerState.modal && focusManagerState.open && !!portalNode;
2389
+
2390
+ // https://codesandbox.io/s/tabbable-portal-f4tng?file=/src/TabbablePortal.tsx
2391
+ React__namespace.useEffect(() => {
2392
+ if (!portalNode || modal) {
2393
+ return undefined;
2394
+ }
2395
+
2396
+ // Make sure elements inside the portal element are tabbable only when the
2397
+ // portal has already been focused, either by tabbing into a focus trap
2398
+ // element outside or using the mouse.
2399
+ function onFocus(event) {
2400
+ if (portalNode && event.relatedTarget && isOutsideEvent(event)) {
2401
+ if (event.type === 'focusin') {
2402
+ if (focusInsideDisabledRef.current) {
2403
+ enableFocusInside(portalNode);
2404
+ focusInsideDisabledRef.current = false;
2405
+ }
2406
+ } else {
2407
+ disableFocusInside(portalNode);
2408
+ focusInsideDisabledRef.current = true;
2409
+ }
2410
+ }
2411
+ }
2412
+
2413
+ // Listen to the event on the capture phase so they run before the focus
2414
+ // trap elements onFocus prop is called.
2415
+ return mergeCleanups(addEventListener(portalNode, 'focusin', onFocus, true), addEventListener(portalNode, 'focusout', onFocus, true));
2416
+ }, [portalNode, modal]);
2417
+ React__namespace.useEffect(() => {
2418
+ if (!portalNode || open !== false) {
2419
+ return;
2420
+ }
2421
+ enableFocusInside(portalNode);
2422
+ focusInsideDisabledRef.current = false;
2423
+ }, [open, portalNode]);
2424
+ const portalContextValue = React__namespace.useMemo(() => ({
2425
+ beforeOutsideRef,
2426
+ afterOutsideRef,
2427
+ beforeInsideRef,
2428
+ afterInsideRef,
2429
+ portalNode,
2430
+ setFocusManagerState
2431
+ }), [portalNode]);
2432
+ return /*#__PURE__*/jsxRuntime.jsxs(React__namespace.Fragment, {
2433
+ children: [portalSubtree, /*#__PURE__*/jsxRuntime.jsxs(PortalContext.Provider, {
2434
+ value: portalContextValue,
2435
+ children: [shouldRenderGuards && portalNode && /*#__PURE__*/jsxRuntime.jsx(FocusGuard, {
2436
+ "data-type": "outside",
2437
+ ref: beforeOutsideRef,
2438
+ onFocus: event => {
2439
+ if (isOutsideEvent(event, portalNode)) {
2440
+ beforeInsideRef.current?.focus();
2441
+ } else {
2442
+ const domReference = focusManagerState ? focusManagerState.domReference : null;
2443
+ const prevTabbable = getPreviousTabbable(domReference);
2444
+ prevTabbable?.focus();
2445
+ }
2446
+ }
2447
+ }), shouldRenderGuards && portalNode && /*#__PURE__*/jsxRuntime.jsx("span", {
2448
+ "aria-owns": portalNode.id,
2449
+ style: ownerVisuallyHidden
2450
+ }), portalNode && /*#__PURE__*/ReactDOM__namespace.createPortal(children, portalNode), shouldRenderGuards && portalNode && /*#__PURE__*/jsxRuntime.jsx(FocusGuard, {
2451
+ "data-type": "outside",
2452
+ ref: afterOutsideRef,
2453
+ onFocus: event => {
2454
+ if (isOutsideEvent(event, portalNode)) {
2455
+ afterInsideRef.current?.focus();
2456
+ } else {
2457
+ const domReference = focusManagerState ? focusManagerState.domReference : null;
2458
+ const nextTabbable = getNextTabbable(domReference);
2459
+ nextTabbable?.focus();
2460
+ if (focusManagerState?.closeOnFocusOut) {
2461
+ focusManagerState?.onOpenChange(false, createChangeEventDetails(focusOut, event.nativeEvent));
2462
+ }
2463
+ }
2464
+ }
2465
+ })]
2466
+ })]
2467
+ });
2468
+ });
2469
+
2470
+ function createEventEmitter() {
2471
+ const map = new Map();
2472
+ return {
2473
+ emit(event, data) {
2474
+ map.get(event)?.forEach(listener => listener(data));
2475
+ },
2476
+ on(event, listener) {
2477
+ if (!map.has(event)) {
2478
+ map.set(event, new Set());
2479
+ }
2480
+ map.get(event).add(listener);
2481
+ },
2482
+ off(event, listener) {
2483
+ map.get(event)?.delete(listener);
2484
+ }
2485
+ };
2486
+ }
2487
+
2488
+ const FloatingNodeContext = /*#__PURE__*/React__namespace.createContext(null);
2489
+ const FloatingTreeContext = /*#__PURE__*/React__namespace.createContext(null);
2490
+ const useFloatingParentNodeId = () => React__namespace.useContext(FloatingNodeContext)?.id || null;
2491
+
2492
+ /**
2493
+ * Returns the nearest floating tree context, if available.
2494
+ */
2495
+ const useFloatingTree = externalTree => {
2496
+ const contextTree = React__namespace.useContext(FloatingTreeContext);
2497
+ return externalTree ?? contextTree;
2498
+ };
2499
+
2500
+ /**
2501
+ * If the provided argument is a ref object, returns its `current` value.
2502
+ * Otherwise, returns the argument itself.
2503
+ */
2504
+ function resolveRef(maybeRef) {
2505
+ if (maybeRef == null) {
2506
+ return maybeRef;
2507
+ }
2508
+ return 'current' in maybeRef ? maybeRef.current : maybeRef;
2509
+ }
2510
+
2511
+ function getEventType(event, lastInteractionType) {
2512
+ const win = floatingUi_utils_dom.getWindow(getTarget(event));
2513
+ if (event instanceof win.KeyboardEvent) {
2514
+ return 'keyboard';
2515
+ }
2516
+ if (event instanceof win.FocusEvent) {
2517
+ // Focus events can be caused by a preceding pointer interaction (e.g., focusout on outside press).
2518
+ // Prefer the last known pointer type if provided, else treat as keyboard.
2519
+ return lastInteractionType || 'keyboard';
2520
+ }
2521
+ if ('pointerType' in event) {
2522
+ return event.pointerType || 'keyboard';
2523
+ }
2524
+ if ('touches' in event) {
2525
+ return 'touch';
2526
+ }
2527
+ if (event instanceof win.MouseEvent) {
2528
+ // onClick events may not contain pointer events, and will fall through to here
2529
+ return lastInteractionType || (event.detail === 0 ? 'keyboard' : 'mouse');
2530
+ }
2531
+ return '';
2532
+ }
2533
+ const LIST_LIMIT = 20;
2534
+ let previouslyFocusedElements = [];
2535
+ function clearDisconnectedPreviouslyFocusedElements() {
2536
+ previouslyFocusedElements = previouslyFocusedElements.filter(entry => {
2537
+ return entry.deref()?.isConnected;
2538
+ });
2539
+ }
2540
+ function addPreviouslyFocusedElement(element) {
2541
+ clearDisconnectedPreviouslyFocusedElements();
2542
+ if (element && floatingUi_utils_dom.getNodeName(element) !== 'body') {
2543
+ previouslyFocusedElements.push(new WeakRef(element));
2544
+ if (previouslyFocusedElements.length > LIST_LIMIT) {
2545
+ previouslyFocusedElements = previouslyFocusedElements.slice(-LIST_LIMIT);
2546
+ }
2547
+ }
2548
+ }
2549
+ function getPreviouslyFocusedElement() {
2550
+ clearDisconnectedPreviouslyFocusedElements();
2551
+ return previouslyFocusedElements[previouslyFocusedElements.length - 1]?.deref();
2552
+ }
2553
+ function getFirstTabbableElement(container) {
2554
+ if (!container) {
2555
+ return null;
2556
+ }
2557
+ if (isTabbable(container)) {
2558
+ return container;
2559
+ }
2560
+ return tabbable(container)[0] || container;
2561
+ }
2562
+ function isFocusable(element) {
2563
+ if (!element || !element.isConnected) {
2564
+ return false;
2565
+ }
2566
+ if (typeof element.checkVisibility === 'function') {
2567
+ return element.checkVisibility();
2568
+ }
2569
+ return isElementVisible(element);
2570
+ }
2571
+ function handleTabIndex(floatingFocusElement, orderRef) {
2572
+ if (floatingFocusElement.hasAttribute('tabindex') && !floatingFocusElement.hasAttribute('data-tabindex')) {
2573
+ return;
2574
+ }
2575
+ if (!orderRef.current.includes('floating') && !floatingFocusElement.getAttribute('role')?.includes('dialog')) {
2576
+ return;
2577
+ }
2578
+ const focusableElements = focusable(floatingFocusElement);
2579
+ const tabbableContent = focusableElements.filter(element => {
2580
+ const dataTabIndex = element.getAttribute('data-tabindex') || '';
2581
+ return isTabbable(element) || element.hasAttribute('data-tabindex') && !dataTabIndex.startsWith('-');
2582
+ });
2583
+ const tabIndex = floatingFocusElement.getAttribute('tabindex');
2584
+ if (orderRef.current.includes('floating') || tabbableContent.length === 0) {
2585
+ if (tabIndex !== '0') {
2586
+ floatingFocusElement.setAttribute('tabindex', '0');
2587
+ }
2588
+ } else if (tabIndex !== '-1' || floatingFocusElement.hasAttribute('data-tabindex') && floatingFocusElement.getAttribute('data-tabindex') !== '-1') {
2589
+ floatingFocusElement.setAttribute('tabindex', '-1');
2590
+ floatingFocusElement.setAttribute('data-tabindex', '-1');
2591
+ }
2592
+ }
2593
+ /**
2594
+ * Provides focus management for the floating element.
2595
+ * @see https://floating-ui.com/docs/FloatingFocusManager
2596
+ * @internal
2597
+ */
2598
+ function FloatingFocusManager(props) {
2599
+ const {
2600
+ context,
2601
+ children,
2602
+ disabled = false,
2603
+ initialFocus = true,
2604
+ returnFocus = true,
2605
+ restoreFocus = false,
2606
+ modal = true,
2607
+ closeOnFocusOut = true,
2608
+ openInteractionType = '',
2609
+ nextFocusableElement,
2610
+ previousFocusableElement,
2611
+ beforeContentFocusGuardRef,
2612
+ externalTree,
2613
+ getInsideElements
2614
+ } = props;
2615
+ const store = 'rootStore' in context ? context.rootStore : context;
2616
+ const open = store.useState('open');
2617
+ const domReference = store.useState('domReferenceElement');
2618
+ const floating = store.useState('floatingElement');
2619
+ const {
2620
+ events,
2621
+ dataRef
2622
+ } = store.context;
2623
+ const getNodeId = useStableCallback(() => dataRef.current.floatingContext?.nodeId);
2624
+ const ignoreInitialFocus = initialFocus === false;
2625
+ // If the reference is a combobox and is typeable (e.g. input/textarea),
2626
+ // there are different focus semantics. The guards should not be rendered, but
2627
+ // aria-hidden should be applied to all nodes still. Further, the visually
2628
+ // hidden dismiss button should only appear at the end of the list, not the
2629
+ // start.
2630
+ const isUntrappedTypeableCombobox = isTypeableCombobox(domReference) && ignoreInitialFocus;
2631
+ const orderRef = React__namespace.useRef(['content']);
2632
+ const initialFocusRef = useValueAsRef(initialFocus);
2633
+ const returnFocusRef = useValueAsRef(returnFocus);
2634
+ const openInteractionTypeRef = useValueAsRef(openInteractionType);
2635
+ const tree = useFloatingTree(externalTree);
2636
+ const portalContext = usePortalContext();
2637
+ const preventReturnFocusRef = React__namespace.useRef(false);
2638
+ const isPointerDownRef = React__namespace.useRef(false);
2639
+ const pointerDownOutsideRef = React__namespace.useRef(false);
2640
+ const lastFocusedTabbableRef = React__namespace.useRef(null);
2641
+ const closeTypeRef = React__namespace.useRef('');
2642
+ const lastInteractionTypeRef = React__namespace.useRef('');
2643
+ const beforeGuardRef = React__namespace.useRef(null);
2644
+ const afterGuardRef = React__namespace.useRef(null);
2645
+ const mergedBeforeGuardRef = useMergedRefs(beforeGuardRef, beforeContentFocusGuardRef, portalContext?.beforeInsideRef);
2646
+ const mergedAfterGuardRef = useMergedRefs(afterGuardRef, portalContext?.afterInsideRef);
2647
+ const blurTimeout = useTimeout();
2648
+ const pointerDownTimeout = useTimeout();
2649
+ const restoreFocusFrame = useAnimationFrame();
2650
+ const isInsidePortal = portalContext != null;
2651
+ const floatingFocusElement = getFloatingFocusElement(floating);
2652
+ const getTabbableContent = useStableCallback((container = floatingFocusElement) => {
2653
+ return container ? tabbable(container) : [];
2654
+ });
2655
+ const getResolvedInsideElements = useStableCallback(() => getInsideElements?.().filter(element => element != null) ?? []);
2656
+
2657
+ // Prevent Tab from escaping the modal when there are no tabbable elements.
2658
+ React__namespace.useEffect(() => {
2659
+ if (disabled || !modal) {
2660
+ return undefined;
2661
+ }
2662
+ function onKeyDown(event) {
2663
+ if (event.key === 'Tab') {
2664
+ // The focus guards have nothing to focus, so we need to stop the event.
2665
+ if (contains(floatingFocusElement, activeElement(ownerDocument(floatingFocusElement))) && getTabbableContent().length === 0 && !isUntrappedTypeableCombobox) {
2666
+ stopEvent(event);
2667
+ }
2668
+ }
2669
+ }
2670
+ const doc = ownerDocument(floatingFocusElement);
2671
+ return addEventListener(doc, 'keydown', onKeyDown);
2672
+ }, [disabled, domReference, floatingFocusElement, modal, orderRef, isUntrappedTypeableCombobox, getTabbableContent]);
2673
+
2674
+ // Track pointer/keyboard interactions to disambiguate focus and outside presses.
2675
+ React__namespace.useEffect(() => {
2676
+ if (disabled || !open) {
2677
+ return undefined;
2678
+ }
2679
+ const doc = ownerDocument(floatingFocusElement);
2680
+ function clearPointerDownOutside() {
2681
+ pointerDownOutsideRef.current = false;
2682
+ }
2683
+ function onPointerDown(event) {
2684
+ const target = getTarget(event);
2685
+ const insideElements = getResolvedInsideElements();
2686
+ const pointerTargetInside = contains(floating, target) || contains(domReference, target) || contains(portalContext?.portalNode, target) || insideElements.some(element => element === target || contains(element, target));
2687
+ pointerDownOutsideRef.current = !pointerTargetInside;
2688
+ lastInteractionTypeRef.current = event.pointerType || 'keyboard';
2689
+ if (target?.closest(`[${CLICK_TRIGGER_IDENTIFIER}]`)) {
2690
+ isPointerDownRef.current = true;
2691
+ }
2692
+ }
2693
+ function onKeyDown() {
2694
+ lastInteractionTypeRef.current = 'keyboard';
2695
+ }
2696
+ return mergeCleanups(addEventListener(doc, 'pointerdown', onPointerDown, true), addEventListener(doc, 'pointerup', clearPointerDownOutside, true), addEventListener(doc, 'pointercancel', clearPointerDownOutside, true), addEventListener(doc, 'keydown', onKeyDown, true));
2697
+ }, [disabled, floating, domReference, floatingFocusElement, open, portalContext, getResolvedInsideElements]);
2698
+
2699
+ // Close on focus out and restore focus within the floating tree when needed.
2700
+ React__namespace.useEffect(() => {
2701
+ if (disabled || !closeOnFocusOut) {
2702
+ return undefined;
2703
+ }
2704
+ const doc = ownerDocument(floatingFocusElement);
2705
+
2706
+ // In Safari, buttons lose focus when pressing them.
2707
+ function handlePointerDown() {
2708
+ isPointerDownRef.current = true;
2709
+ pointerDownTimeout.start(0, () => {
2710
+ isPointerDownRef.current = false;
2711
+ });
2712
+ }
2713
+ function handleFocusIn(event) {
2714
+ const target = getTarget(event);
2715
+ if (isTabbable(target)) {
2716
+ lastFocusedTabbableRef.current = target;
2717
+ }
2718
+ }
2719
+ function handleFocusOutside(event) {
2720
+ const relatedTarget = event.relatedTarget;
2721
+ const currentTarget = event.currentTarget;
2722
+ const target = getTarget(event);
2723
+ queueMicrotask(() => {
2724
+ const nodeId = getNodeId();
2725
+ const triggers = store.context.triggerElements;
2726
+ const insideElements = getResolvedInsideElements();
2727
+ const isRelatedFocusGuard = relatedTarget?.hasAttribute(createAttribute('focus-guard')) && [beforeGuardRef.current, afterGuardRef.current, portalContext?.beforeInsideRef.current, portalContext?.afterInsideRef.current, portalContext?.beforeOutsideRef.current, portalContext?.afterOutsideRef.current, resolveRef(previousFocusableElement), resolveRef(nextFocusableElement)].includes(relatedTarget);
2728
+ const movedToUnrelatedNode = !(contains(domReference, relatedTarget) || contains(floating, relatedTarget) || contains(relatedTarget, floating) || contains(portalContext?.portalNode, relatedTarget) || insideElements.some(element => element === relatedTarget || contains(element, relatedTarget)) || relatedTarget != null && triggers.hasElement(relatedTarget) || triggers.hasMatchingElement(trigger => contains(trigger, relatedTarget)) || isRelatedFocusGuard || tree && (getNodeChildren(tree.nodesRef.current, nodeId).find(node => contains(node.context?.elements.floating, relatedTarget) || contains(node.context?.elements.domReference, relatedTarget)) || getNodeAncestors(tree.nodesRef.current, nodeId).find(node => [node.context?.elements.floating, getFloatingFocusElement(node.context?.elements.floating)].includes(relatedTarget) || node.context?.elements.domReference === relatedTarget)));
2729
+ if (currentTarget === domReference && floatingFocusElement) {
2730
+ handleTabIndex(floatingFocusElement, orderRef);
2731
+ }
2732
+
2733
+ // Restore focus to the previous tabbable element index to prevent
2734
+ // focus from being lost outside the floating tree.
2735
+ if (restoreFocus && currentTarget !== domReference && !isFocusable(target) && activeElement(doc) === doc.body) {
2736
+ // Let `FloatingPortal` effect knows that focus is still inside the
2737
+ // floating tree.
2738
+ if (floatingUi_utils_dom.isHTMLElement(floatingFocusElement)) {
2739
+ floatingFocusElement.focus();
2740
+ // If explicitly requested to restore focus to the popup container, do not search
2741
+ // for the next/previous tabbable element.
2742
+ if (restoreFocus === 'popup') {
2743
+ // If the element is removed on pointerdown, focus tries to move it,
2744
+ // but since it's removed at the same time, focus gets lost as it
2745
+ // happens after the .focus() call above.
2746
+ // In this case, focus needs to be moved asynchronously.
2747
+ restoreFocusFrame.request(() => {
2748
+ floatingFocusElement.focus();
2749
+ });
2750
+ return;
2751
+ }
2752
+ }
2753
+ const tabbableContent = getTabbableContent();
2754
+ const prevTabbable = lastFocusedTabbableRef.current;
2755
+ const nodeToFocus = (prevTabbable && tabbableContent.includes(prevTabbable) ? prevTabbable : null) || tabbableContent[tabbableContent.length - 1] || floatingFocusElement;
2756
+ if (floatingUi_utils_dom.isHTMLElement(nodeToFocus)) {
2757
+ nodeToFocus.focus();
2758
+ }
2759
+ }
2760
+
2761
+ // https://github.com/floating-ui/floating-ui/issues/3060
2762
+ if (dataRef.current.insideReactTree) {
2763
+ dataRef.current.insideReactTree = false;
2764
+ return;
2765
+ }
2766
+
2767
+ // Focus did not move inside the floating tree, and there are no tabbable
2768
+ // portal guards to handle closing.
2769
+ if ((isUntrappedTypeableCombobox ? true : !modal) && relatedTarget && movedToUnrelatedNode && !isPointerDownRef.current && (
2770
+ // Fix React 18 Strict Mode returnFocus due to double rendering.
2771
+ // For an "untrapped" typeable combobox (input role=combobox with
2772
+ // initialFocus=false), re-opening the popup and tabbing out should still close it even
2773
+ // when the previously focused element (e.g. the next tabbable outside the popup) is
2774
+ // focused again. Otherwise, the popup remains open on the second Tab sequence:
2775
+ // click input -> Tab (closes) -> click input -> Tab.
2776
+ // Allow closing when `isUntrappedTypeableCombobox` regardless of the previously focused element.
2777
+ isUntrappedTypeableCombobox || relatedTarget !== getPreviouslyFocusedElement())) {
2778
+ preventReturnFocusRef.current = true;
2779
+ store.setOpen(false, createChangeEventDetails(focusOut, event));
2780
+ }
2781
+ });
2782
+ }
2783
+ function markInsideReactTree() {
2784
+ if (pointerDownOutsideRef.current) {
2785
+ return;
2786
+ }
2787
+ dataRef.current.insideReactTree = true;
2788
+ blurTimeout.start(0, () => {
2789
+ dataRef.current.insideReactTree = false;
2790
+ });
2791
+ }
2792
+ const domReferenceElement = floatingUi_utils_dom.isHTMLElement(domReference) ? domReference : null;
2793
+ if (!floating && !domReferenceElement) {
2794
+ return undefined;
2795
+ }
2796
+ return mergeCleanups(domReferenceElement && addEventListener(domReferenceElement, 'focusout', handleFocusOutside), domReferenceElement && addEventListener(domReferenceElement, 'pointerdown', handlePointerDown), floating && addEventListener(floating, 'focusin', handleFocusIn), floating && addEventListener(floating, 'focusout', handleFocusOutside), floating && portalContext && addEventListener(floating, 'focusout', markInsideReactTree, true));
2797
+ }, [disabled, domReference, floating, floatingFocusElement, modal, tree, portalContext, store, closeOnFocusOut, restoreFocus, getTabbableContent, isUntrappedTypeableCombobox, getNodeId, orderRef, dataRef, blurTimeout, pointerDownTimeout, restoreFocusFrame, nextFocusableElement, previousFocusableElement, getResolvedInsideElements]);
2798
+
2799
+ // Hide everything outside the floating tree from assistive tech while open.
2800
+ React__namespace.useEffect(() => {
2801
+ if (disabled || !floating || !open) {
2802
+ return undefined;
2803
+ }
2804
+
2805
+ // Don't hide portals nested within the parent portal.
2806
+ const portalNodes = Array.from(portalContext?.portalNode?.querySelectorAll(`[${createAttribute('portal')}]`) || []);
2807
+ const ancestors = tree ? getNodeAncestors(tree.nodesRef.current, getNodeId()) : [];
2808
+ const rootAncestorComboboxDomReference = ancestors.find(node => isTypeableCombobox(node.context?.elements.domReference || null))?.context?.elements.domReference;
2809
+ const controlInsideElements = [floating, ...portalNodes, beforeGuardRef.current, afterGuardRef.current, portalContext?.beforeOutsideRef.current, portalContext?.afterOutsideRef.current, ...getResolvedInsideElements()];
2810
+ const insideElements = [...controlInsideElements, rootAncestorComboboxDomReference, resolveRef(previousFocusableElement), resolveRef(nextFocusableElement), isUntrappedTypeableCombobox ? domReference : null].filter(x => x != null);
2811
+ const ariaHiddenCleanup = markOthers(insideElements, {
2812
+ ariaHidden: modal || isUntrappedTypeableCombobox,
2813
+ mark: false
2814
+ });
2815
+ const markerInsideElements = [floating, ...portalNodes].filter(x => x != null);
2816
+ const markerCleanup = markOthers(markerInsideElements);
2817
+ return () => {
2818
+ markerCleanup();
2819
+ ariaHiddenCleanup();
2820
+ };
2821
+ }, [open, disabled, domReference, floating, modal, orderRef, portalContext, isUntrappedTypeableCombobox, tree, getNodeId, nextFocusableElement, previousFocusableElement, getResolvedInsideElements]);
2822
+
2823
+ // Focus the initial element when the floating element opens.
2824
+ useIsoLayoutEffect(() => {
2825
+ if (!open || disabled || !floatingUi_utils_dom.isHTMLElement(floatingFocusElement)) {
2826
+ return;
2827
+ }
2828
+ const doc = ownerDocument(floatingFocusElement);
2829
+ const previouslyFocusedElement = activeElement(doc);
2830
+
2831
+ // Wait for any layout effect state setters to execute to set `tabIndex`.
2832
+ queueMicrotask(() => {
2833
+ const initialFocusValueOrFn = initialFocusRef.current;
2834
+ const resolvedInitialFocus = typeof initialFocusValueOrFn === 'function' ? initialFocusValueOrFn(openInteractionTypeRef.current || '') : initialFocusValueOrFn;
2835
+
2836
+ // `null` should fallback to default behavior in case of an empty ref.
2837
+ if (resolvedInitialFocus === undefined || resolvedInitialFocus === false) {
2838
+ return;
2839
+ }
2840
+ const focusAlreadyInsideFloatingEl = contains(floatingFocusElement, previouslyFocusedElement);
2841
+ if (focusAlreadyInsideFloatingEl) {
2842
+ return;
2843
+ }
2844
+ let focusableElements = null;
2845
+ const getDefaultFocusElement = () => {
2846
+ if (focusableElements == null) {
2847
+ focusableElements = getTabbableContent(floatingFocusElement);
2848
+ }
2849
+ return focusableElements[0] || floatingFocusElement;
2850
+ };
2851
+ let elToFocus;
2852
+ if (resolvedInitialFocus === true || resolvedInitialFocus === null) {
2853
+ elToFocus = getDefaultFocusElement();
2854
+ } else {
2855
+ elToFocus = resolveRef(resolvedInitialFocus);
2856
+ }
2857
+ elToFocus = elToFocus || getDefaultFocusElement();
2858
+ enqueueFocus(elToFocus, {
2859
+ preventScroll: elToFocus === floatingFocusElement
2860
+ });
2861
+ });
2862
+ }, [disabled, open, floatingFocusElement, ignoreInitialFocus, getTabbableContent, initialFocusRef, openInteractionTypeRef]);
2863
+
2864
+ // Track return focus targets and restore focus on unmount/close.
2865
+ useIsoLayoutEffect(() => {
2866
+ if (disabled || !floatingFocusElement) {
2867
+ return undefined;
2868
+ }
2869
+ const doc = ownerDocument(floatingFocusElement);
2870
+ const previouslyFocusedElement = activeElement(doc);
2871
+ addPreviouslyFocusedElement(previouslyFocusedElement);
2872
+
2873
+ // Dismissing via outside press should always ignore `returnFocus` to
2874
+ // prevent unwanted scrolling.
2875
+ function onOpenChangeLocal(details) {
2876
+ if (!details.open) {
2877
+ closeTypeRef.current = getEventType(details.nativeEvent, lastInteractionTypeRef.current);
2878
+ }
2879
+ if (details.reason === triggerHover && details.nativeEvent.type === 'mouseleave') {
2880
+ preventReturnFocusRef.current = true;
2881
+ }
2882
+ if (details.reason !== outsidePress) {
2883
+ return;
2884
+ }
2885
+ if (details.nested) {
2886
+ preventReturnFocusRef.current = false;
2887
+ } else if (isVirtualClick(details.nativeEvent) || isVirtualPointerEvent(details.nativeEvent)) {
2888
+ preventReturnFocusRef.current = false;
2889
+ } else {
2890
+ let isPreventScrollSupported = false;
2891
+ ownerDocument(floatingFocusElement).createElement('div').focus({
2892
+ get preventScroll() {
2893
+ isPreventScrollSupported = true;
2894
+ return false;
2895
+ }
2896
+ });
2897
+ if (isPreventScrollSupported) {
2898
+ preventReturnFocusRef.current = false;
2899
+ } else {
2900
+ preventReturnFocusRef.current = true;
2901
+ }
2902
+ }
2903
+ }
2904
+ events.on('openchange', onOpenChangeLocal);
2905
+ function getReturnElement() {
2906
+ const returnFocusValueOrFn = returnFocusRef.current;
2907
+ let resolvedReturnFocusValue = typeof returnFocusValueOrFn === 'function' ? returnFocusValueOrFn(closeTypeRef.current) : returnFocusValueOrFn;
2908
+
2909
+ // `null` should fallback to default behavior in case of an empty ref.
2910
+ if (resolvedReturnFocusValue === undefined || resolvedReturnFocusValue === false) {
2911
+ return null;
2912
+ }
2913
+ if (resolvedReturnFocusValue === null) {
2914
+ resolvedReturnFocusValue = true;
2915
+ }
2916
+ if (typeof resolvedReturnFocusValue === 'boolean') {
2917
+ const el = domReference || getPreviouslyFocusedElement();
2918
+ return el && el.isConnected ? el : null;
2919
+ }
2920
+ const fallback = domReference || getPreviouslyFocusedElement();
2921
+ return resolveRef(resolvedReturnFocusValue) || fallback || null;
2922
+ }
2923
+ return () => {
2924
+ events.off('openchange', onOpenChangeLocal);
2925
+ const activeEl = activeElement(doc);
2926
+ const insideElements = getResolvedInsideElements();
2927
+ const isFocusInsideFloatingTree = contains(floating, activeEl) || insideElements.some(element => element === activeEl || contains(element, activeEl)) || tree && getNodeChildren(tree.nodesRef.current, getNodeId(), false).some(node => contains(node.context?.elements.floating, activeEl));
2928
+
2929
+ // eslint-disable-next-line react-hooks/exhaustive-deps
2930
+ const returnFocusValueOrFn = returnFocusRef.current;
2931
+ const returnElement = getReturnElement();
2932
+ queueMicrotask(() => {
2933
+ // This is `returnElement`, if it's tabbable, or its first tabbable child.
2934
+ const tabbableReturnElement = getFirstTabbableElement(returnElement);
2935
+ const hasExplicitReturnFocus = typeof returnFocusValueOrFn !== 'boolean';
2936
+ if (returnFocusValueOrFn && !preventReturnFocusRef.current && floatingUi_utils_dom.isHTMLElement(tabbableReturnElement) && (
2937
+ // If the focus moved somewhere else after mount, avoid returning focus
2938
+ // since it likely entered a different element which should be
2939
+ // respected: https://github.com/floating-ui/floating-ui/issues/2607
2940
+ !hasExplicitReturnFocus && tabbableReturnElement !== activeEl && activeEl !== doc.body ? isFocusInsideFloatingTree : true)) {
2941
+ tabbableReturnElement.focus({
2942
+ preventScroll: true
2943
+ });
2944
+ }
2945
+ preventReturnFocusRef.current = false;
2946
+ });
2947
+ };
2948
+ }, [disabled, floating, floatingFocusElement, returnFocusRef, dataRef, events, tree, domReference, getNodeId, getResolvedInsideElements]);
2949
+
2950
+ // Safari may randomly scroll to the bottom of the page if an input inside a popup has focus
2951
+ // when the popup unmounts from the DOM.
2952
+ // By blurring it before the popup unmounts, we can prevent this behavior.
2953
+ useIsoLayoutEffect(() => {
2954
+ if (!isWebKit || open || !floating) {
2955
+ return;
2956
+ }
2957
+ const activeEl = activeElement(ownerDocument(floating));
2958
+ if (!floatingUi_utils_dom.isHTMLElement(activeEl) || !isTypeableElement(activeEl)) {
2959
+ return;
2960
+ }
2961
+ if (contains(floating, activeEl)) {
2962
+ activeEl.blur();
2963
+ }
2964
+ }, [open, floating]);
2965
+ // Synchronize the `context` & `modal` value to the FloatingPortal context.
2966
+ // It will decide whether or not it needs to render its own guards.
2967
+ useIsoLayoutEffect(() => {
2968
+ if (disabled || !portalContext) {
2969
+ return undefined;
2970
+ }
2971
+ portalContext.setFocusManagerState({
2972
+ modal,
2973
+ closeOnFocusOut,
2974
+ open,
2975
+ onOpenChange: store.setOpen,
2976
+ domReference
2977
+ });
2978
+ return () => {
2979
+ portalContext.setFocusManagerState(null);
2980
+ };
2981
+ }, [disabled, portalContext, modal, open, store, closeOnFocusOut, domReference]);
2982
+
2983
+ // Keep the floating element tabIndex in sync and clear stale focus records.
2984
+ useIsoLayoutEffect(() => {
2985
+ if (disabled || !floatingFocusElement) {
2986
+ return undefined;
2987
+ }
2988
+ handleTabIndex(floatingFocusElement, orderRef);
2989
+ return () => {
2990
+ queueMicrotask(clearDisconnectedPreviouslyFocusedElements);
2991
+ };
2992
+ }, [disabled, floatingFocusElement, orderRef]);
2993
+ const shouldRenderGuards = !disabled && (modal ? !isUntrappedTypeableCombobox : true) && (isInsidePortal || modal);
2994
+ return /*#__PURE__*/jsxRuntime.jsxs(React__namespace.Fragment, {
2995
+ children: [shouldRenderGuards && /*#__PURE__*/jsxRuntime.jsx(FocusGuard, {
2996
+ "data-type": "inside",
2997
+ ref: mergedBeforeGuardRef,
2998
+ onFocus: event => {
2999
+ if (modal) {
3000
+ const els = getTabbableContent();
3001
+ enqueueFocus(els[els.length - 1]);
3002
+ } else if (portalContext?.portalNode) {
3003
+ preventReturnFocusRef.current = false;
3004
+ if (isOutsideEvent(event, portalContext.portalNode)) {
3005
+ const nextTabbable = getNextTabbable(domReference);
3006
+ nextTabbable?.focus();
3007
+ } else {
3008
+ resolveRef(previousFocusableElement ?? portalContext.beforeOutsideRef)?.focus();
3009
+ }
3010
+ }
3011
+ }
3012
+ }), children, shouldRenderGuards && /*#__PURE__*/jsxRuntime.jsx(FocusGuard, {
3013
+ "data-type": "inside",
3014
+ ref: mergedAfterGuardRef,
3015
+ onFocus: event => {
3016
+ if (modal) {
3017
+ enqueueFocus(getTabbableContent()[0]);
3018
+ } else if (portalContext?.portalNode) {
3019
+ if (closeOnFocusOut) {
3020
+ preventReturnFocusRef.current = true;
3021
+ }
3022
+ if (isOutsideEvent(event, portalContext.portalNode)) {
3023
+ const prevTabbable = getPreviousTabbable(domReference);
3024
+ prevTabbable?.focus();
3025
+ } else {
3026
+ resolveRef(nextFocusableElement ?? portalContext.afterOutsideRef)?.focus();
3027
+ }
3028
+ }
3029
+ }
3030
+ })]
3031
+ });
3032
+ }
3033
+
3034
+ /**
3035
+ * Opens or closes the floating element when clicking the reference element.
3036
+ * @see https://floating-ui.com/docs/useClick
3037
+ */
3038
+ function useClick(context, props = {}) {
3039
+ const store = 'rootStore' in context ? context.rootStore : context;
3040
+ const dataRef = store.context.dataRef;
3041
+ const {
3042
+ enabled = true,
3043
+ event: eventOption = 'click',
3044
+ toggle = true,
3045
+ ignoreMouse = false,
3046
+ stickIfOpen = true,
3047
+ touchOpenDelay = 0,
3048
+ reason = triggerPress
3049
+ } = props;
3050
+ const pointerTypeRef = React__namespace.useRef(undefined);
3051
+ const frame = useAnimationFrame();
3052
+ const touchOpenTimeout = useTimeout();
3053
+ const reference = React__namespace.useMemo(() => ({
3054
+ onPointerDown(event) {
3055
+ pointerTypeRef.current = event.pointerType;
3056
+ },
3057
+ onMouseDown(event) {
3058
+ const pointerType = pointerTypeRef.current;
3059
+ const nativeEvent = event.nativeEvent;
3060
+ const open = store.select('open');
3061
+
3062
+ // Ignore all buttons except for the "main" button.
3063
+ // https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button
3064
+ if (event.button !== 0 || eventOption === 'click' || isMouseLikePointerType(pointerType) && ignoreMouse) {
3065
+ return;
3066
+ }
3067
+ const openEvent = dataRef.current.openEvent;
3068
+ const openEventType = openEvent?.type;
3069
+ const hasClickedOnInactiveTrigger = store.select('domReferenceElement') !== event.currentTarget;
3070
+ const nextOpen = open && hasClickedOnInactiveTrigger || !(open && toggle && (openEvent && stickIfOpen ? openEventType === 'click' || openEventType === 'mousedown' : true));
3071
+
3072
+ // Animations sometimes won't run on a typeable element if using a rAF.
3073
+ // Focus is always set on these elements. For touch, we may delay opening.
3074
+ const target = getTarget(nativeEvent);
3075
+ if (isTypeableElement(target)) {
3076
+ const details = createChangeEventDetails(reason, nativeEvent, target);
3077
+ if (nextOpen && pointerType === 'touch' && touchOpenDelay > 0) {
3078
+ touchOpenTimeout.start(touchOpenDelay, () => {
3079
+ store.setOpen(true, details);
3080
+ });
3081
+ } else {
3082
+ store.setOpen(nextOpen, details);
3083
+ }
3084
+ return;
3085
+ }
3086
+
3087
+ // Capture the currentTarget before the rAF.
3088
+ // as React sets it to null after the event handler completes.
3089
+ const eventCurrentTarget = event.currentTarget;
3090
+
3091
+ // Wait until focus is set on the element. This is an alternative to
3092
+ // `event.preventDefault()` to avoid :focus-visible from appearing when using a pointer.
3093
+ frame.request(() => {
3094
+ const details = createChangeEventDetails(reason, nativeEvent, eventCurrentTarget);
3095
+ if (nextOpen && pointerType === 'touch' && touchOpenDelay > 0) {
3096
+ touchOpenTimeout.start(touchOpenDelay, () => {
3097
+ store.setOpen(true, details);
3098
+ });
3099
+ } else {
3100
+ store.setOpen(nextOpen, details);
3101
+ }
3102
+ });
3103
+ },
3104
+ onClick(event) {
3105
+ if (eventOption === 'mousedown-only') {
3106
+ return;
3107
+ }
3108
+ const pointerType = pointerTypeRef.current;
3109
+ if (eventOption === 'mousedown' && pointerType) {
3110
+ pointerTypeRef.current = undefined;
3111
+ return;
3112
+ }
3113
+ if (isMouseLikePointerType(pointerType) && ignoreMouse) {
3114
+ return;
3115
+ }
3116
+ const open = store.select('open');
3117
+ const openEvent = dataRef.current.openEvent;
3118
+ const hasClickedOnInactiveTrigger = store.select('domReferenceElement') !== event.currentTarget;
3119
+ const nextOpen = open && hasClickedOnInactiveTrigger || !(open && toggle && (openEvent && stickIfOpen ? isClickLikeEvent(openEvent) : true));
3120
+ const details = createChangeEventDetails(reason, event.nativeEvent, event.currentTarget);
3121
+ if (nextOpen && pointerType === 'touch' && touchOpenDelay > 0) {
3122
+ touchOpenTimeout.start(touchOpenDelay, () => {
3123
+ store.setOpen(true, details);
3124
+ });
3125
+ } else {
3126
+ store.setOpen(nextOpen, details);
3127
+ }
3128
+ },
3129
+ onKeyDown() {
3130
+ pointerTypeRef.current = undefined;
3131
+ }
3132
+ }), [dataRef, eventOption, ignoreMouse, store, stickIfOpen, toggle, frame, touchOpenTimeout, touchOpenDelay, reason]);
3133
+ return React__namespace.useMemo(() => enabled ? {
3134
+ reference
3135
+ } : EMPTY_OBJECT, [enabled, reference]);
3136
+ }
3137
+
3138
+ const bubbleHandlerKeys = {
3139
+ intentional: 'onClick',
3140
+ sloppy: 'onPointerDown'
3141
+ };
3142
+ function alwaysFalse() {
3143
+ return false;
3144
+ }
3145
+ function normalizeProp(normalizable) {
3146
+ return {
3147
+ escapeKey: typeof normalizable === 'boolean' ? normalizable : normalizable?.escapeKey ?? false,
3148
+ outsidePress: typeof normalizable === 'boolean' ? normalizable : normalizable?.outsidePress ?? true
3149
+ };
3150
+ }
3151
+ /**
3152
+ * Closes the floating element when a dismissal is requested — by default, when
3153
+ * the user presses the `escape` key or outside of the floating element.
3154
+ * @see https://floating-ui.com/docs/useDismiss
3155
+ */
3156
+ function useDismiss(context, props = {}) {
3157
+ const store = 'rootStore' in context ? context.rootStore : context;
3158
+ const open = store.useState('open');
3159
+ const floatingElement = store.useState('floatingElement');
3160
+ const {
3161
+ dataRef
3162
+ } = store.context;
3163
+ const {
3164
+ enabled = true,
3165
+ escapeKey: escapeKey$1 = true,
3166
+ outsidePress: outsidePressProp = true,
3167
+ outsidePressEvent = 'sloppy',
3168
+ referencePress = alwaysFalse,
3169
+ referencePressEvent = 'sloppy',
3170
+ bubbles,
3171
+ externalTree
3172
+ } = props;
3173
+ const tree = useFloatingTree(externalTree);
3174
+ const outsidePressFn = useStableCallback(typeof outsidePressProp === 'function' ? outsidePressProp : () => false);
3175
+ const outsidePress$1 = typeof outsidePressProp === 'function' ? outsidePressFn : outsidePressProp;
3176
+ const outsidePressEnabled = outsidePress$1 !== false;
3177
+ const getOutsidePressEventProp = useStableCallback(() => outsidePressEvent);
3178
+ const pressStartedInsideRef = React__namespace.useRef(false);
3179
+ const pressStartPreventedRef = React__namespace.useRef(false);
3180
+ // Ignore only the very next outside click after dragging from inside to outside.
3181
+ const suppressNextOutsideClickRef = React__namespace.useRef(false);
3182
+ const {
3183
+ escapeKey: escapeKeyBubbles,
3184
+ outsidePress: outsidePressBubbles
3185
+ } = normalizeProp(bubbles);
3186
+ const touchStateRef = React__namespace.useRef(null);
3187
+ const cancelDismissOnEndTimeout = useTimeout();
3188
+ const clearInsideReactTreeTimeout = useTimeout();
3189
+ const clearInsideReactTree = useStableCallback(() => {
3190
+ clearInsideReactTreeTimeout.clear();
3191
+ dataRef.current.insideReactTree = false;
3192
+ });
3193
+ const isComposingRef = React__namespace.useRef(false);
3194
+ const currentPointerTypeRef = React__namespace.useRef('');
3195
+ const isReferencePressEnabled = useStableCallback(referencePress);
3196
+ const closeOnEscapeKeyDown = useStableCallback(event => {
3197
+ if (!open || !enabled || !escapeKey$1 || event.key !== 'Escape') {
3198
+ return;
3199
+ }
3200
+
3201
+ // Wait until IME is settled. Pressing `Escape` while composing should
3202
+ // close the compose menu, but not the floating element.
3203
+ if (isComposingRef.current) {
3204
+ return;
3205
+ }
3206
+ const nodeId = dataRef.current.floatingContext?.nodeId;
3207
+ const children = tree ? getNodeChildren(tree.nodesRef.current, nodeId) : [];
3208
+ if (!escapeKeyBubbles) {
3209
+ if (children.length > 0) {
3210
+ let shouldDismiss = true;
3211
+ children.forEach(child => {
3212
+ if (child.context?.open && !child.context.dataRef.current.__escapeKeyBubbles) {
3213
+ shouldDismiss = false;
3214
+ }
3215
+ });
3216
+ if (!shouldDismiss) {
3217
+ return;
3218
+ }
3219
+ }
3220
+ }
3221
+ const native = isReactEvent(event) ? event.nativeEvent : event;
3222
+ const eventDetails = createChangeEventDetails(escapeKey, native);
3223
+ store.setOpen(false, eventDetails);
3224
+ if (!escapeKeyBubbles && !eventDetails.isPropagationAllowed) {
3225
+ event.stopPropagation();
3226
+ }
3227
+ });
3228
+ const markInsideReactTree = useStableCallback(() => {
3229
+ dataRef.current.insideReactTree = true;
3230
+ clearInsideReactTreeTimeout.start(0, clearInsideReactTree);
3231
+ });
3232
+ React__namespace.useEffect(() => {
3233
+ if (!open || !enabled) {
3234
+ return undefined;
3235
+ }
3236
+ dataRef.current.__escapeKeyBubbles = escapeKeyBubbles;
3237
+ dataRef.current.__outsidePressBubbles = outsidePressBubbles;
3238
+ const compositionTimeout = new Timeout();
3239
+ const preventedPressSuppressionTimeout = new Timeout();
3240
+ function handleCompositionStart() {
3241
+ compositionTimeout.clear();
3242
+ isComposingRef.current = true;
3243
+ }
3244
+ function handleCompositionEnd() {
3245
+ // Safari fires `compositionend` before `keydown`, so we need to wait
3246
+ // until the next tick to set `isComposing` to `false`.
3247
+ // https://bugs.webkit.org/show_bug.cgi?id=165004
3248
+ compositionTimeout.start(
3249
+ // 0ms or 1ms don't work in Safari. 5ms appears to consistently work.
3250
+ // Only apply to WebKit for the test to remain 0ms.
3251
+ floatingUi_utils_dom.isWebKit() ? 5 : 0, () => {
3252
+ isComposingRef.current = false;
3253
+ });
3254
+ }
3255
+ function suppressImmediateOutsideClickAfterPreventedStart() {
3256
+ suppressNextOutsideClickRef.current = true;
3257
+ // Firefox can emit the synthetic outside click in a later task after
3258
+ // pointer lock exit, so microtask clearing is too early here.
3259
+ preventedPressSuppressionTimeout.start(0, () => {
3260
+ suppressNextOutsideClickRef.current = false;
3261
+ });
3262
+ }
3263
+ function resetPressStartState() {
3264
+ pressStartedInsideRef.current = false;
3265
+ pressStartPreventedRef.current = false;
3266
+ }
3267
+ function getOutsidePressEvent() {
3268
+ const type = currentPointerTypeRef.current;
3269
+ const computedType = type === 'pen' || !type ? 'mouse' : type;
3270
+ const outsidePressEventValue = getOutsidePressEventProp();
3271
+ const resolved = typeof outsidePressEventValue === 'function' ? outsidePressEventValue() : outsidePressEventValue;
3272
+ if (typeof resolved === 'string') {
3273
+ return resolved;
3274
+ }
3275
+ return resolved[computedType];
3276
+ }
3277
+ function shouldIgnoreEvent(event) {
3278
+ const computedOutsidePressEvent = getOutsidePressEvent();
3279
+ return computedOutsidePressEvent === 'intentional' && event.type !== 'click' || computedOutsidePressEvent === 'sloppy' && event.type === 'click';
3280
+ }
3281
+ function isEventWithinFloatingTree(event) {
3282
+ const nodeId = dataRef.current.floatingContext?.nodeId;
3283
+ const targetIsInsideChildren = tree && getNodeChildren(tree.nodesRef.current, nodeId).some(node => isEventTargetWithin(event, node.context?.elements.floating));
3284
+ return isEventTargetWithin(event, store.select('floatingElement')) || isEventTargetWithin(event, store.select('domReferenceElement')) || targetIsInsideChildren;
3285
+ }
3286
+ function closeOnPressOutside(event) {
3287
+ if (shouldIgnoreEvent(event)) {
3288
+ clearInsideReactTree();
3289
+ return;
3290
+ }
3291
+ if (dataRef.current.insideReactTree) {
3292
+ clearInsideReactTree();
3293
+ return;
3294
+ }
3295
+ const target = getTarget(event);
3296
+ const inertSelector = `[${createAttribute('inert')}]`;
3297
+ const targetRoot = floatingUi_utils_dom.isElement(target) ? target.getRootNode() : null;
3298
+ const markers = Array.from((floatingUi_utils_dom.isShadowRoot(targetRoot) ? targetRoot : ownerDocument(store.select('floatingElement'))).querySelectorAll(inertSelector));
3299
+ const triggers = store.context.triggerElements;
3300
+
3301
+ // If another trigger is clicked, don't close the floating element.
3302
+ if (target && (triggers.hasElement(target) || triggers.hasMatchingElement(trigger => contains(trigger, target)))) {
3303
+ return;
3304
+ }
3305
+ let targetRootAncestor = floatingUi_utils_dom.isElement(target) ? target : null;
3306
+ while (targetRootAncestor && !floatingUi_utils_dom.isLastTraversableNode(targetRootAncestor)) {
3307
+ const nextParent = floatingUi_utils_dom.getParentNode(targetRootAncestor);
3308
+ if (floatingUi_utils_dom.isLastTraversableNode(nextParent) || !floatingUi_utils_dom.isElement(nextParent)) {
3309
+ break;
3310
+ }
3311
+ targetRootAncestor = nextParent;
3312
+ }
3313
+
3314
+ // Check if the click occurred on a third-party element injected after the
3315
+ // floating element rendered.
3316
+ if (markers.length && floatingUi_utils_dom.isElement(target) && !isRootElement(target) &&
3317
+ // Clicked on a direct ancestor (e.g. FloatingOverlay).
3318
+ !contains(target, store.select('floatingElement')) &&
3319
+ // If the target root element contains none of the markers, then the
3320
+ // element was injected after the floating element rendered.
3321
+ markers.every(marker => !contains(targetRootAncestor, marker))) {
3322
+ return;
3323
+ }
3324
+
3325
+ // Check if the click occurred on the scrollbar
3326
+ // Skip for touch events: scrollbars don't receive touch events on most platforms
3327
+ if (floatingUi_utils_dom.isHTMLElement(target) && !('touches' in event)) {
3328
+ const lastTraversableNode = floatingUi_utils_dom.isLastTraversableNode(target);
3329
+ const style = floatingUi_utils_dom.getComputedStyle(target);
3330
+ const scrollRe = /auto|scroll/;
3331
+ const isScrollableX = lastTraversableNode || scrollRe.test(style.overflowX);
3332
+ const isScrollableY = lastTraversableNode || scrollRe.test(style.overflowY);
3333
+ const canScrollX = isScrollableX && target.clientWidth > 0 && target.scrollWidth > target.clientWidth;
3334
+ const canScrollY = isScrollableY && target.clientHeight > 0 && target.scrollHeight > target.clientHeight;
3335
+ const isRTL = style.direction === 'rtl';
3336
+
3337
+ // Check click position relative to scrollbar.
3338
+ // In some browsers it is possible to change the <body> (or window)
3339
+ // scrollbar to the left side, but is very rare and is difficult to
3340
+ // check for. Plus, for modal dialogs with backdrops, it is more
3341
+ // important that the backdrop is checked but not so much the window.
3342
+ const pressedVerticalScrollbar = canScrollY && (isRTL ? event.offsetX <= target.offsetWidth - target.clientWidth : event.offsetX > target.clientWidth);
3343
+ const pressedHorizontalScrollbar = canScrollX && event.offsetY > target.clientHeight;
3344
+ if (pressedVerticalScrollbar || pressedHorizontalScrollbar) {
3345
+ return;
3346
+ }
3347
+ }
3348
+ if (isEventWithinFloatingTree(event)) {
3349
+ return;
3350
+ }
3351
+
3352
+ // In intentional mode, a press that starts inside and ends outside gets
3353
+ // one suppressed outside click. Run this after inside-target checks so
3354
+ // inside clicks don't consume the one-shot suppression.
3355
+ if (getOutsidePressEvent() === 'intentional' && suppressNextOutsideClickRef.current) {
3356
+ preventedPressSuppressionTimeout.clear();
3357
+ suppressNextOutsideClickRef.current = false;
3358
+ return;
3359
+ }
3360
+ if (typeof outsidePress$1 === 'function' && !outsidePress$1(event)) {
3361
+ return;
3362
+ }
3363
+ const nodeId = dataRef.current.floatingContext?.nodeId;
3364
+ const children = tree ? getNodeChildren(tree.nodesRef.current, nodeId) : [];
3365
+ if (children.length > 0) {
3366
+ let shouldDismiss = true;
3367
+ children.forEach(child => {
3368
+ if (child.context?.open && !child.context.dataRef.current.__outsidePressBubbles) {
3369
+ shouldDismiss = false;
3370
+ }
3371
+ });
3372
+ if (!shouldDismiss) {
3373
+ return;
3374
+ }
3375
+ }
3376
+ store.setOpen(false, createChangeEventDetails(outsidePress, event));
3377
+ clearInsideReactTree();
3378
+ }
3379
+ function handlePointerDown(event) {
3380
+ if (getOutsidePressEvent() !== 'sloppy' || event.pointerType === 'touch' || !store.select('open') || !enabled || isEventTargetWithin(event, store.select('floatingElement')) || isEventTargetWithin(event, store.select('domReferenceElement'))) {
3381
+ return;
3382
+ }
3383
+ closeOnPressOutside(event);
3384
+ }
3385
+ function handleTouchStart(event) {
3386
+ if (getOutsidePressEvent() !== 'sloppy' || !store.select('open') || !enabled || isEventTargetWithin(event, store.select('floatingElement')) || isEventTargetWithin(event, store.select('domReferenceElement'))) {
3387
+ return;
3388
+ }
3389
+ const touch = event.touches[0];
3390
+ if (touch) {
3391
+ touchStateRef.current = {
3392
+ startTime: Date.now(),
3393
+ startX: touch.clientX,
3394
+ startY: touch.clientY,
3395
+ dismissOnTouchEnd: false,
3396
+ dismissOnMouseDown: true
3397
+ };
3398
+ cancelDismissOnEndTimeout.start(1000, () => {
3399
+ if (touchStateRef.current) {
3400
+ touchStateRef.current.dismissOnTouchEnd = false;
3401
+ touchStateRef.current.dismissOnMouseDown = false;
3402
+ }
3403
+ });
3404
+ }
3405
+ }
3406
+ function addTargetEventListenerOnce(event, listener) {
3407
+ const target = getTarget(event);
3408
+ if (!target) {
3409
+ return;
3410
+ }
3411
+ const unsubscribe = addEventListener(target, event.type, () => {
3412
+ listener(event);
3413
+ unsubscribe();
3414
+ });
3415
+ }
3416
+ function handleTouchStartCapture(event) {
3417
+ currentPointerTypeRef.current = 'touch';
3418
+ addTargetEventListenerOnce(event, handleTouchStart);
3419
+ }
3420
+ function closeOnPressOutsideCapture(event) {
3421
+ cancelDismissOnEndTimeout.clear();
3422
+ if (event.type === 'pointerdown') {
3423
+ currentPointerTypeRef.current = event.pointerType;
3424
+ }
3425
+ if (event.type === 'mousedown' && touchStateRef.current && !touchStateRef.current.dismissOnMouseDown) {
3426
+ return;
3427
+ }
3428
+ addTargetEventListenerOnce(event, targetEvent => {
3429
+ if (targetEvent.type === 'pointerdown') {
3430
+ handlePointerDown(targetEvent);
3431
+ } else {
3432
+ closeOnPressOutside(targetEvent);
3433
+ }
3434
+ });
3435
+ }
3436
+ function handlePressEndCapture(event) {
3437
+ if (!pressStartedInsideRef.current) {
3438
+ return;
3439
+ }
3440
+ const pressStartedInsideDefaultPrevented = pressStartPreventedRef.current;
3441
+ resetPressStartState();
3442
+ if (getOutsidePressEvent() !== 'intentional') {
3443
+ return;
3444
+ }
3445
+ if (event.type === 'pointercancel') {
3446
+ if (pressStartedInsideDefaultPrevented) {
3447
+ suppressImmediateOutsideClickAfterPreventedStart();
3448
+ }
3449
+ return;
3450
+ }
3451
+ if (isEventWithinFloatingTree(event)) {
3452
+ return;
3453
+ }
3454
+
3455
+ // If pointerdown was prevented, no click may be generated for that
3456
+ // interaction. However, Firefox may still emit an immediate click after
3457
+ // pointerup (e.g. NumberField scrub with pointer lock), so suppress for
3458
+ // one tick to absorb that synthetic click only.
3459
+ if (pressStartedInsideDefaultPrevented) {
3460
+ suppressImmediateOutsideClickAfterPreventedStart();
3461
+ return;
3462
+ }
3463
+
3464
+ // Avoid suppressing when outsidePress explicitly ignores this target.
3465
+ if (typeof outsidePress$1 === 'function' && !outsidePress$1(event)) {
3466
+ return;
3467
+ }
3468
+ preventedPressSuppressionTimeout.clear();
3469
+ suppressNextOutsideClickRef.current = true;
3470
+ clearInsideReactTree();
3471
+ }
3472
+ function handleTouchMove(event) {
3473
+ if (getOutsidePressEvent() !== 'sloppy' || !touchStateRef.current || isEventTargetWithin(event, store.select('floatingElement')) || isEventTargetWithin(event, store.select('domReferenceElement'))) {
3474
+ return;
3475
+ }
3476
+ const touch = event.touches[0];
3477
+ if (!touch) {
3478
+ return;
3479
+ }
3480
+ const deltaX = Math.abs(touch.clientX - touchStateRef.current.startX);
3481
+ const deltaY = Math.abs(touch.clientY - touchStateRef.current.startY);
3482
+ const distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
3483
+ if (distance > 5) {
3484
+ touchStateRef.current.dismissOnTouchEnd = true;
3485
+ }
3486
+ if (distance > 10) {
3487
+ closeOnPressOutside(event);
3488
+ cancelDismissOnEndTimeout.clear();
3489
+ touchStateRef.current = null;
3490
+ }
3491
+ }
3492
+ function handleTouchMoveCapture(event) {
3493
+ addTargetEventListenerOnce(event, handleTouchMove);
3494
+ }
3495
+ function handleTouchEnd(event) {
3496
+ if (getOutsidePressEvent() !== 'sloppy' || !touchStateRef.current || isEventTargetWithin(event, store.select('floatingElement')) || isEventTargetWithin(event, store.select('domReferenceElement'))) {
3497
+ return;
3498
+ }
3499
+ if (touchStateRef.current.dismissOnTouchEnd) {
3500
+ closeOnPressOutside(event);
3501
+ }
3502
+ cancelDismissOnEndTimeout.clear();
3503
+ touchStateRef.current = null;
3504
+ }
3505
+ function handleTouchEndCapture(event) {
3506
+ addTargetEventListenerOnce(event, handleTouchEnd);
3507
+ }
3508
+ const doc = ownerDocument(floatingElement);
3509
+ const unsubscribe = mergeCleanups(escapeKey$1 && mergeCleanups(addEventListener(doc, 'keydown', closeOnEscapeKeyDown), addEventListener(doc, 'compositionstart', handleCompositionStart), addEventListener(doc, 'compositionend', handleCompositionEnd)), outsidePressEnabled && mergeCleanups(addEventListener(doc, 'click', closeOnPressOutsideCapture, true), addEventListener(doc, 'pointerdown', closeOnPressOutsideCapture, true), addEventListener(doc, 'pointerup', handlePressEndCapture, true), addEventListener(doc, 'pointercancel', handlePressEndCapture, true), addEventListener(doc, 'mousedown', closeOnPressOutsideCapture, true), addEventListener(doc, 'mouseup', handlePressEndCapture, true), addEventListener(doc, 'touchstart', handleTouchStartCapture, true), addEventListener(doc, 'touchmove', handleTouchMoveCapture, true), addEventListener(doc, 'touchend', handleTouchEndCapture, true)));
3510
+ return () => {
3511
+ unsubscribe();
3512
+ compositionTimeout.clear();
3513
+ preventedPressSuppressionTimeout.clear();
3514
+ resetPressStartState();
3515
+ suppressNextOutsideClickRef.current = false;
3516
+ };
3517
+ }, [dataRef, floatingElement, escapeKey$1, outsidePressEnabled, outsidePress$1, open, enabled, escapeKeyBubbles, outsidePressBubbles, closeOnEscapeKeyDown, clearInsideReactTree, getOutsidePressEventProp, tree, store, cancelDismissOnEndTimeout]);
3518
+ React__namespace.useEffect(clearInsideReactTree, [outsidePress$1, clearInsideReactTree]);
3519
+ const reference = React__namespace.useMemo(() => ({
3520
+ onKeyDown: closeOnEscapeKeyDown,
3521
+ [bubbleHandlerKeys[referencePressEvent]]: event => {
3522
+ if (!isReferencePressEnabled()) {
3523
+ return;
3524
+ }
3525
+ store.setOpen(false, createChangeEventDetails(triggerPress, event.nativeEvent));
3526
+ },
3527
+ ...(referencePressEvent !== 'intentional' && {
3528
+ onClick(event) {
3529
+ if (!isReferencePressEnabled()) {
3530
+ return;
3531
+ }
3532
+ store.setOpen(false, createChangeEventDetails(triggerPress, event.nativeEvent));
3533
+ }
3534
+ })
3535
+ }), [closeOnEscapeKeyDown, store, referencePressEvent, isReferencePressEnabled]);
3536
+ const markPressStartedInsideReactTree = useStableCallback(event => {
3537
+ if (!open || !enabled || event.button !== 0) {
3538
+ return;
3539
+ }
3540
+ const target = getTarget(event.nativeEvent);
3541
+ // Only treat presses that start within the floating DOM subtree as inside.
3542
+ // This avoids suppressing parent dismissal when interacting with nested portals.
3543
+ if (!contains(store.select('floatingElement'), target)) {
3544
+ return;
3545
+ }
3546
+ if (!pressStartedInsideRef.current) {
3547
+ pressStartedInsideRef.current = true;
3548
+ pressStartPreventedRef.current = false;
3549
+ }
3550
+ });
3551
+ const markInsidePressStartPrevented = useStableCallback(event => {
3552
+ if (!open || !enabled) {
3553
+ return;
3554
+ }
3555
+ if (!(event.defaultPrevented || event.nativeEvent.defaultPrevented)) {
3556
+ return;
3557
+ }
3558
+ if (pressStartedInsideRef.current) {
3559
+ pressStartPreventedRef.current = true;
3560
+ }
3561
+ });
3562
+ const floating = React__namespace.useMemo(() => ({
3563
+ onKeyDown: closeOnEscapeKeyDown,
3564
+ // `onMouseDown` may be blocked if `event.preventDefault()` is called in
3565
+ // `onPointerDown`, such as with <NumberField.ScrubArea>.
3566
+ // See https://github.com/mui/base-ui/pull/3379
3567
+ onPointerDown: markInsidePressStartPrevented,
3568
+ onMouseDown: markInsidePressStartPrevented,
3569
+ onClickCapture: markInsideReactTree,
3570
+ onMouseDownCapture(event) {
3571
+ markInsideReactTree();
3572
+ markPressStartedInsideReactTree(event);
3573
+ },
3574
+ onPointerDownCapture(event) {
3575
+ markInsideReactTree();
3576
+ markPressStartedInsideReactTree(event);
3577
+ },
3578
+ onMouseUpCapture: markInsideReactTree,
3579
+ onTouchEndCapture: markInsideReactTree,
3580
+ onTouchMoveCapture: markInsideReactTree
3581
+ }), [closeOnEscapeKeyDown, markInsideReactTree, markPressStartedInsideReactTree, markInsidePressStartPrevented]);
3582
+ return React__namespace.useMemo(() => enabled ? {
3583
+ reference,
3584
+ floating,
3585
+ trigger: reference
3586
+ } : {}, [enabled, reference, floating]);
3587
+ }
3588
+
3589
+ /**
3590
+ * The NoOptionalParams type is a utility type that checks if a function has optional or default parameters.
3591
+ * If the function has optional or default parameters, it returns a string literal type with an error message.
3592
+ * Otherwise, it returns the original function type.
3593
+ *
3594
+ * This is used to enforce that the combiner function passed to createSelector does not have optional or default parameters,
3595
+ * as memoization relies on the Function.length property, which does not account for optional or default parameters.
3596
+ */
3597
+
3598
+ /**
3599
+ * Creates a selector function that can be used to derive values from the store's state.
3600
+ *
3601
+ * The combiner function can have up to three additional parameters, but it **cannot have optional or default parameters**.
3602
+ *
3603
+ * This function accepts up to six functions and combines them into a single selector function.
3604
+ * The resulting selector will take the state from the combined selectors and any additional parameters required by the combiner.
3605
+ *
3606
+ * The return type of the resulting selector is determined by the return type of the combiner function.
3607
+ *
3608
+ * @example
3609
+ * const selector = createSelector(
3610
+ * (state) => state.disabled
3611
+ * );
3612
+ *
3613
+ * @example
3614
+ * const selector = createSelector(
3615
+ * (state) => state.disabled,
3616
+ * (state) => state.open,
3617
+ * (disabled, open) => ({ disabled, open })
3618
+ * );
3619
+ */
3620
+ /* eslint-disable id-denylist */
3621
+ const createSelector = (a, b, c, d, e, f, ...other) => {
3622
+ if (other.length > 0) {
3623
+ throw new Error(formatErrorMessage(1));
3624
+ }
3625
+ let selector;
3626
+ if (a) {
3627
+ selector = a;
3628
+ } else {
3629
+ throw /* minify-error-disabled */new Error('Missing arguments');
3630
+ }
3631
+ return selector;
3632
+ };
3633
+ /* eslint-enable id-denylist */
3634
+
3635
+ /* Some tests fail in R18 with the raw useSyncExternalStore. It may be possible to make it work
3636
+ * but for now we only enable it for R19+. */
3637
+ const canUseRawUseSyncExternalStore = isReactVersionAtLeast(19);
3638
+ const useStoreImplementation = canUseRawUseSyncExternalStore ? useStoreFast : useStoreLegacy;
3639
+ function useStore(store, selector, a1, a2, a3) {
3640
+ return useStoreImplementation(store, selector, a1, a2, a3);
3641
+ }
3642
+ function useStoreR19(store, selector, a1, a2, a3) {
3643
+ const getSelection = React__namespace.useCallback(() => selector(store.getSnapshot(), a1, a2, a3), [store, selector, a1, a2, a3]);
3644
+ return index.shimExports.useSyncExternalStore(store.subscribe, getSelection, getSelection);
3645
+ }
3646
+ function useStoreFast(store, selector, a1, a2, a3) {
3647
+ {
3648
+ // eslint-disable-next-line react-hooks/rules-of-hooks
3649
+ return useStoreR19(store, selector, a1, a2, a3);
3650
+ }
3651
+ }
3652
+ function useStoreLegacy(store, selector, a1, a2, a3) {
3653
+ return withSelector.withSelectorExports.useSyncExternalStoreWithSelector(store.subscribe, store.getSnapshot, store.getSnapshot, state => selector(state, a1, a2, a3));
3654
+ }
3655
+
3656
+ /**
3657
+ * A data store implementation that allows subscribing to state changes and updating the state.
3658
+ * It uses an observer pattern to notify subscribers when the state changes.
3659
+ */
3660
+ class Store {
3661
+ /**
3662
+ * The current state of the store.
3663
+ * This property is updated immediately when the state changes as a result of calling {@link setState}, {@link update}, or {@link set}.
3664
+ * To subscribe to state changes, use the {@link useState} method. The value returned by {@link useState} is updated after the component renders (similarly to React's useState).
3665
+ * The values can be used directly (to avoid subscribing to the store) in effects or event handlers.
3666
+ *
3667
+ * Do not modify properties in state directly. Instead, use the provided methods to ensure proper state management and listener notification.
3668
+ */
3669
+
3670
+ // Internal state to handle recursive `setState()` calls
3671
+
3672
+ constructor(state) {
3673
+ this.state = state;
3674
+ this.listeners = new Set();
3675
+ this.updateTick = 0;
3676
+ }
3677
+
3678
+ /**
3679
+ * Registers a listener that will be called whenever the store's state changes.
3680
+ *
3681
+ * @param fn The listener function to be called on state changes.
3682
+ * @returns A function to unsubscribe the listener.
3683
+ */
3684
+ subscribe = fn => {
3685
+ this.listeners.add(fn);
3686
+ return () => {
3687
+ this.listeners.delete(fn);
3688
+ };
3689
+ };
3690
+
3691
+ /**
3692
+ * Returns the current state of the store.
3693
+ */
3694
+ getSnapshot = () => {
3695
+ return this.state;
3696
+ };
3697
+
3698
+ /**
3699
+ * Updates the entire store's state and notifies all registered listeners.
3700
+ *
3701
+ * @param newState The new state to set for the store.
3702
+ */
3703
+ setState(newState) {
3704
+ if (this.state === newState) {
3705
+ return;
3706
+ }
3707
+ this.state = newState;
3708
+ this.updateTick += 1;
3709
+ const currentTick = this.updateTick;
3710
+ for (const listener of this.listeners) {
3711
+ if (currentTick !== this.updateTick) {
3712
+ // If the tick has changed, a recursive `setState` call has been made,
3713
+ // and it has already notified all listeners.
3714
+ return;
3715
+ }
3716
+ listener(newState);
3717
+ }
3718
+ }
3719
+
3720
+ /**
3721
+ * Merges the provided changes into the current state and notifies listeners if there are changes.
3722
+ *
3723
+ * @param changes An object containing the changes to apply to the current state.
3724
+ */
3725
+ update(changes) {
3726
+ for (const key in changes) {
3727
+ if (!Object.is(this.state[key], changes[key])) {
3728
+ this.setState({
3729
+ ...this.state,
3730
+ ...changes
3731
+ });
3732
+ return;
3733
+ }
3734
+ }
3735
+ }
3736
+
3737
+ /**
3738
+ * Sets a specific key in the store's state to a new value and notifies listeners if the value has changed.
3739
+ *
3740
+ * @param key The key in the store's state to update.
3741
+ * @param value The new value to set for the specified key.
3742
+ */
3743
+ set(key, value) {
3744
+ if (!Object.is(this.state[key], value)) {
3745
+ this.setState({
3746
+ ...this.state,
3747
+ [key]: value
3748
+ });
3749
+ }
3750
+ }
3751
+
3752
+ /**
3753
+ * Gives the state a new reference and updates all registered listeners.
3754
+ */
3755
+ notifyAll() {
3756
+ const newState = {
3757
+ ...this.state
3758
+ };
3759
+ this.setState(newState);
3760
+ }
3761
+ use(selector, a1, a2, a3) {
3762
+ // eslint-disable-next-line react-hooks/rules-of-hooks
3763
+ return useStore(this, selector, a1, a2, a3);
3764
+ }
3765
+ }
3766
+
3767
+ /* False positives - ESLint thinks we're calling a hook from a class component. */
3768
+ /* eslint-disable react-hooks/rules-of-hooks */
3769
+
3770
+ /**
3771
+ * A Store that supports controlled state keys, non-reactive values and provides utility methods for React.
3772
+ */
3773
+ class ReactStore extends Store {
3774
+ /**
3775
+ * Creates a new ReactStore instance.
3776
+ *
3777
+ * @param state Initial state of the store.
3778
+ * @param context Non-reactive context values.
3779
+ * @param selectors Optional selectors for use with `useState`.
3780
+ */
3781
+ constructor(state, context = {}, selectors) {
3782
+ super(state);
3783
+ this.context = context;
3784
+ this.selectors = selectors;
3785
+ }
3786
+
3787
+ /**
3788
+ * Non-reactive values such as refs, callbacks, etc.
3789
+ */
3790
+
3791
+ /**
3792
+ * Synchronizes a single external value into the store.
3793
+ *
3794
+ * Note that the while the value in `state` is updated immediately, the value returned
3795
+ * by `useState` is updated before the next render (similarly to React's `useState`).
3796
+ */
3797
+ useSyncedValue(key, value) {
3798
+ React__namespace.useDebugValue(key);
3799
+ useIsoLayoutEffect(() => {
3800
+ if (this.state[key] !== value) {
3801
+ this.set(key, value);
3802
+ }
3803
+ }, [key, value]);
3804
+ }
3805
+
3806
+ /**
3807
+ * Synchronizes a single external value into the store and
3808
+ * cleans it up (sets to `undefined`) on unmount.
3809
+ *
3810
+ * Note that the while the value in `state` is updated immediately, the value returned
3811
+ * by `useState` is updated before the next render (similarly to React's `useState`).
3812
+ */
3813
+ useSyncedValueWithCleanup(key, value) {
3814
+ // eslint-disable-next-line consistent-this
3815
+ const store = this;
3816
+ useIsoLayoutEffect(() => {
3817
+ if (store.state[key] !== value) {
3818
+ store.set(key, value);
3819
+ }
3820
+ return () => {
3821
+ store.set(key, undefined);
3822
+ };
3823
+ }, [store, key, value]);
3824
+ }
3825
+
3826
+ /**
3827
+ * Synchronizes multiple external values into the store.
3828
+ *
3829
+ * Note that the while the values in `state` are updated immediately, the values returned
3830
+ * by `useState` are updated before the next render (similarly to React's `useState`).
3831
+ */
3832
+ useSyncedValues(statePart) {
3833
+ // eslint-disable-next-line consistent-this
3834
+ const store = this;
3835
+ const dependencies = Object.values(statePart);
3836
+ useIsoLayoutEffect(() => {
3837
+ store.update(statePart);
3838
+ // eslint-disable-next-line react-hooks/exhaustive-deps
3839
+ }, [store, ...dependencies]);
3840
+ }
3841
+
3842
+ /**
3843
+ * Registers a controllable prop pair (`controlled`, `defaultValue`) for a specific key. If `controlled`
3844
+ * is non-undefined, the store's state at `key` is updated to match `controlled`.
3845
+ */
3846
+ useControlledProp(key, controlled) {
3847
+ React__namespace.useDebugValue(key);
3848
+ const isControlled = controlled !== undefined;
3849
+ useIsoLayoutEffect(() => {
3850
+ if (isControlled && !Object.is(this.state[key], controlled)) {
3851
+ // Set the internal state to match the controlled value.
3852
+ super.setState({
3853
+ ...this.state,
3854
+ [key]: controlled
3855
+ });
3856
+ }
3857
+ }, [key, controlled, isControlled]);
3858
+ }
3859
+
3860
+ /** Gets the current value from the store using a selector with the provided key.
3861
+ *
3862
+ * @param key Key of the selector to use.
3863
+ */
3864
+
3865
+ select(key, a1, a2, a3) {
3866
+ const selector = this.selectors[key];
3867
+ return selector(this.state, a1, a2, a3);
3868
+ }
3869
+
3870
+ /**
3871
+ * Returns a value from the store's state using a selector function.
3872
+ * Used to subscribe to specific parts of the state.
3873
+ * This methods causes a rerender whenever the selected state changes.
3874
+ *
3875
+ * @param key Key of the selector to use.
3876
+ */
3877
+
3878
+ useState(key, a1, a2, a3) {
3879
+ React__namespace.useDebugValue(key);
3880
+ return useStore(this, this.selectors[key], a1, a2, a3);
3881
+ }
3882
+
3883
+ /**
3884
+ * Wraps a function with `useStableCallback` to ensure it has a stable reference
3885
+ * and assigns it to the context.
3886
+ *
3887
+ * @param key Key of the event callback. Must be a function in the context.
3888
+ * @param fn Function to assign.
3889
+ */
3890
+ useContextCallback(key, fn) {
3891
+ React__namespace.useDebugValue(key);
3892
+ const stableFunction = useStableCallback(fn ?? NOOP);
3893
+ this.context[key] = stableFunction;
3894
+ }
3895
+
3896
+ /**
3897
+ * Returns a stable setter function for a specific key in the store's state.
3898
+ * It's commonly used to pass as a ref callback to React elements.
3899
+ *
3900
+ * @param key Key of the state to set.
3901
+ */
3902
+ useStateSetter(key) {
3903
+ const ref = React__namespace.useRef(undefined);
3904
+ if (ref.current === undefined) {
3905
+ ref.current = value => {
3906
+ this.set(key, value);
3907
+ };
3908
+ }
3909
+ return ref.current;
3910
+ }
3911
+
3912
+ /**
3913
+ * Observes changes derived from the store's selectors and calls the listener when the selected value changes.
3914
+ *
3915
+ * @param key Key of the selector to observe.
3916
+ * @param listener Listener function called when the selector result changes.
3917
+ */
3918
+
3919
+ observe(selector, listener) {
3920
+ let selectFn;
3921
+ if (typeof selector === 'function') {
3922
+ selectFn = selector;
3923
+ } else {
3924
+ selectFn = this.selectors[selector];
3925
+ }
3926
+ let prevValue = selectFn(this.state);
3927
+ listener(prevValue, prevValue, this);
3928
+ return this.subscribe(nextState => {
3929
+ const nextValue = selectFn(nextState);
3930
+ if (!Object.is(prevValue, nextValue)) {
3931
+ const oldValue = prevValue;
3932
+ prevValue = nextValue;
3933
+ listener(nextValue, oldValue, this);
3934
+ }
3935
+ });
3936
+ }
3937
+ }
3938
+
3939
+ const selectors = {
3940
+ open: createSelector(state => state.open),
3941
+ transitionStatus: createSelector(state => state.transitionStatus),
3942
+ domReferenceElement: createSelector(state => state.domReferenceElement),
3943
+ referenceElement: createSelector(state => state.positionReference ?? state.referenceElement),
3944
+ floatingElement: createSelector(state => state.floatingElement),
3945
+ floatingId: createSelector(state => state.floatingId)
3946
+ };
3947
+ class FloatingRootStore extends ReactStore {
3948
+ constructor(options) {
3949
+ const {
3950
+ syncOnly,
3951
+ nested,
3952
+ onOpenChange,
3953
+ triggerElements,
3954
+ ...initialState
3955
+ } = options;
3956
+ super({
3957
+ ...initialState,
3958
+ positionReference: initialState.referenceElement,
3959
+ domReferenceElement: initialState.referenceElement
3960
+ }, {
3961
+ onOpenChange,
3962
+ dataRef: {
3963
+ current: {}
3964
+ },
3965
+ events: createEventEmitter(),
3966
+ nested,
3967
+ triggerElements
3968
+ }, selectors);
3969
+ this.syncOnly = syncOnly;
3970
+ }
3971
+
3972
+ /**
3973
+ * Syncs the event used by hover logic to distinguish hover-open from click-like interaction.
3974
+ */
3975
+ syncOpenEvent = (newOpen, event) => {
3976
+ if (!newOpen || !this.state.open ||
3977
+ // Prevent a pending hover-open from overwriting a click-open event, while allowing
3978
+ // click events to upgrade a hover-open.
3979
+ event != null && isClickLikeEvent(event)) {
3980
+ this.context.dataRef.current.openEvent = newOpen ? event : undefined;
3981
+ }
3982
+ };
3983
+
3984
+ /**
3985
+ * Runs the root-owned side effects for an open state change.
3986
+ */
3987
+ dispatchOpenChange = (newOpen, eventDetails) => {
3988
+ this.syncOpenEvent(newOpen, eventDetails.event);
3989
+ const details = {
3990
+ open: newOpen,
3991
+ reason: eventDetails.reason,
3992
+ nativeEvent: eventDetails.event,
3993
+ nested: this.context.nested,
3994
+ triggerElement: eventDetails.trigger
3995
+ };
3996
+ this.context.events.emit('openchange', details);
3997
+ };
3998
+
3999
+ /**
4000
+ * Emits the `openchange` event through the internal event emitter and calls the `onOpenChange` handler with the provided arguments.
4001
+ *
4002
+ * @param newOpen The new open state.
4003
+ * @param eventDetails Details about the event that triggered the open state change.
4004
+ */
4005
+ setOpen = (newOpen, eventDetails) => {
4006
+ if (this.syncOnly) {
4007
+ this.context.onOpenChange?.(newOpen, eventDetails);
4008
+ return;
4009
+ }
4010
+ this.dispatchOpenChange(newOpen, eventDetails);
4011
+ this.context.onOpenChange?.(newOpen, eventDetails);
4012
+ };
4013
+ }
4014
+
4015
+ /**
4016
+ * Provides a status string for CSS animations.
4017
+ * @param open - a boolean that determines if the element is open.
4018
+ * @param enableIdleState - a boolean that enables the `'idle'` state between `'starting'` and `'ending'`
4019
+ */
4020
+ function useTransitionStatus(open, enableIdleState = false, deferEndingState = false) {
4021
+ const [transitionStatus, setTransitionStatus] = React__namespace.useState(open && enableIdleState ? 'idle' : undefined);
4022
+ const [mounted, setMounted] = React__namespace.useState(open);
4023
+ if (open && !mounted) {
4024
+ setMounted(true);
4025
+ setTransitionStatus('starting');
4026
+ }
4027
+ if (!open && mounted && transitionStatus !== 'ending' && !deferEndingState) {
4028
+ setTransitionStatus('ending');
4029
+ }
4030
+ if (!open && !mounted && transitionStatus === 'ending') {
4031
+ setTransitionStatus(undefined);
4032
+ }
4033
+ useIsoLayoutEffect(() => {
4034
+ if (!open && mounted && transitionStatus !== 'ending' && deferEndingState) {
4035
+ const frame = AnimationFrame.request(() => {
4036
+ setTransitionStatus('ending');
4037
+ });
4038
+ return () => {
4039
+ AnimationFrame.cancel(frame);
4040
+ };
4041
+ }
4042
+ return undefined;
4043
+ }, [open, mounted, transitionStatus, deferEndingState]);
4044
+ useIsoLayoutEffect(() => {
4045
+ if (!open || enableIdleState) {
4046
+ return undefined;
4047
+ }
4048
+ const frame = AnimationFrame.request(() => {
4049
+ // Avoid `flushSync` here due to Firefox.
4050
+ // See https://github.com/mui/base-ui/pull/3424
4051
+ setTransitionStatus(undefined);
4052
+ });
4053
+ return () => {
4054
+ AnimationFrame.cancel(frame);
4055
+ };
4056
+ }, [enableIdleState, open]);
4057
+ useIsoLayoutEffect(() => {
4058
+ if (!open || !enableIdleState) {
4059
+ return undefined;
4060
+ }
4061
+ if (open && mounted && transitionStatus !== 'idle') {
4062
+ setTransitionStatus('starting');
4063
+ }
4064
+ const frame = AnimationFrame.request(() => {
4065
+ setTransitionStatus('idle');
4066
+ });
4067
+ return () => {
4068
+ AnimationFrame.cancel(frame);
4069
+ };
4070
+ }, [enableIdleState, open, mounted, transitionStatus]);
4071
+ return {
4072
+ mounted,
4073
+ setMounted,
4074
+ transitionStatus
4075
+ };
4076
+ }
4077
+
4078
+ /**
4079
+ * Executes a function once all animations have finished on the provided element.
4080
+ * @param elementOrRef - The element to watch for animations.
4081
+ * @param waitForStartingStyleRemoved - Whether to wait for [data-starting-style] to be removed before checking for animations.
4082
+ * @param treatAbortedAsFinished - Whether to treat aborted animations as finished. If `false`, and there are aborted animations,
4083
+ * the function will check again if any new animations have started and wait for them to finish.
4084
+ * @returns A function that takes a callback to execute once all animations have finished, and an optional AbortSignal to abort the callback
4085
+ */
4086
+ function useAnimationsFinished(elementOrRef, waitForStartingStyleRemoved = false, treatAbortedAsFinished = true) {
4087
+ const frame = useAnimationFrame();
4088
+ return useStableCallback((fnToExecute,
4089
+ /**
4090
+ * An optional [AbortSignal](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) that
4091
+ * can be used to abort `fnToExecute` before all the animations have finished.
4092
+ * @default null
4093
+ */
4094
+ signal = null) => {
4095
+ frame.cancel();
4096
+ const element = resolveRef(elementOrRef);
4097
+ if (element == null) {
4098
+ return;
4099
+ }
4100
+ const resolvedElement = element;
4101
+ const done = () => {
4102
+ // Synchronously flush the unmounting of the component so that the browser doesn't
4103
+ // paint: https://github.com/mui/base-ui/issues/979
4104
+ ReactDOM__namespace.flushSync(fnToExecute);
4105
+ };
4106
+ if (typeof resolvedElement.getAnimations !== 'function' || globalThis.BASE_UI_ANIMATIONS_DISABLED) {
4107
+ fnToExecute();
4108
+ return;
4109
+ }
4110
+ function exec() {
4111
+ Promise.all(resolvedElement.getAnimations().map(animation => animation.finished)).then(() => {
4112
+ if (!signal?.aborted) {
4113
+ done();
4114
+ }
4115
+ }).catch(() => {
4116
+ if (treatAbortedAsFinished) {
4117
+ if (!signal?.aborted) {
4118
+ done();
4119
+ }
4120
+ return;
4121
+ }
4122
+ const currentAnimations = resolvedElement.getAnimations();
4123
+ if (!signal?.aborted && currentAnimations.length > 0 && currentAnimations.some(animation => animation.pending || animation.playState !== 'finished')) {
4124
+ // Sometimes animations can be aborted because a property they depend on changes while the animation plays.
4125
+ // In such cases, we need to re-check if any new animations have started.
4126
+ exec();
4127
+ }
4128
+ });
4129
+ }
4130
+ if (waitForStartingStyleRemoved) {
4131
+ const startingStyleAttribute = TransitionStatusDataAttributes.startingStyle;
4132
+
4133
+ // If `[data-starting-style]` isn't present, fall back to waiting one more frame
4134
+ // to give "open" animations a chance to be registered.
4135
+ if (!resolvedElement.hasAttribute(startingStyleAttribute)) {
4136
+ frame.request(exec);
4137
+ return;
4138
+ }
4139
+
4140
+ // Wait for `[data-starting-style]` to have been removed.
4141
+ const attributeObserver = new MutationObserver(() => {
4142
+ if (!resolvedElement.hasAttribute(startingStyleAttribute)) {
4143
+ attributeObserver.disconnect();
4144
+ exec();
4145
+ }
4146
+ });
4147
+ attributeObserver.observe(resolvedElement, {
4148
+ attributes: true,
4149
+ attributeFilter: [startingStyleAttribute]
4150
+ });
4151
+ signal?.addEventListener('abort', () => attributeObserver.disconnect(), {
4152
+ once: true
4153
+ });
4154
+ return;
4155
+ }
4156
+ frame.request(exec);
4157
+ });
4158
+ }
4159
+
4160
+ /**
4161
+ * Calls the provided function when the CSS open/close animation or transition completes.
4162
+ */
4163
+ function useOpenChangeComplete(parameters) {
4164
+ const {
4165
+ enabled = true,
4166
+ open,
4167
+ ref,
4168
+ onComplete: onCompleteParam
4169
+ } = parameters;
4170
+ const onComplete = useStableCallback(onCompleteParam);
4171
+ const runOnceAnimationsFinish = useAnimationsFinished(ref, open, false);
4172
+ React__namespace.useEffect(() => {
4173
+ if (!enabled) {
4174
+ return undefined;
4175
+ }
4176
+ const abortController = new AbortController();
4177
+ runOnceAnimationsFinish(onComplete, abortController.signal);
4178
+ return () => {
4179
+ abortController.abort();
4180
+ };
4181
+ }, [enabled, open, onComplete, runOnceAnimationsFinish]);
4182
+ }
4183
+
4184
+ /**
4185
+ * Data structure to keep track of popup trigger elements by their IDs.
4186
+ * Uses both a set of Elements and a map of IDs to Elements for efficient lookups.
4187
+ */
4188
+ class PopupTriggerMap {
4189
+ constructor() {
4190
+ this.elementsSet = new Set();
4191
+ this.idMap = new Map();
4192
+ }
4193
+
4194
+ /**
4195
+ * Adds a trigger element with the given ID.
4196
+ *
4197
+ * Note: The provided element is assumed to not be registered under multiple IDs.
4198
+ */
4199
+ add(id, element) {
4200
+ const existingElement = this.idMap.get(id);
4201
+ if (existingElement === element) {
4202
+ return;
4203
+ }
4204
+ if (existingElement !== undefined) {
4205
+ // We assume that the same element won't be registered under multiple ids.
4206
+ // This is safe considering how useTriggerRegistration is implemented.
4207
+ this.elementsSet.delete(existingElement);
4208
+ }
4209
+ this.elementsSet.add(element);
4210
+ this.idMap.set(id, element);
4211
+ }
4212
+
4213
+ /**
4214
+ * Removes the trigger element with the given ID.
4215
+ */
4216
+ delete(id) {
4217
+ const element = this.idMap.get(id);
4218
+ if (element) {
4219
+ this.elementsSet.delete(element);
4220
+ this.idMap.delete(id);
4221
+ }
4222
+ }
4223
+
4224
+ /**
4225
+ * Whether the given element is registered as a trigger.
4226
+ */
4227
+ hasElement(element) {
4228
+ return this.elementsSet.has(element);
4229
+ }
4230
+
4231
+ /**
4232
+ * Whether there is a registered trigger element matching the given predicate.
4233
+ */
4234
+ hasMatchingElement(predicate) {
4235
+ for (const element of this.elementsSet) {
4236
+ if (predicate(element)) {
4237
+ return true;
4238
+ }
4239
+ }
4240
+ return false;
4241
+ }
4242
+
4243
+ /**
4244
+ * Returns the trigger element associated with the given ID, or undefined if no such element exists.
4245
+ */
4246
+ getById(id) {
4247
+ return this.idMap.get(id);
4248
+ }
4249
+
4250
+ /**
4251
+ * Returns an iterable of all registered trigger entries, where each entry is a tuple of [id, element].
4252
+ */
4253
+ entries() {
4254
+ return this.idMap.entries();
4255
+ }
4256
+
4257
+ /**
4258
+ * Returns an iterable of all registered trigger elements.
4259
+ */
4260
+ elements() {
4261
+ return this.elementsSet.values();
4262
+ }
4263
+
4264
+ /**
4265
+ * Returns the number of registered trigger elements.
4266
+ */
4267
+ get size() {
4268
+ return this.idMap.size;
4269
+ }
4270
+ }
4271
+
4272
+ function getEmptyRootContext() {
4273
+ return new FloatingRootStore({
4274
+ open: false,
4275
+ transitionStatus: undefined,
4276
+ floatingElement: null,
4277
+ referenceElement: null,
4278
+ triggerElements: new PopupTriggerMap(),
4279
+ floatingId: '',
4280
+ syncOnly: false,
4281
+ nested: false,
4282
+ onOpenChange: undefined
4283
+ });
4284
+ }
4285
+
4286
+ /**
4287
+ * State common to all popup stores.
4288
+ */
4289
+
4290
+ function createInitialPopupStoreState() {
4291
+ return {
4292
+ open: false,
4293
+ openProp: undefined,
4294
+ mounted: false,
4295
+ transitionStatus: undefined,
4296
+ floatingRootContext: getEmptyRootContext(),
4297
+ preventUnmountingOnClose: false,
4298
+ payload: undefined,
4299
+ activeTriggerId: null,
4300
+ activeTriggerElement: null,
4301
+ triggerIdProp: undefined,
4302
+ popupElement: null,
4303
+ positionerElement: null,
4304
+ activeTriggerProps: EMPTY_OBJECT,
4305
+ inactiveTriggerProps: EMPTY_OBJECT,
4306
+ popupProps: EMPTY_OBJECT
4307
+ };
4308
+ }
4309
+ const activeTriggerIdSelector = createSelector(state => state.triggerIdProp ?? state.activeTriggerId);
4310
+ const popupStoreSelectors = {
4311
+ open: createSelector(state => state.openProp ?? state.open),
4312
+ mounted: createSelector(state => state.mounted),
4313
+ transitionStatus: createSelector(state => state.transitionStatus),
4314
+ floatingRootContext: createSelector(state => state.floatingRootContext),
4315
+ preventUnmountingOnClose: createSelector(state => state.preventUnmountingOnClose),
4316
+ payload: createSelector(state => state.payload),
4317
+ activeTriggerId: activeTriggerIdSelector,
4318
+ activeTriggerElement: createSelector(state => state.mounted ? state.activeTriggerElement : null),
4319
+ /**
4320
+ * Whether the trigger with the given ID was used to open the popup.
4321
+ */
4322
+ isTriggerActive: createSelector((state, triggerId) => triggerId !== undefined && activeTriggerIdSelector(state) === triggerId),
4323
+ /**
4324
+ * Whether the popup is open and was activated by a trigger with the given ID.
4325
+ */
4326
+ isOpenedByTrigger: createSelector((state, triggerId) => triggerId !== undefined && activeTriggerIdSelector(state) === triggerId && state.open),
4327
+ /**
4328
+ * Whether the popup is mounted and was activated by a trigger with the given ID.
4329
+ */
4330
+ isMountedByTrigger: createSelector((state, triggerId) => triggerId !== undefined && activeTriggerIdSelector(state) === triggerId && state.mounted),
4331
+ triggerProps: createSelector((state, isActive) => isActive ? state.activeTriggerProps : state.inactiveTriggerProps),
4332
+ popupProps: createSelector(state => state.popupProps),
4333
+ popupElement: createSelector(state => state.popupElement),
4334
+ positionerElement: createSelector(state => state.positionerElement)
4335
+ };
4336
+
4337
+ /**
4338
+ * Merges an array of interaction hooks' props into prop getters, allowing
4339
+ * event handler functions to be composed together without overwriting one
4340
+ * another.
4341
+ * @see https://floating-ui.com/docs/useInteractions
4342
+ */
4343
+ function useInteractions(propsList = []) {
4344
+ const referenceDeps = propsList.map(key => key?.reference);
4345
+ const floatingDeps = propsList.map(key => key?.floating);
4346
+ const itemDeps = propsList.map(key => key?.item);
4347
+ const triggerDeps = propsList.map(key => key?.trigger);
4348
+ const getReferenceProps = React__namespace.useCallback(userProps => mergeProps(userProps, propsList, 'reference'),
4349
+ // eslint-disable-next-line react-hooks/exhaustive-deps
4350
+ referenceDeps);
4351
+ const getFloatingProps = React__namespace.useCallback(userProps => mergeProps(userProps, propsList, 'floating'),
4352
+ // eslint-disable-next-line react-hooks/exhaustive-deps
4353
+ floatingDeps);
4354
+ const getItemProps = React__namespace.useCallback(userProps => mergeProps(userProps, propsList, 'item'),
4355
+ // eslint-disable-next-line react-hooks/exhaustive-deps
4356
+ itemDeps);
4357
+ const getTriggerProps = React__namespace.useCallback(userProps => mergeProps(userProps, propsList, 'trigger'),
4358
+ // eslint-disable-next-line react-hooks/exhaustive-deps
4359
+ triggerDeps);
4360
+ return React__namespace.useMemo(() => ({
4361
+ getReferenceProps,
4362
+ getFloatingProps,
4363
+ getItemProps,
4364
+ getTriggerProps
4365
+ }), [getReferenceProps, getFloatingProps, getItemProps, getTriggerProps]);
4366
+ }
4367
+
4368
+ /* eslint-disable guard-for-in */
4369
+
4370
+ function mergeProps(userProps, propsList, elementKey) {
4371
+ const eventHandlers = new Map();
4372
+ const isItem = elementKey === 'item';
4373
+ const outputProps = {};
4374
+ if (elementKey === 'floating') {
4375
+ outputProps.tabIndex = -1;
4376
+ outputProps[FOCUSABLE_ATTRIBUTE] = '';
4377
+ }
4378
+ for (const key in userProps) {
4379
+ if (isItem && userProps) {
4380
+ if (key === ACTIVE_KEY || key === SELECTED_KEY) {
4381
+ continue;
4382
+ }
4383
+ }
4384
+ outputProps[key] = userProps[key];
4385
+ }
4386
+ for (let i = 0; i < propsList.length; i += 1) {
4387
+ let props;
4388
+ const propsOrGetProps = propsList[i]?.[elementKey];
4389
+ if (typeof propsOrGetProps === 'function') {
4390
+ props = userProps ? propsOrGetProps(userProps) : null;
4391
+ } else {
4392
+ props = propsOrGetProps;
4393
+ }
4394
+ if (!props) {
4395
+ continue;
4396
+ }
4397
+ mutablyMergeProps(outputProps, props, isItem, eventHandlers);
4398
+ }
4399
+ mutablyMergeProps(outputProps, userProps, isItem, eventHandlers);
4400
+ return outputProps;
4401
+ }
4402
+ function mutablyMergeProps(outputProps, props, isItem, eventHandlers) {
4403
+ for (const key in props) {
4404
+ const value = props[key];
4405
+ if (isItem && (key === ACTIVE_KEY || key === SELECTED_KEY)) {
4406
+ continue;
4407
+ }
4408
+ if (!key.startsWith('on')) {
4409
+ outputProps[key] = value;
4410
+ } else {
4411
+ if (!eventHandlers.has(key)) {
4412
+ eventHandlers.set(key, []);
4413
+ }
4414
+ if (typeof value === 'function') {
4415
+ eventHandlers.get(key)?.push(value);
4416
+ outputProps[key] = (...args) => {
4417
+ return eventHandlers.get(key)?.map(fn => fn(...args)).find(val => val !== undefined);
4418
+ };
4419
+ }
4420
+ }
4421
+ }
4422
+ }
4423
+
4424
+ function inertValue(value) {
4425
+ if (isReactVersionAtLeast(19)) {
4426
+ return value;
4427
+ }
4428
+ // compatibility with React < 19
4429
+ return value ? 'true' : undefined;
4430
+ }
4431
+
4432
+ const InternalBackdrop = /*#__PURE__*/React__namespace.forwardRef(function InternalBackdrop(props, ref) {
4433
+ const {
4434
+ cutout,
4435
+ ...otherProps
4436
+ } = props;
4437
+ let clipPath;
4438
+ if (cutout) {
4439
+ const rect = cutout.getBoundingClientRect();
4440
+ clipPath = `polygon(0% 0%,100% 0%,100% 100%,0% 100%,0% 0%,${rect.left}px ${rect.top}px,${rect.left}px ${rect.bottom}px,${rect.right}px ${rect.bottom}px,${rect.right}px ${rect.top}px,${rect.left}px ${rect.top}px)`;
4441
+ }
4442
+ return /*#__PURE__*/jsxRuntime.jsx("div", {
4443
+ ref: ref,
4444
+ role: "presentation"
4445
+ // Ensures Floating UI's outside press detection runs, as it considers
4446
+ // it an element that existed when the popup rendered.
4447
+ ,
4448
+ "data-base-ui-inert": "",
4449
+ ...otherProps,
4450
+ style: {
4451
+ position: 'fixed',
4452
+ inset: 0,
4453
+ userSelect: 'none',
4454
+ WebkitUserSelect: 'none',
4455
+ clipPath
4456
+ }
4457
+ });
4458
+ });
4459
+
4460
+ function useOnFirstRender(fn) {
4461
+ const ref = React__namespace.useRef(true);
4462
+ if (ref.current) {
4463
+ ref.current = false;
4464
+ fn();
4465
+ }
4466
+ }
4467
+
4468
+ let originalHtmlStyles = {};
4469
+ let originalBodyStyles = {};
4470
+ let originalHtmlScrollBehavior = '';
4471
+ function hasInsetScrollbars(referenceElement) {
4472
+ if (typeof document === 'undefined') {
4473
+ return false;
4474
+ }
4475
+ const doc = ownerDocument(referenceElement);
4476
+ const win = floatingUi_utils_dom.getWindow(doc);
4477
+ return win.innerWidth - doc.documentElement.clientWidth > 0;
4478
+ }
4479
+ function supportsStableScrollbarGutter(referenceElement) {
4480
+ const supported = typeof CSS !== 'undefined' && CSS.supports && CSS.supports('scrollbar-gutter', 'stable');
4481
+ if (!supported || typeof document === 'undefined') {
4482
+ return false;
4483
+ }
4484
+ const doc = ownerDocument(referenceElement);
4485
+ const html = doc.documentElement;
4486
+ const body = doc.body;
4487
+ const scrollContainer = floatingUi_utils_dom.isOverflowElement(html) ? html : body;
4488
+ const originalScrollContainerOverflowY = scrollContainer.style.overflowY;
4489
+ const originalHtmlStyleGutter = html.style.scrollbarGutter;
4490
+ html.style.scrollbarGutter = 'stable';
4491
+ scrollContainer.style.overflowY = 'scroll';
4492
+ const before = scrollContainer.offsetWidth;
4493
+ scrollContainer.style.overflowY = 'hidden';
4494
+ const after = scrollContainer.offsetWidth;
4495
+ scrollContainer.style.overflowY = originalScrollContainerOverflowY;
4496
+ html.style.scrollbarGutter = originalHtmlStyleGutter;
4497
+ return before === after;
4498
+ }
4499
+ function preventScrollOverlayScrollbars(referenceElement) {
4500
+ const doc = ownerDocument(referenceElement);
4501
+ const html = doc.documentElement;
4502
+ const body = doc.body;
4503
+
4504
+ // If an `overflow` style is present on <html>, we need to lock it, because a lock on <body>
4505
+ // won't have any effect.
4506
+ // But if <body> has an `overflow` style (like `overflow-x: hidden`), we need to lock it
4507
+ // instead, as sticky elements shift otherwise.
4508
+ const elementToLock = floatingUi_utils_dom.isOverflowElement(html) ? html : body;
4509
+ const originalElementToLockStyles = {
4510
+ overflowY: elementToLock.style.overflowY,
4511
+ overflowX: elementToLock.style.overflowX
4512
+ };
4513
+ Object.assign(elementToLock.style, {
4514
+ overflowY: 'hidden',
4515
+ overflowX: 'hidden'
4516
+ });
4517
+ return () => {
4518
+ Object.assign(elementToLock.style, originalElementToLockStyles);
4519
+ };
4520
+ }
4521
+ function preventScrollInsetScrollbars(referenceElement) {
4522
+ const doc = ownerDocument(referenceElement);
4523
+ const html = doc.documentElement;
4524
+ const body = doc.body;
4525
+ const win = floatingUi_utils_dom.getWindow(html);
4526
+ let scrollTop = 0;
4527
+ let scrollLeft = 0;
4528
+ let updateGutterOnly = false;
4529
+ const resizeFrame = AnimationFrame.create();
4530
+
4531
+ // Pinch-zoom in Safari causes a shift. Just don't lock scroll if there's any pinch-zoom.
4532
+ if (isWebKit && (win.visualViewport?.scale ?? 1) !== 1) {
4533
+ return () => {};
4534
+ }
4535
+ function lockScroll() {
4536
+ /* DOM reads: */
4537
+
4538
+ const htmlStyles = win.getComputedStyle(html);
4539
+ const bodyStyles = win.getComputedStyle(body);
4540
+ const htmlScrollbarGutterValue = htmlStyles.scrollbarGutter || '';
4541
+ const hasBothEdges = htmlScrollbarGutterValue.includes('both-edges');
4542
+ const scrollbarGutterValue = hasBothEdges ? 'stable both-edges' : 'stable';
4543
+ scrollTop = html.scrollTop;
4544
+ scrollLeft = html.scrollLeft;
4545
+ originalHtmlStyles = {
4546
+ scrollbarGutter: html.style.scrollbarGutter,
4547
+ overflowY: html.style.overflowY,
4548
+ overflowX: html.style.overflowX
4549
+ };
4550
+ originalHtmlScrollBehavior = html.style.scrollBehavior;
4551
+ originalBodyStyles = {
4552
+ position: body.style.position,
4553
+ height: body.style.height,
4554
+ width: body.style.width,
4555
+ boxSizing: body.style.boxSizing,
4556
+ overflowY: body.style.overflowY,
4557
+ overflowX: body.style.overflowX,
4558
+ scrollBehavior: body.style.scrollBehavior
4559
+ };
4560
+ const isScrollableY = html.scrollHeight > html.clientHeight;
4561
+ const isScrollableX = html.scrollWidth > html.clientWidth;
4562
+ const hasConstantOverflowY = htmlStyles.overflowY === 'scroll' || bodyStyles.overflowY === 'scroll';
4563
+ const hasConstantOverflowX = htmlStyles.overflowX === 'scroll' || bodyStyles.overflowX === 'scroll';
4564
+
4565
+ // Values can be negative in Firefox
4566
+ const scrollbarWidth = Math.max(0, win.innerWidth - body.clientWidth);
4567
+ const scrollbarHeight = Math.max(0, win.innerHeight - body.clientHeight);
4568
+
4569
+ // Avoid shift due to the default <body> margin. This does cause elements to be clipped
4570
+ // with whitespace. Warn if <body> has margins?
4571
+ const marginY = parseFloat(bodyStyles.marginTop) + parseFloat(bodyStyles.marginBottom);
4572
+ const marginX = parseFloat(bodyStyles.marginLeft) + parseFloat(bodyStyles.marginRight);
4573
+ const elementToLock = floatingUi_utils_dom.isOverflowElement(html) ? html : body;
4574
+ updateGutterOnly = supportsStableScrollbarGutter(referenceElement);
4575
+
4576
+ /*
4577
+ * DOM writes:
4578
+ * Do not read the DOM past this point!
4579
+ */
4580
+
4581
+ if (updateGutterOnly) {
4582
+ html.style.scrollbarGutter = scrollbarGutterValue;
4583
+ elementToLock.style.overflowY = 'hidden';
4584
+ elementToLock.style.overflowX = 'hidden';
4585
+ return;
4586
+ }
4587
+ Object.assign(html.style, {
4588
+ scrollbarGutter: scrollbarGutterValue,
4589
+ overflowY: 'hidden',
4590
+ overflowX: 'hidden'
4591
+ });
4592
+ if (isScrollableY || hasConstantOverflowY) {
4593
+ html.style.overflowY = 'scroll';
4594
+ }
4595
+ if (isScrollableX || hasConstantOverflowX) {
4596
+ html.style.overflowX = 'scroll';
4597
+ }
4598
+ Object.assign(body.style, {
4599
+ position: 'relative',
4600
+ height: marginY || scrollbarHeight ? `calc(100dvh - ${marginY + scrollbarHeight}px)` : '100dvh',
4601
+ width: marginX || scrollbarWidth ? `calc(100vw - ${marginX + scrollbarWidth}px)` : '100vw',
4602
+ boxSizing: 'border-box',
4603
+ overflow: 'hidden',
4604
+ scrollBehavior: 'unset'
4605
+ });
4606
+ body.scrollTop = scrollTop;
4607
+ body.scrollLeft = scrollLeft;
4608
+ html.setAttribute('data-base-ui-scroll-locked', '');
4609
+ html.style.scrollBehavior = 'unset';
4610
+ }
4611
+ function cleanup() {
4612
+ Object.assign(html.style, originalHtmlStyles);
4613
+ Object.assign(body.style, originalBodyStyles);
4614
+ if (!updateGutterOnly) {
4615
+ html.scrollTop = scrollTop;
4616
+ html.scrollLeft = scrollLeft;
4617
+ html.removeAttribute('data-base-ui-scroll-locked');
4618
+ html.style.scrollBehavior = originalHtmlScrollBehavior;
4619
+ }
4620
+ }
4621
+ function handleResize() {
4622
+ cleanup();
4623
+ resizeFrame.request(lockScroll);
4624
+ }
4625
+ lockScroll();
4626
+ const unsubscribeResize = addEventListener(win, 'resize', handleResize);
4627
+ return () => {
4628
+ resizeFrame.cancel();
4629
+ cleanup();
4630
+ // Sometimes this cleanup can run after test teardown because it is called
4631
+ // in a `setTimeout(fn, 0)`. Guard the returned cleanup to avoid calling
4632
+ // `removeEventListener` when it is no longer available in tests.
4633
+ if (typeof win.removeEventListener === 'function') {
4634
+ unsubscribeResize();
4635
+ }
4636
+ };
4637
+ }
4638
+ class ScrollLocker {
4639
+ lockCount = 0;
4640
+ restore = null;
4641
+ timeoutLock = Timeout.create();
4642
+ timeoutUnlock = Timeout.create();
4643
+ acquire(referenceElement) {
4644
+ this.lockCount += 1;
4645
+ if (this.lockCount === 1 && this.restore === null) {
4646
+ this.timeoutLock.start(0, () => this.lock(referenceElement));
4647
+ }
4648
+ return this.release;
4649
+ }
4650
+ release = () => {
4651
+ this.lockCount -= 1;
4652
+ if (this.lockCount === 0 && this.restore) {
4653
+ this.timeoutUnlock.start(0, this.unlock);
4654
+ }
4655
+ };
4656
+ unlock = () => {
4657
+ if (this.lockCount === 0 && this.restore) {
4658
+ this.restore?.();
4659
+ this.restore = null;
4660
+ }
4661
+ };
4662
+ lock(referenceElement) {
4663
+ if (this.lockCount === 0 || this.restore !== null) {
4664
+ return;
4665
+ }
4666
+ const doc = ownerDocument(referenceElement);
4667
+ const html = doc.documentElement;
4668
+ const htmlOverflowY = floatingUi_utils_dom.getWindow(html).getComputedStyle(html).overflowY;
4669
+
4670
+ // If the site author already hid overflow on <html>, respect it and bail out.
4671
+ if (htmlOverflowY === 'hidden' || htmlOverflowY === 'clip') {
4672
+ this.restore = NOOP;
4673
+ return;
4674
+ }
4675
+ const hasOverlayScrollbars = isIOS || !hasInsetScrollbars(referenceElement);
4676
+
4677
+ // On iOS, scroll locking does not work if the navbar is collapsed. Due to numerous
4678
+ // side effects and bugs that arise on iOS, it must be researched extensively before
4679
+ // being enabled to ensure it doesn't cause the following issues:
4680
+ // - Textboxes must scroll into view when focused, nor cause a glitchy scroll animation.
4681
+ // - The navbar must not force itself into view and cause layout shift.
4682
+ // - Scroll containers must not flicker upon closing a popup when it has an exit animation.
4683
+ this.restore = hasOverlayScrollbars ? preventScrollOverlayScrollbars(referenceElement) : preventScrollInsetScrollbars(referenceElement);
4684
+ }
4685
+ }
4686
+ const SCROLL_LOCKER = new ScrollLocker();
4687
+
4688
+ /**
4689
+ * Locks the scroll of the document when enabled.
4690
+ *
4691
+ * @param enabled - Whether to enable the scroll lock.
4692
+ * @param referenceElement - Element to use as a reference for lock calculations.
4693
+ */
4694
+ function useScrollLock(enabled = true, referenceElement = null) {
4695
+ useIsoLayoutEffect(() => {
4696
+ if (!enabled) {
4697
+ return undefined;
4698
+ }
4699
+ return SCROLL_LOCKER.acquire(referenceElement);
4700
+ }, [enabled, referenceElement]);
4701
+ }
4702
+
4703
+ /**
4704
+ * Provides a cross-browser way to determine the type of the pointer used to click.
4705
+ * Safari and Firefox do not provide the PointerEvent to the click handler (they use MouseEvent) yet.
4706
+ * Additionally, this implementation detects if the click was triggered by the keyboard.
4707
+ *
4708
+ * @param handler The function to be called when the button is clicked. The first parameter is the original event and the second parameter is the pointer type.
4709
+ */
4710
+ function useEnhancedClickHandler(handler) {
4711
+ const lastClickInteractionTypeRef = React__namespace.useRef('');
4712
+ const handlePointerDown = React__namespace.useCallback(event => {
4713
+ if (event.defaultPrevented) {
4714
+ return;
4715
+ }
4716
+ lastClickInteractionTypeRef.current = event.pointerType;
4717
+ handler(event, event.pointerType);
4718
+ }, [handler]);
4719
+ const handleClick = React__namespace.useCallback(event => {
4720
+ // event.detail has the number of clicks performed on the element. 0 means it was triggered by the keyboard.
4721
+ if (event.detail === 0) {
4722
+ handler(event, 'keyboard');
4723
+ return;
4724
+ }
4725
+ if ('pointerType' in event) {
4726
+ // Chrome and Edge correctly use PointerEvent
4727
+ handler(event, event.pointerType);
4728
+ } else {
4729
+ handler(event, lastClickInteractionTypeRef.current);
4730
+ }
4731
+ lastClickInteractionTypeRef.current = '';
4732
+ }, [handler]);
4733
+ return {
4734
+ onClick: handleClick,
4735
+ onPointerDown: handlePointerDown
4736
+ };
4737
+ }
4738
+
4739
+ function useValueChanged(value, onChange) {
4740
+ const valueRef = React__namespace.useRef(value);
4741
+ const onChangeCallback = useStableCallback(onChange);
4742
+ useIsoLayoutEffect(() => {
4743
+ if (valueRef.current === value) {
4744
+ return;
4745
+ }
4746
+ onChangeCallback(valueRef.current);
4747
+ }, [value, onChangeCallback]);
4748
+ useIsoLayoutEffect(() => {
4749
+ valueRef.current = value;
4750
+ }, [value]);
4751
+ }
4752
+
4753
+ /**
4754
+ * Determines the interaction type (keyboard, mouse, touch, etc.) that opened the component.
4755
+ *
4756
+ * @param open The open state of the component.
4757
+ */
4758
+ function useOpenInteractionType(open) {
4759
+ const [openMethod, setOpenMethod] = React__namespace.useState(null);
4760
+ const handleTriggerClick = useStableCallback((_, interactionType) => {
4761
+ if (!open) {
4762
+ setOpenMethod(interactionType || (
4763
+ // On iOS Safari, the hitslop around touch targets means tapping outside an element's
4764
+ // bounds does not fire `pointerdown` but does fire `mousedown`. The `interactionType`
4765
+ // will be "" in that case.
4766
+ isIOS ? 'touch' : ''));
4767
+ }
4768
+ });
4769
+ useValueChanged(open, previousOpen => {
4770
+ if (previousOpen && !open) {
4771
+ setOpenMethod(null);
4772
+ }
4773
+ });
4774
+ const {
4775
+ onClick,
4776
+ onPointerDown
4777
+ } = useEnhancedClickHandler(handleTriggerClick);
4778
+ return React__namespace.useMemo(() => ({
4779
+ openMethod,
4780
+ triggerProps: {
4781
+ onClick,
4782
+ onPointerDown
4783
+ }
4784
+ }), [openMethod, onClick, onPointerDown]);
4785
+ }
4786
+
4787
+ exports.ARROW_DOWN = ARROW_DOWN;
4788
+ exports.ARROW_LEFT = ARROW_LEFT;
4789
+ exports.ARROW_RIGHT = ARROW_RIGHT;
4790
+ exports.ARROW_UP = ARROW_UP;
4791
+ exports.CLICK_TRIGGER_IDENTIFIER = CLICK_TRIGGER_IDENTIFIER;
4792
+ exports.CommonPopupDataAttributes = CommonPopupDataAttributes;
4793
+ exports.DISABLED_TRANSITIONS_STYLE = DISABLED_TRANSITIONS_STYLE;
4794
+ exports.DROPDOWN_COLLISION_AVOIDANCE = DROPDOWN_COLLISION_AVOIDANCE;
4795
+ exports.EMPTY_ARRAY = EMPTY_ARRAY;
4796
+ exports.EMPTY_OBJECT = EMPTY_OBJECT;
4797
+ exports.FloatingFocusManager = FloatingFocusManager;
4798
+ exports.FloatingPortal = FloatingPortal;
4799
+ exports.FloatingRootStore = FloatingRootStore;
4800
+ exports.InternalBackdrop = InternalBackdrop;
4801
+ exports.NOOP = NOOP;
4802
+ exports.PopupTriggerMap = PopupTriggerMap;
4803
+ exports.ReactStore = ReactStore;
4804
+ exports.Store = Store;
4805
+ exports.activeElement = activeElement;
4806
+ exports.chipRemovePress = chipRemovePress;
4807
+ exports.clearPress = clearPress;
4808
+ exports.closePress = closePress;
4809
+ exports.contains = contains;
4810
+ exports.createChangeEventDetails = createChangeEventDetails;
4811
+ exports.createGenericEventDetails = createGenericEventDetails;
4812
+ exports.createGridCellMap = createGridCellMap;
4813
+ exports.createInitialPopupStoreState = createInitialPopupStoreState;
4814
+ exports.createSelector = createSelector;
4815
+ exports.enqueueFocus = enqueueFocus;
4816
+ exports.escapeKey = escapeKey;
4817
+ exports.findNonDisabledListIndex = findNonDisabledListIndex;
4818
+ exports.focusOut = focusOut;
4819
+ exports.formatErrorMessage = formatErrorMessage;
4820
+ exports.getFloatingFocusElement = getFloatingFocusElement;
4821
+ exports.getGridCellIndexOfCorner = getGridCellIndexOfCorner;
4822
+ exports.getGridCellIndices = getGridCellIndices;
4823
+ exports.getGridNavigatedIndex = getGridNavigatedIndex;
4824
+ exports.getMaxListIndex = getMaxListIndex;
4825
+ exports.getMinListIndex = getMinListIndex;
4826
+ exports.getTarget = getTarget;
4827
+ exports.imperativeAction = imperativeAction;
4828
+ exports.inertValue = inertValue;
4829
+ exports.inputChange = inputChange;
4830
+ exports.inputClear = inputClear;
4831
+ exports.inputPress = inputPress;
4832
+ exports.isAndroid = isAndroid;
4833
+ exports.isElementVisible = isElementVisible;
4834
+ exports.isFirefox = isFirefox;
4835
+ exports.isIOS = isIOS;
4836
+ exports.isIndexOutOfListBounds = isIndexOutOfListBounds;
4837
+ exports.isInteractiveElement = isInteractiveElement;
4838
+ exports.isListIndexDisabled = isListIndexDisabled;
4839
+ exports.isTypeableCombobox = isTypeableCombobox;
4840
+ exports.isVirtualClick = isVirtualClick;
4841
+ exports.isVirtualPointerEvent = isVirtualPointerEvent;
4842
+ exports.itemPress = itemPress;
4843
+ exports.listNavigation = listNavigation;
4844
+ exports.none = none;
4845
+ exports.outsidePress = outsidePress;
4846
+ exports.ownerDocument = ownerDocument;
4847
+ exports.popupStateMapping = popupStateMapping;
4848
+ exports.popupStoreSelectors = popupStoreSelectors;
4849
+ exports.pressableTriggerOpenStateMapping = pressableTriggerOpenStateMapping;
4850
+ exports.stopEvent = stopEvent;
4851
+ exports.transitionStatusMapping = transitionStatusMapping;
4852
+ exports.triggerOpenStateMapping = triggerOpenStateMapping;
4853
+ exports.useBaseUiId = useBaseUiId;
4854
+ exports.useButton = useButton;
4855
+ exports.useClick = useClick;
4856
+ exports.useDismiss = useDismiss;
4857
+ exports.useFloatingParentNodeId = useFloatingParentNodeId;
4858
+ exports.useFloatingTree = useFloatingTree;
4859
+ exports.useId = useId;
4860
+ exports.useInteractions = useInteractions;
4861
+ exports.useIsoLayoutEffect = useIsoLayoutEffect;
4862
+ exports.useMergedRefs = useMergedRefs;
4863
+ exports.useOnFirstRender = useOnFirstRender;
4864
+ exports.useOpenChangeComplete = useOpenChangeComplete;
4865
+ exports.useOpenInteractionType = useOpenInteractionType;
4866
+ exports.useRefWithInit = useRefWithInit;
4867
+ exports.useRenderElement = useRenderElement;
4868
+ exports.useScrollLock = useScrollLock;
4869
+ exports.useStableCallback = useStableCallback;
4870
+ exports.useStore = useStore;
4871
+ exports.useTimeout = useTimeout;
4872
+ exports.useTransitionStatus = useTransitionStatus;
4873
+ exports.useValueAsRef = useValueAsRef;
4874
+ exports.useValueChanged = useValueChanged;
4875
+ exports.visuallyHidden = visuallyHidden;
4876
+ exports.visuallyHiddenInput = visuallyHiddenInput;
4877
+ //# sourceMappingURL=useOpenInteractionType-D4z6FTrA.js.map