api-ref: added syncing between code tabs (#4786)
* api-ref: added syncing between code tabs * updated comment * resolve metadata warning * fix colors
This commit is contained in:
@@ -10,6 +10,7 @@ import { Roboto_Mono } from "next/font/google"
|
||||
import AnalyticsProvider from "@/providers/analytics"
|
||||
import NavbarProvider from "@/providers/navbar"
|
||||
import ModalProvider from "../../../providers/modal"
|
||||
import { ScrollControllerProvider } from "../../../hooks/scroll-utils"
|
||||
|
||||
export const metadata = {
|
||||
title: "Medusa API Reference",
|
||||
@@ -48,15 +49,17 @@ export default function RootLayout({
|
||||
<BaseSpecsProvider>
|
||||
<SidebarProvider>
|
||||
<NavbarProvider>
|
||||
<div className="w-full">
|
||||
<Navbar />
|
||||
<div className="max-w-xxl mx-auto flex w-full px-1.5">
|
||||
<Sidebar />
|
||||
<main className="lg:w-api-ref-main relative mt-4 w-full flex-1 lg:mt-7">
|
||||
{children}
|
||||
</main>
|
||||
<ScrollControllerProvider>
|
||||
<div className="w-full">
|
||||
<Navbar />
|
||||
<div className="max-w-xxl mx-auto flex w-full px-1.5">
|
||||
<Sidebar />
|
||||
<main className="lg:w-api-ref-main relative mt-4 w-full flex-1 lg:mt-7">
|
||||
{children}
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</ScrollControllerProvider>
|
||||
</NavbarProvider>
|
||||
</SidebarProvider>
|
||||
</BaseSpecsProvider>
|
||||
|
||||
@@ -47,6 +47,7 @@ export function generateMetadata({ params: { area } }: ReferencePageProps) {
|
||||
return {
|
||||
title: `Medusa ${capitalize(area)} API Reference`,
|
||||
description: `REST API reference for the Medusa ${area} API. This reference includes code snippets and examples for Medusa JS Client and cURL.`,
|
||||
metadataBase: process.env.NEXT_PUBLIC_BASE_URL,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ const Card = ({ title, text, href, className }: CardProps) => {
|
||||
return (
|
||||
<div
|
||||
className={clsx(
|
||||
"bg-medusa-bg-subtle dark:bg-medusa-bg-subtle-dark w-full rounded",
|
||||
"bg-medusa-bg-subtle dark:bg-medusa-code-bg-base-dark w-full rounded",
|
||||
"shadow-card-rest dark:shadow-card-rest-dark py-0.75 relative px-1",
|
||||
"flex items-center justify-between gap-1 transition-shadow",
|
||||
href && "hover:shadow-card-hover dark:hover:shadow-card-hover-dark",
|
||||
|
||||
@@ -37,7 +37,7 @@ const CodeBlock = ({
|
||||
...themes.vsDark,
|
||||
plain: {
|
||||
...themes.vsDark.plain,
|
||||
backgroundColor: colorMode === "light" ? "#111827" : "#1B1B1B",
|
||||
backgroundColor: colorMode === "light" ? "#111827" : "#1E1E1E",
|
||||
},
|
||||
}}
|
||||
code={source.trim()}
|
||||
|
||||
@@ -1,26 +1,32 @@
|
||||
"use client"
|
||||
|
||||
import clsx from "clsx"
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react"
|
||||
import { useCallback, useEffect, useMemo, useRef } from "react"
|
||||
import CodeBlock, { CodeBlockProps } from "../CodeBlock"
|
||||
import useTabs, { BaseTabType } from "../../hooks/use-tabs"
|
||||
import { useScrollPositionBlocker } from "../../hooks/scroll-utils"
|
||||
|
||||
type TabType = {
|
||||
label: string
|
||||
value: string
|
||||
code?: CodeBlockProps
|
||||
codeBlock?: React.ReactNode
|
||||
}
|
||||
} & BaseTabType
|
||||
|
||||
type CodeTabsProps = {
|
||||
tabs: TabType[]
|
||||
className?: string
|
||||
group?: string
|
||||
}
|
||||
|
||||
const CodeTabs = ({ tabs, className }: CodeTabsProps) => {
|
||||
const [selectedTab, setSelectedTab] = useState(tabs[0])
|
||||
const CodeTabs = ({ tabs, className, group = "client" }: CodeTabsProps) => {
|
||||
const { selectedTab, changeSelectedTab } = useTabs<TabType>({
|
||||
tabs,
|
||||
group,
|
||||
})
|
||||
const tabRefs: (HTMLButtonElement | null)[] = useMemo(() => [], [])
|
||||
const codeTabSelectorRef = useRef<HTMLSpanElement | null>(null)
|
||||
const codeTabsWrapperRef = useRef<HTMLDivElement | null>(null)
|
||||
const { blockElementScrollPositionUntilNextRender } =
|
||||
useScrollPositionBlocker()
|
||||
|
||||
const changeTabSelectorCoordinates = useCallback(
|
||||
(selectedTabElm: HTMLElement) => {
|
||||
@@ -79,18 +85,21 @@ const CodeTabs = ({ tabs, className }: CodeTabsProps) => {
|
||||
<button
|
||||
className={clsx(
|
||||
"text-compact-small-plus xs:border-0 py-0.25 px-0.75 relative z-[2] rounded-full border",
|
||||
selectedTab.value !== tab.value &&
|
||||
(!selectedTab || selectedTab.value !== tab.value) && [
|
||||
"text-medusa-code-text-subtle dark:text-medusa-code-text-subtle-dark border-transparent",
|
||||
selectedTab.value === tab.value &&
|
||||
"text-medusa-code-text-base dark:text-medusa-code-text-base-dark bg-medusa-code-bg-base dark:bg-medusa-code-bg-base-dark xs:!bg-transparent",
|
||||
selectedTab.value !== tab.value &&
|
||||
"hover:bg-medusa-code-bg-base dark:hover:bg-medusa-code-bg-base-dark"
|
||||
"hover:bg-medusa-code-bg-base dark:hover:bg-medusa-code-bg-base-dark",
|
||||
],
|
||||
selectedTab?.value === tab.value &&
|
||||
"text-medusa-code-text-base dark:text-medusa-code-text-base-dark bg-medusa-code-bg-base dark:bg-medusa-code-bg-base-dark xs:!bg-transparent"
|
||||
)}
|
||||
ref={(tabControl) => tabRefs.push(tabControl)}
|
||||
onClick={() => {
|
||||
setSelectedTab(tab)
|
||||
onClick={(e) => {
|
||||
blockElementScrollPositionUntilNextRender(
|
||||
e.target as HTMLButtonElement
|
||||
)
|
||||
changeSelectedTab(tab)
|
||||
}}
|
||||
aria-selected={selectedTab.value === tab.value}
|
||||
aria-selected={selectedTab?.value === tab.value}
|
||||
role="tab"
|
||||
>
|
||||
{tab.label}
|
||||
@@ -99,16 +108,16 @@ const CodeTabs = ({ tabs, className }: CodeTabsProps) => {
|
||||
))}
|
||||
</ul>
|
||||
<>
|
||||
{selectedTab.code && (
|
||||
{selectedTab?.code && (
|
||||
<CodeBlock
|
||||
{...selectedTab.code}
|
||||
{...selectedTab?.code}
|
||||
className={clsx(
|
||||
"!mt-0 !rounded-t-none",
|
||||
selectedTab.code.className
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
{selectedTab.codeBlock && <>{selectedTab.codeBlock}</>}
|
||||
{selectedTab?.codeBlock && <>{selectedTab.codeBlock}</>}
|
||||
</>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -28,13 +28,15 @@ const TagOperationCodeSection = ({
|
||||
<div className={clsx("mt-2 flex flex-col gap-2", className)}>
|
||||
<div
|
||||
className={clsx(
|
||||
"bg-medusa-code-bg-base dark:bg-medusa-code-bg-base-dark border-medusa-border-base dark:border-medusa-border-base-dark px-0.75 rounded border py-0.5",
|
||||
"bg-medusa-bg-subtle dark:bg-medusa-code-bg-base-dark border-medusa-border-base dark:border-medusa-border-base-dark px-0.75 rounded border py-0.5",
|
||||
"text-code-body flex w-full justify-between gap-1"
|
||||
)}
|
||||
>
|
||||
<div className={clsx("flex w-[calc(100%-36px)] gap-1")}>
|
||||
<MethodLabel method={method} className="h-fit" />
|
||||
<code className="break-words break-all">{endpointPath}</code>
|
||||
<code className="text-medusa-fg-subtle dark:text-medusa-code-text-base-dark break-words break-all">
|
||||
{endpointPath}
|
||||
</code>
|
||||
</div>
|
||||
<CopyButton text={endpointPath} tooltipClassName="font-base">
|
||||
<IconCopyOutline iconColorClassName="stroke-medusa-fg-muted dark:stroke-medusa-fg-muted-dark" />
|
||||
|
||||
@@ -0,0 +1,332 @@
|
||||
"use client"
|
||||
|
||||
/* Copied from Docusaurus to maintain scroll position on re-renders. Useful when content of the page is updated dynamically */
|
||||
|
||||
/**
|
||||
* Copyright (c) Facebook, Inc. and its affiliates.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import React, {
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useLayoutEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
type ReactNode,
|
||||
} from "react"
|
||||
|
||||
type EventFunc = (...args: never[]) => unknown
|
||||
|
||||
export function useEvent<T extends EventFunc>(callback: T): T {
|
||||
const ref = useRef<T>(callback)
|
||||
|
||||
useLayoutEffect(() => {
|
||||
ref.current = callback
|
||||
}, [callback])
|
||||
|
||||
// @ts-expect-error: TS is right that this callback may be a supertype of T,
|
||||
// but good enough for our use
|
||||
return useCallback<T>((...args) => ref.current(...args), [])
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets `value` from the last render.
|
||||
*/
|
||||
export function usePrevious<T>(value: T): T | undefined {
|
||||
const ref = useRef<T>()
|
||||
|
||||
useLayoutEffect(() => {
|
||||
ref.current = value
|
||||
})
|
||||
|
||||
return ref.current
|
||||
}
|
||||
|
||||
type ScrollController = {
|
||||
/** A boolean ref tracking whether scroll events are enabled. */
|
||||
scrollEventsEnabledRef: React.MutableRefObject<boolean>
|
||||
/** Enable scroll events in `useScrollPosition`. */
|
||||
enableScrollEvents: () => void
|
||||
/** Disable scroll events in `useScrollPosition`. */
|
||||
disableScrollEvents: () => void
|
||||
}
|
||||
|
||||
function useScrollControllerContextValue(): ScrollController {
|
||||
const scrollEventsEnabledRef = useRef(true)
|
||||
|
||||
return useMemo(
|
||||
() => ({
|
||||
scrollEventsEnabledRef,
|
||||
enableScrollEvents: () => {
|
||||
scrollEventsEnabledRef.current = true
|
||||
},
|
||||
disableScrollEvents: () => {
|
||||
scrollEventsEnabledRef.current = false
|
||||
},
|
||||
}),
|
||||
[]
|
||||
)
|
||||
}
|
||||
|
||||
const ScrollMonitorContext = React.createContext<ScrollController | undefined>(
|
||||
undefined
|
||||
)
|
||||
|
||||
export function ScrollControllerProvider({
|
||||
children,
|
||||
}: {
|
||||
children: ReactNode
|
||||
}): JSX.Element {
|
||||
const value = useScrollControllerContextValue()
|
||||
return (
|
||||
<ScrollMonitorContext.Provider value={value}>
|
||||
{children}
|
||||
</ScrollMonitorContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* We need a way to update the scroll position while ignoring scroll events
|
||||
* so as not to toggle Navbar/BackToTop visibility.
|
||||
*
|
||||
* This API permits to temporarily disable/ignore scroll events. Motivated by
|
||||
* https://github.com/facebook/docusaurus/pull/5618
|
||||
*/
|
||||
export function useScrollController(): ScrollController {
|
||||
const context = useContext(ScrollMonitorContext)
|
||||
if (context == null) {
|
||||
throw new Error(
|
||||
`useScrollController must be used by elements in ScrollControllerProvider`
|
||||
)
|
||||
}
|
||||
return context
|
||||
}
|
||||
|
||||
type ScrollPosition = { scrollX: number; scrollY: number }
|
||||
|
||||
const getScrollPosition = (): ScrollPosition | null => ({
|
||||
scrollX: window.pageXOffset,
|
||||
scrollY: window.pageYOffset,
|
||||
})
|
||||
|
||||
/**
|
||||
* This hook fires an effect when the scroll position changes. The effect will
|
||||
* be provided with the before/after scroll positions. Note that the effect may
|
||||
* not be always run: if scrolling is disabled through `useScrollController`, it
|
||||
* will be a no-op.
|
||||
*
|
||||
* @see {@link useScrollController}
|
||||
*/
|
||||
export function useScrollPosition(
|
||||
effect: (
|
||||
position: ScrollPosition,
|
||||
lastPosition: ScrollPosition | null
|
||||
) => void,
|
||||
deps: unknown[] = []
|
||||
): void {
|
||||
const { scrollEventsEnabledRef } = useScrollController()
|
||||
const lastPositionRef = useRef<ScrollPosition | null>(getScrollPosition())
|
||||
|
||||
const dynamicEffect = useEvent(effect)
|
||||
|
||||
useEffect(() => {
|
||||
const handleScroll = () => {
|
||||
if (!scrollEventsEnabledRef.current) {
|
||||
return
|
||||
}
|
||||
const currentPosition = getScrollPosition()!
|
||||
dynamicEffect(currentPosition, lastPositionRef.current)
|
||||
lastPositionRef.current = currentPosition
|
||||
}
|
||||
|
||||
const opts: AddEventListenerOptions & EventListenerOptions = {
|
||||
passive: true,
|
||||
}
|
||||
|
||||
handleScroll()
|
||||
window.addEventListener("scroll", handleScroll, opts)
|
||||
|
||||
return () => window.removeEventListener("scroll", handleScroll, opts)
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [dynamicEffect, scrollEventsEnabledRef, ...deps])
|
||||
}
|
||||
|
||||
type UseScrollPositionSaver = {
|
||||
/** Measure the top of an element, and store the details. */
|
||||
save: (elem: HTMLElement) => void
|
||||
/**
|
||||
* Restore the page position to keep the stored element's position from
|
||||
* the top of the viewport, and remove the stored details.
|
||||
*/
|
||||
restore: () => { restored: boolean }
|
||||
}
|
||||
|
||||
function useScrollPositionSaver(): UseScrollPositionSaver {
|
||||
const lastElementRef = useRef<{ elem: HTMLElement | null; top: number }>({
|
||||
elem: null,
|
||||
top: 0,
|
||||
})
|
||||
|
||||
const save = useCallback((elem: HTMLElement) => {
|
||||
lastElementRef.current = {
|
||||
elem,
|
||||
top: elem.getBoundingClientRect().top,
|
||||
}
|
||||
}, [])
|
||||
|
||||
const restore = useCallback(() => {
|
||||
const {
|
||||
current: { elem, top },
|
||||
} = lastElementRef
|
||||
if (!elem) {
|
||||
return { restored: false }
|
||||
}
|
||||
const newTop = elem.getBoundingClientRect().top
|
||||
const heightDiff = newTop - top
|
||||
if (heightDiff) {
|
||||
window.scrollBy({ left: 0, top: heightDiff })
|
||||
}
|
||||
lastElementRef.current = { elem: null, top: 0 }
|
||||
|
||||
return { restored: heightDiff !== 0 }
|
||||
}, [])
|
||||
|
||||
return useMemo(() => ({ save, restore }), [restore, save])
|
||||
}
|
||||
|
||||
/**
|
||||
* This hook permits to "block" the scroll position of a DOM element.
|
||||
* The idea is that we should be able to update DOM content above this element
|
||||
* but the screen position of this element should not change.
|
||||
*
|
||||
* Feature motivated by the Tabs groups: clicking on a tab may affect tabs of
|
||||
* the same group upper in the tree, yet to avoid a bad UX, the clicked tab must
|
||||
* remain under the user mouse.
|
||||
*
|
||||
* @see https://github.com/facebook/docusaurus/pull/5618
|
||||
*/
|
||||
export function useScrollPositionBlocker(): {
|
||||
/**
|
||||
* Takes an element, and keeps its screen position no matter what's getting
|
||||
* rendered above it, until the next render.
|
||||
*/
|
||||
blockElementScrollPositionUntilNextRender: (el: HTMLElement) => void
|
||||
} {
|
||||
const scrollController = useScrollController()
|
||||
const scrollPositionSaver = useScrollPositionSaver()
|
||||
|
||||
const nextLayoutEffectCallbackRef = useRef<(() => void) | undefined>(
|
||||
undefined
|
||||
)
|
||||
|
||||
const blockElementScrollPositionUntilNextRender = useCallback(
|
||||
(el: HTMLElement) => {
|
||||
scrollPositionSaver.save(el)
|
||||
scrollController.disableScrollEvents()
|
||||
nextLayoutEffectCallbackRef.current = () => {
|
||||
const { restored } = scrollPositionSaver.restore()
|
||||
nextLayoutEffectCallbackRef.current = undefined
|
||||
|
||||
// Restoring the former scroll position will trigger a scroll event. We
|
||||
// need to wait for next scroll event to happen before enabling the
|
||||
// scrollController events again.
|
||||
if (restored) {
|
||||
const handleScrollRestoreEvent = () => {
|
||||
scrollController.enableScrollEvents()
|
||||
window.removeEventListener("scroll", handleScrollRestoreEvent)
|
||||
}
|
||||
window.addEventListener("scroll", handleScrollRestoreEvent)
|
||||
} else {
|
||||
scrollController.enableScrollEvents()
|
||||
}
|
||||
}
|
||||
},
|
||||
[scrollController, scrollPositionSaver]
|
||||
)
|
||||
|
||||
useLayoutEffect(() => {
|
||||
// Queuing permits to restore scroll position after all useLayoutEffect
|
||||
// have run, and yet preserve the sync nature of the scroll restoration
|
||||
// See https://github.com/facebook/docusaurus/issues/8625
|
||||
queueMicrotask(() => nextLayoutEffectCallbackRef.current?.())
|
||||
})
|
||||
|
||||
return {
|
||||
blockElementScrollPositionUntilNextRender,
|
||||
}
|
||||
}
|
||||
|
||||
type CancelScrollTop = () => void
|
||||
|
||||
function smoothScrollNative(top: number): CancelScrollTop {
|
||||
window.scrollTo({ top, behavior: "smooth" })
|
||||
return () => {
|
||||
// Nothing to cancel, it's natively cancelled if user tries to scroll down
|
||||
}
|
||||
}
|
||||
|
||||
function smoothScrollPolyfill(top: number): CancelScrollTop {
|
||||
let raf: number | null = null
|
||||
const isUpScroll = document.documentElement.scrollTop > top
|
||||
function rafRecursion() {
|
||||
const currentScroll = document.documentElement.scrollTop
|
||||
if (
|
||||
(isUpScroll && currentScroll > top) ||
|
||||
(!isUpScroll && currentScroll < top)
|
||||
) {
|
||||
raf = requestAnimationFrame(rafRecursion)
|
||||
window.scrollTo(0, Math.floor((currentScroll - top) * 0.85) + top)
|
||||
}
|
||||
}
|
||||
rafRecursion()
|
||||
|
||||
// Break the recursion. Prevents the user from "fighting" against that
|
||||
// recursion producing a weird UX
|
||||
return () => raf && cancelAnimationFrame(raf)
|
||||
}
|
||||
|
||||
/**
|
||||
* A "smart polyfill" of `window.scrollTo({ top, behavior: "smooth" })`.
|
||||
* This currently always uses a polyfilled implementation unless
|
||||
* `scroll-behavior: smooth` has been set in CSS, because native support
|
||||
* detection for scroll behavior seems unreliable.
|
||||
*
|
||||
* This hook does not do anything by itself: it returns a start and a stop
|
||||
* handle. You can execute either handle at any time.
|
||||
*/
|
||||
export function useSmoothScrollTo(): {
|
||||
/**
|
||||
* Start the scroll.
|
||||
*
|
||||
* @param top The final scroll top position.
|
||||
*/
|
||||
startScroll: (top: number) => void
|
||||
/**
|
||||
* A cancel function, because the non-native smooth scroll-top
|
||||
* implementation must be interrupted if user scrolls down. If there's no
|
||||
* existing animation or the scroll is using native behavior, this is a no-op.
|
||||
*/
|
||||
cancelScroll: CancelScrollTop
|
||||
} {
|
||||
const cancelRef = useRef<CancelScrollTop | null>(null)
|
||||
// Not all have support for smooth scrolling (particularly Safari mobile iOS)
|
||||
// TODO proper detection is currently unreliable!
|
||||
// see https://github.com/wessberg/scroll-behavior-polyfill/issues/16
|
||||
// For now, we only use native scroll behavior if smooth is already set,
|
||||
// because otherwise the polyfill produces a weird UX when both CSS and JS try
|
||||
// to scroll a page, and they cancel each other.
|
||||
const supportsNativeSmoothScrolling =
|
||||
getComputedStyle(document.documentElement).scrollBehavior === "smooth"
|
||||
return {
|
||||
startScroll: (top: number) => {
|
||||
cancelRef.current = supportsNativeSmoothScrolling
|
||||
? smoothScrollNative(top)
|
||||
: smoothScrollPolyfill(top)
|
||||
},
|
||||
cancelScroll: () => cancelRef.current?.(),
|
||||
}
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
import { useEffect, useState } from "react"
|
||||
|
||||
const useClient = () => {
|
||||
const [isClient, setIsClient] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
setIsClient(true)
|
||||
}, [])
|
||||
|
||||
return isClient
|
||||
}
|
||||
|
||||
export default useClient
|
||||
@@ -1,23 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect } from "react"
|
||||
|
||||
const useHeightObserver = () => {
|
||||
useEffect(() => {
|
||||
const storedHeight = window.localStorage.getItem("height")
|
||||
if (storedHeight) {
|
||||
document.body.style.height = storedHeight
|
||||
}
|
||||
|
||||
const resizeObserver = new ResizeObserver((entries) => {
|
||||
window.localStorage.setItem(
|
||||
"height",
|
||||
`${entries[0].target.clientHeight}px`
|
||||
)
|
||||
})
|
||||
|
||||
resizeObserver.observe(document.body)
|
||||
}, [])
|
||||
}
|
||||
|
||||
export default useHeightObserver
|
||||
@@ -0,0 +1,92 @@
|
||||
import {
|
||||
useCallback,
|
||||
useEffect,
|
||||
useLayoutEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
} from "react"
|
||||
|
||||
export type BaseTabType = {
|
||||
label: string
|
||||
value: string
|
||||
}
|
||||
|
||||
type EventData = {
|
||||
storageValue: string
|
||||
}
|
||||
|
||||
type TabProps<T> = {
|
||||
tabs: T[]
|
||||
group?: string
|
||||
}
|
||||
|
||||
function useTabs<T extends BaseTabType>({ tabs, group }: TabProps<T>) {
|
||||
const [selectedTab, setSelectedTab] = useState<T | null>(null)
|
||||
const storageKey = useMemo(() => `tab_${group}`, [group])
|
||||
const eventKey = useMemo(() => `tab_${group}_changed`, [group])
|
||||
const scrollPosition = useRef<number>(0)
|
||||
|
||||
const changeSelectedTab = (tab: T) => {
|
||||
scrollPosition.current = window.scrollY
|
||||
setSelectedTab(tab)
|
||||
localStorage.setItem(storageKey, tab.value)
|
||||
window.dispatchEvent(
|
||||
new CustomEvent<EventData>(eventKey, {
|
||||
detail: {
|
||||
storageValue: tab.value,
|
||||
},
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
const findTabItem = useCallback(
|
||||
(val: string) => {
|
||||
const lowerVal = val.toLowerCase()
|
||||
return tabs.find((t) => t.value.toLowerCase() === lowerVal)
|
||||
},
|
||||
[tabs]
|
||||
)
|
||||
|
||||
const handleStorageChange = useCallback(
|
||||
(e: CustomEvent<EventData>) => {
|
||||
if (e.detail.storageValue !== selectedTab?.value) {
|
||||
// check if tab exists
|
||||
const tab = findTabItem(e.detail.storageValue)
|
||||
if (tab) {
|
||||
setSelectedTab(tab)
|
||||
}
|
||||
}
|
||||
},
|
||||
[selectedTab, findTabItem]
|
||||
) as EventListener
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedTab) {
|
||||
const storedSelectedTabValue = localStorage.getItem(storageKey)
|
||||
setSelectedTab(
|
||||
storedSelectedTabValue
|
||||
? findTabItem(storedSelectedTabValue) || tabs[0]
|
||||
: tabs[0]
|
||||
)
|
||||
}
|
||||
}, [selectedTab, storageKey, tabs, findTabItem])
|
||||
|
||||
useEffect(() => {
|
||||
window.addEventListener(eventKey, handleStorageChange)
|
||||
|
||||
return () => {
|
||||
window.removeEventListener(eventKey, handleStorageChange)
|
||||
}
|
||||
}, [handleStorageChange, eventKey])
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (scrollPosition.current && window.scrollY !== scrollPosition.current) {
|
||||
window.scrollTo(0, scrollPosition.current)
|
||||
}
|
||||
}, [selectedTab])
|
||||
|
||||
return { selectedTab, changeSelectedTab }
|
||||
}
|
||||
|
||||
export default useTabs
|
||||
@@ -38,8 +38,8 @@
|
||||
"**/*.ts",
|
||||
"**/*.js",
|
||||
".next/types/**/*.ts",
|
||||
"next.config.mjs"
|
||||
, "app/api/algolia/route.mjs" ],
|
||||
"**/*.mjs"
|
||||
],
|
||||
"exclude": [
|
||||
"node_modules",
|
||||
"public",
|
||||
|
||||
@@ -447,7 +447,7 @@ module.exports = {
|
||||
bg: {
|
||||
base: {
|
||||
DEFAULT: "#111827",
|
||||
dark: "#1B1B1B"
|
||||
dark: "#1E1E1E"
|
||||
},
|
||||
header: {
|
||||
DEFAULT: "#1F2937",
|
||||
@@ -547,7 +547,7 @@ module.exports = {
|
||||
"button-danger-pressed": "linear-gradient(180deg, rgba(255, 255, 255, 0.00) 0%, rgba(255, 255, 255, 0.16) 100%)",
|
||||
"button-danger-pressed-dark": "linear-gradient(180deg, rgba(255, 255, 255, 0.00) 0%, rgba(255, 255, 255, 0.14) 100%)",
|
||||
"code-fade": "linear-gradient(90deg, #11182700, #111827 24px)",
|
||||
"code-fade-dark": "linear-gradient(90deg, #1B1B1B00, #1B1B1B 24px)",
|
||||
"code-fade-dark": "linear-gradient(90deg, #1E1E1E00, #1E1E1E 24px)",
|
||||
// TODO remove if not used
|
||||
"docs-button-neutral": "linear-gradient(180deg, #FFF 30.10%, #F8F9FA 100%)",
|
||||
"docs-button-neutral-dark": "linear-gradient(180deg, #2E2E32 0%, #28282C 32.67%)",
|
||||
|
||||
Reference in New Issue
Block a user