forked from shesha-io/shesha-framework
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.ts
More file actions
437 lines (375 loc) · 13.4 KB
/
utils.ts
File metadata and controls
437 lines (375 loc) · 13.4 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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
import { nanoid } from '@/utils/uuid';
import { ColumnsItemProps, IConfigurableColumnsProps, IDataColumnsProps, isDataColumn } from '@/providers/datatableColumnsConfigurator/models';
import { IExpressionExecuterArguments, executeScriptSync } from '@/providers/form/utils';
import { IConfigurableFormComponent, IStyleType } from "@/index";
import { IModelMetadata, IPropertyMetadata, isPropertiesArray, isPropertiesLoader } from '@/interfaces/metadata';
import { camelcaseDotNotation, toCamelCase, humanizeString } from '@/utils/string';
const NEW_KEY = ['{{NEW_KEY}}', '{{GEN_KEY}}'];
const MAX_NUMBER_OF_DEFAULT_COLS = 20;
export const generateNewKey = (json: IConfigurableFormComponent[]): IConfigurableFormComponent[] => {
try {
let stringify = JSON.stringify(json);
NEW_KEY.forEach((key) => {
stringify = stringify.replaceAll(key, nanoid());
});
return JSON.parse(stringify);
} catch {
return json;
}
};
export const flattenConfiguredColumns = (items?: ColumnsItemProps[]): IConfigurableColumnsProps[] => {
const safeItems = Array.isArray(items) ? items : [];
const result: IConfigurableColumnsProps[] = [];
const walk = (item: ColumnsItemProps): void => {
if (!item) return;
const group = item as { childItems?: ColumnsItemProps[] };
if (Array.isArray(group.childItems) && group.childItems.length > 0) {
group.childItems.forEach(walk);
return;
}
result.push(item as IConfigurableColumnsProps);
};
safeItems.forEach(walk);
return result;
};
export const getDataColumnAccessor = (column: IConfigurableColumnsProps): string => {
const candidate = isDataColumn(column)
? column.propertyName
: column.accessor || column.id || '';
return camelcaseDotNotation(candidate);
};
export const collectMetadataPropertyPaths = (properties: IPropertyMetadata[]): string[] => {
const names = new Set<string>();
const normalize = (value?: string | null): string => {
return value ? camelcaseDotNotation(value) : '';
};
const walk = (property: IPropertyMetadata, prefix: string = ''): void => {
if (!property) return;
const segment = normalize(property.path);
if (!segment) return;
const fullPath = prefix && !segment.startsWith(`${prefix}.`)
? `${prefix}.${segment}`
: segment;
names.add(fullPath);
const columnName = normalize(property.columnName);
if (columnName) {
names.add(columnName);
if (prefix && !columnName.startsWith(`${prefix}.`)) {
names.add(`${prefix}.${columnName}`);
}
}
if (isPropertiesArray(property.properties)) {
property.properties.forEach((child) => walk(child, fullPath));
}
};
(properties ?? []).forEach((property) => walk(property));
return Array.from(names);
};
export const filterVisibility =
(context: IExpressionExecuterArguments) =>
({ customVisibility }: IConfigurableColumnsProps): boolean => {
if (customVisibility) {
return executeScriptSync(customVisibility, context);
}
return true;
};
export const defaultStyles = (): IStyleType => {
return {
background: { type: 'color', color: '#fff' },
font: { weight: '400', size: 14, color: '#000', type: 'Segoe UI', align: 'left' },
border: {
border: {
all: { width: '1px', style: 'solid', color: '#d9d9d9' },
top: { width: '1px', style: 'solid', color: '#d9d9d9' },
bottom: { width: '1px', style: 'solid', color: '#d9d9d9' },
left: { width: '1px', style: 'solid', color: '#d9d9d9' },
right: { width: '1px', style: 'solid', color: '#d9d9d9' },
},
radius: { all: 6, topLeft: 6, topRight: 6, bottomLeft: 6, bottomRight: 6 },
borderType: 'all',
radiusType: 'all',
},
dimensions: { width: '100%', height: 'auto', minHeight: 'auto', maxHeight: 'auto', minWidth: '0px', maxWidth: 'none' },
shadow: {
offsetX: 0,
offsetY: 2,
blurRadius: 8,
spreadRadius: 0,
color: 'rgba(0, 0, 0, 0.1)',
},
};
};
export const getTableDefaults = (): {
rowHeight: string;
rowPadding: string;
rowBorder: string;
headerFontSize: string;
headerFontWeight: string;
rowAlternateBackgroundColor: string;
striped: boolean;
hoverHighlight: boolean;
headerBackgroundColor: string;
headerFontFamily: string;
actionIconSize: string;
} => {
return {
rowHeight: 'auto',
rowPadding: '8px 12px',
rowBorder: 'none',
headerFontSize: '14px',
headerFontWeight: '500',
headerBackgroundColor: '#fafafa',
headerFontFamily: 'Segoe UI',
rowAlternateBackgroundColor: '#f5f5f5',
striped: true,
hoverHighlight: true,
actionIconSize: '14px',
};
};
export const getTableSettingsDefaults = (): {
tableSettings: {
rowHeight: string;
rowPadding: string;
rowBorder: string;
headerFontSize: string;
headerFontWeight: string;
rowAlternateBackgroundColor: string;
striped: boolean;
hoverHighlight: boolean;
headerBackgroundColor: string;
};
} => {
const flatDefaults = getTableDefaults();
return {
tableSettings: flatDefaults,
};
};
// Auditing columns to exclude from default column generation
export const AUDITING_COLUMNS = Object.freeze([
'id',
// 'isDeleted',
// 'deleterUserId',
// 'deletionTime',
// 'lastModificationTime',
// 'lastModifierUserId',
// 'creationTime',
// 'creatorUserId',
'markup',
]);
// Supported data types for table columns
export const SUPPORTED_COLUMN_DATA_TYPES = [
'string',
'number',
'boolean',
'date',
'date-time',
];
/**
* Filters metadata properties to exclude auditing and framework-related properties
* @param properties - Array of property metadata
* @returns Filtered array of properties suitable for table columns
*/
export const filterPropertiesForTable = (properties: IPropertyMetadata[]): IPropertyMetadata[] => {
return properties.filter((prop: IPropertyMetadata) => {
const columnName = prop.path || prop.columnName || '';
const isAuditing = AUDITING_COLUMNS.includes(columnName.toLowerCase());
const isFramework = prop.isFrameworkRelated === true;
const isId = columnName.toLowerCase() === 'id';
return !isAuditing && !isFramework && !isId;
});
};
/**
* Filters properties by supported data types for table columns
* @param properties - Array of property metadata
* @returns Properties with supported data types for table display
*/
export const filterPropertiesBySupportedTypes = (properties: IPropertyMetadata[]): IPropertyMetadata[] => {
return properties.filter((property: IPropertyMetadata) => {
return property.dataType && SUPPORTED_COLUMN_DATA_TYPES.includes(property.dataType);
});
};
/**
* Converts property metadata to DataTable column configuration
* @param property - Property metadata
* @param index - Column index for sorting
* @returns DataTable column configuration
*/
export const propertyToDataColumn = (property: IPropertyMetadata, index: number): IDataColumnsProps => {
// Guard against undefined or empty property.path
const rawPath = property.path ?? '';
const fallbackId = `col_${index}`;
return {
id: rawPath || fallbackId,
caption: property.label ?? (rawPath ? humanizeString(rawPath) : `Column ${index + 1}`),
description: property.description,
columnType: 'data' as const,
sortOrder: index,
itemType: 'item' as const,
isVisible: property.isVisible !== false, // Default to visible unless explicitly false
propertyName: rawPath !== '' ? toCamelCase(rawPath) : fallbackId,
allowSorting: true,
accessor: rawPath !== '' ? toCamelCase(rawPath) : fallbackId,
};
};
/**
* Calculates default columns for a DataTable
*
* Processing order:
* 1. Filter out 'id' and framework-related properties (auditing columns like isDeleted, creationTime, etc. are included)
* 2. Filter by supported data types (string, number, boolean, date, date-time)
* 3. Apply maxNumber limit (20) to the resulting valid columns
*
* @param metadata - Model metadata containing properties
* @returns Promise resolving to array of DataTable column configurations (max 20 valid columns)
*/
export const calculateDefaultColumns = async (metadata: IModelMetadata): Promise<IDataColumnsProps[]> => {
if (!metadata || !metadata.properties) {
console.warn('❌ No metadata available for column registration');
return [];
}
let properties: IPropertyMetadata[] = [];
if (isPropertiesArray(metadata.properties)) {
properties = metadata.properties;
} else if (isPropertiesLoader(metadata.properties)) {
try {
properties = await metadata.properties();
if (!properties) {
console.warn('⚠️ PropertiesLoader returned null/undefined, using empty array');
properties = [];
}
} catch (error) {
console.warn('❌ Failed to load properties from PropertiesLoader:', error);
return [];
}
} else {
// metadata.properties is null or undefined
return [];
}
// Filter out framework-related properties (include auditing columns)
const filteredProperties = filterPropertiesForTable(properties);
// Get properties suitable for table columns (filter by supported types)
const supportedProperties = filterPropertiesBySupportedTypes(filteredProperties);
// Apply maxNumber limit to the list of supported properties
const tableColumns = MAX_NUMBER_OF_DEFAULT_COLS > 0 && supportedProperties.length > MAX_NUMBER_OF_DEFAULT_COLS
? supportedProperties.slice(0, MAX_NUMBER_OF_DEFAULT_COLS)
: supportedProperties;
const columnItems: IDataColumnsProps[] = tableColumns.map(propertyToDataColumn);
return columnItems;
};
const addPxUnit = (value?: string | number): string => {
if (!value && value !== 0) return '0px';
const strValue = String(value);
if (/^-?\d+\.?\d*$/.test(strValue)) {
return `${strValue}px`;
}
return strValue;
};
export const convertRowDimensionsToHeight = (rowDimensions?: {
height?: string;
minHeight?: string;
maxHeight?: string;
}): string | undefined => {
if (!rowDimensions?.height) return undefined;
return addPxUnit(rowDimensions.height);
};
export type RowStylingBoxType = {
padding?: {
top?: string | number;
right?: string | number;
bottom?: string | number;
left?: string | number;
};
paddingTop?: string | number;
paddingRight?: string | number;
paddingBottom?: string | number;
paddingLeft?: string | number;
};
export const convertRowPaddingFieldsToPadding = (
top?: string,
right?: string,
bottom?: string,
left?: string,
): string | undefined => {
// If none of the fields are provided, return undefined
if (!top && !right && !bottom && !left) return undefined;
const topPx = addPxUnit(top);
const rightPx = addPxUnit(right);
const bottomPx = addPxUnit(bottom);
const leftPx = addPxUnit(left);
if (topPx === rightPx && rightPx === bottomPx && bottomPx === leftPx) {
return topPx;
}
if (topPx === bottomPx && leftPx === rightPx) {
return `${topPx} ${leftPx}`;
}
return `${topPx} ${rightPx} ${bottomPx} ${leftPx}`;
};
/** @deprecated Use convertRowPaddingFieldsToPadding instead */
export const convertRowStylingBoxToPadding = (rowStylingBox?: string | RowStylingBoxType): string | undefined => {
if (!rowStylingBox) return undefined;
let stylingBox: RowStylingBoxType;
if (typeof rowStylingBox === 'string') {
try {
stylingBox = JSON.parse(rowStylingBox);
} catch (e) {
console.warn('Failed to parse rowStylingBox JSON:', e);
return undefined;
}
} else {
stylingBox = rowStylingBox;
}
let top: string | number | undefined;
let right: string | number | undefined;
let bottom: string | number | undefined;
let left: string | number | undefined;
if (stylingBox?.padding) {
top = stylingBox.padding.top;
right = stylingBox.padding.right;
bottom = stylingBox.padding.bottom;
left = stylingBox.padding.left;
} else if (stylingBox?.paddingTop || stylingBox?.paddingRight ||
stylingBox?.paddingBottom || stylingBox?.paddingLeft) {
top = stylingBox.paddingTop;
right = stylingBox.paddingRight;
bottom = stylingBox.paddingBottom;
left = stylingBox.paddingLeft;
} else {
return undefined;
}
const topPx = addPxUnit(top);
const rightPx = addPxUnit(right);
const bottomPx = addPxUnit(bottom);
const leftPx = addPxUnit(left);
if (topPx === rightPx && rightPx === bottomPx && bottomPx === leftPx) {
return topPx;
}
if (topPx === bottomPx && leftPx === rightPx) {
return `${topPx} ${leftPx}`;
}
return `${topPx} ${rightPx} ${bottomPx} ${leftPx}`;
};
export const convertRowBorderStyleToBorder = (rowBorderStyle?: {
borderType?: string;
border?: {
all?: { width?: string | number; style?: string; color?: string };
top?: { width?: string | number; style?: string; color?: string };
right?: { width?: string | number; style?: string; color?: string };
bottom?: { width?: string | number; style?: string; color?: string };
left?: { width?: string | number; style?: string; color?: string };
};
}): string | undefined => {
if (!rowBorderStyle?.border) return undefined;
const { borderType, border } = rowBorderStyle;
if (borderType === 'all' && border.all) {
const { width, style, color } = border.all;
if (!width || !style || !color) return undefined;
return `${addPxUnit(width)} ${style} ${color}`;
}
const firstBorder = border.top || border.right || border.bottom || border.left;
if (firstBorder) {
const { width, style, color } = firstBorder;
if (!width || !style || !color) return undefined;
return `${addPxUnit(width)} ${style} ${color}`;
}
return undefined;
};