Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: auto spread width when table size is large than columns #1021

Merged
merged 3 commits into from
Sep 13, 2023
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
13 changes: 12 additions & 1 deletion docs/examples/virtual.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ interface RecordType {
}

const columns: ColumnsType = [
// { title: 'title1', dataIndex: 'a', key: 'a', width: 100,},
// { title: 'title1', dataIndex: 'a', key: 'a', width: 100, },
{ title: 'title1', dataIndex: 'a', key: 'a', width: 100, fixed: 'left' },
{ title: 'title2', dataIndex: 'b', key: 'b', width: 100, fixed: 'left', ellipsis: true },
{
Expand Down Expand Up @@ -198,7 +200,7 @@ const Demo = () => {
<VirtualTable
columns={columns}
// expandedRowRender={({ b, c }) => b || c}
scroll={{ x: 1200, y: scrollY ? 200 : null }}
scroll={{ x: 1300, y: scrollY ? 200 : null }}
data={data}
// data={[]}
rowKey="indexKey"
Expand All @@ -209,6 +211,15 @@ const Demo = () => {
}}
// onRow={() => ({ className: 'rowed' })}
rowClassName="nice-try"
getContainerWidth={(ele, width) => {
// Minus border
const borderWidth = getComputedStyle(
ele.querySelector('.rc-virtual-list'),
).borderInlineStartWidth;
const mergedWidth = width - parseInt(borderWidth, 10);

return mergedWidth;
}}
/>
</div>
);
Expand Down
23 changes: 19 additions & 4 deletions src/Table.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,8 @@ export interface TableProps<RecordType = unknown>

direction?: Direction;

sticky?: boolean | TableSticky;

// =================================== Internal ===================================
/**
* @private Internal usage, may remove by refactor. Should always use `columns` instead.
Expand All @@ -143,6 +145,14 @@ export interface TableProps<RecordType = unknown>
// Force column to be average width if not set
tailor?: boolean;

/**
* @private Internal usage, may remove by refactor.
*
* !!! DO NOT USE IN PRODUCTION ENVIRONMENT !!!
*/
// Pass the way to get real width. e.g. exclude the border width
getContainerWidth?: (ele: HTMLElement, width: number) => number;

/**
* @private Internal usage, may remove by refactor.
*
Expand All @@ -151,8 +161,6 @@ export interface TableProps<RecordType = unknown>
internalRefs?: {
body: React.MutableRefObject<HTMLDivElement>;
};

sticky?: boolean | TableSticky;
}

function defaultEmpty() {
Expand Down Expand Up @@ -197,6 +205,7 @@ function Table<RecordType extends DefaultRecordType>(tableProps: TableProps<Reco
transformColumns,
internalRefs,
tailor,
getContainerWidth,

sticky,
} = props;
Expand Down Expand Up @@ -281,6 +290,7 @@ function Table<RecordType extends DefaultRecordType>(tableProps: TableProps<Reco
expandIconColumnIndex: expandableConfig.expandIconColumnIndex,
direction,
scrollWidth: useInternalHooks && tailor && typeof scrollX === 'number' ? scrollX : null,
clientWidth: componentWidth,
},
useInternalHooks ? transformColumns : null,
);
Expand Down Expand Up @@ -432,9 +442,14 @@ function Table<RecordType extends DefaultRecordType>(tableProps: TableProps<Reco
};

const onFullTableResize = ({ width }) => {
if (width !== componentWidth) {
let mergedWidth = fullTableRef.current ? fullTableRef.current.offsetWidth : width;
if (useInternalHooks && getContainerWidth) {
mergedWidth = getContainerWidth(fullTableRef.current, mergedWidth) || mergedWidth;
}

if (mergedWidth !== componentWidth) {
triggerOnScroll();
setComponentWidth(fullTableRef.current ? fullTableRef.current.offsetWidth : width);
setComponentWidth(mergedWidth);
}
};

Expand Down
10 changes: 2 additions & 8 deletions src/VirtualTable/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,26 +17,20 @@ const renderBody: CustomizeScrollBody<any> = (rawData, props) => {

export interface VirtualTableProps<RecordType> extends Omit<TableProps<RecordType>, 'scroll'> {
scroll: {
x: number;
x?: number;
y: number;
};
listItemHeight?: number;
}

const PRESET_COLUMN_WIDTH = 100;

function VirtualTable<RecordType>(props: VirtualTableProps<RecordType>) {
const { columns, scroll, prefixCls = DEFAULT_PREFIX, className, listItemHeight } = props;

let { x: scrollX, y: scrollY } = scroll || {};

// Fill scrollX
if (typeof scrollX !== 'number') {
scrollX = ((columns || []).length + 1) * PRESET_COLUMN_WIDTH;

if (process.env.NODE_ENV !== 'production') {
warning(false, '`scroll.x` in virtual table must be number.');
}
scrollX = 1;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这个改动小弟没咋理解 🤔️

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

通过 Table 的 useColumns 计算,所以这边不需要用户强制配置了。

}

// Fill scrollY
Expand Down
8 changes: 7 additions & 1 deletion src/hooks/useColumns/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,7 @@ function useColumns<RecordType>(
columnWidth,
fixed,
scrollWidth,
clientWidth,
}: {
prefixCls?: string;
columns?: ColumnsType<RecordType>;
Expand All @@ -147,6 +148,7 @@ function useColumns<RecordType>(
direction?: Direction;
expandRowByClick?: boolean;
columnWidth?: number | string;
clientWidth: number;
fixed?: FixedType;
scrollWidth?: number;
},
Expand Down Expand Up @@ -278,7 +280,11 @@ function useColumns<RecordType>(
}

// ========================= FillWidth ========================
const [filledColumns, realScrollWidth] = useWidthColumns(flattenColumns, scrollWidth);
const [filledColumns, realScrollWidth] = useWidthColumns(
flattenColumns,
scrollWidth,
clientWidth,
);

return [mergedColumns, filledColumns, realScrollWidth];
}
Expand Down
28 changes: 24 additions & 4 deletions src/hooks/useColumns/useWidthColumns.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,11 @@ function parseColWidth(totalWidth: number, width: string | number = '') {
/**
* Fill all column with width
*/
export default function useWidthColumns(flattenColumns: ColumnsType<any>, scrollWidth: number) {
export default function useWidthColumns(
flattenColumns: ColumnsType<any>,
scrollWidth: number,
clientWidth: number,
) {
return React.useMemo<[columns: ColumnsType<any>, realScrollWidth: number]>(() => {
// Fill width if needed
if (scrollWidth && scrollWidth > 0) {
Expand All @@ -34,7 +38,7 @@ export default function useWidthColumns(flattenColumns: ColumnsType<any>, scroll
});

// Fill width
let restWidth = scrollWidth - totalWidth;
let restWidth = Math.max(scrollWidth - totalWidth, missWidthCount);
let restCount = missWidthCount;
const avgWidth = restWidth / missWidthCount;

Expand Down Expand Up @@ -63,9 +67,25 @@ export default function useWidthColumns(flattenColumns: ColumnsType<any>, scroll
return clone;
});

return [filledColumns, realTotal];
// If realTotal is less than clientWidth,
// We need extend column width
if (realTotal < clientWidth) {
const scale = clientWidth / realTotal;

restWidth = clientWidth;

filledColumns.forEach((col: any, index) => {
const colWidth = Math.floor(col.width * scale);

col.width = index === filledColumns.length - 1 ? restWidth : colWidth;

restWidth -= colWidth;
});
}

return [filledColumns, Math.max(realTotal, clientWidth)];
}

return [flattenColumns, scrollWidth];
}, [flattenColumns, scrollWidth]);
}, [flattenColumns, scrollWidth, clientWidth]);
}
20 changes: 19 additions & 1 deletion tests/Virtual.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,6 @@ describe('Table.Virtual', () => {
scroll: {} as any,
});

expect(errSpy).toHaveBeenCalledWith('Warning: `scroll.x` in virtual table must be number.');
expect(errSpy).toHaveBeenCalledWith('Warning: `scroll.y` in virtual table must be number.');
});

Expand Down Expand Up @@ -226,4 +225,23 @@ describe('Table.Virtual', () => {

expect(container.querySelector('.bamboo').textContent).toEqual('0');
});

it('columns less than width', async () => {
const { container } = getTable({
columns: [{}, {}],
scroll: {
y: 10,
},
getContainerWidth: () => 200,
data: [{}],
});

resize(container.querySelector('.rc-table'));

await waitFakeTimer();

expect(container.querySelectorAll('col')).toHaveLength(2);
expect(container.querySelectorAll('col')[0]).toHaveStyle({ width: '100px' });
expect(container.querySelectorAll('col')[1]).toHaveStyle({ width: '100px' });
});
});
Loading