Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions .changeset/37444-list-route-defers-form.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
---
'@object-ui/plugin-view': patch
'@object-ui/app-shell': patch
'@objectstack/console': patch
---

perf(plugin-view, app-shell): an object list stops loading the form package before its first screen

Clause-②: no
Metadata-protocol: none

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.

Nothing a user sees or saves changes, apart from a short wait the first time a form opens on a page. Nothing to migrate.
7 changes: 6 additions & 1 deletion ui/packages/app-shell/src/console/AppContent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import { useTrackRouteAsRecent } from '../hooks/useTrackRouteAsRecent.js';
import { useHomePath } from '../hooks/useHomePath.js';
import { readItemPreferLocal, useReadItemsByName } from '../hooks/useObjectPresence.js';
import { useLauncherApps } from '../hooks/useLauncherApps.js';
import { useOpenedOnce } from '../hooks/useOpenedOnce.js';
import { recordFormFieldNames } from '../utils/recordFormFields.js';
import { resolveRecordFormTarget, resolveRecordFormModalLayout, resolveRecordFormChrome, resolveNavigateCreateUrl, resolveNavigateEditUrl, resolvePostCreateTarget, recordFormCreateValues, readRecordFormCreateValues, RECORD_FORM_CREATE_VALUES_STATE } from '../utils/recordFormNavigation.js';
import { deriveRecordSurface, deriveRecordFlowSurface } from '@object-ui/plugin-view/core';
Expand Down Expand Up @@ -1056,6 +1057,10 @@ export function AppContent({ extraRoutes, extraRoutesNoApp }: AppContentProps =
isDialogOpen && !!formObjectDef && routeReadsSettled && routeSlotShown,
recordDrawersOpening,
);
// objectstack#37444: the record form mounts the first time it opens, not with
// every object page. Closed, it drew nothing, yet its lazy chunk (the whole of
// `@object-ui/plugin-form`) was fetched before a list's first screen.
const recordFormMounted = useOpenedOnce(recordFormShown);

