diff --git a/apps/website/content/docs/react/a2ui/getting-started/introduction.mdx b/apps/website/content/docs/react/a2ui/getting-started/introduction.mdx index 329f1eab2..762150ddd 100644 --- a/apps/website/content/docs/react/a2ui/getting-started/introduction.mdx +++ b/apps/website/content/docs/react/a2ui/getting-started/introduction.mdx @@ -13,6 +13,8 @@ The native React APIs on this page are experimental, private source-build packag The server sends a surface description and data-model updates. React retains the received surface, while form controls hold the traveler’s current edits. Search, Select, and Modify send intentional actions; typing does not start another agent run. The example admits a fixed flight-form profile rather than every possible A2UI component. +When components arrive before the data model, `A2uiSurface` shows a placeholder for each component whose data-bound props have no value yet, then mounts it once they do. An input's own `value` may stay unset, so an empty field the traveler fills in still appears. Pass `pendingFallback` to change the placeholder, or `null` to mount every component at once. + The [React conversation walkthrough](/docs/react/langgraph/concepts/conversation-turns) connects this capability to requests, tools, UI state, and saved history. ## Start a conversation diff --git a/apps/website/content/docs/react/render/guides/lifecycle.mdx b/apps/website/content/docs/react/render/guides/lifecycle.mdx index e07090f1c..383ad2899 100644 --- a/apps/website/content/docs/react/render/guides/lifecycle.mdx +++ b/apps/website/content/docs/react/render/guides/lifecycle.mdx @@ -21,7 +21,7 @@ These protections do not validate your application schema. Admit untrusted view Use stable element keys and registry component identities across updates. Container views must place the provided `children` where they belong. [Repeat loops](/docs/react/render/guides/repeat-loops) need meaningful unique identities when items can reorder. -A readiness registry entry can defer its component until its synchronous predicate accepts the props. Follow the [registry guide](/docs/react/render/guides/registry) for that mounted-view boundary. Readiness is presentation admission, not a network completion signal. +A registered component waits behind `RenderPendingFallback` while any resolved prop is undefined, and a readiness registry entry can defer its component until its synchronous predicate accepts the props. Follow the [registry guide](/docs/react/render/guides/registry) for that mounted-view boundary. Readiness is presentation admission, not a network completion signal. ## Retire owned work diff --git a/apps/website/content/docs/react/render/guides/registry.mdx b/apps/website/content/docs/react/render/guides/registry.mdx index 03fd86c34..987e85723 100644 --- a/apps/website/content/docs/react/render/guides/registry.mdx +++ b/apps/website/content/docs/react/render/guides/registry.mdx @@ -22,6 +22,27 @@ export const tripViews: ReactRenderRegistry = { }; ~~~ +## Wait for bound props + +As in the Angular renderer, a registered component does not mount while any of its resolved props is `undefined`, such as a `$state` binding whose path has not arrived. RenderSpec shows `RenderPendingFallback` in its place, a labelled shimmer card that uses the generative UI skeleton classes. Once every prop has a value, the component mounts and stays mounted for that element, even if a value later goes missing. Each repeat row waits on its own props. + +Pass a component as `pendingFallback` to show something else, or pass `null` to mount every component at once. To let one component mount with undefined props, register it as a readiness entry whose predicate always accepts: + +~~~tsx +import type { ReactRenderRegistry } from '@threadplane/react/render'; + +export const views: ReactRenderRegistry = { + Heading: ({ props }) =>

{String(props['text'] ?? '')}

