Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Scrolling helper ported from the JS renderer.
- // Design intent: wheel scrolling moves by whole rows with snapping, short scrolls animate,
- // long scrolls jump immediately, and native/pointer scrolling remains usable.
- let rowScrollBound = false;
- let rowHeightCache = null;
- let rowOffsetCache = null;
- let rowStrideCache = null;
- let rowSnapEnabled = true;
- // Debug logging disabled for handoff; leave commented for easy re-enable.
- // const DEBUG_SCROLL = true;
- const FALLBACK_ROW_HEIGHT = 24;
- const fmt2 = value => (typeof value === "number" ? Math.round(value * 100) / 100 : value);
- let lastSnappedTarget = null;
- let lastSnapSeq = 0;
- // const formatDebug = value => {
- // try {
- // return typeof value === "string" ? value : JSON.stringify(value);
- // } catch {
- // return String(value);
- // }
- // };
- // const makeDebugLogger = log => (...args) => {
- // if (!DEBUG_SCROLL) {
- // return;
- // }
- // const text = args.map(formatDebug).join(" ");
- // if (log) {
- // log(`[scroll-debug] ${text}`);
- // } else {
- // console.debug("[scroll-debug]", ...args);
- // }
- // };
- export function getRowMetrics() {
- return {
- rowHeight: rowHeightCache,
- rowOffset: rowOffsetCache,
- rowStride: rowStrideCache
- };
- }
- export function bindRowScroll({ gridEl, gridTable, scheduleVirtualRender, log, getCurrentMod }) {
- // Bind once per grid element to avoid stacking multiple wheel/scroll handlers.
- if (rowScrollBound || !gridEl) {
- return;
- }
- rowScrollBound = true;
- const debug = () => {};
- // Easing factor for "short" wheel notches; lower = smoother/slower, higher = snappier.
- const ease = 0.2;
- // When we're within this distance of the target, snap to the exact row boundary.
- const epsilon = 0.75;
- // One wheel notch moves exactly N rows by design.
- const rowsPerNotch = 5;
- const pointerDownRef = { current: false };
- const isAnimatingRef = { current: false };
- // targetRef is the intended scroll position used by the animator.
- const targetRef = { top: 0, left: 0 };
- const wheelBurstRef = { lastTs: 0, delta: 0, count: 0 };
- const lastScrollLogSeqRef = { current: 0 };
- const lastAnimateLogSeqRef = { current: 0 };
- const lastScrollTopRef = { current: gridEl.scrollTop };
- let rafId = null;
- const clampTarget = reason => {
- // Clamp to the scrollable bounds; snapping should never push beyond content.
- const minTop = rowOffsetCache != null ? rowOffsetCache : 0;
- const maxTop = Math.max(minTop, gridEl.scrollHeight - gridEl.clientHeight);
- const maxLeft = Math.max(0, gridEl.scrollWidth - gridEl.clientWidth);
- const before = { top: targetRef.top, left: targetRef.left };
- targetRef.top = Math.min(maxTop, Math.max(minTop, targetRef.top));
- targetRef.left = Math.min(maxLeft, Math.max(0, targetRef.left));
- // debug("clamp", `seq=${lastSnapSeq} reason=${reason} minTop=${fmt2(minTop)} maxTop=${fmt2(maxTop)} before=${fmt2(before.top)} after=${fmt2(targetRef.top)}`);
- };
- const refreshRowMetrics = () => {
- // Compute row height/stride and the baseline offset used for snapping.
- // When virtualization is active, prefer measuring real DOM rows to match
- // the rendered layout exactly.
- rowSnapEnabled = true;
- const styles = getComputedStyle(gridEl);
- let rowHeight = Number.parseFloat(styles.getPropertyValue("--app-row-height-px"));
- const gridline = Number.parseFloat(styles.getPropertyValue("--app-gridline-h-px"));
- const hasVirtual = gridTable ? gridTable.querySelector("tbody tr.virtual-spacer") : null;
- const rows = gridTable ? gridTable.querySelectorAll("tbody tr:not(.virtual-spacer)") : null;
- if (hasVirtual) {
- const gridRect = gridEl.getBoundingClientRect();
- if (rows && rows.length > 1) {
- const firstRect = rows[0].getBoundingClientRect();
- const secondRect = rows[1].getBoundingClientRect();
- const stride = secondRect.top - firstRect.top;
- rowHeightCache = firstRect.height || rowHeight || FALLBACK_ROW_HEIGHT;
- rowStrideCache = stride > 0 ? stride : rowHeightCache;
- rowOffsetCache = firstRect.top - gridRect.top + gridEl.scrollTop;
- // debug("metrics-detail-virtual", `mode=measured rowHeight=${fmt2(rowHeightCache)} rowStride=${fmt2(rowStrideCache)} rowOffset=${fmt2(rowOffsetCache)} clientTop=${fmt2(gridEl.clientTop)}`);
- // debug("metrics", `mode=virtual rowHeight=${fmt2(rowHeightCache)} rowStride=${fmt2(rowStrideCache)} rowOffset=${fmt2(rowOffsetCache)}`);
- return;
- }
- if (!Number.isFinite(rowHeight) || rowHeight <= 0) {
- rowHeight = FALLBACK_ROW_HEIGHT;
- }
- const grid = Number.isFinite(gridline) && gridline >= 0 ? gridline : 1;
- rowHeightCache = rowHeight;
- rowStrideCache = rowHeight + grid;
- rowOffsetCache = 0;
- // debug("metrics-detail-virtual", `mode=css rowHeight=${fmt2(rowHeightCache)} rowStride=${fmt2(rowStrideCache)} cssRowHeight=${fmt2(rowHeight)} cssGridline=${fmt2(grid)} clientTop=${fmt2(gridEl.clientTop)}`);
- // debug("metrics", `mode=virtual rowHeight=${fmt2(rowHeightCache)} rowStride=${fmt2(rowStrideCache)} rowOffset=${fmt2(rowOffsetCache)}`);
- return;
- }
- if (!Number.isFinite(rowHeight) || rowHeight <= 0) {
- if (rows && rows.length > 0) {
- rowHeight = rows[0].getBoundingClientRect().height;
- } else {
- rowHeight = FALLBACK_ROW_HEIGHT;
- }
- }
- if (rows && rows.length > 1) {
- const firstHeight = rows[0].getBoundingClientRect().height;
- const secondHeight = rows[1].getBoundingClientRect().height;
- if (Math.abs(firstHeight - secondHeight) > 0.75) {
- rowSnapEnabled = false;
- console.warn("Row heights vary; scroll snapping disabled.");
- }
- }
- rowHeightCache = rowHeight || FALLBACK_ROW_HEIGHT;
- if (rows && rows.length > 0) {
- const gridRect = gridEl.getBoundingClientRect();
- const firstRect = rows[0].getBoundingClientRect();
- // debug("metrics-rows", `rows=${rows.length} gridTop=${fmt2(gridRect.top)} firstTop=${fmt2(firstRect.top)}`);
- rowOffsetCache = firstRect.top - gridRect.top + gridEl.scrollTop;
- // debug("metrics-detail", `theadH=${fmt2(headerRect ? headerRect.height : 0)} clientTop=${fmt2(gridEl.clientTop)} scrollTop=${fmt2(gridEl.scrollTop)} gridTop=${fmt2(gridRect.top)} firstTop=${fmt2(firstRect.top)} rowOffset=${fmt2(rowOffsetCache)}`);
- if (rows.length > 1) {
- const secondRect = rows[1].getBoundingClientRect();
- const stride = secondRect.top - firstRect.top;
- rowStrideCache = stride > 0 ? stride : rowHeightCache;
- } else {
- rowStrideCache = rowHeightCache;
- }
- } else {
- rowOffsetCache = 0;
- rowStrideCache = rowHeightCache;
- }
- // debug("metrics", `mode=dom rowHeight=${fmt2(rowHeightCache)} rowStride=${fmt2(rowStrideCache)} rowOffset=${fmt2(rowOffsetCache)}`);
- };
- refreshRowMetrics();
- targetRef.top = gridEl.scrollTop;
- targetRef.left = gridEl.scrollLeft;
- clampTarget("init");
- window.addEventListener("resize", () => {
- // Recompute metrics on resize to keep snapping aligned with row geometry.
- refreshRowMetrics();
- clampTarget("resize");
- });
- const stopAnimation = () => {
- if (rafId) {
- cancelAnimationFrame(rafId);
- rafId = null;
- }
- isAnimatingRef.current = false;
- };
- const animate = () => {
- // Smoothly ease toward the target for short wheel notches.
- if (pointerDownRef.current) {
- stopAnimation();
- return;
- }
- const currentTop = gridEl.scrollTop;
- const currentLeft = gridEl.scrollLeft;
- const nextTop = currentTop + (targetRef.top - currentTop) * ease;
- const nextLeft = currentLeft + (targetRef.left - currentLeft) * ease;
- const doneTop = Math.abs(targetRef.top - currentTop) < epsilon;
- const doneLeft = Math.abs(targetRef.left - currentLeft) < epsilon;
- isAnimatingRef.current = true;
- if (lastSnapSeq !== lastAnimateLogSeqRef.current) {
- lastAnimateLogSeqRef.current = lastSnapSeq;
- // debug("animate-frame", `seq=${lastSnapSeq} current=${fmt2(currentTop)} target=${fmt2(targetRef.top)}`);
- }
- if (doneTop && doneLeft) {
- if (lastSnapSeq > 0) {
- // debug("animate-stop", `seq=${lastSnapSeq} current=${fmt2(currentTop)} target=${fmt2(targetRef.top)} diff=${fmt2(targetRef.top - currentTop)}`);
- }
- // Final snap to the exact target eliminates fractional drift.
- gridEl.scrollTop = targetRef.top;
- gridEl.scrollLeft = targetRef.left;
- stopAnimation();
- scheduleVirtualRender();
- return;
- }
- gridEl.scrollTo({ top: nextTop, left: nextLeft, behavior: "auto" });
- scheduleVirtualRender();
- rafId = requestAnimationFrame(animate);
- };
- gridEl.addEventListener("wheel", event => {
- // Core design: wheel scroll moves by rows, not pixels. Short notches animate;
- // large bursts jump to the target immediately.
- if (event.ctrlKey) {
- return;
- }
- event.preventDefault();
- const useHorizontal = event.shiftKey || Math.abs(event.deltaX) > Math.abs(event.deltaY);
- const delta = useHorizontal ? (event.deltaX !== 0 ? event.deltaX : event.deltaY) : event.deltaY;
- const absDelta = Math.abs(delta);
- const isWheelNotch = event.deltaMode === 1 || (event.deltaMode === 0 && absDelta >= 40);
- const rowStride = rowStrideCache || rowHeightCache || FALLBACK_ROW_HEIGHT;
- const rowOffset = rowOffsetCache || 0;
- const notchCount = event.deltaMode === 1 ? Math.max(1, Math.round(absDelta)) : Math.max(1, Math.round(absDelta / 120));
- lastSnappedTarget = null;
- if (useHorizontal) {
- if (isWheelNotch) {
- const stepPx = rowsPerNotch * rowStride * notchCount;
- targetRef.left += Math.sign(delta) * stepPx;
- } else {
- targetRef.left += delta;
- }
- } else {
- if (isWheelNotch) {
- const stepPx = rowsPerNotch * rowStride * notchCount;
- targetRef.top += Math.sign(delta) * stepPx;
- if (rowSnapEnabled) {
- // Snap to the nearest row boundary based on the measured offset/stride.
- const unsnapped = targetRef.top;
- const snapBase = rowOffset;
- const snapStride = rowStride;
- const snapped = snapBase + Math.round((unsnapped - snapBase) / snapStride) * snapStride;
- targetRef.top = snapped;
- lastSnappedTarget = snapped;
- lastSnapSeq += 1;
- }
- } else {
- // Pixel-precision scrolling for trackpads; no snapping.
- targetRef.top += delta;
- }
- }
- clampTarget("wheel");
- const now = performance.now();
- if (now - wheelBurstRef.lastTs < 80) {
- wheelBurstRef.delta += absDelta;
- wheelBurstRef.count += 1;
- } else {
- wheelBurstRef.delta = absDelta;
- wheelBurstRef.count = 1;
- }
- wheelBurstRef.lastTs = now;
- const isLargeNotch = isWheelNotch && (wheelBurstRef.delta >= 240 || wheelBurstRef.count >= 3);
- if (isWheelNotch && isLargeNotch) {
- // Large scroll bursts skip the easing so the UI stays responsive.
- stopAnimation();
- gridEl.scrollTop = targetRef.top;
- gridEl.scrollLeft = targetRef.left;
- scheduleVirtualRender();
- return;
- }
- if (!isAnimatingRef.current) {
- rafId = requestAnimationFrame(animate);
- }
- }, { passive: false });
- gridEl.addEventListener("scroll", () => {
- // Native scroll updates (scrollbar drag, touchpad, etc.) update the target.
- const prevScrollTop = lastScrollTopRef.current;
- const currentScrollTop = gridEl.scrollTop;
- lastScrollTopRef.current = currentScrollTop;
- if (!isAnimatingRef.current && !pointerDownRef.current) {
- targetRef.top = currentScrollTop;
- targetRef.left = gridEl.scrollLeft;
- lastSnappedTarget = null;
- clampTarget("native-scroll");
- }
- if (lastSnapSeq !== lastScrollLogSeqRef.current) {
- lastScrollLogSeqRef.current = lastSnapSeq;
- const dir = currentScrollTop > prevScrollTop ? "down" : currentScrollTop < prevScrollTop ? "up" : "flat";
- // debug("scroll-event", `seq=${lastSnapSeq} dir=${dir} scrollNow=${fmt2(currentScrollTop)} targetRef=${fmt2(targetRef.top)}`);
- }
- scheduleVirtualRender();
- }, { passive: true });
- gridEl.addEventListener("pointerdown", () => {
- // Pointer-based scrolling should not be overridden by the animator.
- pointerDownRef.current = true;
- stopAnimation();
- });
- const clearPointerDown = () => {
- pointerDownRef.current = false;
- // Sync the target after pointer interactions to avoid jumps.
- targetRef.top = gridEl.scrollTop;
- targetRef.left = gridEl.scrollLeft;
- clampTarget();
- scheduleVirtualRender();
- };
- window.addEventListener("pointerup", clearPointerDown);
- window.addEventListener("pointercancel", clearPointerDown);
- gridEl.addEventListener("mouseleave", clearPointerDown);
- gridEl._rowScrollApi = {
- refresh: refreshRowMetrics,
- stop: () => {
- // External stop lets callers cancel animations cleanly.
- stopAnimation();
- targetRef.top = gridEl.scrollTop;
- targetRef.left = gridEl.scrollLeft;
- clampTarget();
- },
- syncTarget: () => {
- // External sync keeps the target aligned with any external scroll change.
- stopAnimation();
- targetRef.top = gridEl.scrollTop;
- targetRef.left = gridEl.scrollLeft;
- clampTarget();
- const mod = getCurrentMod ? getCurrentMod() : null;
- if (log) {
- log(`scroll-metrics mod=${mod} rowHeight=${rowHeightCache} rowStride=${rowStrideCache} rowOffset=${rowOffsetCache} scrollHeight=${gridEl.scrollHeight} clientHeight=${gridEl.clientHeight}`);
- }
- scheduleVirtualRender();
- },
- resnap: () => {},
- getLastSnappedTarget: () => lastSnappedTarget,
- getTargetTop: () => targetRef.top,
- getLastSnapSeq: () => lastSnapSeq
- };
- }
Advertisement
Add Comment
Please, Sign In to add comment