|
| 1 | +"use client"; |
| 2 | +import {type AnchorHTMLAttributes} from "react"; |
| 3 | +import {FrameworkProvider} from "fumadocs-core/framework"; |
| 4 | +import type {Framework} from "fumadocs-core/framework"; |
| 5 | +import {useParams, usePathname, useRouter} from "next/navigation"; |
| 6 | +import Link from "next/link"; |
| 7 | +import Image from "next/image"; |
| 8 | +import {RootProvider as BaseRootProvider, type RootProviderProps} from "fumadocs-ui/provider/base"; |
| 9 | + |
| 10 | +const artifactViewer = process.env.NEXT_PUBLIC_ARTIFACT_VIEWER === "true"; |
| 11 | + |
| 12 | +function useNormalizedPathname(): string { |
| 13 | + const pathname = usePathname(); |
| 14 | + return pathname.endsWith("/index.html") |
| 15 | + ? pathname.replace(/\/index\.html$/, "/") |
| 16 | + : pathname; |
| 17 | +} |
| 18 | + |
| 19 | +function addIndexHtml(href: string): string { |
| 20 | + const [path, hash] = href.split("#", 2); |
| 21 | + const normalized = path.endsWith("/") ? `${path}index.html` : `${path}/index.html`; |
| 22 | + return hash != null ? `${normalized}#${hash}` : normalized; |
| 23 | +} |
| 24 | + |
| 25 | +function ArtifactLink({href, prefetch, ...props}: AnchorHTMLAttributes<HTMLAnchorElement> & {prefetch?: boolean}) { |
| 26 | + if (!href || href.startsWith("http")) return <a {...props} href={href}/>; |
| 27 | + return <Link {...props} href={addIndexHtml(href)}/>; |
| 28 | +} |
| 29 | + |
| 30 | +export function RootProvider({children, dir, theme, search, i18n}: RootProviderProps) { |
| 31 | + const LinkComponent = artifactViewer ? ArtifactLink : Link; |
| 32 | + return ( |
| 33 | + <FrameworkProvider usePathname={artifactViewer ? useNormalizedPathname : usePathname} useRouter={useRouter} useParams={useParams} Link={LinkComponent as unknown as Framework["Link"]} Image={Image as unknown as Framework["Image"]}> |
| 34 | + <BaseRootProvider dir={dir} theme={theme} search={search} i18n={i18n}> |
| 35 | + {children} |
| 36 | + </BaseRootProvider> |
| 37 | + </FrameworkProvider> |
| 38 | + ); |
| 39 | +} |
0 commit comments