From e5a68d7c78f29d086b595ba99c7a452df2104e06 Mon Sep 17 00:00:00 2001 From: Innei Date: Tue, 5 Sep 2023 13:17:10 +0800 Subject: [PATCH] fix: toc overflow (#968) --- src/components/site/PostTocItems.tsx | 96 +++++++++++++++++----------- 1 file changed, 60 insertions(+), 36 deletions(-) diff --git a/src/components/site/PostTocItems.tsx b/src/components/site/PostTocItems.tsx index 124f629b..4516e25f 100644 --- a/src/components/site/PostTocItems.tsx +++ b/src/components/site/PostTocItems.tsx @@ -1,7 +1,7 @@ "use client" import type { Result as TocResult } from "mdast-util-toc" -import { createElement, useEffect, useState } from "react" +import { createElement, useEffect, useRef, useState } from "react" import { scrollTo } from "~/lib/utils" @@ -63,45 +63,69 @@ function useActiveId(itemIds: string[]) { function Items(props: ItemsProps) { const { items, activeId, prefix = "" } = props + const [maxWidth, setMaxWidth] = useState(0) + const anchorRef = useRef(null) + useEffect(() => { + const handler = () => { + if (!anchorRef.current) return + const $anchor = anchorRef.current + const pos = $anchor.getBoundingClientRect() + const maxWidth = window.innerWidth - pos.x - 20 + setMaxWidth(maxWidth) + } + + handler() + window.addEventListener("resize", handler) + return () => { + window.removeEventListener("resize", handler) + } + }, []) return (
    - {items?.children?.map((item, index) => ( -
  1. - {item.children.map((child: any, i) => { - const content = `${prefix}${index + 1}. ${child.content}` +
  2. + {maxWidth > 0 && + items?.children?.map((item, index) => ( +
  3. + {item.children.map((child: any, i) => { + const content = `${prefix}${index + 1}. ${child.content}` - return ( - - {child.type === "paragraph" && child.children?.[0]?.url && ( - scrollTo(child.children[0].url)} - title={content} - className={ - (`#${activeId}` === child.children[0].url - ? "text-accent font-bold" - : "text-zinc-400 font-medium") + - " truncate inline-block max-w-full align-bottom hover:text-accent cursor-pointer" - } - > + return ( + + {child.type === "paragraph" && child.children?.[0]?.url && ( - - )} - {child.type === "list" && - createElement(Items, { - items: child, - activeId, - prefix: `${prefix}${index + 1}.`, - })} - - ) - })} -
  4. - ))} + data-url={child.children[0].url} + onClick={() => scrollTo(child.children[0].url)} + title={content} + className={ + (`#${activeId}` === child.children[0].url + ? "text-accent font-bold" + : "text-zinc-400 font-medium") + + " truncate inline-block max-w-full align-bottom hover:text-accent cursor-pointer" + } + > + + + )} + {child.type === "list" && + createElement(Items, { + items: child, + activeId, + prefix: `${prefix}${index + 1}.`, + })} + + ) + })} + + ))}
) }