From 5f021385fa9df9dc925e230331faa857871324ec Mon Sep 17 00:00:00 2001 From: Ilya Mukhortov Date: Sat, 7 Nov 2026 16:17:05 +1000 Subject: [PATCH] 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 --- src/hooks/use-scroll-memory.ts | 119 +++++++++++++++++++++++++++++++++ src/index.ts | 1 + src/kit/section-frame.tsx | 10 ++- 3 files changed, 129 insertions(+), 1 deletion(-) create mode 100644 src/hooks/use-scroll-memory.ts diff --git a/src/hooks/use-scroll-memory.ts b/src/hooks/use-scroll-memory.ts new file mode 100644 index 0000000..eb4ef4e --- /dev/null +++ b/src/hooks/use-scroll-memory.ts @@ -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>() + +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, key: string) { + const keyRef = React.useRef(key) + + // Запоминаем: scroll не всплывает, но ловится на предке в фазе capture. + React.useEffect(() => { + const root = rootRef.current + if (!root) return + const pending = new Set() + 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]) +} diff --git a/src/index.ts b/src/index.ts index c7c9227..7823cad 100644 --- a/src/index.ts +++ b/src/index.ts @@ -41,6 +41,7 @@ export * from "./charts/column-chart" export * from "./charts/sparkline" export * from "./hooks/use-caret" export * from "./hooks/use-media-query" +export * from "./hooks/use-scroll-memory" export * from "./lib/clipboard" export * from "./lib/format" export * from "./lib/masks" diff --git a/src/kit/section-frame.tsx b/src/kit/section-frame.tsx index 2e8d251..8d3a850 100644 --- a/src/kit/section-frame.tsx +++ b/src/kit/section-frame.tsx @@ -1,11 +1,13 @@ import * as React from "react" import { Maximize2Icon, Minimize2Icon } from "lucide-react" +import { useScrollMemory } from "../hooks/use-scroll-memory" import { createStore } from "../lib/store" import { cn } from "../lib/utils" import { Button } from "../ui/button" import { Kbd } from "../ui/kbd" import { Tooltip, TooltipContent, TooltipTrigger } from "../ui/tooltip" +import { useShell } from "./shell-provider" // Развёрнутость общая для всех разделов: переход в другой раздел её не сбрасывает. const maximizedStore = createStore(false) @@ -14,10 +16,14 @@ const toggleMaximized = () => maximizedStore.set((v) => !v) /** * Рамка раздела со вкладками: карточка, сверху полоса (`SectionTabsBar`), под ней контент. * Alt+F или кнопка в полосе — развернуть на весь экран поверх меню, Esc — свернуть. + * Прокрутка контента запоминается по адресу: вернулся на вкладку — на том же месте. * Разделы без вкладок — `PageFrame`. */ export function SectionFrame({ bar, children }: { bar: React.ReactNode; children: React.ReactNode }) { const maximized = maximizedStore.use() + const { pathname, search } = useShell() + const contentRef = React.useRef(null) + useScrollMemory(contentRef, pathname + search) // Alt+F — развернуть/свернуть, Esc — свернуть (если не открыт диалог или меню). React.useEffect(() => { @@ -54,7 +60,9 @@ export function SectionFrame({ bar, children }: { bar: React.ReactNode; children )} > {bar} -
{children}
+
+ {children} +
)