diff --git a/.changeset/36102-grid-field-lazy-body.md b/.changeset/36102-grid-field-lazy-body.md new file mode 100644 index 00000000000..934a1234766 --- /dev/null +++ b/.changeset/36102-grid-field-lazy-body.md @@ -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. diff --git a/packages/spec/liveness/field.json b/packages/spec/liveness/field.json index 5f37d85809c..d2ae6891b7a 100644 --- a/packages/spec/liveness/field.json +++ b/packages/spec/liveness/field.json @@ -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": { diff --git a/ui/apps/console/vite.config.ts b/ui/apps/console/vite.config.ts index f2c19fd620f..52f948a9c7b 100644 --- a/ui/apps/console/vite.config.ts +++ b/ui/apps/console/vite.config.ts @@ -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 }, diff --git a/ui/e2e/live/master-detail.spec.ts b/ui/e2e/live/master-detail.spec.ts index 2d2a4bb5b72..3a9a2cfb8a4 100644 --- a/ui/e2e/live/master-detail.spec.ts +++ b/ui/e2e/live/master-detail.spec.ts @@ -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"). @@ -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) { + 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); + }); +}); diff --git a/ui/packages/fields/src/__tests__/date-carrier-unparsable-8809.test.tsx b/ui/packages/fields/src/__tests__/date-carrier-unparsable-8809.test.tsx index aee34f90ff5..6c7cf535f3c 100644 --- a/ui/packages/fields/src/__tests__/date-carrier-unparsable-8809.test.tsx +++ b/ui/packages/fields/src/__tests__/date-carrier-unparsable-8809.test.tsx @@ -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); diff --git a/ui/packages/fields/src/__tests__/date-locale-channel.test.tsx b/ui/packages/fields/src/__tests__/date-locale-channel.test.tsx index 1d6de325607..bba9d211fb0 100644 --- a/ui/packages/fields/src/__tests__/date-locale-channel.test.tsx +++ b/ui/packages/fields/src/__tests__/date-locale-channel.test.tsx @@ -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 diff --git a/ui/packages/fields/src/__tests__/datetime-widget-faces-8209.test.tsx b/ui/packages/fields/src/__tests__/datetime-widget-faces-8209.test.tsx index 7c79454fb8a..0bf3da1ce9e 100644 --- a/ui/packages/fields/src/__tests__/datetime-widget-faces-8209.test.tsx +++ b/ui/packages/fields/src/__tests__/datetime-widget-faces-8209.test.tsx @@ -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; diff --git a/ui/packages/fields/src/__tests__/display-grid-host-channels-e2e.test.tsx b/ui/packages/fields/src/__tests__/display-grid-host-channels-e2e.test.tsx index 180343a2a18..5d557f85676 100644 --- a/ui/packages/fields/src/__tests__/display-grid-host-channels-e2e.test.tsx +++ b/ui/packages/fields/src/__tests__/display-grid-host-channels-e2e.test.tsx @@ -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; diff --git a/ui/packages/fields/src/__tests__/fields-date-widget-convention-8194.test.tsx b/ui/packages/fields/src/__tests__/fields-date-widget-convention-8194.test.tsx index 315975f19fa..103c3791ff3 100644 --- a/ui/packages/fields/src/__tests__/fields-date-widget-convention-8194.test.tsx +++ b/ui/packages/fields/src/__tests__/fields-date-widget-convention-8194.test.tsx @@ -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 @@ -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. */ diff --git a/ui/packages/fields/src/__tests__/parentCurrency.faces-31912.test.tsx b/ui/packages/fields/src/__tests__/parentCurrency.faces-31912.test.tsx index e99ab382da1..9021d34664d 100644 --- a/ui/packages/fields/src/__tests__/parentCurrency.faces-31912.test.tsx +++ b/ui/packages/fields/src/__tests__/parentCurrency.faces-31912.test.tsx @@ -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); diff --git a/ui/packages/fields/src/__tests__/readonly-host-plumbing-e2e.test.tsx b/ui/packages/fields/src/__tests__/readonly-host-plumbing-e2e.test.tsx index 650fc0fb534..6c5d86b5362 100644 --- a/ui/packages/fields/src/__tests__/readonly-host-plumbing-e2e.test.tsx +++ b/ui/packages/fields/src/__tests__/readonly-host-plumbing-e2e.test.tsx @@ -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'; diff --git a/ui/packages/fields/src/__tests__/widget-aria-invalid-registry-e2e.test.tsx b/ui/packages/fields/src/__tests__/widget-aria-invalid-registry-e2e.test.tsx index 4bd56dacb89..74663b4a58e 100644 --- a/ui/packages/fields/src/__tests__/widget-aria-invalid-registry-e2e.test.tsx +++ b/ui/packages/fields/src/__tests__/widget-aria-invalid-registry-e2e.test.tsx @@ -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'; diff --git a/ui/packages/fields/src/__tests__/widget-dom-leak-e2e.test.tsx b/ui/packages/fields/src/__tests__/widget-dom-leak-e2e.test.tsx index 71003925ae6..85269ccf15a 100644 --- a/ui/packages/fields/src/__tests__/widget-dom-leak-e2e.test.tsx +++ b/ui/packages/fields/src/__tests__/widget-dom-leak-e2e.test.tsx @@ -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'; diff --git a/ui/packages/fields/src/complex-widgets.test.tsx b/ui/packages/fields/src/complex-widgets.test.tsx index 4544d3890aa..f09604a11da 100644 --- a/ui/packages/fields/src/complex-widgets.test.tsx +++ b/ui/packages/fields/src/complex-widgets.test.tsx @@ -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'; diff --git a/ui/packages/fields/src/index.tsx b/ui/packages/fields/src/index.tsx index d2a3f0ce1d6..971c96fc30e 100644 --- a/ui/packages/fields/src/index.tsx +++ b/ui/packages/fields/src/index.tsx @@ -34,6 +34,7 @@ import { deriveHexBadgePalette } from './hexBadgePalette.js'; import { formatNumberFieldValue, formatCurrency, formatPercentPoints, percentCellScale } from './widgets/number-format.js'; import { useFieldTranslation } from './widgets/useFieldTranslation.js'; import { useBooleanValueLabel } from './widgets/booleanValueLabel.js'; +import { loadGridFieldWidget } from './widgets/GridField.js'; import { RecordHoverCard, type RecordHoverCardObjectDef } from './RecordHoverCard.js'; // Module-level cache so multiple renderers fetching the same lookup ID @@ -4820,7 +4821,9 @@ const fieldWidgetMap = { // Complex data types 'object': () => import('./widgets/ObjectField.js').then(m => ({ default: m.ObjectField })), 'vector': () => import('./widgets/VectorField.js').then(m => ({ default: m.VectorField })), - 'grid': () => import('./widgets/GridField.js').then(m => ({ default: m.GridField })), + // The grid's body, through its public face's one loader so a lazy `GridField` + // mounted after this resolved renders without a boundary (objectstack#36102). + 'grid': () => loadGridFieldWidget().then(m => ({ default: m.GridFieldWidget })), // Additional field types from @objectstack/spec 'color': () => import('./widgets/ColorField.js').then(m => ({ default: m.ColorField })), @@ -5499,7 +5502,10 @@ export * from './widgets/AutoNumberField.js'; export * from './widgets/UserField.js'; export * from './widgets/ObjectField.js'; export * from './widgets/VectorField.js'; -export { evalArith, lookupAutofillPatch, computeRow, GridField, LineItemsField, UNTOUCHED_NEW_ROW, isUntouchedNewRow, columnHelpByField } from './widgets/GridField.js'; +// `GridField` / `LineItemsField` are the grid's lazy face: the body loads on +// first use, or earlier through `preloadGridField` (objectstack#36102). The +// pure helpers beside them are eager. See `widgets/GridField.ts`. +export { evalArith, lookupAutofillPatch, computeRow, GridField, LineItemsField, preloadGridField, UNTOUCHED_NEW_ROW, isUntouchedNewRow, columnHelpByField } from './widgets/GridField.js'; export type { ColumnCurrencies, ColumnHelp } from './widgets/GridField.js'; export type { GridColumn } from './widgets/GridField.js'; export * from './widgets/lookupAutofill.js'; diff --git a/ui/packages/fields/src/requiredWhenPrompt.ts b/ui/packages/fields/src/requiredWhenPrompt.ts index 2600a334aa3..d072c4cee09 100644 --- a/ui/packages/fields/src/requiredWhenPrompt.ts +++ b/ui/packages/fields/src/requiredWhenPrompt.ts @@ -25,7 +25,7 @@ * The verdict comes from `@object-ui/core`'s {@link resolveFieldRuleState} — * the SAME function the record form (`components/renderers/form/form.tsx`), * the wizard (`plugin-form/WizardForm.tsx`) and the line-item grid - * (`fields/widgets/GridField.tsx`) resolve `visibleWhen`/`readonlyWhen`/ + * (`fields/widgets/grid-field/GridFieldWidget.tsx`) resolve `visibleWhen`/`readonlyWhen`/ * `requiredWhen` with, which in turn delegates to `@objectstack/formula`'s * `ExpressionEngine`. That is deliberate and load-bearing: the prompt and the * server's enforcement must reach the identical verdict, and a second diff --git a/ui/packages/fields/src/widgets/DateField.impossibleDay-10567.test.tsx b/ui/packages/fields/src/widgets/DateField.impossibleDay-10567.test.tsx index de9254a5af6..5498a623376 100644 --- a/ui/packages/fields/src/widgets/DateField.impossibleDay-10567.test.tsx +++ b/ui/packages/fields/src/widgets/DateField.impossibleDay-10567.test.tsx @@ -37,7 +37,7 @@ import React from 'react'; import { afterEach, describe, expect, it, vi } from 'vitest'; import { cleanup, fireEvent, render, screen } from '@testing-library/react'; import { DateField } from './DateField'; -import { GridField } from './GridField'; +import { GridFieldWidget as GridField } from './grid-field/GridFieldWidget'; afterEach(() => cleanup()); diff --git a/ui/packages/fields/src/widgets/DateTimeField.impossibleDay-10474.test.tsx b/ui/packages/fields/src/widgets/DateTimeField.impossibleDay-10474.test.tsx index b88315d5f8f..e1444f6a031 100644 --- a/ui/packages/fields/src/widgets/DateTimeField.impossibleDay-10474.test.tsx +++ b/ui/packages/fields/src/widgets/DateTimeField.impossibleDay-10474.test.tsx @@ -38,7 +38,7 @@ import React from 'react'; import { afterEach, describe, expect, it, vi } from 'vitest'; import { cleanup, fireEvent, render, screen } from '@testing-library/react'; import { DateTimeField } from './DateTimeField'; -import { GridField } from './GridField'; +import { GridFieldWidget as GridField } from './grid-field/GridFieldWidget'; import { fromDateTimeInputValue, isImpossibleStoredDay, diff --git a/ui/packages/fields/src/widgets/GridField.currencyMinorUnit-10355.test.tsx b/ui/packages/fields/src/widgets/GridField.currencyMinorUnit-10355.test.tsx index 8a67c551823..adb8ceffd20 100644 --- a/ui/packages/fields/src/widgets/GridField.currencyMinorUnit-10355.test.tsx +++ b/ui/packages/fields/src/widgets/GridField.currencyMinorUnit-10355.test.tsx @@ -28,7 +28,8 @@ import { describe, it, expect, vi, afterEach } from 'vitest'; import { render, screen, fireEvent, cleanup } from '@testing-library/react'; import * as React from 'react'; import { LocalizationProvider } from '@object-ui/i18n'; -import { GridField, computeRow, type GridColumn } from './GridField'; +import { GridFieldWidget as GridField } from './grid-field/GridFieldWidget'; +import { computeRow, type GridColumn } from './GridField'; afterEach(() => cleanup()); diff --git a/ui/packages/fields/src/widgets/GridField.currencyScaleNotRead-10783.test.tsx b/ui/packages/fields/src/widgets/GridField.currencyScaleNotRead-10783.test.tsx index f891fcf8f3d..a86a5b4bfb9 100644 --- a/ui/packages/fields/src/widgets/GridField.currencyScaleNotRead-10783.test.tsx +++ b/ui/packages/fields/src/widgets/GridField.currencyScaleNotRead-10783.test.tsx @@ -33,7 +33,8 @@ import { describe, it, expect, afterEach } from 'vitest'; import { render, cleanup } from '@testing-library/react'; import * as React from 'react'; import { LocalizationProvider } from '@object-ui/i18n'; -import { GridField, computeRow, type GridColumn } from './GridField'; +import { GridFieldWidget as GridField } from './grid-field/GridFieldWidget'; +import { computeRow, type GridColumn } from './GridField'; afterEach(() => cleanup()); diff --git a/ui/packages/fields/src/widgets/GridField.declaredSpelling.test.tsx b/ui/packages/fields/src/widgets/GridField.declaredSpelling.test.tsx index a69cce177a5..acbec38ac04 100644 --- a/ui/packages/fields/src/widgets/GridField.declaredSpelling.test.tsx +++ b/ui/packages/fields/src/widgets/GridField.declaredSpelling.test.tsx @@ -40,7 +40,7 @@ import { describe, it, expect, vi } from 'vitest'; import { render, screen, fireEvent } from '@testing-library/react'; import React from 'react'; import type { GridFieldMetadata } from '@object-ui/types'; -import { GridField } from './GridField'; +import { GridFieldWidget as GridField } from './grid-field/GridFieldWidget'; /** Authored exactly as `GridFieldMetadata['columns']` declares — keyed by `name`. */ const columns: NonNullable = [ diff --git a/ui/packages/fields/src/widgets/GridField.displayLocale-9909.test.tsx b/ui/packages/fields/src/widgets/GridField.displayLocale-9909.test.tsx index e18501c0f19..cce4e6a0ab3 100644 --- a/ui/packages/fields/src/widgets/GridField.displayLocale-9909.test.tsx +++ b/ui/packages/fields/src/widgets/GridField.displayLocale-9909.test.tsx @@ -33,7 +33,7 @@ import { render, cleanup } from '@testing-library/react'; import * as React from 'react'; import { I18nProvider, LocalizationProvider } from '@object-ui/i18n'; import { isMachineLocale, recordLocaleArguments } from '@object-ui/test-support'; -import { GridField } from './GridField'; +import { GridFieldWidget as GridField } from './grid-field/GridFieldWidget'; afterEach(() => cleanup()); diff --git a/ui/packages/fields/src/widgets/GridField.fieldKeys-11070.test.tsx b/ui/packages/fields/src/widgets/GridField.fieldKeys-11070.test.tsx index b24d6444afc..618ffbfcd3c 100644 --- a/ui/packages/fields/src/widgets/GridField.fieldKeys-11070.test.tsx +++ b/ui/packages/fields/src/widgets/GridField.fieldKeys-11070.test.tsx @@ -52,7 +52,7 @@ import { describe, expect, it, vi } from 'vitest'; import { fireEvent, render, screen } from '@testing-library/react'; import React from 'react'; import type { GridFieldMetadata } from '@object-ui/types'; -import { GridField } from './GridField'; +import { GridFieldWidget as GridField } from './grid-field/GridFieldWidget'; const columns: NonNullable = [ { name: 'description', label: 'Description', type: 'text' }, diff --git a/ui/packages/fields/src/widgets/GridField.fileCellText-12924.no-provider.test.tsx b/ui/packages/fields/src/widgets/GridField.fileCellText-12924.no-provider.test.tsx index 7eb1da75bdb..d75e79f885b 100644 --- a/ui/packages/fields/src/widgets/GridField.fileCellText-12924.no-provider.test.tsx +++ b/ui/packages/fields/src/widgets/GridField.fileCellText-12924.no-provider.test.tsx @@ -26,7 +26,7 @@ import { describe, it, expect, afterEach } from 'vitest'; import * as React from 'react'; import { render, cleanup } from '@testing-library/react'; -import { GridField } from './GridField'; +import { GridFieldWidget as GridField } from './grid-field/GridFieldWidget'; afterEach(() => cleanup()); diff --git a/ui/packages/fields/src/widgets/GridField.fileCellText-12924.test.tsx b/ui/packages/fields/src/widgets/GridField.fileCellText-12924.test.tsx index da634bfd812..7404306c03e 100644 --- a/ui/packages/fields/src/widgets/GridField.fileCellText-12924.test.tsx +++ b/ui/packages/fields/src/widgets/GridField.fileCellText-12924.test.tsx @@ -31,7 +31,7 @@ import * as React from 'react'; import { render, cleanup, waitFor } from '@testing-library/react'; import { I18nProvider } from '@object-ui/i18n'; import { en, ru, zh } from '@object-ui/i18n/locales'; -import { GridField } from './GridField'; +import { GridFieldWidget as GridField } from './grid-field/GridFieldWidget'; afterEach(() => cleanup()); diff --git a/ui/packages/fields/src/widgets/GridField.i18nChrome-11131.no-provider.test.tsx b/ui/packages/fields/src/widgets/GridField.i18nChrome-11131.no-provider.test.tsx index 15830957490..6efc6485e0d 100644 --- a/ui/packages/fields/src/widgets/GridField.i18nChrome-11131.no-provider.test.tsx +++ b/ui/packages/fields/src/widgets/GridField.i18nChrome-11131.no-provider.test.tsx @@ -25,7 +25,7 @@ import { describe, it, expect, afterEach } from 'vitest'; import * as React from 'react'; import { render, screen, cleanup } from '@testing-library/react'; -import { GridField } from './GridField'; +import { GridFieldWidget as GridField } from './grid-field/GridFieldWidget'; afterEach(() => cleanup()); diff --git a/ui/packages/fields/src/widgets/GridField.i18nChrome-11131.test.tsx b/ui/packages/fields/src/widgets/GridField.i18nChrome-11131.test.tsx index abebae6cf6c..4a5db40d0d8 100644 --- a/ui/packages/fields/src/widgets/GridField.i18nChrome-11131.test.tsx +++ b/ui/packages/fields/src/widgets/GridField.i18nChrome-11131.test.tsx @@ -27,7 +27,7 @@ import { describe, it, expect, afterEach } from 'vitest'; import * as React from 'react'; import { render, screen, cleanup } from '@testing-library/react'; import { I18nProvider } from '@object-ui/i18n'; -import { GridField } from './GridField'; +import { GridFieldWidget as GridField } from './grid-field/GridFieldWidget'; afterEach(() => cleanup()); diff --git a/ui/packages/fields/src/widgets/GridField.i18nChrome-11145.no-provider.test.tsx b/ui/packages/fields/src/widgets/GridField.i18nChrome-11145.no-provider.test.tsx index 033ab867ebe..bedbdf041d1 100644 --- a/ui/packages/fields/src/widgets/GridField.i18nChrome-11145.no-provider.test.tsx +++ b/ui/packages/fields/src/widgets/GridField.i18nChrome-11145.no-provider.test.tsx @@ -29,7 +29,7 @@ import { describe, it, expect } from 'vitest'; import * as React from 'react'; import { render, screen, fireEvent } from '@testing-library/react'; -import { GridField } from './GridField'; +import { GridFieldWidget as GridField } from './grid-field/GridFieldWidget'; const columns = [ { name: 'qty', label: 'Qty', type: 'number' as const }, diff --git a/ui/packages/fields/src/widgets/GridField.i18nChrome-11145.test.tsx b/ui/packages/fields/src/widgets/GridField.i18nChrome-11145.test.tsx index 0b5c0a7ea45..4d30ac500f3 100644 --- a/ui/packages/fields/src/widgets/GridField.i18nChrome-11145.test.tsx +++ b/ui/packages/fields/src/widgets/GridField.i18nChrome-11145.test.tsx @@ -33,7 +33,7 @@ import { describe, it, expect, afterEach } from 'vitest'; import * as React from 'react'; import { render, screen, cleanup, fireEvent, within, waitFor } from '@testing-library/react'; import { I18nProvider } from '@object-ui/i18n'; -import { GridField } from './GridField'; +import { GridFieldWidget as GridField } from './grid-field/GridFieldWidget'; afterEach(() => cleanup()); diff --git a/ui/packages/fields/src/widgets/GridField.impossibleDay-10301.test.tsx b/ui/packages/fields/src/widgets/GridField.impossibleDay-10301.test.tsx index 84b8142922e..eb8ab1adff0 100644 --- a/ui/packages/fields/src/widgets/GridField.impossibleDay-10301.test.tsx +++ b/ui/packages/fields/src/widgets/GridField.impossibleDay-10301.test.tsx @@ -39,7 +39,7 @@ import React from 'react'; import { afterEach, describe, expect, it } from 'vitest'; import { cleanup, render, screen } from '@testing-library/react'; import { formatDate, formatDateTime } from '@object-ui/core'; -import { GridField } from './GridField'; +import { GridFieldWidget as GridField } from './grid-field/GridFieldWidget'; afterEach(() => cleanup()); diff --git a/ui/packages/fields/src/widgets/GridField.keyWarning.test.tsx b/ui/packages/fields/src/widgets/GridField.keyWarning.test.tsx index 5c3cd7b149d..829398b63e4 100644 --- a/ui/packages/fields/src/widgets/GridField.keyWarning.test.tsx +++ b/ui/packages/fields/src/widgets/GridField.keyWarning.test.tsx @@ -31,7 +31,7 @@ import { describe, it, expect, vi } from 'vitest'; import { render } from '@testing-library/react'; import React from 'react'; import type { GridFieldMetadata } from '@object-ui/types'; -import { GridField } from './GridField'; +import { GridFieldWidget as GridField } from './grid-field/GridFieldWidget'; const columns: NonNullable = [ { name: 'product', label: 'Product', type: 'text' }, diff --git a/ui/packages/fields/src/widgets/GridField.lookupAutofill-28245.test.tsx b/ui/packages/fields/src/widgets/GridField.lookupAutofill-28245.test.tsx index 8e77a5d3abe..085d34a3c1a 100644 --- a/ui/packages/fields/src/widgets/GridField.lookupAutofill-28245.test.tsx +++ b/ui/packages/fields/src/widgets/GridField.lookupAutofill-28245.test.tsx @@ -25,7 +25,8 @@ import { describe, it, expect, vi, afterEach } from 'vitest'; import { render, screen, cleanup, waitFor, act, fireEvent } from '@testing-library/react'; import '@testing-library/jest-dom'; import { SchemaRendererContext } from '@object-ui/react'; -import { GridField, lookupAutofillPatch } from './GridField'; +import { GridFieldWidget as GridField } from './grid-field/GridFieldWidget'; +import { lookupAutofillPatch } from './GridField'; import { declaredLookupAutofillPatch, lookupAutofillByField } from './lookupAutofill'; afterEach(cleanup); diff --git a/ui/packages/fields/src/widgets/GridField.readonlyCells-12915.test.tsx b/ui/packages/fields/src/widgets/GridField.readonlyCells-12915.test.tsx index 46dbc2271f6..18f2648e9e8 100644 --- a/ui/packages/fields/src/widgets/GridField.readonlyCells-12915.test.tsx +++ b/ui/packages/fields/src/widgets/GridField.readonlyCells-12915.test.tsx @@ -27,7 +27,8 @@ import { describe, it, expect, afterEach } from 'vitest'; import { render, screen, cleanup, within } from '@testing-library/react'; import * as React from 'react'; import { LocalizationProvider } from '@object-ui/i18n'; -import { GridField, type GridColumn } from './GridField'; +import { GridFieldWidget as GridField } from './grid-field/GridFieldWidget'; +import { type GridColumn } from './GridField'; import { LookupField } from './LookupField'; afterEach(() => cleanup()); diff --git a/ui/packages/fields/src/widgets/GridField.requiredCell.i18n-11160.no-provider.test.tsx b/ui/packages/fields/src/widgets/GridField.requiredCell.i18n-11160.no-provider.test.tsx index 0b6e83df9ae..5568f668c45 100644 --- a/ui/packages/fields/src/widgets/GridField.requiredCell.i18n-11160.no-provider.test.tsx +++ b/ui/packages/fields/src/widgets/GridField.requiredCell.i18n-11160.no-provider.test.tsx @@ -25,7 +25,7 @@ import { describe, it, expect, vi } from 'vitest'; import * as React from 'react'; import { render, screen } from '@testing-library/react'; -import { GridField } from './GridField'; +import { GridFieldWidget as GridField } from './grid-field/GridFieldWidget'; /** Every `error` each wrapped cell control was handed, by kind. */ const seen = vi.hoisted(() => ({ lookup: [] as unknown[], file: [] as unknown[] })); diff --git a/ui/packages/fields/src/widgets/GridField.requiredCell.i18n-11160.test.tsx b/ui/packages/fields/src/widgets/GridField.requiredCell.i18n-11160.test.tsx index 0d7b78ae7e1..4c547783db0 100644 --- a/ui/packages/fields/src/widgets/GridField.requiredCell.i18n-11160.test.tsx +++ b/ui/packages/fields/src/widgets/GridField.requiredCell.i18n-11160.test.tsx @@ -29,7 +29,7 @@ import { describe, it, expect, afterEach, vi } from 'vitest'; import * as React from 'react'; import { render, screen, cleanup, waitFor } from '@testing-library/react'; import { I18nProvider } from '@object-ui/i18n'; -import { GridField } from './GridField'; +import { GridFieldWidget as GridField } from './grid-field/GridFieldWidget'; /** The `error` each wrapped cell control was last handed, by kind. */ const seen = vi.hoisted(() => ({ lookup: [] as unknown[], file: [] as unknown[] })); diff --git a/ui/packages/fields/src/widgets/GridField.retiredSnakeKeys-11610.test.tsx b/ui/packages/fields/src/widgets/GridField.retiredSnakeKeys-11610.test.tsx index f1454627682..78000ca888b 100644 --- a/ui/packages/fields/src/widgets/GridField.retiredSnakeKeys-11610.test.tsx +++ b/ui/packages/fields/src/widgets/GridField.retiredSnakeKeys-11610.test.tsx @@ -40,7 +40,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { fireEvent, render, screen } from '@testing-library/react'; import React from 'react'; import { GRID_FIELD_RETIRED_KEYS, type GridFieldMetadata, type GridFieldRetiredKey } from '@object-ui/types'; -import { GridField } from './GridField'; +import { GridFieldWidget as GridField } from './grid-field/GridFieldWidget'; const columns: NonNullable = [ { name: 'description', label: 'Description', type: 'text' }, diff --git a/ui/packages/fields/src/widgets/GridField.sortFieldCellEdit-12286.test.tsx b/ui/packages/fields/src/widgets/GridField.sortFieldCellEdit-12286.test.tsx index 4e715017f0c..48dd1298341 100644 --- a/ui/packages/fields/src/widgets/GridField.sortFieldCellEdit-12286.test.tsx +++ b/ui/packages/fields/src/widgets/GridField.sortFieldCellEdit-12286.test.tsx @@ -26,7 +26,7 @@ import { describe, expect, it, vi } from 'vitest'; import { fireEvent, render, screen } from '@testing-library/react'; import React from 'react'; import type { GridFieldMetadata } from '@object-ui/types'; -import { GridField } from './GridField'; +import { GridFieldWidget as GridField } from './grid-field/GridFieldWidget'; const field: GridFieldMetadata = { type: 'grid', diff --git a/ui/packages/fields/src/widgets/GridField.test.tsx b/ui/packages/fields/src/widgets/GridField.test.tsx index 4f7989b5c5f..f1bfbfc24d1 100644 --- a/ui/packages/fields/src/widgets/GridField.test.tsx +++ b/ui/packages/fields/src/widgets/GridField.test.tsx @@ -4,7 +4,8 @@ import React from 'react'; import { UploadProvider } from './UploadProvider'; import { Dialog, DialogContent, DialogTitle } from '@object-ui/components'; import { formatDate, formatDateTime } from '@object-ui/core'; -import { GridField, LineItemsField, sumColumn, lookupAutofillPatch, UNTOUCHED_NEW_ROW, isUntouchedNewRow, columnHelpByField } from './GridField'; +import { GridFieldWidget as GridField } from './grid-field/GridFieldWidget'; +import { GridField as GridFieldFace, LineItemsField, sumColumn, lookupAutofillPatch, UNTOUCHED_NEW_ROW, isUntouchedNewRow, columnHelpByField } from './GridField'; const columns = [ { name: 'description', label: 'Description', type: 'text' as const }, @@ -15,7 +16,7 @@ const field = { columns, totalField: 'amount' } as any; describe('GridField / LineItemsField — editable line items', () => { it('is exported under both names', () => { - expect(LineItemsField).toBe(GridField); + expect(LineItemsField).toBe(GridFieldFace); }); it('renders a column header per config and an empty hint', () => { @@ -1292,3 +1293,42 @@ describe('cell faces that open under the cell (objectstack#36023)', () => { }); }); }); + +/** + * objectstack#36102 — `@object-ui/fields` exports a lazy face for the grid + * (`./GridField.ts`); the body (`./grid-field/GridFieldWidget.tsx`) loads + * through one `import()`. Each case re-imports the face from a fresh module + * registry, so "before the body loaded" does not depend on case order. + */ +describe('GridField — the lazy face the package exports (objectstack#36102)', () => { + const lines = [{ description: 'Widget', amount: 5 }]; + + it('a mount before the body loads shows the placeholder, then the grid, and a later render keeps the focused cell', async () => { + vi.resetModules(); + const face = await import('./GridField'); + const view = render( {}} field={field} />); + expect(screen.getByTestId('grid-field-loading')).toBeTruthy(); + + const grid = await screen.findByTestId('line-items'); + expect(screen.queryByTestId('grid-field-loading')).toBeNull(); + const cell = grid.querySelector('input[aria-label="Description"]') as HTMLInputElement; + expect(cell.value).toBe('Widget'); + cell.focus(); + + // The body has loaded now. A render of the same mount must not swap the + // boundary for a direct render: that remounts the body and drops focus. + view.rerender( {}} field={field} />); + expect(cell.isConnected).toBe(true); + expect(document.activeElement).toBe(cell); + }); + + it('a mount after preloadGridField renders the grid in the same render, with no placeholder', async () => { + vi.resetModules(); + const face = await import('./GridField'); + await face.preloadGridField(); + render( {}} field={field} />); + expect(screen.queryByTestId('grid-field-loading')).toBeNull(); + const cell = screen.getByTestId('line-items').querySelector('input[aria-label="Description"]') as HTMLInputElement; + expect(cell.value).toBe('Widget'); + }); +}); diff --git a/ui/packages/fields/src/widgets/GridField.ts b/ui/packages/fields/src/widgets/GridField.ts new file mode 100644 index 00000000000..2e286b33ebd --- /dev/null +++ b/ui/packages/fields/src/widgets/GridField.ts @@ -0,0 +1,467 @@ +// A `.ts` file, JSX-free: the widget body that used to be `GridField.tsx` moved +// to `./grid-field/GridFieldWidget.tsx`, and every import of `./GridField.js` +// still lands here (objectstack#36102). +import React from 'react'; +import type { InlineGridColumn } from '@objectstack/spec/data'; +import { resolveFieldCurrency, currencyFractionDigits } from '../currency.js'; +import { declaredLookupAutofillPatch, type LookupAutofillPair } from './lookupAutofill.js'; +import { fieldHelpText } from '../fieldHelpText.js'; +// Type-only: erased at build, so it adds no edge to the bundle graph. The one +// RUNTIME edge to the widget body is the `import()` in `loadGridFieldWidget`. +import type { GridFieldWidgetProps } from './grid-field/GridFieldWidget.js'; + +/** + * GridField / LineItemsField — the public face of the line-item grid, and its + * pure half. + * + * ## Why the widget body is in another file (objectstack#36102) + * + * The grid's body (`./grid-field/GridFieldWidget.tsx`, the cells, the column + * chooser, the row drag, the in-cell panels' host) is the largest field widget + * in this package, and a record form with line items is the only page that + * draws it. It used to sit on the console's EAGER `ui-components` line anyway: + * the package entry imported it lazily for the `grid` field type AND exported + * it by name, and the package declares `"sideEffects": true`, so the named + * export was a static edge from the entry that no bundler may drop. This + * module is what the entry exports instead, so both names keep their meaning + * and their props: + * + * - `GridField` / `LineItemsField` here render the body through ONE loader, + * {@link loadGridFieldWidget}. A mount after the body has loaded renders it + * directly, in the same render, with no boundary in between; only a mount + * that finds it still loading shows {@link GridFieldLoading} until it + * arrives. Each mount decides once, so a row the user is editing is never + * remounted by the load finishing. + * - {@link preloadGridField} starts that load early. The record forms that + * draw line items (`@object-ui/plugin-form`) call it when they mount, and + * the two that derive a grid's columns from the child object's schema + * (`MasterDetailForm`, `RecordBodyTableEditor`) also wait for it together + * with that schema, so their grid never mounts on the placeholder. + * - The pure helpers below stay in this file, in the eager chunk, because the + * entry exports them by name and they import nothing heavy. + * + * ⛔ Never import `./grid-field/GridFieldWidget.js` statically from outside + * that directory (its tests excepted): a static edge from the eager graph + * undoes the split, and the console build's chunk-membership check + * (`PER_CHUNK_MEMBERSHIP_CARVE_OUTS`) is what reports it. + */ + +/** + * One grid column — `@objectstack/spec`'s inline grid column + * (`InlineGridColumn`, the element of `FieldSchema.inlineColumns`), BY + * REFERENCE (objectui#11070). The spec declares that shape as the strict + * mirror of this widget's column, so the widget's type IS the spec's: one + * declaration, the same one `GridFieldMetadata.columns` and + * `FormField.columns` (`@object-ui/types`) carry. This widget reads each + * column by exactly the spec's keys — every key below is one the spec + * declares, and there is no second spelling of any of them. + * + * How the widget reads the keys (the spec's own descriptions say what each + * MEANS; these are the renderer's notes): + * + * - `name` — the key a column reads and writes on each row object. There is + * deliberately no tolerant alias bridging the spelling objectui#3951 + * retired to this one: a single spelling, enforced at the producer — + * AGENTS.md #0.1 (the spec refuses the retired spelling by name). + * (Wording note: do not restate that rule as an alternation expression over + * the two key names. `column-identity.ratchet.test.ts` (objectui#3104) scans + * these files line by line and cannot tell prose from code, so spelling the + * shape out here registers as a new dual read and fails the gate.) + * - `type` — the cell control and its read/write adapter. `date` / + * `datetime` / `time` are three DISTINCT controls, not one + * (objectui#3569): `` hands back a bare `YYYY-MM-DD` on + * change, so collapsing `datetime` onto it silently DELETED the time + * component from the record. + * - `prefix` — a symbol shown in a `currency` cell IN PLACE OF the resolved + * currency's own symbol. When absent, the cell shows the symbol of the + * currency it resolves (objectui#10355); there is no default symbol. + * - `defaultHidden` — collapsed into the column chooser, not dropped + * (`deriveColumns` sets it beyond the default-visible budget). Required + * columns are never default-hidden. + * - `computed` + `expr` — a read-only column recomputed live from sibling + * cells by this file's own safe arithmetic evaluator (`+ - * / %`, + * parentheses, numeric literals, `record.qty` or bare `qty`), and written + * back into the row so it persists and any running total reflects it. + * - `scale` — decimal places for a computed `number` result. ⛔ Not read on + * a `currency` column (objectui#10783): the resolved currency's CLDR + * fraction digits decide both the stored and the shown width + * (`currencyWidth`), and the spec refuses `scale` on a column declaring + * `type: 'currency'`. A column that takes `currency` from its child field + * at render time is reported by `hydrateColumns` in + * `@object-ui/plugin-form` instead of being read in silence. + * - `autofill` — for a `lookup` column: picking a record copies its fields + * into sibling columns of the same name. On unless set `false`. + * - `readonlyWhen` / `requiredWhen` — CEL predicates evaluated per row + * against the row as `record` plus the header as `parent`. Client-side UX; + * a predicate that faults fails open. + */ +export type GridColumn = InlineGridColumn; + +type Row = Record; + +// ── Safe arithmetic evaluator for computed columns ────────────────────────── +// A tiny recursive-descent parser over `+ - * / %`, parentheses, numeric +// literals and field references (`record.qty` or bare `qty`). Deliberately NOT +// eval()/Function() — only arithmetic, no code execution. Returns a finite +// number, or null when the expression is unparseable or any referenced cell is +// blank/non-numeric (so a computed amount reads "—" until its inputs exist). +type Tok = { t: 'num' | 'id' | 'op' | 'lp' | 'rp'; v: string }; + +function tokenize(s: string): Tok[] | null { + const toks: Tok[] = []; + let i = 0; + while (i < s.length) { + const c = s[i]; + if (c === ' ' || c === '\t' || c === '\n') { i++; continue; } + if ((c >= '0' && c <= '9') || c === '.') { + let j = i + 1; + while (j < s.length && ((s[j] >= '0' && s[j] <= '9') || s[j] === '.')) j++; + toks.push({ t: 'num', v: s.slice(i, j) }); i = j; continue; + } + if (/[a-zA-Z_]/.test(c)) { + let j = i + 1; + while (j < s.length && /[a-zA-Z0-9_.]/.test(s[j])) j++; + toks.push({ t: 'id', v: s.slice(i, j) }); i = j; continue; + } + if (c === '+' || c === '-' || c === '*' || c === '/' || c === '%') { toks.push({ t: 'op', v: c }); i++; continue; } + if (c === '(') { toks.push({ t: 'lp', v: c }); i++; continue; } + if (c === ')') { toks.push({ t: 'rp', v: c }); i++; continue; } + return null; // unsupported character → bail (treat as non-computable) + } + return toks; +} + +/** Resolve an identifier (`record.quantity` / `quantity`) to a numeric cell. */ +function resolveRef(id: string, row: Row): number | null { + const field = id.startsWith('record.') ? id.slice('record.'.length) : id; + const raw = row?.[field]; + if (raw === null || raw === undefined || raw === '') return null; + const n = Number(raw); + return Number.isFinite(n) ? n : null; +} + +/** Evaluate an arithmetic `expr` against `row`. null when blank/unparseable. */ +export function evalArith(expr: string, row: Row): number | null { + const toks = tokenize(expr); + if (!toks || toks.length === 0) return null; + let pos = 0; + let bad = false; + const peek = () => toks[pos]; + const next = () => toks[pos++]; + + function factor(): number { + const tk = peek(); + if (!tk) { bad = true; return NaN; } + if (tk.t === 'op' && tk.v === '-') { next(); return -factor(); } + if (tk.t === 'op' && tk.v === '+') { next(); return factor(); } + if (tk.t === 'num') { next(); return Number(tk.v); } + if (tk.t === 'id') { next(); const v = resolveRef(tk.v, row); if (v === null) { bad = true; return NaN; } return v; } + if (tk.t === 'lp') { + next(); + const v = expression(); + const close = next(); + if (!close || close.t !== 'rp') bad = true; + return v; + } + bad = true; return NaN; + } + function term(): number { + let v = factor(); + while (peek() && peek().t === 'op' && (peek().v === '*' || peek().v === '/' || peek().v === '%')) { + const op = next().v; + const r = factor(); + v = op === '*' ? v * r : op === '/' ? v / r : v % r; + } + return v; + } + function expression(): number { + let v = term(); + while (peek() && peek().t === 'op' && (peek().v === '+' || peek().v === '-')) { + const op = next().v; + const r = term(); + v = op === '+' ? v + r : v - r; + } + return v; + } + const result = expression(); + if (bad || pos !== toks.length || !Number.isFinite(result)) return null; + return result; +} + +/** + * Recompute every {@link GridColumn.computed} cell in `row` from its sibling + * inputs, returning a new row. Called after each edit so computed columns and + * the running total stay live, and so the computed value persists in the batch. + */ +/** + * Build the row patch for a lookup-cell selection: set the FK column to the + * chosen record's id, and (unless the column opts out with `autofill: false`) + * copy any of the record's fields whose names match a sibling column — the + * catalog-typeahead behaviour (pick a product → its unit_price/description fill + * in). Skips the lookup column itself and computed columns. Pure + exported so + * it is unit-testable independent of the picker UI. + * + * `declared` carries the child field's `lookupAutofill` pairs, the row being + * edited and the record the cell held from an earlier pick in this grid. Each + * pair writes its target under the spec's overwrite rule + * (`declaredLookupAutofillPatch`), whatever the column's `autofill` says, and + * a declared target is taken out of the same-named copy, so one target never + * has two writers on one pick. + */ +export function lookupAutofillPatch( + columns: GridColumn[], + col: GridColumn, + record: any, + declared?: { pairs?: readonly LookupAutofillPair[]; row?: Row; previous?: Row | null }, +): Row { + const patch: Row = { [col.name]: record?.value ?? record?.id ?? record?._id }; + const declaredTargets = new Set((declared?.pairs ?? []).map((p) => p.target)); + if (col.autofill !== false && record && typeof record === 'object') { + for (const other of columns) { + if (other.name === col.name || other.computed || other.type === 'lookup') continue; + if (declaredTargets.has(other.name)) continue; + const v = record[other.name]; + if (v !== undefined && v !== null && v !== '') patch[other.name] = v; + } + } + return { ...patch, ...declaredLookupAutofillPatch(declared?.pairs, record, declared?.row, declared?.previous) }; +} + +/** + * The currency a `currency` column is denominated in (objectui#10355). + * + * Read through `resolveFieldCurrency` — the one precedence every currency face + * shares (field `currency` → `currencyConfig.defaultCurrency` → a legacy + * `defaultCurrency` → the tenant default) — ⛔ never a second copy of it. + * + * The field-level legs are handed nothing, deliberately: a grid column + * declares none of those keys — not `GridColumn`, which is the spec's strict + * `InlineGridColumnSchema` element by reference, and that schema refuses + * them — and the column derivation in `@object-ui/plugin-form` + * copies none of them from the child field. Reading them off the column would + * add a renderer read that no authored metadata can reach. So the precedence + * lands on the tenant default, and `undefined` when none is configured: the + * caller then invents no currency, exactly as `CurrencyCellRenderer` does. + */ +function columnCurrency(tenantCurrency: string | undefined): string | undefined { + return resolveFieldCurrency(undefined, tenantCurrency); +} + +/** + * The fraction width of a `currency` column (objectui#10355) — the ONE + * decision behind both its stored computed value and its display. + * + * 1. The resolved currency's CLDR fraction digits (0 for JPY, 2 for USD, 3 for + * KWD), from `currencyFractionDigits`, the helper every currency face + * already uses. It replaced the old default of a literal `2`, under which a + * yen amount was stored with cents it does not have and a dinar amount lost + * its third digit (KWD 3 × 1.2345 stored `3.7`): a currency's decimal places + * are the currency's (ruling 乙 on objectstack-ai/objectstack#19910). + * 2. Otherwise `undefined`: with no minor unit to round to, nothing is + * invented. + * + * ⛔ The column's own `scale` is not an input (objectui#10783). This read it + * first, so an authored `scale` beat the minor unit. `@objectstack/spec` 17.5.0 + * refuses that key on a column declaring `type: 'currency'`, with the remedy + * that the minor unit decides, so a spec-valid typed column never carries one. + * A column that declares no `type` and hydrates to `currency` still can; its + * `scale` is reported where the child field is known (`hydrateColumns` in + * `@object-ui/plugin-form`), not read here. + */ +export function currencyWidth(currency: string | undefined): number | undefined { + return currency ? currencyFractionDigits(currency) : undefined; +} + +/** + * The fraction width a computed cell's STORED value is rounded to. + * + * - `currency` — {@link currencyWidth}; with no resolved currency the value is + * stored as computed. The column's `scale` is not read (objectui#10783). + * - every other type — the column's declared `scale`, unrounded when absent + * (unchanged). + * + * No clamp to the engine's `toFixed` ceiling: the objectui#10071 one retired at + * the objectui#9808 SUNSET (objectui#11073), since `@objectstack/spec` 17.5.0 + * refuses a `scale` above 100 at the declaration. + */ +function storedFractionScale( + c: GridColumn, + tenantCurrency: string | undefined, + columnCurrencies?: ColumnCurrencies, +): number | undefined { + if (c.type !== 'currency') return c.scale; + return currencyWidth(currencyOfColumn(c, tenantCurrency, columnCurrencies)); +} + +/** + * The currencies a host resolved for some of its `currency` columns, by column + * name: a line amount that follows its header's currency through the + * `master_detail` (ADR-0144 D2 as amended) is in the header's code, which only + * the host holding the header record and the child schema can say. A name + * mapped to `undefined` is a column with no known currency (the header holds + * no code yet): it shows no symbol, never the tenant's. + */ +export type ColumnCurrencies = Readonly>; + +/** `c`'s currency: the host's answer for it when it gave one, else {@link columnCurrency}. */ +export function currencyOfColumn( + c: GridColumn, + tenantCurrency: string | undefined, + columnCurrencies: ColumnCurrencies | undefined, +): string | undefined { + return columnCurrencies && Object.prototype.hasOwnProperty.call(columnCurrencies, c.name) + ? columnCurrencies[c.name] + : columnCurrency(tenantCurrency); +} + +/** + * @param tenantCurrency the tenant's default currency (`useLocalization()`), + * the resolver's last step for a `currency` column — see + * {@link storedFractionScale}. + */ +export function computeRow(columns: GridColumn[], row: Row, tenantCurrency?: string, columnCurrencies?: ColumnCurrencies): Row { + const computedCols = columns.filter((c) => c.computed && c.expr); + if (computedCols.length === 0) return row; + const next = { ...row }; + for (const c of computedCols) { + const v = evalArith(c.expr!, next); + if (v === null) { next[c.name] = null; continue; } + const scale = storedFractionScale(c, tenantCurrency, columnCurrencies); + next[c.name] = scale != null ? Number(v.toFixed(scale)) : v; + } + return next; +} + +/** Sum a numeric column across rows (ignoring blanks/NaN). */ +export function sumColumn(rows: Row[], field: string): number { + if (!Array.isArray(rows)) return 0; + return rows.reduce((acc, r) => { + const v = Number(r?.[field]); + return acc + (Number.isFinite(v) ? v : 0); + }, 0); +} + +/** + * The help text of a grid's columns, by column name (objectstack#35804). + * Each value is what the record form draws under the same field. + */ +export type ColumnHelp = Readonly>; + +/** + * The {@link ColumnHelp} of a child object's fields: each field's help read + * through {@link fieldHelpText}, the ONE read the record form's help line uses + * (objectui#12213), so a grid header and the form show the same text. Hand it + * the child object's definition as the server serves it, the one the record + * form reads: another package's `objectExtensions.fieldPatches` are already + * applied there, and the help is in the reader's language. A field with no + * help is left out. + */ +export function columnHelpByField(fields: Readonly> | null | undefined): Record { + const out: Record = {}; + if (!fields || typeof fields !== 'object') return out; + for (const [name, def] of Object.entries(fields)) { + if (!def || typeof def !== 'object') continue; + const help = fieldHelpText(def as Parameters[0]); + if (help) out[name] = help; + } + return out; +} + +/** + * objectstack#35816 — marks a line that `Add` started on the host's + * `newRowValues` and that nobody has edited since. Such a line holds only its + * defaults, and a host may skip it at save like a blank one; any edit to the + * line takes the mark off, so a value the user typed counts as input even when + * it equals the default. A symbol key: `Object.keys`/`Object.entries` and + * `JSON.stringify` (so every write payload) skip it, while the spread copies a + * host or a renumbering makes keep it. Set only when the host passes + * `newRowValues`, so a host that passes none sees rows exactly as before. + */ +export const UNTOUCHED_NEW_ROW: unique symbol = Symbol.for('@object-ui/fields.untouchedNewRow'); + +/** True for a line `Add` started on its defaults and nobody has edited ({@link UNTOUCHED_NEW_ROW}). */ +export function isUntouchedNewRow(row: unknown): boolean { + return row != null && typeof row === 'object' && (row as Record)[UNTOUCHED_NEW_ROW] === true; +} + +type GridFieldWidgetModule = typeof import('./grid-field/GridFieldWidget.js'); + +/** The loaded body, once {@link loadGridFieldWidget} has resolved. */ +let gridFieldWidgetModule: GridFieldWidgetModule | undefined; +let gridFieldWidgetLoad: Promise | undefined; + +/** + * The ONE loader of the grid's body: the lazy face below, {@link + * preloadGridField} and the `grid` form-field loader in `../index.tsx` all go + * through it, so the body is requested once and a mount after any of them has + * resolved renders without a boundary. A failed load is forgotten, so the next + * caller asks again rather than inheriting the failure. + */ +export function loadGridFieldWidget(): Promise { + gridFieldWidgetLoad ??= import('./grid-field/GridFieldWidget.js').then( + (loaded) => { + gridFieldWidgetModule = loaded; + return loaded; + }, + (error: unknown) => { + gridFieldWidgetLoad = undefined; + throw error; + }, + ); + return gridFieldWidgetLoad; +} + +/** + * Start loading the line-item grid's body ahead of its first render. Call it + * where a form that may draw line items mounts; idempotent. The promise + * settles once the body has loaded, so a caller that must render in the same + * tick (a test at module scope) can await it. ⛔ It never rejects, so a caller + * may drop it: a failed preload is reported by the grid's own render, which + * asks again and hands a second failure to the nearest error boundary, where + * it can be seen. + */ +export function preloadGridField(): Promise { + return loadGridFieldWidget().then( + () => undefined, + () => undefined, + ); +} + +const LazyGridFieldWidget = React.lazy(() => + loadGridFieldWidget().then((loaded) => ({ default: loaded.GridFieldWidget })), +); + +/** + * What a grid mounted before its body arrived shows meanwhile: a box of the + * grid's header height, marked busy, so the form does not jump when the table + * replaces it. + */ +function GridFieldLoading(): React.ReactElement { + return React.createElement('div', { + className: 'min-h-10 w-full rounded-md border border-dashed', + 'aria-busy': 'true', + 'data-testid': 'grid-field-loading', + }); +} + +/** + * The `grid` field widget and the master-detail subform's child grid. Same + * props as the body, see `GridFieldWidgetProps`. + */ +export function GridField(props: GridFieldWidgetProps): React.ReactElement { + // Decided once per mount: switching from the boundary to the direct render + // when the load finishes would remount the body and drop the focused cell. + const [loadedAtMount] = React.useState(() => gridFieldWidgetModule); + if (loadedAtMount) { + const { GridFieldWidget } = loadedAtMount; + return React.createElement(GridFieldWidget, props); + } + return React.createElement( + React.Suspense, + { fallback: React.createElement(GridFieldLoading) }, + React.createElement(LazyGridFieldWidget, props), + ); +} + +/** Semantic alias — the master-detail subform's child grid. */ +export const LineItemsField = GridField; diff --git a/ui/packages/fields/src/widgets/GridField.tsx b/ui/packages/fields/src/widgets/grid-field/GridFieldWidget.tsx similarity index 81% rename from ui/packages/fields/src/widgets/GridField.tsx rename to ui/packages/fields/src/widgets/grid-field/GridFieldWidget.tsx index a51a0f45ab1..e23f10e5198 100644 --- a/ui/packages/fields/src/widgets/GridField.tsx +++ b/ui/packages/fields/src/widgets/grid-field/GridFieldWidget.tsx @@ -1,5 +1,5 @@ import React, { useCallback, useRef } from 'react'; -import { FieldWidgetComponentProps } from './types.js'; +import { FieldWidgetComponentProps } from '../types.js'; import { cn, Button, @@ -17,24 +17,49 @@ import { import { Plus, Trash2, SlidersHorizontal, Maximize2, Copy, GripVertical, Info } from 'lucide-react'; import { formatDate, formatDateTime, resolveFieldRuleState, toDisplayDate } from '@object-ui/core'; import { useDisplayLocale, useLocalization, formatDisplayNumber } from '@object-ui/i18n'; -import { resolveFieldCurrency, currencyFractionDigits, currencySymbol } from '../currency.js'; -import { LookupField } from './LookupField.js'; -import { declaredLookupAutofillPatch, type LookupAutofillByField, type LookupAutofillPair } from './lookupAutofill.js'; -import { FileCell } from './FileField.js'; -import { toDateInputValue, toDateTimeInputValue, fromDateTimeInputValue, isImpossibleStoredDay } from './nativeDateValue.js'; -import { useFieldTranslation } from './useFieldTranslation.js'; -import { toDomProps } from './toDomProps.js'; -import { PHONE_TOUCH_HEIGHT, PHONE_TOUCH_SQUARE } from './touchTarget.js'; -import { toHostGroupProps } from './toHostGroupProps.js'; -import { fieldHelpText } from '../fieldHelpText.js'; -import { GRID_CELL_CONTROL_CLASS, GridDateCell, GridSelectCell, GrowingCellInput } from './gridCellPanels.js'; -import { isImeKey } from './imeKey.js'; -import type { InlineGridColumn } from '@objectstack/spec/data'; +import { currencySymbol } from '../../currency.js'; +import { LookupField } from '../LookupField.js'; +import type { LookupAutofillByField } from '../lookupAutofill.js'; +import { FileCell } from '../FileField.js'; +import { toDateInputValue, toDateTimeInputValue, fromDateTimeInputValue, isImpossibleStoredDay } from '../nativeDateValue.js'; +import { useFieldTranslation } from '../useFieldTranslation.js'; +import { toDomProps } from '../toDomProps.js'; +import { PHONE_TOUCH_HEIGHT, PHONE_TOUCH_SQUARE } from '../touchTarget.js'; +import { toHostGroupProps } from '../toHostGroupProps.js'; +import { GRID_CELL_CONTROL_CLASS, GridDateCell, GridSelectCell, GrowingCellInput } from '../gridCellPanels.js'; +import { isImeKey } from '../imeKey.js'; import { GRID_FIELD_RETIRED_KEYS, type GridFieldMetadata, type GridFieldRetiredKey } from '@object-ui/types'; +// The grid's pure half: the column type, the computed-cell evaluator, the +// lookup-pick patch and the row marks. They live beside the public face in +// `../GridField.ts`, in the eager chunk, because `@object-ui/fields` exports +// them by name and they import nothing heavy (objectstack#36102). +import { + computeRow, + currencyOfColumn, + currencyWidth, + isUntouchedNewRow, + lookupAutofillPatch, + sumColumn, + UNTOUCHED_NEW_ROW, + type ColumnCurrencies, + type ColumnHelp, + type GridColumn, +} from '../GridField.js'; /** * GridField / LineItemsField — editable child-grid ("line items") widget. * + * ## Where this module sits (objectstack#36102) + * + * This is the widget BODY, and it is reached only through `import()`: the + * `GridField` / `LineItemsField` that `@object-ui/fields` exports by name are + * the small lazy face in `../GridField.ts`, and the `grid` form-field loader + * imports this file through that face's one loader. ⛔ Do not import it + * statically from anything outside this directory and its tests: one static + * importer in the eager graph puts these bytes back on every console page + * load (`fields-grid` in `apps/console/vite.config.ts`, held to the module by + * `PER_CHUNK_MEMBERSHIP_CARVE_OUTS` in `scripts/check-eager-closure-budget.mjs`). + * * ## Where the host's label and help text land, and why (objectui#4857) * * This widget forwarded nothing a host handed it, so the field's visible label @@ -89,56 +114,6 @@ import { GRID_FIELD_RETIRED_KEYS, type GridFieldMetadata, type GridFieldRetiredK * spelling is refused by name instead of drawn (`RetiredGridFieldKeys`). */ -/** - * One grid column — `@objectstack/spec`'s inline grid column - * (`InlineGridColumn`, the element of `FieldSchema.inlineColumns`), BY - * REFERENCE (objectui#11070). The spec declares that shape as the strict - * mirror of this widget's column, so the widget's type IS the spec's: one - * declaration, the same one `GridFieldMetadata.columns` and - * `FormField.columns` (`@object-ui/types`) carry. This widget reads each - * column by exactly the spec's keys — every key below is one the spec - * declares, and there is no second spelling of any of them. - * - * How the widget reads the keys (the spec's own descriptions say what each - * MEANS; these are the renderer's notes): - * - * - `name` — the key a column reads and writes on each row object. There is - * deliberately no tolerant alias bridging the spelling objectui#3951 - * retired to this one: a single spelling, enforced at the producer — - * AGENTS.md #0.1 (the spec refuses the retired spelling by name). - * (Wording note: do not restate that rule as an alternation expression over - * the two key names. `column-identity.ratchet.test.ts` (objectui#3104) scans - * these files line by line and cannot tell prose from code, so spelling the - * shape out here registers as a new dual read and fails the gate.) - * - `type` — the cell control and its read/write adapter. `date` / - * `datetime` / `time` are three DISTINCT controls, not one - * (objectui#3569): `` hands back a bare `YYYY-MM-DD` on - * change, so collapsing `datetime` onto it silently DELETED the time - * component from the record. - * - `prefix` — a symbol shown in a `currency` cell IN PLACE OF the resolved - * currency's own symbol. When absent, the cell shows the symbol of the - * currency it resolves (objectui#10355); there is no default symbol. - * - `defaultHidden` — collapsed into the column chooser, not dropped - * (`deriveColumns` sets it beyond the default-visible budget). Required - * columns are never default-hidden. - * - `computed` + `expr` — a read-only column recomputed live from sibling - * cells by this file's own safe arithmetic evaluator (`+ - * / %`, - * parentheses, numeric literals, `record.qty` or bare `qty`), and written - * back into the row so it persists and any running total reflects it. - * - `scale` — decimal places for a computed `number` result. ⛔ Not read on - * a `currency` column (objectui#10783): the resolved currency's CLDR - * fraction digits decide both the stored and the shown width - * (`currencyWidth`), and the spec refuses `scale` on a column declaring - * `type: 'currency'`. A column that takes `currency` from its child field - * at render time is reported by `hydrateColumns` in - * `@object-ui/plugin-form` instead of being read in silence. - * - `autofill` — for a `lookup` column: picking a record copies its fields - * into sibling columns of the same name. On unless set `false`. - * - `readonlyWhen` / `requiredWhen` — CEL predicates evaluated per row - * against the row as `record` plus the header as `parent`. Client-side UX; - * a predicate that faults fails open. - */ -export type GridColumn = InlineGridColumn; type Row = Record; @@ -173,240 +148,6 @@ function widthStyle(c: GridColumn): React.CSSProperties { const w = MIN_WIDTH_BY_TYPE[c.type ?? 'text'] ?? 132; return { width: w, minWidth: w }; } - -// ── Safe arithmetic evaluator for computed columns ────────────────────────── -// A tiny recursive-descent parser over `+ - * / %`, parentheses, numeric -// literals and field references (`record.qty` or bare `qty`). Deliberately NOT -// eval()/Function() — only arithmetic, no code execution. Returns a finite -// number, or null when the expression is unparseable or any referenced cell is -// blank/non-numeric (so a computed amount reads "—" until its inputs exist). -type Tok = { t: 'num' | 'id' | 'op' | 'lp' | 'rp'; v: string }; - -function tokenize(s: string): Tok[] | null { - const toks: Tok[] = []; - let i = 0; - while (i < s.length) { - const c = s[i]; - if (c === ' ' || c === '\t' || c === '\n') { i++; continue; } - if ((c >= '0' && c <= '9') || c === '.') { - let j = i + 1; - while (j < s.length && ((s[j] >= '0' && s[j] <= '9') || s[j] === '.')) j++; - toks.push({ t: 'num', v: s.slice(i, j) }); i = j; continue; - } - if (/[a-zA-Z_]/.test(c)) { - let j = i + 1; - while (j < s.length && /[a-zA-Z0-9_.]/.test(s[j])) j++; - toks.push({ t: 'id', v: s.slice(i, j) }); i = j; continue; - } - if (c === '+' || c === '-' || c === '*' || c === '/' || c === '%') { toks.push({ t: 'op', v: c }); i++; continue; } - if (c === '(') { toks.push({ t: 'lp', v: c }); i++; continue; } - if (c === ')') { toks.push({ t: 'rp', v: c }); i++; continue; } - return null; // unsupported character → bail (treat as non-computable) - } - return toks; -} - -/** Resolve an identifier (`record.quantity` / `quantity`) to a numeric cell. */ -function resolveRef(id: string, row: Row): number | null { - const field = id.startsWith('record.') ? id.slice('record.'.length) : id; - const raw = row?.[field]; - if (raw === null || raw === undefined || raw === '') return null; - const n = Number(raw); - return Number.isFinite(n) ? n : null; -} - -/** Evaluate an arithmetic `expr` against `row`. null when blank/unparseable. */ -export function evalArith(expr: string, row: Row): number | null { - const toks = tokenize(expr); - if (!toks || toks.length === 0) return null; - let pos = 0; - let bad = false; - const peek = () => toks[pos]; - const next = () => toks[pos++]; - - function factor(): number { - const tk = peek(); - if (!tk) { bad = true; return NaN; } - if (tk.t === 'op' && tk.v === '-') { next(); return -factor(); } - if (tk.t === 'op' && tk.v === '+') { next(); return factor(); } - if (tk.t === 'num') { next(); return Number(tk.v); } - if (tk.t === 'id') { next(); const v = resolveRef(tk.v, row); if (v === null) { bad = true; return NaN; } return v; } - if (tk.t === 'lp') { - next(); - const v = expression(); - const close = next(); - if (!close || close.t !== 'rp') bad = true; - return v; - } - bad = true; return NaN; - } - function term(): number { - let v = factor(); - while (peek() && peek().t === 'op' && (peek().v === '*' || peek().v === '/' || peek().v === '%')) { - const op = next().v; - const r = factor(); - v = op === '*' ? v * r : op === '/' ? v / r : v % r; - } - return v; - } - function expression(): number { - let v = term(); - while (peek() && peek().t === 'op' && (peek().v === '+' || peek().v === '-')) { - const op = next().v; - const r = term(); - v = op === '+' ? v + r : v - r; - } - return v; - } - const result = expression(); - if (bad || pos !== toks.length || !Number.isFinite(result)) return null; - return result; -} - -/** - * Recompute every {@link GridColumn.computed} cell in `row` from its sibling - * inputs, returning a new row. Called after each edit so computed columns and - * the running total stay live, and so the computed value persists in the batch. - */ -/** - * Build the row patch for a lookup-cell selection: set the FK column to the - * chosen record's id, and (unless the column opts out with `autofill: false`) - * copy any of the record's fields whose names match a sibling column — the - * catalog-typeahead behaviour (pick a product → its unit_price/description fill - * in). Skips the lookup column itself and computed columns. Pure + exported so - * it is unit-testable independent of the picker UI. - * - * `declared` carries the child field's `lookupAutofill` pairs, the row being - * edited and the record the cell held from an earlier pick in this grid. Each - * pair writes its target under the spec's overwrite rule - * (`declaredLookupAutofillPatch`), whatever the column's `autofill` says, and - * a declared target is taken out of the same-named copy, so one target never - * has two writers on one pick. - */ -export function lookupAutofillPatch( - columns: GridColumn[], - col: GridColumn, - record: any, - declared?: { pairs?: readonly LookupAutofillPair[]; row?: Row; previous?: Row | null }, -): Row { - const patch: Row = { [col.name]: record?.value ?? record?.id ?? record?._id }; - const declaredTargets = new Set((declared?.pairs ?? []).map((p) => p.target)); - if (col.autofill !== false && record && typeof record === 'object') { - for (const other of columns) { - if (other.name === col.name || other.computed || other.type === 'lookup') continue; - if (declaredTargets.has(other.name)) continue; - const v = record[other.name]; - if (v !== undefined && v !== null && v !== '') patch[other.name] = v; - } - } - return { ...patch, ...declaredLookupAutofillPatch(declared?.pairs, record, declared?.row, declared?.previous) }; -} - -/** - * The currency a `currency` column is denominated in (objectui#10355). - * - * Read through `resolveFieldCurrency` — the one precedence every currency face - * shares (field `currency` → `currencyConfig.defaultCurrency` → a legacy - * `defaultCurrency` → the tenant default) — ⛔ never a second copy of it. - * - * The field-level legs are handed nothing, deliberately: a grid column - * declares none of those keys — not `GridColumn`, which is the spec's strict - * `InlineGridColumnSchema` element by reference, and that schema refuses - * them — and the column derivation in `@object-ui/plugin-form` - * copies none of them from the child field. Reading them off the column would - * add a renderer read that no authored metadata can reach. So the precedence - * lands on the tenant default, and `undefined` when none is configured: the - * caller then invents no currency, exactly as `CurrencyCellRenderer` does. - */ -function columnCurrency(tenantCurrency: string | undefined): string | undefined { - return resolveFieldCurrency(undefined, tenantCurrency); -} - -/** - * The fraction width of a `currency` column (objectui#10355) — the ONE - * decision behind both its stored computed value and its display. - * - * 1. The resolved currency's CLDR fraction digits (0 for JPY, 2 for USD, 3 for - * KWD), from `currencyFractionDigits`, the helper every currency face - * already uses. It replaced the old default of a literal `2`, under which a - * yen amount was stored with cents it does not have and a dinar amount lost - * its third digit (KWD 3 × 1.2345 stored `3.7`): a currency's decimal places - * are the currency's (ruling 乙 on objectstack-ai/objectstack#19910). - * 2. Otherwise `undefined`: with no minor unit to round to, nothing is - * invented. - * - * ⛔ The column's own `scale` is not an input (objectui#10783). This read it - * first, so an authored `scale` beat the minor unit. `@objectstack/spec` 17.5.0 - * refuses that key on a column declaring `type: 'currency'`, with the remedy - * that the minor unit decides, so a spec-valid typed column never carries one. - * A column that declares no `type` and hydrates to `currency` still can; its - * `scale` is reported where the child field is known (`hydrateColumns` in - * `@object-ui/plugin-form`), not read here. - */ -function currencyWidth(currency: string | undefined): number | undefined { - return currency ? currencyFractionDigits(currency) : undefined; -} - -/** - * The fraction width a computed cell's STORED value is rounded to. - * - * - `currency` — {@link currencyWidth}; with no resolved currency the value is - * stored as computed. The column's `scale` is not read (objectui#10783). - * - every other type — the column's declared `scale`, unrounded when absent - * (unchanged). - * - * No clamp to the engine's `toFixed` ceiling: the objectui#10071 one retired at - * the objectui#9808 SUNSET (objectui#11073), since `@objectstack/spec` 17.5.0 - * refuses a `scale` above 100 at the declaration. - */ -function storedFractionScale( - c: GridColumn, - tenantCurrency: string | undefined, - columnCurrencies?: ColumnCurrencies, -): number | undefined { - if (c.type !== 'currency') return c.scale; - return currencyWidth(currencyOfColumn(c, tenantCurrency, columnCurrencies)); -} - -/** - * The currencies a host resolved for some of its `currency` columns, by column - * name: a line amount that follows its header's currency through the - * `master_detail` (ADR-0144 D2 as amended) is in the header's code, which only - * the host holding the header record and the child schema can say. A name - * mapped to `undefined` is a column with no known currency (the header holds - * no code yet): it shows no symbol, never the tenant's. - */ -export type ColumnCurrencies = Readonly>; - -/** `c`'s currency: the host's answer for it when it gave one, else {@link columnCurrency}. */ -function currencyOfColumn( - c: GridColumn, - tenantCurrency: string | undefined, - columnCurrencies: ColumnCurrencies | undefined, -): string | undefined { - return columnCurrencies && Object.prototype.hasOwnProperty.call(columnCurrencies, c.name) - ? columnCurrencies[c.name] - : columnCurrency(tenantCurrency); -} - -/** - * @param tenantCurrency the tenant's default currency (`useLocalization()`), - * the resolver's last step for a `currency` column — see - * {@link storedFractionScale}. - */ -export function computeRow(columns: GridColumn[], row: Row, tenantCurrency?: string, columnCurrencies?: ColumnCurrencies): Row { - const computedCols = columns.filter((c) => c.computed && c.expr); - if (computedCols.length === 0) return row; - const next = { ...row }; - for (const c of computedCols) { - const v = evalArith(c.expr!, next); - if (v === null) { next[c.name] = null; continue; } - const scale = storedFractionScale(c, tenantCurrency, columnCurrencies); - next[c.name] = scale != null ? Number(v.toFixed(scale)) : v; - } - return next; -} - /** True for the three temporal column types, which all need a formatter on the * read-only surfaces rather than the raw stored string (objectui#3569). */ const isTemporal = (t?: string) => t === 'date' || t === 'datetime' || t === 'time'; @@ -649,17 +390,7 @@ function coerce(type: string | undefined, raw: string): any { if (type === 'datetime') return fromDateTimeInputValue(raw); return raw; } - -/** Sum a numeric column across rows (ignoring blanks/NaN). */ -export function sumColumn(rows: Row[], field: string): number { - if (!Array.isArray(rows)) return 0; - return rows.reduce((acc, r) => { - const v = Number(r?.[field]); - return acc + (Number.isFinite(v) ? v : 0); - }, 0); -} - -type GridFieldProps = FieldWidgetComponentProps & { +export type GridFieldWidgetProps = FieldWidgetComponentProps & { /** When provided, each row shows an "expand" button that opens the row in a * full form (the host — e.g. MasterDetailForm — renders the drawer/modal and * writes the edited values back). Lets a "fat" child be edited in a real form @@ -712,32 +443,6 @@ type GridFieldProps = FieldWidgetComponentProps & { columnHelp?: ColumnHelp; }; -/** - * The help text of a grid's columns, by column name (objectstack#35804). - * Each value is what the record form draws under the same field. - */ -export type ColumnHelp = Readonly>; - -/** - * The {@link ColumnHelp} of a child object's fields: each field's help read - * through {@link fieldHelpText}, the ONE read the record form's help line uses - * (objectui#12213), so a grid header and the form show the same text. Hand it - * the child object's definition as the server serves it, the one the record - * form reads: another package's `objectExtensions.fieldPatches` are already - * applied there, and the help is in the reader's language. A field with no - * help is left out. - */ -export function columnHelpByField(fields: Readonly> | null | undefined): Record { - const out: Record = {}; - if (!fields || typeof fields !== 'object') return out; - for (const [name, def] of Object.entries(fields)) { - if (!def || typeof def !== 'object') continue; - const help = fieldHelpText(def as Parameters[0]); - if (help) out[name] = help; - } - return out; -} - /** * The info button beside a column's header label (objectstack#35804): the * column's help on hover and on keyboard focus, and the button's accessible @@ -828,23 +533,6 @@ function RetiredGridFieldKeys({ message, keys }: { message: string; keys: readon ); } -/** - * objectstack#35816 — marks a line that `Add` started on the host's - * `newRowValues` and that nobody has edited since. Such a line holds only its - * defaults, and a host may skip it at save like a blank one; any edit to the - * line takes the mark off, so a value the user typed counts as input even when - * it equals the default. A symbol key: `Object.keys`/`Object.entries` and - * `JSON.stringify` (so every write payload) skip it, while the spread copies a - * host or a renumbering makes keep it. Set only when the host passes - * `newRowValues`, so a host that passes none sees rows exactly as before. - */ -export const UNTOUCHED_NEW_ROW: unique symbol = Symbol.for('@object-ui/fields.untouchedNewRow'); - -/** True for a line `Add` started on its defaults and nobody has edited ({@link UNTOUCHED_NEW_ROW}). */ -export function isUntouchedNewRow(row: unknown): boolean { - return row != null && typeof row === 'object' && (row as Record)[UNTOUCHED_NEW_ROW] === true; -} - /** The row without its {@link UNTOUCHED_NEW_ROW} mark: an edit makes it input. */ function touched(row: Row): Row { if (!isUntouchedNewRow(row)) return row; @@ -862,7 +550,7 @@ function rowHasId(row: Row): boolean { * snake_case keys is refused by name ({@link RetiredGridFieldKeys}); any other * field draws the grid. */ -export function GridField(props: GridFieldProps) { +export function GridFieldWidget(props: GridFieldWidgetProps) { const retired = retiredGridFieldKeysOf(props.field); if (retired.length > 0) { const message = retiredGridFieldKeysMessage((props.field as { name?: unknown } | undefined)?.name, retired); @@ -888,7 +576,7 @@ function GridFieldBody({ newRowRequiredShown, columnHelp, ...props -}: GridFieldProps) { +}: GridFieldWidgetProps) { // The field-level keys, read as `GridFieldMetadata` declares them and as // nothing else, so a read of a key the type does not declare is a compile // error here rather than a second, unpublished contract (objectui#11070 @@ -1906,6 +1594,3 @@ function GridFieldBody({ ); } - -/** Semantic alias — the master-detail subform's child grid. */ -export const LineItemsField = GridField; diff --git a/ui/packages/fields/src/widgets/imeComposition-35996.test.tsx b/ui/packages/fields/src/widgets/imeComposition-35996.test.tsx index f4d61fb6220..0b9e9b6ccf0 100644 --- a/ui/packages/fields/src/widgets/imeComposition-35996.test.tsx +++ b/ui/packages/fields/src/widgets/imeComposition-35996.test.tsx @@ -33,7 +33,7 @@ import '@testing-library/jest-dom'; import { isImeKey as componentsIsImeKey } from '@object-ui/components'; import { isImeKey } from './imeKey'; -import { GridField } from './GridField'; +import { GridFieldWidget as GridField } from './grid-field/GridFieldWidget'; import { DatePickerField } from './date-picker/DatePickerField'; import { RecordPickerDialog } from './RecordPickerDialog'; import { getCellRenderer } from '../index'; diff --git a/ui/packages/plugin-form/src/LineItemsPanel.tsx b/ui/packages/plugin-form/src/LineItemsPanel.tsx index cd0e3330d84..e7f78d96360 100644 --- a/ui/packages/plugin-form/src/LineItemsPanel.tsx +++ b/ui/packages/plugin-form/src/LineItemsPanel.tsx @@ -26,7 +26,7 @@ import { CardTitle, cn, } from '@object-ui/components'; -import { LineItemsField, lookupAutofillByField, columnHelpByField, useBooleanValueLabel, type GridColumn } from '@object-ui/fields'; +import { LineItemsField, preloadGridField, lookupAutofillByField, columnHelpByField, useBooleanValueLabel, type GridColumn } from '@object-ui/fields'; import type { GridFieldMetadata } from '@object-ui/types'; import { createSafeTranslation, useLocalization } from '@object-ui/i18n'; import { useSchemaContext, useRecordContext, useFilterScope, useResolvedFilter, useDataInvalidation, usePrintPage, NonGridRowCeilingNote } from '@object-ui/react'; @@ -212,6 +212,9 @@ function describeRefusedRowLimit(authored: unknown, childObject: unknown): strin } export const LineItemsPanel: React.FC<{ schema: LineItemsPanelSchema }> = ({ schema }) => { + // The line grid's body loads on first use (objectstack#36102). Start it now, + // while the child schema is fetched, so the grid is there before its columns. + preloadGridField(); const ctx = useSchemaContext() as any; const { t } = useLineItemsTranslation(); // The session's word for a boolean value, which draws a hydrated `boolean` / diff --git a/ui/packages/plugin-form/src/MasterDetailForm.tsx b/ui/packages/plugin-form/src/MasterDetailForm.tsx index 798db9de4f4..84579653bf1 100644 --- a/ui/packages/plugin-form/src/MasterDetailForm.tsx +++ b/ui/packages/plugin-form/src/MasterDetailForm.tsx @@ -34,7 +34,7 @@ import React, { startTransition, useCallback, useContext, useEffect, useMemo, us import { createPortal } from 'react-dom'; import type { BatchTransactionOperation, DataSource, GridFieldMetadata, I18nLabel } from '@object-ui/types'; import { resolveAffordance, runBatchTransaction } from '@object-ui/core'; -import { isUntouchedNewRow, LineItemsField, lookupAutofillByField, columnHelpByField, UNTOUCHED_NEW_ROW, useBooleanValueLabel, type BooleanValueLabel, type ColumnHelp, type GridColumn, type LookupAutofillByField } from '@object-ui/fields'; +import { isUntouchedNewRow, LineItemsField, preloadGridField, lookupAutofillByField, columnHelpByField, UNTOUCHED_NEW_ROW, useBooleanValueLabel, type BooleanValueLabel, type ColumnHelp, type GridColumn, type LookupAutofillByField } from '@object-ui/fields'; import { Button, Card, CardContent, CardHeader, CardTitle, cn, toast } from '@object-ui/components'; import { formatDisplayNumber, @@ -965,6 +965,34 @@ const FormSlotPlacement: React.FC<{ ); }; +/** + * Set once this module's own `preloadGridField()` has settled, so a form that + * mounts after that renders its grids at its first paint. + */ +let gridBodySettled = false; + +/** + * Whether the line grid's body is here (objectstack#36102). The grid is drawn + * only once it is, so a collection stays on "Loading columns…" until then and + * the grid never mounts on its loading placeholder, however its columns were + * reached: derived from the child schema, authored in full, or authored + * untyped and drawn while the derivation is still in flight. A failed load + * settles too: the grid then reports it, through the nearest error boundary. + */ +function useGridBodySettled(): boolean { + const [settled, setSettled] = useState(gridBodySettled); + useEffect(() => { + if (settled) return; + let live = true; + void preloadGridField().then(() => { + gridBodySettled = true; + if (live) setSettled(true); + }); + return () => { live = false; }; + }, [settled]); + return settled; +} + /** * The line-item grids + document totals, isolated from the header form. * @@ -1000,6 +1028,7 @@ const MasterDetailLines: React.FC = ({ // used to pass `toLocaleString` an explicit `undefined`, i.e. the MACHINE's // locale (objectui#9909). const displayLocale = useDisplayLocale(); + const gridBodyReady = useGridBodySettled(); // The tenant default currency (ADR-0053): the totals stack's currency when // the amount field fixes none (objectui#11132). const { currency: tenantCurrency } = useLocalization(); @@ -1211,7 +1240,7 @@ const MasterDetailLines: React.FC = ({ { object: d.childObject, parent: parentObjectName, property: 'relationshipField' }, )}

