@luxalgo/vela-ui 0.3.0 → 0.4.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 (167) hide show
  1. package/CHANGELOG.md +153 -132
  2. package/LICENSE +201 -201
  3. package/NOTICE +28 -28
  4. package/README.md +86 -86
  5. package/cli/engine.mjs +282 -282
  6. package/cli/index.mjs +154 -154
  7. package/dist/callout-bubble.js +2 -2
  8. package/dist/checkbox.js +2 -2
  9. package/dist/{chunk-KKS6NEGI.js → chunk-BWSOMG3G.js} +1 -1
  10. package/dist/chunk-GUIYFQ27.js +30 -0
  11. package/dist/{chunk-B2EZB5ZG.js → chunk-KUWTI2PE.js} +2 -2
  12. package/dist/{chunk-WWHNUKSZ.js → chunk-QGWAN3EP.js} +2 -2
  13. package/dist/{chunk-TBXUF5YX.js → chunk-RH53NQGE.js} +18 -4
  14. package/dist/{chunk-IOOYDSSK.js → chunk-SKFAYTDK.js} +1 -1
  15. package/dist/{chunk-OQXFQMZM.js → chunk-TGJNHUYV.js} +2 -2
  16. package/dist/{chunk-UEO6W37Z.js → chunk-VC7SVSDK.js} +1 -1
  17. package/dist/{chunk-OJ2SEMN6.js → chunk-YT2BSP7O.js} +1 -1
  18. package/dist/collapsible.js +1 -1
  19. package/dist/color-picker.js +4 -4
  20. package/dist/context-menu.js +3 -3
  21. package/dist/dialog.js +3 -3
  22. package/dist/donut.d.ts +1 -1
  23. package/dist/drawer.js +1 -1
  24. package/dist/dropdown-menu.js +3 -3
  25. package/dist/field.js +8 -8
  26. package/dist/{stat.d.ts → figure.d.ts} +9 -9
  27. package/dist/figure.js +41 -0
  28. package/dist/glyph-select.js +3 -3
  29. package/dist/index.d.ts +2 -2
  30. package/dist/index.js +1 -1
  31. package/dist/manifest.json +74 -74
  32. package/dist/number-input.js +2 -2
  33. package/dist/popover.js +2 -2
  34. package/dist/select.d.ts +1 -1
  35. package/dist/select.js +4 -4
  36. package/dist/slider.js +1 -1
  37. package/dist/sort-button.js +1 -1
  38. package/dist/switch.js +1 -1
  39. package/dist/tabs.js +1 -1
  40. package/dist/{theme-Ct-q58xz.d.ts → theme-TefB8vtl.d.ts} +2 -2
  41. package/dist/theme.d.ts +2 -2
  42. package/dist/theme.js +1 -1
  43. package/dist/theme.schema.json +30 -30
  44. package/dist/toast.d.ts +2 -2
  45. package/dist/toast.js +1 -1
  46. package/dist/toggle-group.js +1 -1
  47. package/dist/tooltip.js +1 -1
  48. package/dist/zag.d.ts +11 -2
  49. package/dist/zag.js +1 -1
  50. package/docs/theming.md +217 -217
  51. package/docs/what-to-change.md +20 -20
  52. package/docs/writing-a-component.md +250 -250
  53. package/llms.txt +3 -3
  54. package/package.json +90 -90
  55. package/registry/badge.ts +119 -119
  56. package/registry/bar-chart.ts +215 -215
  57. package/registry/button.ts +387 -387
  58. package/registry/callout-bubble.ts +347 -347
  59. package/registry/card.ts +379 -379
  60. package/registry/checkbox.ts +234 -234
  61. package/registry/collapsible.ts +271 -271
  62. package/registry/color-picker.ts +582 -582
  63. package/registry/context-menu.ts +208 -208
  64. package/registry/data-table.ts +215 -215
  65. package/registry/date-picker.ts +483 -483
  66. package/registry/dialog.ts +551 -551
  67. package/registry/donut.ts +145 -145
  68. package/registry/drawer.ts +636 -636
  69. package/registry/dropdown-menu.ts +762 -762
  70. package/registry/empty.ts +91 -91
  71. package/registry/field.ts +584 -584
  72. package/registry/{stat.ts → figure.ts} +96 -96
  73. package/registry/glyph-select.ts +268 -268
  74. package/registry/hover-card.ts +222 -222
  75. package/registry/input-group.ts +229 -229
  76. package/registry/input.ts +181 -181
  77. package/registry/item.ts +376 -376
  78. package/registry/kbd.ts +64 -64
  79. package/registry/line-chart.ts +218 -218
  80. package/registry/month-grid.ts +328 -328
  81. package/registry/number-input.ts +443 -443
  82. package/registry/popover.ts +368 -368
  83. package/registry/scatter-chart.ts +221 -221
  84. package/registry/select.ts +620 -620
  85. package/registry/slider.ts +259 -259
  86. package/registry/sort-button.ts +189 -189
  87. package/registry/sparkline.ts +114 -114
  88. package/registry/switch.ts +205 -205
  89. package/registry/tabs.ts +426 -426
  90. package/registry/text-area.ts +186 -186
  91. package/registry/toast.ts +965 -965
  92. package/registry/toggle-group.ts +295 -295
  93. package/registry/tooltip.ts +156 -156
  94. package/registry/treemap.ts +847 -847
  95. package/skills/theming-vela-ui/SKILL.md +137 -137
  96. package/skills/using-vela-ui-components/SKILL.md +139 -139
  97. package/skills/writing-vela-ui-components/SKILL.md +163 -163
  98. package/src/components/badge.ts +119 -119
  99. package/src/components/bar-chart.ts +215 -215
  100. package/src/components/button.ts +387 -387
  101. package/src/components/callout-bubble.ts +347 -347
  102. package/src/components/card.ts +379 -379
  103. package/src/components/checkbox.ts +234 -234
  104. package/src/components/collapsible.ts +271 -271
  105. package/src/components/color-picker.ts +582 -582
  106. package/src/components/context-menu.ts +208 -208
  107. package/src/components/data-table.ts +215 -215
  108. package/src/components/date-picker.ts +483 -483
  109. package/src/components/dialog.ts +551 -551
  110. package/src/components/donut.ts +145 -145
  111. package/src/components/drawer.ts +636 -636
  112. package/src/components/dropdown-menu.ts +762 -762
  113. package/src/components/empty.ts +91 -91
  114. package/src/components/field.ts +584 -584
  115. package/src/components/{stat.ts → figure.ts} +96 -96
  116. package/src/components/glyph-select.ts +268 -268
  117. package/src/components/hover-card.ts +222 -222
  118. package/src/components/input-group.ts +229 -229
  119. package/src/components/input.ts +181 -181
  120. package/src/components/item.ts +376 -376
  121. package/src/components/kbd.ts +64 -64
  122. package/src/components/line-chart.ts +218 -218
  123. package/src/components/month-grid.ts +328 -328
  124. package/src/components/number-input.ts +443 -443
  125. package/src/components/popover.ts +368 -368
  126. package/src/components/scatter-chart.ts +221 -221
  127. package/src/components/select.ts +620 -620
  128. package/src/components/slider.ts +259 -259
  129. package/src/components/sort-button.ts +189 -189
  130. package/src/components/sparkline.ts +114 -114
  131. package/src/components/switch.ts +205 -205
  132. package/src/components/tabs.ts +426 -426
  133. package/src/components/text-area.ts +186 -186
  134. package/src/components/toast.ts +965 -965
  135. package/src/components/toggle-group.ts +295 -295
  136. package/src/components/tooltip.ts +156 -156
  137. package/src/components/treemap.ts +847 -847
  138. package/src/index.ts +24 -24
  139. package/src/lib/calendar.ts +117 -117
  140. package/src/lib/chart.ts +72 -72
  141. package/src/lib/color.ts +89 -89
  142. package/src/lib/component-index.ts +163 -163
  143. package/src/lib/css.ts +48 -48
  144. package/src/lib/define.ts +45 -45
  145. package/src/lib/dispose.ts +36 -36
  146. package/src/lib/h.ts +55 -55
  147. package/src/lib/headless.ts +16 -16
  148. package/src/lib/i18n.ts +30 -30
  149. package/src/lib/icons.ts +244 -244
  150. package/src/lib/kit-text.ts +26 -26
  151. package/src/lib/page.ts +24 -24
  152. package/src/lib/palette.ts +81 -81
  153. package/src/lib/placement.ts +188 -188
  154. package/src/lib/scope.ts +135 -135
  155. package/src/lib/styles.ts +53 -53
  156. package/src/lib/surface-events.ts +31 -31
  157. package/src/lib/surface-exit.ts +87 -87
  158. package/src/lib/t.ts +68 -68
  159. package/src/lib/theme.ts +684 -670
  160. package/src/lib/tokens.ts +110 -110
  161. package/src/lib/variants.ts +32 -32
  162. package/src/lib/zag.ts +61 -46
  163. package/stylelint/index.mjs +60 -60
  164. package/stylelint/lint.mjs +81 -81
  165. package/stylelint/plugin.mjs +115 -115
  166. package/dist/chunk-P4MTEMT7.js +0 -23
  167. package/dist/stat.js +0 -41
