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 ? ( - - - - - -
- {t('fields.grid.optionalColumns', { defaultValue: 'Optional columns' })} -
-
- {optionalColumns.map((c) => { - const id = `col-toggle-${c.name}`; - return ( - - ); - })} -
-
-
- ) : null; +} - // ── Read-only / view rendering ──────────────────────────────────────────── - if (readonly) { - return ( -
- {columnChooser &&
{columnChooser}
} -
- - - - - {columns.map((c) => ( - - ))} - - - - {rows.length === 0 ? ( - - - - ) : ( - rows.map((row, rowIdx) => ( - - - {columns.map((c) => ( - - ))} - - )) - )} - - {showTotal && ( - - - - - {columns.length - totalColIndex - 1 > 0 && ( - - - )} -
# - {c.label || c.name} - -
- {t('fields.grid.noItems', { defaultValue: 'No items' })} -
{rowIdx + 1} - {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)) - )} -
- {totalLabel} - - {total.toLocaleString(displayLocale)} - - )} -
-
-
- ); +/** + * 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 ( -
- {adornment && ( - {adornment} - )} - onCellKeyDown(e, rowIdx, colIdx)} - className={cn( - GRID_CELL_CONTROL_CLASS, - PHONE_TOUCH_HEIGHT, - adornment && 'pl-6', - isNumeric(c.type) && 'text-right tabular-nums', - )} - type={c.type === 'time' ? 'time' : isNumeric(c.type) ? 'number' : 'text'} - step={isNumeric(c.type) ? c.step ?? 'any' : undefined} - aria-label={c.label || c.name} - // `time` reads and writes `HH:mm[:ss]`, the stored shape, both ways; - // the date types read through their adapters above (objectui#3566). - value={val != null ? String(val) : ''} - onChange={(e) => setCell(rowIdx, c, e.target.value)} - disabled={locked} - /> -
- ); - }; - - // DOM pass-through (objectui#4857): the container carries the form renderer's - // id / aria-labelledby / aria-describedby, but NOT its `name` (DOM-legal on - // form controls only — the objectui#3291 leak) and NOT its `aria-invalid` - // (control-channel state; this grid reports validity per CELL with its own - // inline marks). `CheckboxesField`'s split, key for key. - const { - 'aria-invalid': _hostAriaInvalid, - name: _domName, - ...groupDomProps - } = toDomProps(props); - // The container answers `role="group"` only when a host actually NAMED it by - // IDREF (objectui#3961) — standalone rendering (a bare SDUI node) hands down - // no `aria-labelledby`, emits no role, and keeps its markup unchanged. - const isLabelledGroup = groupDomProps['aria-labelledby'] != null; - return ( -
- {columnChooser &&
{columnChooser}
} -
- - - - - {columns.map((c) => ( - - ))} - {hasRowActions && - - - {!isList && displayRows.length === 0 ? ( - - - - ) : isList && rows.length === 0 ? ( - - - - ) : ( - displayRows.map((row, rowIdx) => { - const isGhost = hasGhost && rowIdx === rows.length; - const reorderable = allowReorder && !isGhost && !isList; - return ( - { if (dragIndex.current != null) e.preventDefault(); }, - onDrop: (e: React.DragEvent) => { - e.preventDefault(); - if (dragIndex.current != null) { moveRow(dragIndex.current, rowIdx); dragIndex.current = null; } - }, - } - : {})} - > - - {columns.map((c, colIdx) => { - // Inline validation: a required, non-computed cell that's - // empty flags red in place. The "required" verdict honors - // a column's `requiredWhen` CEL rule (B2), evaluated - // against the row + parent header. - // - // The ghost row joins in only when the FORM said this - // grid failed while empty (objectui#3318) — see - // `hostFailedEmpty`. - const required = cellRules(c, row).required; - // objectstack#35816 — a new line waits for the host's - // word before it reads red; a stored line does not. - // objectstack#35940 — a line Add started on its defaults - // and nobody edited never reads red: the save skips it - // and says so, so there is nothing in it to fix. - const newRowWaits = - (newRowRequiredShown === false && !isGhost && !rowHasId(row)) || - isUntouchedNewRow(row); - const invalid = - (!isGhost || hostFailedEmpty) && - !newRowWaits && - !isList && - required && - !c.computed && - (row[c.name] == null || row[c.name] === ''); - return ( - - ); - })} - {hasRowActions && ( - - )} - - ); - }) - )} - - {showTotal && ( - - - - - {(columns.length - totalColIndex - 1 + (hasRowActions ? 1 : 0)) > 0 && ( - - - )} -
# - {c.label || c.name} - {c.required && !c.computed && *} - - } -
- {allowAdd - ? t('fields.grid.noItemsAddHint', { - label: addLabel, - defaultValue: 'No items yet — click “{{label}}” to begin.', - }) - : t('fields.grid.noItems', { defaultValue: 'No items' })} -
- {t('fields.grid.noItemsAddHint', { - label: cfg.addLabel || t('detail.add', { defaultValue: 'Add' }), - defaultValue: 'No items yet — click “{{label}}” to begin.', - })} -
- - {reorderable && ( - { dragIndex.current = rowIdx; }} - onDragEnd={() => { dragIndex.current = null; }} - className="cursor-grab text-muted-foreground/40 opacity-0 transition-opacity group-hover:opacity-100" - title={dragLabel} - aria-label={dragLabel} - data-testid={`line-items-drag-${rowIdx}`} - > - - - )} - {rowIdx + 1} - - - {renderCellInput(c, colIdx, rowIdx, row, invalid)} - -
- {!isGhost && showExpand && ( - - )} - {!isGhost && allowDuplicate && ( - - )} - {!isGhost && allowDelete && ( - - )} -
-
- {totalLabel} - - {total.toLocaleString(displayLocale)} - - )} -
-
- - {allowAdd && ( - - )} -
+ }> + + ); } diff --git a/ui/packages/fields/src/widgets/grid-field/GridFieldWidget.tsx b/ui/packages/fields/src/widgets/grid-field/GridFieldWidget.tsx new file mode 100644 index 00000000000..77b4694d82f --- /dev/null +++ b/ui/packages/fields/src/widgets/grid-field/GridFieldWidget.tsx @@ -0,0 +1,1596 @@ +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 { currencySymbol } from '../../currency.js'; +import { LookupField } from '../LookupField.js'; +import type { LookupAutofillByField } from '../lookupAutofill.js'; +import { FileCell } from '../FileField.js'; +import { toDateInputValue, toDateTimeInputValue, fromDateTimeInputValue, isImpossibleStoredDay } from '../nativeDateValue.js'; +import { useFieldTranslation } from '../useFieldTranslation.js'; +import { toDomProps } from '../toDomProps.js'; +import { PHONE_TOUCH_HEIGHT, PHONE_TOUCH_SQUARE } from '../touchTarget.js'; +import { toHostGroupProps } from '../toHostGroupProps.js'; +import { GRID_CELL_CONTROL_CLASS, GridDateCell, GridSelectCell, GrowingCellInput } from '../gridCellPanels.js'; +import { isImeKey } from '../imeKey.js'; +import { GRID_FIELD_RETIRED_KEYS, type GridFieldMetadata, type GridFieldRetiredKey } from '@object-ui/types'; +// The grid's pure half: the column type, the computed-cell evaluator, the +// lookup-pick patch and the row marks. They live beside the public face in +// `../GridField.tsx`, in the eager chunk, because `@object-ui/fields` exports +// them by name and they import nothing heavy (objectstack#36102). +import { + computeRow, + currencyOfColumn, + currencyWidth, + isUntouchedNewRow, + lookupAutofillPatch, + sumColumn, + UNTOUCHED_NEW_ROW, + type ColumnCurrencies, + type ColumnHelp, + type GridColumn, +} from '../GridField.js'; + +/** + * GridField / LineItemsField — editable child-grid ("line items") widget. + * + * ## Where this module sits (objectstack#36102) + * + * This is the widget BODY, and it is reached only through `import()`: the + * `GridField` / `LineItemsField` that `@object-ui/fields` exports by name are + * the small lazy face in `../GridField.tsx`, and the `grid` form-field loader + * imports this file through that face's one loader. ⛔ Do not import it + * statically from anything outside this directory and its tests: one static + * importer in the eager graph puts these bytes back on every console page + * load (`fields-grid` in `apps/console/vite.config.ts`, held to the module by + * `PER_CHUNK_MEMBERSHIP_CARVE_OUTS` in `scripts/check-eager-closure-budget.mjs`). + * + * ## Where the host's label and help text land, and why (objectui#4857) + * + * This widget forwarded nothing a host handed it, so the field's visible label + * 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)] + * ``` + * + * 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: + * + * - 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. + * + * 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'`. + * + * 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`). + */ + + +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 }; +} +/** 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; +} +export type GridFieldWidgetProps = FieldWidgetComponentProps & { + /** When provided, each row shows an "expand" button that opens the row in a + * full form (the host — e.g. MasterDetailForm — renders the drawer/modal and + * writes the edited values back). Lets a "fat" child be edited in a real form + * 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 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} +
+ ); +} + +/** 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; +} + +/** 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 `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. + */ +export function GridFieldWidget(props: GridFieldWidgetProps) { + const retired = retiredGridFieldKeysOf(props.field); + if (retired.length > 0) { + const message = retiredGridFieldKeysMessage((props.field as { name?: unknown } | undefined)?.name, retired); + return ; + } + return ; +} + +function GridFieldBody({ + value, + onChange, + field, + readonly, + disabled, + className, + error, + onRowExpand, + displayMode, + onAdd, + lookupAutofill, + columnCurrencies, + newRowValues, + newRowRequiredShown, + columnHelp, + ...props +}: GridFieldWidgetProps) { + // The field-level keys, read as `GridFieldMetadata` declares them and as + // nothing else, so a read of a key the type does not declare is a compile + // error here rather than a second, unpublished contract (objectui#11070 + // 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); + }, + [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); + } + }, + [focusCell, rows.length, allowAdd, isList, addRow], + ); + + /** + * 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; + }); + 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], + ); + + /** 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], + ); + 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 ? ( + + + + + +
+ {t('fields.grid.optionalColumns', { defaultValue: 'Optional columns' })} +
+
+ {optionalColumns.map((c) => { + const id = `col-toggle-${c.name}`; + return ( + + ); + })} +
+
+
+ ) : null; + + // ── Read-only / view rendering ──────────────────────────────────────────── + if (readonly) { + return ( +
+ {columnChooser &&
{columnChooser}
} +
+ + + + + {columns.map((c) => ( + + ))} + + + + {rows.length === 0 ? ( + + + + ) : ( + rows.map((row, rowIdx) => ( + + + {columns.map((c) => ( + + ))} + + )) + )} + + {showTotal && ( + + + + + {columns.length - totalColIndex - 1 > 0 && ( + + + )} +
# + {c.label || c.name} + +
+ {t('fields.grid.noItems', { defaultValue: 'No items' })} +
{rowIdx + 1} + {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)) + )} +
+ {totalLabel} + + {total.toLocaleString(displayLocale)} + + )} +
+
+
+ ); + } + + // ── 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 ( +
+ {adornment && ( + {adornment} + )} + onCellKeyDown(e, rowIdx, colIdx)} + className={cn( + GRID_CELL_CONTROL_CLASS, + PHONE_TOUCH_HEIGHT, + adornment && 'pl-6', + isNumeric(c.type) && 'text-right tabular-nums', + )} + type={c.type === 'time' ? 'time' : isNumeric(c.type) ? 'number' : 'text'} + step={isNumeric(c.type) ? c.step ?? 'any' : undefined} + aria-label={c.label || c.name} + // `time` reads and writes `HH:mm[:ss]`, the stored shape, both ways; + // the date types read through their adapters above (objectui#3566). + value={val != null ? String(val) : ''} + onChange={(e) => setCell(rowIdx, c, e.target.value)} + disabled={locked} + /> +
+ ); + }; + + // DOM pass-through (objectui#4857): the container carries the form renderer's + // id / aria-labelledby / aria-describedby, but NOT its `name` (DOM-legal on + // form controls only — the objectui#3291 leak) and NOT its `aria-invalid` + // (control-channel state; this grid reports validity per CELL with its own + // inline marks). `CheckboxesField`'s split, key for key. + const { + 'aria-invalid': _hostAriaInvalid, + name: _domName, + ...groupDomProps + } = toDomProps(props); + // The container answers `role="group"` only when a host actually NAMED it by + // IDREF (objectui#3961) — standalone rendering (a bare SDUI node) hands down + // no `aria-labelledby`, emits no role, and keeps its markup unchanged. + const isLabelledGroup = groupDomProps['aria-labelledby'] != null; + + return ( +
+ {columnChooser &&
{columnChooser}
} +
+ + + + + {columns.map((c) => ( + + ))} + {hasRowActions && + + + {!isList && displayRows.length === 0 ? ( + + + + ) : isList && rows.length === 0 ? ( + + + + ) : ( + displayRows.map((row, rowIdx) => { + const isGhost = hasGhost && rowIdx === rows.length; + const reorderable = allowReorder && !isGhost && !isList; + return ( + { if (dragIndex.current != null) e.preventDefault(); }, + onDrop: (e: React.DragEvent) => { + e.preventDefault(); + if (dragIndex.current != null) { moveRow(dragIndex.current, rowIdx); dragIndex.current = null; } + }, + } + : {})} + > + + {columns.map((c, colIdx) => { + // Inline validation: a required, non-computed cell that's + // empty flags red in place. The "required" verdict honors + // a column's `requiredWhen` CEL rule (B2), evaluated + // against the row + parent header. + // + // The ghost row joins in only when the FORM said this + // grid failed while empty (objectui#3318) — see + // `hostFailedEmpty`. + const required = cellRules(c, row).required; + // objectstack#35816 — a new line waits for the host's + // word before it reads red; a stored line does not. + // objectstack#35940 — a line Add started on its defaults + // and nobody edited never reads red: the save skips it + // and says so, so there is nothing in it to fix. + const newRowWaits = + (newRowRequiredShown === false && !isGhost && !rowHasId(row)) || + isUntouchedNewRow(row); + const invalid = + (!isGhost || hostFailedEmpty) && + !newRowWaits && + !isList && + required && + !c.computed && + (row[c.name] == null || row[c.name] === ''); + return ( + + ); + })} + {hasRowActions && ( + + )} + + ); + }) + )} + + {showTotal && ( + + + + + {(columns.length - totalColIndex - 1 + (hasRowActions ? 1 : 0)) > 0 && ( + + + )} +
# + {c.label || c.name} + {c.required && !c.computed && *} + + } +
+ {allowAdd + ? t('fields.grid.noItemsAddHint', { + label: addLabel, + defaultValue: 'No items yet — click “{{label}}” to begin.', + }) + : t('fields.grid.noItems', { defaultValue: 'No items' })} +
+ {t('fields.grid.noItemsAddHint', { + label: cfg.addLabel || t('detail.add', { defaultValue: 'Add' }), + defaultValue: 'No items yet — click “{{label}}” to begin.', + })} +
+ + {reorderable && ( + { dragIndex.current = rowIdx; }} + onDragEnd={() => { dragIndex.current = null; }} + className="cursor-grab text-muted-foreground/40 opacity-0 transition-opacity group-hover:opacity-100" + title={dragLabel} + aria-label={dragLabel} + data-testid={`line-items-drag-${rowIdx}`} + > + + + )} + {rowIdx + 1} + + + {renderCellInput(c, colIdx, rowIdx, row, invalid)} + +
+ {!isGhost && showExpand && ( + + )} + {!isGhost && allowDuplicate && ( + + )} + {!isGhost && allowDelete && ( + + )} +
+
+ {totalLabel} + + {total.toLocaleString(displayLocale)} + + )} +
+
+ + {allowAdd && ( + + )} +
+ ); +} diff --git a/ui/packages/fields/src/widgets/imeComposition-35996.test.tsx b/ui/packages/fields/src/widgets/imeComposition-35996.test.tsx index f4d61fb6220..0b9e9b6ccf0 100644 --- a/ui/packages/fields/src/widgets/imeComposition-35996.test.tsx +++ b/ui/packages/fields/src/widgets/imeComposition-35996.test.tsx @@ -33,7 +33,7 @@ import '@testing-library/jest-dom'; import { isImeKey as componentsIsImeKey } from '@object-ui/components'; import { isImeKey } from './imeKey'; -import { GridField } from './GridField'; +import { GridFieldWidget as GridField } from './grid-field/GridFieldWidget'; import { DatePickerField } from './date-picker/DatePickerField'; import { RecordPickerDialog } from './RecordPickerDialog'; import { getCellRenderer } from '../index'; diff --git a/ui/packages/plugin-form/src/LineItemsPanel.tsx b/ui/packages/plugin-form/src/LineItemsPanel.tsx index cd0e3330d84..e7f78d96360 100644 --- a/ui/packages/plugin-form/src/LineItemsPanel.tsx +++ b/ui/packages/plugin-form/src/LineItemsPanel.tsx @@ -26,7 +26,7 @@ import { CardTitle, cn, } from '@object-ui/components'; -import { LineItemsField, lookupAutofillByField, columnHelpByField, useBooleanValueLabel, type GridColumn } from '@object-ui/fields'; +import { LineItemsField, preloadGridField, lookupAutofillByField, columnHelpByField, useBooleanValueLabel, type GridColumn } from '@object-ui/fields'; import type { GridFieldMetadata } from '@object-ui/types'; import { createSafeTranslation, useLocalization } from '@object-ui/i18n'; import { useSchemaContext, useRecordContext, useFilterScope, useResolvedFilter, useDataInvalidation, usePrintPage, NonGridRowCeilingNote } from '@object-ui/react'; @@ -212,6 +212,9 @@ function describeRefusedRowLimit(authored: unknown, childObject: unknown): strin } export const LineItemsPanel: React.FC<{ schema: LineItemsPanelSchema }> = ({ schema }) => { + // The line grid's body loads on first use (objectstack#36102). Start it now, + // while the child schema is fetched, so the grid is there before its columns. + preloadGridField(); const ctx = useSchemaContext() as any; const { t } = useLineItemsTranslation(); // The session's word for a boolean value, which draws a hydrated `boolean` / diff --git a/ui/packages/plugin-form/src/MasterDetailForm.tsx b/ui/packages/plugin-form/src/MasterDetailForm.tsx index 798db9de4f4..c5af9e763f4 100644 --- a/ui/packages/plugin-form/src/MasterDetailForm.tsx +++ b/ui/packages/plugin-form/src/MasterDetailForm.tsx @@ -34,7 +34,7 @@ import React, { startTransition, useCallback, useContext, useEffect, useMemo, us import { createPortal } from 'react-dom'; import type { BatchTransactionOperation, DataSource, GridFieldMetadata, I18nLabel } from '@object-ui/types'; import { resolveAffordance, runBatchTransaction } from '@object-ui/core'; -import { isUntouchedNewRow, LineItemsField, lookupAutofillByField, columnHelpByField, UNTOUCHED_NEW_ROW, useBooleanValueLabel, type BooleanValueLabel, type ColumnHelp, type GridColumn, type LookupAutofillByField } from '@object-ui/fields'; +import { isUntouchedNewRow, LineItemsField, preloadGridField, lookupAutofillByField, columnHelpByField, UNTOUCHED_NEW_ROW, useBooleanValueLabel, type BooleanValueLabel, type ColumnHelp, type GridColumn, type LookupAutofillByField } from '@object-ui/fields'; import { Button, Card, CardContent, CardHeader, CardTitle, cn, toast } from '@object-ui/components'; import { formatDisplayNumber, @@ -1319,6 +1319,9 @@ export const MasterDetailForm: React.FC = ({ dataSource, className, }) => { + // The line grid's body loads on first use (objectstack#36102). Start it now, + // while the child schema is fetched, so the grid is there before its columns. + preloadGridField(); const rawDetails = schema.details || []; const isEdit = schema.mode === 'edit' && !!schema.recordId; // `title` / `submitText` / `cancelText` are `I18nLabel` (see the schema diff --git a/ui/packages/plugin-form/src/RecordBodyTableEditor.tsx b/ui/packages/plugin-form/src/RecordBodyTableEditor.tsx index 347ff290009..58ca321e26b 100644 --- a/ui/packages/plugin-form/src/RecordBodyTableEditor.tsx +++ b/ui/packages/plugin-form/src/RecordBodyTableEditor.tsx @@ -37,7 +37,7 @@ import React, { useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'; import type { BatchTransactionOperation, GridFieldMetadata } from '@object-ui/types'; import { resolveAffordance, type SchemaLike } from '@object-ui/core'; -import { LineItemsField, lookupAutofillByField, columnHelpByField, useBooleanValueLabel, type GridColumn } from '@object-ui/fields'; +import { LineItemsField, preloadGridField, lookupAutofillByField, columnHelpByField, useBooleanValueLabel, type GridColumn } from '@object-ui/fields'; import { cn } from '@object-ui/components'; import { useLocalization } from '@object-ui/i18n'; import { usePermissions } from '@object-ui/permissions'; @@ -207,6 +207,9 @@ const BODY_TABLE_EDIT_LIMIT = 500; * a part of the record page's edit state, never a standalone block. */ export const RecordBodyTableEditor: React.FC = ({ objectName, relationshipField, title }) => { + // The line grid's body loads on first use (objectstack#36102). Start it now, + // while the child schema is fetched, so the grid is there before its columns. + preloadGridField(); const session = useContext(RecordEditSessionContext); const record = useRecordContext(); // The record page's adapter, as its related lists read it. diff --git a/ui/scripts/__tests__/vite-ineffective-dynamic-imports.test.ts b/ui/scripts/__tests__/vite-ineffective-dynamic-imports.test.ts index 61ef9db1898..59ddd1dde70 100644 --- a/ui/scripts/__tests__/vite-ineffective-dynamic-imports.test.ts +++ b/ui/scripts/__tests__/vite-ineffective-dynamic-imports.test.ts @@ -155,7 +155,7 @@ describe('formatIneffectiveDynamicImportStandDown', () => { missing: [...DEFEATED_LAZY_FIELD_WIDGETS], }); expect(text).not.toContain('\n'); - expect(text).not.toContain('packages/fields/src/widgets/GridField.tsx'); + expect(text).not.toContain(DEFEATED_LAZY_FIELD_WIDGETS[0]); expect(text).toContain(`${DEFEATED_LAZY_FIELD_WIDGETS.length} did not fire`); }); }); diff --git a/ui/scripts/check-eager-closure-budget.mjs b/ui/scripts/check-eager-closure-budget.mjs index 31e68fa423f..f1ea2fac8c5 100644 --- a/ui/scripts/check-eager-closure-budget.mjs +++ b/ui/scripts/check-eager-closure-budget.mjs @@ -2839,6 +2839,11 @@ export const PER_CHUNK_MEMBERSHIP_CARVE_OUTS = Object.freeze({ // to being ABSENT from the eager closure. fields: Object.freeze([ Object.freeze({ subtree: 'src/widgets/date-picker', chunk: 'fields-date-picker' }), + // objectstack#36102: the line-item grid's body, which only + // `loadGridFieldWidget`'s `import()` reaches; the package entry exports its + // lazy face (`widgets/GridField.tsx`). Same rule as the row above: its chunk + // carries no ceiling, so it must stay ABSENT from the eager closure. + Object.freeze({ subtree: 'src/widgets/grid-field', chunk: 'fields-grid' }), ]), }); diff --git a/ui/scripts/vite-ineffective-dynamic-imports.ts b/ui/scripts/vite-ineffective-dynamic-imports.ts index 2cd07dcebee..bc6650505a4 100644 --- a/ui/scripts/vite-ineffective-dynamic-imports.ts +++ b/ui/scripts/vite-ineffective-dynamic-imports.ts @@ -17,7 +17,7 @@ import type { Plugin, ResolvedConfig, Rollup } from 'vite'; * into another chunk — the laziness is decoration: * * ``` - * [INEFFECTIVE_DYNAMIC_IMPORT] packages/fields/src/widgets/GridField.tsx is + * [INEFFECTIVE_DYNAMIC_IMPORT] packages/fields/src/widgets/VectorField.tsx is * dynamically imported by packages/fields/src/index.tsx but also statically * imported by packages/fields/src/index.tsx, dynamic import will not move * module into another chunk. @@ -188,7 +188,6 @@ export const DEFEATED_LAZY_FIELD_WIDGETS: readonly string[] = Object.freeze([ 'packages/fields/src/widgets/FilterConditionField.tsx', 'packages/fields/src/widgets/FormulaField.tsx', 'packages/fields/src/widgets/GeolocationField.tsx', - 'packages/fields/src/widgets/GridField.tsx', 'packages/fields/src/widgets/ImageCropperDialog.tsx', 'packages/fields/src/widgets/ImageField.tsx', 'packages/fields/src/widgets/LocationField.tsx', From 4ca78ed12cdfa413d9735033c67e88020b86bf3a Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 08:38:45 +0000 Subject: [PATCH 2/8] test(fields): pin the grid's lazy face; the derived-column forms wait for its body preloadGridField resolves once the body has loaded and never rejects, so the forms can drop it and a test at module scope can await it. MasterDetailForm and RecordBodyTableEditor land the derived columns together with the body. A live e2e watches both first-open forms for the loading placeholder. Claude-Session: https://claude.ai/code/session_01QsR2jV3scu6UYPb42n5okQ Co-Authored-By: Claude --- ui/e2e/live/master-detail.spec.ts | 87 ++++++++++++++++++- .../fields/src/widgets/GridField.test.tsx | 39 +++++++++ ui/packages/fields/src/widgets/GridField.tsx | 25 +++--- .../plugin-form/src/MasterDetailForm.tsx | 5 ++ .../src/ModalForm.untypedRepeater.test.tsx | 7 +- .../plugin-form/src/RecordBodyTableEditor.tsx | 6 +- .../masterDetailSectionMembers-8071.test.tsx | 7 +- ...riveMasterDetail.declaredSpelling.test.tsx | 7 +- 8 files changed, 167 insertions(+), 16 deletions(-) diff --git a/ui/e2e/live/master-detail.spec.ts b/ui/e2e/live/master-detail.spec.ts index 2d2a4bb5b72..086624caba8 100644 --- a/ui/e2e/live/master-detail.spec.ts +++ b/ui/e2e/live/master-detail.spec.ts @@ -1,5 +1,5 @@ import { test, expect, type APIRequestContext, type Page, type Response } from '@playwright/test'; -import { selectOption, fillLookup } from './helpers'; +import { selectOption, fillLookup, addLineItem } from './helpers'; /** * Live e2e for the master-detail entry form (showcase "New Project + Tasks"). @@ -145,3 +145,88 @@ test('Create with a task line stores the child referencing the parent', async ({ expect(child?.title).toBe('E2E Task A'); expect(child?.project).toBe(parentId); }); + +/** + * objectstack#36102 — the line-item grid's body left the console's eager chunk: + * `@object-ui/fields` exports a lazy face whose body loads through one + * `import()`, which the record forms start when they mount and wait for with + * the child schema they derive the columns from. On a form's FIRST open the + * grid must therefore mount on its body, never on its loading placeholder + * (`grid-field-loading`), and a cell the user is typing in must keep focus. + * + * The observer is installed before the document's first byte, so it sees every + * attach of the placeholder, however brief. Its control is the grid itself: the + * same observer must have seen `line-items` attach, or a zero count would only + * say the observer saw nothing. + */ +test.describe('the line-item grid on a form\'s first open (objectstack#36102)', () => { + const INVOICES = '/apps/showcase_app/showcase_invoice'; + + /** Count every attach of the placeholder and of the grid, from document start. */ + async function watchGridMounts(page: Page) { + await page.addInitScript(() => { + const seen = { placeholder: 0, grid: 0 }; + (window as unknown as { __gridMounts: typeof seen }).__gridMounts = seen; + const count = (node: Node) => { + if (!(node instanceof Element)) return; + seen.placeholder += node.matches('[data-testid="grid-field-loading"]') ? 1 : 0; + seen.placeholder += node.querySelectorAll('[data-testid="grid-field-loading"]').length; + seen.grid += node.matches('[data-testid="line-items"]') ? 1 : 0; + seen.grid += node.querySelectorAll('[data-testid="line-items"]').length; + }; + new MutationObserver((records) => { + for (const record of records) record.addedNodes.forEach(count); + }).observe(document, { childList: true, subtree: true }); + }); + } + + const gridMounts = (page: Page) => + page.evaluate(() => (window as unknown as { __gridMounts: { placeholder: number; grid: number } }).__gridMounts); + + /** Type into the first Description cell and check the cell kept focus and the text. */ + async function typeKeepsFocus(page: Page, scope: ReturnType) { + const cell = scope.locator('input[aria-label="Description"]').first(); + await cell.click(); + await cell.pressSequentially('first-open'); + // A beat for any late remount to land before it is checked. + await page.waitForTimeout(300); + await expect(cell).toBeFocused(); + await expect(cell).toHaveValue(/first-open$/); + } + + test('the New Invoice form draws its line grid on its body, and a typed cell keeps focus', async ({ page }) => { + await watchGridMounts(page); + await page.goto(INVOICES); + await page.getByTestId('object-view-new-button').first().click(); + const dialog = page.getByRole('dialog'); + const grid = dialog.getByTestId('line-items'); + await expect(grid).toBeVisible(); + + await addLineItem(page); + await typeKeepsFocus(page, grid); + + const mounts = await gridMounts(page); + expect(mounts.grid, 'the observer saw the grid attach (its control)').toBeGreaterThan(0); + expect(mounts.placeholder, 'the grid never mounted on its loading placeholder').toBe(0); + }); + + test('an invoice edit form draws its stored lines on the body, and a typed cell keeps focus', async ({ page, request }) => { + const res = await request.get(`${API}/api/v1/data/showcase_invoice?$top=50`); + expect(res.ok(), `GET showcase_invoice answered ${res.status()}`).toBe(true); + const body = await res.json(); + const invoice = (body?.records ?? body?.data ?? []).find((r: { name?: string }) => r.name === 'INV-1002'); + expect(invoice, 'the seeded draft invoice INV-1002 exists').toBeTruthy(); + + await watchGridMounts(page); + await page.goto(`${INVOICES}/record/${encodeURIComponent(invoice.id ?? invoice._id)}/edit`); + const grid = page.getByTestId('line-items'); + await expect(grid).toBeVisible(); + await expect(grid.locator('input[aria-label="Description"]').first()).not.toHaveValue(''); + + await typeKeepsFocus(page, grid); + + const mounts = await gridMounts(page); + expect(mounts.grid, 'the observer saw the grid attach (its control)').toBeGreaterThan(0); + expect(mounts.placeholder, 'the grid never mounted on its loading placeholder').toBe(0); + }); +}); diff --git a/ui/packages/fields/src/widgets/GridField.test.tsx b/ui/packages/fields/src/widgets/GridField.test.tsx index 851f0af9778..bfae23c9447 100644 --- a/ui/packages/fields/src/widgets/GridField.test.tsx +++ b/ui/packages/fields/src/widgets/GridField.test.tsx @@ -1293,3 +1293,42 @@ describe('cell faces that open under the cell (objectstack#36023)', () => { }); }); }); + +/** + * objectstack#36102 — `@object-ui/fields` exports a lazy face for the grid + * (`./GridField.tsx`); the body (`./grid-field/GridFieldWidget.tsx`) loads + * through one `import()`. Each case re-imports the face from a fresh module + * registry, so "before the body loaded" does not depend on case order. + */ +describe('GridField — the lazy face the package exports (objectstack#36102)', () => { + const lines = [{ description: 'Widget', amount: 5 }]; + + it('a mount before the body loads shows the placeholder, then the grid, and a later render keeps the focused cell', async () => { + vi.resetModules(); + const face = await import('./GridField'); + const view = render( {}} field={field} />); + expect(screen.getByTestId('grid-field-loading')).toBeTruthy(); + + const grid = await screen.findByTestId('line-items'); + expect(screen.queryByTestId('grid-field-loading')).toBeNull(); + const cell = grid.querySelector('input[aria-label="Description"]') as HTMLInputElement; + expect(cell.value).toBe('Widget'); + cell.focus(); + + // The body has loaded now. A render of the same mount must not swap the + // boundary for a direct render: that remounts the body and drops focus. + view.rerender( {}} field={field} />); + expect(cell.isConnected).toBe(true); + expect(document.activeElement).toBe(cell); + }); + + it('a mount after preloadGridField renders the grid in the same render, with no placeholder', async () => { + vi.resetModules(); + const face = await import('./GridField'); + await face.preloadGridField(); + render( {}} field={field} />); + expect(screen.queryByTestId('grid-field-loading')).toBeNull(); + const cell = screen.getByTestId('line-items').querySelector('input[aria-label="Description"]') as HTMLInputElement; + expect(cell.value).toBe('Widget'); + }); +}); diff --git a/ui/packages/fields/src/widgets/GridField.tsx b/ui/packages/fields/src/widgets/GridField.tsx index 34cd1ea412f..8881df46f34 100644 --- a/ui/packages/fields/src/widgets/GridField.tsx +++ b/ui/packages/fields/src/widgets/GridField.tsx @@ -30,9 +30,10 @@ import type { GridFieldWidgetProps } from './grid-field/GridFieldWidget.js'; * 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. + * draw line items (`@object-ui/plugin-form`) call it when they mount, and + * the two that derive a grid's columns from the child object's schema + * (`MasterDetailForm`, `RecordBodyTableEditor`) also wait for it together + * with that schema, so their grid never mounts on the placeholder. * - The pure helpers below stay in this file, in the eager chunk, because the * entry exports them by name and they import nothing heavy. * @@ -409,14 +410,18 @@ export function loadGridFieldWidget(): Promise { /** * 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. + * where a form that may draw line items mounts; idempotent. The promise + * settles once the body has loaded, so a caller that must render in the same + * tick (a test at module scope) can await it. ⛔ It never rejects, so a caller + * may drop it: a failed preload is reported by the grid's own render, which + * asks again and hands a second failure to the nearest error boundary, where + * it can be seen. */ -export function preloadGridField(): void { - loadGridFieldWidget().catch(() => { - // Reported by the render that needs the body; see above. - }); +export function preloadGridField(): Promise { + return loadGridFieldWidget().then( + () => undefined, + () => undefined, + ); } const LazyGridFieldWidget = React.lazy(() => diff --git a/ui/packages/plugin-form/src/MasterDetailForm.tsx b/ui/packages/plugin-form/src/MasterDetailForm.tsx index c5af9e763f4..9613ed82502 100644 --- a/ui/packages/plugin-form/src/MasterDetailForm.tsx +++ b/ui/packages/plugin-form/src/MasterDetailForm.tsx @@ -1589,6 +1589,11 @@ export const MasterDetailForm: React.FC = ({ } }), ); + // 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; }; diff --git a/ui/packages/plugin-form/src/ModalForm.untypedRepeater.test.tsx b/ui/packages/plugin-form/src/ModalForm.untypedRepeater.test.tsx index dd69e1b63ec..875ae9481d1 100644 --- a/ui/packages/plugin-form/src/ModalForm.untypedRepeater.test.tsx +++ b/ui/packages/plugin-form/src/ModalForm.untypedRepeater.test.tsx @@ -29,9 +29,14 @@ import { describe, it, expect, vi } from 'vitest'; import { render, waitFor, fireEvent, screen, act } from '@testing-library/react'; import React from 'react'; -import { registerAllFields, GridField, resolveFormWidgetType } from '@object-ui/fields'; +import { registerAllFields, GridField, preloadGridField, resolveFormWidgetType } from '@object-ui/fields'; import { ModalForm } from './ModalForm'; +// The line grid renders behind `@object-ui/fields`' lazy face (objectstack#36102); +// load its body before the first render, as the record forms' mount-time +// preload does in the console. +await preloadGridField(); + registerAllFields(); const ROWS = [ diff --git a/ui/packages/plugin-form/src/RecordBodyTableEditor.tsx b/ui/packages/plugin-form/src/RecordBodyTableEditor.tsx index 58ca321e26b..6c569ced429 100644 --- a/ui/packages/plugin-form/src/RecordBodyTableEditor.tsx +++ b/ui/packages/plugin-form/src/RecordBodyTableEditor.tsx @@ -234,8 +234,10 @@ export const RecordBodyTableEditor: React.FC = ({ ob useEffect(() => { let cancelled = false; if (!dataSource || typeof dataSource.getObjectSchema !== 'function') return; - Promise.resolve(dataSource.getObjectSchema(objectName)) - .then((s: any) => { if (!cancelled) setChildSchema(s ?? { fields: {} }); }) + // The child schema is what draws the line grid, so it lands together with + // the grid's body (objectstack#36102); `preloadGridField` never rejects. + Promise.all([dataSource.getObjectSchema(objectName), preloadGridField()]) + .then(([s]: [any, void]) => { if (!cancelled) setChildSchema(s ?? { fields: {} }); }) .catch(() => { if (!cancelled) setLoadFailed(true); }); return () => { cancelled = true; }; }, [dataSource, objectName]); diff --git a/ui/packages/plugin-form/src/__tests__/masterDetailSectionMembers-8071.test.tsx b/ui/packages/plugin-form/src/__tests__/masterDetailSectionMembers-8071.test.tsx index 62c50c56527..580b3bb963c 100644 --- a/ui/packages/plugin-form/src/__tests__/masterDetailSectionMembers-8071.test.tsx +++ b/ui/packages/plugin-form/src/__tests__/masterDetailSectionMembers-8071.test.tsx @@ -86,9 +86,14 @@ import { describe, it, expect, vi } from 'vitest'; import { render, waitFor } from '@testing-library/react'; import React from 'react'; -import { registerAllFields } from '@object-ui/fields'; +import { registerAllFields, preloadGridField } from '@object-ui/fields'; import { MasterDetailForm } from '../MasterDetailForm'; +// The line grid renders behind `@object-ui/fields`' lazy face (objectstack#36102); +// load its body before the first render, as the record forms' mount-time +// preload does in the console. +await preloadGridField(); + registerAllFields(); /** Parent object — three text fields, declared in this order. */ diff --git a/ui/packages/plugin-form/src/deriveMasterDetail.declaredSpelling.test.tsx b/ui/packages/plugin-form/src/deriveMasterDetail.declaredSpelling.test.tsx index 1e462baabbb..93f1cfe784d 100644 --- a/ui/packages/plugin-form/src/deriveMasterDetail.declaredSpelling.test.tsx +++ b/ui/packages/plugin-form/src/deriveMasterDetail.declaredSpelling.test.tsx @@ -26,10 +26,15 @@ import { describe, it, expect } from 'vitest'; import { render, screen } from '@testing-library/react'; import React from 'react'; -import { GridField } from '@object-ui/fields'; +import { GridField, preloadGridField } from '@object-ui/fields'; import { deriveColumns, hydrateColumns, deriveDetail } from './deriveMasterDetail'; import { en } from '@object-ui/i18n'; +// The line grid renders behind `@object-ui/fields`' lazy face (objectstack#36102); +// load its body before the first render, as the record forms' mount-time +// preload does in the console. +await preloadGridField(); + /** The `en` session's word for a boolean value: what `useBooleanValueLabel` * (`@object-ui/fields`) draws under `en`. The derive functions require one * (objectui#12924). */ From eaad4b9214494a344b8449397dd1a77c74687eb7 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 09:03:38 +0000 Subject: [PATCH 3/8] perf(console): lower the ui-components ceiling and baseline by the 5,960 bytes GridField took out Two console builds of one tree (b3bcfefc vs 4ca78ed1): ui-components 352,359 -> 346,399 gzipped, aggregate -5,880, the same 105 eager chunks. The two entries that called this card a payback now call it a follow-up. Claude-Session: https://claude.ai/code/session_01QsR2jV3scu6UYPb42n5okQ Co-Authored-By: Claude --- .changeset/36102-grid-field-lazy-body.md | 18 ++++++ .../check-eager-closure-budget.test.ts | 5 +- ui/scripts/check-eager-closure-budget.mjs | 60 +++++++++++++++---- 3 files changed, 72 insertions(+), 11 deletions(-) create mode 100644 .changeset/36102-grid-field-lazy-body.md diff --git a/.changeset/36102-grid-field-lazy-body.md b/.changeset/36102-grid-field-lazy-body.md new file mode 100644 index 00000000000..7effc314e2e --- /dev/null +++ b/.changeset/36102-grid-field-lazy-body.md @@ -0,0 +1,18 @@ +--- +'@object-ui/fields': patch +'@object-ui/plugin-form': patch +--- + +perf(fields): the line-item grid's body loads on first use, and the console's first load no longer carries it + +Clause-②: yes (widening) +Metadata-protocol: none + +The line-item grid (the `grid` field and the line items of a master-detail form) was the largest field widget in the console's first-load bytes, though only a form with line items draws it. Its body now loads the first time a grid is drawn, or earlier, when a form that draws line items mounts. + +- **The same two components.** `GridField` and `LineItemsField` keep their names and their props. They now render the grid's body once it has loaded; a grid mounted before that shows a small busy placeholder until it arrives. A grid mounted after the body loaded renders it directly, and a grid that showed the placeholder keeps its rows and the focused cell when the body arrives. +- **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. + +A host that renders `GridField` or `LineItemsField` itself and needs the grid in its first render calls `preloadGridField()` earlier and waits for it, as the record forms do. No metadata key, value or default changes. diff --git a/ui/scripts/__tests__/check-eager-closure-budget.test.ts b/ui/scripts/__tests__/check-eager-closure-budget.test.ts index 17c362401b6..bccdff08d13 100644 --- a/ui/scripts/__tests__/check-eager-closure-budget.test.ts +++ b/ui/scripts/__tests__/check-eager-closure-budget.test.ts @@ -1283,7 +1283,10 @@ describe('chunk membership (objectui#9345)', () => { expect(PER_CHUNK_MEMBERSHIP.framework).toContain('types'); expect(PER_CHUNK_MEMBERSHIP_CARVE_OUTS).toEqual({ types: [{ subtree: 'src/zod', chunk: 'types-zod' }], - fields: [{ subtree: 'src/widgets/date-picker', chunk: 'fields-date-picker' }], + fields: [ + { subtree: 'src/widgets/date-picker', chunk: 'fields-date-picker' }, + { subtree: 'src/widgets/grid-field', chunk: 'fields-grid' }, + ], }); }); diff --git a/ui/scripts/check-eager-closure-budget.mjs b/ui/scripts/check-eager-closure-budget.mjs index f1ea2fac8c5..1f914759446 100644 --- a/ui/scripts/check-eager-closure-budget.mjs +++ b/ui/scripts/check-eager-closure-budget.mjs @@ -2428,11 +2428,10 @@ export const PER_CHUNK_GZIP_CEILINGS = Object.freeze({ // (`GrowingCellInput`), so a form's line items edit in the cell the way a // list grid does (objectstack#36023 S5). The other ~5.4 KB are SHARED // headroom (355,000 − 349,448 = 5,552 once S5 lands) so the next form-field - // PR does not bounce at once, ⛔ not a budget for a new component group. They - // come back down when the follow-up card the ruling names takes GridField - // out of the eager chunk (it is `import()`ed but also statically exported, - // `packages/fields/src/index.tsx`): re-measure then and lower both numbers - // together. ⛔ Not moved: MAX_EAGER_CLOSURE_GZIP_BYTES (it passes on both + // PR does not bounce at once, ⛔ not a budget for a new component group. The + // card the ruling names (objectstack#36102, GridField out of the eager chunk) + // is a follow-up, not a payback; lower both numbers by the bytes removed. + // ⛔ Not moved: MAX_EAGER_CLOSURE_GZIP_BYTES (it passes on both // builds), BASELINE, REGRESSION_THIS_GATE_MUST_CATCH_BYTES and the other // per-chunk rows. No exemption was added and no import was made lazy. The // headroom `pnpm check:eager-closure` prints on YOUR build is the figure in @@ -2473,9 +2472,8 @@ export const PER_CHUNK_GZIP_CEILINGS = Object.freeze({ // WHAT THE BYTES BUY: SHARED headroom, so form and field PRs stop being // ejected from the queue on this line one at a time, ⛔ not a budget for a // new component group: a whole group still belongs behind a lazy boundary. - // ⭐ PAYBACK: objectstack#36102 takes GridField out of the eager chunk (it is - // `import()`ed but also statically exported, `packages/fields/src/index.tsx`); - // re-measure when it lands. + // objectstack#36102 (GridField out of the eager chunk) is a follow-up, not a + // payback; lower both numbers by the bytes removed. // // WHAT MOVED WITH IT, read from "Raising one" above and the two constraints // it names as checked: this ceiling passes on its baseline below, and @@ -2489,7 +2487,44 @@ export const PER_CHUNK_GZIP_CEILINGS = Object.freeze({ // either: MAX_EAGER_CLOSURE_GZIP_BYTES (it passes on both builds), BASELINE, // REGRESSION_THIS_GATE_MUST_CATCH_BYTES and the other per-chunk rows. No // exemption was added and no import was made lazy. - 'ui-components': 451_100, + // + // ⭐ LOWERED (2026-11-22), from 451,100 by 5,960 bytes, to 445,140, by + // objectstack#36102, the follow-up ruling 7063116595 names (GridField out of + // the eager chunk; seat note 7064483594 on that card, on ruling 7063869131: + // lower the ceiling and baseline by the bytes taken out, no more). Its + // baseline below moved by the same amount, which keeps the + // ceiling-minus-baseline gap this key carried (185,163). + // + // WHAT THE BYTES ARE — one container, one instrument: `CI=true pnpm exec + // turbo run build --filter=@object-ui/console...`, reading + // `apps/console/dist/eager-closure.json`, twice on one tree: `main` at + // `b3bcfefc` alone, then the same `main` with this change (`4ca78ed1`, the + // branch head, whose only console build inputs are this change). Gzipped + // bytes: + // + // | chunk | `b3bcfefc` | `4ca78ed1` | delta | + // |-----------------------|-----------:|-----------:|-------:| + // | `vendor-objectstack` | 674,662 | 674,662 | 0 | + // | `i18n-locale-en` | 66,785 | 66,785 | 0 | + // | `framework` | 88,559 | 88,559 | 0 | + // | `ui-components` | 352,359 | 346,399 | −5,960 | + // | ⇒ aggregate | 1,875,902 | 1,870,022 | −5,880 | + // + // The same 105 eager chunks by name in both builds (2,577 -> 2,578 chunks in + // all: the new one is `fields-grid`, lazy); besides this one, none moved by + // more than 26 bytes (`index` +26). Raw minified bytes of this chunk: + // 1,309,110 -> 1,289,858 (−19,252). + // + // WHAT LEFT: the line-item grid's body, now + // `packages/fields/src/widgets/grid-field/GridFieldWidget.tsx` in the lazy + // `fields-grid` chunk (20,374 raw bytes), reached only through + // `loadGridFieldWidget`'s `import()`. The package entry exports the small + // lazy face in `widgets/GridField.tsx` under the same names, and the pure + // helpers it exports stay here. ⛔ Not moved: MAX_EAGER_CLOSURE_GZIP_BYTES, + // BASELINE, REGRESSION_THIS_GATE_MUST_CATCH_BYTES and the other per-chunk + // rows. No exemption was added. The headroom `pnpm check:eager-closure` + // prints on YOUR build is the figure in force, ⛔ not this one. + 'ui-components': 445_140, }); /** @@ -2710,7 +2745,12 @@ export const PER_CHUNK_BASELINE = Object.freeze({ // (2026-11-21, ruling 7063869131 on objectstack#36023): a ruled raise widens // the gap rather than keeping it (the entry on that key of // PER_CHUNK_GZIP_CEILINGS), so this is again `bbf6b02d9`'s reading. - 'ui-components': 265_937, + // + // Moved with its ceiling (2026-11-22, objectstack#36102), from 265,937 by + // the same −5,960 bytes GridField's body took out (the entry on that key of + // PER_CHUNK_GZIP_CEILINGS), which keeps the ceiling-minus-baseline gap this + // key carried. ⚠️ So this is no longer one build's reading. + 'ui-components': 259_977, }); /** From 3c422050fe9d96588a6d9894b5edeefde4bdac7d Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 09:06:46 +0000 Subject: [PATCH 4/8] refactor(fields): the grid's lazy face is GridField.ts, so the body reads as a move The widget body that was widgets/GridField.tsx now shows as a rename into grid-field/GridFieldWidget.tsx; the face and the pure helpers are a JSX-free GridField.ts that every import of ./GridField.js still reaches. Path notes and the liveness evidence for lookupAutofillPatch follow it. Claude-Session: https://claude.ai/code/session_01QsR2jV3scu6UYPb42n5okQ Co-Authored-By: Claude --- packages/spec/liveness/field.json | 2 +- ui/apps/console/vite.config.ts | 2 +- ...ields-date-widget-convention-8194.test.tsx | 4 +-- ui/packages/fields/src/index.tsx | 2 +- ui/packages/fields/src/requiredWhenPrompt.ts | 2 +- .../fields/src/widgets/GridField.test.tsx | 2 +- .../widgets/{GridField.tsx => GridField.ts} | 27 ++++++++++--------- .../widgets/grid-field/GridFieldWidget.tsx | 4 +-- ui/scripts/check-eager-closure-budget.mjs | 4 +-- 9 files changed, 25 insertions(+), 24 deletions(-) rename ui/packages/fields/src/widgets/{GridField.tsx => GridField.ts} (97%) diff --git a/packages/spec/liveness/field.json b/packages/spec/liveness/field.json index 5f37d85809c..d2ae6891b7a 100644 --- a/packages/spec/liveness/field.json +++ b/packages/spec/liveness/field.json @@ -398,7 +398,7 @@ "status": "live", "verifiedAt": "2026-10-31", "evidenceScope": "in-repo", - "evidence": "ui/packages/fields/src/widgets/lookupAutofill.ts#declaredLookupAutofillPatch (the one fill rule: each target from the picked record's source, filled only while empty or still holding the earlier pick's value unless `overwrite: true`); ui/packages/fields/src/widgets/LookupField.tsx#fillDeclaredTargets (the record form: every single-value pick path, popover, keyboard, quick-create and the browse-all dialog, reads the field's pairs and writes through the host's `onAutofill`); ui/packages/components/src/renderers/form/form.tsx#LOOKUP_AUTOFILL_WIDGET_TYPES (the form renderer hands a lookup its `onAutofill` writer, `form.setValue` as an edit); ui/packages/fields/src/widgets/GridField.tsx#lookupAutofillPatch (the line-item grid: the declared pair fills under the same rule and takes its target out of the same-named `autofill` copy), its pairs handed over by ui/packages/plugin-form/src/MasterDetailForm.tsx#lookupAutofill and ui/packages/plugin-form/src/LineItemsPanel.tsx#lineLookupAutofill through ui/packages/fields/src/widgets/lookupAutofill.ts#lookupAutofillByField; authoring doors unchanged: packages/spec/src/data/field.zod.ts#lookupAutofill, packages/spec/src/data/object.zod.ts#refuseDishonestLookupAutofill, packages/spec/src/stack.zod.ts#collectLookupAutofillErrors", + "evidence": "ui/packages/fields/src/widgets/lookupAutofill.ts#declaredLookupAutofillPatch (the one fill rule: each target from the picked record's source, filled only while empty or still holding the earlier pick's value unless `overwrite: true`); ui/packages/fields/src/widgets/LookupField.tsx#fillDeclaredTargets (the record form: every single-value pick path, popover, keyboard, quick-create and the browse-all dialog, reads the field's pairs and writes through the host's `onAutofill`); ui/packages/components/src/renderers/form/form.tsx#LOOKUP_AUTOFILL_WIDGET_TYPES (the form renderer hands a lookup its `onAutofill` writer, `form.setValue` as an edit); ui/packages/fields/src/widgets/GridField.ts#lookupAutofillPatch (the line-item grid: the declared pair fills under the same rule and takes its target out of the same-named `autofill` copy), its pairs handed over by ui/packages/plugin-form/src/MasterDetailForm.tsx#lookupAutofill and ui/packages/plugin-form/src/LineItemsPanel.tsx#lineLookupAutofill through ui/packages/fields/src/widgets/lookupAutofill.ts#lookupAutofillByField; authoring doors unchanged: packages/spec/src/data/field.zod.ts#lookupAutofill, packages/spec/src/data/object.zod.ts#refuseDishonestLookupAutofill, packages/spec/src/stack.zod.ts#collectLookupAutofillErrors", "note": "LIVE — read by the record form and the line-item grid on a pick. Pinned end to end by ui/packages/plugin-form/src/ObjectForm.lookupAutofill-28245.test.tsx (an empty target fills and is saved, a typed value is kept, `overwrite: true` replaces, an earlier pick's value is replaced, the browse-all dialog fills too, a lookup without the key fills nothing) and ui/packages/fields/src/widgets/GridField.lookupAutofill-28245.test.tsx (the same rule in a grid row, the declared target out of the same-named copy, a stored line's own value kept). Bound: a master-detail collection whose relationship and every column are authored loads no child schema, so its grid fills only the same-named copy. PRODUCER: HotCRM's quote line item (product lookup, `unit_price` from the product's `list_price`).", "children": { "target": { diff --git a/ui/apps/console/vite.config.ts b/ui/apps/console/vite.config.ts index 9d539987423..52f948a9c7b 100644 --- a/ui/apps/console/vite.config.ts +++ b/ui/apps/console/vite.config.ts @@ -1513,7 +1513,7 @@ export default defineConfig({ // 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 + // `widgets/GridField.ts`: the `GridField` / `LineItemsField` the // package exports by name are the small lazy face in that file, so // the entry's named export no longer makes the body a static // dependency of the eager graph. Without this group `ui-components` 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 151e1514560..103c3791ff3 100644 --- a/ui/packages/fields/src/__tests__/fields-date-widget-convention-8194.test.tsx +++ b/ui/packages/fields/src/__tests__/fields-date-widget-convention-8194.test.tsx @@ -23,11 +23,11 @@ * That yields SIX bare no-bag sites, two more than the card's four: * * 1. `widgets/DateField.tsx` readonly `date` widget ← fixed - * 2. `widgets/GridField.tsx` sub-grid `date` column ← fixed + * 2. `widgets/grid-field/GridFieldWidget.tsx` sub-grid `date` column ← fixed * 3. `widgets/FormulaField.tsx` `returnType: 'date'` ← fixed * 4. `widgets/lookupColumnDisplay.tsx` the `$date` fallback ← fixed * 5. `widgets/DateField`'s sibling `DateTimeField.tsx` readonly ← NOT - * 6. `widgets/GridField.tsx`'s `datetime`/`time` branch ← NOT + * 6. `widgets/grid-field/GridFieldWidget.tsx`'s `datetime`/`time` branch ← NOT * * 5 and 6 are DATETIME faces. Their one home is `formatDateTime`, which has * its own face vocabulary (`'compact'` from objectui#7443 versus the verbose diff --git a/ui/packages/fields/src/index.tsx b/ui/packages/fields/src/index.tsx index ec5a486ecf3..971c96fc30e 100644 --- a/ui/packages/fields/src/index.tsx +++ b/ui/packages/fields/src/index.tsx @@ -5504,7 +5504,7 @@ export * from './widgets/ObjectField.js'; export * from './widgets/VectorField.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`. +// pure helpers beside them are eager. See `widgets/GridField.ts`. export { evalArith, lookupAutofillPatch, computeRow, GridField, LineItemsField, preloadGridField, UNTOUCHED_NEW_ROW, isUntouchedNewRow, columnHelpByField } from './widgets/GridField.js'; export type { ColumnCurrencies, ColumnHelp } from './widgets/GridField.js'; export type { GridColumn } from './widgets/GridField.js'; diff --git a/ui/packages/fields/src/requiredWhenPrompt.ts b/ui/packages/fields/src/requiredWhenPrompt.ts index 2600a334aa3..d072c4cee09 100644 --- a/ui/packages/fields/src/requiredWhenPrompt.ts +++ b/ui/packages/fields/src/requiredWhenPrompt.ts @@ -25,7 +25,7 @@ * The verdict comes from `@object-ui/core`'s {@link resolveFieldRuleState} — * the SAME function the record form (`components/renderers/form/form.tsx`), * the wizard (`plugin-form/WizardForm.tsx`) and the line-item grid - * (`fields/widgets/GridField.tsx`) resolve `visibleWhen`/`readonlyWhen`/ + * (`fields/widgets/grid-field/GridFieldWidget.tsx`) resolve `visibleWhen`/`readonlyWhen`/ * `requiredWhen` with, which in turn delegates to `@objectstack/formula`'s * `ExpressionEngine`. That is deliberate and load-bearing: the prompt and the * server's enforcement must reach the identical verdict, and a second diff --git a/ui/packages/fields/src/widgets/GridField.test.tsx b/ui/packages/fields/src/widgets/GridField.test.tsx index bfae23c9447..f1bfbfc24d1 100644 --- a/ui/packages/fields/src/widgets/GridField.test.tsx +++ b/ui/packages/fields/src/widgets/GridField.test.tsx @@ -1296,7 +1296,7 @@ describe('cell faces that open under the cell (objectstack#36023)', () => { /** * objectstack#36102 — `@object-ui/fields` exports a lazy face for the grid - * (`./GridField.tsx`); the body (`./grid-field/GridFieldWidget.tsx`) loads + * (`./GridField.ts`); the body (`./grid-field/GridFieldWidget.tsx`) loads * through one `import()`. Each case re-imports the face from a fresh module * registry, so "before the body loaded" does not depend on case order. */ diff --git a/ui/packages/fields/src/widgets/GridField.tsx b/ui/packages/fields/src/widgets/GridField.ts similarity index 97% rename from ui/packages/fields/src/widgets/GridField.tsx rename to ui/packages/fields/src/widgets/GridField.ts index 8881df46f34..2e286b33ebd 100644 --- a/ui/packages/fields/src/widgets/GridField.tsx +++ b/ui/packages/fields/src/widgets/GridField.ts @@ -1,3 +1,6 @@ +// A `.ts` file, JSX-free: the widget body that used to be `GridField.tsx` moved +// to `./grid-field/GridFieldWidget.tsx`, and every import of `./GridField.js` +// still lands here (objectstack#36102). import React from 'react'; import type { InlineGridColumn } from '@objectstack/spec/data'; import { resolveFieldCurrency, currencyFractionDigits } from '../currency.js'; @@ -433,14 +436,12 @@ const LazyGridFieldWidget = React.lazy(() => * grid's header height, marked busy, so the form does not jump when the table * replaces it. */ -function GridFieldLoading() { - return ( -
- ); +function GridFieldLoading(): React.ReactElement { + return React.createElement('div', { + className: 'min-h-10 w-full rounded-md border border-dashed', + 'aria-busy': 'true', + 'data-testid': 'grid-field-loading', + }); } /** @@ -453,12 +454,12 @@ export function GridField(props: GridFieldWidgetProps): React.ReactElement { const [loadedAtMount] = React.useState(() => gridFieldWidgetModule); if (loadedAtMount) { const { GridFieldWidget } = loadedAtMount; - return ; + return React.createElement(GridFieldWidget, props); } - return ( - }> - - + return React.createElement( + React.Suspense, + { fallback: React.createElement(GridFieldLoading) }, + React.createElement(LazyGridFieldWidget, props), ); } diff --git a/ui/packages/fields/src/widgets/grid-field/GridFieldWidget.tsx b/ui/packages/fields/src/widgets/grid-field/GridFieldWidget.tsx index 77b4694d82f..e23f10e5198 100644 --- a/ui/packages/fields/src/widgets/grid-field/GridFieldWidget.tsx +++ b/ui/packages/fields/src/widgets/grid-field/GridFieldWidget.tsx @@ -31,7 +31,7 @@ import { isImeKey } from '../imeKey.js'; import { GRID_FIELD_RETIRED_KEYS, type GridFieldMetadata, type GridFieldRetiredKey } from '@object-ui/types'; // The grid's pure half: the column type, the computed-cell evaluator, the // lookup-pick patch and the row marks. They live beside the public face in -// `../GridField.tsx`, in the eager chunk, because `@object-ui/fields` exports +// `../GridField.ts`, in the eager chunk, because `@object-ui/fields` exports // them by name and they import nothing heavy (objectstack#36102). import { computeRow, @@ -53,7 +53,7 @@ import { * * This is the widget BODY, and it is reached only through `import()`: the * `GridField` / `LineItemsField` that `@object-ui/fields` exports by name are - * the small lazy face in `../GridField.tsx`, and the `grid` form-field loader + * the small lazy face in `../GridField.ts`, and the `grid` form-field loader * imports this file through that face's one loader. ⛔ Do not import it * statically from anything outside this directory and its tests: one static * importer in the eager graph puts these bytes back on every console page diff --git a/ui/scripts/check-eager-closure-budget.mjs b/ui/scripts/check-eager-closure-budget.mjs index 1f914759446..d13a599ee23 100644 --- a/ui/scripts/check-eager-closure-budget.mjs +++ b/ui/scripts/check-eager-closure-budget.mjs @@ -2519,7 +2519,7 @@ export const PER_CHUNK_GZIP_CEILINGS = Object.freeze({ // `packages/fields/src/widgets/grid-field/GridFieldWidget.tsx` in the lazy // `fields-grid` chunk (20,374 raw bytes), reached only through // `loadGridFieldWidget`'s `import()`. The package entry exports the small - // lazy face in `widgets/GridField.tsx` under the same names, and the pure + // lazy face in `widgets/GridField.ts` under the same names, and the pure // helpers it exports stay here. ⛔ Not moved: MAX_EAGER_CLOSURE_GZIP_BYTES, // BASELINE, REGRESSION_THIS_GATE_MUST_CATCH_BYTES and the other per-chunk // rows. No exemption was added. The headroom `pnpm check:eager-closure` @@ -2881,7 +2881,7 @@ export const PER_CHUNK_MEMBERSHIP_CARVE_OUTS = Object.freeze({ Object.freeze({ subtree: 'src/widgets/date-picker', chunk: 'fields-date-picker' }), // objectstack#36102: the line-item grid's body, which only // `loadGridFieldWidget`'s `import()` reaches; the package entry exports its - // lazy face (`widgets/GridField.tsx`). Same rule as the row above: its chunk + // lazy face (`widgets/GridField.ts`). Same rule as the row above: its chunk // carries no ceiling, so it must stay ABSENT from the eager closure. Object.freeze({ subtree: 'src/widgets/grid-field', chunk: 'fields-grid' }), ]), From e581a9a5e634410d30316d968ad1e98cd8b615d4 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 09:33:18 +0000 Subject: [PATCH 5/8] perf(console): re-read the ui-components drop on the final tree (-5,956) and pin the ceiling to it Claude-Session: https://claude.ai/code/session_01QsR2jV3scu6UYPb42n5okQ Co-Authored-By: Claude --- .../plugin-form/src/RecordBodyTableEditor.tsx | 2 +- ui/scripts/check-eager-closure-budget.mjs | 24 +++++++++---------- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/ui/packages/plugin-form/src/RecordBodyTableEditor.tsx b/ui/packages/plugin-form/src/RecordBodyTableEditor.tsx index 6c569ced429..65da6f35ba3 100644 --- a/ui/packages/plugin-form/src/RecordBodyTableEditor.tsx +++ b/ui/packages/plugin-form/src/RecordBodyTableEditor.tsx @@ -237,7 +237,7 @@ export const RecordBodyTableEditor: React.FC = ({ ob // The child schema is what draws the line grid, so it lands together with // the grid's body (objectstack#36102); `preloadGridField` never rejects. Promise.all([dataSource.getObjectSchema(objectName), preloadGridField()]) - .then(([s]: [any, void]) => { if (!cancelled) setChildSchema(s ?? { fields: {} }); }) + .then(([s]) => { if (!cancelled) setChildSchema(s ?? { fields: {} }); }) .catch(() => { if (!cancelled) setLoadFailed(true); }); return () => { cancelled = true; }; }, [dataSource, objectName]); diff --git a/ui/scripts/check-eager-closure-budget.mjs b/ui/scripts/check-eager-closure-budget.mjs index d13a599ee23..552bc75ba31 100644 --- a/ui/scripts/check-eager-closure-budget.mjs +++ b/ui/scripts/check-eager-closure-budget.mjs @@ -2488,7 +2488,7 @@ export const PER_CHUNK_GZIP_CEILINGS = Object.freeze({ // REGRESSION_THIS_GATE_MUST_CATCH_BYTES and the other per-chunk rows. No // exemption was added and no import was made lazy. // - // ⭐ LOWERED (2026-11-22), from 451,100 by 5,960 bytes, to 445,140, by + // ⭐ LOWERED (2026-11-22), from 451,100 by 5,956 bytes, to 445,144, by // objectstack#36102, the follow-up ruling 7063116595 names (GridField out of // the eager chunk; seat note 7064483594 on that card, on ruling 7063869131: // lower the ceiling and baseline by the bytes taken out, no more). Its @@ -2498,22 +2498,22 @@ export const PER_CHUNK_GZIP_CEILINGS = Object.freeze({ // WHAT THE BYTES ARE — one container, one instrument: `CI=true pnpm exec // turbo run build --filter=@object-ui/console...`, reading // `apps/console/dist/eager-closure.json`, twice on one tree: `main` at - // `b3bcfefc` alone, then the same `main` with this change (`4ca78ed1`, the - // branch head, whose only console build inputs are this change). Gzipped - // bytes: + // `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: // - // | chunk | `b3bcfefc` | `4ca78ed1` | delta | + // | chunk | `b3bcfefc` | `3c422050` | delta | // |-----------------------|-----------:|-----------:|-------:| // | `vendor-objectstack` | 674,662 | 674,662 | 0 | // | `i18n-locale-en` | 66,785 | 66,785 | 0 | // | `framework` | 88,559 | 88,559 | 0 | - // | `ui-components` | 352,359 | 346,399 | −5,960 | - // | ⇒ aggregate | 1,875,902 | 1,870,022 | −5,880 | + // | `ui-components` | 352,359 | 346,403 | −5,956 | + // | ⇒ aggregate | 1,875,902 | 1,869,974 | −5,928 | // // The same 105 eager chunks by name in both builds (2,577 -> 2,578 chunks in // all: the new one is `fields-grid`, lazy); besides this one, none moved by - // more than 26 bytes (`index` +26). Raw minified bytes of this chunk: - // 1,309,110 -> 1,289,858 (−19,252). + // more than 31 bytes (`index` +31). Raw minified bytes of this chunk: + // 1,309,110 -> 1,289,869 (−19,241). // // WHAT LEFT: the line-item grid's body, now // `packages/fields/src/widgets/grid-field/GridFieldWidget.tsx` in the lazy @@ -2524,7 +2524,7 @@ export const PER_CHUNK_GZIP_CEILINGS = Object.freeze({ // BASELINE, REGRESSION_THIS_GATE_MUST_CATCH_BYTES and the other per-chunk // rows. No exemption was added. The headroom `pnpm check:eager-closure` // prints on YOUR build is the figure in force, ⛔ not this one. - 'ui-components': 445_140, + 'ui-components': 445_144, }); /** @@ -2747,10 +2747,10 @@ export const PER_CHUNK_BASELINE = Object.freeze({ // PER_CHUNK_GZIP_CEILINGS), so this is again `bbf6b02d9`'s reading. // // Moved with its ceiling (2026-11-22, objectstack#36102), from 265,937 by - // the same −5,960 bytes GridField's body took out (the entry on that key of + // the same −5,956 bytes GridField's body took out (the entry on that key of // PER_CHUNK_GZIP_CEILINGS), which keeps the ceiling-minus-baseline gap this // key carried. ⚠️ So this is no longer one build's reading. - 'ui-components': 259_977, + 'ui-components': 259_981, }); /** From 51af8021d90db6a3ca390e5ffe1ec81f140953df Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 10:14:47 +0000 Subject: [PATCH 6/8] fix(plugin-form): a master-detail form draws its line grid only once the grid's body is here MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The live pin caught it: the New Invoice form drew its grid on the loading placeholder for about 0.4 s, because a collection with authored but untyped columns renders them while the derivation is still in flight. The lines now stay on "Loading columns…" until the body has settled, on every path; the derive effect no longer waits for it on its own. The edit-form pin types at the end of a stored line's text. Claude-Session: https://claude.ai/code/session_01QsR2jV3scu6UYPb42n5okQ Co-Authored-By: Claude --- ui/e2e/live/master-detail.spec.ts | 2 ++ .../plugin-form/src/MasterDetailForm.tsx | 36 +++++++++++++++---- 2 files changed, 32 insertions(+), 6 deletions(-) diff --git a/ui/e2e/live/master-detail.spec.ts b/ui/e2e/live/master-detail.spec.ts index 086624caba8..3a9a2cfb8a4 100644 --- a/ui/e2e/live/master-detail.spec.ts +++ b/ui/e2e/live/master-detail.spec.ts @@ -187,6 +187,8 @@ test.describe('the line-item grid on a form\'s first open (objectstack#36102)', async function typeKeepsFocus(page: Page, scope: ReturnType) { const cell = scope.locator('input[aria-label="Description"]').first(); await cell.click(); + // A stored line already has text: type at its end, not where the click landed. + await cell.press('End'); await cell.pressSequentially('first-open'); // A beat for any late remount to land before it is checked. await page.waitForTimeout(300); diff --git a/ui/packages/plugin-form/src/MasterDetailForm.tsx b/ui/packages/plugin-form/src/MasterDetailForm.tsx index 9613ed82502..84579653bf1 100644 --- a/ui/packages/plugin-form/src/MasterDetailForm.tsx +++ b/ui/packages/plugin-form/src/MasterDetailForm.tsx @@ -965,6 +965,34 @@ const FormSlotPlacement: React.FC<{ ); }; +/** + * Set once this module's own `preloadGridField()` has settled, so a form that + * mounts after that renders its grids at its first paint. + */ +let gridBodySettled = false; + +/** + * Whether the line grid's body is here (objectstack#36102). The grid is drawn + * only once it is, so a collection stays on "Loading columns…" until then and + * the grid never mounts on its loading placeholder, however its columns were + * reached: derived from the child schema, authored in full, or authored + * untyped and drawn while the derivation is still in flight. A failed load + * settles too: the grid then reports it, through the nearest error boundary. + */ +function useGridBodySettled(): boolean { + const [settled, setSettled] = useState(gridBodySettled); + useEffect(() => { + if (settled) return; + let live = true; + void preloadGridField().then(() => { + gridBodySettled = true; + if (live) setSettled(true); + }); + return () => { live = false; }; + }, [settled]); + return settled; +} + /** * The line-item grids + document totals, isolated from the header form. * @@ -1000,6 +1028,7 @@ const MasterDetailLines: React.FC = ({ // used to pass `toLocaleString` an explicit `undefined`, i.e. the MACHINE's // locale (objectui#9909). const displayLocale = useDisplayLocale(); + const gridBodyReady = useGridBodySettled(); // The tenant default currency (ADR-0053): the totals stack's currency when // the amount field fixes none (objectui#11132). const { currency: tenantCurrency } = useLocalization(); @@ -1211,7 +1240,7 @@ const MasterDetailLines: React.FC = ({ { object: d.childObject, parent: parentObjectName, property: 'relationshipField' }, )}

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

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

) : ( = ({ } }), ); - // 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.