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
13 changes: 13 additions & 0 deletions .changeset/37444-list-route-defers-authoring.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
---
'@object-ui/app-shell': patch
'@objectstack/console': patch
---

perf(app-shell): an object list stops loading the package ask, the view settings panel and the create-view dialog before its first screen

Clause-②: no
Metadata-protocol: none

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.

Nothing a user sees or saves changes, apart from a short wait the first time one of these opens. Nothing to migrate.
Original file line number Diff line number Diff line change
Expand Up @@ -273,25 +273,32 @@ describe('objectstack#35974 — a read-only package\'s view: no Delete, a read-o
expect(panelProps.current?.readOnly).toBe(false);
});

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

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

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

Expand All @@ -313,6 +322,8 @@ describe('objectstack#35974 — a read-only package\'s view: no Delete, a read-o
await settle();
await waitFor(() => expect(screen.getByTestId(`manage-views-row-${SHIPPED.name}`)).toBeTruthy());
expect(await rowOffers(SHIPPED.name)).toEqual(OFFERED);
await clickConfig(SHIPPED.name);
await waitFor(() => expect(panelProps.current?.open).toBe(true));
expect(panelProps.current?.readOnly).toBe(false);
});
});
Expand Down
30 changes: 24 additions & 6 deletions ui/packages/app-shell/src/views/ObjectView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,9 @@ import { MetadataPanel, useMetadataInspector } from './MetadataInspector.js';
// objectstack#33293: the view config panel loads with the first list, not with
// the console. Statically, it held the view-variant inspector, `SchemaForm` and
// the Studio form widgets in the EAGER closure, so a dashboard route downloaded
// them too. It is drawn on every list (closed, it draws nothing), so its chunk
// is fetched as the list mounts, before any admin can open it.
// them too. objectstack#37444: it mounts the first time it is opened, not with
// every list, so the list's first screen no longer fetches it (see
// `useOpenedOnce` below).
const ViewConfigPanel = lazy(() =>
import('./ViewConfigPanel.js').then((m) => ({ default: m.ViewConfigPanel })),
);
Expand All @@ -53,9 +54,24 @@ import { dropPublishedViewList } from './metadata-admin/viewListDrop.js';
// objectstack#33582: the create-view dialog loads with the first list, as the
// view config panel above does. Statically, it held the dataset catalogue and,
// through it, the Studio `en` string namespace in the EAGER closure.
// objectstack#37444: like the panel, it mounts on its first opening.
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 {
usePreviewDrafts,
} from '../preview/PreviewModeContext.js';
Expand Down Expand Up @@ -308,6 +324,8 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co
// refuses with 403. `isAdmin` alone still gates what only reads.
const canAuthorMetadata = useCanAuthorMetadata();
const canManageViews = mayManageViews(isAdmin, canAuthorMetadata);
const viewConfigPanelMounted = useOpenedOnce(showViewConfigPanel && canManageViews);
const createViewDialogMounted = useOpenedOnce(showCreateViewDialog && canManageViews);