// objectstack#27138 — the record the overlay edits may be held by a pending
// approval that locks it. The record's field projection leaves that lock out
Expand Down Expand Up @@ -1763,7 +1768,7 @@ export function AppContent({ extraRoutes, extraRoutesNoApp }: AppContentProps =
</RouteFader>
</Suspense>
</ErrorBoundary>
{formObjectDef && (
{formObjectDef && recordFormMounted && (
// objectstack#35403 — an edit draws the record's owner read-only,
// with Change Owner beside it where the caller may transfer it.
<ConsoleFormOwnerLine>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* objectstack#37444 — an object page mounts the record-form modal the first
* time it opens, so a list's first screen loads no form code.
*
* `AppContent` drew a closed `LazyModalForm` on every object page (the route's
* object is always the form's default object), and a lazy component that is
* drawn loads its chunk even closed: the whole of `@object-ui/plugin-form` was
* fetched before every list's first screen. The bundle half is measured on the
* built console and recorded on the PR; this file pins that the form module is
* not evaluated until the form opens, and that it opens as before.
*
* The instrument: a counted `vi.mock` factory, which runs the first time the
* module is imported. The module registry is per FILE, so the case that needs
* it unloaded runs first, and the later case asserts the count it starts from.
*/

import '@testing-library/jest-dom/vitest';
import { describe, it, expect, vi, afterEach, afterAll } from 'vitest';
import React from 'react';
import { render, cleanup, waitFor, screen } from '@testing-library/react';
import { MemoryRouter, Routes, Route } from 'react-router-dom';
import { createI18n, I18nProvider } from '@object-ui/i18n';
// The console layout's draft bar reaches a dynamic `@objectstack/lint` import;
// its first load is paid here, during collection, not inside a case's clock.
import '@objectstack/lint';

const { loads, modalOpen } = vi.hoisted(() => ({ loads: { form: 0 }, modalOpen: [] as boolean[] }));

vi.mock('@object-ui/plugin-form', async (importOriginal) => {
loads.form += 1;
return {
...(await importOriginal<Record<string, unknown>>()),
ModalForm: ({ schema }: { schema: { open?: boolean; objectName?: string } }) => {
modalOpen.push(!!schema.open);
return <div data-testid="modal-form" data-object={schema.objectName} data-open={String(!!schema.open)} />;
},
ObjectForm: () => null,
};
});

vi.mock('@object-ui/plugin-designer', async (importOriginal) => ({
...(await importOriginal<typeof import('@object-ui/plugin-designer')>()),
CreateAppPage: () => <div data-testid="create-app-page" />,
EditAppPage: () => <div data-testid="edit-app-page" />,
DashboardDesignPage: () => <div data-testid="dashboard-design-page" />,
}));

vi.mock('../../layout/ConsoleLayout', () => ({
ConsoleLayout: ({ children }: { children?: React.ReactNode }) => (
<div data-testid="console-layout">{children}</div>
),
}));
vi.mock('../../chrome/CommandPalette', () => ({ CommandPalette: () => null }));
vi.mock('../../chrome/KeyboardShortcutsDialog', () => ({ KeyboardShortcutsDialog: () => null }));
vi.mock('../../chrome/OnboardingWalkthrough', () => ({ OnboardingWalkthrough: () => null }));
vi.mock('../../views/ObjectView', () => ({ ObjectView: () => <div data-testid="object-view" /> }));
vi.mock('../../views/RecordDetailView', () => ({ RecordDetailView: () => <div data-testid="record-page" /> }));

vi.mock('@object-ui/auth', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
useAuth: () => ({
user: { id: 'u1', name: 'Ada', email: 'ada@example.com', role: 'user' },
getAuthConfig: async () => ({ features: {} }),
activeOrganization: null,
}),
useWorkspaceAdminStatus: () => ({ isAdmin: true, isResolved: true }),
}));

const dataSourceStub = {
onConnectionStateChange: () => () => {},
getConnectionState: () => 'connected',
};
vi.mock('../../providers/AdapterProvider', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
useAdapter: () => dataSourceStub,
}));

const METADATA = {
apps: [{ name: 'crm', label: 'CRM', isDefault: true, navigation: [] }],
objects: [{ name: 'showcase_task', label: 'Task', fields: { subject: { type: 'text', label: 'Subject' } } }],
loading: false,
ensureType: undefined,
error: null,
refresh: async () => {},
};
vi.mock('../../providers/MetadataProvider', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
useMetadata: () => METADATA,
}));

const ACTION_RUNNER = { execute: vi.fn(), runner: { registerHandler: () => {}, getContext: () => ({}) } };
vi.mock('@object-ui/react', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
useActionRunner: () => ACTION_RUNNER,
useGlobalUndo: () => {},
useMutationInvalidationBridge: () => {},
}));

// An edit dialog reads the approvals of the record it edits; none runs here.
vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({ data: [] }), {
status: 200,
headers: { 'Content-Type': 'application/json' },
})));
afterAll(() => vi.unstubAllGlobals());

import { AppContent } from '../AppContent';

function mountAt(url: string) {
const i18n = createI18n({ defaultLanguage: 'en', detectBrowserLanguage: false });
render(
<I18nProvider instance={i18n}>
<MemoryRouter initialEntries={[url]}>
<Routes>
<Route path="/apps/:appName/*" element={<AppContent />} />
</Routes>
</MemoryRouter>
</I18nProvider>,
);
}

afterEach(() => cleanup());

describe('objectstack#37444 — an object page mounts the record form when it opens', () => {
it('a list with no form open loads no form module and draws no modal', async () => {
expect(loads.form).toBe(0);
mountAt('/apps/crm/showcase_task');
await screen.findByTestId('console-layout');
// Long enough for a drawn lazy modal to have asked for its chunk and drawn.
await new Promise<void>((resolve) => setTimeout(resolve, 200));
expect(screen.queryByTestId('modal-form')).toBeNull();
expect(loads.form).toBe(0);
});

it('opening the create form loads it and draws it open', async () => {
expect(loads.form).toBe(0);
mountAt('/apps/crm/showcase_task?form=new');
const modal = await screen.findByTestId('modal-form');
expect(modal).toHaveAttribute('data-object', 'showcase_task');
await waitFor(() => expect(modal).toHaveAttribute('data-open', 'true'));
expect(loads.form).toBe(1);
// It is never drawn closed first: the opening render is the first one.
expect(modalOpen[0]).toBe(true);
});
});
19 changes: 19 additions & 0 deletions ui/packages/app-shell/src/hooks/useOpenedOnce.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

