-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathObjectTable.tsx
More file actions
457 lines (400 loc) · 14 KB
/
Copy pathObjectTable.tsx
File metadata and controls
457 lines (400 loc) · 14 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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
/**
* ObjectUI
* Copyright (c) 2024-present ObjectStack Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* ObjectTable Component
*
* A specialized table component that automatically fetches and displays data from ObjectQL objects.
* It integrates with ObjectQL's schema system to generate columns and handle CRUD operations.
*/
import React, { useEffect, useState, useCallback } from 'react';
import type { ObjectTableSchema, TableColumn, TableSchema } from '@object-ui/types';
import type { ObjectQLDataSource } from '@object-ui/data-objectql';
import { SchemaRenderer } from '@object-ui/react';
export interface ObjectTableProps {
/**
* The schema configuration for the table
*/
schema: ObjectTableSchema;
/**
* ObjectQL data source
* Optional when inline data is provided in schema
*/
dataSource?: ObjectQLDataSource;
/**
* Additional CSS class
*/
className?: string;
/**
* Callback when a row is clicked
*/
onRowClick?: (record: any) => void;
/**
* Callback when a row is edited
*/
onEdit?: (record: any) => void;
/**
* Callback when a row is deleted
*/
onDelete?: (record: any) => void;
/**
* Callback when records are bulk deleted
*/
onBulkDelete?: (records: any[]) => void;
}
/**
* ObjectTable Component
*
* Renders a table for an ObjectQL object with automatic schema integration.
*
* @example
* ```tsx
* <ObjectTable
* schema={{
* type: 'object-table',
* objectName: 'users',
* fields: ['name', 'email', 'status'],
* operations: { create: true, update: true, delete: true }
* }}
* dataSource={objectQLDataSource}
* onEdit={(record) => console.log('Edit', record)}
* onDelete={(record) => console.log('Delete', record)}
* />
* ```
*/
export const ObjectTable: React.FC<ObjectTableProps> = ({
schema,
dataSource,
onRowClick,
onEdit,
onDelete,
onBulkDelete,
}) => {
const [data, setData] = useState<any[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<Error | null>(null);
const [objectSchema, setObjectSchema] = useState<any>(null);
const [columns, setColumns] = useState<TableColumn[]>([]);
const [selectedRows, setSelectedRows] = useState<any[]>([]);
// Check if using inline data
const hasInlineData = Boolean(schema.data);
// Initialize with inline data if provided
useEffect(() => {
if (hasInlineData && schema.data) {
setData(schema.data);
setLoading(false);
}
}, [hasInlineData, schema.data]);
// Fetch object schema from ObjectQL (skip if using inline data)
useEffect(() => {
const fetchObjectSchema = async () => {
try {
if (!dataSource) {
throw new Error('DataSource is required when using ObjectQL schema fetching (inline data not provided)');
}
const schemaData = await dataSource.getObjectSchema(schema.objectName);
setObjectSchema(schemaData);
} catch (err) {
console.error('Failed to fetch object schema:', err);
setError(err as Error);
}
};
// Skip fetching schema if we have inline data and custom columns
if (hasInlineData && schema.columns) {
// Use a minimal schema for inline data with type safety
setObjectSchema({
name: schema.objectName,
fields: {} as Record<string, any>,
});
} else if (schema.objectName && !hasInlineData && dataSource) {
fetchObjectSchema();
}
}, [schema.objectName, schema.columns, dataSource, hasInlineData]);
// Generate columns from object schema or inline data
useEffect(() => {
// For inline data with custom columns, use the custom columns directly
if (hasInlineData && schema.columns) {
setColumns(schema.columns);
return;
}
// For inline data without custom columns, auto-generate from first data row
if (hasInlineData && schema.data && schema.data.length > 0) {
const generatedColumns: TableColumn[] = [];
const firstRow = schema.data[0];
const fieldsToShow = schema.fields || Object.keys(firstRow);
fieldsToShow.forEach((fieldName) => {
generatedColumns.push({
header: fieldName.charAt(0).toUpperCase() + fieldName.slice(1).replace(/_/g, ' '),
accessorKey: fieldName,
});
});
setColumns(generatedColumns);
return;
}
if (!objectSchema) return;
const generatedColumns: TableColumn[] = [];
// Use specified fields or all visible fields from schema
const fieldsToShow = schema.fields || Object.keys(objectSchema.fields || {});
fieldsToShow.forEach((fieldName) => {
const field = objectSchema.fields?.[fieldName];
if (!field) return;
// Check field-level permissions
const hasReadPermission = !field.permissions || field.permissions.read !== false;
if (!hasReadPermission) return; // Skip fields without read permission
// Check if there's a custom column configuration
const customColumn = schema.columns?.find(col => col.accessorKey === fieldName);
if (customColumn) {
generatedColumns.push(customColumn);
} else {
// Auto-generate column from field schema
const column: TableColumn = {
header: field.label || fieldName,
accessorKey: fieldName,
};
// Add field type-specific formatting hints
if (field.type === 'date' || field.type === 'datetime') {
column.type = 'date';
} else if (field.type === 'boolean') {
column.type = 'boolean';
} else if (field.type === 'number' || field.type === 'currency' || field.type === 'percent') {
column.type = 'number';
} else if (field.type === 'image' || field.type === 'file') {
// For file/image fields, display the name or count
column.cell = (value: any) => {
if (!value) return '-';
if (Array.isArray(value)) {
const count = value.length;
const fileType = field.type === 'image' ? 'image' : 'file';
return count === 1 ? `1 ${fileType}` : `${count} ${fileType}s`;
}
return value.name || value.original_name || 'File';
};
} else if (field.type === 'lookup' || field.type === 'master_detail') {
// For relationship fields, display the name property if available
column.cell = (value: any) => {
if (!value) return '-';
if (typeof value === 'object' && value !== null) {
// Try common display properties first
if (value.name) return value.name;
if (value.label) return value.label;
if (value._id) return value._id;
// Fallback to object type indicator
return '[Object]';
}
return String(value);
};
} else if (field.type === 'url') {
// For URL fields, make them clickable
column.cell = (value: any) => {
if (!value) return '-';
return value; // The table renderer should handle URL formatting
};
}
// Add sorting if field is sortable
if (field.sortable !== false) {
column.sortable = true;
}
generatedColumns.push(column);
}
});
// Add actions column if operations are enabled
const operations = schema.operations || { read: true, update: true, delete: true };
if ((operations.update || operations.delete) && (onEdit || onDelete)) {
generatedColumns.push({
header: 'Actions',
accessorKey: '_actions',
cell: (_value: any, row: any) => {
return {
type: 'button-group',
buttons: [
...(operations.update && onEdit ? [{
label: 'Edit',
variant: 'ghost' as const,
size: 'sm' as const,
onClick: () => handleEdit(row),
}] : []),
...(operations.delete && onDelete ? [{
label: 'Delete',
variant: 'ghost' as const,
size: 'sm' as const,
onClick: () => handleDelete(row),
}] : []),
],
};
},
sortable: false,
});
}
setColumns(generatedColumns);
}, [objectSchema, schema.fields, schema.columns, schema.operations, schema.data, hasInlineData, onEdit, onDelete]);
// Fetch data from ObjectQL (skip if using inline data)
const fetchData = useCallback(async () => {
// Don't fetch if using inline data
if (hasInlineData) return;
if (!schema.objectName) return;
if (!dataSource) {
setError(new Error('DataSource is required for remote data fetching (inline data not provided)'));
setLoading(false);
return;
}
setLoading(true);
setError(null);
try {
const params: any = {
$select: schema.fields || undefined,
$top: schema.pageSize || 10,
};
// Add default filters if specified
if (schema.defaultFilters) {
params.$filter = schema.defaultFilters;
}
// Add default sort if specified
if (schema.defaultSort) {
params.$orderby = `${schema.defaultSort.field} ${schema.defaultSort.order}`;
}
const result = await dataSource.find(schema.objectName, params);
setData(result.data || []);
} catch (err) {
console.error('Failed to fetch data:', err);
setError(err as Error);
} finally {
setLoading(false);
}
}, [schema, dataSource, hasInlineData]);
useEffect(() => {
if (columns.length > 0) {
fetchData();
}
}, [columns, fetchData]);
// Handle refresh
const handleRefresh = useCallback(() => {
fetchData();
}, [fetchData]);
// Handle edit action
const handleEdit = useCallback((record: any) => {
if (onEdit) {
onEdit(record);
}
}, [onEdit]);
// Handle delete action with confirmation
const handleDelete = useCallback(async (record: any) => {
if (!onDelete) return;
// Show confirmation dialog
if (typeof window !== 'undefined') {
const confirmed = window.confirm(
`Are you sure you want to delete this ${schema.objectName}?`
);
if (!confirmed) return;
}
try {
// Optimistic update: remove from UI immediately
const recordId = record._id || record.id;
setData(prevData => prevData.filter(item =>
(item._id || item.id) !== recordId
));
// Call backend delete only if we have a dataSource
if (!hasInlineData && dataSource) {
await dataSource.delete(schema.objectName, recordId);
}
// Notify parent
onDelete(record);
} catch (err) {
console.error('Failed to delete record:', err);
// Revert optimistic update on error
if (!hasInlineData) {
await fetchData();
}
alert('Failed to delete record. Please try again.');
}
}, [schema.objectName, dataSource, hasInlineData, onDelete, fetchData]);
// Handle bulk delete action
const handleBulkDelete = useCallback(async (records: any[]) => {
if (!onBulkDelete || records.length === 0) return;
// Show confirmation dialog
if (typeof window !== 'undefined') {
const confirmed = window.confirm(
`Are you sure you want to delete ${records.length} ${schema.objectName}(s)?`
);
if (!confirmed) return;
}
try {
// Optimistic update: remove from UI immediately
const recordIds = records.map(r => r._id || r.id);
setData(prevData => prevData.filter(item =>
!recordIds.includes(item._id || item.id)
));
// Call backend bulk delete only if we have a dataSource
if (!hasInlineData && dataSource) {
await dataSource.bulk(schema.objectName, 'delete', records);
}
// Notify parent
onBulkDelete(records);
// Clear selection
setSelectedRows([]);
} catch (err) {
console.error('Failed to delete records:', err);
// Revert optimistic update on error
if (!hasInlineData) {
await fetchData();
}
alert('Failed to delete records. Please try again.');
}
}, [schema.objectName, dataSource, hasInlineData, onBulkDelete, fetchData]);
// Handle row selection
const handleRowSelect = useCallback((rows: any[]) => {
setSelectedRows(rows);
}, []);
// Render error state
if (error) {
return (
<div className="p-4 border border-red-300 bg-red-50 rounded-md">
<h3 className="text-red-800 font-semibold">Error loading table</h3>
<p className="text-red-600 text-sm mt-1">{error.message}</p>
</div>
);
}
// Render loading state
if (loading && data.length === 0) {
return (
<div className="p-8 text-center">
<div className="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900"></div>
<p className="mt-2 text-sm text-gray-600">Loading {schema.objectName}...</p>
</div>
);
}
// Convert to TableSchema
const tableSchema: TableSchema = {
type: 'table',
caption: schema.title,
columns,
data,
className: schema.className,
selectable: schema.selectable || (onBulkDelete ? 'multiple' : undefined),
onRowSelect: handleRowSelect,
onRowClick: onRowClick,
};
// Add toolbar with bulk actions if selection is enabled
const hasToolbar = selectedRows.length > 0 && onBulkDelete;
return (
<div className="w-full">
{hasToolbar && (
<div className="mb-4 p-3 bg-blue-50 border border-blue-200 rounded-md flex items-center justify-between">
<span className="text-sm text-blue-800">
{selectedRows.length} {schema.objectName}(s) selected
</span>
<button
onClick={() => handleBulkDelete(selectedRows)}
className="px-3 py-1 text-sm bg-red-600 text-white rounded hover:bg-red-700"
>
Delete Selected
</button>
</div>
)}
<SchemaRenderer schema={tableSchema} onAction={handleRefresh} />
</div>
);
};