Skip to content
Source
Sign inSign up
TanStack/form
Open History to see the last commit

select.tsx

580 lines16.5 KB

1import { Select as SelectPrimitive, createListCollection } from '@ark-ui/solid'
2import CheckIcon from 'lucide-solid/icons/check'
3import ChevronDownIcon from 'lucide-solid/icons/chevron-down'
4import ChevronUpIcon from 'lucide-solid/icons/chevron-up'
5import {
6 createContext,
7 createEffect,
8 createMemo,
9 createSignal,
10 onCleanup,
11 splitProps,
12 useContext,
13} from 'solid-js'
14import { Portal } from './portal'
15import type { Accessor, JSX } from 'solid-js'
16import type { ListCollection } from '@ark-ui/solid'
17import { cn } from '@/utils'
18​
19// Ported from the original shadcn/ui + Radix UI + React component.
20// This wraps the Ark UI + SolidJS primitive and preserves shadcn's Tailwind-based
21// design-system API, variants, and styling.
22// https://ui.shadcn.com/
23​
24type SelectItemData = {
25 value: string
26 label: string
27 disabled?: boolean
29​
30type RegisteredSelectItem = {
31 id: symbol
32 item: SelectItemData
34​
35type SelectContextValue = {
36 collection: Accessor<ListCollection<SelectItemData>>
37 removeItem: (id: symbol) => void
38 upsertItem: (id: symbol, item: SelectItemData) => void
40​
41const SelectContext = createContext<SelectContextValue>()
42​
43function useSelectContext() {
44 const context = useContext(SelectContext)
45​
46 if (!context) {
47 throw new Error('Select components must be used within <Select>')
48 }
49​
50 return context
52​
53function getItemLabel(value: string, children: JSX.Element, label?: string) {
54 if (label) {
55 return label
56 }
57​
58 if (typeof children === 'string' || typeof children === 'number') {
59 return String(children)
60 }
61​
62 return value
64​
65type SelectProps = Omit<
66 SelectPrimitive.RootProps<SelectItemData>,
67 'collection'
68> & {
69 collection?: ListCollection<SelectItemData>
71​
72/**
73 * The root component that owns select state and the available item collection.
74 *
75 * @example
76 * ```tsx
77 * <Select defaultValue={["general"]}>
78 * <SelectTrigger>
79 * <SelectValue placeholder="Choose area" />
80 * </SelectTrigger>
81 * <SelectContent>
82 * <SelectScrollUpButton />
83 * <SelectGroup>
84 * <SelectLabel>Workspace</SelectLabel>
85 * <SelectItem value="general">General</SelectItem>
86 * <SelectSeparator />
87 * <SelectItem value="billing">Billing</SelectItem>
88 * </SelectGroup>
89 * <SelectScrollDownButton />
90 * </SelectContent>
91 * </Select>
92 * ```
93 */
94function Select(props: SelectProps) {
95 const [local, others] = splitProps(props, [
96 'children',
97 'collection',
98 'positioning',
99 ])
100 const [registeredItems, setRegisteredItems] = createSignal<
101 Array<RegisteredSelectItem>
102 >([])
103​
104 const internalCollection = createMemo(() =>
105 createListCollection<SelectItemData>({
106 items: registeredItems().map((entry) => entry.item),
107 itemToString: (item) => item.label,
108 itemToValue: (item) => item.value,
109 isItemDisabled: (item) => !!item.disabled,
110 }),
111 )
112​
113 const collection = () => local.collection ?? internalCollection()
114​
115 const context: SelectContextValue = {
116 collection,
117 removeItem: (id) => {
118 setRegisteredItems((items) => items.filter((item) => item.id !== id))
119 },
120 upsertItem: (id, item) => {
121 setRegisteredItems((items) => {
122 const index = items.findIndex((entry) => entry.id === id)
123​
124 if (index === -1) {
125 return [...items, { id, item }]
126 }
127​
128 const nextItems = items.slice()
129 nextItems[index] = { id, item }
130 return nextItems
131 })
132 },
133 }
134​
135 return (
136 <SelectContext.Provider value={context}>
137 <SelectPrimitive.Root
138 data-slot="select"
139 collection={collection()}
140 positioning={{ fitViewport: true, ...local.positioning }}
141 {...others}
142 >
143 <SelectPrimitive.HiddenSelect />
144 {local.children}
145 </SelectPrimitive.Root>
146 </SelectContext.Provider>
147 )
149​
150/**
151 * Groups related SelectItem options within SelectContent.
152 *
153 * @example
154 * ```tsx
155 * <Select defaultValue={["general"]}>
156 * <SelectTrigger>
157 * <SelectValue placeholder="Choose area" />
158 * </SelectTrigger>
159 * <SelectContent>
160 * <SelectScrollUpButton />
161 * <SelectGroup>
162 * <SelectLabel>Workspace</SelectLabel>
163 * <SelectItem value="general">General</SelectItem>
164 * <SelectSeparator />
165 * <SelectItem value="billing">Billing</SelectItem>
166 * </SelectGroup>
167 * <SelectScrollDownButton />
168 * </SelectContent>
169 * </Select>
170 * ```
171 */
172function SelectGroup(props: SelectPrimitive.ItemGroupProps) {
173 const [local, others] = splitProps(props, ['class'])
174​
175 return (
176 <SelectPrimitive.ItemGroup
177 data-slot="select-group"
178 class={cn('scroll-my-1 p-1', local.class)}
179 {...others}
180 />
181 )
183​
184/**
185 * Displays the selected item label or placeholder inside a SelectTrigger.
186 *
187 * @example
188 * ```tsx
189 * <Select defaultValue={["general"]}>
190 * <SelectTrigger>
191 * <SelectValue placeholder="Choose area" />
192 * </SelectTrigger>
193 * <SelectContent>
194 * <SelectScrollUpButton />
195 * <SelectGroup>
196 * <SelectLabel>Workspace</SelectLabel>
197 * <SelectItem value="general">General</SelectItem>
198 * <SelectSeparator />
199 * <SelectItem value="billing">Billing</SelectItem>
200 * </SelectGroup>
201 * <SelectScrollDownButton />
202 * </SelectContent>
203 * </Select>
204 * ```
205 */
206function SelectValue(props: SelectPrimitive.ValueTextProps) {
207 const [local, others] = splitProps(props, ['class'])
208​
209 return (
210 <SelectPrimitive.ValueText
211 data-slot="select-value"
212 class={local.class}
213 {...others}
214 />
215 )
217​
218type SelectTriggerProps = SelectPrimitive.TriggerProps & {
219 size?: 'sm' | 'default'
221​
222/**
223 * The button-like control that opens the SelectContent popover.
224 *
225 * @example
226 * ```tsx
227 * <Select defaultValue={["general"]}>
228 * <SelectTrigger>
229 * <SelectValue placeholder="Choose area" />
230 * </SelectTrigger>
231 * <SelectContent>
232 * <SelectScrollUpButton />
233 * <SelectGroup>
234 * <SelectLabel>Workspace</SelectLabel>
235 * <SelectItem value="general">General</SelectItem>
236 * <SelectSeparator />
237 * <SelectItem value="billing">Billing</SelectItem>
238 * </SelectGroup>
239 * <SelectScrollDownButton />
240 * </SelectContent>
241 * </Select>
242 * ```
243 */
244function SelectTrigger(props: SelectTriggerProps) {
245 const [local, others] = splitProps(props, ['class', 'size', 'children'])
246​
247 const size = () => local.size ?? 'default'
248​
249 return (
250 <SelectPrimitive.Control data-slot="select-control" class="contents">
251 <SelectPrimitive.Trigger
252 data-slot="select-trigger"
253 data-size={size()}
254 class={cn(
255 "flex w-fit items-center justify-between gap-1.5 rounded-lg border border-input bg-transparent py-2 pr-2 pl-2.5 text-sm whitespace-nowrap transition-colors outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-placeholder:text-muted-foreground data-[size=default]:h-8 data-[size=sm]:h-7 data-[size=sm]:rounded-[min(var(--radius-md),10px)] *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-1.5 dark:bg-input/30 dark:hover:bg-input/50 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
256 local.class,
257 )}
258 {...others}
259 >
260 {local.children}
261 <SelectPrimitive.Indicator data-slot="select-icon">
262 <ChevronDownIcon class="pointer-events-none size-4 text-muted-foreground" />
263 </SelectPrimitive.Indicator>
264 </SelectPrimitive.Trigger>
265 </SelectPrimitive.Control>
266 )
268​
269type SelectContentProps = SelectPrimitive.ContentProps & {
270 position?: 'item-aligned' | 'popper'
271 align?: 'start' | 'center' | 'end'
273​
274/**
275 * The floating listbox surface that contains SelectItem options.
276 *
277 * @example
278 * ```tsx
279 * <Select defaultValue={["general"]}>
280 * <SelectTrigger>
281 * <SelectValue placeholder="Choose area" />
282 * </SelectTrigger>
283 * <SelectContent>
284 * <SelectScrollUpButton />
285 * <SelectGroup>
286 * <SelectLabel>Workspace</SelectLabel>
287 * <SelectItem value="general">General</SelectItem>
288 * <SelectSeparator />
289 * <SelectItem value="billing">Billing</SelectItem>
290 * </SelectGroup>
291 * <SelectScrollDownButton />
292 * </SelectContent>
293 * </Select>
294 * ```
295 */
296function SelectContent(props: SelectContentProps) {
297 const [local, others] = splitProps(props, [
298 'class',
299 'children',
300 'position',
301 'align',
302 ])
303​
304 const position = () => local.position ?? 'item-aligned'
305 const align = () => local.align ?? 'center'
306​
307 return (
308 <Portal>
309 <SelectPrimitive.Positioner data-slot="select-positioner">
310 <SelectPrimitive.Content
311 data-slot="select-content"
312 data-align={align()}
313 data-align-trigger={position() === 'item-aligned'}
314 class={cn(
315 'relative z-50 max-h-[min(var(--available-height,20rem),20rem)] min-w-36 origin-(--transform-origin) overflow-hidden rounded-lg bg-popover text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 data-[align-trigger=true]:animate-none data-[placement^=bottom]:slide-in-from-top-2 data-[placement^=left]:slide-in-from-right-2 data-[placement^=right]:slide-in-from-left-2 data-[placement^=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95',
316 position() === 'popper' &&
317 'data-[placement^=bottom]:translate-y-1 data-[placement^=left]:-translate-x-1 data-[placement^=right]:translate-x-1 data-[placement^=top]:-translate-y-1',
318 local.class,
319 )}
320 {...others}
321 >
322 <SelectPrimitive.List
323 data-slot="select-list"
324 data-position={position()}
325 class="max-h-[inherit] overflow-x-hidden overflow-y-auto data-[position=popper]:w-full data-[position=popper]:min-w-(--reference-width)"
326 >
327 {local.children}
328 </SelectPrimitive.List>
329 </SelectPrimitive.Content>
330 </SelectPrimitive.Positioner>
331 </Portal>
332 )
334​
335/**
336 * A muted label for a group of SelectItem options.
337 *
338 * @example
339 * ```tsx
340 * <Select defaultValue={["general"]}>
341 * <SelectTrigger>
342 * <SelectValue placeholder="Choose area" />
343 * </SelectTrigger>
344 * <SelectContent>
345 * <SelectScrollUpButton />
346 * <SelectGroup>
347 * <SelectLabel>Workspace</SelectLabel>
348 * <SelectItem value="general">General</SelectItem>
349 * <SelectSeparator />
350 * <SelectItem value="billing">Billing</SelectItem>
351 * </SelectGroup>
352 * <SelectScrollDownButton />
353 * </SelectContent>
354 * </Select>
355 * ```
356 */
357function SelectLabel(props: SelectPrimitive.ItemGroupLabelProps) {
358 const [local, others] = splitProps(props, ['class'])
359​
360 return (
361 <SelectPrimitive.ItemGroupLabel
362 data-slot="select-label"
363 class={cn('px-1.5 py-1 text-xs text-muted-foreground', local.class)}
364 {...others}
365 />
366 )
368​
369type SelectItemProps = Omit<SelectPrimitive.ItemProps, 'children' | 'item'> & {
370 children?: JSX.Element
371 disabled?: boolean
372 label?: string
373 textValue?: string
374 value: string
376​
377/**
378 * A selectable option that registers itself with the parent Select collection.
379 *
380 * @example
381 * ```tsx
382 * <Select defaultValue={["general"]}>
383 * <SelectTrigger>
384 * <SelectValue placeholder="Choose area" />
385 * </SelectTrigger>
386 * <SelectContent>
387 * <SelectScrollUpButton />
388 * <SelectGroup>
389 * <SelectLabel>Workspace</SelectLabel>
390 * <SelectItem value="general">General</SelectItem>
391 * <SelectSeparator />
392 * <SelectItem value="billing">Billing</SelectItem>
393 * </SelectGroup>
394 * <SelectScrollDownButton />
395 * </SelectContent>
396 * </Select>
397 * ```
398 */
399function SelectItem(props: SelectItemProps) {
400 const [local, others] = splitProps(props, [
401 'class',
402 'children',
403 'disabled',
404 'label',
405 'textValue',
406 'value',
407 ])
408 const context = useSelectContext()
409 const id = Symbol('select-item')
410​
411 const item = (): SelectItemData => ({
412 value: local.value,
413 label: getItemLabel(
414 local.value,
415 local.children,
416 local.textValue ?? local.label,
417 ),
418 disabled: local.disabled,
419 })
420​
421 createEffect(() => {
422 context.upsertItem(id, item())
423 })
424​
425 onCleanup(() => {
426 context.removeItem(id)
427 })
428​
429 const collectionItem = () => context.collection().find(local.value) ?? item()
430​
431 return (
432 <SelectPrimitive.Item
433 data-slot="select-item"
434 item={collectionItem()}
435 class={cn(
436 "relative flex w-full cursor-default items-center gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none data-highlighted:bg-accent data-highlighted:text-accent-foreground not-data-[variant=destructive]:data-highlighted:**:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
437 local.class,
438 )}
439 {...others}
440 >
441 <span class="pointer-events-none absolute right-2 flex size-4 items-center justify-center">
442 <SelectPrimitive.ItemIndicator>
443 <CheckIcon class="pointer-events-none" />
444 </SelectPrimitive.ItemIndicator>
445 </span>
446 <SelectPrimitive.ItemText>{local.children}</SelectPrimitive.ItemText>
447 </SelectPrimitive.Item>
448 )
450​
451/**
452 * A visual divider between groups or related SelectItem options.
453 *
454 * @example
455 * ```tsx
456 * <Select defaultValue={["general"]}>
457 * <SelectTrigger>
458 * <SelectValue placeholder="Choose area" />
459 * </SelectTrigger>
460 * <SelectContent>
461 * <SelectScrollUpButton />
462 * <SelectGroup>
463 * <SelectLabel>Workspace</SelectLabel>
464 * <SelectItem value="general">General</SelectItem>
465 * <SelectSeparator />
466 * <SelectItem value="billing">Billing</SelectItem>
467 * </SelectGroup>
468 * <SelectScrollDownButton />
469 * </SelectContent>
470 * </Select>
471 * ```
472 */
473function SelectSeparator(props: JSX.HTMLElementTags['div']) {
474 const [local, others] = splitProps(props, ['class'])
475​
476 return (
477 <div
478 role="separator"
479 aria-orientation="horizontal"
480 data-slot="select-separator"
481 class={cn('pointer-events-none -mx-1 my-1 h-px bg-border', local.class)}
482 {...others}
483 />
484 )
486​
487/**
488 * An optional scroll affordance for overflowing SelectContent above the visible
489 * list.
490 *
491 * @example
492 * ```tsx
493 * <Select defaultValue={["general"]}>
494 * <SelectTrigger>
495 * <SelectValue placeholder="Choose area" />
496 * </SelectTrigger>
497 * <SelectContent>
498 * <SelectScrollUpButton />
499 * <SelectGroup>
500 * <SelectLabel>Workspace</SelectLabel>
501 * <SelectItem value="general">General</SelectItem>
502 * <SelectSeparator />
503 * <SelectItem value="billing">Billing</SelectItem>
504 * </SelectGroup>
505 * <SelectScrollDownButton />
506 * </SelectContent>
507 * </Select>
508 * ```
509 */
510function SelectScrollUpButton(props: JSX.HTMLElementTags['div']) {
511 const [local, others] = splitProps(props, ['class'])
512​
513 return (
514 <div
515 aria-hidden="true"
516 data-slot="select-scroll-up-button"
517 class={cn(
518 "z-10 flex cursor-default items-center justify-center bg-popover py-1 [&_svg:not([class*='size-'])]:size-4",
519 local.class,
520 )}
521 {...others}
522 >
523 <ChevronUpIcon />
524 </div>
525 )
527​
528/**
529 * An optional scroll affordance for overflowing SelectContent below the visible
530 * list.
531 *
532 * @example
533 * ```tsx
534 * <Select defaultValue={["general"]}>
535 * <SelectTrigger>
536 * <SelectValue placeholder="Choose area" />
537 * </SelectTrigger>
538 * <SelectContent>
539 * <SelectScrollUpButton />
540 * <SelectGroup>
541 * <SelectLabel>Workspace</SelectLabel>
542 * <SelectItem value="general">General</SelectItem>
543 * <SelectSeparator />
544 * <SelectItem value="billing">Billing</SelectItem>
545 * </SelectGroup>
546 * <SelectScrollDownButton />
547 * </SelectContent>
548 * </Select>
549 * ```
550 */
551function SelectScrollDownButton(props: JSX.HTMLElementTags['div']) {
552 const [local, others] = splitProps(props, ['class'])
553​
554 return (
555 <div
556 aria-hidden="true"
557 data-slot="select-scroll-down-button"
558 class={cn(
559 "z-10 flex cursor-default items-center justify-center bg-popover py-1 [&_svg:not([class*='size-'])]:size-4",
560 local.class,
561 )}
562 {...others}
563 >
564 <ChevronDownIcon />
565 </div>
566 )
568​
569export {
570 Select,
571 SelectContent,
572 SelectGroup,
573 SelectItem,
574 SelectLabel,
575 SelectScrollDownButton,
576 SelectScrollUpButton,
577 SelectSeparator,
578 SelectTrigger,
579 SelectValue,