- ) : !d.columns?.length ? ( + ) : !d.columns?.length || !gridBodyReady ? (

{t('form.masterDetail.loadingColumns')}

) : ( = ({ dataSource, className, }) => { + // The line grid's body loads on first use (objectstack#36102). Start it now, + // while the child schema is fetched, so the grid is there before its columns. + preloadGridField(); const rawDetails = schema.details || []; const isEdit = schema.mode === 'edit' && !!schema.recordId; // `title` / `submitText` / `cancelText` are `I18nLabel` (see the schema diff --git a/ui/packages/plugin-form/src/ModalForm.untypedRepeater.test.tsx b/ui/packages/plugin-form/src/ModalForm.untypedRepeater.test.tsx index dd69e1b63ec..875ae9481d1 100644 --- a/ui/packages/plugin-form/src/ModalForm.untypedRepeater.test.tsx +++ b/ui/packages/plugin-form/src/ModalForm.untypedRepeater.test.tsx @@ -29,9 +29,14 @@ import { describe, it, expect, vi } from 'vitest'; import { render, waitFor, fireEvent, screen, act } from '@testing-library/react'; import React from 'react'; -import { registerAllFields, GridField, resolveFormWidgetType } from '@object-ui/fields'; +import { registerAllFields, GridField, preloadGridField, resolveFormWidgetType } from '@object-ui/fields'; import { ModalForm } from './ModalForm'; +// The line grid renders behind `@object-ui/fields`' lazy face (objectstack#36102); +// load its body before the first render, as the record forms' mount-time +// preload does in the console. +await preloadGridField(); + registerAllFields(); const ROWS = [ diff --git a/ui/packages/plugin-form/src/RecordBodyTableEditor.tsx b/ui/packages/plugin-form/src/RecordBodyTableEditor.tsx index 347ff290009..65da6f35ba3 100644 --- a/ui/packages/plugin-form/src/RecordBodyTableEditor.tsx +++ b/ui/packages/plugin-form/src/RecordBodyTableEditor.tsx @@ -37,7 +37,7 @@ import React, { useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'; import type { BatchTransactionOperation, GridFieldMetadata } from '@object-ui/types'; import { resolveAffordance, type SchemaLike } from '@object-ui/core'; -import { LineItemsField, lookupAutofillByField, columnHelpByField, useBooleanValueLabel, type GridColumn } from '@object-ui/fields'; +import { LineItemsField, preloadGridField, lookupAutofillByField, columnHelpByField, useBooleanValueLabel, type GridColumn } from '@object-ui/fields'; import { cn } from '@object-ui/components'; import { useLocalization } from '@object-ui/i18n'; import { usePermissions } from '@object-ui/permissions'; @@ -207,6 +207,9 @@ const BODY_TABLE_EDIT_LIMIT = 500; * a part of the record page's edit state, never a standalone block. */ export const RecordBodyTableEditor: React.FC = ({ objectName, relationshipField, title }) => { + // The line grid's body loads on first use (objectstack#36102). Start it now, + // while the child schema is fetched, so the grid is there before its columns. + preloadGridField(); const session = useContext(RecordEditSessionContext); const record = useRecordContext(); // The record page's adapter, as its related lists read it. @@ -231,8 +234,10 @@ export const RecordBodyTableEditor: React.FC = ({ ob useEffect(() => { let cancelled = false; if (!dataSource || typeof dataSource.getObjectSchema !== 'function') return; - Promise.resolve(dataSource.getObjectSchema(objectName)) - .then((s: any) => { if (!cancelled) setChildSchema(s ?? { fields: {} }); }) + // The child schema is what draws the line grid, so it lands together with + // the grid's body (objectstack#36102); `preloadGridField` never rejects. + Promise.all([dataSource.getObjectSchema(objectName), preloadGridField()]) + .then(([s]) => { if (!cancelled) setChildSchema(s ?? { fields: {} }); }) .catch(() => { if (!cancelled) setLoadFailed(true); }); return () => { cancelled = true; }; }, [dataSource, objectName]); diff --git a/ui/packages/plugin-form/src/__tests__/masterDetailSectionMembers-8071.test.tsx b/ui/packages/plugin-form/src/__tests__/masterDetailSectionMembers-8071.test.tsx index 62c50c56527..580b3bb963c 100644 --- a/ui/packages/plugin-form/src/__tests__/masterDetailSectionMembers-8071.test.tsx +++ b/ui/packages/plugin-form/src/__tests__/masterDetailSectionMembers-8071.test.tsx @@ -86,9 +86,14 @@ import { describe, it, expect, vi } from 'vitest'; import { render, waitFor } from '@testing-library/react'; import React from 'react'; -import { registerAllFields } from '@object-ui/fields'; +import { registerAllFields, preloadGridField } from '@object-ui/fields'; import { MasterDetailForm } from '../MasterDetailForm'; +// The line grid renders behind `@object-ui/fields`' lazy face (objectstack#36102); +// load its body before the first render, as the record forms' mount-time +// preload does in the console. +await preloadGridField(); + registerAllFields(); /** Parent object — three text fields, declared in this order. */ diff --git a/ui/packages/plugin-form/src/deriveMasterDetail.declaredSpelling.test.tsx b/ui/packages/plugin-form/src/deriveMasterDetail.declaredSpelling.test.tsx index 1e462baabbb..93f1cfe784d 100644 --- a/ui/packages/plugin-form/src/deriveMasterDetail.declaredSpelling.test.tsx +++ b/ui/packages/plugin-form/src/deriveMasterDetail.declaredSpelling.test.tsx @@ -26,10 +26,15 @@ import { describe, it, expect } from 'vitest'; import { render, screen } from '@testing-library/react'; import React from 'react'; -import { GridField } from '@object-ui/fields'; +import { GridField, preloadGridField } from '@object-ui/fields'; import { deriveColumns, hydrateColumns, deriveDetail } from './deriveMasterDetail'; import { en } from '@object-ui/i18n'; +// The line grid renders behind `@object-ui/fields`' lazy face (objectstack#36102); +// load its body before the first render, as the record forms' mount-time +// preload does in the console. +await preloadGridField(); + /** The `en` session's word for a boolean value: what `useBooleanValueLabel` * (`@object-ui/fields`) draws under `en`. The derive functions require one * (objectui#12924). */ diff --git a/ui/scripts/__tests__/check-eager-closure-budget.test.ts b/ui/scripts/__tests__/check-eager-closure-budget.test.ts index 17c362401b6..bccdff08d13 100644 --- a/ui/scripts/__tests__/check-eager-closure-budget.test.ts +++ b/ui/scripts/__tests__/check-eager-closure-budget.test.ts @@ -1283,7 +1283,10 @@ describe('chunk membership (objectui#9345)', () => { expect(PER_CHUNK_MEMBERSHIP.framework).toContain('types'); expect(PER_CHUNK_MEMBERSHIP_CARVE_OUTS).toEqual({ types: [{ subtree: 'src/zod', chunk: 'types-zod' }], - fields: [{ subtree: 'src/widgets/date-picker', chunk: 'fields-date-picker' }], + fields: [ + { subtree: 'src/widgets/date-picker', chunk: 'fields-date-picker' }, + { subtree: 'src/widgets/grid-field', chunk: 'fields-grid' }, + ], }); }); diff --git a/ui/scripts/__tests__/vite-ineffective-dynamic-imports.test.ts b/ui/scripts/__tests__/vite-ineffective-dynamic-imports.test.ts index 61ef9db1898..59ddd1dde70 100644 --- a/ui/scripts/__tests__/vite-ineffective-dynamic-imports.test.ts +++ b/ui/scripts/__tests__/vite-ineffective-dynamic-imports.test.ts @@ -155,7 +155,7 @@ describe('formatIneffectiveDynamicImportStandDown', () => { missing: [...DEFEATED_LAZY_FIELD_WIDGETS], }); expect(text).not.toContain('\n'); - expect(text).not.toContain('packages/fields/src/widgets/GridField.tsx'); + expect(text).not.toContain(DEFEATED_LAZY_FIELD_WIDGETS[0]); expect(text).toContain(`${DEFEATED_LAZY_FIELD_WIDGETS.length} did not fire`); }); }); diff --git a/ui/scripts/check-eager-closure-budget.mjs b/ui/scripts/check-eager-closure-budget.mjs index 31e68fa423f..02527ed011b 100644 --- a/ui/scripts/check-eager-closure-budget.mjs +++ b/ui/scripts/check-eager-closure-budget.mjs @@ -2428,11 +2428,10 @@ export const PER_CHUNK_GZIP_CEILINGS = Object.freeze({ // (`GrowingCellInput`), so a form's line items edit in the cell the way a // list grid does (objectstack#36023 S5). The other ~5.4 KB are SHARED // headroom (355,000 − 349,448 = 5,552 once S5 lands) so the next form-field - // PR does not bounce at once, ⛔ not a budget for a new component group. They - // come back down when the follow-up card the ruling names takes GridField - // out of the eager chunk (it is `import()`ed but also statically exported, - // `packages/fields/src/index.tsx`): re-measure then and lower both numbers - // together. ⛔ Not moved: MAX_EAGER_CLOSURE_GZIP_BYTES (it passes on both + // PR does not bounce at once, ⛔ not a budget for a new component group. The + // card the ruling names (objectstack#36102, GridField out of the eager chunk) + // is a follow-up, not a payback; lower both numbers by the bytes removed. + // ⛔ Not moved: MAX_EAGER_CLOSURE_GZIP_BYTES (it passes on both // builds), BASELINE, REGRESSION_THIS_GATE_MUST_CATCH_BYTES and the other // per-chunk rows. No exemption was added and no import was made lazy. The // headroom `pnpm check:eager-closure` prints on YOUR build is the figure in @@ -2473,9 +2472,8 @@ export const PER_CHUNK_GZIP_CEILINGS = Object.freeze({ // WHAT THE BYTES BUY: SHARED headroom, so form and field PRs stop being // ejected from the queue on this line one at a time, ⛔ not a budget for a // new component group: a whole group still belongs behind a lazy boundary. - // ⭐ PAYBACK: objectstack#36102 takes GridField out of the eager chunk (it is - // `import()`ed but also statically exported, `packages/fields/src/index.tsx`); - // re-measure when it lands. + // objectstack#36102 (GridField out of the eager chunk) is a follow-up, not a + // payback; lower both numbers by the bytes removed. // // WHAT MOVED WITH IT, read from "Raising one" above and the two constraints // it names as checked: this ceiling passes on its baseline below, and @@ -2489,7 +2487,44 @@ export const PER_CHUNK_GZIP_CEILINGS = Object.freeze({ // either: MAX_EAGER_CLOSURE_GZIP_BYTES (it passes on both builds), BASELINE, // REGRESSION_THIS_GATE_MUST_CATCH_BYTES and the other per-chunk rows. No // exemption was added and no import was made lazy. - 'ui-components': 451_100, + // + // ⭐ LOWERED (2026-11-22), from 451,100 by 5,956 bytes, to 445,144, by + // objectstack#36102, the follow-up ruling 7063116595 names (GridField out of + // the eager chunk; seat note 7064483594 on that card, on ruling 7063869131: + // lower the ceiling and baseline by the bytes taken out, no more). Its + // baseline below moved by the same amount, which keeps the + // ceiling-minus-baseline gap this key carried (185,163). + // + // WHAT THE BYTES ARE — one container, one instrument: `CI=true pnpm exec + // turbo run build --filter=@object-ui/console...`, reading + // `apps/console/dist/eager-closure.json`, twice on one tree: `main` at + // `b3bcfefc` alone, then the same `main` with this change (`3c422050`, a + // branch commit on that base; re-read on the branch's final head, this + // chunk is still 346,403 and the aggregate is within 3 bytes). Gzipped bytes: + // + // | chunk | `b3bcfefc` | `3c422050` | delta | + // |-----------------------|-----------:|-----------:|-------:| + // | `vendor-objectstack` | 674,662 | 674,662 | 0 | + // | `i18n-locale-en` | 66,785 | 66,785 | 0 | + // | `framework` | 88,559 | 88,559 | 0 | + // | `ui-components` | 352,359 | 346,403 | −5,956 | + // | ⇒ aggregate | 1,875,902 | 1,869,974 | −5,928 | + // + // The same 105 eager chunks by name in both builds (2,577 -> 2,578 chunks in + // all: the new one is `fields-grid`, lazy); besides this one, none moved by + // more than 31 bytes (`index` +31). Raw minified bytes of this chunk: + // 1,309,110 -> 1,289,869 (−19,241). + // + // WHAT LEFT: the line-item grid's body, now + // `packages/fields/src/widgets/grid-field/GridFieldWidget.tsx` in the lazy + // `fields-grid` chunk (20,374 raw bytes), reached only through + // `loadGridFieldWidget`'s `import()`. The package entry exports the small + // lazy face in `widgets/GridField.ts` under the same names, and the pure + // helpers it exports stay here. ⛔ Not moved: MAX_EAGER_CLOSURE_GZIP_BYTES, + // BASELINE, REGRESSION_THIS_GATE_MUST_CATCH_BYTES and the other per-chunk + // rows. No exemption was added. The headroom `pnpm check:eager-closure` + // prints on YOUR build is the figure in force, ⛔ not this one. + 'ui-components': 445_144, }); /** @@ -2710,7 +2745,12 @@ export const PER_CHUNK_BASELINE = Object.freeze({ // (2026-11-21, ruling 7063869131 on objectstack#36023): a ruled raise widens // the gap rather than keeping it (the entry on that key of // PER_CHUNK_GZIP_CEILINGS), so this is again `bbf6b02d9`'s reading. - 'ui-components': 265_937, + // + // Moved with its ceiling (2026-11-22, objectstack#36102), from 265,937 by + // the same −5,956 bytes GridField's body took out (the entry on that key of + // PER_CHUNK_GZIP_CEILINGS), which keeps the ceiling-minus-baseline gap this + // key carried. ⚠️ So this is no longer one build's reading. + 'ui-components': 259_981, }); /** @@ -2839,6 +2879,11 @@ export const PER_CHUNK_MEMBERSHIP_CARVE_OUTS = Object.freeze({ // to being ABSENT from the eager closure. fields: Object.freeze([ Object.freeze({ subtree: 'src/widgets/date-picker', chunk: 'fields-date-picker' }), + // objectstack#36102: the line-item grid's body, which only + // `loadGridFieldWidget`'s `import()` reaches; the package entry exports its + // lazy face (`widgets/GridField.ts`). Same rule as the row above: its chunk + // carries no ceiling, so it must stay ABSENT from the eager closure. + Object.freeze({ subtree: 'src/widgets/grid-field', chunk: 'fields-grid' }), ]), }); diff --git a/ui/scripts/vite-ineffective-dynamic-imports.ts b/ui/scripts/vite-ineffective-dynamic-imports.ts index 2cd07dcebee..bc6650505a4 100644 --- a/ui/scripts/vite-ineffective-dynamic-imports.ts +++ b/ui/scripts/vite-ineffective-dynamic-imports.ts @@ -17,7 +17,7 @@ import type { Plugin, ResolvedConfig, Rollup } from 'vite'; * into another chunk — the laziness is decoration: * * ``` - * [INEFFECTIVE_DYNAMIC_IMPORT] packages/fields/src/widgets/GridField.tsx is + * [INEFFECTIVE_DYNAMIC_IMPORT] packages/fields/src/widgets/VectorField.tsx is * dynamically imported by packages/fields/src/index.tsx but also statically * imported by packages/fields/src/index.tsx, dynamic import will not move * module into another chunk. @@ -188,7 +188,6 @@ export const DEFEATED_LAZY_FIELD_WIDGETS: readonly string[] = Object.freeze([ 'packages/fields/src/widgets/FilterConditionField.tsx', 'packages/fields/src/widgets/FormulaField.tsx', 'packages/fields/src/widgets/GeolocationField.tsx', - 'packages/fields/src/widgets/GridField.tsx', 'packages/fields/src/widgets/ImageCropperDialog.tsx', 'packages/fields/src/widgets/ImageField.tsx', 'packages/fields/src/widgets/LocationField.tsx',