import type { ChangeStop } from './diffView' import type { StickyScrollSettings } from './types' import { useCallback, useLayoutEffect, useRef, useState } from 'react' import { nextStop } from './diffView' import { pageLayout } from './pageLayout' import { flash } from './useReveal' import { stickyInset } from './useStickyScroll' /** 跳到的那处离筛选栏下沿留多少像素。 */ const MARGIN = 8 /** * 「上一处 / 下一处」和点总览条的刻度:跳到一处改动。它在折叠着的块里时先展开那几层(expand),渲染好了再把它滚到筛选栏下面 * (钉着外层卡片时在钉着的几行下面,sticky 是 VS Code 的 Sticky Scroll 设置)、闪几下。 * 接着走从哪算:跳完之后页面没滚过就从刚跳到的那处接着走,用户自己滚过了就按视口顶上那块的行找(见 nextStop)。 */ export function useChangeNav(stops: readonly ChangeStop[], collapsed: ReadonlySet, expand: (ids: string[]) => void, sticky: StickyScrollSettings | undefined): { move: (step: 1 | -1) => void goTo: (stop: ChangeStop) => void } { const [target, setTarget] = useState(null) /** 最近一次跳到的那处,和跳完时页面滚到哪 */ const jumped = useRef<{ id: string, scrollY: number } | null>(null) useLayoutEffect(() => { if (!target) return const hidden = target.ancestors.filter(id => collapsed.has(id)) if (hidden.length > 0) { expand(hidden) return } const card = document.querySelector(`.cr-block[data-id="${target.id}"]`) if (card) { pageLayout.settle(card) window.scrollTo(0, card.getBoundingClientRect().top + window.scrollY - pageLayout.pinnedHeight() - stickyInset(card, sticky) - MARGIN) flash(card) } jumped.current = { id: target.id, scrollY: window.scrollY } setTarget(null) }, [target, collapsed, expand, sticky]) const move = useCallback((step: 1 | -1) => { if (stops.length === 0) return const from = jumped.current && Math.abs(window.scrollY - jumped.current.scrollY) < 2 ? jumped.current.id : undefined const index = from === undefined ? -1 : stops.findIndex(stop => stop.id === from) const at = index >= 0 ? { index } : { line: pageLayout.anchorAt(window.scrollY + pageLayout.pinnedHeight())?.line } setTarget(stops[nextStop(stops, at, step)]) }, [stops]) return { move, goTo: setTarget } }