Skip to content

Commit 52971ff

Browse files
fix(fields): a failed first load of the line-item grid body recovers on the next mount (#36607)
Fixes #36451 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:控制台记录表单里的明细行表格,第一次加载失败一次后(网络抖动、发版换了文件名),之后再打开表单即可正常显示表格,不用刷新整页。 - 为什么做:明细行表格按需加载的收尾问题,替所有碰到一次加载失败的表单用户解决「只能刷新页面」。 - 出错会怎样:只影响明细行表格的加载方式,最坏是加载失败时照旧显示报错;可直接撤回。 - 要你做什么:无。 ## What changes - `GridField` / `LineItemsField` (`ui/packages/fields/src/widgets/GridField.ts`) no longer render the body through a module-scope `React.lazy`. A lazy component keeps its first outcome for good, a rejection included, so after one failed load of the body every later mount rethrew that failure until the page was reloaded, although `loadGridFieldWidget` already forgot the failure. A mount that finds the body still loading now renders `GridFieldOnceLoaded`: it shows the existing loading placeholder, asks the one loader from an effect (so only a committed mount requests anything; a render React discards before commit cannot loop on a failing chunk), throws a failed load to the nearest error boundary, and the next mount asks again. A mount after the body has loaded still renders it directly in the same render; `preloadGridField()` is unchanged and never rejects. - The `grid` entry of the form-field loader map (`ui/packages/fields/src/index.tsx`) resolves to that face instead of a `React.lazy` around the body, so the registered `field:grid` widget and `getLazyFieldWidget('grid')` recover the same way. The face is already in the eager chunk (the entry exports it), so this adds no edge to the body. - Patch changeset for `@object-ui/fields`. Read first, by risk: 1. `GridField.ts`, the `GridFieldOnceLoaded` function: the effect-driven load, the cleanup guard, the throw of a failed outcome. 2. `index.tsx`, the `grid` entry of the loader map. 3. `GridField.test.tsx`, the new `after one failed load of the body` describe inside the existing lazy-face block. ## Tests Two pins in the existing lazy-face block of `GridField.test.tsx`: the body module is mocked to fail its first load once and then load normally; the first mount must reach the error boundary and a later mount must render the grid, once for the `GridField` face and once for `getLazyFieldWidget('grid')`. <details><summary>Premise, measured on main's code (both pins red)</summary> `GridField.ts` and `index.tsx` replaced by their blobs at the branch point `e17c2ae1a` (hash-verified on disk), then the pins run: ``` × a later mount of GridField renders the grid once the body is reachable, with no reload × a later mount of the grid form-field widget renders the grid too Tests 2 failed | 107 skipped (109) ``` Both failures: the later mount shows the boundary fallback (`grid-load-failed`), never `line-items`. Restored with `git checkout HEAD`, `git diff HEAD` empty, HEAD blob hashes matched. </details> <details><summary>Ablation, one half at a time</summary> - Face reverted to main, `index.tsx` fixed: both pins red (the form-field entry reaches the reverted face). - `index.tsx` reverted to main, face fixed: only the form-field pin red (`1 failed | 1 passed`). Each leg restored and verified the same way. </details> <details><summary>Package run at head 66d9f58</summary> `pnpm --dir ui exec vitest run --maxWorkers=2 packages/fields/ && pnpm --filter @object-ui/fields run type-check` under the shared verify lock: ``` Test Files 322 passed | 1 skipped (323) Tests 4893 passed | 7 skipped (4900) VERDICT command-exit 0 ``` `pnpm --dir ui exec vitest run scripts/` (derived gate): 172 files passed, VERDICT command-exit 0. ESLint on the three changed files: 0 errors (warnings pre-existing). </details> <details><summary>Derived gates at head 66d9f58</summary> `dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` derived 39 families; all 39 run, all exit 0, `--ran` reconciliation: 39 run, 0 NOT-MEASURED, 0 UNRUN. First pass: `check:query-options-erasure` and `check:type-check-debt` hit a 300 s harness timeout and `check:watch-hint-literal` exited 1 once (cause not established); each re-run to completion, exit 0. </details> ## Acceptance notes - A form drawing a `grid` field now shows the grid's own loading placeholder (a dashed box of the header's height) while the body loads, where it showed the form's own suspense fallback before. - Boundary not measured here: the retry calls `import()` again for the same chunk URL. Whether a given browser re-fetches a module whose earlier dynamic import failed is engine behaviour; the pins run under vitest/jsdom only. - Card step 3, measured with a throwaway test (deleted, not committed): the same edge, a module-scope `React.lazy` keeping a failed first load until reload, holds for `FieldEditWidget`'s date picker (measured; its datetime picker and rich-text panel are the same construction), `richTextDisplay`'s markdown content (measured), `FilterConditionCell` (measured), the per-type lazy cache of `getLazyFieldWidget` and `registerField` for every other type (measured for `date`), and `ImageField`'s cropper dialog (same construction, not measured). None is changed here; they are listed for the seat. - No README or docs sentence is made false by this change. ## Verification Two-minute check: `pnpm --dir ui exec vitest run packages/fields/src/widgets/GridField.test.tsx -t "after one failed load"` from the repo root; expect `2 passed`. --- _Generated by [Claude Code](https://claude.ai/code/session_01ADHkmNmMEXS4EzeVz9RjvD)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent c6075a7 commit 52971ff

4 files changed

Lines changed: 127 additions & 20 deletions

File tree

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
'@object-ui/fields': patch
3+
---
4+
5+
fix(fields): a line-item grid whose first load failed loads again on its next mount, with no page reload
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
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.
11+
12+
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.

‎ui/packages/fields/src/index.tsx‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ import { deriveHexBadgePalette } from './hexBadgePalette.js';
3636
import { formatNumberFieldValue, formatCurrency, formatPercentPoints, percentCellScale } from './widgets/number-format.js';
3737
import { useFieldTranslation } from './widgets/useFieldTranslation.js';
3838
import { useBooleanValueLabel } from './widgets/booleanValueLabel.js';
39-
import { loadGridFieldWidget } from './widgets/GridField.js';
39+
import { GridField } from './widgets/GridField.js';
4040
import { RecordHoverCard, type RecordHoverCardObjectDef } from './RecordHoverCard.js';
4141

4242
// Module-level cache so multiple renderers fetching the same lookup ID
@@ -4832,9 +4832,11 @@ const fieldWidgetMap = {
48324832
// Complex data types
48334833
'object': () => import('./widgets/ObjectField.js').then(m => ({ default: m.ObjectField })),
48344834
'vector': () => import('./widgets/VectorField.js').then(m => ({ default: m.VectorField })),
4835-
// The grid's body, through its public face's one loader so a lazy `GridField`
4836-
// mounted after this resolved renders without a boundary (objectstack#36102).
4837-
'grid': () => loadGridFieldWidget().then(m => ({ default: m.GridFieldWidget })),
4835+
// The grid's public face, already in this chunk, not its body: the face loads
4836+
// the body through its one loader (objectstack#36102) and asks again after a
4837+
// failed load, where a `React.lazy` wrapped around the body here would keep
4838+
// the failure until the page is reloaded (objectstack#36451).
4839+
'grid': () => Promise.resolve({ default: GridField }),
48384840

48394841
// Additional field types from @objectstack/spec
48404842
'color': () => import('./widgets/ColorField.js').then(m => ({ default: m.ColorField })),

‎ui/packages/fields/src/widgets/GridField.test.tsx‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1575,4 +1575,68 @@ describe('GridField — the lazy face the package exports (objectstack#36102)',
15751575
const cell = screen.getByTestId('line-items').querySelector('input[aria-label="Description"]') as HTMLInputElement;
15761576
expect(cell.value).toBe('Widget');
15771577
});
1578+
1579+
// objectstack#36451 — a host that renders the grid without preloading it,
1580+
// whose first request for the body fails once (a network blip, a deploy that
1581+
// swapped chunk names), must not keep that failure for the whole session.
1582+
describe('after one failed load of the body', () => {
1583+
class Boundary extends React.Component<{ children: React.ReactNode }, { failed: boolean }> {
1584+
state = { failed: false };
1585+
static getDerivedStateFromError() {
1586+
return { failed: true };
1587+
}
1588+
render() {
1589+
return this.state.failed ? <div data-testid="grid-load-failed" /> : this.props.children;
1590+
}
1591+
}
1592+
1593+
/** Fail the next load of the body once, then let it through; restored by the returned call. */
1594+
function failTheNextBodyLoad(): () => void {
1595+
vi.resetModules();
1596+
let failNextLoad = true;
1597+
vi.doMock('./grid-field/GridFieldWidget', async (importOriginal) => {
1598+
if (failNextLoad) {
1599+
failNextLoad = false;
1600+
throw new Error('Failed to fetch dynamically imported module: fields-grid');
1601+
}
1602+
return importOriginal();
1603+
});
1604+
const quiet = vi.spyOn(console, 'error').mockImplementation(() => {});
1605+
return () => {
1606+
quiet.mockRestore();
1607+
vi.doUnmock('./grid-field/GridFieldWidget');
1608+
};
1609+
}
1610+
1611+
async function expectFailedThenRecovered(Grid: React.ComponentType<React.ComponentProps<typeof GridFieldFace>>): Promise<void> {
1612+
const first = render(<Boundary><React.Suspense fallback={null}><Grid value={lines} onChange={() => {}} field={field} /></React.Suspense></Boundary>);
1613+
await screen.findByTestId('grid-load-failed');
1614+
first.unmount();
1615+
1616+
render(<Boundary><React.Suspense fallback={null}><Grid value={lines} onChange={() => {}} field={field} /></React.Suspense></Boundary>);
1617+
const cell = (await screen.findByTestId('line-items')).querySelector('input[aria-label="Description"]') as HTMLInputElement;
1618+
expect(cell.value).toBe('Widget');
1619+
expect(screen.queryByTestId('grid-load-failed')).toBeNull();
1620+
}
1621+
1622+
it('a later mount of GridField renders the grid once the body is reachable, with no reload', async () => {
1623+
const restore = failTheNextBodyLoad();
1624+
try {
1625+
const face = await import('./GridField');
1626+
await expectFailedThenRecovered(face.GridField);
1627+
} finally {
1628+
restore();
1629+
}
1630+
});
1631+
1632+
it('a later mount of the grid form-field widget renders the grid too', async () => {
1633+
const restore = failTheNextBodyLoad();
1634+
try {
1635+
const fields = await import('../index');
1636+
await expectFailedThenRecovered(fields.getLazyFieldWidget('grid'));
1637+
} finally {
1638+
restore();
1639+
}
1640+
});
1641+
});
15781642
});

