@dashforge/tw 0.1.0-beta

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 (299) hide show
  1. package/.swcrc +29 -0
  2. package/CHANGELOG.md +131 -0
  3. package/LICENSE +21 -0
  4. package/README.md +244 -0
  5. package/dist/components/AppShell/AppShell.d.ts +32 -0
  6. package/dist/components/AppShell/AppShell.d.ts.map +1 -0
  7. package/dist/components/AppShell/appShell.types.d.ts +62 -0
  8. package/dist/components/AppShell/appShell.types.d.ts.map +1 -0
  9. package/dist/components/AppShell/appShell.variants.d.ts +65 -0
  10. package/dist/components/AppShell/appShell.variants.d.ts.map +1 -0
  11. package/dist/components/Autocomplete/Autocomplete.d.ts +32 -0
  12. package/dist/components/Autocomplete/Autocomplete.d.ts.map +1 -0
  13. package/dist/components/Autocomplete/autocomplete.types.d.ts +214 -0
  14. package/dist/components/Autocomplete/autocomplete.types.d.ts.map +1 -0
  15. package/dist/components/Autocomplete/autocomplete.variants.d.ts +214 -0
  16. package/dist/components/Autocomplete/autocomplete.variants.d.ts.map +1 -0
  17. package/dist/components/Breadcrumbs/Breadcrumbs.d.ts +23 -0
  18. package/dist/components/Breadcrumbs/Breadcrumbs.d.ts.map +1 -0
  19. package/dist/components/Breadcrumbs/breadcrumbs.types.d.ts +98 -0
  20. package/dist/components/Breadcrumbs/breadcrumbs.types.d.ts.map +1 -0
  21. package/dist/components/Breadcrumbs/breadcrumbs.variants.d.ts +85 -0
  22. package/dist/components/Breadcrumbs/breadcrumbs.variants.d.ts.map +1 -0
  23. package/dist/components/Button/Button.d.ts +44 -0
  24. package/dist/components/Button/Button.d.ts.map +1 -0
  25. package/dist/components/Button/button.types.d.ts +66 -0
  26. package/dist/components/Button/button.types.d.ts.map +1 -0
  27. package/dist/components/Button/button.variants.d.ts +104 -0
  28. package/dist/components/Button/button.variants.d.ts.map +1 -0
  29. package/dist/components/Checkbox/Checkbox.d.ts +31 -0
  30. package/dist/components/Checkbox/Checkbox.d.ts.map +1 -0
  31. package/dist/components/Checkbox/checkbox.types.d.ts +86 -0
  32. package/dist/components/Checkbox/checkbox.types.d.ts.map +1 -0
  33. package/dist/components/Checkbox/checkbox.variants.d.ts +109 -0
  34. package/dist/components/Checkbox/checkbox.variants.d.ts.map +1 -0
  35. package/dist/components/ConfirmDialog/ConfirmDialog.d.ts +38 -0
  36. package/dist/components/ConfirmDialog/ConfirmDialog.d.ts.map +1 -0
  37. package/dist/components/ConfirmDialog/confirmDialog.types.d.ts +80 -0
  38. package/dist/components/ConfirmDialog/confirmDialog.types.d.ts.map +1 -0
  39. package/dist/components/ConfirmDialog/confirmDialog.variants.d.ts +90 -0
  40. package/dist/components/ConfirmDialog/confirmDialog.variants.d.ts.map +1 -0
  41. package/dist/components/DateTimePicker/DateTimePicker.d.ts +49 -0
  42. package/dist/components/DateTimePicker/DateTimePicker.d.ts.map +1 -0
  43. package/dist/components/DateTimePicker/dateTimePicker.types.d.ts +95 -0
  44. package/dist/components/DateTimePicker/dateTimePicker.types.d.ts.map +1 -0
  45. package/dist/components/DateTimePicker/dateTimePicker.variants.d.ts +165 -0
  46. package/dist/components/DateTimePicker/dateTimePicker.variants.d.ts.map +1 -0
  47. package/dist/components/LeftNav/LeftNav.d.ts +34 -0
  48. package/dist/components/LeftNav/LeftNav.d.ts.map +1 -0
  49. package/dist/components/LeftNav/leftNav.types.d.ts +136 -0
  50. package/dist/components/LeftNav/leftNav.types.d.ts.map +1 -0
  51. package/dist/components/LeftNav/leftNav.variants.d.ts +143 -0
  52. package/dist/components/LeftNav/leftNav.variants.d.ts.map +1 -0
  53. package/dist/components/NumberField/NumberField.d.ts +18 -0
  54. package/dist/components/NumberField/NumberField.d.ts.map +1 -0
  55. package/dist/components/NumberField/numberField.types.d.ts +79 -0
  56. package/dist/components/NumberField/numberField.types.d.ts.map +1 -0
  57. package/dist/components/NumberField/numberField.variants.d.ts +169 -0
  58. package/dist/components/NumberField/numberField.variants.d.ts.map +1 -0
  59. package/dist/components/OTPField/OTPField.d.ts +25 -0
  60. package/dist/components/OTPField/OTPField.d.ts.map +1 -0
  61. package/dist/components/OTPField/otpField.types.d.ts +74 -0
  62. package/dist/components/OTPField/otpField.types.d.ts.map +1 -0
  63. package/dist/components/OTPField/otpField.variants.d.ts +105 -0
  64. package/dist/components/OTPField/otpField.variants.d.ts.map +1 -0
  65. package/dist/components/RadioGroup/RadioGroup.d.ts +35 -0
  66. package/dist/components/RadioGroup/RadioGroup.d.ts.map +1 -0
  67. package/dist/components/RadioGroup/radioGroup.types.d.ts +103 -0
  68. package/dist/components/RadioGroup/radioGroup.types.d.ts.map +1 -0
  69. package/dist/components/RadioGroup/radioGroup.variants.d.ts +166 -0
  70. package/dist/components/RadioGroup/radioGroup.variants.d.ts.map +1 -0
  71. package/dist/components/Snackbar/Snackbar.d.ts +37 -0
  72. package/dist/components/Snackbar/Snackbar.d.ts.map +1 -0
  73. package/dist/components/Snackbar/snackbar.types.d.ts +86 -0
  74. package/dist/components/Snackbar/snackbar.types.d.ts.map +1 -0
  75. package/dist/components/Snackbar/snackbar.variants.d.ts +153 -0
  76. package/dist/components/Snackbar/snackbar.variants.d.ts.map +1 -0
  77. package/dist/components/Switch/Switch.d.ts +15 -0
  78. package/dist/components/Switch/Switch.d.ts.map +1 -0
  79. package/dist/components/Switch/switch.types.d.ts +47 -0
  80. package/dist/components/Switch/switch.types.d.ts.map +1 -0
  81. package/dist/components/Switch/switch.variants.d.ts +105 -0
  82. package/dist/components/Switch/switch.variants.d.ts.map +1 -0
  83. package/dist/components/TextField/TextField.d.ts +25 -0
  84. package/dist/components/TextField/TextField.d.ts.map +1 -0
  85. package/dist/components/TextField/textField.types.d.ts +72 -0
  86. package/dist/components/TextField/textField.types.d.ts.map +1 -0
  87. package/dist/components/TextField/textField.variants.d.ts +160 -0
  88. package/dist/components/TextField/textField.variants.d.ts.map +1 -0
  89. package/dist/components/Textarea/Textarea.d.ts +16 -0
  90. package/dist/components/Textarea/Textarea.d.ts.map +1 -0
  91. package/dist/components/Textarea/textarea.types.d.ts +63 -0
  92. package/dist/components/Textarea/textarea.types.d.ts.map +1 -0
  93. package/dist/components/Textarea/textarea.variants.d.ts +197 -0
  94. package/dist/components/Textarea/textarea.variants.d.ts.map +1 -0
  95. package/dist/components/TopBar/TopBar.d.ts +33 -0
  96. package/dist/components/TopBar/TopBar.d.ts.map +1 -0
  97. package/dist/components/TopBar/topBar.types.d.ts +49 -0
  98. package/dist/components/TopBar/topBar.types.d.ts.map +1 -0
  99. package/dist/components/TopBar/topBar.variants.d.ts +79 -0
  100. package/dist/components/TopBar/topBar.variants.d.ts.map +1 -0
  101. package/dist/components/_shared/resolveValidationState.d.ts +42 -0
  102. package/dist/components/_shared/resolveValidationState.d.ts.map +1 -0
  103. package/dist/hooks/useAccessState.d.ts +37 -0
  104. package/dist/hooks/useAccessState.d.ts.map +1 -0
  105. package/dist/index.d.ts +82 -0
  106. package/dist/index.d.ts.map +1 -0
  107. package/dist/index.esm.js +4958 -0
  108. package/dist/src/components/AppShell/AppShell.d.ts +32 -0
  109. package/dist/src/components/AppShell/AppShell.d.ts.map +1 -0
  110. package/dist/src/components/AppShell/appShell.types.d.ts +62 -0
  111. package/dist/src/components/AppShell/appShell.types.d.ts.map +1 -0
  112. package/dist/src/components/AppShell/appShell.variants.d.ts +65 -0
  113. package/dist/src/components/AppShell/appShell.variants.d.ts.map +1 -0
  114. package/dist/src/components/Autocomplete/Autocomplete.d.ts +32 -0
  115. package/dist/src/components/Autocomplete/Autocomplete.d.ts.map +1 -0
  116. package/dist/src/components/Autocomplete/autocomplete.types.d.ts +214 -0
  117. package/dist/src/components/Autocomplete/autocomplete.types.d.ts.map +1 -0
  118. package/dist/src/components/Autocomplete/autocomplete.variants.d.ts +214 -0
  119. package/dist/src/components/Autocomplete/autocomplete.variants.d.ts.map +1 -0
  120. package/dist/src/components/Breadcrumbs/Breadcrumbs.d.ts +23 -0
  121. package/dist/src/components/Breadcrumbs/Breadcrumbs.d.ts.map +1 -0
  122. package/dist/src/components/Breadcrumbs/breadcrumbs.types.d.ts +98 -0
  123. package/dist/src/components/Breadcrumbs/breadcrumbs.types.d.ts.map +1 -0
  124. package/dist/src/components/Breadcrumbs/breadcrumbs.variants.d.ts +85 -0
  125. package/dist/src/components/Breadcrumbs/breadcrumbs.variants.d.ts.map +1 -0
  126. package/dist/src/components/Button/Button.d.ts +44 -0
  127. package/dist/src/components/Button/Button.d.ts.map +1 -0
  128. package/dist/src/components/Button/button.types.d.ts +66 -0
  129. package/dist/src/components/Button/button.types.d.ts.map +1 -0
  130. package/dist/src/components/Button/button.variants.d.ts +104 -0
  131. package/dist/src/components/Button/button.variants.d.ts.map +1 -0
  132. package/dist/src/components/Checkbox/Checkbox.d.ts +31 -0
  133. package/dist/src/components/Checkbox/Checkbox.d.ts.map +1 -0
  134. package/dist/src/components/Checkbox/checkbox.types.d.ts +86 -0
  135. package/dist/src/components/Checkbox/checkbox.types.d.ts.map +1 -0
  136. package/dist/src/components/Checkbox/checkbox.variants.d.ts +109 -0
  137. package/dist/src/components/Checkbox/checkbox.variants.d.ts.map +1 -0
  138. package/dist/src/components/ConfirmDialog/ConfirmDialog.d.ts +38 -0
  139. package/dist/src/components/ConfirmDialog/ConfirmDialog.d.ts.map +1 -0
  140. package/dist/src/components/ConfirmDialog/confirmDialog.types.d.ts +80 -0
  141. package/dist/src/components/ConfirmDialog/confirmDialog.types.d.ts.map +1 -0
  142. package/dist/src/components/ConfirmDialog/confirmDialog.variants.d.ts +90 -0
  143. package/dist/src/components/ConfirmDialog/confirmDialog.variants.d.ts.map +1 -0
  144. package/dist/src/components/DateTimePicker/DateTimePicker.d.ts +49 -0
  145. package/dist/src/components/DateTimePicker/DateTimePicker.d.ts.map +1 -0
  146. package/dist/src/components/DateTimePicker/dateTimePicker.types.d.ts +95 -0
  147. package/dist/src/components/DateTimePicker/dateTimePicker.types.d.ts.map +1 -0
  148. package/dist/src/components/DateTimePicker/dateTimePicker.variants.d.ts +165 -0
  149. package/dist/src/components/DateTimePicker/dateTimePicker.variants.d.ts.map +1 -0
  150. package/dist/src/components/LeftNav/LeftNav.d.ts +34 -0
  151. package/dist/src/components/LeftNav/LeftNav.d.ts.map +1 -0
  152. package/dist/src/components/LeftNav/leftNav.types.d.ts +136 -0
  153. package/dist/src/components/LeftNav/leftNav.types.d.ts.map +1 -0
  154. package/dist/src/components/LeftNav/leftNav.variants.d.ts +143 -0
  155. package/dist/src/components/LeftNav/leftNav.variants.d.ts.map +1 -0
  156. package/dist/src/components/NumberField/NumberField.d.ts +18 -0
  157. package/dist/src/components/NumberField/NumberField.d.ts.map +1 -0
  158. package/dist/src/components/NumberField/numberField.types.d.ts +79 -0
  159. package/dist/src/components/NumberField/numberField.types.d.ts.map +1 -0
  160. package/dist/src/components/NumberField/numberField.variants.d.ts +169 -0
  161. package/dist/src/components/NumberField/numberField.variants.d.ts.map +1 -0
  162. package/dist/src/components/OTPField/OTPField.d.ts +25 -0
  163. package/dist/src/components/OTPField/OTPField.d.ts.map +1 -0
  164. package/dist/src/components/OTPField/otpField.types.d.ts +74 -0
  165. package/dist/src/components/OTPField/otpField.types.d.ts.map +1 -0
  166. package/dist/src/components/OTPField/otpField.variants.d.ts +105 -0
  167. package/dist/src/components/OTPField/otpField.variants.d.ts.map +1 -0
  168. package/dist/src/components/RadioGroup/RadioGroup.d.ts +35 -0
  169. package/dist/src/components/RadioGroup/RadioGroup.d.ts.map +1 -0
  170. package/dist/src/components/RadioGroup/radioGroup.types.d.ts +103 -0
  171. package/dist/src/components/RadioGroup/radioGroup.types.d.ts.map +1 -0
  172. package/dist/src/components/RadioGroup/radioGroup.variants.d.ts +166 -0
  173. package/dist/src/components/RadioGroup/radioGroup.variants.d.ts.map +1 -0
  174. package/dist/src/components/Snackbar/Snackbar.d.ts +37 -0
  175. package/dist/src/components/Snackbar/Snackbar.d.ts.map +1 -0
  176. package/dist/src/components/Snackbar/snackbar.types.d.ts +86 -0
  177. package/dist/src/components/Snackbar/snackbar.types.d.ts.map +1 -0
  178. package/dist/src/components/Snackbar/snackbar.variants.d.ts +153 -0
  179. package/dist/src/components/Snackbar/snackbar.variants.d.ts.map +1 -0
  180. package/dist/src/components/Switch/Switch.d.ts +15 -0
  181. package/dist/src/components/Switch/Switch.d.ts.map +1 -0
  182. package/dist/src/components/Switch/switch.types.d.ts +47 -0
  183. package/dist/src/components/Switch/switch.types.d.ts.map +1 -0
  184. package/dist/src/components/Switch/switch.variants.d.ts +105 -0
  185. package/dist/src/components/Switch/switch.variants.d.ts.map +1 -0
  186. package/dist/src/components/TextField/TextField.d.ts +25 -0
  187. package/dist/src/components/TextField/TextField.d.ts.map +1 -0
  188. package/dist/src/components/TextField/textField.types.d.ts +72 -0
  189. package/dist/src/components/TextField/textField.types.d.ts.map +1 -0
  190. package/dist/src/components/TextField/textField.variants.d.ts +160 -0
  191. package/dist/src/components/TextField/textField.variants.d.ts.map +1 -0
  192. package/dist/src/components/Textarea/Textarea.d.ts +16 -0
  193. package/dist/src/components/Textarea/Textarea.d.ts.map +1 -0
  194. package/dist/src/components/Textarea/textarea.types.d.ts +63 -0
  195. package/dist/src/components/Textarea/textarea.types.d.ts.map +1 -0
  196. package/dist/src/components/Textarea/textarea.variants.d.ts +197 -0
  197. package/dist/src/components/Textarea/textarea.variants.d.ts.map +1 -0
  198. package/dist/src/components/TopBar/TopBar.d.ts +33 -0
  199. package/dist/src/components/TopBar/TopBar.d.ts.map +1 -0
  200. package/dist/src/components/TopBar/topBar.types.d.ts +49 -0
  201. package/dist/src/components/TopBar/topBar.types.d.ts.map +1 -0
  202. package/dist/src/components/TopBar/topBar.variants.d.ts +79 -0
  203. package/dist/src/components/TopBar/topBar.variants.d.ts.map +1 -0
  204. package/dist/src/components/_shared/resolveValidationState.d.ts +42 -0
  205. package/dist/src/components/_shared/resolveValidationState.d.ts.map +1 -0
  206. package/dist/src/hooks/useAccessState.d.ts +37 -0
  207. package/dist/src/hooks/useAccessState.d.ts.map +1 -0
  208. package/dist/src/index.d.ts +82 -0
  209. package/dist/src/index.d.ts.map +1 -0
  210. package/dist/src/utils/cn.d.ts +26 -0
  211. package/dist/src/utils/cn.d.ts.map +1 -0
  212. package/dist/tsconfig.lib.tsbuildinfo +1 -0
  213. package/dist/utils/cn.d.ts +26 -0
  214. package/dist/utils/cn.d.ts.map +1 -0
  215. package/eslint.config.mjs +47 -0
  216. package/package.json +37 -0
  217. package/project.json +15 -0
  218. package/rollup.config.cjs +16 -0
  219. package/src/components/AppShell/AppShell.test.tsx +223 -0
  220. package/src/components/AppShell/AppShell.tsx +114 -0
  221. package/src/components/AppShell/appShell.types.ts +49 -0
  222. package/src/components/AppShell/appShell.variants.ts +48 -0
  223. package/src/components/Autocomplete/Autocomplete.perf.test.tsx +225 -0
  224. package/src/components/Autocomplete/Autocomplete.test.tsx +556 -0
  225. package/src/components/Autocomplete/Autocomplete.tsx +996 -0
  226. package/src/components/Autocomplete/autocomplete.types.ts +198 -0
  227. package/src/components/Autocomplete/autocomplete.variants.ts +135 -0
  228. package/src/components/Breadcrumbs/Breadcrumbs.perf.test.tsx +125 -0
  229. package/src/components/Breadcrumbs/Breadcrumbs.test.tsx +231 -0
  230. package/src/components/Breadcrumbs/Breadcrumbs.tsx +203 -0
  231. package/src/components/Breadcrumbs/breadcrumbs.types.ts +87 -0
  232. package/src/components/Breadcrumbs/breadcrumbs.variants.ts +49 -0
  233. package/src/components/Button/Button.test.tsx +183 -0
  234. package/src/components/Button/Button.tsx +139 -0
  235. package/src/components/Button/button.types.ts +74 -0
  236. package/src/components/Button/button.variants.ts +159 -0
  237. package/src/components/Checkbox/Checkbox.test.tsx +146 -0
  238. package/src/components/Checkbox/Checkbox.tsx +228 -0
  239. package/src/components/Checkbox/checkbox.types.ts +88 -0
  240. package/src/components/Checkbox/checkbox.variants.ts +68 -0
  241. package/src/components/ConfirmDialog/ConfirmDialog.perf.test.tsx +172 -0
  242. package/src/components/ConfirmDialog/ConfirmDialog.test.tsx +311 -0
  243. package/src/components/ConfirmDialog/ConfirmDialog.tsx +252 -0
  244. package/src/components/ConfirmDialog/confirmDialog.types.ts +70 -0
  245. package/src/components/ConfirmDialog/confirmDialog.variants.ts +76 -0
  246. package/src/components/DateTimePicker/DateTimePicker.perf.test.tsx +153 -0
  247. package/src/components/DateTimePicker/DateTimePicker.test.tsx +204 -0
  248. package/src/components/DateTimePicker/DateTimePicker.tsx +319 -0
  249. package/src/components/DateTimePicker/dateTimePicker.types.ts +83 -0
  250. package/src/components/DateTimePicker/dateTimePicker.variants.ts +84 -0
  251. package/src/components/LeftNav/LeftNav.perf.test.tsx +172 -0
  252. package/src/components/LeftNav/LeftNav.test.tsx +302 -0
  253. package/src/components/LeftNav/LeftNav.tsx +330 -0
  254. package/src/components/LeftNav/leftNav.types.ts +120 -0
  255. package/src/components/LeftNav/leftNav.variants.ts +96 -0
  256. package/src/components/NumberField/NumberField.test.tsx +83 -0
  257. package/src/components/NumberField/NumberField.tsx +293 -0
  258. package/src/components/NumberField/numberField.types.ts +72 -0
  259. package/src/components/NumberField/numberField.variants.ts +94 -0
  260. package/src/components/OTPField/OTPField.test.tsx +121 -0
  261. package/src/components/OTPField/OTPField.tsx +250 -0
  262. package/src/components/OTPField/otpField.types.ts +58 -0
  263. package/src/components/OTPField/otpField.variants.ts +72 -0
  264. package/src/components/RadioGroup/RadioGroup.test.tsx +140 -0
  265. package/src/components/RadioGroup/RadioGroup.tsx +261 -0
  266. package/src/components/RadioGroup/radioGroup.types.ts +85 -0
  267. package/src/components/RadioGroup/radioGroup.variants.ts +87 -0
  268. package/src/components/Snackbar/Snackbar.perf.test.tsx +144 -0
  269. package/src/components/Snackbar/Snackbar.test.tsx +327 -0
  270. package/src/components/Snackbar/Snackbar.tsx +298 -0
  271. package/src/components/Snackbar/snackbar.types.ts +83 -0
  272. package/src/components/Snackbar/snackbar.variants.ts +72 -0
  273. package/src/components/Switch/Switch.test.tsx +131 -0
  274. package/src/components/Switch/Switch.tsx +158 -0
  275. package/src/components/Switch/switch.types.ts +36 -0
  276. package/src/components/Switch/switch.variants.ts +65 -0
  277. package/src/components/TextField/TextField.test.tsx +194 -0
  278. package/src/components/TextField/TextField.tsx +216 -0
  279. package/src/components/TextField/textField.types.ts +70 -0
  280. package/src/components/TextField/textField.variants.ts +87 -0
  281. package/src/components/Textarea/Textarea.test.tsx +75 -0
  282. package/src/components/Textarea/Textarea.tsx +190 -0
  283. package/src/components/Textarea/textarea.types.ts +60 -0
  284. package/src/components/Textarea/textarea.variants.ts +85 -0
  285. package/src/components/TopBar/TopBar.test.tsx +129 -0
  286. package/src/components/TopBar/TopBar.tsx +66 -0
  287. package/src/components/TopBar/topBar.types.ts +42 -0
  288. package/src/components/TopBar/topBar.variants.ts +38 -0
  289. package/src/components/_shared/resolveValidationState.ts +60 -0
  290. package/src/hooks/useAccessState.spec.tsx +161 -0
  291. package/src/hooks/useAccessState.ts +81 -0
  292. package/src/index.ts +191 -0
  293. package/src/utils/cn.spec.ts +16 -0
  294. package/src/utils/cn.ts +29 -0
  295. package/tsconfig.json +13 -0
  296. package/tsconfig.lib.json +55 -0
  297. package/tsconfig.spec.json +34 -0
  298. package/vite.config.ts +25 -0
  299. package/vitest.config.mts +22 -0
