-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathObjectGrid.tsx
More file actions
1401 lines (1271 loc) · 56 KB
/
ObjectGrid.tsx
File metadata and controls
1401 lines (1271 loc) · 56 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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* 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.
*/
/**
* ObjectGrid Component
*
* A specialized grid component built on top of data-table.
* Auto-generates columns from ObjectQL schema with type-aware rendering.
* Implements the grid view type from @objectstack/spec view.zod ListView schema.
*
* Features:
* - Traditional table/grid with CRUD operations
* - Search, filters, pagination
* - Column resizing, sorting
* - Row selection
* - Inline editing support
*/
import React, { useEffect, useState, useCallback, useMemo } from 'react';
import type { ObjectGridSchema, DataSource, ListColumn, ViewData } from '@object-ui/types';
import { SchemaRenderer, useDataScope, useNavigationOverlay, useAction } from '@object-ui/react';
import { getCellRenderer, formatCurrency, formatCompactCurrency, formatDate, formatPercent, humanizeLabel } from '@object-ui/fields';
import {
Badge, Button, NavigationOverlay,
Popover, PopoverContent, PopoverTrigger,
} from '@object-ui/components';
import { usePullToRefresh } from '@object-ui/mobile';
import { evaluatePlainCondition, buildExpandFields } from '@object-ui/core';
import { ChevronRight, ChevronDown, Download, Rows2, Rows3, Rows4, AlignJustify, Type, Hash, Calendar, CheckSquare, User, Tag, Clock } from 'lucide-react';
import { useRowColor } from './useRowColor';
import { useGroupedData } from './useGroupedData';
import { GroupRow } from './GroupRow';
import { useColumnSummary } from './useColumnSummary';
import { RowActionMenu, formatActionLabel } from './components/RowActionMenu';
import { BulkActionBar } from './components/BulkActionBar';
export interface ObjectGridProps {
schema: ObjectGridSchema;
dataSource?: DataSource;
className?: string;
onRowClick?: (record: any) => void;
onEdit?: (record: any) => void;
onDelete?: (record: any) => void;
onBulkDelete?: (records: any[]) => void;
onCellChange?: (rowIndex: number, columnKey: string, newValue: any, row: any) => void;
onRowSave?: (rowIndex: number, changes: Record<string, any>, row: any) => void | Promise<void>;
onBatchSave?: (changes: Array<{ rowIndex: number; changes: Record<string, any>; row: any }>) => void | Promise<void>;
onRowSelect?: (selectedRows: any[]) => void;
onAddRecord?: () => void;
}
/**
* Helper to get data configuration from schema
* Handles both new ViewData format and legacy inline data
*/
function getDataConfig(schema: ObjectGridSchema): ViewData | null {
// New format: explicit data configuration
if (schema.data) {
// Check if data is an array (shorthand format) or already a ViewData object
if (Array.isArray(schema.data)) {
// Convert array shorthand to proper ViewData format
return {
provider: 'value',
items: schema.data,
};
}
// Already in ViewData format
return schema.data;
}
// Legacy format: staticData field
if (schema.staticData) {
return {
provider: 'value',
items: schema.staticData,
};
}
// Default: use object provider with objectName
if (schema.objectName) {
return {
provider: 'object',
object: schema.objectName,
};
}
return null;
}
/**
* Helper to normalize columns configuration
* Handles both string[] and ListColumn[] formats
*/
function normalizeColumns(
columns: string[] | ListColumn[] | undefined
): ListColumn[] | string[] | undefined {
if (!columns || columns.length === 0) return undefined;
// Already in ListColumn format - check for object type with optional chaining
if (typeof columns[0] === 'object' && columns[0] !== null) {
return columns as ListColumn[];
}
// String array format
return columns as string[];
}
export const ObjectGrid: React.FC<ObjectGridProps> = ({
schema,
dataSource,
onEdit,
onDelete,
onRowSelect,
onRowClick,
onCellChange,
onRowSave,
onBatchSave,
onAddRecord,
...rest
}) => {
const [data, setData] = useState<any[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<Error | null>(null);
const [objectSchema, setObjectSchema] = useState<any>(null);
const [useCardView, setUseCardView] = useState(false);
const [refreshKey, setRefreshKey] = useState(0);
const [showExport, setShowExport] = useState(false);
const [rowHeightMode, setRowHeightMode] = useState<'compact' | 'short' | 'medium' | 'tall' | 'extra_tall'>(schema.rowHeight ?? 'medium');
const [selectedRows, setSelectedRows] = useState<any[]>([]);
// Column state persistence (order and widths)
const columnStorageKey = React.useMemo(() => {
return schema.id
? `grid-columns-${schema.objectName}-${schema.id}`
: `grid-columns-${schema.objectName}`;
}, [schema.objectName, schema.id]);
const [columnState, setColumnState] = useState<{
order?: string[];
widths?: Record<string, number>;
}>(() => {
try {
const saved = localStorage.getItem(columnStorageKey);
return saved ? JSON.parse(saved) : {};
} catch {
return {};
}
});
const saveColumnState = useCallback((state: typeof columnState) => {
setColumnState(state);
try {
localStorage.setItem(columnStorageKey, JSON.stringify(state));
} catch (e) {
console.warn('Failed to persist column state:', e);
}
}, [columnStorageKey]);
const handlePullRefresh = useCallback(async () => {
setRefreshKey(k => k + 1);
}, []);
const { ref: pullRef, isRefreshing, pullDistance } = usePullToRefresh<HTMLDivElement>({
onRefresh: handlePullRefresh,
enabled: !!dataSource && !!schema.objectName,
});
useEffect(() => {
const checkWidth = () => setUseCardView(window.innerWidth < 480);
checkWidth();
window.addEventListener('resize', checkWidth);
return () => window.removeEventListener('resize', checkWidth);
}, []);
// Check if data is passed directly (from ListView)
const passedData = (rest as any).data;
// Resolve bound data if 'bind' property exists
const boundData = useDataScope(schema.bind);
// Get data configuration (supports both new and legacy formats)
const rawDataConfig = getDataConfig(schema);
// Memoize dataConfig using deep comparison to prevent infinite loops
const dataConfig = React.useMemo(() => {
// If we have passed data (highest priority), treat it as value provider
if (passedData && Array.isArray(passedData)) {
return {
provider: 'value',
items: passedData
};
}
// If we have bound data, it takes precedence as inline value
if (boundData && Array.isArray(boundData)) {
return {
provider: 'value',
items: boundData
};
}
return rawDataConfig;
}, [JSON.stringify(rawDataConfig), boundData, passedData]);
const hasInlineData = dataConfig?.provider === 'value';
// Extract stable primitive/reference-stable values from schema for dependency arrays.
// This prevents infinite re-render loops when schema is a new object on each render
// (e.g. when rendered through SchemaRenderer which creates a fresh evaluatedSchema).
const objectName = dataConfig?.provider === 'object' && dataConfig && 'object' in dataConfig
? (dataConfig as any).object
: schema.objectName;
const schemaFields = schema.fields;
const schemaColumns = schema.columns;
const schemaFilter = schema.filter;
const schemaSort = schema.sort;
const schemaPagination = schema.pagination;
const schemaPageSize = schema.pageSize;
// --- Inline data effect (synchronous, no fetch needed) ---
useEffect(() => {
if (hasInlineData && dataConfig?.provider === 'value') {
// Only update if data is different to avoid infinite loop
setData(prev => {
const newItems = dataConfig.items as any[];
if (JSON.stringify(prev) !== JSON.stringify(newItems)) {
return newItems;
}
return prev;
});
setLoading(false);
}
}, [hasInlineData, dataConfig]);
// --- Unified async data loading effect ---
// Combines schema fetch + data fetch into a single async flow with AbortController.
// This avoids the fragile "chained effects" pattern where Effect 1 sets objectSchema,
// triggering Effect 2 to call fetchData — a pattern prone to infinite loops when
// fetchData's reference is unstable.
useEffect(() => {
if (hasInlineData) return;
let cancelled = false;
const loadSchemaAndData = async () => {
setLoading(true);
setError(null);
try {
// --- Step 1: Resolve object schema ---
let resolvedSchema: any = null;
const cols = normalizeColumns(schemaColumns) || schemaFields;
if (cols && objectName) {
// We have explicit columns — use a minimal schema stub
resolvedSchema = { name: objectName, fields: {} };
} else if (objectName && dataSource) {
// Fetch full schema from DataSource
const schemaData = await dataSource.getObjectSchema(objectName);
if (cancelled) return;
resolvedSchema = schemaData;
} else if (!objectName) {
throw new Error('Object name required for data fetching');
} else {
throw new Error('DataSource required');
}
if (!cancelled) {
setObjectSchema(resolvedSchema);
}
// --- Step 2: Fetch data ---
if (dataSource && objectName) {
const getSelectFields = () => {
if (schemaFields) return schemaFields;
if (schemaColumns && Array.isArray(schemaColumns)) {
return schemaColumns.map((c: any) => typeof c === 'string' ? c : c.field);
}
return undefined;
};
const params: any = {
$select: getSelectFields(),
$top: (schemaPagination as any)?.pageSize || schemaPageSize || 50,
};
// Support new filter format
if (schemaFilter && Array.isArray(schemaFilter)) {
params.$filter = schemaFilter;
} else if (schema.defaultFilters) {
// Legacy support
params.$filter = schema.defaultFilters;
}
// Support new sort format
if (schemaSort) {
if (typeof schemaSort === 'string') {
params.$orderby = schemaSort;
} else if (Array.isArray(schemaSort)) {
params.$orderby = schemaSort
.map((s: any) => `${s.field} ${s.order}`)
.join(', ');
}
} else if (schema.defaultSort) {
// Legacy support
params.$orderby = `${(schema.defaultSort as any).field} ${(schema.defaultSort as any).order}`;
}
// Auto-inject $expand for lookup/master_detail fields
const expand = buildExpandFields(resolvedSchema?.fields, schemaColumns ?? schemaFields);
if (expand.length > 0) {
params.$expand = expand;
}
const result = await dataSource.find(objectName, params);
if (cancelled) return;
setData(result.data || []);
}
} catch (err) {
if (!cancelled) {
setError(err as Error);
}
} finally {
if (!cancelled) {
setLoading(false);
}
}
};
loadSchemaAndData();
return () => {
cancelled = true;
};
}, [objectName, schemaFields, schemaColumns, schemaFilter, schemaSort, schemaPagination, schemaPageSize, dataSource, hasInlineData, dataConfig, refreshKey]);
// --- NavigationConfig support ---
// Must be called before any early returns to satisfy React hooks rules
const navigation = useNavigationOverlay({
navigation: schema.navigation,
objectName: schema.objectName,
onNavigate: schema.onNavigate,
onRowClick,
});
// --- Action support for action columns ---
const { execute: executeAction } = useAction();
// --- Row color support ---
const getRowClassName = useRowColor(schema.rowColor);
// --- Conditional formatting support ---
const getRowStyle = useCallback((row: Record<string, unknown>): React.CSSProperties | undefined => {
const rules = schema.conditionalFormatting;
if (!rules || rules.length === 0) return undefined;
for (const rule of rules) {
let match = false;
const expression =
('condition' in rule ? (rule as any).condition : undefined)
|| ('expression' in rule ? (rule as any).expression : undefined)
|| undefined;
if (expression) {
match = evaluatePlainCondition(expression, row as Record<string, any>);
} else if ('field' in rule && 'operator' in rule && (rule as any).field && (rule as any).operator) {
const r = rule as any;
const fieldValue = row[r.field];
switch (r.operator) {
case 'equals': match = fieldValue === r.value; break;
case 'not_equals': match = fieldValue !== r.value; break;
case 'contains': match = typeof fieldValue === 'string' && typeof r.value === 'string' && fieldValue.includes(r.value); break;
case 'greater_than': match = typeof fieldValue === 'number' && typeof r.value === 'number' && fieldValue > r.value; break;
case 'less_than': match = typeof fieldValue === 'number' && typeof r.value === 'number' && fieldValue < r.value; break;
case 'in': match = Array.isArray(r.value) && r.value.includes(fieldValue); break;
}
}
if (match) {
const style: React.CSSProperties = {};
if ('style' in rule && (rule as any).style) Object.assign(style, (rule as any).style);
if ('backgroundColor' in rule && (rule as any).backgroundColor) style.backgroundColor = (rule as any).backgroundColor;
if ('textColor' in rule && (rule as any).textColor) style.color = (rule as any).textColor;
if ('borderColor' in rule && (rule as any).borderColor) style.borderColor = (rule as any).borderColor;
return style;
}
}
return undefined;
}, [schema.conditionalFormatting]);
// --- Grouping support ---
const { groups, isGrouped, toggleGroup } = useGroupedData(schema.grouping, data);
// --- Column summary support ---
const summaryColumns = React.useMemo(() => {
const cols = normalizeColumns(schema.columns);
if (cols && cols.length > 0 && typeof cols[0] === 'object') {
return cols as ListColumn[];
}
return undefined;
}, [schema.columns]);
const { summaries, hasSummary } = useColumnSummary(summaryColumns, data);
const generateColumns = useCallback(() => {
// Map field type to column header icon (Airtable-style)
const getTypeIcon = (fieldType: string | null): React.ReactNode => {
if (!fieldType) return <Type className="h-3.5 w-3.5" />;
const iconMap: Record<string, React.ReactNode> = {
text: <Type className="h-3.5 w-3.5" />,
number: <Hash className="h-3.5 w-3.5" />,
currency: <Hash className="h-3.5 w-3.5" />,
percent: <Hash className="h-3.5 w-3.5" />,
date: <Calendar className="h-3.5 w-3.5" />,
datetime: <Clock className="h-3.5 w-3.5" />,
boolean: <CheckSquare className="h-3.5 w-3.5" />,
user: <User className="h-3.5 w-3.5" />,
select: <Tag className="h-3.5 w-3.5" />,
};
return iconMap[fieldType] || <Type className="h-3.5 w-3.5" />;
};
// Auto-infer column type from field name and data values (Airtable-style)
const inferColumnType = (col: ListColumn): string | null => {
if (col.type) return col.type; // Explicit type takes priority
const fieldLower = col.field.toLowerCase();
// Infer boolean fields
const booleanFields = ['completed', 'is_completed', 'done', 'active', 'enabled', 'archived'];
if (booleanFields.some(f => fieldLower === f || fieldLower === `is_${f}`)) {
return 'boolean';
}
// Infer datetime fields (fields with time component: created_time, modified_time, *_at patterns)
const datetimePatterns = ['created_time', 'modified_time', 'updated_time', 'created_at', 'updated_at', 'modified_at', 'last_login', 'logged_at'];
if (datetimePatterns.some(p => fieldLower === p || fieldLower.endsWith(`_${p}`))) {
return 'datetime';
}
// Infer date fields from name patterns
const datePatterns = ['date', 'due', 'created', 'updated', 'deadline', 'start', 'end', 'expires'];
if (datePatterns.some(p => fieldLower.includes(p))) {
// Verify with data: check if sample values look like dates
if (data.length > 0) {
const sample = data.find(row => row[col.field] != null)?.[col.field];
if (typeof sample === 'string' && !isNaN(Date.parse(sample))) {
return 'date';
}
}
return 'date';
}
// Infer percent fields from name patterns
const percentFields = ['probability', 'percent', 'percentage', 'completion', 'progress', 'rate'];
if (percentFields.some(f => fieldLower.includes(f))) {
if (data.length > 0) {
const sample = data.find(row => row[col.field] != null)?.[col.field];
if (typeof sample === 'number') {
return 'percent';
}
}
}
// Infer select/badge fields (status, priority, category, etc.)
const selectFields = ['status', 'priority', 'category', 'stage', 'type', 'severity', 'level'];
if (selectFields.some(f => fieldLower.includes(f))) {
if (data.length > 0) {
const uniqueValues = new Set(data.map(row => row[col.field]).filter(Boolean));
if (uniqueValues.size > 0 && uniqueValues.size <= 10) {
return 'select';
}
}
}
// Infer user/assignee fields
const userFields = ['assignee', 'owner', 'author', 'reporter', 'creator', 'user'];
if (userFields.some(f => fieldLower.includes(f))) {
return 'user';
}
// Infer currency/amount fields
const currencyFields = ['amount', 'price', 'total', 'revenue', 'cost', 'budget', 'salary'];
if (currencyFields.some(f => fieldLower.includes(f))) {
if (data.length > 0) {
const sample = data.find(row => row[col.field] != null)?.[col.field];
if (typeof sample === 'number') {
return 'currency';
}
}
}
// Fallback: detect ISO date strings in data values (catch-all for unmatched field names)
if (data.length > 0) {
const sample = data.find(row => row[col.field] != null)?.[col.field];
if (typeof sample === 'string' && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/.test(sample)) {
return 'datetime';
}
}
return null;
};
// Use normalized columns (support both new and legacy)
const cols = normalizeColumns(schemaColumns);
if (cols) {
// Check if columns are already in data-table format (have 'accessorKey')
// vs ListColumn format (have 'field')
if (cols.length > 0 && typeof cols[0] === 'object' && cols[0] !== null) {
const firstCol = cols[0] as any;
// Already in data-table format - apply type inference for columns without custom cell renderers
if ('accessorKey' in firstCol) {
return (cols as any[]).map((col) => {
if (col.cell) return col; // already has custom renderer
const syntheticCol: ListColumn = { field: col.accessorKey, label: col.header, type: col.type };
const inferredType = inferColumnType(syntheticCol);
if (!inferredType) return col;
const CellRenderer = getCellRenderer(inferredType);
const fieldMeta: Record<string, any> = { name: col.accessorKey, type: inferredType };
if (inferredType === 'select') {
const uniqueValues = Array.from(new Set(data.map(row => row[col.accessorKey]).filter(Boolean)));
fieldMeta.options = uniqueValues.map((v: any) => ({ value: v, label: humanizeLabel(String(v)) }));
}
return {
...col,
headerIcon: getTypeIcon(inferredType),
cell: (value: any) => <CellRenderer value={value} field={fieldMeta as any} />,
};
});
}
// ListColumn format - convert to data-table format with full feature support
if ('field' in firstCol) {
return (cols as ListColumn[])
.filter((col) => col?.field && typeof col.field === 'string' && !col.hidden)
.map((col, colIndex) => {
const header = col.label || col.field.charAt(0).toUpperCase() + col.field.slice(1).replace(/_/g, ' ');
// Build custom cell renderer based on column configuration
let cellRenderer: ((value: any, row: any) => React.ReactNode) | undefined;
// Type-based cell renderer with auto-inference (e.g., "currency", "date", "boolean")
const inferredType = inferColumnType(col);
const CellRenderer = inferredType ? getCellRenderer(inferredType) : null;
// Build field metadata for cell renderers (includes options for select fields)
const fieldMeta: Record<string, any> = { name: col.field, type: inferredType || 'text' };
if (inferredType === 'select' && !(col as any).options) {
// Auto-generate options from unique data values for inferred select fields
const uniqueValues = Array.from(new Set(data.map(row => row[col.field]).filter(Boolean)));
fieldMeta.options = uniqueValues.map(v => ({ value: v, label: humanizeLabel(String(v)) }));
}
if ((col as any).options) {
fieldMeta.options = (col as any).options;
}
// Auto-link primary field (first column) to record detail (Airtable-style)
const isPrimaryField = colIndex === 0 && !col.link && !col.action;
const isLinked = col.link || isPrimaryField;
if ((col.link && col.action) || (isPrimaryField && col.action)) {
// Both link and action: link takes priority for navigation, action executes on secondary interaction
cellRenderer = (value: any, row: any) => {
const displayContent = CellRenderer
? <CellRenderer value={value} field={fieldMeta as any} />
: (value != null && value !== '' ? String(value) : <span className="text-muted-foreground/50 text-xs italic">—</span>);
return (
<button
type="button"
className="text-primary font-medium underline-offset-4 hover:underline cursor-pointer bg-transparent border-none p-0 text-left font-inherit"
data-testid={isPrimaryField ? 'primary-field-link' : 'link-cell'}
onClick={(e) => {
e.stopPropagation();
navigation.handleClick(row);
}}
>
{displayContent}
</button>
);
};
} else if (isLinked) {
// Link column: clicking navigates to the record detail
cellRenderer = (value: any, row: any) => {
const displayContent = CellRenderer
? <CellRenderer value={value} field={fieldMeta as any} />
: (value != null && value !== '' ? String(value) : <span className="text-muted-foreground/50 text-xs italic">—</span>);
return (
<button
type="button"
className="text-primary font-medium underline-offset-4 hover:underline cursor-pointer bg-transparent border-none p-0 text-left font-inherit"
data-testid={isPrimaryField ? 'primary-field-link' : 'link-cell'}
onClick={(e) => {
e.stopPropagation();
navigation.handleClick(row);
}}
>
{displayContent}
</button>
);
};
} else if (col.action) {
// Action column: render as action button
cellRenderer = (value: any, row: any) => {
return (
<Button
variant="outline"
size="sm"
className="h-7 text-xs"
data-testid="action-cell"
onClick={(e) => {
e.stopPropagation();
executeAction({
type: col.action!,
params: { record: row, field: col.field, value },
});
}}
>
{formatActionLabel(col.action!)}
</Button>
);
};
} else if (CellRenderer) {
// Type-only cell renderer (no link/action)
cellRenderer = (value: any) => (
<CellRenderer value={value} field={fieldMeta as any} />
);
} else {
// Default renderer with empty value handling
cellRenderer = (value: any) => (
value != null && value !== ''
? <span>{String(value)}</span>
: <span className="text-muted-foreground/50 text-xs italic">—</span>
);
}
// Wrap with prefix compound cell renderer (Airtable-style: [Badge] Text in same cell)
const prefixConfig = (col as any).prefix;
if (prefixConfig?.field) {
const baseCellRenderer = cellRenderer;
const PrefixRenderer = prefixConfig.type === 'badge' ? getCellRenderer('select') : null;
cellRenderer = (value: any, row: any) => {
const prefixValue = row[prefixConfig.field];
const prefixEl = prefixValue != null && prefixValue !== ''
? PrefixRenderer
? <PrefixRenderer value={prefixValue} field={{ name: prefixConfig.field, type: 'select' } as any} />
: <span className="text-muted-foreground text-xs mr-1.5">{String(prefixValue)}</span>
: null;
return (
<span className="flex items-center gap-1.5">
{prefixEl}
{baseCellRenderer(value, row)}
</span>
);
};
}
// Auto-infer alignment from field type if not explicitly set
const numericTypes = ['number', 'currency', 'percent'];
const effectiveType = inferredType || col.type;
const inferredAlign = col.align || (effectiveType && numericTypes.includes(effectiveType) ? 'right' as const : undefined);
// Determine if column should be hidden on mobile
const isEssential = colIndex === 0 || (col as any).essential === true;
return {
header,
accessorKey: col.field,
headerIcon: getTypeIcon(inferredType),
...(!isEssential && { className: 'hidden sm:table-cell' }),
...(col.width && { width: col.width }),
...(inferredAlign && { align: inferredAlign }),
sortable: col.sortable !== false,
...(col.resizable !== undefined && { resizable: col.resizable }),
...(col.wrap !== undefined && { wrap: col.wrap }),
...(cellRenderer && { cell: cellRenderer }),
...(col.pinned && { pinned: col.pinned }),
};
});
}
}
// String array format - filter out invalid entries
return (cols as string[])
.filter((fieldName) => typeof fieldName === 'string' && fieldName.trim().length > 0)
.map((fieldName) => {
const fieldLabel = objectSchema?.fields?.[fieldName]?.label;
return {
header: fieldLabel || fieldName.charAt(0).toUpperCase() + fieldName.slice(1).replace(/_/g, ' '),
accessorKey: fieldName,
};
});
}
// Legacy support: use 'fields' if columns not provided
if (hasInlineData) {
const inlineData = dataConfig?.provider === 'value' ? dataConfig.items as any[] : [];
if (inlineData.length > 0) {
const fieldsToShow = schemaFields || Object.keys(inlineData[0]);
return fieldsToShow.map((fieldName) => ({
header: fieldName.charAt(0).toUpperCase() + fieldName.slice(1).replace(/_/g, ' '),
accessorKey: fieldName,
}));
}
}
if (!objectSchema) return [];
const generatedColumns: any[] = [];
const fieldsToShow = schemaFields || Object.keys(objectSchema.fields || {});
fieldsToShow.forEach((fieldName) => {
const field = objectSchema.fields?.[fieldName];
if (!field) return;
if (field.permissions && field.permissions.read === false) return;
const CellRenderer = getCellRenderer(field.type);
const numericTypes = ['number', 'currency', 'percent'];
generatedColumns.push({
header: field.label || fieldName,
accessorKey: fieldName,
...(numericTypes.includes(field.type) && { align: 'right' }),
cell: (value: any) => <CellRenderer value={value} field={field} />,
sortable: field.sortable !== false,
});
});
return generatedColumns;
}, [objectSchema, schemaFields, schemaColumns, dataConfig, hasInlineData, navigation.handleClick, executeAction, data]);
const handleExport = useCallback((format: 'csv' | 'xlsx' | 'json' | 'pdf') => {
const exportConfig = schema.exportOptions;
const maxRecords = exportConfig?.maxRecords || 0;
const includeHeaders = exportConfig?.includeHeaders !== false;
const prefix = exportConfig?.fileNamePrefix || schema.objectName || 'export';
const exportData = maxRecords > 0 ? data.slice(0, maxRecords) : data;
const downloadFile = (blob: Blob, filename: string) => {
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
a.click();
URL.revokeObjectURL(url);
};
const escapeCsvValue = (val: any): string => {
const str = val == null ? '' : String(val);
return str.includes(',') || str.includes('"') || str.includes('\n') || str.includes('\r')
? `"${str.replace(/"/g, '""')}"`
: str;
};
if (format === 'csv') {
const cols = generateColumns().filter((c: any) => c.accessorKey !== '_actions');
const fields = cols.map((c: any) => c.accessorKey);
const headers = cols.map((c: any) => c.header);
const rows: string[] = [];
if (includeHeaders) {
rows.push(headers.join(','));
}
exportData.forEach(record => {
rows.push(fields.map((f: string) => escapeCsvValue(record[f])).join(','));
});
downloadFile(new Blob([rows.join('\n')], { type: 'text/csv;charset=utf-8;' }), `${prefix}.csv`);
} else if (format === 'json') {
downloadFile(new Blob([JSON.stringify(exportData, null, 2)], { type: 'application/json' }), `${prefix}.json`);
}
setShowExport(false);
}, [data, schema.exportOptions, schema.objectName, generateColumns]);
if (error) {
return (
<div className="p-3 sm:p-4 border border-red-300 bg-red-50 rounded-md">
<h3 className="text-red-800 font-semibold">Error loading grid</h3>
<p className="text-red-600 text-sm mt-1">{error.message}</p>
</div>
);
}
if (loading && data.length === 0) {
if (useCardView) {
return (
<div className="space-y-2 p-2">
{[1, 2, 3].map((i) => (
<div key={i} className="border rounded-lg p-3 bg-card animate-pulse">
<div className="h-5 bg-muted rounded w-3/4 mb-3" />
<div className="flex items-center justify-between mb-2">
<div className="h-4 bg-muted rounded w-1/4" />
<div className="h-5 bg-muted rounded-full w-20" />
</div>
<div className="h-3 bg-muted rounded w-1/3" />
</div>
))}
</div>
);
}
return (
<div className="p-4 sm:p-8 text-center">
<div className="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-foreground"></div>
<p className="mt-2 text-sm text-muted-foreground">Loading grid...</p>
</div>
);
}
const columns = generateColumns();
// Apply persisted column order and widths
let persistedColumns = [...columns];
// Apply saved widths
if (columnState.widths) {
persistedColumns = persistedColumns.map((col: any) => {
const savedWidth = columnState.widths?.[col.accessorKey];
if (savedWidth) {
return { ...col, size: savedWidth };
}
return col;
});
}
// Apply saved order
if (columnState.order && columnState.order.length > 0) {
const orderMap = new Map(columnState.order.map((key: string, i: number) => [key, i]));
persistedColumns.sort((a: any, b: any) => {
const orderA = orderMap.get(a.accessorKey) ?? Infinity;
const orderB = orderMap.get(b.accessorKey) ?? Infinity;
return orderA - orderB;
});
}
const operations = 'operations' in schema ? schema.operations : undefined;
const hasActions = operations && (operations.update || operations.delete);
const hasRowActions = schema.rowActions && schema.rowActions.length > 0;
const columnsWithActions = (hasActions || hasRowActions) ? [
...persistedColumns,
{
header: 'Actions',
accessorKey: '_actions',
cell: (_value: any, row: any) => (
<RowActionMenu
row={row}
rowActions={schema.rowActions}
canEdit={!!(operations?.update && onEdit)}
canDelete={!!(operations?.delete && onDelete)}
onEdit={onEdit}
onDelete={onDelete}
onAction={(action, r) => executeAction({ type: action, params: { record: r } })}
/>
),
sortable: false,
},
] : persistedColumns;
// --- Pinned column reordering ---
// Reorder: pinned:'left' first, unpinned middle, pinned:'right' last
const pinnedLeftCols = columnsWithActions.filter((c: any) => c.pinned === 'left');
const pinnedRightCols = columnsWithActions.filter((c: any) => c.pinned === 'right');
const unpinnedCols = columnsWithActions.filter((c: any) => !c.pinned);
const hasPinnedColumns = pinnedLeftCols.length > 0 || pinnedRightCols.length > 0;
const rightPinnedClasses = 'sticky right-0 z-10 bg-background border-l border-border';
const orderedColumns = hasPinnedColumns
? [
...pinnedLeftCols,
...unpinnedCols,
...pinnedRightCols.map((col: any) => ({
...col,
className: [col.className, rightPinnedClasses].filter(Boolean).join(' '),
cellClassName: [col.cellClassName, rightPinnedClasses].filter(Boolean).join(' '),
})),
]
: columnsWithActions;
// Calculate frozenColumns: if pinned columns exist, use left-pinned count; otherwise use schema default
const effectiveFrozenColumns = hasPinnedColumns
? pinnedLeftCols.length
: (schema.frozenColumns ?? 1);
// Determine selection mode (support both new and legacy formats)
let selectionMode: 'none' | 'single' | 'multiple' | boolean = false;
if (schema.selection?.type) {
selectionMode = schema.selection.type === 'none' ? false : schema.selection.type;
} else if (schema.selectable !== undefined) {
// Legacy support
selectionMode = schema.selectable;
}
// Determine pagination settings (support both new and legacy formats)
const paginationEnabled = schema.pagination !== undefined
? true
: (schema.showPagination !== undefined ? schema.showPagination : true);
const pageSize = schema.pagination?.pageSize
|| schema.pageSize
|| 10;
// Determine search settings
const searchEnabled = schema.searchableFields !== undefined
? schema.searchableFields.length > 0
: (schema.showSearch !== undefined ? schema.showSearch : true);
const dataTableSchema: any = {
type: 'data-table',
caption: schema.label || schema.title,
columns: orderedColumns,
data,
pagination: paginationEnabled,
pageSize: pageSize,
searchable: searchEnabled,
selectable: selectionMode,
sortable: true,
exportable: operations?.export,
rowActions: hasActions,
resizableColumns: schema.resizable ?? schema.resizableColumns ?? true,
reorderableColumns: schema.reorderableColumns ?? false,
editable: schema.editable ?? false,
className: schema.className,
cellClassName: rowHeightMode === 'compact'
? 'px-3 py-1 text-[13px] leading-tight'
: rowHeightMode === 'short'
? 'px-3 py-1 text-[13px] leading-normal'
: rowHeightMode === 'tall'
? 'px-3 py-2.5 text-sm'
: rowHeightMode === 'extra_tall'
? 'px-3 py-3.5 text-sm leading-relaxed'
: 'px-3 py-1.5 text-[13px] leading-normal',
showRowNumbers: true,
showAddRow: !!operations?.create,
onAddRecord: onAddRecord,
rowClassName: schema.rowColor ? (row: any, _idx: number) => getRowClassName(row) : undefined,
rowStyle: schema.conditionalFormatting?.length ? (row: any, _idx: number) => getRowStyle(row) : undefined,
frozenColumns: effectiveFrozenColumns,
onSelectionChange: (rows: any[]) => {
setSelectedRows(rows);
onRowSelect?.(rows);
},
onRowClick: navigation.handleClick,
onCellChange: onCellChange,
onRowSave: onRowSave,
onBatchSave: onBatchSave,
onColumnResize: (columnKey: string, width: number) => {
saveColumnState({
...columnState,
widths: { ...columnState.widths, [columnKey]: width },
});
},
onColumnReorder: (newOrder: string[]) => {
saveColumnState({
...columnState,
order: newOrder,
});
},
};
/** Build a per-group data-table schema (inherits everything except data & pagination). */
const buildGroupTableSchema = (groupRows: any[]) => ({
...dataTableSchema,
caption: undefined,
data: groupRows,
pagination: false,
searchable: false,
});
// Build record detail title
const detailTitle = schema.label
? `${schema.label} Detail`
: schema.objectName
? `${schema.objectName.charAt(0).toUpperCase() + schema.objectName.slice(1)} Detail`
: 'Record Detail';
// Mobile card-view fallback for screens below 480px
if (useCardView && data.length > 0 && !isGrouped) {
const displayColumns = generateColumns().filter((c: any) => c.accessorKey !== '_actions');
// Build a lookup of column metadata for smart rendering
const colMap = new Map<string, any>();
displayColumns.forEach((col: any) => colMap.set(col.accessorKey, col));
// Identify special columns by inferred type for visual hierarchy
const titleCol = displayColumns[0]; // First column is always the title
const amountKeys = ['amount', 'price', 'total', 'revenue', 'cost', 'value', 'budget', 'salary'];
const stageKeys = ['stage', 'status', 'priority', 'category', 'severity', 'level'];
const dateKeys = ['date', 'due', 'created', 'updated', 'deadline', 'start', 'end', 'expires'];
const percentKeys = ['probability', 'percent', 'rate', 'ratio', 'confidence', 'score'];
// Stage badge color mapping for common pipeline stages
const stageBadgeColor = (value: string): string => {
const v = (value || '').toLowerCase();
if (v.includes('won') || v.includes('completed') || v.includes('done') || v.includes('active'))
return 'bg-green-100 text-green-800 border-green-300';
if (v.includes('lost') || v.includes('cancelled') || v.includes('rejected') || v.includes('closed lost'))
return 'bg-red-100 text-red-800 border-red-300';
if (v.includes('negotiation') || v.includes('review') || v.includes('in progress'))
return 'bg-yellow-100 text-yellow-800 border-yellow-300';
if (v.includes('proposal') || v.includes('pending'))