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