Repository navigation
Expand file tree
/
Copy pathObjectView.tsx
More file actions
1692 lines (1627 loc) · 85.5 KB
/
Copy pathObjectView.tsx
File metadata and controls
1692 lines (1627 loc) · 85.5 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, type ReactNode } from 'react';
import { useParams, useSearchParams, useNavigate, useLocation, useHref, createSearchParams } from 'react-router-dom';
import { resolveAffordance, type FilterTokenScope, type SchemaLike } from '@object-ui/core';
import { useObjectListLayout } from './listLayoutStore.js';
const ImportWizard = lazy(() =>
import('@object-ui/plugin-grid').then((m) => ({ default: m.ImportWizard })),
);
import { ObjectView as PluginObjectView, ManageViewsDialog } from '@object-ui/plugin-view';
// 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 { CheckSquare, Plus } from 'lucide-react';
import { DropdownMenuItem, ObjectIconTile } from '@object-ui/components';
import { requestListSelection, useListPageSelectable, useListPageSelecting } from '@object-ui/plugin-grid';
import type { ListToolbarTrailingState } from '@object-ui/plugin-list';
import { usePublishPhonePageBar } from '../layout/PhonePageBar.js';
import { useObjectListFavorite } from '../layout/SidebarItemMenu.js';
import { useMetaItemRefusal } from '../hooks/useMetaItemRefusal.js';
import { useTenancyPosture } from '../hooks/useTenancyPosture.js';
import { useServedViewItems } from '../hooks/useServedViewItems.js';
import { servedObjectLabel, servedObjectPluralLabel } from '../hooks/servedObjectLabel.js';
import type { DataSource } from '@object-ui/types';
import { MetadataPanel, useMetadataInspector } from './MetadataInspector.js';
// objectstack#33293: the view config panel loads with the first list, not with
// the console. Statically, it held the view-variant inspector, `SchemaForm` and
// the Studio form widgets in the EAGER closure, so a dashboard route downloaded
// them too. It is drawn on every list (closed, it draws nothing), so its chunk
// is fetched as the list mounts, before any admin can open it.
const ViewConfigPanel = lazy(() =>
import('./ViewConfigPanel.js').then((m) => ({ default: m.ViewConfigPanel })),
);
import { useMetadataClient } from './metadata-admin/useMetadata.js';
import { dropPublishedViewList } from './metadata-admin/viewListDrop.js';
// objectstack#33582: the create-view dialog loads with the first list, as the
// view config panel above does. Statically, it held the dataset catalogue and,
// through it, the Studio `en` string namespace in the EAGER closure.
const CreateViewDialog = lazy(() =>
import('./CreateViewDialog.js').then((m) => ({ default: m.CreateViewDialog })),
);
import {
usePreviewDrafts,
} from '../preview/PreviewModeContext.js';
import { IDENTITY_IMPORT_WRITE_MODES } from './identityImport.js';
import { IdentityImportOptions, IdentityImportResultExtra, identityImportFields } from './IdentityImportPanels.js';
import { ManagedUsersInviteLine } from './managedEnvironmentUsers.js';
import { importTargetFields } from './importTargetFields.js';
import { resolveViewId } from '../utils/resolveViewId.js';
import { usePhoneViewport } from '../hooks/usePhoneViewport.js';
import { studioPackageId } from '../utils/appRoute.js';
import { usePinnedListView } from './pinnedListView.js';
import { defaultListViewId, isSavedViewId, viewRowId } from '../utils/viewIdentity.js';
import { usePackageSaveRead } from '../hooks/useStudioDesignGate.js';
import { useObjectActions } from '../hooks/useObjectActions.js';
import { useObjectTranslation, useObjectLabel } from '@object-ui/i18n';
import { usePermissions } from '@object-ui/permissions';
import { useAuth, useWorkspaceAdminStatus } from '@object-ui/auth';
import { ActionProvider, useActionTextLocalizer, RelatedRecordActionsProvider, notifyDataChanged } from '@object-ui/react';
import { toast } from 'sonner';
import { useConsoleActionRuntime } from '../hooks/useConsoleActionRuntime.js';
import {
VIEW_TYPE_ICONS,
FALLBACK_USER,
} from './objectViewHelpers.js';
import {
defaultListColumnsFromObject,
loadViewOverrides,
buildViewTabs,
} from './objectViewTabs.js';
import { ObjectNotFoundState } from './objectViewChrome.js';
import { useObjectViewLiveData } from './objectViewLiveData.js';
import { useObjectViewIdentity } from './objectViewIdentity.js';
import { useObjectViewRecordNavigation } from './objectViewRecordNavigation.js';
import { useObjectViewToolbarAffordances } from './objectViewToolbarAffordances.js';
import { useObjectViewHeaderToolbar } from './objectViewHeaderToolbar.js';
import { useObjectViewListUrlState, useObjectViewUrlFilters } from './objectViewListUrlState.js';
import { useObjectViewTitleSwitcher } from './objectViewTitleSwitcher.js';
import { useObjectViewPluginSchema } from './objectViewPluginSchema.js';
import { useObjectViewHeaderChrome } from './objectViewHeaderChrome.js';
import {
ListViewBarHostContext,
OBJECT_VIEW_PAGE_COLUMN_ATTR,
ObjectViewBarTrailing,
ObjectViewMoreMenu,
ObjectViewPageHeader,
type ObjectViewPageBarProps,
} from './objectViewPageHeader.js';
import { ObjectViewRecordOverlay } from './objectViewRecordOverlay.js';
import { useObjectViewListRenderer } from './objectViewListRenderer.js';
import { ListDraftActions } from './ListDraftActions.js';
import { viewSaveRefusalText } from './viewSaveRefusal.js';
import { listDraftPreference, listDraftScope, useListDraft } from './listDraftStore.js';
import { useObjectViewViewCrud, useRuntimeCreateApp } from './objectViewViewCrud.js';
import { mayShareViews, useViewSharing } from './objectViewViewSharing.js';
import { useCanAuthorMetadata } from '../hooks/useCanAuthorMetadata.js';
import {
PERSONAL_VIEW_OBJECT,
buildInPlaceViewConfig,
buildPersonalViewConfig,
layListStateOverView,
personalViewEntry,
personalViewPanelFilters,
usePersonalViews,
} from './personalViews.js';
import { PersonalViewNameDialog } from './PersonalViewNameDialog.js';
import { parseListStateParams } from './userFilterUrlState.js';
import { FILTER_FOLD_REFUSAL_KEYS } from './viewFilterFold.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, except `storedLegacyOptions`, retired with the `options`
// bag it read (#25923).
export {
timelineViewOptions,
calendarViewOptions,
ganttViewOptions,
galleryViewOptions,
kanbanViewOptions,
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();
const [searchParams, setSearchParamsNow] = useSearchParams();
// The router's setter is a new function whenever the search changes, and
// every list handler built on it (the URL state write-backs, the row
// click, the pane's step) would change with it: a `?recordId=` change —
// a row click, a step — would re-render the whole list (objectstack#27545).
// One setter for the page's life, calling the latest one.
const setSearchParamsRef = useRef(setSearchParamsNow);
setSearchParamsRef.current = setSearchParamsNow;
const location = useLocation();
// objectstack#30850 — the router hands a functional update the params it
// last RENDERED, and its navigation commits in a transition. Two writes
// before that commit (a search term, then the list's own page reset that
// term causes) would each start from the same params, and the second
// would drop the first. So each write starts from the one before it until
// the location moves (a new `location.key`, which every navigation makes).
const locationKeyRef = useRef(location.key);
locationKeyRef.current = location.key;
const pendingSearchRef = useRef<{ locationKey: string; params: URLSearchParams } | undefined>(undefined);
const setSearchParams = useCallback<typeof setSearchParamsNow>(
(next, options) => setSearchParamsRef.current((rendered) => {
const pending = pendingSearchRef.current;
const base = pending && pending.locationKey === locationKeyRef.current
? new URLSearchParams(pending.params)
: rendered;
const params = createSearchParams(typeof next === 'function' ? next(base) : next);
pendingSearchRef.current = { locationKey: locationKeyRef.current, params };
return params;
}, options),
[],
);
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);
// 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).
// What this list is titled: a served object's label is already translated
// (objectstack#30311), so it is drawn as given; the bundle is asked only
// when the definition carries none. The header, the favorite and an
// unlabelled view's tab all read this one function, so they agree.
const listTitleOf = useCallback(
(def: { name: string; label?: unknown; pluralLabel?: unknown }) => servedObjectPluralLabel(def, language, objectPluralLabel),
[language, objectPluralLabel],
);
const listFavorite = useObjectListFavorite({
appSegment: appName,
objectName,
label: listTitleOf(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 = listTitleOf(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;
// 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]);
// objectstack#25992 slice 7: environment entitlements, the list actions and the
// create and import toolbar verdicts moved to `./objectViewToolbarAffordances.ts`.
const {
isEnvironmentList,
environmentEntitlements,
listActions,
localizedToolbarActions,
objectCanCreate,
createVisible,
createDisabled,
listAddRecordOpensCreate,
pageOffersCreate,
objectCanImport,
importVisible,
importDisabled,
} = useObjectViewToolbarAffordances({
objectDef,
dataSource,
actionRuntime,
refreshKey,
perms,
localizeActionTexts,
newVerdict,
importVerdict,
});
// 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.
// Import wizard open/close state — toolbar entry triggers it.
const [showImport, setShowImport] = useState(false);
// objectstack#25992 slice 5: identity import and the managed-environment Users
// marker moved to `./objectViewIdentity.tsx`.
const {
identityImportEnabled,
managedUsers,
managedUserMarker,
identityPasswordPolicy,
setIdentityPasswordPolicy,
identityDataSource,
} = useObjectViewIdentity({ objectDef, isAdmin, dataSource, refreshKey, t, actionRuntime });
// ─── 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[]>([]);
// objectstack#29635 — the reader's own views of this object, My views
// (`sys_personal_view` rows, `./personalViews.ts`). They join the list's
// views below, so the switcher, the pin and the address resolve them like
// any other view; a reader the server grants nothing reads none.
const personalViews = usePersonalViews({ dataSource, objectName: objectDef.name, userId: user?.id, perms });
const personalViewIds = useMemo(
() => new Set(personalViews.views.map((v) => v.id)),
[personalViews.views],
);
// objectstack#35955 — the reader's list LAYOUT for this object, in this
// browser only (`./listLayoutStore.ts`): the tab order, and per view the
// column widths and the row height. Never written to the server or into
// the shared view: the view's authored values stay every other reader's.
const listLayout = useObjectListLayout(objectName);
// Content keys, not identities (AGENTS.md #10): the views memo and the list
// relay re-run when the reader's tab order changes, and on nothing else.
const prefViewOrderKey = JSON.stringify(listLayout.layout.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',
}),
});
// The reader's own views, after the object's (objectstack#29635). A
// row id never carries a `.`, so it never names a package view; one
// that collides with a view id here is not added a second time.
for (const personal of personalViews.views) {
if (!viewList.some((v) => v.id === personal.id)) viewList.push(personalViewEntry(personal) as (typeof viewList)[number]);
}
// 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; `listLayout`). 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, personalViews.views]);
// Active View State — merge saved draft if available for this view.
// Resolution priority: URL viewId → ?view= → the reader's pinned view →
// user-marked default → first.
const defaultViewId = useMemo(() => {
const def = views.find((v: any) => v.isDefault);
return def?.id;
}, [views]);
// objectstack#27594 — the view this reader pinned for the object (📌 in the
// title's view switcher), kept per object in the reader's workspace
// preferences. A pin naming a view the list no longer offers is no pin.
// Kept per organization (objectstack#36244): the pin can name a personal
// view, which exists in one organization only.
const [pinnedViewChoice, setPinnedViewChoice] = usePinnedListView(objectDef.name);
const pinnedViewId = useMemo(
() => resolveViewId(pinnedViewChoice, views.map((v: any) => v.id), objectDef.name) ?? null,
[pinnedViewChoice, views, objectDef.name],
);
// 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.
// objectstack#29635 — while the reader's own views are being read, a
// requested or pinned view the list does not hold yet may be one of them:
// the list waits for that read (`awaitingPersonalViews`), and the refusal
// probe is not asked. Any other open paints at once, and My views joins
// the switcher when the read lands.
const personalViewsLoading = personalViews.status === 'loading';
const awaitingPersonalViews = personalViewsLoading
&& ((!!requestedViewId && !resolvedViewId) || (!!pinnedViewChoice && !pinnedViewId));
const missedViewName = requestedViewId && !resolvedViewId && !previewDrafts && !personalViewsLoading
? (requestedViewId.includes('.') ? requestedViewId : `${objectDef.name}.${requestedViewId}`)
: null;
const viewAccess = useMetaItemRefusal('view', missedViewName);
// objectstack#36409 — a view the address names that the server says is
// gone (deleted, or never there): the list opens its default view, and
// says why once per name.
const goneViewNoticed = useRef<string | null>(null);
useEffect(() => {
if (!viewAccess.absent || !missedViewName || goneViewNoticed.current === missedViewName) return;
goneViewNoticed.current = missedViewName;
toast.info(t('view.switcher.viewGone', {
defaultValue: 'The view you opened is no longer available, so the list shows its default view.',
}));
}, [viewAccess.absent, missedViewName, t]);
const activeViewId = resolvedViewId || pinnedViewId || 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;
// The list's toolbar state is read through this field gate wherever it is
// read (the seed, Save as my view, 保存): a field the object does not
// declare, or one this reader cannot read, is no list state.
const acceptListField = (field: string) =>
!!objectDef.fields?.[field]
&& (!perms.isLoaded || perms.checkField(objectDef.name, field, 'read'));
// objectstack#30073 — a personal view's own conditions are Filter panel
// rows (`personalViewPanelFilters`), edited there and saved back by 保存.
// Keyed on the stored conditions' content (ui/AGENTS.md #10).
const activeIsPersonal = !!activeView?.id && personalViewIds.has(activeView.id);
const panelFiltersKey = activeIsPersonal ? JSON.stringify((activeView as any)?.filter ?? null) : '';
const viewPanelFilters = useMemo(
() => (panelFiltersKey ? personalViewPanelFilters(activeView, acceptListField) : undefined),
// eslint-disable-next-line react-hooks/exhaustive-deps -- keyed on the content the fold reads
[panelFiltersKey, objectDef, perms.isLoaded],
);
// objectstack#25992 slice 8: the header toolbar actions, the nav `runAction` deep link
// and the `action:bar` node moved to `./objectViewHeaderToolbar.ts`.
const { headerToolbarActions, toolbarActionsWithDeepLink, toolbarBar } = useObjectViewHeaderToolbar({
activeView,
localizedToolbarActions,
isEnvironmentList,
});
// objectstack#35955 — the open list's DRAFT: what the reader changed and
// has not saved (`./listDraftStore.ts`). It outlives this page while a
// record is open as a page, and goes when another view or object opens.
const listDraft = useListDraft(listDraftScope(user?.id, objectName ?? '', activeView?.id ? String(activeView.id) : ''));
/** The list on screen in the reader-state shape the view builders read (draft + kept widths and row height). */
const draftPreferenceOf = (id: string | undefined) =>
id ? listDraftPreference(listDraft.draft, listLayout.layout.perView?.[id]) : undefined;
/** The Display panel's layout and row colour the draft holds, for the view builders. */
const draftDisplay = {
...(listDraft.draft.viewType ? { viewType: listDraft.draft.viewType } : {}),
...(listDraft.draft.rowColor !== undefined ? { rowColor: listDraft.draft.rowColor } : {}),
};
// objectstack#25992 slice 8: the list's toolbar state in the URL (seed, write-back,
// "Reset view") moved to `./objectViewListUrlState.ts`.
const {
listIdentityKey,
listSeedRef,
ownListParamsRef,
writeListUrlState,
handleListPersonalizationChange,
listDraftParts,
handleResetView,
clearSourceListState,
readPanelFilters,
listPage,
} = useObjectViewListUrlState({
objectName,
objectDef,
activeView,
viewResolving: awaitingPersonalViews,
listDraft: listDraft.draft,
perms,
user,
searchParams,
setSearchParams,
});
// objectstack#35955 — Discard and Save at the condition row's end (the
// 「Personalized」 marker of objectstack#28950 before them): drawn only while
// the reader's list holds a draft, and the one way back to the view.
// objectstack#30073 — 保存: the list on screen written back into the open
// personal view, through the body Save as my view builds (so the stored
// shape is the same), then the reader's list state for it is cleared and
// the list opens again on the saved view. A panel the fold cannot write
// losslessly keeps the refusal Save as my view gives.
// The reader's own `sys_personal_view` rows: one grant read for Save as my
// view (create) and for Rename and 保存 (update).
const personalViewsReady = personalViews.status === 'ready';
const personalGrant = (action: 'create' | 'update') => !perms.isLoaded || perms.can(PERSONAL_VIEW_OBJECT, action);
const canUpdatePersonalView = activeIsPersonal && personalViewsReady && personalGrant('update');
const handleSaveToPersonalView = async () => {
if (!activeView || !activeIsPersonal) return;
const built = buildPersonalViewConfig(objectDef.name, activeView, {
// The panel's group is the one the list shows (an emptied panel
// included), not the address's copy of it.
url: { ...parseListStateParams(searchParams, acceptListField), filters: readPanelFilters() },
preference: draftPreferenceOf(activeView.id),
panelFilters: viewPanelFilters,
summaries: listDraft.draft.summaries,
display: draftDisplay,
});
if (!built.ok) {
toast.error(t('form.saveError'), { description: t(FILTER_FOLD_REFUSAL_KEYS[built.reason]) });
return;
}
try {
await personalViews.update(activeView.id, built.config);
// objectstack#35955 — the draft is the view now: Discard and Save
// go, and the list opens again on the saved view (its sort and
// filter chips stay, the view carries them).
handleResetView();
toast.success(t('console.objectView.draft.saved'));
} catch (err) {
console.error('[ObjectView] Failed to save a personal view:', err);
toast.error(t('form.saveError'), {
description: viewSaveRefusalText(err, t),
classNames: { description: 'whitespace-pre-line' },
});
}
};
// objectstack#29635 — the one test for creating one of the reader's own
// views, shared by Save as my view here and the view switcher's create
// card: a reader who cannot read the list's own object has no list to keep.
const listReadable = !perms.isLoaded || perms.can(objectDef.name, 'read');
const canCreatePersonalView = personalViewsReady && personalGrant('create') && listReadable && !!activeView && !viewAccess.refusal;
// objectstack#25992 slice 11b: the view-config save and create handlers, view switching
// and the view-tab CRUD callbacks moved to `./objectViewViewCrud.tsx` (the mobile view
// switcher it also registered retired with objectstack#27058).
const {
handleViewConfigSave,
handleDraftBarChange,
handleViewSaveAndPublish,
handleViewCreate,
handleViewUpdate,
handleViewChange,
handleCreateView,
handleViewAction,
handleRenameView,
handleDeleteView,
handleRestoreFactoryView,
handlePinView,
handleSetDefaultView,
handleReorderViews,
handleConfigView,
handleAddView,
} = useObjectViewViewCrud({
dataSource,
objects,
navigate,
objectName,
viewId,
t,
metadataClient,
previewDrafts,
setShowViewConfigPanel,
setViewConfigPanelMode,
setShowCreateViewDialog,
setViewDraft,
setRefreshKey,
confirmHandler,
savedViews,
listLayout,
views,
activeViewId,
baseView,
});
// objectstack#35955 — 「Save to this view」 on a shared view: offered to
// the reader who may edit it (an admin, on a view the metadata door
// stores, whose package takes saves). One confirm
// (everyone using the view sees it), then the list on screen is saved and
// published at once (ruling record 7058616478). A view with a pending
// draft is not saved: that draft is never published on its saver's
// behalf, and the reader is sent to the view settings. The reader's row
// height is theirs, never the view's: the view keeps its own.
//
// objectstack#36195 — whether the view's package takes saves is read
// before the save is offered: the open saved view's own package (its
// row's served `_packageId`, read for an admin only), and the save is not
// offered while that package list is unread (on a slow boot the list
// draws seconds before it lands) nor when it carries the package
// read-only. A failed read and a package the list leaves out still offer
// it, as before: the server's write gate refuses what it refuses, and
// the refusal is said in the reader's words (`viewSaveRefusalText`).
const activeSavedViewRow = activeView && isAdmin && !activeIsPersonal
? savedViews.find((sv: any) => viewRowId(sv) === activeView.id)
: undefined;
const activeViewPackageSaveRead = usePackageSaveRead(studioPackageId(activeSavedViewRow));
const canSaveToSharedView = !isEnvironmentList && !activeIsPersonal && !!activeView && isAdmin
&& activeViewPackageSaveRead === 'takes' && isSavedViewId(savedViews, String(activeView.id));
const handleSaveToSharedView = async () => {
if (!activeView || !canSaveToSharedView) return;
const confirmed = await confirmHandler(
// The view's name as its tab draws it (objectstack#35955 L1-b S1): a
// label is an I18nLabel with no default, so never the raw value.
t('console.objectView.draft.saveToViewConfirm', { name: listLabel }),
{
title: t('console.objectView.draft.saveToViewConfirmTitle'),
confirmText: t('console.objectView.draft.saveToViewConfirmButton'),
cancelText: t('console.objectView.cancel'),
},
);
if (!confirmed) return;
const pref = draftPreferenceOf(activeView.id);
const laid = layListStateOverView(activeView, {
url: { ...parseListStateParams(searchParams, acceptListField), filters: readPanelFilters() },
preference: pref ? { ...pref, rowHeight: undefined } : undefined,
panelFilters: viewPanelFilters,
summaries: listDraft.draft.summaries,
display: draftDisplay,
});
if (!laid.ok) {
toast.error(t('form.saveError'), { description: t(FILTER_FOLD_REFUSAL_KEYS[laid.reason]) });
return;
}
const outcome = await handleViewSaveAndPublish(laid.view);
if (outcome === 'pending-draft') {
toast.error(t('console.objectView.draft.pendingDraft'));
return;
}
if (outcome !== 'published') return;
// The draft is the view now, for everyone: Discard and Save go, and
// the list opens again on the saved view (its chips stay).
handleResetView();
toast.success(t('console.objectView.draft.savedForEveryone'));
};
// objectstack#35955 — Discard and Save while the list holds a draft, at
// the end of the condition row (the phone draws the same slot). 「Save to
// this view」 writes one of the reader's own views, or the shared view
// for a reader who may edit it; 「Save as my view」 asks a name.
const saveToThisView = canUpdatePersonalView
? () => { void handleSaveToPersonalView(); }
: canSaveToSharedView
? () => { void handleSaveToSharedView(); }
: undefined;
const draftActions = !isEnvironmentList && listDraftParts.length > 0 ? (
<ListDraftActions
parts={listDraftParts}
onDiscard={handleResetView}
onSaveToView={saveToThisView}
onSaveAsMyView={canCreatePersonalView ? () => setPersonalViewDialog({ mode: 'saveAs' }) : undefined}
/>
) : null;
// objectstack#29635 — creating one of the reader's own views, and Rename
// and Delete on them. Creating is offered to any reader the server lets
// save one (`sys_personal_view` read and create), not to admins only, in
// the view switcher's in-place create card (objectstack#35553, which
// folded Save as my view into it); a rename's name is asked in
// `PersonalViewNameDialog`. A reader who cannot read the list's own object
// is offered no create: there is no list to keep (`listReadable`, above).
const [personalViewDialog, setPersonalViewDialog] = useState<{ mode: 'rename'; viewId: string } | { mode: 'saveAs' } | null>(null);
const openPersonalView = (id: string) => {
if (viewId) navigate(`../${id}`, { relative: 'path' });
else navigate(`view/${id}`);
};
const handleRenamePersonalView = async (id: string, label: string): Promise<boolean> => {
try {
await personalViews.rename(id, label);
return true;
} catch (err) {
console.error('[ObjectView] Failed to rename a personal view:', err);
toast.error(t('objectViewActions.renameFailed'), {
description: err instanceof Error ? err.message : String(err),
classNames: { description: 'whitespace-pre-line' },
});
return false;
}
};
/** Delete one of the reader's own views through the owner's door; the list falls back to the default view. */
const handleDeletePersonalView = async (id: string) => {
const target = personalViews.views.find((v) => v.id === id);
if (!target) return;
const confirmed = await confirmHandler(
t('console.objectView.deleteViewConfirm', { name: target.label }),
{
title: t('console.objectView.deleteViewTitle'),
confirmText: t('console.objectView.delete'),
cancelText: t('console.objectView.cancel'),
},
);
if (!confirmed) return;
try {
await personalViews.remove(id);
// The reader's pin on it goes with it, and an address naming it
// gives way to the list's own default.
if (pinnedViewChoice === id) setPinnedViewChoice(null);
if (id === activeViewId && viewId) navigate('../..', { relative: 'path' });
} catch (err) {
console.error('[ObjectView] Failed to delete a personal view:', err);
toast.error(t('objectViewActions.deleteFailed'), {
description: err instanceof Error ? err.message : String(err),
classNames: { description: 'whitespace-pre-line' },
});
}
};
const renamingPersonalView = personalViewDialog?.mode === 'rename'
? personalViews.views.find((v) => v.id === personalViewDialog.viewId)
: undefined;
/**