Raw
1 import {
2 Badge,
3 Button,
4 clx,
5 DropdownMenu,
6 IconButton,
7 Kbd,
8 Text,
9 } from "@medusajs/ui"
10 import { Command } from "cmdk"
11 import { Dialog as RadixDialog } from "radix-ui"
12 import {
13 ComponentPropsWithoutRef,
14 ElementRef,
15 forwardRef,
16 Fragment,
17 useCallback,
18 useEffect,
19 useImperativeHandle,
20 useMemo,
21 useRef,
22 useState,
23 } from "react"
24 import { useTranslation } from "react-i18next"
25 import { useLocation, useNavigate } from "react-router-dom"
26
27 import {
28 ArrowUturnLeft,
29 MagnifyingGlass,
30 Plus,
31 Spinner,
32 TriangleDownMini,
33 } from "@medusajs/icons"
34 import { matchSorter } from "match-sorter"
35
36 import { resolveSearchEntityGroupLabel } from "../../lib/search/search-entities"
37 import { useSearch } from "../../providers/search-provider"
38 import { Skeleton } from "../common/skeleton"
39 import { Thumbnail } from "../common/thumbnail"
40 import {
41 DEFAULT_SEARCH_LIMIT,
42 getSearchAreas,
43 SEARCH_LIMIT_INCREMENT,
44 } from "./constants"
45 import { SearchArea } from "./types"
46 import { useSearchResults } from "./use-search-results"
47 import { useDocumentDirection } from "../../hooks/use-document-direction"
48
49 export const Search = () => {
50 const [area, setArea] = useState<SearchArea>("all")
51 const [search, setSearch] = useState("")
52 const [limit, setLimit] = useState(DEFAULT_SEARCH_LIMIT)
53 const { open, onOpenChange } = useSearch()
54 const location = useLocation()
55 const { t } = useTranslation()
56 const navigate = useNavigate()
57
58 const inputRef = useRef<HTMLInputElement>(null)
59 const listRef = useRef<HTMLDivElement>(null)
60
61 const { staticResults, dynamicResults, isFetching } = useSearchResults({
62 area,
63 limit,
64 q: search,
65 })
66
67 const handleReset = useCallback(() => {
68 setArea("all")
69 setSearch("")
70 setLimit(DEFAULT_SEARCH_LIMIT)
71 }, [setLimit])
72
73 const handleBack = () => {
74 handleReset()
75 inputRef.current?.focus()
76 }
77
78 const handleOpenChange = useCallback(
79 (open: boolean) => {
80 if (!open) {
81 handleReset()
82 }
83
84 onOpenChange(open)
85 },
86 [onOpenChange, handleReset]
87 )
88
89 useEffect(() => {
90 handleOpenChange(false)
91 }, [location.pathname, handleOpenChange])
92
93 const handleSelect = (item: { to?: string; callback?: () => void }) => {
94 handleOpenChange(false)
95
96 if (item.to) {
97 navigate(item.to)
98 return
99 }
100
101 if (item.callback) {
102 item.callback()
103 return
104 }
105 }
106
107 const handleShowMore = (area: SearchArea) => {
108 if (area === "all") {
109 setLimit(DEFAULT_SEARCH_LIMIT)
110 } else {
111 setLimit(SEARCH_LIMIT_INCREMENT)
112 }
113 setArea(area)
114 inputRef.current?.focus()
115 }
116
117 const handleLoadMore = () => {
118 setLimit((l) => l + SEARCH_LIMIT_INCREMENT)
119 }
120
121 const filteredStaticResults = useMemo(() => {
122 const filteredResults: typeof staticResults = []
123
124 staticResults.forEach((group) => {
125 const filteredItems = matchSorter(group.items, search, {
126 keys: ["label"],
127 })
128
129 if (filteredItems.length === 0) {
130 return
131 }
132
133 filteredResults.push({
134 ...group,
135 items: filteredItems,
136 })
137 })
138
139 return filteredResults
140 }, [staticResults, search])
141
142 const handleSearch = (q: string) => {
143 setSearch(q)
144 listRef.current?.scrollTo({ top: 0 })
145 }
146
147 const showLoading = useMemo(() => {
148 return isFetching && !dynamicResults.length && !filteredStaticResults.length
149 }, [isFetching, dynamicResults, filteredStaticResults])
150
151 return (
152 <CommandDialog open={open} onOpenChange={handleOpenChange}>
153 <CommandInput
154 isFetching={isFetching}
155 ref={inputRef}
156 area={area}
157 setArea={setArea}
158 value={search}
159 onValueChange={handleSearch}
160 onBack={area !== "all" ? handleBack : undefined}
161 placeholder={t("app.search.placeholder")}
162 />
163 <CommandList ref={listRef}>
164 {showLoading && <CommandLoading />}
165 {dynamicResults.map((group) => {
166 return (
167 <CommandGroup key={group.title} heading={group.title}>
168 {group.items.map((item) => {
169 return (
170 <CommandItem
171 key={item.id}
172 onSelect={() => handleSelect(item)}
173 value={item.value}
174 className="flex items-center justify-between"
175 >
176 <div className="flex items-center gap-x-3">
177 {item.thumbnail && (
178 <Thumbnail
179 alt={item.title}
180 src={item.thumbnail}
181 size="small"
182 />
183 )}
184 <span>{item.title}</span>
185 {item.subtitle && (
186 <span className="text-ui-fg-muted">
187 {item.subtitle}
188 </span>
189 )}
190 </div>
191 </CommandItem>
192 )
193 })}
194 {group.hasMore && area === "all" && (
195 <CommandItem
196 onSelect={() => handleShowMore(group.area)}
197 hidden={true}
198 value={`${group.title}:show:more`} // Prevent the "Show more" buttons across groups from sharing the same value/state
199 >
200 <div className="text-ui-fg-muted flex items-center gap-x-3">
201 <Plus />
202 <Text size="small" leading="compact" weight="plus">
203 {t("app.search.showMore")}
204 </Text>
205 </div>
206 </CommandItem>
207 )}
208 {group.hasMore && area === group.area && (
209 <CommandItem
210 onSelect={handleLoadMore}
211 hidden={true}
212 value={`${group.title}:load:more`}
213 >
214 <div className="text-ui-fg-muted flex items-center gap-x-3">
215 <Plus />
216 <Text size="small" leading="compact" weight="plus">
217 {t("app.search.loadMore", {
218 count: Math.min(
219 SEARCH_LIMIT_INCREMENT,
220 group.count - limit
221 ),
222 })}
223 </Text>
224 </div>
225 </CommandItem>
226 )}
227 </CommandGroup>
228 )
229 })}
230 {filteredStaticResults.map((group) => {
231 return (
232 <CommandGroup
233 key={group.title}
234 heading={t(`app.keyboardShortcuts.${group.title}`)}
235 >
236 {group.items.map((item) => {
237 return (
238 <CommandItem
239 key={item.label}
240 onSelect={() => handleSelect(item)}
241 className="flex items-center justify-between"
242 >
243 <span>{item.label}</span>
244 <div className="flex items-center gap-x-1.5">
245 {item.keys.Mac?.map((key, index) => {
246 return (
247 <div
248 className="flex items-center gap-x-1"
249 key={index}
250 >
251 <Kbd>{key}</Kbd>
252 {index < (item.keys.Mac?.length || 0) - 1 && (
253 <span className="txt-compact-xsmall text-ui-fg-subtle">
254 {t("app.keyboardShortcuts.then")}
255 </span>
256 )}
257 </div>
258 )
259 })}
260 </div>
261 </CommandItem>
262 )
263 })}
264 </CommandGroup>
265 )
266 })}
267 {!showLoading && <CommandEmpty q={search} />}
268 </CommandList>
269 </CommandDialog>
270 )
271 }
272
273 const CommandPalette = forwardRef<
274 ElementRef<typeof Command>,
275 ComponentPropsWithoutRef<typeof Command>
276 >(({ className, ...props }, ref) => (
277 <Command
278 shouldFilter={false}
279 ref={ref}
280 className={clx(
281 "bg-popover text-popover-foreground flex h-full w-full flex-col overflow-hidden rounded-md",
282 className
283 )}
284 {...props}
285 />
286 ))
287 CommandPalette.displayName = Command.displayName
288
289 const CommandDialog = ({ children, ...props }: RadixDialog.DialogProps) => {
290 const { t } = useTranslation()
291
292 return (
293 <RadixDialog.Root {...props}>
294 <RadixDialog.Portal>
295 <RadixDialog.Overlay className="bg-ui-bg-overlay fixed inset-0" />
296 <RadixDialog.Content className="bg-ui-bg-base shadow-elevation-modal fixed left-[50%] top-[50%] flex max-h-[calc(100%-16px)] w-[calc(100%-16px)] min-w-0 max-w-2xl translate-x-[-50%] translate-y-[-50%] flex-col overflow-hidden rounded-xl p-0">
297 <RadixDialog.Title className="sr-only">
298 {t("app.search.title")}
299 </RadixDialog.Title>
300 <RadixDialog.Description className="sr-only">
301 {t("app.search.description")}
302 </RadixDialog.Description>
303 <CommandPalette className="[&_[cmdk-group-heading]]:text-muted-foreground flex h-full flex-col overflow-hidden [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0">
304 {children}
305 </CommandPalette>
306 <div className="bg-ui-bg-field text-ui-fg-subtle flex items-center justify-end border-t px-4 py-3">
307 <div className="flex items-center gap-x-3">
308 <div className="flex items-center gap-x-2">
309 <Text size="xsmall" leading="compact">
310 {t("app.search.navigation")}
311 </Text>
312 <div className="flex items-center gap-x-1">
313 <Kbd className="bg-ui-bg-field-component">↓</Kbd>
314 <Kbd className="bg-ui-bg-field-component">↑</Kbd>
315 </div>
316 </div>
317 <div className="bg-ui-border-strong h-3 w-px" />
318 <div className="flex items-center gap-x-2">
319 <Text size="xsmall" leading="compact">
320 {t("app.search.openResult")}
321 </Text>
322 <Kbd className="bg-ui-bg-field-component">↵</Kbd>
323 </div>
324 </div>
325 </div>
326 </RadixDialog.Content>
327 </RadixDialog.Portal>
328 </RadixDialog.Root>
329 )
330 }
331
332 const CommandInput = forwardRef<
333 ElementRef<typeof Command.Input>,
334 ComponentPropsWithoutRef<typeof Command.Input> & {
335 area: SearchArea
336 setArea: (area: SearchArea) => void
337 isFetching: boolean
338 onBack?: () => void
339 }
340 >(
341 (
342 {
343 className,
344 value,
345 onValueChange,
346 area,
347 setArea,
348 isFetching,
349 onBack,
350 ...props
351 },
352 ref
353 ) => {
354 const { t } = useTranslation()
355 const innerRef = useRef<HTMLInputElement>(null)
356 const direction = useDocumentDirection()
357 useImperativeHandle<HTMLInputElement | null, HTMLInputElement | null>(
358 ref,
359 () => innerRef.current
360 )
361
362 return (
363 <div className="flex flex-col border-b">
364 <div className="px-4 pt-4">
365 <DropdownMenu dir={direction}>
366 <DropdownMenu.Trigger asChild>
367 <Badge
368 size="2xsmall"
369 className="hover:bg-ui-bg-base-pressed transition-fg cursor-pointer"
370 >
371 {resolveSearchEntityGroupLabel(area, t)}
372 <TriangleDownMini className="text-ui-fg-muted" />
373 </Badge>
374 </DropdownMenu.Trigger>
375 <DropdownMenu.Content
376 align="start"
377 className="h-full max-h-[360px] overflow-auto"
378 onCloseAutoFocus={(e) => {
379 e.preventDefault()
380 innerRef.current?.focus()
381 }}
382 >
383 <DropdownMenu.RadioGroup
384 value={area}
385 onValueChange={(v) => setArea(v as SearchArea)}
386 >
387 {getSearchAreas().map((searchArea) => (
388 <Fragment key={searchArea}>
389 {searchArea === "command" && <DropdownMenu.Separator />}
390 <DropdownMenu.RadioItem value={searchArea}>
391 {resolveSearchEntityGroupLabel(searchArea, t)}
392 </DropdownMenu.RadioItem>
393 {searchArea === "all" && <DropdownMenu.Separator />}
394 </Fragment>
395 ))}
396 </DropdownMenu.RadioGroup>
397 </DropdownMenu.Content>
398 </DropdownMenu>
399 </div>
400 <div className="relative flex items-center gap-x-2 px-4 py-3">
401 {onBack && (
402 <IconButton
403 type="button"
404 size="small"
405 variant="transparent"
406 onClick={onBack}
407 >
408 <ArrowUturnLeft className="text-ui-fg-muted" />
409 </IconButton>
410 )}
411 <Command.Input
412 ref={innerRef}
413 value={value}
414 onValueChange={onValueChange}
415 className={clx(
416 "placeholder:text-ui-fg-muted flex !h-6 w-full rounded-md bg-transparent text-sm outline-none disabled:cursor-not-allowed disabled:opacity-50",
417 className
418 )}
419 {...props}
420 />
421 <div className="absolute end-4 top-1/2 flex -translate-y-1/2 items-center justify-end gap-x-2">
422 {isFetching && (
423 <Spinner className="text-ui-fg-muted animate-spin" />
424 )}
425 {value && (
426 <Button
427 variant="transparent"
428 size="small"
429 className="text-ui-fg-muted hover:text-ui-fg-subtle"
430 type="button"
431 onClick={() => {
432 onValueChange?.("")
433 innerRef.current?.focus()
434 }}
435 >
436 {t("actions.clear")}
437 </Button>
438 )}
439 </div>
440 </div>
441 </div>
442 )
443 }
444 )
445
446 CommandInput.displayName = Command.Input.displayName
447
448 const CommandList = forwardRef<
449 ElementRef<typeof Command.List>,
450 ComponentPropsWithoutRef<typeof Command.List>
451 >(({ className, ...props }, ref) => (
452 <Command.List
453 ref={ref}
454 className={clx(
455 "h-[300px] overflow-y-auto overflow-x-hidden px-2 pb-4",
456 className
457 )}
458 {...props}
459 />
460 ))
461
462 CommandList.displayName = Command.List.displayName
463
464 const CommandEmpty = forwardRef<
465 ElementRef<typeof Command.Empty>,
466 Omit<ComponentPropsWithoutRef<typeof Command.Empty>, "children"> & {
467 q?: string
468 }
469 >((props, ref) => {
470 const { t } = useTranslation()
471
472 return (
473 <Command.Empty ref={ref} className="py-6 text-center text-sm" {...props}>
474 <div className="text-ui-fg-subtle flex min-h-[236px] flex-col items-center justify-center gap-y-3">
475 <MagnifyingGlass className="text-ui-fg-subtle" />
476 <div className="flex flex-col items-center justify-center gap-y-1">
477 <Text size="small" weight="plus" leading="compact">
478 {props.q
479 ? t("app.search.noResultsTitle")
480 : t("app.search.emptySearchTitle")}
481 </Text>
482 <Text size="small" className="text-ui-fg-muted">
483 {props.q
484 ? t("app.search.noResultsMessage")
485 : t("app.search.emptySearchMessage")}
486 </Text>
487 </div>
488 </div>
489 </Command.Empty>
490 )
491 })
492
493 CommandEmpty.displayName = Command.Empty.displayName
494
495 const CommandLoading = forwardRef<
496 ElementRef<typeof Command.Loading>,
497 ComponentPropsWithoutRef<typeof Command.Loading>
498 >((props, ref) => {
499 return (
500 <Command.Loading
501 ref={ref}
502 {...props}
503 className="bg-ui-bg-base flex flex-col"
504 >
505 <div className="w-full px-2 pb-1 pt-3">
506 <Skeleton className="h-5 w-10" />
507 </div>
508 {Array.from({ length: 7 }).map((_, index) => (
509 <div key={index} className="w-full p-2">
510 <Skeleton className="h-5 w-full" />
511 </div>
512 ))}
513 </Command.Loading>
514 )
515 })
516 CommandLoading.displayName = Command.Loading.displayName
517
518 const CommandGroup = forwardRef<
519 ElementRef<typeof Command.Group>,
520 ComponentPropsWithoutRef<typeof Command.Group>
521 >(({ className, ...props }, ref) => (
522 <Command.Group
523 ref={ref}
524 className={clx(
525 "text-ui-fg-base [&_[cmdk-group-heading]]:text-ui-fg-muted [&_[cmdk-group-heading]]:txt-compact-xsmall-plus overflow-hidden [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:pb-1 [&_[cmdk-group-heading]]:pt-3 [&_[cmdk-item]]:py-2",
526 className
527 )}
528 {...props}
529 />
530 ))
531
532 CommandGroup.displayName = Command.Group.displayName
533
534 const CommandSeparator = forwardRef<
535 ElementRef<typeof Command.Separator>,
536 ComponentPropsWithoutRef<typeof Command.Separator>
537 >(({ className, ...props }, ref) => (
538 <Command.Separator
539 ref={ref}
540 className={clx("bg-border -mx-1 h-px", className)}
541 {...props}
542 />
543 ))
544 CommandSeparator.displayName = Command.Separator.displayName
545
546 const CommandItem = forwardRef<
547 ElementRef<typeof Command.Item>,
548 ComponentPropsWithoutRef<typeof Command.Item>
549 >(({ className, ...props }, ref) => (
550 <Command.Item
551 ref={ref}
552 className={clx(
553 "aria-selected:bg-ui-bg-base-hover focus-visible:bg-ui-bg-base-hover txt-compact-small [&>svg]:text-ui-fg-subtle relative flex cursor-pointer select-none items-center gap-x-3 rounded-md p-2 outline-none data-[disabled]:pointer-events-none data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50",
554 className
555 )}
556 {...props}
557 />
558 ))
559
560 CommandItem.displayName = Command.Item.displayName