Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .changeset/36451-grid-field-lazy-retry.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
'@object-ui/fields': patch
---

fix(fields): a line-item grid whose first load failed loads again on its next mount, with no page reload

Clause-②: no
Metadata-protocol: none

The line-item grid's body loads on first use. When that first load failed once (a network blip, a deploy that swapped chunk names) and the host had not preloaded it, the grid showed its error from then on, even after the body was reachable again, until the page was reloaded. `GridField` / `LineItemsField` no longer hold the body in a `React.lazy`, which keeps a failed load for good: each mount that finds the body still loading asks for it once, a failure still reaches the nearest error boundary, and the next mount asks again. The `grid` form-field widget (the registered `field:grid` and `getLazyFieldWidget('grid')`) now resolves to that same face, so it recovers the same way.

What does not change: a mount after the body has loaded renders it directly, `preloadGridField()` still never rejects, and the props of both names are unchanged. A form drawing a `grid` field shows the grid's own loading placeholder while the body loads. No metadata key, value or default changes.
10 changes: 6 additions & 4 deletions ui/packages/fields/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,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 { GridField } from './widgets/GridField.js';
import { RecordHoverCard, type RecordHoverCardObjectDef } from './RecordHoverCard.js';

// Module-level cache so multiple renderers fetching the same lookup ID
Expand Down Expand Up @@ -4832,9 +4832,11 @@ 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 })),
// 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 })),
// The grid's public face, already in this chunk, not its body: the face loads
// the body through its one loader (objectstack#36102) and asks again after a
// failed load, where a `React.lazy` wrapped around the body here would keep
// the failure until the page is reloaded (objectstack#36451).
'grid': () => Promise.resolve({ default: GridField }),

// Additional field types from @objectstack/spec
'color': () => import('./widgets/ColorField.js').then(m => ({ default: m.ColorField })),
Expand Down
64 changes: 64 additions & 0 deletions ui/packages/fields/src/widgets/GridField.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1575,4 +1575,68 @@ describe('GridField — the lazy face the package exports (objectstack#36102)',
const cell = screen.getByTestId('line-items').querySelector('input[aria-label="Description"]') as HTMLInputElement;
expect(cell.value).toBe('Widget');
});

// objectstack#36451 — a host that renders the grid without preloading it,
// whose first request for the body fails once (a network blip, a deploy that
// swapped chunk names), must not keep that failure for the whole session.
describe('after one failed load of the body', () => {
class Boundary extends React.Component<{ children: React.ReactNode }, { failed: boolean }> {
state = { failed: false };
static getDerivedStateFromError() {
return { failed: true };
}
render() {
return this.state.failed ? <div data-testid="grid-load-failed" /> : this.props.children;
}
}

/** Fail the next load of the body once, then let it through; restored by the returned call. */
function failTheNextBodyLoad(): () => void {
vi.resetModules();
let failNextLoad = true;
vi.doMock('./grid-field/GridFieldWidget', async (importOriginal) => {
if (failNextLoad) {
failNextLoad = false;
throw new Error('Failed to fetch dynamically imported module: fields-grid');
}
return importOriginal();
});
const quiet = vi.spyOn(console, 'error').mockImplementation(() => {});
return () => {
quiet.mockRestore();
vi.doUnmock('./grid-field/GridFieldWidget');
};
}

async function expectFailedThenRecovered(Grid: React.ComponentType<React.ComponentProps<typeof GridFieldFace>>): Promise<void> {
const first = render(<Boundary><React.Suspense fallback={null}><Grid value={lines} onChange={() => {}} field={field} /></React.Suspense></Boundary>);
await screen.findByTestId('grid-load-failed');
first.unmount();

render(<Boundary><React.Suspense fallback={null}><Grid value={lines} onChange={() => {}} field={field} /></React.Suspense></Boundary>);
const cell = (await screen.findByTestId('line-items')).querySelector('input[aria-label="Description"]') as HTMLInputElement;
expect(cell.value).toBe('Widget');
expect(screen.queryByTestId('grid-load-failed')).toBeNull();
}

it('a later mount of GridField renders the grid once the body is reachable, with no reload', async () => {
const restore = failTheNextBodyLoad();
try {
const face = await import('./GridField');
await expectFailedThenRecovered(face.GridField);
} finally {
restore();
}
});

it('a later mount of the grid form-field widget renders the grid too', async () => {
const restore = failTheNextBodyLoad();
try {
const fields = await import('../index');
await expectFailedThenRecovered(fields.getLazyFieldWidget('grid'));
} finally {
restore();
}
});
});
});
61 changes: 45 additions & 16 deletions ui/packages/fields/src/widgets/GridField.ts
Original file line number Diff line number Diff line change
Expand Up @@ -422,11 +422,12 @@ let gridFieldWidgetModule: GridFieldWidgetModule | undefined;
let gridFieldWidgetLoad: Promise<GridFieldWidgetModule> | undefined;

