From 8ba257d836b950a5556de7bf1e16060c8a8e9617 Mon Sep 17 00:00:00 2001 From: DIYgod Date: Wed, 7 Jun 2023 23:06:37 +0100 Subject: [PATCH] feat: optimize url hash scrolling --- src/components/common/PageContent.tsx | 20 +++----------- src/components/common/ReactionComment.tsx | 12 ++------- src/components/site/PostToc.tsx | 26 +++++++++--------- src/lib/utils.ts | 32 ++++++++++++++++++----- 4 files changed, 43 insertions(+), 47 deletions(-) diff --git a/src/components/common/PageContent.tsx b/src/components/common/PageContent.tsx index 7f717b3d..60f9bd85 100644 --- a/src/components/common/PageContent.tsx +++ b/src/components/common/PageContent.tsx @@ -7,7 +7,7 @@ import { PostToc } from "~/components/site/PostToc" import { useCodeCopy } from "~/hooks/useCodeCopy" import { useHash } from "~/hooks/useHash" import { ExpandedCharacter, ExpandedNote } from "~/lib/types" -import { calculateElementTop, cn } from "~/lib/utils" +import { cn, scrollTo } from "~/lib/utils" import { renderPageContent } from "~/markdown" export const PageContent: React.FC<{ @@ -35,7 +35,6 @@ export const PageContent: React.FC<{ site, withActions, }) => { - const hash = useHash() useCodeCopy() const inParsedContent = useMemo(() => { @@ -49,22 +48,9 @@ export const PageContent: React.FC<{ } }, [content, isComment, parsedContent]) + const hash = useHash() useEffect(() => { - const _hash = decodeURIComponent(hash.slice(1)) - if (!_hash) return - if (history.state?.preventScrollToToc) { - history.state.preventScrollToToc = false - return - } - const targetElement = document.querySelector( - `#user-content-${decodeURIComponent(_hash)}`, - ) as HTMLElement - if (!targetElement) return - - window.scrollTo({ - top: calculateElementTop(targetElement) - 20, - behavior: "smooth", - }) + scrollTo(hash) }, [hash]) return ( diff --git a/src/components/common/ReactionComment.tsx b/src/components/common/ReactionComment.tsx index 30463570..8b4505bc 100644 --- a/src/components/common/ReactionComment.tsx +++ b/src/components/common/ReactionComment.tsx @@ -2,7 +2,7 @@ import { Tooltip } from "~/components/ui/Tooltip" import { useTranslation } from "~/lib/i18n/client" -import { calculateElementTop, cn } from "~/lib/utils" +import { cn, scrollTo } from "~/lib/utils" import { useCheckComment, useGetComments } from "~/queries/page" import { Button } from "../ui/Button" @@ -23,14 +23,6 @@ export const ReactionComment: React.FC<{ noteId: noteId, }) - const comment = () => { - const targetElement = document.querySelector("#comments") as HTMLElement - window.scrollTo({ - top: calculateElementTop(targetElement) - 20, - behavior: "smooth", - }) - } - return ( <>
@@ -45,7 +37,7 @@ export const ReactionComment: React.FC<{ "!h-auto flex-col", )} isAutoWidth={true} - onClick={comment} + onClick={() => scrollTo("#comments", true)} > {(() => { const inner = ( diff --git a/src/components/site/PostToc.tsx b/src/components/site/PostToc.tsx index 008350cb..bdc423aa 100644 --- a/src/components/site/PostToc.tsx +++ b/src/components/site/PostToc.tsx @@ -6,6 +6,8 @@ import { toHast } from "mdast-util-to-hast" import type { Result as TocResult } from "mdast-util-toc" import React, { createElement, useEffect, useRef, useState } from "react" +import { scrollTo } from "~/lib/utils" + const inlineElements = ["delete", "strong", "emphasis", "inlineCode"] function getLinkNode(node: any): List["children"] { @@ -29,7 +31,7 @@ function getIds(items: TocResult["map"]) { } function getElement(id: string) { - return document.querySelector(`a[href="#${id}"]`) + return document.querySelector(`#user-content-${id}`) } function useActiveId(itemIds: string[]) { @@ -39,14 +41,7 @@ function useActiveId(itemIds: string[]) { (entries) => { entries.forEach((entry) => { if (entry.isIntersecting) { - // const state = history.state - - // history.replaceState( - // { ...state, preventScrollToToc: true }, - // "", - // entry.target.getAttribute("href"), - // ) - setActiveId(entry.target.getAttribute("href")) + setActiveId(entry.target.id.replace("user-content-", "")) } }) }, @@ -69,11 +64,13 @@ function useActiveId(itemIds: string[]) { }, [itemIds]) return activeId } + interface ItemsProps { items: TocResult["map"] activeId?: string | null prefix?: string } + function Items(props: ItemsProps) { const { items, activeId, prefix = "" } = props return ( @@ -98,14 +95,15 @@ function Items(props: ItemsProps) { return ( {child.type === "paragraph" && child.children?.[0]?.url && ( - scrollTo(child.children[0].url)} title={content} className={ - (activeId === child.children[0].url + (`#${activeId}` === child.children[0].url ? "text-accent" : "text-zinc-700") + - " truncate inline-block max-w-full align-bottom hover:text-accent" + " truncate inline-block max-w-full align-bottom hover:text-accent cursor-pointer" } > - + )} {child.type === "list" && createElement(Items, { diff --git a/src/lib/utils.ts b/src/lib/utils.ts index dad3758a..223a9f81 100644 --- a/src/lib/utils.ts +++ b/src/lib/utils.ts @@ -40,13 +40,33 @@ export const throttle = (func: Function, limit: number) => { } } -export const calculateElementTop = (el: HTMLElement) => { - let top = 0 - while (el) { - top += el.offsetTop - el = el.offsetParent as HTMLElement +export const scrollTo = (hash: string, notUserContent?: boolean) => { + const calculateElementTop = (el: HTMLElement) => { + let top = 0 + while (el) { + top += el.offsetTop + el = el.offsetParent as HTMLElement + } + return top } - return top + + const _hash = decodeURIComponent(hash.slice(1)) + if (!_hash) return + if (history.state?.preventScrollToToc) { + history.state.preventScrollToToc = false + return + } + const targetElement = document.querySelector( + notUserContent + ? `#${decodeURIComponent(_hash)}` + : `#user-content-${decodeURIComponent(_hash)}`, + ) as HTMLElement + if (!targetElement) return + + window.scrollTo({ + top: calculateElementTop(targetElement) - 20, + behavior: "smooth", + }) } export function getStringLength(str: string) {