Skip to content

Commit bd4f207

Browse files
committed
perf(app-shell): an object list loads the package ask, the view settings panel and the create-view dialog only when opened
The list route imported the package ask and the designer strings statically and drew the ask, the view config panel and the create-view dialog closed on every list, so ~183 KB (brotli) of authoring code was fetched before the list's first screen. Each now loads on its first opening and stays mounted after; a refused view create loads its words with the refusal. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01L9qibxzGFPvShbd2qnkdEv
1 parent 3511432 commit bd4f207

7 files changed

Lines changed: 327 additions & 29 deletions
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
---
2+
'@object-ui/app-shell': patch
3+
'@objectstack/console': patch
4+
---
5+
6+
perf(app-shell): an object list stops loading the package ask, the view settings panel and the create-view dialog before its first screen
7+
8+
Clause-②: no
9+
Metadata-protocol: none
10+
11+
An object list page fetched about 183 KB (brotli) of authoring code before its first screen, though it only needs that code when someone opens it. Three pieces did this. The "pick or create a package" ask that a view create may open was drawn closed on every list, and it brought in the package page's create dialog, its form and the Studio strings. The view settings panel and the create-view dialog were also drawn closed on every list. Now each one loads the first time it is opened, and after that it stays mounted, so closing it works as before. When a view create is refused, the reason loads with the refusal, and its toast shows once those strings arrive.
12+
13+
Nothing a user sees or saves changes, apart from a short wait the first time one of these opens. Nothing to migrate.

‎ui/packages/app-shell/src/views/ObjectView.readOnlyPackageViewSaves-35974.test.tsx‎

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -273,25 +273,32 @@ describe('objectstack#35974 — a read-only package\'s view: no Delete, a read-o
273273
expect(panelProps.current?.readOnly).toBe(false);
274274
});
275275

276+
// objectstack#37444: the panel mounts the first time it is opened, so the
277+
// cases below that read the open view's panel open it, through that view's
278+
// own row (the door that opens the panel on a given view).
276279
it('the panel opens on the shipped view read-only', async () => {
277280
mount(SHIPPED.name);
278281
await settle();
282+
await clickConfig(SHIPPED.name);
279283
await waitFor(() => expect(panelProps.current?.activeView?.id).toBe(SHIPPED.name));
280284
await waitFor(() => expect(panelProps.current?.readOnly).toBe(true));
281285
});
282286

283287
it('the panel on a shared view saved into the customization package is not read-only', async () => {
284288
mount(CUSTOM.name);
285289
await settle();
290+
await clickConfig(CUSTOM.name);
286291
await waitFor(() => expect(panelProps.current?.activeView?.id).toBe(CUSTOM.name));
287292
expect(panelProps.current?.readOnly).toBe(false);
288293
});
289294

290-
it('on the reader\'s own view the panel is not read-only and Manage views is unchanged', async () => {
295+
it('on the reader\'s own view the closed panel is not mounted and Manage views is unchanged', async () => {
291296
mount(PERSONAL.id);
292297
await settle();
293-
await waitFor(() => expect(panelProps.current?.activeView?.id).toBe(PERSONAL.id));
294-
expect(panelProps.current?.readOnly).toBe(false);
298+
// objectstack#37444: closed, the panel is not mounted at all (it used to be,
299+
// and this case read the verdict a closed panel was handed). Its own view is
300+
// no row of Manage views, so no row opens the panel on it.
301+
expect(panelProps.current).toBeNull();
295302
// My views are no row of Manage views; the shared rows are judged as ever.
296303
expect(screen.queryByTestId(`manage-views-row-${PERSONAL.id}`)).toBeNull();
297304
await waitFor(async () => expect(await rowOffers(SHIPPED.name)).toEqual(FACTORY_OFFERS));
@@ -304,6 +311,8 @@ describe('objectstack#35974 — a read-only package\'s view: no Delete, a read-o
304311
await settle();
305312
await waitFor(() => expect(screen.getByTestId(`manage-views-row-${SHIPPED.name}`)).toBeTruthy());
306313
expect(await rowOffers(SHIPPED.name)).toEqual(OFFERED);
314+
await clickConfig(SHIPPED.name);
315+
await waitFor(() => expect(panelProps.current?.open).toBe(true));
307316
expect(panelProps.current?.readOnly).toBe(false);
308317
});
309318

@@ -313,6 +322,8 @@ describe('objectstack#35974 — a read-only package\'s view: no Delete, a read-o
313322
await settle();
314323
await waitFor(() => expect(screen.getByTestId(`manage-views-row-${SHIPPED.name}`)).toBeTruthy());
315324
expect(await rowOffers(SHIPPED.name)).toEqual(OFFERED);
325+
await clickConfig(SHIPPED.name);
326+
await waitFor(() => expect(panelProps.current?.open).toBe(true));
316327
expect(panelProps.current?.readOnly).toBe(false);
317328
});
318329
});