‎ui/packages/fields/src/widgets/GridField.ts‎

Lines changed: 45 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -422,11 +422,12 @@ let gridFieldWidgetModule: GridFieldWidgetModule | undefined;
422422
let gridFieldWidgetLoad: Promise<GridFieldWidgetModule> | undefined;
423423

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

461-
const LazyGridFieldWidget = React.lazy(() =>
462-
loadGridFieldWidget().then((loaded) => ({ default: loaded.GridFieldWidget })),
463-
);
464-
465462
/**
466463
* What a grid mounted before its body arrived shows meanwhile: a box of the
467464
* grid's header height, marked busy, so the form does not jump when the table
@@ -480,18 +477,50 @@ function GridFieldLoading(): React.ReactElement {
480477
* props as the body, see `GridFieldWidgetProps`.
481478
*/
482479
export function GridField(props: GridFieldWidgetProps): React.ReactElement {
483-
// Decided once per mount: switching from the boundary to the direct render
484-
// when the load finishes would remount the body and drop the focused cell.
480+
// Decided once per mount: switching from the loading face to the direct
481+
// render when the load finishes would remount the body and drop the focused
482+
// cell.
485483
const [loadedAtMount] = React.useState(() => gridFieldWidgetModule);
486484
if (loadedAtMount) {
487485
const { GridFieldWidget } = loadedAtMount;
488486
return React.createElement(GridFieldWidget, props);
489487
}
490-
return React.createElement(
491-
React.Suspense,
492-
{ fallback: React.createElement(GridFieldLoading) },
493-
React.createElement(LazyGridFieldWidget, props),
494-
);
488+
return React.createElement(GridFieldOnceLoaded, props);
489+
}
490+
491+
type GridFieldLoadOutcome =
492+
| { readonly loaded: GridFieldWidgetModule }
493+
| { readonly failed: unknown };
494+
495+
/**
496+
* A grid mounted before its body arrived: {@link GridFieldLoading} until the
497+
* body loads, then the body. Each COMMITTED mount asks the loader once, from an
498+
* effect, and a failed load is thrown from the next render to the nearest
499+
* error boundary. Not `React.lazy`: a lazy component keeps its first outcome
500+
* for good, a rejection included, so a later mount would rethrow that failure
501+
* until the page is reloaded. A render React discards before it commits runs
502+
* no effect, so it requests nothing, and the loader forgets a failure, so the
503+
* next mount (an error boundary's reset, a reopened form) loads again.
504+
*/
505+
function GridFieldOnceLoaded(props: GridFieldWidgetProps): React.ReactElement {
506+
const [outcome, setOutcome] = React.useState<GridFieldLoadOutcome | undefined>(undefined);
507+
React.useEffect(() => {
508+
let mounted = true;
509+
loadGridFieldWidget().then(
510+
(loaded) => {
511+
if (mounted) setOutcome({ loaded });
512+
},
513+
(failed: unknown) => {
514+
if (mounted) setOutcome({ failed });
515+
},
516+
);
517+
return () => {
518+
mounted = false;
519+
};
520+
}, []);
521+
if (!outcome) return React.createElement(GridFieldLoading);
522+
if ('failed' in outcome) throw outcome.failed;
523+
return React.createElement(outcome.loaded.GridFieldWidget, props);
495524
}
496525

497526
/** Semantic alias — the master-detail subform's child grid. */

0 commit comments

Comments
 (0)