, + Note: { + kind: 'readiness', + component: ({ props }) =>

{String(props['text'] ?? '')}

, + isReady: () => true, + }, +}; +~~~ + +A readiness entry decides with its own predicate. Without its own `fallback`, it shows the tree's `pendingFallback`. The element reports `mounted` to `onEvent` once, when the placeholder first renders, which matches the Angular renderer. + The [React conversation walkthrough](/docs/react/langgraph/concepts/conversation-turns) connects this capability to requests, tools, UI state, and saved history. ## Try each registry mode diff --git a/cockpit/ag-ui/json-render/react/src/dashboard-views.spec.tsx b/cockpit/ag-ui/json-render/react/src/dashboard-views.spec.tsx index c2384e1c7..23267d36a 100644 --- a/cockpit/ag-ui/json-render/react/src/dashboard-views.spec.tsx +++ b/cockpit/ag-ui/json-render/react/src/dashboard-views.spec.tsx @@ -255,7 +255,8 @@ it('updates the same retained layout from latest shared state without mutating t }); it('distinguishes unavailable data from valid empty lists and zero values', () => { const view = render(); - expect(screen.getAllByText('Waiting for dashboard data…')).toHaveLength(4); + // RenderSpec holds each view behind its placeholder until the bound data arrives. + expect(screen.getAllByText('Building UI…')).toHaveLength(4); view.rerender( { const view = render(); - expect(screen.getAllByText('Waiting for dashboard data…')).toHaveLength(4); + // RenderSpec holds each view behind its placeholder until the bound data arrives. + expect(screen.getAllByText('Building UI…')).toHaveLength(4); view.rerender( Mounted too early

; +} +const defaultWaitSpec: RenderSpecData = { + root: 'wait', + elements: { + wait: { type: 'Wait', props: { absent: { $state: '/missing' } } }, + }, +}; +const defaultWaitRegistry: ReactRenderRegistry = { Wait: DefaultWaitReal }; const rowSpec: RenderSpecData = { root: 'rows', elements: { @@ -184,18 +195,29 @@ function App() { return ( <>

{descriptor}

- +
+ +
+ {/* Direct exotic components receive undefined props only with the documented opt-out. */} +
+ +
); diff --git a/libs/react/src/a2ui/catalog/choices.spec.tsx b/libs/react/src/a2ui/catalog/choices.spec.tsx index 614132f1b..881d2ef48 100644 --- a/libs/react/src/a2ui/catalog/choices.spec.tsx +++ b/libs/react/src/a2ui/catalog/choices.spec.tsx @@ -313,7 +313,7 @@ describe('A2UI DateTimeInput', () => { }); it('maps min and max to the native bounds in the same format', () => { - const { element } = input({ min: '2026-03-01T00:00:00', max: { path: '/latest' } }, '2026-03-04'); + const { element } = input({ min: '2026-03-01T00:00:00' }, '2026-03-04'); expect([element.min, element.max]).toEqual(['2026-03-01', '']); cleanup(); const surfaces = store( diff --git a/libs/react/src/a2ui/catalog/index.ts b/libs/react/src/a2ui/catalog/index.ts index 57ae25f61..d07f3818d 100644 --- a/libs/react/src/a2ui/catalog/index.ts +++ b/libs/react/src/a2ui/catalog/index.ts @@ -1,4 +1,7 @@ -import type { ReactRenderRegistry } from '../../render/index.js'; +import type { + ReactRenderRegistry, + RenderReadinessEntry, +} from '../../render/index.js'; import { A2uiAudioPlayer } from './audio-player.js'; import { A2uiButton } from './button.js'; import { A2uiCard } from './card.js'; @@ -18,7 +21,22 @@ import { A2uiText } from './text.js'; import { A2uiTextField } from './text-field.js'; import { A2uiVideo } from './video.js'; -const CATALOG: ReactRenderRegistry = Object.freeze({ +/** + * An input waits, like every other component, while a prop such as its label + * has not arrived; its `value` alone may stay undefined, because the person + * fills an unseeded field. + */ +const ready: RenderReadinessEntry['isReady'] = (props) => + Object.entries(props).every( + ([key, value]) => key === 'value' || value !== undefined + ); +const input = ( + component: RenderReadinessEntry['component'] +): RenderReadinessEntry => + Object.freeze({ kind: 'readiness', component, isReady: ready }); + +/** Every basic component, mounted at once, for a surface whose `pendingFallback` is null. */ +const EAGER: ReactRenderRegistry = Object.freeze({ AudioPlayer: A2uiAudioPlayer, Button: A2uiButton, Card: A2uiCard, @@ -39,12 +57,28 @@ const CATALOG: ReactRenderRegistry = Object.freeze({ Video: A2uiVideo, }); +const CATALOG: ReactRenderRegistry = Object.freeze({ + ...EAGER, + CheckBox: input(A2uiCheckBox), + ChoicePicker: input(A2uiChoicePicker), + DateTimeInput: input(A2uiDateTimeInput), + Slider: input(A2uiSlider), + TextField: input(A2uiTextField), +}); + /** * The A2UI basic catalog: Text, Image, Icon, Video, AudioPlayer, Row, Column, * List, Card, Divider, Tabs, Modal, TextField, CheckBox, ChoicePicker, * DateTimeInput, Slider and Button. Inputs write to the surface's store when `A2uiSurface` is given one; - * a Button hands its event action to the surface's `onAction`. + * a Button hands its event action to the surface's `onAction`. A component + * shows a placeholder while a data-bound prop has no value yet, except an + * input's own `value`. */ export function a2uiBasicCatalog(): ReactRenderRegistry { return CATALOG; } + +/** The basic catalog without any wait, so every component mounts at once. */ +export function a2uiEagerCatalog(): ReactRenderRegistry { + return EAGER; +} diff --git a/libs/react/src/a2ui/message-surfaces.spec.tsx b/libs/react/src/a2ui/message-surfaces.spec.tsx index c0d6f3cad..850a1ec7a 100644 --- a/libs/react/src/a2ui/message-surfaces.spec.tsx +++ b/libs/react/src/a2ui/message-surfaces.spec.tsx @@ -158,8 +158,12 @@ describe('A2uiMessageSurfaces', () => { expect(view.queryByRole('status')).not.toBeNull(); expect(surfaceIds(view.container)).toEqual([]); view.rerender(); - expect(view.queryByRole('status')).toBeNull(); expect(surfaceIds(view.container)).toEqual(['trip']); + // The surface is live; only its Text bound to /title waits for the data model. + expect(view.getByRole('status').closest('.a2ui-surface')).not.toBeNull(); + view.rerender(); + expect(view.queryByRole('status')).toBeNull(); + expect(view.container.textContent).toContain('Lyon'); }); it('renders nothing for a finished message with no surface', () => { diff --git a/libs/react/src/a2ui/message-surfaces.tsx b/libs/react/src/a2ui/message-surfaces.tsx index e697d65ac..6b0b11576 100644 --- a/libs/react/src/a2ui/message-surfaces.tsx +++ b/libs/react/src/a2ui/message-surfaces.tsx @@ -25,7 +25,12 @@ export interface A2uiMessageContent { export interface A2uiMessageSurfacesProps extends Pick< A2uiSurfaceProps, - 'onAction' | 'onValidationError' | 'functions' | 'catalog' | 'className' + | 'onAction' + | 'onValidationError' + | 'functions' + | 'catalog' + | 'pendingFallback' + | 'className' > { readonly content: A2uiMessageContent; } diff --git a/libs/react/src/a2ui/readiness.spec.tsx b/libs/react/src/a2ui/readiness.spec.tsx new file mode 100644 index 000000000..3e82786d1 --- /dev/null +++ b/libs/react/src/a2ui/readiness.spec.tsx @@ -0,0 +1,80 @@ +import { cleanup, render } from '@testing-library/react'; +import { afterEach, describe, expect, it } from 'vitest'; +import type { A2uiSurfaceSnapshot } from '@threadplane/content/a2ui'; +import type { RenderViewProps } from '../render/index'; +import { A2uiSurface } from './index'; + +afterEach(cleanup); + +type Component = A2uiSurfaceSnapshot['components'][number]; +const surface = ( + components: readonly Component[], + dataModel: A2uiSurfaceSnapshot['dataModel'] = {} +): A2uiSurfaceSnapshot => ({ + surfaceId: 's1', + catalogId: 'basic', + components, + dataModel, +}); +const components: readonly Component[] = [ + { id: 'root', component: 'Column', children: ['title', 'guest'] }, + { id: 'title', component: 'Text', text: { path: '/title' } }, + { + id: 'guest', + component: 'TextField', + label: { path: '/guestLabel' }, + value: { path: '/guest' }, + }, +]; + +describe('A2uiSurface readiness', () => { + it('shows placeholders for components that arrive before the data model, then mounts them', () => { + const view = render(); + const pending = view.getAllByRole('status'); + expect(pending).toHaveLength(2); + expect(pending.every((el) => el.closest('.a2ui-surface'))).toBe(true); + expect(view.queryByRole('textbox')).toBeNull(); + + // The input value is never seeded: the person fills it in. + view.rerender( + + ); + expect(view.queryByRole('status')).toBeNull(); + expect(view.container.textContent).toContain('Lyon trip'); + expect((view.getByLabelText('Guest') as HTMLInputElement).value).toBe(''); + }); + + it('keeps a mounted component when its data later goes missing', () => { + const view = render( + + ); + const field = view.getByRole('textbox'); + view.rerender(); + expect(view.queryByRole('status')).toBeNull(); + expect(view.getByRole('textbox')).toBe(field); + }); + + it('takes a custom pendingFallback, or null to mount at once', () => { + const Pending = ({ elementKey }: RenderViewProps) => ( +

waiting

+ ); + const view = render( + + ); + expect( + [...view.container.querySelectorAll('[data-pending]')].map((el) => + el.getAttribute('data-pending') + ) + ).toEqual(['title', 'guest']); + cleanup(); + const eager = render( + + ); + expect(eager.queryByRole('status')).toBeNull(); + expect(eager.getByRole('textbox')).toBeTruthy(); + }); +}); diff --git a/libs/react/src/a2ui/styles.css b/libs/react/src/a2ui/styles.css index 43fabd734..6308be85d 100644 --- a/libs/react/src/a2ui/styles.css +++ b/libs/react/src/a2ui/styles.css @@ -541,6 +541,63 @@ .a2ui-unsupported { display: contents; } +/* RenderPendingFallback: a component whose data-bound props have not arrived. */ +.a2ui-surface .tp-render-pending { + display: block; + box-sizing: border-box; + inline-size: 100%; + min-inline-size: 0; + padding: var(--a2ui-spacing-3); + border: 1px solid var(--a2ui-outline); + border-radius: var(--a2ui-shape-medium); + background: var(--a2ui-surface-variant); + color: var(--a2ui-on-surface-variant); + font-size: var(--a2ui-typography-label-size); +} +.a2ui-surface .tp-render-pending .tp-genui-skeleton__label { + display: block; + margin-block-end: var(--a2ui-spacing-2); +} +.a2ui-surface .tp-render-pending .tp-genui-skeleton__rows { + display: flex; + flex-direction: column; + gap: var(--a2ui-spacing-2); +} +.a2ui-surface .tp-render-pending .tp-genui-skeleton__row { + display: block; + block-size: 0.625rem; + border-radius: var(--a2ui-shape-extra-small); + background: linear-gradient( + 90deg, + color-mix(in srgb, currentColor 22%, transparent) 0%, + color-mix(in srgb, currentColor 10%, transparent) 50%, + color-mix(in srgb, currentColor 22%, transparent) 100% + ); + background-size: 200% 100%; + animation: a2ui-pending-shimmer 1.4s ease-in-out infinite; +} +.a2ui-surface .tp-render-pending .tp-genui-skeleton__row:nth-child(1) { + inline-size: 70%; +} +.a2ui-surface .tp-render-pending .tp-genui-skeleton__row:nth-child(2) { + inline-size: 90%; +} +.a2ui-surface .tp-render-pending .tp-genui-skeleton__row:nth-child(3) { + inline-size: 50%; +} +@keyframes a2ui-pending-shimmer { + 0% { + background-position: 200% 0; + } + 100% { + background-position: -200% 0; + } +} +@media (prefers-reduced-motion: reduce) { + .a2ui-surface .tp-render-pending .tp-genui-skeleton__row { + animation: none; + } +} @media (forced-colors: active) { .a2ui-card, .a2ui-divider--horizontal { @@ -555,6 +612,12 @@ .a2ui-modal { border-color: CanvasText; } + .a2ui-surface .tp-render-pending { + border-color: CanvasText; + } + .a2ui-surface .tp-render-pending .tp-genui-skeleton__row { + background: GrayText; + } .a2ui-tf__input, .a2ui-dti__input, .a2ui-cp__filter { diff --git a/libs/react/src/a2ui/surface.tsx b/libs/react/src/a2ui/surface.tsx index 99fef827a..0b0664a0f 100644 --- a/libs/react/src/a2ui/surface.tsx +++ b/libs/react/src/a2ui/surface.tsx @@ -11,8 +11,12 @@ import { type A2uiSurfaceSnapshot, type A2uiValue, } from '@threadplane/content/a2ui'; -import { RenderSpec, type ReactRenderRegistry } from '../render/index.js'; -import { a2uiBasicCatalog } from './catalog/index.js'; +import { + RenderSpec, + type ReactRenderRegistry, + type RenderSpecProps, +} from '../render/index.js'; +import { a2uiBasicCatalog, a2uiEagerCatalog } from './catalog/index.js'; import { A2uiDefaultFallback } from './default-fallback.js'; import { A2uiActionContext, @@ -137,6 +141,13 @@ export interface A2uiSurfaceProps { }; /** Components by A2UI name. Defaults to `a2uiBasicCatalog()`; keep it stable. */ readonly catalog?: ReactRenderRegistry; + /** + * Shown in place of a component while a data-bound prop has no value yet, + * such as components that arrive before the data model. Defaults to + * `RenderPendingFallback`; `null` mounts every component of the default + * catalog at once. A readiness entry in your own `catalog` still decides. + */ + readonly pendingFallback?: RenderSpecProps['pendingFallback']; readonly className?: string; } @@ -149,7 +160,9 @@ export interface A2uiSurfaceProps { * show their messages until they pass. A Button whose own `checks` fail is * disabled. A Button with a function-call action runs it here, through * `functions` or the built-in `openUrl`, without consulting `checks` on - * inputs. Function-call props show their current value. A component the + * inputs. Function-call props show their current value. A component whose + * data-bound props have not arrived shows `pendingFallback` until they do, + * then stays mounted; an input's own `value` may stay unset. A component the * catalog lacks keeps its children. A child template is stamped once per * item of its list; inputs, checks and actions inside it work on that item. * The surface's `theme` sets the accent colour from a hex `primaryColor` and @@ -162,6 +175,7 @@ export function A2uiSurface({ onValidationError, functions, catalog, + pendingFallback, className, }: A2uiSurfaceProps) { const { spec, state, sources } = useMemo( @@ -276,9 +290,13 @@ export function A2uiSurface({ diff --git a/libs/react/src/a2ui/surface.type-test.tsx b/libs/react/src/a2ui/surface.type-test.tsx index de3bfc5a1..3030457bf 100644 --- a/libs/react/src/a2ui/surface.type-test.tsx +++ b/libs/react/src/a2ui/surface.type-test.tsx @@ -5,9 +5,12 @@ import type { A2uiValidationErrorMessage, A2uiValue, } from '@threadplane/content/a2ui'; -import type { ReactNode } from 'react'; +import type { ComponentType, ReactNode } from 'react'; import type { MessageA2uiContent } from '../chat/index.js'; -import type { ReactRenderRegistry } from '../render/index.js'; +import type { + ReactRenderRegistry, + RenderViewProps, +} from '../render/index.js'; import { A2uiMessageSurfaces, A2uiSurface, @@ -40,6 +43,7 @@ export type PropsContract = Assert< }) => void; }; readonly catalog?: ReactRenderRegistry; + readonly pendingFallback?: ComponentType | null; readonly className?: string; } > @@ -150,7 +154,12 @@ export type MessageSurfacesPropsContract = Assert< { [K in keyof A2uiMessageSurfacesProps]: A2uiMessageSurfacesProps[K] }, { readonly content: A2uiMessageContent } & Pick< A2uiSurfaceProps, - 'onAction' | 'onValidationError' | 'functions' | 'catalog' | 'className' + | 'onAction' + | 'onValidationError' + | 'functions' + | 'catalog' + | 'pendingFallback' + | 'className' > extends infer T ? { [K in keyof T]: T[K] } : never diff --git a/libs/react/src/chat/generative-ui.tsx b/libs/react/src/chat/generative-ui.tsx index 006707ed2..fad7c0cec 100644 --- a/libs/react/src/chat/generative-ui.tsx +++ b/libs/react/src/chat/generative-ui.tsx @@ -74,6 +74,11 @@ export interface MessageGenerativeUi { readonly functions?: ReactRenderFunctions; /** Rendered for a spec component the registry lacks; see `RenderSpecProps.fallback`. */ readonly fallback?: ComponentType; + /** + * Shown in place of a spec element while a bound prop has no value yet; see + * `RenderSpecProps.pendingFallback`. `null` mounts every element at once. + */ + readonly pendingFallback?: ComponentType | null; /** * Actions a spec's `on` bindings may run; see `RenderSpecProps.handlers`. A * binding that names an action missing here does nothing. Setting this @@ -314,6 +319,7 @@ function SpecSurface({ registry: options.registry, functions: options.functions, fallback: options.fallback, + pendingFallback: options.pendingFallback, loading: streaming, }; return ( diff --git a/libs/react/src/chat/message-list-interactive-ui.spec.tsx b/libs/react/src/chat/message-list-interactive-ui.spec.tsx index f1a52bf12..e5dd16ab9 100644 --- a/libs/react/src/chat/message-list-interactive-ui.spec.tsx +++ b/libs/react/src/chat/message-list-interactive-ui.spec.tsx @@ -194,12 +194,30 @@ describe('MessageList generativeUi interaction', () => { const view = render( ); - expect(echoes(view.container)).toEqual(['']); + // Bound props wait for the state, behind the render placeholder. + expect(echoes(view.container)).toEqual([]); + expect(view.container.querySelector('.tp-render-pending')).not.toBeNull(); view.rerender(); + expect(view.container.querySelector('.tp-render-pending')).toBeNull(); expect(echoes(view.container)).toEqual(['Ada']); fireEvent.change(view.getByRole('textbox', { name: 'Guest' }), { target: { value: 'Grace' }, }); expect(echoes(view.container)).toEqual(['Grace']); }); + + it('mounts bound elements at once with pendingFallback null', () => { + const content = createMessageContent(); + const rows = content.project( + snapshot([assistant(FORM.slice(0, FORM.indexOf(',"state"')), 'a', true)]) + ); + const options: MessageGenerativeUi = { + registry, + handlers: {}, + pendingFallback: null, + }; + const view = render(); + expect(echoes(view.container)).toEqual(['']); + expect(view.container.querySelector('.tp-render-pending')).toBeNull(); + }); }); diff --git a/libs/react/src/render/computed-functions.spec.tsx b/libs/react/src/render/computed-functions.spec.tsx index 566ac12d9..8f0e9d35e 100644 --- a/libs/react/src/render/computed-functions.spec.tsx +++ b/libs/react/src/render/computed-functions.spec.tsx @@ -221,7 +221,9 @@ describe('RenderSpec computed functions', () => { {...{ functions: {} }} /> ); - expect(view.container.querySelector('p')?.textContent).toBe(''); + // An unknown function resolves to undefined, so the element waits. + expect(view.container.querySelector('p')).toBeNull(); + expect(view.getByRole('status')).toBeTruthy(); } ); diff --git a/libs/react/src/render/default-readiness.spec.tsx b/libs/react/src/render/default-readiness.spec.tsx new file mode 100644 index 000000000..9f2b0f08e --- /dev/null +++ b/libs/react/src/render/default-readiness.spec.tsx @@ -0,0 +1,186 @@ +import { cleanup, render } from '@testing-library/react'; +import { afterEach, describe, expect, it } from 'vitest'; +import { + RenderPendingFallback, + RenderSpec, + type ReactRenderRegistry, + type RenderEvent, + type RenderSpecData, + type RenderViewProps, +} from './index'; + +afterEach(cleanup); + +const Label = ({ props }: RenderViewProps) => ( +

{String(props['text'])}

+); +const Box = ({ children }: RenderViewProps) =>
{children}
; +const bound: RenderSpecData = { + root: 'label', + elements: { + label: { type: 'Label', props: { text: { $state: '/title' } } }, + }, +}; + +describe('default readiness', () => { + it('shows the default placeholder while a bound prop is undefined, then the component', () => { + const view = render( + + ); + expect(view.queryByTestId('label')).toBeNull(); + const status = view.getByRole('status'); + expect(status.className).toContain('tp-genui-skeleton'); + expect(status.textContent).toContain('Building UI'); + view.rerender( + + ); + expect(view.queryByRole('status')).toBeNull(); + expect(view.getByTestId('label').textContent).toBe('Lyon'); + }); + + it('latches: a ready element never returns to the placeholder', () => { + const view = render( + + ); + const label = view.getByTestId('label'); + view.rerender(); + expect(view.queryByRole('status')).toBeNull(); + expect(view.getByTestId('label')).toBe(label); + expect(label.textContent).toBe('undefined'); + }); + + it('mounts an element with only literal or defined props at once', () => { + const spec: RenderSpecData = { + root: 'label', + elements: { label: { type: 'Label', props: { text: 'Plain' } } }, + }; + const view = render(); + expect(view.queryByRole('status')).toBeNull(); + expect(view.getByTestId('label').textContent).toBe('Plain'); + }); + + it('gates each repeat row on its own props and latches per row', () => { + const spec: RenderSpecData = { + root: 'rows', + elements: { + rows: { + type: 'Box', + props: {}, + children: ['row'], + repeat: { statePath: '/rows', key: 'id' }, + }, + row: { type: 'Label', props: { text: { $item: 'text' } } }, + }, + }; + const registry = { Box, Label } satisfies ReactRenderRegistry; + const view = render( + + ); + expect(view.getAllByTestId('label').map((el) => el.textContent)).toEqual([ + 'A', + ]); + expect(view.getAllByRole('status')).toHaveLength(1); + view.rerender( + + ); + expect(view.queryByRole('status')).toBeNull(); + expect(view.getAllByTestId('label').map((el) => el.textContent)).toEqual([ + 'undefined', + 'B', + ]); + }); + + it('uses a custom pendingFallback with the pending view props', () => { + const Pending = ({ elementKey, props }: RenderViewProps) => ( +

+ waiting {elementKey} {String('text' in props)} +

+ ); + const view = render( + + ); + expect(view.getByText('waiting label true')).toBeTruthy(); + expect(view.queryByRole('status')).toBeNull(); + }); + + it('opts out for the tree with pendingFallback null', () => { + const view = render( + + ); + expect(view.queryByRole('status')).toBeNull(); + expect(view.getByTestId('label').textContent).toBe('undefined'); + }); + + it('opts out for one entry with a readiness entry that is always ready', () => { + const registry = { + Label: { kind: 'readiness', component: Label, isReady: () => true }, + } satisfies ReactRenderRegistry; + const view = render( + + ); + expect(view.queryByRole('status')).toBeNull(); + expect(view.getByTestId('label').textContent).toBe('undefined'); + }); + + it('does not gate the fallback for unknown types', () => { + const spec: RenderSpecData = { + root: 'x', + elements: { x: { type: 'Unknown', props: { text: { $state: '/t' } } } }, + }; + const view = render( + + ); + expect(view.getByTestId('label').textContent).toBe('undefined'); + }); + + it('reports the element mounted once, while the placeholder shows, as Angular does', () => { + const events: RenderEvent[] = []; + const view = render( + events.push(event)} + /> + ); + view.rerender( + events.push(event)} + /> + ); + const mounts = events.filter( + (event) => + event.type === 'lifecycle' && + event.scope === 'element' && + event.event === 'mounted' + ); + expect(mounts).toHaveLength(1); + expect(view.getByTestId('label').textContent).toBe('Lyon'); + }); + + it('exports the default placeholder for reuse', () => { + const view = render(); + expect(view.getByRole('status').textContent).toContain('Building UI'); + }); +}); diff --git a/libs/react/src/render/index.ts b/libs/react/src/render/index.ts index 680fddc6a..3afbece6b 100644 --- a/libs/react/src/render/index.ts +++ b/libs/react/src/render/index.ts @@ -1,5 +1,6 @@ 'use client'; export { RenderSpec } from './render-spec.js'; +export { RenderPendingFallback } from './pending-fallback.js'; export { RenderDevtools } from './devtools.js'; export type { RenderDevtoolsProps } from './devtools.js'; export { createRenderLifecycle } from './lifecycle.js'; diff --git a/libs/react/src/render/pending-fallback.tsx b/libs/react/src/render/pending-fallback.tsx new file mode 100644 index 000000000..994140dee --- /dev/null +++ b/libs/react/src/render/pending-fallback.tsx @@ -0,0 +1,24 @@ +import type { ComponentType } from 'react'; +import type { RenderViewProps } from './types.js'; + +/** + * The placeholder `RenderSpec` shows in place of a registered element while any + * of its resolved props is still undefined. It uses the `GenerativeUiSkeleton` + * markup and classes, so the chat and A2UI stylesheets style it. Pass your own + * component as `RenderSpec`'s `pendingFallback` to replace it. + */ +export const RenderPendingFallback: ComponentType = () => ( +
+ Building UI… +
+); diff --git a/libs/react/src/render/readiness.spec.tsx b/libs/react/src/render/readiness.spec.tsx index a1f42583f..1a641b85a 100644 --- a/libs/react/src/render/readiness.spec.tsx +++ b/libs/react/src/render/readiness.spec.tsx @@ -108,10 +108,17 @@ function node(value?: string) { } function mount( initial: RenderReadinessEntry = entry(), - state: NonNullable = node('ready') + state: NonNullable = node('ready'), + // `null` turns off the default wait for direct components. + pendingFallback?: null ) { const view = render( - + ); return { ...view, @@ -120,7 +127,12 @@ function mount( nextState = node() ) { view.rerender( - + ); }, }; @@ -133,7 +145,7 @@ function edit(view: ReturnType) { describe('readiness contracts', () => { it.each(['function', 'memo', 'forwardRef'])( - 'keeps direct %s views immediate with undefined props', + 'keeps direct %s views immediate with undefined props when pendingFallback is null', (kind) => { const Component = kind === 'memo' @@ -145,7 +157,7 @@ describe('readiness contracts', () => { )) : Input; - const view = mount(entry()); + const view = mount(entry(), node('ready'), null); view.update(Component); expect(view.getByText('undefined')).toBeTruthy(); expect(view.getByRole('textbox')).toBeTruthy(); @@ -251,7 +263,7 @@ describe('readiness contracts', () => { ) ).toThrow(error); }); - it('uses null for absent pending fallback and reserves top fallback for unknown types', () => { + it('uses the tree placeholder for absent pending fallback, null when turned off, and reserves top fallback for unknown types', () => { const top = vi.fn(() =>

unknown

); const view = render( { fallback={top} /> ); + expect(view.getByRole('status').textContent).toContain('Building UI'); + view.rerender( + + ); expect(view.container.textContent).toBe(''); expect(top).not.toHaveBeenCalled(); view.rerender(); @@ -270,7 +292,11 @@ describe('readiness contracts', () => { const Component = memo(Input); Object.setPrototypeOf(Component, { kind: 'readiness' }); const view = render( - + ); expect(view.getByRole('textbox')).toBeTruthy(); }); @@ -407,7 +433,7 @@ describe('readiness contracts', () => { }); it('resets descriptor lifetime across direct component dispatch', () => { const config = entry(); - const view = mount(config); + const view = mount(config, node('ready'), null); const old = edit(view); view.update(Input); expect(view.getByRole('textbox')).not.toBe(old); diff --git a/libs/react/src/render/readiness.tsx b/libs/react/src/render/readiness.tsx index aae661078..bc88baa63 100644 --- a/libs/react/src/render/readiness.tsx +++ b/libs/react/src/render/readiness.tsx @@ -24,6 +24,20 @@ function sameContract(left: Contract, right: Contract): boolean { ); } +function admit( + entry: RenderReadinessEntry, + props: RenderViewProps['props'] +): boolean { + if (typeof entry.isReady !== 'function') + throw new TypeError('Render readiness isReady must be a function.'); + const result = entry.isReady(props); + if (typeof result !== 'boolean') + throw new TypeError( + 'Render readiness isReady must return a synchronous boolean.' + ); + return result; +} + /** A gate is unmounted by the renderer's normal missing/hidden/direct paths. */ export function ReadinessGate({ entry, @@ -39,24 +53,17 @@ export function ReadinessGate({ component: entry.component, isReady: entry.isReady, }; + // A first render that is ready starts admitted, so the real view renders once + // rather than again from the layout effect. An abandoned mount discards it. const [committed, setCommitted] = useState(() => ({ contract, generation: 0, - mounted: false, + mounted: admit(entry, view.props), })); const unchanged = sameContract(committed.contract, contract); const generation = committed.generation + (unchanged ? 0 : 1); let ready = unchanged && committed.mounted; - if (!ready) { - if (typeof entry.isReady !== 'function') - throw new TypeError('Render readiness isReady must be a function.'); - const result = entry.isReady(view.props); - if (typeof result !== 'boolean') - throw new TypeError( - 'Render readiness isReady must return a synchronous boolean.' - ); - ready = result; - } + if (!ready) ready = admit(entry, view.props); // Only a successful commit of this subtree records admission. Suspended or // abandoned candidates cannot latch; a committed pending contract retires A. useLayoutEffect(() => { diff --git a/libs/react/src/render/render-spec.spec.tsx b/libs/react/src/render/render-spec.spec.tsx index 5abf78147..f7ee1cc39 100644 --- a/libs/react/src/render/render-spec.spec.tsx +++ b/libs/react/src/render/render-spec.spec.tsx @@ -352,7 +352,14 @@ describe('RenderSpec', () => { }, }; const before = JSON.stringify({ state, spec }); - render(); + render( + + ); if (!captured) throw new Error('Capture view did not render'); expect(captured.props['missing']).toBeUndefined(); const payload = captured.props['payload'] as { diff --git a/libs/react/src/render/render-spec.tsx b/libs/react/src/render/render-spec.tsx index a46bf2648..a262a5421 100644 --- a/libs/react/src/render/render-spec.tsx +++ b/libs/react/src/render/render-spec.tsx @@ -26,6 +26,7 @@ import type { import { ownRenderValue } from './values.js'; import { ownRenderFunctions } from './functions.js'; import { ReadinessGate } from './readiness.js'; +import { RenderPendingFallback } from './pending-fallback.js'; import { RenderDevtoolsMark, RenderDevtoolsScope } from './devtools.js'; import type { RenderReadinessEntry, @@ -42,8 +43,12 @@ const EMPTY_STATE = Object.freeze({}); const NO_STORE = Object.freeze({}); const noSubscription = () => () => undefined; declare const process: { readonly env: { readonly NODE_ENV?: string } }; +/** The default admission: every resolved prop has a value, as in Angular's renderer. */ +const allPropsDefined: RenderReadinessEntry['isReady'] = (props) => + Object.values(props).every((value) => value !== undefined); interface ElementProps extends Pick { + readonly pendingFallback: RenderSpecProps['pendingFallback']; readonly spec: NonNullable; readonly elementKey: string; readonly context: PropResolutionContext; @@ -74,6 +79,7 @@ function Element({ registry, loading, fallback, + pendingFallback, context, ancestors, interaction, @@ -89,10 +95,10 @@ function Element({ ) ) return null; - const entry = - (Object.hasOwn(registry, element.type) - ? registry[element.type] - : undefined) ?? fallback; + const registered = Object.hasOwn(registry, element.type) + ? registry[element.type] + : undefined; + const entry = registered ?? fallback; if (!entry) return null; const rawProps = ownRenderValue(element.props, true) as Record< string, @@ -117,6 +123,7 @@ function Element({ registry={registry} loading={loading} fallback={fallback} + pendingFallback={pendingFallback} context={childContext} ancestors={nextAncestors} interaction={interaction} @@ -178,16 +185,40 @@ function Element({ }, }; const Component = entry as Exclude; + // As in Angular, a registered component waits while any resolved prop is + // undefined, and a readiness entry without its own fallback shows the tree's + // placeholder. `pendingFallback={null}` turns both off. The unknown-type + // `fallback` is not a registry entry and mounts at once. + const placeholder = + pendingFallback === null + ? undefined + : pendingFallback ?? RenderPendingFallback; + const own = + Object.hasOwn(entry, 'kind') && + (entry as RenderReadinessEntry).kind === 'readiness' + ? (entry as RenderReadinessEntry) + : undefined; + const gate: RenderReadinessEntry | undefined = own + ? own.fallback !== undefined || placeholder === undefined + ? own + : { ...own, fallback: placeholder } + : registered !== undefined && placeholder !== undefined + ? { + kind: 'readiness', + component: Component, + isReady: allPropsDefined, + fallback: placeholder, + } + : undefined; return ( - {Object.hasOwn(entry, 'kind') && - (entry as RenderReadinessEntry).kind === 'readiness' ? ( + {gate !== undefined ? ( @@ -238,6 +269,7 @@ export function RenderSpec({ functions, loading, fallback, + pendingFallback, handlers, onEvent, }: RenderSpecProps) { @@ -299,6 +331,7 @@ export function RenderSpec({ registry={registry} loading={loading} fallback={fallback} + pendingFallback={pendingFallback} context={{ stateModel, functions: ownRenderFunctions(functions) }} ancestors={new Set()} interaction={interaction} diff --git a/libs/react/src/render/render.type-test.ts b/libs/react/src/render/render.type-test.ts index 484868b25..eee43960e 100644 --- a/libs/react/src/render/render.type-test.ts +++ b/libs/react/src/render/render.type-test.ts @@ -13,7 +13,7 @@ import type { RenderStore, } from './index.js'; import type { RenderState } from '@threadplane/content/render-state'; -import { RenderSpec } from './index.js'; +import { RenderPendingFallback, RenderSpec } from './index.js'; import type { Json } from '@threadplane/content/json'; const spec = { @@ -34,6 +34,10 @@ const functions: ReactRenderFunctions = { uppercase: ({ value }) => String(value).toUpperCase(), }; RenderSpec({ spec, registry, functions }); +RenderSpec({ spec, registry, pendingFallback: RenderPendingFallback }); +RenderSpec({ spec, registry, pendingFallback: null }); +// @ts-expect-error pendingFallback is a component or null, not an element. +RenderSpec({ spec, registry, pendingFallback: 'Loading' }); export function computedContracts( args: Readonly>, diff --git a/libs/react/src/render/seeded-state.spec.tsx b/libs/react/src/render/seeded-state.spec.tsx index 72379e57d..52800d55a 100644 --- a/libs/react/src/render/seeded-state.spec.tsx +++ b/libs/react/src/render/seeded-state.spec.tsx @@ -94,7 +94,8 @@ describe('RenderSpec state carried by the spec', () => { it('seeds the store when state first appears in a later spec', () => { const view = render(); - expect(field(view).readOnly).toBe(true); + // The field waits for its bound value. + expect(view.queryByRole('textbox', { name: 'Name' })).toBeNull(); view.rerender( ); @@ -103,7 +104,9 @@ describe('RenderSpec state carried by the spec', () => { }); it('stays read-only for a spec without state', () => { - const view = render(); + const view = render( + + ); expect(field(view).value).toBe(''); expect(field(view).readOnly).toBe(true); }); diff --git a/libs/react/src/render/types.ts b/libs/react/src/render/types.ts index 2daee7367..208e59eee 100644 --- a/libs/react/src/render/types.ts +++ b/libs/react/src/render/types.ts @@ -131,7 +131,15 @@ interface RenderSpecBaseProps { readonly registry: ReactRenderRegistry; readonly functions?: ReactRenderFunctions; readonly loading?: boolean; + /** Renders an element whose type the registry does not name. Without it, such elements are left out. */ readonly fallback?: ComponentType; + /** + * Shown in place of a registered component while any of the element's resolved props is + * undefined, such as a state path that has not arrived. Once the props resolve, the component + * mounts and stays mounted for that element. Defaults to `RenderPendingFallback`; `null` mounts + * every component at once. A readiness entry decides for itself and uses its own `fallback`. + */ + readonly pendingFallback?: ComponentType | null; /** Actions the spec's `on` bindings may run. Without them, events do nothing. */ readonly handlers?: ReactRenderHandlers; /** Notified when an action runs, the store changes, or a view reports a result. */ diff --git a/scripts/react-parity/dispositions.json b/scripts/react-parity/dispositions.json index 0987ec8a6..debc2e423 100644 --- a/scripts/react-parity/dispositions.json +++ b/scripts/react-parity/dispositions.json @@ -19415,6 +19415,26 @@ "treatment": "react", "status": "in-progress", "note": "Turns RenderSpec lifecycle, stateChange and handler events into first-mount, mount-count and latest-activity timings, the React counterpart of Angular RENDER_LIFECYCLE." + }, + { + "id": "export:libs/react/src/render/index.ts#RenderPendingFallback", + "taskIds": [ + "T20", + "T24" + ], + "treatment": "react", + "status": "in-progress", + "note": "Default placeholder RenderSpec shows while a registered element has an undefined resolved prop, the React counterpart of Angular DefaultFallbackComponent and A2uiDefaultFallbackComponent. Uses the GenerativeUiSkeleton markup." + }, + { + "id": "source:libs/react/src/render/pending-fallback.tsx", + "taskIds": [ + "T20", + "T24" + ], + "treatment": "react", + "status": "in-progress", + "note": "RenderPendingFallback: the default readiness placeholder for every registered component, mirroring Angular defineAngularRegistry's DefaultFallbackComponent." } ] } diff --git a/scripts/react-parity/verify-packages.mjs b/scripts/react-parity/verify-packages.mjs index 588e0b402..f4aae9161 100644 --- a/scripts/react-parity/verify-packages.mjs +++ b/scripts/react-parity/verify-packages.mjs @@ -246,11 +246,11 @@ export type CitationSourceVisualFunctionContract = CitationDisplayAssert = (() => T extends A ? 1 : 2) extends (() => T extends B ? 1 : 2) ? true : false; type A2uiAssert = T; -export type A2uiSurfacePropsContract = A2uiAssert void; readonly onValidationError?: (error: import('@threadplane/content/a2ui').A2uiValidationErrorMessage) => void; readonly functions?: { readonly [name: string]: (args: { readonly [name: string]: import('@threadplane/content/a2ui').A2uiValue }) => void }; readonly catalog?: import('@threadplane/react/render').ReactRenderRegistry; readonly className?: string }>>; +export type A2uiSurfacePropsContract = A2uiAssert void; readonly onValidationError?: (error: import('@threadplane/content/a2ui').A2uiValidationErrorMessage) => void; readonly functions?: { readonly [name: string]: (args: { readonly [name: string]: import('@threadplane/content/a2ui').A2uiValue }) => void }; readonly catalog?: import('@threadplane/react/render').ReactRenderRegistry; readonly pendingFallback?: import('react').ComponentType | null; readonly className?: string }>>; export type A2uiSurfaceParameterContract = A2uiAssert[0], import('@threadplane/react/a2ui').A2uiSurfaceProps>>; export type A2uiMessageContentContract = A2uiAssert>; export type A2uiMessageSurfacesParameterContract = A2uiAssert[0], import('@threadplane/react/a2ui').A2uiMessageSurfacesProps>>; -export type A2uiMessageSurfacesPropsContract = A2uiAssert>; +export type A2uiMessageSurfacesPropsContract = A2uiAssert>; export type A2uiSurfaceWriterContract = A2uiAssert void }>>; export type A2uiSurfacesSetValueContract = A2uiAssert boolean>>; export type A2uiCreateActionMessageContract = A2uiAssert import('@threadplane/content/a2ui').A2uiActionMessage | null>>; @@ -521,7 +521,7 @@ const SUPPORTED_EXPORTS = { ], 'react/debug': ['ChatDebug', 'StateDiff', 'useAgentDevtools'], 'react/markdown': ['Markdown', 'MarkdownComponentsProvider', 'MarkdownCopyButton'], - 'react/render': ['RenderSpec', 'createRenderLifecycle', 'RenderDevtools'], + 'react/render': ['RenderSpec', 'createRenderLifecycle', 'RenderDevtools', 'RenderPendingFallback'], 'react/a2ui': ['A2uiSurface', 'a2uiBasicCatalog', 'useA2uiSurfaceWriter', 'A2uiMessageSurfaces', 'a2uiClientCapabilities'], 'content/messages': ['createMessageContent', 'deriveDomain', 'deriveSourceType', 'deriveMonogram', 'monogramHue', 'formatPublished', 'monogramColor', 'citationTypeMeta', 'citationTypeLabel', 'citationSourceVisual'], 'content/json': ['createJson'], diff --git a/scripts/react-parity/verify-packages.spec.mjs b/scripts/react-parity/verify-packages.spec.mjs index fc10c7659..b8cdc4584 100644 --- a/scripts/react-parity/verify-packages.spec.mjs +++ b/scripts/react-parity/verify-packages.spec.mjs @@ -1086,7 +1086,7 @@ test('React chat requires its real supported export', () => { assert.throws(() => packageVerifier.assertSupportedExports('react/chat', { ...supported, isTyping: forwarded }), /isTyping/); assert.throws(() => packageVerifier.assertSupportedExports('core', { completeDelivery: forwarded }), /completeDelivery/); }); -test('React render requires exactly the RenderSpec, lifecycle recorder and RenderDevtools runtime exports', () => { +test('React render requires exactly the RenderSpec, lifecycle recorder, RenderDevtools and RenderPendingFallback runtime exports', () => { const RenderSpec = () => null; const createRenderLifecycle = () => ({}); assert.throws(() => packageVerifier.assertSupportedExports('react/a2ui', {}), /A2uiSurface/); @@ -1100,8 +1100,10 @@ test('React render requires exactly the RenderSpec, lifecycle recorder and Rende assert.throws(() => packageVerifier.assertSupportedExports('react/render', {}), /RenderSpec/); assert.throws(() => packageVerifier.assertSupportedExports('react/render', { RenderSpec }), /createRenderLifecycle/); assert.throws(() => packageVerifier.assertSupportedExports('react/render', { RenderSpec, createRenderLifecycle }), /RenderDevtools/); - assert.doesNotThrow(() => packageVerifier.assertSupportedExports('react/render', { RenderSpec, createRenderLifecycle, RenderDevtools })); - assert.throws(() => packageVerifier.assertSupportedExports('react/render', { RenderSpec, createRenderLifecycle, RenderDevtools, createStateStore: () => ({}) }), /unexpected/); + const RenderPendingFallback = () => null; + assert.throws(() => packageVerifier.assertSupportedExports('react/render', { RenderSpec, createRenderLifecycle, RenderDevtools }), /RenderPendingFallback/); + assert.doesNotThrow(() => packageVerifier.assertSupportedExports('react/render', { RenderSpec, createRenderLifecycle, RenderDevtools, RenderPendingFallback })); + assert.throws(() => packageVerifier.assertSupportedExports('react/render', { RenderSpec, createRenderLifecycle, RenderDevtools, RenderPendingFallback, createStateStore: () => ({}) }), /unexpected/); }); test('headless framework root rejects the render adapter and engine', () => { assert.throws(() => packageVerifier.assertHeadlessInputs({ 'node_modules/@threadplane/react/src/render/render-spec.js': {} }), /render/i); diff --git a/scripts/react-parity/verify-react-readiness.mjs b/scripts/react-parity/verify-react-readiness.mjs index c737a2e09..e508f67f2 100644 --- a/scripts/react-parity/verify-react-readiness.mjs +++ b/scripts/react-parity/verify-react-readiness.mjs @@ -447,13 +447,25 @@ export async function verifyReadinessBrowser( })) assert.equal(await view.getAttribute(attr), expected, attr); } - if (visible) + if (visible) { for (const name of ['direct-memo', 'direct-forward']) assert.equal( await page.getByTestId(name).textContent(), 'undefined', - 'Direct exotic component preserves undefined' + 'Direct exotic component preserves undefined with pendingFallback null' ); + const wait = page.getByTestId('default-wait'); + assert.equal( + await wait.locator('.tp-render-pending[role="status"]').count(), + 1, + 'Default placeholder stands in for an unresolved binding' + ); + assert.equal( + await page.getByTestId('default-wait-real').count(), + 0, + 'Default wait withholds the component' + ); + } }; const screenshot = async (action, index) => { if (directory) @@ -599,8 +611,18 @@ export async function verifyReadinessBrowser( if (action === 'Missing while hidden') current = { real: false }; if (action === 'Show pending') current = { real: false, pending: true, value: null }; - if (['Null fallback', 'Remount pending'].includes(action)) + if (['Null fallback', 'Remount pending'].includes(action)) { current = { real: false }; + // A readiness entry without its own fallback shows the tree's default placeholder. + assert.equal( + await page + .getByTestId('main-tree') + .locator('.tp-render-pending[role="status"]') + .count(), + 1, + 'Absent readiness fallback uses the default placeholder' + ); + } if (action === 'Ready after remount') { current = { real: true,