-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathListView.tsx
More file actions
1185 lines (1081 loc) · 43.7 KB
/
ListView.tsx
File metadata and controls
1185 lines (1081 loc) · 43.7 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, icons, type LucideIcon } from 'lucide-react';
import type { FilterGroup } from '@object-ui/components';
import { ViewSwitcher, ViewType } from './ViewSwitcher';
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 { ExpressionEvaluator } from '@object-ui/core';
import { useObjectTranslation } 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': return '=';
case 'notEquals': return '!=';
case 'contains': return 'contains';
case 'notContains': return 'notcontains';
case 'greaterThan': return '>';
case 'greaterOrEqual': return '>=';
case 'lessThan': return '<';
case 'lessOrEqual': return '<=';
case 'in': return 'in';
case 'notIn': return 'not in';
case 'before': return '<';
case 'after': return '>';
default: return '=';
}
}
/**
* 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;
}
/**
* 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;
// Expression-based evaluation (L2 feature) using safe ExpressionEvaluator
if (rule.expression) {
try {
const evaluator = new ExpressionEvaluator({ data: record });
const result = evaluator.evaluate(rule.expression, { throwOnError: true });
match = result === true;
} catch {
match = false;
}
} else {
// Standard field/operator/value evaluation
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) {
const style: React.CSSProperties = {};
if (rule.backgroundColor) style.backgroundColor = rule.backgroundColor;
if (rule.textColor) style.color = rule.textColor;
if (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.sort': 'Sort',
'list.export': 'Export',
'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.',
};
/**
* 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;
},
};
}
}
export const ListView: React.FC<ListViewProps> = ({
schema: propSchema,
className,
onViewChange,
onFilterChange,
onSortChange,
onSearchChange,
onRowClick,
showViewSwitcher = false,
...props
}) => {
// i18n support for record count and other labels
const { t } = useListViewTranslation();
// Kernel level default: Ensure viewType is always defined (default to 'grid')
const schema = React.useMemo(() => ({
...propSchema,
viewType: propSchema.viewType || 'grid'
}), [propSchema]);
const [currentView, setCurrentView] = React.useState<ViewType>(
(schema.viewType as ViewType)
);
const [searchTerm, setSearchTerm] = React.useState('');
// 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 => ({
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: []
});
// 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 [refreshKey, setRefreshKey] = React.useState(0);
const [dataLimitReached, setDataLimitReached] = React.useState(false);
// 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 => {
if (qf.defaultActive) defaults.add(qf.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: 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);
// 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',
medium: 'comfortable',
tall: 'spacious',
};
return map[schema.rowHeight] || 'comfortable';
}
return 'comfortable';
}, [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;
const fetchObjectDef = async () => {
if (!dataSource || !schema.objectName) 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);
}
};
fetchObjectDef();
return () => { isMounted = false; };
}, [schema.objectName, dataSource]);
// Fetch data effect
React.useEffect(() => {
let isMounted = true;
const requestId = ++fetchRequestIdRef.current;
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 (schema.quickFilters && activeQuickFilters.size > 0) {
schema.quickFilters.forEach(qf => {
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;
// Configurable page size from schema.pagination, default 100
const pageSize = schema.pagination?.pageSize || 100;
const results = await dataSource.find(schema.objectName, {
$filter: finalFilter,
$orderby: sort,
$top: pageSize,
});
// 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;
}
}
setData(items);
setDataLimitReached(items.length >= pageSize);
} 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, dataSource, schema.filters, schema.pagination?.pageSize, currentSort, currentFilters, activeQuickFilters, userFilterConditions, refreshKey]); // Re-fetch on filter/sort change
// Available view types based on schema configuration
const availableViews = React.useMemo(() => {
const views: ViewType[] = ['grid'];
// Check for Kanban capabilities
if (schema.options?.kanban?.groupField) {
views.push('kanban');
}
// Check for Gallery capabilities
if (schema.options?.gallery?.imageField) {
views.push('gallery');
}
// Check for Calendar capabilities
if (schema.options?.calendar?.startDateField) {
views.push('calendar');
}
// Check for Timeline capabilities
if (schema.options?.timeline?.startDateField || schema.options?.timeline?.dateField || schema.options?.calendar?.startDateField) {
views.push('timeline');
}
// Check for Gantt capabilities
if (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
// This ensures that if a view is configured as "map", the map button is shown even if we missed the options check above
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]);
// 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,
};
switch (currentView) {
case 'grid':
return {
type: 'object-grid',
...baseProps,
columns: effectiveFields,
...(schema.conditionalFormatting ? { conditionalFormatting: schema.conditionalFormatting } : {}),
...(schema.inlineEdit != null ? { editable: schema.inlineEdit } : {}),
...(schema.options?.grid || {}),
};
case 'kanban':
return {
type: 'object-kanban',
...baseProps,
groupBy: schema.options?.kanban?.groupField || 'status',
groupField: schema.options?.kanban?.groupField || 'status',
titleField: schema.options?.kanban?.titleField || 'name',
cardFields: effectiveFields || [],
...(schema.options?.kanban || {}),
};
case 'calendar':
return {
type: 'object-calendar',
...baseProps,
startDateField: schema.options?.calendar?.startDateField || 'start_date',
endDateField: schema.options?.calendar?.endDateField || 'end_date',
titleField: schema.options?.calendar?.titleField || 'name',
...(schema.options?.calendar || {}),
};
case 'gallery':
return {
type: 'object-gallery',
...baseProps,
imageField: schema.options?.gallery?.imageField,
titleField: schema.options?.gallery?.titleField || 'name',
subtitleField: schema.options?.gallery?.subtitleField,
...(schema.options?.gallery || {}),
};
case 'timeline':
return {
type: 'object-timeline',
...baseProps,
startDateField: schema.options?.timeline?.startDateField || schema.options?.timeline?.dateField || 'created_at',
titleField: schema.options?.timeline?.titleField || 'name',
...(schema.options?.timeline || {}),
};
case 'gantt':
return {
type: 'object-gantt',
...baseProps,
startDateField: schema.options?.gantt?.startDateField || 'start_date',
endDateField: schema.options?.gantt?.endDateField || 'end_date',
progressField: schema.options?.gantt?.progressField || 'progress',
dependenciesField: schema.options?.gantt?.dependenciesField || 'dependencies',
...(schema.options?.gantt || {}),
};
case 'map':
return {
type: 'object-map',
...baseProps,
locationField: schema.options?.map?.locationField || 'location',
...(schema.options?.map || {}),
};
default:
return baseProps;
}
}, [currentView, schema, currentSort, effectiveFields]);
const hasFilters = currentFilters.conditions && currentFilters.conditions.length > 0;
const filterFields = React.useMemo(() => {
if (!objectDef?.fields) {
// Fallback to schema fields if objectDef not loaded yet
return (schema.fields || []).map((f: any) => {
if (typeof f === 'string') return { value: f, label: f, type: 'text' };
return {
value: f.name || f.fieldName,
label: f.label || f.name,
type: f.type || 'text',
options: f.options
};
});
}
return Object.entries(objectDef.fields).map(([key, field]: [string, any]) => ({
value: key,
label: field.label || key,
type: field.type || 'text',
options: field.options
}));
}, [objectDef, schema.fields]);
const [searchExpanded, setSearchExpanded] = React.useState(false);
// Quick filter toggle handler
const toggleQuickFilter = React.useCallback((id: string) => {
setActiveQuickFilters(prev => {
const next = new Set(prev);
if (next.has(id)) {
next.delete(id);
} else {
next.add(id);
}
return next;
});
}, []);
// Export handler
const handleExport = React.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;
if (format === 'csv') {
const fields = effectiveFields.map((f: any) => typeof f === 'string' ? f : (f.name || f.fieldName || f.field));
const rows: string[] = [];
if (includeHeaders) {
rows.push(fields.join(','));
}
exportData.forEach(record => {
rows.push(fields.map((f: string) => {
const val = record[f];
// Type-safe serialization: handle arrays, objects, null/undefined
let str: string;
if (val == null) {
str = '';
} else if (Array.isArray(val)) {
str = val.map(v =>
(v != null && typeof v === 'object') ? JSON.stringify(v) : String(v ?? ''),
).join('; ');
} else if (typeof val === 'object') {
str = JSON.stringify(val);
} else {
str = String(val);
}
// Escape CSV special characters
const needsQuoting = str.includes(',') || str.includes('"')
|| str.includes('\n') || str.includes('\r');
return needsQuoting ? `"${str.replace(/"/g, '""')}"` : str;
}).join(','));
});
const blob = new Blob([rows.join('\n')], { type: 'text/csv;charset=utf-8;' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `${prefix}.csv`;
a.click();
URL.revokeObjectURL(url);
} else if (format === 'json') {
const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `${prefix}.json`;
a.click();
URL.revokeObjectURL(url);
}
setShowExport(false);
}, [data, effectiveFields, schema.exportOptions, schema.objectName]);
// All available fields for hide/show
const allFields = React.useMemo(() => {
return (schema.fields || []).map((f: any) => {
if (typeof f === 'string') return { name: f, label: f };
return { name: f.name || f.fieldName || f.field, label: f.label || f.name || f.field };
});
}, [schema.fields]);
return (
<div
ref={pullRef}
className={cn('flex flex-col h-full bg-background relative', className)}
{...(schema.aria?.label ? { 'aria-label': schema.aria.label } : {})}
{...(schema.aria?.describedBy ? { 'aria-describedby': schema.aria.describedBy } : {})}
{...(schema.aria?.live ? { 'aria-live': schema.aria.live } : {})}
role="region"
>
{pullDistance > 0 && (
<div
className="flex items-center justify-center text-xs text-muted-foreground"
style={{ height: pullDistance }}
>
{isRefreshing ? 'Refreshing…' : 'Pull to refresh'}
</div>
)}
{/* Airtable-style Toolbar — Row 1: View tabs */}
{showViewSwitcher && (
<div className="border-b px-4 py-1 flex items-center bg-background">
<ViewSwitcher
currentView={currentView}
availableViews={availableViews}
onViewChange={handleViewChange}
/>
</div>
)}
{/* Airtable-style Toolbar — Row 2: Tool buttons */}
<div className="border-b px-2 sm:px-4 py-1 flex items-center justify-between gap-1 sm:gap-2 bg-background">
<div className="flex items-center gap-0.5 overflow-hidden flex-1 min-w-0">
{/* Hide Fields */}
<Popover open={showHideFields} onOpenChange={setShowHideFields}>
<PopoverTrigger asChild>
<Button
variant="ghost"
size="sm"
className={cn(
"h-7 px-2 text-muted-foreground hover:text-primary text-xs",
hiddenFields.size > 0 && "text-primary"
)}
>
<EyeOff className="h-3.5 w-3.5 mr-1.5" />
<span className="hidden sm:inline">Hide fields</span>
{hiddenFields.size > 0 && (
<span className="ml-1 flex h-4 min-w-[16px] items-center justify-center rounded-full bg-primary/10 text-[10px] font-medium text-primary">
{hiddenFields.size}
</span>
)}
</Button>
</PopoverTrigger>
<PopoverContent align="start" className="w-64 p-3">
<div className="space-y-2">
<div className="flex items-center justify-between border-b pb-2">
<h4 className="font-medium text-sm">Hide Fields</h4>
{hiddenFields.size > 0 && (
<Button variant="ghost" size="sm" className="h-6 px-2 text-xs" onClick={() => setHiddenFields(new Set())}>
Show all
</Button>
)}
</div>
<div className="max-h-60 overflow-y-auto space-y-1">
{allFields.map(field => (
<label key={field.name} className="flex items-center gap-2 text-sm py-1 px-1 rounded hover:bg-muted cursor-pointer">
<input
type="checkbox"
checked={!hiddenFields.has(field.name)}
onChange={() => {
setHiddenFields(prev => {
const next = new Set(prev);
if (next.has(field.name)) {
next.delete(field.name);
} else {
next.add(field.name);
}
return next;
});
}}
className="rounded border-input"
/>
<span className="truncate">{field.label}</span>
</label>
))}
</div>
</div>
</PopoverContent>
</Popover>
{/* Filter */}
<Popover open={showFilters} onOpenChange={setShowFilters}>
<PopoverTrigger asChild>
<Button
variant="ghost"
size="sm"
className={cn(
"h-7 px-2 text-muted-foreground hover:text-primary text-xs",
hasFilters && "text-primary"
)}
>
<SlidersHorizontal className="h-3.5 w-3.5 mr-1.5" />
<span className="hidden sm:inline">Filter</span>
{hasFilters && (
<span className="ml-1 flex h-4 min-w-[16px] items-center justify-center rounded-full bg-primary/10 text-[10px] font-medium text-primary">
{currentFilters.conditions?.length || 0}
</span>
)}
</Button>
</PopoverTrigger>
<PopoverContent align="start" className="w-[calc(100vw-2rem)] sm:w-[600px] max-w-[600px] p-3 sm:p-4">
<div className="space-y-4">
<div className="flex items-center justify-between border-b pb-2">
<h4 className="font-medium text-sm">Filter Records</h4>
</div>
<FilterBuilder
fields={filterFields}
value={currentFilters}
onChange={(newFilters) => {
setCurrentFilters(newFilters);
if (onFilterChange) onFilterChange(newFilters);
}}
/>
</div>
</PopoverContent>
</Popover>
{/* Group */}
<Button
variant="ghost"
size="sm"
className="h-7 px-2 text-muted-foreground hover:text-primary text-xs"
disabled
>
<Group className="h-3.5 w-3.5 mr-1.5" />
<span className="hidden sm:inline">Group</span>
</Button>
{/* Sort */}
<Popover open={showSort} onOpenChange={setShowSort}>
<PopoverTrigger asChild>
<Button
variant="ghost"
size="sm"
className={cn(
"h-7 px-2 text-muted-foreground hover:text-primary text-xs",
currentSort.length > 0 && "text-primary"
)}
>
<ArrowUpDown className="h-3.5 w-3.5 mr-1.5" />
<span className="hidden sm:inline">Sort</span>
{currentSort.length > 0 && (
<span className="ml-1 flex h-4 min-w-[16px] items-center justify-center rounded-full bg-primary/10 text-[10px] font-medium text-primary">
{currentSort.length}
</span>
)}
</Button>
</PopoverTrigger>
<PopoverContent align="start" className="w-[calc(100vw-2rem)] sm:w-[600px] max-w-[600px] p-3 sm:p-4">
<div className="space-y-4">
<div className="flex items-center justify-between border-b pb-2">
<h4 className="font-medium text-sm">Sort Records</h4>
</div>
<SortBuilder
fields={filterFields}
value={currentSort}
onChange={(newSort) => {
setCurrentSort(newSort);
if (onSortChange) onSortChange(newSort);
}}
/>
</div>
</PopoverContent>
</Popover>
{/* Color */}
<Button
variant="ghost"
size="sm"
className="h-7 px-2 text-muted-foreground hover:text-primary text-xs"
disabled
>
<Paintbrush className="h-3.5 w-3.5 mr-1.5" />
<span className="hidden sm:inline">Color</span>
</Button>
{/* Row Height / Density Mode */}
<Button
variant="ghost"
size="sm"
className="h-7 px-2 text-muted-foreground hover:text-primary text-xs hidden lg:flex"
onClick={density.cycle}
title={`Density: ${density.mode}`}
>
<AlignJustify className="h-3.5 w-3.5 mr-1.5" />
<span className="hidden sm:inline capitalize">{density.mode}</span>
</Button>
{/* Export */}
{schema.exportOptions && (
<Popover open={showExport} onOpenChange={setShowExport}>
<PopoverTrigger asChild>
<Button
variant="ghost"
size="sm"
className="h-7 px-2 text-muted-foreground hover:text-primary text-xs"
>
<Download className="h-3.5 w-3.5 mr-1.5" />
<span className="hidden sm:inline">Export</span>
</Button>
</PopoverTrigger>
<PopoverContent align="start" className="w-48 p-2">
<div className="space-y-1">
{(schema.exportOptions.formats || ['csv', 'json']).map(format => (
<Button
key={format}
variant="ghost"
size="sm"