-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathListView.tsx
More file actions
1725 lines (1590 loc) · 69.4 KB
/
ListView.tsx
File metadata and controls
1725 lines (1590 loc) · 69.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
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.
*/
import * as React from 'react';
import { cn, Button, Input, Popover, PopoverContent, PopoverTrigger, FilterBuilder, SortBuilder, NavigationOverlay } from '@object-ui/components';
import type { SortItem } from '@object-ui/components';
import { Search, SlidersHorizontal, ArrowUpDown, X, EyeOff, Group, Paintbrush, Ruler, Inbox, Download, AlignJustify, Share2, Printer, Plus, icons, type LucideIcon } from 'lucide-react';
import type { FilterGroup } from '@object-ui/components';
import { ViewSwitcher, ViewType } from './ViewSwitcher';
import { TabBar } from './components/TabBar';
import type { ViewTab } from './components/TabBar';
import { UserFilters } from './UserFilters';
import { SchemaRenderer, useNavigationOverlay } from '@object-ui/react';
import { useDensityMode } from '@object-ui/react';
import type { ListViewSchema } from '@object-ui/types';
import { usePullToRefresh } from '@object-ui/mobile';
import { evaluatePlainCondition, normalizeQuickFilter, normalizeQuickFilters, buildExpandFields } from '@object-ui/core';
import { useObjectTranslation, useObjectLabel } from '@object-ui/i18n';
export interface ListViewProps {
schema: ListViewSchema;
className?: string;
onViewChange?: (view: ViewType) => void;
onFilterChange?: (filters: any) => void;
onSortChange?: (sort: any) => void;
onSearchChange?: (search: string) => void;
/** Callback when a row/item is clicked (overrides NavigationConfig) */
onRowClick?: (record: Record<string, unknown>) => void;
/** Show view type switcher (Grid/Kanban/etc). Default: false (view type is fixed) */
showViewSwitcher?: boolean;
[key: string]: any;
}
// Helper to convert FilterBuilder group to ObjectStack AST
function mapOperator(op: string) {
switch (op) {
case 'equals': case 'eq': return '=';
case 'notEquals': case 'ne': case 'neq': return '!=';
case 'contains': return 'contains';
case 'notContains': return 'notcontains';
case 'greaterThan': case 'gt': return '>';
case 'greaterOrEqual': case 'gte': return '>=';
case 'lessThan': case 'lt': return '<';
case 'lessOrEqual': case 'lte': return '<=';
case 'in': return 'in';
case 'notIn': return 'not in';
case 'before': return '<';
case 'after': return '>';
default: return op;
}
}
/**
* Normalize a single filter condition: convert `in`/`not in` operators
* into backend-compatible `or`/`and` of equality conditions.
* E.g., ['status', 'in', ['a','b']] → ['or', ['status','=','a'], ['status','=','b']]
*/
export function normalizeFilterCondition(condition: any[]): any[] {
if (!Array.isArray(condition) || condition.length < 3) return condition;
const [field, op, value] = condition;
// Recurse into logical groups
if (typeof field === 'string' && (field === 'and' || field === 'or')) {
return [field, ...condition.slice(1).map((c: any) =>
Array.isArray(c) ? normalizeFilterCondition(c) : c
)];
}
if (op === 'in' && Array.isArray(value)) {
if (value.length === 0) return [];
if (value.length === 1) return [field, '=', value[0]];
return ['or', ...value.map((v: any) => [field, '=', v])];
}
if (op === 'not in' && Array.isArray(value)) {
if (value.length === 0) return [];
if (value.length === 1) return [field, '!=', value[0]];
return ['and', ...value.map((v: any) => [field, '!=', v])];
}
return condition;
}
/**
* Format an action identifier string into a human-readable label.
* e.g., 'send_email' → 'Send Email'
*/
function formatActionLabel(action: string): string {
return action.replace(/_/g, ' ').replace(/\b\w/g, c => c.toUpperCase());
}
/**
* Normalize an array of filter conditions, expanding `in`/`not in` operators
* and ensuring consistent AST structure.
*/
export function normalizeFilters(filters: any[]): any[] {
if (!Array.isArray(filters) || filters.length === 0) return [];
return filters
.map(f => Array.isArray(f) ? normalizeFilterCondition(f) : f)
.filter(f => Array.isArray(f) && f.length > 0);
}
function convertFilterGroupToAST(group: FilterGroup): any[] {
if (!group || !group.conditions || group.conditions.length === 0) return [];
const conditions = group.conditions.map(c => {
if (c.operator === 'isEmpty') return [c.field, '=', null];
if (c.operator === 'isNotEmpty') return [c.field, '!=', null];
return [c.field, mapOperator(c.operator), c.value];
});
// Normalize in/not-in conditions for backend compatibility
const normalized = normalizeFilters(conditions);
if (normalized.length === 0) return [];
if (normalized.length === 1) return normalized[0];
return [group.logic, ...normalized];
}
/**
* Evaluate conditional formatting rules against a record.
* Returns a CSSProperties object for the first matching rule, or empty object.
* Supports both field/operator/value rules and expression-based rules.
*
* Exported for use by child view renderers (e.g., ObjectGrid) and consumers
* who need to evaluate formatting rules outside the ListView component.
*/
export function evaluateConditionalFormatting(
record: Record<string, unknown>,
rules?: ListViewSchema['conditionalFormatting']
): React.CSSProperties {
if (!rules || rules.length === 0) return {};
for (const rule of rules) {
let match = false;
// Determine expression: spec uses 'condition', ObjectUI uses 'expression'
const expression =
('condition' in rule ? rule.condition : undefined)
|| ('expression' in rule ? rule.expression : undefined)
|| undefined;
// Expression-based evaluation using safe ExpressionEvaluator
// Supports both template expressions (${data.field > value}) and
// plain Spec expressions (field == 'value').
if (expression) {
match = evaluatePlainCondition(expression, record as Record<string, any>);
} else if ('field' in rule && 'operator' in rule && rule.field && rule.operator) {
// Standard field/operator/value evaluation (ObjectUI format)
const fieldValue = record[rule.field];
switch (rule.operator) {
case 'equals':
match = fieldValue === rule.value;
break;
case 'not_equals':
match = fieldValue !== rule.value;
break;
case 'contains':
match = typeof fieldValue === 'string' && typeof rule.value === 'string' && fieldValue.includes(rule.value);
break;
case 'greater_than':
match = typeof fieldValue === 'number' && typeof rule.value === 'number' && fieldValue > rule.value;
break;
case 'less_than':
match = typeof fieldValue === 'number' && typeof rule.value === 'number' && fieldValue < rule.value;
break;
case 'in':
match = Array.isArray(rule.value) && rule.value.includes(fieldValue);
break;
}
}
if (match) {
// Build style: spec 'style' object is base, individual properties override
const style: React.CSSProperties = {};
if ('style' in rule && rule.style) Object.assign(style, rule.style);
if ('backgroundColor' in rule && rule.backgroundColor) style.backgroundColor = rule.backgroundColor;
if ('textColor' in rule && rule.textColor) style.color = rule.textColor;
if ('borderColor' in rule && rule.borderColor) style.borderColor = rule.borderColor;
return style;
}
}
return {};
}
// Default English translations for fallback when I18nProvider is not available
const LIST_DEFAULT_TRANSLATIONS: Record<string, string> = {
'list.recordCount': '{{count}} records',
'list.recordCountOne': '{{count}} record',
'list.noItems': 'No items found',
'list.noItemsMessage': 'There are no records to display. Try adjusting your filters or adding new data.',
'list.search': 'Search',
'list.filter': 'Filter',
'list.filterRecords': 'Filter Records',
'list.sort': 'Sort',
'list.sortRecords': 'Sort Records',
'list.group': 'Group',
'list.groupBy': 'Group By',
'list.export': 'Export',
'list.exportAs': 'Export as {{format}}',
'list.color': 'Color',
'list.rowColor': 'Row Color',
'list.colorByField': 'Color by field',
'list.clear': 'Clear',
'list.none': 'None',
'list.hideFields': 'Hide fields',
'list.showAll': 'Show all',
'list.pullToRefresh': 'Pull to refresh',
'list.refreshing': 'Refreshing…',
'list.dataLimitReached': 'Showing first {{limit}} records. More data may be available.',
'list.addRecord': 'Add record',
'list.tabs': 'Tabs',
'list.allRecords': 'All Records',
'list.share': 'Share',
'list.print': 'Print',
'list.hideFieldsTitle': 'Hide Fields',
};
/**
* Safe wrapper for useObjectTranslation that falls back to English defaults
* when I18nProvider is not available (e.g., standalone usage outside console).
*/
function useListViewTranslation() {
try {
const result = useObjectTranslation();
const testValue = result.t('list.recordCount');
if (testValue === 'list.recordCount') {
// i18n returned the key itself — not initialized
return {
t: (key: string, options?: Record<string, unknown>) => {
let value = LIST_DEFAULT_TRANSLATIONS[key] || key;
if (options) {
for (const [k, v] of Object.entries(options)) {
value = value.replace(`{{${k}}}`, String(v));
}
}
return value;
},
};
}
return { t: result.t };
} catch {
return {
t: (key: string, options?: Record<string, unknown>) => {
let value = LIST_DEFAULT_TRANSLATIONS[key] || key;
if (options) {
for (const [k, v] of Object.entries(options)) {
value = value.replace(`{{${k}}}`, String(v));
}
}
return value;
},
};
}
}
/**
* Safe wrapper for useObjectLabel that falls back to identity when I18nProvider is unavailable.
*/
function useListFieldLabel() {
try {
const { fieldLabel } = useObjectLabel();
return { fieldLabel };
} catch {
return {
fieldLabel: (_objectName: string, _fieldName: string, fallback: string) => fallback,
};
}
}
/**
* Imperative handle exposed by ListView via React.forwardRef.
* Allows parent components to trigger a data refresh programmatically.
*
* @example
* ```tsx
* const listRef = React.useRef<ListViewHandle>(null);
* <ListView ref={listRef} schema={schema} />
* // After a mutation:
* listRef.current?.refresh();
* ```
*/
export interface ListViewHandle {
/** Force the ListView to re-fetch data from the DataSource */
refresh(): void;
}
export const ListView = React.forwardRef<ListViewHandle, ListViewProps>(({
schema: propSchema,
className,
onViewChange,
onFilterChange,
onSortChange,
onSearchChange,
onRowClick,
showViewSwitcher = false,
...props
}, ref) => {
// i18n support for record count and other labels
const { t } = useListViewTranslation();
const { fieldLabel: resolveFieldLabel } = useListFieldLabel();
// Kernel level default: Ensure viewType is always defined (default to 'grid')
const schema = React.useMemo(() => ({
...propSchema,
viewType: propSchema.viewType || 'grid'
}), [propSchema]);
// Convenience: resolve field label with schema.objectName pre-bound
const tFieldLabel = React.useCallback(
(fieldName: string, fallback: string) =>
schema.objectName ? resolveFieldLabel(schema.objectName, fieldName, fallback) : fallback,
[schema.objectName, resolveFieldLabel],
);
// Resolve toolbar visibility flags: userActions overrides showX flags
const toolbarFlags = React.useMemo(() => {
const ua = schema.userActions;
const addRecordEnabled = schema.addRecord?.enabled === true && ua?.addRecordForm !== false;
return {
showSearch: ua?.search !== undefined ? ua.search : schema.showSearch !== false,
showSort: ua?.sort !== undefined ? ua.sort : schema.showSort !== false,
showFilters: ua?.filter !== undefined ? ua.filter : schema.showFilters !== false,
showDensity: ua?.rowHeight !== undefined ? ua.rowHeight : schema.showDensity === true,
showHideFields: schema.showHideFields === true,
showGroup: schema.showGroup !== false,
showColor: schema.showColor === true,
showAddRecord: addRecordEnabled,
addRecordPosition: (schema.addRecord?.position === 'bottom' ? 'bottom' : 'top') as 'top' | 'bottom',
};
}, [schema.userActions, schema.showSearch, schema.showSort, schema.showFilters, schema.showDensity, schema.showHideFields, schema.showGroup, schema.showColor, schema.addRecord, schema.userActions?.addRecordForm]);
const [currentView, setCurrentView] = React.useState<ViewType>(
(schema.viewType as ViewType)
);
const [searchTerm, setSearchTerm] = React.useState('');
const [showSearchPopover, setShowSearchPopover] = React.useState(false);
// Sort State
const [showSort, setShowSort] = React.useState(false);
const [currentSort, setCurrentSort] = React.useState<SortItem[]>(() => {
if (schema.sort && schema.sort.length > 0) {
return schema.sort.map(s => {
// Support legacy string format "field desc"
if (typeof s === 'string') {
const parts = s.trim().split(/\s+/);
return {
id: crypto.randomUUID(),
field: parts[0],
order: (parts[1]?.toLowerCase() === 'desc' ? 'desc' : 'asc') as 'asc' | 'desc',
};
}
return {
id: crypto.randomUUID(),
field: s.field,
order: (s.order as 'asc' | 'desc') || 'asc',
};
});
}
return [];
});
const [showFilters, setShowFilters] = React.useState(false);
const [currentFilters, setCurrentFilters] = React.useState<FilterGroup>({
id: 'root',
logic: 'and',
conditions: []
});
// Tab State
const [activeTab, setActiveTab] = React.useState<string | undefined>(() => {
if (!schema.tabs || schema.tabs.length === 0) return undefined;
const defaultTab = schema.tabs.find(t => t.isDefault);
return defaultTab?.name ?? schema.tabs[0]?.name;
});
const handleTabChange = React.useCallback(
(tab: ViewTab) => {
setActiveTab(tab.name);
// Apply tab filter if defined
if (tab.filter) {
const tabFilters: FilterGroup = {
id: `tab-filter-${tab.name}`,
logic: tab.filter.logic || 'and',
conditions: tab.filter.conditions || [],
};
setCurrentFilters(tabFilters);
onFilterChange?.(tabFilters);
} else {
const emptyFilters: FilterGroup = { id: 'root', logic: 'and', conditions: [] };
setCurrentFilters(emptyFilters);
onFilterChange?.(emptyFilters);
}
},
[onFilterChange],
);
// Data State
const dataSource = props.dataSource;
const [data, setData] = React.useState<any[]>([]);
const [loading, setLoading] = React.useState(false);
const [objectDef, setObjectDef] = React.useState<any>(null);
const [objectDefLoaded, setObjectDefLoaded] = React.useState(false);
const [refreshKey, setRefreshKey] = React.useState(0);
const [dataLimitReached, setDataLimitReached] = React.useState(false);
// --- P1: Imperative refresh API ---
React.useImperativeHandle(ref, () => ({
refresh: () => setRefreshKey(k => k + 1),
}), []);
// --- P2: Auto-subscribe to DataSource mutation events ---
// When an external refreshTrigger is provided, rely on that instead of
// subscribing to dataSource mutations to avoid double refreshes.
React.useEffect(() => {
if (!dataSource?.onMutation || !schema.objectName || schema.refreshTrigger) return;
const unsub = dataSource.onMutation((event) => {
if (event.resource === schema.objectName) {
setRefreshKey(k => k + 1);
}
});
return unsub;
}, [dataSource, schema.objectName, schema.refreshTrigger]);
// Dynamic page size state (wired from pageSizeOptions selector)
const [dynamicPageSize, setDynamicPageSize] = React.useState<number | undefined>(undefined);
const effectivePageSize = dynamicPageSize ?? schema.pagination?.pageSize ?? 100;
// Grouping state (initialized from schema, user can add/remove via popover)
const [groupingConfig, setGroupingConfig] = React.useState(schema.grouping);
const [showGroupPopover, setShowGroupPopover] = React.useState(false);
// Row color state (initialized from schema, user can configure via popover)
const [rowColorConfig, setRowColorConfig] = React.useState(schema.rowColor);
const [showColorPopover, setShowColorPopover] = React.useState(false);
// Bulk action state
const [selectedRows, setSelectedRows] = React.useState<any[]>([]);
// Request counter for debounce — only the latest request writes data
const fetchRequestIdRef = React.useRef(0);
// Quick Filters State
const [activeQuickFilters, setActiveQuickFilters] = React.useState<Set<string>>(() => {
const defaults = new Set<string>();
schema.quickFilters?.forEach(qf => {
const normalized = normalizeQuickFilter(qf);
if (normalized.defaultActive) defaults.add(normalized.id);
});
return defaults;
});
// User Filters State (Airtable Interfaces-style)
const [userFilterConditions, setUserFilterConditions] = React.useState<any[]>([]);
// Auto-derive userFilters from objectDef when not explicitly configured
const resolvedUserFilters = React.useMemo<ListViewSchema['userFilters'] | undefined>(() => {
// If explicitly configured, use as-is
if (schema.userFilters) return schema.userFilters;
// Auto-derive from objectDef for select/multi-select/boolean fields
if (!objectDef?.fields) return undefined;
const FILTERABLE_FIELD_TYPES = new Set(['select', 'multi-select', 'boolean']);
const derivedFields: NonNullable<NonNullable<ListViewSchema['userFilters']>['fields']> = [];
const fieldsEntries: Array<[string, any]> = Array.isArray(objectDef.fields)
? objectDef.fields.map((f: any) => [f.name, f])
: Object.entries(objectDef.fields);
for (const [key, field] of fieldsEntries) {
// Include fields with a filterable type, or fields that have options without an explicit type
if (FILTERABLE_FIELD_TYPES.has(field.type) || (field.options && !field.type)) {
derivedFields.push({
field: key,
label: tFieldLabel(key, field.label || key),
type: field.type === 'boolean' ? 'boolean' : field.type === 'multi-select' ? 'multi-select' : 'select',
});
}
}
if (derivedFields.length === 0) return undefined;
return { element: 'dropdown', fields: derivedFields };
}, [schema.userFilters, objectDef]);
// Hidden Fields State (initialized from schema)
const [hiddenFields, setHiddenFields] = React.useState<Set<string>>(
() => new Set(schema.hiddenFields || [])
);
const [showHideFields, setShowHideFields] = React.useState(false);
// Export State
const [showExport, setShowExport] = React.useState(false);
// Normalize quickFilters: support both ObjectUI format { id, label, filters[] }
// and spec format { field, operator, value }. Spec items are auto-converted.
const normalizedQuickFilters = React.useMemo(
() => normalizeQuickFilters(schema.quickFilters),
[schema.quickFilters],
);
// Normalize exportOptions: support both ObjectUI object format and spec string[] format
const resolvedExportOptions = React.useMemo(() => {
if (!schema.exportOptions) return undefined;
// Spec format: simple string[] like ['csv', 'xlsx']
if (Array.isArray(schema.exportOptions)) {
return { formats: schema.exportOptions as Array<'csv' | 'xlsx' | 'json' | 'pdf'> };
}
// ObjectUI format: already an object
return schema.exportOptions;
}, [schema.exportOptions]);
// Density Mode — rowHeight maps to density if densityMode not explicitly set
const resolvedDensity = React.useMemo(() => {
if (schema.densityMode) return schema.densityMode;
if (schema.rowHeight) {
const map: Record<string, 'compact' | 'comfortable' | 'spacious'> = {
compact: 'compact',
short: 'compact',
medium: 'comfortable',
tall: 'spacious',
extra_tall: 'spacious',
};
return map[schema.rowHeight] || 'comfortable';
}
return 'compact';
}, [schema.densityMode, schema.rowHeight]);
const density = useDensityMode(resolvedDensity);
const handlePullRefresh = React.useCallback(async () => {
setRefreshKey(k => k + 1);
}, []);
const { ref: pullRef, isRefreshing, pullDistance } = usePullToRefresh<HTMLDivElement>({
onRefresh: handlePullRefresh,
enabled: !!dataSource && !!schema.objectName,
});
const storageKey = React.useMemo(() => {
return schema.id
? `listview-${schema.objectName}-${schema.id}-view`
: `listview-${schema.objectName}-view`;
}, [schema.objectName, schema.id]);
// Fetch object definition
React.useEffect(() => {
let isMounted = true;
// Reset loaded flag so data fetch waits for the new schema
setObjectDefLoaded(false);
setObjectDef(null);
const fetchObjectDef = async () => {
if (!dataSource || !schema.objectName) {
setObjectDefLoaded(true);
return;
}
try {
const def = await dataSource.getObjectSchema(schema.objectName);
if (isMounted) {
setObjectDef(def);
}
} catch (err) {
console.warn("Failed to fetch object schema for ListView:", err);
} finally {
if (isMounted) {
setObjectDefLoaded(true);
}
}
};
fetchObjectDef();
return () => { isMounted = false; };
}, [schema.objectName, dataSource]);
// Auto-compute $expand fields from objectDef (lookup / master_detail)
const expandFields = React.useMemo(
() => buildExpandFields(objectDef?.fields, schema.fields),
[objectDef?.fields, schema.fields],
);
// Fetch data effect — supports schema.data (ViewDataSchema) provider modes
React.useEffect(() => {
let isMounted = true;
const requestId = ++fetchRequestIdRef.current;
// Check for inline data via schema.data provider: 'value'
if (schema.data && typeof schema.data === 'object' && !Array.isArray(schema.data)) {
const dataConfig = schema.data as any;
if (dataConfig.provider === 'value' && Array.isArray(dataConfig.items)) {
let items = dataConfig.items;
if (searchTerm) {
const q = searchTerm.toLowerCase();
items = items.filter((row: any) =>
Object.values(row).some(
(v) => v != null && String(v).toLowerCase().includes(q),
),
);
}
setData(items);
setLoading(false);
setDataLimitReached(false);
return;
}
}
// Also support schema.data as a plain array (shorthand for value provider)
if (Array.isArray(schema.data)) {
let items = schema.data as any[];
if (searchTerm) {
const q = searchTerm.toLowerCase();
items = items.filter((row: any) =>
Object.values(row).some(
(v) => v != null && String(v).toLowerCase().includes(q),
),
);
}
setData(items);
setLoading(false);
setDataLimitReached(false);
return;
}
// Wait for objectDef to load before fetching data so that $expand is computed
if (!objectDefLoaded) return;
const fetchData = async () => {
if (!dataSource || !schema.objectName) return;
setLoading(true);
try {
// Construct filter
let finalFilter: any = [];
const baseFilter = schema.filters || [];
const userFilter = convertFilterGroupToAST(currentFilters);
// Collect active quick filter conditions
const quickFilterConditions: any[] = [];
if (normalizedQuickFilters && activeQuickFilters.size > 0) {
normalizedQuickFilters.forEach((qf: any) => {
if (activeQuickFilters.has(qf.id) && qf.filters && qf.filters.length > 0) {
quickFilterConditions.push(qf.filters);
}
});
}
// Normalize userFilter conditions (convert `in` to `or` of `=`)
const normalizedUserFilterConditions = normalizeFilters(userFilterConditions);
// Merge all filter sources with consistent structure
const allFilters = [
...(baseFilter.length > 0 ? [baseFilter] : []),
...(userFilter.length > 0 ? [userFilter] : []),
...quickFilterConditions,
...normalizedUserFilterConditions,
].filter(f => Array.isArray(f) && f.length > 0);
if (allFilters.length > 1) {
finalFilter = ['and', ...allFilters];
} else if (allFilters.length === 1) {
finalFilter = allFilters[0];
}
// Convert sort to query format
// Use array format to ensure order is preserved (Object keys are not guaranteed ordered)
const sort: any = currentSort.length > 0
? currentSort
.filter(item => item.field) // Ensure field is selected
.map(item => ({ field: item.field, order: item.order }))
: undefined;
const results = await dataSource.find(schema.objectName, {
$filter: finalFilter,
$orderby: sort,
$top: effectivePageSize,
...(expandFields.length > 0 ? { $expand: expandFields } : {}),
...(searchTerm ? {
$search: searchTerm,
...(schema.searchableFields && schema.searchableFields.length > 0
? { $searchFields: schema.searchableFields }
: {}),
} : {}),
});
// Stale request guard: only apply the latest request's results
if (!isMounted || requestId !== fetchRequestIdRef.current) return;
let items: any[] = [];
if (Array.isArray(results)) {
items = results;
} else if (results && typeof results === 'object') {
if (Array.isArray((results as any).data)) {
items = (results as any).data;
} else if (Array.isArray((results as any).records)) {
items = (results as any).records;
} else if (Array.isArray((results as any).value)) {
items = (results as any).value;
}
}
setData(items);
setDataLimitReached(items.length >= effectivePageSize);
} catch (err) {
// Only log errors from the latest request
if (requestId === fetchRequestIdRef.current) {
console.error("ListView data fetch error:", err);
}
} finally {
if (isMounted && requestId === fetchRequestIdRef.current) {
setLoading(false);
}
}
};
fetchData();
return () => { isMounted = false; };
}, [schema.objectName, schema.data, dataSource, schema.filters, effectivePageSize, currentSort, currentFilters, activeQuickFilters, normalizedQuickFilters, userFilterConditions, refreshKey, searchTerm, schema.searchableFields, expandFields, objectDefLoaded, schema.refreshTrigger]); // Re-fetch on filter/sort/search/refreshTrigger change
// Available view types based on schema configuration
const availableViews = React.useMemo(() => {
// If appearance.allowedVisualizations is set, use it as whitelist
if (schema.appearance?.allowedVisualizations && schema.appearance.allowedVisualizations.length > 0) {
return schema.appearance.allowedVisualizations.filter(v =>
['grid', 'kanban', 'gallery', 'calendar', 'timeline', 'gantt', 'map'].includes(v)
) as ViewType[];
}
const views: ViewType[] = ['grid'];
// Check for Kanban capabilities (spec config takes precedence)
if (schema.kanban?.groupField || schema.options?.kanban?.groupField) {
views.push('kanban');
}
// Check for Gallery capabilities (spec config takes precedence)
if (schema.gallery?.coverField || schema.gallery?.imageField || schema.options?.gallery?.imageField) {
views.push('gallery');
}
// Check for Calendar capabilities (spec config takes precedence)
if (schema.calendar?.startDateField || schema.options?.calendar?.startDateField) {
views.push('calendar');
}
// Check for Timeline capabilities (spec config takes precedence)
if (schema.timeline?.startDateField || schema.options?.timeline?.startDateField || schema.options?.timeline?.dateField || schema.options?.calendar?.startDateField) {
views.push('timeline');
}
// Check for Gantt capabilities (spec config takes precedence)
if (schema.gantt?.startDateField || schema.options?.gantt?.startDateField) {
views.push('gantt');
}
// Check for Map capabilities
if (schema.options?.map?.locationField || (schema.options?.map?.latitudeField && schema.options?.map?.longitudeField)) {
views.push('map');
}
// Always allow switching back to the viewType defined in schema if it's one of the supported types
if (schema.viewType && !views.includes(schema.viewType as ViewType) &&
['grid', 'kanban', 'calendar', 'timeline', 'gantt', 'map', 'gallery'].includes(schema.viewType)) {
views.push(schema.viewType as ViewType);
}
return views;
}, [schema.options, schema.viewType, schema.kanban, schema.calendar, schema.gantt, schema.gallery, schema.timeline, schema.appearance?.allowedVisualizations]);
// Sync view from props
React.useEffect(() => {
if (schema.viewType) {
setCurrentView(schema.viewType as ViewType);
}
}, [schema.viewType]);
// Load saved view preference (DISABLED: interfering with schema-defined views)
/*
React.useEffect(() => {
try {
const savedView = localStorage.getItem(storageKey);
if (savedView && ['grid', 'kanban', 'calendar', 'timeline', 'gantt', 'map', 'gallery'].includes(savedView) && availableViews.includes(savedView as ViewType)) {
setCurrentView(savedView as ViewType);
}
} catch (error) {
console.warn('Failed to load view preference from localStorage:', error);
}
}, [storageKey, availableViews]);
*/
const handleViewChange = React.useCallback((view: ViewType) => {
setCurrentView(view);
try {
localStorage.setItem(storageKey, view);
} catch (error) {
console.warn('Failed to save view preference to localStorage:', error);
}
onViewChange?.(view);
}, [storageKey, onViewChange]);
const handleSearchChange = React.useCallback((value: string) => {
setSearchTerm(value);
onSearchChange?.(value);
}, [onSearchChange]);
// --- NavigationConfig support ---
const navigation = useNavigationOverlay({
navigation: schema.navigation,
objectName: schema.objectName,
onNavigate: schema.onNavigate,
onRowClick,
});
// Apply hiddenFields and fieldOrder to produce effective fields
const effectiveFields = React.useMemo(() => {
let fields = schema.fields || [];
// Defensive: ensure fields is an array of strings/objects
if (!Array.isArray(fields)) {
fields = [];
}
// Remove hidden fields
if (hiddenFields.size > 0) {
fields = fields.filter((f: any) => {
const fieldName = typeof f === 'string' ? f : (f?.name || f?.fieldName || f?.field);
return fieldName != null && !hiddenFields.has(fieldName);
});
}
// Apply field order
if (schema.fieldOrder && schema.fieldOrder.length > 0) {
const orderMap = new Map(schema.fieldOrder.map((f, i) => [f, i]));
fields = [...fields].sort((a: any, b: any) => {
const nameA = typeof a === 'string' ? a : (a?.name || a?.fieldName || a?.field);
const nameB = typeof b === 'string' ? b : (b?.name || b?.fieldName || b?.field);
const orderA = orderMap.get(nameA) ?? Infinity;
const orderB = orderMap.get(nameB) ?? Infinity;
return orderA - orderB;
});
}
return fields;
}, [schema.fields, hiddenFields, schema.fieldOrder]);
// Generate the appropriate view component schema
const viewComponentSchema = React.useMemo(() => {
const baseProps = {
objectName: schema.objectName,
fields: effectiveFields,
filters: schema.filters,
sort: currentSort,
className: "h-full w-full",
// Disable internal controls that clash with ListView toolbar
showSearch: false,
// Pass navigation click handler to child views
onRowClick: navigation.handleClick,
// Forward display properties to child views
...(schema.striped != null ? { striped: schema.striped } : {}),
...(schema.bordered != null ? { bordered: schema.bordered } : {}),
};
switch (currentView) {
case 'grid':
return {
type: 'object-grid',
...baseProps,
columns: effectiveFields,
...(schema.conditionalFormatting ? { conditionalFormatting: schema.conditionalFormatting } : {}),
...(schema.inlineEdit != null ? { editable: schema.inlineEdit } : {}),
...(schema.wrapHeaders != null ? { wrapHeaders: schema.wrapHeaders } : {}),
...(schema.virtualScroll != null ? { virtualScroll: schema.virtualScroll } : {}),
...(schema.resizable != null ? { resizable: schema.resizable } : {}),
...(schema.selection ? { selection: schema.selection } : {}),
...(schema.pagination ? { pagination: schema.pagination } : {}),
...(groupingConfig ? { grouping: groupingConfig } : {}),
...(rowColorConfig ? { rowColor: rowColorConfig } : {}),
...(schema.rowActions ? { rowActions: schema.rowActions } : {}),
...(schema.bulkActions ? { batchActions: schema.bulkActions } : {}),
...(schema.options?.grid || {}),
};
case 'kanban':
return {
type: 'object-kanban',
...baseProps,
groupBy: schema.kanban?.groupField || schema.options?.kanban?.groupField || 'status',
groupField: schema.kanban?.groupField || schema.options?.kanban?.groupField || 'status',
titleField: schema.kanban?.titleField || schema.options?.kanban?.titleField || 'name',
cardFields: schema.kanban?.cardFields || effectiveFields || [],
...(groupingConfig ? { grouping: groupingConfig } : {}),
...(schema.options?.kanban || {}),
...(schema.kanban || {}),
};
case 'calendar':
return {
type: 'object-calendar',
...baseProps,
startDateField: schema.calendar?.startDateField || schema.options?.calendar?.startDateField || 'start_date',
endDateField: schema.calendar?.endDateField || schema.options?.calendar?.endDateField || 'end_date',
titleField: schema.calendar?.titleField || schema.options?.calendar?.titleField || 'name',
...(schema.calendar?.defaultView ? { defaultView: schema.calendar.defaultView } : {}),
...(schema.options?.calendar || {}),
...(schema.calendar || {}),
};
case 'gallery': {
// Merge spec config over legacy options into nested gallery prop
const mergedGallery = {
...(schema.options?.gallery || {}),
...(schema.gallery || {}),
};
return {
type: 'object-gallery',
...baseProps,
// Nested gallery config (spec-compliant, used by ObjectGallery)
gallery: Object.keys(mergedGallery).length > 0 ? mergedGallery : undefined,
// Deprecated top-level props for backward compat
imageField: schema.gallery?.coverField || schema.gallery?.imageField || schema.options?.gallery?.imageField,
titleField: schema.gallery?.titleField || schema.options?.gallery?.titleField || 'name',
subtitleField: schema.gallery?.subtitleField || schema.options?.gallery?.subtitleField,
...(groupingConfig ? { grouping: groupingConfig } : {}),
};
}
case 'timeline': {
// Merge spec config over legacy options into nested timeline prop
const mergedTimeline = {
...(schema.options?.timeline || {}),
...(schema.timeline || {}),
};
return {
type: 'object-timeline',
...baseProps,
// Nested timeline config (spec-compliant, used by ObjectTimeline)
timeline: Object.keys(mergedTimeline).length > 0 ? mergedTimeline : undefined,
// Deprecated top-level props for backward compat
startDateField: schema.timeline?.startDateField || schema.options?.timeline?.startDateField || schema.options?.timeline?.dateField || 'created_at',
titleField: schema.timeline?.titleField || schema.options?.timeline?.titleField || 'name',
...(schema.timeline?.endDateField ? { endDateField: schema.timeline.endDateField } : {}),
...(schema.timeline?.groupByField ? { groupByField: schema.timeline.groupByField } : {}),
...(schema.timeline?.colorField ? { colorField: schema.timeline.colorField } : {}),
...(schema.timeline?.scale ? { scale: schema.timeline.scale } : {}),
};
}
case 'gantt':
return {
type: 'object-gantt',
...baseProps,
startDateField: schema.gantt?.startDateField || schema.options?.gantt?.startDateField || 'start_date',
endDateField: schema.gantt?.endDateField || schema.options?.gantt?.endDateField || 'end_date',
progressField: schema.gantt?.progressField || schema.options?.gantt?.progressField || 'progress',
dependenciesField: schema.gantt?.dependenciesField || schema.options?.gantt?.dependenciesField || 'dependencies',
...(schema.gantt?.titleField ? { titleField: schema.gantt.titleField } : {}),
...(schema.options?.gantt || {}),
...(schema.gantt || {}),
};
case 'map':
return {
type: 'object-map',
...baseProps,
locationField: schema.options?.map?.locationField || 'location',
...(schema.options?.map || {}),
};
default:
return baseProps;
}
}, [currentView, schema, currentSort, effectiveFields, groupingConfig, rowColorConfig, navigation.handleClick]);
const hasFilters = currentFilters.conditions && currentFilters.conditions.length > 0;
const filterFields = React.useMemo(() => {
let fields: Array<{ value: string; label: string; type: string; options?: any }>;
if (!objectDef?.fields) {
// Fallback to schema fields if objectDef not loaded yet
fields = (schema.fields || []).map((f: any) => {
if (typeof f === 'string') return { value: f, label: f, type: 'text' };
const fieldName = f.name || f.fieldName;
return {
value: fieldName,
label: tFieldLabel(fieldName, f.label || f.name),
type: f.type || 'text',
options: f.options
};
});
} else {
fields = Object.entries(objectDef.fields).map(([key, field]: [string, any]) => ({
value: key,
label: tFieldLabel(key, field.label || key),
type: field.type || 'text',
options: field.options
}));
}
// Apply filterableFields whitelist restriction
if (schema.filterableFields && schema.filterableFields.length > 0) {
const allowed = new Set(schema.filterableFields);
fields = fields.filter(f => allowed.has(f.value));
}