-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathListView.tsx
More file actions
2582 lines (2424 loc) · 117 KB
/
Copy pathListView.tsx
File metadata and controls
2582 lines (2424 loc) · 117 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, GroupingEditor, Select, SelectContent, SelectItem, SelectTrigger, SelectValue, RefreshIndicator, DataEmptyState } from '@object-ui/components';
import type { SortItem } from '@object-ui/components';
import { Search, SlidersHorizontal, ArrowUpDown, X, EyeOff, Pencil, Group, Paintbrush, Ruler, Inbox, Download, AlignJustify, Rows4, Rows3, Rows2, Share2, Printer, Plus, Trash2, CheckSquare, AlertTriangle, RotateCw, Loader2, icons, type LucideIcon } from 'lucide-react';
import type { FilterGroup } from '@object-ui/components';
import { ViewSwitcherDropdown, ViewType } from './ViewSwitcher';
import { ViewSettingsPopover } from './components/ViewSettingsPopover';
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 { detectStatusField } from '@object-ui/types';
import { usePullToRefresh } from '@object-ui/mobile';
import { resolveConditionalFormatting, buildExpandFields, buildExportFileName } from '@object-ui/core';
import { useObjectTranslation, useObjectLabel, useSafeFieldLabel } from '@object-ui/i18n';
import { usePermissions } from '@object-ui/permissions';
export interface ListViewProps {
schema: ListViewSchema;
className?: string;
onViewChange?: (view: ViewType) => void;
onFilterChange?: (filters: any) => void;
onSortChange?: (sort: any) => void;
onSearchChange?: (search: string) => void;
/** Called when the user toggles fields via the Hide Fields popover. */
onHiddenFieldsChange?: (hidden: string[]) => void;
/** Called when the user toggles inline record editing in View settings. */
onInlineEditChange?: (next: boolean) => void;
/** Called when the user resizes/reorders columns in the underlying grid. */
onColumnStateChange?: (state: { order?: string[]; widths?: Record<string, number> }) => 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;
/** Initial user-filter selections to restore (field → values; `_tab` for the active preset). */
userFilterSelections?: Record<string, Array<string | number | boolean>>;
/** Fires with the raw user-filter selections whenever the user changes them. */
onUserFilterSelectionsChange?: (selections: Record<string, Array<string | number | boolean>>) => void;
/**
* Initial advanced-filter (FilterBuilder) group to restore at mount, e.g.
* from a per-user localStorage cache. Read once by the lazy initializer —
* later prop changes don't override in-flight user edits, so hosts remount
* (via `key`) when they need to swap the restored value (view switch).
*/
initialFilters?: FilterGroup;
/** Initial search term to restore at mount (same one-shot semantics as `initialFilters`). */
initialSearchTerm?: string;
[key: string]: any;
}
// Helper to convert FilterBuilder group to ObjectStack AST.
// Accepts both the FilterBuilder vocabulary (camelCase) and the
// @objectstack/spec ViewFilterRule vocabulary (snake_case).
function mapOperator(op: string) {
switch (op) {
case 'equals': case 'eq': return '=';
case 'notEquals': case 'not_equals': case 'ne': case 'neq': return '!=';
case 'contains': return 'contains';
case 'notContains': case 'not_contains': case 'notcontains': return 'notcontains';
case 'startsWith': case 'starts_with': return 'startswith';
case 'greaterThan': case 'greater_than': case 'gt': return '>';
case 'greaterOrEqual': case 'greater_than_or_equal': case 'gte': return '>=';
case 'lessThan': case 'less_than': case 'lt': return '<';
case 'lessOrEqual': case 'less_than_or_equal': case 'lte': return '<=';
case 'in': return 'in';
case 'notIn': case 'not_in': case 'nin': return 'not in';
case 'before': return '<';
case 'after': return '>';
default: return op;
}
}
/**
* Normalize a single filter condition: convert `in`/`not in` operators
* into backend-compatible `or`/`and` of equality conditions.
* E.g., ['status', 'in', ['a','b']] → ['or', ['status','=','a'], ['status','=','b']]
*/
export function normalizeFilterCondition(condition: any[]): any[] {
if (!Array.isArray(condition) || condition.length < 3) return condition;
const [field, op, value] = condition;
// Recurse into logical groups
if (typeof field === 'string' && (field === 'and' || field === 'or')) {
return [field, ...condition.slice(1).map((c: any) =>
Array.isArray(c) ? normalizeFilterCondition(c) : c
)];
}
if (op === 'in' && Array.isArray(value)) {
if (value.length === 0) return [];
if (value.length === 1) return [field, '=', value[0]];
return ['or', ...value.map((v: any) => [field, '=', v])];
}
if (op === 'not in' && Array.isArray(value)) {
if (value.length === 0) return [];
if (value.length === 1) return [field, '!=', value[0]];
return ['and', ...value.map((v: any) => [field, '!=', v])];
}
return condition;
}
/**
* Format an action identifier string into a human-readable label.
* e.g., 'send_email' → 'Send Email'
*/
/**
* Normalize a view's `sort` declaration to SortItem[]. @objectstack/spec
* ListViewSchema.sort is `string | Array<{ field, order }>` — the TOP-LEVEL
* value may be a bare string ("name desc"); array entries may be strings
* (legacy "field desc") or `{ field, order }` objects. Calling `.map` on the
* bare-string form threw "schema.sort.map is not a function" and crashed the
* list (spec/renderer shape-mismatch audit, objectui#2578 follow-up).
*/
export function parseSortConfig(sort: unknown): SortItem[] {
const entries = typeof sort === 'string' ? [sort] : Array.isArray(sort) ? sort : [];
const items: SortItem[] = [];
for (const s of entries) {
if (typeof s === 'string') {
const parts = s.trim().split(/\s+/);
if (!parts[0]) continue;
items.push({
id: crypto.randomUUID(),
field: parts[0],
order: (parts[1]?.toLowerCase() === 'desc' ? 'desc' : 'asc') as 'asc' | 'desc',
});
} else if (s && typeof s === 'object' && typeof (s as any).field === 'string') {
items.push({
id: crypto.randomUUID(),
field: (s as any).field,
order: ((s as any).order as 'asc' | 'desc') || 'asc',
});
}
}
return items;
}
function formatActionLabel(action: string): string {
return action.replace(/_/g, ' ').replace(/\b\w/g, c => c.toUpperCase());
}
/**
* Normalize an array of filter conditions, expanding `in`/`not in` operators
* and ensuring consistent AST structure.
*/
export function normalizeFilters(filters: any[]): any[] {
if (!Array.isArray(filters) || filters.length === 0) return [];
return filters
.map(f => Array.isArray(f) ? normalizeFilterCondition(f) : f)
.filter(f => Array.isArray(f) && f.length > 0);
}
export function convertFilterGroupToAST(group: FilterGroup): any[] {
if (!group || !group.conditions || group.conditions.length === 0) return [];
const conditions = group.conditions
.filter(c => {
// isEmpty/isNotEmpty carry no value input — always keep them.
if (c.operator === 'isEmpty' || c.operator === 'isNotEmpty') return true;
// Skip incomplete rows (no value entered yet). Emitting `[field, op, '']`
// would be a silently-wrong filter (matches only empty) rather than
// "no filter", excluding all rows. Matches groupToCondition in
// datasetFilterCondition.ts (#1964).
const v = c.value;
return !(v == null || v === '' || (Array.isArray(v) && v.length === 0));
})
.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 all three historical rule shapes (spec `{ condition, style }`,
* ObjectUI `{ expression, … }`, native `{ field, operator, value, … }`).
*
* Thin wrapper over `@object-ui/core`'s `resolveConditionalFormatting`, which
* evaluates every predicate on the canonical CEL engine (with a legacy-dialect
* fallback) so a list view speaks the same expression dialect the server does
* (issue #1584 / ADR-0058). Kept exported for back-compat with consumers that
* evaluate formatting outside the ListView component.
*
* @param scope Extra top-level scope (the host predicate scope) bound
* alongside the row, so `features.*` / `current_user.*`
* conditions resolve as they do on grid rows / kanban cards.
*/
export function evaluateConditionalFormatting(
record: Record<string, unknown>,
rules?: ListViewSchema['conditionalFormatting'],
scope?: Record<string, unknown>
): React.CSSProperties {
return resolveConditionalFormatting(record, rules as any, scope) as React.CSSProperties;
}
// 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.',
// First-run (truly empty, no filter/search) vs filtered-to-empty. Showing
// "adjust your filters" to a brand-new user with nothing to adjust is wrong.
'list.firstRunTitle': 'Nothing here yet',
'list.firstRunMessage': 'Create your first record to get started.',
'list.noMatches': 'No matching records',
'list.noMatchesMessage': 'No records match your current filters or search. Try adjusting or clearing them.',
'list.loading': 'Loading records…',
// Load FAILED (network / server error) — distinct from empty. Offer retry.
'list.loadErrorTitle': 'Couldn\u2019t load records',
'list.loadErrorMessage': 'Something went wrong while loading this data. Check your connection and try again.',
'list.retry': 'Retry',
'list.search': 'Search',
'list.filter': 'Filter',
'list.filterRecords': 'Filter Records',
'list.sort': 'Sort',
'list.sortRecords': 'Sort Records',
'list.group': 'Group',
'list.groupBy': 'Group By',
'list.export': 'Export',
'list.exportAs': 'Export as {{format}}',
'list.color': 'Color',
'list.rowColor': 'Row Color',
'list.colorByField': 'Color by field',
'list.clear': 'Clear',
'list.none': 'None',
'list.hideFields': 'Hide fields',
'list.showAll': 'Show all',
'list.pullToRefresh': 'Pull to refresh',
'list.refresh': 'Refresh',
'list.refreshing': 'Refreshing…',
'list.dataLimitReached': 'Showing first {{limit}} records. More data may be available.',
'list.addRecord': 'Add record',
'list.tabs': 'Tabs',
'list.allRecords': 'All Records',
'list.share': 'Share',
'list.print': 'Print',
'list.hideFieldsTitle': 'Hide Fields',
'table.rowsPerPage': 'Rows per page',
'grid.toolbar.densityMode': 'Density',
'grid.toolbar.densityCompact': 'Compact',
'grid.toolbar.densityComfortable': 'Comfortable',
'grid.toolbar.densitySpacious': 'Spacious',
'grid.toolbar.densityCycleHint': '{{label}} (click to cycle)',
'grid.toolbar.densityCycleShortHint': 'Click to cycle',
'list.viewSettings': 'View settings',
'list.viewSettingsHint': 'Grouping, color, density, and visible fields.',
};
const fallbackListT = (key: string, options?: Record<string, unknown>) => {
let value = LIST_DEFAULT_TRANSLATIONS[key] || key;
if (options) {
for (const [k, v] of Object.entries(options)) {
value = value.replace(`{{${k}}}`, String(v));
}
}
return value;
};
/**
* Safe wrapper for 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: fallbackListT };
}
return { t: result.t };
} catch {
return { t: fallbackListT };
}
}
/**
* Thin selector over useObjectLabel. The underlying hook is provider-safe
* (optional context + global i18n fallback), so no try/catch — wrapping a
* hook call in try/catch violates rules-of-hooks: a throw after other hooks
* ran would desync hook order on the next render (same fix as
* fields#useFieldLabel, objectui#2595).
*/
function useListFieldLabel() {
const { fieldLabel, actionLabel, objectLabel } = useObjectLabel();
return { fieldLabel, actionLabel, objectLabel };
}
/**
* Imperative handle exposed by ListView via React.forwardRef.
* Allows parent components to trigger a data refresh programmatically.
*
* @example
* ```tsx
* const listRef = React.useRef<ListViewHandle>(null);
* <ListView ref={listRef} schema={schema} />
* // After a mutation:
* listRef.current?.refresh();
* ```
*/
export interface ListViewHandle {
/** Force the ListView to re-fetch data from the DataSource */
refresh(): void;
}
export const ListView = React.forwardRef<ListViewHandle, ListViewProps>(({
schema: propSchema,
className,
onViewChange,
onFilterChange,
onSortChange,
onSearchChange,
onHiddenFieldsChange,
onInlineEditChange,
onColumnStateChange,
onRowClick,
showViewSwitcher: showViewSwitcherProp,
userFilterSelections,
onUserFilterSelectionsChange,
initialFilters,
initialSearchTerm,
...props
}, ref) => {
// The switcher can be enabled either by the host component (prop) or by
// the schema itself (ADR-0047 — ObjectView/InterfaceListPage stamp it on
// the schema when appearance.allowedVisualizations whitelists >1 type).
const showViewSwitcher = showViewSwitcherProp ?? (propSchema as any)?.showViewSwitcher ?? false;
// i18n support for record count and other labels
const { t } = useListViewTranslation();
const { fieldLabel: resolveFieldLabel, actionLabel: resolveActionLabel, objectLabel: resolveObjectLabel } = useListFieldLabel();
const { translateOptions } = useSafeFieldLabel();
// Kernel level default: Ensure viewType is always a RENDERABLE kind.
// Two inputs must land on 'grid': a missing viewType, and the view-metadata
// kind `'list'` (AI-authored views store `type/viewKind: 'list'`, which hosts
// forward verbatim) — 'list' names the view CATEGORY, not a renderer, and
// letting it through used to hit the typeless default branch below and
// render as a red "Unknown component type" box.
// Perf: only allocate a new object when normalization is actually needed,
// otherwise return propSchema as-is so downstream useMemos see a stable
// reference when callers already provide a renderable viewType (the common case).
const schema = React.useMemo(
() =>
propSchema.viewType && (propSchema.viewType as string) !== 'list'
? propSchema
: { ...propSchema, viewType: 'grid' },
[propSchema],
);
// Convenience: resolve field label with schema.objectName pre-bound
const tFieldLabel = React.useCallback(
(fieldName: string, fallback: string) =>
schema.objectName ? resolveFieldLabel(schema.objectName, fieldName, fallback) : fallback,
[schema.objectName, resolveFieldLabel],
);
// Convenience: resolve action label with schema.objectName pre-bound.
// Falls back to title-casing the action key when no i18n resource is found,
// matching the previous local `formatActionLabel` helper.
const tActionLabel = React.useCallback(
(actionName: string) => {
const fallback = formatActionLabel(actionName);
if (schema.objectName && typeof resolveActionLabel === 'function') {
return resolveActionLabel(schema.objectName, actionName, fallback);
}
return fallback;
},
[schema.objectName, resolveActionLabel],
);
// Resolve toolbar visibility flags: userActions overrides showX flags
const toolbarFlags = React.useMemo(() => {
const ua = schema.userActions;
const addRecordEnabled = schema.addRecord?.enabled === true && ua?.addRecordForm !== false;
// `refresh` is spec-canonical (`userActions.refresh`, @objectstack/spec). The
// installed spec type may predate the field, so read it defensively. Visible by
// default (opt-out via `userActions.refresh: false`), like the other toggles.
const uaRefresh = (ua as { refresh?: boolean } | undefined)?.refresh;
return {
showSearch: ua?.search !== undefined ? ua.search : schema.showSearch !== false,
showSort: ua?.sort !== undefined ? ua.sort : schema.showSort !== false,
showFilters: ua?.filter !== undefined ? ua.filter : schema.showFilters !== false,
showRefresh: uaRefresh !== undefined ? uaRefresh : true,
showDensity: ua?.rowHeight !== undefined ? ua.rowHeight : schema.showDensity !== false,
showHideFields: schema.showHideFields === true,
showGroup: schema.showGroup !== false,
showColor: schema.showColor === true,
compactToolbar: schema.compactToolbar === true,
showAddRecord: addRecordEnabled,
addRecordPosition: (schema.addRecord?.position === 'bottom' ? 'bottom' : 'top') as 'top' | 'bottom',
};
}, [schema.userActions, schema.showSearch, schema.showSort, schema.showFilters, schema.showDensity, schema.showHideFields, schema.showGroup, schema.showColor, schema.compactToolbar, schema.addRecord, schema.userActions?.addRecordForm]);
const [currentView, setCurrentView] = React.useState<ViewType>(
(schema.viewType as ViewType)
);
const [searchTerm, setSearchTerm] = React.useState(() => initialSearchTerm ?? '');
const [showSearchPopover, setShowSearchPopover] = React.useState(false);
// Sort State
const [showSort, setShowSort] = React.useState(false);
const [currentSort, setCurrentSort] = React.useState<SortItem[]>(() =>
parseSortConfig(schema.sort),
);
// Sync when parent schema.sort changes (view switch / reload pulls a
// saved override). Compare by stringified payload to avoid render loops.
const schemaSortKey = React.useMemo(
() => JSON.stringify(schema.sort || []),
[schema.sort]
);
React.useEffect(() => {
setCurrentSort(parseSortConfig(schema.sort));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [schemaSortKey]);
const [showFilters, setShowFilters] = React.useState(false);
const [currentFilters, setCurrentFilters] = React.useState<FilterGroup>(() =>
initialFilters && Array.isArray(initialFilters.conditions)
? initialFilters
: {
id: 'root',
logic: 'and',
conditions: []
}
);
// Data State
const dataSource = props.dataSource;
const [data, setData] = React.useState<any[]>([]);
// Load failure (network / server error) is distinct from "empty": we must
// not tell a user to "create your first record" when the fetch actually
// failed. Captured here so the render can show a retryable error panel.
const [loadError, setLoadError] = React.useState<string | null>(null);
// Start in loading state when we will fetch from a dataSource so the empty
// state doesn't flash before the first effect runs. Inline data (schema.data
// as an array or a `value` provider) starts as not-loading.
const [loading, setLoading] = React.useState<boolean>(() => {
if (Array.isArray(schema.data)) return false;
if (
schema.data &&
typeof schema.data === 'object' &&
(schema.data as any).provider === 'value' &&
Array.isArray((schema.data as any).items)
) {
return false;
}
// Renderer-owned data (gantt + api provider): ListView never fetches,
// so don't flash its skeleton either.
if (
schema.viewType === 'gantt' &&
schema.data &&
typeof schema.data === 'object' &&
!Array.isArray(schema.data) &&
(schema.data as any).provider === 'api'
) {
return false;
}
return true;
});
const [objectDef, setObjectDef] = React.useState<any>(null);
const [objectDefLoaded, setObjectDefLoaded] = React.useState(false);
const [refreshKey, setRefreshKey] = React.useState(0);
const [dataLimitReached, setDataLimitReached] = React.useState(false);
// --- P1: Imperative refresh API ---
React.useImperativeHandle(ref, () => ({
refresh: () => setRefreshKey(k => k + 1),
}), []);
// --- P2: Auto-subscribe to DataSource mutation events ---
// Refetch whenever the bound object is mutated through the DataSource. This
// is the ONLY refresh signal for inline-edit "Save All": ObjectGrid persists
// those edits by calling dataSource.update() directly, with no form-success
// handler to bump an external refreshTrigger — so subscribing even when
// `refreshTrigger` is provided is required, not redundant. Form/delete flows
// also bump refreshTrigger; the extra refetch that produces is harmless
// because find() coalesces concurrent identical reads into one round-trip.
React.useEffect(() => {
if (!dataSource?.onMutation || !schema.objectName) return;
const unsub = dataSource.onMutation((event: any) => {
if (event.resource === schema.objectName) {
setRefreshKey(k => k + 1);
}
});
return unsub;
}, [dataSource, schema.objectName]);
// Dynamic page size state (wired from pageSizeOptions selector)
const [dynamicPageSize, setDynamicPageSize] = React.useState<number | undefined>(undefined);
const effectivePageSize = dynamicPageSize ?? schema.pagination?.pageSize ?? 100;
// --- Server-side pagination (#2212) ---
// ListView owns the fetch, so it owns paging too: it requests one window at a
// time ($skip = (page-1)*size) and reads the real match `total` from the
// result. That total + page controls are handed DOWN to the flat grid view so
// its existing (single) DataTable pager becomes server-driven — records past
// the first window are reachable, and we never stack a second pager on top.
const [serverPage, setServerPage] = React.useState(1);
const [serverTotal, setServerTotal] = React.useState<number | null>(null);
// Grouping state (initialized from schema, user can add/remove via popover).
// Supports three input shapes from the schema:
// 1. Spec-compliant `grouping: { fields: [...] }` (preferred — supports
// arbitrary nesting depth).
// 2. Shorthand `groupBy: 'fieldname'` written by the view config UI for
// the primary group.
// 3. Optional `groupBy2: 'fieldname'` for a secondary (nested) group,
// enabling Airtable-style two-level grouping from the visual editor.
// Any combination of (2) + (3) is normalized into a multi-level
// GroupingConfig so the renderer honors grouping configured visually.
const initialGroupingConfig = React.useMemo(() => {
if (schema.grouping?.fields?.length) return schema.grouping;
const primary = typeof schema.groupBy === 'string' ? schema.groupBy.trim() : '';
const secondary = typeof schema.groupBy2 === 'string' ? schema.groupBy2.trim() : '';
const fields: Array<{ field: string; order: 'asc'; collapsed: boolean }> = [];
if (primary) fields.push({ field: primary, order: 'asc', collapsed: false });
if (secondary && secondary !== primary) {
fields.push({ field: secondary, order: 'asc', collapsed: false });
}
return fields.length > 0 ? { fields } : undefined;
}, [schema.grouping, schema.groupBy, schema.groupBy2]);
const [groupingConfig, setGroupingConfig] = React.useState(initialGroupingConfig);
const [showGroupPopover, setShowGroupPopover] = React.useState(false);
// Re-sync grouping when the underlying schema-driven config changes (e.g. the
// user edits `groupBy` in the view designer). User-driven changes via the
// popover keep the latest interaction since this only fires on schema deltas.
const lastSchemaGroupingRef = React.useRef(initialGroupingConfig);
React.useEffect(() => {
if (lastSchemaGroupingRef.current !== initialGroupingConfig) {
lastSchemaGroupingRef.current = initialGroupingConfig;
setGroupingConfig(initialGroupingConfig);
}
}, [initialGroupingConfig]);
// Row color state (initialized from schema, user can configure via popover)
const [rowColorConfig, setRowColorConfig] = React.useState(schema.rowColor);
const [showColorPopover, setShowColorPopover] = React.useState(false);
// Bulk action state
const [selectedRows, setSelectedRows] = React.useState<any[]>([]);
// Request counter for debounce — only the latest request writes data
const fetchRequestIdRef = React.useRef(0);
// User Filters State (Airtable Interfaces-style)
const [userFilterConditions, setUserFilterConditions] = React.useState<any[]>([]);
// User filters render ONLY when explicitly configured (ADR-0047 §data
// mode): saved list views already act as the preset switcher, so an
// unconfigured view keeps a clean toolbar instead of growing auto-derived
// dropdowns. When a config asks for dropdown/toggle elements without
// naming fields, fill the field list from objectDef select-like fields so
// authors can write `userFilters: { element: 'dropdown' }` as shorthand.
const resolvedUserFilters = React.useMemo<ListViewSchema['userFilters'] | undefined>(() => {
const configured = schema.userFilters;
if (!configured) return undefined;
if (configured.element === 'tabs') return configured;
if (configured.fields && configured.fields.length > 0) return configured;
if (!objectDef?.fields) return configured;
const FILTERABLE_FIELD_TYPES = new Set(['select', 'multi-select', 'boolean']);
const derivedFields: NonNullable<NonNullable<ListViewSchema['userFilters']>['fields']> = [];
const fieldsEntries: Array<[string, any]> = Array.isArray(objectDef.fields)
? objectDef.fields.map((f: any) => [f.name, f])
: Object.entries(objectDef.fields);
for (const [key, field] of fieldsEntries) {
// Include fields with a filterable type, or fields that have options without an explicit type
if (FILTERABLE_FIELD_TYPES.has(field.type) || (field.options && !field.type)) {
derivedFields.push({
field: key,
label: tFieldLabel(key, field.label || key),
type: field.type === 'boolean' ? 'boolean' : field.type === 'multi-select' ? 'multi-select' : 'select',
});
}
}
if (derivedFields.length === 0) return configured;
return { ...configured, fields: derivedFields };
}, [schema.userFilters, objectDef, tFieldLabel]);
// ADR-0053: userFilters (dropdown | tabs) is the sole page filter control.
const filterElements = resolvedUserFilters;
// Hidden Fields State (initialized from schema)
const [hiddenFields, setHiddenFields] = React.useState<Set<string>>(
() => new Set(schema.hiddenFields || [])
);
// Sync when parent schema changes (e.g. switching between views, reload
// pulls a saved override). Wrapped in JSON to avoid Set identity churn.
const schemaHiddenKey = React.useMemo(
() => JSON.stringify(schema.hiddenFields || []),
[schema.hiddenFields]
);
React.useEffect(() => {
setHiddenFields(new Set(schema.hiddenFields || []));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [schemaHiddenKey]);
// Setter that also notifies parent for persistence (debounced upstream).
const updateHiddenFields = React.useCallback(
(next: Set<string>) => {
setHiddenFields(next);
onHiddenFieldsChange?.(Array.from(next));
},
[onHiddenFieldsChange]
);
const [showHideFields, setShowHideFields] = React.useState(false);
// Inline-edit State (initialized from schema). Kept local — like hiddenFields
// — so the toolbar toggle flips the grid immediately. The parent persists via
// onInlineEditChange (debounced) and doesn't update the `inlineEdit` prop
// synchronously, so reading `schema.inlineEdit` directly would make the button
// appear dead until a full reload.
const [inlineEdit, setInlineEdit] = React.useState<boolean>(() => !!schema.inlineEdit);
React.useEffect(() => {
setInlineEdit(!!schema.inlineEdit);
}, [schema.inlineEdit]);
// Setter that also notifies parent for persistence (debounced upstream).
const updateInlineEdit = React.useCallback(
(next: boolean) => {
setInlineEdit(next);
onInlineEditChange?.(next);
},
[onInlineEditChange]
);
// Export State
const [showExport, setShowExport] = React.useState(false);
// Server-streamed export (xlsx / type-aware csv|json) in-flight + last error.
const [exportBusy, setExportBusy] = React.useState(false);
const [exportError, setExportError] = React.useState<string | null>(null);
// Object-level export permission gate. Default-allow: export stays enabled
// unless `allowExport === false` or `operations.export === false`.
const exportPermitted = schema.allowExport !== false && schema.operations?.export !== false;
// Normalize exportOptions: support both ObjectUI object format and spec string[] format
const resolvedExportOptions = React.useMemo(() => {
if (!schema.exportOptions) return undefined;
// Spec format: simple string[] like ['csv', 'xlsx']
if (Array.isArray(schema.exportOptions)) {
return { formats: schema.exportOptions as Array<'csv' | 'xlsx' | 'json' | 'pdf'> };
}
// ObjectUI format: already an object
return schema.exportOptions;
}, [schema.exportOptions]);
// Density Mode — rowHeight maps to density if densityMode not explicitly set
const resolvedDensity = React.useMemo(() => {
if (schema.densityMode) return schema.densityMode;
if (schema.rowHeight) {
const map: Record<string, 'compact' | 'comfortable' | 'spacious'> = {
compact: 'compact',
short: 'compact',
medium: 'comfortable',
tall: 'spacious',
extra_tall: 'spacious',
};
return map[schema.rowHeight] || 'comfortable';
}
return 'compact';
}, [schema.densityMode, schema.rowHeight]);
const density = useDensityMode(resolvedDensity, {
onChange: schema.onDensityChange,
});
// ── Gallery card density ────────────────────────────────────────────
// Separate from the table `density.mode` (which controls rowHeight) —
// the gallery uses 3 column counts mapped to `GalleryConfig.cardSize`
// (small/medium/large). Persisted per-object so users can keep
// Accounts compact while leaving Products comfortable.
type GalleryCardSize = 'small' | 'medium' | 'large';
const galleryDensityKey = React.useMemo(
() => `objectui:gallery:density:${schema.objectName ?? 'default'}`,
[schema.objectName],
);
const [galleryCardSize, setGalleryCardSize] = React.useState<GalleryCardSize>(() => {
if (typeof window === 'undefined') return (schema.gallery?.cardSize as GalleryCardSize) ?? 'medium';
try {
const v = window.localStorage.getItem(galleryDensityKey);
if (v === 'small' || v === 'medium' || v === 'large') return v;
} catch { /* private mode — fall through */ }
return (schema.gallery?.cardSize as GalleryCardSize) ?? 'medium';
});
const cycleGalleryDensity = React.useCallback(() => {
setGalleryCardSize((prev) => {
const next: GalleryCardSize = prev === 'large' ? 'medium' : prev === 'medium' ? 'small' : 'large';
try { window.localStorage.setItem(galleryDensityKey, next); } catch { /* ignore */ }
return next;
});
}, [galleryDensityKey]);
const handlePullRefresh = React.useCallback(async () => {
setRefreshKey(k => k + 1);
}, []);
const { ref: pullRef, isRefreshing, pullDistance } = usePullToRefresh<HTMLDivElement>({
onRefresh: handlePullRefresh,
enabled: !!dataSource && !!schema.objectName,
});
const storageKey = React.useMemo(() => {
return schema.id
? `listview-${schema.objectName}-${schema.id}-view`
: `listview-${schema.objectName}-view`;
}, [schema.objectName, schema.id]);
// Fetch object definition
React.useEffect(() => {
let isMounted = true;
// Reset loaded flag so data fetch waits for the new schema
setObjectDefLoaded(false);
setObjectDef(null);
const fetchObjectDef = async () => {
if (!dataSource || !schema.objectName) {
setObjectDefLoaded(true);
return;
}
if (typeof dataSource.getObjectSchema !== 'function') {
setObjectDefLoaded(true);
return;
}
try {
const def = await dataSource.getObjectSchema(schema.objectName);
if (isMounted) {
setObjectDef(def);
}
} catch (err) {
console.warn("Failed to fetch object schema for ListView:", err);
} finally {
if (isMounted) {
setObjectDefLoaded(true);
}
}
};
fetchObjectDef();
return () => { isMounted = false; };
}, [schema.objectName, dataSource]);
// Auto-compute $expand fields from objectDef (lookup / master_detail).
//
// Important: include not only the user-declared `schema.fields` (table
// columns) but also the runtime fields used by alternate view types
// (kanban cardFields, calendar dateField, gallery coverField, etc.).
// Otherwise a kanban whose card shows `account` would request
// `?select=...,account,...` but never `populate=account`, so the server
// returns the bare FK ID instead of the expanded record. This is why
// list view shows "Initech Solutions" but kanban used to show
// "8UY9zHWBfjYjYor4" for the same field.
const expandFields = React.useMemo(() => {
const baseColumns = Array.isArray(schema.fields)
? (schema.fields as any[])
.map((f) => (typeof f === 'string' ? f : f?.field))
.filter((v): v is string => typeof v === 'string' && v.length > 0)
: [];
const collected = new Set<string>(baseColumns);
const collectViewFields = (v: any) => {
if (!v) return;
const candidates = [
v.groupField, v.groupBy,
v.titleField, v.cardTitle,
v.startDateField, v.endDateField, v.dateField, v.endField,
v.colorField, v.allDayField,
v.coverField, v.imageField, v.subtitleField,
v.swimlaneField, v.valueField,
...(Array.isArray(v.cardFields) ? v.cardFields : []),
...(Array.isArray(v.visibleFields) ? v.visibleFields : []),
...(Array.isArray(v.metaFields) ? v.metaFields : []),
];
for (const f of candidates) {
if (typeof f === 'string' && f) collected.add(f);
}
};
collectViewFields((schema as any).kanban);
collectViewFields((schema as any).options?.kanban);
collectViewFields((schema as any).calendar);
collectViewFields((schema as any).options?.calendar);
collectViewFields((schema as any).gallery);
collectViewFields((schema as any).options?.gallery);
collectViewFields((schema as any).timeline);
collectViewFields((schema as any).options?.timeline);
collectViewFields((schema as any).gantt);
collectViewFields((schema as any).options?.gantt);
const augmented = collected.size > 0 ? Array.from(collected) : undefined;
return buildExpandFields(objectDef?.fields, augmented);
}, [
objectDef?.fields,
schema.fields,
(schema as any).kanban,
(schema as any).calendar,
(schema as any).gallery,
(schema as any).timeline,
(schema as any).gantt,
(schema as any).options,
]);
// Permissions context — must be read before the data-fetch effect so
// the effect can FLS-gate the `$select` projection (preventing the
// server from returning denied fields). Also feeds the column-list
// gate further down the file.
const perms = usePermissions();
// A gantt view whose `data` names the api provider is fed by a composite
// endpoint that ObjectGantt resolves itself (resolveDataSource →
// ApiDataSource, reads AND write-backs). ListView must neither fetch
// schema.objectName rows for it nor pass its `data` prop down — the prop
// short-circuits the renderer's own fetch, so stale object rows would
// replace the endpoint's tree.
const ganttOwnsData =
currentView === 'gantt' &&
!!schema.data &&
typeof schema.data === 'object' &&
!Array.isArray(schema.data) &&
(schema.data as any).provider === 'api';
// Fetch data effect — supports schema.data (ViewDataSchema) provider modes
React.useEffect(() => {
let isMounted = true;
const requestId = ++fetchRequestIdRef.current;
// Check for inline data via schema.data provider: 'value'
if (schema.data && typeof schema.data === 'object' && !Array.isArray(schema.data)) {
const dataConfig = schema.data as any;
if (dataConfig.provider === 'value' && Array.isArray(dataConfig.items)) {
let items = dataConfig.items;
if (searchTerm) {
const q = searchTerm.toLowerCase();
items = items.filter((row: any) =>
Object.values(row).some(
(v) => v != null && String(v).toLowerCase().includes(q),
),
);
}
setData(items);
setLoading(false);
setDataLimitReached(false);
return;
}
}
// Also support schema.data as a plain array (shorthand for value provider)
if (Array.isArray(schema.data)) {
let items = schema.data as any[];
if (searchTerm) {
const q = searchTerm.toLowerCase();
items = items.filter((row: any) =>
Object.values(row).some(
(v) => v != null && String(v).toLowerCase().includes(q),
),
);
}
setData(items);
setLoading(false);
setDataLimitReached(false);
return;
}
// Renderer-owned data (gantt + api provider): the view component fetches
// from its endpoint itself; just clear the loading state.
if (ganttOwnsData) {
setLoading(false);
setDataLimitReached(false);
return;
}
// Wait for objectDef to load before fetching data so that $expand is computed
if (!objectDefLoaded) return;
const fetchData = async () => {
if (!dataSource || !schema.objectName) {
// No way to fetch — clear the loading state so the empty state
// (or downstream view) can render instead of an indefinite skeleton.
setLoading(false);
return;
}
setLoading(true);
setLoadError(null);
try {
// Construct filter
let finalFilter: any = [];
const baseFilter = schema.filters || [];
const userFilter = convertFilterGroupToAST(currentFilters);
// 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] : []),
...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;
// Build a $select projection from the columns the listview actually
// shows (plus required relational keys). This trims server payload
// significantly for wide objects.
//
// FLS: also drop columns the current user cannot read. Sending a
// denied field in $select would leak the value at the server
// boundary even though the UI hides it — server-side trust must
// never be defeated by what the client requests.
const selectFields = (() => {
const rawCols = Array.isArray(schema.fields)
? (schema.fields as any[])
.map(f => (typeof f === 'string' ? f : f?.field))
.filter((v): v is string => typeof v === 'string' && v.length > 0)
: [];
const cols = (perms?.isLoaded && schema.objectName)
? rawCols.filter(c => perms.checkField(schema.objectName!, c, 'read'))
: rawCols;
if (cols.length === 0) return undefined;
// Don't speculatively add `_id` / `name` — some backends reject
// unknown select keys with an empty result set rather than
// ignoring them. Stick to the user-requested columns plus the
// expanded relation roots (which we know are valid because
// buildExpandFields() derived them from the object schema).
const required = new Set<string>(['id']);
for (const c of cols) required.add(c);
for (const e of expandFields) required.add(e);
// Real fields of the object, used to gate the SPECULATIVE
// view-binding fields below. The comment above is the tell: "some
// backends reject unknown select keys with an empty result set
// rather than ignoring them" — the cloud multi-tenant runtime does
// exactly that, so a single unknown column in $select silently
// zeroes the whole list (an AI-built `product` view auto-requesting
// `status`/`due_date`/`image` then looks like "no data exists").
// The user-declared `cols` and `expandFields` are already
// known-valid (perms.checkField / buildExpandFields derived them
// from the schema); only the auto-included view-binding fields are
// unsafe. When the object schema isn't loaded yet we can't
// validate, so we keep the prior permissive behavior (the data
// fetch waits for objectDefLoaded, so this is virtually never hit).
const knownObjectFields = (() => {
const f = objectDef?.fields;
if (!f) return null;
const names = Array.isArray(f)
? (f as any[]).map(x => x?.name).filter((n): n is string => typeof n === 'string')
: Object.keys(f);
const s = new Set<string>(names);
s.add('id'); s.add('created_at'); s.add('updated_at');
return s;
})();
const addSpeculative = (f: unknown) => {
if (typeof f !== 'string' || !f) return;
if (!knownObjectFields || knownObjectFields.has(f)) required.add(f);
};
// View-specific runtime fields. Each non-grid view binds to one
// or more record fields (groupBy for kanban, dates for calendar/
// timeline/gantt, image/title for gallery). Without these in the
// projection the view renders correctly-shaped records but with
// blank values — e.g. a kanban grouped by `industry` puts every
// card into the implicit "no value" column. Added via
// addSpeculative so a binding naming a field this object lacks is
// dropped instead of poisoning the query.
const collectViewFields = (v: any) => {
if (!v) return;