Raw
1 "use client"
2
3 import React, {
4 createContext,
5 useCallback,
6 useContext,
7 useEffect,
8 useMemo,
9 useReducer,
10 useRef,
11 useState,
12 } from "react"
13 import { Sidebar } from "types"
14 import {
15 areSidebarItemsEqual,
16 findSidebarItem,
17 getSidebarItemWithHistory,
18 isSidebarItemLink,
19 } from "../../utils/sidebar-utils"
20 import { useSiteConfig } from "../SiteConfig"
21 import { useIsBrowser } from "../BrowserProvider"
22 import { getScrolledTop } from "../../utils/get-scrolled-top"
23 import { usePathname, useRouter } from "next/navigation"
24
25 export type SidebarActionOptions = {
26 sidebar_id: string
27 /**
28 * When specified, the items are added as children of the parent item
29 */
30 parent?: {
31 type: Sidebar.InteractiveSidebarItemTypes
32 path: string
33 title: string
34 /**
35 * Whether to change the loaded state of the parent item
36 */
37 changeLoaded?: boolean
38 }
39 /**
40 * The position to insert the items at
41 */
42 indexPosition?: number
43 /**
44 * If enabled, the items are filtered to not add items that already exist
45 */
46 ignoreExisting?: boolean
47 }
48
49 export type SidebarStyleOptions = {
50 /**
51 * Useful for projects that have nested sidebars.
52 */
53 disableActiveTransition?: boolean
54 }
55
56 export type UpdateSidebarItemTypes =
57 | Partial<Pick<Sidebar.SidebarItemLink, "path" | "title" | "additionalElms">>
58 | Partial<
59 Pick<
60 Sidebar.SidebarItemCategory,
61 "title" | "loaded" | "onOpen" | "children"
62 >
63 >
64 | Partial<Pick<Sidebar.SidebarItemSidebar, "title" | "children">>
65
66 export type UpdateActionType = {
67 sidebar_id: string
68 items: {
69 existingItem: Sidebar.SidebarItem
70 newItem: UpdateSidebarItemTypes
71 options?: {
72 setChildrenBehavior: "replace" | "merge"
73 }
74 }[]
75 }
76
77 export type SidebarContextType = {
78 sidebars: Sidebar.Sidebar[]
79 /**
80 * The sidebar that is currently shown
81 */
82 shownSidebar: Sidebar.Sidebar | Sidebar.SidebarItemSidebar | undefined
83 activePath: string | null
84 activeItem: Sidebar.SidebarItemLink | null
85 setActivePath: (path: string | null) => void
86 /**
87 * Check if an item is active. This includes checking its child items,
88 * so for UI links that have children, the `checkLinkChildren` option should be set to `false`
89 * to ensure that the link isn't shown as active if a child link is active.
90 */
91 isItemActive: (options: {
92 item: Sidebar.InteractiveSidebarItem
93 checkLinkChildren?: boolean
94 }) => boolean
95 addItems: (
96 items: Sidebar.SidebarItem[],
97 options?: SidebarActionOptions
98 ) => void
99 updateItems: (options: UpdateActionType) => void
100 removeItems: (options: {
101 items: Sidebar.SidebarItem[]
102 sidebar_id: string
103 }) => void
104 mobileSidebarOpen: boolean
105 setMobileSidebarOpen: React.Dispatch<React.SetStateAction<boolean>>
106 desktopSidebarOpen: boolean
107 setDesktopSidebarOpen: React.Dispatch<React.SetStateAction<boolean>>
108 // Whether the items in the sidebar are static or are added dynamically
109 // TODO look into generating the sidebar item of the API reference
110 isSidebarStatic: boolean
111 /**
112 * Whether the active path should change when the hash changes
113 * This is only used by the API reference
114 */
115 shouldHandleHashChange: boolean
116 sidebarRef: React.RefObject<HTMLDivElement | null>
117 /**
118 * Go back in the sidebar history
119 */
120 goBack: () => void
121 /**
122 * The height of the top part of the sidebar
123 */
124 sidebarTopHeight: number
125 setSidebarTopHeight: React.Dispatch<React.SetStateAction<number>>
126 /**
127 * Reset the sidebar to its initial state (the sidebars passed as a prop)
128 */
129 resetItems: () => void
130 updatePersistedCategoryState: (title: string, opened: boolean) => void
131 getPersistedCategoryState: (title: string) => boolean | undefined
132 persistCategoryState: boolean
133 isSidebarShown: boolean
134 sidebarHistory: string[]
135 /**
136 * Get the first link child of a sidebar
137 */
138 getSidebarFirstLinkChild: (
139 sidebar: Sidebar.Sidebar | Sidebar.SidebarItemSidebar
140 ) => Sidebar.SidebarItemLink | undefined
141 getSidebar: (
142 sidebar_id: string
143 ) => Sidebar.Sidebar | Sidebar.SidebarItemSidebar
144 } & SidebarStyleOptions
145
146 export const SidebarContext = createContext<SidebarContextType | null>(null)
147
148 export type ActionType =
149 | {
150 type: "add" | "update-child"
151 items: Sidebar.SidebarItem[]
152 options?: SidebarActionOptions
153 }
154 | {
155 type: "replace"
156 sidebars: Sidebar.Sidebar[]
157 }
158 | {
159 type: "remove"
160 items: Sidebar.SidebarItem[]
161 sidebar_id: string
162 }
163 | ({
164 type: "update"
165 } & UpdateActionType)
166
167 export const reducer = (
168 state: Sidebar.Sidebar[],
169 actionData: ActionType
170 ): Sidebar.Sidebar[] => {
171 switch (actionData.type) {
172 case "replace":
173 return actionData.sidebars
174 case "remove": {
175 const { sidebar_id, items: itemsToRemove } = actionData
176 return state.map((sidebar) => {
177 if (sidebar.sidebar_id === sidebar_id) {
178 return {
179 ...sidebar,
180 items: sidebar.items.filter((item) => {
181 return !itemsToRemove.some((itemToRemove) =>
182 areSidebarItemsEqual({
183 itemA: item,
184 itemB: itemToRemove,
185 })
186 )
187 }),
188 }
189 }
190 return sidebar
191 })
192 }
193 case "update":
194 return state.map((sidebar) => {
195 if (sidebar.sidebar_id === actionData.sidebar_id) {
196 return {
197 ...sidebar,
198 items: sidebar.items.map((item) => {
199 const itemToUpdate = actionData.items.find((i) =>
200 areSidebarItemsEqual({
201 itemA: item,
202 itemB: i.existingItem,
203 })
204 )
205 if (itemToUpdate) {
206 const updatedItem = {
207 ...item,
208 ...itemToUpdate.newItem,
209 } as Sidebar.SidebarItem
210
211 if ("children" in updatedItem) {
212 updatedItem.children =
213 itemToUpdate.options?.setChildrenBehavior === "merge"
214 ? [
215 ...((item as Sidebar.InteractiveSidebarItem)
216 .children || []),
217 ...(updatedItem.children || []),
218 ]
219 : updatedItem.children
220 }
221
222 return updatedItem
223 }
224 return item
225 }),
226 }
227 }
228 return sidebar
229 })
230 }
231
232 const { type, options } = actionData
233 let { items } = actionData
234
235 const { parent, ignoreExisting = false, indexPosition } = options || {}
236 const sidebarIndex = state.findIndex(
237 (s) => s.sidebar_id === options?.sidebar_id
238 )
239 const sidebar = state[sidebarIndex]
240
241 if (!sidebar) {
242 return state
243 }
244
245 if (!ignoreExisting) {
246 items = items.filter(
247 (item) =>
248 findSidebarItem({ sidebarItems: sidebar.items, item }) === undefined
249 )
250 }
251
252 if (!items.length) {
253 return state
254 }
255
256 switch (type) {
257 case "add":
258 return [
259 ...state.slice(0, sidebarIndex),
260 {
261 ...sidebar,
262 items:
263 indexPosition !== undefined
264 ? [
265 ...sidebar.items.slice(0, indexPosition),
266 ...items,
267 ...sidebar.items.slice(indexPosition),
268 ]
269 : [...sidebar.items, ...items],
270 },
271 ...state.slice(sidebarIndex + 1),
272 ]
273 case "update-child":
274 // find item index
275 return [
276 ...state.slice(0, sidebarIndex),
277 {
278 ...sidebar,
279 items: sidebar.items.map((i) => {
280 if (i.type === "separator") {
281 return i
282 }
283 if (
284 parent &&
285 areSidebarItemsEqual({
286 itemA: i,
287 itemB: parent as Sidebar.InteractiveSidebarItem,
288 })
289 ) {
290 return {
291 ...i,
292 children:
293 indexPosition !== undefined
294 ? [
295 ...(i.children?.slice(0, indexPosition) || []),
296 ...items,
297 ...(i.children?.slice(indexPosition) || []),
298 ]
299 : [...(i.children || []), ...items],
300 loaded: parent.changeLoaded
301 ? true
302 : isSidebarItemLink(i)
303 ? i.loaded
304 : true,
305 }
306 }
307 return i
308 }),
309 },
310 ...state.slice(sidebarIndex + 1),
311 ]
312 default:
313 return state
314 }
315 }
316
317 export type SidebarProviderProps = {
318 children?: React.ReactNode
319 isLoading?: boolean
320 setIsLoading?: React.Dispatch<React.SetStateAction<boolean>>
321 sidebars: Sidebar.Sidebar[]
322 shouldHandleHashChange?: boolean
323 shouldHandlePathChange?: boolean
324 scrollableElement?: Element | Window
325 isSidebarStatic?: boolean
326 persistCategoryState?: boolean
327 disableActiveTransition?: boolean
328 } & SidebarStyleOptions
329
330 export const SidebarProvider = ({
331 children,
332 isLoading,
333 setIsLoading,
334 sidebars: initialSidebars = [],
335 shouldHandleHashChange = false,
336 shouldHandlePathChange = true,
337 scrollableElement,
338 isSidebarStatic = true,
339 persistCategoryState = true,
340 disableActiveTransition = true,
341 }: SidebarProviderProps) => {
342 const {
343 config: { project },
344 } = useSiteConfig()
345 const categoriesStorageKey = `${project.title}_categories`
346 const hideSidebarStorageKey = `hide_sidebar`
347 const [sidebars, dispatch] = useReducer(reducer, initialSidebars)
348 const [activePath, setActivePath] = useState<string | null>("")
349 const [mobileSidebarOpen, setMobileSidebarOpen] = useState<boolean>(false)
350 const [desktopSidebarOpen, setDesktopSidebarOpen] = useState(true)
351 const sidebarRef = useRef<HTMLDivElement>(null)
352 const [sidebarTopHeight, setSidebarTopHeight] = useState(0)
353
354 const pathname = usePathname()
355 const router = useRouter()
356 const { isBrowser } = useIsBrowser()
357
358 const resolvedScrollableElement = useMemo(() => {
359 if (!isBrowser) {
360 return
361 }
362
363 return scrollableElement || window
364 }, [scrollableElement, isBrowser])
365
366 const activeMainSidebar = useMemo(() => {
367 if (!activePath || sidebars.length === 1) {
368 // set first sidebar as active
369 return sidebars[0]
370 }
371 return (
372 sidebars.find(
373 (s) =>
374 findSidebarItem({
375 sidebarItems: s.items,
376 item: { type: "link", path: activePath, title: "" },
377 compareTitles: false,
378 }) !== undefined
379 ) || sidebars[0]
380 )
381 }, [sidebars, activePath])
382
383 const { activeItem, sidebarHistory } = useMemo(() => {
384 if (!activePath) {
385 return {
386 activeItem: null,
387 sidebarHistory: [] as string[],
388 }
389 }
390 const result =
391 getSidebarItemWithHistory({
392 sidebarItems: activeMainSidebar.items,
393 item: { type: "link", path: activePath, title: "" },
394 compareTitles: false,
395 }) || null
396
397 return {
398 ...result,
399 sidebarHistory: [
400 activeMainSidebar.sidebar_id,
401 ...(result.sidebarHistory || []),
402 ],
403 activeItem: (result.item as Sidebar.SidebarItemLink) || null,
404 }
405 }, [activePath, activeMainSidebar])
406
407 const getSidebar = useCallback(
408 (sidebar_id: string) => {
409 return (
410 sidebars.find((s) => s.sidebar_id === sidebar_id) ||
411 (findSidebarItem({
412 sidebarItems: activeMainSidebar.items || [],
413 item: { type: "sidebar", sidebar_id, title: "" },
414 compareTitles: false,
415 }) as Sidebar.SidebarItemSidebar)
416 )
417 },
418 [sidebars, activeMainSidebar]
419 )
420
421 const shownSidebar = useMemo(() => {
422 if (!sidebarHistory.length) {
423 return sidebars.length === 1 ? sidebars[0] : undefined
424 }
425
426 return getSidebar(sidebarHistory[sidebarHistory.length - 1])
427 }, [activeMainSidebar, sidebarHistory, getSidebar])
428
429 const isItemActive: SidebarContextType["isItemActive"] = useCallback(
430 ({ item, checkLinkChildren = true }): boolean => {
431 if (!activePath) {
432 return false
433 }
434
435 // a link — or a category with its own path (e.g. an API-ref tag) —
436 // matches directly when its path equals the active path
437 if ("path" in item && item.path === activePath) {
438 return true
439 }
440
441 if (isSidebarItemLink(item) && !checkLinkChildren) {
442 return false
443 }
444
445 return (
446 item.children?.some((child) => {
447 if (child.type === "separator") {
448 return false
449 }
450
451 return isItemActive({
452 item: child as Sidebar.InteractiveSidebarItem,
453 checkLinkChildren,
454 })
455 }) || false
456 )
457 },
458 [activePath]
459 )
460
461 const isSidebarShown = useMemo(() => {
462 if (!isBrowser) {
463 return true
464 }
465
466 return document.getElementsByTagName("aside").length > 0
467 }, [isBrowser])
468
469 const addItems = (
470 newItems: Sidebar.SidebarItem[],
471 options?: SidebarActionOptions
472 ) => {
473 dispatch({
474 type: options?.parent ? "update-child" : "add",
475 items: newItems,
476 options,
477 })
478 }
479
480 const updateItems = ({ sidebar_id, items }: UpdateActionType) => {
481 dispatch({
482 type: "update",
483 items,
484 sidebar_id,
485 })
486 }
487
488 const removeItems = ({
489 items,
490 sidebar_id,
491 }: {
492 items: Sidebar.SidebarItem[]
493 sidebar_id: string
494 }) => {
495 dispatch({
496 type: "remove",
497 items,
498 sidebar_id,
499 })
500 }
501
502 const resetItems = useCallback(() => {
503 dispatch({
504 type: "replace",
505 sidebars: initialSidebars,
506 })
507 }, [initialSidebars])
508
509 const init = () => {
510 const currentPath = location.hash.replace("#", "")
511 if (currentPath) {
512 setActivePath(currentPath)
513 } else {
514 const firstChild = getFirstLinkChild(activeMainSidebar.items)
515
516 if (firstChild) {
517 setActivePath(firstChild.path)
518 }
519 }
520 }
521
522 useEffect(() => {
523 if (shouldHandleHashChange) {
524 init()
525 }
526 }, [shouldHandleHashChange])
527
528 const handleScroll = useCallback(() => {
529 const scrolledTop = getScrolledTop(resolvedScrollableElement)
530 // account for navbar height
531 if (scrolledTop >= 0 && scrolledTop <= 56) {
532 const firstChild = getFirstLinkChild(activeMainSidebar.items)
533
534 if (firstChild) {
535 setActivePath(firstChild.path)
536 router.push(`#${firstChild.path}`, {
537 scroll: false,
538 })
539 }
540 }
541 }, [activeMainSidebar, resolvedScrollableElement])
542
543 useEffect(() => {
544 if (!shouldHandleHashChange || !resolvedScrollableElement) {
545 return
546 }
547
548 resolvedScrollableElement.addEventListener("scroll", handleScroll)
549
550 return () => {
551 resolvedScrollableElement.removeEventListener("scroll", handleScroll)
552 }
553 }, [shouldHandleHashChange, resolvedScrollableElement, handleScroll])
554
555 useEffect(() => {
556 if (!shouldHandleHashChange || !isBrowser) {
557 return
558 }
559
560 // this is mainly triggered by Algolia
561 const handleHashChange = () => {
562 const currentPath = location.hash.replace("#", "")
563 if (currentPath !== activePath) {
564 setActivePath(currentPath)
565 }
566 }
567
568 window.addEventListener("hashchange", handleHashChange)
569
570 return () => {
571 window.removeEventListener("hashchange", handleHashChange)
572 }
573 }, [shouldHandleHashChange, isBrowser])
574
575 useEffect(() => {
576 if (isLoading && sidebars.length) {
577 setIsLoading?.(false)
578 }
579 }, [sidebars, isLoading, setIsLoading])
580
581 useEffect(() => {
582 if (!shouldHandlePathChange) {
583 return
584 }
585
586 if (pathname !== activePath) {
587 setActivePath(pathname)
588 }
589 }, [shouldHandlePathChange, pathname])
590
591 useEffect(() => {
592 if (!isBrowser) {
593 return
594 }
595
596 const storageValue = localStorage.getItem(hideSidebarStorageKey)
597
598 if (storageValue !== null) {
599 setDesktopSidebarOpen(storageValue === "false")
600 }
601 }, [isBrowser])
602
603 useEffect(() => {
604 if (!isBrowser) {
605 return
606 }
607
608 localStorage.setItem(
609 hideSidebarStorageKey,
610 `${desktopSidebarOpen === false}`
611 )
612 }, [isBrowser, desktopSidebarOpen])
613
614 useEffect(() => {
615 if (initialSidebars[0].sidebar_id !== sidebars[0].sidebar_id) {
616 resetItems()
617 }
618 }, [initialSidebars])
619
620 const updatePersistedCategoryState = (title: string, opened: boolean) => {
621 const storageData = JSON.parse(
622 localStorage.getItem(categoriesStorageKey) || "{}"
623 )
624 if (!Object.hasOwn(storageData, project.title)) {
625 storageData[project.title] = {}
626 }
627
628 storageData[project.title] = {
629 ...storageData[project.title],
630 [title]: opened,
631 }
632
633 localStorage.setItem(categoriesStorageKey, JSON.stringify(storageData))
634 }
635
636 const getPersistedCategoryState = (title: string): boolean | undefined => {
637 const storageData = JSON.parse(
638 localStorage.getItem(categoriesStorageKey) || "{}"
639 )
640
641 return !Object.hasOwn(storageData, project.title) ||
642 !Object.hasOwn(storageData[project.title], title)
643 ? undefined
644 : storageData[project.title][title]
645 }
646
647 const getFirstLinkChild = useCallback(
648 (items: Sidebar.SidebarItem[]): Sidebar.SidebarItemLink | undefined => {
649 let foundItem: Sidebar.SidebarItemLink | undefined
650 items.some((item) => {
651 if (item.type === "link") {
652 foundItem = item
653 } else if ("children" in item && item.children) {
654 foundItem = getFirstLinkChild(item.children)
655 }
656
657 return foundItem !== undefined
658 })
659
660 return foundItem
661 },
662 []
663 )
664
665 const getSidebarFirstLinkChild = useCallback(
666 (
667 sidebar: Sidebar.Sidebar | Sidebar.SidebarItemSidebar
668 ): Sidebar.SidebarItemLink | undefined => {
669 const itemsToSearch =
670 "items" in sidebar ? sidebar.items : sidebar.children || []
671
672 return getFirstLinkChild(itemsToSearch)
673 },
674 [getFirstLinkChild]
675 )
676
677 const openSidebar = (sidebar_id: string) => {
678 const sidebar = getSidebar(sidebar_id)
679 if (!sidebar) {
680 return
681 }
682
683 const firstChild = getSidebarFirstLinkChild(sidebar)
684
685 if (firstChild) {
686 setActivePath(firstChild.path)
687 router.replace(firstChild.path)
688 }
689 }
690
691 const goBack = () => {
692 if (!sidebarHistory || sidebarHistory.length <= 1) {
693 openSidebar(activeMainSidebar.sidebar_id)
694 } else {
695 const lastSidebar = sidebarHistory[sidebarHistory.length - 2]
696
697 openSidebar(lastSidebar)
698 }
699 }
700
701 return (
702 <SidebarContext.Provider
703 value={{
704 sidebars,
705 shownSidebar,
706 activePath,
707 activeItem,
708 setActivePath,
709 isItemActive,
710 addItems,
711 updateItems,
712 removeItems,
713 mobileSidebarOpen,
714 setMobileSidebarOpen,
715 desktopSidebarOpen,
716 setDesktopSidebarOpen,
717 isSidebarStatic,
718 shouldHandleHashChange,
719 sidebarRef,
720 goBack,
721 sidebarTopHeight,
722 setSidebarTopHeight,
723 resetItems,
724 updatePersistedCategoryState,
725 getPersistedCategoryState,
726 persistCategoryState,
727 isSidebarShown,
728 sidebarHistory,
729 getSidebarFirstLinkChild,
730 getSidebar,
731 disableActiveTransition,
732 }}
733 >
734 {children}
735 </SidebarContext.Provider>
736 )
737 }
738
739 export const useSidebar = (): SidebarContextType => {
740 const context = useContext(SidebarContext)
741
742 if (!context) {
743 throw new Error("useSidebar must be used inside a SidebarProvider")
744 }
745
746 return context
747 }