1"use client";
2
3import { useControllableState } from "@radix-ui/react-use-controllable-state";
4import { ChevronsUpDownIcon, PlusIcon } from "lucide-react";
5import {
6 type ComponentProps,
7 createContext,
8 type ReactNode,
9 useContext,
10 useEffect,
11 useRef,
12 useState,
13} from "react";
14import { Button } from "@/components/ui/button";
15import {
16 Command,
17 CommandEmpty,
18 CommandGroup,
19 CommandInput,
20 CommandItem,
21 CommandList,
22 CommandSeparator,
23} from "@/components/ui/command";
24import {
25 Popover,
26 PopoverContent,
27 PopoverTrigger,
28} from "@/components/ui/popover";
29import { cn } from "@/lib/utils";
30
31type ComboboxData = {
32 label: string;
33 value: string;
34};
35
36type ComboboxContextType = {
37 data: ComboboxData[];
38 type: string;
39 value: string;
40 onValueChange: (value: string) => void;
41 open: boolean;
42 onOpenChange: (open: boolean) => void;
43 width: number;
44 setWidth: (width: number) => void;
45 inputValue: string;
46 setInputValue: (value: string) => void;
47};
48
49const ComboboxContext = createContext<ComboboxContextType>({
50 data: [],
51 type: "item",
52 value: "",
53 onValueChange: () => {},
54 open: false,
55 onOpenChange: () => {},
56 width: 200,
57 setWidth: () => {},
58 inputValue: "",
59 setInputValue: () => {},
60});
61
62export type ComboboxProps = ComponentProps<typeof Popover> & {
63 data: ComboboxData[];
64 type: string;
65 defaultValue?: string;
66 value?: string;
67 onValueChange?: (value: string) => void;
68 open?: boolean;
69 onOpenChange?: (open: boolean) => void;
70};
71
72export const Combobox = ({
73 data,
74 type,
75 defaultValue,
76 value: controlledValue,
77 onValueChange: controlledOnValueChange,
78 defaultOpen = false,
79 open: controlledOpen,
80 onOpenChange: controlledOnOpenChange,
81 ...props
82}: ComboboxProps) => {
83 const [value, onValueChange] = useControllableState({
84 defaultProp: defaultValue ?? "",
85 prop: controlledValue,
86 onChange: controlledOnValueChange,
87 });
88 const [open, onOpenChange] = useControllableState({
89 defaultProp: defaultOpen,
90 prop: controlledOpen,
91 onChange: controlledOnOpenChange,
92 });
93 const [width, setWidth] = useState(200);
94 const [inputValue, setInputValue] = useState("");
95
96 return (
97 <ComboboxContext.Provider
98 value={{
99 type,
100 value,
101 onValueChange,
102 open,
103 onOpenChange,
104 data,
105 width,
106 setWidth,
107 inputValue,
108 setInputValue,
109 }}
110 >
111 <Popover {...props} onOpenChange={onOpenChange} open={open} />
112 </ComboboxContext.Provider>
113 );
114};
115
116export type ComboboxTriggerProps = ComponentProps<typeof Button>;
117
118export const ComboboxTrigger = ({
119 children,
120 ...props
121}: ComboboxTriggerProps) => {
122 const { value, data, type, setWidth } = useContext(ComboboxContext);
123 const ref = useRef<HTMLButtonElement>(null);
124
125 useEffect(() => {
126 // Create a ResizeObserver to detect width changes
127 const resizeObserver = new ResizeObserver((entries) => {
128 for (const entry of entries) {
129 const newWidth = (entry.target as HTMLElement).offsetWidth;
130 if (newWidth) {
131 setWidth?.(newWidth);
132 }
133 }
134 });
135
136 if (ref.current) {
137 resizeObserver.observe(ref.current);
138 }
139
140 // Clean up the observer when component unmounts
141 return () => {
142 resizeObserver.disconnect();
143 };
144 }, [setWidth]);
145
146 return (
147 <PopoverTrigger asChild>
148 <Button variant="outline" {...props} ref={ref}>
149 {children ?? (
150 <span className="flex w-full items-center justify-between gap-2">
151 {value
152 ? data.find((item) => item.value === value)?.label
153 : `Select ${type}...`}
154 <ChevronsUpDownIcon
155 className="shrink-0 text-muted-foreground"
156 size={16}
157 />
158 </span>
159 )}
160 </Button>
161 </PopoverTrigger>
162 );
163};
164
165export type ComboboxContentProps = ComponentProps<typeof Command> & {
166 popoverOptions?: ComponentProps<typeof PopoverContent>;
167};
168
169export const ComboboxContent = ({
170 className,
171 popoverOptions,
172 ...props
173}: ComboboxContentProps) => {
174 const { width } = useContext(ComboboxContext);
175
176 return (
177 <PopoverContent
178 className={cn("p-0", className)}
179 style={{ width }}
180 {...popoverOptions}
181 >
182 <Command {...props} />
183 </PopoverContent>
184 );
185};
186
187export type ComboboxInputProps = ComponentProps<typeof CommandInput> & {
188 value?: string;
189 defaultValue?: string;
190 onValueChange?: (value: string) => void;
191};
192
193export const ComboboxInput = ({
194 value: controlledValue,
195 defaultValue,
196 onValueChange: controlledOnValueChange,
197 ...props
198}: ComboboxInputProps) => {
199 const { type, inputValue, setInputValue } = useContext(ComboboxContext);
200
201 const [value, onValueChange] = useControllableState({
202 defaultProp: defaultValue ?? inputValue,
203 prop: controlledValue,
204 onChange: (newValue) => {
205 // Sync with context state
206 setInputValue(newValue);
207 // Call external onChange if provided
208 controlledOnValueChange?.(newValue);
209 },
210 });
211
212 return (
213 <CommandInput
214 onValueChange={onValueChange}
215 placeholder={`Search ${type}...`}
216 value={value}
217 {...props}
218 />
219 );
220};
221
222export type ComboboxListProps = ComponentProps<typeof CommandList>;
223
224export const ComboboxList = (props: ComboboxListProps) => (
225 <CommandList {...props} />
226);
227
228export type ComboboxEmptyProps = ComponentProps<typeof CommandEmpty>;
229
230export const ComboboxEmpty = ({ children, ...props }: ComboboxEmptyProps) => {
231 const { type } = useContext(ComboboxContext);
232
233 return (
234 <CommandEmpty {...props}>{children ?? `No ${type} found.`}</CommandEmpty>
235 );
236};
237
238export type ComboboxGroupProps = ComponentProps<typeof CommandGroup>;
239
240export const ComboboxGroup = (props: ComboboxGroupProps) => (
241 <CommandGroup {...props} />
242);
243
244export type ComboboxItemProps = ComponentProps<typeof CommandItem>;
245
246export const ComboboxItem = (props: ComboboxItemProps) => {
247 const { onValueChange, onOpenChange } = useContext(ComboboxContext);
248
249 return (
250 <CommandItem
251 onSelect={(currentValue) => {
252 onValueChange(currentValue);
253 onOpenChange(false);
254 }}
255 {...props}
256 />
257 );
258};
259
260export type ComboboxSeparatorProps = ComponentProps<typeof CommandSeparator>;
261
262export const ComboboxSeparator = (props: ComboboxSeparatorProps) => (
263 <CommandSeparator {...props} />
264);
265
266export type ComboboxCreateNewProps = {
267 onCreateNew: (value: string) => void;
268 children?: (inputValue: string) => ReactNode;
269 className?: string;
270};
271
272export const ComboboxCreateNew = ({
273 onCreateNew,
274 children,
275 className,
276}: ComboboxCreateNewProps) => {
277 const { inputValue, type, onValueChange, onOpenChange } =
278 useContext(ComboboxContext);
279
280 if (!inputValue.trim()) {
281 return null;
282 }
283
284 const handleCreateNew = () => {
285 onCreateNew(inputValue.trim());
286 onValueChange(inputValue.trim());
287 onOpenChange(false);
288 };
289
290 return (
291 <button
292 className={cn(
293 "relative flex w-full cursor-pointer select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none aria-selected:bg-accent aria-selected:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
294 className
295 )}
296 onClick={handleCreateNew}
297 type="button"
298 >
299 {children ? (
300 children(inputValue)
301 ) : (
302 <>
303 <PlusIcon className="h-4 w-4 text-muted-foreground" />
304 <span>{`Create new ${type}: "${inputValue}"`}</span>
305 </>
306 )}
307 </button>
308 );
309};
310