"use client" import * as React from "react" import { bindVerticalScrollListeners, getStickyTableHeaderOffset } from "../../lib/page-scroll-port" import { rafThrottle } from "../../lib/raf-throttle" import { Tip } from "../ui/tip" import { DropdownMenu } from "../ui/dropdown-menu" import { useIsClient } from "../../hooks/use-is-client" import type { ColumnDef } from "./types" import { hasVisibleFocus } from "./table-helpers" /** * Sticky column header: tracks when the real header scrolls out of view, mirrors its * horizontal scroll into the floating clone, and hides the clone while a header * control has visible focus or an open menu. The clone is positioned directly on * the DOM, not through React state, so scrolling never re-renders the table. */ export function useFloatingHeader>({ displayCols, showColumnHeaders, totalWidth, }: { displayCols: ColumnDef[] showColumnHeaders: boolean totalWidth: number }) { const tableWrapRef = React.useRef(null) const tableHeadRef = React.useRef(null) const [headerIsStuck, setHeaderIsStuck] = React.useState(false) /** * Visible keyboard focus (or an open column menu) in the real `` while * sticky — unhide it and drop the floating clone so the focus ring + ⋯ show. * Parent `opacity-0` otherwise hides children even when Tip portals the label. * Gated on `:focus-visible`, not `:focus`: a mouse click on a column ⋯ leaves * focus parked there, which would otherwise keep the clone unmounted for good. */ const [headerKeyboardActive, setHeaderKeyboardActive] = React.useState(false) const [headerMenuOpenCount, setHeaderMenuOpenCount] = React.useState(0) const headerSurfaceActive = headerKeyboardActive || headerMenuOpenCount > 0 const effectiveHeaderStuck = showColumnHeaders && headerIsStuck && !headerSurfaceActive const bumpHeaderMenuOpen = React.useCallback((open: boolean) => { setHeaderMenuOpenCount(n => Math.max(0, n + (open ? 1 : -1))) }, []) // Document-level sync — Tip + Dropdown can make thead focusCapture alone flaky. // Portaled menus are covered by `headerMenuOpenCount` (real thead only), not // by treating every `[role=menu]` as active (that would unmount the floating clone). React.useLayoutEffect(() => { if (!headerIsStuck) { setHeaderKeyboardActive(false) return } const sync = () => { const head = tableHeadRef.current const active = document.activeElement const inHead = !!(active && head?.contains(active)) setHeaderKeyboardActive(inHead && hasVisibleFocus(active)) } document.addEventListener("focusin", sync) document.addEventListener("focusout", sync) sync() return () => { document.removeEventListener("focusin", sync) document.removeEventListener("focusout", sync) } }, [headerIsStuck]) // Horizontal scroll for the floating header — DOM-mutated (same rationale as // floatingHeaderWrapperRef). React state here re-rendered the whole sticky // thead on every horizontal tick. const headerScrollLeftRef = React.useRef(0) const floatingHeaderTranslateRef = React.useRef(null) // The sticky-header position is mutated **directly on the DOM** rather // than going through React state. State updates on every scroll tick // were re-rendering the entire `` (with its full DropdownMenu per // column) on each rAF — visibly sluggish on long tables. The wrapper // ref's style is updated inside `apply()` below; the gate stays in // React state via `headerIsStuck` (a boolean that flips rarely). const floatingHeaderWrapperRef = React.useRef(null) // Cache last-applied position so we skip DOM writes when nothing // changed. Pure vertical scroll doesn't move `rect.left`/`rect.width`, // so the wrapper's style stays untouched and the browser keeps layout // cached frame-to-frame. Without this, every rAF wrote 4 style props → // browser invalidated layout → next read forced a layout flush → // visible scroll jank. const lastFloatingHeaderApplied = React.useRef<{ left: number width: number top: number }>({ left: -1, width: -1, top: -1 }) // Inner `` element of the scroll wrapper, captured once when the // header pins. Avoids `querySelector + getBoundingClientRect` on every // scroll tick (the latter forces a full layout pass on the table tree). const innerTableElRef = React.useRef(null) const [floatingHeaderTableWidth, setFloatingHeaderTableWidth] = React.useState(totalWidth) /** * Inner scrollport width of the sticky header (body's `clientWidth` — * already excludes the wrapper's `border-x`). Tracked separately from * the wrapper's outer width (which has its own `border border-border` * that overlays the body's borders exactly). Used by * `floatingHeaderPinnedStyle` to compute max-scroll for right-pinned columns. */ const [floatingHeaderInnerWidth, setFloatingHeaderInnerWidth] = React.useState(0) const syncFloatingHeaderScroll = React.useCallback((scrollLeft: number) => { if (headerScrollLeftRef.current === scrollLeft) return headerScrollLeftRef.current = scrollLeft const translateEl = floatingHeaderTranslateRef.current if (translateEl) { translateEl.style.transform = `translateX(${-scrollLeft}px)` } const visibleWidth = floatingHeaderInnerWidth > 0 ? floatingHeaderInnerWidth : tableWrapRef.current?.clientWidth ?? floatingHeaderTableWidth const maxScroll = Math.max(0, floatingHeaderTableWidth - visibleWidth) const pinned = translateEl?.querySelectorAll("[data-dt-floating-pin]") pinned?.forEach(el => { const pin = el.dataset.dtFloatingPin if (pin !== "left" && pin !== "right") return const translateX = pin === "left" ? scrollLeft : scrollLeft - maxScroll el.style.transform = `translateX(${translateX}px)` }) }, [floatingHeaderInnerWidth, floatingHeaderTableWidth]) const isClient = useIsClient() React.useEffect(() => { if (!showColumnHeaders) return const wrapEl = tableWrapRef.current const headEl = tableHeadRef.current if (!wrapEl || !headEl) return const update = () => { const wrapRect = wrapEl.getBoundingClientRect() const headHeight = headEl.getBoundingClientRect().height || 0 const headerOffset = getStickyTableHeaderOffset() const stuck = wrapRect.top <= headerOffset && wrapRect.bottom > (headHeight + headerOffset + 1) setHeaderIsStuck(prev => (prev === stuck ? prev : stuck)) } const scheduled = rafThrottle(update) const rafId = requestAnimationFrame(update) // Hub pages scroll in `[data-page-scroll]`, not `window` — bind both plus resize. const unbindVerticalScroll = bindVerticalScrollListeners(scheduled) wrapEl.addEventListener("scroll", scheduled, { passive: true }) const resizeObserver = new ResizeObserver(() => scheduled()) resizeObserver.observe(wrapEl) resizeObserver.observe(headEl) return () => { cancelAnimationFrame(rafId) scheduled.cancel() unbindVerticalScroll() resizeObserver.disconnect() wrapEl.removeEventListener("scroll", scheduled) } }, [showColumnHeaders]) React.useLayoutEffect(() => { if (!effectiveHeaderStuck) return const wrapEl = tableWrapRef.current if (!wrapEl) return // Capture once — cheaper than `querySelector` per scroll tick, and // the inner table element is stable while the wrapper is mounted. innerTableElRef.current = wrapEl.querySelector("table") const last = lastFloatingHeaderApplied.current // Reset cache so the first `apply()` after pin always writes. last.left = -1 last.width = -1 last.top = -1 let pendingTableMeasure = true const apply = () => { const rect = wrapEl.getBoundingClientRect() const headerOffset = getStickyTableHeaderOffset() // 1) Wrapper position — DOM mutation guarded by a cache. On pure // vertical scroll `rect.left`/`rect.width` don't change, so we // write nothing → browser keeps layout cached → no scroll jank. const wrapperEl = floatingHeaderWrapperRef.current if (wrapperEl) { if (last.top !== headerOffset) { wrapperEl.style.position = "fixed" wrapperEl.style.top = `${headerOffset}px` wrapperEl.style.zIndex = "50" last.top = headerOffset } if (last.left !== rect.left) { wrapperEl.style.left = `${rect.left}px` last.left = rect.left } if (last.width !== rect.width) { wrapperEl.style.width = `${rect.width}px` last.width = rect.width } } // 2) Inner / table widths — only re-measure when the wrapper or // underlying table actually resized. The dedicated ResizeObserver // below sets `pendingTableMeasure` so a pure-scroll tick skips the // expensive `getBoundingClientRect` on the inner `
`. // `clientWidth` already excludes the wrapper's `border-x`, so we use // it directly as the inner scrollport width. const innerWidth = Math.max(0, wrapEl.clientWidth) setFloatingHeaderInnerWidth(prev => (prev === innerWidth ? prev : innerWidth)) if (pendingTableMeasure) { const innerTableWidth = innerTableElRef.current?.getBoundingClientRect().width ?? 0 const renderedTableWidth = Math.max(totalWidth, innerWidth, innerTableWidth) setFloatingHeaderTableWidth(prev => (prev === renderedTableWidth ? prev : renderedTableWidth)) pendingTableMeasure = false } // 3) Horizontal scroll — DOM sync (no React commit). syncFloatingHeaderScroll(wrapEl.scrollLeft) } apply() const scheduled = rafThrottle(apply) // Wrap-element resize → re-measure the inner table next tick. const wrapRO = new ResizeObserver(() => { pendingTableMeasure = true scheduled() }) wrapRO.observe(wrapEl) // Inner table resize (e.g. column resize) → also re-measure. let tableRO: ResizeObserver | undefined if (innerTableElRef.current) { tableRO = new ResizeObserver(() => { pendingTableMeasure = true scheduled() }) tableRO.observe(innerTableElRef.current) } const unbindVerticalScroll = bindVerticalScrollListeners(scheduled) return () => { scheduled.cancel() unbindVerticalScroll() wrapRO.disconnect() tableRO?.disconnect() } }, [effectiveHeaderStuck, totalWidth, displayCols.length, syncFloatingHeaderScroll]) return { bumpHeaderMenuOpen, effectiveHeaderStuck, floatingHeaderInnerWidth, floatingHeaderTableWidth, floatingHeaderTranslateRef, floatingHeaderWrapperRef, headerIsStuck, headerScrollLeftRef, headerSurfaceActive, isClient, setHeaderKeyboardActive, syncFloatingHeaderScroll, tableHeadRef, tableWrapRef, } }