From fd83ee9a3927b9a07c8de6c676c69283659700c6 Mon Sep 17 00:00:00 2001 From: Rylan Date: Thu, 19 Nov 2026 15:42:07 +0800 Subject: [PATCH 1/3] fix(table): recalculate fixed columns after resize --- .../table/__tests__/enhanced-table.test.tsx | 22 ++- .../components/table/__tests__/table.test.tsx | 133 ++++++++++++++---- .../table/hooks/useColumnResize.tsx | 8 +- packages/components/table/hooks/useFixed.ts | 35 ++++- test/utils/index.jsx | 86 +++++++++-- 5 files changed, 223 insertions(+), 61 deletions(-) diff --git a/packages/components/table/__tests__/enhanced-table.test.tsx b/packages/components/table/__tests__/enhanced-table.test.tsx index 24550d2860..0091f80eda 100644 --- a/packages/components/table/__tests__/enhanced-table.test.tsx +++ b/packages/components/table/__tests__/enhanced-table.test.tsx @@ -191,18 +191,6 @@ describe('EnhancedTable', () => { })); } - function mockTableScrollContainer(element: HTMLElement, scrollHeight: number, clientHeight: number) { - Object.defineProperty(element, 'scrollHeight', { - value: scrollHeight, - configurable: true, - }); - Object.defineProperty(element, 'clientHeight', { - value: clientHeight, - configurable: true, - }); - element.scrollTop = 0; - } - function ControlledVirtualTreeTable() { const [expandedTreeNodes, setExpandedTreeNodes] = useState>([]); const [data] = useState(() => getVirtualTreeData(ROOT_COUNT)); @@ -227,14 +215,20 @@ describe('EnhancedTable', () => { } const restoreMock = mockElementSizes([ - { selector: '.t-table__content', height: TABLE_HEIGHT, width: 800 }, + { + selector: '.t-table__content', + height: TABLE_HEIGHT, + width: 800, + clientHeight: TABLE_HEIGHT, + scrollHeight: ROOT_COUNT * VIRTUAL_ROW_HEIGHT, + }, { selector: 'tr', height: VIRTUAL_ROW_HEIGHT, width: 800 }, ]); try { const { container } = render(); const scrollElement = container.querySelector('.t-table__content') as HTMLElement; - mockTableScrollContainer(scrollElement, ROOT_COUNT * VIRTUAL_ROW_HEIGHT, TABLE_HEIGHT); + scrollElement.scrollTop = 0; await act(async () => { await mockDelay(20); diff --git a/packages/components/table/__tests__/table.test.tsx b/packages/components/table/__tests__/table.test.tsx index 75a9fb033e..ad67d9befa 100644 --- a/packages/components/table/__tests__/table.test.tsx +++ b/packages/components/table/__tests__/table.test.tsx @@ -1,5 +1,5 @@ import React, { useState } from 'react'; -import { fireEvent, render, vi, waitFor } from '@test/utils'; +import { act, fireEvent, mockDelay, mockElementSizes, render, vi, waitFor } from '@test/utils'; import { Table } from '..'; @@ -893,6 +893,96 @@ describe('Table', () => { }); describe('scenarios', () => { + test('resizable fixed columns recalculate offsets after widening and narrowing', async () => { + const defaultWidths: Record = { + name: 120, + status: 100, + email: 180, + detail: 200, + }; + const getColumnWidth = (element: HTMLElement) => { + const width = parseFloat(element.style.width || ''); + return Number.isNaN(width) ? defaultWidths[element.dataset.colkey] || 100 : width; + }; + const contentSize = (element: HTMLElement, contentValue: number) => + element.classList.contains('t-table__content') ? contentValue : 0; + const restoreElementMock = mockElementSizes([ + { + selector: '.t-table__content', + width: 300, + height: 200, + clientWidth: 300, + clientHeight: 200, + scrollWidth: 600, + scrollHeight: 200, + }, + { selector: 'th', width: getColumnWidth, height: 40 }, + { + selector: '*', + width: (element: HTMLElement) => contentSize(element, 600) || 600, + height: 200, + }, + ]); + + try { + const { container } = render( + , + ); + + const getNameTh = () => container.querySelector('th[data-colkey="name"]') as HTMLElement; + const getStatusTh = () => container.querySelector('th[data-colkey="status"]') as HTMLElement; + const dragNameColumn = async (startX: number, endX: number) => { + const nameTh = getNameTh(); + fireEvent.mouseMove(nameTh, { clientX: startX }); + fireEvent.mouseDown(nameTh, { clientX: startX, button: 0 }); + await act(async () => { + document.dispatchEvent( + new MouseEvent('mousemove', { + clientX: endX, + buttons: 1, + bubbles: true, + }), + ); + document.dispatchEvent(new MouseEvent('mouseup', { clientX: endX, bubbles: true })); + }); + await mockDelay(20); + }; + + await dragNameColumn(116, 196); + await waitFor(() => { + expect(getNameTh()).toHaveStyle({ width: '200px' }); + }); + + await dragNameColumn(196, 116); + await waitFor(() => { + expect(getNameTh()).toHaveStyle({ width: '120px' }); + expect(getStatusTh()).toHaveStyle({ left: '120px' }); + }); + } finally { + restoreElementMock(); + } + }); + describe('columns[row-select] with selectedRowKeys state', () => { const selectColumns = [ { @@ -1073,43 +1163,30 @@ describe('Table', () => { const getPopups = () => document.querySelectorAll('.t-table__filter-pop-content'); describe('Virtual scroll', () => { - const descriptors: Array<[string, PropertyDescriptor]> = []; const { scrollTo } = HTMLElement.prototype; - - function mockSize(prop: string, value: number) { - const origin = Object.getOwnPropertyDescriptor(HTMLElement.prototype, prop); - if (origin) descriptors.push([prop, origin]); - Object.defineProperty(HTMLElement.prototype, prop, { - configurable: true, - get: () => value, - }); - } + let layoutMock: (() => void) | undefined; beforeAll(() => { - mockSize('clientWidth', 800); - mockSize('clientHeight', 200); - mockSize('scrollHeight', 4000); - mockSize('scrollWidth', 800); + layoutMock = mockElementSizes([ + { + selector: '.t-table__content', + width: 800, + height: 200, + scrollWidth: 800, + scrollHeight: 4000, + }, + { selector: 'thead', width: 800, height: 200 }, + { selector: 'tbody', width: 800, height: 200 }, + { selector: 'tr', width: 800, height: 200 }, + ]); // jsdom 未实现 Element.scrollTo HTMLElement.prototype.scrollTo = function scrollTo() { // do nothing }; - HTMLElement.prototype.getBoundingClientRect = function getBoundingClientRect() { - return { - width: 800, - height: 200, - top: 0, - left: 0, - right: 800, - bottom: 200, - x: 0, - y: 0, - } as DOMRect; - }; }); afterAll(() => { - descriptors.forEach(([prop, descriptor]) => Object.defineProperty(HTMLElement.prototype, prop, descriptor)); + layoutMock?.(); HTMLElement.prototype.scrollTo = scrollTo; }); diff --git a/packages/components/table/hooks/useColumnResize.tsx b/packages/components/table/hooks/useColumnResize.tsx index 194c34cc89..b7ce53b5f6 100644 --- a/packages/components/table/hooks/useColumnResize.tsx +++ b/packages/components/table/hooks/useColumnResize.tsx @@ -129,8 +129,8 @@ export default function useColumnResize(params: { const colKey = target.getAttribute('data-colkey'); if (!leafColumns.find((t) => t.colKey === colKey)) return; const targetBoundRect = target.getBoundingClientRect(); - const thRightCursor = targetBoundRect.right - e.pageX <= distance; - const thLeftCursor = e.pageX - targetBoundRect.left <= distance; + const thRightCursor = targetBoundRect.right - e.clientX <= distance; + const thLeftCursor = e.clientX - targetBoundRect.left <= distance; const isFixedToRight = isColRightFixActive(col); // 在单元格分割线的右侧 @@ -242,7 +242,7 @@ export default function useColumnResize(params: { // 开始拖拽,记录下鼠标起始位置 resizeLineParams.isDragging = true; - resizeLineParams.draggingStart = e.pageX || 0; + resizeLineParams.draggingStart = e.clientX || 0; // 初始化 resizeLine 标记线 if (resizeLineRef?.current) { @@ -262,7 +262,7 @@ export default function useColumnResize(params: { return; } if (resizeLineParams.isDragging) { - const left = resizeLinePos + e.x - resizeLineParams.draggingStart; + const left = resizeLinePos + e.clientX - resizeLineParams.draggingStart; const styles = { ...resizeLineParams.resizeLineStyle, left: `${Math.min(Math.max(left, minResizeLineLeft), maxResizeLineLeft)}px`, diff --git a/packages/components/table/hooks/useFixed.ts b/packages/components/table/hooks/useFixed.ts index f8be5f345d..8390d0b8ce 100644 --- a/packages/components/table/hooks/useFixed.ts +++ b/packages/components/table/hooks/useFixed.ts @@ -6,6 +6,7 @@ import { getIEVersion } from '@tdesign/common-js/utils/helper'; import { off, on } from '../../_util/listener'; import useDeepEffect from '../../hooks/useDeepEffect'; +import useLayoutEffect from '../../hooks/useLayoutEffect'; import usePrevious from '../../hooks/usePrevious'; import { resizeObserverElement } from '../utils'; @@ -110,12 +111,16 @@ export default function useFixed( const [scrollbarWidth, setScrollbarWidth] = useState(6); // 固定列、固定表头、固定表尾等内容的位置信息 const [rowAndColFixedPosition, setRowAndColFixedPosition] = useState(() => new Map()); + const [layoutId, setLayoutId] = useState(0); const [showColumnShadow, setShowColumnShadow] = useState({ left: false, right: false, }); // 虚拟滚动无法使用 CSS sticky 固定表头 - const [virtualScrollHeaderPos, setVirtualScrollHeaderPos] = useState<{ left: number; top: number }>({ + const [virtualScrollHeaderPos, setVirtualScrollHeaderPos] = useState<{ + left: number; + top: number; + }>({ left: 0, top: 0, }); @@ -239,7 +244,10 @@ export default function useFixed( } const obj = initialColumnMap.get(colKey || j); if (obj?.col?.fixed) { - initialColumnMap.set(colKey, { ...obj, width: th?.getBoundingClientRect?.().width }); + initialColumnMap.set(colKey, { + ...obj, + width: th?.getBoundingClientRect?.().width, + }); } } } @@ -267,7 +275,10 @@ export default function useFixed( defaultBottom = thead?.getBoundingClientRect?.().height || 0; } thisRowInfo.top = (lastRowInfo.top || defaultBottom) + (lastRowInfo.height || 0); - initialColumnMap.set(rowId, { ...thisRowInfo, height: tr?.getBoundingClientRect?.().height }); + initialColumnMap.set(rowId, { + ...thisRowInfo, + height: tr?.getBoundingClientRect?.().height, + }); } for (let i = data.length - 1; i >= data.length - fixedBottomRows; i--) { /** @@ -285,7 +296,10 @@ export default function useFixed( defaultBottom = tfoot?.getBoundingClientRect?.().height || 0; } thisRowInfo.bottom = (lastRowInfo.bottom || defaultBottom) + (lastRowInfo.height || 0); - initialColumnMap.set(rowId, { ...thisRowInfo, height: tr?.getBoundingClientRect?.().height }); + initialColumnMap.set(rowId, { + ...thisRowInfo, + height: tr?.getBoundingClientRect?.().height, + }); } }; @@ -523,7 +537,9 @@ export default function useFixed( if (isFixedColumn || isFixedHeader) { updateFixedStatus(); - updateColumnFixedShadow(tableContentRef.current, { skipScrollLimit: true }); + updateColumnFixedShadow(tableContentRef.current, { + skipScrollLimit: true, + }); } }; @@ -574,9 +590,16 @@ export default function useFixed( }, []); const updateTableAfterColumnResize = () => { + setLayoutId((id) => id + 1); + }; + + useLayoutEffect(() => { + if (!layoutId) return; updateFixedStatus(); updateFixedHeader(); - }; + updateColumnFixedShadow(tableContentRef.current, { skipScrollLimit: true }); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [layoutId]); return { tableWidth, diff --git a/test/utils/index.jsx b/test/utils/index.jsx index 72e3d8ac66..77cf628f64 100644 --- a/test/utils/index.jsx +++ b/test/utils/index.jsx @@ -234,10 +234,14 @@ export function mockResizeObserver(mockData = {}, mockFunc = {}) { * 批量模拟多个 DOM 元素的尺寸与位置信息 * @param {Array<{ * selector: string - * width?: number - * height?: number - * left?: number - * top?: number + * width?: number | ((element: HTMLElement) => number) + * height?: number | ((element: HTMLElement) => number) + * clientWidth?: number | ((element: HTMLElement) => number) + * clientHeight?: number | ((element: HTMLElement) => number) + * scrollWidth?: number | ((element: HTMLElement) => number) + * scrollHeight?: number | ((element: HTMLElement) => number) + * left?: number | ((element: HTMLElement) => number) + * top?: number | ((element: HTMLElement) => number) * }>} elementSizes */ export function mockElementSizes(elementSizes = []) { @@ -246,6 +250,10 @@ export function mockElementSizes(elementSizes = []) { const originalOffsetHeight = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'offsetHeight'); const originalOffsetLeft = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'offsetLeft'); const originalOffsetTop = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'offsetTop'); + const originalClientWidth = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'clientWidth'); + const originalClientHeight = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'clientHeight'); + const originalScrollWidth = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'scrollWidth'); + const originalScrollHeight = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'scrollHeight'); const isElementHidden = (element) => { if (element.hidden) return true; @@ -263,6 +271,11 @@ export function mockElementSizes(elementSizes = []) { return false; }); + const getConfigValue = (element, value, fallback) => { + if (typeof value === 'function') return value(element); + return value ?? fallback; + }; + Element.prototype.getBoundingClientRect = vi.fn(function () { // 如果元素被隐藏,返回全零的 DOMRect if (isElementHidden(this)) { @@ -283,7 +296,10 @@ export function mockElementSizes(elementSizes = []) { return originalGetBoundingClientRect.call(this); } - const { width = 100, height = 40, left = 0, top = 0 } = config; + const width = getConfigValue(this, config.width, 100); + const height = getConfigValue(this, config.height, 40); + const left = getConfigValue(this, config.left, 0); + const top = getConfigValue(this, config.top, 0); return { width, height, @@ -302,7 +318,7 @@ export function mockElementSizes(elementSizes = []) { if (isElementHidden(this)) return 0; const config = findConfig(this); - return config?.width || originalOffsetWidth?.get?.call(this) || 0; + return getConfigValue(this, config?.width, originalOffsetWidth?.get?.call(this) || 0); }, configurable: true, }, @@ -311,7 +327,7 @@ export function mockElementSizes(elementSizes = []) { if (isElementHidden(this)) return 0; const config = findConfig(this); - return config?.height || originalOffsetHeight?.get?.call(this) || 0; + return getConfigValue(this, config?.height, originalOffsetHeight?.get?.call(this) || 0); }, configurable: true, }, @@ -319,7 +335,7 @@ export function mockElementSizes(elementSizes = []) { get() { if (isElementHidden(this)) return 0; const config = findConfig(this); - return config?.left || originalOffsetLeft?.get?.call(this) || 0; + return getConfigValue(this, config?.left, originalOffsetLeft?.get?.call(this) || 0); }, configurable: true, }, @@ -327,7 +343,47 @@ export function mockElementSizes(elementSizes = []) { get() { if (isElementHidden(this)) return 0; const config = findConfig(this); - return config?.top || originalOffsetTop?.get?.call(this) || 0; + return getConfigValue(this, config?.top, originalOffsetTop?.get?.call(this) || 0); + }, + configurable: true, + }, + clientWidth: { + get() { + if (isElementHidden(this)) return 0; + const config = findConfig(this); + return getConfigValue(this, config?.clientWidth ?? config?.width, originalClientWidth?.get?.call(this) ?? 0); + }, + configurable: true, + }, + clientHeight: { + get() { + if (isElementHidden(this)) return 0; + const config = findConfig(this); + return getConfigValue(this, config?.clientHeight ?? config?.height, originalClientHeight?.get?.call(this) ?? 0); + }, + configurable: true, + }, + scrollWidth: { + get() { + if (isElementHidden(this)) return 0; + const config = findConfig(this); + return getConfigValue( + this, + config?.scrollWidth ?? config?.clientWidth ?? config?.width, + originalScrollWidth?.get?.call(this) ?? 0, + ); + }, + configurable: true, + }, + scrollHeight: { + get() { + if (isElementHidden(this)) return 0; + const config = findConfig(this); + return getConfigValue( + this, + config?.scrollHeight ?? config?.clientHeight ?? config?.height, + originalScrollHeight?.get?.call(this) ?? 0, + ); }, configurable: true, }, @@ -348,5 +404,17 @@ export function mockElementSizes(elementSizes = []) { if (originalOffsetTop) { Object.defineProperty(HTMLElement.prototype, 'offsetTop', originalOffsetTop); } + if (originalClientWidth) { + Object.defineProperty(HTMLElement.prototype, 'clientWidth', originalClientWidth); + } + if (originalClientHeight) { + Object.defineProperty(HTMLElement.prototype, 'clientHeight', originalClientHeight); + } + if (originalScrollWidth) { + Object.defineProperty(HTMLElement.prototype, 'scrollWidth', originalScrollWidth); + } + if (originalScrollHeight) { + Object.defineProperty(HTMLElement.prototype, 'scrollHeight', originalScrollHeight); + } }; } From de4ae5f1fe4a36f48bedd7bfd7cb2aa607a36175 Mon Sep 17 00:00:00 2001 From: Rylan Date: Thu, 19 Nov 2026 19:50:57 +0800 Subject: [PATCH 2/3] chore: optimize test --- .../components/table/__tests__/table.test.tsx | 13 ++---- test/utils/index.jsx | 40 ++++++++----------- 2 files changed, 20 insertions(+), 33 deletions(-) diff --git a/packages/components/table/__tests__/table.test.tsx b/packages/components/table/__tests__/table.test.tsx index ad67d9befa..b85eeafa66 100644 --- a/packages/components/table/__tests__/table.test.tsx +++ b/packages/components/table/__tests__/table.test.tsx @@ -904,9 +904,7 @@ describe('Table', () => { const width = parseFloat(element.style.width || ''); return Number.isNaN(width) ? defaultWidths[element.dataset.colkey] || 100 : width; }; - const contentSize = (element: HTMLElement, contentValue: number) => - element.classList.contains('t-table__content') ? contentValue : 0; - const restoreElementMock = mockElementSizes([ + const resetElementMock = mockElementSizes([ { selector: '.t-table__content', width: 300, @@ -917,11 +915,7 @@ describe('Table', () => { scrollHeight: 200, }, { selector: 'th', width: getColumnWidth, height: 40 }, - { - selector: '*', - width: (element: HTMLElement) => contentSize(element, 600) || 600, - height: 200, - }, + { selector: '*', width: 600, height: 200 }, ]); try { @@ -971,6 +965,7 @@ describe('Table', () => { await dragNameColumn(116, 196); await waitFor(() => { expect(getNameTh()).toHaveStyle({ width: '200px' }); + expect(getStatusTh()).toHaveStyle({ left: '200px' }); }); await dragNameColumn(196, 116); @@ -979,7 +974,7 @@ describe('Table', () => { expect(getStatusTh()).toHaveStyle({ left: '120px' }); }); } finally { - restoreElementMock(); + resetElementMock(); } }); diff --git a/test/utils/index.jsx b/test/utils/index.jsx index 77cf628f64..157dc02390 100644 --- a/test/utils/index.jsx +++ b/test/utils/index.jsx @@ -389,32 +389,24 @@ export function mockElementSizes(elementSizes = []) { }, }); + const resetSizeProperty = (prop, descriptor) => { + if (descriptor) { + Object.defineProperty(HTMLElement.prototype, prop, descriptor); + return; + } + delete HTMLElement.prototype[prop]; + }; + // 清理函数 return () => { Element.prototype.getBoundingClientRect = originalGetBoundingClientRect; - if (originalOffsetWidth) { - Object.defineProperty(HTMLElement.prototype, 'offsetWidth', originalOffsetWidth); - } - if (originalOffsetHeight) { - Object.defineProperty(HTMLElement.prototype, 'offsetHeight', originalOffsetHeight); - } - if (originalOffsetLeft) { - Object.defineProperty(HTMLElement.prototype, 'offsetLeft', originalOffsetLeft); - } - if (originalOffsetTop) { - Object.defineProperty(HTMLElement.prototype, 'offsetTop', originalOffsetTop); - } - if (originalClientWidth) { - Object.defineProperty(HTMLElement.prototype, 'clientWidth', originalClientWidth); - } - if (originalClientHeight) { - Object.defineProperty(HTMLElement.prototype, 'clientHeight', originalClientHeight); - } - if (originalScrollWidth) { - Object.defineProperty(HTMLElement.prototype, 'scrollWidth', originalScrollWidth); - } - if (originalScrollHeight) { - Object.defineProperty(HTMLElement.prototype, 'scrollHeight', originalScrollHeight); - } + resetSizeProperty('offsetWidth', originalOffsetWidth); + resetSizeProperty('offsetHeight', originalOffsetHeight); + resetSizeProperty('offsetLeft', originalOffsetLeft); + resetSizeProperty('offsetTop', originalOffsetTop); + resetSizeProperty('clientWidth', originalClientWidth); + resetSizeProperty('clientHeight', originalClientHeight); + resetSizeProperty('scrollWidth', originalScrollWidth); + resetSizeProperty('scrollHeight', originalScrollHeight); }; } From ca10d048064e1cd42817589e61c1d98932f3d831 Mon Sep 17 00:00:00 2001 From: tdesign-bot Date: Thu, 26 Nov 2026 10:33:44 +0000 Subject: [PATCH 3/3] chore: stash changelog [ci skip] --- packages/tdesign-react/.changelog/pr-4496.md | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 packages/tdesign-react/.changelog/pr-4496.md diff --git a/packages/tdesign-react/.changelog/pr-4496.md b/packages/tdesign-react/.changelog/pr-4496.md new file mode 100644 index 0000000000..b5fc1c8cb1 --- /dev/null +++ b/packages/tdesign-react/.changelog/pr-4496.md @@ -0,0 +1,6 @@ +--- +pr_number: 4496 +contributor: RylanBot +--- + +- fix(Table): 修复固定列拖拽调整宽度后未及时更新,导致固定区域透出其他列内容的问题 @RylanBot ([#4496](https://github.com/Tencent/tdesign-react/pull/4496))