-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathListView.tsx
More file actions
653 lines (594 loc) · 23.1 KB
/
ListView.tsx
File metadata and controls
653 lines (594 loc) · 23.1 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
/**
* 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, icons, type LucideIcon } from 'lucide-react';
import type { FilterGroup } from '@object-ui/components';
import { ViewSwitcher, ViewType } from './ViewSwitcher';
import { SchemaRenderer, useNavigationOverlay } from '@object-ui/react';
import type { ListViewSchema } from '@object-ui/types';
import { usePullToRefresh } from '@object-ui/mobile';
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 '=';
}
}
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];
});
if (conditions.length === 1) return conditions[0];
return [group.logic, ...conditions];
}
export const ListView: React.FC<ListViewProps> = ({
schema: propSchema,
className,
onViewChange,
onFilterChange,
onSortChange,
onSearchChange,
onRowClick,
showViewSwitcher = false,
...props
}) => {
// 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 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 fetchData = async () => {
if (!dataSource || !schema.objectName) return;
setLoading(true);
try {
// Construct filter
let finalFilter: any = [];
const baseFilter = schema.filters || [];
const userFilter = convertFilterGroupToAST(currentFilters);
// Merge base filters and user filters
if (baseFilter.length > 0 && userFilter.length > 0) {
finalFilter = ['and', baseFilter, userFilter];
} else if (userFilter.length > 0) {
finalFilter = userFilter;
} else {
finalFilter = baseFilter;
}
// 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: 100 // Default pagination limit
});
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;
}
}
if (isMounted) {
setData(items);
}
} catch (err) {
console.error("ListView data fetch error:", err);
} finally {
if (isMounted) setLoading(false);
}
};
fetchData();
return () => { isMounted = false; };
}, [schema.objectName, dataSource, schema.filters, currentSort, currentFilters, 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,
});
// Generate the appropriate view component schema
const viewComponentSchema = React.useMemo(() => {
const baseProps = {
objectName: schema.objectName,
fields: schema.fields,
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: schema.fields,
...(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: schema.fields || [],
...(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]);
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);
return (
<div ref={pullRef} className={cn('flex flex-col h-full bg-background relative', className)}>
{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 */}
<Button
variant="ghost"
size="sm"
className="h-7 px-2 text-muted-foreground hover:text-primary text-xs"
disabled
>
<EyeOff className="h-3.5 w-3.5 mr-1.5" />
<span className="hidden sm:inline">Hide fields</span>
</Button>
{/* 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 */}
<Button
variant="ghost"
size="sm"
className="h-7 px-2 text-muted-foreground hover:text-primary text-xs hidden lg:flex"
disabled
>
<Ruler className="h-3.5 w-3.5 mr-1.5" />
<span className="hidden sm:inline">Row height</span>
</Button>
</div>
{/* Right: Search */}
<div className="flex items-center gap-1">
{searchExpanded ? (
<div className="relative w-36 sm:w-48 lg:w-64">
<Search className="absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground" />
<Input
placeholder="Find..."
value={searchTerm}
onChange={(e) => handleSearchChange(e.target.value)}
className="pl-7 h-7 text-xs bg-muted/50 border-transparent hover:bg-muted focus:bg-background focus:border-input transition-colors"
autoFocus
onBlur={() => {
if (!searchTerm) setSearchExpanded(false);
}}
/>
<Button
variant="ghost"
size="sm"
className="absolute right-0.5 top-1/2 -translate-y-1/2 h-5 w-5 p-0 hover:bg-muted-foreground/20"
onClick={() => {
handleSearchChange('');
setSearchExpanded(false);
}}
>
<X className="h-3 w-3" />
</Button>
</div>
) : (
<Button
variant="ghost"
size="sm"
className="h-7 px-2 text-muted-foreground hover:text-primary text-xs"
onClick={() => setSearchExpanded(true)}
>
<Search className="h-3.5 w-3.5 mr-1.5" />
<span className="hidden sm:inline">Search</span>
</Button>
)}
</div>
</div>
{/* Filters Panel - Removed as it is now in Popover */}
{/* View Content */}
<div key={currentView} className="flex-1 min-h-0 bg-background relative overflow-hidden animate-in fade-in-0 duration-200">
{!loading && data.length === 0 ? (
(() => {
const iconName = schema.emptyState?.icon;
const ResolvedIcon: LucideIcon = iconName
? ((icons as Record<string, LucideIcon>)[
iconName.split('-').map(w => w.charAt(0).toUpperCase() + w.slice(1)).join('')
] ?? Inbox)
: Inbox;
return (
<div className="flex flex-col items-center justify-center h-full min-h-[200px] text-center p-8" data-testid="empty-state">
<ResolvedIcon className="h-12 w-12 text-muted-foreground/50 mb-4" />
<h3 className="text-lg font-medium text-foreground mb-1">
{(typeof schema.emptyState?.title === 'string' ? schema.emptyState.title : undefined) ?? 'No items found'}
</h3>
<p className="text-sm text-muted-foreground max-w-md">
{(typeof schema.emptyState?.message === 'string' ? schema.emptyState.message : undefined) ?? 'There are no records to display. Try adjusting your filters or adding new data.'}
</p>
</div>
);
})()
) : (
<SchemaRenderer
schema={viewComponentSchema}
{...props}
data={data}
loading={loading}
/>
)}
</div>
{/* Navigation Overlay (drawer/modal/popover) */}
{navigation.isOverlay && (
<NavigationOverlay
{...navigation}
title={
schema.label
? `${schema.label} Detail`
: schema.objectName
? `${schema.objectName.charAt(0).toUpperCase() + schema.objectName.slice(1)} Detail`
: 'Record Detail'
}
>
{(record) => (
<div className="space-y-3">
{Object.entries(record).map(([key, value]) => (
<div key={key} className="flex flex-col">
<span className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
{key.replace(/_/g, ' ')}
</span>
<span className="text-sm">{String(value ?? '—')}</span>
</div>
))}
</div>
)}
</NavigationOverlay>
)}
</div>
);
};