From 17ec6d7ae2521ea06ad30d5eca91ba679630b701 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 21:42:36 +0000 Subject: [PATCH 1/5] wip(fields): recoverable lazy field widgets --- ui/packages/fields/src/FieldEditWidget.tsx | 7 +- .../lazyWidgetRecovery-36608.test.tsx | 290 ++++++++++++++++++ ui/packages/fields/src/index.tsx | 24 +- ui/packages/fields/src/recoverableLazy.ts | 91 ++++++ .../src/widgets/FilterConditionCell.tsx | 3 +- ui/packages/fields/src/widgets/ImageField.tsx | 5 +- .../fields/src/widgets/richTextDisplay.tsx | 3 +- 7 files changed, 406 insertions(+), 17 deletions(-) create mode 100644 ui/packages/fields/src/__tests__/lazyWidgetRecovery-36608.test.tsx create mode 100644 ui/packages/fields/src/recoverableLazy.ts diff --git a/ui/packages/fields/src/FieldEditWidget.tsx b/ui/packages/fields/src/FieldEditWidget.tsx index 12f20f024e4..bdc6399d813 100644 --- a/ui/packages/fields/src/FieldEditWidget.tsx +++ b/ui/packages/fields/src/FieldEditWidget.tsx @@ -7,6 +7,7 @@ */ import React from 'react'; +import { recoverableLazy } from './recoverableLazy.js'; import type { FieldWidgetComponentProps } from './widgets/types.js'; // The package's own executor of the DOM pass-through declaration, reused here // 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'; * what makes that text reach the edit (objectui#12664, the `renderCellEditor` * contract on `DataTableSchema`). */ -const DatePickerEditWidget = React.lazy(() => +const DatePickerEditWidget = recoverableLazy(() => import('./widgets/date-picker/DatePickerField.js').then((m) => ({ default: m.DatePickerField })), ); -const DateTimePickerEditWidget = React.lazy(() => +const DateTimePickerEditWidget = recoverableLazy(() => import('./widgets/date-picker/DatePickerField.js').then((m) => ({ default: m.DateTimePickerField })), ); @@ -105,7 +106,7 @@ const DateTimePickerEditWidget = React.lazy(() => * uses for these three types, for the list grid's cell panel * ({@link IN_CELL_PANEL_EDIT_WIDGETS}). */ -const RichTextPanelEditWidget = React.lazy(() => +const RichTextPanelEditWidget = recoverableLazy(() => import('./widgets/RichTextField.js').then((m) => ({ default: m.RichTextField })), ); diff --git a/ui/packages/fields/src/__tests__/lazyWidgetRecovery-36608.test.tsx b/ui/packages/fields/src/__tests__/lazyWidgetRecovery-36608.test.tsx new file mode 100644 index 00000000000..da83167aff4 --- /dev/null +++ b/ui/packages/fields/src/__tests__/lazyWidgetRecovery-36608.test.tsx @@ -0,0 +1,290 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#36608 — a lazily loaded field widget whose first chunk load + * fails (a deploy that replaced the chunk, a dropped connection) must not keep + * that failure until the page is reloaded. Every lazy site of this package goes + * through `recoverableLazy`; the first block pins the helper, the rest pin each + * site: a failed first load reaches the error boundary, and a later mount + * renders the widget once the chunk is reachable. + */ +import React from 'react'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; + +afterEach(() => cleanup()); + +class Boundary extends React.Component<{ children: React.ReactNode }, { failed: boolean }> { + state = { failed: false }; + static getDerivedStateFromError() { + return { failed: true }; + } + render() { + return this.state.failed ?
: this.props.children; + } +} + +/** Lets pending promises and timers settle. */ +const settle = () => new Promise((resolve) => setTimeout(resolve, 30)); + +function Loaded(): React.ReactElement { + return
; +} + +describe('recoverableLazy', () => { + async function load() { + vi.resetModules(); + return (await import('../recoverableLazy')).recoverableLazy; + } + + function tree(Widget: React.ComponentType) { + return ( + + }> + + + + ); + } + + it('suspends to the host fallback while loading, and a later mount renders in the same pass', async () => { + const recoverableLazy = await load(); + const loader = vi.fn(async () => ({ default: Loaded })); + const Widget = recoverableLazy(loader); + + const first = render(tree(Widget)); + expect(screen.getByTestId('host-fallback')).toBeTruthy(); + await screen.findByTestId('widget-loaded'); + first.unmount(); + + render(tree(Widget)); + expect(screen.getByTestId('widget-loaded')).toBeTruthy(); + expect(loader).toHaveBeenCalledTimes(1); + }); + + it('mounts that ask while the chunk loads share one request', async () => { + const recoverableLazy = await load(); + const loader = vi.fn(async () => ({ default: Loaded })); + const Widget = recoverableLazy(loader); + + render( + + + + , + ); + await waitFor(() => expect(screen.getAllByTestId('widget-loaded')).toHaveLength(2)); + expect(loader).toHaveBeenCalledTimes(1); + }); + + it('a failed load reaches the error boundary once, without asking again, and the next mount loads', async () => { + const recoverableLazy = await load(); + const quiet = vi.spyOn(console, 'error').mockImplementation(() => {}); + try { + const loader = vi + .fn<() => Promise<{ default: React.ComponentType }>>() + .mockRejectedValueOnce(new Error('Failed to fetch dynamically imported module')) + .mockResolvedValue({ default: Loaded }); + const Widget = recoverableLazy(loader); + + const first = render(tree(Widget)); + await screen.findByTestId('load-failed'); + // The failure is shown, not retried in a loop behind the loading face. + await settle(); + expect(loader).toHaveBeenCalledTimes(1); + first.unmount(); + + render(tree(Widget)); + await screen.findByTestId('widget-loaded'); + expect(screen.queryByTestId('load-failed')).toBeNull(); + expect(loader).toHaveBeenCalledTimes(2); + } finally { + quiet.mockRestore(); + } + }); + + it('holds under StrictMode: one request per failure, and the next mount loads', async () => { + const recoverableLazy = await load(); + const quiet = vi.spyOn(console, 'error').mockImplementation(() => {}); + try { + const loader = vi + .fn<() => Promise<{ default: React.ComponentType }>>() + .mockRejectedValueOnce(new Error('Failed to fetch dynamically imported module')) + .mockResolvedValue({ default: Loaded }); + const Widget = recoverableLazy(loader); + + const first = render({tree(Widget)}); + await screen.findByTestId('load-failed'); + await settle(); + expect(loader).toHaveBeenCalledTimes(1); + first.unmount(); + + render({tree(Widget)}); + await screen.findByTestId('widget-loaded'); + expect(loader).toHaveBeenCalledTimes(2); + } finally { + quiet.mockRestore(); + } + }); +}); + +/** + * Fail the next load of `chunk` (a path relative to this file) once, then + * answer `loaded`. Restored by the returned call. + */ +function failTheNextLoadOf(chunk: string, loaded: Record): () => void { + vi.resetModules(); + let failNextLoad = true; + vi.doMock(chunk, () => { + if (failNextLoad) { + failNextLoad = false; + throw new Error(`Failed to fetch dynamically imported module: ${chunk}`); + } + return loaded; + }); + const quiet = vi.spyOn(console, 'error').mockImplementation(() => {}); + return () => { + quiet.mockRestore(); + vi.doUnmock(chunk); + }; +} + +/** Mounts `draw()` under a boundary: first the failure, then — on a later mount — the widget. */ +async function expectFailedThenRecovered(draw: () => React.ReactElement, afterMount?: () => void): Promise { + const first = render({draw()}); + afterMount?.(); + await screen.findByTestId('load-failed'); + first.unmount(); + + render({draw()}); + afterMount?.(); + await screen.findByTestId('widget-loaded'); + expect(screen.queryByTestId('load-failed')).toBeNull(); +} + +describe('each lazy field-widget site recovers after one failed chunk load', () => { + it('FieldEditWidget: the date picker', async () => { + const restore = failTheNextLoadOf('../widgets/date-picker/DatePickerField', { + DatePickerField: Loaded, + DateTimePickerField: Loaded, + }); + try { + const { FieldEditWidget } = await import('../FieldEditWidget'); + await expectFailedThenRecovered(() => ( + {}} /> + )); + } finally { + restore(); + } + }); + + it('FieldEditWidget: the datetime picker', async () => { + const restore = failTheNextLoadOf('../widgets/date-picker/DatePickerField', { + DatePickerField: Loaded, + DateTimePickerField: Loaded, + }); + try { + const { FieldEditWidget } = await import('../FieldEditWidget'); + await expectFailedThenRecovered(() => ( + {}} /> + )); + } finally { + restore(); + } + }); + + it("FieldEditWidget: the rich text editor in the cell's panel", async () => { + const restore = failTheNextLoadOf('../widgets/RichTextField', { RichTextField: Loaded }); + try { + const { FieldEditWidget } = await import('../FieldEditWidget'); + await expectFailedThenRecovered(() => ( + {}} inCell /> + )); + } finally { + restore(); + } + }); + + it('the markdown read face (richTextDisplay)', async () => { + const restore = failTheNextLoadOf('../widgets/MarkdownContent', { default: Loaded }); + try { + const { RICH_TEXT_CELL_RENDERERS } = await import('../widgets/richTextDisplay'); + const Markdown = RICH_TEXT_CELL_RENDERERS.markdown; + await expectFailedThenRecovered(() => ( + + )); + } finally { + restore(); + } + }); + + it('FilterConditionCell', async () => { + const restore = failTheNextLoadOf('../widgets/FilterConditionField', { FilterConditionField: Loaded }); + try { + const { FilterConditionCell } = await import('../widgets/FilterConditionCell'); + await expectFailedThenRecovered(() => ( + + )); + } finally { + restore(); + } + }); + + it("the image field's crop dialog", async () => { + const restore = failTheNextLoadOf('../widgets/ImageCropperDialog', { ImageCropperDialog: Loaded }); + try { + const { ImageField } = await import('../widgets/ImageField'); + const cover = { name: 'cover.png', url: 'https://cdn.example/cover.png', mime_type: 'image/png' }; + await expectFailedThenRecovered( + () => {}} />, + () => fireEvent.click(screen.getByTestId('image-field-crop-0')), + ); + } finally { + restore(); + } + }); + + it('getLazyFieldWidget', async () => { + const restore = failTheNextLoadOf('../widgets/date-picker/DatePickerField', { + DatePickerField: Loaded, + DateTimePickerField: Loaded, + }); + try { + const { getLazyFieldWidget } = await import('../index'); + const DateWidget = getLazyFieldWidget('date'); + await expectFailedThenRecovered(() => ( + {}} /> + )); + } finally { + restore(); + } + }); + + it('registerField (the form registry)', async () => { + const restore = failTheNextLoadOf('../widgets/date-picker/DatePickerField', { + DatePickerField: Loaded, + DateTimePickerField: Loaded, + }); + try { + const { registerField } = await import('../index'); + const { ComponentRegistry } = await import('@object-ui/core'); + registerField('date'); + const Registered = ComponentRegistry.get('date', 'field') as React.ComponentType>; + expect(Registered).toBeTruthy(); + await expectFailedThenRecovered(() => ( + {}} /> + )); + } finally { + restore(); + } + }); +}); diff --git a/ui/packages/fields/src/index.tsx b/ui/packages/fields/src/index.tsx index 0431cf91cd2..3634e231d86 100644 --- a/ui/packages/fields/src/index.tsx +++ b/ui/packages/fields/src/index.tsx @@ -24,6 +24,7 @@ import { SchemaRendererContext as _SchemaRendererContext } from '@object-ui/reac import { useRelatedRecordActions } from '@object-ui/react'; import { usePermissions } from '@object-ui/permissions'; import { withFieldCarrier } from './withFieldCarrier.js'; +import { recoverableLazy } from './recoverableLazy.js'; // Pure formatting rule shared with `AddressField`'s readonly branch — no React, // so this does not pull the widget out of its lazy chunk (objectui#4037). import { formatAddress, type AddressValue } from './widgets/address-format.js'; @@ -4834,8 +4835,8 @@ const fieldWidgetMap = { 'vector': () => import('./widgets/VectorField.js').then(m => ({ default: m.VectorField })), // 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). + // failed load, where a lazy wrapper around the body here would add a second + // loader beside the face's own (objectstack#36451). 'grid': () => Promise.resolve({ default: GridField }), // Additional field types from @objectstack/spec @@ -4969,22 +4970,24 @@ export { fieldHelpText } from './fieldHelpText.js'; // page's compact related rows). export { RecordHoverCard, type RecordHoverCardProps, type RecordHoverCardObjectDef } from './RecordHoverCard.js'; -/** Cache so each widget type creates one lazy component (and one chunk request). */ +/** Cache so each widget type creates one lazy component (and one chunk request at a time). */ const lazyFieldWidgets = new Map>(); /** * Lazily-loaded form field widget for a field type. Shares the exact loaders * of {@link fieldWidgetMap} (the same components `registerField` registers for - * forms), wrapped in `React.lazy` and cached per type — so a consumer can + * forms), wrapped in `recoverableLazy` and cached per type — so a consumer can * render any form-supported field type without eagerly bundling every widget. * Render inside a `` boundary. Unknown types resolve to the `text` - * widget via {@link resolveFormWidgetType}. + * widget via {@link resolveFormWidgetType}. A failed chunk load reaches the + * nearest error boundary and is not kept: the next mount loads again + * (objectstack#36608). */ export function getLazyFieldWidget(fieldType: string): React.ComponentType { const key = resolveFormWidgetType(fieldType); // A retired key has no loader in `fieldWidgetMap` by construction, so it is // answered with the tombstone before the lazy path (which would otherwise - // call `React.lazy(undefined)`). The tombstone is BOUND to `key`: a host + // call the lazy wrapper with no loader). The tombstone is BOUND to `key`: a host // that resolved the key from an authored `widget` hands over a `field` whose // `type` is a live type, and the refusal must name what was resolved // (objectui#10471) — see {@link retiredFieldTombstoneFor}. @@ -4992,7 +4995,7 @@ export function getLazyFieldWidget(fieldType: string): React.ComponentType let Widget = lazyFieldWidgets.get(key); if (!Widget) { // `resolveFormWidgetType` only returns keys the map holds, hence the `!`. - Widget = React.lazy(fieldWidgetLoaderByKey[key]!); + Widget = recoverableLazy(fieldWidgetLoaderByKey[key]!); lazyFieldWidgets.set(key, Widget); } return Widget; @@ -5052,7 +5055,7 @@ const FIELD_TYPES_SKIP_FALLBACK = new Set([ // `kind:'html'` page drew a code editor and dropped its text. 'code', // No other package owns the bare `time`/`address` key, but `registerField` - // wraps each call in a fresh `React.lazy(...)`, so re-registration (HMR, + // wraps each call in a fresh lazy component, so re-registration (HMR, // re-import) fails the registry's identity check every time and logs the // same "bare-name fallback overwritten" warning at every boot regardless. 'time', @@ -5229,8 +5232,9 @@ export function registerField(fieldType: string): void { return; } - // Create lazy component - const LazyFieldWidget = React.lazy(loader); + // Create lazy component. A failed chunk load is not kept: the next mount + // loads again (objectstack#36608). + const LazyFieldWidget = recoverableLazy(loader); // Register with field namespace. No LAYOUT wrapper — the form renderer owns // label/description/spacing. The only thing wrapped is the metadata carrier: diff --git a/ui/packages/fields/src/recoverableLazy.ts b/ui/packages/fields/src/recoverableLazy.ts new file mode 100644 index 00000000000..c77c9dd90db --- /dev/null +++ b/ui/packages/fields/src/recoverableLazy.ts @@ -0,0 +1,91 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +// JSX-free on purpose: this module is on the package's eager line, and every +// lazily loaded field widget reaches its chunk through it (objectstack#36608). +import React from 'react'; + +/** What `React.lazy` takes: a dynamic import of a module whose `default` is the component. */ +export type LazyWidgetLoader

= () => Promise<{ default: React.ComponentType

}>; + +/** One request for the chunk, shared by every mount that asks while it stands. */ +interface LoadAttempt

{ + readonly Lazy: React.ComponentType

; + /** Set once a failure of this request has been shown; the next mount asks again. */ + retired: boolean; +} + +/** + * `React.lazy`, except that a failed load is not kept for the rest of the + * session (objectstack#36608). + * + * A `React.lazy` component caches its first import promise, a rejection + * included: once the chunk fails to load (a deploy that replaced it, a dropped + * connection), every later mount rethrows that failure until the page is + * reloaded. Here each MOUNT picks the current request when it is first + * created, and a failure retires that request, so a later mount (an error + * boundary's reset, a reopened form, a revisited page) loads the chunk again. + * + * - Loading and loaded behave as `React.lazy` does: the mount suspends to the + * host's nearest `Suspense` boundary while the chunk loads, and a mount after + * it has loaded renders in the same pass. Every mount shares one request. + * - A failed load resolves to a stand-in that COMMITS once, rendering nothing, + * and then throws the failure to the nearest error boundary. Committing first + * is what makes the retry safe: a mount that never committed keeps no state, + * so React's own re-render of it (after the promise settles, or its one + * synchronous retry of an errored render) would otherwise pick a fresh + * request and suspend again, hiding the failure behind a loading face and + * asking the network in a loop. The committed mount holds on to the failed + * request, so it rethrows the same failure for as long as it is re-rendered; + * only a NEW mount asks again. + * + * Call it at module scope (or once per registration), never during render: + * each call is its own cache, as each `React.lazy` call is. + */ +export function recoverableLazy

(loader: LazyWidgetLoader

): React.ComponentType

{ + let current: LoadAttempt

| undefined; + + const currentAttempt = (): LoadAttempt

=> { + if (!current || current.retired) { + const attempt: { Lazy?: React.ComponentType

; retired: boolean } = { retired: false }; + attempt.Lazy = React.lazy(() => + loader().then( + (loaded) => loaded, + (error: unknown) => ({ default: failedLoad

(attempt as LoadAttempt

, error) }), + ), + ) as unknown as React.ComponentType

; + current = attempt as LoadAttempt

; + } + return current; + }; + + function RecoverableLazy(props: P): React.ReactElement { + // Picked once per mount: the mount that saw a failure keeps rethrowing it + // rather than asking the network again on every re-render. + const [attempt] = React.useState(currentAttempt); + return React.createElement(attempt.Lazy as React.ComponentType, props); + } + return RecoverableLazy; +} + +/** + * The stand-in a failed load resolves to: commits once (nothing drawn), retires + * the request so the next mount asks again, then throws the failure from its + * next render to the nearest error boundary. + */ +function failedLoad

(attempt: LoadAttempt

, error: unknown): React.ComponentType

{ + return function FailedLazyLoad(): null { + const [committed, setCommitted] = React.useState(false); + React.useEffect(() => { + attempt.retired = true; + setCommitted(true); + }, []); + if (committed) throw error; + return null; + }; +} diff --git a/ui/packages/fields/src/widgets/FilterConditionCell.tsx b/ui/packages/fields/src/widgets/FilterConditionCell.tsx index b76dbe4206a..caa318fbe32 100644 --- a/ui/packages/fields/src/widgets/FilterConditionCell.tsx +++ b/ui/packages/fields/src/widgets/FilterConditionCell.tsx @@ -25,8 +25,9 @@ import { EmptyValue } from '@object-ui/components'; import { isEmptyValue } from '@object-ui/core'; import { coerceToSafeValue } from '../coerceToSafeValue.js'; import type { CellRendererProps } from '../index.js'; +import { recoverableLazy } from '../recoverableLazy.js'; -const LazyFilterConditionField = React.lazy(() => +const LazyFilterConditionField = recoverableLazy(() => import('./FilterConditionField.js').then((m) => ({ default: m.FilterConditionField })), ); diff --git a/ui/packages/fields/src/widgets/ImageField.tsx b/ui/packages/fields/src/widgets/ImageField.tsx index 043fa421ba4..e1035f25f6d 100644 --- a/ui/packages/fields/src/widgets/ImageField.tsx +++ b/ui/packages/fields/src/widgets/ImageField.tsx @@ -1,4 +1,4 @@ -import React, { useRef, useState, useCallback, lazy, Suspense } from 'react'; +import React, { useRef, useState, useCallback, Suspense } from 'react'; import { Button, EmptyValue } from '@object-ui/components'; import { useUpload } from './UploadProvider.js'; import { useObjectTranslation } from '@object-ui/i18n'; @@ -29,10 +29,11 @@ import { fileValueForResubmit } from './file-refused.js'; import { RestrictedFileAffordance } from './file-affordance.js'; import { PHONE_TOUCH_HEIGHT } from './touchTarget.js'; import { pickNativeImage, useNativeImagePickOffered } from './nativeImagePick.js'; +import { recoverableLazy } from '../recoverableLazy.js'; // Lazy-load the cropper so the dialog (canvas + crop logic) is not in the initial // ImageField bundle. Consumers that never crop pay zero cost. -const ImageCropperDialog = lazy(() => +const ImageCropperDialog = recoverableLazy(() => import('./ImageCropperDialog.js').then((m) => ({ default: m.ImageCropperDialog })), ); diff --git a/ui/packages/fields/src/widgets/richTextDisplay.tsx b/ui/packages/fields/src/widgets/richTextDisplay.tsx index baccb823651..7c52ad65338 100644 --- a/ui/packages/fields/src/widgets/richTextDisplay.tsx +++ b/ui/packages/fields/src/widgets/richTextDisplay.tsx @@ -36,8 +36,9 @@ import { EmptyValue } from '@object-ui/components'; import { coerceToSafeValue } from '../coerceToSafeValue.js'; import { renderSanitizedHtml } from './sanitizedHtml.js'; import type { CellRendererProps } from '../index.js'; +import { recoverableLazy } from '../recoverableLazy.js'; -const LazyMarkdownContent = React.lazy(() => import('./MarkdownContent.js')); +const LazyMarkdownContent = recoverableLazy(() => import('./MarkdownContent.js')); /** * The two faces a rich-content value is drawn in, shared by the markdown and From c42f157fd779b319910272e46366b130873b8973 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 21:50:40 +0000 Subject: [PATCH 2/5] chore(changeset): lazy field widgets recover after a failed chunk load --- .changeset/36608-lazy-field-widgets-recover.md | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 .changeset/36608-lazy-field-widgets-recover.md diff --git a/.changeset/36608-lazy-field-widgets-recover.md b/.changeset/36608-lazy-field-widgets-recover.md new file mode 100644 index 00000000000..a73d2b72917 --- /dev/null +++ b/.changeset/36608-lazy-field-widgets-recover.md @@ -0,0 +1,10 @@ +--- +'@object-ui/fields': patch +--- + +fix(fields): a lazily loaded field widget whose chunk failed to load once loads again on its next mount, with no page reload + +Clause-②: no +Metadata-protocol: none + +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. From 3a71d955beafb42cbb99ebda7a7edbb8003daf17 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 22:03:09 +0000 Subject: [PATCH 3/5] fix(fields): type recoverableLazy like React.lazy --- ui/packages/fields/src/recoverableLazy.ts | 30 ++++++++++++----------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/ui/packages/fields/src/recoverableLazy.ts b/ui/packages/fields/src/recoverableLazy.ts index c77c9dd90db..e032eb87b34 100644 --- a/ui/packages/fields/src/recoverableLazy.ts +++ b/ui/packages/fields/src/recoverableLazy.ts @@ -11,11 +11,11 @@ import React from 'react'; /** What `React.lazy` takes: a dynamic import of a module whose `default` is the component. */ -export type LazyWidgetLoader

= () => Promise<{ default: React.ComponentType

}>; +export type LazyWidgetLoader> = () => Promise<{ default: C }>; /** One request for the chunk, shared by every mount that asks while it stands. */ -interface LoadAttempt

{ - readonly Lazy: React.ComponentType

; +interface LoadAttempt { + readonly Lazy: React.ComponentType; /** Set once a failure of this request has been shown; the next mount asks again. */ retired: boolean; } @@ -47,28 +47,30 @@ interface LoadAttempt

{ * Call it at module scope (or once per registration), never during render: * each call is its own cache, as each `React.lazy` call is. */ -export function recoverableLazy

(loader: LazyWidgetLoader

): React.ComponentType

{ - let current: LoadAttempt

| undefined; +export function recoverableLazy>( + loader: LazyWidgetLoader, +): React.ComponentType> { + let current: LoadAttempt | undefined; - const currentAttempt = (): LoadAttempt

=> { + const currentAttempt = (): LoadAttempt => { if (!current || current.retired) { - const attempt: { Lazy?: React.ComponentType

; retired: boolean } = { retired: false }; - attempt.Lazy = React.lazy(() => + const attempt: { Lazy?: React.ComponentType; retired: boolean } = { retired: false }; + attempt.Lazy = React.lazy>(() => loader().then( (loaded) => loaded, - (error: unknown) => ({ default: failedLoad

(attempt as LoadAttempt

, error) }), + (error: unknown) => ({ default: failedLoad(attempt as LoadAttempt, error) }), ), - ) as unknown as React.ComponentType

; - current = attempt as LoadAttempt

; + ); + current = attempt as LoadAttempt; } return current; }; - function RecoverableLazy(props: P): React.ReactElement { + function RecoverableLazy(props: React.ComponentProps): React.ReactElement { // Picked once per mount: the mount that saw a failure keeps rethrowing it // rather than asking the network again on every re-render. const [attempt] = React.useState(currentAttempt); - return React.createElement(attempt.Lazy as React.ComponentType, props); + return React.createElement(attempt.Lazy, props); } return RecoverableLazy; } @@ -78,7 +80,7 @@ export function recoverableLazy

(loader: LazyWidgetLoader

): React.Component * the request so the next mount asks again, then throws the failure from its * next render to the nearest error boundary. */ -function failedLoad

(attempt: LoadAttempt

, error: unknown): React.ComponentType

{ +function failedLoad(attempt: LoadAttempt, error: unknown): React.ComponentType { return function FailedLazyLoad(): null { const [committed, setCommitted] = React.useState(false); React.useEffect(() => { From b572a5856104198246f6cd4f8c9ba955116fce47 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 22:14:02 +0000 Subject: [PATCH 4/5] test(fields): load the core registry at collection in the lazy recovery pins --- .../fields/src/__tests__/lazyWidgetRecovery-36608.test.tsx | 3 +++ 1 file changed, 3 insertions(+) diff --git a/ui/packages/fields/src/__tests__/lazyWidgetRecovery-36608.test.tsx b/ui/packages/fields/src/__tests__/lazyWidgetRecovery-36608.test.tsx index da83167aff4..3b65501e8b8 100644 --- a/ui/packages/fields/src/__tests__/lazyWidgetRecovery-36608.test.tsx +++ b/ui/packages/fields/src/__tests__/lazyWidgetRecovery-36608.test.tsx @@ -17,6 +17,9 @@ import React from 'react'; import { afterEach, describe, expect, it, vi } from 'vitest'; import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; +// Paid at collection, not inside a test's clock: the registry pin imports it +// again after `vi.resetModules` (check:test-source-alias). +import '@object-ui/core'; afterEach(() => cleanup()); From 672b03e08f725bfc6372c61e689641c5a32862d4 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 22:46:06 +0000 Subject: [PATCH 5/5] fix(fields): recoverable lazy widgets hand over the loaded widget through load(); the form-field census reads it --- .../form-field-channel-census-12130.test.tsx | 21 +++++--------- .../lazyWidgetRecovery-36608.test.tsx | 2 ++ ui/packages/fields/src/recoverableLazy.ts | 29 +++++++++++++++++-- 3 files changed, 35 insertions(+), 17 deletions(-) diff --git a/ui/examples/schema-catalog/test/form-field-channel-census-12130.test.tsx b/ui/examples/schema-catalog/test/form-field-channel-census-12130.test.tsx index 9981a2c75fd..a24368cab4c 100644 --- a/ui/examples/schema-catalog/test/form-field-channel-census-12130.test.tsx +++ b/ui/examples/schema-catalog/test/form-field-channel-census-12130.test.tsx @@ -121,23 +121,16 @@ function recorded(target: T, via: 'entry' | 'props'): T { /* ── every field widget, re-registered with recorded props ───────────────── */ -interface LazyInternals { - _init: (payload: unknown) => unknown; - _payload: unknown; -} type WidgetFn = (props: Record) => React.ReactNode; -/** The component a `React.lazy` resolves to. Module loading, not rendering. */ +/** + * The component a lazily loaded field widget resolves to. Module loading, not + * rendering: `getLazyFieldWidget` hands back the fields package's recoverable + * lazy component, whose `load()` resolves to the widget itself + * (objectstack#36608). + */ async function resolveLazy(lazy: unknown): Promise { - const internals = lazy as LazyInternals; - for (;;) { - try { - return internals._init(internals._payload); - } catch (pending) { - if (pending && typeof (pending as PromiseLike).then === 'function') await pending; - else throw pending; - } - } + return (lazy as { load(): Promise }).load(); } const MEMO = Symbol.for('react.memo'); diff --git a/ui/packages/fields/src/__tests__/lazyWidgetRecovery-36608.test.tsx b/ui/packages/fields/src/__tests__/lazyWidgetRecovery-36608.test.tsx index 3b65501e8b8..705c5f8ef1b 100644 --- a/ui/packages/fields/src/__tests__/lazyWidgetRecovery-36608.test.tsx +++ b/ui/packages/fields/src/__tests__/lazyWidgetRecovery-36608.test.tsx @@ -68,6 +68,8 @@ describe('recoverableLazy', () => { render(tree(Widget)); expect(screen.getByTestId('widget-loaded')).toBeTruthy(); + // `load()` hands over the widget itself, through the same request. + expect(await Widget.load()).toBe(Loaded); expect(loader).toHaveBeenCalledTimes(1); }); diff --git a/ui/packages/fields/src/recoverableLazy.ts b/ui/packages/fields/src/recoverableLazy.ts index e032eb87b34..ce4e65e3a46 100644 --- a/ui/packages/fields/src/recoverableLazy.ts +++ b/ui/packages/fields/src/recoverableLazy.ts @@ -13,6 +13,17 @@ import React from 'react'; /** What `React.lazy` takes: a dynamic import of a module whose `default` is the component. */ export type LazyWidgetLoader> = () => Promise<{ default: C }>; +/** + * The component {@link recoverableLazy} returns. `load()` resolves to the + * loaded widget itself, through the same shared request a mount makes (and, + * like a mount, asks again after a failure). It is the seam a caller that + * needs the widget's own function, not an element of it, reads instead of + * `React.lazy`'s private fields; hosts render the component and never need it. + */ +export type RecoverableLazyComponent> = React.ComponentType< + React.ComponentProps +> & { load(): Promise }; + /** One request for the chunk, shared by every mount that asks while it stands. */ interface LoadAttempt { readonly Lazy: React.ComponentType; @@ -49,14 +60,24 @@ interface LoadAttempt { */ export function recoverableLazy>( loader: LazyWidgetLoader, -): React.ComponentType> { +): RecoverableLazyComponent { let current: LoadAttempt | undefined; + // The import in flight, shared by every attempt and by `load()`; forgotten + // on failure, so whoever asks next imports again. + let inflight: Promise<{ default: C }> | undefined; + const importOnce = (): Promise<{ default: C }> => { + inflight ??= loader().catch((error: unknown) => { + inflight = undefined; + throw error; + }); + return inflight; + }; const currentAttempt = (): LoadAttempt => { if (!current || current.retired) { const attempt: { Lazy?: React.ComponentType; retired: boolean } = { retired: false }; attempt.Lazy = React.lazy>(() => - loader().then( + importOnce().then( (loaded) => loaded, (error: unknown) => ({ default: failedLoad(attempt as LoadAttempt, error) }), ), @@ -72,7 +93,9 @@ export function recoverableLazy>( const [attempt] = React.useState(currentAttempt); return React.createElement(attempt.Lazy, props); } - return RecoverableLazy; + return Object.assign(RecoverableLazy, { + load: (): Promise => importOnce().then((loaded) => loaded.default), + }); } /**