Skip to content

expanded&sticky support expandedRowOffset #1281

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

Closed
Closed
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>
82 changes: 82 additions & 0 deletions docs/examples/expandedSticky.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
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();
};
Comment on lines +7 to +20
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

修复数组变异的副作用问题

getRowSpan 函数存在副作用问题:直接调用 source.reverse() 会修改原始数组,这可能导致意外的行为。

应用以下修改来避免副作用:

-export const getRowSpan = (source: (string | number | undefined)[] = []) => {
+export const getRowSpan = (source: (string | number | undefined)[] = []) => {
   const list: { rowSpan?: number }[] = [];
   let span = 0;
-  source.reverse().forEach((key, index) => {
+  const reversedSource = [...source].reverse();
+  reversedSource.forEach((key, index) => {
     span = span + 1;
-    if (key !== source[index + 1]) {
+    if (key !== reversedSource[index + 1]) {
       list.push({ rowSpan: span });
       span = 0;
     } else {
       list.push({ rowSpan: 0 });
     }
   });
   return list.reverse();
 };
📝 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
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();
};
export const getRowSpan = (source: (string | number | undefined)[] = []) => {
const list: { rowSpan?: number }[] = [];
let span = 0;
const reversedSource = [...source].reverse();
reversedSource.forEach((key, index) => {
span = span + 1;
if (key !== reversedSource[index + 1]) {
list.push({ rowSpan: span });
span = 0;
} else {
list.push({ rowSpan: 0 });
}
});
return list.reverse();
};
🤖 Prompt for AI Agents
In docs/examples/expandedSticky.tsx around lines 7 to 20, the getRowSpan
function mutates the original source array by calling source.reverse(), causing
side effects. To fix this, create a shallow copy of the source array before
reversing it, for example by using source.slice().reverse(), so the original
array remains unchanged and side effects are avoided.


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,
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;
},
},
Table.EXPAND_COLUMN,
{ 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: 800 }}
columns={columns}
data={data}
expandable={{
expandedRowOffset: 1,
expandedRowKeys,
onExpandedRowsChange: keys => setExpandedRowKeys(keys),
expandedRowRender: record => <p style={{ margin: 0 }}>{record.key}</p>,
}}
className="table"
/>
</div>
);
};

export default Demo;
15 changes: 13 additions & 2 deletions src/Body/BodyRow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import Cell from '../Cell';
import { responseImmutable } from '../context/TableContext';
import devRenderTimes from '../hooks/useRenderTimes';
import useRowInfo from '../hooks/useRowInfo';
import type { ColumnType, CustomizeComponent } from '../interface';
import type { ColumnType, CustomizeComponent, ExpandableConfig } from '../interface';
import ExpandedRow from './ExpandedRow';
import { computedExpandedClassName } from '../utils/expandUtil';

Expand All @@ -19,6 +19,7 @@ export interface BodyRowProps<RecordType> {
scopeCellComponent: CustomizeComponent;
indent?: number;
rowKey: React.Key;
expandedRowOffset?: ExpandableConfig<RecordType>['expandedRowOffset'];
}

