forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

0 watching0 forksTypeScript5.5 MiBdcf123aBurak Boduroğlu2 months ago674 commits

select.tsx186 lines, 6.9 KiBHistoryRawDownload
1import { For, Show, createEffect, createSignal, onCleanup, onMount, splitProps, type ComponentProps, type JSX } from "solid-js";
2import {
3 DropdownMenu,
4 DropdownMenuContent,
5 DropdownMenuItem,
6 DropdownMenuTrigger,
7} from "@/components/ui/dropdown-menu";
8import { IconCheck, IconChevronDown } from "@/components/ui/icons";
9import { cn } from "@/lib/cn";
10
11/** Shared trigger look for every dropdown-style picker (Select, DropdownSelect). */
12const SELECT_TRIGGER =
13 "inline-flex items-center justify-between gap-2.5 rounded-lg border border-border/70 bg-muted/40 px-2.5 text-[13px] font-medium text-foreground transition-colors hover:border-border hover:bg-muted focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 disabled:pointer-events-none disabled:opacity-50 data-expanded:border-border data-expanded:bg-muted";
14
15export type SelectOption<T extends string | number = string> = {
16 value: T;
17 label: string;
18 icon?: JSX.Element;
19};
20
21export type DropdownSelectProps<T extends string | number = string> = {
22 options: SelectOption<T>[];
23 value: T;
24 onChange: (value: T) => void;
25 placeholder?: string;
26 labelPrefix?: string;
27 class?: string;
28 triggerClass?: string;
29 disabled?: boolean;
30};
31
32export function DropdownSelect<T extends string | number = string>(props: DropdownSelectProps<T>) {
33 const selectedOption = () => props.options.find((opt) => opt.value === props.value);
34 const displayLabel = () => selectedOption()?.label ?? props.placeholder ?? "";
35
36 return (
37 <DropdownMenu placement="bottom-start" gutter={6}>
38 <DropdownMenuTrigger
39 disabled={props.disabled}
40 class={cn(
41 SELECT_TRIGGER,
42 "h-8",
43 props.triggerClass,
44 props.class,
45 )}
46 >
47 <div class="flex items-center gap-1.5 min-w-0 truncate">
48 <Show when={props.labelPrefix}>
49 <span class="shrink-0 text-xs font-semibold text-muted-foreground">{props.labelPrefix}:</span>
50 </Show>
51 <Show when={selectedOption()?.icon}>
52 <span class="shrink-0">{selectedOption()!.icon}</span>
53 </Show>
54 <span class="truncate font-medium">{displayLabel()}</span>
55 </div>
56 <IconChevronDown class="h-3.5 w-3.5 shrink-0 opacity-60 transition-transform duration-200" />
57 </DropdownMenuTrigger>
58 <DropdownMenuContent class="max-h-72 min-w-48 overflow-y-auto">
59 <For each={props.options}>
60 {(option) => {
61 const isSelected = () => option.value === props.value;
62 return (
63 <DropdownMenuItem
64 class={cn(
65 "flex items-center justify-between gap-2.5 text-sm",
66 isSelected() && "bg-primary/10 text-primary-text font-semibold",
67 )}
68 onSelect={() => props.onChange(option.value)}
69 >
70 <div class="flex items-center gap-2 min-w-0 truncate">
71 <Show when={option.icon}>
72 <span class="shrink-0">{option.icon}</span>
73 </Show>
74 <span class="truncate">{option.label}</span>
75 </div>
76 <Show when={isSelected()}>
77 <IconCheck class="h-3.5 w-3.5 shrink-0 text-primary-text" />
78 </Show>
79 </DropdownMenuItem>
80 );
81 }}
82 </For>
83 </DropdownMenuContent>
84 </DropdownMenu>
85 );
86}
87
88export type SelectProps = ComponentProps<"select"> & {
89 wrapperClass?: string;
90};
91
92type OptionSnapshot = { value: string; label: string; disabled: boolean };
93
94/**
95 * Drop-in for a native `<select>` with `<option>` children, drawn as the app's
96 * own dropdown menu. The native element stays in the DOM (visually hidden) and
97 * remains the source of truth: it holds `name`/`required`/labels for forms and
98 * tests, and picking an item sets its value and fires a real `change` event,
99 * so every existing `onChange={(e) => e.currentTarget.value}` keeps working.
100 */
101export function Select(props: SelectProps) {
102 const [local, rest] = splitProps(props, ["class", "wrapperClass", "disabled"]);
103 let native: HTMLSelectElement | undefined;
104 const [options, setOptions] = createSignal<OptionSnapshot[]>([]);
105 const [current, setCurrent] = createSignal("");
106
107 const snapshot = () => {
108 if (!native) return;
109 setOptions(
110 Array.from(native.options).map((option) => ({
111 value: option.value,
112 label: option.textContent ?? "",
113 disabled: option.disabled,
114 })),
115 );
116 setCurrent(native.value);
117 };
118
119 onMount(() => {
120 snapshot();
121 // <For> inside the select adds options after mount; follow them.
122 const observer = new MutationObserver(snapshot);
123 observer.observe(native!, { childList: true, subtree: true, characterData: true, attributes: true });
124 native!.addEventListener("change", snapshot);
125 onCleanup(() => {
126 observer.disconnect();
127 native?.removeEventListener("change", snapshot);
128 });
129 });
130 // A controlled `value` can change without touching the option list.
131 createEffect(() => {
132 void props.value;
133 queueMicrotask(snapshot);
134 });
135
136 const selected = () => options().find((option) => option.value === current()) ?? options()[0];
137
138 const pick = (value: string) => {
139 if (!native || native.value === value) return;
140 native.value = value;
141 native.dispatchEvent(new Event("input", { bubbles: true }));
142 native.dispatchEvent(new Event("change", { bubbles: true }));
143 };
144
145 return (
146 <div class={cn("relative w-full", local.wrapperClass)}>
147 <select
148 ref={native}
149 tabIndex={-1}
150 aria-hidden="true"
151 disabled={local.disabled}
152 class="sr-only"
153 {...rest}
154 />
155 <DropdownMenu placement="bottom-start" gutter={6} sameWidth>
156 <DropdownMenuTrigger
157 disabled={local.disabled}
158 aria-label={props["aria-label"] ?? selected()?.label}
159 class={cn(SELECT_TRIGGER, "h-9 w-full", local.class)}
160 >
161 <span class="min-w-0 flex-1 truncate text-left">{selected()?.label ?? ""}</span>
162 <IconChevronDown class="h-3.5 w-3.5 shrink-0 opacity-60" />
163 </DropdownMenuTrigger>
164 <DropdownMenuContent class="max-h-72 min-w-40 overflow-y-auto">
165 <For each={options()}>
166 {(option) => (
167 <DropdownMenuItem
168 disabled={option.disabled}
169 class={cn(
170 "flex items-center justify-between gap-2.5 text-sm",
171 option.value === current() && "bg-primary/10 font-semibold text-primary-text",
172 )}
173 onSelect={() => pick(option.value)}
174 >
175 <span class="truncate">{option.label}</span>
176 <Show when={option.value === current()}>
177 <IconCheck class="h-3.5 w-3.5 shrink-0 text-primary-text" />
178 </Show>
179 </DropdownMenuItem>
180 )}
181 </For>
182 </DropdownMenuContent>
183 </DropdownMenu>
184 </div>
185 );
186}