From 2434e3eeea154f2b8b239f3bc13ec80bf56da67a Mon Sep 17 00:00:00 2001 From: Shahed Nasser Date: Fri, 22 Nov 2024 17:54:42 +0200 Subject: [PATCH] docs: fix base path not added to hash links --- .../src/components/Heading/H2/index.tsx | 18 +++-------- .../src/components/Heading/H3/index.tsx | 20 ++---------- www/packages/docs-ui/src/hooks/index.ts | 1 + .../src/hooks/use-heading-url/index.tsx | 32 +++++++++++++++++++ 4 files changed, 41 insertions(+), 30 deletions(-) create mode 100644 www/packages/docs-ui/src/hooks/use-heading-url/index.tsx diff --git a/www/packages/docs-ui/src/components/Heading/H2/index.tsx b/www/packages/docs-ui/src/components/Heading/H2/index.tsx index f4c856072614f..92b28a8aafbad 100644 --- a/www/packages/docs-ui/src/components/Heading/H2/index.tsx +++ b/www/packages/docs-ui/src/components/Heading/H2/index.tsx @@ -1,10 +1,9 @@ "use client" import clsx from "clsx" -import React, { useMemo } from "react" +import React from "react" import { CopyButton, Link } from "@/components" -import { useIsBrowser } from "../../../providers" -import { usePathname } from "next/navigation" +import { useHeadingUrl } from "../../.." type H2Props = React.HTMLAttributes & { id?: string @@ -12,16 +11,9 @@ type H2Props = React.HTMLAttributes & { } export const H2 = ({ className, children, passRef, ...props }: H2Props) => { - const { isBrowser } = useIsBrowser() - const pathname = usePathname() - const copyText = useMemo(() => { - const hash = `#${props.id}` - if (!isBrowser) { - return hash - } - - return `${window.location.origin}${pathname}${hash}` - }, [props.id, isBrowser, pathname]) + const copyText = useHeadingUrl({ + id: props.id || "", + }) return (

& { id?: string } export const H3 = ({ className, children, ...props }: H3Props) => { - const { isBrowser } = useIsBrowser() - const copyText = useMemo(() => { - const url = `#${props.id}` - if (!isBrowser) { - return url - } - - const hashIndex = window.location.href.indexOf("#") - return ( - window.location.href.substring( - 0, - hashIndex !== -1 ? hashIndex : window.location.href.length - ) + url - ) - }, [props.id, isBrowser]) + const copyText = useHeadingUrl({ id: props.id || "" }) return (

{ + const { isBrowser } = useIsBrowser() + const { + config: { basePath }, + } = useSiteConfig() + const pathname = usePathname() + const headingUrl = useMemo(() => { + const hash = `#${id}` + if (!isBrowser) { + return hash + } + + const url = `${window.location.origin}${basePath}${pathname}`.replace( + /\/$/, + "" + ) + + return `${url}${hash}` + }, [id, isBrowser, pathname]) + + return headingUrl +}