Skip to content

Commit 6a6dc4b

Browse files
committed
perf(plugin-view, app-shell): an object list loads the form package only when a form opens
The object view drew its create / edit form from a static import of @object-ui/plugin-form, and the console drew a closed record-form dialog on every object page, so a list's first screen fetched the whole form package. The object view now loads ObjectForm lazily inside the drawer or modal that mounts it, and the console mounts the record-form dialog the first time it opens (useOpenedOnce, now shared with the view settings panel and the create-view dialog). Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01L9qibxzGFPvShbd2qnkdEv
1 parent 4d07ddb commit 6a6dc4b

10 files changed

Lines changed: 290 additions & 21 deletions
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
'@object-ui/plugin-view': patch
3+
'@object-ui/app-shell': patch
4+
'@objectstack/console': patch
5+
---
6+
7+
perf(plugin-view, app-shell): an object list stops loading the form package before its first screen
8+
9+
Clause-②: no
10+
Metadata-protocol: none
11+
12+
An object list page fetched the whole form package (about 46 KB gzip) before its first screen, though it draws a form only when someone creates or edits a record. Two things did this. The object view imported its create and edit form statically, and the console drew a closed record-form dialog on every object page. Now the object view loads its form the first time one opens, and the console mounts the record-form dialog the first time it opens and keeps it mounted after that, so closing it works as before.
13+
14+
Nothing a user sees or saves changes, apart from a short wait the first time a form opens on a page. Nothing to migrate.

‎ui/packages/app-shell/src/console/AppContent.tsx‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ import { useTrackRouteAsRecent } from '../hooks/useTrackRouteAsRecent.js';
3232
import { useHomePath } from '../hooks/useHomePath.js';
3333
import { readItemPreferLocal, useReadItemsByName } from '../hooks/useObjectPresence.js';
3434
import { useLauncherApps } from '../hooks/useLauncherApps.js';
35+
import { useOpenedOnce } from '../hooks/useOpenedOnce.js';
3536
import { recordFormFieldNames } from '../utils/recordFormFields.js';
3637
import { resolveRecordFormTarget, resolveRecordFormModalLayout, resolveRecordFormChrome, resolveNavigateCreateUrl, resolveNavigateEditUrl, resolvePostCreateTarget, recordFormCreateValues, readRecordFormCreateValues, RECORD_FORM_CREATE_VALUES_STATE } from '../utils/recordFormNavigation.js';
3738
import { deriveRecordSurface, deriveRecordFlowSurface } from '@object-ui/plugin-view/core';
@@ -1056,6 +1057,10 @@ export function AppContent({ extraRoutes, extraRoutesNoApp }: AppContentProps =
10561057
isDialogOpen && !!formObjectDef && routeReadsSettled && routeSlotShown,
10571058
recordDrawersOpening,
10581059
);
1060+
// objectstack#37444: the record form mounts the first time it opens, not with
1061+
// every object page. Closed, it drew nothing, yet its lazy chunk (the whole of
1062+
// `@object-ui/plugin-form`) was fetched before a list's first screen.
1063+
const recordFormMounted = useOpenedOnce(recordFormShown);
10591064

