Repository navigation
Expand file tree
/
Copy pathObjectView.tsx
More file actions
3172 lines (3065 loc) · 176 KB
/
Copy pathObjectView.tsx
File metadata and controls
3172 lines (3065 loc) · 176 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
/**
* Console ObjectView
*
* Thin wrapper around the plugin-view ObjectView that adds:
* - Multi-view resolution from objectDef.listViews
* - MetadataInspector toggle
* - Drawer for record detail preview
* - useObjectActions for toolbar create button
* - ListView delegation for non-grid view types (kanban, calendar, chart, etc.)
*/
import { useMemo, useState, useCallback, useEffect, useRef, lazy, Suspense, createElement, type ReactNode } from 'react';
import { useParams, useSearchParams, useNavigate, useLocation, useHref } from 'react-router-dom';
import { DENSITY_MODE_TO_ROW_HEIGHT, normalizeListViewSchema, resolveAffordance, isRecordScopedAction, type FilterTokenScope, type SchemaLike } from '@object-ui/core';
import {
parseUserFilterParams,
applyUserFilterParams,
parseListStateParams,
applyListStateParams,
userFilterParamsKey,
type ListStatePatch,
type ListUrlState,
} from './userFilterUrlState.js';
import { buildListFilterKey, readListFilterState, writeListFilterState } from './listFilterStorage.js';
import { useObjectListPreferences, type ListViewPreference } from '../context/ListPreferencesProvider.js';
import { parseUrlEqualityFilterTriples } from './drillUrlFilters.js';
import { formatMetadataError } from '@object-ui/data-objectstack';
const ObjectChart = lazy(() =>
import('@object-ui/plugin-charts').then((m) => ({ default: m.ObjectChart })),
);
const ImportWizard = lazy(() =>
import('@object-ui/plugin-grid').then((m) => ({ default: m.ImportWizard })),
);
import { ListView } from '@object-ui/plugin-list';
import { ObjectView as PluginObjectView, ViewTabBar, ManageViewsDialog, deriveRecordSurface, overlayWidthFor } from '@object-ui/plugin-view';
import type { ViewTabItem } from '@object-ui/plugin-view';
import { RECORD_DRAWER_PARAM } from '../urlParams.js';
// Plugin registration is handled by the host app (e.g. apps/console/src/main.tsx
// uses ComponentRegistry.registerLazy so heavy plugins stay code-split).
// Do NOT add eager `import '@object-ui/plugin-*'` side-effect imports here.
import {
Button,
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
Empty,
EmptyTitle,
EmptyDescription,
NavigationOverlay,
} from '@object-ui/components';
import { Plus, Upload, Lock, MoreHorizontal, RotateCcw } from 'lucide-react';
import { FavoriteMenuItem, useObjectListFavorite } from '../layout/SidebarItemMenu.js';
import { useMetaItemRefusal } from '../hooks/useMetaItemRefusal.js';
import { useTenancyPosture } from '../hooks/useTenancyPosture.js';
import { useServedViewItems } from '../hooks/useServedViewItems.js';
import { viewTabLabel } from './viewTabLabel.js';
import { getIcon } from '../utils/getIcon.js';
import type { ActionBarSchema, DataSource, UIActionSchema, ListViewSchema, TreeViewConfig, ViewNavigationConfig } from '@object-ui/types';
import { MetadataPanel, useMetadataInspector } from './MetadataInspector.js';
import { ViewConfigPanel } from './ViewConfigPanel.js';
import { useMetadataClient } from './metadata-admin/useMetadata.js';
import { dropPublishedViewList } from './metadata-admin/viewListDrop.js';
import { persistRuntimeMetadata, createRuntimeMetadata, viewEnvelope } from './runtime-metadata-persistence.js';
import { CreateViewDialog } from './CreateViewDialog.js';
import {
usePreviewDrafts,
PREVIEW_QUERY_FLAG,
PREVIEW_QUERY_VALUE,
} from '../preview/PreviewModeContext.js';
import { PageHeader } from '../layout/PageHeader.js';
import { useMobileViewSwitcherRegistration } from '../layout/MobileViewSwitcherContext.js';
import type { MobileViewSwitcherItem } from '../layout/MobileViewSwitcherContext.js';
import { ManagedByBadge } from '../components/ManagedByBadge.js';
import { isSetupAppSegment } from '../console/setupApp.js';
import { RecordDetailView } from './RecordDetailView.js';
import type { RowCrudPredicates } from '../utils/crudAffordances.js';
import { createIdentityImportDataSource, IDENTITY_IMPORT_OBJECT, IDENTITY_IMPORT_WRITE_MODES, type IdentityPasswordPolicy } from './identityImport.js';
import { IdentityImportOptions, IdentityImportResultExtra, identityImportFields } from './IdentityImportPanels.js';
import { ManagedUsersInviteLine, MANAGED_USERS_OBJECT, UnauthorizedUserMarker, UserGrantLoader, isManagedEnvironment } from './managedEnvironmentUsers.js';
import { importTargetFields } from './importTargetFields.js';
import { useExpressionContext } from '../providers/ExpressionProvider.js';
import { listToolbarDrawsAction, resolveManagedByEmptyState } from '../utils/managedByEmptyState.js';
import { mayReadObject } from '../utils/navObjectReadGate.js';
import { resolveViewId } from '../utils/resolveViewId.js';
import { defaultListViewId, viewRowId, isSavedViewId } from '../utils/viewIdentity.js';
import { warnSuppressedListNav } from '../utils/warnSuppressedListNav.js';
import { useObjectActions } from '../hooks/useObjectActions.js';
import { useObjectTranslation, useObjectLabel, useDisplayLocale, pickLocalized } from '@object-ui/i18n';
import { usePermissions } from '@object-ui/permissions';
import { useAuth, useWorkspaceAdminStatus } from '@object-ui/auth';
import { useRealtimeSubscription, useConflictResolution } from '@object-ui/collaboration';
import { ActionProvider, useNavigationOverlay, SchemaRenderer, useActionTextLocalizer, useRowPredicate, RelatedRecordActionsProvider, notifyDataChanged, useCapabilityGate, usePredicateScope, useMetadata } from '@object-ui/react';
import { toast } from 'sonner';
import { useConsoleActionRuntime } from '../hooks/useConsoleActionRuntime.js';
import { useOfferedNavRunAction } from '../hooks/useNavRunAction.js';
import { actionRendersAt } from '@object-ui/types';
import { useEnvironmentEntitlements } from '../environment/useEnvironmentEntitlements.js';
import { EnvironmentListToolbar } from '../environment/EnvironmentListToolbar.js';
import {
VIEW_TYPE_ICONS,
FALLBACK_USER,
substituteFilterTokens,
declaredPrimaryToolbarAction,
selectFilterParams,
MOBILE_FAB_LIST_CLEARANCE,
} from './objectViewHelpers.js';
import { listRecordDetailUrl, listRecordActionsValue } from './objectViewRecordLinks.js';
import {
defaultListColumnsFromObject,
bulkWiredActionNamesKey,
buildAddViewSpec,
loadViewOverrides,
buildViewTabs,
setDefaultViewPatches,
buildViewConfigSaveBody,
} from './objectViewTabs.js';
import {
timelineViewOptions,
calendarViewOptions,
ganttViewOptions,
galleryViewOptions,
kanbanViewOptions,
storedLegacyOptions,
isSameOptionsValue,
dispatchViewPatches,
} from './objectViewOptions.js';
import { ObjectNotFoundState, useViewTabsFit, keepInlineEditModeForTheSession } from './objectViewChrome.js';
// objectstack#25992 slice 1: these module-level helpers moved to the sibling
// `objectView*.ts` modules above. Every name this file exported stays
// exported from here, so imports by path keep resolving.
export { declaredPrimaryToolbarAction, selectFilterParams } from './objectViewHelpers.js';
export { listRecordDetailUrl, listRecordActionsValue } from './objectViewRecordLinks.js';
export type { ListRecordRoutes } from './objectViewRecordLinks.js';
export {
defaultListColumnsFromObject,
buildAddViewSpec,
sanitizeViewOverride,
loadViewOverrides,
buildViewTabs,
setDefaultViewPatches,
buildViewConfigSaveBody,
} from './objectViewTabs.js';
// objectstack#25992 slice 2: the view-options family and `dispatchViewPatches`
// moved to `./objectViewOptions.ts`; every name exported here before stays
// exported from here.
export {
timelineViewOptions,
calendarViewOptions,
ganttViewOptions,
galleryViewOptions,
kanbanViewOptions,
storedLegacyOptions,
dispatchViewPatches,
} from './objectViewOptions.js';
// objectstack#25992 slice 3: `ObjectNotFoundState` moved to `./objectViewChrome.tsx`
// and stays exported from here (`AppContent` imports it by this path).
export { ObjectNotFoundState } from './objectViewChrome.js';
/**
* Props of the Console `ObjectView`, the route-level object surface
* `@object-ui/app-shell` exports (objectui#7483).
*
* The parameter used to be a bare `any`, which erased the prop NAMES as well as
* their values: a misspelled prop compiled clean and was silently dropped. As an
* object type, JSX excess-property checking now refuses a name that is not here,
* and the two required members are refused when omitted.
*
* Named `ConsoleObjectViewProps` rather than `ObjectViewProps` because
* `@object-ui/plugin-view` already owns that name for its schema-driven view,
* a different shape (objectui#6172: one authority per exported type name).
*/
export interface ConsoleObjectViewProps {
/** The host's data adapter — the published `DataSource` contract. */
dataSource: DataSource;
/**
* The app's object definitions. The view resolves the route's
* `:objectName` against this list and renders the "object not found"
* state when it is absent.
*/
objects: any[];
/** Opens a record for editing (the toolbar's and the drawer's edit action). */
onEdit: (record: Record<string, unknown>) => void;
/**
* Bumped by the host to refetch the list after a change made outside this
* view (for example a record saved in a form the host owns).
*/
externalRefreshKey?: number;
}
export function ObjectView({ dataSource, objects, onEdit, externalRefreshKey }: ConsoleObjectViewProps) {
const { objectName } = useParams();
// Resolve the object definition up front. When it's missing we render the
// "object not found" empty state *here*, before the inner component mounts.
// This is the key to keeping the Rules of Hooks satisfied: ObjectViewInner
// holds ~50 hooks and must call them unconditionally, so the missing-object
// branch lives in this thin wrapper instead of as a mid-component early
// return. The inner subtree then mounts/unmounts as a whole (object exists
// ↔ doesn't) rather than toggling the number of hooks executed per render.
const objectDef = objects.find((o: any) => o.name === objectName);
if (!objectDef) return <ObjectNotFoundState objectName={objectName} />;
return (
<ObjectViewInner
dataSource={dataSource}
objects={objects}
onEdit={onEdit}
externalRefreshKey={externalRefreshKey}
/>
);
}
/**
* Inner ObjectView body. Only mounted by {@link ObjectView} once the object
* definition is known to exist, so every hook below runs unconditionally on
* every render of this component — no early return sits between hook calls.
*/
function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: ConsoleObjectViewProps) {
const navigate = useNavigate();
// The router's root href, basename included: the join every console host
// publishing `recordHref` uses (`documentHref`, objectui#12233).
const routerRootHref = useHref('/');
const { appName, objectName, viewId } = useParams();
// objectui#12606 — inside the Setup app the list drops its `#` row
// numbers (see the `ListView` below). Read off
// the route's own `:appName`, the one signal the page header reads too.
const inSetup = isSetupAppSegment(appName);
const [searchParams, setSearchParams] = useSearchParams();
const location = useLocation();
const { showDebug } = useMetadataInspector();
const { t, language } = useObjectTranslation();
const { objectLabel, objectPluralLabel, objectDescription: objectDesc, viewLabel, viewEmptyState, actionParamText, fieldLabel, fieldOptionLabel } = useObjectLabel();
// The views a server read served — `/meta/view`, and the object document's
// own `listViews` — already translated: their labels are drawn as given,
// every other view's through `viewLabel` (objectui#11295, objectui#11336).
const servedViews = useServedViewItems();
// label + confirmText + successMessage through ONE call (objectui#4265).
const localizeActionTexts = useActionTextLocalizer();
// ADR-0105: under group posture default list columns get a trailing
// organization_id attribution column (reads span all the user's orgs).
const orgAttribution = useTenancyPosture() === 'group';
// ADR-0034: runtime view edits persist via the metadata draft/publish
// model (the `sys_view` table is retired).
const metadataClient = useMetadataClient();
// ADR-0037: in draft-preview mode (`?preview=draft`), `listViews()` reads
// the draft-overlaid world so a view just created via "Add View" shows up
// in the ViewTabBar before it is published. Normal mode sees published
// views only (the publish gate stays intact).
const previewDrafts = usePreviewDrafts();
// Inline view config panel state (Airtable-style right sidebar)
const [showViewConfigPanel, setShowViewConfigPanel] = useState(false);
const [viewConfigPanelMode, setViewConfigPanelMode] = useState<'create' | 'edit'>('edit');
// Airtable-style "Create view" dialog (type picker + name input)
const [showCreateViewDialog, setShowCreateViewDialog] = useState(false);
// Manage Views dialog (vertical sortable list of all views)
const [manageViewsOpen, setManageViewsOpen] = useState(false);
// Draft state for view config edits — cached locally, saved on demand
const [viewDraft, setViewDraft] = useState<Record<string, any> | null>(null);
// objectui#12504 — no toolbar control writes the shared view. The sort and
// the column layout (objectui#12418), the density and the Hide Fields
// popover (objectui#12474) are the user's own list state (`listPrefs`), and
// the shared view is written only by an explicit save
// (`handleViewConfigSave`, below). The toolbar-to-view writer that lived
// here, `persistViewPatch`, retired with the adapter method it was the last
// caller of. ⛔ Do not bring one back: `ObjectView.overlayPatchOnly.test.ts`
// pins its absence.
/*
* There is deliberately NO `persistViewFilter` here (objectui#4155).
*
* The list toolbar's filter panel is the USER's state — it belongs to the
* session and to that user's own list state (`listPrefs`, objectui#12418),
* not to the view's stored body. It used to persist: every `onFilterChange` the panel
* emitted was folded and written to the view overlay, so merely opening the
* panel and clicking `Add filter` wrote an incomplete `field equals ''`
* condition into `sys_metadata` — which then REPLACED the source-declared
* `filter` for every user of that view and emptied the list, unrecoverably
* from the panel itself.
*
* The threshold for writing a view overlay is an EXPLICIT save:
* `handleViewConfigSave` (the view config panel) and `handleSaveAsView`
* (`ObjectDataPage`). `ObjectDataPage` already made this choice for the
* sibling surface — "Deliberately NO onSortChange/onFilterChange
* persistence hooks: this surface never writes back to any saved view"
* (#2251) — and this surface was the outlier.
*
* `foldFilterGroupToSpecRules` (objectstack#5159) is still the one dialect
* for those explicit paths — the Studio inspector's `FilterBuilderField`
* folds through it. What is gone is the automatic write, not the fold.
*/
/**
* The view-config panel's edit Save. Resolves whether the draft was staged,
* so the panel stays dirty, and announces no draft, on anything but `true`
* (objectui#11583).
*/
const handleViewConfigSave = useCallback(async (draft: Record<string, any>): Promise<boolean> => {
setViewDraft(draft);
setRefreshKey(k => k + 1);
// ADR-0034: stage a per-item draft via the metadata seam; an explicit
// Publish (RuntimeDraftBar) promotes it + records a version.
const vid = draft.id;
if (!metadataClient || !vid) {
console.warn('[ViewConfigPanel] Cannot persist view config: missing metadataClient or viewId.');
return false;
}
try {
// `dataSource` + `objectName` let the seam drop this object's view
// cache keys (#4373) — the adapter owns which keys those are.
await persistRuntimeMetadata('view', vid, buildViewConfigSaveBody(objectName, draft), {
metadataClient,
dataSource,
objectName,
});
return true;
} catch (err) {
console.error('[ViewConfigPanel] Failed to persist view config:', err);
// objectui#11583: a refused save is SAID, with the door's own
// message, as the Create View doors do (objectui#11578).
toast.error(t('form.saveError'), {
description: formatMetadataError(err),
classNames: { description: 'whitespace-pre-line' },
});
return false;
}
}, [metadataClient, dataSource, objectName, t]);
/**
* Create a new view: the Create View dialog's door and the view-config
* panel's create mode. Resolves whether the view was saved, so the dialog
* closes only on `true` (objectui#11578).
*/
const handleViewCreate = useCallback(async (config: Record<string, any>): Promise<boolean> => {
try {
let createdId: string | undefined;
if (metadataClient) {
// ADR-0005 overlay path — write the full spec under a unique
// `name` via the metadata customization API instead of into
// the physical `sys_view` table (whose columns no longer
// accommodate the spec shape: arrays, nested objects, etc.).
// The spec comes from the builder "Save as view" also uses
// (`buildAddViewSpec` → `buildNewViewSpec`, objectui#11581):
// this door supplies only its default business columns.
const objectDef = objects?.find?.((o: any) => o.name === objectName);
const spec = buildAddViewSpec(config, objectDef);
// ADR-0034: a new view is created as an invisible per-item
// draft via the metadata seam; an explicit Publish promotes it.
// The auto-activation below stays here; the canonical ViewItem
// envelope + qualified-name identity live in the seam.
//
// #2767 P1: the qualified name `<object>.<key>` is used as BOTH
// the URL segment and `body.name`, so the sys_metadata row key,
// the ViewTabBar tab id, and the body identity all agree and the
// draft → read → publish loop resolves.
const env = viewEnvelope(objectName, spec, {
name: (config as any)?.name,
label: config.label,
});
createdId = await createRuntimeMetadata('view', env.name, env, {
metadataClient,
// #4373: this flow is the second door into the same rows the
// adapter caches. Hand it the adapter (the `dataSource` prop
// IS the `ObjectStackAdapter`, via `AppContent`'s
// `useAdapter()`) so the seam can drop the object's view keys.
dataSource,
objectName,
});
}
setShowViewConfigPanel(false);
setViewConfigPanelMode('edit');
setRefreshKey(k => k + 1);
// Auto-activate the newly created view (Airtable parity), and close
// the main-path loop (#2767 P4): a fresh view is a DRAFT, invisible
// to a normal (published-only) read, so navigating there plainly
// would land on "view not found". Enter draft-preview mode
// (`?preview=draft`) instead — the DraftPreviewBar then lets the
// user verify and Publish in one click. If already in preview, the
// sticky provider keeps the flag, so no suffix is needed.
if (createdId) {
const previewSuffix = previewDrafts
? ''
: `?${PREVIEW_QUERY_FLAG}=${PREVIEW_QUERY_VALUE}`;
if (viewId) {
navigate(`../${createdId}${previewSuffix}`, { relative: 'path' });
} else {
navigate(`view/${createdId}${previewSuffix}`);
}
}
return true;
} catch (err) {
console.error('[ViewConfigPanel] Failed to create view:', err);
// objectui#11578: a refused save is SAID, with the door's own
// message (the field-anchored issues of a 422, or the refusal's
// text), and reported to the dialog as unsaved so it stays open.
toast.error(t('form.saveError'), {
description: formatMetadataError(err),
classNames: { description: 'whitespace-pre-line' },
});
return false;
}
}, [dataSource, objectName, objects, navigate, viewId, metadataClient, previewDrafts, t]);
// Record count tracking for footer
const [recordCount, setRecordCount] = useState<number | undefined>(undefined);
// Admin users automatically get design tools (no toggle needed)
const { user, activeOrganization } = useAuth();
const { isAdmin } = useWorkspaceAdminStatus();
const perms = usePermissions();
// Get Object Definition. The outer ObjectView wrapper already guards the
// missing-object case, so this always resolves while this component is
// mounted — every hook below can therefore run unconditionally.
const objectDef = objects.find((o: any) => o.name === objectName);
// The page's favorites entry, in the header's overflow menu (objectui#12427):
// it pins the app's own navigation entry for this list when the app has one,
// and keeps an `object:` favorite only for an object the app does not list.
// The entry the list is starred under is named with the plural the title
// reads (objectui#11733).
const listFavorite = useObjectListFavorite({
appSegment: appName,
objectName,
label: objectPluralLabel(objectDef),
});
// A view stored with no `label` is named by the object's plural label, on
// its tab and on the record page's way back alike (objectui#12774).
const unlabelledViewText = objectPluralLabel(objectDef);
// Refresh trigger — bumped after view CRUD or this page's own data writes.
const [ownRefreshKey, setRefreshKey] = useState(0);
/**
* objectui#10572 — the page's refresh signal: its own counter plus the
* console's `externalRefreshKey` (record-form save, undo, redo), summed IN
* THE RENDER that receives the prop. Both only grow, so the sum moves
* whenever either does, and every reader below sees an external bump in the
* same commit as the prop.
*
* It used to be MIRRORED instead: a passive effect copied each external
* bump into this counter one commit later. The console declares the same
* undo / redo on the data-invalidation bus in the same tick as the bump,
* and `ListView` reads that bus, so the mirror split one write into two
* list reads — the bus nonce in one commit, `refreshTrigger` in the next.
* PR objectui#10494's contract is that a writer's two notices land in one
* render; summing here keeps this host inside it. ⛔ Do not reintroduce the
* mirror, and do not add `externalRefreshKey` on top of a value that still
* mirrors it — either one reaches the list twice.
*/
const refreshKey = ownRefreshKey + (typeof externalRefreshKey === 'number' ? externalRefreshKey : 0);
/**
* objectui#10035 — this page learned that the object's DATA changed by a
* path that is not a data-source write the console's
* `useMutationInvalidationBridge` announces: a server action, flow or API
* action (raw HTTP), an import (`importRecords` emits no `onMutation`), a
* realtime event (another user's write), an explicit refresh action, or a
* delete this page ran. The counter reaches `ListView`'s own rows as
* `refreshTrigger`; the renderers that query for themselves (`ObjectGrid`,
* `ObjectGantt`, `ObjectChart`) read the data-invalidation bus instead, so
* the change is declared there too — AGENTS.md #8's corollary. It used to
* reach them only by remounting the whole list.
*
* View CRUD (rename, pin, reorder, config save) keeps bumping the counter
* alone: it changes the view's metadata, not the object's data, and the new
* view config reaches every renderer as props.
*
* objectui#13057 — a refresh also re-reads the saved views from the server.
* The adapter answers `listViews` from the published view list it stored
* for this open, so the refresh drops that list first; the counter bump
* then re-runs the saved-views read below, which asks the server again.
*/
const refreshData = useCallback(() => {
dropPublishedViewList(dataSource);
setRefreshKey((k) => k + 1);
if (objectDef.name) notifyDataChanged({ objectName: objectDef.name });
}, [dataSource, objectDef.name]);
// Shared console action runtime: confirm/param/result dialogs, the
// authenticated api/flow/server-action handlers, SPA navigation, and the
// paused screen-flow runner. The same runtime PageView mounts (#1605).
// ObjectView additionally feeds its confirm/toast handlers into
// useObjectActions below, so it consumes the hook directly (rather than the
// ConsoleActionRuntimeProvider wrapper).
const actionRuntime = useConsoleActionRuntime({
dataSource,
objects,
objectName: objectDef.name,
onRefresh: refreshData,
// A `type: 'form'` action on the list opens its form in this app's
// shell (objectui#13433).
routeAppSegment: appName,
});
const { confirmHandler, toastHandler } = actionRuntime;
// Environment list (sys_environment) is entitlement- + state-aware: born
// with one production env per org, its single `create_environment` action
// means different things — "Set up your production environment", "Add
// development environment", or a locked plan-tier mark linking to the
// upgrade page (objectui#12190) — depending on org state.
// Resolved org-side here; the hook is a no-op for every other object.
const isEnvironmentList = objectDef.name === 'sys_environment';
const environmentEntitlements = useEnvironmentEntitlements({
enabled: isEnvironmentList,
dataSource,
authFetch: actionRuntime.authFetch,
apiBase: (import.meta as any).env?.VITE_SERVER_URL || '',
refreshKey,
});
// objectui#12109 — this object's list actions are drawn only for a caller
// who may read the object. Every one of them is bound to it (an action's
// `objectName` is what merges it into `objectDef.actions`), and a caller
// without read gets the list's "You don't have access" under them, so a
// drawn action could only end there. The verdict is the one the sidebar
// prunes this object's navigation entry on (`mayReadObject`), so the entry
// and its list actions go together. A boolean, read each render from the
// provider's verdict, so the memo below keys on a primitive (AGENTS.md #10).
const listActionsReadable = mayReadObject(perms.can, objectDef.name);
const listActions = listActionsReadable ? objectDef.actions : undefined;
// Localized `list_toolbar` actions, shared by the generic action bar and the
// environment-aware toolbar (the action:bar renderer filters by location).
// The header reads them through `headerToolbarActions`, which drops the
// selection bar's duplicates once the active view is resolved (objectui#12462).
const localizedToolbarActions = useMemo(
() => (listActionsReadable ? objectDef.actions || [] : []).map((a: any) => localizeActionTexts(objectDef.name, a)),
[objectDef, localizeActionTexts, listActionsReadable],
);
// Resolve which generic CRUD affordances belong in the toolbar for
// this object's lifecycle bucket (`managedBy`). config tables show
// New/Edit/Delete but no CSV Import; system / append-only / better-auth
// hide the lot — those flows go through purpose-built actions on the
// source record (e.g. "Submit for Approval" on an Opportunity creates
// an `sys_approval_request`). Permissions still gate the buttons.
// [objectstack#3391] Intersect the bucket affordances with the server's effective API
// operation set for this object (from /me/permissions apiOperations), so the
// toolbar never offers Import/Export/New/Edit/Delete the server would 405.
// `undefined` (unrestricted object / old backend) leaves affordances as-is.
// objectui#12082: New and Import are the `listNew` / `listImport` rows of
// the affordance-to-grant map (`resolveAffordance` in `@object-ui/core`),
// which ANDs the caller's create grant onto that intersection itself and
// surfaces the row's `userActions` predicates only when all three allow it.
// The identity-import bypass below is independent of the `listImport` row.
const { newVerdict, importVerdict } = useMemo(() => {
const source = { objectSchema: objectDef as SchemaLike, objectName: objectDef.name, perms };
return {
newVerdict: resolveAffordance('listNew', source),
importVerdict: resolveAffordance('listImport', source),
};
}, [objectDef, perms]);
// Externally-triggered refreshes (e.g. global ModalForm submit, undo, redo)
// reach every `refreshKey` reader through the sum declared with the counter
// above (objectui#10572), not through a mirroring effect.
/**
* [#5153] The object-list toolbar's CREATE predicates — the `create` half
* of the toolbar-scope pair on THIS surface. #4646 (PR #5145) gave
* `createPredicates` a consumer on the **related list**
* (`RelatedRecordActionsBridge`); the standalone object-list page kept
* gating its "New" on the object-level verdict alone, so one
* `userActions.create` object form got two different verdicts depending on
* which surface rendered the button — honoured on a record page's related
* list, ignored here. `visibleWhen: false` (the objectui#3492 shape) did
* not hide this "New".
*
* BINDING, LAYERING and the fail-CLOSED / fail-SOFT split are the import
* half's, immediately below, verbatim — the spec types the two toolbar keys
* identically and binds them in one breath. See that docblock for the
* reasoning; the only thing that differs here is which affordance is gated.
*
* TWO RENDER POINTS, ONE VERDICT. The affordance surfaces twice on this
* page — the PageHeader button (desktop) and the phone-only floating "+"
* that stands in for it once the header is hidden. They are one affordance
* rendered twice, so both consume these SAME two values; computing the
* predicate once here is what keeps them from disagreeing with each other.
*/
const objectCanCreate = newVerdict.allowed;
const createPredicates: RowCrudPredicates | undefined = newVerdict.predicates;
/** `visibleWhen` — fails CLOSED, declared-ness by `?? true`. As Import. */
const createVisible = useRowPredicate(createPredicates?.visibleWhen ?? true, null, {
fallback: false,
warnOnError: true,
label: 'builtin:create:visibleWhen',
});
/** `disabledWhen` — fails SOFT, `!= null` declared-ness OUTSIDE the eval. */
const createDisabledPred = useRowPredicate(createPredicates?.disabledWhen, null, {
fallback: false,
warnOnError: true,
label: 'builtin:create:disabledWhen',
});
const createDisabled = createPredicates?.disabledWhen != null && createDisabledPred;
/**
* objectui#11687 — does this page offer a way to add a row? The New button
* above, or a `list_toolbar` action the schema-driven toolbar draws (Invite
* User, Register OAuth Application, …), each by the verdict its own control
* renders on. The managed-by empty state reads it: a `better-auth` list
* must not say rows are "not added by hand here" beside such a button.
* A boolean, computed each render from the payload (`objectDef.actions`),
* so `renderListView` depends on a primitive, not a memoised identity
* (AGENTS.md #10).
*/
/**
* objectui#13089 — the view's `addRecord` Add button opens this page's own
* create (`actions.create`, the header New's), so it is offered exactly
* where that New is offered and live: the object-level verdict, the
* toolbar-scope `visibleWhen`, and not greyed by `disabledWhen` (`ListView`
* draws no greyed Add button). A boolean, so `renderListView` depends on
* a primitive (AGENTS.md #10).
*/
const listAddRecordOpensCreate = objectCanCreate && createVisible && !createDisabled;
const mayInvokeToolbarAction = useCapabilityGate();
const toolbarPredicateScope = usePredicateScope();
const pageOffersCreate =
(objectCanCreate && createVisible) ||
listToolbarDrawsAction(listActions, mayInvokeToolbarAction, toolbarPredicateScope);
/**
* [#5142] The object-list toolbar's IMPORT predicates — the `import` half
* of the toolbar-scope pair the spec resolver emits, mirroring what
* `RelatedRecordActionsBridge` does for `create` (objectui#4646).
*
* `@objectstack/spec@17.0.0` types `userActions.create` and
* `userActions.import` identically and `resolveCrudAffordances` emits a
* predicate envelope for each; the docblock binds them in one breath
* ("`importPredicates` — same binding as `createPredicates`"). #4646 gave
* `create` a consumer and left `import` declared-and-inert: an author could
* write `userActions.import.visibleWhen`, have the spec accept it and the
* resolver parse it, and watch this toolbar offer the CSV wizard anyway.
*
* BINDING (the spec docblock's, not an invention here). Unlike the ROW
* predicates, a toolbar predicate evaluates ONCE per toolbar against the
* record of the scope the toolbar sits in — the host parent record on a
* related list, and **no record at all on a standalone object list**, which
* is what this surface is. So `null` is passed deliberately below: a
* predicate reading `record.*` has nothing to bind, faults, and — per the
* fail-CLOSED rule — hides the button, exactly as the spec spells out.
* Predicates over the host scope (`os.user.*` / `features.*`) bind normally
* and are the meaningful shape here.
*
* LAYERING: surfaced only when the object-level verdict already passed —
* the same posture the related-list bridge takes, because a predicate may
* not RE-OPEN what the bucket, the effective API operations (objectstack#3391) or the
* principal's grant have closed. The identity-import bypass below is a
* different affordance entirely (it does not read the `listImport` row) and
* is deliberately left outside this layer.
*/
const objectCanImport = importVerdict.allowed;
const importPredicates: RowCrudPredicates | undefined = importVerdict.predicates;
/**
* `visibleWhen` — fails CLOSED, and counts as DECLARED by `?? true` rather
* than by truthiness, so `visibleWhen: false` hides Import instead of
* reading as "ungated" (the objectui#3492 invariant). The `true` default is
* a boolean, which the evaluator short-circuits without touching the engine
* — an object with no import predicates pays no evaluation at all.
*/
const importVisible = useRowPredicate(importPredicates?.visibleWhen ?? true, null, {
fallback: false,
warnOnError: true,
label: 'builtin:import:visibleWhen',
});
/**
* `disabledWhen` — fails SOFT (an unevaluable predicate must not grey a
* button forever), with the `!= null` declared-ness gate OUTSIDE the
* evaluation so `disabledWhen: ''` reads as "no condition" rather than as
* "disable". Verbatim the posture of the record header (PR #4515), the
* row kebab, and the related-list toolbar.
*/
const importDisabledPred = useRowPredicate(importPredicates?.disabledWhen, null, {
fallback: false,
warnOnError: true,
label: 'builtin:import:disabledWhen',
});
const importDisabled = importPredicates?.disabledWhen != null && importDisabledPred;
// Import wizard open/close state — toolbar entry triggers it.
const [showImport, setShowImport] = useState(false);
// ─── Identity import (framework#2782) ────────────────────────────────
// sys_user's generic import affordance stays FALSE (a data-layer insert
// would bypass better-auth's hashing and never create a credential), but
// platform admins get the same wizard wired to the dedicated
// /api/v1/auth/admin/import-users pipeline. Gated on the deployment's
// admin surface (features.admin from /api/v1/auth/config) plus the
// caller being a workspace admin (the server re-checks, ADR-0068).
// objectui#13330 — and never on a managed environment
// (`features.cloudManaged`): there the server answers `admin/import-users`
// with 409 `RESOURCE_CONFLICT`, because people arrive from the hosting
// organisation through its identity provider.
const { features } = useExpressionContext();
const isIdentityImport = objectDef.name === IDENTITY_IMPORT_OBJECT;
const identityImportEnabled =
isIdentityImport && features?.admin === true && isAdmin && !isManagedEnvironment(features);
// ─── Setup → Users on a managed environment (objectui#13330) ─────────
// The line that says where people are invited, and the marker on a user
// who holds no permission set beyond the baseline. The marker reads the
// grant rows through one loader per list (`managedEnvironmentUsers.tsx`),
// rebuilt when the list refreshes, so a grant made elsewhere shows on the
// next load. The metadata store is read through a ref: its context value is
// rebuilt whenever any cached type settles (AGENTS.md #10).
const managedUsers = objectDef.name === MANAGED_USERS_OBJECT && isManagedEnvironment(features);
const metadataStore = useMetadata();
const metadataStoreRef = useRef(metadataStore);
metadataStoreRef.current = metadataStore;
const grantLoaderRef = useRef<{ refreshKey: number; source: unknown; loader: UserGrantLoader } | null>(null);
if (
managedUsers &&
dataSource &&
(grantLoaderRef.current?.refreshKey !== refreshKey || grantLoaderRef.current?.source !== dataSource)
) {
grantLoaderRef.current = {
refreshKey,
source: dataSource,
loader: new UserGrantLoader(dataSource as any, {
ensureType: (type: string) => metadataStoreRef.current.ensureType(type),
getTypeStatus: (type: string) => metadataStoreRef.current.getTypeStatus?.(type) ?? 'ready',
}),
};
}
const grantLoader = managedUsers ? grantLoaderRef.current?.loader : undefined;
const managedUserMarker = useCallback(
(row: Record<string, unknown>) => {
const id = row?.id ?? row?._id;
if (!grantLoader || id === undefined || id === null || id === '') return null;
return <UnauthorizedUserMarker loader={grantLoader} userId={String(id)} t={t} />;
},
[grantLoader, t],
);
const [identityPasswordPolicy, setIdentityPasswordPolicy] = useState<IdentityPasswordPolicy>('auto');
const identityPolicyRef = useRef<IdentityPasswordPolicy>('auto');
identityPolicyRef.current = identityPasswordPolicy;
const identityDataSource = useMemo(
() => (identityImportEnabled
? createIdentityImportDataSource({
base: dataSource,
authFetch: actionRuntime.authFetch,
baseUrl: import.meta.env.VITE_SERVER_URL || '',
getPasswordPolicy: () => identityPolicyRef.current,
})
: undefined),
[identityImportEnabled, dataSource, actionRuntime.authFetch],
);
// ─── User-defined views (metadata overlay) ──────────────────────────
// Saved views created via the ViewConfigPanel ("Add View") live in the
// metadata overlay (`/meta/view`). We fetch them via `listViews` and merge
// into `views` so the ViewTabBar renders them alongside metadata-defined
// listViews.
const [savedViews, setSavedViews] = useState<any[]>([]);
// objectui#12418 — the signed-in user's OWN list state for this object:
// the tab order, and per view the sort, the Filter panel's conditions and
// the column layout. A toolbar change writes here (`sys_user_preference`
// `ui.list.<object>`, localStorage as the cache), never into the shared
// view: the view's authored values stay the default for every user with
// no preference. See `ListPreferencesProvider`.
const listPrefs = useObjectListPreferences(objectName);
// Content keys, not identities (AGENTS.md #10): the views memo and the list
// relay re-run when what the user stored changes, and on nothing else.
const prefViewOrderKey = JSON.stringify(listPrefs.preference.viewOrder ?? []);
useEffect(() => {
let cancelled = false;
if (!objectName) {
setSavedViews([]);
return;
}
// Read saved views from the metadata overlay (`/meta/view`) via the
// adapter's `listViews`. Adapters without it surface no saved views.
if (typeof (dataSource as any)?.listViews === 'function') {
(dataSource as any).listViews(objectName, { previewDrafts })
.then((rows: any[]) => {
if (cancelled) return;
// Normalize: ensure each view has an `id` for ViewTabBar
// (which is name-keyed downstream).
//
// objectui#11013 — no `objectName` is stamped here any more.
// It was read `sv.objectName || sv.object`, the undeclared
// spelling first, and no reader of this array consumed the
// stamp: the handlers act on the route's `objectName`. What
// it did do was ride a saved view's whole-body toolbar save
// back into the stored row, an undeclared key the console
// itself minted. The row's bound object is its declared
// `object`, which `listViews()` carries.
const normalized = (rows || []).map((sv: any) => ({
...sv,
// Overlay rows are keyed by `name`. Prefer that as the
// tab id so a duplicate's `id` field (which may have
// been copied verbatim from the source artifact) does
// not collide with the source's view id during dedup.
// `viewRowId` owns that rule for every consumer of this
// array too, so the key written here and the key read
// back cannot drift apart (objectui#4211).
id: viewRowId(sv),
}));
setSavedViews(normalized);
})
.catch((err: any) => {
console.error('[ObjectView] Failed to load overlay views:', err);
if (!cancelled) setSavedViews([]);
});
return () => { cancelled = true; };
}
// No overlay API available (e.g. a minimal adapter / test mock) → no
// saved views. The retired `sys_view` table is no longer read.
setSavedViews([]);
return () => { cancelled = true; };
}, [dataSource, objectName, refreshKey, previewDrafts]);
// Persisted per-view config overrides: the rows stored under a view's id,
// separately from `objectDef.listViews` (the embedded definition) — an
// explicit save's, and the personalization overlays an earlier console's
// toolbar wrote (that write retired in objectui#12504; the rows at rest are
// still read). Org-wide shared settings (objectstack#7494's ruling), not a
// per-user preference. Keyed by viewId → partial view config to merge.
//
// Reading strategy (batch first, per-view fallback) lives in the exported
// `loadViewOverrides` above so it can be pinned directly — see its doc for
// why an empty batch result is authoritative but a rejected one is not.
const [viewOverrides, setViewOverrides] = useState<Record<string, any>>({});
useEffect(() => {
let cancelled = false;
if (!dataSource || !objectName) {
setViewOverrides({});
return;
}
// `listViews` is canonical (#5362; @objectstack/spec declares only camelCase). The
// `list_views` leg is a compatibility READ for stored pre-settlement documents
// (that stock has never been censused: objectstack#7917). Never WRITE the snake key.
const definedViews = (objectDef.listViews || objectDef.list_views || {}) as Record<string, any>;
const ids = Object.keys(definedViews);
// Include the primary view id so overrides apply to it too. Its identity
// comes from the view composer (objectui#3770) — the same id the override
// was persisted under, since a view's stored row is named by its view id.
const primaryId = defaultListViewId(objectDef.name, (objectDef as any).list);
if (primaryId && !ids.includes(primaryId)) ids.unshift(primaryId);
if (ids.length === 0) {
setViewOverrides({});
return;
}
loadViewOverrides(dataSource, objectName, ids).then((map) => {
if (!cancelled) setViewOverrides(map);
});
return () => { cancelled = true; };
}, [dataSource, objectName, objectDef.listViews, objectDef.list_views, (objectDef as any).list, refreshKey]);
// Resolve Views from objectDef.listViews (camelCase per @objectstack/spec)
const { list: views, derivedColumnViewIds } = useMemo(() => {
// Default columns for the auto-generated "所有记录" view (and any saved
// grid view with no explicit columns). `highlightFields` (ADR-0085) wins;
// otherwise the first business fields — framework-injected system / audit
// / ownership columns (notably the non-readonly `owner_id`) are excluded
// by the shared classifier. #2702 applied this to ObjectGrid /
// InterfaceListPage; this view resolves its columns here (#2777).
const resolveDefaultColumns = (): string[] =>
defaultListColumnsFromObject(objectDef, 5, { orgAttribution });
const viewList = buildViewTabs({
definedViews: objectDef.listViews || objectDef.list_views || {},
primary: (objectDef as any).list,
primaryId: defaultListViewId(objectDef.name, (objectDef as any).list),
savedViews,
viewOverrides,
// No `columns` here: the fill below derives them, and records
// the tab as one whose columns the author never declared.
fallbackTab: () => ({
id: 'all',
label: t('console.objectView.allRecords'),
type: 'grid',
}),
});
// Apply default columns to any grid-like view that has no explicit
// columns (e.g. saved views created via "Add View" before the user
// configured fields). Without this, the grid renders an empty header
// row and the data fetch omits a `select` clause.
//
// objectui#10694 — the fill DRAWS defaults; it does not DECLARE a
// projection. `ListViewSchema.columns` (spec source at objectstack
// `origin/main`, objectstack#19598): "An empty list declares no
// projection, so neither of them applies" — `hiddenFields` and
// `fieldOrder`. So every tab filled here is recorded, and the relay
// applies neither key to it (see `activeViewDeclaresColumns`). An
// ABSENT `columns` reads the same as an empty one: the spec requires
// the key, so absence declares no projection either.
const GRID_LIKE = new Set(['grid', 'list', 'table']);
const derived = new Set<string>();
for (const v of viewList) {
if (!GRID_LIKE.has(v.type)) continue;
if (!Array.isArray(v.columns) || v.columns.length === 0) {
v.columns = resolveDefaultColumns();
derived.add(v.id);
}
}
// Stable sort: respect the user's own view-order preference (for both
// metadata and saved views; objectui#12418, `listPrefs`). Falls back
// to: metadata views first in declared order, then saved views by
// `sortOrder` / created_at — the authored order, every user's default.
const indexOf = new Map(viewList.map((v, i) => [v.id, i]));
const userOrder: string[] = JSON.parse(prefViewOrderKey);
const userOrderIndex = new Map(userOrder.map((id, i) => [id, i]));
viewList.sort((a, b) => {
const aUser = userOrderIndex.get(a.id);
const bUser = userOrderIndex.get(b.id);
if (aUser !== undefined && bUser !== undefined) return aUser - bUser;
if (aUser !== undefined) return -1;
if (bUser !== undefined) return 1;
const aSaved = savedViews.find((sv: any) => viewRowId(sv) === a.id);
const bSaved = savedViews.find((sv: any) => viewRowId(sv) === b.id);
const aHasOrder = aSaved && typeof aSaved.sortOrder === 'number';
const bHasOrder = bSaved && typeof bSaved.sortOrder === 'number';
// Only an explicit user `sortOrder` should reorder views away from
// the metadata-declared sequence. A bare overlay row (no sortOrder)
// must not demote a metadata view: that would break primary-view
// promotion (which relies on declared order) for objects whose
// overlay seeded a baseline `sys_view` row without sort info.
if (aHasOrder && bHasOrder) {
if (aSaved.sortOrder !== bSaved.sortOrder) {
return aSaved.sortOrder - bSaved.sortOrder;
}
return (aSaved.created_at || '').localeCompare(bSaved.created_at || '');
}
if (aHasOrder) return -1;
if (bHasOrder) return 1;
return (indexOf.get(a.id) ?? 0) - (indexOf.get(b.id) ?? 0);
});
return { list: viewList, derivedColumnViewIds: derived };
}, [objectDef, savedViews, viewOverrides, t, orgAttribution, prefViewOrderKey]);
// Active View State — merge saved draft if available for this view.
// Resolution priority: URL viewId → ?view= → user-marked default → first.
const defaultViewId = useMemo(() => {
const def = views.find((v: any) => v.isDefault);
return def?.id;
}, [views]);
// Canonical view ids are fully qualified (`<object>.<viewKind>`, see
// MetadataProvider), but nav items emit `viewName` verbatim — usually
// the short form — and legacy embedded listViews carry bare keys (incl.
// the `'all'` fallback). Resolve the URL-requested name in both
// directions, and never swallow a miss silently (#2217).
const requestedViewId = viewId || searchParams.get('view') || undefined;
const resolvedViewId = useMemo(
() => resolveViewId(requestedViewId, views.map((v: any) => v.id), objectDef.name),
[requestedViewId, views, objectDef.name],
);
useEffect(() => {
if (requestedViewId && !resolvedViewId) {
console.warn(
`[ObjectView] Requested view "${requestedViewId}" not found on object "${objectDef.name}"; ` +
`falling back to the default view. Known views: ${views.map((v: any) => v.id).join(', ')}`,
);
}
}, [requestedViewId, resolvedViewId, objectDef.name, views]);
// objectui#12112 — a requested view that missed may be one the server
// refuses this caller: `/meta/view` lists only the views they may open
// (objectstack#22731), so the switcher never carries it, while a URL still
// can. The by-name read tells a refusal from absence. It is asked by the
// canonical `OBJECT.KEY` name that route addresses a view item by (a short
// name is the key), and not in draft preview, whose list is the draft
// world while the probe reads the published one. A refusal replaces the
// list below; any other answer keeps the fall-back to the default view.
const missedViewName = requestedViewId && !resolvedViewId && !previewDrafts
? (requestedViewId.includes('.') ? requestedViewId : `${objectDef.name}.${requestedViewId}`)
: null;
const viewAccess = useMetaItemRefusal('view', missedViewName);
const activeViewId = resolvedViewId || defaultViewId || views[0]?.id;
const baseView = views.find((v: any) => v.id === activeViewId) || views[0];
const activeView = viewDraft && viewDraft.id === baseView?.id
? { ...baseView, ...viewDraft }
: baseView;
// objectui#12462 (ruling A-narrow) — the header does not draw a duplicate of
// the selection bar. The bar is the list toolbar in its selection mode: a
// `list_toolbar` action the ACTIVE view wires to it (`bulkActions`, or a
// `bulkActionDefs` entry) is still drawn at its declared placement, on the
// rows it acts on, so the header's permanent copy is the duplicate. Only a
// RECORD-SCOPED action leaves (`isRecordScopedAction`: it also mounts on
// rows or records). Launched from the header it runs on exactly one ticked
// row, which the bar's per-record run covers. An object-level action keeps
// its header entry, because it can run with nothing selected and the bar
// cannot. Nothing else moves: the bar reads the same view keys itself.
//
// The names are the ones `ObjectGrid` folds into its bar from the keys this
// page relays to it (see `renderListView`): every non-empty `bulkActions`
// name except `delete`, which the grid routes to its built-in bulk delete
// rather than to an object action, and the `name` of every `bulkActionDefs`
// entry the grid can render. Keyed on a string of the names, not on
// `activeView`, which is a fresh object on every render while a draft is