@agile-plus/headless 0.1.2 → 0.2.0

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 (231) hide show
  1. package/README.md +24 -17
  2. package/dist/index.cjs +4163 -223
  3. package/dist/index.cjs.map +1 -1
  4. package/dist/index.d.cts +33 -0
  5. package/dist/index.d.ts +33 -0
  6. package/dist/index.js +4258 -216
  7. package/dist/index.js.map +1 -1
  8. package/dist/types-BxsQI7P5.d.cts +93 -0
  9. package/dist/types-BxsQI7P5.d.ts +93 -0
  10. package/dist/types-zpeY0yvD.d.cts +73 -0
  11. package/dist/types-zpeY0yvD.d.ts +73 -0
  12. package/dist/useAccordion/index.cjs +149 -0
  13. package/dist/useAccordion/index.cjs.map +1 -0
  14. package/dist/useAccordion/index.d.cts +119 -0
  15. package/dist/useAccordion/index.d.ts +119 -0
  16. package/dist/useAccordion/index.js +128 -0
  17. package/dist/useAccordion/index.js.map +1 -0
  18. package/dist/useAvatar/index.cjs +135 -0
  19. package/dist/useAvatar/index.cjs.map +1 -0
  20. package/dist/useAvatar/index.d.cts +120 -0
  21. package/dist/useAvatar/index.d.ts +120 -0
  22. package/dist/useAvatar/index.js +106 -0
  23. package/dist/useAvatar/index.js.map +1 -0
  24. package/dist/useCheckbox/index.cjs +3 -1
  25. package/dist/useCheckbox/index.cjs.map +1 -1
  26. package/dist/useCheckbox/index.js +3 -1
  27. package/dist/useCheckbox/index.js.map +1 -1
  28. package/dist/useCollapsible/index.cjs +10 -0
  29. package/dist/useCollapsible/index.cjs.map +1 -1
  30. package/dist/useCollapsible/index.js +11 -1
  31. package/dist/useCollapsible/index.js.map +1 -1
  32. package/dist/useDatePicker/index.cjs +684 -0
  33. package/dist/useDatePicker/index.cjs.map +1 -0
  34. package/dist/useDatePicker/index.d.cts +191 -0
  35. package/dist/useDatePicker/index.d.ts +191 -0
  36. package/dist/useDatePicker/index.js +671 -0
  37. package/dist/useDatePicker/index.js.map +1 -0
  38. package/dist/useDateRangePicker/index.cjs +614 -0
  39. package/dist/useDateRangePicker/index.cjs.map +1 -0
  40. package/dist/useDateRangePicker/index.d.cts +159 -0
  41. package/dist/useDateRangePicker/index.d.ts +159 -0
  42. package/dist/useDateRangePicker/index.js +601 -0
  43. package/dist/useDateRangePicker/index.js.map +1 -0
  44. package/dist/useDialog/index.cjs.map +1 -1
  45. package/dist/useDialog/index.js.map +1 -1
  46. package/dist/useDropdownMenu/index.cjs +468 -0
  47. package/dist/useDropdownMenu/index.cjs.map +1 -0
  48. package/dist/useDropdownMenu/index.d.cts +73 -0
  49. package/dist/useDropdownMenu/index.d.ts +73 -0
  50. package/dist/useDropdownMenu/index.js +441 -0
  51. package/dist/useDropdownMenu/index.js.map +1 -0
  52. package/dist/useEllipsis/index.cjs +181 -0
  53. package/dist/useEllipsis/index.cjs.map +1 -0
  54. package/dist/useEllipsis/index.d.cts +67 -0
  55. package/dist/useEllipsis/index.d.ts +67 -0
  56. package/dist/useEllipsis/index.js +162 -0
  57. package/dist/useEllipsis/index.js.map +1 -0
  58. package/dist/useFloating/index.cjs +177 -0
  59. package/dist/useFloating/index.cjs.map +1 -0
  60. package/dist/useFloating/index.d.cts +21 -0
  61. package/dist/useFloating/index.d.ts +21 -0
  62. package/dist/useFloating/index.js +150 -0
  63. package/dist/useFloating/index.js.map +1 -0
  64. package/dist/useFormControl/index.cjs +5 -0
  65. package/dist/useFormControl/index.cjs.map +1 -1
  66. package/dist/useFormControl/index.js +5 -0
  67. package/dist/useFormControl/index.js.map +1 -1
  68. package/dist/useInput/index.cjs +192 -0
  69. package/dist/useInput/index.cjs.map +1 -0
  70. package/dist/useInput/index.d.cts +41 -0
  71. package/dist/useInput/index.d.ts +41 -0
  72. package/dist/useInput/index.js +165 -0
  73. package/dist/useInput/index.js.map +1 -0
  74. package/dist/useKeepMounted/index.cjs +44 -0
  75. package/dist/useKeepMounted/index.cjs.map +1 -0
  76. package/dist/useKeepMounted/index.d.cts +45 -0
  77. package/dist/useKeepMounted/index.d.ts +45 -0
  78. package/dist/useKeepMounted/index.js +17 -0
  79. package/dist/useKeepMounted/index.js.map +1 -0
  80. package/dist/useMenu/index.cjs +438 -0
  81. package/dist/useMenu/index.cjs.map +1 -0
  82. package/dist/useMenu/index.d.cts +134 -0
  83. package/dist/useMenu/index.d.ts +134 -0
  84. package/dist/useMenu/index.js +419 -0
  85. package/dist/useMenu/index.js.map +1 -0
  86. package/dist/usePagination/index.cjs +113 -0
  87. package/dist/usePagination/index.cjs.map +1 -0
  88. package/dist/usePagination/index.d.cts +139 -0
  89. package/dist/usePagination/index.d.ts +139 -0
  90. package/dist/usePagination/index.js +95 -0
  91. package/dist/usePagination/index.js.map +1 -0
  92. package/dist/usePopover/index.cjs +312 -0
  93. package/dist/usePopover/index.cjs.map +1 -0
  94. package/dist/usePopover/index.d.cts +71 -0
  95. package/dist/usePopover/index.d.ts +71 -0
  96. package/dist/usePopover/index.js +285 -0
  97. package/dist/usePopover/index.js.map +1 -0
  98. package/dist/useSelect/index.cjs +729 -0
  99. package/dist/useSelect/index.cjs.map +1 -0
  100. package/dist/useSelect/index.d.cts +193 -0
  101. package/dist/useSelect/index.d.ts +193 -0
  102. package/dist/useSelect/index.js +710 -0
  103. package/dist/useSelect/index.js.map +1 -0
  104. package/dist/useSplitter/index.cjs +558 -0
  105. package/dist/useSplitter/index.cjs.map +1 -0
  106. package/dist/useSplitter/index.d.cts +307 -0
  107. package/dist/useSplitter/index.d.ts +307 -0
  108. package/dist/useSplitter/index.js +541 -0
  109. package/dist/useSplitter/index.js.map +1 -0
  110. package/dist/useSwitch/index.cjs +4 -1
  111. package/dist/useSwitch/index.cjs.map +1 -1
  112. package/dist/useSwitch/index.js +4 -1
  113. package/dist/useSwitch/index.js.map +1 -1
  114. package/dist/useTable/index.cjs +308 -0
  115. package/dist/useTable/index.cjs.map +1 -0
  116. package/dist/useTable/index.d.cts +242 -0
  117. package/dist/useTable/index.d.ts +242 -0
  118. package/dist/useTable/index.js +301 -0
  119. package/dist/useTable/index.js.map +1 -0
  120. package/dist/useTabs/index.cjs +13 -4
  121. package/dist/useTabs/index.cjs.map +1 -1
  122. package/dist/useTabs/index.d.cts +5 -1
  123. package/dist/useTabs/index.d.ts +5 -1
  124. package/dist/useTabs/index.js +13 -4
  125. package/dist/useTabs/index.js.map +1 -1
  126. package/dist/useTextControl-Dcq0GFmg.d.cts +63 -0
  127. package/dist/useTextControl-Dcq0GFmg.d.ts +63 -0
  128. package/dist/useTextarea/index.cjs +186 -0
  129. package/dist/useTextarea/index.cjs.map +1 -0
  130. package/dist/useTextarea/index.d.cts +30 -0
  131. package/dist/useTextarea/index.d.ts +30 -0
  132. package/dist/useTextarea/index.js +159 -0
  133. package/dist/useTextarea/index.js.map +1 -0
  134. package/dist/useToast/index.cjs +27 -20
  135. package/dist/useToast/index.cjs.map +1 -1
  136. package/dist/useToast/index.js +27 -20
  137. package/dist/useToast/index.js.map +1 -1
  138. package/dist/useToastViewport/index.cjs +1 -3
  139. package/dist/useToastViewport/index.cjs.map +1 -1
  140. package/dist/useToastViewport/index.js +1 -3
  141. package/dist/useToastViewport/index.js.map +1 -1
  142. package/dist/useTooltip/index.cjs +357 -0
  143. package/dist/useTooltip/index.cjs.map +1 -0
  144. package/dist/useTooltip/index.d.cts +81 -0
  145. package/dist/useTooltip/index.d.ts +81 -0
  146. package/dist/useTooltip/index.js +338 -0
  147. package/dist/useTooltip/index.js.map +1 -0
  148. package/dist/useVirtualList/index.cjs +308 -0
  149. package/dist/useVirtualList/index.cjs.map +1 -0
  150. package/dist/useVirtualList/index.d.cts +31 -0
  151. package/dist/useVirtualList/index.d.ts +31 -0
  152. package/dist/useVirtualList/index.js +288 -0
  153. package/dist/useVirtualList/index.js.map +1 -0
  154. package/dist/useVirtualTree/index.cjs +520 -0
  155. package/dist/useVirtualTree/index.cjs.map +1 -0
  156. package/dist/useVirtualTree/index.d.cts +146 -0
  157. package/dist/useVirtualTree/index.d.ts +146 -0
  158. package/dist/useVirtualTree/index.js +511 -0
  159. package/dist/useVirtualTree/index.js.map +1 -0
  160. package/package.json +121 -2
  161. package/src/index.ts +38 -0
  162. package/src/useAccordion/index.ts +7 -0
  163. package/src/useAccordion/types.ts +118 -0
  164. package/src/useAccordion/useAccordion.ts +130 -0
  165. package/src/useAvatar/index.ts +14 -0
  166. package/src/useAvatar/types.ts +90 -0
  167. package/src/useAvatar/useAvatar.ts +39 -0
  168. package/src/useAvatar/useAvatarFallback.ts +62 -0
  169. package/src/useAvatar/useAvatarImage.ts +78 -0
  170. package/src/useCheckbox/useCheckbox.ts +4 -1
  171. package/src/useCollapsible/useCollapsible.ts +22 -1
  172. package/src/useDatePicker/index.ts +9 -0
  173. package/src/useDatePicker/types.ts +177 -0
  174. package/src/useDatePicker/useDatePicker.ts +688 -0
  175. package/src/useDateRangePicker/index.ts +8 -0
  176. package/src/useDateRangePicker/types.ts +146 -0
  177. package/src/useDateRangePicker/useDateRangePicker.ts +618 -0
  178. package/src/useDropdownMenu/index.ts +3 -0
  179. package/src/useDropdownMenu/types.ts +61 -0
  180. package/src/useDropdownMenu/useDropdownMenu.ts +322 -0
  181. package/src/useEllipsis/index.ts +3 -0
  182. package/src/useEllipsis/types.ts +51 -0
  183. package/src/useEllipsis/useEllipsis.ts +169 -0
  184. package/src/useFloating/index.ts +3 -0
  185. package/src/useFloating/types.ts +79 -0
  186. package/src/useFloating/useFloating.ts +199 -0
  187. package/src/useFormControl/useFormControl.ts +13 -0
  188. package/src/useInput/index.ts +3 -0
  189. package/src/useInput/types.ts +29 -0
  190. package/src/useInput/useInput.ts +40 -0
  191. package/src/useKeepMounted/index.ts +3 -0
  192. package/src/useKeepMounted/types.ts +29 -0
  193. package/src/useKeepMounted/useKeepMounted.ts +34 -0
  194. package/src/useMenu/index.ts +9 -0
  195. package/src/useMenu/types.ts +126 -0
  196. package/src/useMenu/useMenu.ts +504 -0
  197. package/src/usePagination/index.ts +3 -0
  198. package/src/usePagination/types.ts +137 -0
  199. package/src/usePagination/usePagination.ts +109 -0
  200. package/src/usePopover/index.ts +3 -0
  201. package/src/usePopover/types.ts +65 -0
  202. package/src/usePopover/usePopover.ts +157 -0
  203. package/src/useSelect/index.ts +9 -0
  204. package/src/useSelect/types.ts +184 -0
  205. package/src/useSelect/useSelect.ts +713 -0
  206. package/src/useSplitter/index.ts +10 -0
  207. package/src/useSplitter/types.ts +336 -0
  208. package/src/useSplitter/useSplitter.ts +648 -0
  209. package/src/useSplitter/useSplitterPanel.ts +106 -0
  210. package/src/useSwitch/useSwitch.ts +6 -1
  211. package/src/useTable/index.ts +3 -0
  212. package/src/useTable/types.ts +282 -0
  213. package/src/useTable/useTable.ts +407 -0
  214. package/src/useTabs/types.ts +5 -1
  215. package/src/useTabs/useTabs.ts +30 -6
  216. package/src/useTextarea/index.ts +3 -0
  217. package/src/useTextarea/types.ts +17 -0
  218. package/src/useTextarea/useTextarea.ts +34 -0
  219. package/src/useToast/useToast.ts +43 -26
  220. package/src/useToastViewport/useToastViewport.ts +10 -9
  221. package/src/useTooltip/index.ts +3 -0
  222. package/src/useTooltip/types.ts +72 -0
  223. package/src/useTooltip/useTooltip.ts +240 -0
  224. package/src/useVirtualList/index.ts +8 -0
  225. package/src/useVirtualList/types.ts +95 -0
  226. package/src/useVirtualList/useVirtualList.ts +478 -0
  227. package/src/useVirtualTree/index.ts +3 -0
  228. package/src/useVirtualTree/types.ts +179 -0
  229. package/src/useVirtualTree/useVirtualTree.ts +342 -0
  230. package/src/utils/useFocusTrap.ts +2 -0
  231. package/src/utils/useTextControl.ts +191 -0
