@hzab/list-render 1.10.21-alpha.0 → 1.10.21-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,257 @@
1
+ export const getNavigatorLanguage = (): string => navigator.language || "en-US";
2
+
3
+ function getLocaleSeparators(locale: string) {
4
+ const testNumber = 123456.789;
5
+ const localeFormattedNumber = Intl.NumberFormat(locale).format(testNumber);
6
+
7
+ // Get the thousands separator of the locale
8
+ const thousandsSeparator = localeFormattedNumber.split("123")[1][0];
9
+
10
+ // Get the decimal separator of the locale
11
+ const decimalSeparator = localeFormattedNumber.split("123")[1][4];
12
+ return { thousandsSeparator, decimalSeparator };
13
+ }
14
+ export function parseLocaleNumber(stringNumber: string, locale = getNavigatorLanguage()): number {
15
+ if (!stringNumber.trim()) return NaN;
16
+ const { thousandsSeparator, decimalSeparator } = getLocaleSeparators(locale);
17
+ const normalizedStringNumber = stringNumber.replace(/\u00A0/g, " "); // Replace non-breaking space with normal space
18
+ const numberString = normalizedStringNumber
19
+ .replace(new RegExp(`[${thousandsSeparator}\\s]`, "g"), "") // Replace thousands separator and white-space
20
+ .replace(new RegExp(`\\${decimalSeparator}`, "g"), "."); // Replace decimal separator
21
+
22
+ const trimmedNumberString = numberString.replace(/^(?!-)\D+|\D+$/g, ""); // Remove characters before first and after last number, but keep negative sign
23
+ if (trimmedNumberString === null || trimmedNumberString.trim().length === 0) {
24
+ return NaN;
25
+ }
26
+ return Number(trimmedNumberString);
27
+ }
28
+
29
+
30
+ function isReactElement(value) {
31
+ return value !== null && typeof value === "object";
32
+ }
33
+ const getTitle = (item) => {
34
+ return typeof item?.title == "function"
35
+ ? isReactElement(item?.title())
36
+ ? item?.title()?.props.children
37
+ : String(item?.title()) || ""
38
+ : String(item?.title) || ""
39
+ }
40
+
41
+ export function convertColumnsToRows(columns, headerRowHeight = 40) {
42
+ // 获取所有叶子节点
43
+ const getLeaves = (cols) => {
44
+ return cols.reduce((acc, col) => {
45
+ if (col.children?.length) {
46
+ return [...acc, ...getLeaves(col.children)];
47
+ }
48
+ return [...acc, col];
49
+ }, []);
50
+ };
51
+
52
+ // 计算最大深度
53
+ const getDepth = (cols, depth = 1) => {
54
+ return cols.reduce((max, col) => {
55
+ if (col.children?.length) {
56
+ return Math.max(max, getDepth(col.children, depth + 1));
57
+ }
58
+ return Math.max(max, depth);
59
+ }, depth);
60
+ };
61
+
62
+ const leafColumns = getLeaves(columns);
63
+ const totalDepth = getDepth(columns);
64
+ const totalCols = leafColumns.length;
65
+
66
+ // 构建表头树
67
+ const buildTree = (cols, depth = 0) => {
68
+ return cols.map((col) => {
69
+ const hasChildren = col.children?.length > 0;
70
+ if (!hasChildren) {
71
+ return {
72
+ ...col,
73
+ rowspan: totalDepth - depth,
74
+ colspan: 1,
75
+ _depth: depth,
76
+ _isLeaf: true,
77
+ };
78
+ }
79
+ const leafCount = getLeaves(col.children).length;
80
+ return {
81
+ ...col,
82
+ rowspan: 1,
83
+ colspan: leafCount,
84
+ _depth: depth,
85
+ _isLeaf: false,
86
+ children: buildTree(col.children, depth + 1),
87
+ };
88
+ });
89
+ };
90
+
91
+ const tree = buildTree(columns, 0);
92
+
93
+ // 初始化行
94
+ const rows: any = Array.from({ length: totalDepth }, (_, i) => ({
95
+ rowId: `header-${i}`,
96
+ height: headerRowHeight,
97
+ cells: [],
98
+ }));
99
+
100
+
101
+ // 递归填充行
102
+ const fillRow = (nodes, rowIndex = 0) => {
103
+ nodes.forEach((node) => {
104
+ if (node._isLeaf) {
105
+ const cell = {
106
+ ...node,
107
+ type: node?.type == "rowSelection" ? "rowSelection" : "header",
108
+ text: getTitle(node),
109
+ dataIndex: node.dataIndex,
110
+ width: node.width,
111
+ rowspan: node.rowspan,
112
+ style: node?.type == "rowSelection" ? node?.style : {},
113
+ };
114
+ if (node.sorter) cell.sorter = node.sorter;
115
+ if (node.key) cell.key = node.key;
116
+ rows[rowIndex].cells.push(cell);
117
+ } else {
118
+ // 父节点:添加colspan
119
+ rows[rowIndex].cells.push({
120
+ ...node,
121
+ type: node?.type == "rowSelection" ? "rowSelection" : "header",
122
+ text: getTitle(node),
123
+ colspan: node.colspan,
124
+ });
125
+ if (node.children) {
126
+ fillRow(node.children, rowIndex + 1);
127
+ }
128
+ }
129
+ });
130
+ };
131
+
132
+ fillRow(tree, 0);
133
+
134
+ // 补全每一行的cell,使长度一致
135
+ rows.forEach((row, rowIndex) => {
136
+ const newCells = [];
137
+ let colIndex = 0;
138
+ let cellIndex = 0;
139
+
140
+ while (colIndex < totalCols) {
141
+ const currentCell = row.cells[cellIndex];
142
+
143
+ if (!currentCell) {
144
+ // 如果当前行没有足够的cell,从叶子节点补充
145
+ const leaf = leafColumns[colIndex];
146
+ newCells.push({
147
+ ...leaf,
148
+ type: leaf?.type == "rowSelection" ? "rowSelection" : "header",
149
+ text: getTitle(leaf),
150
+ dataIndex: leaf.dataIndex,
151
+ width: leaf.width,
152
+ rowspan: rowIndex === totalDepth - 1 ? 1 : undefined,
153
+ });
154
+ colIndex++;
155
+ cellIndex++;
156
+ continue;
157
+ }
158
+
159
+ const colspan = currentCell.colspan || 1;
160
+ const rowspan = currentCell.rowspan || 1;
161
+
162
+ // 检查当前cell是否应该出现在这一行
163
+ // 如果rowspan > 1,表示它跨多行,但只在第一行出现
164
+ if (rowspan > 1 && rowIndex > 0) {
165
+ // 这个cell不应该出现在当前行,跳过
166
+ colIndex += colspan;
167
+ cellIndex++;
168
+ continue;
169
+ }
170
+
171
+ // 如果当前cell有colspan,需要补全后面的空cell
172
+ newCells.push(currentCell);
173
+ colIndex += colspan;
174
+ cellIndex++;
175
+
176
+ // 如果colspan > 1,后面补充空cell
177
+ for (let i = 1; i < colspan; i++) {
178
+ newCells.push({
179
+ type: "header",
180
+ text: "",
181
+ });
182
+ }
183
+ }
184
+
185
+ row.cells = newCells;
186
+ });
187
+
188
+ // 最后一行的特殊处理:确保所有叶子节点都有对应的cell
189
+ const lastRow = rows[totalDepth - 1];
190
+ const lastRowCells = [];
191
+ let leafIndex = 0;
192
+
193
+ // 遍历所有叶子节点
194
+ leafColumns.forEach((leaf, index) => {
195
+ // 检查是否已经在lastRow中有对应的cell
196
+ const existingCell = lastRow.cells.find((cell) => cell.dataIndex === leaf.dataIndex && cell.text === leaf.title);
197
+
198
+ if (existingCell) {
199
+ lastRowCells.push(existingCell);
200
+ } else {
201
+ // 创建新的cell
202
+ lastRowCells.push({
203
+ ...leaf,
204
+ type: leaf?.type == "rowSelection" ? "rowSelection" : "header",
205
+ text: getTitle(leaf),
206
+ dataIndex: leaf.dataIndex,
207
+ width: leaf.width,
208
+ rowspan: 1,
209
+ });
210
+ }
211
+ });
212
+
213
+ lastRow.cells = lastRowCells;
214
+
215
+ // 确保所有行的cell数量等于totalCols
216
+ rows.forEach((row) => {
217
+ // 如果cell数量少于totalCols,补充空cell
218
+ while (row.cells.length < totalCols) {
219
+ row.cells.push({
220
+ type: "header",
221
+ text: "",
222
+ });
223
+ }
224
+ });
225
+
226
+ return rows;
227
+ }
228
+
229
+
230
+ export function flattenColumns(columns: any[]) {
231
+ const result: any[] = [];
232
+
233
+ function traverse(cols) {
234
+ cols.forEach((col) => {
235
+ if (col.children && col.children.length > 0) {
236
+ traverse(col.children);
237
+ } else {
238
+ // 创建新对象,只保留需要的属性
239
+ const { title, dataIndex, key, width, sorter, k, ...rest } = col;
240
+ result.push({
241
+ type: "Input",
242
+ dataIndex,
243
+ title,
244
+ ...(key && { key }),
245
+ ...(width && { width }),
246
+ ...(sorter && { sorter }),
247
+ ...(k && { k }),
248
+ // 如果需要保留其他属性
249
+ ...rest,
250
+ });
251
+ }
252
+ });
253
+ }
254
+
255
+ traverse(columns);
256
+ return result;
257
+ }
@@ -0,0 +1,259 @@
1
+ import { useEffect, useMemo, useState } from "react";
2
+
3
+ import {
4
+ Cell,
5
+ CellTemplate,
6
+ Compatible,
7
+ getCellProperty,
8
+ getCharFromKey,
9
+ isAlphaNumericKey,
10
+ keyCodes,
11
+ Uncertain,
12
+ UncertainCompatible,
13
+ } from "@silevis/reactgrid";
14
+ import { getVal } from "../../../common/utils";
15
+
16
+ export type OptionType = {
17
+ label: string;
18
+ value: string | number;
19
+ isDisabled?: boolean;
20
+ };
21
+
22
+ export interface BaseCell extends Cell {
23
+ selectedValue?: string;
24
+ value: string | number;
25
+ values: OptionType[];
26
+ isDisabled?: boolean;
27
+ isOpen?: boolean;
28
+ inputValue?: string;
29
+ }
30
+ interface DIProps {
31
+ onCellChanged: (...args: any[]) => void;
32
+ cell: Record<string, any>;
33
+ isInEditMode?: boolean;
34
+ }
35
+
36
+ export const WidthWrap = (opt: any, edit = false) => {
37
+ const { WrapComponent, ReadWrapComponent } = opt;
38
+
39
+ class createBaseCellTemplate implements CellTemplate<BaseCell> {
40
+ getCompatibleCell(uncertainCell: Uncertain<BaseCell>): Compatible<BaseCell> {
41
+ let selectedValue: string | undefined;
42
+ try {
43
+ selectedValue = getCellProperty(uncertainCell, "selectedValue", "number");
44
+ } catch {
45
+ selectedValue = undefined;
46
+ }
47
+ if (!selectedValue) {
48
+ try {
49
+ selectedValue = getCellProperty(uncertainCell, "selectedValue", "string");
50
+ } catch {
51
+ selectedValue = undefined;
52
+ }
53
+ }
54
+
55
+ let values: any;
56
+ try {
57
+ values = getCellProperty(uncertainCell, "values", "object");
58
+ } catch {
59
+ values = [];
60
+ }
61
+
62
+ const value = selectedValue ? parseFloat(selectedValue) : NaN;
63
+
64
+ let isDisabled = true;
65
+ try {
66
+ isDisabled = getCellProperty(uncertainCell, "isDisabled", "boolean");
67
+ } catch {
68
+ isDisabled = false;
69
+ }
70
+
71
+ let inputValue: string | undefined;
72
+ try {
73
+ inputValue = getCellProperty(uncertainCell, "inputValue", "string");
74
+ } catch {
75
+ inputValue = undefined;
76
+ }
77
+
78
+ const text = selectedValue || "";
79
+
80
+ return { ...uncertainCell, selectedValue, text, value, values, isDisabled, inputValue };
81
+ }
82
+
83
+ update(cell: Compatible<BaseCell>, cellToMerge: UncertainCompatible<BaseCell>): Compatible<BaseCell> {
84
+ const selectedValueFromText = cell.values.some((val: any) => val.value === cellToMerge.text)
85
+ ? cellToMerge.text
86
+ : undefined;
87
+ return this.getCompatibleCell({
88
+ ...cell,
89
+ selectedValue: selectedValueFromText,
90
+ isOpen: cellToMerge?.isOpen,
91
+ inputValue: cellToMerge.inputValue,
92
+ });
93
+ }
94
+
95
+ getClassName(cell: Compatible<BaseCell>, isInEditMode: boolean): string {
96
+ const isOpen = cell.isOpen ? "open" : "closed";
97
+ return `${cell.className ? cell.className : ""}${isOpen}`;
98
+ }
99
+
100
+ // handleKeyDown(
101
+ // cell: Compatible<BaseCell>,
102
+ // keyCode: number,
103
+ // ctrl: boolean,
104
+ // shift: boolean,
105
+ // alt: boolean,
106
+ // key: string,
107
+ // capsLock: boolean,
108
+ // ): { cell: Compatible<BaseCell>; enableEditMode: boolean } {
109
+ // if ((keyCode === keyCodes.SPACE || keyCode === keyCodes.ENTER) && !shift) {
110
+ // return {
111
+ // cell: this.getCompatibleCell({
112
+ // ...cell,
113
+ // isOpen: !cell.isOpen,
114
+ // }),
115
+ // enableEditMode: false,
116
+ // };
117
+ // }
118
+
119
+ // const char = getCharFromKey(key, shift, capsLock);
120
+
121
+ // if (!ctrl && !alt && isAlphaNumericKey(keyCode) && !(shift && keyCode === keyCodes.SPACE))
122
+ // return {
123
+ // cell: this.getCompatibleCell({
124
+ // ...cell,
125
+ // inputValue: char,
126
+ // isOpen: !cell.isOpen,
127
+ // }),
128
+ // enableEditMode: false,
129
+ // };
130
+
131
+ // return { cell, enableEditMode: false };
132
+ // }
133
+
134
+ handleCompositionEnd(
135
+ cell: Compatible<BaseCell>,
136
+ eventData: any,
137
+ ): { cell: Compatible<BaseCell>; enableEditMode: boolean } {
138
+ return {
139
+ cell: {
140
+ ...cell,
141
+ inputValue: eventData,
142
+ isOpen: !cell.isOpen,
143
+ },
144
+ enableEditMode: false,
145
+ };
146
+ }
147
+
148
+ render(
149
+ cell: Compatible<BaseCell>,
150
+ isInEditMode: boolean,
151
+ onCellChanged: (cell: Compatible<BaseCell>, commit: boolean) => void,
152
+ ): React.ReactNode {
153
+ if (edit) {
154
+ return (
155
+ <div onPointerDown={(e) => e.stopPropagation()}>
156
+ <WrapComponent record={cell?.record} rowId={cell?.rowId} item={cell}></WrapComponent>
157
+ </div>
158
+ );
159
+ }
160
+ return (
161
+ <BaseTemplate
162
+ onCellChanged={(cell) => onCellChanged(this.getCompatibleCell(cell), true)}
163
+ cell={cell}
164
+ isInEditMode={isInEditMode}
165
+ />
166
+ );
167
+ }
168
+ }
169
+
170
+ const BaseTemplate: React.FC<DIProps> = ({ onCellChanged, cell, isInEditMode }) => {
171
+ const [isOpen, setIsOpen] = useState<boolean>(false);
172
+ const datatypeId = cell?.columnId + cell?.rowId;
173
+ useEffect(() => {
174
+ // 处理下拉选项弹层失焦逻辑
175
+ function onClick() {
176
+ if (window.gridEditId != datatypeId) {
177
+ setIsOpen(false);
178
+ }
179
+ }
180
+ document.addEventListener("click", onClick);
181
+ return () => {
182
+ document.removeEventListener("click", onClick);
183
+ };
184
+ }, []);
185
+
186
+ const _value = useMemo(() => {
187
+ let str = "selectedValue";
188
+ if (cell?.type.includes("DatePicker")) {
189
+ str = "inputValue";
190
+ }
191
+ return str;
192
+ }, [cell]);
193
+
194
+ const echoValue = useMemo(() => {
195
+ if(!cell?.getField){
196
+ return
197
+ }
198
+ return getVal(
199
+ { ...(cell?.getField && cell?.getField()), enum: cell?.getField()?.enum || cell?.values },
200
+ { [cell?.getField && cell?.getField().name]: cell[_value] },
201
+ );
202
+ }, [cell, _value]);
203
+
204
+ return (
205
+ <div
206
+ style={{ width: "100%", height: "100%", display: "flex", alignItems: "center" }}
207
+ onDoubleClick={(e) => {
208
+ console.log(cell,"c222ellcellcellcellcell");
209
+ if (cell?.nonEditable) {
210
+ return;
211
+ }
212
+ setIsOpen(true);
213
+ }}
214
+ >
215
+ {isOpen ? (
216
+ <div onPointerDown={(e) => e.stopPropagation()} style={{ width: "100%" }}>
217
+ <WrapComponent
218
+ key={cell?.id}
219
+ ref={(input) => {
220
+ if (input) {
221
+ input?.focus();
222
+ }
223
+ }}
224
+ open={isOpen}
225
+ style={{ width: "100%", display: "flex", alignItems: "center" }}
226
+ value={cell[_value]}
227
+ options={cell.values}
228
+ onChange={(e) => {
229
+ setIsOpen(false);
230
+ if (cell?.type.includes("DatePicker")) {
231
+ onCellChanged({ ...cell, inputValue: e?.target?.value || e });
232
+ return;
233
+ }
234
+ onCellChanged({ ...cell, selectedValue: e?.target?.value || e });
235
+ }}
236
+ {...((cell?.getField && cell?.getField()["x-component-props"]) || {})}
237
+ ></WrapComponent>
238
+ </div>
239
+ ) : (
240
+ <div>
241
+ {ReadWrapComponent ? (
242
+ <ReadWrapComponent
243
+ key={cell?.id}
244
+ value={echoValue}
245
+ record={cell?.record}
246
+ rowId={cell?.rowId}
247
+ item={cell}
248
+ />
249
+ ) : (
250
+ <div style={{ height: "100%", display: "flex", alignItems: "center" }}>{echoValue}</div>
251
+ )}
252
+ </div>
253
+ )}
254
+ </div>
255
+ );
256
+ };
257
+
258
+ return new createBaseCellTemplate();
259
+ };
@@ -0,0 +1,10 @@
1
+ .grid-container {
2
+ overflow: auto;
3
+ position: relative;
4
+
5
+
6
+
7
+ .ant-select {
8
+ width: 100% !important;
9
+ }
10
+ }