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,750 @@
1
+ import { Renderer, Subscription } from "effect/ui";
2
+ import * as AtomRegistry from "effect/reactivity/AtomRegistry";
3
+ import { Context, Effect, Exit, Fiber, Layer, Option, Predicate, Queue, Schema, Scope, Stream } from "effect";
4
+ import { createElement, Fragment, isValidElement, useEffect, use, useLayoutEffect, useSyncExternalStore } from "react";
5
+ import * as React from "./React.js";
6
+ import { containsComponentMarker, ReactHostContext } from "./internal/react-component-bridge.js";
7
+ import { makePlacementBridge } from "./internal/child-placement.js";
8
+ import { renderView } from "./internal/render-view.js";
9
+ import { toReactElement } from "./internal/to-react-element.js";
10
+ const useIsomorphicLayoutEffect = typeof globalThis !== "undefined" && "document" in globalThis ? useLayoutEffect : useEffect;
11
+ const HostNodeBrand = Symbol.for("effect-ui-react/host-node");
12
+ function isHostNode(value) {
13
+ return Predicate.isObject(value) && HostNodeBrand in value;
14
+ }
15
+ /** Mounts into an existing host for the current Scope, inheriting application services. */
16
+ export const mountEffect = Effect.fnUntraced(function* (component, props, renderer, options) {
17
+ const outerContext = yield* Effect.context();
18
+ const hostContext = yield* Layer.build(renderer.layer);
19
+ const fullContext = Context.merge(outerContext, hostContext);
20
+ renderer.setContext(fullContext);
21
+ return yield* Renderer.mount(component, props, renderer.container, options).pipe(Effect.provide(fullContext));
22
+ });
23
+ /** A scoped application mount; closing the Layer unmounts the Effect tree. */
24
+ export function mount(component, props, renderer, options) {
25
+ return Layer.effectDiscard(mountEffect(component, props, renderer, options));
26
+ }
27
+ /**
28
+ * Starts `component` with the services `layer` builds, for an existing React
29
+ * app (or a platform that renders one root component) to render through the
30
+ * returned `Component`. Call it once, at module level: every rendered
31
+ * `Component` shows this one tree, which lives until `dispose` is called.
32
+ */
33
+ export function make(component, props, layer, options) {
34
+ const renderer = options?.renderer ?? makeHost();
35
+ const scope = Scope.makeUnsafe();
36
+ let context = Context.empty();
37
+ // This is an entry point for non-Effect callers. Effect callers use mountEffect.
38
+ // The Layer is built into `scope` rather than with `Effect.provide`, which
39
+ // would release its services as soon as mounting finished.
40
+ const mounting = Effect.runPromise(Effect.gen(function* () {
41
+ const services = yield* Layer.build(layer);
42
+ const fullContext = Context.merge(yield* Effect.context(), services);
43
+ context = fullContext;
44
+ return yield* mountEffect(component, props, renderer, options).pipe(Effect.provide(fullContext));
45
+ }).pipe(Scope.provide(scope), Effect.onError(() => Scope.close(scope, Exit.void))), { onFiberStart: (fiber) => { Fiber.runIn(fiber, scope); } });
46
+ const root = Object.assign(mounting.then((value) => {
47
+ Object.assign(root, { status: "fulfilled", value });
48
+ return value;
49
+ }, (reason) => {
50
+ Object.assign(root, { status: "rejected", reason });
51
+ throw reason;
52
+ }), {
53
+ // React's thenable protocol also lets renderToString read an already mounted
54
+ // tree synchronously, without first suspending to discover its result.
55
+ status: "pending"
56
+ });
57
+ function Component() {
58
+ use(root);
59
+ return createElement(renderer.Root);
60
+ }
61
+ return {
62
+ Component,
63
+ root,
64
+ dispose: () => Effect.runPromiseWith(context)(Scope.close(scope, Exit.void))
65
+ };
66
+ }
67
+ function sameKeys(a, b) {
68
+ const aKeys = a === undefined ? [] : Object.keys(a);
69
+ const bKeys = b === undefined ? [] : Object.keys(b);
70
+ if (aKeys.length !== bKeys.length)
71
+ return false;
72
+ for (const key of aKeys) {
73
+ if (b === undefined || !(key in b))
74
+ return false;
75
+ }
76
+ return true;
77
+ }
78
+ const DEFAULT_CONTROLLED = new Set(["value", "checked", "selected"]);
79
+ const SourceChanged = Symbol.for("effect-ui-react/source-changed");
80
+ const isSourceChanged = (msg) => Predicate.isObject(msg) && SourceChanged in msg;
81
+ // Re-renders a shell when React hands its source a new value.
82
+ const followSource = (source, name = "source") => Subscription.make(name, Stream.callback(Effect.fnUntraced(function* (queue) {
83
+ yield* Effect.acquireRelease(Effect.sync(() => source.subscribe(() => {
84
+ Queue.offerUnsafe(queue, { [SourceChanged]: source.version() });
85
+ })), (unsubscribe) => Effect.sync(unsubscribe));
86
+ })));
87
+ // The shells below receive live objects from React (sources, render callbacks,
88
+ // mounted nodes), so their schemas check the shape instead of decoding data.
89
+ const isSource = (input) => Predicate.hasProperty(input, "current") && Predicate.isFunction(input.current) &&
90
+ Predicate.hasProperty(input, "version") && Predicate.isFunction(input.version) &&
91
+ Predicate.hasProperty(input, "subscribe") && Predicate.isFunction(input.subscribe);
92
+ const SourceSchema = () => Schema.declare((input) => isSource(input));
93
+ const RenderSourceSchema = SourceSchema();
94
+ const DynamicNodeSourceSchema = SourceSchema();
95
+ const PlacementTargetSchema = Schema.declare((input) => Predicate.hasProperty(input, "kind") && (input.kind === "component"
96
+ ? Predicate.hasProperty(input, "component")
97
+ : (input.kind === "render" || input.kind === "node") &&
98
+ Predicate.hasProperty(input, "source") && isSource(input.source)));
99
+ // Shells forward whatever the content inside them dispatches, so their
100
+ // messages are only known to be values.
101
+ const ShellMessage = Schema.Unknown;
102
+ const RenderShell = React.component({
103
+ name: "ReactComponentBridge",
104
+ props: Schema.Struct({
105
+ render: RenderSourceSchema,
106
+ reactProps: Schema.Unknown
107
+ }),
108
+ model: Schema.Number,
109
+ message: ShellMessage
110
+ }).make({
111
+ init: ($) => $.props.render.version(),
112
+ subscriptions: ($) => [followSource($.props.render)],
113
+ update: ($, msg) => isSourceChanged(msg) ? msg[SourceChanged] : $.model,
114
+ view: (h) => (h.props.render.current()(h, h.props.reactProps) ?? null)
115
+ });
116
+ const renderDispatchIdentity = (msg) => msg;
117
+ const DynamicNodeShell = React.component({
118
+ name: "DynamicNodeBridge",
119
+ props: Schema.Struct({ source: DynamicNodeSourceSchema }),
120
+ model: Schema.Number,
121
+ message: ShellMessage
122
+ }).make({
123
+ init: ($) => $.props.source.version(),
124
+ subscriptions: ($) => [followSource($.props.source)],
125
+ update: ($, msg) => {
126
+ if (isSourceChanged(msg))
127
+ return msg[SourceChanged];
128
+ $.props.source.current().dispatch(msg);
129
+ return $.model;
130
+ },
131
+ view: (h) => h.props.source.current().node
132
+ });
133
+ // Renders one React-created child inside its Effect owner. Its props, render
134
+ // callback or node arrive through sources, so React updates re-render only
135
+ // this shell, never the owner.
136
+ const PlacementShell = React.component({
137
+ name: "ReactPlacement",
138
+ props: Schema.Struct({
139
+ target: PlacementTargetSchema,
140
+ props: SourceSchema()
141
+ }),
142
+ model: Schema.Number,
143
+ message: ShellMessage
144
+ }).make({
145
+ init: () => 0,
146
+ subscriptions: ($) => {
147
+ const { target, props } = $.props;
148
+ return target.kind === "component"
149
+ ? [followSource(props, "props")]
150
+ : [followSource(props, "props"), followSource(target.source, target.kind)];
151
+ },
152
+ update: ($, msg) => {
153
+ if (isSourceChanged(msg))
154
+ return $.model + 1;
155
+ const { target } = $.props;
156
+ if (target.kind === "node")
157
+ target.source.current().dispatch(msg);
158
+ return $.model;
159
+ },
160
+ view: (h) => {
161
+ const { target, props } = h.props;
162
+ switch (target.kind) {
163
+ case "node":
164
+ return target.source.current().node;
165
+ case "render":
166
+ return (target.source.current()(h, props.current()) ?? null);
167
+ case "component":
168
+ return target.component(h, { props: props.current() });
169
+ }
170
+ }
171
+ });
172
+ /**
173
+ * Creates a renderer-agnostic React host for `effect/ui`.
174
+ * Depends only on `effect`, `effect/ui`, and `react` (no `react-dom` or DOM globals).
175
+ */
176
+ export function makeHost(options) {
177
+ let nextId = 0;
178
+ const dirtyBoundaries = new Set();
179
+ const dirtyBridges = new Set();
180
+ const pendingBoundaries = new Set();
181
+ const afterCommitWaiters = new Set();
182
+ const boundaryComponents = new Map();
183
+ let attachedContext;
184
+ // Placements are written to the registry React.component readers resolve:
185
+ // the app's own when one is provided above the host, otherwise this one.
186
+ let hostRegistry = AtomRegistry.make();
187
+ function flushFirstCommitWaiters(boundary) {
188
+ if (boundary.firstCommitWaiters.size === 0)
189
+ return;
190
+ const waiters = Array.from(boundary.firstCommitWaiters);
191
+ boundary.firstCommitWaiters.clear();
192
+ for (const resolve of waiters)
193
+ resolve();
194
+ }
195
+ function flushAfterCommitWaiters() {
196
+ if (pendingBoundaries.size > 0 || afterCommitWaiters.size === 0)
197
+ return;
198
+ const waiters = Array.from(afterCommitWaiters);
199
+ afterCommitWaiters.clear();
200
+ for (const resolve of waiters)
201
+ resolve();
202
+ }
203
+ function markBoundarySettled(boundary) {
204
+ if (!pendingBoundaries.delete(boundary))
205
+ return;
206
+ flushAfterCommitWaiters();
207
+ }
208
+ function getRefCallback(target) {
209
+ if (target.refCallback === undefined) {
210
+ let userCleanup;
211
+ target.refCallback = (instance) => {
212
+ target.refTarget = instance == null ? undefined : instance;
213
+ const userRef = target.props.ref;
214
+ if (instance == null && userCleanup !== undefined) {
215
+ const cleanup = userCleanup;
216
+ userCleanup = undefined;
217
+ cleanup();
218
+ return;
219
+ }
220
+ if (typeof userRef === "function") {
221
+ const cleanup = userRef(instance);
222
+ userCleanup = typeof cleanup === "function" ? cleanup : undefined;
223
+ }
224
+ else if (Predicate.isObject(userRef) && "current" in userRef) {
225
+ ;
226
+ userRef.current = instance;
227
+ }
228
+ };
229
+ }
230
+ return target.refCallback;
231
+ }
232
+ function useBoundarySnapshot(boundary) {
233
+ const snapshot = useSyncExternalStore(boundary.store.subscribe, boundary.store.getSnapshot, boundary.store.getSnapshot);
234
+ // Explicitly approved exception to the AGENTS.md rule against useLayoutEffect /
235
+ // useEffect in the React host: notifies post-commit hooks (such as controlled
236
+ // input caret restoration in `effect-ui-react/dom`) and resolves `React.Host.afterCommit`
237
+ // and first-commit ref waiters once React finishes committing the latest snapshot.
238
+ useIsomorphicLayoutEffect(() => {
239
+ boundary.committed = true;
240
+ flushFirstCommitWaiters(boundary);
241
+ options?.onAfterCommit?.();
242
+ if (Object.is(snapshot, boundary.snapshot)) {
243
+ markBoundarySettled(boundary);
244
+ }
245
+ }, [snapshot]);
246
+ return snapshot;
247
+ }
248
+ function getBoundaryComponent(name) {
249
+ let Boundary = boundaryComponents.get(name);
250
+ if (Boundary === undefined) {
251
+ const Component = ({ boundary, bridge }) => {
252
+ const snapshot = useBoundarySnapshot(boundary);
253
+ return bridge === undefined
254
+ ? snapshot
255
+ : createElement(ReactHostContext.Provider, { value: bridge }, snapshot);
256
+ };
257
+ Object.defineProperty(Component, "name", { value: name });
258
+ Component.displayName = name;
259
+ Boundary = Component;
260
+ boundaryComponents.set(name, Boundary);
261
+ }
262
+ return Boundary;
263
+ }
264
+ function rebuildBoundary(target) {
265
+ const boundary = target.boundary;
266
+ if (boundary === undefined || !boundary.dirty)
267
+ return;
268
+ boundary.dirty = false;
269
+ boundary.snapshot = createElement(Fragment, null, ...target.children.map(toReact));
270
+ }
271
+ function createBoundary(target) {
272
+ const listeners = new Set();
273
+ const boundary = {
274
+ listeners,
275
+ firstCommitWaiters: new Set(),
276
+ committed: false,
277
+ dirty: true,
278
+ snapshot: null,
279
+ store: {
280
+ subscribe: (listener) => {
281
+ listeners.add(listener);
282
+ return () => {
283
+ listeners.delete(listener);
284
+ if (listeners.size === 0) {
285
+ markBoundarySettled(boundary);
286
+ }
287
+ };
288
+ },
289
+ getSnapshot: () => {
290
+ if (boundary.dirty)
291
+ rebuildBoundary(target);
292
+ return boundary.snapshot;
293
+ }
294
+ }
295
+ };
296
+ dirtyBoundaries.add(target);
297
+ return boundary;
298
+ }
299
+ const node = (tag) => {
300
+ const created = {
301
+ [HostNodeBrand]: true,
302
+ id: nextId++,
303
+ tag,
304
+ attrs: {},
305
+ props: {},
306
+ children: [],
307
+ dirty: true
308
+ };
309
+ if (tag === "$root" || tag === "$boundary" || tag === "$placement") {
310
+ created.boundary = createBoundary(created);
311
+ }
312
+ return created;
313
+ };
314
+ const container = node("$root");
315
+ const activeRoots = new Set([container]);
316
+ function isConnected(target) {
317
+ let current = target;
318
+ while (current !== undefined) {
319
+ if (activeRoots.has(current))
320
+ return true;
321
+ current = current.parent;
322
+ }
323
+ return false;
324
+ }
325
+ function markDirty(target) {
326
+ let current = target;
327
+ while (current !== undefined) {
328
+ if (current.boundary !== undefined) {
329
+ if (!current.boundary.dirty) {
330
+ current.boundary.dirty = true;
331
+ dirtyBoundaries.add(current);
332
+ }
333
+ return;
334
+ }
335
+ if (current.dirty)
336
+ return;
337
+ current.dirty = true;
338
+ current = current.parent;
339
+ }
340
+ }
341
+ function detach(child) {
342
+ const parent = child.parent;
343
+ if (!parent)
344
+ return;
345
+ parent.children.splice(parent.children.indexOf(child), 1);
346
+ child.parent = undefined;
347
+ markDirty(parent);
348
+ }
349
+ function remove(child) {
350
+ if (child.tag === "$placement") {
351
+ ;
352
+ child.props.$placementHandle?.attach(undefined);
353
+ }
354
+ child.refTarget = undefined;
355
+ if (child.boundary !== undefined) {
356
+ flushFirstCommitWaiters(child.boundary);
357
+ markBoundarySettled(child.boundary);
358
+ }
359
+ detach(child);
360
+ }
361
+ function getRenderDispatch(target) {
362
+ if (target.renderDispatch === undefined) {
363
+ target.renderDispatch = (msg) => {
364
+ target.events?.dispatch("$renderDispatch", renderDispatchIdentity, msg);
365
+ };
366
+ }
367
+ return target.renderDispatch;
368
+ }
369
+ function renderPropNode(propNode) {
370
+ const children = propNode.children.map(toReact);
371
+ const result = children.length === 1 && isValidElement(children[0])
372
+ ? children[0]
373
+ : createElement(Fragment, null, ...children);
374
+ propNode.cached = result;
375
+ propNode.dirty = false;
376
+ return result;
377
+ }
378
+ function renderElement(target) {
379
+ const hasHandlers = target.events !== undefined && Object.keys(target.events.handlers).length > 0;
380
+ if (hasHandlers && target.handlerCache === undefined) {
381
+ target.handlerCache = new Map();
382
+ }
383
+ if (target.componentCache === undefined && Object.values(target.props).some(containsComponentMarker)) {
384
+ target.componentCache = new Map();
385
+ }
386
+ let propOverrides;
387
+ const normalChildren = [];
388
+ for (const child of target.children) {
389
+ if (child.tag === "$prop") {
390
+ const propName = child.props.$propName;
391
+ if (typeof propName === "string") {
392
+ propOverrides ??= {};
393
+ propOverrides[propName] = renderPropNode(child);
394
+ }
395
+ continue;
396
+ }
397
+ normalChildren.push(toReact(child));
398
+ }
399
+ const attachRef = target.props.$hasRef === true;
400
+ const dispatchMessage = getRenderDispatch(target);
401
+ return toReactElement(target, normalChildren, {
402
+ key: target.id,
403
+ binding: target.events,
404
+ getBinding: () => target.events,
405
+ handlerCache: target.handlerCache,
406
+ refCallback: attachRef ? getRefCallback(target) : undefined,
407
+ componentCache: target.componentCache,
408
+ onDirtyBridge: (entry) => {
409
+ dirtyBridges.add(entry);
410
+ },
411
+ propOverrides,
412
+ renderDynamic: (view) => renderView(view, {
413
+ getBinding: () => target.events,
414
+ dispatchMessage
415
+ })
416
+ });
417
+ }
418
+ function toReact(target) {
419
+ if (!target.dirty)
420
+ return target.cached;
421
+ let next;
422
+ if (target.tag === "$text") {
423
+ next = target.text;
424
+ }
425
+ else if (target.tag === "$placementScope") {
426
+ // Content a component handed to a headless child or slot: React mounts
427
+ // inside register with the scope, which that child instance renders.
428
+ const name = typeof target.props.$name === "string" ? target.props.$name : "EffectComponent";
429
+ next = createElement(ReactHostContext.Provider, { key: target.id, value: placementBridgeOf(target, name) }, ...target.children.map(toReact));
430
+ }
431
+ else if (target.tag === "$prop" || target.tag === "$placement") {
432
+ next = null;
433
+ }
434
+ else if (target.boundary !== undefined) {
435
+ const name = typeof target.props.$name === "string" ? target.props.$name : "EffectComponent";
436
+ next = createElement(getBoundaryComponent(name), {
437
+ key: target.id,
438
+ boundary: target.boundary,
439
+ bridge: placementBridgeOf(target, name)
440
+ });
441
+ }
442
+ else {
443
+ next = renderElement(target);
444
+ }
445
+ target.cached = next;
446
+ target.dirty = false;
447
+ return next;
448
+ }
449
+ function placementBridgeOf(target, name) {
450
+ const owner = target.props.$placementOwner;
451
+ if (typeof owner !== "string")
452
+ return undefined;
453
+ target.placementBridge ??= makePlacementBridge(name, owner, bridgeContext, hostRegistry, PlacementShell);
454
+ return target.placementBridge;
455
+ }
456
+ const afterCommit = Effect.suspend(() => {
457
+ if (pendingBoundaries.size === 0)
458
+ return Effect.void;
459
+ return Effect.callback((resume) => {
460
+ const onSettled = () => resume(Effect.void);
461
+ afterCommitWaiters.add(onSettled);
462
+ return Effect.sync(() => {
463
+ afterCommitWaiters.delete(onSettled);
464
+ });
465
+ });
466
+ });
467
+ function owningBoundaryOf(target) {
468
+ let current = target;
469
+ while (current !== undefined) {
470
+ if (current.boundary !== undefined)
471
+ return current.boundary;
472
+ current = current.parent;
473
+ }
474
+ return undefined;
475
+ }
476
+ const resolveRef = Effect.fnUntraced(function* (target) {
477
+ yield* afterCommit;
478
+ if (!isHostNode(target))
479
+ return Option.some(target);
480
+ if (target.refTarget !== undefined)
481
+ return Option.some(target.refTarget);
482
+ if (!isConnected(target))
483
+ return Option.none();
484
+ const boundary = owningBoundaryOf(target);
485
+ if (boundary !== undefined && !boundary.committed) {
486
+ yield* Effect.callback((resume) => {
487
+ const onCommit = () => resume(Effect.void);
488
+ boundary.firstCommitWaiters.add(onCommit);
489
+ return Effect.sync(() => {
490
+ boundary.firstCommitWaiters.delete(onCommit);
491
+ });
492
+ });
493
+ }
494
+ return target.refTarget !== undefined
495
+ ? Option.some(target.refTarget)
496
+ : Option.none();
497
+ });
498
+ const runMount = Effect.fnUntraced(function* (hostMount, send) {
499
+ const running = hostMount;
500
+ const resolved = yield* resolveRef(running.node);
501
+ if (Option.isNone(resolved))
502
+ return;
503
+ const initialMount = running.mount;
504
+ const changes = Stream.unwrap(Effect.gen(function* () {
505
+ const kept = running.mount["~args"];
506
+ let made = running.args;
507
+ if (made === undefined) {
508
+ const fresh = (made = running.args = kept.make(running.mount.args));
509
+ yield* Scope.addFinalizer(running.scope, Effect.sync(() => kept.close(fresh)));
510
+ }
511
+ return kept.changes(made);
512
+ }));
513
+ return yield* initialMount.run(resolved.value, initialMount.args, changes, send);
514
+ });
515
+ const host = {
516
+ elements: [React.name],
517
+ controlled: options?.controlled ?? DEFAULT_CONTROLLED,
518
+ runsMounts: runMount,
519
+ ...(options?.head !== undefined ? { head: options.head } : {}),
520
+ createElement: node,
521
+ createText: (text) => ({ ...node("$text"), text }),
522
+ setText: (target, text) => {
523
+ if (target.text === text)
524
+ return;
525
+ target.text = text;
526
+ markDirty(target);
527
+ },
528
+ setAttr: (target, name, value) => {
529
+ if (value === undefined) {
530
+ if (!(name in target.attrs))
531
+ return;
532
+ delete target.attrs[name];
533
+ }
534
+ else {
535
+ if (target.attrs[name] === value)
536
+ return;
537
+ target.attrs[name] = value;
538
+ }
539
+ markDirty(target);
540
+ },
541
+ setProp: (target, name, value) => {
542
+ if (name === "$placementHandle" && value !== target.props[name]) {
543
+ const boundary = target.boundary;
544
+ const output = createElement(getBoundaryComponent("ReactPlacement"), { boundary });
545
+ value?.attach({
546
+ subscribe: boundary.store.subscribe,
547
+ getSnapshot: () => output
548
+ });
549
+ }
550
+ if (name === "$placementOwner" && value !== target.props[name]) {
551
+ target.placementBridge = undefined;
552
+ }
553
+ if (value === undefined) {
554
+ if (!(name in target.props))
555
+ return;
556
+ delete target.props[name];
557
+ }
558
+ else {
559
+ if (Object.is(target.props[name], value))
560
+ return;
561
+ target.props[name] = value;
562
+ }
563
+ if (target.boundary !== undefined) {
564
+ target.dirty = true;
565
+ markDirty(target.parent);
566
+ return;
567
+ }
568
+ markDirty(target);
569
+ },
570
+ insertBefore: (parent, child, ref) => {
571
+ if (child === ref)
572
+ return;
573
+ const currentIndex = child.parent === parent ? parent.children.indexOf(child) : -1;
574
+ const targetIndex = ref === undefined ? parent.children.length : parent.children.indexOf(ref);
575
+ if (targetIndex < 0)
576
+ throw new Error("Reference node is not a child of parent");
577
+ if (currentIndex >= 0 && currentIndex === targetIndex - 1) {
578
+ return;
579
+ }
580
+ detach(child);
581
+ const insertIndex = currentIndex >= 0 && currentIndex < targetIndex ? targetIndex - 1 : targetIndex;
582
+ parent.children.splice(insertIndex, 0, child);
583
+ child.parent = parent;
584
+ markDirty(parent);
585
+ },
586
+ remove,
587
+ parentOf: (target) => target.parent,
588
+ nextOf: (target) => {
589
+ const siblings = target.parent?.children;
590
+ return siblings?.[siblings.indexOf(target) + 1];
591
+ },
592
+ setEvents: (target, handlers, dispatch, eventOptions) => {
593
+ const prevHandlers = target.events?.handlers;
594
+ target.events = {
595
+ handlers,
596
+ dispatch: (event, handler, payload, onMessage) => {
597
+ options?.onBeforeDispatch?.(payload);
598
+ return dispatch(event, handler, payload, onMessage);
599
+ },
600
+ options: eventOptions
601
+ };
602
+ if (target.handlerCache !== undefined) {
603
+ for (const name of target.handlerCache.keys()) {
604
+ if (!(name in handlers))
605
+ target.handlerCache.delete(name);
606
+ }
607
+ }
608
+ if (!sameKeys(prevHandlers, handlers)) {
609
+ markDirty(target);
610
+ }
611
+ },
612
+ commit: () => {
613
+ if (dirtyBoundaries.size === 0 && dirtyBridges.size === 0)
614
+ return;
615
+ const batch = Array.from(dirtyBoundaries);
616
+ dirtyBoundaries.clear();
617
+ const toNotify = [];
618
+ // Pass 1: publish immutable snapshots for every connected dirty boundary.
619
+ for (const boundaryNode of batch) {
620
+ if (!isConnected(boundaryNode))
621
+ continue;
622
+ rebuildBoundary(boundaryNode);
623
+ const boundary = boundaryNode.boundary;
624
+ if (boundary !== undefined && boundary.listeners.size > 0) {
625
+ pendingBoundaries.add(boundary);
626
+ toNotify.push(boundary);
627
+ }
628
+ }
629
+ const bridgesToNotify = Array.from(dirtyBridges);
630
+ dirtyBridges.clear();
631
+ // Pass 2: notify mounted React boundaries and component bridges once all snapshots are ready.
632
+ for (const boundary of toNotify) {
633
+ for (const listener of boundary.listeners)
634
+ listener();
635
+ }
636
+ for (const bridge of bridgesToNotify) {
637
+ for (const listener of bridge.listeners)
638
+ listener();
639
+ }
640
+ }
641
+ };
642
+ const reactHost = {
643
+ afterCommit,
644
+ resolve: (target) => {
645
+ if (isHostNode(target)) {
646
+ const instance = target.refTarget;
647
+ return instance !== undefined ? Option.some(instance) : Option.none();
648
+ }
649
+ return Option.some(target);
650
+ },
651
+ resolveRef
652
+ };
653
+ const rawLayer = Layer.mergeAll(Renderer.layer(host), Layer.succeed(React.Host, reactHost));
654
+ const layer = Layer.effectContext(Effect.gen(function* () {
655
+ const outerContext = yield* Effect.context();
656
+ const rendering = yield* Layer.build(rawLayer);
657
+ // Every React.component reads its placements through an Atom, so make
658
+ // sure some AtomRegistry exists without replacing an app-provided one.
659
+ const existing = yield* Effect.serviceOption(AtomRegistry.AtomRegistry);
660
+ if (Option.isSome(existing))
661
+ hostRegistry = existing.value;
662
+ const built = Option.isSome(existing)
663
+ ? rendering
664
+ : Context.add(rendering, AtomRegistry.AtomRegistry, hostRegistry);
665
+ attachedContext = Context.merge(outerContext, built);
666
+ return built;
667
+ }));
668
+ function setContext(context) {
669
+ attachedContext = context;
670
+ }
671
+ function mountComponent(component, initialProps) {
672
+ if (attachedContext === undefined) {
673
+ throw new Error("Build the React host layer before rendering bridged components");
674
+ }
675
+ const parentScope = Context.get(attachedContext, Scope.Scope);
676
+ const childScope = Scope.forkUnsafe(parentScope);
677
+ const subContainer = node("$root");
678
+ activeRoots.add(subContainer);
679
+ let mountedRoot;
680
+ let pendingProps;
681
+ let closed = false;
682
+ const ctx = Context.merge(attachedContext, Context.make(Scope.Scope, childScope));
683
+ const mountEffect = Renderer.mount(component, initialProps, subContainer).pipe(Effect.provide(ctx), Effect.tap((root) => Effect.sync(() => {
684
+ if (closed)
685
+ return;
686
+ mountedRoot = root;
687
+ if (pendingProps !== undefined) {
688
+ root.setProps(pendingProps.value);
689
+ pendingProps = undefined;
690
+ }
691
+ })));
692
+ // React invokes this outside a fiber. Re-enter with the captured services
693
+ // and references, and bind suspended mounting to the subtree lifetime.
694
+ Fiber.runIn(Effect.runForkWith(ctx)(mountEffect), childScope);
695
+ return {
696
+ boundary: subContainer.boundary.store,
697
+ setProps: (nextProps) => {
698
+ if (closed)
699
+ return;
700
+ if (mountedRoot !== undefined) {
701
+ mountedRoot.setProps(nextProps);
702
+ }
703
+ else {
704
+ pendingProps = { value: nextProps };
705
+ }
706
+ },
707
+ close: () => {
708
+ if (closed)
709
+ return;
710
+ closed = true;
711
+ mountedRoot = undefined;
712
+ activeRoots.delete(subContainer);
713
+ flushFirstCommitWaiters(subContainer.boundary);
714
+ markBoundarySettled(subContainer.boundary);
715
+ Effect.runForkWith(ctx)(Scope.close(childScope, Exit.void));
716
+ }
717
+ };
718
+ }
719
+ function renderServerComponent(component, initialProps) {
720
+ const handle = mountComponent(component, initialProps);
721
+ try {
722
+ return handle.boundary.getSnapshot();
723
+ }
724
+ finally {
725
+ handle.close();
726
+ }
727
+ }
728
+ const bridgeContext = {
729
+ mountComponent,
730
+ mountRender: (render, initialProps) => {
731
+ const handle = mountComponent(RenderShell, { render, reactProps: initialProps });
732
+ return {
733
+ ...handle,
734
+ setProps: (reactProps) => handle.setProps({ render, reactProps })
735
+ };
736
+ },
737
+ mountDynamicNode: (source) => mountComponent(DynamicNodeShell, { source }),
738
+ renderServerComponent,
739
+ renderServerRender: (render, initialProps) => renderServerComponent(RenderShell, { render, reactProps: initialProps }),
740
+ renderServerDynamicNode: (source) => renderServerComponent(DynamicNodeShell, { source })
741
+ };
742
+ const rootBoundary = container.boundary;
743
+ function RootBoundary() {
744
+ return useBoundarySnapshot(rootBoundary);
745
+ }
746
+ function Root(props) {
747
+ return createElement(ReactHostContext.Provider, { value: bridgeContext }, props.children !== undefined ? props.children : createElement(RootBoundary));
748
+ }
749
+ return { host, reactHost, layer, container, Root, setContext };
750
+ }