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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion apps/website/content/docs-catalog.json
Original file line number Diff line number Diff line change
Expand Up @@ -662,7 +662,7 @@
},
"react": {
"source": "react/render/guides/events.mdx",
"description": "Handle React controls in application code while RenderSpec reads supplied state and prepared data."
"description": "Run application actions from a spec's on bindings, write bound inputs to a store, and observe what the rendered tree did."
}
}
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,4 @@ Continue with [registry](/docs/react/render/guides/registry), [state](/docs/reac

The application validates untrusted data and owns parsing, asynchronous work, and disposal. RenderSpec's plain-data checks are not application-schema validation.

This React entry has no specification action dispatcher, form provider, or watch-effect executor. [Events](/docs/react/render/guides/events) explains the supported application-owned controls. [Lifecycle](/docs/react/render/guides/lifecycle) follows parser and view lifetime. These client-side guides do not claim server rendering, hydration, or full Angular Render parity.
A spec can name actions in its `on` bindings, and only the `handlers` your application supplies run; with a writable `store`, bound inputs can edit state. This React entry has no form provider or watch-effect executor. [Events](/docs/react/render/guides/events) explains actions, the store, and `onEvent`. [Lifecycle](/docs/react/render/guides/lifecycle) follows parser and view lifetime. These client-side guides do not claim server rendering, hydration, or full Angular Render parity.
Original file line number Diff line number Diff line change
Expand Up @@ -62,4 +62,4 @@ A view receives resolved props and rendered children. It does not receive raw ne

The example's completion means the finished parser output matches the validated source. It is not a model-response outcome. Seeking rebuilds parser state, while pausing cancels obsolete playback callbacks.

Next, add [state bindings](/docs/react/render/guides/state-store) or [element visibility](/docs/react/render/guides/element-rendering). Keep user actions explicit through [application-owned events](/docs/react/render/guides/events).
Next, add [state bindings](/docs/react/render/guides/state-store) or [element visibility](/docs/react/render/guides/element-rendering). Run user actions through [application-supplied handlers](/docs/react/render/guides/events).
174 changes: 142 additions & 32 deletions apps/website/content/docs/react/render/guides/events.mdx
Original file line number Diff line number Diff line change
@@ -1,65 +1,175 @@
---
title: Events
description: Handle React controls in application code while RenderSpec reads supplied state and prepared data.
description: Run application actions from a spec's on bindings, write bound inputs to a store, and observe what the rendered tree did.
---

# Handle render interactions

React Render currently has no specification-driven action dispatcher or `onAction` prop. Its supported interaction boundary is ordinary React event handling owned by the application.
A spec names actions in an element's `on` property. A registered view calls `emit` when the user interacts, and `RenderSpec` runs the matching action from the `handlers` you supply. The spec can only name actions; nothing runs unless your application provides it.

These APIs are experimental, private source-build packages. Do not translate Angular event-forwarding examples into an invented React render API.
These APIs are experimental, private source-build packages.

## Follow an actual state change
## Name an action in the spec

The [Element Rendering example](/docs/react/render/guides/element-rendering) places a **Show detail** checkbox outside the generated tree. In `app.tsx`, its `onChange` calls the supplied `onShowDetailChange` callback.
The `on` property maps an event name to one action binding, or to a list that runs in order:

The client composition in `main.tsx` handles that callback by calling the owned render state's `set('/showDetail', value)`. The view observes the state snapshot and passes it to `RenderSpec`. Visibility reads the next supplied value.
```tsx
import type { RenderSpecData } from '@threadplane/react/render';

That path is explicit: user action, owner update, new snapshot, new rendering. Playback and sample changes do not overwrite the user's visibility choice.
const spec: RenderSpecData = {
root: 'save',
elements: {
save: {
type: 'Button',
props: { label: 'Save trip' },
on: {
press: { action: 'saveTrip', params: { destination: { $state: '/destination' } } },
},
},
},
};
```

Each binding is an `ActionBinding` from `@json-render/core`:

| Field | What it does |
|-------|--------------|
| `action` | The name looked up in `handlers`. A name you did not supply does nothing. |
| `params` | Values resolved like element props, in the element's own repeat row, then passed to the action. |
| `confirm` | Asks the user with the browser's confirmation dialog first; the action is skipped when they decline. |
| `onSuccess` | After the action returns or its promise resolves: `set` values in the store, run another `action`, or `navigate` to an http, https or relative address. |
| `onError` | After the action throws or rejects: `set` values (`'$error.message'` becomes the error's message) or run another `action`. Without `onError`, a thrown error reaches the view. |

## Keep executable behavior in authored code
`preventDefault` is not applied for you. Event payloads are plain data, so a view that needs it calls `event.preventDefault()` itself.

This private source-build client component keeps the control outside the generated tree and supplies the next state explicitly:
## Emit from a registered view

Every registered view receives `emit`. Call it with the event name, and optionally a plain-data payload that is merged over the resolved params:

```tsx
import type { RenderViewProps } from '@threadplane/react/render';

export function Button({ props, emit }: RenderViewProps) {
return (
<button type="button" onClick={() => emit?.('press')}>
{String(props['label'] ?? '')}
</button>
);
}
```

`emit` is undefined for a readiness fallback, so a placeholder cannot act before the real view mounts. A payload that is not plain data, such as a DOM event or a function, is rejected with a `TypeError`.

## Supply the actions

Pass the actions as `handlers`. Each receives the resolved params as frozen plain data and may return a promise:

```tsx
import { RenderSpec, type ReactRenderHandlers } from '@threadplane/react/render';

const handlers: ReactRenderHandlers = {
saveTrip: async ({ destination }) => {
await saveTrip(String(destination));
},
};

export function Trip() {
return <RenderSpec spec={spec} registry={registry} state={{ destination: 'Lisbon' }} handlers={handlers} />;
}
```

A press always runs the handlers of the latest render, so you can pass a new map without remounting the views.

## Let bound inputs write state

With read-only `state`, views receive no `set` and the tree cannot change your data. Pass a `store` instead, such as the owner from `createRenderState`, and views receive `set`. An input bound with `$bindState` writes to the path in its `bindings`. This complete example saves the edited destination through an action:

~~~tsx
import { useState } from 'react';
import { createRenderState } from '@threadplane/content/render-state';
import {
RenderSpec,
type ReactRenderHandlers,
type ReactRenderRegistry,
type RenderSpecData,
type RenderViewProps,
} from '@threadplane/react/render';

const registry: ReactRenderRegistry = {
Text: ({ props }) => <p>{String(props['text'] ?? '')}</p>,
};
function Field({ props, bindings, set }: RenderViewProps) {
return (
<input
aria-label={String(props['label'] ?? '')}
value={String(props['value'] ?? '')}
readOnly={set === undefined}
onChange={(event) => {
const path = bindings?.['value'];
if (path) set?.(path, event.target.value);
}}
/>
);
}

function Button({ props, emit }: RenderViewProps) {
return (
<button type="button" onClick={() => emit?.('press')}>
{String(props['label'] ?? '')}
</button>
);
}

function Form({ children }: RenderViewProps) {
return <form onSubmit={(event) => event.preventDefault()}>{children}</form>;
}

const registry: ReactRenderRegistry = { Button, Field, Form };
const spec: RenderSpecData = {
root: 'destination',
root: 'form',
elements: {
destination: { type: 'Text', props: { text: { $state: '/destination' } } },
form: { type: 'Form', props: {}, children: ['destination', 'save'] },
destination: {
type: 'Field',
props: { label: 'Destination', value: { $bindState: '/destination' } },
},
save: {
type: 'Button',
props: { label: 'Save trip' },
on: {
press: {
action: 'saveTrip',
params: { destination: { $state: '/destination' } },
onSuccess: { set: { '/saved': true } },
},
},
},
},
};
const store = createRenderState({ destination: 'Lisbon', saved: false });
const handlers: ReactRenderHandlers = {
saveTrip: async ({ destination }) => {
await fetch('/api/trips', { method: 'POST', body: JSON.stringify({ destination }) });
},
};

export function DestinationControl() {
const [destination, setDestination] = useState('Portland');
return (
<>
<input
aria-label="Destination"
value={destination}
onChange={(event) => setDestination(event.target.value)}
/>
<RenderSpec spec={spec} registry={registry} state={{ destination }} />
</>
);
export function TripEditor() {
return <RenderSpec spec={spec} registry={registry} store={store} handlers={handlers} />;
}
~~~

Your own registered React components can use ordinary React handlers and application context. Their commands remain your application's responsibility. RenderSpec supplies data props, binding paths, child views, element identity, and loading information; it supplies no automatic state writer or tool executor.
`RenderSpec` reads the store's snapshot and renders again when it changes. `onSuccess` and `onError` `set` follow-ups write to the same store. Pass `state` or `store`, not both.

## Observe what happened

`onEvent` receives a notification when an action runs, when the store changes, and when a view reports a value through `result`:

Do not put callback functions in a specification's raw props. The renderer accepts plain data and rejects executable values. A `bindings` path tells an authored view where data came from; it does not write to that path automatically.
| `type` | Fields |
|--------|--------|
| `'handler'` | `action`, `params`, and `result`: what the action returned, or what its promise resolved to |
| `'stateChange'` | `path`, `value`, and the whole `snapshot` after the write |
| `'result'` | `value` and the `elementKey` of the view that reported it |

## Admit commands separately
```tsx
<RenderSpec spec={spec} registry={registry} store={store} handlers={handlers} onEvent={(event) => console.log(event)} />
```

If a control eventually requests a tool, submission, or persistent change, validate the intent at the application owner. Rendering, visibility evaluation, and computed functions must remain free of those effects.
Once the tree unmounts, a late promise no longer writes the store, runs follow-ups, or reports events.

See [State Store](/docs/react/render/guides/state-store) for editable local values and [Lifecycle](/docs/react/render/guides/lifecycle) for retiring work. Forms, action providers, and watch effects are outside this private React entry.
See [State Store](/docs/react/render/guides/state-store) for read-only state owned by React, and [Lifecycle](/docs/react/render/guides/lifecycle) for retiring work.
2 changes: 1 addition & 1 deletion apps/website/content/docs/react/render/guides/registry.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ Changing registry mode does not rewrite the JSON or move playback. Your choice s

The host owns two stable frozen maps: the complete Heading, Text, Card and Badge registry, and a map with Badge omitted. RenderSpec receives the selected registry and the optional fallback. React uses a plain map of view components; this preview does not require Angular registry helpers.

A registered view receives read-only resolved props, elementKey, loading and children. Heading and Card display the children supplied by RenderSpec exactly once. Text and Badge are leaves. The authored fallback displays a literal label and uses the same loading flag. It is intentionally demonstrated only for the known Badge type omitted from the selected map.
A registered view receives read-only resolved props, elementKey, loading and children. It also receives `emit` to fire the element's `on` bindings, `result` to report a value, and `set` when RenderSpec has a writable store; see [Events](/docs/react/render/guides/events). Heading and Card display the children supplied by RenderSpec exactly once. Text and Badge are leaves. The authored fallback displays a literal label and uses the same loading flag. It is intentionally demonstrated only for the known Badge type omitted from the selected map.

<ExampleCode file="cockpit/render/registry/react/src/views.tsx" />

Expand Down
2 changes: 2 additions & 0 deletions apps/website/content/docs/react/render/guides/state-store.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ export function DestinationPreview() {

The [React conversation walkthrough](/docs/react/langgraph/concepts/conversation-turns) connects this capability to requests, tools, UI state, and saved history.

To let controls inside the rendered tree edit values, pass a writable `store`, such as the owner from `createRenderState`, instead of `state`. [Events](/docs/react/render/guides/events) shows bound inputs writing through `set` and actions updating the store.

## Edit local state

Choose **Run**, select **User Profile**, **Nested Paths** or **Form Display**, and press **Finish**. **Name**, **Age** and **Theme** sit outside the rendered tree and update its visible values. Age accepts whole numbers from 0 to 150; an invalid draft keeps the last valid value until you correct it. Theme changes the displayed preference. Reloading restores Alice, age 30, and Dark.
Expand Down
18 changes: 15 additions & 3 deletions fixtures/react-parity/runtime/render-types.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,20 @@ export function readonlyContracts(
) {
// @ts-expect-error raw JSON is not prepared data
const raw = <RenderSpec spec="{}" registry={registry} />;
// @ts-expect-error commands remain application owned
const handlers = <RenderSpec spec={spec} registry={registry} handlers={{}} />;
// @ts-expect-error installed actions are functions, not data
const handlers = <RenderSpec spec={spec} registry={registry} handlers={{ save: 1 }} />;
// Actions and events are application-supplied functions.
const actions = (
<RenderSpec
spec={spec}
registry={registry}
handlers={{ save: (params) => params['id'] }}
onEvent={(event) => event.type}
/>
);
props.emit?.('press', { id: 'a' });
// @ts-expect-error installed event payloads are plain data
props.emit?.('press', { run: () => 1 });
// @ts-expect-error source children are readonly
element.children?.push('new');
// @ts-expect-error source props are readonly
Expand All @@ -54,7 +66,7 @@ export function readonlyContracts(
props.props['changed'] = 1;
// @ts-expect-error schema validation is not a renderer capability
const schema = <RenderSpec spec={spec} registry={registry} schema={{}} />;
return { raw, handlers, schema };
return { raw, handlers, actions, schema };
}

const InstalledView = ({ props }: RenderViewProps) => (
Expand Down
7 changes: 7 additions & 0 deletions libs/react/src/render/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,19 @@
export { RenderSpec } from './render-spec.js';
export type {
ReactRenderFunctions,
ReactRenderHandlers,
ReactRenderRegistry,
RenderActionHandler,
RenderComputedFunction,
RenderElementData,
RenderEvent,
RenderHandlerEvent,
RenderReadinessEntry,
RenderResultEvent,
RenderSpecData,
RenderSpecProps,
RenderStateChangeEvent,
RenderStore,
RenderValue,
RenderViewProps,
} from './types.js';
Loading
Loading