From ba6809a5063b6712e7354281a82bdf9fdaa110d7 Mon Sep 17 00:00:00 2001
From: Claude
Date: Sun, 22 Nov 2026 07:58:34 +0000
Subject: [PATCH 1/8] perf(fields): the line-item grid's body leaves the
console's eager ui-components chunk
GridField / LineItemsField keep their names and props; the package entry now
exports a small lazy face whose body (widgets/grid-field/GridFieldWidget.tsx)
is reached only through one import(). The pure helpers the entry exports stay
eager. The console gets a fields-grid chunk group and a carve-out row; the
record forms that draw line items preload the body on mount.
Claude-Session: https://claude.ai/code/session_01QsR2jV3scu6UYPb42n5okQ
Co-Authored-By: Claude
---
ui/apps/console/vite.config.ts | 24 +
.../date-carrier-unparsable-8809.test.tsx | 2 +-
.../__tests__/date-locale-channel.test.tsx | 2 +-
.../datetime-widget-faces-8209.test.tsx | 2 +-
.../display-grid-host-channels-e2e.test.tsx | 2 +-
...ields-date-widget-convention-8194.test.tsx | 2 +-
.../parentCurrency.faces-31912.test.tsx | 2 +-
.../readonly-host-plumbing-e2e.test.tsx | 2 +-
.../widget-aria-invalid-registry-e2e.test.tsx | 2 +-
.../__tests__/widget-dom-leak-e2e.test.tsx | 2 +-
.../fields/src/complex-widgets.test.tsx | 2 +-
ui/packages/fields/src/index.tsx | 10 +-
.../DateField.impossibleDay-10567.test.tsx | 2 +-
...DateTimeField.impossibleDay-10474.test.tsx | 2 +-
...GridField.currencyMinorUnit-10355.test.tsx | 3 +-
...dField.currencyScaleNotRead-10783.test.tsx | 3 +-
.../GridField.declaredSpelling.test.tsx | 2 +-
.../GridField.displayLocale-9909.test.tsx | 2 +-
.../GridField.fieldKeys-11070.test.tsx | 2 +-
...ld.fileCellText-12924.no-provider.test.tsx | 2 +-
.../GridField.fileCellText-12924.test.tsx | 2 +-
...ield.i18nChrome-11131.no-provider.test.tsx | 2 +-
.../GridField.i18nChrome-11131.test.tsx | 2 +-
...ield.i18nChrome-11145.no-provider.test.tsx | 2 +-
.../GridField.i18nChrome-11145.test.tsx | 2 +-
.../GridField.impossibleDay-10301.test.tsx | 2 +-
.../src/widgets/GridField.keyWarning.test.tsx | 2 +-
.../GridField.lookupAutofill-28245.test.tsx | 3 +-
.../GridField.readonlyCells-12915.test.tsx | 3 +-
...quiredCell.i18n-11160.no-provider.test.tsx | 2 +-
...GridField.requiredCell.i18n-11160.test.tsx | 2 +-
.../GridField.retiredSnakeKeys-11610.test.tsx | 2 +-
...GridField.sortFieldCellEdit-12286.test.tsx | 2 +-
.../fields/src/widgets/GridField.test.tsx | 5 +-
ui/packages/fields/src/widgets/GridField.tsx | 1642 +----------------
.../widgets/grid-field/GridFieldWidget.tsx | 1596 ++++++++++++++++
.../src/widgets/imeComposition-35996.test.tsx | 2 +-
.../plugin-form/src/LineItemsPanel.tsx | 5 +-
.../plugin-form/src/MasterDetailForm.tsx | 5 +-
.../plugin-form/src/RecordBodyTableEditor.tsx | 5 +-
.../vite-ineffective-dynamic-imports.test.ts | 2 +-
ui/scripts/check-eager-closure-budget.mjs | 5 +
.../vite-ineffective-dynamic-imports.ts | 3 +-
43 files changed, 1782 insertions(+), 1588 deletions(-)
create mode 100644 ui/packages/fields/src/widgets/grid-field/GridFieldWidget.tsx
diff --git a/ui/apps/console/vite.config.ts b/ui/apps/console/vite.config.ts
index f2c19fd620f..9d539987423 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.tsx`: 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/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..151e1514560 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
@@ -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..ec5a486ecf3 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.tsx`.
+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/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..851f0af9778 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', () => {
diff --git a/ui/packages/fields/src/widgets/GridField.tsx b/ui/packages/fields/src/widgets/GridField.tsx
index a51a0f45ab1..34cd1ea412f 100644
--- a/ui/packages/fields/src/widgets/GridField.tsx
+++ b/ui/packages/fields/src/widgets/GridField.tsx
@@ -1,92 +1,45 @@
-import React, { useCallback, useRef } from 'react';
-import { FieldWidgetComponentProps } from './types.js';
-import {
- cn,
- Button,
- Input,
- Popover,
- PopoverTrigger,
- PopoverContent,
- Checkbox,
- Label,
- Tooltip,
- TooltipContent,
- TooltipProvider,
- TooltipTrigger,
-} from '@object-ui/components';
-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 React from 'react';
import type { InlineGridColumn } from '@objectstack/spec/data';
-import { GRID_FIELD_RETIRED_KEYS, type GridFieldMetadata, type GridFieldRetiredKey } from '@object-ui/types';
+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 — editable child-grid ("line items") widget.
- *
- * ## 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
- * pointed `for` at an id no element carried and the help text had zero
- * consumers. Measured on `origin/main` at `e71c854ce`, a real form, editable
- * state, `description` set:
- *
- * ```
- * bare (no columns) for=DANGLING hostIdEl=NONE consumers=0 focusables=[button]
- * columns + one row for=DANGLING hostIdEl=NONE consumers=0 focusables=[drag,
- * input(Item), input(Qty), button(Duplicate row),
- * button(Remove row), input(Item), input(Qty), button(Add)]
- * ```
+ * GridField / LineItemsField — the public face of the line-item grid, and its
+ * pure half.
*
- * The bare row's single focusable is the auxiliary "Add line" BUTTON — labelable,
- * but routing the host id (and so the label's `for`) onto it would make the
- * field's label NAME the add-row action and make a click on the label insert a
- * row. Every realistic config is a composite: many cell inputs, each with its
- * own `aria-label`, under one container. So this widget declares
- * `labelling: 'group'` (see `FIELD_WIDGET_LABELLING` in `../index`) — the
- * objectui#3961 composite shape, like `address` — and the CONTAINER consumes the
- * host's keys:
+ * ## Why the widget body is in another file (objectstack#36102)
*
- * - editable / list mode: the root div takes the DOM pass-through minus `name`
- * (DOM-legal on form controls only — the objectui#3291 leak) and minus
- * `aria-invalid` (control-channel state; this grid reports validity per CELL,
- * with its own inline marks), answering `role="group"` only when a host
- * actually named it — `CheckboxesField`'s split, key for key.
+ * 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:
*
- * That strip STANDS (objectui#3318 upheld it rather than overturning it):
- * the container is not a control, so the host's state is not re-routed onto
- * it. What #3318 added is the other half the strip implied but nobody had
- * built — the host's failure now DRIVES the per-cell channel this comment
- * already claimed as the reporting path. See `hostFailedEmpty`.
- * - readonly: the table replaces the inputs entirely, so that surface takes the
- * name AND the description via `toHostGroupProps` — `'instead-of-the-inputs'`.
+ * - `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 call it when they mount, while their child object's
+ * schema is still being fetched, so the grid is there before its columns
+ * are.
+ * - The pure helpers below stay in this file, in the eager chunk, because the
+ * entry exports them by name and they import nothing heavy.
*
- * A controlled component: `value` is an array of row objects, `onChange`
- * receives the next array. It renders one editable cell per configured
- * column, supports add / delete row, and shows a running total of a numeric
- * column. This is the renderer for the `field:grid` widget and the cell
- * engine behind the master-detail subform (see ADR-0001).
- *
- * Column config: `@objectstack/spec`'s inline grid column, by reference —
- * see {@link GridColumn}.
- *
- * Field-level config: the keys `GridFieldMetadata` (`@object-ui/types`)
- * declares, each read under that one spelling (objectui#11070 round 8), and
- * no other key: `sortField`, the last key read before any face declared it,
- * is declared there too (objectui#11070 round 9). objectui#11610 renamed all
- * eight from snake_case to camelCase; a field still carrying a snake_case
- * spelling is refused by name instead of drawn (`RetiredGridFieldKeys`).
+ * ⛔ 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.
*/
/**
@@ -142,38 +95,6 @@ export type GridColumn = InlineGridColumn;
type Row = Record;
-const isNumeric = (t?: string) => t === 'number' || t === 'currency';
-
-/** Comfortable minimum widths per column type so cells never get crushed; the
- * grid scrolls horizontally instead. Authors can still pin a `width`. */
-const MIN_WIDTH_BY_TYPE: Record = {
- text: 160,
- select: 132,
- lookup: 168,
- number: 104,
- currency: 116,
- date: 150,
- // `` renders a day AND a wall clock, so it needs
- // materially more room than a date cell before the browser starts eliding.
- datetime: 200,
- time: 116,
- file: 168,
-};
-const minWidthFor = (c: GridColumn): number => c.width ?? MIN_WIDTH_BY_TYPE[c.type ?? 'text'] ?? 132;
-
-/**
- * Per-column sizing. Text columns flex to absorb slack (so the description
- * never gets crushed), while numeric / select / date / lookup columns get a
- * fixed sensible width — the role-based sizing every enterprise line grid uses
- * (Qty stays narrow, Description stays wide). Authors can still pin `width`.
- */
-function widthStyle(c: GridColumn): React.CSSProperties {
- if (c.width) return { width: c.width, minWidth: c.width };
- if ((c.type ?? 'text') === 'text') return { minWidth: 180 }; // flex, no fixed width
- 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
@@ -343,7 +264,7 @@ function columnCurrency(tenantCurrency: string | undefined): string | undefined
* `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 {
+export function currencyWidth(currency: string | undefined): number | undefined {
return currency ? currencyFractionDigits(currency) : undefined;
}
@@ -379,7 +300,7 @@ function storedFractionScale(
export type ColumnCurrencies = Readonly>;
/** `c`'s currency: the host's answer for it when it gave one, else {@link columnCurrency}. */
-function currencyOfColumn(
+export function currencyOfColumn(
c: GridColumn,
tenantCurrency: string | undefined,
columnCurrencies: ColumnCurrencies | undefined,
@@ -407,249 +328,6 @@ export function computeRow(columns: GridColumn[], row: Row, tenantCurrency?: str
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';
-
-/**
- * Read-only display text for a temporal cell (objectui#3569).
- *
- * The stored shapes differ per type and so must the rendering — which is only
- * decidable now that `datetime`/`time` are no longer collapsed onto `date`:
- *
- * - `date` — a calendar day. Its VERBATIM `YYYY-MM-DD` (`toDateInputValue`
- * keeps a stored string's leading day as written) goes through the
- * shared parse step `toDisplayDate`, which builds local midnight of that day,
- * never the UTC midnight `new Date('2026-06-17')` would give, so the 17th
- * stays the 17th west of Greenwich. It used to build that `Date` here, by
- * hand, with `new Date(y, m - 1, d)`, which rolls `2026-02-30` into March
- * 2nd: the step's refusal of a nonexistent day (objectui#10026) never
- * reached this cell (objectui#10301).
- * - `datetime` — an instant, rendered on `formatDateTime`'s `'compact'` face:
- * local day + local time, the same basis `toDateTimeInputValue` uses for the
- * editor, so the two never disagree about a real instant. ⚠️ It no longer
- * matches `DateTimeField`'s readonly rendering, and that is the RULING on
- * objectui#8209 rather than a drift: both sites went to the one home
- * `formatDateTime`, each on the face of its register — a dense grid cell is
- * `'compact'`, a readonly form / detail field is the verbose default.
- * - `time` — a zone-less wall clock (`HH:mm[:ss]`); it is already display-ready.
- *
- * An unparseable value falls through to its raw string rather than rendering
- * "Invalid Date" — showing the user what is actually stored beats hiding it.
- * On both the `date` and `datetime` arms "unparseable" is whatever
- * `toDisplayDate` refuses, a day its month does not have included, so this
- * cell shows `2026-02-30` as stored instead of a real day nobody wrote.
- *
- * `locale` is threaded rather than left to `Intl`'s default (objectui#4468):
- * the default is the MACHINE's locale, which has nothing to do with the
- * session, so a Chinese form rendered `6/17/2026` in its line items.
- */
-function temporalText(type: string | undefined, value: any, locale: string): string {
- const raw = String(value);
- if (type === 'time') return raw;
- if (type === 'date') {
- const ymd = toDateInputValue(value);
- if (!ymd) return raw;
- const day = toDisplayDate(ymd);
- if (Number.isNaN(day.getTime())) return raw;
- // `formatDate`'s DEFAULT style — the one home for the `date` display
- // convention (objectui#8194, following the maintainer's ruling A behind
- // `c15d7eca6`). This branch used to call `toLocaleDateString(locale)`
- // with NO options bag, i.e. `Intl`'s numeric default (`7/4/2026`), so a
- // sub-grid cell and a `date` field cell on the same screen rendered the
- // same value two ways — the split ruling A settled, one surface over.
- // Current-year values lose the year here now (`Jul 4`); past- and
- // future-year values are byte-identical.
- //
- // The two guards above still own the unparseable case, so this branch
- // never reaches `formatDate`'s `—`: an unreadable stored value keeps
- // showing what is actually stored (objectui#3569). `day` is handed over
- // as a `Date`, which the shared function uses verbatim.
- return formatDate(day, undefined, { locale });
- }
- // Validity is the shared parse step's answer, so a date-time written on a
- // nonexistent day is refused here too (objectui#10301). The formatter still
- // takes the engine's `new Date(raw)`: this arm renders an INSTANT, exactly as
- // `DateTimeCellRenderer` does with the same split.
- if (Number.isNaN(toDisplayDate(value instanceof Date ? value : raw).getTime())) return raw;
- const dt = value instanceof Date ? value : new Date(raw);
- // `formatDateTime`'s `'compact'` face — the one home for the `datetime`
- // display convention (objectui#7443), on the face the maintainer ruled for
- // THIS register on objectui#8209. A sub-grid cell sits beside `datetime`
- // cells, and `DateTimeCellRenderer`'s own default face is `'compact'`, so
- // that is the register's face here. This branch used to compose
- // `toLocaleDateString(locale)` and `toLocaleTimeString(locale)` with NO
- // options bag, which put seconds in a dense cell that the `datetime` cell
- // one component over never showed.
- //
- // ⛔ The style is a LITERAL, not an authored read, and that departs from the
- // call shape the ruling wrote (`field.format ?? 'compact'`). It has to:
- // `temporalText` is handed a column `type`, and the `GridColumn` its caller
- // holds — the spec's inline grid column, by reference — declares no
- // `format` key at all, so there is nothing here to reuse the way
- // `DateTimeCellRenderer` reuses `DateTimeFieldMetadata.format`. Spelling the
- // read anyway would mean DECLARING that key, which the same ruling forbids
- // in the same breath ("reuse, not a new declaration"). The ruled FACE is
- // delivered; only the read that would have selected it is absent, because
- // the vocabulary it would read does not exist on this surface.
- //
- // The `Number.isNaN` guard above still owns the unparseable case, so this
- // branch never reaches `formatDateTime`'s `—`: an unreadable stored value
- // keeps showing what is actually stored (objectui#3569), exactly as the
- // `date` branch's guards do.
- return formatDateTime(dt, { style: 'compact', locale });
-}
-
-/**
- * The symbol a `currency` cell shows: the column's authored `prefix`, else the
- * resolved currency's own symbol through `currencySymbol` (the one channel
- * `CurrencyField` uses too), else nothing. ⛔ No default symbol
- * (objectui#10355): both currency faces of this grid used to fall back to a
- * literal `¥`, so a USD tenant's line items read `¥1,234.57`.
- */
-function currencyAdornment(c: GridColumn, currency: string | undefined, locale: string): string {
- if (c.prefix) return c.prefix;
- return currency ? currencySymbol(currency, locale) : '';
-}
-
-/**
- * Display text for a finite amount in a `currency` cell (objectui#10355).
- *
- * The width is {@link currencyWidth} — the same decision that rounds the
- * stored value — so a yen amount shows no decimals and a dinar amount three,
- * whatever `scale` the column carries (objectui#10783). With no resolved
- * currency there is no width to take, and the amount keeps the plain locale
- * format this branch always had.
- *
- * With no authored `prefix`, the amount is `Intl`'s own currency format, so
- * the symbol sits where the locale puts it (`¥3,704`, `3.704 ¥` in de-DE). An
- * authored `prefix` replaces the symbol, not the width.
- */
-function currencyText(c: GridColumn, n: number, currency: string | undefined, locale: string): string {
- const digits = currencyWidth(currency);
- const width = digits === undefined ? {} : { minimumFractionDigits: digits, maximumFractionDigits: digits };
- if (c.prefix || !currency) {
- return `${currencyAdornment(c, currency, locale)}${formatDisplayNumber(n, { locale, ...width })}`;
- }
- try {
- return formatDisplayNumber(n, { locale, currency, ...width });
- } catch {
- // A malformed currency code: `Intl` refuses it. Show the code beside the
- // amount rather than take the cell down — `formatCurrency`'s fallback.
- return `${currency} ${n.toFixed(digits)}`;
- }
-}
-
-/**
- * The session-language words a file cell's text is made of (objectui#12924),
- * read by the component from the packs and handed to {@link cellDisplayText}:
- * the count a cell holding several files states (`detail.fileCount`, the count
- * family `FileCellRenderer` states a file count with), and the name a file
- * whose value carries none is shown by (`fields.file.fileFallback`, the name
- * `FileField` and `FileCellRenderer` give it). Both used to be the English
- * literals `N files` / `File` here, on every locale.
- */
-interface FileCellText {
- count: (count: number) => string;
- nameless: string;
-}
-
-/** Read-only display text for a cell in list mode (select → option label,
- * currency/number → formatted, date/datetime/time → localized, file → its
- * name or a count of its files, empty → em dash). Lookups render separately.
- * `currency` is the column's resolved currency, read only by the currency
- * branch. The component binds `fileText` once, as its `displayText`. */
-function cellDisplayText(c: GridColumn, value: any, locale: string, fileText: FileCellText, currency?: string): string {
- if (value === null || value === undefined || value === '') return '—';
- if (isTemporal(c.type)) return temporalText(c.type, value, locale);
- if (c.type === 'file') {
- const files = Array.isArray(value) ? value : [value];
- if (files.length === 0) return '—';
- if (files.length > 1) return fileText.count(files.length);
- const f = files[0];
- return typeof f === 'string' ? f : f?.name || f?.original_name || fileText.nameless;
- }
- if (c.type === 'select' && Array.isArray(c.options)) {
- const opt = c.options.find((o) => String(o.value) === String(value));
- return opt ? opt.label : String(value);
- }
- if (isNumeric(c.type)) {
- const n = Number(value);
- // The numeric branch formats in the SAME declared locale the temporal
- // branch above is handed. It used to drop it, so one grid row read a date
- // in the session's convention beside an amount grouped and decimal-marked
- // the machine's way (objectui#9909).
- if (Number.isFinite(n)) return c.type === 'currency' ? currencyText(c, n, currency, locale) : n.toLocaleString(locale);
- }
- if (Array.isArray(value)) return value.join(', ');
- return String(value);
-}
-
-/**
- * The cell values a `boolean` / `toggle` field's write is stored as, each with
- * the boolean it stands for: the readings the engine's write normalisation
- * (`BOOLEAN_READINGS` in `@objectstack/objectql`'s record validator) turns into
- * a boolean before it validates a row, compared the same way (SameValueZero).
- * Every other value is no reading, and is left as it is.
- */
-const BOOLEAN_READINGS: ReadonlyMap = new Map([
- ['true', true],
- ['1', true],
- [1, true],
- ['false', false],
- ['0', false],
- [0, false],
-]);
-
-/**
- * A column over a `boolean` / `toggle` child field: the `select` column
- * `@object-ui/plugin-form` derives for one, whose two options store the
- * strings `'true'` / `'false'` (`optionsFor` in `deriveMasterDetail.ts`). A
- * grid column carries no field definition, so this option pair is what names
- * the field's type here.
- */
-function isBooleanSelectColumn(c: GridColumn): boolean {
- if (c.type !== 'select' || !Array.isArray(c.options) || c.options.length !== 2) return false;
- const values = new Set(c.options.map((o) => o.value));
- return values.has('true') && values.has('false');
-}
-
-/**
- * The row a column's `readonlyWhen` / `requiredWhen` predicate reads as
- * `record`: the row, with each boolean column's cell read as the boolean it
- * stands for. The select cell writes the string `'true'` / `'false'` into the
- * row, so `record.won == true` compared a string and the cell marker showed
- * the wrong state, while the server — which stores and judges the boolean —
- * refused the row. Only the predicate's view changes: the cell still shows,
- * and the row still saves, what the select wrote.
- */
-function ruleRecordOf(booleanColumns: readonly string[], row: Row | undefined): Record {
- const base: Row = row || {};
- let out: Row | undefined;
- for (const name of booleanColumns) {
- const judged = BOOLEAN_READINGS.get(base[name]);
- if (judged !== undefined) (out ??= { ...base })[name] = judged;
- }
- return out ?? base;
-}
-
-function coerce(type: string | undefined, raw: string): any {
- if (isNumeric(type)) {
- if (raw === '' || raw == null) return null;
- const n = Number(raw);
- return Number.isNaN(n) ? raw : n;
- }
- // `` hands back a ZONE-LESS local wall clock;
- // storing that verbatim would put the write on a different basis from the
- // read (`toDateTimeInputValue`), so a user in UTC+8 who picked 08:33 would
- // store 08:33Z and see 16:33 back. The pair must be used as a pair — this is
- // the same contract `DateTimeField` follows (objectui#3127 / #3569).
- // `date` and `time` need no conversion: their controls already emit exactly
- // the stored shape (`YYYY-MM-DD`, `HH:mm`).
- 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;
@@ -659,59 +337,6 @@ export function sumColumn(rows: Row[], field: string): number {
}, 0);
}
-type GridFieldProps = 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
- * while the grid stays a quick at-a-glance editor. */
- onRowExpand?: (rowIndex: number) => void;
- /** 'grid' (default) = editable cells; 'list' = read-only rows whose primary
- * action is per-row edit (via `onRowExpand`) and whose Add opens a new row
- * in the full form (via `onAdd`). The form-factor for "fat" children. */
- displayMode?: 'grid' | 'list';
- /** In 'list' mode, "Add" calls this (host opens the full form for a new row)
- * instead of inserting a blank inline row. */
- onAdd?: () => void;
- /** The header/parent record, bound as `parent` when evaluating a column's
- * `readonlyWhen` / `requiredWhen` CEL predicate — so a line cell can react to
- * the header (`parent.status == 'paid'`). Supplied by MasterDetailForm. */
- contextRecord?: Record;
- /** The child object's declared `lookupAutofill` pairs, by lookup column
- * name (`lookupAutofillByField` over the child's fields). A grid column
- * carries no field definition, so the host that knows the child object
- * hands them over. Supplied by MasterDetailForm and LineItemsPanel. */
- lookupAutofill?: LookupAutofillByField;
- /** The currency of each `currency` column whose host knows it
- * ({@link ColumnCurrencies}): a grid column carries no field definition,
- * so the master-detail host that holds the header and the child schema
- * hands it over. A column it does not name is in the tenant currency. */
- columnCurrencies?: ColumnCurrencies;
- /** The values a new line starts with (objectstack#35816): the child
- * object's static field defaults, by field name. A grid column carries no
- * default (the spec's inline column refuses `defaultValue`), so the host
- * that holds the child schema hands them over. Every new line takes them:
- * "Add", Enter on the last line, and a line typed into the entry line an
- * empty grid draws after the form refused it (`hostFailedEmpty`). A line
- * already in the value keeps what it holds. Absent: a new line starts
- * blank, as before. */
- newRowValues?: Row;
- /** When the host sets it, an empty required cell on a NEW line (one with
- * no id) is flagged only while it is `true` (objectstack#35816): a line
- * the user just added does not read red before the host has tried to save
- * it, and does once a save was refused. A stored line is flagged as
- * before. Absent: every line is flagged at once, as before. A line still
- * marked {@link UNTOUCHED_NEW_ROW} is never flagged (objectstack#35940):
- * the host skips it at save. */
- newRowRequiredShown?: boolean;
- /** The help text of each column's child field, by column name
- * ({@link ColumnHelp}, objectstack#35804): drawn as an info button beside
- * the column's header label. A grid column carries no field definition (the
- * spec's inline column declares no help key), so the host that holds the
- * child object's served definition hands it over through
- * {@link columnHelpByField}. A column it does not name draws no button. */
- 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.
@@ -738,96 +363,6 @@ export function columnHelpByField(fields: Readonly> | nu
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
- * name is the help itself, so a screen reader hears it on reaching the button.
- * Its own provider, so the grid draws it under any host.
- */
-function ColumnHeaderHelp({ help }: { help: string | undefined }) {
- if (!help) return null;
- return (
-
-
-
-
-
- {help}
-
-
- );
-}
-
-/**
- * The retired snake_case field-level keys a grid field's metadata carries, in
- * {@link GRID_FIELD_RETIRED_KEYS} order (objectui#11610). A key holding
- * `undefined` is not counted: no JSON document can carry one, and the TS and
- * zod faces accept it too, so all three faces draw the line in one place.
- */
-function retiredGridFieldKeysOf(field: unknown): GridFieldRetiredKey[] {
- if (field == null || typeof field !== 'object') return [];
- const carrier = field as Record;
- return (Object.keys(GRID_FIELD_RETIRED_KEYS) as GridFieldRetiredKey[]).filter(
- (key) => carrier[key] !== undefined,
- );
-}
-
-/**
- * The prescription a grid field carrying retired keys answers with: names the
- * field when it has a name, then each retired key beside the camelCase key to
- * write. One sentence, read by the alert and by the console line.
- */
-function retiredGridFieldKeysMessage(fieldName: unknown, keys: readonly GridFieldRetiredKey[]): string {
- const which = typeof fieldName === 'string' && fieldName ? `Grid field \`${fieldName}\`` : 'This grid field';
- const renames = keys.map((key) => `\`${key}\` → \`${GRID_FIELD_RETIRED_KEYS[key]}\``).join(', ');
- return (
- `[object-ui] ${which} carries retired snake_case key(s): ${renames}. ` +
- "The grid's field-level keys are camelCase since objectui#11610 and it reads no snake_case spelling, " +
- 'so the grid is not drawn until each key is renamed; the values stay the same.'
- );
-}
-
-/**
- * Messages already logged this session, so a refused grid inside a rendered
- * list logs once, not once per mount (the `reportRetiredFieldType` discipline).
- */
-const reportedRetiredGridFieldKeys = new Set();
-
-/**
- * The widget-path face of the objectui#11610 retirement: what a grid field
- * carrying a retired snake_case key renders INSTEAD of the grid. The shape is
- * `RetiredFieldTombstone`'s (`../index`), this package's settled answer to an
- * entry the renderer cannot honour: an inline alert naming the keys and the
- * replacements, plus a `console.error` with the same text. Nothing is thrown,
- * so the rest of the form still draws, and nothing is silently dropped: a grid
- * drawn without the author's `allow_add: false` would look like it worked.
- * The rows are untouched, since the alert never calls `onChange`.
- */
-function RetiredGridFieldKeys({ message, keys }: { message: string; keys: readonly GridFieldRetiredKey[] }) {
- React.useEffect(() => {
- if (reportedRetiredGridFieldKeys.has(message)) return;
- reportedRetiredGridFieldKeys.add(message);
- console.error(message);
- }, [message]);
- return (
-
- {message}
-
- );
-}
-
/**
* 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
@@ -845,1065 +380,80 @@ 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;
- const { [UNTOUCHED_NEW_ROW]: _untouched, ...rest } = row as Row & { [UNTOUCHED_NEW_ROW]?: true };
- return rest;
-}
+type GridFieldWidgetModule = typeof import('./grid-field/GridFieldWidget.js');
-/** A line the server already stores carries its id (`id`, `_id` or `recordId`). */
-function rowHasId(row: Row): boolean {
- return [row.id, row._id, row.recordId].some((v) => v != null && v !== '');
-}
+/** The loaded body, once {@link loadGridFieldWidget} has resolved. */
+let gridFieldWidgetModule: GridFieldWidgetModule | undefined;
+let gridFieldWidgetLoad: Promise | undefined;
/**
- * The `grid` field widget. A field whose metadata carries one of the retired
- * snake_case keys is refused by name ({@link RetiredGridFieldKeys}); any other
- * field draws the grid.
+ * 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 GridField(props: GridFieldProps) {
- const retired = retiredGridFieldKeysOf(props.field);
- if (retired.length > 0) {
- const message = retiredGridFieldKeysMessage((props.field as { name?: unknown } | undefined)?.name, retired);
- return ;
- }
- return ;
-}
-
-function GridFieldBody({
- value,
- onChange,
- field,
- readonly,
- disabled,
- className,
- error,
- onRowExpand,
- displayMode,
- onAdd,
- lookupAutofill,
- columnCurrencies,
- newRowValues,
- newRowRequiredShown,
- columnHelp,
- ...props
-}: GridFieldProps) {
- // 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
- // rounds 8 and 9).
- const cfg = (field || {}) as Partial;
- const allColumns: GridColumn[] = cfg.columns || [];
- const rows: Row[] = Array.isArray(value) ? value : [];
- const contextRecord = props.contextRecord;
- // The one locale channel every field renderer resolves through: tenant
- // regional default → active UI language → 'en' (objectui#4468). Read here
- // and passed down, since `displayText` is a pure helper.
- const displayLocale = useDisplayLocale();
- // The editable `date` / `datetime` cell's notice for a stored nonexistent
- // day (objectui#10474, objectui#10567) — the sentences `DateField` and
- // `DateTimeField` show for it too. Since objectui#11131 also the grid's own
- // default chrome: the Add button and the two empty states, English literals
- // until then. Each `defaultValue` is the `en` pack's value (held to it by
- // `pnpm check:i18n-keys`), which is what a provider-less host renders.
- // Since objectui#11145 the rest of the chrome too: the column chooser, the
- // footer total, the computed cell's tooltip and the row actions.
- const { t } = useFieldTranslation();
- // One key per row action, read by both its `aria-label` and its `title`
- // (objectui#11145). The two used to disagree for two of them (`Open row` /
- // `Open full form`, `Duplicate row` / `Duplicate line`); the accessible
- // name is the text kept.
- const dragLabel = t('view.dragToReorder', { defaultValue: 'Drag to reorder' });
- const openRowLabel = t('fields.grid.openRow', { defaultValue: 'Open row' });
- const duplicateRowLabel = t('fields.grid.duplicateRow', { defaultValue: 'Duplicate row' });
- const removeRowLabel = t('fields.grid.removeRow', { defaultValue: 'Remove row' });
- const totalLabel = t('form.masterDetail.total', { defaultValue: 'Total' });
- // A required, empty cell's text (objectui#11160): the plain cell's `title`,
- // and the `error` the lookup and file cells take. One expression for all
- // three, reading the pack's `validation.required` with the column's label
- // in `{{field}}`: the sentence the form renderer shows for a required field.
- const requiredCellText = (c: GridColumn) =>
- t('validation.required', { field: c.label || c.name, defaultValue: '{{field}} is required' });
- // A file cell's text in the session language (objectui#12924): the count of
- // several files and the name of a nameless one. Bound into `displayText`
- // here, so every cell that draws its text through it — the list-mode cell,
- // the computed cell and the read-only table — takes the same words.
- const fileText: FileCellText = {
- count: (count) => t('detail.fileCount', { count, defaultValue: '{{count}} files' }),
- nameless: t('fields.file.fileFallback', { defaultValue: 'File' }),
- };
- const displayText = (c: GridColumn, value: any, locale: string, cellCurrency?: string) =>
- cellDisplayText(c, value, locale, fileText, cellCurrency);
- const cellIdBase = React.useId();
- // The tenant default currency (ADR-0053) — the resolver's last step, and in
- // practice the currency of every `currency` column (objectui#10355, see
- // `columnCurrency`). It decides the stored width of a computed currency
- // cell (`computeRow`), the currency face `displayText` renders, and the
- // editable currency cell's symbol.
- const { currency: tenantCurrency } = useLocalization();
- // Per column: the host's answer for a column it resolved, else the above.
- const currencyOf = (c: GridColumn) => currencyOfColumn(c, tenantCurrency, columnCurrencies);
-
- // Per-cell CEL rule state (B2 in grids). A column with no readonlyWhen/
- // requiredWhen resolves to its static flags (cheap fast-path — no engine
- // call). Otherwise evaluate against the row (`record`) + header (`parent`),
- // the row's boolean cells read as booleans (`ruleRecordOf`). Every column,
- // shown or not, since a predicate may read any cell of the row.
- const booleanColumns = React.useMemo(
- () => allColumns.filter(isBooleanSelectColumn).map((c) => c.name),
- [allColumns],
- );
- const cellRules = useCallback(
- (c: GridColumn, row: Row): { readonly: boolean; required: boolean } => {
- if (!c.readonlyWhen && !c.requiredWhen) {
- return { readonly: false, required: !!c.required };
- }
- const s = resolveFieldRuleState(
- { readonlyWhen: c.readonlyWhen, requiredWhen: c.requiredWhen },
- ruleRecordOf(booleanColumns, row),
- { required: !!c.required, readonly: false },
- undefined,
- contextRecord ? { parent: contextRecord } : undefined,
- );
- return { readonly: s.readonly, required: s.required };
- },
- [contextRecord, booleanColumns],
- );
- // List mode: rows are read-only at-a-glance; editing happens in the full form.
- const isList = displayMode === 'list' && !readonly;
-
- // Column visibility — a curated default-visible set with the rest revealable
- // via the column chooser (mainstream "personalize columns" pattern). Required
- // columns are always visible; nothing is ever silently dropped.
- const [extraShown, setExtraShown] = React.useState>(() => new Set());
- const optionalColumns = allColumns.filter((c) => c.defaultHidden && !c.required);
- const columns: GridColumn[] = allColumns.filter(
- (c) => !c.defaultHidden || c.required || extraShown.has(c.name),
- );
- const toggleColumn = useCallback((fieldName: string) => {
- setExtraShown((prev) => {
- const next = new Set(prev);
- if (next.has(fieldName)) next.delete(fieldName);
- else next.add(fieldName);
- return next;
- });
- }, []);
-
- const allowAdd = cfg.allowAdd !== false && !readonly && !disabled;
- const allowDelete = cfg.allowDelete !== false && !readonly && !disabled;
- // A duplicate IS an add, so it is offered exactly when adding is. There is
- // no key of its own: `allow_duplicate` was read here while no face declared
- // it and round 8's census of both repositories found no producer of it, so
- // it was retired under ADR-0049 (objectui#11070 round 8), keeping the
- // behaviour its default gave.
- const allowDuplicate = allowAdd;
- // Per-row "expand to full form" (mainstream hybrid: quick grid + rich form).
- const showExpand = typeof onRowExpand === 'function' && !readonly;
- // Enterprise line grids (NetSuite/SAP/Salesforce) show a line-number column,
- // always: the `show_line_numbers` switch was retired with `allow_duplicate`,
- // for the same reason (objectui#11070 round 8).
- const minRows: number = cfg.minRows ?? 0;
- const maxRows: number | undefined = cfg.maxRows;
- // The CHILD column summed into the footer: the spec's `amountField` (an
- // `inlineAmountField` / `subforms[].amountField`), which both adapters in
- // `@object-ui/plugin-form` write here. ⚠️ Same name as the spec's
- // `totalField` on those surfaces, which is the PARENT field that receives
- // the rollup on save; the grid's key names the child column. One spelling:
- // the `amount_field` / `amountField` reads beside it are retired, round 8's
- // census having found no producer of either (objectui#11070 round 8).
- const totalField: string | undefined = cfg.totalField;
- // When set, the row's order is persisted by stamping `row[sortField] = index`
- // on every change that adds, removes or moves a row — so drag-reorder
- // survives a reload (the app adds a numeric position field and lists sort by
- // it). Without it, reorder is order-of-entry. A cell edit moves no row, so it
- // leaves every row's position as it was read (objectui#12286): renumbering
- // there wrote a position onto lines the user never touched whenever the
- // stored positions were not already 0, 1, 2, … in the order drawn (tied,
- // empty, or gapped).
- // Declared on `GridFieldMetadata`; its producer is `deriveDetail`
- // (`@object-ui/plugin-form`, through `MasterDetailForm`), which picks the
- // child object's `position` / `sort_order` / … field (objectui#11070 round 9).
- const sortField: string | undefined = cfg.sortField;
- // Drag-to-reorder is on for editable grids (off in read-only / list mode),
- // and `allowReorder: false` turns it off: the key `GridFieldMetadata`
- // declares. The undeclared `reorderable` this used to read is retired
- // (objectui#11070 round 8).
- const allowReorder = cfg.allowReorder !== false && !readonly && !disabled;
-
- /** Hand the next rows out; `renumber: false` is a cell edit, which moves no row. */
- const emit = useCallback(
- (next: Row[], renumber = true) => {
- onChange?.(sortField && renumber ? next.map((r, i) => ({ ...r, [sortField]: i })) : next);
- },
- [onChange, sortField],
- );
-
- const blankRow = useCallback((): Row => {
- const blank: Row = {};
- for (const c of columns) blank[c.name] = null;
- // objectstack#35816 — a new line starts on the defaults the host knows,
- // so a required column with a default is filled, not flagged empty.
- return newRowValues ? { ...blank, ...newRowValues } : blank;
- }, [columns, newRowValues]);
-
- /**
- * Merge a field patch into a row. `rowIdx === rows.length` targets the
- * entry line an empty grid draws once the form refused it (`hasGhost`) —
- * editing it materialises a new real row. Computed columns are recomputed
- * for the touched row on every change.
- */
- const applyPatch = useCallback(
- (rowIdx: number, patch: Row) => {
- const isGhost = rowIdx >= rows.length;
- if (isGhost) {
- if (maxRows != null && rows.length >= maxRows) return;
- emit([...rows, computeRow(columns, { ...blankRow(), ...patch }, tenantCurrency, columnCurrencies)]);
- return;
- }
- emit(rows.map((r, i) => (i === rowIdx ? computeRow(columns, { ...touched(r), ...patch }, tenantCurrency, columnCurrencies) : r)), false);
+export function loadGridFieldWidget(): Promise {
+ gridFieldWidgetLoad ??= import('./grid-field/GridFieldWidget.js').then(
+ (loaded) => {
+ gridFieldWidgetModule = loaded;
+ return loaded;
},
- [rows, columns, maxRows, blankRow, emit, tenantCurrency, columnCurrencies],
- );
-
- const applyCell = useCallback(
- (rowIdx: number, columnName: string, value: any) => applyPatch(rowIdx, { [columnName]: value }),
- [applyPatch],
- );
-
- /**
- * A lookup cell selection — set the FK id and auto-fill any sibling cells
- * whose column name matches a field on the chosen record (and isn't itself a
- * lookup/computed column). The catalog-typeahead behaviour every invoicing
- * tool has: pick a product → its unit_price / description drop into the row.
- * Opt out per column with `autofill: false`.
- *
- * The column's declared `lookupAutofill` pairs fill their targets too, under
- * the spec's overwrite rule. "An earlier pick filled it" is read from the
- * records picked in this grid, keyed by column and id: the record the cell
- * held before this pick, if this grid picked it, is the one whose `source`
- * values count as pick-filled. Keyed by the row's own lookup value rather
- * than its index, so adding, removing or reordering rows cannot misattribute it.
- */
- const pickedLookupRecords = useRef(new Map());
- const applyLookupSelection = useCallback(
- (rowIdx: number, col: GridColumn, record: any) => {
- const row = rows[rowIdx] ?? blankRow();
- const pickKey = (id: unknown) => `${col.name}\u0000${String(id)}`;
- const heldId = row[col.name];
- const previous = heldId == null || heldId === '' ? null : pickedLookupRecords.current.get(pickKey(heldId)) ?? null;
- const patch = lookupAutofillPatch(columns, col, record, { pairs: lookupAutofill?.[col.name], row, previous });
- if (record && typeof record === 'object' && patch[col.name] != null) {
- pickedLookupRecords.current.set(pickKey(patch[col.name]), record);
- }
- applyPatch(rowIdx, patch);
- },
- [columns, rows, blankRow, lookupAutofill, applyPatch],
- );
-
- /** Set a cell to an already-typed value (lookup ids, etc.) without coercion. */
- const setCellValue = useCallback(
- (rowIdx: number, columnName: string, value: any) => applyCell(rowIdx, columnName, value),
- [applyCell],
- );
-
- const setCell = useCallback(
- (rowIdx: number, col: GridColumn, raw: string) => {
- applyCell(rowIdx, col.name, coerce(col.type, raw));
- },
- [applyCell],
- );
-
- // Keyboard navigation across cells (spreadsheet-style): the table is a focus
- // grid. Enter / ArrowUp / ArrowDown move between rows in the same column;
- // Tab / Shift-Tab fall through to the browser's natural row-major order.
- // Cells carry data-cell="row-col" so we can target neighbours.
- //
- // objectstack#35507 — the grid no longer draws an empty entry line under
- // its lines, so the two keyboard paths that line carried are kept here: Add
- // moves focus into the line it appends (Tab reaches Add after the last
- // line), and Enter on the last line appends a line and moves to the same
- // column in it. The line exists only once the host hands it back in
- // `value`, so the focus waits for it (`pendingFocus`).
- const gridRef = useRef(null);
- const focusCell = useCallback((rowIdx: number, colIdx: number): boolean => {
- const el = gridRef.current?.querySelector(`[data-cell="${rowIdx}-${colIdx}"]`);
- if (!el) return false;
- el.focus();
- if (el instanceof HTMLInputElement) el.select();
- return true;
- }, []);
- /** The line and column to focus once the host hands an appended line back; `null` column = its first focusable cell. */
- const pendingFocus = useRef<{ rowIdx: number; colIdx: number | null } | null>(null);
- React.useEffect(() => {
- const pending = pendingFocus.current;
- if (!pending || rows.length <= pending.rowIdx) return;
- pendingFocus.current = null;
- if (pending.colIdx != null && focusCell(pending.rowIdx, pending.colIdx)) return;
- const first = gridRef.current?.querySelector(`[data-cell^="${pending.rowIdx}-"]`);
- if (first) {
- first.focus();
- if (first instanceof HTMLInputElement) first.select();
- }
- }, [rows.length, focusCell]);
-
- /** The Esc snapshot of the cell being visited; see the Esc block below. */
- const cellVisit = useRef<{ key: string; rowIdx: number; row: Row; count: number } | null>(null);
-
- const addRow = useCallback((focusColIdx: number | null = null) => {
- if (maxRows != null && rows.length >= maxRows) return;
- pendingFocus.current = { rowIdx: rows.length, colIdx: focusColIdx };
- cellVisit.current = null;
- // objectstack#35816 — a line Add starts on the host's defaults is marked
- // untouched until its first edit (`UNTOUCHED_NEW_ROW`).
- emit([...rows, newRowValues ? { ...blankRow(), [UNTOUCHED_NEW_ROW]: true } : blankRow()]);
- }, [rows, blankRow, maxRows, emit, newRowValues]);
-
- const onCellKeyDown = useCallback(
- (e: React.KeyboardEvent, rowIdx: number, colIdx: number) => {
- // objectstack#35996 — Enter and the arrows pressed while an input
- // method composes pick or move its candidate: the grid neither moves
- // nor appends a line on them.
- if (isImeKey(e)) return;
- if (e.key === 'Enter' && rowIdx === rows.length - 1 && allowAdd && !isList) {
- e.preventDefault();
- addRow(colIdx);
- } else if (e.key === 'ArrowDown' || e.key === 'Enter') {
- e.preventDefault();
- focusCell(rowIdx + 1, colIdx);
- } else if (e.key === 'ArrowUp') {
- e.preventDefault();
- if (rowIdx > 0) focusCell(rowIdx - 1, colIdx);
- }
+ (error: unknown) => {
+ gridFieldWidgetLoad = undefined;
+ throw error;
},
- [focusCell, rows.length, allowAdd, isList, addRow],
);
+ return gridFieldWidgetLoad;
+}
- /**
- * Esc in a cell takes back what this visit to the cell changed
- * (objectstack#36023): the line returns to what it held when the cell was
- * entered, its other cells included (a lookup pick's autofill), and the
- * untouched mark of a new line with it. The key stops at the grid, so a
- * form open in a dialog keeps its dialog and every other line: Esc in a
- * cell never closes it. A cell whose panel is open hands Esc to the panel,
- * which closes and writes nothing.
- *
- * Read on the window's capture phase, ahead of the dialog's own document
- * listener, which would close the dialog before any handler in the table
- * ran.
- *
- * The snapshot is held by line index, so a change to the lines themselves
- * (add, remove, duplicate, move) ends the visit: after it the same index
- * can draw another line, and putting the snapshot back would overwrite
- * that line with a removed or moved one. The line count is kept with the
- * snapshot as a second guard, for a host that replaces the lines itself.
- * (`cellVisit` is declared above `addRow`, which ends the visit too.)
- */
- const rowsRef = useRef(rows);
- const emitRef = useRef(emit);
- React.useLayoutEffect(() => {
- rowsRef.current = rows;
- emitRef.current = emit;
+/**
+ * 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. A failed preload is
+ * not reported here: the grid's own render asks again and a failure there
+ * reaches the nearest error boundary, where it can be seen.
+ */
+export function preloadGridField(): void {
+ loadGridFieldWidget().catch(() => {
+ // Reported by the render that needs the body; see above.
});
- const cellKeyOf = (el: EventTarget | null): { key: string; rowIdx: number } | null => {
- const cell = el instanceof Element ? el.closest('[data-grid-cell]') : null;
- const key = cell?.getAttribute('data-grid-cell');
- if (!cell || !key || !gridRef.current?.contains(cell)) return null;
- return { key, rowIdx: Number(key.slice(0, key.indexOf(':'))) };
- };
- const onGridFocus = (e: React.FocusEvent) => {
- const at = cellKeyOf(e.target);
- if (!at || cellVisit.current?.key === at.key) return;
- const row = rowsRef.current[at.rowIdx];
- cellVisit.current = row ? { key: at.key, rowIdx: at.rowIdx, row, count: rowsRef.current.length } : null;
- };
- const onGridBlur = (e: React.FocusEvent) => {
- const to = e.relatedTarget as Element | null;
- // Into a cell's own panel (portaled out of the table) is still the visit.
- if (to && (gridRef.current?.contains(to) || to.closest('[data-radix-popper-content-wrapper]'))) return;
- cellVisit.current = null;
- };
- const editable = !readonly && !isList;
- React.useEffect(() => {
- if (!editable) return;
- const onKey = (e: KeyboardEvent) => {
- if (e.key !== 'Escape' || e.defaultPrevented || isImeKey({ nativeEvent: e, keyCode: e.keyCode })) return;
- const at = cellKeyOf(e.target);
- if (!at) return;
- const cell = (e.target as Element).closest('[data-grid-cell]');
- if (cell?.querySelector('[aria-expanded="true"]')) return;
- e.stopPropagation();
- e.preventDefault();
- const visit = cellVisit.current;
- const current = rowsRef.current;
- if (!visit || visit.key !== at.key || visit.count !== current.length || current[visit.rowIdx] === visit.row) return;
- emitRef.current(current.map((r, i) => (i === visit.rowIdx ? visit.row : r)), false);
- };
- window.addEventListener('keydown', onKey, true);
- return () => window.removeEventListener('keydown', onKey, true);
- }, [editable]);
-
- const removeRow = useCallback(
- (rowIdx: number) => {
- if (rows.length <= minRows) return;
- cellVisit.current = null;
- emit(rows.filter((_, i) => i !== rowIdx));
- },
- [rows, minRows, emit],
- );
+}
- /** Duplicate a row (id stripped so the copy persists as a new record),
- * inserted directly below the original — handy for near-identical lines. */
- const duplicateRow = useCallback(
- (rowIdx: number) => {
- if (maxRows != null && rows.length >= maxRows) return;
- const src = rows[rowIdx];
- if (!src) return;
- const { id: _i, _id: _i2, recordId: _i3, ...copy } = src as any;
- const next = [...rows];
- // A copy is a line the user made, so it is not an untouched one.
- next.splice(rowIdx + 1, 0, touched({ ...copy }));
- cellVisit.current = null;
- emit(next);
- },
- [rows, maxRows, emit],
- );
+const LazyGridFieldWidget = React.lazy(() =>
+ loadGridFieldWidget().then((loaded) => ({ default: loaded.GridFieldWidget })),
+);
- /** Move a row from one position to another (drag-to-reorder). */
- const moveRow = useCallback(
- (from: number, to: number) => {
- if (from === to || from < 0 || to < 0 || from >= rows.length || to >= rows.length) return;
- const next = [...rows];
- const [moved] = next.splice(from, 1);
- next.splice(to, 0, moved);
- cellVisit.current = null;
- emit(next);
- },
- [rows, emit],
+/**
+ * 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() {
+ return (
+
);
- const dragIndex = useRef(null);
-
- const hasRowActions = showExpand || allowDelete || allowDuplicate;
- const actionColWidth = ((showExpand ? 1 : 0) + (allowDuplicate ? 1 : 0) + (allowDelete ? 1 : 0)) * 34 + 12;
-
- const showTotal = !!totalField;
- const total = showTotal ? sumColumn(rows, totalField!) : 0;
- // Align the running total under the column it sums (not blindly under the
- // last column). The label sits right-aligned immediately to its left.
- const totalColIndex = showTotal ? Math.max(0, columns.findIndex((c) => c.name === totalField)) : -1;
-
- // Column chooser — reveal/hide the optional (default-hidden) columns. Only
- // rendered when there are optional columns to manage.
- const columnChooser = optionalColumns.length > 0 ? (
-
-
-
-
-
-
- {c.type === 'lookup' && row[c.name] != null && row[c.name] !== '' ? (
- {}}
- readonly
- field={{ reference: c.reference, displayField: c.displayField, idField: c.idField } as any}
- />
- ) : (
- // Every other cell reads through `displayText`, as the
- // list-mode cell does. `String(value)` put the stored
- // shape on screen: a raw ISO for a temporal column
- // (objectui#3569), a select's stored value instead of
- // its option label, and an amount ungrouped and in no
- // locale (objectui#12915).
- displayText(c, row[c.name], displayLocale, currencyOf(c))
- )}
-
- ))}
-
- ))
- )}
-
- {showTotal && (
-
-
-
- {totalLabel}
-
-
- {total.toLocaleString(displayLocale)}
-
- {columns.length - totalColIndex - 1 > 0 && (
-
- )}
-
-
- )}
-
-
-
- );
+/**
+ * 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 ;
}
-
- // ── Editable rendering ──────────────────────────────────────────────────────
- // objectstack#35507 — no empty entry line is drawn under the lines. It used
- // to be, always ("start-with-one + auto-append"), directly above the Add
- // button, which does the same job: it had no actions, produced no write, and
- // users read it as a broken line they could not delete. Both followed
- // `allowAdd`, so no grid loses its way to add a line; Add and Enter on the
- // last line carry its keyboard path (see `pendingFocus`). An empty grid says
- // so and names the Add button instead.
- //
- // One state still draws the entry line: a REQUIRED grid the form refused
- // while EMPTY (`hostFailedEmpty`, below). There the line is what the
- // failure is about: its required cells carry the field's failure to
- // assistive tech on the controls a user types into to fix it (objectui#3318),
- // and the Add button, the only other control, is an action, not what is
- // invalid. Typing into it materialises a real line, as before.
- const hostFailedEmpty = !!error && rows.length === 0;
- const hasGhost = !isList && allowAdd && hostFailedEmpty && (maxRows == null || maxRows > 0);
- const displayRows: Row[] = hasGhost ? [...rows, blankRow()] : rows;
- const addLabel = cfg.addLabel || t('fields.grid.addLine', { defaultValue: 'Add line' });
-
- /**
- * FORM-level failure driving the per-CELL channel (objectui#3318).
- *
- * This widget reports validity per cell, and the container deliberately does
- * NOT take the host's `aria-invalid` (objectui#4857 — it is control-channel
- * state and the container is not a control). That left one real gap: a
- * REQUIRED grid submitted while still EMPTY fails at the form level, renders
- * its "is required" message, and marked nothing — every row was a ghost, and
- * ghosts were skipped, so assistive tech was told nothing at all. A sighted
- * user saw the red message; a screen-reader user saw no field state.
- *
- * So when the host reports a failure on an empty grid, the ghost row — the
- * entry line the user would actually type into to fix it — stops being
- * skipped and its required cells flag like any other. Deliberately narrow:
- * a POPULATED grid already marks its own empty required cells inline, so
- * this changes nothing there, and an empty grid that has NOT failed stays
- * unmarked (no premature alarm before validation runs).
- *
- * Since objectstack#35507 that entry line is drawn ONLY in this state: an
- * empty grid that has not failed draws its empty-state hint instead.
- * (`hostFailedEmpty` itself is computed above, beside `hasGhost`.)
- */
-
- /** Cell content: read-only display (list mode / computed columns) or an
- * editable borderless control (spreadsheet feel).
- *
- * `invalid` is the cell's validity, and it lands on the CONTROL this
- * renders — the focusable element a keyboard user edits and the only one
- * assistive tech reads a control state from (objectui#3318). The read-only
- * branches below ignore it: list-mode and computed cells cannot be invalid
- * (the caller's `invalid` is false for both), and a text span is exactly
- * the wrapper the sweep forbids marking. */
- const renderCellInput = (
- c: GridColumn,
- colIdx: number,
- rowIdx: number,
- row: Row,
- invalid = false,
- ) => {
- const val = row?.[c.name];
- // A readonlyWhen-TRUE cell is locked: treat like the form-wide `disabled`.
- const locked = disabled || cellRules(c, row).readonly;
- // List (form-factor) mode → read-only at-a-glance display.
- if (isList) {
- if (c.type === 'lookup' && val != null && val !== '') {
- return (
- {}} readonly
- field={{ reference: c.reference, displayField: c.displayField, idField: c.idField } as any} />
- );
- }
- return (
-
- {displayText(c, val, displayLocale, currencyOf(c))}
-
- );
- }
- // Computed column → read-only, recomputed live, formatted.
- if (c.computed) {
- return (
-
- {displayText(c, val, displayLocale, currencyOf(c))}
-
- );
- }
- if (c.type === 'lookup') {
- return (
- setCellValue(rowIdx, c.name, v)}
- onSelectRecord={(rec: any) => applyLookupSelection(rowIdx, c, rec)}
- compact
- field={{ reference: c.reference, displayField: c.displayField, idField: c.idField, multiple: c.multiple, options: c.options, placeholder: '—' } as any}
- disabled={locked}
- // The published `error` slot, not a hand-rolled attribute: LookupField
- // already puts `aria-invalid` on its own focusable trigger from it.
- error={invalid ? requiredCellText(c) : undefined}
- />
- );
- }
- // File / image column → a real upload control in the cell (objectui#2360),
- // not a text input: chips for uploaded files + a compact picker button.
- if (c.type === 'file') {
- return (
- setCellValue(rowIdx, c.name, v)}
- multiple={c.multiple}
- accept={Array.isArray(c.accept) && c.accept.length > 0 ? c.accept.join(',') : undefined}
- disabled={locked}
- aria-label={c.label || c.name}
- data-cell={`${rowIdx}-${colIdx}`}
- // The published `error` slot, not a hand-rolled attribute — same
- // wiring as the lookup branch above: FileCell puts `aria-invalid` on
- // its own focusable picker button from it (objectui#5431, closing
- // the one cell type #3318 left out).
- error={invalid ? requiredCellText(c) : undefined}
- />
- );
- }
- // objectstack#36023 — the option list opens under the cell, searchable,
- // and a pick writes the value; the cell keeps showing the label meanwhile.
- if (c.type === 'select') {
- return (
- ({ value: String(o.value), label: o.label }))}
- value={val}
- onPick={(v) => setCell(rowIdx, c, v)}
- disabled={locked}
- invalid={invalid}
- label={c.label || c.name}
- onNavKeyDown={(e) => onCellKeyDown(e, rowIdx, colIdx)}
- data-cell={`${rowIdx}-${colIdx}`}
- />
- );
- }
- // The editable currency cell shows the SAME symbol its display face does
- // (objectui#10355) — `currencyAdornment`, never a default `¥`.
- const adornment = c.type === 'currency' ? currencyAdornment(c, currencyOf(c), displayLocale) : '';
- // A `date` or `datetime` cell holding a value written on a day that does
- // not exist (objectui#10474, objectui#10567): its control can paint that
- // only blank — the `date` control sanitises the verbatim day
- // `toDateInputValue` keeps, so it is handed `""` below, as the `datetime`
- // adapter already does — so the
- // control is marked invalid, its description naming the stored string.
- // Nothing is written until the user picks a new value — the same face
- // `DateField` / `DateTimeField` give it.
- const impossibleDay = (c.type === 'date' || c.type === 'datetime') && isImpossibleStoredDay(val);
- const noticeId = impossibleDay ? `${cellIdBase}-impossible-${rowIdx}-${colIdx}` : undefined;
- const impossibleText = impossibleDay
- ? t(c.type === 'date' ? 'fields.date.impossibleDay' : 'fields.dateTime.impossibleDay', { value: String(val) })
- : null;
- // objectstack#36023 — a date or date-time cell is still typed into, and
- // its calendar opens under the cell on arrival. The stored-day notice
- // reads at the top of that calendar, and stays the control's description
- // (out of sight in the cell, so the row keeps its height).
- if (c.type === 'date' || c.type === 'datetime') {
- return (
- <>
- onCellKeyDown(e, rowIdx, colIdx)}
- className={cn(GRID_CELL_CONTROL_CLASS, PHONE_TOUCH_HEIGHT)}
- nativeValue={c.type === 'date' ? (impossibleDay ? '' : toDateInputValue(val)) : toDateTimeInputValue(val)}
- onNativeChange={(next) => setCell(rowIdx, c, next)}
- notice={impossibleText}
- disabled={locked}
- />
- {impossibleDay && (
-
- {impossibleText}
-
- )}
- >
- );
- }
- // A text cell floats right over its neighbours while its text is longer
- // than the column (objectstack#36023); numbers and times keep their box.
- const CellInput = !c.type || c.type === 'text' ? GrowingCellInput : Input;
- return (
-
) : (
= ({
}
}),
);
- // The derived columns are what draw the line grid, so they land together
- // with its body (objectstack#36102): the collection stays on "Loading
- // columns…" until both are here, and the grid never mounts on its
- // loading placeholder. `preloadGridField` never rejects.
- await preloadGridField();
if (!cancelled) setResolvedEntries(out);
})();
return () => { cancelled = true; };
From eb10283083a14bed026d9ad123c8cd9745f02a25 Mon Sep 17 00:00:00 2001
From: Claude
Date: Sun, 22 Nov 2026 10:52:05 +0000
Subject: [PATCH 7/8] docs(console): the ui-components entry reads its
final-head re-measure
Re-read on the branch's final head, the chunk is still 346,403 and the
aggregate is within 3 bytes; the note no longer says no eager byte moved.
Claude-Session: https://claude.ai/code/session_01QsR2jV3scu6UYPb42n5okQ
Co-Authored-By: Claude
---
ui/scripts/check-eager-closure-budget.mjs | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/ui/scripts/check-eager-closure-budget.mjs b/ui/scripts/check-eager-closure-budget.mjs
index 552bc75ba31..02527ed011b 100644
--- a/ui/scripts/check-eager-closure-budget.mjs
+++ b/ui/scripts/check-eager-closure-budget.mjs
@@ -2499,8 +2499,8 @@ export const PER_CHUNK_GZIP_CEILINGS = Object.freeze({
// 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; the branch's later commits change no emitted
- // byte of the eager closure). Gzipped bytes:
+ // 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 |
// |-----------------------|-----------:|-----------:|-------:|
From 20b27d25997318ffac26ea46d7e1452c9e977b13 Mon Sep 17 00:00:00 2001
From: Claude
Date: Sun, 22 Nov 2026 11:42:24 +0000
Subject: [PATCH 8/8] docs(changeset): name the console and spec releases, and
say what the face pins
The console's dist is shaped by the new fields-grid group and the spec ships
the liveness ledger whose evidence path moved, so both take a patch entry.
The face sentence now says what the tests pin: a grid that showed the
placeholder never remounts the body on a later render.
Claude-Session: https://claude.ai/code/session_01QsR2jV3scu6UYPb42n5okQ
Co-Authored-By: Claude
---
.changeset/36102-grid-field-lazy-body.md | 6 +++++-
1 file changed, 5 insertions(+), 1 deletion(-)
diff --git a/.changeset/36102-grid-field-lazy-body.md b/.changeset/36102-grid-field-lazy-body.md
index 7effc314e2e..934a1234766 100644
--- a/.changeset/36102-grid-field-lazy-body.md
+++ b/.changeset/36102-grid-field-lazy-body.md
@@ -1,6 +1,8 @@
---
'@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
@@ -10,9 +12,11 @@ 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 keeps its rows and the focused cell when the body arrives.
+- **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.