effect-ui-react 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +305 -2
  3. package/dist/Intrinsics.d.ts +16 -0
  4. package/dist/Intrinsics.js +1 -0
  5. package/dist/React.d.ts +58 -0
  6. package/dist/React.js +55 -0
  7. package/dist/ReactHost.d.ts +115 -0
  8. package/dist/ReactHost.js +750 -0
  9. package/dist/ReactRefs.d.ts +16 -0
  10. package/dist/ReactRefs.js +23 -0
  11. package/dist/dom/ReactDomCommand.d.ts +83 -0
  12. package/dist/dom/ReactDomCommand.js +86 -0
  13. package/dist/dom/ReactDomFiles.d.ts +1 -0
  14. package/dist/dom/ReactDomFiles.js +1 -0
  15. package/dist/dom/ReactDomHead.d.ts +1 -0
  16. package/dist/dom/ReactDomHead.js +1 -0
  17. package/dist/dom/ReactDomHost.d.ts +60 -0
  18. package/dist/dom/ReactDomHost.js +186 -0
  19. package/dist/dom/ReactDomImages.d.ts +1 -0
  20. package/dist/dom/ReactDomImages.js +1 -0
  21. package/dist/dom/ReactDomKeyboard.d.ts +1 -0
  22. package/dist/dom/ReactDomKeyboard.js +1 -0
  23. package/dist/dom/ReactDomRouter.d.ts +1 -0
  24. package/dist/dom/ReactDomRouter.js +1 -0
  25. package/dist/dom/ReactDomScheduler.d.ts +1 -0
  26. package/dist/dom/ReactDomScheduler.js +1 -0
  27. package/dist/dom/ReactDomSubscription.d.ts +1 -0
  28. package/dist/dom/ReactDomSubscription.js +1 -0
  29. package/dist/dom/index.d.ts +10 -0
  30. package/dist/dom/index.js +10 -0
  31. package/dist/dom/intrinsics.d.ts +21 -0
  32. package/dist/dom/intrinsics.js +1 -0
  33. package/dist/dom/server/ReactDomServer.d.ts +11 -0
  34. package/dist/dom/server/ReactDomServer.js +16 -0
  35. package/dist/dom/server/index.d.ts +1 -0
  36. package/dist/dom/server/index.js +1 -0
  37. package/dist/index.d.ts +3 -0
  38. package/dist/index.js +3 -0
  39. package/dist/internal/child-placement.d.ts +49 -0
  40. package/dist/internal/child-placement.js +136 -0
  41. package/dist/internal/react-component-bridge.d.ts +133 -0
  42. package/dist/internal/react-component-bridge.js +220 -0
  43. package/dist/internal/react-element.d.ts +138 -0
  44. package/dist/internal/react-element.js +261 -0
  45. package/dist/internal/render-view.d.ts +24 -0
  46. package/dist/internal/render-view.js +110 -0
  47. package/dist/internal/to-react-element.d.ts +20 -0
  48. package/dist/internal/to-react-element.js +135 -0
  49. package/dist/internal/wrap-helper.d.ts +9 -0
  50. package/dist/internal/wrap-helper.js +31 -0
  51. package/package.json +78 -3
