SectionFrame remembers scroll position per address

useScrollMemory(ref, key) records every scroll container inside ref and
restores it when the key comes back, holding the position until layout
settles. SectionFrame keys it by pathname + search, so section tabs and
in-card sub-tabs return to where the user left them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ilya Mukhortov 2026-11-07 16:17:05 +10:00
parent a413c3893d
commit 5f021385fa
3 changed files with 129 additions and 1 deletions

View File

@ -0,0 +1,119 @@
import * as React from "react"
/**
* Память прокрутки по ключу (обычно — адрес страницы).
*
* Следит за всеми прокручиваемыми контейнерами внутри `rootRef` (ScrollArea, колонки, overflow-auto)
* и, когда ключ снова становится текущим, возвращает каждый на прежнее место.
* Контейнер узнаётся по пути от корня (индексы детей), поэтому разметка страницы не меняется.
* Хранится в памяти вкладки браузера, перезагрузку не переживает.
*/
type Position = { top: number; left: number }
const LIMIT = 50
const HOLD_MS = 600
const memory = new Map<string, Map<string, Position>>()
function pathOf(root: Element, el: Element): string | null {
const parts: number[] = []
let node: Element | null = el
while (node && node !== root) {
const parent: Element | null = node.parentElement
if (!parent) return null
parts.push(Array.prototype.indexOf.call(parent.children, node))
node = parent
}
return node === root ? parts.reverse().join(".") : null
}
function resolve(root: Element, path: string): Element | null {
let node: Element | undefined = root
for (const part of path ? path.split(".") : []) {
node = node?.children[Number(part)]
if (!node) return null
}
return node ?? null
}
function remember(key: string, path: string, pos: Position) {
let entry = memory.get(key)
if (entry) {
memory.delete(key) // в конец — самый свежий
} else {
entry = new Map()
if (memory.size >= LIMIT) memory.delete(memory.keys().next().value!)
}
memory.set(key, entry)
if (pos.top === 0 && pos.left === 0) entry.delete(path)
else entry.set(path, pos)
}
export function useScrollMemory(rootRef: React.RefObject<HTMLElement | null>, key: string) {
const keyRef = React.useRef(key)
// Запоминаем: scroll не всплывает, но ловится на предке в фазе capture.
React.useEffect(() => {
const root = rootRef.current
if (!root) return
const pending = new Set<Element>()
let frame = 0
const flush = () => {
frame = 0
for (const el of pending) {
const path = pathOf(root, el)
if (path !== null) remember(keyRef.current, path, { top: el.scrollTop, left: el.scrollLeft })
}
pending.clear()
}
const onScroll = (event: Event) => {
if (!(event.target instanceof Element)) return
pending.add(event.target)
if (!frame) frame = requestAnimationFrame(flush)
}
root.addEventListener("scroll", onScroll, { capture: true, passive: true })
return () => {
root.removeEventListener("scroll", onScroll, { capture: true })
if (frame) cancelAnimationFrame(frame)
}
}, [rootRef])
// Возвращаем сразу после отрисовки нового адреса и держим позицию, пока раскладка
// не устоится: контейнер может появиться позже или ненадолго стать короче, и браузер
// прижмёт скролл. Любое действие человека (колесо, касание, клик, клавиша) отпускает.
React.useLayoutEffect(() => {
keyRef.current = key
const root = rootRef.current
const saved = memory.get(key)
if (!root || !saved?.size) return
const target = [...saved]
const until = performance.now() + HOLD_MS
let frame = 0
const apply = () => {
for (const [path, pos] of target) {
const el = resolve(root, path)
if (!el) continue
if (Math.abs(el.scrollTop - pos.top) > 1) el.scrollTop = pos.top
if (Math.abs(el.scrollLeft - pos.left) > 1) el.scrollLeft = pos.left
}
frame = performance.now() < until ? requestAnimationFrame(apply) : 0
}
const release = () => {
cancelAnimationFrame(frame)
frame = 0
}
const inputs = ["wheel", "touchstart", "pointerdown", "keydown"] as const
inputs.forEach((type) => root.addEventListener(type, release, { capture: true, passive: true }))
apply()
return () => {
release()
inputs.forEach((type) => root.removeEventListener(type, release, { capture: true }))
}
}, [rootRef, key])
}

View File

@ -41,6 +41,7 @@ export * from "./charts/column-chart"
export * from "./charts/sparkline" export * from "./charts/sparkline"
export * from "./hooks/use-caret" export * from "./hooks/use-caret"
export * from "./hooks/use-media-query" export * from "./hooks/use-media-query"
export * from "./hooks/use-scroll-memory"
export * from "./lib/clipboard" export * from "./lib/clipboard"
export * from "./lib/format" export * from "./lib/format"
export * from "./lib/masks" export * from "./lib/masks"

View File

@ -1,11 +1,13 @@
import * as React from "react" import * as React from "react"
import { Maximize2Icon, Minimize2Icon } from "lucide-react" import { Maximize2Icon, Minimize2Icon } from "lucide-react"
import { useScrollMemory } from "../hooks/use-scroll-memory"
import { createStore } from "../lib/store" import { createStore } from "../lib/store"
import { cn } from "../lib/utils" import { cn } from "../lib/utils"
import { Button } from "../ui/button" import { Button } from "../ui/button"
import { Kbd } from "../ui/kbd" import { Kbd } from "../ui/kbd"
import { Tooltip, TooltipContent, TooltipTrigger } from "../ui/tooltip" import { Tooltip, TooltipContent, TooltipTrigger } from "../ui/tooltip"
import { useShell } from "./shell-provider"
// Развёрнутость общая для всех разделов: переход в другой раздел её не сбрасывает. // Развёрнутость общая для всех разделов: переход в другой раздел её не сбрасывает.
const maximizedStore = createStore(false) const maximizedStore = createStore(false)
@ -14,10 +16,14 @@ const toggleMaximized = () => maximizedStore.set((v) => !v)
/** /**
* Рамка раздела со вкладками: карточка, сверху полоса (`SectionTabsBar`), под ней контент. * Рамка раздела со вкладками: карточка, сверху полоса (`SectionTabsBar`), под ней контент.
* Alt+F или кнопка в полосе — развернуть на весь экран поверх меню, Esc — свернуть. * Alt+F или кнопка в полосе — развернуть на весь экран поверх меню, Esc — свернуть.
* Прокрутка контента запоминается по адресу: вернулся на вкладку — на том же месте.
* Разделы без вкладок — `PageFrame`. * Разделы без вкладок — `PageFrame`.
*/ */
export function SectionFrame({ bar, children }: { bar: React.ReactNode; children: React.ReactNode }) { export function SectionFrame({ bar, children }: { bar: React.ReactNode; children: React.ReactNode }) {
const maximized = maximizedStore.use() const maximized = maximizedStore.use()
const { pathname, search } = useShell()
const contentRef = React.useRef<HTMLDivElement>(null)
useScrollMemory(contentRef, pathname + search)
// Alt+F — развернуть/свернуть, Esc — свернуть (если не открыт диалог или меню). // Alt+F — развернуть/свернуть, Esc — свернуть (если не открыт диалог или меню).
React.useEffect(() => { React.useEffect(() => {
@ -54,7 +60,9 @@ export function SectionFrame({ bar, children }: { bar: React.ReactNode; children
)} )}
> >
{bar} {bar}
<div className="relative flex min-h-0 flex-1 flex-col">{children}</div> <div ref={contentRef} className="relative flex min-h-0 flex-1 flex-col">
{children}
</div>
</div> </div>
</div> </div>
) )