Skip to content
Merged
22 changes: 22 additions & 0 deletions .changeset/36102-grid-field-lazy-body.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
---
'@object-ui/fields': patch
'@object-ui/plugin-form': patch
'@object-ui/console': patch
'@objectstack/spec': patch
---

perf(fields): the line-item grid's body loads on first use, and the console's first load no longer carries it

Clause-②: yes (widening)
Metadata-protocol: none

The line-item grid (the `grid` field and the line items of a master-detail form) was the largest field widget in the console's first-load bytes, though only a form with line items draws it. Its body now loads the first time a grid is drawn, or earlier, when a form that draws line items mounts.

- **The same two components.** `GridField` and `LineItemsField` keep their names and their props. They now render the grid's body once it has loaded; a grid mounted before that shows a small busy placeholder until it arrives. A grid mounted after the body loaded renders it directly, and a grid that showed the placeholder draws the body once it arrives and never remounts it on a later render, so its rows and focused cell stay.
- **One new export, `preloadGridField()`.** It starts loading the body ahead of the first grid. It is safe to call often, its promise settles once the body has loaded, and it never rejects: a failed load is reported by the grid that needs it, through the nearest error boundary.
- **The record forms wait for it.** `MasterDetailForm` and the record page's line-item editor derive a grid's columns from the child object's schema, and now show those columns only once the body has loaded as well, so on a form's first open the grid never shows the placeholder. `LineItemsPanel` starts the load when it mounts.
- **The helpers stay where they were.** `evalArith`, `computeRow`, `lookupAutofillPatch`, `columnHelpByField`, `UNTOUCHED_NEW_ROW`, `isUntouchedNewRow` and the `GridColumn`, `ColumnCurrencies` and `ColumnHelp` types are exported as before and load with the package.
- **The console loads it on demand.** The console's build puts the grid's body in a chunk of its own (`fields-grid`), loaded on demand, so its first load is about 6 KB (gzip) smaller.
- **The liveness ledger points at the helper's new file.** In `@objectstack/spec`, the evidence path for `lookupAutofill` in the field liveness ledger now names `widgets/GridField.ts`, where `lookupAutofillPatch` lives; the verdict does not change.