‎ui/packages/app-shell/src/views/ObjectView.tsx‎

Lines changed: 24 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -43,8 +43,9 @@ import { MetadataPanel, useMetadataInspector } from './MetadataInspector.js';
4343
// objectstack#33293: the view config panel loads with the first list, not with
4444
// the console. Statically, it held the view-variant inspector, `SchemaForm` and
4545
// the Studio form widgets in the EAGER closure, so a dashboard route downloaded
46-
// them too. It is drawn on every list (closed, it draws nothing), so its chunk
47-
// is fetched as the list mounts, before any admin can open it.
46+
// them too. objectstack#37444: it mounts the first time it is opened, not with
47+
// every list, so the list's first screen no longer fetches it (see
48+
// `useOpenedOnce` below).
4849
const ViewConfigPanel = lazy(() =>
4950
import('./ViewConfigPanel.js').then((m) => ({ default: m.ViewConfigPanel })),
5051
);
@@ -53,9 +54,24 @@ import { dropPublishedViewList } from './metadata-admin/viewListDrop.js';
5354
// objectstack#33582: the create-view dialog loads with the first list, as the
5455
// view config panel above does. Statically, it held the dataset catalogue and,
5556
// through it, the Studio `en` string namespace in the EAGER closure.
57+
// objectstack#37444: like the panel, it mounts on its first opening.
5658
const CreateViewDialog = lazy(() =>
5759
import('./CreateViewDialog.js').then((m) => ({ default: m.CreateViewDialog })),
5860
);
61+
62+
/**
63+
* objectstack#37444 — `true` from the first render `open` is, and from then on.
64+
* A lazy panel or dialog behind it loads only when someone opens it (closed, it
65+
* draws nothing, so mounting it with every list only fetched its chunk before
66+
* the list's first screen), and stays mounted after, so closing it animates and
67+
* keeps its state as before. The state is adjusted during render, React's way of
68+
* deriving state from a prop, so the opening render already mounts it.
69+
*/
70+
function useOpenedOnce(open: boolean): boolean {
71+
const [opened, setOpened] = useState(open);
72+
if (open && !opened) setOpened(true);
73+
return opened || open;
74+
}
5975
import {
6076
usePreviewDrafts,
6177
} from '../preview/PreviewModeContext.js';
@@ -308,6 +324,8 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co
308324
// refuses with 403. `isAdmin` alone still gates what only reads.
309325
const canAuthorMetadata = useCanAuthorMetadata();
310326
const canManageViews = mayManageViews(isAdmin, canAuthorMetadata);
327+
const viewConfigPanelMounted = useOpenedOnce(showViewConfigPanel && canManageViews);
328+
const createViewDialogMounted = useOpenedOnce(showCreateViewDialog && canManageViews);
311329