// ==================================================================================
Expand Down Expand Up @@ -102,6 +103,7 @@ function BodyRow<RecordType extends { children?: readonly RecordType[] }>(
rowComponent: RowComponent,
cellComponent,
scopeCellComponent,
expandedRowOffset = 0,
} = props;
const rowInfo = useRowInfo(record, rowKey, index, indent);
const {
Expand Down Expand Up @@ -184,6 +186,14 @@ function BodyRow<RecordType extends { children?: readonly RecordType[] }>(
if (rowSupportExpand && (expandedRef.current || expanded)) {
const expandContent = expandedRowRender(record, index, indent + 1, expanded);

const offsetColumns = flattenColumns.filter((_, idx) => idx < expandedRowOffset);
let offsetWidth = 0;
offsetColumns.forEach(item => {
if (typeof item.width === 'number') {
offsetWidth = offsetWidth + (item.width ?? 0);
}
});

expandRowNode = (
<ExpandedRow
expanded={expanded}
Expand All @@ -195,7 +205,8 @@ function BodyRow<RecordType extends { children?: readonly RecordType[] }>(
prefixCls={prefixCls}
component={RowComponent}
cellComponent={cellComponent}
colSpan={flattenColumns.length}
offsetWidth={offsetWidth}
colSpan={flattenColumns.length - expandedRowOffset}
isEmpty={false}
>
{expandContent}
Expand Down
5 changes: 3 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;
offsetWidth?: number;
}

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

const { scrollbarSize, fixHeader, fixColumn, componentWidth, horizonScroll } = useContext(
Expand All @@ -39,12 +41,11 @@ function ExpandedRow(props: ExpandedRowProps) {

// Cache render node
let contentNode = children;

if (isEmpty ? horizonScroll && componentWidth : fixColumn) {
contentNode = (
<div
style={{
width: componentWidth - (fixHeader && !isEmpty ? scrollbarSize : 0),
width: componentWidth - offsetWidth - (fixHeader && !isEmpty ? scrollbarSize : 0),
position: 'sticky',
left: 0,
overflow: 'hidden',
Expand Down
3 changes: 3 additions & 0 deletions src/Body/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ function Body<RecordType>(props: BodyProps<RecordType>) {
expandedKeys,
childrenColumnName,
emptyNode,
expandedRowOffset,
} = useContext(TableContext, [
'prefixCls',
'getComponent',
Expand All @@ -40,6 +41,7 @@ function Body<RecordType>(props: BodyProps<RecordType>) {
'expandedKeys',
'childrenColumnName',
'emptyNode',
'expandedRowOffset',
]);

const flattenData: { record: RecordType; indent: number; index: number }[] =
Expand Down Expand Up @@ -74,6 +76,7 @@ function Body<RecordType>(props: BodyProps<RecordType>) {
cellComponent={tdComponent}
scopeCellComponent={thComponent}
indent={indent}
expandedRowOffset={expandedRowOffset}
/>
);
});
Expand Down
2 changes: 2 additions & 0 deletions src/Table.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -822,6 +822,7 @@ function Table<RecordType extends DefaultRecordType>(
expandableType,
expandRowByClick: expandableConfig.expandRowByClick,
expandedRowRender: expandableConfig.expandedRowRender,
expandedRowOffset: expandableConfig.expandedRowOffset,
onTriggerExpand,
expandIconColumnIndex: expandableConfig.expandIconColumnIndex,
indentSize: expandableConfig.indentSize,
Expand Down Expand Up @@ -872,6 +873,7 @@ function Table<RecordType extends DefaultRecordType>(
expandableType,
expandableConfig.expandRowByClick,
expandableConfig.expandedRowRender,
expandableConfig.expandedRowOffset,
onTriggerExpand,
expandableConfig.expandIconColumnIndex,
expandableConfig.indentSize,
Expand Down
3 changes: 2 additions & 1 deletion 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 All @@ -29,7 +30,6 @@ export interface TableContextProps<RecordType = any> {
direction: Direction;
fixedInfoList: readonly FixedInfo[];
isSticky: boolean;
supportSticky: boolean;
componentWidth: number;
fixHeader: boolean;
fixColumn: boolean;
Expand All @@ -50,6 +50,7 @@ export interface TableContextProps<RecordType = any> {
expandIcon: RenderExpandIcon<RecordType>;
onTriggerExpand: TriggerEventHandler<RecordType>;
expandIconColumnIndex: number;
expandedRowOffset: ExpandableConfig<RecordType>['expandedRowOffset'];
allColumnsFixedLeft: boolean;

// Column
Expand Down
1 change: 1 addition & 0 deletions src/interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,7 @@ export interface ExpandableConfig<RecordType> {
rowExpandable?: (record: RecordType) => boolean;
columnWidth?: number | string;
fixed?: FixedType;
expandedRowOffset?: number;
}

// =================== Render ===================
Expand Down