Skip to content

Commit 9f84e5f

Browse files
fix(fields): lazy field widgets load again after a failed chunk load (#36786)
<!-- claude-projects-attribution: {"github_login":"os-warren"} --> _Requested by **Warren** · [project thread](https://claude.ai/code/project/chan_01U5RdnAAmkSQmZbqh6FtqZ8?thread=cmsg_01U5RdnAAmkSQmZbqh6FtqZ8Jauz9zBKmCvktkHXwUiSe1)_ Fixes #36608 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:表单和列表里的日期、日期时间、富文本、筛选条件、图片裁剪等控件,某次加载失败(刚发版换了文件、网络断了一下)后,重新打开表单或页面即可恢复,不用再整页刷新。 - 为什么做:同类问题之前只修了明细行表格这一处,这次把字段包里其余所有延迟加载的控件一次收口到同一个机制上。 - 出错会怎样:最坏是某个控件在首次加载时多等一下或仍显示加载失败,可直接撤回本次改动,不涉及数据。 - 要你做什么:无。 ## What changes - New internal helper `ui/packages/fields/src/recoverableLazy.ts` (not exported from the package entry). It is `React.lazy` with one difference: a failed chunk load is not kept for the session. - Loading and loaded behave as `React.lazy`: the mount suspends to the host's nearest `Suspense` boundary, a mount after the chunk loaded renders in the same pass, and every mount shares one request. Hosts that wait on `Suspense` to reveal a form body keep doing so. - A failed load resolves to a stand-in that commits once (draws nothing), retires that request, then throws the failure from its next render to the nearest error boundary. The committed mount keeps rethrowing for as long as it is re-rendered; only a NEW mount (an error boundary's reset, a reopened form, a revisited page) asks for the chunk again. - Every `React.lazy` site in the fields package now goes through it: `FieldEditWidget` (date, datetime, the rich text cell-panel editor), `richTextDisplay` (markdown read face), `FilterConditionCell`, `ImageField`'s crop dialog, `getLazyFieldWidget`, and `registerField` (the form registry path; the card's re-check grep lists it, so it is in scope). `git grep -n "React.lazy\|lazy(" ui/packages/fields/src` now hits only the helper and comments. - The returned component also carries `load()`, which resolves to the loaded widget itself through the same shared request (and asks again after a failure). `getLazyFieldWidget`'s declared return type is unchanged (`React.ComponentType`); `load()` is the seam for a caller that needs the widget's own function rather than an element of it. - `ui/examples/schema-catalog/test/form-field-channel-census-12130.test.tsx` read `React.lazy`'s private `_init`/`_payload` off `getLazyFieldWidget`'s result to reach each widget's render function; it now calls `load()`. CI caught this at b572a58 (`Test UI (13/16)`: `TypeError: internals._init is not a function`); at 672b03e that file passes locally (37 tests). - `GridField` keeps its own loader from #36607 unchanged. - Patch changeset for `@object-ui/fields`. ### Why not #36607's effect-based wrapper as is The card suggests #36607's approach. That wrapper loads from an effect and draws its own loading face, so it never suspends. Applied to `getLazyFieldWidget` / `registerField`, every cold-loaded form field would stop suspending to its host's `Suspense` fallback (the form bodies' pending skeletons, the action dialogs' widget fallbacks) and the host would reveal half-loaded forms. The helper keeps `Suspense` on the happy path and borrows #36607's key idea only on the failure path: a request is forgotten only from a committed mount, so the failure is shown instead of retried in a loop. The tempting simpler variant (forget the failed request in the render that throws) is wrong, and the second ablation below shows it: a mount that never committed keeps no state, so React's re-render after the rejection picks a fresh request, suspends again, and the error never reaches the boundary. ## Tests `ui/packages/fields/src/__tests__/lazyWidgetRecovery-36608.test.tsx`, 12 tests: - the helper: suspends to the host fallback, later mounts render in the same pass, concurrent mounts share one request, a failure reaches the boundary with exactly one request (no retry loop), the next mount loads; the same under `StrictMode`. - one pin per site (date, datetime, rich text panel editor, markdown read face, filter-condition cell, image crop dialog, `getLazyFieldWidget('date')`, `registerField('date')`): the chunk module is mocked to fail its first import, the first mount lands on the error boundary, a later mount renders the widget. One family file rather than a pin per component file: every site pin needs `vi.resetModules` plus a module mock of that site's chunk, which would leak into the existing shared files' other tests. ## Acceptance notes - None filed. Nothing out of scope was found. ## Verification Two-minute check: `cd ui && pnpm exec vitest run packages/fields/src/__tests__/lazyWidgetRecovery-36608.test.tsx`, expect 12 passed. Read first, by risk: 1. `ui/packages/fields/src/recoverableLazy.ts`, the whole file (the stand-in's commit-then-throw is the part that matters). 2. `ui/packages/fields/src/index.tsx`, `getLazyFieldWidget` and `registerField`. 3. `ui/packages/fields/src/FieldEditWidget.tsx`, the three lazy editors. <details><summary>Local readings at head 672b03e</summary> - `cd ui && pnpm exec vitest run packages/fields/src/__tests__/lazyWidgetRecovery-36608.test.tsx examples/schema-catalog/test/form-field-channel-census-12130.test.tsx`: Test Files 2 passed, Tests 49 passed (12 new pins, one of them also pinning `load()`, plus the census). - `pnpm --filter @object-ui/fields test`: Test Files 326 passed, 1 skipped (327); Tests 4980 passed, 7 skipped (4987). Run at c42f157 plus the typing fix; the later commits touch the helper's `load()`, the new test file and the census test, all re-run above, and `type-check` re-ran at 672b03e: exit 0. - `pnpm --filter @object-ui/fields type-check` (both tsc programs; the new test file is in `tsconfig.test.json`'s program, `--listFiles` counts 1): exit 0. - Ablations, each through `scripts/ablation-replace.mjs` (anchor hit 1 to 0, restore proven by blob equals HEAD and empty `git diff HEAD`); the tests import source, so no rebuild leg: 1. the stand-in never retires its request (`attempt.retired = false`): 10 of 12 red (both helper failure pins and all 8 site pins). 2. the naive variant (retire and throw in the same render, no commit first): both helper failure pins red; the first mount shows the widget, not the error boundary, because the failure was swallowed and retried behind the loading face. 3. `getLazyFieldWidget` back on `React.lazy`: its site pin red. - Derived gate families (`dispatch-gates.mjs --commands`), exit codes captured before any pipe: 36 run, all exit 0, including `check:type-check-debt`, `check:test-source-alias` (first red on a dynamic `@object-ui/core` import inside a test body, fixed by a module-top import), `check:query-options-erasure`, `check:type-check-coverage`, `check:nul-bytes`, `check:cross-package-test-inputs`, `check:engine-double-contract`, the changeset gates and `check-adr-0087-registration`. Left to CI: `check:published-files`, `check:driver-memory-census`, `pnpm --dir ui exec vitest run scripts/`. - `scripts/pm/overlap-check.mjs` before each push: VERDICT clean (origin/main merges cleanly, 0 open PR heads share a file). </details> <!-- signed: repo:objectstack#1 · os-warren · session_01JQwxbZs5obPjDPPXTHrc6A --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent ff0d1f1 commit 9f84e5f

9 files changed

Lines changed: 453 additions & 31 deletions

File tree

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@object-ui/fields': patch
3+
---
4+
5+
fix(fields): a lazily loaded field widget whose chunk failed to load once loads again on its next mount, with no page reload
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
The date and datetime pickers, the rich-content editor and read face, the filter-condition cell, the image field's crop dialog and every widget reached through `getLazyFieldWidget` or `registerField` were `React.lazy` components. A lazy component keeps its first import outcome, a rejection included, so after one failed chunk load (a deploy that replaced the chunk, a dropped connection) the widget stayed broken until the page was reloaded. They now load through one shared wrapper: loading and loaded behave as before (the host's `Suspense` fallback shows while the chunk loads), a failed load still reaches the nearest error boundary, and the next mount (an error boundary's reset, a reopened form, a revisited page) asks for the chunk again. The mounted widget that saw the failure does not retry by itself, so an unreachable chunk is not requested in a loop.

‎ui/examples/schema-catalog/test/form-field-channel-census-12130.test.tsx‎

Lines changed: 7 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -121,23 +121,16 @@ function recorded<T extends object>(target: T, via: 'entry' | 'props'): T {
121121

122122
/* ── every field widget, re-registered with recorded props ───────────────── */
123123

124-
interface LazyInternals {
125-
_init: (payload: unknown) => unknown;
126-
_payload: unknown;
127-
}
128124
type WidgetFn = (props: Record<string, unknown>) => React.ReactNode;
129125

130-
/** The component a `React.lazy` resolves to. Module loading, not rendering. */
126+
/**
127+
* The component a lazily loaded field widget resolves to. Module loading, not
128+
* rendering: `getLazyFieldWidget` hands back the fields package's recoverable
129+
* lazy component, whose `load()` resolves to the widget itself
130+
* (objectstack#36608).
131+
*/
131132
async function resolveLazy(lazy: unknown): Promise<unknown> {
132-
const internals = lazy as LazyInternals;
133-
for (;;) {
134-
try {
135-
return internals._init(internals._payload);
136-
} catch (pending) {
137-
if (pending && typeof (pending as PromiseLike<unknown>).then === 'function') await pending;
138-
else throw pending;
139-
}
140-
}
133+
return (lazy as { load(): Promise<unknown> }).load();
141134
}
142135

143136
const MEMO = Symbol.for('react.memo');

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

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
*/
88

99
import React from 'react';
10+
import { recoverableLazy } from './recoverableLazy.js';
1011
import type { FieldWidgetComponentProps } from './widgets/types.js';
1112
// The package's own executor of the DOM pass-through declaration, reused here
1213
// rather than re-listed — see the note on this component's return statement.
@@ -92,10 +93,10 @@ import { RICH_TEXT_FIELD_TYPES } from './widgets/richTextDisplay.js';
9293
* what makes that text reach the edit (objectui#12664, the `renderCellEditor`
9394
* contract on `DataTableSchema`).
9495
*/
95-
const DatePickerEditWidget = React.lazy(() =>
96+
const DatePickerEditWidget = recoverableLazy(() =>
9697
import('./widgets/date-picker/DatePickerField.js').then((m) => ({ default: m.DatePickerField })),
9798
);
98-
const DateTimePickerEditWidget = React.lazy(() =>
99+
const DateTimePickerEditWidget = recoverableLazy(() =>
99100
import('./widgets/date-picker/DatePickerField.js').then((m) => ({ default: m.DateTimePickerField })),
100101
);
101102

@@ -105,7 +106,7 @@ const DateTimePickerEditWidget = React.lazy(() =>
105106
* uses for these three types, for the list grid's cell panel
106107
* ({@link IN_CELL_PANEL_EDIT_WIDGETS}).
107108
*/
108-
const RichTextPanelEditWidget = React.lazy(() =>
109+
const RichTextPanelEditWidget = recoverableLazy(() =>
109110
import('./widgets/RichTextField.js').then((m) => ({ default: m.RichTextField })),
110111
);
111112

Lines changed: 295 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,295 @@
1+
/**
2+
* ObjectUI
3+
* Copyright (c) 2024-present ObjectStack Inc.
4+
*
5+
* This source code is licensed under the MIT license found in the
6+
* LICENSE file in the root directory of this source tree.
7+
*/
8+
9+
/**
10+
* objectstack#36608 — a lazily loaded field widget whose first chunk load
11+
* fails (a deploy that replaced the chunk, a dropped connection) must not keep
12+
* that failure until the page is reloaded. Every lazy site of this package goes
13+
* through `recoverableLazy`; the first block pins the helper, the rest pin each
14+
* site: a failed first load reaches the error boundary, and a later mount
15+
* renders the widget once the chunk is reachable.
16+
*/
17+
import React from 'react';
18+
import { afterEach, describe, expect, it, vi } from 'vitest';
19+
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
20+
// Paid at collection, not inside a test's clock: the registry pin imports it
21+
// again after `vi.resetModules` (check:test-source-alias).
22+
import '@object-ui/core';
23+
24+
afterEach(() => cleanup());
25+
26+
class Boundary extends React.Component<{ children: React.ReactNode }, { failed: boolean }> {
27+
state = { failed: false };
28+
static getDerivedStateFromError() {
29+
return { failed: true };
30+
}
31+
render() {
32+
return this.state.failed ? <div data-testid="load-failed" /> : this.props.children;
33+
}
34+
}
35+
36+
/** Lets pending promises and timers settle. */
37+
const settle = () => new Promise((resolve) => setTimeout(resolve, 30));
38+
39+
function Loaded(): React.ReactElement {
40+
return <div data-testid="widget-loaded" />;
41+
}
42+
43+
describe('recoverableLazy', () => {
44+
async function load() {
45+
vi.resetModules();
46+
return (await import('../recoverableLazy')).recoverableLazy;
47+
}
48+
49+
function tree(Widget: React.ComponentType<object>) {
50+
return (
51+
<Boundary>
52+
<React.Suspense fallback={<div data-testid="host-fallback" />}>
53+
<Widget />
54+
</React.Suspense>
55+
</Boundary>
56+
);
57+
}
58+
59+
it('suspends to the host fallback while loading, and a later mount renders in the same pass', async () => {
60+
const recoverableLazy = await load();
61+
const loader = vi.fn(async () => ({ default: Loaded }));
62+
const Widget = recoverableLazy(loader);
63+
64+
const first = render(tree(Widget));
65+
expect(screen.getByTestId('host-fallback')).toBeTruthy();
66+
await screen.findByTestId('widget-loaded');
67+
first.unmount();
68+
69+
render(tree(Widget));
70+
expect(screen.getByTestId('widget-loaded')).toBeTruthy();
71+
// `load()` hands over the widget itself, through the same request.
72+
expect(await Widget.load()).toBe(Loaded);
73+
expect(loader).toHaveBeenCalledTimes(1);
74+
});
75+
76+
it('mounts that ask while the chunk loads share one request', async () => {
77+
const recoverableLazy = await load();
78+
const loader = vi.fn(async () => ({ default: Loaded }));
79+
const Widget = recoverableLazy(loader);
80+
81+
render(
82+
<React.Suspense fallback={null}>
83+
<Widget />
84+
<Widget />
85+
</React.Suspense>,
86+
);
87+
await waitFor(() => expect(screen.getAllByTestId('widget-loaded')).toHaveLength(2));
88+
expect(loader).toHaveBeenCalledTimes(1);
89+
});
90+
91+
it('a failed load reaches the error boundary once, without asking again, and the next mount loads', async () => {
92+
const recoverableLazy = await load();
93+
const quiet = vi.spyOn(console, 'error').mockImplementation(() => {});
94+
try {
95+
const loader = vi
96+
.fn<() => Promise<{ default: React.ComponentType<object> }>>()
97+
.mockRejectedValueOnce(new Error('Failed to fetch dynamically imported module'))
98+
.mockResolvedValue({ default: Loaded });
99+
const Widget = recoverableLazy(loader);
100+
101+
const first = render(tree(Widget));
102+
await screen.findByTestId('load-failed');
103+
// The failure is shown, not retried in a loop behind the loading face.
104+
await settle();
105+
expect(loader).toHaveBeenCalledTimes(1);
106+
first.unmount();
107+
108+
render(tree(Widget));
109+
await screen.findByTestId('widget-loaded');
110+
expect(screen.queryByTestId('load-failed')).toBeNull();
111+
expect(loader).toHaveBeenCalledTimes(2);
112+
} finally {
113+
quiet.mockRestore();
114+
}
115+
});
116+
117+
it('holds under StrictMode: one request per failure, and the next mount loads', async () => {
118+
const recoverableLazy = await load();
119+
const quiet = vi.spyOn(console, 'error').mockImplementation(() => {});
120+
try {
121+
const loader = vi
122+
.fn<() => Promise<{ default: React.ComponentType<object> }>>()
123+
.mockRejectedValueOnce(new Error('Failed to fetch dynamically imported module'))
124+
.mockResolvedValue({ default: Loaded });
125+
const Widget = recoverableLazy(loader);
126+
127+
const first = render(<React.StrictMode>{tree(Widget)}</React.StrictMode>);
128+
await screen.findByTestId('load-failed');
129+
await settle();
130+
expect(loader).toHaveBeenCalledTimes(1);
131+
first.unmount();
132+
133+
render(<React.StrictMode>{tree(Widget)}</React.StrictMode>);
134+
await screen.findByTestId('widget-loaded');
135+
expect(loader).toHaveBeenCalledTimes(2);
136+
} finally {
137+
quiet.mockRestore();
138+
}
139+
});
140+
});
141+
142+
/**
143+
* Fail the next load of `chunk` (a path relative to this file) once, then
144+
* answer `loaded`. Restored by the returned call.
145+
*/
146+
function failTheNextLoadOf(chunk: string, loaded: Record<string, unknown>): () => void {
147+
vi.resetModules();
148+
let failNextLoad = true;
149+
vi.doMock(chunk, () => {
150+
if (failNextLoad) {
151+
failNextLoad = false;
152+
throw new Error(`Failed to fetch dynamically imported module: ${chunk}`);
153+
}
154+
return loaded;
155+
});
156+
const quiet = vi.spyOn(console, 'error').mockImplementation(() => {});
157+
return () => {
158+
quiet.mockRestore();
159+
vi.doUnmock(chunk);
160+
};
161+
}
162+
163+
/** Mounts `draw()` under a boundary: first the failure, then — on a later mount — the widget. */
164+
async function expectFailedThenRecovered(draw: () => React.ReactElement, afterMount?: () => void): Promise<void> {
165+
const first = render(<Boundary><React.Suspense fallback={null}>{draw()}</React.Suspense></Boundary>);
166+
afterMount?.();
167+
await screen.findByTestId('load-failed');
168+
first.unmount();
169+
170+
render(<Boundary><React.Suspense fallback={null}>{draw()}</React.Suspense></Boundary>);
171+
afterMount?.();
172+
await screen.findByTestId('widget-loaded');
173+
expect(screen.queryByTestId('load-failed')).toBeNull();
174+
}
175+
176+
describe('each lazy field-widget site recovers after one failed chunk load', () => {
177+
it('FieldEditWidget: the date picker', async () => {
178+
const restore = failTheNextLoadOf('../widgets/date-picker/DatePickerField', {
179+
DatePickerField: Loaded,
180+
DateTimePickerField: Loaded,
181+
});
182+
try {
183+
const { FieldEditWidget } = await import('../FieldEditWidget');
184+
await expectFailedThenRecovered(() => (
185+
<FieldEditWidget field={{ name: 'due', type: 'date' } as never} value="2026-10-16" onChange={() => {}} />
186+
));
187+
} finally {
188+
restore();
189+
}
190+
});
191+
192+
it('FieldEditWidget: the datetime picker', async () => {
193+
const restore = failTheNextLoadOf('../widgets/date-picker/DatePickerField', {
194+
DatePickerField: Loaded,
195+
DateTimePickerField: Loaded,
196+
});
197+
try {
198+
const { FieldEditWidget } = await import('../FieldEditWidget');
199+
await expectFailedThenRecovered(() => (
200+
<FieldEditWidget field={{ name: 'at', type: 'datetime' } as never} value="" onChange={() => {}} />
201+
));
202+
} finally {
203+
restore();
204+
}
205+
});
206+
207+
it("FieldEditWidget: the rich text editor in the cell's panel", async () => {
208+
const restore = failTheNextLoadOf('../widgets/RichTextField', { RichTextField: Loaded });
209+
try {
210+
const { FieldEditWidget } = await import('../FieldEditWidget');
211+
await expectFailedThenRecovered(() => (
212+
<FieldEditWidget field={{ name: 'notes', type: 'markdown' } as never} value="**x**" onChange={() => {}} inCell />
213+
));
214+
} finally {
215+
restore();
216+
}
217+
});
218+
219+
it('the markdown read face (richTextDisplay)', async () => {
220+
const restore = failTheNextLoadOf('../widgets/MarkdownContent', { default: Loaded });
221+
try {
222+
const { RICH_TEXT_CELL_RENDERERS } = await import('../widgets/richTextDisplay');
223+
const Markdown = RICH_TEXT_CELL_RENDERERS.markdown;
224+
await expectFailedThenRecovered(() => (
225+
<Markdown value="**bold**" field={{ name: 'notes', type: 'markdown' } as never} />
226+
));
227+
} finally {
228+
restore();
229+
}
230+
});
231+
232+
it('FilterConditionCell', async () => {
233+
const restore = failTheNextLoadOf('../widgets/FilterConditionField', { FilterConditionField: Loaded });
234+
try {
235+
const { FilterConditionCell } = await import('../widgets/FilterConditionCell');
236+
await expectFailedThenRecovered(() => (
237+
<FilterConditionCell
238+
value='{"field":"priority","operator":"eq","value":"urgent"}'
239+
field={{ name: 'criteria', type: 'textarea', widget: 'filter-condition' } as never}
240+
/>
241+
));
242+
} finally {
243+
restore();
244+
}
245+
});
246+
247+
it("the image field's crop dialog", async () => {
248+
const restore = failTheNextLoadOf('../widgets/ImageCropperDialog', { ImageCropperDialog: Loaded });
249+
try {
250+
const { ImageField } = await import('../widgets/ImageField');
251+
const cover = { name: 'cover.png', url: 'https://cdn.example/cover.png', mime_type: 'image/png' };
252+
await expectFailedThenRecovered(
253+
() => <ImageField field={{ name: 'p_cover', crop: true } as never} value={cover} onChange={() => {}} />,
254+
() => fireEvent.click(screen.getByTestId('image-field-crop-0')),
255+
);
256+
} finally {
257+
restore();
258+
}
259+
});
260+
261+
it('getLazyFieldWidget', async () => {
262+
const restore = failTheNextLoadOf('../widgets/date-picker/DatePickerField', {
263+
DatePickerField: Loaded,
264+
DateTimePickerField: Loaded,
265+
});
266+
try {
267+
const { getLazyFieldWidget } = await import('../index');
268+
const DateWidget = getLazyFieldWidget('date');
269+
await expectFailedThenRecovered(() => (
270+
<DateWidget field={{ name: 'due', type: 'date' }} value="2026-10-16" onChange={() => {}} />
271+
));
272+
} finally {
273+
restore();
274+
}
275+
});
276+
277+
it('registerField (the form registry)', async () => {
278+
const restore = failTheNextLoadOf('../widgets/date-picker/DatePickerField', {
279+
DatePickerField: Loaded,
280+
DateTimePickerField: Loaded,
281+
});
282+
try {
283+
const { registerField } = await import('../index');
284+
const { ComponentRegistry } = await import('@object-ui/core');
285+
registerField('date');
286+
const Registered = ComponentRegistry.get('date', 'field') as React.ComponentType<Record<string, unknown>>;
287+
expect(Registered).toBeTruthy();
288+
await expectFailedThenRecovered(() => (
289+
<Registered schema={{ name: 'due', type: 'date' }} value="2026-10-16" onChange={() => {}} />
290+
));
291+
} finally {
292+
restore();
293+
}
294+
});
295+
});

0 commit comments

Comments
 (0)