From fb4ca522440aced4d2aa18fda2a9d5c43e32d0d1 Mon Sep 17 00:00:00 2001 From: Innei Date: Wed, 28 Aug 2024 19:30:08 +0800 Subject: [PATCH] feat: support toc parser Signed-off-by: Innei --- .../src/components/ui/markdown/Markdown.tsx | 25 ++- .../components/ui/markdown/components/Toc.tsx | 181 ++++++++++++++++++ .../ui/markdown/components/TocItem.tsx | 76 ++++++++ src/renderer/src/lib/scroller.ts | 13 +- .../src/modules/entry-content/index.tsx | 24 ++- src/renderer/src/styles/tailwind-extend.css | 37 ++++ 6 files changed, 341 insertions(+), 15 deletions(-) create mode 100644 src/renderer/src/components/ui/markdown/components/Toc.tsx create mode 100644 src/renderer/src/components/ui/markdown/components/TocItem.tsx diff --git a/src/renderer/src/components/ui/markdown/Markdown.tsx b/src/renderer/src/components/ui/markdown/Markdown.tsx index 6609a6297..e5561790e 100644 --- a/src/renderer/src/components/ui/markdown/Markdown.tsx +++ b/src/renderer/src/components/ui/markdown/Markdown.tsx @@ -18,15 +18,19 @@ export const Markdown: Component< [children, stableRemarkOptions], ) + const ref = useRef(null) return ( -
- {markdownElement} -
+ +
+ {markdownElement} +
+
) } @@ -34,12 +38,14 @@ export const HTML = ( props: { children: string | null | undefined as: A + + accessory?: React.ReactNode } & JSX.IntrinsicElements[A] & Partial<{ renderInlineStyle: boolean }>, ) => { - const { children, renderInlineStyle, as = "div", ...rest } = props + const { children, renderInlineStyle, as = "div", accessory, ...rest } = props const stableRemarkOptions = useState({ renderInlineStyle })[0] const markdownElement = useMemo( @@ -55,6 +61,7 @@ export const HTML = ( return ( {createElement(as, { ...rest, ref }, markdownElement)} + {accessory} ) } diff --git a/src/renderer/src/components/ui/markdown/components/Toc.tsx b/src/renderer/src/components/ui/markdown/components/Toc.tsx new file mode 100644 index 000000000..6dd29b75f --- /dev/null +++ b/src/renderer/src/components/ui/markdown/components/Toc.tsx @@ -0,0 +1,181 @@ +import { springScrollToElement } from "@renderer/lib/scroller" +import { cn } from "@renderer/lib/utils" +import { atom, useAtom } from "jotai" +import { + memo, + startTransition, + useContext, + useEffect, + useMemo, + useRef, + useState, +} from "react" +import { useEventCallback } from "usehooks-ts" + +import { useScrollViewElement } from "../../scroll-area/hooks" +import { MarkdownRenderContainerRefContext } from "../context" +import { TocItem } from "./TocItem" + +export interface ITocItem { + depth: number + title: string + anchorId: string + index: number + + $heading: HTMLHeadingElement +} + +export const Toc: Component = ({ className }) => { + const markdownElement = useContext(MarkdownRenderContainerRefContext) + + const $headings = useMemo( + () => + (markdownElement?.querySelectorAll("h1, h2, h3, h4, h5, h6") || + []) as HTMLHeadingElement[], + [markdownElement], + ) + const toc: ITocItem[] = useMemo( + () => + Array.from($headings).map((el, idx) => { + const depth = +el.tagName.slice(1) + const elClone = el.cloneNode(true) as HTMLElement + + const title = elClone.textContent || "" + + const index = idx + + return { + depth, + index: Number.isNaN(index) ? -1 : index, + title, + anchorId: el.dataset.rid || "", + $heading: el, + } + }), + [$headings], + ) + + const rootDepth = useMemo( + () => + toc?.length ? + (toc.reduce( + (d: number, cur) => Math.min(d, cur.depth), + toc[0]?.depth || 0, + ) as any as number) : + 0, + [toc], + ) + + const [_, setTreeRef] = useState() + const [activeId, setActiveId] = useActiveId($headings) + + const scrollContainerElement = useScrollViewElement() + + const handleScrollTo = useEventCallback( + (i: number, $el: HTMLElement | null, anchorId: string) => { + if ($el) { + const handle = () => { + springScrollToElement($el, -100, scrollContainerElement!).then(() => { + setActiveId?.(anchorId) + }) + } + handle() + } + }, + ) + if (toc.length === 0) return null + return ( +
+
    + {toc?.map((heading) => ( + + ))} +
+
+ ) +} +const tocActiveIdAtom = atom(null) +function useActiveId($headings: HTMLHeadingElement[]) { + const [activeId, setActiveId] = useAtom(tocActiveIdAtom) + const scrollContainerElement = useScrollViewElement() + useEffect(() => { + const observer = new IntersectionObserver( + (entries) => { + entries.forEach((entry) => { + if (entry.isIntersecting) { + startTransition(() => { + setActiveId((entry.target as HTMLElement).dataset.rid || "") + }) + } + }) + }, + { rootMargin: `-100px 0px -100px 0px`, root: scrollContainerElement }, + ) + $headings.forEach(($heading) => { + observer.observe($heading) + }) + return () => { + observer.disconnect() + } + }, [$headings, scrollContainerElement, setActiveId]) + + return [activeId, setActiveId] as const +} + +const MemoedItem = memo<{ + isActive: boolean + heading: ITocItem + rootDepth: number + onClick?: (i: number, $el: HTMLElement | null, anchorId: string) => void +}>((props) => { + const { + heading, + isActive, + onClick, + rootDepth, + // containerRef + } = props + + const itemRef = useRef(null) + + useEffect(() => { + if (!isActive) return + + const $item = itemRef.current + if (!$item) return + const $container = $item.parentElement + if (!$container) return + + const containerHeight = $container.clientHeight + const itemHeight = $item.clientHeight + const itemOffsetTop = $item.offsetTop + const { scrollTop } = $container + + const itemTop = itemOffsetTop - scrollTop + const itemBottom = itemTop + itemHeight + if (itemTop < 0 || itemBottom > containerHeight) { + $container.scrollTop = + itemOffsetTop - containerHeight / 2 + itemHeight / 2 + } + }, [isActive]) + + return ( + + ) + }) +MemoedItem.displayName = "MemoedItem" diff --git a/src/renderer/src/components/ui/markdown/components/TocItem.tsx b/src/renderer/src/components/ui/markdown/components/TocItem.tsx new file mode 100644 index 000000000..957b67979 --- /dev/null +++ b/src/renderer/src/components/ui/markdown/components/TocItem.tsx @@ -0,0 +1,76 @@ +import { cn } from "@renderer/lib/utils" +import type { FC, MouseEvent } from "react" +import { + memo, + useCallback, + useRef, +} from "react" + +export interface ITocItem { + depth: number + title: string + anchorId: string + index: number + + $heading: HTMLHeadingElement +} + +export const TocItem: FC<{ + heading: ITocItem + + active: boolean + rootDepth: number + onClick?: (i: number, $el: HTMLElement | null, anchorId: string) => void +}> = memo((props) => { + const { active, onClick, heading } = props + const { $heading, anchorId, depth, index, title } = heading + + const $ref = useRef(null) + + // useEffect(() => { + // if (active) { + // $ref.current?.scrollIntoView({ behavior: "smooth" }) + // } + // }, []) + return ( + + ) +}) + +const widthMap = { + 1: 72, + 2: 60, + 3: 48, + 4: 36, + 5: 24, + 6: 12, +} + +TocItem.displayName = "TocItem" diff --git a/src/renderer/src/lib/scroller.ts b/src/renderer/src/lib/scroller.ts index 5df955282..0d3690ed6 100644 --- a/src/renderer/src/lib/scroller.ts +++ b/src/renderer/src/lib/scroller.ts @@ -12,28 +12,31 @@ export const springScrollTo = ( const stopSpringScrollHandler = () => { animation.stop() } + const el = scrollerElement || window const animation = animateValue({ keyframes: [scrollTop + 1, y], autoplay: true, ...microDampingPreset, onPlay() { - window.addEventListener("wheel", stopSpringScrollHandler) - window.addEventListener("touchmove", stopSpringScrollHandler) + el.addEventListener("wheel", stopSpringScrollHandler) + el.addEventListener("touchmove", stopSpringScrollHandler) }, onUpdate(latest) { if (latest <= 0) { animation.stop() } - const el = scrollerElement || window + el.scrollTo(0, latest) }, }) animation.then(() => { - window.removeEventListener("wheel", stopSpringScrollHandler) - window.removeEventListener("touchmove", stopSpringScrollHandler) + el.removeEventListener("wheel", stopSpringScrollHandler) + el.removeEventListener("touchmove", stopSpringScrollHandler) }) + + return animation } export const springScrollToElement = ( diff --git a/src/renderer/src/modules/entry-content/index.tsx b/src/renderer/src/modules/entry-content/index.tsx index 33a237fbc..96242aba2 100644 --- a/src/renderer/src/modules/entry-content/index.tsx +++ b/src/renderer/src/modules/entry-content/index.tsx @@ -11,6 +11,8 @@ import { m } from "@renderer/components/common/Motion" import { ShadowDOM } from "@renderer/components/common/ShadowDOM" import { AutoResizeHeight } from "@renderer/components/ui/auto-resize-height" import { HTML } from "@renderer/components/ui/markdown" +import { Toc } from "@renderer/components/ui/markdown/components/Toc" +import { RootPortal } from "@renderer/components/ui/portal" import { ScrollArea } from "@renderer/components/ui/scroll-area" import { isWebBuild, ROUTE_FEED_PENDING } from "@renderer/constants" import { useEntryReadabilityToggle } from "@renderer/hooks/biz/useEntryActions" @@ -26,6 +28,7 @@ import { cn } from "@renderer/lib/utils" import type { ActiveEntryId } from "@renderer/models" import { useIsSoFWrappedElement, + useWrappedElement, WrappedElementProvider, } from "@renderer/providers/wrapped-element-provider" import { Queries } from "@renderer/queries" @@ -207,8 +210,8 @@ export const EntryContentRender: Component<{ entryId: string }> = ({
+ -
{(summary.isLoading || summary.data) && (
@@ -230,6 +233,7 @@ export const EntryContentRender: Component<{ entryId: string }> = ({ {!isInReadabilityMode ? ( } as="article" className="prose dark:prose-invert prose-h1:text-[1.6em]" renderInlineStyle={readerRenderInlineStyle} @@ -432,3 +436,21 @@ const RenderError: FallbackRender = ({ error }) => {
) } + +const ContainerToc: FC<{ + entryId: string +}> = (props) => { + const wrappedElement = useWrappedElement() + return ( + +
+
+ +
+
+
+ ) +} diff --git a/src/renderer/src/styles/tailwind-extend.css b/src/renderer/src/styles/tailwind-extend.css index 28cef0f42..ba97d1c2d 100644 --- a/src/renderer/src/styles/tailwind-extend.css +++ b/src/renderer/src/styles/tailwind-extend.css @@ -317,3 +317,40 @@ box-shadow: 0px -5px 20px -11px var(--bg); } } + +@layer utilities { + .easing-spring-soft { + --spring-easing: linear( + 0, + 0.0019, + 0.0073 1.2%, + 0.0274 2.39%, + 0.0624, + 0.1075 5.08%, + 0.2108 7.62%, + 0.4632 13.15%, + 0.5727 15.69%, + 0.6768 18.38%, + 0.7617 20.92%, + 0.8365, + 0.8963 26.29%, + 0.921 27.64%, + 0.9447, + 0.9647, + 0.9813 32.12%, + 1.0028 34.66%, + 1.0185 37.5%, + 1.0279 40.64%, + 1.0315 44.07%, + 1.0291 49%, + 1.0105 62.9%, + 1.0028 71.86%, + 0.9994 82.62%, + 0.9993 99.95% + ); + --spring-duration: 1.157s; + + animation-timing-function: var(--spring-easing); + animation-duration: var(--spring-duration); + } +}