import { useState } from 'react';

/**
* objectstack#37444 — `true` from the first render `open` is, and from then on.
* A lazy panel or dialog behind it loads only when someone opens it (closed, it
* draws nothing, so mounting it with every page only fetched its chunk before
* the page's first screen), and stays mounted after, so closing it animates and
* keeps its state as before. The state is adjusted during render, React's way of
* deriving state from a prop, so the opening render already mounts it.
*
* Package-internal: not exported from `./index.ts` or the package entry.
*/
export function useOpenedOnce(open: boolean): boolean {
const [opened, setOpened] = useState(open);
if (open && !opened) setOpened(true);
return opened || open;
}
14 changes: 1 addition & 13 deletions ui/packages/app-shell/src/views/ObjectView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -59,19 +59,7 @@ const CreateViewDialog = lazy(() =>
import('./CreateViewDialog.js').then((m) => ({ default: m.CreateViewDialog })),
);

/**
* objectstack#37444 — `true` from the first render `open` is, and from then on.
* A lazy panel or dialog behind it loads only when someone opens it (closed, it
* draws nothing, so mounting it with every list only fetched its chunk before
* the list's first screen), and stays mounted after, so closing it animates and
* keeps its state as before. The state is adjusted during render, React's way of
* deriving state from a prop, so the opening render already mounts it.
*/
function useOpenedOnce(open: boolean): boolean {
const [opened, setOpened] = useState(open);
if (open && !opened) setOpened(true);
return opened || open;
}
import { useOpenedOnce } from '../hooks/useOpenedOnce.js';
import {
usePreviewDrafts,
} from '../preview/PreviewModeContext.js';
Expand Down
20 changes: 17 additions & 3 deletions ui/packages/plugin-view/src/ObjectView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@ import type {
TreeViewConfig,
} from '@object-ui/types';
import { ObjectGrid } from '@object-ui/plugin-grid';
import { ObjectForm } from '@object-ui/plugin-form';
import {
cn,
Dialog,
Expand Down Expand Up @@ -99,6 +98,17 @@ import { usePermissions } from '@object-ui/permissions';
import { ViewSwitcher } from './ViewSwitcher';
import { useStableIdentity, isStructurallyEqual } from './stableIdentity';

/**
* The create / edit form, loaded the first time one opens (objectstack#37444).
*
* A static import put the whole of `@object-ui/plugin-form` on every list's
* first screen, though the form is drawn only inside the drawer or modal below,
* whose content mounts when it opens. Its chunk now loads on that first open.
*/
const ObjectForm = React.lazy(() =>
import('@object-ui/plugin-form').then((m) => ({ default: m.ObjectForm })),
);

/**
* SchemaRenderer from @object-ui/react, used to render sub-view schemas.
*/
Expand Down Expand Up @@ -2934,7 +2944,9 @@ export const ObjectView: React.FC<ObjectViewProps> = ({
const renderDrawerForm = () => {
const form = (
<div className="flex-1 overflow-y-auto px-4 pb-4">
<ObjectForm schema={buildFormSchema()} dataSource={dataSource} />
<React.Suspense fallback={null}>
<ObjectForm schema={buildFormSchema()} dataSource={dataSource} />
</React.Suspense>
</div>
);
if (isMobile) {
Expand Down Expand Up @@ -2981,7 +2993,9 @@ export const ObjectView: React.FC<ObjectViewProps> = ({
<DialogDescription>{formDescriptionText}</DialogDescription>
)}
</DialogHeader>
<ObjectForm schema={buildFormSchema()} dataSource={dataSource} />
<React.Suspense fallback={null}>
<ObjectForm schema={buildFormSchema()} dataSource={dataSource} />
</React.Suspense>
</DialogContent>
</Dialog>
);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* objectstack#37444 — an object view loads `@object-ui/plugin-form` the first
* time its create / edit form opens, not with the list.
*
* `ObjectView` imported `ObjectForm` statically, so every list's first screen
* fetched the whole form package, though the form is drawn only inside the
* drawer or modal that mounts its content when it opens. The bundle half (which
* chunks a list load fetches) is measured on the built console and recorded on
* the PR. What a unit test can pin is that the form module is not evaluated
* until a form opens.
*
* The instrument: `vi.mock(path, factory)` runs `factory` the first time the
* module is imported, and not before. A STATIC import of the form package in
* `ObjectView`'s graph runs it while this file imports `ObjectView`, before any
* case starts, and the first case reds. The module registry is per FILE, so the
* case that needs it unloaded runs first, and the later case asserts the count
* it starts from.
*/

import { describe, it, expect, vi } from 'vitest';
import { render, screen, waitFor, act, fireEvent } from '@testing-library/react';
import type { DataSource, ObjectViewSchema } from '@object-ui/types';

const loads = vi.hoisted(() => ({ form: 0 }));

vi.mock('@object-ui/plugin-grid', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
ObjectGrid: () => <div data-testid="object-grid" />,
}));
vi.mock('@object-ui/plugin-form', async (importOriginal) => {
loads.form += 1;
return {
...(await importOriginal<Record<string, unknown>>()),
ObjectForm: ({ schema }: { schema: { mode?: string } }) => <div data-testid="object-form" data-mode={schema.mode} />,
};
});

import { ObjectView } from '../ObjectView';

function makeDataSource() {
const state = { settled: false };
const ds = {
find: vi.fn().mockResolvedValue({ data: [], total: 0 }),
findOne: vi.fn(),
create: vi.fn(),
update: vi.fn(),
delete: vi.fn(),
getObjectSchema: vi.fn(async () => {
state.settled = true;
return { name: 'task', label: 'Tasks', fields: { name: { type: 'text' } } };
}),
};
return { ds: ds as unknown as DataSource, state };
}

describe('objectstack#37444 — the object view loads the form package when a form opens', () => {
it('importing and drawing the list evaluates no form module', async () => {
expect(loads.form).toBe(0);
const { ds, state } = makeDataSource();
const schema = { type: 'object-view', objectName: 'task', layout: 'drawer' } as unknown as ObjectViewSchema;
render(<ObjectView schema={schema} dataSource={ds} />);
await screen.findByTestId('object-grid');
await waitFor(() => expect(state.settled, 'the object schema was never read').toBe(true));
await act(async () => {});
expect(screen.queryByTestId('object-form')).toBeNull();
expect(loads.form).toBe(0);

// Opening the create form loads it, and the form is drawn for that verb.
fireEvent.click(screen.getByRole('button', { name: 'New' }));
const form = await screen.findByTestId('object-form');
expect(form.getAttribute('data-mode')).toBe('create');
expect(loads.form).toBe(1);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -108,9 +108,12 @@ async function clickCell(named: Record<string, unknown>, userActions?: Record<st
// One tick lets React flush the editor, so `false` means "never opened",
// not "not opened yet".
await new Promise((r) => setTimeout(r, 50));
// objectstack#37444: the record form loads on its first opening, so its
// presence is waited for rather than read on this tick.
const recordForm = await screen.findByTestId('object-form', {}, { timeout: 500 }).then(() => true, () => false);
return {
editor: document.querySelector('td[data-editing-cell] input') != null,
recordForm: screen.queryByTestId('object-form') != null,
recordForm,
};
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,9 +100,12 @@ async function clickCell(table: NonNullable<ObjectViewSchema['table']>, userActi
// One tick lets React flush the editor, so `false` means "never opened",
// not "not opened yet".
await new Promise((r) => setTimeout(r, 50));
// objectstack#37444: the record form loads on its first opening, so its
// presence is waited for rather than read on this tick.
const recordForm = await screen.findByTestId('object-form', {}, { timeout: 500 }).then(() => true, () => false);
return {
editor: document.querySelector('td[data-editing-cell] input') != null,
recordForm: screen.queryByTestId('object-form') != null,
recordForm,
};
}

Expand Down
Loading
Loading