Raw
1 import { HttpTypes } from "@medusajs/types"
2 import { TFunction } from "i18next"
3 import { useEffect, useMemo, useState } from "react"
4 import { useTranslation } from "react-i18next"
5 import { useAdminSearch } from "../../hooks/api"
6 import {
7 getSearchEntity,
8 getSearchEntityNames,
9 hasSearchEntity,
10 isSearchRegistryCustomized,
11 resolveSearchEntityGroupLabel,
12 } from "../../lib/search/search-entities"
13 import { Shortcut, ShortcutType } from "../../providers/keybind-provider"
14 import { useGlobalShortcuts } from "../../providers/keybind-provider/hooks"
15 import { DynamicSearchResult, SearchArea } from "./types"
16
17 type UseSearchProps = {
18 q?: string
19 limit: number
20 area?: SearchArea
21 }
22
23 export const useSearchResults = ({
24 q,
25 limit,
26 area = "all",
27 }: UseSearchProps) => {
28 const staticResults = useStaticSearchResults(area)
29 const { dynamicResults, isFetching } = useDynamicSearchResults(area, limit, q)
30
31 return {
32 staticResults,
33 dynamicResults,
34 isFetching,
35 }
36 }
37
38 const useStaticSearchResults = (currentArea: SearchArea) => {
39 const globalCommands = useGlobalShortcuts()
40
41 const results = useMemo(() => {
42 const groups = new Map<ShortcutType, Shortcut[]>()
43
44 globalCommands.forEach((command) => {
45 const group = groups.get(command.type) || []
46 group.push(command)
47 groups.set(command.type, group)
48 })
49
50 let filteredGroups: [ShortcutType, Shortcut[]][]
51
52 switch (currentArea) {
53 case "all":
54 filteredGroups = Array.from(groups)
55 break
56 case "navigation":
57 filteredGroups = Array.from(groups).filter(
58 ([type]) => type === "pageShortcut" || type === "settingShortcut"
59 )
60 break
61 case "command":
62 filteredGroups = Array.from(groups).filter(
63 ([type]) => type === "commandShortcut"
64 )
65 break
66 default:
67 filteredGroups = []
68 }
69
70 return filteredGroups.map(([title, items]) => ({
71 title,
72 items,
73 }))
74 }, [globalCommands, currentArea])
75
76 return results
77 }
78
79 const useDynamicSearchResults = (
80 currentArea: SearchArea,
81 limit: number,
82 q?: string
83 ) => {
84 const { t } = useTranslation()
85 const debouncedSearch = useDebouncedSearch(q, 300)
86
87 const registeredEntities = useMemo(() => getSearchEntityNames(), [])
88
89 const entity = useMemo(() => {
90 if (currentArea === "all") {
91 // With an untouched registry the server's defaults match the client's,
92 // so let `/admin/search` decide what "all" covers (engine-only when the
93 // Search Module is enabled). Once an app customizes the registry,
94 // enumerate it so only its entities are searched.
95 return isSearchRegistryCustomized() && registeredEntities.length
96 ? registeredEntities
97 : undefined
98 }
99
100 if (hasSearchEntity(currentArea)) {
101 return [currentArea]
102 }
103
104 return undefined
105 }, [currentArea, registeredEntities])
106
107 const isDynamicArea =
108 hasSearchEntity(currentArea) ||
109 // "all" with a registry customized down to nothing has nothing to fetch.
110 (currentArea === "all" &&
111 (!isSearchRegistryCustomized() || registeredEntities.length > 0))
112
113 const { results, isFetching } = useAdminSearch(
114 {
115 q: debouncedSearch,
116 limit,
117 entity,
118 },
119 {
120 enabled: Boolean(debouncedSearch) && isDynamicArea,
121 }
122 )
123
124 const dynamicResults = useMemo(() => {
125 if (!q || !results?.length) {
126 return []
127 }
128
129 return results
130 .map((group) => transformSearchResultGroup(group, limit, t))
131 .filter(
132 (group): group is DynamicSearchResult =>
133 !!group && group.items.length > 0
134 )
135 }, [q, results, limit, t])
136
137 // Treat the debounce wait as loading too — otherwise `CommandEmpty` flashes
138 // "no results" for ~300ms before the request even starts.
139 const isWaitingForDebounce = Boolean(q) && q !== debouncedSearch
140
141 return {
142 dynamicResults,
143 isFetching:
144 isDynamicArea &&
145 (isWaitingForDebounce || (Boolean(debouncedSearch) && isFetching)),
146 }
147 }
148
149 const useDebouncedSearch = (value: string | undefined, delay: number) => {
150 const [debouncedValue, setDebouncedValue] = useState(value)
151
152 useEffect(() => {
153 const handler = setTimeout(() => {
154 setDebouncedValue(value)
155 }, delay)
156
157 return () => {
158 clearTimeout(handler)
159 }
160 }, [value, delay])
161
162 return debouncedValue
163 }
164
165 function transformSearchResultGroup(
166 group: HttpTypes.AdminSearchResultGroup,
167 limit: number,
168 t: TFunction
169 ): DynamicSearchResult | undefined {
170 const transform = getSearchEntity(group.entity)?.transform
171
172 if (!transform || !Array.isArray(group.data)) {
173 return undefined
174 }
175
176 return {
177 title: resolveSearchEntityGroupLabel(group.entity, t),
178 area: group.entity,
179 hasMore: group.count > limit,
180 count: group.count,
181 items: group.data.map(transform),
182 }
183 }