@@ -1,620 +1,620 @@
1
- // Select: a trigger button and a themed option list on a popover, with an overlay scrollbar
2
- // for long lists. `md` is the shared 100px kit column and ellipsizes the trigger; `sm` is a
3
- // compact toolbar select that hugs its widest option. The open list shows full labels.
4
- import type { ChartTheme } from '../lib/tokens';
5
- import { iconEl } from '../lib/icons';
6
- import { css, defineStyles } from '../lib/css';
7
- import { defineComponent } from '../lib/define';
8
- import { ownTeardown } from '../lib/dispose';
9
- import { addSlot, h } from '../lib/h';
10
- import { t } from '../lib/t';
11
- import { variants } from '../lib/variants';
12
- import { nextUid, normalizeProps, runMachine, spreadProps } from '../lib/zag';
13
- import * as zagListbox from '@zag-js/listbox';
14
- import { Popover, closeOpenPopovers, openPopoverTrigger, type PlacementProps, type PopoverBoundary, type PopoverOptions } from './popover';
15
-
16
- export type SelectSize = 'sm' | 'md';
17
-
18
- export interface SelectOption {
19
- value: string;
20
- label: string;
21
- }
22
-
23
- export interface SelectControllerOptions {
24
- options: readonly SelectOption[];
25
- value?: string;
26
- /** The value it starts with when `value` is not given. */
27
- defaultValue?: string;
28
- /** Shown while no option is picked: the value stays `''` until the user picks one. Without
29
- * it, the first option is picked to start with. */
30
- placeholder?: string;
31
- size?: SelectSize;
32
- /** Stretch the trigger to its parent. Off: the shared 100px kit column (ellipsis). */
33
- fill?: boolean;
34
- disabled?: boolean;
35
- /** Called when the user picks an option. */
36
- onValueChange?: (value: string, label: string) => void;
37
- /** @deprecated Use `onValueChange`. */
38
- onChange?: (value: string, label: string) => void;
39
- }
40
-
41
- export interface SelectController {
42
- options: readonly SelectOption[];
43
- value: string;
44
- size: SelectSize;
45
- fill: boolean;
46
- disabled: boolean;
47
- setValue(v: string): void;
48
- labelOf(value: string): string;
49
- pick(value: string): { value: string; label: string };
50
- }
51
-
52
- /** The select's options and current value, without DOM. */
53
- export function selectController(opts: SelectControllerOptions): SelectController {
54
- const options = opts.options;
55
- let value = opts.value ?? opts.defaultValue ?? (opts.placeholder !== undefined ? '' : (options[0]?.value ?? ''));
56
- const size = opts.size ?? 'md';
57
- return {
58
- options,
59
- get value() {
60
- return value;
61
- },
62
- size,
63
- fill: opts.fill ?? size !== 'sm',
64
- disabled: opts.disabled ?? false,
65
- setValue(v: string) {
66
- value = v;
67
- },
68
- labelOf(v: string) {
69
- return options.find((o) => o.value === v)?.label ?? v;
70
- },
71
- pick(v: string) {
72
- value = v;
73
- const label = options.find((o) => o.value === v)?.label ?? v;
74
- opts.onValueChange?.(v, label);
75
- opts.onChange?.(v, label);
76
- return { value: v, label };
77
- },
78
- };
79
- }
80
-
81
- export const selectDef = defineComponent({
82
- name: 'select',
83
- parts: ['root', 'trigger', 'value', 'icon', 'sizer', 'native', 'content', 'viewport', 'item', 'rail', 'thumb'],
84
- settings: { radius: t.radius.md, 'content-radius': t.radius.md, 'thumb-radius': '2px', 'focus-ring': `0 0 0 3px ${t.focus.soft}` },
85
- });
86
-
87
- export const selectVariants = variants({ size: ['md', 'sm'] });
88
-
89
- /** Where the list opens and how (shadcn's placement props, defaults below and start-aligned,
90
- * 4px away, as wide as the trigger at least). */
91
- export interface SelectListPopoverOpts extends PlacementProps {
92
- theme?: ChartTheme;
93
- matchWidth?: boolean;
94
- /** @deprecated Use `collisionBoundary`. */
95
- boundary?: PopoverBoundary;
96
- boundaryInset?: number;
97
- /** @deprecated Use `sideOffset`. */
98
- gap?: number;
99
- host?: HTMLElement;
100
- position?: PopoverOptions['position'];
101
- zIndex?: string | number;
102
- size?: SelectSize;
103
- /** Move the focus into the open list, for the arrow keys and typeahead (and back to the
104
- * trigger when it closes). Off by default: a trigger the user types in keeps the focus. */
105
- focusList?: boolean;
106
- onClose?: () => void;
107
- }
108
-
109
- export interface SelectOptions extends SelectControllerOptions, PlacementProps {
110
- id?: string;
111
- /** Submitted with its form under this name: a hidden native select carries the value. */
112
- name?: string;
113
- /** A form does not submit while no option is picked (with `placeholder`). */
114
- required?: boolean;
115
- theme?: ChartTheme;
116
- /** The open list's other options (its host, layer, width). Its placement props are the
117
- * select's own; set here, they give way to those. */
118
- list?: SelectListPopoverOpts;
119
- }
120
-
121
- export type SelectProps = SelectOptions;
122
-
123
- export const SELECT_STYLE_ID = 'vela-ui-select-3';
124
-
125
- export const SELECT_CSS = css`
126
- @layer vela.ui {
127
- [data-slot='select-trigger'] {
128
- display: flex;
129
- align-items: center;
130
- width: 100%;
131
- min-width: 0;
132
- box-sizing: border-box;
133
- height: 34px;
134
- padding-block: 0;
135
- padding-inline: 8px 26px;
136
- background: transparent;
137
- border: 1px solid ${t.border.strong};
138
- border-radius: ${selectDef.vars.radius};
139
- color: ${t.fg.bright};
140
- font-size: 14px;
141
- font-family: inherit;
142
- cursor: pointer;
143
- text-align: start;
144
- outline: 2px solid transparent;
145
- transition:
146
- border-color ${t.dur.fast} ease,
147
- box-shadow ${t.dur.fast} ease;
148
-
149
- &:hover {
150
- border-color: ${t.fg.muted};
151
- }
152
- &:focus {
153
- border-color: ${t.focus};
154
- box-shadow: ${selectDef.vars['focus-ring']};
155
- }
156
- }
157
- [data-slot='select-value'] {
158
- flex: 1;
159
- min-width: 0;
160
- overflow: hidden;
161
- text-overflow: ellipsis;
162
- white-space: nowrap;
163
- }
164
- [data-slot='select-icon'] {
165
- position: absolute;
166
- inset-inline-end: 8px;
167
- top: 50%;
168
- transform: translateY(-50%);
169
- pointer-events: none;
170
- display: flex;
171
- opacity: 0.55;
172
- line-height: 0;
173
- color: inherit;
174
-
175
- & > span,
176
- & svg {
177
- width: 12px;
178
- height: 12px;
179
- display: block;
180
- }
181
- }
182
- [data-slot='select-sizer'] {
183
- visibility: hidden;
184
- height: 0;
185
- overflow: hidden;
186
- font-size: 13px;
187
-
188
- & span {
189
- display: block;
190
- height: 0;
191
- white-space: nowrap;
192
- padding-block: 0;
193
- padding-inline: 8px 26px;
194
- border-inline: 1px solid transparent;
195
- }
196
- }
197
- [data-slot='select-viewport'] {
198
- width: max-content;
199
- min-width: 100%;
200
- max-height: none;
201
- overflow: hidden;
202
- }
203
- [data-slot='select-rail'] {
204
- position: relative;
205
- flex: none;
206
- width: 3px;
207
- margin-block: 2px;
208
- margin-inline: 0 1px;
209
- pointer-events: none;
210
- }
211
- [data-slot='select-thumb'] {
212
- width: 3px;
213
- border-radius: ${selectDef.vars['thumb-radius']};
214
- background: ${t.scroll};
215
- }
216
- [data-slot='select-item'] {
217
- display: block;
218
- width: auto;
219
- min-width: 100%;
220
- white-space: nowrap;
221
- text-align: start;
222
- padding: 7px 10px;
223
- border: none;
224
- border-radius: ${t.radius.sm};
225
- background: transparent;
226
- color: inherit;
227
- cursor: pointer;
228
- font: inherit;
229
- font-weight: 400;
230
-
231
- &:hover,
232
- &[data-highlighted] {
233
- background: ${t.hover};
234
- }
235
- &[data-checked] {
236
- background: ${t.hover.strong};
237
- color: ${t.fg.bright};
238
- }
239
- &[data-checked]:hover,
240
- &[data-checked][data-highlighted] {
241
- background: ${t.hover.strong};
242
- }
243
- }
244
- /* The highlighted option shows where the keyboard is; the list itself draws no ring. */
245
- [data-slot='select-viewport']:focus {
246
- outline: 2px solid transparent;
247
- }
248
- [data-slot='select-value'][data-placeholder] {
249
- color: ${t.fg.muted};
250
- }
251
- /* Seen by forms and their validation, never by the user. */
252
- [data-slot='select-native'] {
253
- position: absolute;
254
- width: 1px;
255
- height: 1px;
256
- margin: -1px;
257
- padding: 0;
258
- border: 0;
259
- overflow: hidden;
260
- clip-path: inset(50%);
261
- white-space: nowrap;
262
- pointer-events: none;
263
- }
264
- [data-slot='select'] {
265
- position: relative;
266
- min-width: 0;
267
-
268
- &:where(:not([hidden])) {
269
- display: inline-block;
270
- }
271
- &[data-fill] {
272
- width: 100%;
273
- }
274
- /* The closed trigger matches NumberInput and TextField (100px); long labels
275
- ellipsize, and the open list still sizes to the longest item. */
276
- &:not([data-fill]) {
277
- width: 100px;
278
- flex: none;
279
- justify-self: start;
280
- }
281
- &[data-size='sm'] [data-slot='select-trigger'] {
282
- height: 28px;
283
- background: ${t.surface.elev};
284
- border-radius: ${t.radius.sm};
285
- color: ${t.fg};
286
- font-size: 13px;
287
- box-shadow: none;
288
- }
289
- &[data-size='sm'] [data-slot='select-trigger']:focus {
290
- box-shadow: none;
291
- border-color: ${t.fg.muted};
292
- }
293
- /* Compact toolbar selects still hug the widest option (no 100px kit column). */
294
- &[data-size='sm']:not([data-fill]) {
295
- width: auto;
296
- max-width: 200px;
297
- }
298
- }
299
- [data-slot~='select-content'] {
300
- width: max-content;
301
- background: ${t.bg};
302
- color: ${t.fg};
303
- border: none;
304
- border-radius: ${selectDef.vars['content-radius']};
305
- box-shadow: ${t.shadow};
306
- font: 14px ${t.font};
307
- padding: 4px;
308
- overflow: hidden;
309
-
310
- &[data-size='sm'] {
311
- font-size: 13px;
312
- background: ${t.surface.overlay};
313
- }
314
- &[data-scroll] {
315
- display: flex;
316
- align-items: stretch;
317
- gap: 2px;
318
- }
319
- &[data-scroll] [data-slot='select-viewport'] {
320
- flex: 1 1 auto;
321
- min-width: min-content;
322
- max-height: 240px;
323
- overflow-y: auto;
324
- scrollbar-width: none;
325
- }
326
- &[data-scroll] [data-slot='select-viewport']::-webkit-scrollbar {
327
- display: none;
328
- width: 0;
329
- height: 0;
330
- }
331
- }
332
- }
333
- `;
334
-
335
- const injectStyles = defineStyles(SELECT_STYLE_ID, SELECT_CSS);
336
-
337
- function syncThumb(list: HTMLElement, thumb: HTMLElement): void {
338
- const view = list.clientHeight;
339
- const total = list.scrollHeight;
340
- if (total <= view) {
341
- thumb.style.height = '0';
342
- return;
343
- }
344
- const thumbH = Math.max(20, (view / total) * view);
345
- const top = (list.scrollTop / (total - view)) * (view - thumbH);
346
- thumb.style.height = `${Math.round(thumbH)}px`;
347
- thumb.style.transform = `translateY(${Math.round(top)}px`;
348
- }
349
-
350
- /** Fill `menu` with the options, a listbox (Zag's listbox machine: the arrow keys, Home/End,
351
- * Enter and typeahead while it has the focus). A click picks at once; one pick per fill.
352
- * Call {@link decorateSelectScroll} after the menu is on screen; call the returned function
353
- * when the menu goes away. */
354
- export function fillSelectList(menu: HTMLElement, options: readonly SelectOption[], current: string, onPick: (value: string, label: string) => void): () => void {
355
- injectStyles(menu.ownerDocument);
356
- addSlot(menu, selectDef.slot('content'));
357
- let picked = false;
358
- const choose = (value: string): void => {
359
- const option = options.find((o) => o.value === value);
360
- if (picked || !option) return;
361
- picked = true;
362
- onPick(option.value, option.label);
363
- };
364
- const items = options.map((p) =>
365
- h('button', {
366
- className: 'vela-select-item',
367
- slot: selectDef.slot('item'),
368
- attrs: { type: 'button', tabindex: -1 },
369
- data: { checked: p.value === current ? '1' : null },
370
- text: p.label,
371
- on: {
372
- click: (e) => {
373
- e.stopPropagation();
374
- choose(p.value);
375
- },
376
- },
377
- }),
378
- );
379
- const viewport = h('div', { className: 'vela-select-items', slot: selectDef.slot('viewport') }, items);
380
- menu.replaceChildren(viewport);
381
- const mid = nextUid('vela-select-list');
382
- const known = options.some((o) => o.value === current);
383
- const machine = runMachine(
384
- zagListbox.machine,
385
- {
386
- id: mid,
387
- collection: zagListbox.collection({ items: options, itemToValue: (o) => o.value, itemToString: (o) => o.label }),
388
- selectionMode: 'single',
389
- defaultValue: known ? [current] : [],
390
- defaultHighlightedValue: known ? current : null,
391
- // The keyboard's pick (Enter) arrives here, a beat after the key.
392
- onSelect: ({ value }) => choose(value),
393
- },
394
- (service) => {
395
- const api = zagListbox.connect(service, normalizeProps);
396
- spreadProps(viewport, api.getContentProps(), mid);
397
- options.forEach((item, i) => spreadProps(items[i]!, api.getItemProps({ item, highlightOnHover: true }), mid));
398
- },
399
- );
400
- // After the machine's own handler: the picking key ends here, so it can't also press the
401
- // trigger the focus returns to.
402
- viewport.addEventListener('keydown', (e) => {
403
- if (e.key === 'Enter' || e.key === ' ') e.preventDefault();
404
- });
405
- return () => machine.stop();
406
- }
407
-
408
- /** Overlay scrollbar + scroll-into-view — needs a laid-out list (after the popover is shown). */
409
- export function decorateSelectScroll(menu: HTMLElement): void {
410
- const list = menu.querySelector<HTMLElement>(`[data-slot='${selectDef.slot('viewport')}']`);
411
- if (!list) return;
412
- if (list.scrollHeight > 240) {
413
- menu.classList.add('is-scroll');
414
- menu.dataset.scroll = '';
415
- const thumb = h('div', { className: 'vela-select-thumb', slot: selectDef.slot('thumb') });
416
- menu.appendChild(h('div', { className: 'vela-select-rail', slot: selectDef.slot('rail') }, thumb));
417
- list.addEventListener('scroll', () => syncThumb(list, thumb));
418
- syncThumb(list, thumb);
419
- }
420
- menu.querySelector<HTMLElement>(`[data-slot='${selectDef.slot('item')}'][data-checked]`)?.scrollIntoView({ block: 'nearest' });
421
- list.dispatchEvent(new Event('scroll'));
422
- }
423
-
424
- /** Open (or re-click close) a themed option list under `trigger`. */
425
- export function toggleSelectList(
426
- trigger: HTMLElement,
427
- options: readonly SelectOption[],
428
- current: string,
429
- onPick: (value: string, label: string) => void,
430
- opts: SelectListPopoverOpts = {},
431
- ): Popover | null {
432
- if (openPopoverTrigger() === trigger) {
433
- closeOpenPopovers();
434
- return null;
435
- }
436
- return openSelectList(trigger, options, current, onPick, opts);
437
- }
438
-
439
- export function openSelectList(
440
- trigger: HTMLElement,
441
- options: readonly SelectOption[],
442
- current: string,
443
- onPick: (value: string, label: string) => void,
444
- opts: SelectListPopoverOpts = {},
445
- ): Popover {
446
- injectStyles(trigger.ownerDocument);
447
- closeOpenPopovers();
448
- let dispose: (() => void) | null = null;
449
- const pop = new Popover({
450
- trigger,
451
- theme: opts.theme,
452
- matchWidth: opts.matchWidth ?? true,
453
- collisionBoundary: opts.collisionBoundary ?? opts.boundary,
454
- boundaryInset: opts.boundaryInset,
455
- side: opts.side,
456
- sideOffset: opts.sideOffset ?? opts.gap ?? 4,
457
- align: opts.align ?? 'start',
458
- alignOffset: opts.alignOffset,
459
- avoidCollisions: opts.avoidCollisions,
460
- collisionPadding: opts.collisionPadding,
461
- host: opts.host,
462
- position: opts.position,
463
- zIndex: opts.zIndex,
464
- className: 'vela-select-list',
465
- slot: selectDef.slot('content'),
466
- onClose: () => {
467
- dispose?.();
468
- dispose = null;
469
- const active = trigger.ownerDocument.activeElement;
470
- if (opts.focusList && (!active || active === trigger.ownerDocument.body || pop.el.contains(active))) trigger.focus({ preventScroll: true });
471
- opts.onClose?.();
472
- },
473
- content: (el) => {
474
- if (opts.size) el.dataset.size = opts.size;
475
- dispose = fillSelectList(el, options, current, (value, label) => {
476
- pop.hide();
477
- onPick(value, label);
478
- });
479
- },
480
- });
481
- pop.show();
482
- decorateSelectScroll(pop.el);
483
- pop.reposition();
484
- if (opts.focusList) pop.el.querySelector<HTMLElement>(`[data-slot='${selectDef.slot('viewport')}']`)?.focus({ preventScroll: true });
485
- return pop;
486
- }
487
-
488
- export class Select {
489
- readonly el: HTMLElement;
490
- private readonly trigger: HTMLButtonElement;
491
- private readonly labelEl: HTMLElement;
492
- private readonly ctrl: SelectController;
493
- private readonly listOpts: SelectListPopoverOpts;
494
- private readonly placeholder: string | undefined;
495
- private readonly native: HTMLSelectElement | null;
496
- private readonly release: () => void;
497
- private list: Popover | null = null;
498
-
499
- constructor(opts: SelectOptions) {
500
- const doc = opts.list?.host?.ownerDocument ?? document;
501
- injectStyles(doc);
502
- this.ctrl = selectController(opts);
503
- const placed = Object.fromEntries(
504
- (['side', 'align', 'sideOffset', 'alignOffset', 'avoidCollisions', 'collisionPadding', 'collisionBoundary'] as const).filter((k) => opts[k] !== undefined).map((k) => [k, opts[k]]),
505
- ) as PlacementProps;
506
- this.listOpts = { ...opts.list, ...placed, theme: opts.theme ?? opts.list?.theme, size: this.ctrl.size };
507
-
508
- this.placeholder = opts.placeholder;
509
- const label = h('span', { className: 'vela-select-label', slot: selectDef.slot('value') });
510
- const btn = h(
511
- 'button',
512
- {
513
- className: 'vela-select-trigger',
514
- slot: selectDef.slot('trigger'),
515
- attrs: { type: 'button', id: opts.id, 'aria-haspopup': 'listbox', 'aria-expanded': 'false', 'aria-required': opts.required ? 'true' : undefined },
516
- },
517
- label,
518
- h('span', { className: 'vela-select-chevron', slot: selectDef.slot('icon') }, iconEl('chevron-down', doc)),
519
- );
520
- btn.disabled = this.ctrl.disabled;
521
- // Compact toolbar selects hug the widest option. md uses a fixed 100px
522
- // column and ellipsizes the trigger; the open list still shows full labels.
523
- const sizer =
524
- this.ctrl.size === 'sm'
525
- ? h(
526
- 'div',
527
- { className: 'vela-select-sizer', slot: selectDef.slot('sizer'), attrs: { 'aria-hidden': 'true' } },
528
- this.ctrl.options.map((o) => h('span', { text: o.label })),
529
- )
530
- : null;
531
- this.native =
532
- opts.name !== undefined
533
- ? h(
534
- 'select',
535
- { slot: selectDef.slot('native'), attrs: { name: opts.name, 'aria-hidden': 'true', tabindex: -1 } },
536
- opts.placeholder !== undefined ? h('option', { attrs: { value: '' } }) : null,
537
- this.ctrl.options.map((o) => h('option', { attrs: { value: o.value }, text: o.label })),
538
- )
539
- : null;
540
- if (this.native) {
541
- this.native.required = opts.required === true;
542
- this.native.disabled = this.ctrl.disabled;
543
- }
544
- this.el = h('div', { className: 'vela-select', slot: selectDef.slot('root'), attrs: selectVariants({ size: this.ctrl.size }), data: { fill: this.ctrl.fill } }, btn, sizer, this.native);
545
-
546
- // Suppress the default mousedown focus: when this press outside-dismisses an open
547
- // popover, Chrome's focus action can scroll the dialog body under the pointer.
548
- btn.addEventListener('pointerdown', (e) => {
549
- e.preventDefault();
550
- btn.focus({ preventScroll: true });
551
- });
552
- btn.addEventListener('click', (e) => {
553
- e.stopPropagation();
554
- this.toggle();
555
- });
556
- btn.addEventListener('keydown', (e) => {
557
- if ((e.key === 'ArrowDown' || e.key === 'ArrowUp') && !this.list) {
558
- e.preventDefault();
559
- this.toggle();
560
- }
561
- });
562
-
563
- this.trigger = btn;
564
- this.labelEl = label;
565
- this.paint();
566
- this.release = ownTeardown(this.el, () => {
567
- this.list?.hide();
568
- this.list = null;
569
- });
570
- }
571
-
572
- get value(): string {
573
- return this.ctrl.value;
574
- }
575
-
576
- setValue(v: string): void {
577
- this.ctrl.setValue(v);
578
- this.paint();
579
- }
580
-
581
- /** The trigger shows the picked option's label, or the placeholder while none is picked. */
582
- private paint(): void {
583
- const v = this.ctrl.value;
584
- const empty = this.placeholder !== undefined && !this.ctrl.options.some((o) => o.value === v);
585
- this.labelEl.textContent = empty ? (this.placeholder ?? '') : this.ctrl.labelOf(v);
586
- this.labelEl.toggleAttribute('data-placeholder', empty);
587
- if (this.native) this.native.value = empty ? '' : v;
588
- }
589
-
590
- toggle(): void {
591
- this.list = toggleSelectList(
592
- this.trigger,
593
- this.ctrl.options,
594
- this.ctrl.value,
595
- (value) => {
596
- this.ctrl.pick(value);
597
- this.paint();
598
- this.list = null;
599
- },
600
- {
601
- ...this.listOpts,
602
- focusList: true,
603
- onClose: () => {
604
- this.list = null;
605
- this.trigger.setAttribute('aria-expanded', 'false');
606
- this.listOpts.onClose?.();
607
- },
608
- },
609
- );
610
- this.trigger.setAttribute('aria-expanded', String(this.list !== null));
611
- }
612
-
613
- destroy(): void {
614
- this.release();
615
- }
616
- }
617
-
618
- export function createSelect(props: SelectProps): Select {
619
- return new Select(props);
620
- }
1
+ // Select: a trigger button and a themed option list on a popover, with an overlay scrollbar
2
+ // for long lists. `md` is the shared 100px kit column and ellipsizes the trigger; `sm` is a
3
+ // compact toolbar select that hugs its widest option. The open list shows full labels.
4
+ import type { ChartTheme } from '../lib/tokens';
5
+ import { iconEl } from '../lib/icons';
6
+ import { css, defineStyles } from '../lib/css';
7
+ import { defineComponent } from '../lib/define';
8
+ import { ownTeardown } from '../lib/dispose';
9
+ import { addSlot, h } from '../lib/h';
10
+ import { t } from '../lib/t';
11
+ import { variants } from '../lib/variants';
12
+ import { nextUid, normalizeProps, runMachine, spreadProps } from '../lib/zag';
13
+ import * as zagListbox from '@zag-js/listbox';
14
+ import { Popover, closeOpenPopovers, openPopoverTrigger, type PlacementProps, type PopoverBoundary, type PopoverOptions } from './popover';
15
+
16
+ export type SelectSize = 'sm' | 'md';
17
+
18
+ export interface SelectOption {
19
+ value: string;
20
+ label: string;
21
+ }
22
+
23
+ export interface SelectControllerOptions {
24
+ options: readonly SelectOption[];
25
+ value?: string;
26
+ /** The value it starts with when `value` is not given. */
27
+ defaultValue?: string;
28
+ /** Shown while no option is picked: the value stays `''` until the user picks one. Without
29
+ * it, the first option is picked to start with. */
30
+ placeholder?: string;
31
+ size?: SelectSize;
32
+ /** Stretch the trigger to its parent. Off: the shared 100px kit column (ellipsis). */
33
+ fill?: boolean;
34
+ disabled?: boolean;
35
+ /** Called when the user picks an option. */
36
+ onValueChange?: (value: string, label: string) => void;
37
+ /** @deprecated Use `onValueChange`. */
38
+ onChange?: (value: string, label: string) => void;
39
+ }
40
+
41
+ export interface SelectController {
42
+ options: readonly SelectOption[];
43
+ value: string;
44
+ size: SelectSize;
45
+ fill: boolean;
46
+ disabled: boolean;
47
+ setValue(v: string): void;
48
+ labelOf(value: string): string;
49
+ pick(value: string): { value: string; label: string };
50
+ }
51
+
52
+ /** The select's options and current value, without DOM. */
53
+ export function selectController(opts: SelectControllerOptions): SelectController {
54
+ const options = opts.options;
55
+ let value = opts.value ?? opts.defaultValue ?? (opts.placeholder !== undefined ? '' : (options[0]?.value ?? ''));
56
+ const size = opts.size ?? 'md';
57
+ return {
58
+ options,
59
+ get value() {
60
+ return value;
61
+ },
62
+ size,
63
+ fill: opts.fill ?? size !== 'sm',
64
+ disabled: opts.disabled ?? false,
65
+ setValue(v: string) {
66
+ value = v;
67
+ },
68
+ labelOf(v: string) {
69
+ return options.find((o) => o.value === v)?.label ?? v;
70
+ },
71
+ pick(v: string) {
72
+ value = v;
73
+ const label = options.find((o) => o.value === v)?.label ?? v;
74
+ opts.onValueChange?.(v, label);
75
+ opts.onChange?.(v, label);
76
+ return { value: v, label };
77
+ },
78
+ };
79
+ }
80
+
81
+ export const selectDef = defineComponent({
82
+ name: 'select',
83
+ parts: ['root', 'trigger', 'value', 'icon', 'sizer', 'native', 'content', 'viewport', 'item', 'rail', 'thumb'],
84
+ settings: { radius: t.radius.md, 'content-radius': t.radius.md, 'thumb-radius': '2px', 'focus-ring': `0 0 0 3px ${t.focus.soft}` },
85
+ });
86
+
87
+ export const selectVariants = variants({ size: ['md', 'sm'] });
88
+
89
+ /** Where the list opens and how (shadcn's placement props, defaults below and start-aligned,
90
+ * 4px away, as wide as the trigger at least). */
91
+ export interface SelectListPopoverOpts extends PlacementProps {
92
+ theme?: ChartTheme;
93
+ matchWidth?: boolean;
94
+ /** @deprecated Use `collisionBoundary`. */
95
+ boundary?: PopoverBoundary;
96
+ boundaryInset?: number;
97
+ /** @deprecated Use `sideOffset`. */
98
+ gap?: number;
99
+ host?: HTMLElement;
100
+ position?: PopoverOptions['position'];
101
+ zIndex?: string | number;
102
+ size?: SelectSize;
103
+ /** Move the focus into the open list, for the arrow keys and typeahead (and back to the
104
+ * trigger when it closes). Off by default: a trigger the user types in keeps the focus. */
105
+ focusList?: boolean;
106
+ onClose?: () => void;
107
+ }
108
+
109
+ export interface SelectOptions extends SelectControllerOptions, PlacementProps {
110
+ id?: string;
111
+ /** Submitted with its form under this name: a hidden native select carries the value. */
112
+ name?: string;
113
+ /** A form does not submit while no option is picked (with `placeholder`). */
114
+ required?: boolean;
115
+ theme?: ChartTheme;
116
+ /** The open list's other options (its host, layer, width). Its placement props are the
117
+ * select's own; set here, they give way to those. */
118
+ list?: SelectListPopoverOpts;
119
+ }
120
+
121
+ export type SelectProps = SelectOptions;
122
+
123
+ export const SELECT_STYLE_ID = 'vela-ui-select-3';
124
+
125
+ export const SELECT_CSS = css`
126
+ @layer vela.ui {
127
+ [data-slot='select-trigger'] {
128
+ display: flex;
129
+ align-items: center;
130
+ width: 100%;
131
+ min-width: 0;
132
+ box-sizing: border-box;
133
+ height: 34px;
134
+ padding-block: 0;
135
+ padding-inline: 8px 26px;
136
+ background: transparent;
137
+ border: 1px solid ${t.border.strong};
138
+ border-radius: ${selectDef.vars.radius};
139
+ color: ${t.fg.bright};
140
+ font-size: 14px;
141
+ font-family: inherit;
142
+ cursor: pointer;
143
+ text-align: start;
144
+ outline: 2px solid transparent;
145
+ transition:
146
+ border-color ${t.dur.fast} ease,
147
+ box-shadow ${t.dur.fast} ease;
148
+
149
+ &:hover {
150
+ border-color: ${t.fg.muted};
151
+ }
152
+ &:focus {
153
+ border-color: ${t.focus};
154
+ box-shadow: ${selectDef.vars['focus-ring']};
155
+ }
156
+ }
157
+ [data-slot='select-value'] {
158
+ flex: 1;
159
+ min-width: 0;
160
+ overflow: hidden;
161
+ text-overflow: ellipsis;
162
+ white-space: nowrap;
163
+ }
164
+ [data-slot='select-icon'] {
165
+ position: absolute;
166
+ inset-inline-end: 8px;
167
+ top: 50%;
168
+ transform: translateY(-50%);
169
+ pointer-events: none;
170
+ display: flex;
171
+ opacity: 0.55;
172
+ line-height: 0;
173
+ color: inherit;
174
+
175
+ & > span,
176
+ & svg {
177
+ width: 12px;
178
+ height: 12px;
179
+ display: block;
180
+ }
181
+ }
182
+ [data-slot='select-sizer'] {
183
+ visibility: hidden;
184
+ height: 0;
185
+ overflow: hidden;
186
+ font-size: 13px;
187
+
188
+ & span {
189
+ display: block;
190
+ height: 0;
191
+ white-space: nowrap;
192
+ padding-block: 0;
193
+ padding-inline: 8px 26px;
194
+ border-inline: 1px solid transparent;
195
+ }
196
+ }
197
+ [data-slot='select-viewport'] {
198
+ width: max-content;
199
+ min-width: 100%;
200
+ max-height: none;
201
+ overflow: hidden;
202
+ }
203
+ [data-slot='select-rail'] {
204
+ position: relative;
205
+ flex: none;
206
+ width: 3px;
207
+ margin-block: 2px;
208
+ margin-inline: 0 1px;
209
+ pointer-events: none;
210
+ }
211
+ [data-slot='select-thumb'] {
212
+ width: 3px;
213
+ border-radius: ${selectDef.vars['thumb-radius']};
214
+ background: ${t.scroll};
215
+ }
216
+ [data-slot='select-item'] {
217
+ display: block;
218
+ width: auto;
219
+ min-width: 100%;
220
+ white-space: nowrap;
221
+ text-align: start;
222
+ padding: 7px 10px;
223
+ border: none;
224
+ border-radius: ${t.radius.sm};
225
+ background: transparent;
226
+ color: inherit;
227
+ cursor: pointer;
228
+ font: inherit;
229
+ font-weight: 400;
230
+
231
+ &:hover,
232
+ &[data-highlighted] {
233
+ background: ${t.hover};
234
+ }
235
+ &[data-checked] {
236
+ background: ${t.hover.strong};
237
+ color: ${t.fg.bright};
238
+ }
239
+ &[data-checked]:hover,
240
+ &[data-checked][data-highlighted] {
241
+ background: ${t.hover.strong};
242
+ }
243
+ }
244
+ /* The highlighted option shows where the keyboard is; the list itself draws no ring. */
245
+ [data-slot='select-viewport']:focus {
246
+ outline: 2px solid transparent;
247
+ }
248
+ [data-slot='select-value'][data-placeholder] {
249
+ color: ${t.fg.muted};
250
+ }
251
+ /* Seen by forms and their validation, never by the user. */
252
+ [data-slot='select-native'] {
253
+ position: absolute;
254
+ width: 1px;
255
+ height: 1px;
256
+ margin: -1px;
257
+ padding: 0;
258
+ border: 0;
259
+ overflow: hidden;
260
+ clip-path: inset(50%);
261
+ white-space: nowrap;
262
+ pointer-events: none;
263
+ }
264
+ [data-slot='select'] {
265
+ position: relative;
266
+ min-width: 0;
267
+
268
+ &:where(:not([hidden])) {
269
+ display: inline-block;
270
+ }
271
+ &[data-fill] {
272
+ width: 100%;
273
+ }
274
+ /* The closed trigger matches NumberInput and TextField (100px); long labels
275
+ ellipsize, and the open list still sizes to the longest item. */
276
+ &:not([data-fill]) {
277
+ width: 100px;
278
+ flex: none;
279
+ justify-self: start;
280
+ }
281
+ &[data-size='sm'] [data-slot='select-trigger'] {
282
+ height: 28px;
283
+ background: ${t.surface.elev};
284
+ border-radius: ${t.radius.sm};
285
+ color: ${t.fg};
286
+ font-size: 13px;
287
+ box-shadow: none;
288
+ }
289
+ &[data-size='sm'] [data-slot='select-trigger']:focus {
290
+ box-shadow: none;
291
+ border-color: ${t.fg.muted};
292
+ }
293
+ /* Compact toolbar selects still hug the widest option (no 100px kit column). */
294
+ &[data-size='sm']:not([data-fill]) {
295
+ width: auto;
296
+ max-width: 200px;
297
+ }
298
+ }
299
+ [data-slot~='select-content'] {
300
+ width: max-content;
301
+ background: ${t.bg};
302
+ color: ${t.fg};
303
+ border: none;
304
+ border-radius: ${selectDef.vars['content-radius']};
305
+ box-shadow: ${t.shadow};
306
+ font: 14px ${t.font};
307
+ padding: 4px;
308
+ overflow: hidden;
309
+
310
+ &[data-size='sm'] {
311
+ font-size: 13px;
312
+ background: ${t.surface.overlay};
313
+ }
314
+ &[data-scroll] {
315
+ display: flex;
316
+ align-items: stretch;
317
+ gap: 2px;
318
+ }
319
+ &[data-scroll] [data-slot='select-viewport'] {
320
+ flex: 1 1 auto;
321
+ min-width: min-content;
322
+ max-height: 240px;
323
+ overflow-y: auto;
324
+ scrollbar-width: none;
325
+ }
326
+ &[data-scroll] [data-slot='select-viewport']::-webkit-scrollbar {
327
+ display: none;
328
+ width: 0;
329
+ height: 0;
330
+ }
331
+ }
332
+ }
333
+ `;
334
+
335
+ const injectStyles = defineStyles(SELECT_STYLE_ID, SELECT_CSS);
336
+
337
+ function syncThumb(list: HTMLElement, thumb: HTMLElement): void {
338
+ const view = list.clientHeight;
339
+ const total = list.scrollHeight;
340
+ if (total <= view) {
341
+ thumb.style.height = '0';
342
+ return;
343
+ }
344
+ const thumbH = Math.max(20, (view / total) * view);
345
+ const top = (list.scrollTop / (total - view)) * (view - thumbH);
346
+ thumb.style.height = `${Math.round(thumbH)}px`;
347
+ thumb.style.transform = `translateY(${Math.round(top)}px`;
348
+ }
349
+
350
+ /** Fill `menu` with the options, a listbox (Zag's listbox machine: the arrow keys, Home/End,
351
+ * Enter and typeahead while it has the focus). A click picks at once; one pick per fill.
352
+ * Call {@link decorateSelectScroll} after the menu is on screen; call the returned function
353
+ * when the menu goes away. */
354
+ export function fillSelectList(menu: HTMLElement, options: readonly SelectOption[], current: string, onPick: (value: string, label: string) => void): () => void {
355
+ injectStyles(menu.ownerDocument);
356
+ addSlot(menu, selectDef.slot('content'));
357
+ let picked = false;
358
+ const choose = (value: string): void => {
359
+ const option = options.find((o) => o.value === value);
360
+ if (picked || !option) return;
361
+ picked = true;
362
+ onPick(option.value, option.label);
363
+ };
364
+ const items = options.map((p) =>
365
+ h('button', {
366
+ className: 'vela-select-item',
367
+ slot: selectDef.slot('item'),
368
+ attrs: { type: 'button', tabindex: -1 },
369
+ data: { checked: p.value === current ? '1' : null },
370
+ text: p.label,
371
+ on: {
372
+ click: (e) => {
373
+ e.stopPropagation();
374
+ choose(p.value);
375
+ },
376
+ },
377
+ }),
378
+ );
379
+ const viewport = h('div', { className: 'vela-select-items', slot: selectDef.slot('viewport') }, items);
380
+ menu.replaceChildren(viewport);
381
+ const mid = nextUid('vela-select-list');
382
+ const known = options.some((o) => o.value === current);
383
+ const machine = runMachine(
384
+ zagListbox.machine,
385
+ {
386
+ id: mid,
387
+ collection: zagListbox.collection({ items: options, itemToValue: (o) => o.value, itemToString: (o) => o.label }),
388
+ selectionMode: 'single',
389
+ defaultValue: known ? [current] : [],
390
+ defaultHighlightedValue: known ? current : null,
391
+ // The keyboard's pick (Enter) arrives here, a beat after the key.
392
+ onSelect: ({ value }) => choose(value),
393
+ },
394
+ (service) => {
395
+ const api = zagListbox.connect(service, normalizeProps);
396
+ spreadProps(viewport, api.getContentProps(), mid);
397
+ options.forEach((item, i) => spreadProps(items[i]!, api.getItemProps({ item, highlightOnHover: true }), mid));
398
+ },
399
+ );
400
+ // After the machine's own handler: the picking key ends here, so it can't also press the
401
+ // trigger the focus returns to.
402
+ viewport.addEventListener('keydown', (e) => {
403
+ if (e.key === 'Enter' || e.key === ' ') e.preventDefault();
404
+ });
405
+ return () => machine.stop();
406
+ }
407
+
408
+ /** Overlay scrollbar + scroll-into-view — needs a laid-out list (after the popover is shown). */
409
+ export function decorateSelectScroll(menu: HTMLElement): void {
410
+ const list = menu.querySelector<HTMLElement>(`[data-slot='${selectDef.slot('viewport')}']`);
411
+ if (!list) return;
412
+ if (list.scrollHeight > 240) {
413
+ menu.classList.add('is-scroll');
414
+ menu.dataset.scroll = '';
415
+ const thumb = h('div', { className: 'vela-select-thumb', slot: selectDef.slot('thumb') });
416
+ menu.appendChild(h('div', { className: 'vela-select-rail', slot: selectDef.slot('rail') }, thumb));
417
+ list.addEventListener('scroll', () => syncThumb(list, thumb));
418
+ syncThumb(list, thumb);
419
+ }
420
+ menu.querySelector<HTMLElement>(`[data-slot='${selectDef.slot('item')}'][data-checked]`)?.scrollIntoView({ block: 'nearest' });
421
+ list.dispatchEvent(new Event('scroll'));
422
+ }
423
+
424
+ /** Open (or re-click close) a themed option list under `trigger`. */
425
+ export function toggleSelectList(
426
+ trigger: HTMLElement,
427
+ options: readonly SelectOption[],
428
+ current: string,
429
+ onPick: (value: string, label: string) => void,
430
+ opts: SelectListPopoverOpts = {},
431
+ ): Popover | null {
432
+ if (openPopoverTrigger() === trigger) {
433
+ closeOpenPopovers();
434
+ return null;
435
+ }
436
+ return openSelectList(trigger, options, current, onPick, opts);
437
+ }
438
+
439
+ export function openSelectList(
440
+ trigger: HTMLElement,
441
+ options: readonly SelectOption[],
442
+ current: string,
443
+ onPick: (value: string, label: string) => void,
444
+ opts: SelectListPopoverOpts = {},
445
+ ): Popover {
446
+ injectStyles(trigger.ownerDocument);
447
+ closeOpenPopovers();
448
+ let dispose: (() => void) | null = null;
449
+ const pop = new Popover({
450
+ trigger,
451
+ theme: opts.theme,
452
+ matchWidth: opts.matchWidth ?? true,
453
+ collisionBoundary: opts.collisionBoundary ?? opts.boundary,
454
+ boundaryInset: opts.boundaryInset,
455
+ side: opts.side,
456
+ sideOffset: opts.sideOffset ?? opts.gap ?? 4,
457
+ align: opts.align ?? 'start',
458
+ alignOffset: opts.alignOffset,
459
+ avoidCollisions: opts.avoidCollisions,
460
+ collisionPadding: opts.collisionPadding,
461
+ host: opts.host,
462
+ position: opts.position,
463
+ zIndex: opts.zIndex,
464
+ className: 'vela-select-list',
465
+ slot: selectDef.slot('content'),
466
+ onClose: () => {
467
+ dispose?.();
468
+ dispose = null;
469
+ const active = trigger.ownerDocument.activeElement;
470
+ if (opts.focusList && (!active || active === trigger.ownerDocument.body || pop.el.contains(active))) trigger.focus({ preventScroll: true });
471
+ opts.onClose?.();
472
+ },
473
+ content: (el) => {
474
+ if (opts.size) el.dataset.size = opts.size;
475
+ dispose = fillSelectList(el, options, current, (value, label) => {
476
+ pop.hide();
477
+ onPick(value, label);
478
+ });
479
+ },
480
+ });
481
+ pop.show();
482
+ decorateSelectScroll(pop.el);
483
+ pop.reposition();
484
+ if (opts.focusList) pop.el.querySelector<HTMLElement>(`[data-slot='${selectDef.slot('viewport')}']`)?.focus({ preventScroll: true });
485
+ return pop;
486
+ }
487
+
488
+ export class Select {
489
+ readonly el: HTMLElement;
490
+ private readonly trigger: HTMLButtonElement;
491
+ private readonly labelEl: HTMLElement;
492
+ private readonly ctrl: SelectController;
493
+ private readonly listOpts: SelectListPopoverOpts;
494
+ private readonly placeholder: string | undefined;
495
+ private readonly native: HTMLSelectElement | null;
496
+ private readonly release: () => void;
497
+ private list: Popover | null = null;
498
+
499
+ constructor(opts: SelectOptions) {
500
+ const doc = opts.list?.host?.ownerDocument ?? document;
501
+ injectStyles(doc);
502
+ this.ctrl = selectController(opts);
503
+ const placed = Object.fromEntries(
504
+ (['side', 'align', 'sideOffset', 'alignOffset', 'avoidCollisions', 'collisionPadding', 'collisionBoundary'] as const).filter((k) => opts[k] !== undefined).map((k) => [k, opts[k]]),
505
+ ) as PlacementProps;
506
+ this.listOpts = { ...opts.list, ...placed, theme: opts.theme ?? opts.list?.theme, size: this.ctrl.size };
507
+
508
+ this.placeholder = opts.placeholder;
509
+ const label = h('span', { className: 'vela-select-label', slot: selectDef.slot('value') });
510
+ const btn = h(
511
+ 'button',
512
+ {
513
+ className: 'vela-select-trigger',
514
+ slot: selectDef.slot('trigger'),
515
+ attrs: { type: 'button', id: opts.id, 'aria-haspopup': 'listbox', 'aria-expanded': 'false', 'aria-required': opts.required ? 'true' : undefined },
516
+ },
517
+ label,
518
+ h('span', { className: 'vela-select-chevron', slot: selectDef.slot('icon') }, iconEl('chevron-down', doc)),
519
+ );
520
+ btn.disabled = this.ctrl.disabled;
521
+ // Compact toolbar selects hug the widest option. md uses a fixed 100px
522
+ // column and ellipsizes the trigger; the open list still shows full labels.
523
+ const sizer =
524
+ this.ctrl.size === 'sm'
525
+ ? h(
526
+ 'div',
527
+ { className: 'vela-select-sizer', slot: selectDef.slot('sizer'), attrs: { 'aria-hidden': 'true' } },
528
+ this.ctrl.options.map((o) => h('span', { text: o.label })),
529
+ )
530
+ : null;
531
+ this.native =
532
+ opts.name !== undefined
533
+ ? h(
534
+ 'select',
535
+ { slot: selectDef.slot('native'), attrs: { name: opts.name, 'aria-hidden': 'true', tabindex: -1 } },
536
+ opts.placeholder !== undefined ? h('option', { attrs: { value: '' } }) : null,
537
+ this.ctrl.options.map((o) => h('option', { attrs: { value: o.value }, text: o.label })),
538
+ )
539
+ : null;
540
+ if (this.native) {
541
+ this.native.required = opts.required === true;
542
+ this.native.disabled = this.ctrl.disabled;
543
+ }
544
+ this.el = h('div', { className: 'vela-select', slot: selectDef.slot('root'), attrs: selectVariants({ size: this.ctrl.size }), data: { fill: this.ctrl.fill } }, btn, sizer, this.native);
545
+
546
+ // Suppress the default mousedown focus: when this press outside-dismisses an open
547
+ // popover, Chrome's focus action can scroll the dialog body under the pointer.
548
+ btn.addEventListener('pointerdown', (e) => {
549
+ e.preventDefault();
550
+ btn.focus({ preventScroll: true });
551
+ });
552
+ btn.addEventListener('click', (e) => {
553
+ e.stopPropagation();
554
+ this.toggle();
555
+ });
556
+ btn.addEventListener('keydown', (e) => {
557
+ if ((e.key === 'ArrowDown' || e.key === 'ArrowUp') && !this.list) {
558
+ e.preventDefault();
559
+ this.toggle();
560
+ }
561
+ });
562
+
563
+ this.trigger = btn;
564
+ this.labelEl = label;
565
+ this.paint();
566
+ this.release = ownTeardown(this.el, () => {
567
+ this.list?.hide();
568
+ this.list = null;
569
+ });
570
+ }
571
+
572
+ get value(): string {
573
+ return this.ctrl.value;
574
+ }
575
+
576
+ setValue(v: string): void {
577
+ this.ctrl.setValue(v);
578
+ this.paint();
579
+ }
580
+
581
+ /** The trigger shows the picked option's label, or the placeholder while none is picked. */
582
+ private paint(): void {
583
+ const v = this.ctrl.value;
584
+ const empty = this.placeholder !== undefined && !this.ctrl.options.some((o) => o.value === v);
585
+ this.labelEl.textContent = empty ? (this.placeholder ?? '') : this.ctrl.labelOf(v);
586
+ this.labelEl.toggleAttribute('data-placeholder', empty);
587
+ if (this.native) this.native.value = empty ? '' : v;
588
+ }
589
+
590
+ toggle(): void {
591
+ this.list = toggleSelectList(
592
+ this.trigger,
593
+ this.ctrl.options,
594
+ this.ctrl.value,
595
+ (value) => {
596
+ this.ctrl.pick(value);
597
+ this.paint();
598
+ this.list = null;
599
+ },
600
+ {
601
+ ...this.listOpts,
602
+ focusList: true,
603
+ onClose: () => {
604
+ this.list = null;
605
+ this.trigger.setAttribute('aria-expanded', 'false');
606
+ this.listOpts.onClose?.();
607
+ },
608
+ },
609
+ );
610
+ this.trigger.setAttribute('aria-expanded', String(this.list !== null));
611
+ }
612
+
613
+ destroy(): void {
614
+ this.release();
615
+ }
616
+ }
617
+
618
+ export function createSelect(props: SelectProps): Select {
619
+ return new Select(props);
620
+ }