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
8 changes: 8 additions & 0 deletions docs/demo/expandedSticky.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
title: expandedSticky
nav:
title: Demo
path: /demo
---

<code src="../examples/expandedSticky.tsx"></code>
95 changes: 95 additions & 0 deletions docs/examples/expandedSticky.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import React, { useState } from 'react';
import type { ColumnType } from 'rc-table';
import Table from 'rc-table';
import '../../assets/index.less';

// 合并单元格
export const getRowSpan = (source: (string | number | undefined)[] = []) => {
const list: { rowSpan?: number }[] = [];
let span = 0;
source.reverse().forEach((key, index) => {
span = span + 1;
if (key !== source[index + 1]) {
list.push({ rowSpan: span });
span = 0;
} else {
list.push({ rowSpan: 0 });
}
});
return list.reverse();
};

const Demo = () => {
const [expandedRowKeys, setExpandedRowKeys] = useState<readonly React.Key[]>([]);

const data = [
{ key: 'a', a: '小二', d: '文零西路' },
{ key: 'b', a: '张三', d: '文一西路' },
{ key: 'c', a: '张三', d: '文二西路' },
];
// const rowKeys = data.map(item => item.key);

// const rowSpanList = getRowSpan(data.map(item => item.a));

const columns: ColumnType<Record<string, any>>[] = [
{
title: '手机号',
dataIndex: 'a',
width: 100,
colSpan: 2,
// fixed: 'left',
onCell: (_, index) => {
// const { rowSpan = 1 } = rowSpanList[index];
// const props: React.TdHTMLAttributes<HTMLTableCellElement> = {};
// props.rowSpan = rowSpan;
// if (rowSpan >= 1) {
// let currentRowSpan = rowSpan;
// for (let i = index; i < index + rowSpan; i += 1) {
// const rowKey = rowKeys[i];
// if (expandedRowKeys.includes(rowKey)) {
// currentRowSpan += 1;
// }
// }
// props.rowSpan = currentRowSpan;
// }
// return props;

if (index === 1) {
return {
rowSpan: 2,
};
} else if (index === 2) {
return {
rowSpan: 0,
};
}
},
},
{ title: 'key', dataIndex: 'key2', colSpan: 0, width: 100 },
Table.EXPAND_COLUMN,
{ title: 'key', dataIndex: 'key' },
{ title: 'Address', fixed: 'right', dataIndex: 'd', width: 200 },
];

return (
<div style={{ height: 10000 }}>
<h2>expanded & sticky</h2>
<Table<Record<string, any>>
rowKey="key"
sticky
scroll={{ x: 1000 }}
columns={columns}
data={data}
expandable={{
expandedRowOffset: 2,
expandedRowKeys,
onExpandedRowsChange: keys => setExpandedRowKeys(keys),
expandedRowRender: record => <p style={{ margin: 0 }}>expandedRowRender: {record.key}</p>,
}}
className="table"
/>
</div>
);
};

export default Demo;
45 changes: 39 additions & 6 deletions src/Body/BodyRow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import useRowInfo from '../hooks/useRowInfo';
import type { ColumnType, CustomizeComponent } from '../interface';
import ExpandedRow from './ExpandedRow';
import { computedExpandedClassName } from '../utils/expandUtil';
import { TableProps } from '..';
import type { TableProps } from '..';

