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