@@ -0,0 +1,713 @@
1
+ import { computed, onScopeDispose, ref, shallowRef, toValue, useId, watch } from 'vue';
2
+
3
+ import { getHiddenSelectStyle, writeNativeSelectValue } from '@agile-plus/primitives/form';
4
+
5
+ import {
6
+ DEFAULT_TYPEAHEAD_TIMEOUT,
7
+ appendTypeaheadSearch,
8
+ findTypeaheadMatch,
9
+ resolveOpenHighlight,
10
+ resolveScrollTop,
11
+ resolveSelectHighlight,
12
+ resolveSelectKeyIntent,
13
+ } from '@agile-plus/primitives/select';
14
+
15
+ import { useControllable } from '../utils/useControllable';
16
+ import { useCollection } from '../utils/useCollection';
17
+ import { useFormResetListener } from '../utils/useFormResetListener';
18
+ import { useResizeObserver } from '../utils/useResizeObserver';
19
+ import { isBrowser } from '../utils/env';
20
+ import { useFloating } from '../useFloating';
21
+
22
+ import type { CSSProperties } from 'vue';
23
+
24
+ import type { HiddenInputSize } from '@agile-plus/primitives/form';
25
+
26
+ import type { SelectItemEntry, SelectOption, UseSelectOptions, UseSelectReturn } from './types';
27
+
28
+ /** 触发元素与列表之间的缺省间距,与成品层的视觉留白一致。 */
29
+ const DEFAULT_OFFSET = 4;
30
+
31
+ /** 列表与视口边缘的缺省留白。 */
32
+ const DEFAULT_PADDING = 8;
33
+
34
+ /**
35
+ * Select 的 Vue 适配。
36
+ *
37
+ * 四块职责:**选中值与开合**(两个独立的受控状态)、**选项注册表**(顺序即导航顺序)、
38
+ * **键盘与 typeahead**(规则全部下沉 primitives)、**定位与表单接入**。
39
+ *
40
+ * 焦点模型采用 ARIA 的 select-only combobox:焦点**始终留在触发元素**上,列表通过
41
+ * `aria-activedescendant` 指向高亮项,而不是把焦点移进浮层。这样不需要焦点陷阱,
42
+ * Tab 天然能走出组件,读屏也能逐项播报;代价是列表里的选项不可聚焦,因此指针按下
43
+ * 必须 preventDefault,否则点击选项会把焦点从触发元素上抢走并立刻触发关闭。
44
+ *
45
+ * typeahead 不持有定时器:搜索串的重置由「距上次按键多久」判定,时间戳在按键时读取,
46
+ * 因此没有需要清理的资源,也不依赖 fake timers 就能单测。
47
+ */
48
+ export function useSelect(options: UseSelectOptions = {}): UseSelectReturn {
49
+ const uid = useId();
50
+ const triggerId = `select-trigger-${uid}`;
51
+ const contentId = `select-content-${uid}`;
52
+
53
+ const valueState = useControllable<string>({
54
+ value: () => toValue(options.modelValue),
55
+ defaultValue: options.defaultValue ?? '',
56
+ onChange: (next) => options.onValueChange?.(next),
57
+ });
58
+
59
+ const openState = useControllable<boolean>({
60
+ value: () => toValue(options.open),
61
+ defaultValue: options.defaultOpen ?? false,
62
+ onChange: (next) => options.onOpenChange?.(next),
63
+ });
64
+
65
+ const value = valueState.value;
66
+ const isOpen = openState.value;
67
+
68
+ const isDisabled = computed(() => toValue(options.disabled) === true);
69
+ const isRequired = computed(() => toValue(options.required) === true);
70
+ const loop = options.loop ?? true;
71
+
72
+ const highlightedValue = ref<string | null>(null);
73
+
74
+ const collection = useCollection<SelectItemEntry>({ key: (entry) => entry.id });
75
+
76
+ const floating = useFloating({
77
+ placement: options.placement ?? 'bottom-start',
78
+ offset: options.offset ?? DEFAULT_OFFSET,
79
+ flip: options.flip,
80
+ shift: options.shift,
81
+ padding: options.padding ?? DEFAULT_PADDING,
82
+ strategy: options.strategy,
83
+ open: isOpen,
84
+ });
85
+
86
+ const viewportElement = ref<HTMLElement | null>(null);
87
+ const nativeSelectElement = ref<HTMLSelectElement | null>(null);
88
+
89
+ const triggerSize = shallowRef<HiddenInputSize | null>(null);
90
+
91
+ /** 按注册顺序排列的选项,禁用态已合并整体禁用。 */
92
+ const optionList = computed<SelectOption[]>(() =>
93
+ collection.items.value.map((entry) => ({
94
+ value: entry.value.value,
95
+ textValue: entry.textValue.value,
96
+ disabled: isDisabled.value || entry.disabled.value,
97
+ }))
98
+ );
99
+
100
+ const hasValue = computed(() => value.value !== '');
101
+
102
+ /**
103
+ * 选项快照缓存。列表改为懒渲染(打开才挂载)后,关闭态实时注册表为空,但三条
104
+ * 路径仍需要完整选项表:触发元素回显选中文本、关闭态 typeahead、隐藏原生 select
105
+ * 的 option 列表。缓存只增改不清空,保留最近一次见过的文本与禁用态;打开态的
106
+ * 键盘导航仍用实时注册表(顺序即 DOM 顺序)。
107
+ */
108
+ const optionCache = shallowRef(new Map<string, SelectOption>());
109
+
110
+ // 数据驱动种子:首次打开前就填充快照,保证回显 / typeahead / 原生 select 可用。
111
+ // 种子兼容 label / textValue 两种写法(成品层 options 用 label)。
112
+ watch(
113
+ () => toValue(options.options) ?? [],
114
+ (list) => {
115
+ if (list.length === 0) return;
116
+
117
+ const next = new Map(optionCache.value);
118
+
119
+ for (const option of list) {
120
+ next.set(option.value, {
121
+ value: option.value,
122
+ textValue: option.textValue ?? option.label ?? option.value,
123
+ disabled: option.disabled === true,
124
+ });
125
+ }
126
+
127
+ optionCache.value = next;
128
+ },
129
+ { immediate: true }
130
+ );
131
+
132
+ watch(
133
+ optionList,
134
+ (list) => {
135
+ if (list.length === 0) return;
136
+
137
+ const next = new Map(optionCache.value);
138
+
139
+ for (const option of list) next.set(option.value, option);
140
+
141
+ optionCache.value = next;
142
+ },
143
+ { immediate: true }
144
+ );
145
+
146
+ const cachedOptions = computed(() => [...optionCache.value.values()]);
147
+
148
+ /** 关闭态 typeahead 用缓存(实时注册表为空),打开态用实时注册表。 */
149
+ const typeaheadOptions = computed(() =>
150
+ optionList.value.length > 0 ? optionList.value : cachedOptions.value
151
+ );
152
+
153
+ const selectedText = computed(
154
+ () =>
155
+ optionList.value.find((option) => option.value === value.value)?.textValue ??
156
+ optionCache.value.get(value.value)?.textValue ??
157
+ ''
158
+ );
159
+
160
+ /** 当前高亮项的 DOM id,供触发元素的 aria-activedescendant 指向。 */
161
+ const activeDescendantId = computed(() => {
162
+ if (!isOpen.value || highlightedValue.value === null) return undefined;
163
+
164
+ return collection.items.value.find((entry) => entry.value.value === highlightedValue.value)?.id;
165
+ });
166
+
167
+ const isFormControl = computed(() => {
168
+ if (toValue(options.name) || toValue(options.form)) return true;
169
+
170
+ const trigger = floating.referenceRef.value;
171
+
172
+ // 触发元素尚未挂载(含 SSR 首帧)时按表单控件处理,保证无 JS 时提交路径仍然存在。
173
+ if (!trigger) return true;
174
+
175
+ return trigger.closest('form') !== null;
176
+ });
177
+
178
+ const resize = useResizeObserver(measureTrigger);
179
+
180
+ let typeaheadSearch = '';
181
+ let typeaheadAt: number | null = null;
182
+
183
+ function getItemId(localId: string): string {
184
+ return `${contentId}-item-${localId}`;
185
+ }
186
+
187
+ function findEntry(itemValue: string): SelectItemEntry | undefined {
188
+ return collection.items.value.find((entry) => entry.value.value === itemValue);
189
+ }
190
+
191
+ function setValue(next: string): void {
192
+ valueState.set(next);
193
+ }
194
+
195
+ /**
196
+ * 打开下拉并决定高亮落点。
197
+ *
198
+ * 落点由 primitives 算出(选中项优先,否则按按键方向取边界),这里只负责落地。
199
+ * 整体禁用时不打开:受控模式下外部也可能直接调用 open(),不能只靠属性表挡住。
200
+ */
201
+ function open(): void {
202
+ if (isDisabled.value) return;
203
+
204
+ highlightedValue.value = resolveOpenHighlight({
205
+ options: optionList.value,
206
+ selectedValue: value.value,
207
+ edge: 'first',
208
+ });
209
+
210
+ openState.set(true);
211
+ }
212
+
213
+ function close(): void {
214
+ highlightedValue.value = null;
215
+ typeaheadSearch = '';
216
+ typeaheadAt = null;
217
+
218
+ openState.set(false);
219
+ }
220
+
221
+ function toggle(): void {
222
+ if (isOpen.value) close();
223
+ else open();
224
+ }
225
+
226
+ function commitHighlighted(): void {
227
+ const current = highlightedValue.value;
228
+
229
+ if (current !== null) setValue(current);
230
+
231
+ close();
232
+ }
233
+
234
+ function moveHighlight(intent: 'next' | 'prev' | 'first' | 'last'): void {
235
+ const next = resolveSelectHighlight({
236
+ intent,
237
+ options: optionList.value,
238
+ currentValue: highlightedValue.value,
239
+ loop,
240
+ });
241
+
242
+ // null 表示不移动(列表为空或不循环时已到边界),此时保持原高亮而不是清空。
243
+ if (next !== null) highlightedValue.value = next;
244
+ }
245
+
246
+ /**
247
+ * 累积搜索串并跳到命中项。
248
+ *
249
+ * 打开时只移动高亮,关闭时直接改选中值——后者是原生 select 的手感:不展开也能
250
+ * 用键盘换值。命中不了时保持原状,不清空已有选择。
251
+ */
252
+ function runTypeahead(char: string): void {
253
+ const now = Date.now();
254
+ const timeout = toValue(options.typeaheadTimeout) ?? DEFAULT_TYPEAHEAD_TIMEOUT;
255
+
256
+ typeaheadSearch = appendTypeaheadSearch({
257
+ previous: typeaheadSearch,
258
+ char,
259
+ elapsed: typeaheadAt === null ? timeout : now - typeaheadAt,
260
+ timeout,
261
+ });
262
+ typeaheadAt = now;
263
+
264
+ const match = findTypeaheadMatch({
265
+ options: typeaheadOptions.value,
266
+ search: typeaheadSearch,
267
+ currentValue: isOpen.value ? highlightedValue.value : value.value || null,
268
+ });
269
+
270
+ if (match === null) return;
271
+
272
+ if (isOpen.value) highlightedValue.value = match;
273
+ else setValue(match);
274
+ }
275
+
276
+ function onTriggerClick(): void {
277
+ if (isDisabled.value) return;
278
+
279
+ toggle();
280
+ }
281
+
282
+ function onTriggerKeydown(event: KeyboardEvent): void {
283
+ if (isDisabled.value) return;
284
+
285
+ const intent = resolveSelectKeyIntent({
286
+ key: event.key,
287
+ open: isOpen.value,
288
+ hasModifierKey: event.ctrlKey || event.altKey || event.metaKey,
289
+ });
290
+
291
+ if (intent.kind === 'none') return;
292
+
293
+ // Tab 是唯一不拦默认行为的意图:关闭后焦点要继续走向下一个控件。
294
+ if (intent.kind !== 'tab-out') event.preventDefault();
295
+
296
+ switch (intent.kind) {
297
+ case 'open':
298
+ highlightedValue.value = resolveOpenHighlight({
299
+ options: optionList.value,
300
+ selectedValue: value.value,
301
+ edge: intent.edge,
302
+ });
303
+ openState.set(true);
304
+ break;
305
+
306
+ case 'close':
307
+ close();
308
+ break;
309
+
310
+ case 'tab-out':
311
+ close();
312
+ break;
313
+
314
+ case 'commit':
315
+ commitHighlighted();
316
+ break;
317
+
318
+ case 'highlight':
319
+ moveHighlight(intent.intent);
320
+ break;
321
+
322
+ case 'typeahead':
323
+ runTypeahead(intent.char);
324
+ break;
325
+ }
326
+ }
327
+
328
+ /**
329
+ * 焦点离开组件时关闭。
330
+ *
331
+ * 焦点仍在触发元素或列表内部时不算离开:点击选项已经 preventDefault 保住焦点,
332
+ * 但消费者可能用 asChild 换成可聚焦元素,此时 relatedTarget 会落在组件内部。
333
+ */
334
+ function onTriggerBlur(event: FocusEvent): void {
335
+ const next = event.relatedTarget;
336
+
337
+ if (next instanceof Node) {
338
+ const trigger = floating.referenceRef.value;
339
+ const content = floating.floatingRef.value;
340
+
341
+ if (trigger?.contains(next) || content?.contains(next)) return;
342
+ }
343
+
344
+ close();
345
+ }
346
+
347
+ /**
348
+ * 列表内指针按下必须阻止默认行为。
349
+ *
350
+ * 选项是 role="option" 的不可聚焦元素,浏览器默认会把焦点移到 body,触发元素随即
351
+ * blur 并关闭下拉——表现为「点不中选项」。滚动条拖动同样受益于此。
352
+ */
353
+ function onContentPointerDown(event: PointerEvent | MouseEvent): void {
354
+ event.preventDefault();
355
+ }
356
+
357
+ function onContentPointerLeave(): void {
358
+ highlightedValue.value = null;
359
+ }
360
+
361
+ function onItemPointerMove(itemValue: string): void {
362
+ const option = optionList.value.find((entry) => entry.value === itemValue);
363
+
364
+ if (!option || option.disabled) return;
365
+
366
+ highlightedValue.value = itemValue;
367
+ }
368
+
369
+ function onItemClick(itemValue: string): void {
370
+ const option = optionList.value.find((entry) => entry.value === itemValue);
371
+
372
+ if (!option || option.disabled) return;
373
+
374
+ setValue(itemValue);
375
+ close();
376
+
377
+ // 关闭后把焦点交还触发元素:指针按下时保住的焦点可能已被消费者的结构改变。
378
+ floating.referenceRef.value?.focus();
379
+ }
380
+
381
+ function getTriggerProps(): Record<string, unknown> {
382
+ const labelledby = toValue(options.ariaLabelledby);
383
+ const describedby = toValue(options.ariaDescribedby);
384
+
385
+ return {
386
+ id: triggerId,
387
+ role: 'combobox',
388
+ 'aria-expanded': isOpen.value,
389
+ 'aria-controls': contentId,
390
+ 'aria-haspopup': 'listbox',
391
+ // 列表被 portal 到 body,不是触发元素的 DOM 后代。aria-activedescendant 要求
392
+ // 被指向的元素在自身子树内或经 aria-owns 建立归属,因此打开时显式声明所有权,
393
+ // 否则读屏会拒绝播报高亮项。关闭时不声明:那会把一个 hidden 的子树挂进来。
394
+ 'aria-owns': isOpen.value ? contentId : undefined,
395
+ 'aria-activedescendant': activeDescendantId.value,
396
+ 'aria-required': isRequired.value || undefined,
397
+ 'aria-disabled': isDisabled.value || undefined,
398
+ 'aria-labelledby': labelledby || undefined,
399
+ 'aria-describedby': describedby || undefined,
400
+ 'data-state': isOpen.value ? 'open' : 'closed',
401
+ 'data-disabled': isDisabled.value ? '' : undefined,
402
+ // 占位态交给样式层决定文字颜色,逻辑层不输出 class。
403
+ 'data-placeholder': hasValue.value ? undefined : '',
404
+ disabled: isDisabled.value || undefined,
405
+ };
406
+ }
407
+
408
+ function getContentProps(): Record<string, unknown> {
409
+ return {
410
+ id: contentId,
411
+ role: 'listbox',
412
+ 'aria-labelledby': toValue(options.ariaLabelledby) || triggerId,
413
+ 'aria-orientation': 'vertical',
414
+ 'data-state': isOpen.value ? 'open' : 'closed',
415
+ };
416
+ }
417
+
418
+ function getViewportProps(): Record<string, unknown> {
419
+ return {
420
+ role: 'presentation',
421
+ 'data-part': 'viewport',
422
+ // 视口是滚动容器,必须可聚焦才能让键盘用户用滚轮/方向键之外的方式滚动;
423
+ // 但焦点模型要求焦点留在触发元素,因此这里只给 -1,不进 Tab 序列。
424
+ tabindex: -1,
425
+ };
426
+ }
427
+
428
+ function getItemProps(itemValue: string): Record<string, unknown> {
429
+ const option = optionList.value.find((entry) => entry.value === itemValue);
430
+ const disabled = option?.disabled === true;
431
+ const selected = value.value === itemValue;
432
+
433
+ return {
434
+ id: findEntry(itemValue)?.id,
435
+ role: 'option',
436
+ 'aria-selected': selected,
437
+ 'aria-disabled': disabled || undefined,
438
+ 'data-state': selected ? 'checked' : 'unchecked',
439
+ 'data-highlighted': highlightedValue.value === itemValue ? '' : undefined,
440
+ 'data-disabled': disabled ? '' : undefined,
441
+ 'data-value': itemValue,
442
+ };
443
+ }
444
+
445
+ function getGroupProps(labelId: string): Record<string, unknown> {
446
+ return { role: 'group', 'aria-labelledby': labelId };
447
+ }
448
+
449
+ function getLabelProps(id: string): Record<string, unknown> {
450
+ return { id, 'data-part': 'label' };
451
+ }
452
+
453
+ function getSeparatorProps(): Record<string, unknown> {
454
+ return { role: 'separator', 'aria-orientation': 'horizontal' };
455
+ }
456
+
457
+ function getValueProps(): Record<string, unknown> {
458
+ return { 'data-part': 'value', 'data-placeholder': hasValue.value ? undefined : '' };
459
+ }
460
+
461
+ function getIconProps(): Record<string, unknown> {
462
+ return { 'aria-hidden': 'true', 'data-part': 'icon' };
463
+ }
464
+
465
+ function getNativeSelectProps(): Record<string, unknown> | null {
466
+ if (!isFormControl.value) return null;
467
+
468
+ const name = toValue(options.name);
469
+ const form = toValue(options.form);
470
+
471
+ return {
472
+ name: name || undefined,
473
+ form: form || undefined,
474
+ required: isRequired.value,
475
+ disabled: isDisabled.value,
476
+ tabindex: -1,
477
+ 'aria-hidden': 'true',
478
+ style: getHiddenSelectStyle(triggerSize.value),
479
+ };
480
+ }
481
+
482
+ function setTriggerElement(node: unknown): void {
483
+ floating.referenceRef.value = node instanceof HTMLElement ? node : null;
484
+ }
485
+
486
+ function setContentElement(node: unknown): void {
487
+ floating.floatingRef.value = node instanceof HTMLElement ? node : null;
488
+ }
489
+
490
+ function setViewportElement(node: unknown): void {
491
+ viewportElement.value = node instanceof HTMLElement ? node : null;
492
+ }
493
+
494
+ function setNativeSelectElement(node: unknown): void {
495
+ nativeSelectElement.value = node instanceof HTMLSelectElement ? node : null;
496
+ }
497
+
498
+ /**
499
+ * 一次读取阶段量完触发元素尺寸,之后不再碰布局。
500
+ *
501
+ * 只量尺寸:可用高度由 useFloating 在同一次测量里算出(availableSpace),这里再挂
502
+ * 一套 scroll / resize 监听会让同一帧读两次布局,既浪费也会让位置与尺寸差一帧。
503
+ *
504
+ * 尺寸只在真的变化时写入:它既决定列表最小宽度也决定隐藏原生 select 的覆盖面积,
505
+ * 无条件写入会把「尺寸变 → 重定位 → 再量」这条链路变成每帧重渲染。
506
+ */
507
+ function measureTrigger(): void {
508
+ const trigger = floating.referenceRef.value;
509
+
510
+ if (!trigger || !isBrowser) {
511
+ triggerSize.value = null;
512
+
513
+ return;
514
+ }
515
+
516
+ const rect = trigger.getBoundingClientRect();
517
+ const current = triggerSize.value;
518
+
519
+ if (!current || current.width !== rect.width || current.height !== rect.height) {
520
+ triggerSize.value = { width: rect.width, height: rect.height };
521
+ }
522
+ }
523
+
524
+ const contentStyle = computed<CSSProperties>(() => {
525
+ const available = floating.availableSpace.value;
526
+
527
+ return {
528
+ ...floating.floatingStyle.value,
529
+ ...(triggerSize.value
530
+ ? { '--y-select-trigger-width': `${triggerSize.value.width}px` }
531
+ : null),
532
+ ...(available ? { '--y-select-content-available-height': `${available.height}px` } : null),
533
+ };
534
+ });
535
+
536
+ /** 把高亮项滚进视口;只动视口自己的 scrollTop,不连带滚动页面。 */
537
+ function scrollHighlightedIntoView(): void {
538
+ const viewport = viewportElement.value;
539
+ const current = highlightedValue.value;
540
+
541
+ if (!viewport || current === null) return;
542
+
543
+ const item = findEntry(current)?.element.value;
544
+
545
+ if (!item) return;
546
+
547
+ const itemRect = item.getBoundingClientRect();
548
+ const viewportRect = viewport.getBoundingClientRect();
549
+
550
+ viewport.scrollTop = resolveScrollTop({
551
+ scrollTop: viewport.scrollTop,
552
+ itemOffset: itemRect.top - viewportRect.top,
553
+ itemSize: itemRect.height,
554
+ viewportSize: viewportRect.height,
555
+ });
556
+ }
557
+
558
+ function handleDocumentPointerDown(event: PointerEvent): void {
559
+ const target = event.target;
560
+
561
+ if (!(target instanceof Node)) return;
562
+
563
+ const trigger = floating.referenceRef.value;
564
+ const content = floating.floatingRef.value;
565
+
566
+ if (trigger?.contains(target) || content?.contains(target)) return;
567
+
568
+ close();
569
+ }
570
+
571
+ function attachDismiss(): void {
572
+ document.addEventListener('pointerdown', handleDocumentPointerDown, true);
573
+ }
574
+
575
+ function detachDismiss(): void {
576
+ document.removeEventListener('pointerdown', handleDocumentPointerDown, true);
577
+ }
578
+
579
+ // 关闭时不挂监听:不可见的下拉不需要跟踪外部点击。滚动跟随由 useFloating 承担。
580
+ watch(
581
+ isOpen,
582
+ (open) => {
583
+ if (!isBrowser) return;
584
+
585
+ detachDismiss();
586
+
587
+ if (open) attachDismiss();
588
+ },
589
+ { immediate: true }
590
+ );
591
+
592
+ watch(
593
+ () => floating.referenceRef.value,
594
+ (trigger) => {
595
+ resize.disconnect();
596
+
597
+ if (!isBrowser) return;
598
+
599
+ measureTrigger();
600
+
601
+ resize.observe(trigger);
602
+ },
603
+ { flush: 'post' }
604
+ );
605
+
606
+ watch(highlightedValue, () => scrollHighlightedIntoView(), { flush: 'post' });
607
+
608
+ // 选项被卸载或禁用后,高亮不能停在一个不存在/不可选的项上。
609
+ // 懒渲染下打开瞬间注册表还是空的(内容尚未挂载),等选项登记后再落高亮。
610
+ watch(optionList, (list) => {
611
+ const current = highlightedValue.value;
612
+
613
+ if (current === null) {
614
+ if (isOpen.value && list.length > 0) {
615
+ highlightedValue.value = resolveOpenHighlight({
616
+ options: list,
617
+ selectedValue: value.value,
618
+ edge: 'first',
619
+ });
620
+ }
621
+
622
+ return;
623
+ }
624
+
625
+ const option = list.find((entry) => entry.value === current);
626
+
627
+ if (!option || option.disabled) highlightedValue.value = null;
628
+ });
629
+
630
+ const initialValue = value.value;
631
+
632
+ useFormResetListener(
633
+ floating.referenceRef,
634
+ () => setValue(initialValue),
635
+ () => toValue(options.form)
636
+ );
637
+
638
+ /**
639
+ * 把选中值写进隐藏原生 select 并通知表单。
640
+ *
641
+ * 与 Checkbox / Switch 的 BubbleInput 同一套理由:组件状态是另一套真源,不接这条
642
+ * 路径 FormData、`form.addEventListener('change')` 与依赖 change 的表单库都看不到
643
+ * 变化。初次挂载只写值不派发,避免页面刚出现就冒出一批事件。
644
+ */
645
+ function syncNativeSelect(notify: boolean): void {
646
+ const select = nativeSelectElement.value;
647
+
648
+ if (!select) return;
649
+
650
+ writeNativeSelectValue(select, value.value);
651
+
652
+ if (notify) select.dispatchEvent(new Event('change', { bubbles: true }));
653
+ }
654
+
655
+ watch(nativeSelectElement, (select) => {
656
+ if (!select) return;
657
+
658
+ syncNativeSelect(false);
659
+ });
660
+
661
+ watch(value, () => syncNativeSelect(true));
662
+
663
+ // 选项是异步渲染的:注册表变化后当前值可能才第一次有对应的 option,需要补写一次。
664
+ watch(optionList, () => syncNativeSelect(false));
665
+
666
+ onScopeDispose(() => {
667
+ detachDismiss();
668
+ resize.disconnect();
669
+ });
670
+
671
+ return {
672
+ value,
673
+ isOpen,
674
+ isDisabled,
675
+ highlightedValue: computed(() => highlightedValue.value),
676
+ selectedText,
677
+ hasValue,
678
+ options: optionList,
679
+ nativeOptions: cachedOptions,
680
+ triggerId,
681
+ contentId,
682
+ floating,
683
+ contentStyle,
684
+ setValue,
685
+ open,
686
+ close,
687
+ toggle,
688
+ getItemId,
689
+ registerItem: collection.add,
690
+ getTriggerProps,
691
+ getContentProps,
692
+ getViewportProps,
693
+ getItemProps,
694
+ getGroupProps,
695
+ getLabelProps,
696
+ getSeparatorProps,
697
+ getValueProps,
698
+ getIconProps,
699
+ isFormControl,
700
+ getNativeSelectProps,
701
+ setTriggerElement,
702
+ setContentElement,
703
+ setViewportElement,
704
+ setNativeSelectElement,
705
+ onTriggerClick,
706
+ onTriggerKeydown,
707
+ onTriggerBlur,
708
+ onContentPointerDown,
709
+ onContentPointerLeave,
710
+ onItemPointerMove,
711
+ onItemClick,
712
+ };
713
+ }