Guest User

Untitled

a guest
Jan 25th, 2026
171
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Scrolling helper ported from the JS renderer.
  2. // Design intent: wheel scrolling moves by whole rows with snapping, short scrolls animate,
  3. // long scrolls jump immediately, and native/pointer scrolling remains usable.
  4. let rowScrollBound = false;
  5. let rowHeightCache = null;
  6. let rowOffsetCache = null;
  7. let rowStrideCache = null;
  8. let rowSnapEnabled = true;
  9. // Debug logging disabled for handoff; leave commented for easy re-enable.
  10. // const DEBUG_SCROLL = true;
  11. const FALLBACK_ROW_HEIGHT = 24;
  12. const fmt2 = value => (typeof value === "number" ? Math.round(value * 100) / 100 : value);
  13. let lastSnappedTarget = null;
  14. let lastSnapSeq = 0;
  15.  
  16. // const formatDebug = value => {
  17. //   try {
  18. //     return typeof value === "string" ? value : JSON.stringify(value);
  19. //   } catch {
  20. //     return String(value);
  21. //   }
  22. // };
  23.  
  24. // const makeDebugLogger = log => (...args) => {
  25. //   if (!DEBUG_SCROLL) {
  26. //     return;
  27. //   }
  28. //   const text = args.map(formatDebug).join(" ");
  29. //   if (log) {
  30. //     log(`[scroll-debug] ${text}`);
  31. //   } else {
  32. //     console.debug("[scroll-debug]", ...args);
  33. //   }
  34. // };
  35.  
  36. export function getRowMetrics() {
  37.   return {
  38.     rowHeight: rowHeightCache,
  39.     rowOffset: rowOffsetCache,
  40.     rowStride: rowStrideCache
  41.   };
  42. }
  43.  
  44. export function bindRowScroll({ gridEl, gridTable, scheduleVirtualRender, log, getCurrentMod }) {
  45.   // Bind once per grid element to avoid stacking multiple wheel/scroll handlers.
  46.   if (rowScrollBound || !gridEl) {
  47.     return;
  48.   }
  49.   rowScrollBound = true;
  50.   const debug = () => {};
  51.   // Easing factor for "short" wheel notches; lower = smoother/slower, higher = snappier.
  52.   const ease = 0.2;
  53.   // When we're within this distance of the target, snap to the exact row boundary.
  54.   const epsilon = 0.75;
  55.   // One wheel notch moves exactly N rows by design.
  56.   const rowsPerNotch = 5;
  57.   const pointerDownRef = { current: false };
  58.   const isAnimatingRef = { current: false };
  59.   // targetRef is the intended scroll position used by the animator.
  60.   const targetRef = { top: 0, left: 0 };
  61.   const wheelBurstRef = { lastTs: 0, delta: 0, count: 0 };
  62.   const lastScrollLogSeqRef = { current: 0 };
  63.   const lastAnimateLogSeqRef = { current: 0 };
  64.   const lastScrollTopRef = { current: gridEl.scrollTop };
  65.   let rafId = null;
  66.  
  67.   const clampTarget = reason => {
  68.     // Clamp to the scrollable bounds; snapping should never push beyond content.
  69.     const minTop = rowOffsetCache != null ? rowOffsetCache : 0;
  70.     const maxTop = Math.max(minTop, gridEl.scrollHeight - gridEl.clientHeight);
  71.     const maxLeft = Math.max(0, gridEl.scrollWidth - gridEl.clientWidth);
  72.     const before = { top: targetRef.top, left: targetRef.left };
  73.     targetRef.top = Math.min(maxTop, Math.max(minTop, targetRef.top));
  74.     targetRef.left = Math.min(maxLeft, Math.max(0, targetRef.left));
  75.     // debug("clamp", `seq=${lastSnapSeq} reason=${reason} minTop=${fmt2(minTop)} maxTop=${fmt2(maxTop)} before=${fmt2(before.top)} after=${fmt2(targetRef.top)}`);
  76.   };
  77.  
  78.   const refreshRowMetrics = () => {
  79.     // Compute row height/stride and the baseline offset used for snapping.
  80.     // When virtualization is active, prefer measuring real DOM rows to match
  81.     // the rendered layout exactly.
  82.     rowSnapEnabled = true;
  83.     const styles = getComputedStyle(gridEl);
  84.     let rowHeight = Number.parseFloat(styles.getPropertyValue("--app-row-height-px"));
  85.     const gridline = Number.parseFloat(styles.getPropertyValue("--app-gridline-h-px"));
  86.     const hasVirtual = gridTable ? gridTable.querySelector("tbody tr.virtual-spacer") : null;
  87.     const rows = gridTable ? gridTable.querySelectorAll("tbody tr:not(.virtual-spacer)") : null;
  88.     if (hasVirtual) {
  89.       const gridRect = gridEl.getBoundingClientRect();
  90.       if (rows && rows.length > 1) {
  91.         const firstRect = rows[0].getBoundingClientRect();
  92.         const secondRect = rows[1].getBoundingClientRect();
  93.         const stride = secondRect.top - firstRect.top;
  94.         rowHeightCache = firstRect.height || rowHeight || FALLBACK_ROW_HEIGHT;
  95.         rowStrideCache = stride > 0 ? stride : rowHeightCache;
  96.         rowOffsetCache = firstRect.top - gridRect.top + gridEl.scrollTop;
  97.         // debug("metrics-detail-virtual", `mode=measured rowHeight=${fmt2(rowHeightCache)} rowStride=${fmt2(rowStrideCache)} rowOffset=${fmt2(rowOffsetCache)} clientTop=${fmt2(gridEl.clientTop)}`);
  98.         // debug("metrics", `mode=virtual rowHeight=${fmt2(rowHeightCache)} rowStride=${fmt2(rowStrideCache)} rowOffset=${fmt2(rowOffsetCache)}`);
  99.         return;
  100.       }
  101.       if (!Number.isFinite(rowHeight) || rowHeight <= 0) {
  102.         rowHeight = FALLBACK_ROW_HEIGHT;
  103.       }
  104.       const grid = Number.isFinite(gridline) && gridline >= 0 ? gridline : 1;
  105.       rowHeightCache = rowHeight;
  106.       rowStrideCache = rowHeight + grid;
  107.       rowOffsetCache = 0;
  108.       // debug("metrics-detail-virtual", `mode=css rowHeight=${fmt2(rowHeightCache)} rowStride=${fmt2(rowStrideCache)} cssRowHeight=${fmt2(rowHeight)} cssGridline=${fmt2(grid)} clientTop=${fmt2(gridEl.clientTop)}`);
  109.       // debug("metrics", `mode=virtual rowHeight=${fmt2(rowHeightCache)} rowStride=${fmt2(rowStrideCache)} rowOffset=${fmt2(rowOffsetCache)}`);
  110.       return;
  111.     }
  112.     if (!Number.isFinite(rowHeight) || rowHeight <= 0) {
  113.       if (rows && rows.length > 0) {
  114.         rowHeight = rows[0].getBoundingClientRect().height;
  115.       } else {
  116.         rowHeight = FALLBACK_ROW_HEIGHT;
  117.       }
  118.     }
  119.     if (rows && rows.length > 1) {
  120.       const firstHeight = rows[0].getBoundingClientRect().height;
  121.       const secondHeight = rows[1].getBoundingClientRect().height;
  122.       if (Math.abs(firstHeight - secondHeight) > 0.75) {
  123.         rowSnapEnabled = false;
  124.         console.warn("Row heights vary; scroll snapping disabled.");
  125.       }
  126.     }
  127.     rowHeightCache = rowHeight || FALLBACK_ROW_HEIGHT;
  128.     if (rows && rows.length > 0) {
  129.       const gridRect = gridEl.getBoundingClientRect();
  130.       const firstRect = rows[0].getBoundingClientRect();
  131.       // debug("metrics-rows", `rows=${rows.length} gridTop=${fmt2(gridRect.top)} firstTop=${fmt2(firstRect.top)}`);
  132.       rowOffsetCache = firstRect.top - gridRect.top + gridEl.scrollTop;
  133.       // 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)}`);
  134.       if (rows.length > 1) {
  135.         const secondRect = rows[1].getBoundingClientRect();
  136.         const stride = secondRect.top - firstRect.top;
  137.         rowStrideCache = stride > 0 ? stride : rowHeightCache;
  138.       } else {
  139.         rowStrideCache = rowHeightCache;
  140.       }
  141.     } else {
  142.       rowOffsetCache = 0;
  143.       rowStrideCache = rowHeightCache;
  144.     }
  145.     // debug("metrics", `mode=dom rowHeight=${fmt2(rowHeightCache)} rowStride=${fmt2(rowStrideCache)} rowOffset=${fmt2(rowOffsetCache)}`);
  146.   };
  147.  
  148.   refreshRowMetrics();
  149.   targetRef.top = gridEl.scrollTop;
  150.   targetRef.left = gridEl.scrollLeft;
  151.   clampTarget("init");
  152.   window.addEventListener("resize", () => {
  153.     // Recompute metrics on resize to keep snapping aligned with row geometry.
  154.     refreshRowMetrics();
  155.     clampTarget("resize");
  156.   });
  157.  
  158.   const stopAnimation = () => {
  159.     if (rafId) {
  160.       cancelAnimationFrame(rafId);
  161.       rafId = null;
  162.     }
  163.     isAnimatingRef.current = false;
  164.   };
  165.  
  166.   const animate = () => {
  167.     // Smoothly ease toward the target for short wheel notches.
  168.     if (pointerDownRef.current) {
  169.       stopAnimation();
  170.       return;
  171.     }
  172.     const currentTop = gridEl.scrollTop;
  173.     const currentLeft = gridEl.scrollLeft;
  174.     const nextTop = currentTop + (targetRef.top - currentTop) * ease;
  175.     const nextLeft = currentLeft + (targetRef.left - currentLeft) * ease;
  176.     const doneTop = Math.abs(targetRef.top - currentTop) < epsilon;
  177.     const doneLeft = Math.abs(targetRef.left - currentLeft) < epsilon;
  178.     isAnimatingRef.current = true;
  179.     if (lastSnapSeq !== lastAnimateLogSeqRef.current) {
  180.       lastAnimateLogSeqRef.current = lastSnapSeq;
  181.       // debug("animate-frame", `seq=${lastSnapSeq} current=${fmt2(currentTop)} target=${fmt2(targetRef.top)}`);
  182.     }
  183.     if (doneTop && doneLeft) {
  184.       if (lastSnapSeq > 0) {
  185.         // debug("animate-stop", `seq=${lastSnapSeq} current=${fmt2(currentTop)} target=${fmt2(targetRef.top)} diff=${fmt2(targetRef.top - currentTop)}`);
  186.       }
  187.       // Final snap to the exact target eliminates fractional drift.
  188.       gridEl.scrollTop = targetRef.top;
  189.       gridEl.scrollLeft = targetRef.left;
  190.       stopAnimation();
  191.       scheduleVirtualRender();
  192.       return;
  193.     }
  194.     gridEl.scrollTo({ top: nextTop, left: nextLeft, behavior: "auto" });
  195.     scheduleVirtualRender();
  196.     rafId = requestAnimationFrame(animate);
  197.   };
  198.  
  199.   gridEl.addEventListener("wheel", event => {
  200.     // Core design: wheel scroll moves by rows, not pixels. Short notches animate;
  201.     // large bursts jump to the target immediately.
  202.     if (event.ctrlKey) {
  203.       return;
  204.     }
  205.     event.preventDefault();
  206.     const useHorizontal = event.shiftKey || Math.abs(event.deltaX) > Math.abs(event.deltaY);
  207.     const delta = useHorizontal ? (event.deltaX !== 0 ? event.deltaX : event.deltaY) : event.deltaY;
  208.     const absDelta = Math.abs(delta);
  209.     const isWheelNotch = event.deltaMode === 1 || (event.deltaMode === 0 && absDelta >= 40);
  210.     const rowStride = rowStrideCache || rowHeightCache || FALLBACK_ROW_HEIGHT;
  211.     const rowOffset = rowOffsetCache || 0;
  212.     const notchCount = event.deltaMode === 1 ? Math.max(1, Math.round(absDelta)) : Math.max(1, Math.round(absDelta / 120));
  213.     lastSnappedTarget = null;
  214.     if (useHorizontal) {
  215.       if (isWheelNotch) {
  216.         const stepPx = rowsPerNotch * rowStride * notchCount;
  217.         targetRef.left += Math.sign(delta) * stepPx;
  218.       } else {
  219.         targetRef.left += delta;
  220.       }
  221.     } else {
  222.       if (isWheelNotch) {
  223.         const stepPx = rowsPerNotch * rowStride * notchCount;
  224.         targetRef.top += Math.sign(delta) * stepPx;
  225.         if (rowSnapEnabled) {
  226.           // Snap to the nearest row boundary based on the measured offset/stride.
  227.           const unsnapped = targetRef.top;
  228.           const snapBase = rowOffset;
  229.           const snapStride = rowStride;
  230.           const snapped = snapBase + Math.round((unsnapped - snapBase) / snapStride) * snapStride;
  231.           targetRef.top = snapped;
  232.           lastSnappedTarget = snapped;
  233.           lastSnapSeq += 1;
  234.         }
  235.       } else {
  236.         // Pixel-precision scrolling for trackpads; no snapping.
  237.         targetRef.top += delta;
  238.       }
  239.     }
  240.     clampTarget("wheel");
  241.     const now = performance.now();
  242.     if (now - wheelBurstRef.lastTs < 80) {
  243.       wheelBurstRef.delta += absDelta;
  244.       wheelBurstRef.count += 1;
  245.     } else {
  246.       wheelBurstRef.delta = absDelta;
  247.       wheelBurstRef.count = 1;
  248.     }
  249.     wheelBurstRef.lastTs = now;
  250.     const isLargeNotch = isWheelNotch && (wheelBurstRef.delta >= 240 || wheelBurstRef.count >= 3);
  251.     if (isWheelNotch && isLargeNotch) {
  252.       // Large scroll bursts skip the easing so the UI stays responsive.
  253.       stopAnimation();
  254.       gridEl.scrollTop = targetRef.top;
  255.       gridEl.scrollLeft = targetRef.left;
  256.       scheduleVirtualRender();
  257.       return;
  258.     }
  259.     if (!isAnimatingRef.current) {
  260.       rafId = requestAnimationFrame(animate);
  261.     }
  262.   }, { passive: false });
  263.  
  264.   gridEl.addEventListener("scroll", () => {
  265.     // Native scroll updates (scrollbar drag, touchpad, etc.) update the target.
  266.     const prevScrollTop = lastScrollTopRef.current;
  267.     const currentScrollTop = gridEl.scrollTop;
  268.     lastScrollTopRef.current = currentScrollTop;
  269.     if (!isAnimatingRef.current && !pointerDownRef.current) {
  270.       targetRef.top = currentScrollTop;
  271.       targetRef.left = gridEl.scrollLeft;
  272.       lastSnappedTarget = null;
  273.       clampTarget("native-scroll");
  274.     }
  275.     if (lastSnapSeq !== lastScrollLogSeqRef.current) {
  276.       lastScrollLogSeqRef.current = lastSnapSeq;
  277.       const dir = currentScrollTop > prevScrollTop ? "down" : currentScrollTop < prevScrollTop ? "up" : "flat";
  278.       // debug("scroll-event", `seq=${lastSnapSeq} dir=${dir} scrollNow=${fmt2(currentScrollTop)} targetRef=${fmt2(targetRef.top)}`);
  279.     }
  280.     scheduleVirtualRender();
  281.   }, { passive: true });
  282.  
  283.   gridEl.addEventListener("pointerdown", () => {
  284.     // Pointer-based scrolling should not be overridden by the animator.
  285.     pointerDownRef.current = true;
  286.     stopAnimation();
  287.   });
  288.   const clearPointerDown = () => {
  289.     pointerDownRef.current = false;
  290.     // Sync the target after pointer interactions to avoid jumps.
  291.     targetRef.top = gridEl.scrollTop;
  292.     targetRef.left = gridEl.scrollLeft;
  293.     clampTarget();
  294.     scheduleVirtualRender();
  295.   };
  296.   window.addEventListener("pointerup", clearPointerDown);
  297.   window.addEventListener("pointercancel", clearPointerDown);
  298.   gridEl.addEventListener("mouseleave", clearPointerDown);
  299.  
  300.   gridEl._rowScrollApi = {
  301.     refresh: refreshRowMetrics,
  302.     stop: () => {
  303.       // External stop lets callers cancel animations cleanly.
  304.       stopAnimation();
  305.       targetRef.top = gridEl.scrollTop;
  306.       targetRef.left = gridEl.scrollLeft;
  307.       clampTarget();
  308.     },
  309.     syncTarget: () => {
  310.       // External sync keeps the target aligned with any external scroll change.
  311.       stopAnimation();
  312.       targetRef.top = gridEl.scrollTop;
  313.       targetRef.left = gridEl.scrollLeft;
  314.       clampTarget();
  315.       const mod = getCurrentMod ? getCurrentMod() : null;
  316.       if (log) {
  317.         log(`scroll-metrics mod=${mod} rowHeight=${rowHeightCache} rowStride=${rowStrideCache} rowOffset=${rowOffsetCache} scrollHeight=${gridEl.scrollHeight} clientHeight=${gridEl.clientHeight}`);
  318.       }
  319.       scheduleVirtualRender();
  320.     },
  321.     resnap: () => {},
  322.     getLastSnappedTarget: () => lastSnappedTarget,
  323.     getTargetTop: () => targetRef.top,
  324.     getLastSnapSeq: () => lastSnapSeq
  325.   };
  326. }
  327.  
Advertisement
Add Comment
Please, Sign In to add comment