From 46a0f8e0e8aa205a0d4af24ddb0bd515f1cb515b Mon Sep 17 00:00:00 2001 From: jinxq <15618719643@163.com> Date: Thu, 3 Dec 2026 16:21:14 +0800 Subject: [PATCH 1/4] feat: virtual column culling, scrollbar header align, scrollTo left Cull off-screen scrollable columns with spacers while keeping fixed columns. Measure the vertical scrollbar gutter and widen the header table so maxScrollLeft matches the body under native overflow. Support scrollTo({ left }) on native and proxied virtual bodies. Use abs(x) for column-range math under RTL. --- src/FixedHolder/index.tsx | 7 +- src/Table.tsx | 77 +++++++++++------ src/VirtualTable/BodyGrid.tsx | 22 ++++- src/VirtualTable/BodyLine.tsx | 147 ++++++++++++++++++++++++++++----- src/VirtualTable/colVirtual.ts | 78 +++++++++++++++++ src/VirtualTable/context.ts | 4 + src/interface.ts | 2 + tests/colVirtual.spec.ts | 51 ++++++++++++ tests/refs.spec.tsx | 12 +++ 9 files changed, 352 insertions(+), 48 deletions(-) create mode 100644 src/VirtualTable/colVirtual.ts create mode 100644 tests/colVirtual.spec.ts diff --git a/src/FixedHolder/index.tsx b/src/FixedHolder/index.tsx index fdcc1132f..fc9065333 100644 --- a/src/FixedHolder/index.tsx +++ b/src/FixedHolder/index.tsx @@ -184,7 +184,12 @@ const FixedHolder = React.forwardRef>((pro tableLayout, minWidth: '100%', // https://github.com/ant-design/ant-design/issues/54894 - width: scrollX, + // With scrollbar placeholder column, header table width is scrollX + combinationScrollBarSize + // so maxScrollLeft matches the body (content scrollX, viewport reduced by vertical scrollbar). + width: + typeof scrollX === 'number' && combinationScrollBarSize + ? scrollX + combinationScrollBarSize + : scrollX, }} > {isColGroupEmpty ? ( diff --git a/src/Table.tsx b/src/Table.tsx index 6fdbe1e35..6dd768d87 100644 --- a/src/Table.tsx +++ b/src/Table.tsx @@ -361,27 +361,29 @@ const Table = ( nativeElement: fullTableRef.current, scrollTo: config => { if (scrollBodyRef.current instanceof HTMLElement) { - // Native scroll - const { index, top, key, offset, align = 'nearest' } = config; - - if (validNumberValue(top)) { - // In top mode, offset is ignored - scrollBodyRef.current?.scrollTo({ top }); + // Native scroll (including non-virtual body) + const { index, top, left, key, offset, align = 'nearest' } = config; + const body = scrollBodyRef.current; + const hasTop = validNumberValue(top); + const hasLeft = validNumberValue(left); + + if (hasTop || hasLeft) { + body.scrollTo({ + top: hasTop ? top : body.scrollTop, + left: hasLeft ? left : body.scrollLeft, + }); } else { const mergedKey = key ?? getRowKey(mergedData[index]); - const targetElement = scrollBodyRef.current.querySelector( - `[data-row-key="${mergedKey}"]`, - ); + const targetElement = body.querySelector(`[data-row-key="${mergedKey}"]`); if (targetElement) { targetElement.scrollIntoView({ block: align }); if (offset) { - const container = scrollBodyRef.current; - container.scrollTo({ top: container.scrollTop + offset }); + body.scrollTo({ top: body.scrollTop + offset }); } } } } else if ((scrollBodyRef.current as any)?.scrollTo) { - // Pass to proxy + // Pass to proxy (virtual table -> virtual-list) (scrollBodyRef.current as any).scrollTo(config); } }, @@ -588,15 +590,39 @@ const Table = ( // ===================== Effects ====================== const [scrollbarSize, setScrollbarSize] = React.useState(0); - useLayoutEffect(() => { - if (!tailor || !useInternalHooks) { - if (scrollBodyRef.current instanceof Element) { - setScrollbarSize(getTargetScrollBarSize(scrollBodyRef.current).width); - } else { - setScrollbarSize(getTargetScrollBarSize(scrollBodyContainerRef.current).width); - } + /** Measure vertical scrollbar gutter; virtual tables use the holder (native overflow:auto) so header/body maxScrollLeft stay aligned. */ + const measureScrollbarSize = React.useCallback(() => { + const body = scrollBodyRef.current as unknown as + HTMLElement | { nativeElement?: HTMLElement } | null; + + let target: HTMLElement | null = null; + + if (body instanceof HTMLElement) { + target = body; + } else if (body?.nativeElement instanceof HTMLElement) { + target = + (body.nativeElement.querySelector(`.${prefixCls}-tbody-virtual-holder`) as HTMLElement) || + body.nativeElement; + } else if (scrollBodyContainerRef.current instanceof HTMLElement) { + target = scrollBodyContainerRef.current; } - }, []); + + if (!target) { + return; + } + + // Prefer measured gutter (Chrome thin bars are often 6-15px); fall back to util system width. + const gap = Math.max(0, target.offsetWidth - target.clientWidth); + const next = gap > 0 ? gap : getTargetScrollBarSize(target).width; + + setScrollbarSize(prev => (prev === next ? prev : next)); + }, [prefixCls]); + + useLayoutEffect(() => { + measureScrollbarSize(); + const rafId = window.requestAnimationFrame(() => measureScrollbarSize()); + return () => window.cancelAnimationFrame(rafId); + }, [measureScrollbarSize, hasData, flattenColumns.length]); // ================== INTERNAL HOOKS ================== React.useEffect(() => { @@ -695,11 +721,12 @@ const Table = ( onScroll: onInternalScroll, }); - headerProps.colWidths = flattenColumns.map(({ width }, index) => { - const colWidth = - index === flattenColumns.length - 1 ? (width as number) - scrollbarSize : width; - if (typeof colWidth === 'number' && !Number.isNaN(colWidth)) { - return colWidth; + // With native vertical scroll the bar sits outside the content box. Keep column widths and + // append a scrollbar placeholder column so header maxScrollLeft matches the body; do not + // subtract scrollbarSize from the last column. + headerProps.colWidths = flattenColumns.map(({ width }) => { + if (typeof width === 'number' && !Number.isNaN(width)) { + return width; } if (process.env.NODE_ENV !== 'production') { diff --git a/src/VirtualTable/BodyGrid.tsx b/src/VirtualTable/BodyGrid.tsx index 11bf129ab..d50a7f409 100644 --- a/src/VirtualTable/BodyGrid.tsx +++ b/src/VirtualTable/BodyGrid.tsx @@ -10,6 +10,7 @@ import type { VirtualScrollConfig, } from '../interface'; import BodyLine from './BodyLine'; +import { getVisibleColumnRange } from './colVirtual'; import { GridContext, StaticContext } from './context'; const ALIGN_MAP: Record = { @@ -41,6 +42,7 @@ const Grid = React.forwardRef((props, ref) => { childrenColumnName, scrollX, direction, + componentWidth, } = useContext(TableContext, [ 'flattenColumns', 'onColumnResize', @@ -50,6 +52,7 @@ const Grid = React.forwardRef((props, ref) => { 'childrenColumnName', 'scrollX', 'direction', + 'componentWidth', ]); const { @@ -81,6 +84,13 @@ const Grid = React.forwardRef((props, ref) => { [columnsWidth], ); + const [offsetX, setOffsetX] = React.useState(0); + + const { startCol: colStart, endCol: colEnd } = React.useMemo( + () => getVisibleColumnRange(columnsOffset, offsetX, componentWidth || 0), + [columnsOffset, offsetX, componentWidth], + ); + React.useEffect(() => { columnsWidth.forEach(([key, width]) => { onColumnResize(key, width); @@ -243,7 +253,10 @@ const Grid = React.forwardRef((props, ref) => { }; // ========================= Context ========================== - const gridContext = React.useMemo(() => ({ columnsOffset }), [columnsOffset]); + const gridContext = React.useMemo( + () => ({ columnsOffset, colStart, colEnd }), + [columnsOffset, colStart, colEnd], + ); // ========================== Render ========================== const tblPrefixCls = `${prefixCls}-tbody`; @@ -277,12 +290,17 @@ const Grid = React.forwardRef((props, ref) => { scrollWidth={scrollX as number} direction={direction} onVirtualScroll={({ x }) => { + // Column virtualization uses LTR offset math; list may report negative x in RTL. + setOffsetX(Math.abs(x)); onScroll({ currentTarget: listRef.current?.nativeElement, scrollLeft: x, }); }} - onScroll={onTablePropScroll} + onScroll={e => { + setOffsetX(Math.abs(e.currentTarget.scrollLeft)); + onTablePropScroll?.(e as React.UIEvent); + }} extraRender={extraRender} > {(item, index, itemProps) => { diff --git a/src/VirtualTable/BodyLine.tsx b/src/VirtualTable/BodyLine.tsx index 03167329e..65c7a929f 100644 --- a/src/VirtualTable/BodyLine.tsx +++ b/src/VirtualTable/BodyLine.tsx @@ -5,10 +5,37 @@ import Cell from '../Cell'; import TableContext, { responseImmutable } from '../context/TableContext'; import type { FlattenData } from '../hooks/useFlattenRecords'; import useRowInfo from '../hooks/useRowInfo'; +import { getColumnWidthByIndex, isFixedColumn } from './colVirtual'; import VirtualCell from './VirtualCell'; -import { StaticContext } from './context'; +import { GridContext, StaticContext } from './context'; import { computedExpandedClassName } from '../utils/expandUtil'; +/** Merged placeholder for horizontally culled columns */ +const HorzSpacerCell = React.memo( + ({ + width, + prefixCls, + component: Component = 'div', + }: { + width: number; + prefixCls: string; + component?: React.ElementType; + }) => ( + + ), +); + +HorzSpacerCell.displayName = 'HorzSpacerCell'; + export interface BodyLineProps { data: FlattenData; index: number; @@ -36,6 +63,11 @@ const BodyLine = React.forwardRef((props, ref) => 'styles', ]); const { getComponent } = useContext(StaticContext, ['getComponent']); + const { + columnsOffset = [], + colStart = 0, + colEnd = Number.MAX_SAFE_INTEGER, + } = useContext(GridContext, ['columnsOffset', 'colStart', 'colEnd']) || {}; const rowInfo = useRowInfo(record, rowKey, index, indent); @@ -101,6 +133,99 @@ const BodyLine = React.forwardRef((props, ref) => rowStyle.pointerEvents = 'none'; } + const cells: React.ReactNode[] = []; + let leftSpacerWidth = 0; + let rightSpacerWidth = 0; + + const flushLeftSpacer = () => { + if (leftSpacerWidth <= 0) { + return; + } + cells.push( + , + ); + leftSpacerWidth = 0; + }; + + const flushRightSpacer = () => { + if (rightSpacerWidth <= 0) { + return; + } + cells.push( + , + ); + rightSpacerWidth = 0; + }; + + flattenColumns.forEach((column, colIndex) => { + const width = getColumnWidthByIndex(columnsOffset, colIndex); + + if (isFixedColumn(column)) { + flushLeftSpacer(); + flushRightSpacer(); + cells.push( + , + ); + return; + } + + if (colIndex < colStart) { + leftSpacerWidth += width; + return; + } + + if (colIndex <= colEnd) { + flushLeftSpacer(); + cells.push( + , + ); + return; + } + + rightSpacerWidth += width; + }); + + flushLeftSpacer(); + flushRightSpacer(); + const rowNode = ( ((props, ref) => })} style={{ ...rowStyle, ...rowProps?.style, ...styles?.body?.row }} > - {flattenColumns.map((column, colIndex) => { - return ( - - ); - })} + {cells} ); diff --git a/src/VirtualTable/colVirtual.ts b/src/VirtualTable/colVirtual.ts new file mode 100644 index 000000000..b105e43d8 --- /dev/null +++ b/src/VirtualTable/colVirtual.ts @@ -0,0 +1,78 @@ +/** Horizontal column virtualization helpers from scrollLeft / viewport width. */ + +export const COL_VIRTUAL_BUFFER = 300; + +/** + * columnsOffset[i] is the prefix sum of widths for columns 0..i (right edge of column i). + * Returns the first column whose right edge is greater than offset. + */ +export function findColumnIndexByOffset(columnsOffset: number[], offset: number): number { + if (!columnsOffset.length) { + return 0; + } + + const target = Math.max(0, offset); + let low = 0; + let high = columnsOffset.length - 1; + let result = columnsOffset.length - 1; + + while (low <= high) { + const mid = (low + high) >> 1; + if (columnsOffset[mid] > target) { + result = mid; + high = mid - 1; + } else { + low = mid + 1; + } + } + + return result; +} + +export function getColumnStartOffset(columnsOffset: number[], colIndex: number): number { + if (colIndex <= 0) { + return 0; + } + return columnsOffset[colIndex - 1] || 0; +} + +export function getColumnWidthByIndex(columnsOffset: number[], colIndex: number): number { + return (columnsOffset[colIndex] || 0) - getColumnStartOffset(columnsOffset, colIndex); +} + +export type ColVisibleRange = { + startCol: number; + endCol: number; +}; + +/** + * Compute the scrollable column range that should render for the current scrollLeft. + * Fixed columns are always kept by the row renderer. + */ +export function getVisibleColumnRange( + columnsOffset: number[], + scrollLeft: number, + viewportWidth: number, + buffer: number = COL_VIRTUAL_BUFFER, +): ColVisibleRange { + const len = columnsOffset.length; + if (!len || viewportWidth <= 0) { + return { startCol: 0, endCol: Math.max(0, len - 1) }; + } + + const totalWidth = columnsOffset[len - 1] || 0; + const visibleStart = Math.max(0, scrollLeft - buffer); + const visibleEnd = Math.min(totalWidth, scrollLeft + viewportWidth + buffer); + + return { + startCol: findColumnIndexByOffset(columnsOffset, visibleStart), + endCol: findColumnIndexByOffset(columnsOffset, Math.max(visibleStart, visibleEnd)), + }; +} + +export function isFixedColumn(column: { fixed?: unknown } | null | undefined): boolean { + const fixed = column?.fixed; + return ( + fixed === true || fixed === 'left' || fixed === 'right' || fixed === 'start' || fixed === 'end' + ); +} diff --git a/src/VirtualTable/context.ts b/src/VirtualTable/context.ts index d2f7c1f5d..944e0e215 100644 --- a/src/VirtualTable/context.ts +++ b/src/VirtualTable/context.ts @@ -13,6 +13,10 @@ export const StaticContext = createContext(null); export interface GridContextProps { columnsOffset: number[]; + /** First visible scrollable column index (includes buffer) */ + colStart: number; + /** Last visible scrollable column index (includes buffer) */ + colEnd: number; } export const GridContext = createContext(null); diff --git a/src/interface.ts b/src/interface.ts index fb9671074..e4dec7a49 100644 --- a/src/interface.ts +++ b/src/interface.ts @@ -36,6 +36,8 @@ export type ScrollConfig = { key?: Key; /** The absolute scroll position from top */ top?: number; + /** The absolute horizontal scroll position */ + left?: number; /** * Additional offset in pixels to apply to the scroll position. * Only effective when using `key` or `index` mode. diff --git a/tests/colVirtual.spec.ts b/tests/colVirtual.spec.ts new file mode 100644 index 000000000..ed8a2de07 --- /dev/null +++ b/tests/colVirtual.spec.ts @@ -0,0 +1,51 @@ +import { + COL_VIRTUAL_BUFFER, + findColumnIndexByOffset, + getColumnStartOffset, + getColumnWidthByIndex, + getVisibleColumnRange, + isFixedColumn, +} from '../src/VirtualTable/colVirtual'; + +describe('colVirtual', () => { + // widths: 100, 100, 100, 100, 100 -> prefix 100,200,300,400,500 + const columnsOffset = [100, 200, 300, 400, 500]; + + it('findColumnIndexByOffset returns first column past offset', () => { + expect(findColumnIndexByOffset(columnsOffset, 0)).toBe(0); + expect(findColumnIndexByOffset(columnsOffset, 100)).toBe(1); + expect(findColumnIndexByOffset(columnsOffset, 250)).toBe(2); + expect(findColumnIndexByOffset([], 10)).toBe(0); + }); + + it('getColumnStartOffset / getColumnWidthByIndex', () => { + expect(getColumnStartOffset(columnsOffset, 0)).toBe(0); + expect(getColumnStartOffset(columnsOffset, 2)).toBe(200); + expect(getColumnWidthByIndex(columnsOffset, 0)).toBe(100); + expect(getColumnWidthByIndex(columnsOffset, 3)).toBe(100); + }); + + it('getVisibleColumnRange includes buffer and falls back when viewport is 0', () => { + expect(getVisibleColumnRange(columnsOffset, 0, 0)).toEqual({ + startCol: 0, + endCol: 4, + }); + + const range = getVisibleColumnRange(columnsOffset, 150, 100, 0); + expect(range.startCol).toBe(1); + expect(range.endCol).toBe(2); + + const buffered = getVisibleColumnRange(columnsOffset, 150, 100, COL_VIRTUAL_BUFFER); + expect(buffered.startCol).toBeLessThanOrEqual(range.startCol); + expect(buffered.endCol).toBeGreaterThanOrEqual(range.endCol); + }); + + it('isFixedColumn', () => { + expect(isFixedColumn({ fixed: 'left' })).toBe(true); + expect(isFixedColumn({ fixed: 'right' })).toBe(true); + expect(isFixedColumn({ fixed: true })).toBe(true); + expect(isFixedColumn({ fixed: 'start' })).toBe(true); + expect(isFixedColumn({})).toBe(false); + expect(isFixedColumn(null)).toBe(false); + }); +}); diff --git a/tests/refs.spec.tsx b/tests/refs.spec.tsx index 2afcb72f7..add0d51db 100644 --- a/tests/refs.spec.tsx +++ b/tests/refs.spec.tsx @@ -51,6 +51,18 @@ describe('Table.Ref', () => { expect(scrollParam.top).toEqual(903); + // Scroll left (preserve current top when only left is set) + ref.current.scrollTo({ + left: 120, + }); + expect(scrollParam.left).toEqual(120); + + ref.current.scrollTo({ + top: 40, + left: 80, + }); + expect(scrollParam).toEqual({ top: 40, left: 80 }); + // Scroll index ref.current.scrollTo({ index: 0, From 23f5ce8536def7d512831576c23ead3288ca4fac Mon Sep 17 00:00:00 2001 From: jinxq <15618719643@163.com> Date: Thu, 3 Dec 2026 16:40:15 +0800 Subject: [PATCH 2/4] fix: sync col virtual offsetX and keep crossing colSpan cells Programmatic scrollTo/scrollLeft and simulated onScroll now keep offsetX aligned; measureScrollbar skips system gutter when gap is 0 under simulated scroll; BodyLine keeps merges that cross the cull window. --- src/Table.tsx | 16 ++++- src/VirtualTable/BodyGrid.tsx | 19 +++++- src/VirtualTable/BodyLine.tsx | 109 ++++++++++++++++++++-------------- 3 files changed, 97 insertions(+), 47 deletions(-) diff --git a/src/Table.tsx b/src/Table.tsx index 6dd768d87..cb11188e7 100644 --- a/src/Table.tsx +++ b/src/Table.tsx @@ -611,9 +611,21 @@ const Table = ( return; } - // Prefer measured gutter (Chrome thin bars are often 6-15px); fall back to util system width. + // Prefer measured gutter. When gap is 0, only fall back to system width for native + // overflow:auto/scroll; simulated lists hide the bar (gap=0 is valid — do not invent 15px). const gap = Math.max(0, target.offsetWidth - target.clientWidth); - const next = gap > 0 ? gap : getTargetScrollBarSize(target).width; + let next = gap; + if (gap === 0) { + const { overflowY, overflowX } = getComputedStyle(target); + const nativeOverflow = + overflowY === 'auto' || + overflowY === 'scroll' || + overflowX === 'auto' || + overflowX === 'scroll'; + if (nativeOverflow) { + next = getTargetScrollBarSize(target).width; + } + } setScrollbarSize(prev => (prev === next ? prev : next)); }, [prefixCls]); diff --git a/src/VirtualTable/BodyGrid.tsx b/src/VirtualTable/BodyGrid.tsx index d50a7f409..773c052f4 100644 --- a/src/VirtualTable/BodyGrid.tsx +++ b/src/VirtualTable/BodyGrid.tsx @@ -98,6 +98,13 @@ const Grid = React.forwardRef((props, ref) => { }, [columnsWidth]); // =========================== Ref ============================ + const syncOffsetXFromList = React.useCallback(() => { + const x = listRef.current?.getScrollInfo()?.x; + if (x !== undefined) { + setOffsetX(Math.abs(x)); + } + }, []); + React.useImperativeHandle(ref, () => { const obj = { scrollTo: (config: VirtualScrollConfig) => { @@ -110,6 +117,12 @@ const Grid = React.forwardRef((props, ref) => { offset, align: virtualAlign, }); + // scrollTo may not emit onVirtualScroll (esp. left-only); keep col virtual in sync + if (restConfig.left !== undefined) { + setOffsetX(Math.abs(restConfig.left)); + } else { + syncOffsetXFromList(); + } }, nativeElement: listRef.current?.nativeElement, } as unknown as GridRef; @@ -121,6 +134,7 @@ const Grid = React.forwardRef((props, ref) => { listRef.current?.scrollTo({ left: value, }); + setOffsetX(Math.abs(value)); }, }); @@ -298,7 +312,10 @@ const Grid = React.forwardRef((props, ref) => { }); }} onScroll={e => { - setOffsetX(Math.abs(e.currentTarget.scrollLeft)); + // Simulated horizontal uses list state (holder.scrollLeft stays 0); prefer getScrollInfo. + const listX = listRef.current?.getScrollInfo()?.x; + const domLeft = Math.abs(e.currentTarget.scrollLeft); + setOffsetX(Math.abs(listX ?? domLeft)); onTablePropScroll?.(e as React.UIEvent); }} extraRender={extraRender} diff --git a/src/VirtualTable/BodyLine.tsx b/src/VirtualTable/BodyLine.tsx index 65c7a929f..6eb7ff9cd 100644 --- a/src/VirtualTable/BodyLine.tsx +++ b/src/VirtualTable/BodyLine.tsx @@ -167,61 +167,82 @@ const BodyLine = React.forwardRef((props, ref) => rightSpacerWidth = 0; }; - flattenColumns.forEach((column, colIndex) => { - const width = getColumnWidthByIndex(columnsOffset, colIndex); + const getColSpan = (column: (typeof flattenColumns)[number]) => { + const { onCell } = column; + if (onCell) { + const cellProps = onCell(record, renderIndex) as React.TdHTMLAttributes; + if (typeof cellProps?.colSpan === 'number') { + return cellProps.colSpan; + } + } + return 1; + }; + + const pushVirtualCell = (column: (typeof flattenColumns)[number], colIndex: number) => { + cells.push( + , + ); + }; + + for (let colIndex = 0; colIndex < flattenColumns.length;) { + const column = flattenColumns[colIndex]; + const colSpan = getColSpan(column); + + // Covered by a previous merge — width belongs to the start cell / spacer already + if (colSpan === 0) { + colIndex += 1; + continue; + } + + const spanEnd = colIndex + Math.max(colSpan, 1) - 1; + const spanWidth = (() => { + let w = 0; + for (let i = colIndex; i <= spanEnd && i < flattenColumns.length; i += 1) { + w += getColumnWidthByIndex(columnsOffset, i); + } + return w; + })(); if (isFixedColumn(column)) { flushLeftSpacer(); flushRightSpacer(); - cells.push( - , - ); - return; + pushVirtualCell(column, colIndex); + colIndex = spanEnd + 1; + continue; } - if (colIndex < colStart) { - leftSpacerWidth += width; - return; + const intersectsVisible = spanEnd >= colStart && colIndex <= colEnd; + + if (colIndex < colStart && !intersectsVisible) { + leftSpacerWidth += spanWidth; + colIndex = spanEnd + 1; + continue; } - if (colIndex <= colEnd) { + if (intersectsVisible) { flushLeftSpacer(); - cells.push( - , - ); - return; + pushVirtualCell(column, colIndex); + colIndex = spanEnd + 1; + continue; } - rightSpacerWidth += width; - }); + rightSpacerWidth += spanWidth; + colIndex = spanEnd + 1; + } flushLeftSpacer(); flushRightSpacer(); From 07ad29f0866aa74dc7225ed840ae73f17b395927 Mon Sep 17 00:00:00 2001 From: jinxq <15618719643@163.com> Date: Thu, 3 Dec 2026 16:53:14 +0800 Subject: [PATCH 3/4] fix: keep measured scrollbar gap and colSpan layout under cull Use measured gutter only; sync offsetX only when left is set (raf clamp); call onCell with row index; drop negative margin when covered columns are skipped. --- src/Table.tsx | 19 +++---------------- src/VirtualTable/BodyGrid.tsx | 31 ++++++++++++++++++------------- src/VirtualTable/BodyLine.tsx | 3 ++- src/VirtualTable/VirtualCell.tsx | 9 ++++----- 4 files changed, 27 insertions(+), 35 deletions(-) diff --git a/src/Table.tsx b/src/Table.tsx index cb11188e7..d657e4f59 100644 --- a/src/Table.tsx +++ b/src/Table.tsx @@ -29,7 +29,6 @@ import ResizeObserver from '@rc-component/resize-observer'; import { getDOM, get as getValue, - getTargetScrollBarSize, isEqual, isNonNullable, isReactRenderable, @@ -611,21 +610,9 @@ const Table = ( return; } - // Prefer measured gutter. When gap is 0, only fall back to system width for native - // overflow:auto/scroll; simulated lists hide the bar (gap=0 is valid — do not invent 15px). - const gap = Math.max(0, target.offsetWidth - target.clientWidth); - let next = gap; - if (gap === 0) { - const { overflowY, overflowX } = getComputedStyle(target); - const nativeOverflow = - overflowY === 'auto' || - overflowY === 'scroll' || - overflowX === 'auto' || - overflowX === 'scroll'; - if (nativeOverflow) { - next = getTargetScrollBarSize(target).width; - } - } + // Prefer measured gutter only. gap=0 is valid (overlay / no overflow / simulated hide) — + // do not invent a system width from overflow:auto alone. + const next = Math.max(0, target.offsetWidth - target.clientWidth); setScrollbarSize(prev => (prev === next ? prev : next)); }, [prefixCls]); diff --git a/src/VirtualTable/BodyGrid.tsx b/src/VirtualTable/BodyGrid.tsx index 773c052f4..6575d3026 100644 --- a/src/VirtualTable/BodyGrid.tsx +++ b/src/VirtualTable/BodyGrid.tsx @@ -98,14 +98,23 @@ const Grid = React.forwardRef((props, ref) => { }, [columnsWidth]); // =========================== Ref ============================ - const syncOffsetXFromList = React.useCallback(() => { - const x = listRef.current?.getScrollInfo()?.x; - if (x !== undefined) { - setOffsetX(Math.abs(x)); - } - }, []); - React.useImperativeHandle(ref, () => { + const syncOffsetXAfterScroll = (queuedLeft?: number) => { + if (queuedLeft !== undefined) { + setOffsetX(Math.abs(queuedLeft)); + } + // List may clamp left; sync actual after apply. Skip when left omitted so a + // vertical-only scrollTo does not wipe offsetX from a stale snapshot. + if (queuedLeft !== undefined) { + requestAnimationFrame(() => { + const x = listRef.current?.getScrollInfo()?.x; + if (x !== undefined) { + setOffsetX(Math.abs(x)); + } + }); + } + }; + const obj = { scrollTo: (config: VirtualScrollConfig) => { const { align, offset, ...restConfig } = config; @@ -118,11 +127,7 @@ const Grid = React.forwardRef((props, ref) => { align: virtualAlign, }); // scrollTo may not emit onVirtualScroll (esp. left-only); keep col virtual in sync - if (restConfig.left !== undefined) { - setOffsetX(Math.abs(restConfig.left)); - } else { - syncOffsetXFromList(); - } + syncOffsetXAfterScroll(restConfig.left); }, nativeElement: listRef.current?.nativeElement, } as unknown as GridRef; @@ -134,7 +139,7 @@ const Grid = React.forwardRef((props, ref) => { listRef.current?.scrollTo({ left: value, }); - setOffsetX(Math.abs(value)); + syncOffsetXAfterScroll(value); }, }); diff --git a/src/VirtualTable/BodyLine.tsx b/src/VirtualTable/BodyLine.tsx index 6eb7ff9cd..d1977f71f 100644 --- a/src/VirtualTable/BodyLine.tsx +++ b/src/VirtualTable/BodyLine.tsx @@ -167,10 +167,11 @@ const BodyLine = React.forwardRef((props, ref) => rightSpacerWidth = 0; }; + // Match VirtualCell / getCellProps: onCell(record, index) uses row index, not renderIndex const getColSpan = (column: (typeof flattenColumns)[number]) => { const { onCell } = column; if (onCell) { - const cellProps = onCell(record, renderIndex) as React.TdHTMLAttributes; + const cellProps = onCell(record, index) as React.TdHTMLAttributes; if (typeof cellProps?.colSpan === 'number') { return cellProps.colSpan; } diff --git a/src/VirtualTable/VirtualCell.tsx b/src/VirtualTable/VirtualCell.tsx index 339c6c0d0..e7789444f 100644 --- a/src/VirtualTable/VirtualCell.tsx +++ b/src/VirtualTable/VirtualCell.tsx @@ -52,7 +52,7 @@ const VirtualCell = (props: VirtualCellProps) => { getHeight, } = props; - const { render, dataIndex, className: columnClassName, width: colWidth } = column; + const { render, dataIndex, className: columnClassName } = column; const { columnsOffset } = useContext(GridContext, ['columnsOffset']); @@ -72,16 +72,15 @@ const VirtualCell = (props: VirtualCellProps) => { const startColIndex = colIndex - 1; const concatColWidth = getColumnWidth(startColIndex, colSpan, columnsOffset); - // margin offset - const marginOffset = colSpan > 1 ? (colWidth as number) - concatColWidth : 0; - + // BodyLine skips covered (colSpan===0) columns, so occupy full span width. + // Negative marginRight was only needed when those placeholders stayed in the row. // ========================== Style =========================== const mergedStyle: React.CSSProperties = { ...cellStyle, ...style, flex: `0 0 ${concatColWidth}px`, width: `${concatColWidth}px`, - marginRight: marginOffset, + marginRight: 0, pointerEvents: 'auto', }; From a7c25a26e7da86511abd64feb3ff09750fb39578 Mon Sep 17 00:00:00 2001 From: jinxq <15618719643@163.com> Date: Thu, 3 Dec 2026 17:07:22 +0800 Subject: [PATCH 4/4] fix: keep zero-colSpan placeholders and remeasure gutter on fixHeader RowSpan-covered colSpan=0 cells keep hidden width when visited; same-row merges still skip via spanEnd. Remeasure scrollbar when fixed header / sticky toggles. --- src/Table.tsx | 2 +- src/VirtualTable/BodyLine.tsx | 16 +++++++++++++++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/src/Table.tsx b/src/Table.tsx index d657e4f59..0a873e573 100644 --- a/src/Table.tsx +++ b/src/Table.tsx @@ -621,7 +621,7 @@ const Table = ( measureScrollbarSize(); const rafId = window.requestAnimationFrame(() => measureScrollbarSize()); return () => window.cancelAnimationFrame(rafId); - }, [measureScrollbarSize, hasData, flattenColumns.length]); + }, [measureScrollbarSize, hasData, flattenColumns.length, fixHeader, isSticky]); // ================== INTERNAL HOOKS ================== React.useEffect(() => { diff --git a/src/VirtualTable/BodyLine.tsx b/src/VirtualTable/BodyLine.tsx index d1977f71f..6e83481ea 100644 --- a/src/VirtualTable/BodyLine.tsx +++ b/src/VirtualTable/BodyLine.tsx @@ -203,8 +203,22 @@ const BodyLine = React.forwardRef((props, ref) => const column = flattenColumns[colIndex]; const colSpan = getColSpan(column); - // Covered by a previous merge — width belongs to the start cell / spacer already + // colSpan===0 still visited here means coverage from another row (e.g. rowSpan), + // not a same-row span we already jumped via spanEnd. Keep a hidden placeholder width. if (colSpan === 0) { + const width = getColumnWidthByIndex(columnsOffset, colIndex); + if (isFixedColumn(column)) { + flushLeftSpacer(); + flushRightSpacer(); + pushVirtualCell(column, colIndex); + } else if (colIndex < colStart) { + leftSpacerWidth += width; + } else if (colIndex <= colEnd) { + flushLeftSpacer(); + pushVirtualCell(column, colIndex); + } else { + rightSpacerWidth += width; + } colIndex += 1; continue; }