A host that renders `GridField` or `LineItemsField` itself and needs the grid in its first render calls `preloadGridField()` earlier and waits for it, as the record forms do. No metadata key, value or default changes.
2 changes: 1 addition & 1 deletion packages/spec/liveness/field.json
Original file line number Diff line number Diff line change
Expand Up @@ -398,7 +398,7 @@
"status": "live",
"verifiedAt": "2026-10-31",
"evidenceScope": "in-repo",
"evidence": "ui/packages/fields/src/widgets/lookupAutofill.ts#declaredLookupAutofillPatch (the one fill rule: each target from the picked record's source, filled only while empty or still holding the earlier pick's value unless `overwrite: true`); ui/packages/fields/src/widgets/LookupField.tsx#fillDeclaredTargets (the record form: every single-value pick path, popover, keyboard, quick-create and the browse-all dialog, reads the field's pairs and writes through the host's `onAutofill`); ui/packages/components/src/renderers/form/form.tsx#LOOKUP_AUTOFILL_WIDGET_TYPES (the form renderer hands a lookup its `onAutofill` writer, `form.setValue` as an edit); ui/packages/fields/src/widgets/GridField.tsx#lookupAutofillPatch (the line-item grid: the declared pair fills under the same rule and takes its target out of the same-named `autofill` copy), its pairs handed over by ui/packages/plugin-form/src/MasterDetailForm.tsx#lookupAutofill and ui/packages/plugin-form/src/LineItemsPanel.tsx#lineLookupAutofill through ui/packages/fields/src/widgets/lookupAutofill.ts#lookupAutofillByField; authoring doors unchanged: packages/spec/src/data/field.zod.ts#lookupAutofill, packages/spec/src/data/object.zod.ts#refuseDishonestLookupAutofill, packages/spec/src/stack.zod.ts#collectLookupAutofillErrors",
"evidence": "ui/packages/fields/src/widgets/lookupAutofill.ts#declaredLookupAutofillPatch (the one fill rule: each target from the picked record's source, filled only while empty or still holding the earlier pick's value unless `overwrite: true`); ui/packages/fields/src/widgets/LookupField.tsx#fillDeclaredTargets (the record form: every single-value pick path, popover, keyboard, quick-create and the browse-all dialog, reads the field's pairs and writes through the host's `onAutofill`); ui/packages/components/src/renderers/form/form.tsx#LOOKUP_AUTOFILL_WIDGET_TYPES (the form renderer hands a lookup its `onAutofill` writer, `form.setValue` as an edit); ui/packages/fields/src/widgets/GridField.ts#lookupAutofillPatch (the line-item grid: the declared pair fills under the same rule and takes its target out of the same-named `autofill` copy), its pairs handed over by ui/packages/plugin-form/src/MasterDetailForm.tsx#lookupAutofill and ui/packages/plugin-form/src/LineItemsPanel.tsx#lineLookupAutofill through ui/packages/fields/src/widgets/lookupAutofill.ts#lookupAutofillByField; authoring doors unchanged: packages/spec/src/data/field.zod.ts#lookupAutofill, packages/spec/src/data/object.zod.ts#refuseDishonestLookupAutofill, packages/spec/src/stack.zod.ts#collectLookupAutofillErrors",
"note": "LIVE — read by the record form and the line-item grid on a pick. Pinned end to end by ui/packages/plugin-form/src/ObjectForm.lookupAutofill-28245.test.tsx (an empty target fills and is saved, a typed value is kept, `overwrite: true` replaces, an earlier pick's value is replaced, the browse-all dialog fills too, a lookup without the key fills nothing) and ui/packages/fields/src/widgets/GridField.lookupAutofill-28245.test.tsx (the same rule in a grid row, the declared target out of the same-named copy, a stored line's own value kept). Bound: a master-detail collection whose relationship and every column are authored loads no child schema, so its grid fills only the same-named copy. PRODUCER: HotCRM's quote line item (product lookup, `unit_price` from the product's `list_price`).",
"children": {
"target": {
Expand Down
24 changes: 24 additions & 0 deletions ui/apps/console/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1507,6 +1507,30 @@ export default defineConfig({
priority: 82,
includeDependenciesRecursively: false,
},
//
// ## The line-item grid leaves the eager line (objectstack#36102)
//
// The same mechanism as the date picker above, one widget over. The
// grid's body is `packages/fields/src/widgets/grid-field/`, and
// nothing reaches it but `loadGridFieldWidget`'s `import()` in
// `widgets/GridField.ts`: the `GridField` / `LineItemsField` the
// package exports by name are the small lazy face in that file, so
// the entry's named export no longer makes the body a static
// dependency of the eager graph. Without this group `ui-components`
// would still claim the directory by path. Its pure helpers, which
// the entry also exports, stay in `ui-components`. The record forms
// that draw line items preload it on mount.
// `PER_CHUNK_MEMBERSHIP_CARVE_OUTS` in
// `scripts/check-eager-closure-budget.mjs` holds the split to the
// module, and errors if this chunk ever joins the eager closure.
// `includeDependenciesRecursively: false` for the reason given on
// `fields-date-picker`.
{
name: 'fields-grid',
test: /[\\/]packages[\\/]fields[\\/]src[\\/]widgets[\\/]grid-field[\\/]/,
priority: 82,
includeDependenciesRecursively: false,
},
{ name: 'ui-components', test: /[\\/]packages[\\/](components|fields)[\\/]/, priority: 80 },
{ name: 'ui-layout', test: /[\\/]packages[\\/]layout[\\/]/, priority: 80 },
{ name: 'infrastructure', test: /[\\/]packages[\\/](auth|permissions|tenant)[\\/]/, priority: 80 },
Expand Down
89 changes: 88 additions & 1 deletion ui/e2e/live/master-detail.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { test, expect, type APIRequestContext, type Page, type Response } from '@playwright/test';
import { selectOption, fillLookup } from './helpers';
import { selectOption, fillLookup, addLineItem } from './helpers';

/**
* Live e2e for the master-detail entry form (showcase "New Project + Tasks").
Expand Down Expand Up @@ -145,3 +145,90 @@ test('Create with a task line stores the child referencing the parent', async ({
expect(child?.title).toBe('E2E Task A');
expect(child?.project).toBe(parentId);
});

/**
* objectstack#36102 — the line-item grid's body left the console's eager chunk:
* `@object-ui/fields` exports a lazy face whose body loads through one
* `import()`, which the record forms start when they mount and wait for with
* the child schema they derive the columns from. On a form's FIRST open the
* grid must therefore mount on its body, never on its loading placeholder
* (`grid-field-loading`), and a cell the user is typing in must keep focus.
*
* The observer is installed before the document's first byte, so it sees every
* attach of the placeholder, however brief. Its control is the grid itself: the
* same observer must have seen `line-items` attach, or a zero count would only
* say the observer saw nothing.
*/
test.describe('the line-item grid on a form\'s first open (objectstack#36102)', () => {
const INVOICES = '/apps/showcase_app/showcase_invoice';

/** Count every attach of the placeholder and of the grid, from document start. */
async function watchGridMounts(page: Page) {
await page.addInitScript(() => {
const seen = { placeholder: 0, grid: 0 };
(window as unknown as { __gridMounts: typeof seen }).__gridMounts = seen;
const count = (node: Node) => {
if (!(node instanceof Element)) return;
seen.placeholder += node.matches('[data-testid="grid-field-loading"]') ? 1 : 0;
seen.placeholder += node.querySelectorAll('[data-testid="grid-field-loading"]').length;
seen.grid += node.matches('[data-testid="line-items"]') ? 1 : 0;
seen.grid += node.querySelectorAll('[data-testid="line-items"]').length;
};
new MutationObserver((records) => {
for (const record of records) record.addedNodes.forEach(count);
}).observe(document, { childList: true, subtree: true });
});
}

const gridMounts = (page: Page) =>
page.evaluate(() => (window as unknown as { __gridMounts: { placeholder: number; grid: number } }).__gridMounts);

/** Type into the first Description cell and check the cell kept focus and the text. */
async function typeKeepsFocus(page: Page, scope: ReturnType<Page['getByTestId']>) {
const cell = scope.locator('input[aria-label="Description"]').first();
await cell.click();
// A stored line already has text: type at its end, not where the click landed.
await cell.press('End');
await cell.pressSequentially('first-open');
// A beat for any late remount to land before it is checked.
await page.waitForTimeout(300);
await expect(cell).toBeFocused();
await expect(cell).toHaveValue(/first-open$/);
}

test('the New Invoice form draws its line grid on its body, and a typed cell keeps focus', async ({ page }) => {
await watchGridMounts(page);
await page.goto(INVOICES);
await page.getByTestId('object-view-new-button').first().click();
const dialog = page.getByRole('dialog');
const grid = dialog.getByTestId('line-items');
await expect(grid).toBeVisible();

await addLineItem(page);
await typeKeepsFocus(page, grid);

const mounts = await gridMounts(page);
expect(mounts.grid, 'the observer saw the grid attach (its control)').toBeGreaterThan(0);
expect(mounts.placeholder, 'the grid never mounted on its loading placeholder').toBe(0);
});

test('an invoice edit form draws its stored lines on the body, and a typed cell keeps focus', async ({ page, request }) => {
const res = await request.get(`${API}/api/v1/data/showcase_invoice?$top=50`);
expect(res.ok(), `GET showcase_invoice answered ${res.status()}`).toBe(true);
const body = await res.json();
const invoice = (body?.records ?? body?.data ?? []).find((r: { name?: string }) => r.name === 'INV-1002');
expect(invoice, 'the seeded draft invoice INV-1002 exists').toBeTruthy();

await watchGridMounts(page);
await page.goto(`${INVOICES}/record/${encodeURIComponent(invoice.id ?? invoice._id)}/edit`);
const grid = page.getByTestId('line-items');
await expect(grid).toBeVisible();
await expect(grid.locator('input[aria-label="Description"]').first()).not.toHaveValue('');

await typeKeepsFocus(page, grid);

const mounts = await gridMounts(page);
expect(mounts.grid, 'the observer saw the grid attach (its control)').toBeGreaterThan(0);
expect(mounts.placeholder, 'the grid never mounted on its loading placeholder').toBe(0);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ import { formatDate } from '@object-ui/core';
import { I18nProvider, LocalizationProvider } from '@object-ui/i18n';
import { DateField } from '../widgets/DateField';
import { FormulaField } from '../widgets/FormulaField';
import { GridField } from '../widgets/GridField';
import { GridFieldWidget as GridField } from '../widgets/grid-field/GridFieldWidget';
import { renderLookupColumnValue } from '../widgets/lookupColumnDisplay';

afterEach(cleanup);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ import { DateCellRenderer, DateTimeCellRenderer } from '../index';
import { DateField } from '../widgets/DateField';
import { DateTimeField } from '../widgets/DateTimeField';
import { FormulaField } from '../widgets/FormulaField';
import { GridField } from '../widgets/GridField';
import { GridFieldWidget as GridField } from '../widgets/grid-field/GridFieldWidget';

/**
* `n` days from today, pinned to local noon so a run that starts near
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ import '@testing-library/jest-dom';
import { formatDateTime } from '@object-ui/core';
import { I18nProvider, LocalizationProvider } from '@object-ui/i18n';
import { DateTimeField } from '../widgets/DateTimeField';
import { GridField } from '../widgets/GridField';
import { GridFieldWidget as GridField } from '../widgets/grid-field/GridFieldWidget';

/** The five locales this change was measured in (objectui#8194's set). */
const LOCALES = ['en', 'de', 'zh', 'ja', 'ar'] as const;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ import { FormulaField } from '../widgets/FormulaField';
import { SummaryField } from '../widgets/SummaryField';
import { AutoNumberField } from '../widgets/AutoNumberField';
import { VectorField } from '../widgets/VectorField';
import { GridField } from '../widgets/GridField';
import { GridFieldWidget as GridField } from '../widgets/grid-field/GridFieldWidget';
import { TextField } from '../widgets/TextField';

const DISPLAY_TYPES = ['formula', 'summary', 'auto_number', 'vector'] as const;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,11 @@
* That yields SIX bare no-bag sites, two more than the card's four:
*
* 1. `widgets/DateField.tsx` readonly `date` widget ← fixed
* 2. `widgets/GridField.tsx` sub-grid `date` column ← fixed
* 2. `widgets/grid-field/GridFieldWidget.tsx` sub-grid `date` column ← fixed
* 3. `widgets/FormulaField.tsx` `returnType: 'date'` ← fixed
* 4. `widgets/lookupColumnDisplay.tsx` the `$date` fallback ← fixed
* 5. `widgets/DateField`'s sibling `DateTimeField.tsx` readonly ← NOT
* 6. `widgets/GridField.tsx`'s `datetime`/`time` branch ← NOT
* 6. `widgets/grid-field/GridFieldWidget.tsx`'s `datetime`/`time` branch ← NOT
*
* 5 and 6 are DATETIME faces. Their one home is `formatDateTime`, which has
* its own face vocabulary (`'compact'` from objectui#7443 versus the verbose
Expand Down Expand Up @@ -83,7 +83,7 @@ import { I18nProvider, LocalizationProvider } from '@object-ui/i18n';
import { DateField } from '../widgets/DateField';
import { DateTimeField } from '../widgets/DateTimeField';
import { FormulaField } from '../widgets/FormulaField';
import { GridField } from '../widgets/GridField';
import { GridFieldWidget as GridField } from '../widgets/grid-field/GridFieldWidget';
import { renderLookupColumnValue } from '../widgets/lookupColumnDisplay';

/** The five locales this change was measured in. */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import '@object-ui/components';
import { FormulaCellRenderer, withFollowedParentObject } from '../index';
import { CurrencyField } from '../widgets/CurrencyField';
import { SummaryField } from '../widgets/SummaryField';
import { GridField } from '../widgets/GridField';
import { GridFieldWidget as GridField } from '../widgets/grid-field/GridFieldWidget';
import { TextField } from '../widgets/TextField';

afterEach(cleanup);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ import { AutoNumberField } from '../widgets/AutoNumberField';
import { UserField } from '../widgets/UserField';
import { ObjectField } from '../widgets/ObjectField';
import { VectorField } from '../widgets/VectorField';
import { GridField } from '../widgets/GridField';
import { GridFieldWidget as GridField } from '../widgets/grid-field/GridFieldWidget';
import { ColorField } from '../widgets/ColorField';
import { SliderField } from '../widgets/SliderField';
import { CodeField } from '../widgets/CodeField';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ import { AutoNumberField } from '../widgets/AutoNumberField';
import { UserField } from '../widgets/UserField';
import { ObjectField } from '../widgets/ObjectField';
import { VectorField } from '../widgets/VectorField';
import { GridField } from '../widgets/GridField';
import { GridFieldWidget as GridField } from '../widgets/grid-field/GridFieldWidget';
import { ColorField } from '../widgets/ColorField';
import { SliderField } from '../widgets/SliderField';
import { RatingField } from '../widgets/RatingField';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ import { AutoNumberField } from '../widgets/AutoNumberField';
import { UserField } from '../widgets/UserField';
import { ObjectField } from '../widgets/ObjectField';
import { VectorField } from '../widgets/VectorField';
import { GridField } from '../widgets/GridField';
import { GridFieldWidget as GridField } from '../widgets/grid-field/GridFieldWidget';
import { ColorField } from '../widgets/ColorField';
import { SliderField } from '../widgets/SliderField';
import { RatingField } from '../widgets/RatingField';
Expand Down
2 changes: 1 addition & 1 deletion ui/packages/fields/src/complex-widgets.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { LookupField } from './widgets/LookupField';
import { ActionProvider } from '@object-ui/react';
import { FieldEditWidget } from './FieldEditWidget';
import { MasterDetailField } from './widgets/MasterDetailField';
import { GridField } from './widgets/GridField';
import { GridFieldWidget as GridField } from './widgets/grid-field/GridFieldWidget';
import { FileField, FileCell } from './widgets/FileField';
import { UploadProvider } from './widgets/UploadProvider';
import type { UploadAdapter, UploadResult } from '@object-ui/types';
Expand Down
Loading
Loading