@@ -0,0 +1,996 @@
1
+ import {
2
+ useCallback,
3
+ useContext,
4
+ useEffect,
5
+ useId,
6
+ useMemo,
7
+ useRef,
8
+ useState,
9
+ type KeyboardEvent,
10
+ type MouseEvent,
11
+ type ReactNode,
12
+ } from 'react';
13
+ import { DashFormContext, useEngineVisibility } from '@dashforge/ui-core';
14
+ import type { DashFormBridge, FieldRegistration } from '@dashforge/ui-core';
15
+ import { useDashFieldMeta } from '@dashforge/forms';
16
+ import { cn } from '../../utils/cn.js';
17
+ import { useAccessState } from '../../hooks/useAccessState.js';
18
+ import { resolveValidationState } from '../_shared/resolveValidationState.js';
19
+ import { autocompleteVariants } from './autocomplete.variants.js';
20
+ import type {
21
+ AutocompleteOption,
22
+ AutocompleteProps,
23
+ AutocompleteValue,
24
+ } from './autocomplete.types.js';
25
+
26
+ /**
27
+ * Coerce a raw value (from bridge / props) into a canonical shape:
28
+ *
29
+ * - Multi-select: returns `string[]` (empty for null/undefined)
30
+ * - Single-select: returns `string | null`
31
+ */
32
+ function coerceValue(raw: unknown, isMulti: boolean): AutocompleteValue {
33
+ if (isMulti) {
34
+ if (raw == null) return [];
35
+ if (Array.isArray(raw)) return raw.map(String);
36
+ return [String(raw)];
37
+ }
38
+ if (raw == null) return null;
39
+ if (Array.isArray(raw)) return raw[0] != null ? String(raw[0]) : null;
40
+ return String(raw);
41
+ }
42
+
43
+ /** Derive a Set of selected keys from a canonical value. */
44
+ function getSelectedKeys(value: AutocompleteValue): Set<string> {
45
+ if (value == null) return new Set();
46
+ if (Array.isArray(value)) return new Set(value);
47
+ return new Set([value]);
48
+ }
49
+
50
+ // Default accessor implementations. Assume `AutocompleteOption` shape —
51
+ // safe because the generic defaults to that shape, and consumers using
52
+ // a custom `TOption` must pass their own `getOptionValue` / `Label`.
53
+ // We type the input as `unknown` here to keep the defaults assignable
54
+ // to `(o: TOption) => …` for arbitrary `TOption` without forcing a cast
55
+ // at every call site.
56
+ const defaultGetOptionValue = (option: unknown): string =>
57
+ (option as AutocompleteOption).value;
58
+ const defaultGetOptionLabel = (option: unknown) =>
59
+ (option as AutocompleteOption).label;
60
+ const defaultGetOptionDisabled = (option: unknown): boolean =>
61
+ Boolean((option as AutocompleteOption).disabled);
62
+
63
+ /**
64
+ * Dashforge TW Autocomplete — bridge-integrated single-select combobox.
65
+ *
66
+ * **Implementation note (F5-A, rev. 2)**
67
+ *
68
+ * The first revision wrapped `react-aria-components`' `<ComboBox>` to get
69
+ * AAA-grade a11y for free. In practice React Aria's internal state
70
+ * machine fought every controlled-state pattern we tried (the input text
71
+ * would not clear when `selectedKey` went to `null`, even with a forced
72
+ * remount via `key` bumping). To get deterministic behaviour we own all
73
+ * of the state ourselves:
74
+ *
75
+ * - `inputValue` — the visible text in the `<input>`
76
+ * - `isOpen` — popover visibility
77
+ * - `highlightedIndex` — keyboard navigation cursor
78
+ *
79
+ * A11y is still solid:
80
+ * - `role="combobox"` + `aria-autocomplete="list"` on the input
81
+ * - `aria-expanded`, `aria-controls`, `aria-activedescendant`
82
+ * - `role="listbox"` / `role="option"` with `aria-selected`
83
+ * - Full keyboard nav (↑/↓ navigate, Enter selects, Escape closes,
84
+ * Home/End jump, Tab closes, click-outside closes)
85
+ * - Required field gets `aria-required="true"`
86
+ *
87
+ * F5-A scope: single-select, static options, contains-substring filter
88
+ * (case-insensitive). Multi-select, free-solo text, generic option
89
+ * shapes, and async runtime options (`optionsFromFieldData`) are
90
+ * deferred to F5-A-bis.
91
+ */
92
+ export function Autocomplete<TOption = AutocompleteOption>(
93
+ props: AutocompleteProps<TOption>
94
+ ) {
95
+ const {
96
+ name,
97
+ rules,
98
+ options,
99
+ visibleWhen,
100
+ layout = 'stacked',
101
+ size,
102
+ label,
103
+ helperText,
104
+ required,
105
+ error,
106
+ disabled,
107
+ fullWidth,
108
+ access,
109
+ sx,
110
+ slotProps,
111
+ placeholder,
112
+ value: explicitValue,
113
+ defaultValue,
114
+ onValueChange,
115
+ emptyMessage = 'No matching options',
116
+ getOptionValue = defaultGetOptionValue as (option: TOption) => string,
117
+ getOptionLabel = defaultGetOptionLabel as (option: TOption) => ReactNode,
118
+ getOptionDisabled = defaultGetOptionDisabled as (option: TOption) => boolean,
119
+ getOptionKey,
120
+ multiple,
121
+ freeSolo,
122
+ loadOptions,
123
+ loadDebounceMs = 250,
124
+ loadingMessage = 'Loading…',
125
+ } = props;
126
+
127
+ const isMulti = Boolean(multiple);
128
+
129
+ // Default the React-key accessor to `getOptionValue` (typical case:
130
+ // value is unique). Consumers override only when distinct option
131
+ // records can share the same persisted value.
132
+ const resolveOptionKey = getOptionKey ?? getOptionValue;
133
+
134
+ /**
135
+ * Resolve the string label of an option, if it is a string. Returns
136
+ * `undefined` for non-string labels (e.g., `<span>`) so callers can
137
+ * fall back to the persisted value for `textValue` / input text.
138
+ */
139
+ const labelAsString = (option: TOption): string | undefined => {
140
+ const lbl = getOptionLabel(option);
141
+ return typeof lbl === 'string' ? lbl : undefined;
142
+ };
143
+
144
+ // ───── Hooks (unconditional) ─────
145
+ const bridge = useContext(DashFormContext) as DashFormBridge | null;
146
+ const isVisible = useEngineVisibility(bridge?.engine, visibleWhen);
147
+ useDashFieldMeta(name);
148
+ const accessState = useAccessState(access);
149
+
150
+ const baseId = useId();
151
+ const labelId = `${baseId}-label`;
152
+ const helperId = `${baseId}-help`;
153
+ const listboxId = `${baseId}-listbox`;
154
+ const optionIdPrefix = `${baseId}-opt-`;
155
+
156
+ // StrictMode-safe unregister-on-unmount
157
+ const unregisterRef = useRef({ bridge, name });
158
+ unregisterRef.current = { bridge, name };
159
+ const isMountedRef = useRef(false);
160
+
161
+ useEffect(() => {
162
+ isMountedRef.current = true;
163
+ return () => {
164
+ isMountedRef.current = false;
165
+ const { bridge: cap, name: capName } = unregisterRef.current;
166
+ queueMicrotask(() => {
167
+ if (!isMountedRef.current) cap?.unregister?.(capName);
168
+ });
169
+ };
170
+ }, []);
171
+
172
+ // ───── Local UI state (we own EVERYTHING) ─────
173
+
174
+ /**
175
+ * The visible text in the `<input>`. Seeded from the initial value
176
+ * (single-select only — in multi mode the chips show the selection
177
+ * separately and the input always starts empty).
178
+ */
179
+ const [inputValue, setInputValue] = useState<string>(() => {
180
+ if (isMulti) return '';
181
+ let initialKey: string | null = null;
182
+ if (explicitValue !== undefined) {
183
+ initialKey = typeof explicitValue === 'string' ? explicitValue : null;
184
+ } else if (defaultValue !== undefined) {
185
+ initialKey = typeof defaultValue === 'string' ? defaultValue : null;
186
+ } else if (bridge?.register) {
187
+ const bv = bridge.getValue(name);
188
+ initialKey = bv == null ? null : String(bv);
189
+ }
190
+ if (initialKey == null) return '';
191
+ const found = options.find((opt) => getOptionValue(opt) === initialKey);
192
+ // Free-solo: if the initial key doesn't match any option, fall back
193
+ // to the key string itself (it IS the user-visible text).
194
+ return found
195
+ ? labelAsString(found) ?? (freeSolo ? initialKey : '')
196
+ : freeSolo
197
+ ? initialKey
198
+ : '';
199
+ });
200
+
201
+ /** Uncontrolled-mode internal selection (form mode uses the bridge). */
202
+ const [uncontrolledValue, setUncontrolledValue] = useState<AutocompleteValue>(
203
+ () => {
204
+ if (explicitValue !== undefined) return coerceValue(explicitValue, isMulti);
205
+ if (defaultValue !== undefined) return coerceValue(defaultValue, isMulti);
206
+ return isMulti ? [] : null;
207
+ }
208
+ );
209
+
210
+ /**
211
+ * Whether the user has interacted with the field in uncontrolled mode.
212
+ * Before first interaction, `defaultValue` wins (so a rerender with a
213
+ * new `defaultValue` is reflected in `resolvedValue` / `inputValue`).
214
+ * After first interaction, the user's choice (stored in
215
+ * `uncontrolledValue` / `inputValue`) wins.
216
+ */
217
+ const [hasInteracted, setHasInteracted] = useState(false);
218
+
219
+ const [isOpen, setIsOpen] = useState(false);
220
+ const [highlightedIndex, setHighlightedIndex] = useState(-1);
221
+
222
+ // Async-options state (only used when `loadOptions` is provided).
223
+ // - `asyncOptions` is `null` before the first fetch resolves; after,
224
+ // it holds whatever the loader returned. It always takes
225
+ // precedence over the static `options` prop once non-null.
226
+ // - `isLoading` true between a debounce-firing fetch and its
227
+ // resolution.
228
+ const [asyncOptions, setAsyncOptions] = useState<TOption[] | null>(null);
229
+ const [isLoading, setIsLoading] = useState(false);
230
+
231
+ const rootRef = useRef<HTMLDivElement | null>(null);
232
+ const inputRef = useRef<HTMLInputElement | null>(null);
233
+ const listboxRef = useRef<HTMLUListElement | null>(null);
234
+ /**
235
+ * Monotonic counter for the in-flight `loadOptions` fetch so a
236
+ * later-typed query can't get overtaken by a slower earlier fetch.
237
+ * Each fire bumps the counter; only the response whose generation
238
+ * matches the current counter is allowed to commit state.
239
+ */
240
+ const fetchGenRef = useRef(0);
241
+
242
+ // ───── Derived (no hooks below this point can be skipped) ─────
243
+ //
244
+ // Everything in this block runs every render so the hooks below
245
+ // (useMemo / useCallback / useEffect) stay above any early-return
246
+ // guards — see rules of hooks.
247
+
248
+ const effectiveDisabled = Boolean(disabled) || accessState.disabled;
249
+ const effectiveReadOnly = accessState.readonly;
250
+ const isFormMode = Boolean(bridge?.register);
251
+
252
+ let resolvedError = error;
253
+ let resolvedHelperText: typeof helperText = helperText;
254
+ let registration: FieldRegistration | null = null;
255
+ let resolvedValue: AutocompleteValue;
256
+
257
+ if (isFormMode && bridge) {
258
+ registration = bridge.register(name, rules);
259
+ const validation = resolveValidationState(name, bridge, error, helperText);
260
+ resolvedError = validation.error;
261
+ resolvedHelperText = validation.helperText;
262
+ if (explicitValue !== undefined) {
263
+ resolvedValue = coerceValue(explicitValue, isMulti);
264
+ } else {
265
+ resolvedValue = coerceValue(bridge.getValue(name), isMulti);
266
+ }
267
+ } else if (explicitValue !== undefined) {
268
+ resolvedValue = coerceValue(explicitValue, isMulti);
269
+ } else if (!hasInteracted && defaultValue !== undefined) {
270
+ resolvedValue = coerceValue(defaultValue, isMulti);
271
+ } else {
272
+ resolvedValue = uncontrolledValue;
273
+ }
274
+
275
+ // Set of currently-selected keys. Always exists (empty Set when no
276
+ // selection) — internal lookups can call `.has(key)` without null
277
+ // checks.
278
+ const selectedKeys = getSelectedKeys(resolvedValue);
279
+ // Convenience: for the clear button visibility + the "should keep
280
+ // popover open after pick" decision.
281
+ const hasAnySelection = selectedKeys.size > 0;
282
+ // Single-select compatibility: the one selected key (null in multi
283
+ // or when nothing is picked).
284
+ const singleSelectedKey =
285
+ !isMulti && typeof resolvedValue === 'string' ? resolvedValue : null;
286
+
287
+ // Visible input value:
288
+ // - Multi-select: always the locally-managed `inputValue` (selection
289
+ // is rendered as chips, not echoed in the input).
290
+ // - Single-select, before first interaction: derive from `resolvedValue`
291
+ // so a rerender with a new `defaultValue` is reflected immediately.
292
+ // - Single-select, after first interaction: trust `inputValue` (which
293
+ // `commitSelection` + `handleInputChange` keep in sync).
294
+ let displayInputValue: string = inputValue;
295
+ if (!isMulti && !hasInteracted) {
296
+ if (singleSelectedKey == null) {
297
+ displayInputValue = '';
298
+ } else {
299
+ const found = options.find(
300
+ (opt) => getOptionValue(opt) === singleSelectedKey
301
+ );
302
+ const found_label = found ? labelAsString(found) : undefined;
303
+ if (found_label !== undefined) {
304
+ displayInputValue = found_label;
305
+ } else if (freeSolo) {
306
+ // No matching option ⇒ this is a free-solo value; the key
307
+ // itself is the displayable text.
308
+ displayInputValue = singleSelectedKey;
309
+ }
310
+ }
311
+ }
312
+
313
+ // ───── Effective options source ─────
314
+ //
315
+ // Precedence: live async results > static `options` prop.
316
+ //
317
+ // While `loadOptions` is configured, the SERVER is responsible for
318
+ // filtering, so the client-side `contains` filter below is bypassed
319
+ // (using it would double-filter and hide rows the server intentionally
320
+ // returned).
321
+ const effectiveOptions: TOption[] =
322
+ loadOptions && asyncOptions !== null ? asyncOptions : options;
323
+ const useServerFilter = Boolean(loadOptions);
324
+
325
+ // ───── Filtering ─────
326
+ const filteredOptions = useMemo<TOption[]>(() => {
327
+ // Async mode: trust the server's filter; never apply a client-side
328
+ // one on top.
329
+ if (useServerFilter) return effectiveOptions;
330
+
331
+ // Single-select: when the field is closed and the input shows the
332
+ // exact selected label, show the FULL list on the next open (rather
333
+ // than the single-match filter the label would produce).
334
+ //
335
+ // Multi-select: the input value is purely the filter query (the
336
+ // selection lives in the chips), so this short-circuit doesn't apply.
337
+ if (!isMulti) {
338
+ const selectedOpt = effectiveOptions.find(
339
+ (o) => getOptionValue(o) === singleSelectedKey
340
+ );
341
+ const selectedLabel = selectedOpt ? labelAsString(selectedOpt) : undefined;
342
+ const isShowingSelected =
343
+ selectedLabel !== undefined && selectedLabel === displayInputValue;
344
+ if (!displayInputValue || isShowingSelected) return effectiveOptions;
345
+ } else if (!displayInputValue) {
346
+ return effectiveOptions;
347
+ }
348
+ const query = displayInputValue.toLowerCase();
349
+ return effectiveOptions.filter((opt) => {
350
+ const text = labelAsString(opt) ?? getOptionValue(opt);
351
+ return text.toLowerCase().includes(query);
352
+ });
353
+ // Accessors omitted by design — see commitSelection useCallback comment.
354
+ // eslint-disable-next-line react-hooks/exhaustive-deps
355
+ }, [
356
+ effectiveOptions,
357
+ displayInputValue,
358
+ singleSelectedKey,
359
+ isMulti,
360
+ useServerFilter,
361
+ ]);
362
+
363
+ // ───── Helpers ─────
364
+
365
+ /**
366
+ * Commit a value change to the bridge / state.
367
+ *
368
+ * **Single-select**: `next` is the new selected key, or `null` to
369
+ * clear. Replaces the previous selection.
370
+ *
371
+ * **Multi-select**:
372
+ * - `next === null` → clear all (emit `[]`).
373
+ * - `next === <key>` → toggle that key in the selection set.
374
+ *
375
+ * Sync to `inputValue`:
376
+ * - Single + non-null key → write the option's label into the input.
377
+ * - Single + null → empty the input.
378
+ * - Multi → always clear the input (the filter query is irrelevant
379
+ * once a chip has been added).
380
+ */
381
+ const commitSelection = useCallback(
382
+ (next: string | null) => {
383
+ // 1) Mark dirty so `defaultValue` no longer takes precedence.
384
+ setHasInteracted(true);
385
+
386
+ // 2) Compute the new persisted value.
387
+ let nextValue: AutocompleteValue;
388
+ if (isMulti) {
389
+ if (next == null) {
390
+ nextValue = [];
391
+ } else {
392
+ const set = new Set(selectedKeys);
393
+ if (set.has(next)) set.delete(next);
394
+ else set.add(next);
395
+ nextValue = Array.from(set);
396
+ }
397
+ // Multi mode: clear the filter input after every toggle.
398
+ setInputValue('');
399
+ } else {
400
+ nextValue = next;
401
+ // Single mode: sync the input label.
402
+ if (next == null) {
403
+ setInputValue('');
404
+ } else {
405
+ const found = options.find((opt) => getOptionValue(opt) === next);
406
+ const found_label = found ? labelAsString(found) : undefined;
407
+ if (found_label !== undefined) {
408
+ setInputValue(found_label);
409
+ }
410
+ }
411
+ }
412
+
413
+ // 3) Persist.
414
+ if (isFormMode && bridge) {
415
+ bridge.setValue?.(name, nextValue);
416
+ void registration?.onChange?.({
417
+ target: {
418
+ name,
419
+ // RHF + native form: array values are passed through as-is
420
+ // (RHF accepts any shape); the empty string fallback for
421
+ // null preserves the single-select contract.
422
+ value: nextValue == null ? '' : (nextValue as unknown as string),
423
+ },
424
+ type: 'change',
425
+ });
426
+ } else if (explicitValue === undefined) {
427
+ setUncontrolledValue(nextValue);
428
+ }
429
+
430
+ // 4) Notify consumer.
431
+ onValueChange?.(nextValue);
432
+ },
433
+ // Accessors omitted by design — see filteredOptions useMemo comment.
434
+ // eslint-disable-next-line react-hooks/exhaustive-deps
435
+ [
436
+ options,
437
+ isFormMode,
438
+ bridge,
439
+ name,
440
+ registration,
441
+ explicitValue,
442
+ onValueChange,
443
+ isMulti,
444
+ selectedKeys,
445
+ ]
446
+ );
447
+
448
+ const openPopover = useCallback(() => {
449
+ if (effectiveDisabled || effectiveReadOnly) return;
450
+ setIsOpen(true);
451
+ // Highlight the (single-)selected item on open, falling back to the
452
+ // first item. In multi mode, always start at the first visible item.
453
+ const selectedIdx =
454
+ !isMulti && singleSelectedKey
455
+ ? filteredOptions.findIndex(
456
+ (o) => getOptionValue(o) === singleSelectedKey
457
+ )
458
+ : -1;
459
+ setHighlightedIndex(selectedIdx >= 0 ? selectedIdx : 0);
460
+ // Accessors omitted by design — see filteredOptions useMemo comment.
461
+ // eslint-disable-next-line react-hooks/exhaustive-deps
462
+ }, [
463
+ effectiveDisabled,
464
+ effectiveReadOnly,
465
+ filteredOptions,
466
+ singleSelectedKey,
467
+ isMulti,
468
+ ]);
469
+
470
+ const closePopover = useCallback(() => {
471
+ setIsOpen(false);
472
+ setHighlightedIndex(-1);
473
+ }, []);
474
+
475
+ // ───── Click-outside ─────
476
+ useEffect(() => {
477
+ if (!isOpen) return;
478
+ const handlePointerDown = (event: globalThis.MouseEvent) => {
479
+ const root = rootRef.current;
480
+ if (!root) return;
481
+ if (root.contains(event.target as Node)) return;
482
+ closePopover();
483
+ // Multi mode: just clear the filter query (chips remain).
484
+ // Single + free-solo: commit the typed text as the value (the
485
+ // user's text IS the truth) — leave input alone afterwards.
486
+ // Single (no free-solo): revert input to the selected option's
487
+ // label or empty.
488
+ if (isMulti) {
489
+ setInputValue('');
490
+ } else if (freeSolo && inputValue.trim() !== '') {
491
+ const typed = inputValue.trim();
492
+ const matched = options.find((o) => labelAsString(o) === typed);
493
+ const nextKey = matched ? getOptionValue(matched) : typed;
494
+ if (singleSelectedKey !== nextKey) {
495
+ commitSelection(nextKey);
496
+ }
497
+ } else if (singleSelectedKey) {
498
+ const selected = options.find(
499
+ (o) => getOptionValue(o) === singleSelectedKey
500
+ );
501
+ const selected_label = selected ? labelAsString(selected) : undefined;
502
+ if (selected_label !== undefined) {
503
+ setInputValue(selected_label);
504
+ }
505
+ } else {
506
+ setInputValue('');
507
+ }
508
+ };
509
+ document.addEventListener('mousedown', handlePointerDown);
510
+ return () => document.removeEventListener('mousedown', handlePointerDown);
511
+ // Accessors omitted by design — see filteredOptions useMemo comment.
512
+ // eslint-disable-next-line react-hooks/exhaustive-deps
513
+ }, [
514
+ isOpen,
515
+ closePopover,
516
+ options,
517
+ singleSelectedKey,
518
+ isMulti,
519
+ freeSolo,
520
+ inputValue,
521
+ commitSelection,
522
+ ]);
523
+
524
+ // ───── Async option loading (debounced) ─────
525
+ useEffect(() => {
526
+ if (!loadOptions) return;
527
+ const myGen = ++fetchGenRef.current;
528
+ setIsLoading(true);
529
+ const timer = setTimeout(() => {
530
+ // Bail if the user re-typed during the debounce window — a newer
531
+ // generation has already been kicked off.
532
+ if (myGen !== fetchGenRef.current) return;
533
+ Promise.resolve(loadOptions(inputValue))
534
+ .then((next) => {
535
+ if (myGen === fetchGenRef.current) {
536
+ setAsyncOptions(next);
537
+ setIsLoading(false);
538
+ }
539
+ })
540
+ .catch(() => {
541
+ // Surface failures as an empty list; consumer's preferred
542
+ // error UI can be threaded via `emptyMessage` once they
543
+ // detect their own loader fault upstream.
544
+ if (myGen === fetchGenRef.current) {
545
+ setAsyncOptions([]);
546
+ setIsLoading(false);
547
+ }
548
+ });
549
+ }, loadDebounceMs);
550
+ return () => clearTimeout(timer);
551
+ // `loadOptions` is intentionally not in the deps — consumers
552
+ // typically pass an inline arrow which would otherwise trigger a
553
+ // refetch on every render. Treat it as stable (mirror of MUI's
554
+ // `loadOptions` contract).
555
+ // eslint-disable-next-line react-hooks/exhaustive-deps
556
+ }, [inputValue, loadDebounceMs]);
557
+
558
+ // ───── Handlers ─────
559
+
560
+ const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
561
+ const next = event.target.value;
562
+ setHasInteracted(true);
563
+ setInputValue(next);
564
+ if (!isOpen) setIsOpen(true);
565
+ // Reset highlight to first visible option on every keystroke; the
566
+ // filtered list will recompute on next render.
567
+ setHighlightedIndex(0);
568
+ };
569
+
570
+ const handleKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
571
+ if (effectiveDisabled || effectiveReadOnly) return;
572
+
573
+ // Multi-select: Backspace at the start of an empty input removes
574
+ // the last selected chip. (Matches the de-facto pattern used by
575
+ // chip-input UIs across the React ecosystem.)
576
+ if (
577
+ isMulti &&
578
+ event.key === 'Backspace' &&
579
+ inputValue === '' &&
580
+ selectedKeys.size > 0
581
+ ) {
582
+ event.preventDefault();
583
+ // Set guarantees ≥ 1 entry here (size > 0 above), but TS can't
584
+ // prove it — fall back to the loop variant to avoid the non-null
585
+ // assertion lint rule.
586
+ const arr = Array.from(selectedKeys);
587
+ const last = arr[arr.length - 1];
588
+ if (last !== undefined) {
589
+ commitSelection(last); // toggle removes
590
+ }
591
+ return;
592
+ }
593
+
594
+ if (event.key === 'ArrowDown') {
595
+ event.preventDefault();
596
+ if (!isOpen) {
597
+ openPopover();
598
+ return;
599
+ }
600
+ setHighlightedIndex((idx) => {
601
+ const max = filteredOptions.length - 1;
602
+ if (max < 0) return -1;
603
+ return idx >= max ? 0 : idx + 1;
604
+ });
605
+ return;
606
+ }
607
+ if (event.key === 'ArrowUp') {
608
+ event.preventDefault();
609
+ if (!isOpen) {
610
+ openPopover();
611
+ return;
612
+ }
613
+ setHighlightedIndex((idx) => {
614
+ const max = filteredOptions.length - 1;
615
+ if (max < 0) return -1;
616
+ return idx <= 0 ? max : idx - 1;
617
+ });
618
+ return;
619
+ }
620
+ if (event.key === 'Home' && isOpen) {
621
+ event.preventDefault();
622
+ setHighlightedIndex(filteredOptions.length ? 0 : -1);
623
+ return;
624
+ }
625
+ if (event.key === 'End' && isOpen) {
626
+ event.preventDefault();
627
+ setHighlightedIndex(filteredOptions.length ? filteredOptions.length - 1 : -1);
628
+ return;
629
+ }
630
+ if (event.key === 'Enter') {
631
+ // Preferred path: highlighted option is committed.
632
+ if (
633
+ isOpen &&
634
+ highlightedIndex >= 0 &&
635
+ highlightedIndex < filteredOptions.length
636
+ ) {
637
+ event.preventDefault();
638
+ const opt = filteredOptions[highlightedIndex];
639
+ if (!getOptionDisabled(opt)) {
640
+ commitSelection(getOptionValue(opt));
641
+ if (!isMulti) {
642
+ closePopover();
643
+ } else {
644
+ setHighlightedIndex(0);
645
+ }
646
+ }
647
+ return;
648
+ }
649
+ // Free-solo path: commit the typed text as the value.
650
+ if (freeSolo && inputValue.trim() !== '') {
651
+ event.preventDefault();
652
+ const typed = inputValue.trim();
653
+ // Snap to an exact-label match if one exists, even when the
654
+ // dropdown was filtered to zero rows — protects the contract
655
+ // that "the value is always a known option when one matches."
656
+ const matched = options.find(
657
+ (o) => labelAsString(o) === typed
658
+ );
659
+ commitSelection(matched ? getOptionValue(matched) : typed);
660
+ if (!isMulti) closePopover();
661
+ else setHighlightedIndex(0);
662
+ }
663
+ return;
664
+ }
665
+ if (event.key === 'Escape') {
666
+ if (isOpen) {
667
+ event.preventDefault();
668
+ closePopover();
669
+ // Multi: clear filter; selection stays in chips.
670
+ // Single: revert input to the displayable form of the committed
671
+ // value — either the matched option's label, or (in free-solo)
672
+ // the raw string that was committed.
673
+ if (isMulti) {
674
+ setInputValue('');
675
+ } else if (singleSelectedKey) {
676
+ const selected = options.find(
677
+ (o) => getOptionValue(o) === singleSelectedKey
678
+ );
679
+ const selected_label = selected ? labelAsString(selected) : undefined;
680
+ setInputValue(selected_label ?? (freeSolo ? singleSelectedKey : ''));
681
+ } else {
682
+ setInputValue('');
683
+ }
684
+ }
685
+ return;
686
+ }
687
+ if (event.key === 'Tab') {
688
+ // Let focus leave naturally; just close.
689
+ if (isOpen) closePopover();
690
+ return;
691
+ }
692
+ };
693
+
694
+ const handleBlur = () => {
695
+ // Free-solo (single mode): commit the typed text on blur so the
696
+ // user doesn't have to remember to press Enter. Multi + free-solo
697
+ // is Enter-only (blur would commit accidental whitespace from
698
+ // tab-out).
699
+ if (freeSolo && !isMulti && inputValue.trim() !== '') {
700
+ const typed = inputValue.trim();
701
+ const matched = options.find((o) => labelAsString(o) === typed);
702
+ const nextKey = matched ? getOptionValue(matched) : typed;
703
+ // Only commit if this would actually change the value.
704
+ if (singleSelectedKey !== nextKey) {
705
+ commitSelection(nextKey);
706
+ }
707
+ }
708
+ if (!isFormMode || !bridge) return;
709
+ const raw = bridge.getValue(name);
710
+ // Multi mode: bridge value is an array — passthrough.
711
+ const current = raw == null ? '' : (raw as unknown as string);
712
+ registration?.onBlur?.({
713
+ target: { name, value: current },
714
+ type: 'blur',
715
+ });
716
+ };
717
+
718
+ const handleOptionClick = (opt: TOption) => {
719
+ if (getOptionDisabled(opt)) return;
720
+ commitSelection(getOptionValue(opt));
721
+ // Multi-select: keep the popover open for chained picks.
722
+ if (!isMulti) {
723
+ closePopover();
724
+ } else {
725
+ setHighlightedIndex(0);
726
+ }
727
+ inputRef.current?.focus();
728
+ };
729
+
730
+ // Pattern: `onMouseDown` preventDefault keeps focus on the `<input>`
731
+ // (without this, clicking the chevron blurs the input and we lose the
732
+ // popover-on-focus open state). `onClick` does the actual work so
733
+ // testing-library's `fireEvent.click(...)` also triggers it.
734
+ const preventBlur = (event: MouseEvent<HTMLElement>) => {
735
+ event.preventDefault();
736
+ };
737
+
738
+ const handleTriggerClick = () => {
739
+ if (effectiveDisabled || effectiveReadOnly) return;
740
+ if (isOpen) {
741
+ closePopover();
742
+ } else {
743
+ openPopover();
744
+ }
745
+ inputRef.current?.focus();
746
+ };
747
+
748
+ const handleClearClick = () => {
749
+ if (effectiveDisabled || effectiveReadOnly) return;
750
+ commitSelection(null);
751
+ inputRef.current?.focus();
752
+ };
753
+
754
+ // ───── Render-time guards (after all hooks) ─────
755
+
756
+ if (!isVisible) return null;
757
+ if (!accessState.visible) return null;
758
+
759
+ const v = autocompleteVariants({
760
+ size,
761
+ layout,
762
+ error: resolvedError,
763
+ fullWidth,
764
+ disabled: effectiveDisabled,
765
+ });
766
+
767
+ const activeOptionId =
768
+ isOpen && highlightedIndex >= 0 && highlightedIndex < filteredOptions.length
769
+ ? `${optionIdPrefix}${getOptionValue(filteredOptions[highlightedIndex])}`
770
+ : undefined;
771
+
772
+ return (
773
+ <div
774
+ ref={rootRef}
775
+ className={cn(v.root(), sx, slotProps?.root?.className)}
776
+ >
777
+ {label && (
778
+ <label
779
+ id={labelId}
780
+ htmlFor={`${baseId}-input`}
781
+ className={cn(v.label(), slotProps?.label?.className)}
782
+ >
783
+ {label}
784
+ {required && (
785
+ <span
786
+ aria-hidden="true"
787
+ className={cn(
788
+ v.requiredMark(),
789
+ slotProps?.requiredMark?.className
790
+ )}
791
+ >
792
+ *
793
+ </span>
794
+ )}
795
+ </label>
796
+ )}
797
+
798
+ <div
799
+ className={cn(
800
+ v.inputWrapper(),
801
+ // Multi mode: let chips wrap and replace the fixed `h-*`
802
+ // with `min-h-*` so the wrapper grows with selections.
803
+ isMulti && 'flex-wrap min-h-[var(--ac-min-h,2.5rem)] !h-auto py-1',
804
+ slotProps?.inputWrapper?.className
805
+ )}
806
+ >
807
+ {isMulti && selectedKeys.size > 0 && (
808
+ <div
809
+ className={cn(
810
+ v.chipsList(),
811
+ slotProps?.chipsList?.className
812
+ )}
813
+ >
814
+ {Array.from(selectedKeys).map((key) => {
815
+ const opt = options.find((o) => getOptionValue(o) === key);
816
+ const labelNode = opt ? getOptionLabel(opt) : key;
817
+ const labelText = opt ? labelAsString(opt) ?? key : key;
818
+ return (
819
+ <span
820
+ key={key}
821
+ className={cn(v.chip(), slotProps?.chip?.className)}
822
+ data-chip-key={key}
823
+ >
824
+ {labelNode}
825
+ {!effectiveDisabled && !effectiveReadOnly && (
826
+ <button
827
+ type="button"
828
+ onMouseDown={preventBlur}
829
+ onClick={() => {
830
+ commitSelection(key); // toggle removes
831
+ inputRef.current?.focus();
832
+ }}
833
+ aria-label={`Remove ${labelText}`}
834
+ tabIndex={-1}
835
+ className={cn(
836
+ v.chipRemove(),
837
+ slotProps?.chipRemove?.className
838
+ )}
839
+ >
840
+ ×
841
+ </button>
842
+ )}
843
+ </span>
844
+ );
845
+ })}
846
+ </div>
847
+ )}
848
+
849
+ <input
850
+ ref={inputRef}
851
+ id={`${baseId}-input`}
852
+ name={name}
853
+ type="text"
854
+ role="combobox"
855
+ aria-autocomplete="list"
856
+ aria-expanded={isOpen}
857
+ aria-controls={isOpen ? listboxId : undefined}
858
+ aria-activedescendant={activeOptionId}
859
+ aria-labelledby={label ? labelId : undefined}
860
+ aria-describedby={resolvedHelperText ? helperId : undefined}
861
+ aria-invalid={resolvedError ? true : undefined}
862
+ aria-required={required ? true : undefined}
863
+ placeholder={
864
+ // In multi mode hide the placeholder once the user has at
865
+ // least one chip — the chips already convey "something is
866
+ // selected" and the placeholder would clutter the UI.
867
+ isMulti && selectedKeys.size > 0 ? undefined : placeholder
868
+ }
869
+ value={displayInputValue}
870
+ onChange={handleInputChange}
871
+ onKeyDown={handleKeyDown}
872
+ onFocus={openPopover}
873
+ onBlur={handleBlur}
874
+ disabled={effectiveDisabled}
875
+ readOnly={effectiveReadOnly}
876
+ autoComplete="off"
877
+ // Multi mode: give the input some min-width so it stays
878
+ // clickable even with many chips, and let it shrink/grow with
879
+ // the available row space.
880
+ className={cn(
881
+ v.input(),
882
+ isMulti && 'min-w-[6rem] flex-1 basis-24',
883
+ slotProps?.input?.className
884
+ )}
885
+ />
886
+
887
+ {hasAnySelection && !effectiveDisabled && !effectiveReadOnly && (
888
+ <button
889
+ type="button"
890
+ onMouseDown={preventBlur}
891
+ onClick={handleClearClick}
892
+ aria-label="Clear selection"
893
+ tabIndex={-1}
894
+ className={cn(v.clearButton(), slotProps?.clearButton?.className)}
895
+ >
896
+ ×
897
+ </button>
898
+ )}
899
+
900
+ <button
901
+ type="button"
902
+ onMouseDown={preventBlur}
903
+ onClick={handleTriggerClick}
904
+ aria-label="Open"
905
+ aria-haspopup="listbox"
906
+ aria-expanded={isOpen}
907
+ tabIndex={-1}
908
+ disabled={effectiveDisabled}
909
+ className={cn(v.trigger(), slotProps?.trigger?.className)}
910
+ >
911
+ ▾
912
+ </button>
913
+
914
+ {isOpen && (
915
+ <ul
916
+ ref={listboxRef}
917
+ id={listboxId}
918
+ role="listbox"
919
+ aria-labelledby={label ? labelId : undefined}
920
+ className={cn(
921
+ v.popover(),
922
+ 'absolute left-0 right-0 top-full',
923
+ v.listBox(),
924
+ slotProps?.popover?.className,
925
+ slotProps?.listBox?.className
926
+ )}
927
+ >
928
+ {isLoading ? (
929
+ <li
930
+ className={cn(
931
+ v.emptyState(),
932
+ slotProps?.emptyState?.className
933
+ )}
934
+ aria-live="polite"
935
+ aria-busy="true"
936
+ >
937
+ {loadingMessage}
938
+ </li>
939
+ ) : filteredOptions.length === 0 ? (
940
+ <li
941
+ className={cn(
942
+ v.emptyState(),
943
+ slotProps?.emptyState?.className
944
+ )}
945
+ >
946
+ {emptyMessage}
947
+ </li>
948
+ ) : (
949
+ filteredOptions.map((opt, idx) => {
950
+ const optValue = getOptionValue(opt);
951
+ const optDisabled = getOptionDisabled(opt);
952
+ const isHighlighted = idx === highlightedIndex;
953
+ const isSelected = selectedKeys.has(optValue);
954
+ return (
955
+ <li
956
+ key={resolveOptionKey(opt)}
957
+ id={`${optionIdPrefix}${optValue}`}
958
+ role="option"
959
+ aria-selected={isSelected}
960
+ aria-disabled={optDisabled || undefined}
961
+ data-focused={isHighlighted || undefined}
962
+ data-selected={isSelected || undefined}
963
+ data-disabled={optDisabled || undefined}
964
+ onMouseDown={preventBlur}
965
+ onClick={() => handleOptionClick(opt)}
966
+ onMouseEnter={() => setHighlightedIndex(idx)}
967
+ className={cn(
968
+ v.listItem(),
969
+ slotProps?.listItem?.className
970
+ )}
971
+ >
972
+ {getOptionLabel(opt)}
973
+ </li>
974
+ );
975
+ })
976
+ )}
977
+ </ul>
978
+ )}
979
+ </div>
980
+
981
+ {resolvedHelperText && (
982
+ <p
983
+ id={helperId}
984
+ className={cn(
985
+ resolvedError ? v.errorText() : v.helperText(),
986
+ resolvedError
987
+ ? slotProps?.errorText?.className
988
+ : slotProps?.helperText?.className
989
+ )}
990
+ >
991
+ {resolvedHelperText}
992
+ </p>
993
+ )}
994
+ </div>
995
+ );
996
+ }