-
Notifications
You must be signed in to change notification settings - Fork 383
Expand file tree
/
Copy pathuseRowSelect.tsx
More file actions
269 lines (245 loc) · 10 KB
/
useRowSelect.tsx
File metadata and controls
269 lines (245 loc) · 10 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
// 行选中相关功能:单选 + 多选
import {
CreateElement, computed, toRefs, h, ref, watch,
} from 'vue';
import { get, intersection, isFunction } from 'lodash-es';
import useDefaultValue from '../../hooks/useDefaultValue';
import {
ActiveRowActionContext,
PrimaryTableCellParams,
PrimaryTableCol,
RowClassNameParams,
TableRowData,
TdPrimaryTableProps,
} from '../type';
import { isRowSelectedDisabled } from '../../_common/js/table/utils';
import { TableClassName } from './useClassName';
import Checkbox from '../../checkbox';
import Radio from '../../radio';
import { ClassName } from '../../common';
import log from '../../_common/js/log';
export default function useRowSelect(
props: TdPrimaryTableProps,
tableSelectedClasses: TableClassName['tableSelectedClasses'],
) {
const {
selectedRowKeys, columns, data, rowKey, reserveSelectedRowOnPaginate,
} = toRefs(props);
const currentPaginateData = ref<TableRowData[]>(data.value);
const selectedRowClassNames = ref();
// 远程分页场景下,data 变化时需要同步更新 currentPaginateData
watch(data, (newData) => {
currentPaginateData.value = newData;
});
const [tSelectedRowKeys, setTSelectedRowKeys] = useDefaultValue(
selectedRowKeys,
props.defaultSelectedRowKeys || [],
props.onSelectChange,
'selectedRowKeys',
'select-change',
);
const selectedRowDataMap = ref(new Map<string | number, TableRowData>());
const selectColumn = computed(() => props.columns.find(({ type }) => ['multiple', 'single'].includes(type)));
const canSelectedRows = computed(() => {
const currentData = reserveSelectedRowOnPaginate.value ? data.value : currentPaginateData.value;
return currentData.filter((row, rowIndex): boolean => !isDisabled(row, rowIndex));
});
// 选中的行,和所有可以选择的行,交集,用于计算 isSelectedAll 和 isIndeterminate
const intersectionKeys = computed(() => intersection(
tSelectedRowKeys.value,
canSelectedRows.value.map((t) => get(t, props.rowKey || 'id')),
));
const allowUncheck = computed(() => {
const singleSelectCol = columns.value.find((col) => col.type === 'single');
if (!singleSelectCol || !singleSelectCol.checkProps || !('allowUncheck' in singleSelectCol.checkProps)) return false;
return singleSelectCol.checkProps.allowUncheck;
});
watch(
[data, columns, tSelectedRowKeys, selectColumn, rowKey],
() => {
const disabledRowFunc = (p: RowClassNameParams<TableRowData>): ClassName => selectColumn.value.disabled(p) ? tableSelectedClasses.disabled : '';
const disabledRowClass = selectColumn.value?.disabled ? disabledRowFunc : undefined;
const selected = new Set(tSelectedRowKeys.value);
const selectedRowClassFunc = ({ row }: RowClassNameParams<TableRowData>) => {
const rowId = get(row, props.rowKey || 'id');
return selected.has(rowId) ? tableSelectedClasses.selected : '';
};
const selectedRowClass = selected.size ? selectedRowClassFunc : undefined;
selectedRowClassNames.value = [disabledRowClass, selectedRowClass].filter((v) => v);
},
{ immediate: true },
);
function isDisabled(row: Record<string, any>, rowIndex: number): boolean {
return isRowSelectedDisabled(selectColumn.value, row, rowIndex);
}
// eslint-disable-next-line
function getSelectedHeader(h: CreateElement) {
// 判断条件直接写在jsx中,防止变量被computed捕获,选中行重新计算了columns
return () => (
<Checkbox
checked={canSelectedRows.value.length !== 0 && intersectionKeys.value.length === canSelectedRows.value.length}
indeterminate={
intersectionKeys.value.length > 0 && intersectionKeys.value.length < canSelectedRows.value.length
}
disabled={!canSelectedRows.value.length}
{...{ on: { change: handleSelectAll } }}
/>
);
}
function getRowSelectDisabledData(p: PrimaryTableCellParams<TableRowData>) {
const { col, row, rowIndex } = p;
const disabled: boolean = typeof col.disabled === 'function' ? col.disabled({ row, rowIndex }) : col.disabled;
const checkProps = isFunction(col.checkProps) ? col.checkProps({ row, rowIndex }) : col.checkProps;
return {
disabled: disabled || checkProps?.disabled,
checkProps,
};
}
// eslint-disable-next-line
function renderSelectCell(h: CreateElement, p: PrimaryTableCellParams<TableRowData>) {
const { col: column, row = {} } = p;
const checked = tSelectedRowKeys.value.includes(get(row, props.rowKey || 'id'));
const { disabled, checkProps } = getRowSelectDisabledData(p);
const selectBoxProps = {
props: {
checked,
disabled,
...checkProps,
},
on: {
click: ({ e }: { e: MouseEvent }) => {
// 选中行功能中,点击 checkbox/radio 需阻止事件冒泡,避免触发不必要的 onRowClick
e?.stopPropagation();
},
// radio 单选框可再点击一次关闭选择,input / change 事件无法监听
change: () => handleSelectChange(row),
},
};
if (column.type === 'single') return <Radio {...selectBoxProps} />;
if (column.type === 'multiple') {
const isIndeterminate = props.indeterminateSelectedRowKeys?.length
? props.indeterminateSelectedRowKeys.includes(get(row, props.rowKey))
: false;
return <Checkbox indeterminate={isIndeterminate} {...selectBoxProps} />;
}
return null;
}
function handleSelectChange(row: TableRowData = {}) {
let selectedRowKeys = [...tSelectedRowKeys.value];
const reRowKey = props.rowKey || 'id';
const id = get(row, reRowKey);
const selectedRowIndex = selectedRowKeys.indexOf(id);
const isExisted = selectedRowIndex !== -1;
if (selectColumn.value.type === 'multiple') {
isExisted ? selectedRowKeys.splice(selectedRowIndex, 1) : selectedRowKeys.push(id);
} else if (selectColumn.value.type === 'single') {
selectedRowKeys = isExisted && allowUncheck.value ? [] : [id];
} else {
log.warn('Table', '`column.type` must be one of `multiple` and `single`');
return;
}
setTSelectedRowKeys(selectedRowKeys, {
selectedRowData: selectedRowKeys.map((t) => selectedRowDataMap.value.get(t)).filter((rowData) => !!rowData),
currentRowKey: id,
currentRowData: row,
type: isExisted ? 'uncheck' : 'check',
});
}
function handleSelectAll(checked: boolean) {
const reRowKey = props.rowKey || 'id';
const canSelectedRowKeys = canSelectedRows.value.map((record) => get(record, reRowKey));
const disabledSelectedRowKeys = selectedRowKeys.value?.filter((id) => !canSelectedRowKeys.includes(id)) || [];
const allIds = checked ? [...disabledSelectedRowKeys, ...canSelectedRowKeys] : [...disabledSelectedRowKeys];
setTSelectedRowKeys(allIds, {
selectedRowData: checked ? allIds.map((t) => selectedRowDataMap.value.get(t)) : [],
type: checked ? 'check' : 'uncheck',
currentRowKey: 'CHECK_ALL_BOX',
});
}
function formatToRowSelectColumn(col: PrimaryTableCol) {
const isSelection = ['multiple', 'single'].includes(col.type);
if (!isSelection) return col;
return {
...col,
width: col.width || 64,
className: [tableSelectedClasses.checkCell, col.className],
cell: (h: CreateElement, p: PrimaryTableCellParams<TableRowData>) => renderSelectCell(h, p),
title: col.type === 'multiple' ? getSelectedHeader(h) : col.title,
};
}
const onInnerSelectRowClick: TdPrimaryTableProps['onRowClick'] = ({ row, index }) => {
const selectedColIndex = props.columns.findIndex((item) => item.colKey === 'row-select');
if (selectedColIndex === -1) return;
const { disabled } = getRowSelectDisabledData({
row,
rowIndex: index,
col: props.columns[selectedColIndex],
colIndex: selectedColIndex,
});
if (disabled) return;
handleSelectChange(row);
};
watch(
[data, rowKey],
() => {
for (let i = 0, len = data.value.length; i < len; i++) {
selectedRowDataMap.value.set(get(data.value[i], rowKey.value || 'id'), data.value[i]);
}
},
{ immediate: true },
);
// 是否开启了行选中功能
const showRowSelect = computed(() => !!selectColumn.value);
const clearAllSelectedRowKeys = () => {
setTSelectedRowKeys([], {
selectedRowData: [],
currentRowKey: undefined,
currentRowData: undefined,
type: 'uncheck',
});
};
const handleRowSelectWithAreaSelection = ({ activeRowList, action }: ActiveRowActionContext<TableRowData>) => {
if (!showRowSelect.value) return;
if (action === 'clear') {
clearAllSelectedRowKeys();
return;
}
if (selectColumn.value?.type === 'single') {
if (action === 'space-one-selection') {
handleSelectChange(activeRowList[0].row);
}
return;
}
const validAreaSelection = activeRowList.filter(
({ row, rowIndex }) => !getRowSelectDisabledData({
row,
rowIndex,
col: selectColumn.value,
colIndex: undefined,
}).disabled,
);
if (!validAreaSelection.length) return;
const areaSelectionKeys = validAreaSelection.map(({ row }) => get(row, props.rowKey));
const intersectionKeys = intersection(tSelectedRowKeys.value, areaSelectionKeys);
const toCheck = intersectionKeys.length !== areaSelectionKeys.length;
const clearedKeys = tSelectedRowKeys.value.filter((key) => !areaSelectionKeys.includes(key));
const newSelectedRowKeys = toCheck ? [...new Set(tSelectedRowKeys.value.concat(areaSelectionKeys))] : clearedKeys;
const currentRowData = action === 'space-one-selection' ? activeRowList[0].row : undefined;
setTSelectedRowKeys(newSelectedRowKeys, {
selectedRowData: activeRowList,
currentRowKey: get(currentRowData, props.rowKey),
currentRowData,
type: toCheck ? 'check' : 'uncheck',
});
};
return {
selectColumn,
showRowSelect,
selectedRowClassNames,
currentPaginateData,
setTSelectedRowKeys,
formatToRowSelectColumn,
onInnerSelectRowClick,
handleRowSelectWithAreaSelection,
};
}