Files
otunes/apps/web/components/scroll-restoration.tsx
T

108 lines
3.8 KiB
TypeScript

"use client"
import { useLayoutEffect, useRef } from "react"
import { usePathname, useSearchParams } from "next/navigation"
const historyKey = "otunesScrollKey"
const scrollSelector = '[data-slot="scroll-area-viewport"], .overflow-y-auto'
type Position = { top: number; left: number }
// Track page containers independently of the window, including split library views.
export function ScrollRestoration({ children }: { children: React.ReactNode }) {
const pathname = usePathname()
const searchParams = useSearchParams()
const route = `${pathname}?${searchParams.toString()}`
const rootRef = useRef<HTMLDivElement>(null)
const positions = useRef(new Map<string, Map<number, Position>>())
useLayoutEffect(() => {
const root = rootRef.current
if (!root) return
const key =
typeof history.state?.[historyKey] === "string"
? (history.state[historyKey] as string)
: crypto.randomUUID()
history.replaceState({ ...history.state, [historyKey]: key }, "")
const saved = positions.current.get(key)
const pending = new Map(saved)
if (!positions.current.has(key)) positions.current.set(key, new Map())
// Bound memory during long listening sessions.
if (positions.current.size > 100) {
const oldest = positions.current.keys().next().value
if (oldest !== undefined) positions.current.delete(oldest)
}
const containers = () =>
Array.from(root.querySelectorAll<HTMLElement>(scrollSelector)).filter(
(element) => element.getClientRects().length > 0
)
const restore = () => {
for (const [index, element] of containers().entries()) {
const position = pending.get(index)
if (!position) continue
element.scrollTo({
top: position.top,
left: position.left,
behavior: "instant",
})
// Keep waiting if asynchronous content is still too short.
if (
Math.abs(element.scrollTop - position.top) < 1 &&
Math.abs(element.scrollLeft - position.left) < 1
) {
pending.delete(index)
}
}
}
const record = (event: Event) => {
if (!(event.target instanceof HTMLElement)) return
const index = containers().indexOf(event.target)
if (index < 0 || pending.has(index)) return
positions.current.get(key)?.set(index, {
top: event.target.scrollTop,
left: event.target.scrollLeft,
})
}
const stopRestoring = () => {
pending.clear()
observer.disconnect()
resizeObserver.disconnect()
}
const observer = new MutationObserver(() => {
restore()
for (const element of containers()) {
resizeObserver.observe(element)
for (const child of element.children) resizeObserver.observe(child)
}
})
const resizeObserver = new ResizeObserver(restore)
if (pending.size) {
observer.observe(root, { childList: true, subtree: true })
for (const element of containers()) {
resizeObserver.observe(element)
for (const child of element.children) resizeObserver.observe(child)
}
restore()
}
const timeout = window.setTimeout(stopRestoring, 10_000)
root.addEventListener("scroll", record, true)
root.addEventListener("wheel", stopRestoring, { passive: true })
root.addEventListener("touchstart", stopRestoring, { passive: true })
root.addEventListener("keydown", stopRestoring)
return () => {
window.clearTimeout(timeout)
stopRestoring()
root.removeEventListener("scroll", record, true)
root.removeEventListener("wheel", stopRestoring)
root.removeEventListener("touchstart", stopRestoring)
root.removeEventListener("keydown", stopRestoring)
}
}, [route])
return (
<div ref={rootRef} className="contents">
{children}
</div>
)
}