diff --git a/packages/components/table/__tests__/enhanced-table.test.tsx b/packages/components/table/__tests__/enhanced-table.test.tsx index 4df03ca84b..f39f76692a 100644 --- a/packages/components/table/__tests__/enhanced-table.test.tsx +++ b/packages/components/table/__tests__/enhanced-table.test.tsx @@ -230,18 +230,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)); @@ -266,14 +254,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 1a37ac6a42..d3fd3c2f76 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 { createEvent, fireEvent, mockDelay, mockElementSizes, render, vi, waitFor } from '@test/utils'; +import { act, createEvent, fireEvent, mockDelay, mockElementSizes, render, vi, waitFor } from '@test/utils'; import { Table } from '..'; @@ -922,6 +922,91 @@ 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 resetElementMock = 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: 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' }); + expect(getStatusTh()).toHaveStyle({ left: '200px' }); + }); + + await dragNameColumn(196, 116); + await waitFor(() => { + expect(getNameTh()).toHaveStyle({ width: '120px' }); + expect(getStatusTh()).toHaveStyle({ left: '120px' }); + }); + } finally { + resetElementMock(); + } + }); + describe('columns[row-select] with selectedRowKeys state', () => { const selectColumns = [ { @@ -1227,8 +1312,9 @@ describe('Table', () => { const getPopups = () => document.querySelectorAll('.t-table__filter-pop-content'); describe('Virtual scroll', () => { - const descriptors: Array<[string, PropertyDescriptor]> = []; const { scrollTo } = HTMLElement.prototype; + const descriptors: Array<[string, PropertyDescriptor]> = []; + let layoutMock: (() => void) | undefined; const hadOwnBoundingRect = Object.prototype.hasOwnProperty.call(HTMLElement.prototype, 'getBoundingClientRect'); const originalGetBoundingClientRect = HTMLElement.prototype.getBoundingClientRect; @@ -1246,6 +1332,18 @@ describe('Table', () => { 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 @@ -1265,6 +1363,7 @@ describe('Table', () => { }); afterAll(() => { + layoutMock?.(); descriptors.forEach(([prop, descriptor]) => Object.defineProperty(HTMLElement.prototype, prop, descriptor)); HTMLElement.prototype.scrollTo = scrollTo; if (hadOwnBoundingRect) { diff --git a/packages/components/table/hooks/useColumnResize.tsx b/packages/components/table/hooks/useColumnResize.tsx index 679bdc2ebb..df09da69d0 100644 --- a/packages/components/table/hooks/useColumnResize.tsx +++ b/packages/components/table/hooks/useColumnResize.tsx @@ -133,8 +133,8 @@ export default function useColumnResize(params: { 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); // 在单元格分割线的右侧 @@ -251,7 +251,7 @@ export default function useColumnResize(params: { // 开始拖拽,记录下鼠标起始位置 resizeLineParams.isDragging = true; - resizeLineParams.draggingStart = e.pageX || 0; + resizeLineParams.draggingStart = e.clientX || 0; // 初始化 resizeLine 标记线 if (resizeLineRef?.current) { @@ -271,7 +271,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/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)) diff --git a/test/utils/index.jsx b/test/utils/index.jsx index 72e3d8ac66..157dc02390 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,26 +343,70 @@ 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, }, }); + 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); - } + resetSizeProperty('offsetWidth', originalOffsetWidth); + resetSizeProperty('offsetHeight', originalOffsetHeight); + resetSizeProperty('offsetLeft', originalOffsetLeft); + resetSizeProperty('offsetTop', originalOffsetTop); + resetSizeProperty('clientWidth', originalClientWidth); + resetSizeProperty('clientHeight', originalClientHeight); + resetSizeProperty('scrollWidth', originalScrollWidth); + resetSizeProperty('scrollHeight', originalScrollHeight); }; }