1 "use client"
2
3 import React, { useCallback, useEffect, useMemo, useState } from "react"
4 import {
5 Card,
6 CardList,
7 getLocalSearch,
8 H2,
9 H3,
10 H4,
11 Hr,
12 LocalSearch,
13 MarkdownContent,
14 SearchInput,
15 useIsBrowser,
16 useSidebar,
17 } from "../.."
18 import { Sidebar } from "types"
19 import slugify from "slugify"
20 import { MDXComponents } from "../.."
21 import { ChevronDoubleRight, ExclamationCircle } from "@medusajs/icons"
22 import { isSidebarItemLink } from "../../utils/sidebar-utils"
23
24 type HeadingComponent = (
25 props: React.HTMLAttributes<HTMLHeadingElement>
26 ) => React.JSX.Element
27
28 export type UseChildDocsProps = {
29 onlyTopLevel?: boolean
30 type?: "sidebar" | "item"
31 hideItems?: string[]
32 showItems?: string[]
33 hideTitle?: boolean
34 hideDescription?: boolean
35 titleLevel?: number
36 startChildLevel?: number
37 endChildLevel?: number
38 itemsPerRow?: number
39 defaultItemsPerRow?: number
40 search?: {
41 enable: boolean
42 storageKey?: string
43 placeholder?: string
44 }
45 }
46
47 export const useChildDocs = ({
48 onlyTopLevel = false,
49 hideItems = [],
50 showItems,
51 type = "sidebar",
52 hideTitle = false,
53 hideDescription = false,
54 titleLevel = 2,
55 startChildLevel = 1,
56 endChildLevel = -1,
57 itemsPerRow,
58 defaultItemsPerRow,
59 search: {
60 enable: enableSearch = false,
61 storageKey = "child-docs",
62 ...searchProps
63 } = { enable: false },
64 }: UseChildDocsProps) => {
65 const { shownSidebar, activeItem, getSidebarFirstLinkChild } = useSidebar()
66 const { isBrowser } = useIsBrowser()
67 const [searchQuery, setSearchQuery] = useState("")
68 const [localSearch, setLocalSearch] = useState<
69 LocalSearch<Sidebar.SidebarItemLink> | undefined
70 >()
71 const TitleHeaderComponent = useCallback(
72 (level: number): HeadingComponent => {
73 switch (level) {
74 case 3:
75 return H3
76 case 4:
77 return H4
78 case 5:
79 return MDXComponents["h5"] as HeadingComponent
80 case 6:
81 return MDXComponents["h6"] as HeadingComponent
82 default:
83 return H2
84 }
85 },
86 []
87 )
88 const filterType = useMemo(() => {
89 return showItems !== undefined
90 ? "show"
91 : hideItems.length > 0
92 ? "hide"
93 : "all"
94 }, [showItems, hideItems])
95
96 const filterCondition = (item: Sidebar.SidebarItem): boolean => {
97 if (item.type === "separator") {
98 return false
99 }
100 switch (filterType) {
101 case "hide":
102 return (
103 (!isSidebarItemLink(item) || !hideItems.includes(item.path)) &&
104 !hideItems.includes(item.title)
105 )
106 case "show":
107 return (
108 (isSidebarItemLink(item) && showItems!.includes(item.path)) ||
109 showItems!.includes(item.title)
110 )
111 case "all":
112 return true
113 }
114 }
115
116 const filterItems = (
117 items: Sidebar.SidebarItem[]
118 ): Sidebar.InteractiveSidebarItem[] => {
119 return (items.filter(filterCondition) as Sidebar.InteractiveSidebarItem[])
120 .map((item) => Object.assign({}, item))
121 .map((item) => {
122 if (item.children && filterType === "hide") {
123 item.children = filterItems(item.children)
124 }
125
126 return item
127 })
128 }
129
130 const filterNonInteractiveItems = (
131 items: Sidebar.SidebarItem[] | undefined
132 ): Sidebar.InteractiveSidebarItem[] => {
133 return (
134 (items?.filter(
135 (item) => item.type !== "separator" && !item.hideFromChildItems
136 ) as Sidebar.InteractiveSidebarItem[]) || []
137 )
138 }
139
140 const getChildrenForLevel = ({
141 item,
142 currentLevel = 1,
143 }: {
144 item: Sidebar.InteractiveSidebarItem
145 currentLevel?: number
146 }): Sidebar.InteractiveSidebarItem[] | undefined => {
147 if (
148 (endChildLevel > 0 && currentLevel > endChildLevel) ||
149 !item.children ||
150 item.hideFromChildItems
151 ) {
152 return
153 }
154 if (currentLevel >= startChildLevel) {
155 return filterNonInteractiveItems(item.children)
156 }
157
158 const childrenResult: Sidebar.InteractiveSidebarItem[] = []
159
160 filterNonInteractiveItems(item.children).forEach((child) => {
161 const childChildren = getChildrenForLevel({
162 item: child,
163 currentLevel: currentLevel + 1,
164 })
165
166 if (!childChildren) {
167 return
168 }
169
170 childrenResult.push(...childChildren)
171 })
172
173 return childrenResult
174 }
175
176 const filteredItems = useMemo(() => {
177 let targetItems =
178 type === "sidebar"
179 ? shownSidebar && "items" in shownSidebar
180 ? shownSidebar.items
181 : shownSidebar?.children || []
182 : [...(activeItem?.children || [])]
183 if (filterType !== "all" && targetItems) {
184 targetItems = filterItems(targetItems)
185 }
186
187 return filterNonInteractiveItems(targetItems)
188 }, [shownSidebar, type, activeItem, filterType])
189
190 const searchableItems = useMemo(() => {
191 const searchableItems: Sidebar.SidebarItemLink[] = []
192 if (!enableSearch) {
193 return searchableItems
194 }
195 if (onlyTopLevel) {
196 filteredItems.forEach((item) => {
197 if (isSidebarItemLink(item)) {
198 searchableItems.push(item)
199 } else {
200 const firstChild = item.children?.find((child) =>
201 isSidebarItemLink(child)
202 )
203 if (firstChild) {
204 searchableItems.push(firstChild as Sidebar.SidebarItemLink)
205 }
206 }
207 })
208 } else {
209 filteredItems?.forEach((item) => {
210 const childItems: Sidebar.SidebarItemLink[] =
211 (getChildrenForLevel({ item })?.filter((childItem) => {
212 return isSidebarItemLink(childItem)
213 }) as Sidebar.SidebarItemLink[]) || []
214 searchableItems.push(...childItems)
215 })
216 }
217
218 return searchableItems
219 }, [filteredItems, onlyTopLevel, enableSearch])
220
221 useEffect(() => {
222 if (!enableSearch && localSearch) {
223 setLocalSearch(undefined)
224 return
225 }
226 if (!enableSearch || !searchableItems?.length || localSearch) {
227 return
228 }
229
230 setLocalSearch(
231 getLocalSearch<Sidebar.SidebarItemLink>({
232 docs: searchableItems,
233 searchableFields: ["title", "description"],
234 options: {
235 storeFields: ["title", "description", "path", "type"],
236 searchOptions: {
237 boost: { title: 2 },
238 prefix: true,
239 fuzzy: 0.2,
240 },
241 idField: "path",
242 },
243 })
244 )
245 }, [searchableItems, enableSearch, localSearch])
246
247 const searchResult = useMemo(() => {
248 return localSearch?.search(searchQuery) || []
249 }, [localSearch, searchQuery])
250
251 useEffect(() => {
252 if (!isBrowser || !enableSearch) {
253 return
254 }
255
256 const storedQuery = localStorage.getItem(`${storageKey}-query`)
257 if (storedQuery) {
258 setSearchQuery(storedQuery)
259 }
260 }, [isBrowser, storageKey, enableSearch])
261
262 useEffect(() => {
263 if (!isBrowser || !enableSearch) {
264 return
265 }
266
267 localStorage.setItem(`${storageKey}-query`, searchQuery)
268 }, [isBrowser, searchQuery, storageKey, enableSearch])
269
270 const getTopLevelElms = (items?: Sidebar.InteractiveSidebarItem[]) => {
271 const itemsToShow: {
272 [k: string]: Sidebar.InteractiveSidebarItem
273 } = {}
274 items?.forEach((childItem) => {
275 const href = isSidebarItemLink(childItem)
276 ? childItem.path
277 : childItem.type === "sidebar"
278 ? getSidebarFirstLinkChild(childItem)?.path
279 : (
280 childItem.children?.find((item) =>
281 isSidebarItemLink(item)
282 ) as Sidebar.SidebarItemLink
283 )?.path
284
285 if (!href) {
286 return
287 }
288
289 itemsToShow[href] = childItem
290 })
291 const itemsToShowEntries = Object.entries(itemsToShow)
292 if (!itemsToShowEntries.length) {
293 return <></>
294 }
295 return (
296 <CardList
297 items={itemsToShowEntries.map(([href, childItem]) => {
298 return {
299 title: childItem.title,
300 href,
301 rightIcon:
302 childItem.type === "ref" ? ChevronDoubleRight : undefined,
303 text: childItem.description,
304 }
305 })}
306 itemsPerRow={itemsPerRow}
307 defaultItemsPerRow={defaultItemsPerRow}
308 />
309 )
310 }
311
312 const getAllLevelsElms = ({
313 items,
314 headerLevel = titleLevel,
315 currentLevel = 1,
316 }: {
317 items?: Sidebar.InteractiveSidebarItem[]
318 headerLevel?: number
319 currentLevel?: number
320 }) => {
321 return items?.map((item, key) => {
322 const itemChildren = getChildrenForLevel({ item, currentLevel })
323 const HeadingComponent = itemChildren?.length
324 ? TitleHeaderComponent(headerLevel)
325 : undefined
326 const linkChildren =
327 itemChildren?.filter(
328 (item) => isSidebarItemLink(item) || item.type === "sidebar"
329 ) || []
330 const categoryChildren =
331 itemChildren?.filter(
332 (child) => child.type === "category" || child.type === "sub-category"
333 ) || []
334 const showLinkAsCard = !HeadingComponent && isSidebarItemLink(item)
335
336 return (
337 <React.Fragment key={key}>
338 {HeadingComponent && (
339 <>
340 {!hideTitle && (
341 <>
342 <HeadingComponent id={slugify(item.title.toLowerCase())}>
343 {item.title}
344 </HeadingComponent>
345 {!hideDescription && item.description && (
346 <MarkdownContent
347 allowedElements={["a", "code", "ul", "ol", "p"]}
348 >
349 {item.description}
350 </MarkdownContent>
351 )}
352 </>
353 )}
354 {linkChildren.length > 0 && (
355 <CardList
356 items={
357 linkChildren.map((childItem) => {
358 const href = isSidebarItemLink(childItem)
359 ? childItem.path
360 : getSidebarFirstLinkChild(
361 childItem as Sidebar.SidebarItemSidebar
362 )?.path
363 return {
364 title: childItem.title,
365 href,
366 text: childItem.description,
367 rightIcon:
368 childItem.type === "ref"
369 ? ChevronDoubleRight
370 : undefined,
371 }
372 }) || []
373 }
374 itemsPerRow={itemsPerRow}
375 defaultItemsPerRow={defaultItemsPerRow}
376 className="mb-docs_1"
377 />
378 )}
379 {categoryChildren.length > 0 &&
380 getAllLevelsElms({
381 items: categoryChildren,
382 headerLevel: headerLevel + 1,
383 currentLevel: currentLevel + 1,
384 })}
385 {key !== items.length - 1 && headerLevel === 2 && <Hr />}
386 </>
387 )}
388 {showLinkAsCard && (
389 <Card
390 title={item.title}
391 href={item.path}
392 text={item.description}
393 rightIcon={item.type === "ref" ? ChevronDoubleRight : undefined}
394 />
395 )}
396 </React.Fragment>
397 )
398 })
399 }
400
401 const getSearchResultElms = () => {
402 const Heading = TitleHeaderComponent(titleLevel)
403 return (
404 <>
405 <Heading>Search Results</Heading>
406 {searchResult.length > 0 && (
407 <CardList
408 items={searchResult.map((item) => ({
409 title: item.title,
410 href: item.path,
411 text: item.description,
412 rightIcon: item.type === "ref" ? ChevronDoubleRight : undefined,
413 highlightText: item.terms,
414 }))}
415 itemsPerRow={itemsPerRow}
416 defaultItemsPerRow={defaultItemsPerRow}
417 className="my-docs_2"
418 />
419 )}
420 {!searchResult.length && (
421 <div className="flex flex-col justify-center items-center gap-docs_0.75">
422 <ExclamationCircle className="text-medusa-fg-subtle" />
423 <span className="text-compact-small-plus text-medusa-fg-base text-center">
424 No results found matching your query.
425 </span>
426 <span className="text-compact-small text-medusa-fg-subtle text-center">
427 Try searching with another term or clearing the search.
428 </span>
429 </div>
430 )}
431 </>
432 )
433 }
434
435 const getElms = () => {
436 return (
437 <>
438 {enableSearch && (
439 <SearchInput
440 value={searchQuery || ""}
441 onChange={setSearchQuery}
442 {...searchProps}
443 />
444 )}
445 {searchQuery && getSearchResultElms()}
446 {!searchQuery && (
447 <>
448 {onlyTopLevel
449 ? getTopLevelElms(filteredItems)
450 : getAllLevelsElms({
451 items: filteredItems,
452 })}
453 </>
454 )}
455 </>
456 )
457 }
458
459 return {
460 items: filteredItems,
461 component: getElms(),
462 }
463 }