import {ResizeObserver} from '@juggle/resize-observer' import {SCROLL_BAR_WIDTH} from '../constants' /** * 页面级吸顶表头 + 吸底横向滚动条控制器(brick 宽表专用)。 * * 背景:`.brick-table-main-body-wrap` 自带 `overflow: auto hidden`,本身是一个横向滚动容器, * 会把原生 `position: sticky` 的作用域限制在其内部,无法相对页面/外层容器吸顶。故采用 * 「克隆 `.brick-table` 根节点 + `position: fixed` 浮层」方案: * * - 吸顶表头:真实表头滚出滚动区顶部时,克隆一份(去掉 tbody)用 fixed 悬浮到顶部;浮层通过 * `scrollLeft` 与真实表体同步横向偏移,从而保留左固定列(sticky-left)的吸附效果。 * - 吸底滚动条:真实横向滚动条落到滚动区底部之外时,再造一条 fixed 到底部的横向滚动条, * 与真实表体双向同步 `scrollLeft`(互斥锁防抖),让用户任何时候都能横向拖动宽表。 * * 该控制器不依赖 React,只操作传入的 DOM,供 Table 类组件在生命周期里挂载/刷新/卸载。 */ export interface StickyControllerOptions { /** 取 `.brick-table` 根节点(通常来自 Table 的 refTable) */ getRoot: () => HTMLElement | null /** 表头吸顶时距滚动区顶部的偏移,默认 0 */ top?: number /** 滚动条吸底时距滚动区底部的偏移,默认 0 */ bottom?: number /** * 可选的内层纵向滚动容器。缺省 → 相对 window(整页滚动); * 传入 → 吸顶/吸底相对该容器计算,并监听其滚动。 */ getScrollTarget?: () => HTMLElement | null } const HEADER_CLASS = 'brick-table-sticky-float-header' const SCROLLBAR_CLASS = 'brick-table-sticky-float-scrollbar' const SCROLLBAR_INNER_CLASS = 'brick-table-sticky-float-scrollbar-inner' export class StickyController { private readonly options: StickyControllerOptions private floatEl: HTMLElement | null = null private scrollbarEl: HTMLElement | null = null private scrollbarInner: HTMLElement | null = null private cloneBodyWrap: HTMLElement | null = null private cloneRoot: HTMLElement | null = null private root: HTMLElement | null = null private bodyWrap: HTMLElement | null = null private scrollTarget: HTMLElement | null = null // scrollbar ↔ bodyWrap 双向同步互斥,避免相互触发 scroll 造成抖动/死循环 private syncingScroll = false private raf = 0 private resizeObserver: ResizeObserver | null = null constructor(options: StickyControllerOptions) { this.options = options } private get topOffset() { return this.options.top ?? 0 } private get bottomOffset() { return this.options.bottom ?? 0 } // 滚动区顶部在视口中的 Y(无内层容器时即视口顶 0)+ top 偏移 private getContainerTop() { const base = this.scrollTarget ? this.scrollTarget.getBoundingClientRect().top : 0 return base + this.topOffset } // 滚动区底部在视口中的 Y(无内层容器时即视口底 innerHeight)- bottom 偏移 private getContainerBottom() { const base = this.scrollTarget ? this.scrollTarget.getBoundingClientRect().bottom : window.innerHeight return base - this.bottomOffset } /** 挂载:创建浮层 + 绑定监听。重复调用前应先 destroy。 */ mount() { const root = this.options.getRoot() const bodyWrap = root?.querySelector('.brick-table-main-body-wrap') if (!root || !bodyWrap) { return } this.root = root this.bodyWrap = bodyWrap this.scrollTarget = this.options.getScrollTarget?.() ?? null const floatEl = document.createElement('div') floatEl.className = HEADER_CLASS floatEl.style.display = 'none' this.floatEl = floatEl const scrollbarEl = document.createElement('div') scrollbarEl.className = SCROLLBAR_CLASS scrollbarEl.style.display = 'none' // 高度直接取系统滚动条厚度:经典滚动条(鼠标/始终显示)> 0 → 吸底条可见; // overlay 滚动条(macOS 触摸板)为 0 → 条带塌掉不占位,无空白条,跟随系统 idle 隐藏 scrollbarEl.style.height = `${SCROLL_BAR_WIDTH}px` const scrollbarInner = document.createElement('div') scrollbarInner.className = SCROLLBAR_INNER_CLASS scrollbarEl.appendChild(scrollbarInner) this.scrollbarEl = scrollbarEl this.scrollbarInner = scrollbarInner this.build() document.body.appendChild(floatEl) document.body.appendChild(scrollbarEl) floatEl.addEventListener('click', this.onFloatClick) scrollbarEl.addEventListener('scroll', this.onScrollbarScroll, {passive: true}) window.addEventListener('scroll', this.onScroll, {passive: true}) window.addEventListener('resize', this.onResize) bodyWrap.addEventListener('scroll', this.onScroll, {passive: true}) if (this.scrollTarget) { this.scrollTarget.addEventListener('scroll', this.onScroll, {passive: true}) } // 侧栏收起/展开等布局变化不触发 window.resize,用 RO 兜底重算浮层位置/宽度 this.resizeObserver = new ResizeObserver(() => this.sync()) this.resizeObserver.observe(root) this.sync() // 首帧 brick 可能尚未测好列宽,下一帧再重建一次 this.raf = requestAnimationFrame(() => { this.build() this.sync() }) } /** 刷新:数据/列宽变化后重建克隆并重新定位(供 componentDidUpdate 调用)。 */ refresh() { if (!this.floatEl) { return } this.scrollTarget = this.options.getScrollTarget?.() ?? null this.build() this.sync() } /** 卸载:移除浮层 + 解绑所有监听。 */ destroy() { cancelAnimationFrame(this.raf) this.resizeObserver?.disconnect() this.resizeObserver = null window.removeEventListener('scroll', this.onScroll) window.removeEventListener('resize', this.onResize) this.bodyWrap?.removeEventListener('scroll', this.onScroll) this.scrollTarget?.removeEventListener('scroll', this.onScroll) this.floatEl?.removeEventListener('click', this.onFloatClick) this.scrollbarEl?.removeEventListener('scroll', this.onScrollbarScroll) this.floatEl?.remove() this.scrollbarEl?.remove() this.floatEl = null this.scrollbarEl = null this.scrollbarInner = null this.cloneBodyWrap = null this.cloneRoot = null this.root = null this.bodyWrap = null this.scrollTarget = null } // 克隆去掉 tbody,列宽会退化到只按表头文字撑开。把真实 的渲染列宽逐列拷到克隆 , // 并给克隆 table 设 table-layout:fixed,强制按拷贝列宽渲染,与真实表保持一致。 private syncColWidths(clone: HTMLElement) { const bodyWrap = this.bodyWrap if (!bodyWrap) { return } const realTable = bodyWrap.querySelector('table') const cloneTable = clone.querySelector('table') if (!realTable || !cloneTable) { return } const realCols = realTable.querySelectorAll('colgroup col') const cloneCols = cloneTable.querySelectorAll('colgroup col') if (!realCols.length || realCols.length !== cloneCols.length) { return } realCols.forEach((col, i) => { const w = col.getBoundingClientRect().width if (w > 0) { cloneCols[i].style.width = `${w}px` } }) cloneTable.style.tableLayout = 'fixed' cloneTable.style.width = `${realTable.getBoundingClientRect().width}px` } private build() { const {floatEl, root} = this if (!floatEl || !root) { return } floatEl.innerHTML = '' const clone = root.cloneNode(true) as HTMLElement clone.querySelectorAll('tbody').forEach(tb => tb.remove()) // 吸顶悬浮贴页面顶部,圆角不合适 clone.style.borderRadius = '0' // 克隆 th 覆写 pointer-events:auto 以便点击(排序等);外层 floatEl 保持 none,只有 th 截获点击 clone.querySelectorAll('th').forEach(th => { (th as HTMLElement).style.pointerEvents = 'auto' }) floatEl.appendChild(clone) this.cloneRoot = clone this.cloneBodyWrap = clone.querySelector('.brick-table-main-body-wrap') if (this.cloneBodyWrap) { // 克隆层不出横向滚动条,靠 scrollLeft 同步 this.cloneBodyWrap.style.overflow = 'hidden' } this.syncColWidths(clone) } // brick 的固定列 shadow 由根 `.brick-table` 上的 `brick-table-scroll-x-position-*` 类切换(见 _fixed.scss)。 // 克隆层是 build 时的静态快照,横向滚动时真实根节点的类会更新而克隆不会 → 左右固定列 shadow 停在旧态。 // 每次 sync 把这组类从真实根节点同步到克隆根节点,保证浮层表头的左右固定列 shadow 与真实表一致。 private syncScrollPositionClasses() { const {root, cloneRoot} = this if (!root || !cloneRoot) { return } const prefix = 'brick-table-scroll-x-position-' Array.from(cloneRoot.classList).forEach(cls => { if (cls.startsWith(prefix)) { cloneRoot.classList.remove(cls) } }) Array.from(root.classList).forEach(cls => { if (cls.startsWith(prefix)) { cloneRoot.classList.add(cls) } }) } private readonly sync = () => { const {root, bodyWrap, floatEl} = this if (!root || !bodyWrap || !floatEl) { return } const thead = root.querySelector('thead') if (!thead) { floatEl.style.display = 'none' return } const rect = root.getBoundingClientRect() const headH = thead.getBoundingClientRect().height const containerTop = this.getContainerTop() // 真实表头已滚出滚动区顶部、且表格底部仍在表头下方 → 显示悬浮表头 const active = rect.top < containerTop && rect.bottom > containerTop + headH if (!active) { floatEl.style.display = 'none' } else { floatEl.style.display = 'block' floatEl.style.top = `${containerTop}px` floatEl.style.left = `${rect.left}px` // 用 offsetWidth(含边框)而非 clientWidth,否则右侧漏 1~2px 边框宽度 floatEl.style.width = `${root.offsetWidth}px` if (this.cloneBodyWrap) { this.cloneBodyWrap.scrollLeft = bodyWrap.scrollLeft } // 同步固定列 shadow 的滚动位置类,保证左右固定列在浮层里的边界阴影正确 this.syncScrollPositionClasses() } this.syncScrollbar() } private syncScrollbar() { const {bodyWrap, scrollbarEl, scrollbarInner} = this if (!bodyWrap || !scrollbarEl || !scrollbarInner) { return } // +1 容差,规避亚像素导致的误判 const canScroll = bodyWrap.scrollWidth > bodyWrap.clientWidth + 1 const barRect = bodyWrap.getBoundingClientRect() const containerBottom = this.getContainerBottom() // 真实滚动条贴 bodyWrap 底边:底边超出滚动区底部即被顶出可视区,需吸底兜底; // 同时表格顶部要仍在滚动区内,否则整表已滚过去,无需显示 const barActive = canScroll && barRect.bottom > containerBottom && barRect.top < containerBottom if (!barActive) { scrollbarEl.style.display = 'none' return } scrollbarEl.style.display = 'block' scrollbarEl.style.bottom = `${Math.max(0, window.innerHeight - containerBottom)}px` scrollbarEl.style.left = `${barRect.left}px` // 用可视宽度 clientWidth(不含纵向滚动条占位),与真实容器可视区对齐 scrollbarEl.style.width = `${bodyWrap.clientWidth}px` scrollbarInner.style.width = `${bodyWrap.scrollWidth}px` if (!this.syncingScroll) { this.syncingScroll = true scrollbarEl.scrollLeft = bodyWrap.scrollLeft this.syncingScroll = false } } // 拖动吸底滚动条 → 驱动真实容器与吸顶克隆层 private readonly onScrollbarScroll = () => { const {bodyWrap, scrollbarEl} = this if (this.syncingScroll || !bodyWrap || !scrollbarEl) { return } this.syncingScroll = true bodyWrap.scrollLeft = scrollbarEl.scrollLeft if (this.cloneBodyWrap) { this.cloneBodyWrap.scrollLeft = scrollbarEl.scrollLeft } this.syncingScroll = false } // 克隆表头 th 点击 → 按列索引转发到真实表头对应 th,使排序等表头交互生效 private readonly onFloatClick = (e: MouseEvent) => { const {floatEl, bodyWrap} = this if (!floatEl || !bodyWrap) { return } const cloneTh = (e.target as HTMLElement).closest('th') if (!cloneTh) { return } const cloneThead = floatEl.querySelector('thead') const realThead = bodyWrap.querySelector('thead') if (!cloneThead || !realThead) { return } const cloneThs = Array.from(cloneThead.querySelectorAll('th')) const realThs = Array.from(realThead.querySelectorAll('th')) const idx = cloneThs.indexOf(cloneTh) if (idx >= 0 && idx < realThs.length) { // brick 排序 handler 挂在 th 内的 .brick-table-sorter 上,非 th 本身 const sortTrigger = realThs[idx].querySelector('.brick-table-sorter') if (sortTrigger) { sortTrigger.click() } } } private readonly onScroll = () => this.sync() private readonly onResize = () => { this.build() this.sync() } }