10601065
// objectstack#27138 — the record the overlay edits may be held by a pending
10611066
// approval that locks it. The record's field projection leaves that lock out
@@ -1763,7 +1768,7 @@ export function AppContent({ extraRoutes, extraRoutesNoApp }: AppContentProps =
17631768
</RouteFader>
17641769
</Suspense>
17651770
</ErrorBoundary>
1766-
{formObjectDef && (
1771+
{formObjectDef && recordFormMounted && (
17671772
// objectstack#35403 — an edit draws the record's owner read-only,
17681773
// with Change Owner beside it where the caller may transfer it.
17691774
<ConsoleFormOwnerLine>
Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,146 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* objectstack#37444 — an object page mounts the record-form modal the first
5+
* time it opens, so a list's first screen loads no form code.
6+
*
7+
* `AppContent` drew a closed `LazyModalForm` on every object page (the route's
8+
* object is always the form's default object), and a lazy component that is
9+
* drawn loads its chunk even closed: the whole of `@object-ui/plugin-form` was
10+
* fetched before every list's first screen. The bundle half is measured on the
11+
* built console and recorded on the PR; this file pins that the form module is
12+
* not evaluated until the form opens, and that it opens as before.
13+
*
14+
* The instrument: a counted `vi.mock` factory, which runs the first time the
15+
* module is imported. The module registry is per FILE, so the case that needs
16+
* it unloaded runs first, and the later case asserts the count it starts from.
17+
*/
18+
19+
import '@testing-library/jest-dom/vitest';
20+
import { describe, it, expect, vi, afterEach, afterAll } from 'vitest';
21+
import React from 'react';
22+
import { render, cleanup, waitFor, screen } from '@testing-library/react';
23+
import { MemoryRouter, Routes, Route } from 'react-router-dom';
24+
import { createI18n, I18nProvider } from '@object-ui/i18n';
25+
// The console layout's draft bar reaches a dynamic `@objectstack/lint` import;
26+
// its first load is paid here, during collection, not inside a case's clock.
27+
import '@objectstack/lint';
28+
29+
const { loads, modalOpen } = vi.hoisted(() => ({ loads: { form: 0 }, modalOpen: [] as boolean[] }));
30+
31+
vi.mock('@object-ui/plugin-form', async (importOriginal) => {
32+
loads.form += 1;
33+
return {
34+
...(await importOriginal<Record<string, unknown>>()),
35+
ModalForm: ({ schema }: { schema: { open?: boolean; objectName?: string } }) => {
36+
modalOpen.push(!!schema.open);
37+
return <div data-testid="modal-form" data-object={schema.objectName} data-open={String(!!schema.open)} />;
38+
},
39+
ObjectForm: () => null,
40+
};
41+
});
42+
43+
vi.mock('@object-ui/plugin-designer', async (importOriginal) => ({
44+
...(await importOriginal<typeof import('@object-ui/plugin-designer')>()),
45+
CreateAppPage: () => <div data-testid="create-app-page" />,
46+
EditAppPage: () => <div data-testid="edit-app-page" />,
47+
DashboardDesignPage: () => <div data-testid="dashboard-design-page" />,
48+
}));
49+
50+
vi.mock('../../layout/ConsoleLayout', () => ({
51+
ConsoleLayout: ({ children }: { children?: React.ReactNode }) => (
52+
<div data-testid="console-layout">{children}</div>
53+
),
54+
}));
55+
vi.mock('../../chrome/CommandPalette', () => ({ CommandPalette: () => null }));
56+
vi.mock('../../chrome/KeyboardShortcutsDialog', () => ({ KeyboardShortcutsDialog: () => null }));
57+
vi.mock('../../chrome/OnboardingWalkthrough', () => ({ OnboardingWalkthrough: () => null }));
58+
vi.mock('../../views/ObjectView', () => ({ ObjectView: () => <div data-testid="object-view" /> }));
59+
vi.mock('../../views/RecordDetailView', () => ({ RecordDetailView: () => <div data-testid="record-page" /> }));
60+
61+
vi.mock('@object-ui/auth', async (importOriginal) => ({
62+
...(await importOriginal<Record<string, unknown>>()),
63+
useAuth: () => ({
64+
user: { id: 'u1', name: 'Ada', email: 'ada@example.com', role: 'user' },
65+
getAuthConfig: async () => ({ features: {} }),
66+
activeOrganization: null,
67+
}),
68+
useWorkspaceAdminStatus: () => ({ isAdmin: true, isResolved: true }),
69+
}));
70+
71+
const dataSourceStub = {
72+
onConnectionStateChange: () => () => {},
73+
getConnectionState: () => 'connected',
74+
};
75+
vi.mock('../../providers/AdapterProvider', async (importOriginal) => ({
76+
...(await importOriginal<Record<string, unknown>>()),
77+
useAdapter: () => dataSourceStub,
78+
}));
79+
80+
const METADATA = {
81+
apps: [{ name: 'crm', label: 'CRM', isDefault: true, navigation: [] }],
82+
objects: [{ name: 'showcase_task', label: 'Task', fields: { subject: { type: 'text', label: 'Subject' } } }],
83+
loading: false,
84+
ensureType: undefined,
85+
error: null,
86+
refresh: async () => {},
87+
};
88+
vi.mock('../../providers/MetadataProvider', async (importOriginal) => ({
89+
...(await importOriginal<Record<string, unknown>>()),
90+
useMetadata: () => METADATA,
91+
}));
92+
93+
const ACTION_RUNNER = { execute: vi.fn(), runner: { registerHandler: () => {}, getContext: () => ({}) } };
94+
vi.mock('@object-ui/react', async (importOriginal) => ({
95+
...(await importOriginal<Record<string, unknown>>()),
96+
useActionRunner: () => ACTION_RUNNER,
97+
useGlobalUndo: () => {},
98+
useMutationInvalidationBridge: () => {},
99+
}));
100+
101+
// An edit dialog reads the approvals of the record it edits; none runs here.
102+
vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({ data: [] }), {
103+
status: 200,
104+
headers: { 'Content-Type': 'application/json' },
105+
})));
106+
afterAll(() => vi.unstubAllGlobals());
107+
108+
import { AppContent } from '../AppContent';
109+
110+
function mountAt(url: string) {
111+
const i18n = createI18n({ defaultLanguage: 'en', detectBrowserLanguage: false });
112+
render(
113+
<I18nProvider instance={i18n}>
114+
<MemoryRouter initialEntries={[url]}>
115+
<Routes>
116+
<Route path="/apps/:appName/*" element={<AppContent />} />
117+
</Routes>
118+
</MemoryRouter>
119+
</I18nProvider>,
120+
);
121+
}
122+
123+
afterEach(() => cleanup());
124+
125+
describe('objectstack#37444 — an object page mounts the record form when it opens', () => {
126+
it('a list with no form open loads no form module and draws no modal', async () => {
127+
expect(loads.form).toBe(0);
128+
mountAt('/apps/crm/showcase_task');
129+
await screen.findByTestId('console-layout');
130+
// Long enough for a drawn lazy modal to have asked for its chunk and drawn.
131+
await new Promise<void>((resolve) => setTimeout(resolve, 200));
132+
expect(screen.queryByTestId('modal-form')).toBeNull();
133+
expect(loads.form).toBe(0);
134+
});
135+
136+
it('opening the create form loads it and draws it open', async () => {
137+
expect(loads.form).toBe(0);
138+
mountAt('/apps/crm/showcase_task?form=new');
139+
const modal = await screen.findByTestId('modal-form');
140+
expect(modal).toHaveAttribute('data-object', 'showcase_task');
141+
await waitFor(() => expect(modal).toHaveAttribute('data-open', 'true'));
142+
expect(loads.form).toBe(1);
143+
// It is never drawn closed first: the opening render is the first one.
144+
expect(modalOpen[0]).toBe(true);
145+
});
146+
});
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
import { useState } from 'react';
4+
5+
/**
6+
* objectstack#37444 — `true` from the first render `open` is, and from then on.
7+
* A lazy panel or dialog behind it loads only when someone opens it (closed, it
8+
* draws nothing, so mounting it with every page only fetched its chunk before
9+
* the page's first screen), and stays mounted after, so closing it animates and
10+
* keeps its state as before. The state is adjusted during render, React's way of
11+
* deriving state from a prop, so the opening render already mounts it.
12+
*
13+
* Package-internal: not exported from `./index.ts` or the package entry.
14+
*/
15+
export function useOpenedOnce(open: boolean): boolean {
16+
const [opened, setOpened] = useState(open);
17+
if (open && !opened) setOpened(true);
18+
return opened || open;
19+
}

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

Lines changed: 1 addition & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -59,19 +59,7 @@ const CreateViewDialog = lazy(() =>
5959
import('./CreateViewDialog.js').then((m) => ({ default: m.CreateViewDialog })),
6060
);
6161

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-
}
62+
import { useOpenedOnce } from '../hooks/useOpenedOnce.js';
7563
import {
7664
usePreviewDrafts,
7765
} from '../preview/PreviewModeContext.js';

‎ui/packages/plugin-view/src/ObjectView.tsx‎

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,6 @@ import type {
3636
TreeViewConfig,
3737
} from '@object-ui/types';
3838
import { ObjectGrid } from '@object-ui/plugin-grid';
39-
import { ObjectForm } from '@object-ui/plugin-form';
4039
import {
4140
cn,
4241
Dialog,
@@ -99,6 +98,17 @@ import { usePermissions } from '@object-ui/permissions';
9998
import { ViewSwitcher } from './ViewSwitcher';
10099
import { useStableIdentity, isStructurallyEqual } from './stableIdentity';
101100

101+
/**
102+
* The create / edit form, loaded the first time one opens (objectstack#37444).
103+
*
104+
* A static import put the whole of `@object-ui/plugin-form` on every list's
105+
* first screen, though the form is drawn only inside the drawer or modal below,
106+
* whose content mounts when it opens. Its chunk now loads on that first open.
107+
*/
108+
const ObjectForm = React.lazy(() =>
109+
import('@object-ui/plugin-form').then((m) => ({ default: m.ObjectForm })),
110+
);
111+
102112
/**
103113
* SchemaRenderer from @object-ui/react, used to render sub-view schemas.
104114
*/
@@ -2934,7 +2944,9 @@ export const ObjectView: React.FC<ObjectViewProps> = ({
29342944
const renderDrawerForm = () => {
29352945
const form = (
29362946
<div className="flex-1 overflow-y-auto px-4 pb-4">
2937-
<ObjectForm schema={buildFormSchema()} dataSource={dataSource} />
2947+
<React.Suspense fallback={null}>
2948+
<ObjectForm schema={buildFormSchema()} dataSource={dataSource} />
2949+
</React.Suspense>
29382950
</div>
29392951
);
29402952
if (isMobile) {
@@ -2981,7 +2993,9 @@ export const ObjectView: React.FC<ObjectViewProps> = ({
29812993
<DialogDescription>{formDescriptionText}</DialogDescription>
29822994
)}
29832995
</DialogHeader>
2984-
<ObjectForm schema={buildFormSchema()} dataSource={dataSource} />
2996+
<React.Suspense fallback={null}>
2997+
<ObjectForm schema={buildFormSchema()} dataSource={dataSource} />
2998+
</React.Suspense>
29852999
</DialogContent>
29863000
</Dialog>
29873001
);
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* objectstack#37444 — an object view loads `@object-ui/plugin-form` the first
5+
* time its create / edit form opens, not with the list.
6+
*
7+
* `ObjectView` imported `ObjectForm` statically, so every list's first screen
8+
* fetched the whole form package, though the form is drawn only inside the
9+
* drawer or modal that mounts its content when it opens. The bundle half (which
10+
* chunks a list load fetches) is measured on the built console and recorded on
11+
* the PR. What a unit test can pin is that the form module is not evaluated
12+
* until a form opens.
13+
*
14+
* The instrument: `vi.mock(path, factory)` runs `factory` the first time the
15+
* module is imported, and not before. A STATIC import of the form package in
16+
* `ObjectView`'s graph runs it while this file imports `ObjectView`, before any
17+
* case starts, and the first case reds. The module registry is per FILE, so the
18+
* case that needs it unloaded runs first, and the later case asserts the count
19+
* it starts from.
20+
*/
21+
22+
import { describe, it, expect, vi } from 'vitest';
23+
import { render, screen, waitFor, act, fireEvent } from '@testing-library/react';
24+
import type { DataSource, ObjectViewSchema } from '@object-ui/types';
25+
26+
const loads = vi.hoisted(() => ({ form: 0 }));
27+
28+
vi.mock('@object-ui/plugin-grid', async (importOriginal) => ({
29+
...(await importOriginal<Record<string, unknown>>()),
30+
ObjectGrid: () => <div data-testid="object-grid" />,
31+
}));
32+
vi.mock('@object-ui/plugin-form', async (importOriginal) => {
33+
loads.form += 1;
34+
return {
35+
...(await importOriginal<Record<string, unknown>>()),
36+
ObjectForm: ({ schema }: { schema: { mode?: string } }) => <div data-testid="object-form" data-mode={schema.mode} />,
37+
};
38+
});
39+
40+
import { ObjectView } from '../ObjectView';
41+
42+
function makeDataSource() {
43+
const state = { settled: false };
44+
const ds = {
45+
find: vi.fn().mockResolvedValue({ data: [], total: 0 }),
46+
findOne: vi.fn(),
47+
create: vi.fn(),
48+
update: vi.fn(),
49+
delete: vi.fn(),
50+
getObjectSchema: vi.fn(async () => {
51+
state.settled = true;
52+
return { name: 'task', label: 'Tasks', fields: { name: { type: 'text' } } };
53+
}),
54+
};
55+
return { ds: ds as unknown as DataSource, state };
56+
}
57+
58+
describe('objectstack#37444 — the object view loads the form package when a form opens', () => {
59+
it('importing and drawing the list evaluates no form module', async () => {
60+
expect(loads.form).toBe(0);
61+
const { ds, state } = makeDataSource();
62+
const schema = { type: 'object-view', objectName: 'task', layout: 'drawer' } as unknown as ObjectViewSchema;
63+
render(<ObjectView schema={schema} dataSource={ds} />);
64+
await screen.findByTestId('object-grid');
65+
await waitFor(() => expect(state.settled, 'the object schema was never read').toBe(true));
66+
await act(async () => {});
67+
expect(screen.queryByTestId('object-form')).toBeNull();
68+
expect(loads.form).toBe(0);
69+
70+
// Opening the create form loads it, and the form is drawn for that verb.
71+
fireEvent.click(screen.getByRole('button', { name: 'New' }));
72+
const form = await screen.findByTestId('object-form');
73+
expect(form.getAttribute('data-mode')).toBe('create');
74+
expect(loads.form).toBe(1);
75+
});
76+
});

‎ui/packages/plugin-view/src/__tests__/ObjectView.namedViewInlineEdit-10885.test.tsx‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,9 +108,12 @@ async function clickCell(named: Record<string, unknown>, userActions?: Record<st
108108
// One tick lets React flush the editor, so `false` means "never opened",
109109
// not "not opened yet".
110110
await new Promise((r) => setTimeout(r, 50));
111+
// objectstack#37444: the record form loads on its first opening, so its
112+
// presence is waited for rather than read on this tick.
113+
const recordForm = await screen.findByTestId('object-form', {}, { timeout: 500 }).then(() => true, () => false);
111114
return {
112115
editor: document.querySelector('td[data-editing-cell] input') != null,
113-
recordForm: screen.queryByTestId('object-form') != null,
116+
recordForm,
114117
};
115118
}
116119

‎ui/packages/plugin-view/src/__tests__/ObjectView.tableEditable-10976.test.tsx‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -100,9 +100,12 @@ async function clickCell(table: NonNullable<ObjectViewSchema['table']>, userActi
100100
// One tick lets React flush the editor, so `false` means "never opened",
101101
// not "not opened yet".
102102
await new Promise((r) => setTimeout(r, 50));
103+
// objectstack#37444: the record form loads on its first opening, so its
104+
// presence is waited for rather than read on this tick.
105+
const recordForm = await screen.findByTestId('object-form', {}, { timeout: 500 }).then(() => true, () => false);
103106
return {
104107
editor: document.querySelector('td[data-editing-cell] input') != null,
105-
recordForm: screen.queryByTestId('object-form') != null,
108+
recordForm,
106109
};
107110
}
108111

0 commit comments

Comments
 (0)