-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathObjectView.tsx
More file actions
1285 lines (1186 loc) · 49.2 KB
/
Copy pathObjectView.tsx
File metadata and controls
1285 lines (1186 loc) · 49.2 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.
*/
/**
* ObjectView Component
*
* A complete object management interface that combines multi-view data display
* (grid, kanban, calendar, gallery, timeline, gantt, map) with ObjectForm
* for create/edit operations.
*
* Features:
* - Multi-view type rendering via SchemaRenderer
* - Named listViews support (e.g., "All", "My Records", "Active")
* - Navigation config for row click behavior (page/drawer/modal/none/new_window)
* - Direct data fetching for all view types
* - Integrated search, filter, and sort controls
* - ViewSwitcher for toggling between view types
*/
import React, { useEffect, useState, useCallback, useMemo, useRef } from 'react';
import type {
ObjectViewSchema,
ObjectGridSchema,
ObjectFormSchema,
DataSource,
ViewSwitcherSchema,
FilterUISchema,
SortUISchema,
ViewType,
NamedListView,
ViewNavigationConfig,
} from '@object-ui/types';
import { ObjectGrid } from '@object-ui/plugin-grid';
import { ObjectForm } from '@object-ui/plugin-form';
import {
cn,
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogDescription,
Drawer,
DrawerContent,
DrawerHeader,
DrawerTitle,
DrawerDescription,
NavigationOverlay,
Button,
Tabs,
TabsList,
TabsTrigger,
useIsMobile,
} from '@object-ui/components';
import { Plus } from 'lucide-react';
import { useObjectTranslation } from '@object-ui/i18n';
import { buildExpandFields } from '@object-ui/core';
import { SchemaRenderer as ImportedSchemaRenderer } from '@object-ui/react';
import { ViewSwitcher } from './ViewSwitcher';
import { deriveRecordSurface } from './recordSurface';
/**
* SchemaRenderer from @object-ui/react, used to render sub-view schemas.
*/
const SchemaRendererComponent: React.FC<any> = ImportedSchemaRenderer;
/**
* Record-create verb, shared with the runtime object pages: both surfaces
* resolve `console.objectView.new` ("New" / 新建) so the Studio grid toolbar
* and the running app never disagree (framework#2615 P3). Falls back to
* English when no I18nProvider is mounted (standalone usage) — via the
* key-identity probe, not a caught throw.
*/
function useCreateVerb(): string {
// No try/catch: `useObjectTranslation` is provider-safe (optional context
// read + react-i18next global-instance fallback) and never throws, so the
// key-identity probe below is the whole "no provider" path. Wrapping a hook
// in try/catch violates rules-of-hooks — a throw after it ran would desync
// hook order on the next render (objectui#2879, same class as #2595/#2596).
const { t } = useObjectTranslation();
const value = t('console.objectView.new');
return value === 'console.objectView.new' ? 'New' : value;
}
export interface ObjectViewProps {
/**
* The schema configuration for the view
*/
schema: ObjectViewSchema;
/**
* Data source (ObjectQL or ObjectStack adapter).
* If not provided, falls back to SchemaRendererProvider context.
*/
dataSource: DataSource;
/**
* Additional CSS class
*/
className?: string;
/**
* Views available for the ViewSwitcher.
* Each view defines a type (grid, kanban, calendar, etc.) and display columns/config.
* If not provided, uses schema.listViews or falls back to default grid view.
*/
views?: Array<{
id: string;
label: string;
type: ViewType;
columns?: string[];
sort?: Array<{ field: string; direction: 'asc' | 'desc' }>;
filter?: any[];
[key: string]: any;
}>;
/**
* The currently active view ID.
* Used for controlled ViewSwitcher state.
*/
activeViewId?: string;
/**
* Callback when the active view changes
*/
onViewChange?: (viewId: string) => void;
/**
* Callback when a row is clicked (for record detail navigation)
*/
onRowClick?: (record: Record<string, unknown>) => void;
/**
* Callback when edit is triggered on a record
*/
onEdit?: (record: Record<string, unknown>) => void;
/**
* Render a custom ListView implementation for multi-view support.
* When provided, this replaces the default view rendering for the content area.
*/
/**
* ADR-0053: when the host (app-shell ObjectView) already renders the view
* switcher (ViewTabBar), set this so the inner view doesn't render its own
* duplicate named-view tab row. Standalone consumers leave it unset.
*/
hideNamedViewTabs?: boolean;
renderListView?: (props: {
schema: any;
dataSource: DataSource;
onEdit?: (record: Record<string, unknown>) => void;
onRowClick?: (record: Record<string, unknown>) => void;
className?: string;
/** Current refresh counter — increment signals that a mutation occurred */
refreshKey?: number;
/** Same handler the built-in toolbar's "+ New" button uses — forward it
* into the custom list view's own add-record affordance (e.g. ListView's
* `addRecord.enabled` toolbar button) so callers can fold record creation
* into their list's toolbar instead of the separate `showCreate` row. */
onAddRecord?: () => void;
}) => React.ReactNode;
/**
* Toolbar addon: extra elements to render in the toolbar (e.g., MetadataToggle)
*/
toolbarAddon?: React.ReactNode;
/**
* Callback when the "+" create view button is clicked in ViewSwitcher.
*/
onCreateView?: () => void;
/**
* Callback when a per-view action is triggered in ViewSwitcher.
*/
onViewAction?: (action: string, viewType: ViewType) => void;
}
type FormMode = 'create' | 'edit' | 'view';
/**
* ObjectView Component
*
* Renders a complete object management interface with multi-view rendering
* and integrated CRUD operations.
*
* @example Basic usage (grid only)
* ```tsx
* <ObjectView
* schema={{
* type: 'object-view',
* objectName: 'users',
* layout: 'drawer',
* showSearch: true,
* showFilters: true,
* }}
* dataSource={dataSource}
* />
* ```
*
* @example Named listViews
* ```tsx
* <ObjectView
* schema={{
* type: 'object-view',
* objectName: 'contacts',
* listViews: {
* all: { label: 'All Contacts', type: 'grid', columns: ['name', 'email', 'phone'] },
* board: { label: 'By Status', type: 'kanban', options: { kanban: { groupField: 'status' } } },
* calendar: { label: 'Meetings', type: 'calendar', options: { calendar: { startDateField: 'meeting_date' } } },
* },
* defaultListView: 'all',
* }}
* dataSource={dataSource}
* />
* ```
*
* @example With navigation config
* ```tsx
* <ObjectView
* schema={{
* type: 'object-view',
* objectName: 'accounts',
* navigation: { mode: 'drawer', width: '600px' },
* }}
* dataSource={dataSource}
* />
* ```
*/
export const ObjectView: React.FC<ObjectViewProps> = ({
schema,
dataSource,
className,
views: viewsProp,
activeViewId,
onViewChange,
onRowClick,
onEdit: onEditProp,
renderListView,
hideNamedViewTabs,
toolbarAddon,
onCreateView,
onViewAction,
}) => {
const createVerb = useCreateVerb();
const [objectSchema, setObjectSchema] = useState<Record<string, unknown> | null>(null);
// Assigned in the render body (not in an effect) so the fetchData effect always
// reads the latest objectSchema without needing it as a dependency. This matches
// the same pattern used in ObjectCalendar's objectSchemaRef.
const objectSchemaRef = useRef<Record<string, unknown> | null>(null);
objectSchemaRef.current = objectSchema;
const [isFormOpen, setIsFormOpen] = useState(false);
const [formMode, setFormMode] = useState<FormMode>('create');
const [selectedRecord, setSelectedRecord] = useState<Record<string, unknown> | null>(null);
const [refreshKey, setRefreshKey] = useState(0);
// P2: Auto-subscribe to DataSource mutation events for non-grid views.
// When a DataSource implements onMutation(), ObjectView auto-refreshes
// its own data fetch (for non-grid view types like kanban, calendar, etc.)
// whenever a create/update/delete occurs on the same objectName.
//
// ListView-driven configurations already manage refreshKey via
// form success / delete handlers. To avoid double refreshes and
// duplicate find() calls, skip auto-subscription when renderListView is provided.
useEffect(() => {
if (!dataSource?.onMutation || !schema.objectName) return;
if (renderListView) return;
const unsub = dataSource.onMutation((event: any) => {
if (event.resource === schema.objectName) {
setRefreshKey(prev => prev + 1);
}
});
return unsub;
}, [dataSource, schema.objectName, renderListView]);
// Data fetching state for non-grid views
const [data, setData] = useState<any[]>([]);
const [loading, setLoading] = useState(false);
// Filter & Sort state
const [filterValues, setFilterValues] = useState<Record<string, any>>({});
const [sortConfig, setSortConfig] = useState<Array<{ field: string; direction: 'asc' | 'desc' }>>([]);
// --- Named listViews ---
const namedListViews = schema.listViews;
const hasNamedViews = namedListViews != null && Object.keys(namedListViews).length > 0;
const [activeNamedView, setActiveNamedView] = useState<string>(() => {
if (schema.defaultListView && namedListViews?.[schema.defaultListView]) {
return schema.defaultListView;
}
if (namedListViews) {
const keys = Object.keys(namedListViews);
return keys[0] || '';
}
return '';
});
// Get current named view config
const currentNamedViewConfig: NamedListView | null = useMemo(() => {
if (!hasNamedViews || !activeNamedView) return null;
return namedListViews![activeNamedView] || null;
}, [hasNamedViews, activeNamedView, namedListViews]);
// --- Multi-view type state (prop-based views) ---
const viewsPropResolved = useMemo(() => {
if (viewsProp && viewsProp.length > 0) return viewsProp;
return null;
}, [viewsProp]);
const hasMultiView = viewsPropResolved != null && viewsPropResolved.length > 0;
const currentActiveViewId = activeViewId || viewsPropResolved?.[0]?.id;
const activeView = viewsPropResolved?.find(v => v.id === currentActiveViewId) || viewsPropResolved?.[0];
// Current view type from named view, multi-view prop, or default
const currentViewType: string = useMemo(() => {
if (currentNamedViewConfig?.type) return currentNamedViewConfig.type;
if (activeView?.type) return activeView.type;
return schema.defaultViewType || 'grid';
}, [currentNamedViewConfig, activeView, schema.defaultViewType]);
// Navigation config
const navigationConfig: ViewNavigationConfig | undefined = schema.navigation;
// Fetch object schema from ObjectQL/ObjectStack
useEffect(() => {
let isMounted = true;
const fetchObjectSchema = async () => {
try {
const schemaData = await dataSource.getObjectSchema(schema.objectName);
if (isMounted) setObjectSchema(schemaData);
} catch (err) {
console.error('Failed to fetch object schema:', err);
}
};
if (schema.objectName && dataSource) {
fetchObjectSchema();
}
return () => { isMounted = false; };
}, [schema.objectName, dataSource]);
// Fetch data for non-grid view types (grid handles its own data via ObjectGrid)
useEffect(() => {
let isMounted = true;
const fetchData = async () => {
// When renderListView is provided, the custom list view (e.g. ListView)
// handles its own data fetching — skip to avoid duplicate requests and
// unnecessary re-renders that can cause duplicate records in child views.
if (renderListView) return;
// Only fetch for non-grid views (ObjectGrid has its own data fetching)
if (currentViewType === 'grid') return;
if (!dataSource || !schema.objectName) return;
setLoading(true);
try {
// Build filter
const baseFilter = currentNamedViewConfig?.filter || activeView?.filter || schema.table?.defaultFilters || [];
const userFilter = Object.entries(filterValues)
.filter(([, v]) => v !== undefined && v !== '' && v !== null)
.map(([field, value]) => [field, '=', value]);
let finalFilter: any = [];
if (baseFilter.length > 0 && userFilter.length > 0) {
finalFilter = ['and', ...baseFilter, ...userFilter];
} else if (userFilter.length === 1) {
finalFilter = userFilter[0];
} else if (userFilter.length > 1) {
finalFilter = ['and', ...userFilter];
} else {
finalFilter = baseFilter;
}
// Build sort
const sort = sortConfig.length > 0
? sortConfig.map(s => ({ field: s.field, order: s.direction }))
: (currentNamedViewConfig?.sort || activeView?.sort || schema.table?.defaultSort || undefined);
// Auto-inject $expand for lookup/master_detail fields.
// Use a ref instead of the state variable to avoid re-running this effect
// every time the object schema loads — that would cause a double-fetch and
// duplicate events in child views like the calendar.
const expand = buildExpandFields((objectSchemaRef.current as any)?.fields);
const results = await dataSource.find(schema.objectName, {
$filter: finalFilter.length > 0 ? finalFilter : undefined,
$orderby: sort,
$top: 100,
...(expand.length > 0 ? { $expand: expand } : {}),
});
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;
}
}
if (isMounted) setData(items);
} catch (err) {
console.error('ObjectView data fetch error:', err);
} finally {
if (isMounted) setLoading(false);
}
};
fetchData();
return () => { isMounted = false; };
// objectSchema intentionally omitted from deps — read via ref to prevent double-fetch
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [schema.objectName, dataSource, currentViewType, filterValues, sortConfig, refreshKey, currentNamedViewConfig, activeView, renderListView]);
// Determine layout mode. #2578: default the record surface from how heavy the
// object is — a field-heavy object opens create/edit/detail as a full page, a
// light one as a drawer. Mobile always pages. An explicit `schema.layout` (or
// a per-view navigation config, handled in handleRowClick) still wins.
const isMobile = useIsMobile();
const layout = schema.layout || deriveRecordSurface(objectSchema, { viewport: isMobile ? 'mobile' : 'desktop' });
// Determine enabled operations
const operations = schema.operations || schema.table?.operations || {
create: true,
read: true,
update: true,
delete: true,
};
// Handle create action
const handleCreate = useCallback(() => {
if (layout === 'page' && schema.onNavigate) {
schema.onNavigate('new', 'edit');
} else {
setFormMode('create');
setSelectedRecord(null);
setIsFormOpen(true);
}
}, [layout, schema]);
// Handle edit action
const handleEdit = useCallback((record: Record<string, unknown>) => {
if (onEditProp) {
onEditProp(record);
return;
}
if (layout === 'page' && schema.onNavigate) {
const recordId = record.id || record._id;
schema.onNavigate(recordId as string | number, 'edit');
} else {
setFormMode('edit');
setSelectedRecord(record);
setIsFormOpen(true);
}
}, [layout, schema, onEditProp]);
// Handle view action (read a record)
const handleView = useCallback((record: Record<string, unknown>) => {
if (layout === 'page' && schema.onNavigate) {
const recordId = record.id || record._id;
schema.onNavigate(recordId as string | number, 'view');
} else {
setFormMode('view');
setSelectedRecord(record);
setIsFormOpen(true);
}
}, [layout, schema]);
// Handle row click - respects NavigationConfig
const handleRowClick = useCallback((record: Record<string, unknown>) => {
if (onRowClick) {
onRowClick(record);
return;
}
// Check NavigationConfig
if (navigationConfig) {
if (navigationConfig.mode === 'none' || navigationConfig.preventNavigation) {
return; // Do nothing
}
if (navigationConfig.mode === 'new_window' || navigationConfig.openNewTab) {
const recordId = record.id || record._id;
const url = `/${schema.objectName}/${encodeURIComponent(String(recordId))}`;
window.open(url, '_blank');
return;
}
if (navigationConfig.mode === 'drawer') {
setFormMode('view');
setSelectedRecord(record);
setIsFormOpen(true);
return;
}
if (navigationConfig.mode === 'modal') {
setFormMode('view');
setSelectedRecord(record);
setIsFormOpen(true);
return;
}
if (navigationConfig.mode === 'page') {
const recordId = record.id || record._id;
if (schema.onNavigate) {
schema.onNavigate(recordId as string | number, 'view');
}
return;
}
if (navigationConfig.mode === 'split' || navigationConfig.mode === 'popover') {
setFormMode('view');
setSelectedRecord(record);
setIsFormOpen(true);
return;
}
}
// Default behavior
if (operations.read !== false) {
handleView(record);
}
}, [onRowClick, navigationConfig, operations.read, handleView, schema]);
// Handle delete action
const handleDelete = useCallback((_record: Record<string, unknown>) => {
setRefreshKey(prev => prev + 1);
}, []);
// Handle bulk delete action
const handleBulkDelete = useCallback((_records: Record<string, unknown>[]) => {
setRefreshKey(prev => prev + 1);
}, []);
// Handle form submission
const handleFormSuccess = useCallback(() => {
setIsFormOpen(false);
setSelectedRecord(null);
setRefreshKey(prev => prev + 1);
}, []);
// Handle form cancellation
const handleFormCancel = useCallback(() => {
setIsFormOpen(false);
setSelectedRecord(null);
}, []);
// Handle refresh
const handleRefresh = useCallback(() => {
setRefreshKey(prev => prev + 1);
}, []);
// --- ViewSwitcher schema (for multi-view prop views) ---
const viewSwitcherSchema: ViewSwitcherSchema | null = useMemo(() => {
if (!hasMultiView || !viewsPropResolved || viewsPropResolved.length <= 1) return null;
return {
type: 'view-switcher' as const,
variant: 'tabs',
position: 'top',
persistPreference: true,
storageKey: `view-pref-${schema.objectName}`,
defaultView: (activeView?.type || 'grid') as ViewType,
activeView: (activeView?.type || 'grid') as ViewType,
views: viewsPropResolved.map(v => {
const iconMap: Record<string, string> = {
kanban: 'kanban',
calendar: 'calendar',
map: 'map',
gallery: 'layout-grid',
timeline: 'activity',
gantt: 'gantt-chart',
grid: 'table',
list: 'list',
detail: 'file-text',
chart: 'bar-chart-3',
};
return {
type: v.type as ViewType,
label: v.label,
icon: iconMap[v.type] || 'table',
};
}),
allowCreateView: schema.allowCreateView,
viewActions: schema.viewActions,
};
}, [hasMultiView, viewsPropResolved, activeView, schema.objectName, schema.allowCreateView, schema.viewActions]);
// Handle view type change from ViewSwitcher → map back to view ID
const handleViewTypeChange = useCallback((viewType: ViewType) => {
if (!viewsPropResolved) return;
const matched = viewsPropResolved.find(v => v.type === viewType);
if (matched && onViewChange) {
onViewChange(matched.id);
}
}, [viewsPropResolved, onViewChange]);
// Handle named view change
const handleNamedViewChange = useCallback((viewKey: string) => {
setActiveNamedView(viewKey);
}, []);
// --- FilterUI schema (auto-generated from objectSchema or filterableFields) ---
const filterSchema: FilterUISchema | null = useMemo(() => {
if (schema.showFilters === false) return null;
// If filterableFields specified, use only those
const filterableFieldNames = schema.filterableFields;
const fields = (objectSchema as any)?.fields || {};
const fieldEntries = filterableFieldNames
? filterableFieldNames.map(name => [name, fields[name] || { label: name }] as [string, any])
: Object.entries(fields).filter(([, f]: [string, any]) => !f.hidden).slice(0, 8);
const filterableFieldDefs = fieldEntries.map(([key, f]: [string, any]) => {
const fieldType = f.type || 'text';
let filterType: 'text' | 'number' | 'select' | 'multi-select' | 'date' | 'boolean' = 'text';
let options: Array<{ label: string; value: any }> | undefined;
if (fieldType === 'number' || fieldType === 'currency' || fieldType === 'percent') {
filterType = 'number';
} else if (fieldType === 'boolean' || fieldType === 'toggle') {
filterType = 'boolean';
} else if (fieldType === 'date' || fieldType === 'datetime') {
filterType = 'date';
} else if (fieldType === 'select' || fieldType === 'status' || f.options) {
filterType = 'select';
options = (f.options || []).map((o: any) =>
typeof o === 'string' ? { label: o, value: o } : { label: o.label, value: o.value },
);
} else if (fieldType === 'lookup' || fieldType === 'master_detail' || fieldType === 'user' || fieldType === 'owner') {
if (f.options && f.options.length > 0) {
filterType = 'multi-select';
options = (f.options || []).map((o: any) =>
typeof o === 'string' ? { label: o, value: o } : { label: o.label, value: o.value },
);
}
}
return {
field: key,
label: f.label || key,
type: filterType,
placeholder: `Filter ${f.label || key}...`,
...(options ? { options } : {}),
};
});
if (filterableFieldDefs.length === 0) return null;
return {
type: 'filter-ui' as const,
layout: 'popover' as const,
showClear: true,
showApply: true,
filters: filterableFieldDefs,
values: filterValues,
};
}, [schema.showFilters, schema.filterableFields, objectSchema, filterValues]);
// --- SortUI schema ---
const showSort = (schema as ObjectViewSchema).showSort;
const sortSchema: SortUISchema | null = useMemo(() => {
if (showSort === false) return null;
const fields = (objectSchema as any)?.fields || {};
const sortableFields = Object.entries(fields)
.filter(([, f]: [string, any]) => !f.hidden)
.slice(0, 10)
.map(([key, f]: [string, any]) => ({ field: key, label: f.label || key }));
if (sortableFields.length === 0) return null;
return {
type: 'sort-ui' as const,
variant: 'dropdown' as const,
multiple: false,
fields: sortableFields,
sort: sortConfig,
};
}, [objectSchema, sortConfig, showSort]);
// --- Generate view component schema for non-grid views ---
const generateViewSchema = useCallback((viewType: string): any => {
const baseProps: Record<string, any> = {
objectName: schema.objectName,
fields: currentNamedViewConfig?.columns || activeView?.columns || schema.table?.fields,
className: 'h-full w-full',
showSearch: activeView?.showSearch ?? schema.showSearch ?? false,
showSort: activeView?.showSort ?? schema.showSort ?? false,
showFilters: activeView?.showFilters ?? schema.showFilters ?? false,
striped: activeView?.striped ?? false,
bordered: activeView?.bordered ?? false,
color: activeView?.color,
};
// Resolve type-specific options from current named view or active view
// Per @objectstack/spec, type-specific config MUST be nested under the view type key
const viewOptions = currentNamedViewConfig?.options || activeView || {};
// Dev-mode warning for flat property access violations
if (process.env.NODE_ENV === 'development') {
const flatKeys = ['startDateField', 'endDateField', 'dateField', 'groupBy', 'groupField',
'locationField', 'imageField', 'dependenciesField', 'progressField', 'titleField',
'subtitleField', 'latitudeField', 'longitudeField'];
const nestedConfig = viewOptions[viewType] || {};
const found = flatKeys.filter(k => k in viewOptions && !(k in nestedConfig));
if (found.length > 0) {
console.warn(
`[Spec Compliance] View options use flat properties ${JSON.stringify(found)}. ` +
`Move them under options.${viewType} per @objectstack/spec protocol.`
);
}
}
switch (viewType) {
case 'kanban': {
// Per @objectstack/spec, kanban-specific config lives under view.kanban.*
// `groupByField` is the canonical name (spec); `groupField` is a legacy alias.
// `kanban.columns` (when provided) lists the FIELDS to render on each card —
// these are NOT lanes; lanes are derived from the groupBy field's options.
const kanbanCfg = viewOptions.kanban || {};
const groupBy =
kanbanCfg.groupByField ||
kanbanCfg.groupField ||
'status';
// Card display fields: prefer explicit kanban.columns, fall back to the
// view's outer columns. Strip out these from the spread below so they
// don't leak into schema.columns (which the kanban component interprets
// as LANES).
const cardFields: string[] =
(Array.isArray(kanbanCfg.columns) && kanbanCfg.columns.length > 0
? kanbanCfg.columns
: baseProps.fields) || [];
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { columns: _kanbanColumns, groupByField: _gbf, groupField: _gf, titleField: _tf, conditionalFormatting: _kanbanCf, ...restKanban } = kanbanCfg;
// Forward conditional formatting to kanban (issue #1584): nested
// `options.kanban.conditionalFormatting` wins, then the view-level, then
// the schema-level rule — matching how the grid branch resolves it.
// Previously the top-level rule was dropped for kanban entirely.
const kanbanConditionalFormatting =
kanbanCfg.conditionalFormatting ??
activeView?.conditionalFormatting ??
(schema as any).conditionalFormatting;
return {
type: 'object-kanban',
...baseProps,
groupBy,
groupField: groupBy,
titleField: kanbanCfg.titleField || 'name',
cardFields,
...restKanban,
...(kanbanConditionalFormatting ? { conditionalFormatting: kanbanConditionalFormatting } : {}),
};
}
case 'calendar':
return {
type: 'object-calendar',
...baseProps,
startDateField: viewOptions.calendar?.startDateField || 'start_date',
endDateField: viewOptions.calendar?.endDateField || 'end_date',
titleField: viewOptions.calendar?.titleField || 'name',
...(viewOptions.calendar || {}),
};
case 'gallery':
return {
type: 'object-gallery',
...baseProps,
// `coverField` is the spec key; `imageField` is the legacy alias that
// ObjectGallery still consults as a flat prop.
imageField: viewOptions.gallery?.coverField || viewOptions.gallery?.imageField,
titleField: viewOptions.gallery?.titleField || 'name',
...(viewOptions.gallery || {}),
};
case 'timeline':
return {
type: 'object-timeline',
...baseProps,
// `startDateField` is the spec key; `dateField` is the legacy alias.
startDateField: viewOptions.timeline?.startDateField || viewOptions.timeline?.dateField || 'created_at',
titleField: viewOptions.timeline?.titleField || 'name',
...(viewOptions.timeline || {}),
};
case 'gantt':
return {
type: 'object-gantt',
...baseProps,
startDateField: viewOptions.gantt?.startDateField || 'start_date',
endDateField: viewOptions.gantt?.endDateField || 'end_date',
progressField: viewOptions.gantt?.progressField || 'progress',
dependenciesField: viewOptions.gantt?.dependenciesField || 'dependencies',
...(viewOptions.gantt || {}),
};
case 'map':
return {
type: 'object-map',
...baseProps,
locationField: viewOptions.map?.locationField || 'location',
...(viewOptions.map || {}),
};
case 'tree':
return {
type: 'object-tree',
...baseProps,
// Single-parent pointer field; auto-detected from the object's
// `tree`/self-reference field when not specified.
parentField: viewOptions.tree?.parentField,
labelField: viewOptions.tree?.labelField || viewOptions.tree?.titleField || 'name',
// The view's columns double as the tree-grid's flat columns.
fields: viewOptions.tree?.fields || baseProps.fields,
defaultExpandedDepth: viewOptions.tree?.defaultExpandedDepth,
...(viewOptions.tree || {}),
};
case 'chart': {
// Aggregated chart of the object's records, delegating to the same
// object-chart component the dashboard uses.
const chartCfg = viewOptions.chart || {};
// ADR-0021 (#1890): dataset-bound chart — the single author-facing shape.
if (chartCfg.dataset) {
const dims: string[] = Array.isArray(chartCfg.dimensions) ? chartCfg.dimensions : [];
const vals: string[] = Array.isArray(chartCfg.values) ? chartCfg.values : [];
return {
type: 'object-chart',
dataset: chartCfg.dataset,
dimensions: dims,
values: vals,
chartType: chartCfg.chartType || 'bar',
xAxisKey: dims[0],
series: vals.map((v: string) => ({ dataKey: v, label: v })),
className: 'h-[400px] w-full',
};
}
// Legacy inline aggregate (deprecated — pre-ADR-0021 metadata).
const valueField = (Array.isArray(chartCfg.yAxisFields) && chartCfg.yAxisFields[0])
|| chartCfg.valueField || 'value';
const categoryField = chartCfg.xAxisField || chartCfg.categoryField || 'name';
return {
type: 'object-chart',
objectName: schema.objectName,
chartType: chartCfg.chartType || 'bar',
aggregate: {
field: valueField,
function: chartCfg.aggregation || 'count',
groupBy: categoryField,
},
xAxisKey: categoryField,
series: [{ dataKey: valueField, label: valueField }],
className: 'h-[400px] w-full',
};
}
default:
return null;
}
}, [schema.objectName, schema.table?.fields, currentNamedViewConfig, activeView]);
// Build grid schema (default content renderer)
const gridSchema: ObjectGridSchema = useMemo(() => ({
type: 'object-grid',
objectName: schema.objectName,
title: schema.table?.title,
description: schema.table?.description,
fields: currentNamedViewConfig?.columns || activeView?.columns || schema.table?.fields,
columns: currentNamedViewConfig?.columns || activeView?.columns || schema.table?.columns,
operations: {
...operations,
create: false, // Create is handled by the view's create button
},
defaultFilters: currentNamedViewConfig?.filter || activeView?.filter || schema.table?.defaultFilters,
defaultSort: currentNamedViewConfig?.sort || activeView?.sort || schema.table?.defaultSort,
pageSize: schema.table?.pageSize,
selectable: schema.table?.selectable,
striped: activeView?.striped ?? schema.table?.striped,
bordered: activeView?.bordered ?? schema.table?.bordered,
className: schema.table?.className,
}), [schema, operations, currentNamedViewConfig, activeView]);
// Build form schema
const buildFormSchema = (): ObjectFormSchema => {
const recordId = selectedRecord
? ((selectedRecord.id || selectedRecord._id) as string | number | undefined)
: undefined;
return {
type: 'object-form',
objectName: schema.objectName,
mode: formMode,
recordId,
title: schema.form?.title,
description: schema.form?.description,
fields: schema.form?.fields,
customFields: schema.form?.customFields,
// #2545: `sections` is the spec-aligned key (it used to be dropped
// here); `groups` is its deprecated legacy alias, normalized to
// sections inside ObjectForm.
sections: schema.form?.sections,
groups: schema.form?.groups,
layout: schema.form?.layout,
columns: schema.form?.columns,
showSubmit: schema.form?.showSubmit,
submitText: schema.form?.submitText,
showCancel: schema.form?.showCancel,
cancelText: schema.form?.cancelText,
showReset: schema.form?.showReset,
initialValues: schema.form?.initialValues,
// framework#1894 / #2998: forward the spec-aligned structured
// `buttons`/`defaults`; ObjectForm folds them onto the flat props above
// (an explicitly-set flat key still wins).
buttons: schema.form?.buttons,
defaults: schema.form?.defaults,
readOnly: schema.form?.readOnly || formMode === 'view',
className: schema.form?.className,
// Master-detail by config: a form view can declare inline child
// collections; ObjectForm renders them as an atomic master-detail form
// (no bespoke page). ObjectForm skips them in view mode.
subforms: schema.form?.subforms,
onSuccess: handleFormSuccess,
onCancel: handleFormCancel,
};
};
// Get form title based on mode
const getFormTitle = (): string => {
if (schema.form?.title) return schema.form.title;
const objectLabel = (objectSchema?.label as string) || schema.objectName;
switch (formMode) {
case 'create': return `Create ${objectLabel}`;
case 'edit': return `Edit ${objectLabel}`;
case 'view': return `View ${objectLabel}`;
default: return objectLabel;
}
};
// Determine form container width from navigation config
const formWidthClass = useMemo(() => {
const w = navigationConfig?.width;
if (!w) return '';
if (typeof w === 'number') return `max-w-[${w}px]`;
return `max-w-[${w}]`;
}, [navigationConfig]);
// Render the form in a drawer
const renderDrawerForm = () => (
<Drawer open={isFormOpen} onOpenChange={setIsFormOpen} direction="right">
<DrawerContent className={cn('w-full sm:max-w-2xl', formWidthClass)}>
<DrawerHeader>
<DrawerTitle>{getFormTitle()}</DrawerTitle>
{schema.form?.description && (
<DrawerDescription>{schema.form.description}</DrawerDescription>
)}
</DrawerHeader>
<div className="flex-1 overflow-y-auto px-4 pb-4">
<ObjectForm schema={buildFormSchema()} dataSource={dataSource} />
</div>
</DrawerContent>
</Drawer>
);
// Render the form in a modal
const renderModalForm = () => (
<Dialog open={isFormOpen} onOpenChange={setIsFormOpen}>
<DialogContent className={cn('max-w-2xl max-h-[90vh] overflow-y-auto', formWidthClass)}>
<DialogHeader>
<DialogTitle>{getFormTitle()}</DialogTitle>
{schema.form?.description && (
<DialogDescription>{schema.form.description}</DialogDescription>
)}
</DialogHeader>
<ObjectForm schema={buildFormSchema()} dataSource={dataSource} />
</DialogContent>
</Dialog>
);
// Compute merged filters for the list
const mergedFilters = useMemo(() => {
const hasUserFilters = Object.keys(filterValues).some(
k => filterValues[k] !== undefined && filterValues[k] !== '' && filterValues[k] !== null,
);
if (hasUserFilters) {
return Object.entries(filterValues)
.filter(([, v]) => v !== undefined && v !== '' && v !== null)
.map(([field, value]) => ({ field, operator: 'equals' as const, value }));
}
return currentNamedViewConfig?.filter || activeView?.filter || schema.table?.defaultFilters;
}, [filterValues, currentNamedViewConfig, activeView, schema.table?.defaultFilters]);
const mergedSort = useMemo(() => {
return sortConfig.length > 0
? sortConfig
: currentNamedViewConfig?.sort || activeView?.sort || schema.table?.defaultSort;
}, [sortConfig, currentNamedViewConfig, activeView, schema.table?.defaultSort]);
// --- Content renderer ---
const renderContent = () => {
const key = `${schema.objectName}-${activeNamedView || activeView?.id || 'default'}-${currentViewType}-${refreshKey}`;
// If a custom renderListView is provided, use it
if (renderListView) {
return renderListView({
schema: {
type: 'list-view',