index.tsx
14.1 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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
import type { CSSProperties, ReactNode } from 'react';
import type { ColumnsType, TableProps } from 'antd/es/table';
import { UButton, UTable, UTooltip, FillTable } from '@uj/ui';
import { PermButton } from '@/access';
import type { ActionSchema } from '../formSchema';
/** 列表分页统一默认每页条数。 */
export const DEFAULT_PAGE_SIZE = 10;
/** 表格列扩展:line 为 1 时单行省略并显示完整提示;大于 1 时按指定行数截断。 */
export type DataTableColumn<T> = ColumnsType<T>[number] & { line?: number };
export type DataTableColumnsType<T> = DataTableColumn<T>[];
/** 通用行选择配置,兼容原生受控选中值、回调和逐行禁用。 */
export interface DataTableRowSelection<T> extends NonNullable<TableProps<T>['rowSelection']> {
/** 暂停整组选择交互,保留已有勾选,适用于请求或批量操作期间。 */
disabled?: boolean;
}
/** 列表行操作配置;配置 permission 时自动使用权限按钮。 */
export interface RowActionSchema<T> extends Omit<ActionSchema, 'danger' | 'label' | 'onClick'> {
/** 可按当前行动态生成操作文案。 */
label: ReactNode | ((record: T) => ReactNode);
/** 可按当前行动态决定是否使用警示颜色。 */
danger?: boolean | ((record: T) => boolean);
onClick: (record: T) => void;
visible?: (record: T) => boolean;
}
export interface DataTableProps<T> extends Pick<
TableProps<T>,
'dataSource' | 'loading' | 'rowKey' | 'onChange' | 'scroll' | 'size' | 'locale' | 'className'
> {
columns: DataTableColumnsType<T>;
/** true 开启默认多选,false/省略关闭;对象可配置受控选择与禁用规则。 */
rowSelection?: boolean | DataTableRowSelection<T>;
showIndex?: boolean;
pagination?:
| {
current: number;
/** 每页条数,默认 10。 */
pageSize?: number;
total: number;
onChange: (page: number, pageSize: number) => void;
/** 是否展示每页条数选择,默认展示。 */
showSizeChanger?: boolean;
/** 每页条数选择项,默认 10 / 20 / 50 / 100。 */
pageSizeOptions?: (string | number)[];
/** 默认展示总数;false 隐藏,也可传入自定义文案。 */
showTotal?: boolean | ((total: number, range: [number, number]) => ReactNode);
}
| false;
actions?: ActionSchema[];
/** 行内操作。配置 permission 时自动按权限显示,未配置则使用普通按钮。 */
rowActions?: RowActionSchema<T>[];
/** 行内操作列标题,默认“操作”。 */
actionColumnTitle?: ReactNode;
/** 行内操作列宽度。可不传:未传时按按钮文案自动估算;传了但偏小时也会自动取较大值,避免按钮被列宽砍掉。 */
actionColumnWidth?: number;
actionColumnFixed?: 'left' | 'right';
toolbarClassName?: string;
toolbarTitle?: ReactNode;
fillHeight?: boolean;
/** 接口返回的分页对象;传入后自动从 recordsKey 读取列表数据。 */
pageData?: Record<string, unknown>;
/** 分页对象中的列表字段名,默认 records。 */
recordsKey?: string;
/** 分页对象中的总数、页码和每页条数字段名。 */
totalKey?: string;
currentKey?: string;
sizeKey?: string;
}
export function DataTable<T extends object>({
columns,
showIndex,
pagination,
actions,
rowActions,
rowSelection,
actionColumnTitle = '操作',
actionColumnWidth,
actionColumnFixed = 'right',
toolbarClassName,
toolbarTitle,
fillHeight = false,
pageData,
recordsKey = 'records',
totalKey = 'total',
currentKey = 'current',
sizeKey = 'size',
...props
}: DataTableProps<T>) {
const records = pageData?.[recordsKey];
const dataSource = Array.isArray(records) ? (records as T[]) : props.dataSource;
const { disabled, getCheckboxProps, getTitleCheckboxProps, ...selectionOptions } =
typeof rowSelection === 'object' ? rowSelection : {};
const resolvedSelection: TableProps<T>['rowSelection'] = rowSelection
? {
type: 'checkbox',
fixed: 'left',
columnWidth: 48,
preserveSelectedRowKeys: false,
...selectionOptions,
selections: disabled ? false : selectionOptions.selections,
getCheckboxProps: (record) => {
const checkboxProps = getCheckboxProps?.(record);
return { ...checkboxProps, disabled: disabled || checkboxProps?.disabled };
},
getTitleCheckboxProps: () => {
const checkboxProps = getTitleCheckboxProps?.();
return { ...checkboxProps, disabled: disabled || checkboxProps?.disabled };
},
}
: undefined;
const resolvedPagination = pagination
? {
...pagination,
current: Number(pageData?.[currentKey] ?? pagination.current),
pageSize: Number(pageData?.[sizeKey] ?? pagination.pageSize ?? DEFAULT_PAGE_SIZE),
total: Number(pageData?.[totalKey] ?? pagination.total),
}
: pagination;
const page = resolvedPagination || undefined;
const renderActionButton = (
action: Omit<ActionSchema, 'onClick'>,
onClick: () => void,
key: string,
isRowAction = false,
style?: CSSProperties,
) => {
const type = action.type ?? (isRowAction ? ('text' as const) : undefined);
const buttonProps = {
danger: action.danger,
disabled: action.disabled,
onClick,
type,
// 行内操作按 small 出:默认高度会把每一行撑到 60px 以上,
// 两个四字操作并排就会换行,整行再翻一倍(见 .uj-row-actions 的 nowrap 说明)。
size: isRowAction ? ('small' as const) : undefined,
// 行内配色统一交给 @uj/ui 的 .uj-row-actions / .uj-row-action 规则。
// 旧版在这里给每个 text 按钮塞内联 color(主色或 error),内联样式会压过
// 组件层 CSS,导致「一行只留一个常驻彩色」这类规范根本无法收口。
style,
};
return action.permission ? (
<PermButton key={key} permission={action.permission} {...buttonProps}>
{action.label}
</PermButton>
) : (
<UButton key={key} {...buttonProps}>
{action.label}
</UButton>
);
};
// 操作列宽由「内容」决定,页面传值降级为下限建议。
// 旧公式 Math.max(页面值, 估算值) 会无条件尊重页面拍出来的宽列:角色页传 280,
// 三个按钮实际只需约 154px,多出的 94px 全变成「表头在左、按钮在右」之间的空白;
// 11 个列表页传了 80~280 共 8 种宽度,留白随页面随机变化,这是列表组件的通病。
// 现在把宽度钳制在 [估算值, 估算值+16px]:下限保证 fixed 布局下 nowrap 的按钮组
// 不被裁掉,上限给动态文案(函数型 label 按 4 字估)留约一个汉字的余量。
const estimatedActionWidth = estimateActionWidth(rowActions);
const resolvedActionWidth = Math.min(
Math.max(actionColumnWidth ?? 0, estimatedActionWidth),
estimatedActionWidth + 16,
);
const actionColumn: ColumnsType<T>[number] | undefined = rowActions?.length
? {
title: actionColumnTitle,
key: '__actions',
width: resolvedActionWidth,
fixed: actionColumnFixed,
// 表头与单元格共用左锚点:内容由 .uj-row-actions 的 flex-start 落在 +16px,
// 表头也落在 +16px,不再出现「表头贴左、按钮贴右」的两个起点。
align: 'left',
// 固定右列的 1px 左边界由这个类名承担(见 ui.css),不依赖 antd 内部类名。
className: 'uj-table-cell-actions',
render: (_: unknown, record: T) => {
const visibleActions = rowActions.filter((action) => action.visible?.(record) ?? true);
// 操作间距由 .uj-row-actions 的 gap 统一给:原来按「后面还有没有权限按钮」
// 手算 marginRight,多一个无权限的动作就会漏出半格间距。
return (
<div className="uj-row-actions">
{visibleActions.map((action, index) => {
const label =
typeof action.label === 'function' ? action.label(record) : action.label;
const danger =
typeof action.danger === 'function' ? action.danger(record) : action.danger;
return renderActionButton(
{ ...action, danger, label },
() => action.onClick(record),
`row-action-${index}`,
true,
);
})}
</div>
);
},
}
: undefined;
const sourceColumns: DataTableColumnsType<T> = showIndex
? [
{
title: '序号',
key: '__index',
width: 72,
render: (_: unknown, _row: T, index: number) =>
((page?.current ?? 1) - 1) * (page?.pageSize ?? 0) + index + 1,
},
...columns,
...(actionColumn ? [actionColumn] : []),
]
: [...columns, ...(actionColumn ? [actionColumn] : [])];
const hasLineLimit = hasLineConfigured(sourceColumns);
const minTableWidth = getMinimumTableWidth(sourceColumns);
const tableColumns = withLineLimit(sourceColumns);
const TableComponent = fillHeight ? FillTable<T> : UTable<T>;
return (
<>
{toolbarTitle || actions?.length ? (
<div className={['uj-table-toolbar', toolbarClassName].filter(Boolean).join(' ')}>
<div className="uj-table-toolbar__title">{toolbarTitle}</div>
{actions?.length ? (
<div className="uj-table-toolbar__actions">
{actions.map((action, index) =>
renderActionButton(action, action.onClick, `toolbar-action-${index}`),
)}
</div>
) : null}
</div>
) : null}
<TableComponent
{...props}
// 默认 medium:antd 的默认档是 large(上下各 16px padding),
// 列表页因此比设计令牌(Table.cellPaddingBlockMD 12)整整高出一档。
size={props.size ?? 'middle'}
dataSource={dataSource}
columns={tableColumns}
tableLayout={hasLineLimit ? 'fixed' : undefined}
rowSelection={resolvedSelection}
scroll={{ ...props.scroll, x: props.scroll?.x ?? minTableWidth }}
pagination={
resolvedPagination === false
? false
: resolvedPagination && {
...resolvedPagination,
current: resolvedPagination.current,
pageSize: resolvedPagination.pageSize,
total: resolvedPagination.total,
onChange: resolvedPagination.onChange,
showSizeChanger: resolvedPagination.showSizeChanger ?? true,
pageSizeOptions: resolvedPagination.pageSizeOptions ?? [10, 20, 50, 100],
showTotal:
typeof resolvedPagination.showTotal === 'function'
? resolvedPagination.showTotal
: resolvedPagination.showTotal === false
? undefined
: (total: number) => `共 ${total} 条`,
}
}
/>
</>
);
}
function hasLineConfigured<T extends object>(columns: ColumnsType<T>): boolean {
return columns.some((column) => {
const customColumn = column as DataTableColumn<T>;
return (
Boolean(customColumn.line) ||
('children' in column &&
Boolean(column.children?.length) &&
hasLineConfigured(column.children))
);
});
}
function getMinimumTableWidth<T extends object>(columns: ColumnsType<T>): number {
return columns.reduce((width, column) => {
if ('children' in column && column.children) {
return width + getMinimumTableWidth(column.children);
}
return width + (typeof column.width === 'number' ? column.width : 120);
}, 0);
}
/**
* 估出操作列该给多宽:逐按钮量字面宽度(中文 ~14px / 其它 ~8px)+ 小号文字按钮左右内边距(各 7px)
* + 按钮间距(--uj-space-1=4px)+ 单元格左右内边距(各 16px)。
* 动态文案(函数型 label)按 4 个汉字保守估,宁可宽一点也不要把按钮挤掉。
*/
function estimateActionWidth<T extends object>(actions?: RowActionSchema<T>[]): number {
if (!actions?.length) return 0;
const buttonWidth = (action: RowActionSchema<T>): number => {
const raw = typeof action.label === 'function' ? '四个字' : action.label;
const text = typeof raw === 'string' ? raw : '四个字';
let textWidth = 0;
for (const char of text) textWidth += /[一-龥]/.test(char) ? 14 : 8;
return textWidth + 14; // 小号文字按钮左右内边距 7px × 2
};
const buttons = actions.reduce((sum, action) => sum + buttonWidth(action), 0);
const gaps = (actions.length - 1) * 4;
return Math.ceil(buttons + gaps + 32); // 32 = 单元格左右内边距 16px × 2
}
function withLineLimit<T extends object>(columns: DataTableColumnsType<T>): ColumnsType<T> {
return columns.map((column) => {
if ('children' in column && column.children) {
return { ...column, children: withLineLimit(column.children as DataTableColumnsType<T>) };
}
if (!column.line || column.line < 1) return column;
const { line, render, ...rest } = column;
return {
...rest,
render: (value: unknown, record: T, index: number) => {
const content = toCellContent(render?.(value, record, index), value);
const title =
typeof value === 'string' || typeof value === 'number' ? String(value) : content;
return (
<UTooltip title={title}>
<span style={lineStyle(line)}>{content}</span>
</UTooltip>
);
},
};
});
}
function toCellContent(rendered: unknown, fallback: unknown): ReactNode {
if (rendered && typeof rendered === 'object' && 'children' in rendered && 'props' in rendered) {
return (rendered as { children: ReactNode }).children;
}
return (rendered ?? fallback) as ReactNode;
}
function lineStyle(line: number): CSSProperties {
if (line === 1)
return { display: 'block', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' };
return {
display: '-webkit-box',
overflow: 'hidden',
WebkitBoxOrient: 'vertical',
WebkitLineClamp: line,
whiteSpace: 'pre-wrap',
overflowWrap: 'anywhere',
};
}