export interface BodyRowProps<RecordType> {
record: RecordType;
Expand All @@ -22,6 +22,14 @@ export interface BodyRowProps<RecordType> {
scopeCellComponent: CustomizeComponent;
indent?: number;
rowKey: React.Key;
rowKeys: React.Key[];

// Expanded Row
expandedRowInfo?: {
offset: number;
colSpan: number;
sticky: number;
};
}

// ==================================================================================
Expand All @@ -33,6 +41,8 @@ export function getCellProps<RecordType>(
colIndex: number,
indent: number,
index: number,
rowKeys: React.Key[] = [],
expandedRowOffset = 0,
) {
const {
record,
Expand All @@ -46,6 +56,8 @@ export function getCellProps<RecordType>(
expanded,
hasNestChildren,
onTriggerExpand,
expandable,
expandedKeys,
} = rowInfo;

const key = columnsKey[colIndex];
Expand All @@ -71,16 +83,32 @@ export function getCellProps<RecordType>(
);
}

let additionalCellProps: React.TdHTMLAttributes<HTMLElement>;
if (column.onCell) {
additionalCellProps = column.onCell(record, index);
const additionalCellProps = column.onCell?.(record, index) || {};

// Expandable row has offset
if (expandedRowOffset) {
const { rowSpan = 1 } = additionalCellProps;

// For expandable row with rowSpan,
// We should increase the rowSpan if the row is expanded
if (expandable && rowSpan && colIndex < expandedRowOffset) {
let currentRowSpan = rowSpan;

for (let i = index; i < index + rowSpan; i += 1) {
const rowKey = rowKeys[i];
if (expandedKeys.has(rowKey)) {
currentRowSpan += 1;
}
}
additionalCellProps.rowSpan = currentRowSpan;
}
}
Comment on lines +89 to 105
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

建议添加数组边界检查

在第 98 行访问 rowKeys[i] 时,应该确保索引不超出数组范围,以避免潜在的运行时错误。

   // Expandable row has offset
   if (expandedRowOffset) {
     const { rowSpan = 1 } = additionalCellProps;
 
     // For expandable row with rowSpan,
     // We should increase the rowSpan if the row is expanded
     if (expandable && rowSpan && colIndex < expandedRowOffset) {
       let currentRowSpan = rowSpan;
 
       for (let i = index; i < index + rowSpan; i += 1) {
+        if (i >= rowKeys.length) {
+          break;
+        }
         const rowKey = rowKeys[i];
         if (expandedKeys.has(rowKey)) {
           currentRowSpan += 1;
         }
       }
       additionalCellProps.rowSpan = currentRowSpan;
     }
   }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (expandedRowOffset) {
const { rowSpan = 1 } = additionalCellProps;
// For expandable row with rowSpan,
// We should increase the rowSpan if the row is expanded
if (expandable && rowSpan && colIndex < expandedRowOffset) {
let currentRowSpan = rowSpan;
for (let i = index; i < index + rowSpan; i += 1) {
const rowKey = rowKeys[i];
if (expandedKeys.has(rowKey)) {
currentRowSpan += 1;
}
}
additionalCellProps.rowSpan = currentRowSpan;
}
}
if (expandedRowOffset) {
const { rowSpan = 1 } = additionalCellProps;
// For expandable row with rowSpan,
// We should increase the rowSpan if the row is expanded
if (expandable && rowSpan && colIndex < expandedRowOffset) {
let currentRowSpan = rowSpan;
for (let i = index; i < index + rowSpan; i += 1) {
if (i >= rowKeys.length) {
break;
}
const rowKey = rowKeys[i];
if (expandedKeys.has(rowKey)) {
currentRowSpan += 1;
}
}
additionalCellProps.rowSpan = currentRowSpan;
}
}
🤖 Prompt for AI Agents
In src/Body/BodyRow.tsx around lines 89 to 105, the code accesses rowKeys[i]
without checking if i is within the bounds of the rowKeys array, which can cause
runtime errors. Add a boundary check inside the for loop to ensure i is less
than rowKeys.length before accessing rowKeys[i]. This prevents out-of-range
access and potential crashes.


return {
key,
fixedInfo,
appendCellNode,
additionalCellProps: additionalCellProps || {},
additionalCellProps: additionalCellProps,
};
}

Expand All @@ -103,10 +131,12 @@ function BodyRow<RecordType extends { children?: readonly RecordType[] }>(
index,
renderIndex,
rowKey,
rowKeys,
indent = 0,
rowComponent: RowComponent,
cellComponent,
scopeCellComponent,
expandedRowInfo,
} = props;

const rowInfo = useRowInfo(record, rowKey, index, indent);
Expand Down Expand Up @@ -164,6 +194,8 @@ function BodyRow<RecordType extends { children?: readonly RecordType[] }>(
colIndex,
indent,
index,
rowKeys,
expandedRowInfo?.offset,
);

return (
Expand Down Expand Up @@ -207,8 +239,9 @@ function BodyRow<RecordType extends { children?: readonly RecordType[] }>(
prefixCls={prefixCls}
component={RowComponent}
cellComponent={cellComponent}
colSpan={flattenColumns.length}
colSpan={expandedRowInfo ? expandedRowInfo.colSpan : flattenColumns.length}
isEmpty={false}
stickyOffset={expandedRowInfo?.sticky}
>
{expandContent}
</ExpandedRow>
Expand Down
6 changes: 4 additions & 2 deletions src/Body/ExpandedRow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export interface ExpandedRowProps {
children: React.ReactNode;
colSpan: number;
isEmpty: boolean;
stickyOffset?: number;
}

function ExpandedRow(props: ExpandedRowProps) {
Expand All @@ -30,6 +31,7 @@ function ExpandedRow(props: ExpandedRowProps) {
expanded,
colSpan,
isEmpty,
stickyOffset = 0,
} = props;

const { scrollbarSize, fixHeader, fixColumn, componentWidth, horizonScroll } = useContext(
Expand All @@ -44,9 +46,9 @@ function ExpandedRow(props: ExpandedRowProps) {
contentNode = (
<div
style={{
width: componentWidth - (fixHeader && !isEmpty ? scrollbarSize : 0),
width: componentWidth - stickyOffset - (fixHeader && !isEmpty ? scrollbarSize : 0),
position: 'sticky',
left: 0,
left: stickyOffset,
overflow: 'hidden',
}}
className={`${prefixCls}-expanded-row-fixed`}
Expand Down
44 changes: 37 additions & 7 deletions src/Body/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ function Body<RecordType>(props: BodyProps<RecordType>) {
emptyNode,
classNames,
styles,
expandedRowOffset = 0,
colWidths,
} = useContext(TableContext, [
'prefixCls',
'getComponent',
Expand All @@ -45,18 +47,45 @@ function Body<RecordType>(props: BodyProps<RecordType>) {
'emptyNode',
'classNames',
'styles',
'expandedRowOffset',
'fixedInfoList',
'colWidths',
]);
const { body: bodyCls = {} } = classNames || {};
const { body: bodyStyles = {} } = styles || {};

const flattenData: { record: RecordType; indent: number; index: number }[] =
useFlattenRecords<RecordType>(data, childrenColumnName, expandedKeys, getRowKey);
const flattenData = useFlattenRecords<RecordType>(
data,
childrenColumnName,
expandedKeys,
getRowKey,
);

const rowKeys = React.useMemo(() => flattenData.map(item => item.rowKey), [flattenData]);

// =================== Performance ====================
const perfRef = React.useRef<PerfRecord>({
renderWithProps: false,
});

// ===================== Expanded =====================
// `expandedRowOffset` data is same for all the rows.
// Let's calc on Body side to save performance.
const expandedRowInfo = React.useMemo(() => {
const expandedColSpan = flattenColumns.length - expandedRowOffset;

let expandedStickyStart = 0;
for (let i = 0; i < expandedRowOffset; i += 1) {
expandedStickyStart += colWidths[i] || 0;
}

return {
offset: expandedRowOffset,
colSpan: expandedColSpan,
sticky: expandedStickyStart,
};
}, [flattenColumns.length, expandedRowOffset, colWidths]);

// ====================== Render ======================
const WrapperComponent = getComponent(['body', 'wrapper'], 'tbody');
const trComponent = getComponent(['body', 'row'], 'tr');
Expand All @@ -66,23 +95,24 @@ function Body<RecordType>(props: BodyProps<RecordType>) {
let rows: React.ReactNode;
if (data.length) {
rows = flattenData.map((item, idx) => {
const { record, indent, index: renderIndex } = item;

const key = getRowKey(record, idx);
const { record, indent, index: renderIndex, rowKey } = item;

return (
<BodyRow
classNames={bodyCls}
styles={bodyStyles}
key={key}
rowKey={key}
key={rowKey}
rowKey={rowKey}
rowKeys={rowKeys}
record={record}
index={idx}
renderIndex={renderIndex}
rowComponent={trComponent}
cellComponent={tdComponent}
scopeCellComponent={thComponent}
indent={indent}
// Expanded row info
expandedRowInfo={expandedRowInfo}
/>
);
});
Expand Down
4 changes: 4 additions & 0 deletions src/Table.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -870,6 +870,7 @@ function Table<RecordType extends DefaultRecordType>(
expandableType,
expandRowByClick: expandableConfig.expandRowByClick,
expandedRowRender: expandableConfig.expandedRowRender,
expandedRowOffset: expandableConfig.expandedRowOffset,
onTriggerExpand,
expandIconColumnIndex: expandableConfig.expandIconColumnIndex,
indentSize: expandableConfig.indentSize,
Expand All @@ -880,6 +881,7 @@ function Table<RecordType extends DefaultRecordType>(
columns,
flattenColumns,
onColumnResize,
colWidths,

// Row
hoverStartRow: startRow,
Expand Down Expand Up @@ -920,6 +922,7 @@ function Table<RecordType extends DefaultRecordType>(
expandableType,
expandableConfig.expandRowByClick,
expandableConfig.expandedRowRender,
expandableConfig.expandedRowOffset,
onTriggerExpand,
expandableConfig.expandIconColumnIndex,
expandableConfig.indentSize,
Expand All @@ -929,6 +932,7 @@ function Table<RecordType extends DefaultRecordType>(
columns,
flattenColumns,
onColumnResize,
colWidths,

// Row
startRow,
Expand Down
1 change: 1 addition & 0 deletions src/VirtualTable/VirtualCell.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ function VirtualCell<RecordType = any>(props: VirtualCellProps<RecordType>) {

const { columnsOffset } = useContext(GridContext, ['columnsOffset']);

// TODO: support `expandableRowOffset`
const { key, fixedInfo, appendCellNode, additionalCellProps } = getCellProps(
rowInfo,
column,
Expand Down
4 changes: 4 additions & 0 deletions src/context/TableContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type {
ColumnsType,
ColumnType,
Direction,
ExpandableConfig,
ExpandableType,
ExpandedRowRender,
GetComponent,
Expand Down Expand Up @@ -61,6 +62,7 @@ export interface TableContextProps<RecordType = any> {
columns: ColumnsType<RecordType>;
flattenColumns: readonly ColumnType<RecordType>[];
onColumnResize: (columnKey: React.Key, width: number) => void;
colWidths: number[];

// Row
hoverStartRow: number;
Expand All @@ -73,6 +75,8 @@ export interface TableContextProps<RecordType = any> {
childrenColumnName: string;

rowHoverable?: boolean;

expandedRowOffset: ExpandableConfig<RecordType>['expandedRowOffset'];
}

const TableContext = createContext<TableContextProps>();
Expand Down
Loading