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..0a873e573 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, @@ -361,27 +360,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 +589,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 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]); + + useLayoutEffect(() => { + measureScrollbarSize(); + const rafId = window.requestAnimationFrame(() => measureScrollbarSize()); + return () => window.cancelAnimationFrame(rafId); + }, [measureScrollbarSize, hasData, flattenColumns.length, fixHeader, isSticky]); // ================== INTERNAL HOOKS ================== React.useEffect(() => { @@ -695,11 +720,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..6575d3026 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); @@ -89,6 +99,22 @@ const Grid = React.forwardRef((props, ref) => { // =========================== Ref ============================ 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; @@ -100,6 +126,8 @@ const Grid = React.forwardRef((props, ref) => { offset, align: virtualAlign, }); + // scrollTo may not emit onVirtualScroll (esp. left-only); keep col virtual in sync + syncOffsetXAfterScroll(restConfig.left); }, nativeElement: listRef.current?.nativeElement, } as unknown as GridRef; @@ -111,6 +139,7 @@ const Grid = React.forwardRef((props, ref) => { listRef.current?.scrollTo({ left: value, }); + syncOffsetXAfterScroll(value); }, }); @@ -243,7 +272,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 +309,20 @@ 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 => { + // 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} > {(item, index, itemProps) => { diff --git a/src/VirtualTable/BodyLine.tsx b/src/VirtualTable/BodyLine.tsx index 03167329e..6e83481ea 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,135 @@ 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; + }; + + // 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, index) 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); + + // 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; + } + + 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(); + pushVirtualCell(column, colIndex); + colIndex = spanEnd + 1; + continue; + } + + const intersectsVisible = spanEnd >= colStart && colIndex <= colEnd; + + if (colIndex < colStart && !intersectsVisible) { + leftSpacerWidth += spanWidth; + colIndex = spanEnd + 1; + continue; + } + + if (intersectsVisible) { + flushLeftSpacer(); + pushVirtualCell(column, colIndex); + colIndex = spanEnd + 1; + continue; + } + + rightSpacerWidth += spanWidth; + colIndex = spanEnd + 1; + } + + flushLeftSpacer(); + flushRightSpacer(); + const rowNode = ( ((props, ref) => })} style={{ ...rowStyle, ...rowProps?.style, ...styles?.body?.row }} > - {flattenColumns.map((column, colIndex) => { - return ( - - ); - })} + {cells} ); 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', }; 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,