/**
* The ONE loader of the grid's body: the lazy face below, {@link
* preloadGridField} and the `grid` form-field loader in `../index.tsx` all go
* through it, so the body is requested once and a mount after any of them has
* resolved renders without a boundary. A failed load is forgotten, so the next
* caller asks again rather than inheriting the failure.
* The ONE loader of the grid's body: the face below and {@link
* preloadGridField} go through it (and the `grid` form-field loader in
* `../index.tsx` reaches it through the face), so the body is requested once
* and a mount after any of them has resolved renders without a boundary. A
* failed load is forgotten, so the next caller asks again rather than
* inheriting the failure.
*/
export function loadGridFieldWidget(): Promise<GridFieldWidgetModule> {
gridFieldWidgetLoad ??= import('./grid-field/GridFieldWidget.js').then(
Expand Down Expand Up @@ -458,10 +459,6 @@ export function preloadGridField(): Promise<void> {
);
}

const LazyGridFieldWidget = React.lazy(() =>
loadGridFieldWidget().then((loaded) => ({ default: loaded.GridFieldWidget })),
);

/**
* What a grid mounted before its body arrived shows meanwhile: a box of the
* grid's header height, marked busy, so the form does not jump when the table
Expand All @@ -480,18 +477,50 @@ function GridFieldLoading(): React.ReactElement {
* 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.
// Decided once per mount: switching from the loading face to the direct
// render when the load finishes would remount the body and drop the focused
// cell.
const [loadedAtMount] = React.useState(() => gridFieldWidgetModule);
if (loadedAtMount) {
const { GridFieldWidget } = loadedAtMount;
return React.createElement(GridFieldWidget, props);
}
return React.createElement(
React.Suspense,
{ fallback: React.createElement(GridFieldLoading) },
React.createElement(LazyGridFieldWidget, props),
);
return React.createElement(GridFieldOnceLoaded, props);
}

type GridFieldLoadOutcome =
| { readonly loaded: GridFieldWidgetModule }
| { readonly failed: unknown };

/**
* A grid mounted before its body arrived: {@link GridFieldLoading} until the
* body loads, then the body. Each COMMITTED mount asks the loader once, from an
* effect, and a failed load is thrown from the next render to the nearest
* error boundary. Not `React.lazy`: a lazy component keeps its first outcome
* for good, a rejection included, so a later mount would rethrow that failure
* until the page is reloaded. A render React discards before it commits runs
* no effect, so it requests nothing, and the loader forgets a failure, so the
* next mount (an error boundary's reset, a reopened form) loads again.
*/
function GridFieldOnceLoaded(props: GridFieldWidgetProps): React.ReactElement {
const [outcome, setOutcome] = React.useState<GridFieldLoadOutcome | undefined>(undefined);
React.useEffect(() => {
let mounted = true;
loadGridFieldWidget().then(
(loaded) => {
if (mounted) setOutcome({ loaded });
},
(failed: unknown) => {
if (mounted) setOutcome({ failed });
},
);
return () => {
mounted = false;
};
}, []);
if (!outcome) return React.createElement(GridFieldLoading);
if ('failed' in outcome) throw outcome.failed;
return React.createElement(outcome.loaded.GridFieldWidget, props);
}

/** Semantic alias — the master-detail subform's child grid. */
Expand Down
Loading