@@ -0,0 +1,136 @@
1
+ import { View, UiAtom } from "effect/ui";
2
+ import { Atom } from "effect/reactivity";
3
+ import { makeSource } from "./react-component-bridge.js";
4
+ const EMPTY = [];
5
+ const NO_OWNERS = new Map();
6
+ // React-created children waiting to be declared by their Effect owner, grouped
7
+ // by the owner's component name, then by the owner instance's `h.id`. Values
8
+ // live in the host's AtomRegistry, so each registry (and each test) starts
9
+ // empty, and a member is dropped once its last reader unmounts.
10
+ const placementsAtom = Atom.family((_name) => Atom.make(NO_OWNERS));
11
+ const Placements = UiAtom.family(placementsAtom, { name: "ReactPlacements" });
12
+ function setEntries(registry, name, owner, update) {
13
+ const atom = placementsAtom(name);
14
+ const owners = new Map(registry.get(atom));
15
+ const next = update(owners.get(owner) ?? EMPTY);
16
+ if (next.length === 0)
17
+ owners.delete(owner);
18
+ else
19
+ owners.set(owner, next);
20
+ registry.set(atom, owners);
21
+ }
22
+ /** The hidden `reads` entry every `React.component` declares. */
23
+ export const placementsReadKey = "~reactPlacements";
24
+ export function placementsRead(name) {
25
+ // Optional, so Scenes and direct `view` calls see no placements instead of
26
+ // requiring a value for this internal key.
27
+ return { owner: Placements, optional: true, select: () => name };
28
+ }
29
+ const ownerIdName = "~react-placements";
30
+ let nextEntryId = 0;
31
+ /**
32
+ * The bridge a component's `$boundary` provides to React descendants. Mounts
33
+ * become entries the owner's view declares as ordinary Effect children, so
34
+ * they keep the owner's environment, shared owners and collected reports.
35
+ */
36
+ export function makePlacementBridge(name, owner, parent, registry, shell) {
37
+ // The owner re-renders only when a placement is added or removed. Props
38
+ // React passes later go through the placement's own source to the shell:
39
+ // re-rendering the owner for them would hand React libraries fresh inline
40
+ // props, which would update the placement again, forever.
41
+ const mount = (target, initialProps) => {
42
+ const id = String(nextEntryId++);
43
+ const props = makeSource(initialProps);
44
+ let store;
45
+ let unsubscribe;
46
+ let closed = false;
47
+ const listeners = new Set();
48
+ const publish = () => {
49
+ for (const listener of listeners)
50
+ listener();
51
+ };
52
+ const handle = {
53
+ attach: (next) => {
54
+ unsubscribe?.();
55
+ store = next;
56
+ unsubscribe = store?.subscribe(publish);
57
+ },
58
+ boundary: {
59
+ subscribe: (listener) => {
60
+ listeners.add(listener);
61
+ return () => {
62
+ listeners.delete(listener);
63
+ };
64
+ },
65
+ getSnapshot: () => store?.getSnapshot() ?? null
66
+ },
67
+ setProps: (next) => {
68
+ if (!closed)
69
+ props.set(next);
70
+ },
71
+ close: () => {
72
+ if (closed)
73
+ return;
74
+ closed = true;
75
+ unsubscribe?.();
76
+ unsubscribe = undefined;
77
+ store = undefined;
78
+ setEntries(registry, name, owner, (entries) => entries.filter((entry) => entry.id !== id));
79
+ }
80
+ };
81
+ const entry = { id, component: shell, props: { target, props }, handle };
82
+ setEntries(registry, name, owner, (entries) => [...entries, entry]);
83
+ return handle;
84
+ };
85
+ return {
86
+ mountComponent: (target, initialProps) => mount({ kind: "component", component: target }, initialProps),
87
+ mountRender: (render, reactProps) => mount({ kind: "render", source: render }, reactProps),
88
+ mountDynamicNode: (node) => mount({ kind: "node", source: node }, undefined),
89
+ // Server rendering never subscribes, so placements never register there.
90
+ renderServerComponent: parent.renderServerComponent,
91
+ renderServerRender: parent.renderServerRender,
92
+ renderServerDynamicNode: parent.renderServerDynamicNode
93
+ };
94
+ }
95
+ function placedChildren(h, entries) {
96
+ return entries.map((entry) => new View.ContainerBuilder("$placement")
97
+ .key(entry.id)
98
+ .prop("$placementHandle", entry.handle)
99
+ .children(entry.component(h, { key: entry.id, props: entry.props })));
100
+ }
101
+ /**
102
+ * Wraps a `React.component` view in its `$boundary`, appending the children
103
+ * React descendants placed through this instance's bridge.
104
+ *
105
+ * Content this view hands to a child (a headless `view` or `slots`) renders
106
+ * inside that child, so it gets a `$placementScope` with its own owner id:
107
+ * React mounts inside it are declared there and owned by the child instance,
108
+ * keeping the child's shared state and Layers in scope.
109
+ */
110
+ export function boundaryView(name, h, content) {
111
+ const owners = h.reads?.[placementsReadKey];
112
+ const container = (tag, owner, inner) => new View.ContainerBuilder(tag)
113
+ .prop("$name", name)
114
+ .prop("$placementOwner", owner)
115
+ .children(...visitAll(inner, owner), ...placedChildren(h, owners?.get(owner) ?? EMPTY));
116
+ // Scope ids follow the view's shape (`parent.index` and `parent.index:slot`),
117
+ // so a child calling its `view` again on its own gets the same ids.
118
+ const visitAll = (inner, parent) => {
119
+ let index = 0;
120
+ const visit = (node) => {
121
+ if (node._tag === "Element")
122
+ return { ...node, children: node.children.map(visit) };
123
+ if (node._tag !== "Child" || (node.view === undefined && node.slots === undefined))
124
+ return node;
125
+ const at = `${parent}.${index++}`;
126
+ const view = node.view;
127
+ return {
128
+ ...node,
129
+ view: view === undefined ? undefined : (parts) => container("$placementScope", at, view(parts)),
130
+ slots: node.slots === undefined ? undefined : Object.fromEntries(Object.entries(node.slots).map(([slot, value]) => [slot, container("$placementScope", `${at}:${slot}`, value)]))
131
+ };
132
+ };
133
+ return View.children([inner]).map(visit);
134
+ };
135
+ return container("$boundary", h.id(ownerIdName), content);
136
+ }
@@ -0,0 +1,133 @@
1
+ import type { Component, View } from "effect/ui";
2
+ import { type ComponentType, type FunctionComponent, type ReactNode } from "react";
3
+ export declare const ComponentSymbol: unique symbol;
4
+ export declare const ComponentRequirementsSymbol: unique symbol;
5
+ export declare const RenderSymbol: unique symbol;
6
+ export declare const EventSymbol: unique symbol;
7
+ export interface EventMarker {
8
+ readonly [EventSymbol]: {
9
+ readonly handler: unknown;
10
+ readonly options?: View.EventOptions | undefined;
11
+ };
12
+ }
13
+ export declare function isEventMarker(value: unknown): value is EventMarker;
14
+ export declare const PROP_PATH_SEPARATOR = "\0";
15
+ export declare const MAX_NESTED_PROP_DEPTH = 5;
16
+ export type RenderSpec = {
17
+ readonly kind: "view";
18
+ readonly view: View.Input<any, any>;
19
+ } | {
20
+ readonly kind: "fn";
21
+ readonly fn: (...args: ReadonlyArray<unknown>) => View.Input<any, any>;
22
+ };
23
+ export interface RenderMarker {
24
+ readonly [RenderSymbol]: RenderSpec;
25
+ }
26
+ export declare function isRenderMarker(value: unknown): value is RenderMarker;
27
+ export declare function isNestedPropsContainer(value: unknown): value is object;
28
+ /**
29
+ * An internal React `FunctionComponent<P>` produced by the host bridge,
30
+ * carrying phantom Effect service requirements `R`.
31
+ */
32
+ export type BridgedComponent<P, R = never> = FunctionComponent<P> & {
33
+ readonly [ComponentRequirementsSymbol]?: () => R;
34
+ };
35
+ /**
36
+ * An opaque marker produced by `h.component(...)` and resolved into a stable
37
+ * `ComponentType<P>` on the enclosing `HostNode`.
38
+ */
39
+ export interface ComponentPropMarker<P, R = never> {
40
+ readonly [ComponentSymbol]: (props: P) => void;
41
+ readonly [ComponentRequirementsSymbol]?: () => R;
42
+ }
43
+ export type EffectComponentAny = Component.Mountable.Members<any, any, any, never>;
44
+ export type ComponentSpec = {
45
+ readonly kind: "component";
46
+ readonly component: EffectComponentAny;
47
+ } | {
48
+ readonly kind: "render";
49
+ readonly fn: (h: any, props: any) => View.Input<any, any>;
50
+ };
51
+ export interface ComponentMarker {
52
+ readonly [ComponentSymbol]: ComponentSpec;
53
+ }
54
+ export declare function isComponentMarker(value: unknown): value is ComponentMarker;
55
+ /** Whether a prop value is, or nests inside arrays and object literals, an `h.component(...)` marker. */
56
+ export declare function containsComponentMarker(value: unknown): boolean;
57
+ export declare function isEffectComponent(value: unknown): value is EffectComponentAny;
58
+ export interface BoundaryStore {
59
+ readonly subscribe: (listener: () => void) => () => void;
60
+ readonly getSnapshot: () => ReactNode;
61
+ }
62
+ export interface SubtreeHandle {
63
+ readonly boundary: BoundaryStore;
64
+ readonly setProps: (props: unknown) => void;
65
+ readonly close: () => void;
66
+ }
67
+ /**
68
+ * A stable handle on a value React recomputes whenever the owning Effect view
69
+ * renders: an `h.component((h, props) => ...)` callback or a dynamic node.
70
+ * Placed shells read `current()` and re-render on `subscribe`, so a new value
71
+ * never goes back through the owner (which would re-render it in a loop).
72
+ */
73
+ export interface Source<A> {
74
+ readonly current: () => A;
75
+ readonly version: () => number;
76
+ readonly subscribe: (listener: () => void) => () => void;
77
+ }
78
+ export type RenderSource = Source<(h: any, props: any) => View.Input<any, any>>;
79
+ export interface DynamicNodeValue {
80
+ readonly node: View.Node<any, any>;
81
+ readonly dispatch: (msg: unknown) => void;
82
+ }
83
+ export type DynamicNodeSource = Source<DynamicNodeValue>;
84
+ export declare function makeSource<A>(initial: A): Source<A> & {
85
+ readonly set: (value: A) => void;
86
+ };
87
+ export interface HostBridgeContext {
88
+ readonly mountComponent: (component: EffectComponentAny, initialProps: unknown) => SubtreeHandle;
89
+ readonly mountRender: (render: RenderSource, initialProps: unknown) => SubtreeHandle;
90
+ readonly mountDynamicNode: (source: DynamicNodeSource) => SubtreeHandle;
91
+ readonly renderServerComponent: (component: EffectComponentAny, initialProps: unknown) => ReactNode;
92
+ readonly renderServerRender: (render: RenderSource, initialProps: unknown) => ReactNode;
93
+ readonly renderServerDynamicNode: (source: DynamicNodeSource) => ReactNode;
94
+ }
95
+ export declare const ReactHostContext: import("react").Context<HostBridgeContext | undefined>;
96
+ /**
97
+ * Creates a React `ComponentType` that mounts an Effect UI component inside
98
+ * the enclosing `ReactHost` context via `useSyncExternalStore` (zero `useEffect`
99
+ * or `useLayoutEffect`), forwarding React props straight through and rendering
100
+ * synchronously on SSR via `getServerSnapshot`.
101
+ */
102
+ export declare function createBridgedEffectComponent(component: EffectComponentAny): ComponentType<any>;
103
+ export type ComponentBridgeCacheEntry = {
104
+ readonly kind: "component";
105
+ readonly target: EffectComponentAny;
106
+ readonly Wrapper: ComponentType<any>;
107
+ } | RenderBridgeCacheEntry;
108
+ export interface RenderBridgeCacheEntry {
109
+ readonly kind: "render";
110
+ readonly Wrapper: ComponentType<any>;
111
+ latestFn: (h: any, props: any) => View.Input<any, any>;
112
+ version: number;
113
+ readonly listeners: Set<() => void>;
114
+ }
115
+ export type ComponentBridgeCache = Map<string, ComponentBridgeCacheEntry>;
116
+ /**
117
+ * Creates a stable host-node cache entry for `h.component((h, props) => ...)`.
118
+ * The `Wrapper` identity stays constant while `entry.latestFn` updates in place.
119
+ */
120
+ export declare function createRenderBridgeEntry(initialFn: (h: any, props: any) => View.Input<any, any>): RenderBridgeCacheEntry;
121
+ export interface DynamicNodeBridgeProps {
122
+ readonly node: View.Node<any, any>;
123
+ readonly dispatch: (msg: unknown) => void;
124
+ }
125
+ /**
126
+ * Stable React component used for per-node runtime mounting inside dynamic
127
+ * `h.render((...args) => ...)` and function-as-child callbacks (Effect child
128
+ * components, `onMount`, or nested `h.component` props).
129
+ */
130
+ export declare function DynamicNodeBridge(props: DynamicNodeBridgeProps): ReactNode;
131
+ export declare namespace DynamicNodeBridge {
132
+ var displayName: string;
133
+ }
@@ -0,0 +1,220 @@
1
+ import { Predicate } from "effect";
2
+ import { createContext, isValidElement, useContext, useState, useSyncExternalStore } from "react";
3
+ export const ComponentSymbol = Symbol.for("effect-ui-react/component");
4
+ export const ComponentRequirementsSymbol = Symbol.for("effect-ui-react/component-requirements");
5
+ export const RenderSymbol = Symbol.for("effect-ui-react/render");
6
+ export const EventSymbol = Symbol.for("effect-ui-react/event");
7
+ export function isEventMarker(value) {
8
+ return Predicate.isObject(value) && EventSymbol in value;
9
+ }
10
+ // Separates the steps of a path to a marker nested in a prop, such as
11
+ // `items\0` + `0\0onDismiss`. Top-level prop names never contain it.
12
+ export const PROP_PATH_SEPARATOR = "\u0000";
13
+ // Markers may be nested through at most five prop containers. Besides bounding
14
+ // the work, this keeps circular plain objects from overflowing the stack.
15
+ export const MAX_NESTED_PROP_DEPTH = 5;
16
+ export function isRenderMarker(value) {
17
+ return Predicate.isObject(value) && RenderSymbol in value;
18
+ }
19
+ // Arrays and object literals, never class instances or React objects (including
20
+ // forwardRef and memo component types, which may carry circular metadata).
21
+ export function isNestedPropsContainer(value) {
22
+ if (Array.isArray(value))
23
+ return true;
24
+ if (!Predicate.isObject(value) || "$$typeof" in value || isValidElement(value))
25
+ return false;
26
+ const proto = Object.getPrototypeOf(value);
27
+ return proto === Object.prototype || proto === null;
28
+ }
29
+ export function isComponentMarker(value) {
30
+ return Predicate.isObject(value) && ComponentSymbol in value;
31
+ }
32
+ /** Whether a prop value is, or nests inside arrays and object literals, an `h.component(...)` marker. */
33
+ export function containsComponentMarker(value) {
34
+ return containsComponentMarkerAtDepth(value, 0);
35
+ }
36
+ function containsComponentMarkerAtDepth(value, depth) {
37
+ if (isComponentMarker(value))
38
+ return true;
39
+ if (depth >= MAX_NESTED_PROP_DEPTH || !isNestedPropsContainer(value))
40
+ return false;
41
+ for (const entry of Object.values(value)) {
42
+ if (containsComponentMarkerAtDepth(entry, depth + 1))
43
+ return true;
44
+ }
45
+ return false;
46
+ }
47
+ export function isEffectComponent(value) {
48
+ return (typeof value === "function" &&
49
+ "definition" in value &&
50
+ "init" in value &&
51
+ "update" in value &&
52
+ "view" in value);
53
+ }
54
+ export function makeSource(initial) {
55
+ let value = initial;
56
+ let version = 0;
57
+ const listeners = new Set();
58
+ return {
59
+ current: () => value,
60
+ version: () => version,
61
+ subscribe: (listener) => {
62
+ listeners.add(listener);
63
+ return () => {
64
+ listeners.delete(listener);
65
+ };
66
+ },
67
+ set: (next) => {
68
+ value = next;
69
+ version++;
70
+ for (const listener of listeners)
71
+ listener();
72
+ }
73
+ };
74
+ }
75
+ export const ReactHostContext = createContext(undefined);
76
+ function shallowEqual(a, b) {
77
+ if (Object.is(a, b))
78
+ return true;
79
+ if (!Predicate.isObject(a) || !Predicate.isObject(b))
80
+ return false;
81
+ const aRec = a;
82
+ const bRec = b;
83
+ const aKeys = Object.keys(aRec);
84
+ const bKeys = Object.keys(bRec);
85
+ if (aKeys.length !== bKeys.length)
86
+ return false;
87
+ for (const key of aKeys) {
88
+ if (!(key in bRec) || !Object.is(aRec[key], bRec[key]))
89
+ return false;
90
+ }
91
+ return true;
92
+ }
93
+ function createBridgeInstanceBox(bridge, initialProps, mount, renderServer) {
94
+ const listeners = new Set();
95
+ let mounted;
96
+ let latestProps = initialProps;
97
+ let updatingProps = false;
98
+ let serverSnapshot;
99
+ return {
100
+ update: (nextBridge, props) => {
101
+ bridge = nextBridge;
102
+ if (shallowEqual(latestProps, props))
103
+ return;
104
+ latestProps = props;
105
+ // React is already rendering these props; don't notify it recursively.
106
+ updatingProps = true;
107
+ try {
108
+ mounted?.handle.setProps(props);
109
+ }
110
+ finally {
111
+ updatingProps = false;
112
+ }
113
+ },
114
+ subscribe: (listener) => {
115
+ listeners.add(listener);
116
+ if (mounted === undefined) {
117
+ const handle = mount(bridge, latestProps);
118
+ const unsubscribe = handle.boundary.subscribe(() => {
119
+ if (updatingProps)
120
+ return;
121
+ for (const current of listeners)
122
+ current();
123
+ });
124
+ mounted = { handle, unsubscribe };
125
+ }
126
+ return () => {
127
+ listeners.delete(listener);
128
+ if (listeners.size === 0 && mounted !== undefined) {
129
+ const current = mounted;
130
+ mounted = undefined;
131
+ current.unsubscribe();
132
+ current.handle.close();
133
+ }
134
+ };
135
+ },
136
+ getSnapshot: () => mounted?.handle.boundary.getSnapshot() ?? null,
137
+ getServerSnapshot: () => {
138
+ if (serverSnapshot === undefined || !shallowEqual(serverSnapshot.props, latestProps)) {
139
+ serverSnapshot = { props: latestProps, value: renderServer(bridge, latestProps) };
140
+ }
141
+ return serverSnapshot.value;
142
+ }
143
+ };
144
+ }
145
+ /**
146
+ * Creates a React `ComponentType` that mounts an Effect UI component inside
147
+ * the enclosing `ReactHost` context via `useSyncExternalStore` (zero `useEffect`
148
+ * or `useLayoutEffect`), forwarding React props straight through and rendering
149
+ * synchronously on SSR via `getServerSnapshot`.
150
+ */
151
+ export function createBridgedEffectComponent(component) {
152
+ const name = component.definition.name;
153
+ const Bridged = (reactProps) => {
154
+ const bridge = useContext(ReactHostContext);
155
+ if (bridge === undefined) {
156
+ throw new Error(`effect-ui-react: <${name} /> must be rendered inside a ReactHost / ReactDomHost tree.`);
157
+ }
158
+ const [box] = useState(() => createBridgeInstanceBox(bridge, reactProps, (currentBridge, props) => currentBridge.mountComponent(component, props), (currentBridge, props) => currentBridge.renderServerComponent(component, props)));
159
+ box.update(bridge, reactProps);
160
+ return useSyncExternalStore(box.subscribe, box.getSnapshot, box.getServerSnapshot);
161
+ };
162
+ Object.defineProperty(Bridged, "name", { value: name });
163
+ Bridged.displayName = name;
164
+ return Bridged;
165
+ }
166
+ /**
167
+ * Creates a stable host-node cache entry for `h.component((h, props) => ...)`.
168
+ * The `Wrapper` identity stays constant while `entry.latestFn` updates in place.
169
+ */
170
+ export function createRenderBridgeEntry(initialFn) {
171
+ const listeners = new Set();
172
+ const source = {
173
+ current: () => entry.latestFn,
174
+ version: () => entry.version,
175
+ subscribe: (listener) => {
176
+ listeners.add(listener);
177
+ return () => {
178
+ listeners.delete(listener);
179
+ };
180
+ }
181
+ };
182
+ const RenderBridged = (reactProps) => {
183
+ const bridge = useContext(ReactHostContext);
184
+ if (bridge === undefined) {
185
+ throw new Error("effect-ui-react: h.component(...) must be rendered inside a ReactHost / ReactDomHost tree.");
186
+ }
187
+ const [box] = useState(() => createBridgeInstanceBox(bridge, reactProps, (currentBridge, props) => currentBridge.mountRender(source, props), (currentBridge, props) => currentBridge.renderServerRender(source, props)));
188
+ box.update(bridge, reactProps);
189
+ return useSyncExternalStore(box.subscribe, box.getSnapshot, box.getServerSnapshot);
190
+ };
191
+ RenderBridged.displayName = "ReactComponentBridge";
192
+ const entry = {
193
+ kind: "render",
194
+ Wrapper: RenderBridged,
195
+ latestFn: initialFn,
196
+ version: 0,
197
+ listeners
198
+ };
199
+ return entry;
200
+ }
201
+ /**
202
+ * Stable React component used for per-node runtime mounting inside dynamic
203
+ * `h.render((...args) => ...)` and function-as-child callbacks (Effect child
204
+ * components, `onMount`, or nested `h.component` props).
205
+ */
206
+ export function DynamicNodeBridge(props) {
207
+ const bridge = useContext(ReactHostContext);
208
+ if (bridge === undefined) {
209
+ throw new Error("effect-ui-react: dynamic render callbacks with Effect UI child components or onMount require an owning ReactHost / ReactDomHost.");
210
+ }
211
+ const [source] = useState(() => makeSource({ node: props.node, dispatch: props.dispatch }));
212
+ const [box] = useState(() => createBridgeInstanceBox(bridge, source, (currentBridge) => currentBridge.mountDynamicNode(source), (currentBridge) => currentBridge.renderServerDynamicNode(source)));
213
+ box.update(bridge, source);
214
+ const prev = source.current();
215
+ if (prev.node !== props.node || prev.dispatch !== props.dispatch) {
216
+ source.set({ node: props.node, dispatch: props.dispatch });
217
+ }
218
+ return useSyncExternalStore(box.subscribe, box.getSnapshot, box.getServerSnapshot);
219
+ }
220
+ DynamicNodeBridge.displayName = "DynamicNodeBridge";
@@ -0,0 +1,138 @@
1
+ import { type Component, Mount, type Renderer, View } from "effect/ui";
2
+ import { type ComponentType, type ElementType, type FunctionComponent, type ReactElement as ReactElementNode, type ReactNode, type Ref as ReactRef } from "react";
3
+ import type { IntrinsicElements, VoidIntrinsicElements } from "../Intrinsics.js";
4
+ import { ComponentRequirementsSymbol, type BridgedComponent, type ComponentPropMarker } from "./react-component-bridge.js";
5
+ type IsAny<T> = 0 extends 1 & T ? true : false;
6
+ type IsUnknown<T> = IsAny<T> extends true ? false : unknown extends T ? true : false;
7
+ export type AcceptsReactElement<T> = IsAny<T> extends true ? false : IsUnknown<T> extends true ? false : ReactElementNode extends NonNullable<T> ? true : false;
8
+ type ChildrenCallbackArgs<T> = T extends (...args: infer A) => infer Ret ? AcceptsReactElement<Ret> extends true ? A : never : never;
9
+ type HasChildrenCallback<T> = [ChildrenCallbackArgs<NonNullable<T>>] extends [never] ? false : true;
10
+ type ExtractRefTarget<R> = [NonNullable<R>] extends [ReactRef<infer T>] ? T : never;
11
+ export type HostNodeOfProps<P> = P extends unknown ? "ref" extends keyof P ? [ExtractRefTarget<P["ref"]>] extends [never] ? unknown : ExtractRefTarget<P["ref"]> : unknown : never;
12
+ type RefValue<R> = R | (ExtractRefTarget<R> extends never ? never : Renderer.Ref<any> & {
13
+ readonly "~Node"?: (_: never) => ExtractRefTarget<R>;
14
+ });
15
+ export type RefParam<P> = P extends unknown ? "ref" extends keyof P ? RefValue<NonNullable<P["ref"]>> : never : never;
16
+ export type DataAttributes = {
17
+ readonly [key: `data-${string}`]: unknown;
18
+ };
19
+ export type ChildRequirements<C> = [C] extends [never] ? never : [unknown] extends [View.Requirements<C>] ? never : View.Requirements<C>;
20
+ type ExtractRequirement<T> = [NonNullable<T>] extends [
21
+ {
22
+ readonly [ComponentRequirementsSymbol]?: () => infer R;
23
+ }
24
+ ] ? [unknown] extends [R] ? never : R : never;
25
+ type NestedDepth = [never, 0, 1, 2, 3];
26
+ type NestedRecordRequirements<T, D extends number = 4> = [D] extends [never] ? never : [NonNullable<T>] extends [(...args: ReadonlyArray<any>) => any] ? never : [NonNullable<T>] extends [ReadonlyArray<infer E>] ? ExtractRequirement<E> | NestedRecordRequirements<E, NestedDepth[D]> : [NonNullable<T>] extends [Record<string, unknown>] ? {
27
+ [K in keyof NonNullable<T>]-?: ExtractRequirement<NonNullable<T>[K]> | NestedRecordRequirements<NonNullable<T>[K], NestedDepth[D]>;
28
+ }[keyof NonNullable<T>] : never;
29
+ type PropRequirements<Props> = {
30
+ [K in keyof Props]-?: ExtractRequirement<Props[K]> | NestedRecordRequirements<Props[K]>;
31
+ }[keyof Props];
32
+ type UnionKeys<T> = T extends unknown ? keyof T : never;
33
+ type RejectExcess<Actual, Expected> = [Exclude<keyof Actual, UnionKeys<Expected>>] extends [never] ? unknown : {
34
+ readonly [K in Exclude<keyof Actual, UnionKeys<Expected>>]: never;
35
+ };
36
+ type BridgedComponentMember<M, D extends number> = M extends ComponentType<infer CP> ? Exclude<M, FunctionComponent<CP>> | BridgedComponent<CP, any> | ComponentPropMarker<CP, any> : [D] extends [never] ? M : M extends ReactElementNode | Date | RegExp | Promise<any> | ((...args: ReadonlyArray<any>) => any) ? M : M extends object ? {
37
+ [K in keyof M]: BridgedComponentProp<M[K], NestedDepth[D]>;
38
+ } : M;
39
+ type BridgedComponentProp<T, D extends number = 4> = IsAny<T> extends true ? T : IsUnknown<T> extends true ? T : BridgedComponentMember<T, D>;
40
+ type WithBridgedComponents<P> = {
41
+ [K in keyof P]: BridgedComponentProp<P[K]>;
42
+ };
43
+ export type ReactProps<P> = P extends unknown ? Partial<WithBridgedComponents<Omit<P, "children" | "ref" | "key">>> : never;
44
+ type PropValueFor<Bag, K extends string> = Bag extends unknown ? K extends keyof Bag ? Bag[K] : never : never;
45
+ export type ReactEventHandler<Msg, Args extends ReadonlyArray<any>> = Msg | ((...args: Args) => Msg | undefined);
46
+ export interface EventHelper<Msg> {
47
+ (msg: Msg, options?: View.EventOptions | undefined): () => void;
48
+ <Args extends ReadonlyArray<any>>(handler: (...args: Args) => Msg | undefined, options?: View.EventOptions | undefined): (...args: Args) => void;
49
+ }
50
+ export type RenderPropValue<R = never> = [R] extends [never] ? ReactElementNode : ReactElementNode & {
51
+ readonly [ComponentRequirementsSymbol]?: () => R;
52
+ };
53
+ export type RenderCallbackValue<Args extends ReadonlyArray<any>, R = never> = [R] extends [never] ? (...args: Args) => ReactElementNode : ((...args: Args) => ReactElementNode) & {
54
+ readonly [ComponentRequirementsSymbol]?: () => R;
55
+ };
56
+ export interface RenderHelper<Msg> {
57
+ <const Out extends View.Input<Msg, unknown>>(view: Out): RenderPropValue<ChildRequirements<Out>>;
58
+ <Args extends ReadonlyArray<any>, const Out extends View.Input<Msg, unknown>>(fn: (...args: Args) => Out): RenderCallbackValue<Args, ChildRequirements<Out>>;
59
+ }
60
+ export interface ComponentHelper<Host, H> {
61
+ <Name extends string, Props, Model, CompMsg, Events, R, V extends View.Elements>(component: Component.Members<Name, Props, Model, CompMsg, Events, R, V, any> & ([Renderer.HostOf<V>] extends [Host] ? unknown : never)): ComponentPropMarker<Props, R>;
62
+ <P, const Out extends View.Input<never, unknown> = never>(render: (h: H, props: P) => Out): ComponentPropMarker<P, ChildRequirements<Out>>;
63
+ }
64
+ export type VoidIntrinsicTag = keyof VoidIntrinsicElements & string;
65
+ type ChildrenPropOf<P> = P extends unknown ? ("children" extends keyof P ? P["children"] : never) : never;
66
+ interface ViewChildren<Msg> {
67
+ children<This, const C extends ReadonlyArray<View.Input<Msg, unknown> | ReactElementNode>>(this: This, ...inputs: C): View.WithRequirements<This, View.Requirements<C[number]>>;
68
+ }
69
+ interface CallbackChildren<P, Msg> {
70
+ children<This, const Out extends View.Input<Msg, unknown>>(this: This, render: (...args: ChildrenCallbackArgs<NonNullable<ChildrenPropOf<P>>>) => Out): View.WithRequirements<This, ChildRequirements<Out>>;
71
+ }
72
+ type ChildrenMethods<P, Msg, Tag extends string = string> = Tag extends VoidIntrinsicTag ? {} : "children" extends UnionKeys<P> ? AcceptsReactElement<ChildrenPropOf<P>> extends true ? ViewChildren<Msg> & (HasChildrenCallback<ChildrenPropOf<P>> extends true ? CallbackChildren<P, Msg> : {}) : HasChildrenCallback<ChildrenPropOf<P>> extends true ? CallbackChildren<P, Msg> : {
73
+ children<This>(this: This, value: ChildrenPropOf<P>): This;
74
+ } : {};
75
+ /**
76
+ * Fluent builder for React elements and components (`h.div`, `h.input`, `h.el(View)`, `h.el("custom-tag")`).
77
+ * Subclasses `View.ElementBuilder` so `.key()`, `.ref()`, `.onMount()`, `.forward()`,
78
+ * `.pipe()`, and `View.Shorthand` work natively across Effect UI.
79
+ */
80
+ export declare class ReactElementBuilder<out Msg, out R = never, in out P = {}, out Tag extends string = string, in out Node = HostNodeOfProps<P>> extends View.ElementBuilder<Msg, R, any, Node, Tag> {
81
+ }
82
+ export interface ReactElementBuilder<out Msg, out R = never, in out P = {}, out Tag extends string = string, in out Node = HostNodeOfProps<P>> {
83
+ /**
84
+ * Phantom: keeps `ReactBuilder` through `View.WithRequirements`.
85
+ */
86
+ readonly "~With"?: ReactBuilder<P, Msg, R | this["~Add"], Tag, Node>;
87
+ prop<This, K extends UnionKeys<ReactProps<P>> & string, const V extends PropValueFor<ReactProps<P>, K>>(this: This, name: K, value: V): View.WithRequirements<This, ExtractRequirement<V> | NestedRecordRequirements<V>>;
88
+ /** @internal Keeps `ReactElementBuilder` structurally assignable to `View.ElementBuilder`. */
89
+ prop(name: never, value: never): this;
90
+ props<This, const Props extends ReactProps<P>>(this: This, properties: Props & RejectExcess<NoInfer<Props>, ReactProps<P>>): View.WithRequirements<This, PropRequirements<Props>>;
91
+ /** @internal Keeps `ReactElementBuilder` structurally assignable to `View.ElementBuilder`. */
92
+ props(properties: never): this;
93
+ /**
94
+ * Forwards a raw third-party React props object (such as Base UI's `render(props, state)` bag,
95
+ * which may include `ref` or `children`). Prefer `.props()`, `.ref()`, `.key()`, and `.children()`
96
+ * for direct authoring.
97
+ */
98
+ spread<This>(this: This, properties: object): This;
99
+ ref(ref: RefParam<P>): this;
100
+ /** @internal Keeps `ReactElementBuilder` structurally assignable to `View.ElementBuilder`. */
101
+ ref(ref: never): this;
102
+ onMount<This, R2 = never>(this: This, mount: Mount.Issued<Msg | Component.Noop, R2, Node, never> | undefined): View.WithRequirements<This, R2>;
103
+ onMount<This>(this: This, mount: Mount.Issued<Msg | Component.Noop | View.MountHint, any, Node, never>): never;
104
+ }
105
+ export type ReactBuilder<P, Msg, R = never, Tag extends string = string, Node = HostNodeOfProps<P>> = ReactElementBuilder<Msg, R, P, Tag, Node> & ChildrenMethods<P, Msg, Tag>;
106
+ type MaybeShorthand<B> = B extends {
107
+ readonly children: (...inputs: any) => View.WithRequirements<B, any>;
108
+ } ? View.Shorthand<B> : B;
109
+ export type IntrinsicBuilder<K extends string, P, Msg> = K extends VoidIntrinsicTag ? ReactBuilder<P & DataAttributes, Msg, never, K> : "children" extends UnionKeys<P> ? AcceptsReactElement<ChildrenPropOf<P>> extends true ? MaybeShorthand<ReactBuilder<P & DataAttributes, Msg, never, K>> : ReactBuilder<P & DataAttributes, Msg, never, K> : ReactBuilder<P & DataAttributes, Msg, never, K>;
110
+ export type IntrinsicElementBuilder<K extends string, P, Msg> = ReactBuilder<P & DataAttributes, Msg, never, K>;
111
+ export interface ElHelper<Msg> {
112
+ <P>(component: ComponentType<P>): ReactBuilder<P, Msg, never, "$react">;
113
+ <K extends keyof IntrinsicElements & string>(tag: K): IntrinsicElementBuilder<K, IntrinsicElements[K], Msg>;
114
+ <K extends keyof IntrinsicElements & string, const C extends readonly [View.Input<Msg, unknown>, ...ReadonlyArray<View.Input<Msg, unknown>>]>(tag: K, ...children: C): ReactBuilder<IntrinsicElements[K] & DataAttributes, Msg, View.Requirements<C[number]>, K>;
115
+ (tag: string): ReactBuilder<Record<string, unknown> & {
116
+ readonly children?: ReactNode;
117
+ }, Msg, never, string>;
118
+ <const C extends readonly [View.Input<Msg, unknown>, ...ReadonlyArray<View.Input<Msg, unknown>>]>(tag: string, ...children: C): ReactBuilder<Record<string, unknown> & {
119
+ readonly children?: ReactNode;
120
+ }, Msg, View.Requirements<C[number]>, string>;
121
+ }
122
+ export declare function eventHandler<Msg>(msg: Msg, options?: View.EventOptions | undefined): () => void;
123
+ export declare function eventHandler<Msg, Args extends ReadonlyArray<any>>(handler: (...args: Args) => Msg | undefined, options?: View.EventOptions | undefined): (...args: Args) => void;
124
+ export declare function renderProp<Msg, const Out extends View.Input<Msg, unknown>>(view: Out): RenderPropValue<ChildRequirements<Out>>;
125
+ export declare function renderProp<Msg, Args extends ReadonlyArray<any>, const Out extends View.Input<Msg, unknown>>(fn: (...args: Args) => Out): RenderCallbackValue<Args, ChildRequirements<Out>>;
126
+ export declare function componentProp(target: unknown): unknown;
127
+ /**
128
+ * Creates a cached intrinsic JSX root builder that supports fluent chaining
129
+ * (`h.div.props({ className: "..." }).children(...)`) and callable children
130
+ * shorthand (`h.strong("bold")`, `h.div(child1, child2)`).
131
+ */
132
+ export declare function createIntrinsicRoot(tag: string): unknown;
133
+ /**
134
+ * Creates a fluent `ReactElementBuilder` for a React component or tag string
135
+ * (`h.el(View)`, `h.el(Button)`, `h.el("custom-tag")`).
136
+ */
137
+ export declare function reactEl(type: ElementType, ...children: ReadonlyArray<unknown>): unknown;
138
+ export {};