// Get Object Definition. The outer ObjectView wrapper already guards the
// missing-object case, so this always resolves while this component is
Expand Down Expand Up @@ -1710,7 +1728,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co
showViewConfigPanel && canManageViews ? 'max-w-[280px] opacity-100' : 'max-w-0 opacity-0'
}`}
>
<Suspense fallback={null}>
{viewConfigPanelMounted && <Suspense fallback={null}>
<ViewConfigPanel
open={showViewConfigPanel && canManageViews}
onClose={() => { setShowViewConfigPanel(false); setViewConfigPanelMode('edit'); }}
Expand All @@ -1725,17 +1743,17 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co
onAfterChange={handleDraftBarChange}
readOnly={viewConfigPanelReadOnly}
/>
</Suspense>
</Suspense>}
</div>
<Suspense fallback={null}>
{createViewDialogMounted && <Suspense fallback={null}>
<CreateViewDialog
open={showCreateViewDialog && canManageViews}
onOpenChange={setShowCreateViewDialog}
existingLabels={views.map((v: any) => v.label).filter(Boolean)}
objectDef={objectDef}
onCreate={(cfg) => handleViewCreate(cfg)}
/>
</Suspense>
</Suspense>}
<PersonalViewNameDialog
open={!!personalViewDialog}
onOpenChange={(open) => { if (!open) setPersonalViewDialog(null); }}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@

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

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

// The view's source reaches a dynamic import of `@objectstack/lint`: pay its
// load at collection, never inside a case's clocked window (`check:test-source-alias`).
// objectstack#37444: the list's Settings view action, drawn beside the real
// plugin view (whose own view switcher the console hides), so a case can open
// the panel the way the action does.
vi.mock('@object-ui/plugin-view', async (importOriginal) => {
const actual = await importOriginal<typeof import('@object-ui/plugin-view')>();
const Real = actual.ObjectView;
return {
...actual,
ObjectView: (props: React.ComponentProps<typeof Real>) => (
<>
<button
type="button"
data-testid="stub-view-action-settings"
onClick={() => props.onViewAction?.('settings', 'grid')}
/>
<Real {...props} />
</>
),
};
});

import '@objectstack/lint';
import { ObjectView } from './ObjectView';
import { ExpressionProvider } from '../providers/ExpressionProvider';
Expand Down Expand Up @@ -182,10 +203,22 @@ function mountObjectView() {
);
}

/**
* objectstack#37444 — the panel mounts the first time it is opened, so each case
* opens it through the list's Settings view action (the `viewActions` entry
* `objectViewPluginSchema.ts` gives an administrator; the view switcher draws
* it as a button that calls `onViewAction('settings', type)`).
*/
async function openViewConfig() {
fireEvent.click(await waitFor(() => screen.getByTestId('stub-view-action-settings')));
await waitFor(() => screen.getByTestId('stub-view-config-save'));
}

describe('ObjectView — Edit view config → Save (objectui#10210)', () => {
it('stages a spec-valid ViewItem envelope on the row the tab is keyed by', async () => {
mountObjectView();
await settle();
await openViewConfig();

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

await act(async () => {
fireEvent.click(screen.getByTestId('stub-view-config-guarded-save'));
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* objectstack#37444 — the object list route loads no authoring code before its
* first screen.
*
* ## What changed, and what this file pins about it
*
* `objectViewViewCrud.tsx` and `objectViewViewSharing.ts` imported the package
* ask (`./metadata-admin/PackageCreateAsk`) and the designer strings
* (`./metadata-admin/i18n`) statically, and the ask's dialog was rendered,
* closed, on every list. Through them the list route's graph held the package
* page's create dialog, `SchemaForm` and the Studio catalogue. The view config
* panel and the create-view dialog, both `lazy()`, were also drawn closed on
* every list, so their chunks were fetched before the list's first screen too.
* The bundle half (which chunks a list load fetches, and the LCP it costs) is
* measured on the built console and recorded on the PR. What a unit test CAN
* pin is that none of those modules is evaluated until someone asks for it.
*
* ## The instrument: counted mock factories
*
* `vi.mock(path, factory)` runs `factory` the first time the module is
* imported, and not before. Each count below is the unit-level image of "its
* chunk was fetched". A STATIC import of one of them anywhere in
* `ObjectView.tsx`'s graph runs its factory while this file imports
* `ObjectView`, before any case starts, and the first case reds.
*
* ⚠️ The module registry is per FILE, so a load cannot be undone between
* cases. The case that needs every module unloaded runs first, and each later
* case asserts the count it STARTS from, so a reorder fails loudly.
*/

import '@testing-library/jest-dom/vitest';
import * as React from 'react';
import { describe, it, expect, vi } from 'vitest';
import { act, render, screen, waitFor, fireEvent } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';

const loads = vi.hoisted(() => ({
packageAsk: 0,
packagesPage: 0,
schemaForm: 0,
designerStrings: 0,
viewConfigPanel: 0,
createViewDialog: 0,
}));

const toastError = vi.hoisted(() => vi.fn());

vi.mock('sonner', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
toast: { error: toastError, success: vi.fn(), info: vi.fn(), warning: vi.fn(), message: vi.fn() },
}));

vi.mock('../providers/MetadataProvider', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
useMetadata: () => ({ apps: [] }),
}));

// A stand-in dialog: open, it offers one package; the case answers with it.
vi.mock('./metadata-admin/PackageCreateAsk', () => {
loads.packageAsk += 1;
return {
PackageCreateAskDialog: ({ open, onAnswer }: { open: boolean; onAnswer: (id: string | null) => void }) => (
<div data-testid="stub-package-ask" data-open={String(open)}>
<button type="button" data-testid="stub-package-ask-pick" onClick={() => onAnswer('com.example.pick')} />
</div>
),
runtimeCreateRefusalText: (notSaved: { reason: string }, kind: string, locale: string) =>
notSaved.reason === 'cancelled' ? null : `refused ${kind} in ${locale}`,
};
});

vi.mock('./metadata-admin/PackagesPage', async (importOriginal) => {
loads.packagesPage += 1;
return importOriginal<Record<string, unknown>>();
});

vi.mock('./metadata-admin/SchemaForm', async (importOriginal) => {
loads.schemaForm += 1;
return importOriginal<Record<string, unknown>>();
});

vi.mock('./metadata-admin/i18n', async (importOriginal) => {
loads.designerStrings += 1;
return importOriginal<Record<string, unknown>>();
});

vi.mock('./ViewConfigPanel', async (importOriginal) => {
loads.viewConfigPanel += 1;
return importOriginal<Record<string, unknown>>();
});

vi.mock('./CreateViewDialog', async (importOriginal) => {
loads.createViewDialog += 1;
return importOriginal<Record<string, unknown>>();
});

// `objectViewViewCrud` reaches a dynamic `import('@objectstack/lint')`: pay its
// load at collection, never inside a case's clocked window.
import '@objectstack/lint';
import './ObjectView';
import { reportViewNotSaved, useRuntimeCreateApp } from './objectViewViewCrud';
import { RuntimeCreateNotSavedError } from './runtime-metadata-persistence';

type CreateApp = ReturnType<typeof useRuntimeCreateApp>;

function AskHost({ onApp }: { onApp: (app: CreateApp) => void }) {
const app = useRuntimeCreateApp();
onApp(app);
return app.askDialog;
}

describe('objectstack#37444 — the object list route loads no authoring code before it is asked', () => {
it('importing the list route evaluates none of the authoring modules', () => {
expect(loads).toEqual({
packageAsk: 0,
packagesPage: 0,
schemaForm: 0,
designerStrings: 0,
viewConfigPanel: 0,
createViewDialog: 0,
});
});

it('the package ask loads its dialog on the first ask, answers it, and keeps it mounted closed', async () => {
expect(loads.packageAsk).toBe(0);
let app: CreateApp | null = null;
render(
<MemoryRouter>
<AskHost onApp={(next) => { app = next; }} />
</MemoryRouter>,
);
// Nothing asked yet: the dialog module is not loaded and nothing is drawn.
expect(loads.packageAsk).toBe(0);
expect(screen.queryByTestId('stub-package-ask')).toBeNull();

let answer: Promise<string | null> | undefined;
act(() => {
answer = app!.askPackage({ preselect: null });
});
await waitFor(() => expect(screen.getByTestId('stub-package-ask')).toHaveAttribute('data-open', 'true'));
expect(loads.packageAsk).toBe(1);

fireEvent.click(screen.getByTestId('stub-package-ask-pick'));
await expect(answer!).resolves.toBe('com.example.pick');
// Answered, it closes but stays mounted, so it closes the way it always did.
await waitFor(() => expect(screen.getByTestId('stub-package-ask')).toHaveAttribute('data-open', 'false'));
});

it('a refused view create says why once its words have loaded; a cancelled one says nothing', async () => {
toastError.mockClear();
expect(reportViewNotSaved(new Error('other'), 'en')).toBe(false);
expect(reportViewNotSaved(new RuntimeCreateNotSavedError('system-app'), 'zh-CN')).toBe(true);
// The words are in the designer strings, loaded on the refusal: the toast follows.
await waitFor(() => expect(toastError).toHaveBeenCalledTimes(1));
expect(toastError).toHaveBeenCalledWith('refused view in zh-CN');
expect(reportViewNotSaved(new RuntimeCreateNotSavedError('cancelled'), 'en')).toBe(true);
await act(() => new Promise<void>((resolve) => setTimeout(resolve, 50)));
expect(toastError).toHaveBeenCalledTimes(1);
});
});
Loading
Loading