1 import {
2 Combobox as PrimitiveCombobox,
3 ComboboxDisclosure as PrimitiveComboboxDisclosure,
4 ComboboxItem as PrimitiveComboboxItem,
5 ComboboxItemCheck as PrimitiveComboboxItemCheck,
6 ComboboxItemValue as PrimitiveComboboxItemValue,
7 ComboboxPopover as PrimitiveComboboxPopover,
8 ComboboxProvider as PrimitiveComboboxProvider,
9 Separator as PrimitiveSeparator,
10 } from "@ariakit/react";
11 import {
12 CheckMini,
13 EllipseMiniSolid,
14 PlusMini,
15 TrianglesMini,
16 XMarkMini,
17 } from "@medusajs/icons";
18 import { clx, Text } from "@medusajs/ui";
19 import { matchSorter } from "match-sorter";
20 import {
21 ComponentPropsWithoutRef,
22 CSSProperties,
23 ForwardedRef,
24 Fragment,
25 ReactNode,
26 useCallback,
27 useDeferredValue,
28 useImperativeHandle,
29 useMemo,
30 useRef,
31 useState,
32 useTransition,
33 } from "react";
34 import { genericForwardRef } from "../utils/refs";
35
36 type ComboboxOption = {
37 value: string;
38 label: string;
39 disabled?: boolean;
40 };
41
42 type Value = string[] | string;
43
44 const TABLUAR_NUM_WIDTH = 8;
45 const TAG_BASE_WIDTH = 28;
46
47 interface ComboboxProps<T extends Value = Value>
48 extends Omit<ComponentPropsWithoutRef<"input">, "onChange" | "value"> {
49 value?: T;
50 onChange?: (value?: T) => void;
51 searchValue?: string;
52 onSearchValueChange?: (value: string) => void;
53 options: ComboboxOption[];
54 fetchNextPage?: () => void;
55 isFetchingNextPage?: boolean;
56 onCreateOption?: (value: string) => void;
57 noResultsPlaceholder?: ReactNode;
58 allowClear?: boolean;
59 }
60
61 const ComboboxImpl = <T extends Value = string>(
62 {
63 value: controlledValue,
64 onChange,
65 searchValue: controlledSearchValue,
66 onSearchValueChange,
67 options,
68 className,
69 placeholder,
70 fetchNextPage,
71 isFetchingNextPage,
72 onCreateOption,
73 noResultsPlaceholder,
74 allowClear,
75 ...inputProps
76 }: ComboboxProps<T>,
77 ref: ForwardedRef<HTMLInputElement>
78 ) => {
79 const [open, setOpen] = useState(false);
80 const [isPending, startTransition] = useTransition();
81
82 const comboboxRef = useRef<HTMLInputElement>(null);
83 const listboxRef = useRef<HTMLDivElement>(null);
84
85 useImperativeHandle(ref, () => comboboxRef.current!);
86
87 const isValueControlled = controlledValue !== undefined;
88 const isSearchControlled = controlledSearchValue !== undefined;
89
90 const isArrayValue = Array.isArray(controlledValue);
91 const emptyState = (isArrayValue ? [] : "") as T;
92
93 const [uncontrolledSearchValue, setUncontrolledSearchValue] = useState(
94 controlledSearchValue || ""
95 );
96 const defferedSearchValue = useDeferredValue(uncontrolledSearchValue);
97
98 const [uncontrolledValue, setUncontrolledValue] = useState<T>(emptyState);
99
100 const searchValue = isSearchControlled
101 ? controlledSearchValue
102 : uncontrolledSearchValue;
103 const selectedValues = isValueControlled
104 ? controlledValue
105 : uncontrolledValue;
106
107 const handleValueChange = (newValues?: T) => {
108 // check if the value already exists in options
109 const exists = options
110 .filter((o) => !o.disabled)
111 .find((o) => {
112 if (isArrayValue) {
113 return newValues?.includes(o.value);
114 }
115 return o.value === newValues;
116 });
117
118 // If the value does not exist in the options, and the component has a handler
119 // for creating new options, call it.
120 if (!exists && onCreateOption && newValues) {
121 onCreateOption(newValues as string);
122 }
123
124 if (!isValueControlled) {
125 setUncontrolledValue(newValues || emptyState);
126 }
127
128 if (onChange) {
129 onChange(newValues);
130 }
131
132 setUncontrolledSearchValue("");
133 };
134
135 const handleSearchChange = (query: string) => {
136 setUncontrolledSearchValue(query);
137
138 if (onSearchValueChange) {
139 onSearchValueChange(query);
140 }
141 };
142
143 /**
144 * Filter and sort the options based on the search value,
145 * and whether the value is already selected.
146 *
147 * This is only used when the search value is uncontrolled.
148 */
149 const matches = useMemo(() => {
150 if (isSearchControlled) {
151 return [];
152 }
153
154 return matchSorter(options, defferedSearchValue, {
155 keys: ["label"],
156 });
157 }, [options, defferedSearchValue, isSearchControlled]);
158
159 const observer = useRef(
160 new IntersectionObserver(
161 (entries) => {
162 const first = entries[0];
163 if (first.isIntersecting) {
164 fetchNextPage?.();
165 }
166 },
167 { threshold: 1 }
168 )
169 );
170
171 const lastOptionRef = useCallback(
172 (node: HTMLDivElement) => {
173 if (isFetchingNextPage) {
174 return;
175 }
176 if (observer.current) {
177 observer.current.disconnect();
178 }
179 if (node) {
180 observer.current.observe(node);
181 }
182 },
183 [isFetchingNextPage]
184 );
185
186 const handleOpenChange = (open: boolean) => {
187 if (!open) {
188 setUncontrolledSearchValue("");
189 }
190
191 setOpen(open);
192 };
193
194 const hasValue = selectedValues?.length > 0;
195
196 const showTag = hasValue && isArrayValue;
197 const showSelected = showTag && !searchValue && !open;
198
199 const hideInput = !isArrayValue && !open;
200 const selectedLabel = options.find((o) => o.value === selectedValues)?.label;
201
202 const hidePlaceholder = showSelected || open;
203
204 const tagWidth = useMemo(() => {
205 if (!Array.isArray(selectedValues)) {
206 return TAG_BASE_WIDTH + TABLUAR_NUM_WIDTH; // There can only be a single digit
207 }
208
209 const count = selectedValues.length;
210 const digits = count.toString().length;
211
212 return TAG_BASE_WIDTH + digits * TABLUAR_NUM_WIDTH;
213 }, [selectedValues]);
214
215 const results = useMemo(() => {
216 return isSearchControlled ? options : matches;
217 }, [matches, options, isSearchControlled]);
218
219 return (
220 <PrimitiveComboboxProvider
221 open={open}
222 setOpen={handleOpenChange}
223 selectedValue={selectedValues}
224 setSelectedValue={(value) => handleValueChange(value as T)}
225 value={uncontrolledSearchValue}
226 setValue={(query) => {
227 startTransition(() => handleSearchChange(query));
228 }}
229 >
230 <div
231 className={clx(
232 "relative flex cursor-pointer items-center gap-x-2 overflow-hidden",
233 "h-8 w-full rounded-md",
234 "bg-ui-bg-field transition-fg shadow-borders-base",
235 "has-[input:focus]:shadow-borders-interactive-with-active",
236 "has-[:invalid]:shadow-borders-error has-[[aria-invalid=true]]:shadow-borders-error",
237 "has-[:disabled]:bg-ui-bg-disabled has-[:disabled]:text-ui-fg-disabled has-[:disabled]:cursor-not-allowed",
238 className
239 )}
240 style={
241 {
242 "--tag-width": `${tagWidth}px`,
243 } as CSSProperties
244 }
245 >
246 {showTag && (
247 <button
248 type="button"
249 onClick={(e) => {
250 e.preventDefault();
251 handleValueChange(undefined);
252 }}
253 className="bg-ui-bg-base hover:bg-ui-bg-base-hover txt-compact-small-plus text-ui-fg-subtle focus-within:border-ui-fg-interactive transition-fg absolute left-0.5 top-0.5 z-[1] flex h-[28px] items-center rounded-[4px] border py-[3px] pl-1.5 pr-1 outline-none"
254 >
255 <span className="tabular-nums">{selectedValues.length}</span>
256 <XMarkMini className="text-ui-fg-muted" />
257 </button>
258 )}
259 <div className="relative flex size-full items-center">
260 {showSelected && (
261 <div
262 className={clx(
263 "pointer-events-none absolute inset-y-0 flex size-full items-center",
264 {
265 "left-[calc(var(--tag-width)+8px)]": showTag,
266 "left-2": !showTag,
267 }
268 )}
269 >
270 <Text size="small" leading="compact">
271 Selected
272 </Text>
273 </div>
274 )}
275 {hideInput && (
276 <div
277 className={clx(
278 "pointer-events-none absolute inset-y-0 flex size-full items-center overflow-hidden",
279 {
280 "left-[calc(var(--tag-width)+8px)]": showTag,
281 "left-2": !showTag,
282 }
283 )}
284 >
285 <Text size="small" leading="compact" className="truncate">
286 {selectedLabel}
287 </Text>
288 </div>
289 )}
290 <PrimitiveCombobox
291 autoSelect
292 ref={comboboxRef}
293 onFocus={() => setOpen(true)}
294 className={clx(
295 "txt-compact-small text-ui-fg-base !placeholder:text-ui-fg-muted transition-fg size-full cursor-pointer bg-transparent pl-2 pr-8 outline-none focus:cursor-text",
296 "hover:bg-ui-bg-field-hover",
297 {
298 "opacity-0": hideInput,
299 "pl-2": !showTag,
300 "pl-[calc(var(--tag-width)+8px)]": showTag,
301 }
302 )}
303 placeholder={hidePlaceholder ? undefined : placeholder}
304 {...inputProps}
305 />
306 </div>
307 {allowClear && controlledValue && (
308 <button
309 type="button"
310 onClick={(e) => {
311 e.preventDefault();
312 handleValueChange(undefined);
313 }}
314 className="bg-ui-bg-base hover:bg-ui-bg-base-hover txt-compact-small-plus text-ui-fg-subtle focus-within:border-ui-fg-interactive transition-fg absolute right-[28px] top-0.5 z-[1] flex h-[28px] items-center rounded-[4px] border px-1.5 py-[2px] outline-none"
315 >
316 <XMarkMini className="text-ui-fg-muted" />
317 </button>
318 )}
319 <PrimitiveComboboxDisclosure
320 render={(props) => {
321 return (
322 <button
323 {...props}
324 type="button"
325 className="text-ui-fg-muted transition-fg hover:bg-ui-bg-field-hover absolute right-0 flex size-8 items-center justify-center rounded-r outline-none"
326 >
327 <TrianglesMini />
328 </button>
329 );
330 }}
331 />
332 </div>
333 <PrimitiveComboboxPopover
334 gutter={4}
335 sameWidth
336 ref={listboxRef}
337 role="listbox"
338 className={clx(
339 "shadow-elevation-flyout bg-ui-bg-base z-50 rounded-[8px] p-1",
340 "max-h-[200px] overflow-y-auto",
341 "data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",
342 "data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95",
343 "data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2"
344 )}
345 style={{
346 pointerEvents: open ? "auto" : "none",
347 }}
348 aria-busy={isPending}
349 >
350 {results.map(({ value, label, disabled }) => (
351 <PrimitiveComboboxItem
352 key={value}
353 value={value}
354 focusOnHover
355 setValueOnClick={false}
356 disabled={disabled}
357 className={clx(
358 "transition-fg bg-ui-bg-base data-[active-item=true]:bg-ui-bg-base-hover group flex cursor-pointer items-center gap-x-2 rounded-[4px] px-2 py-1",
359 {
360 "text-ui-fg-disabled": disabled,
361 "bg-ui-bg-component": disabled,
362 }
363 )}
364 >
365 <PrimitiveComboboxItemCheck className="flex !size-5 items-center justify-center">
366 {isArrayValue ? <CheckMini /> : <EllipseMiniSolid />}
367 </PrimitiveComboboxItemCheck>
368 <PrimitiveComboboxItemValue className="txt-compact-small">
369 {label}
370 </PrimitiveComboboxItemValue>
371 </PrimitiveComboboxItem>
372 ))}
373 {!!fetchNextPage && <div ref={lastOptionRef} className="w-px" />}
374 {isFetchingNextPage && (
375 <div className="transition-fg bg-ui-bg-base flex items-center rounded-[4px] px-2 py-1.5">
376 <div className="bg-ui-bg-component size-full h-5 w-full animate-pulse rounded-[4px]" />
377 </div>
378 )}
379 {!results.length &&
380 (noResultsPlaceholder && !searchValue?.length ? (
381 noResultsPlaceholder
382 ) : (
383 <div className="flex items-center gap-x-2 rounded-[4px] px-2 py-1.5">
384 <Text
385 size="small"
386 leading="compact"
387 className="text-ui-fg-subtle"
388 >
389 No results found
390 </Text>
391 </div>
392 ))}
393 {!results.length && onCreateOption && (
394 <Fragment>
395 <PrimitiveSeparator className="bg-ui-border-base -mx-1" />
396 <PrimitiveComboboxItem
397 value={uncontrolledSearchValue}
398 focusOnHover
399 setValueOnClick={false}
400 className="transition-fg bg-ui-bg-base data-[active-item=true]:bg-ui-bg-base-hover group mt-1 flex cursor-pointer items-center gap-x-2 rounded-[4px] px-2 py-1.5"
401 >
402 <PlusMini className="text-ui-fg-subtle" />
403 <Text size="small" leading="compact">
404 Create &quot;{searchValue}&quot;
405 </Text>
406 </PrimitiveComboboxItem>
407 </Fragment>
408 )}
409 </PrimitiveComboboxPopover>
410 </PrimitiveComboboxProvider>
411 );
412 };
413
414 export const Combobox = genericForwardRef(ComboboxImpl);