312330
// Get Object Definition. The outer ObjectView wrapper already guards the
313331
// missing-object case, so this always resolves while this component is
@@ -1710,7 +1728,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co
17101728
showViewConfigPanel && canManageViews ? 'max-w-[280px] opacity-100' : 'max-w-0 opacity-0'
17111729
}`}
17121730
>
1713-
<Suspense fallback={null}>
1731+
{viewConfigPanelMounted && <Suspense fallback={null}>
17141732
<ViewConfigPanel
17151733
open={showViewConfigPanel && canManageViews}
17161734
onClose={() => { setShowViewConfigPanel(false); setViewConfigPanelMode('edit'); }}
@@ -1725,17 +1743,17 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co
17251743
onAfterChange={handleDraftBarChange}
17261744
readOnly={viewConfigPanelReadOnly}
17271745
/>
1728-
</Suspense>
1746+
</Suspense>}
17291747
</div>
1730-
<Suspense fallback={null}>
1748+
{createViewDialogMounted && <Suspense fallback={null}>
17311749
<CreateViewDialog
17321750
open={showCreateViewDialog && canManageViews}
17331751
onOpenChange={setShowCreateViewDialog}
17341752
existingLabels={views.map((v: any) => v.label).filter(Boolean)}
17351753
objectDef={objectDef}
17361754
onCreate={(cfg) => handleViewCreate(cfg)}
17371755
/>
1738-
</Suspense>
1756+
</Suspense>}
17391757
<PersonalViewNameDialog
17401758
open={!!personalViewDialog}
17411759
onOpenChange={(open) => { if (!open) setPersonalViewDialog(null); }}

‎ui/packages/app-shell/src/views/ObjectView.viewConfigSaveWiring-10210.test.tsx‎

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121

2222
import * as React from 'react';
2323
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
24-
import { render, cleanup, act, screen, fireEvent } from '@testing-library/react';
24+
import { render, cleanup, act, screen, fireEvent, waitFor } from '@testing-library/react';
2525
import { MemoryRouter, Routes, Route } from 'react-router-dom';
2626
import { ViewMetadataSchema } from '@objectstack/spec/ui';
2727

@@ -116,6 +116,27 @@ vi.mock('./ViewConfigPanel', () => {
116116

117117
// The view's source reaches a dynamic import of `@objectstack/lint`: pay its
118118
// load at collection, never inside a case's clocked window (`check:test-source-alias`).
119+
// objectstack#37444: the list's Settings view action, drawn beside the real
120+
// plugin view (whose own view switcher the console hides), so a case can open
121+
// the panel the way the action does.
122+
vi.mock('@object-ui/plugin-view', async (importOriginal) => {
123+
const actual = await importOriginal<typeof import('@object-ui/plugin-view')>();
124+
const Real = actual.ObjectView;
125+
return {
126+
...actual,
127+
ObjectView: (props: React.ComponentProps<typeof Real>) => (
128+
<>
129+
<button
130+
type="button"
131+
data-testid="stub-view-action-settings"
132+
onClick={() => props.onViewAction?.('settings', 'grid')}
133+
/>
134+
<Real {...props} />
135+
</>
136+
),
137+
};
138+
});
139+
119140
import '@objectstack/lint';
120141
import { ObjectView } from './ObjectView';
121142
import { ExpressionProvider } from '../providers/ExpressionProvider';
@@ -182,10 +203,22 @@ function mountObjectView() {
182203
);
183204
}
184205

206+
/**
207+
* objectstack#37444 — the panel mounts the first time it is opened, so each case
208+
* opens it through the list's Settings view action (the `viewActions` entry
209+
* `objectViewPluginSchema.ts` gives an administrator; the view switcher draws
210+
* it as a button that calls `onViewAction('settings', type)`).
211+
*/
212+
async function openViewConfig() {
213+
fireEvent.click(await waitFor(() => screen.getByTestId('stub-view-action-settings')));
214+
await waitFor(() => screen.getByTestId('stub-view-config-save'));
215+
}
216+
185217
describe('ObjectView — Edit view config → Save (objectui#10210)', () => {
186218
it('stages a spec-valid ViewItem envelope on the row the tab is keyed by', async () => {
187219
mountObjectView();
188220
await settle();
221+
await openViewConfig();
189222

190223
await act(async () => {
191224
fireEvent.click(screen.getByTestId('stub-view-config-save'));
@@ -208,6 +241,7 @@ describe('ObjectView — the view settings save writes through the panel\'s guar
208241
it('sends the envelope through the guard the panel hands it, never straight to the client', async () => {
209242
mountObjectView();
210243
await settle();
244+
await openViewConfig();
211245

212246
await act(async () => {
213247
fireEvent.click(screen.getByTestId('stub-view-config-guarded-save'));
Lines changed: 162 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,162 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* objectstack#37444 — the object list route loads no authoring code before its
5+
* first screen.
6+
*
7+
* ## What changed, and what this file pins about it
8+
*
9+
* `objectViewViewCrud.tsx` and `objectViewViewSharing.ts` imported the package
10+
* ask (`./metadata-admin/PackageCreateAsk`) and the designer strings
11+
* (`./metadata-admin/i18n`) statically, and the ask's dialog was rendered,
12+
* closed, on every list. Through them the list route's graph held the package
13+
* page's create dialog, `SchemaForm` and the Studio catalogue. The view config
14+
* panel and the create-view dialog, both `lazy()`, were also drawn closed on
15+
* every list, so their chunks were fetched before the list's first screen too.
16+
* The bundle half (which chunks a list load fetches, and the LCP it costs) is
17+
* measured on the built console and recorded on the PR. What a unit test CAN
18+
* pin is that none of those modules is evaluated until someone asks for it.
19+
*
20+
* ## The instrument: counted mock factories
21+
*
22+
* `vi.mock(path, factory)` runs `factory` the first time the module is
23+
* imported, and not before. Each count below is the unit-level image of "its
24+
* chunk was fetched". A STATIC import of one of them anywhere in
25+
* `ObjectView.tsx`'s graph runs its factory while this file imports
26+
* `ObjectView`, before any case starts, and the first case reds.
27+
*
28+
* ⚠️ The module registry is per FILE, so a load cannot be undone between
29+
* cases. The case that needs every module unloaded runs first, and each later
30+
* case asserts the count it STARTS from, so a reorder fails loudly.
31+
*/
32+
33+
import '@testing-library/jest-dom/vitest';
34+
import * as React from 'react';
35+
import { describe, it, expect, vi } from 'vitest';
36+
import { act, render, screen, waitFor, fireEvent } from '@testing-library/react';
37+
import { MemoryRouter } from 'react-router-dom';
38+
39+
const loads = vi.hoisted(() => ({
40+
packageAsk: 0,
41+
packagesPage: 0,
42+
schemaForm: 0,
43+
designerStrings: 0,
44+
viewConfigPanel: 0,
45+
createViewDialog: 0,
46+
}));
47+
48+
const toastError = vi.hoisted(() => vi.fn());
49+
50+
vi.mock('sonner', async (importOriginal) => ({
51+
...(await importOriginal<Record<string, unknown>>()),
52+
toast: { error: toastError, success: vi.fn(), info: vi.fn(), warning: vi.fn(), message: vi.fn() },
53+
}));
54+
55+
vi.mock('../providers/MetadataProvider', async (importOriginal) => ({
56+
...(await importOriginal<Record<string, unknown>>()),
57+
useMetadata: () => ({ apps: [] }),
58+
}));
59+
60+
// A stand-in dialog: open, it offers one package; the case answers with it.
61+
vi.mock('./metadata-admin/PackageCreateAsk', () => {
62+
loads.packageAsk += 1;
63+
return {
64+
PackageCreateAskDialog: ({ open, onAnswer }: { open: boolean; onAnswer: (id: string | null) => void }) => (
65+
<div data-testid="stub-package-ask" data-open={String(open)}>
66+
<button type="button" data-testid="stub-package-ask-pick" onClick={() => onAnswer('com.example.pick')} />
67+
</div>
68+
),
69+
runtimeCreateRefusalText: (notSaved: { reason: string }, kind: string, locale: string) =>
70+
notSaved.reason === 'cancelled' ? null : `refused ${kind} in ${locale}`,
71+
};
72+
});
73+
74+
vi.mock('./metadata-admin/PackagesPage', async (importOriginal) => {
75+
loads.packagesPage += 1;
76+
return importOriginal<Record<string, unknown>>();
77+
});
78+
79+
vi.mock('./metadata-admin/SchemaForm', async (importOriginal) => {
80+
loads.schemaForm += 1;
81+
return importOriginal<Record<string, unknown>>();
82+
});
83+
84+
vi.mock('./metadata-admin/i18n', async (importOriginal) => {
85+
loads.designerStrings += 1;
86+
return importOriginal<Record<string, unknown>>();
87+
});
88+
89+
vi.mock('./ViewConfigPanel', async (importOriginal) => {
90+
loads.viewConfigPanel += 1;
91+
return importOriginal<Record<string, unknown>>();
92+
});
93+
94+
vi.mock('./CreateViewDialog', async (importOriginal) => {
95+
loads.createViewDialog += 1;
96+
return importOriginal<Record<string, unknown>>();
97+
});
98+
99+
// `objectViewViewCrud` reaches a dynamic `import('@objectstack/lint')`: pay its
100+
// load at collection, never inside a case's clocked window.
101+
import '@objectstack/lint';
102+
import './ObjectView';
103+
import { reportViewNotSaved, useRuntimeCreateApp } from './objectViewViewCrud';
104+
import { RuntimeCreateNotSavedError } from './runtime-metadata-persistence';
105+
106+
type CreateApp = ReturnType<typeof useRuntimeCreateApp>;
107+
108+
function AskHost({ onApp }: { onApp: (app: CreateApp) => void }) {
109+
const app = useRuntimeCreateApp();
110+
onApp(app);
111+
return app.askDialog;
112+
}
113+
114+
describe('objectstack#37444 — the object list route loads no authoring code before it is asked', () => {
115+
it('importing the list route evaluates none of the authoring modules', () => {
116+
expect(loads).toEqual({
117+
packageAsk: 0,
118+
packagesPage: 0,
119+
schemaForm: 0,
120+
designerStrings: 0,
121+
viewConfigPanel: 0,
122+
createViewDialog: 0,
123+
});
124+
});
125+
126+
it('the package ask loads its dialog on the first ask, answers it, and keeps it mounted closed', async () => {
127+
expect(loads.packageAsk).toBe(0);
128+
let app: CreateApp | null = null;
129+
render(
130+
<MemoryRouter>
131+
<AskHost onApp={(next) => { app = next; }} />
132+
</MemoryRouter>,
133+
);
134+
// Nothing asked yet: the dialog module is not loaded and nothing is drawn.
135+
expect(loads.packageAsk).toBe(0);
136+
expect(screen.queryByTestId('stub-package-ask')).toBeNull();
137+
138+
let answer: Promise<string | null> | undefined;
139+
act(() => {
140+
answer = app!.askPackage({ preselect: null });
141+
});
142+
await waitFor(() => expect(screen.getByTestId('stub-package-ask')).toHaveAttribute('data-open', 'true'));
143+
expect(loads.packageAsk).toBe(1);
144+
145+
fireEvent.click(screen.getByTestId('stub-package-ask-pick'));
146+
await expect(answer!).resolves.toBe('com.example.pick');
147+
// Answered, it closes but stays mounted, so it closes the way it always did.
148+
await waitFor(() => expect(screen.getByTestId('stub-package-ask')).toHaveAttribute('data-open', 'false'));
149+
});
150+
151+
it('a refused view create says why once its words have loaded; a cancelled one says nothing', async () => {
152+
toastError.mockClear();
153+
expect(reportViewNotSaved(new Error('other'), 'en')).toBe(false);
154+
expect(reportViewNotSaved(new RuntimeCreateNotSavedError('system-app'), 'zh-CN')).toBe(true);
155+
// The words are in the designer strings, loaded on the refusal: the toast follows.
156+
await waitFor(() => expect(toastError).toHaveBeenCalledTimes(1));
157+
expect(toastError).toHaveBeenCalledWith('refused view in zh-CN');
158+
expect(reportViewNotSaved(new RuntimeCreateNotSavedError('cancelled'), 'en')).toBe(true);
159+
await act(() => new Promise<void>((resolve) => setTimeout(resolve, 50)));
160+
expect(toastError).toHaveBeenCalledTimes(1);
161+
});
162+
});

0 commit comments

Comments
 (0)