1 /*
2 * Coordinates the deep-link scroll (driven by TagSection) with the per-section
3 * scroll-spy (in TagOperation / TagSectionSchema).
4 *
5 * The scroll-spy updates the URL via history.replaceState, which Next syncs to
6 * usePathname. Without coordination, a section at the top on load (the schema or
7 * the first operation) would claim the URL before the target operation's scroll
8 * runs — changing the pathname and aborting the deep-link scroll (so it "stays
9 * on the schema"). While a navigation-scroll is settling we lock the scroll-spy;
10 * and scroll-spy URL updates are marked so the deep-link controller can tell
11 * them apart from real navigations.
12 */
13
14 let lockCount = 0
15 let lastScrollSpyPath: string | null = null
16
17 /**
18 * Acquire the scroll-spy lock. Returns a release function (idempotent).
19 */
20 export function lockScrollSpy(): () => void {
21 lockCount++
22 let released = false
23 return () => {
24 if (released) {
25 return
26 }
27 released = true
28 lockCount = Math.max(0, lockCount - 1)
29 }
30 }
31
32 export function isScrollSpyLocked(): boolean {
33 return lockCount > 0
34 }
35
36 /**
37 * Record a path the scroll-spy just wrote to the URL.
38 */
39 export function markScrollSpyNavigation(path: string): void {
40 lastScrollSpyPath = path
41 }
42
43 /**
44 * Returns true (once) if the given path was the last scroll-spy URL update —
45 * i.e. this pathname change came from scroll-spy, not a real navigation.
46 */
47 export function isScrollSpyNavigation(path: string): boolean {
48 if (lastScrollSpyPath === path) {
49 lastScrollSpyPath = null
50 return true
51 }
52 return false
53 }
54
55 let scrollSpyTimer: ReturnType<typeof setTimeout> | null = null
56
57 /**
58 * Debounce scroll-spy updates so fast scrolling applies a single update once it
59 * settles (one URL/highlight change) instead of one per crossed section. This
60 * avoids per-crossing re-render churn and keeps the deep-link controller from
61 * treating each intermediate pathname change as a navigation and re-scrolling.
62 */
63 export function scheduleScrollSpyUpdate(apply: () => void): void {
64 if (scrollSpyTimer) {
65 clearTimeout(scrollSpyTimer)
66 }
67 scrollSpyTimer = setTimeout(() => {
68 scrollSpyTimer = null
69 apply()
70 }, 120)
71 }