Raw
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 { Badge, 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 } from "react"
33 import { useTranslation } from "react-i18next"
34
35 import { genericForwardRef } from "../../utilities/generic-forward-ref"
36
37 type ComboboxOption = {
38 value: string
39 label: string
40 disabled?: boolean
41 }
42
43 export type Value = string[] | string
44
45 const TABLUAR_NUM_WIDTH = 8
46 const TAG_BASE_WIDTH = 28
47
48 export interface ComboboxProps<T extends Value = Value>
49 extends Omit<ComponentPropsWithoutRef<"input">, "onChange" | "value"> {
50 value?: T
51 onChange?: (value?: T) => void
52 searchValue?: string
53 onSearchValueChange?: (value: string) => void
54 options: ComboboxOption[]
55 fetchNextPage?: () => void
56 isFetchingNextPage?: boolean
57 onCreateOption?: (value: string) => void
58 shouldAlwaysShowCreateOption?: boolean
59 noResultsPlaceholder?: ReactNode
60 allowClear?: boolean
61 forceHideInput?: boolean // always hide input -> used for singe value select that don't have query/filter
62 displayMode?: "count" | "chips" // how to display multiple selected values
63 }
64
65 const ComboboxImpl = <T extends Value = string>(
66 {
67 value: controlledValue,
68 onChange,
69 searchValue: controlledSearchValue,
70 onSearchValueChange,
71 options,
72 className,
73 placeholder,
74 fetchNextPage,
75 isFetchingNextPage,
76 onCreateOption,
77 shouldAlwaysShowCreateOption,
78 noResultsPlaceholder,
79 allowClear,
80 forceHideInput,
81 displayMode = "count",
82 ...inputProps
83 }: ComboboxProps<T>,
84 ref: ForwardedRef<HTMLInputElement>
85 ) => {
86 const [open, setOpen] = useState(false)
87 const { t } = useTranslation()
88
89 const comboboxRef = useRef<HTMLInputElement>(null)
90 const listboxRef = useRef<HTMLDivElement>(null)
91
92 useImperativeHandle(ref, () => comboboxRef.current!)
93
94 const isValueControlled = controlledValue !== undefined
95 const isSearchControlled = controlledSearchValue !== undefined
96
97 const isArrayValue = Array.isArray(controlledValue)
98 const emptyState = (isArrayValue ? [] : "") as T
99
100 const [uncontrolledSearchValue, setUncontrolledSearchValue] = useState(
101 controlledSearchValue || ""
102 )
103 const defferedSearchValue = useDeferredValue(uncontrolledSearchValue)
104
105 const [uncontrolledValue, setUncontrolledValue] = useState<T>(emptyState)
106
107 const searchValue = isSearchControlled
108 ? controlledSearchValue
109 : uncontrolledSearchValue
110 const selectedValues = isValueControlled ? controlledValue : uncontrolledValue
111
112 const handleValueChange = (newValues?: T) => {
113 // check if the value already exists in options
114 const exists = options
115 .filter((o) => !o.disabled)
116 .find((o) => {
117 if (isArrayValue && newValues?.length) {
118 // only check if the last added value
119 return newValues[newValues.length - 1]?.includes(o.value)
120 }
121 return o.value === newValues
122 })
123
124 // If the value does not exist in the options, and the component has a handler
125 // for creating new options, call it.
126 if (!exists && onCreateOption && newValues) {
127 onCreateOption(newValues as string)
128 }
129
130 if (!isValueControlled) {
131 setUncontrolledValue(newValues || emptyState)
132 }
133
134 if (onChange) {
135 onChange(newValues)
136 }
137
138 setUncontrolledSearchValue("")
139 if (onSearchValueChange) {
140 onSearchValueChange("")
141 }
142 }
143
144 const handleSearchChange = (query: string) => {
145 setUncontrolledSearchValue(query)
146
147 if (onSearchValueChange) {
148 onSearchValueChange(query)
149 }
150 }
151
152 const handleRemoveValue = (valueToRemove: string) => {
153 if (!isArrayValue || !Array.isArray(selectedValues)) {
154 return
155 }
156
157 const newValues = selectedValues.filter((v) => v !== valueToRemove) as T
158 handleValueChange(newValues)
159 }
160
161 /**
162 * Filter and sort the options based on the search value,
163 * and whether the value is already selected.
164 *
165 * This is only used when the search value is uncontrolled.
166 */
167 const matches = useMemo(() => {
168 if (isSearchControlled) {
169 return []
170 }
171
172 // do not use `matcher` if the input is hidden
173 if (forceHideInput) {
174 return options
175 }
176
177 return matchSorter(options, defferedSearchValue, {
178 keys: ["label"],
179 })
180 }, [options, defferedSearchValue, isSearchControlled, forceHideInput])
181
182 const observer = useRef(
183 new IntersectionObserver(
184 (entries) => {
185 const first = entries[0]
186 if (first.isIntersecting) {
187 fetchNextPage?.()
188 }
189 },
190 { threshold: 1 }
191 )
192 )
193
194 const lastOptionRef = useCallback(
195 (node: HTMLDivElement) => {
196 if (isFetchingNextPage) {
197 return
198 }
199 if (observer.current) {
200 observer.current.disconnect()
201 }
202 if (node) {
203 observer.current.observe(node)
204 }
205 },
206 [isFetchingNextPage]
207 )
208
209 const handleOpenChange = (open: boolean) => {
210 if (!open) {
211 setUncontrolledSearchValue("")
212 if (onSearchValueChange) {
213 onSearchValueChange("")
214 }
215 }
216
217 setOpen(open)
218 }
219
220 const hasValue = isArrayValue ? selectedValues?.length > 0 : !!selectedValues
221
222 const showTag = hasValue && isArrayValue
223 const showSelected = showTag && !searchValue && !open
224
225 const hideInput = forceHideInput || (!isArrayValue && hasValue && !open)
226 const selectedLabel = options.find((o) => o.value === selectedValues)?.label
227
228 const hidePlaceholder = showSelected || open
229
230 const tagWidth = useMemo(() => {
231 if (!Array.isArray(selectedValues)) {
232 return TAG_BASE_WIDTH + TABLUAR_NUM_WIDTH // There can only be a single digit
233 }
234
235 const count = selectedValues.length
236 const digits = count.toString().length
237
238 return TAG_BASE_WIDTH + digits * TABLUAR_NUM_WIDTH
239 }, [selectedValues])
240
241 const results = useMemo(() => {
242 return isSearchControlled ? options : matches
243 }, [matches, options, isSearchControlled])
244
245 const normalizedSearchValue = searchValue?.trim() ?? ""
246 const hasLabelMatch =
247 !!normalizedSearchValue.length &&
248 options.some(
249 (option) =>
250 option.label.trim().toLowerCase() ===
251 normalizedSearchValue.toLowerCase()
252 )
253
254 return (
255 <PrimitiveComboboxProvider
256 open={open}
257 setOpen={handleOpenChange}
258 selectedValue={selectedValues}
259 setSelectedValue={(value) => {
260 // TMP: fix issue where sometimes first element of the array is empty string
261 if (Array.isArray(value) && value[0] === "") {
262 value.shift()
263 }
264 handleValueChange(value as T)
265 }}
266 value={searchValue}
267 setValue={(query) => {
268 handleSearchChange(query)
269 }}
270 >
271 {displayMode === "chips" && isArrayValue ? (
272 <div
273 className={clx(
274 "relative flex cursor-pointer flex-wrap items-center gap-1.5",
275 "min-h-8 w-full rounded-md",
276 "bg-ui-bg-field transition-fg shadow-borders-base",
277 "has-[input:focus]:shadow-borders-interactive-with-active",
278 "has-[:invalid]:shadow-borders-error has-[[aria-invalid=true]]:shadow-borders-error",
279 "has-[:disabled]:bg-ui-bg-disabled has-[:disabled]:text-ui-fg-disabled has-[:disabled]:cursor-not-allowed",
280 "p-1",
281 className
282 )}
283 >
284 {Array.isArray(selectedValues) &&
285 selectedValues.map((value) => {
286 const option = options.find((o) => o.value === value)
287 if (!option) return null
288
289 return (
290 <Badge
291 key={value}
292 size="2xsmall"
293 className="transition-fg gap-x-0.5 pl-1.5 pr-1 max-w-full min-w-0 overflow-hidden"
294 >
295 <span className="truncate min-w-0">{option.label}</span>
296 <button
297 tabIndex={-1}
298 type="button"
299 onClick={(e) => {
300 e.preventDefault()
301 handleRemoveValue(value)
302 }}
303 className="text-ui-fg-subtle transition-fg outline-none shrink-0"
304 >
305 <XMarkMini />
306 </button>
307 </Badge>
308 )
309 })}
310 <div className="relative flex min-w-[120px] flex-1 items-center">
311 <PrimitiveCombobox
312 autoSelect
313 ref={comboboxRef}
314 onFocus={() => setOpen(true)}
315 className={clx(
316 "txt-compact-small text-ui-fg-base !placeholder:text-ui-fg-muted transition-fg size-full cursor-pointer bg-transparent pe-8 ps-1 outline-none focus:cursor-text"
317 )}
318 placeholder={
319 Array.isArray(selectedValues) && selectedValues.length > 0
320 ? undefined
321 : placeholder
322 }
323 {...inputProps}
324 />
325 </div>
326 <PrimitiveComboboxDisclosure
327 render={(props) => {
328 return (
329 <button
330 {...props}
331 type="button"
332 className="text-ui-fg-muted transition-fg hover:bg-ui-bg-field-hover absolute end-0 top-0 flex h-8 w-8 items-center justify-center rounded-r outline-none"
333 >
334 <TrianglesMini />
335 </button>
336 )
337 }}
338 />
339 </div>
340 ) : (
341 <div
342 className={clx(
343 "relative flex cursor-pointer items-center gap-x-2 overflow-hidden",
344 "h-8 w-full rounded-md",
345 "bg-ui-bg-field transition-fg shadow-borders-base",
346 "has-[input:focus]:shadow-borders-interactive-with-active",
347 "has-[:invalid]:shadow-borders-error has-[[aria-invalid=true]]:shadow-borders-error",
348 "has-[:disabled]:bg-ui-bg-disabled has-[:disabled]:text-ui-fg-disabled has-[:disabled]:cursor-not-allowed",
349 className
350 )}
351 style={
352 {
353 "--tag-width": `${tagWidth}px`,
354 } as CSSProperties
355 }
356 >
357 {showTag && (
358 <button
359 type="button"
360 onClick={(e) => {
361 e.preventDefault()
362 handleValueChange(
363 isArrayValue ? ([] as unknown as T) : undefined
364 )
365 }}
366 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 start-0.5 top-0.5 z-[1] flex h-[28px] items-center rounded-[4px] border py-[3px] pe-1 ps-1.5 outline-none"
367 >
368 <span className="tabular-nums">{selectedValues.length}</span>
369 <XMarkMini className="text-ui-fg-muted" />
370 </button>
371 )}
372 <div className="relative flex size-full items-center">
373 {showSelected && (
374 <div
375 className={clx(
376 "pointer-events-none absolute inset-y-0 flex size-full items-center",
377 {
378 "start-[calc(var(--tag-width)+8px)]": showTag,
379 "start-2": !showTag,
380 }
381 )}
382 >
383 <Text size="small" leading="compact">
384 {t("general.selected")}
385 </Text>
386 </div>
387 )}
388 {hideInput && (
389 <div
390 className={clx(
391 "pointer-events-none absolute inset-y-0 flex size-full items-center overflow-hidden",
392 {
393 "start-[calc(var(--tag-width)+8px)]": showTag,
394 "start-2": !showTag,
395 }
396 )}
397 >
398 <Text size="small" leading="compact" className="truncate">
399 {selectedLabel}
400 </Text>
401 </div>
402 )}
403 <PrimitiveCombobox
404 autoSelect
405 ref={comboboxRef}
406 onFocus={() => setOpen(true)}
407 className={clx(
408 "txt-compact-small text-ui-fg-base !placeholder:text-ui-fg-muted transition-fg size-full cursor-pointer bg-transparent pe-8 ps-2 outline-none focus:cursor-text",
409 {
410 "opacity-0": hideInput,
411 "ps-2": !showTag,
412 "ps-[calc(var(--tag-width)+8px)]": showTag,
413 }
414 )}
415 placeholder={hidePlaceholder ? undefined : placeholder}
416 {...inputProps}
417 />
418 </div>
419 {allowClear && controlledValue && (
420 <button
421 type="button"
422 onClick={(e) => {
423 e.preventDefault()
424 handleValueChange(undefined)
425 }}
426 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 end-[28px] top-0.5 z-[1] flex h-[28px] items-center rounded-[4px] border px-1.5 py-[2px] outline-none"
427 >
428 <XMarkMini className="text-ui-fg-muted" />
429 </button>
430 )}
431 <PrimitiveComboboxDisclosure
432 render={(props) => {
433 return (
434 <button
435 {...props}
436 type="button"
437 className="text-ui-fg-muted transition-fg hover:bg-ui-bg-field-hover absolute end-0 flex size-8 items-center justify-center rounded-r outline-none"
438 >
439 <TrianglesMini />
440 </button>
441 )
442 }}
443 />
444 </div>
445 )}
446 <PrimitiveComboboxPopover
447 gutter={4}
448 sameWidth
449 ref={listboxRef}
450 role="listbox"
451 className={clx(
452 "shadow-elevation-flyout bg-ui-bg-base z-50 rounded-[8px] p-1",
453 "max-h-[200px] overflow-y-auto",
454 "data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",
455 "data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95",
456 "data-[side=bottom]:slide-in-from-top-2 data-[side=start]:slide-in-from-end-2 data-[side=end]:slide-in-from-start-2 data-[side=top]:slide-in-from-bottom-2"
457 )}
458 style={{
459 pointerEvents: open ? "auto" : "none",
460 }}
461 >
462 {results.map(({ value, label, disabled }) => (
463 <PrimitiveComboboxItem
464 key={value}
465 value={value}
466 focusOnHover
467 setValueOnClick={false}
468 disabled={disabled}
469 className={clx(
470 "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",
471 {
472 "text-ui-fg-disabled": disabled,
473 "bg-ui-bg-component": disabled,
474 }
475 )}
476 >
477 <PrimitiveComboboxItemCheck className="flex !size-5 items-center justify-center">
478 {isArrayValue ? <CheckMini /> : <EllipseMiniSolid />}
479 </PrimitiveComboboxItemCheck>
480 <PrimitiveComboboxItemValue className="txt-compact-small">
481 {label}
482 </PrimitiveComboboxItemValue>
483 </PrimitiveComboboxItem>
484 ))}
485 {!!fetchNextPage && <div ref={lastOptionRef} className="w-px" />}
486 {isFetchingNextPage && (
487 <div className="transition-fg bg-ui-bg-base flex items-center rounded-[4px] px-2 py-1.5">
488 <div className="bg-ui-bg-component size-full h-5 w-full animate-pulse rounded-[4px]" />
489 </div>
490 )}
491 {!results.length &&
492 (noResultsPlaceholder && !searchValue?.length ? (
493 noResultsPlaceholder
494 ) : (
495 <div className="flex items-center gap-x-2 rounded-[4px] px-2 py-1.5">
496 <Text
497 size="small"
498 leading="compact"
499 className="text-ui-fg-subtle"
500 >
501 {t("general.noResultsTitle")}
502 </Text>
503 </div>
504 ))}
505 {(!results.length ||
506 (shouldAlwaysShowCreateOption && normalizedSearchValue.length > 0)) &&
507 onCreateOption && (
508 <Fragment>
509 <PrimitiveSeparator className="bg-ui-border-base -mx-1" />
510 <PrimitiveComboboxItem
511 value={searchValue}
512 focusOnHover
513 setValueOnClick={false}
514 disabled={hasLabelMatch}
515 className={clx(
516 "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",
517 {
518 "text-ui-fg-disabled bg-ui-bg-component cursor-not-allowed":
519 hasLabelMatch,
520 }
521 )}
522 >
523 <PlusMini className="text-ui-fg-subtle" />
524 <Text size="small" leading="compact">
525 {t("actions.create")} &quot;{searchValue}&quot;
526 </Text>
527 </PrimitiveComboboxItem>
528 </Fragment>
529 )}
530 </PrimitiveComboboxPopover>
531 </PrimitiveComboboxProvider>
532 )
533 }
534
535 export const Combobox = genericForwardRef(ComboboxImpl)