Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 8 additions & 14 deletions packages/components/table/__tests__/enhanced-table.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<Array<string | number>>([]);
const [data] = useState(() => getVirtualTreeData(ROOT_COUNT));
Expand All @@ -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(<ControlledVirtualTreeTable />);
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);
Expand Down
103 changes: 101 additions & 2 deletions packages/components/table/__tests__/table.test.tsx
Original file line number Diff line number Diff line change
@@ -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 '..';

Expand Down Expand Up @@ -922,6 +922,91 @@ describe('Table', () => {
});

describe('scenarios', () => {
test('resizable fixed columns recalculate offsets after widening and narrowing', async () => {
const defaultWidths: Record<string, number> = {
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(
<Table
rowKey="id"
data={[
{
id: 1,
name: 'Name',
status: 'Status',
email: 'name@example.com',
detail: 'Detail',
},
]}
columns={[
{ colKey: 'name', title: 'Name', fixed: 'left', width: 120 },
{ colKey: 'status', title: 'Status', fixed: 'left', width: 100 },
{ colKey: 'email', title: 'Email', width: 180 },
{ colKey: 'detail', title: 'Detail', width: 200 },
]}
bordered
resizable
tableLayout="fixed"
/>,
);

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 = [
{
Expand Down Expand Up @@ -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;

Expand All @@ -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
Expand All @@ -1265,6 +1363,7 @@ describe('Table', () => {
});

afterAll(() => {
layoutMock?.();
descriptors.forEach(([prop, descriptor]) => Object.defineProperty(HTMLElement.prototype, prop, descriptor));
HTMLElement.prototype.scrollTo = scrollTo;
if (hadOwnBoundingRect) {
Expand Down
8 changes: 4 additions & 4 deletions packages/components/table/hooks/useColumnResize.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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);

// 在单元格分割线的右侧
Expand Down Expand Up @@ -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) {
Expand All @@ -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`,
Expand Down
35 changes: 29 additions & 6 deletions packages/components/table/hooks/useFixed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -110,12 +111,16 @@ export default function useFixed(
const [scrollbarWidth, setScrollbarWidth] = useState(6);
// 固定列、固定表头、固定表尾等内容的位置信息
const [rowAndColFixedPosition, setRowAndColFixedPosition] = useState<RowAndColFixedPosition>(() => 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,
});
Expand Down Expand Up @@ -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,
});
}
}
}
Expand Down Expand Up @@ -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--) {
/**
Expand All @@ -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,
});
}
};

Expand Down Expand Up @@ -523,7 +537,9 @@ export default function useFixed(

if (isFixedColumn || isFixedHeader) {
updateFixedStatus();
updateColumnFixedShadow(tableContentRef.current, { skipScrollLimit: true });
updateColumnFixedShadow(tableContentRef.current, {
skipScrollLimit: true,
});
}
};

Expand Down Expand Up @@ -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,
Expand Down
6 changes: 6 additions & 0 deletions packages/tdesign-react/.changelog/pr-4496.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
pr_number: 4496
contributor: RylanBot
---

- fix(Table): 修复固定列拖拽调整宽度后未及时更新,导致固定区域透出其他列内容的问题 @RylanBot ([#4496](https://github.com/Tencent/tdesign-react/pull/4496))
Loading