Repository navigation
Expand file tree
/
Copy pathAppContent.tsx
More file actions
1914 lines (1832 loc) · 102 KB
/
Copy pathAppContent.tsx
File metadata and controls
1914 lines (1832 loc) · 102 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
/**
* AppContent — inner SPA rendered under /apps/:appName/*.
*
* Owns the per-app shell: ConsoleLayout, CommandPalette, KeyboardShortcutsDialog,
* route table for object/dashboard/report/page views, and the global ModalForm
* used by ObjectView edit actions. The outer routing skeleton (BrowserRouter,
* AuthGuard, AdapterProvider, MetadataProvider, theme/toaster, /home, /login,
* /organizations) is provided by `createConsole` from @object-ui/app-shell.
*/
import { Routes, Route, Navigate, matchRoutes, useNavigate, useLocation, useParams, useSearchParams } from 'react-router-dom';
import { useState, useEffect, useCallback, useRef, lazy, Suspense, useMemo, createElement, type ComponentType, type ReactNode } from 'react';
import { useAssistant } from '../assistant/assistantBus.js';
import { ModalForm } from '@object-ui/plugin-form';
import { Empty, EmptyTitle, EmptyDescription, Button } from '@object-ui/components';
import { toast } from 'sonner';
import { useActionRunner, useGlobalUndo, useMutationInvalidationBridge, notifyDataChanged, FilterScopeProvider } from '@object-ui/react';
import { getRecordDisplayName } from '@object-ui/core';
import { useObjectTranslation, useObjectLabel } from '@object-ui/i18n';
import type { AppAccessVerdict, ConnectionState } from '@object-ui/data-objectstack';
import { useAuth, useWorkspaceAdminStatus } from '@object-ui/auth';
import { useMetadata } from '../providers/MetadataProvider.js';
import { useAdapter } from '../providers/AdapterProvider.js';
import { usePreviewDrafts } from '../preview/PreviewModeContext.js';
import { PreviewDraftEmptyState } from '../preview/PreviewDraftEmptyState.js';
import {
ExpressionProvider,
createExpressionEvaluator,
isObjectFieldVisible,
useExpressionPermissions,
useExpressionSystemPermissions,
} from '../providers/ExpressionProvider.js';
import { buildExpressionUser } from '../providers/expressionUser.js';
import { useTrackRouteAsRecent } from '../hooks/useTrackRouteAsRecent.js';
import { useHomePath } from '../hooks/useHomePath.js';
import { useSignedInUserLocale } from '../hooks/useUserLocale.js';
import { resolveRecordFormTarget, resolveRecordFormModalLayout, resolveNavigateCreateUrl, resolveNavigateEditUrl, resolvePostCreateTarget, recordFormCreateValues, readRecordFormCreateValues, RECORD_FORM_CREATE_VALUES_STATE } from '../utils/recordFormNavigation.js';
import { deriveRecordSurface, deriveRecordFlowSurface } from '@object-ui/plugin-view';
import { RECORD_FORM_PARAM, RECORD_FORM_OBJECT_PARAM, RECORD_FORM_LINK_PARAM } from '../urlParams.js';
import { appAddressSegment, appRouteSegment, canonicalAppPathname, matchAppBySegment } from '../utils/appRoute.js';
import { resolveHref, type NavTemplateContext } from '@object-ui/layout';
import type { NavigationItem } from '@object-ui/types';
// Components (eagerly loaded — always needed)
import { ConsoleLayout } from '../layout/ConsoleLayout.js';
import { CommandPalette } from '../chrome/CommandPalette.js';
import { ErrorBoundary } from '../chrome/ErrorBoundary.js';
import { LoadingScreen } from '../chrome/LoadingScreen.js';
import { RedirectWithSplash } from '../chrome/RedirectWithSplash.js';
import { ObjectView } from '../views/ObjectView.js';
// objectui#13052 — on its own line: the line above is the eager-walk control
// `scripts/__tests__/vite-declared-lazy-views.test.ts` reads verbatim.
import { ObjectNotFoundState } from '../views/ObjectView.js';
import { KeyboardShortcutsDialog } from '../chrome/KeyboardShortcutsDialog.js';
import { OnboardingWalkthrough } from '../chrome/OnboardingWalkthrough.js';
import { RouteFader } from '../chrome/RouteFader.js';
import { NavigationSyncEffect } from '../hooks/useNavigationSync.js';
import { AppNoAccessEmptyState } from './AppNoAccessEmptyState.js';
import { appNamesOnlyUnreadableObjects, appServesNoNavigation } from './appServesNoNavigation.js';
import {
useNavMemberGates,
navEntriesShownToMember,
navEntriesShownOncePendingReadsShow,
} from '../hooks/useNavMemberGates.js';
import { resolveSetupAppPath } from './ConsoleShell.js';
import { APP_ROUTE_METADATA_READS, collectRoutePaths, metadataReadsForAppRoute, type LazyMetadataType } from './appRouteMetadataReads.js';
import { readAppObjectScope } from './appObjectScope.js';
import { preferLocal } from '../utils/preferLocal.js';
import { SkeletonDashboard, SkeletonDetail, SkeletonGrid } from '../skeletons/index.js';
// Route-based code splitting — lazy-load less-frequently-used routes.
//
// objectui#12980 — every route element below is a `preloadableLazy`: its chunk
// import starts as soon as `AppContent` knows the route (`preloadAppRouteChunk`,
// in parallel with the route's metadata reads), not when the route element
// first renders. A plain `React.lazy` element first renders when the console
// chrome commits, so it suspends there even with the chunk cached, and its
// fallback is the boot splash: react-dom then holds that fallback for its
// reveal throttle (`FALLBACK_THROTTLE_MS`, 300 ms in react-dom 19.2) after the
// route's data was already in, about 0.28 s of splash on every console open,
// measured. A route element whose chunk has resolved by its first render
// renders the component itself and never suspends; one still in flight falls
// back to the lazy wrapper and its Suspense fallback, as before.
type RouteElementModule<P> = { default: ComponentType<P> };
interface PreloadableRouteElement<P> {
(props: P): ReactNode;
/** Starts the chunk import (once); a failed import may be started again. */
preload: () => Promise<RouteElementModule<P>>;
}
function preloadableLazy<P extends object>(load: () => Promise<ComponentType<P>>): PreloadableRouteElement<P> {
let resolved: ComponentType<P> | null = null;
let pending: Promise<RouteElementModule<P>> | null = null;
const preload = () => {
if (!pending) {
pending = load().then(
(component) => {
resolved = component;
return { default: component };
},
(err: unknown) => {
pending = null;
throw err;
},
);
}
return pending;
};
const Lazy = lazy(preload);
function RouteElement(props: P): ReactNode {
// Chosen once per mount: switching an instance from the lazy wrapper to
// the component would remount the route's whole subtree.
const [Component] = useState<ComponentType<P>>(() => resolved ?? Lazy);
return createElement(Component, props);
}
return Object.assign(RouteElement, { preload });
}
// Spelled `routeChunk.lazy(() => import('…'))` at every declaration below:
// `scripts/vite-declared-lazy-views.ts` reads AppContent's lazy route views by
// that text, and these are still exactly that (a dynamic import per view).
const routeChunk = { lazy: preloadableLazy };
const RecordDetailView = routeChunk.lazy(() => import('../views/RecordDetailView.js').then(m => m.RecordDetailView));
const DashboardView = routeChunk.lazy(() => import('../views/DashboardView.js').then(m => m.DashboardView));
const PageView = routeChunk.lazy(() => import('../views/PageView.js').then(m => m.PageView));
const ReportView = routeChunk.lazy(() => import('../views/ReportView.js').then(m => m.ReportView));
const AppReportIndexView = routeChunk.lazy(() => import('../views/AppReportIndexView.js').then(m => m.AppReportIndexView));
const SearchResultsPage = routeChunk.lazy(() => import('../views/SearchResultsPage.js').then(m => m.SearchResultsPage));
const RecordFormPage = routeChunk.lazy(() => import('../views/RecordFormPage.js').then(m => m.RecordFormPage));
const ComponentNavView = routeChunk.lazy(() => import('../views/ComponentNavView.js').then(m => m.ComponentNavView));
const ObjectDataPage = routeChunk.lazy(() => import('../views/ObjectDataPage.js').then(m => m.ObjectDataPage));
// Metadata admin — mounted under /apps/:app/metadata. Lives at the top
// level so URLs read like a normal nested resource (RFC-style) instead of
// piggy-backing on the legacy ComponentRegistry fan-out.
const MetadataDirectoryPage = routeChunk.lazy(() => import('../views/metadata-admin/index.js').then(m => m.MetadataDirectoryPage));
const MetadataResourceListPage = routeChunk.lazy(() => import('../views/metadata-admin/index.js').then(m => m.MetadataResourceListPage));
const MetadataResourceEditPage = routeChunk.lazy(() => import('../views/metadata-admin/index.js').then(m => m.MetadataResourceEditPage));
const MetadataResourceHistoryPage = routeChunk.lazy(() => import('../views/metadata-admin/index.js').then(m => m.MetadataResourceHistoryPage));
const MetadataDiagnosticsPage = routeChunk.lazy(() => import('../views/metadata-admin/index.js').then(m => m.MetadataDiagnosticsPage));
// App authoring + dashboard editor pages — sourced from
// @object-ui/plugin-designer so third-party hosts can opt out by not
// registering these routes.
const CreateAppPage = routeChunk.lazy(() => import('@object-ui/plugin-designer').then(m => m.CreateAppPage));
const EditAppPage = routeChunk.lazy(() => import('@object-ui/plugin-designer').then(m => m.EditAppPage));
const DashboardDesignPage = routeChunk.lazy(() => import('@object-ui/plugin-designer').then(m => m.DashboardDesignPage));
// Marketplace pages — first-class platform feature; mounted at `system/marketplace`
// under any active app so admins can browse + install from inside the runtime.
const MarketplacePage = routeChunk.lazy(() => import('./marketplace/MarketplacePage.js').then(m => m.MarketplacePage));
const MarketplacePackagePage = routeChunk.lazy(() => import('./marketplace/MarketplacePackagePage.js').then(m => m.MarketplacePackagePage));
/**
* objectui#12980 — the lazy element each `AppContent` route path renders
* (paths relative to `/apps/:appName`, as `appRouteMetadataReads.ts` spells
* them). A path not listed renders an eagerly bundled element.
*/
const APP_ROUTE_CHUNKS: ReadonlyArray<{ path: string; chunk: { preload: () => Promise<unknown> } }> = [
{ path: 'metadata', chunk: MetadataDirectoryPage },
{ path: 'metadata/_diagnostics', chunk: MetadataDiagnosticsPage },
{ path: 'metadata/:type', chunk: MetadataResourceListPage },
{ path: 'metadata/:type/new', chunk: MetadataResourceEditPage },
{ path: 'metadata/:type/:name', chunk: MetadataResourceEditPage },
{ path: 'metadata/:type/:name/history', chunk: MetadataResourceHistoryPage },
{ path: ':objectName/new', chunk: RecordFormPage },
{ path: ':objectName/data', chunk: ObjectDataPage },
{ path: ':objectName/record/:recordId', chunk: RecordDetailView },
{ path: ':objectName/record/:recordId/edit', chunk: RecordFormPage },
{ path: ':objectName/record/:recordId/page/:pageName', chunk: RecordDetailView },
{ path: 'dashboard/:dashboardName', chunk: DashboardView },
{ path: 'report/:reportName', chunk: ReportView },
{ path: 'reports', chunk: AppReportIndexView },
{ path: 'page/:pageName', chunk: PageView },
{ path: 'component/:ns/:name/*', chunk: ComponentNavView },
{ path: 'design/dashboard/:dashboardName', chunk: DashboardDesignPage },
{ path: 'search', chunk: SearchResultsPage },
{ path: 'create-app', chunk: CreateAppPage },
{ path: 'edit-app/:editAppName', chunk: EditAppPage },
{ path: 'system/marketplace', chunk: MarketplacePage },
{ path: 'system/marketplace/:packageId', chunk: MarketplacePackagePage },
];
/**
* Starts the chunk import of the lazy element the route at `subPath` renders.
* Matched the way `<Routes>` ranks paths, beside every eagerly rendered path
* `AppContent` and the host declare, so a path that resolves to an eager
* element (or to a host route) starts nothing.
*/
function preloadAppRouteChunk(subPath: string, hostPaths: readonly string[] = []): void {
const routes = [
...APP_ROUTE_METADATA_READS.map(({ path }) => ({
path,
chunk: APP_ROUTE_CHUNKS.find((row) => row.path === path)?.chunk,
})),
...hostPaths.map((path) => ({ path, chunk: undefined })),
];
const matches = matchRoutes(routes, `/${subPath.replace(/^\/+/, '')}`);
const chunk = matches?.[matches.length - 1].route.chunk;
// A failed import rejects here as well as in the route's own render; the
// render's error boundary is the one that reports it.
if (chunk) void chunk.preload().catch(() => {});
}
interface AppContentProps {
/**
* Extra <Route> elements appended to the inner /apps/:appName/* router.
* Hosts can use this to mount console-specific routes (e.g. /system, legacy
* metadata editor) without forking AppContent.
*/
extraRoutes?: ReactNode;
/**
* Extra <Route> elements rendered when there is no active app but the URL
* matches a special path (create-app, system). Mirrors `extraRoutes` for
* the no-app branch.
*/
extraRoutesNoApp?: ReactNode;
}
/**
* Bridges the global chat's "Review N change(s)" affordance (ADR-0033 Phase B)
* to the metadata designer. The chat publishes a review target on `assistantBus`;
* this navigator — which lives inside the app router and knows the app base —
* routes to `/apps/:appName/metadata/:type/:name?review=1`, where the designer
* reloads the pending draft and opens its review/diff.
*/
function DraftReviewNavigator({ appName }: { appName: string | undefined }) {
const { reviewSeq, reviewTarget } = useAssistant();
const navigate = useNavigate();
const lastSeq = useRef(reviewSeq);
useEffect(() => {
if (reviewSeq === lastSeq.current || !reviewTarget || !appName) return;
lastSeq.current = reviewSeq;
const { type, name } = reviewTarget;
navigate(
`/apps/${appName}/metadata/${encodeURIComponent(type)}/${encodeURIComponent(name)}?review=1`,
);
}, [reviewSeq, reviewTarget, appName, navigate]);
return null;
}
/**
* The predicate-evaluation identity `ExpressionProvider` binds as
* `current_user` / `ctx.user` / `os.user`.
*
* MOVED to `../providers/expressionUser.js` in objectui#6515 and re-exported
* here so the published name is unchanged. It moved because `AppContent`
* `lazy()`-loads `views/RecordFormPage.tsx`, which mounts an
* `ExpressionProvider` of its own: importing the normaliser from THIS module
* would put a static edge from that split chunk back into the module it was
* split out of — the edge `scripts/check-eager-closure-budget.mjs` weighs — so
* the view hand-rolled a narrower descriptor instead, and the `id` /
* `isPlatformAdmin` it dropped made every predicate naming them FAULT and fail
* OPEN. The new home is a leaf module beside the provider it feeds, which every
* mount site can import without dragging a chunk along.
*
* This re-export is the back-compat half of that move; the doc comment that
* explains the SHAPE lives with the function.
*/
export { buildExpressionUser };
/**
* The console URL that renders a record on a NAMED record page
* (objectui#12715): `/apps/APP/OBJECT/record/ID/page/PAGE`.
*
* The record route `:objectName/record/:recordId` shows a record on the page
* its object's page assignment picks (the object's default record page). This
* sibling names the page in the path instead, so a document that is not the
* default (a print page, a delivery note) renders for the same record at a URL
* a browser can load. It is a path segment, the way the record route already
* spells its `/edit` sub-route, never a query: an optional query would let a
* stray parameter change which document the default route draws, and `page` is
* a page-scoped list parameter elsewhere. `RecordDetailView` renders the named
* page only when it is a record page of OBJECT, and shows a not-found state for
* any other name; it never falls back to the default page. The server's print
* service binds to this spelling, so it is exported for the route test to pin.
*/
export const RECORD_NAMED_PAGE_ROUTE = ':objectName/record/:recordId/page/:pageName';
export function AppContent({ extraRoutes, extraRoutesNoApp }: AppContentProps = {}) {
const [connectionState, setConnectionState] = useState<ConnectionState>('disconnected');
const { user, getAuthConfig, activeOrganization } = useAuth();
// objectui#4473 — read at the top (hooks are unconditional); consumed by the
// no-app guard far below, where the comment explains what it decides.
const { isAdmin: isWorkspaceAdmin, isResolved: isWorkspaceAdminResolved } = useWorkspaceAdminStatus();
const dataSource = useAdapter();
// Deployment-level feature flags from `/api/v1/auth/config`. Used by
// CEL predicates on metadata actions (e.g. `sys_organization`'s
// create button is hidden when `multiOrgEnabled === false`). We keep
// it empty until the fetch resolves so predicates default to "visible"
// and we don't briefly hide UI on slow networks.
const [features, setFeatures] = useState<Record<string, any>>({});
useEffect(() => {
let cancelled = false;
getAuthConfig()
.then((cfg) => {
if (cancelled) return;
setFeatures((cfg?.features as Record<string, any>) ?? {});
})
.catch(() => {
/* leave empty — predicates default to visible */
});
return () => {
cancelled = true;
};
}, [getAuthConfig]);
const navigate = useNavigate();
const location = useLocation();
const { appName } = useParams();
// ⛔ `objects` is not destructured here: reading it loads the whole registry
// (objectui#12811). It is read below only on a route that needs all of it.
const metadata = useMetadata();
const { apps, loading: metadataLoading, ensureType, getTypeStatus, error: metadataError, refresh: refreshMetadata, readObjectScope } = metadata;
// objectui#7373 — where this file's two "you cannot be here" exits land. Both
// sit BELOW the readiness gate further down (`metadataLoading` &c), so the
// list they resolve against has settled; an app list that failed to load is
// `[]`, which resolves to the launcher — the unchanged status quo, never a
// worse answer than the literal it replaced.
const homePath = useHomePath();
const previewDrafts = usePreviewDrafts();
const { t } = useObjectTranslation();
const { objectLabel, objectPluralLabel } = useObjectLabel();
// Hidden apps (`App.hidden`) are excluded from app-listing surfaces
// (sidebar switcher, home grid, app switcher). The active app for the
// current route is still looked up across ALL apps so /apps/account
// resolves correctly; only the fallback (no appName → first app)
// skips hidden apps to avoid landing the user on a personal-settings
// app by default.
//
// ⛔ `hidden` only — never `_unpublished` (objectstack#6955 / objectstack-ai/objectstack#4829 A1). The
// publish gate is enforced server-side; duplicating it here would strand a
// builder on their own unpublished app.
const activeApps = apps.filter((a: any) => a.active !== false);
const launcherApps = activeApps.filter((a: any) => a.hidden !== true);
// ADR-0048 (A) — the route segment is the package id; resolve by it,
// falling back to the app name (legacy/alias URL).
// Built-in pseudo-routes under /apps/* that are NOT metadata apps (create-app,
// system/*, metadata/*, setup). They must keep working — and may fall back to
// a default app — regardless of whether the segment resolves to an app.
// #3638 — `system` / `metadata` are matched as whole path SEGMENTS, not as
// substrings. `pathname.includes('/system')` was also true for any segment
// that merely STARTS with `system` (`system_log`, `system_setting`,
// `systems`), and likewise for `metadata` (`metadata_import`, …). That made
// `isSpecialRoute` true for an ordinary `/apps/:app/:objectName` URL whose
// object name happened to start that way — which suppressed
// `requestedAppMissing` below and let a MISTYPED app name silently render a
// DIFFERENT app (the exact failure the comment on the fallback describes).
// Every real pseudo-route spells them as full segments — `system/marketplace`,
// `system/metadata/:type`, `metadata/:type`, `component/metadata/resource` —
// so the segment test keeps all of them true (pinned in
// `__tests__/AppContent.pseudoRouteSegments.test.tsx`).
const pathSegments = location.pathname.split('/');
const isCreateAppRoute = location.pathname.endsWith('/create-app');
const isSystemRoute = pathSegments.includes('system');
const isMetadataRoute = pathSegments.includes('metadata');
const isSetupRoute =
location.pathname === '/apps/setup' || location.pathname.startsWith('/apps/setup/');
const isSpecialRoute = isCreateAppRoute || isSystemRoute || isMetadataRoute || isSetupRoute;
const matchedApp = matchAppBySegment(apps, appName);
const activeApp =
matchedApp ||
// Fall back to a default/first app only when NO specific app was requested
// (bare /apps, the default redirect) OR for a built-in pseudo-route above.
// A normal unmatched appName must NOT silently render a DIFFERENT app — the
// readiness guard below shows loading / not-available instead. (Fixes "the
// preview / nav renders the WRONG app right after building a new one".)
((!appName || isSpecialRoute)
? (launcherApps.find((a: any) => a.isDefault === true) || launcherApps[0])
: undefined);
// ADR-0048 (A) — the segment every `/apps/…` path this component builds is
// keyed on: the matched app's one address (`appAddressSegment` — its package
// id), else the URL's own, else the resolved app's route segment. Never
// `activeApp.name` raw: on a package-id route that is a second address for
// the same app, and the recent-items tracker below matches it against the URL
// (objectui#11818).
const appSegment = appAddressSegment(apps, matchedApp) ?? appName ?? appRouteSegment(activeApp);
// objectstack-ai/objectstack#26183 — a URL that reached the app through its
// NAME alias moves to the app's one address, path, search, hash and history
// state kept. The alias still opens (old bookmarks and shared links keep
// working), but a page left on it built every link on the alias while the
// sidebar built on the package id: one app, two address families. `replace`,
// so Back never returns to the alias. An effect rather than a `<Navigate>`
// return, so a layout already on screen is not unmounted for the swap.
const canonicalPathname = canonicalAppPathname(apps, appName, location.pathname);
useEffect(() => {
if (!canonicalPathname) return;
navigate(`${canonicalPathname}${location.search}${location.hash}`, {
replace: true,
state: location.state,
});
}, [canonicalPathname, location.search, location.hash, location.state, navigate]);
// objectui#12809 — the lazy metadata buckets the CURRENT route reads at
// render (`appRouteMetadataReads.ts` declares them per route). This used to
// be a preload of all four (`object`, `dashboard`, `report`, `page`) that held
// the splash on every route; now the splash holds only for the current
// route's, and a later navigation onto a route whose buckets have not landed
// shows a skeleton in the route slot (below) instead of an empty list or a
// "not found". The record-form overlay (`?form=`) edits a record of an object,
// so it reads `object` on any route.
const hostRoutePaths = useMemo(
() => [...collectRoutePaths(extraRoutes), ...collectRoutePaths(extraRoutesNoApp)],
[extraRoutes, extraRoutesNoApp],
);
const appSubPath = location.pathname.split('/').filter(Boolean).slice(2).join('/');
const routeReads = metadataReadsForAppRoute(appSubPath, hostRoutePaths);
// objectui#12980 — the route's element chunk loads beside its metadata reads,
// so it is in hand when the splash gate below passes (see `preloadableLazy`).
useEffect(() => {
preloadAppRouteChunk(appSubPath, hostRoutePaths);
}, [appSubPath, hostRoutePaths]);
// objectui#12811 — which objects this route and the chrome around it read:
// the app's object scope on the routes `appObjectScope.ts` names, inside an
// app whose served item carries its package; the whole registry everywhere
// else, as before (that module says why). A page route reads the objects
// its page binds (objectui#12980), resolved as `PageView` resolves the page,
// and a record route those of its declared record page (objectui#13046).
const {
candidate: scopeCandidate,
scope: objectScope,
ready: objectScopeReady,
failedNames: routeObjectReadsFailed,
routeObjectRefusal,
} = readAppObjectScope(
readObjectScope,
activeApp,
appSubPath,
location.search,
hostRoutePaths,
(pageName) => {
const status = getTypeStatus?.('page');
return {
page: preferLocal(metadata.pages as any[], pageName, (activeApp as any)?._packageId),
settled: status === undefined || status === 'ready' || status === 'error',
};
},
// objectui#13046 — a record route reads the objects its declared record
// page binds, picked from the page list as `RecordDetailView` picks it.
() => {
const status = getTypeStatus?.('page');
return {
pages: Array.isArray(metadata.pages) ? (metadata.pages as unknown[]) : [],
settled: status === undefined || status === 'ready' || status === 'error',
};
},
);
// Until the app list has loaded, a scope candidate does not know its package
// yet, and reads nothing (the splash is up).
const readsWholeRegistry = !scopeCandidate || (!metadataLoading && !objectScope);
const allObjects: any[] = objectScope
? objectScope.objects
: readsWholeRegistry ? metadata.objects : NO_OBJECTS;
const routeReadsKey = [
...routeReads.filter((type) => type !== 'object' || readsWholeRegistry),
...(searchParamsHasRecordForm(location.search) && !routeReads.includes('object') ? ['object'] : []),
].join(',');
const bucketsSettled = useLazyMetadataSettled(routeReadsKey, ensureType, getTypeStatus);
const routeReadsSettled = bucketsSettled && (!objectScope || objectScopeReady);
// Set once the first frame past the splash has rendered. After it, a route
// waiting on its buckets draws its skeleton inside the console chrome rather
// than taking the whole console back to the splash.
const firstPaintDone = useRef(false);
// A normal app was requested but isn't present in the loaded metadata — the
// post-publish readiness lag, or a genuinely-missing app. Applies in BOTH
// preview and published mode (preview already guarded this; published used to
// fall through to the wrong-app fallback above — the bug). Pseudo-routes are
// excluded so they keep their default-app fallback.
const requestedAppMissing = !!appName && !matchedApp && !isSpecialRoute;
// objectui#12706 — the pseudo-routes above skip `requestedAppMissing`, so
// until this the access verdict was never asked for them: a session the Setup
// app refuses (no `setup.access`; the server leaves Setup out of its list)
// opened `/apps/setup` and got the DEFAULT app's landing under that app's
// chrome, and `/apps/setup/metadata/...` drew Setup's item pages (the
// permission-set and position editors) the same way.
//
// Two of them now wait on the verdict for the app the URL names (the same
// probe as `requestedAppMissing` below) and draw the access-denied screen on
// `denied`: the metadata-admin routes (`metadata/...`, with the legacy
// spellings that redirect onto them) and Setup's root, the app's own landing.
// Every other verdict keeps the pseudo-route rendering above, so an app that
// does not exist, a server that does not answer and an adapter without the
// probe change nothing.
//
// ⛔ Not the rest of the Setup subtree. `/system/*` links forward onto
// `/apps/setup/system/*` (`SystemRedirect`, `ConsoleShell.tsx`), the server's
// approval links (`/system/approvals?request=`) among them, and that inbox
// opens records at `/apps/setup/OBJECT/record/ID` (`ApprovalsInboxPage`'s
// `recordHref`). A member reaches both under the Setup segment, so whether
// they wait on Setup's verdict is a product decision, left open on
// objectui#12706.
const isSetupRootRoute = location.pathname === '/apps/setup' || location.pathname === '/apps/setup/';
const appSurfaceAwaitsVerdict = !!appName && !matchedApp && (isMetadataRoute || isSetupRootRoute);
// Post-publish readiness: when a requested app isn't in the loaded metadata,
// re-check ONCE (the registry can lag a beat behind a publish) before
// concluding it's absent — so a just-built app resolves on its own instead
// of flashing "not available", while we still never render a foreign app.
//
// objectui#4522 — the run is stored WITH the app it ran for and read back
// only for that app. Held loose from a name, it was a flag for "a re-check
// HAS run", reset on exactly one condition: `requestedAppMissing` going
// false. Two missing apps in a row never satisfy that — `requestedAppMissing`
// is true before the transition and true after it — so the state rode across
// as 'done' and the SECOND app got no re-check at all. An app reached second
// in one mount (launcher, then a typo'd URL, then the real freshly-published
// app; or two attempts while a build lands) was shown "not available" with no
// refresh behind it. Same keying as `accessProbe` below, deliberately: one
// pattern in this file, not two.
const [missingRecheckRun, setMissingRecheckRun] =
useState<{ app: string; phase: 'checking' | 'done' } | null>(null);
const missingRecheck: 'idle' | 'checking' | 'done' =
missingRecheckRun && missingRecheckRun.app === appName ? missingRecheckRun.phase : 'idle';
useEffect(() => {
if (!requestedAppMissing) {
// ⛔ The `if` is load-bearing — do not "simplify" it into an
// unconditional `setMissingRecheckRun(null)` (or the functional form
// `run => run === null ? run : null`, which reads as if React's bailout
// covers it). `refreshMetadata` is a dep of this effect and its identity
// comes from the HOST's metadata context: the shipped `MetadataProvider`
// memoizes it, but a host — or a test — that hands back a fresh function
// each render makes this effect run after every render. With no state
// update in the body that is a no-op; with one, it is an infinite render
// loop, and the surface it starves is the LAZY route inside
// `ConsoleLayout`, which then never mounts. Measured while landing
// objectui#4522: 4250 un-acted updates in one second and a permanently
// empty content area on `/apps/setup/system/record/workgroups`, pinned
// now by `apps/console/src/__tests__/AppContent.systemHubRoutes.test.tsx`
// and by the resolved-app case in this state's own test file.
if (missingRecheckRun !== null) setMissingRecheckRun(null);
return;
}
if (missingRecheck === 'idle' && !metadataLoading && !previewDrafts && appName) {
const rechecked = appName;
setMissingRecheckRun({ app: rechecked, phase: 'checking' });
// Settled BY NAME rather than by the `cancelled` flag the probe below
// uses: this effect re-runs on its own state change, so a cleanup-based
// cancel would fire on the way out of 'checking' and strand the check
// there forever. A refresh landing late for a previous app leaves the
// current app's run untouched.
Promise.resolve(refreshMetadata()).finally(() =>
setMissingRecheckRun(run => (run?.app === rechecked ? { app: rechecked, phase: 'done' } : run)),
);
}
}, [requestedAppMissing, metadataLoading, previewDrafts, missingRecheck, missingRecheckRun, appName, refreshMetadata]);
// objectui#4252 — WHY the app is missing, once the re-check above has settled
// and it still is. The list this reads is the generic metadata list route
// `GET /api/v1/meta/:type`, requested with the SINGULAR type segment `app`
// (`MetadataProvider` → `client.meta.getItems('app')`), and the server filters
// it per session (`filterAppForUser`, `packages/rest/src/rest-server.ts`), so
// a withheld app and a nonexistent one are byte-identical in the list: both
// absent. Everything this component can read
// from the list has therefore already been read, and the remaining question
// has to be asked of the BY-NAME route, which answers it explicitly since
// objectstack#8013 (403 `PERMISSION_DENIED` for exists-but-unauthorized; 404
// for every kind of absence). The maintainer ruling put the answer there
// rather than as a flag in the list, so nothing below re-reads the list.
//
// Every verdict here is a MEASURED one, and the screen says only what was
// measured — never what it guesses. objectui#4252 applied that rule to
// `denied`; objectui#9262 applied the same rule to the rest of this screen's
// population, which was seven further causes wearing one sentence about
// publishing. `not_found` and `unreachable` are separate answers the
// transport had always given and the probe used to fold into one `unknown`
// (see `AppAccessVerdict`), so the branches below un-fold a collapse rather
// than ask anything new — the enumeration surface the 2026-08-12 ruling
// guarded is untouched, and the control plane still answers the same way for
// every app the caller may not see.
//
// `unknown` now means only "nothing was asked": a host injected a DataSource
// that cannot answer this (AGENTS #1). Guessing a cause for it would be the
// same defect mirrored, so it keeps the screen that asserts nothing.
// The verdict is stored WITH the app it describes, and read back only for
// that app. Two missing apps in a row keep `requestedAppMissing` true the
// whole way across, so nothing in this branch is reset by the transition — a
// verdict held loose from its name would ride into the next URL and answer
// for an app it never probed, telling a user their typo is a permission
// problem. (`missingRecheck` above had the same shape and the same defect —
// costing one skipped refresh rather than a wrong screen, which is why it was
// filed separately; objectui#4522 keyed it the same way.)
const [accessProbe, setAccessProbe] = useState<{ app: string; verdict: AppAccessVerdict } | null>(null);
// A missing app is asked once its re-check has settled; an app surface under
// a pseudo-route (objectui#12706, above) once the list has loaded, since a
// list still loading has matched nothing yet.
const verdictWanted =
(requestedAppMissing && missingRecheck === 'done') || (appSurfaceAwaitsVerdict && !metadataLoading);
useEffect(() => {
if (!verdictWanted || previewDrafts || !appName) {
// Cleared on the way out too, so the Retry button below (which returns
// `missingRecheck` to 'idle') re-asks instead of replaying an answer.
setAccessProbe(p => (p === null ? p : null));
return;
}
if (accessProbe?.app === appName) return;
const probe = dataSource?.probeAppAccess;
if (typeof probe !== 'function') {
// AGENTS #1 — the console is protocol-agnostic: a host may inject a
// DataSource that cannot answer this. `unknown` is exactly that: the
// question was never put, so the screen asserts nothing (objectui#9262).
setAccessProbe({ app: appName, verdict: 'unknown' });
return;
}
let cancelled = false;
const probed = appName;
void Promise.resolve(probe.call(dataSource, probed))
.then(verdict => { if (!cancelled) setAccessProbe({ app: probed, verdict }); })
// A probe that REJECTS has failed — `probeAppAccess` itself never throws,
// so reaching here means a host implementation did. That is the absence
// of an answer, not the absence of an app: `unreachable`, never `unknown`
// (which now means nothing was asked at all) — objectui#9262.
.catch(() => { if (!cancelled) setAccessProbe({ app: probed, verdict: 'unreachable' }); });
return () => { cancelled = true; };
}, [verdictWanted, previewDrafts, appName, accessProbe, dataSource]);
// Never the previous app's answer: while a probe for a newly-requested app is
// in flight, this is null and the branch below waits rather than rendering the
// one it already has.
const accessVerdict: AppAccessVerdict | null =
accessProbe && accessProbe.app === appName ? accessProbe.verdict : null;
useEffect(() => {
if (!activeApp?.name) return;
// ADR-0048 — build against the URL's own segment (`appSegment`, which may be
// the package id) so the match works and the redirect keeps the same segment;
// `activeApp.name` would flip a `/apps/<packageId>/…` URL to the name form.
const packageMetadataPath = `/apps/${appSegment}/metadata/package`;
if (
location.pathname === packageMetadataPath ||
location.pathname.startsWith(`${packageMetadataPath}/`)
) {
navigate(`/apps/${appSegment}/component/developer/packages`, { replace: true });
}
}, [activeApp?.name, appSegment, location.pathname, navigate]);
// objectstack-ai/objectstack#2604 — the create/edit overlay is URL-driven (`?form=new` / `?form=<id>`),
// not component state: the record form is a TASK overlay over the origin
// route, and putting its open-state in the URL makes browser Back close the
// overlay (returning to the intact origin) instead of abandoning the route
// with the overlay marooned on top. Same pattern as the detail drawer's
// `?recordId=…` (useUrlOverlay / ADR-0054 C3). Open pushes a history entry;
// every close strips the param with `replace` so no stale reopen-entry stays
// ahead in history.
const [searchParams, setSearchParams] = useSearchParams();
const recordFormParam = searchParams.get(RECORD_FORM_PARAM);
// objectstack-ai/objectstack#2604 D3 — child-task extension of the record-form URL contract:
// `formObject` names the object the form edits when it is NOT the route's
// object (a subtable child opened over its parent's detail); `formLink`
// ("field:id") pre-links the parent on create. Keeping the whole task in
// the URL means Back closes the overlay and a refresh reopens it still
// correctly parent-linked — no transient component state to lose.
const formObjectParam = searchParams.get(RECORD_FORM_OBJECT_PARAM);
const formLinkParam = searchParams.get(RECORD_FORM_LINK_PARAM);
const editingRecord = useMemo(
() => (recordFormParam && recordFormParam !== 'new' ? { id: recordFormParam } : null),
[recordFormParam],
);
const formLinkValues = useMemo(() => {
if (!formLinkParam) return undefined;
const i = formLinkParam.indexOf(':');
if (i <= 0) return undefined;
return { [formLinkParam.slice(0, i)]: formLinkParam.slice(i + 1) };
}, [formLinkParam]);
const [refreshKey, setRefreshKey] = useState(0);
const isDialogOpen = !!recordFormParam;
// objectui#12291 — a seeded create's values, carried by the history entry
// that opened the overlay (`handleEdit` below). The object the router keeps
// for that entry, so its identity holds until the entry changes.
const overlayCreateValues = editingRecord ? undefined : readRecordFormCreateValues(location.state);
// Close the record-form overlay by stripping `?form` in place. Reads the
// LIVE location (not the hook's render-time snapshot) so it stays a no-op
// when a success handler already navigated away in the same tick (the
// post-create redirect below).
const closeRecordForm = useCallback(() => {
const sp = new URLSearchParams(window.location.search);
if (!sp.has(RECORD_FORM_PARAM) && !sp.has(RECORD_FORM_OBJECT_PARAM) && !sp.has(RECORD_FORM_LINK_PARAM)) return;
sp.delete(RECORD_FORM_PARAM);
sp.delete(RECORD_FORM_OBJECT_PARAM);
sp.delete(RECORD_FORM_LINK_PARAM);
setSearchParams(sp, { replace: true });
}, [setSearchParams]);
const { execute: executeAction, runner } = useActionRunner();
// objectui#2269 — bridge every dataSource write (create/update/delete →
// MutationEvent) onto the invalidation bus, ONCE for the whole console.
// Readers (record detail, related lists, count badges) refetch in place;
// nothing is remounted for a data refresh.
useMutationInvalidationBridge(dataSource);
// objectui#10059 — the signed-in user's language has ONE source of truth,
// `sys_user.locale`. Mounted here, beside the bridge above, because it reads
// the column back off that bus: the profile page's language card writes the
// same column through the same adapter, so its save reaches this reader and
// the UI follows without a reload. See `hooks/useUserLocale.ts` for why the
// device-local value is a cache from here on rather than a second setting.
useSignedInUserLocale();
// objectui#11080 — both toasts read the session's language: the words around
// the operation's description are pack keys beside `actions.undo`, and the
// description itself is interpolated unchanged.
useGlobalUndo({
dataSource: dataSource ?? undefined,
onUndo: (op: any) => {
toast.info(t('actions.undoneOperation', { description: op.description }), { duration: 4000 });
setRefreshKey(k => k + 1);
// Precisely-scoped invalidation — UndoableOperation carries the target
// (objectName + recordId), so detail readers refresh in place too.
if (op?.objectName) notifyDataChanged({ objectName: op.objectName, recordId: op.recordId });
},
onRedo: (op: any) => {
toast.info(t('actions.redoneOperation', { description: op.description }), { duration: 3000 });
setRefreshKey(k => k + 1);
if (op?.objectName) notifyDataChanged({ objectName: op.objectName, recordId: op.recordId });
},
});
useEffect(() => {
runner.registerHandler('crud_success', async (action: any) => {
closeRecordForm();
setRefreshKey(k => k + 1);
toast.success(action.params?.message ?? 'Record saved successfully');
return { success: true, reload: true };
});
runner.registerHandler('dialog_cancel', async () => {
closeRecordForm();
return { success: true };
});
// Page-mode navigation handlers — declarative counterparts to the
// imperative `handleEdit` callback. These let JSON schemas open the
// full-screen create/edit pages directly via `<action:button>` without
// any custom code:
// { "type": "action:button", "actionType": "navigate_create",
// "properties": { "params": { "objectName": "..." } } }
// { "type": "action:button", "actionType": "navigate_edit",
// "properties": { "params": { "objectName": "...", "recordId": "..." } } }
// The button forwards `properties.params` as the runner's `params`,
// which is what the handlers below read (objectui#10289, ruling A: a
// node-level `params` is only the `ActionParam[]` input list).
// The `objectName` param falls back to the action context's
// `objectName` (set per view) so action buttons mounted inside an
// ObjectView can omit it.
// NOTE on duplication below: each handler reads `runner.getContext()`
// INSIDE its closure (at action-invocation time) rather than once at
// registration. Hoisting the call outside the registrations would
// freeze the context to whatever it was when the effect last ran,
// breaking dynamic per-view `runner.updateContext({ objectName, ... })`
// calls (used by ObjectView / RecordDetailView). Keep the call where
// it is.
runner.registerHandler('navigate_create', async (action: any) => {
const ctx = runner.getContext?.() ?? {};
const result = resolveNavigateCreateUrl({
action,
context: ctx,
defaultBaseUrl: `/apps/${appName ?? ''}`,
});
if (!result.success) return result;
navigate(result.url);
return { success: true };
});
runner.registerHandler('navigate_edit', async (action: any) => {
const ctx = runner.getContext?.() ?? {};
const result = resolveNavigateEditUrl({
action,
context: ctx,
defaultBaseUrl: `/apps/${appName ?? ''}`,
});
if (!result.success) return result;
navigate(result.url);
return { success: true };
});
// NOTE: `flow` actions are handled at the per-view ActionProvider level
// (RecordDetailView / ObjectView) so they share the same ActionRunner that
// <action:button> renderers consume via useAction(). Do NOT register a
// `flow` handler on this top-level useActionRunner — it lives on a
// different ActionRunner instance and would never be invoked from the
// record/list action buttons.
}, [runner, navigate, appName, closeRecordForm]);
useEffect(() => {
if (!dataSource) return;
const unsub = dataSource.onConnectionStateChange((event: any) => {
setConnectionState(event.state);
if (event.error) console.error('[Console] Connection error:', event.error);
});
setConnectionState(dataSource.getConnectionState());
return unsub;
}, [dataSource]);
const cleanParts = location.pathname.split('/').filter(Boolean);
let objectNameFromPath = cleanParts[2];
if (
objectNameFromPath === 'view' ||
objectNameFromPath === 'record' ||
objectNameFromPath === 'page' ||
objectNameFromPath === 'dashboard' ||
objectNameFromPath === 'design'
) {
objectNameFromPath = '';
}
const currentObjectDef = allObjects.find((o: any) => o.name === objectNameFromPath);
// The object the record-form overlay edits: the route's object by default,
// or the `formObject` child override (objectstack-ai/objectstack#2604 D3 — subtable child task opened
// over its parent's detail).
const formObjectDef = formObjectParam
? allObjects.find((o: any) => o.name === formObjectParam)
: currentObjectDef;
const isChildFormTask = !!formObjectParam && formObjectParam !== currentObjectDef?.name;
// objectstack-ai/objectstack#26172 — a record save names the record it wrote
// (`ux-conventions.write-feedback`): `Task "Quarterly review" created`. The
// name is the saved record's display name from the ONE ADR-0079 resolver,
// read through the object being saved. The resolver's floor (`Record #<id>`,
// or the empty fallback for an id-less row) is not a name, so a record with
// nothing nameable keeps the object-label toast it always had.
const recordSaveMessage = useCallback((saved: any): string => {
const label = formObjectDef ? objectLabel(formObjectDef as any) : t('common.record', { defaultValue: 'Record' });
const resolved = saved && typeof saved === 'object'
? getRecordDisplayName(formObjectDef, saved, { fallback: '' })
: '';
const id = saved?.id ?? saved?._id;
const title = resolved && !(id !== null && id !== undefined && resolved === `Record #${id}`)
? resolved
: undefined;
if (editingRecord) {
return title
? t('form.updatedNamed', { object: label, title, defaultValue: `${label} "${title}" updated` })
: t('form.updateSuccess', { object: label, defaultValue: `${label} updated successfully` });
}
return title
? t('form.createdNamed', { object: label, title, defaultValue: `${label} "${title}" created` })
: t('form.createSuccess', { object: label, defaultValue: `${label} created successfully` });
}, [editingRecord, formObjectDef, objectLabel, t]);
const handleCrudSuccess = useCallback((saved?: any) => {
executeAction({
type: 'crud_success',
params: { message: recordSaveMessage(saved) },
});
}, [executeAction, recordSaveMessage]);
const handleDialogCancel = useCallback(() => {
executeAction({ type: 'dialog_cancel' });
}, [executeAction]);
// objectstack-ai/objectstack#2604 save invariant — *edit never moves you; create takes you to the
// record you made.* Edit save: the origin route is untouched (crud_success
// bumps refreshKey → origin refetches in place). Create save: land on the
// new record's detail, on ITS derived surface — a light object's detail is
// the drawer over the still-intact list; a heavy one is the detail route.
// `replace: true` swaps out the transient `?form=…` entry so Back returns
// to the pre-create origin.
const handleRecordFormSuccess = useCallback(async (saved: any) => {
// Child task (objectstack-ai/objectstack#2604 D3): the parent detail must stay EXACTLY as it was —
// active tab, scroll, everything. So do NOT go through crud_success;
// the child's open related lists refetch on their own via the
// invalidation bus (#2269): the dataSource write already emitted a
// MutationEvent that the bridge fans out — no manual notify needed.
if (isChildFormTask) {
toast.success(recordSaveMessage(saved));
closeRecordForm();
return;
}
handleCrudSuccess(saved);
if (editingRecord || !currentObjectDef) return;
const target = resolvePostCreateTarget({
objectName: currentObjectDef.name,
baseUrl: appSegment ? `/apps/${appSegment}` : '',
pathname: location.pathname,
search: window.location.search,
surface: deriveRecordSurface(currentObjectDef),
recordId: saved?.id ?? saved?._id,
});
if (target.kind === 'none') return;
if (target.kind === 'detail-page') {
// The new record's detail is a fresh route carrying no `?from=` trail,
// so on its own it renders NO back affordance — a dead-end. Thread the
// create's originating route as a history-state `from`, mirroring
// ObjectView's list-row navigation (which is why clicking a row DOES
// yield a back link). The origin is a list/view route, not a record, so
// it rides history state rather than the record-only `?from=` trail.
const originSp = new URLSearchParams(window.location.search);
originSp.delete(RECORD_FORM_PARAM);
originSp.delete(RECORD_FORM_OBJECT_PARAM);
originSp.delete(RECORD_FORM_LINK_PARAM);
const originQs = originSp.toString();
const originPath = `${location.pathname}${originQs ? `?${originQs}` : ''}`;
// The origin is a list of the object's records, so the back link names
// it with the plural, as ObjectView's row navigation does (objectui#11733).
const originLabel = objectPluralLabel(currentObjectDef);
navigate(target.url, {
replace: true,
state: originLabel ? { from: { pathname: originPath, label: originLabel } } : undefined,
});
return;
}
navigate(target.url, { replace: true });
}, [handleCrudSuccess, recordSaveMessage, isChildFormTask, editingRecord, currentObjectDef, appSegment, location.pathname, navigate, closeRecordForm, objectPluralLabel]);
// Track recent items on route change. The hook matches `appName` against the
// pathname's app segment, so it takes the ROUTE SEGMENT: handed
// `activeApp.name`, it recorded nothing on a package-id route (objectui#11818).
useTrackRouteAsRecent({
pathname: location.pathname,
appName: appSegment,
objects: allObjects,
});
const handleEdit = (record: any) => {
// Page-mode opt-in: when the object metadata declares
// `editMode: 'page'`, route to the full-screen create/edit page instead
// of opening the global ModalForm. Default behavior (modal) is
// preserved for any object without the flag.
const target = resolveRecordFormTarget({
objectDef: currentObjectDef as any,
baseUrl: appSegment ? `/apps/${appSegment}` : '',
record,
});
if (target.kind === 'page') {
navigate(target.url);
return;
}
// Open the overlay via the URL (pushes one history entry → Back closes
// the overlay, origin intact). `new` = create; a record id = edit.
const rawId = record?.id ?? record?._id;
const sp = new URLSearchParams(window.location.search);
sp.set(RECORD_FORM_PARAM, rawId != null && rawId !== '' ? String(rawId) : 'new');
// Top-level task on the route's own object — drop any stale child-task
// overrides (see the record-form URL contract above).
sp.delete(RECORD_FORM_OBJECT_PARAM);
sp.delete(RECORD_FORM_LINK_PARAM);
// objectui#12291 — a new record that arrives carrying values (the
// calendar's empty-day hand-off sends the day clicked) opens the create
// form with them, riding the history entry this push makes
// (`RECORD_FORM_CREATE_VALUES_STATE`). Page mode carries them in its URL,
// above (`resolveRecordFormTarget`).
const createValues = recordFormCreateValues(record);
setSearchParams(
sp,
createValues ? { state: { [RECORD_FORM_CREATE_VALUES_STATE]: createValues } } : undefined,
);
};
const handleAppChange = (newAppName: string) => {
navigate(`/apps/${newAppName}`);
};
// Evaluator for the ModalForm's field-visibility gates below, over the SAME
// bag the `ExpressionProvider` this component mounts publishes — one builder,
// called with the same inputs (objectui#6493). This one sits ABOVE that
// provider in its own tree, so it cannot read it back through the hook; what
// it can do is stop hand-writing a second, narrower bag.
//
// Two roots the private bag dropped, both of which fail OPEN when named:
// `current_user` (and the `ctx.user` / `os.user` spellings of the same
// object) and `features`. Its `user` was hand-rolled too, without
// `positions` — so `'sales' in current_user.positions`, the gate the server
// enforces on write, faulted here rather than hiding the field.
// objectui#4421 — the same `permissions` input the provider below reads, so
// `current_user.can(...)` in a field's `visibleWhen` answers here exactly as
// it does under the provider (one bag, objectui#6493).
// objectui#13083 — and the `systemPermissions` list beside it, so
// `current_user.hasCapability(name)` answers here as it does under the
// provider (objectui#13006) instead of faulting on an unbound list.
const expressionPermissions = useExpressionPermissions();
const expressionSystemPermissions = useExpressionSystemPermissions();
const expressionEvaluator = useMemo(
// ⛔ No `app`: objectui#8155 removed it from the predicate scope, because
// neither ADR-0068 nor the engine's `SCOPE_ROOTS` declares such a root.
//
// ⛔ No `data` either: objectui#8166. This site passed `editingRecord` under
// that root, and it was the ONE mount in the repo where the ambient `data`
// was not empty — so an authored `visibleWhen: "data.status == 'x'"`
// RESOLVED here, silently, against the record being edited, while the SAME
// predicate on the SAME modal's per-field rules (form.tsx, over the
// provider's `data={{}}`) faulted, and the same predicate in CREATE mode
// (`editingRecord` null) faulted too. One authored string, three answers,
// none of them the row's canonical `record.*` binding (`83fe6e741`).
// The row reaches field predicates as `record`, from the form's own
// `ruleRecord` — not from this bag, which is why nothing is lost here.
() => createExpressionEvaluator({
user: buildExpressionUser(user),