@cognitap/radiant 0.0.91 → 0.0.92

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 (129) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/dist/library/a2ui/A2uiPlaceholder.d.ts +14 -0
  3. package/dist/library/a2ui/A2uiPlaceholder.d.ts.map +1 -0
  4. package/dist/library/a2ui/A2uiPlaceholder.js +44 -0
  5. package/dist/library/a2ui/A2uiPlaceholder.js.map +1 -0
  6. package/dist/library/a2ui/A2uiSurface.d.ts +33 -0
  7. package/dist/library/a2ui/A2uiSurface.d.ts.map +1 -0
  8. package/dist/library/a2ui/A2uiSurface.js +542 -0
  9. package/dist/library/a2ui/A2uiSurface.js.map +1 -0
  10. package/dist/library/a2ui/accessibility.d.ts +31 -0
  11. package/dist/library/a2ui/accessibility.d.ts.map +1 -0
  12. package/dist/library/a2ui/accessibility.js +108 -0
  13. package/dist/library/a2ui/accessibility.js.map +1 -0
  14. package/dist/library/a2ui/accessibilityRules.d.ts +28 -0
  15. package/dist/library/a2ui/accessibilityRules.d.ts.map +1 -0
  16. package/dist/library/a2ui/accessibilityRules.js +73 -0
  17. package/dist/library/a2ui/accessibilityRules.js.map +1 -0
  18. package/dist/library/a2ui/catalogGenerator.d.ts +29 -0
  19. package/dist/library/a2ui/catalogGenerator.d.ts.map +1 -0
  20. package/dist/library/a2ui/catalogGenerator.js +578 -0
  21. package/dist/library/a2ui/catalogGenerator.js.map +1 -0
  22. package/dist/library/a2ui/coerce.d.ts +16 -0
  23. package/dist/library/a2ui/coerce.d.ts.map +1 -0
  24. package/dist/library/a2ui/coerce.js +254 -0
  25. package/dist/library/a2ui/coerce.js.map +1 -0
  26. package/dist/library/a2ui/entries.d.ts +6 -0
  27. package/dist/library/a2ui/entries.d.ts.map +1 -0
  28. package/dist/library/a2ui/entries.js +277 -0
  29. package/dist/library/a2ui/entries.js.map +1 -0
  30. package/dist/library/a2ui/fixtures.d.ts +38 -0
  31. package/dist/library/a2ui/fixtures.d.ts.map +1 -0
  32. package/dist/library/a2ui/fixtures.js +389 -0
  33. package/dist/library/a2ui/fixtures.js.map +1 -0
  34. package/dist/library/a2ui/index.d.ts +17 -0
  35. package/dist/library/a2ui/index.d.ts.map +1 -0
  36. package/dist/library/a2ui/index.js +9 -0
  37. package/dist/library/a2ui/index.js.map +1 -0
  38. package/dist/library/a2ui/protocolErrors.d.ts +13 -0
  39. package/dist/library/a2ui/protocolErrors.d.ts.map +1 -0
  40. package/dist/library/a2ui/protocolErrors.js +48 -0
  41. package/dist/library/a2ui/protocolErrors.js.map +1 -0
  42. package/dist/library/a2ui/registry.d.ts +58 -0
  43. package/dist/library/a2ui/registry.d.ts.map +1 -0
  44. package/dist/library/a2ui/registry.js +128 -0
  45. package/dist/library/a2ui/registry.js.map +1 -0
  46. package/dist/library/a2ui/sanitize.d.ts +7 -0
  47. package/dist/library/a2ui/sanitize.d.ts.map +1 -0
  48. package/dist/library/a2ui/sanitize.js +54 -0
  49. package/dist/library/a2ui/sanitize.js.map +1 -0
  50. package/dist/library/a2ui/surfaceRuntime.d.ts +34 -0
  51. package/dist/library/a2ui/surfaceRuntime.d.ts.map +1 -0
  52. package/dist/library/a2ui/surfaceRuntime.js +284 -0
  53. package/dist/library/a2ui/surfaceRuntime.js.map +1 -0
  54. package/dist/library/catalog/actions.d.ts +40 -0
  55. package/dist/library/catalog/actions.d.ts.map +1 -0
  56. package/dist/library/catalog/actions.js +70 -0
  57. package/dist/library/catalog/actions.js.map +1 -0
  58. package/dist/library/catalog/coerce.d.ts +70 -0
  59. package/dist/library/catalog/coerce.d.ts.map +1 -0
  60. package/dist/library/catalog/coerce.js +332 -0
  61. package/dist/library/catalog/coerce.js.map +1 -0
  62. package/dist/library/catalog/index.d.ts +9 -0
  63. package/dist/library/catalog/index.d.ts.map +1 -0
  64. package/dist/library/catalog/index.js +6 -0
  65. package/dist/library/catalog/index.js.map +1 -0
  66. package/dist/library/catalog/radiantCatalog.d.ts +9 -0
  67. package/dist/library/catalog/radiantCatalog.d.ts.map +1 -0
  68. package/dist/library/catalog/radiantCatalog.js +902 -0
  69. package/dist/library/catalog/radiantCatalog.js.map +1 -0
  70. package/dist/library/catalog/types.d.ts +113 -0
  71. package/dist/library/catalog/types.d.ts.map +1 -0
  72. package/dist/library/catalog/types.js +27 -0
  73. package/dist/library/catalog/types.js.map +1 -0
  74. package/dist/library/catalog/validate.d.ts +31 -0
  75. package/dist/library/catalog/validate.d.ts.map +1 -0
  76. package/dist/library/catalog/validate.js +420 -0
  77. package/dist/library/catalog/validate.js.map +1 -0
  78. package/dist/library/components/Card/Card.d.ts +6 -2
  79. package/dist/library/components/Card/Card.d.ts.map +1 -1
  80. package/dist/library/components/Card/Card.js +12 -4
  81. package/dist/library/components/Card/Card.js.map +1 -1
  82. package/dist/library/components/Table/Table.d.ts +6 -2
  83. package/dist/library/components/Table/Table.d.ts.map +1 -1
  84. package/dist/library/components/Table/Table.js +10 -4
  85. package/dist/library/components/Table/Table.js.map +1 -1
  86. package/dist/library/index.d.ts +1 -1
  87. package/dist/library/index.d.ts.map +1 -1
  88. package/dist/library/presentation.d.ts +3 -0
  89. package/dist/library/presentation.d.ts.map +1 -1
  90. package/dist/library/styles.css +1 -1
  91. package/dist/library/themes/components.d.ts +6 -0
  92. package/dist/library/themes/components.d.ts.map +1 -1
  93. package/dist/library/themes/components.js +6 -0
  94. package/dist/library/themes/components.js.map +1 -1
  95. package/dist/library/themes/tokens.d.ts +4 -0
  96. package/dist/library/themes/tokens.d.ts.map +1 -1
  97. package/dist/library/themes/tokens.js +3 -0
  98. package/dist/library/themes/tokens.js.map +1 -1
  99. package/docs/accessibility.md +6 -0
  100. package/docs/architecture.md +13 -1
  101. package/docs/theming.md +13 -0
  102. package/package.json +17 -5
  103. package/src/a2ui/A2uiPlaceholder.tsx +64 -0
  104. package/src/a2ui/A2uiSurface.tsx +790 -0
  105. package/src/a2ui/accessibility.ts +145 -0
  106. package/src/a2ui/accessibilityRules.ts +106 -0
  107. package/src/a2ui/catalog.json +317 -0
  108. package/src/a2ui/catalogGenerator.ts +717 -0
  109. package/src/a2ui/coerce.ts +379 -0
  110. package/src/a2ui/entries.tsx +519 -0
  111. package/src/a2ui/fixtures.ts +402 -0
  112. package/src/a2ui/index.ts +50 -0
  113. package/src/a2ui/protocolErrors.ts +63 -0
  114. package/src/a2ui/registry.ts +221 -0
  115. package/src/a2ui/sanitize.ts +51 -0
  116. package/src/a2ui/surfaceRuntime.ts +317 -0
  117. package/src/catalog/actions.ts +108 -0
  118. package/src/catalog/coerce.ts +447 -0
  119. package/src/catalog/index.ts +67 -0
  120. package/src/catalog/radiantCatalog.ts +949 -0
  121. package/src/catalog/types.ts +159 -0
  122. package/src/catalog/validate.ts +454 -0
  123. package/src/components/Card/Card.tsx +35 -19
  124. package/src/components/Table/Table.tsx +16 -3
  125. package/src/index.ts +1 -1
  126. package/src/presentation.ts +3 -0
  127. package/src/themes/baseline.css +3 -0
  128. package/src/themes/components.ts +6 -0
  129. package/src/themes/tokens.ts +7 -0
@@ -0,0 +1,790 @@
1
+ 'use client'
2
+
3
+ import {
4
+ cloneElement,
5
+ Component,
6
+ Fragment,
7
+ isValidElement,
8
+ memo,
9
+ useCallback,
10
+ useContext,
11
+ useEffect,
12
+ useLayoutEffect,
13
+ useRef,
14
+ useState,
15
+ useSyncExternalStore,
16
+ type ErrorInfo,
17
+ type ReactNode,
18
+ type Ref
19
+ } from 'react'
20
+ import { cn } from 'cn'
21
+ import type { ComponentApi, FunctionImplementation } from '@a2ui/web_core/catalog'
22
+ import { MessageProcessor, type ProcessableMessage } from '@a2ui/web_core/processing'
23
+ import { effect, getValue, peekValue, type Signal } from '@a2ui/web_core/reactivity'
24
+ import { NodeResolver, type ComponentNode } from '@a2ui/web_core/resolution'
25
+ import type { ActionPayload, SurfaceModel } from '@a2ui/web_core/state'
26
+ import {
27
+ createCatalogActionEvent,
28
+ snapshotSurfaceState,
29
+ type CatalogActionEvent,
30
+ type CatalogDiagnostic
31
+ } from '../catalog/index.js'
32
+ import { isPlainRecord } from '../catalog/coerce.js'
33
+ import { focusRingClass } from '../components/shared/focusStyles.js'
34
+ import type { MotionProfile } from '../motion/config.js'
35
+ import { MotionProfileContext } from '../motion/context.js'
36
+ import { useComposedRefs } from '../react/useComposedRefs.js'
37
+ import { warnA2uiAccessibility } from './accessibility.js'
38
+ import { A2UI_PROTOCOL_VERSION } from './catalogGenerator.js'
39
+ import {
40
+ COERCED_NOOP_ACTION_NAME,
41
+ coerceA2uiMessages,
42
+ extractA2uiNodeFallbackText,
43
+ getRegistryEntry
44
+ } from './coerce.js'
45
+ import { A2uiPlaceholder, createPlaceholderTracker } from './A2uiPlaceholder.js'
46
+ import { radiantA2uiRegistry } from './entries.js'
47
+ import {
48
+ createsSurface,
49
+ deletesSurface,
50
+ streamedComponents,
51
+ protocolErrorDiagnostic,
52
+ supersededBy,
53
+ updatesSurface
54
+ } from './protocolErrors.js'
55
+ import type { A2uiRegistry, A2uiRenderOptions } from './registry.js'
56
+ import type { A2uiMessage } from './sanitize.js'
57
+ import {
58
+ animateNodeEntry,
59
+ captureFocusSnapshot,
60
+ cloneMessageValue,
61
+ createMicrotaskCoalescer,
62
+ isHtmlElement,
63
+ isMessagePrefix,
64
+ restoreFocusFallback,
65
+ type FocusSnapshot,
66
+ type NodeHost
67
+ } from './surfaceRuntime.js'
68
+
69
+ /**
70
+ * Outbound action payload delivered by `A2uiSurface`.
71
+ * Implements the protocol-independent `CatalogActionEvent` (`{ action, surfaceId, nodeId, state }`)
72
+ * while preserving the underlying A2UI wire fields (`name`, `sourceComponentId`, `context`, `timestamp`).
73
+ */
74
+ export type A2uiActionPayload = CatalogActionEvent & ActionPayload
75
+
76
+ export type A2uiSurfaceProps = {
77
+ /** Identifier of the A2UI surface to render. */
78
+ readonly surfaceId: string
79
+ /** A2UI 1.0 protocol messages defining and updating the surface. */
80
+ readonly messages: readonly A2uiMessage[]
81
+ /** Registry mapping A2UI component names to Radiant adapters. Defaults to `radiantA2uiRegistry`. */
82
+ readonly registry?: A2uiRegistry
83
+ /** Host callback invoked when an outbound A2UI action event fires. */
84
+ readonly onAction?: (action: A2uiActionPayload) => void
85
+ /**
86
+ * Host callback invoked whenever a prop is coerced, defaulted, stripped, or falls back, and for
87
+ * catalog or protocol errors (`kind: 'error'` with a `code`).
88
+ */
89
+ readonly onDiagnostic?: (diagnostic: CatalogDiagnostic) => void
90
+ }
91
+
92
+ function isVisibleHost(element: HTMLElement): boolean {
93
+ if (!element.isConnected || element.hidden || element.getClientRects().length === 0) return false
94
+ const win = element.ownerDocument.defaultView
95
+ return !win || win.getComputedStyle(element).visibility !== 'hidden'
96
+ }
97
+
98
+ function createSurfaceDomRuntime(initialMotionProfile: MotionProfile) {
99
+ const hosts = new Map<string, NodeHost & { readonly elements?: readonly HTMLElement[] }>()
100
+ const mountedInstances = new Map<string, string>()
101
+ const containers = new Set<string>()
102
+ const committedInstances = new Set<string>()
103
+ const pendingMounts = new Set<string>()
104
+ const unmountedInstances = new Set<string>()
105
+ let surfaceElement: HTMLDivElement | null = null
106
+ let motionProfile = initialMotionProfile
107
+ let pendingFocus: FocusSnapshot | null = null
108
+ const placeholders = createPlaceholderTracker()
109
+ // Text nodes whose latest definition has not streamed its text yet; they reserve a line.
110
+ const pendingText = new Set<string>()
111
+
112
+ function flushBatch() {
113
+ if (pendingFocus) {
114
+ const snapshot = pendingFocus
115
+ pendingFocus = null
116
+ restoreFocusFallback(surfaceElement, snapshot, hosts)
117
+ }
118
+ if (surfaceElement?.isConnected && pendingMounts.size > 0) {
119
+ for (const nodeId of pendingMounts) {
120
+ const host = hosts.get(nodeId)
121
+ if (!host || host.isContainer || !host.element.isConnected) continue
122
+ if (committedInstances.has(host.instanceId) && unmountedInstances.has(host.instanceId)) {
123
+ continue
124
+ }
125
+ for (const el of host.elements ?? [host.element]) {
126
+ if (el.isConnected) animateNodeEntry(el, motionProfile)
127
+ }
128
+ }
129
+ pendingMounts.clear()
130
+ }
131
+ for (const [nodeId, host] of hosts) {
132
+ if (!mountedInstances.has(nodeId) || !host.element.isConnected) hosts.delete(nodeId)
133
+ }
134
+ for (const nodeId of containers) {
135
+ if (!mountedInstances.has(nodeId)) containers.delete(nodeId)
136
+ }
137
+ unmountedInstances.clear()
138
+ committedInstances.clear()
139
+ for (const instanceId of mountedInstances.values()) committedInstances.add(instanceId)
140
+ }
141
+
142
+ const scheduleBatchFlush = createMicrotaskCoalescer(flushBatch)
143
+
144
+ function captureFocus() {
145
+ if (!pendingFocus) pendingFocus = captureFocusSnapshot(surfaceElement, hosts)
146
+ if (pendingFocus) scheduleBatchFlush()
147
+ }
148
+
149
+ return {
150
+ placeholders,
151
+ pendingText,
152
+ setSurfaceElement(element: HTMLDivElement | null) {
153
+ surfaceElement = element
154
+ },
155
+ setMotionProfile(nextProfile: MotionProfile) {
156
+ motionProfile = nextProfile
157
+ },
158
+ setNodeHost(
159
+ nodeId: string,
160
+ instanceId: string,
161
+ element: unknown,
162
+ isContainer?: boolean,
163
+ elements?: readonly HTMLElement[]
164
+ ) {
165
+ if (isHtmlElement(element)) {
166
+ hosts.set(nodeId, {
167
+ nodeId,
168
+ instanceId,
169
+ element,
170
+ elements,
171
+ isContainer: isContainer ?? containers.has(nodeId)
172
+ })
173
+ } else if (element === null) {
174
+ hosts.delete(nodeId)
175
+ }
176
+ },
177
+ captureFocus,
178
+ onNodeMount(nodeId: string, instanceId: string, requestProbe: () => void) {
179
+ mountedInstances.set(nodeId, instanceId)
180
+ pendingMounts.add(nodeId)
181
+ const host = hosts.get(nodeId)
182
+ if (
183
+ !containers.has(nodeId) &&
184
+ (!host || host.instanceId !== instanceId || !host.element.isConnected)
185
+ ) {
186
+ requestProbe()
187
+ }
188
+ scheduleBatchFlush()
189
+ },
190
+ onNodeUnmount(nodeId: string, instanceId: string) {
191
+ mountedInstances.delete(nodeId)
192
+ pendingMounts.delete(nodeId)
193
+ unmountedInstances.add(instanceId)
194
+ captureFocus()
195
+ scheduleBatchFlush()
196
+ },
197
+ setNodeContainer(nodeId: string, isContainer: boolean) {
198
+ if (isContainer) containers.add(nodeId)
199
+ else containers.delete(nodeId)
200
+ const host = hosts.get(nodeId)
201
+ if (host && host.isContainer !== isContainer) hosts.set(nodeId, { ...host, isContainer })
202
+ },
203
+ onSurfaceRebuild() {
204
+ committedInstances.clear()
205
+ pendingMounts.clear()
206
+ unmountedInstances.clear()
207
+ }
208
+ }
209
+ }
210
+
211
+ type SurfaceDomRuntime = ReturnType<typeof createSurfaceDomRuntime>
212
+
213
+ function useSignalValue<T>(signal: Signal<T> | undefined): T | undefined {
214
+ return useSyncExternalStore(
215
+ onStoreChange => {
216
+ if (!signal) return () => {}
217
+ let initial = true
218
+ return effect(() => {
219
+ getValue(signal)
220
+ if (initial) {
221
+ initial = false
222
+ return
223
+ }
224
+ onStoreChange()
225
+ })
226
+ },
227
+ () => (signal ? peekValue(signal) : undefined),
228
+ () => (signal ? peekValue(signal) : undefined)
229
+ )
230
+ }
231
+
232
+ const boundaryFallbackText = (node: ComponentNode, token: unknown) =>
233
+ extractA2uiNodeFallbackText(node, isPlainRecord(token) ? token : undefined)
234
+
235
+ type BoundaryProps = {
236
+ readonly node: ComponentNode
237
+ readonly resetToken: unknown
238
+ readonly onDiagnostic: (diagnostic: CatalogDiagnostic) => void
239
+ readonly onFallbackRef?: Ref<HTMLElement>
240
+ readonly children: ReactNode
241
+ }
242
+
243
+ class A2uiNodeErrorBoundary extends Component<
244
+ BoundaryProps,
245
+ { readonly failed: boolean; readonly failedToken: unknown }
246
+ > {
247
+ override state = { failed: false, failedToken: undefined as unknown }
248
+
249
+ static getDerivedStateFromError() {
250
+ return { failed: true }
251
+ }
252
+
253
+ static getDerivedStateFromProps(
254
+ next: BoundaryProps,
255
+ prev: { readonly failed: boolean; readonly failedToken: unknown }
256
+ ) {
257
+ if (!prev.failed) return null
258
+ if (prev.failedToken === undefined) return { failed: true, failedToken: next.resetToken }
259
+ return next.resetToken !== prev.failedToken ? { failed: false, failedToken: undefined } : null
260
+ }
261
+
262
+ override componentDidCatch(error: Error, _info: ErrorInfo) {
263
+ const { node, resetToken, onDiagnostic } = this.props
264
+ onDiagnostic({
265
+ kind: 'fallback',
266
+ nodeId: node.componentId,
267
+ component: node.type,
268
+ prop: 'render',
269
+ received: error.message || 'Render error',
270
+ used: boundaryFallbackText(node, resetToken),
271
+ reason: 'Component threw during render.'
272
+ })
273
+ }
274
+
275
+ override render(): ReactNode {
276
+ if (!this.state.failed) return this.props.children
277
+ const text = boundaryFallbackText(this.props.node, this.props.resetToken)
278
+ return text ? (
279
+ <span
280
+ ref={this.props.onFallbackRef}
281
+ data-slot="a2ui-fallback"
282
+ data-node-id={this.props.node.componentId}
283
+ >
284
+ {text}
285
+ </span>
286
+ ) : null
287
+ }
288
+ }
289
+
290
+ type A2uiNodeRendererProps = {
291
+ readonly node: ComponentNode
292
+ readonly registry: A2uiRegistry
293
+ readonly inline: boolean
294
+ readonly onDiagnostic: (diagnostic: CatalogDiagnostic) => void
295
+ readonly runtime: SurfaceDomRuntime
296
+ }
297
+
298
+ const A2uiNodeRenderer = memo(function A2uiNodeRenderer({
299
+ node,
300
+ registry,
301
+ inline,
302
+ onDiagnostic,
303
+ runtime
304
+ }: A2uiNodeRendererProps): ReactNode {
305
+ const props = useSignalValue(node.props)
306
+ const resolved = Boolean(props) && node.state === 'resolved'
307
+ const entry = resolved ? getRegistryEntry(registry, node.type) : undefined
308
+ const active = Boolean(entry)
309
+
310
+ let hasChildNodes = false
311
+ const adapted =
312
+ props && entry
313
+ ? entry.adapter(props, {
314
+ node,
315
+ inline,
316
+ renderNode(child: ComponentNode, options?: A2uiRenderOptions) {
317
+ if (!options?.inline) hasChildNodes = true
318
+ return (
319
+ <A2uiNodeRenderer
320
+ key={child.id}
321
+ node={child}
322
+ registry={registry}
323
+ inline={options?.inline ?? false}
324
+ onDiagnostic={onDiagnostic}
325
+ runtime={runtime}
326
+ />
327
+ )
328
+ }
329
+ })
330
+ : null
331
+ // Text whose text has not streamed yet stays empty but reserves its line.
332
+ const rendered =
333
+ runtime.pendingText.has(node.componentId) &&
334
+ isValidElement<{ className?: string }>(adapted) &&
335
+ adapted.type !== Fragment
336
+ ? cloneElement(adapted, {
337
+ className: cn(
338
+ adapted.props.className,
339
+ inline ? 'inline-block min-h-[1lh]' : 'block min-h-[1lh]'
340
+ )
341
+ })
342
+ : adapted
343
+
344
+ const isContainer = node.type === 'Column' || hasChildNodes
345
+ const [probing, setProbing] = useState(false)
346
+ const startRef = useRef<HTMLTemplateElement>(null)
347
+
348
+ const setHostRef = useCallback(
349
+ (element: HTMLElement | null) => runtime.setNodeHost(node.id, node.instanceId, element),
350
+ [node.id, node.instanceId, runtime]
351
+ )
352
+ const hostElement =
353
+ !inline && isValidElement<{ ref?: Ref<HTMLElement> }>(rendered) && rendered.type !== Fragment
354
+ ? rendered
355
+ : null
356
+ const composedRef = useComposedRefs(setHostRef, hostElement?.props.ref)
357
+
358
+ useLayoutEffect(() => {
359
+ if (active && !inline) runtime.setNodeContainer(node.id, isContainer)
360
+ }, [active, inline, isContainer, node.id, props, runtime])
361
+
362
+ useLayoutEffect(() => {
363
+ if (!active || inline) return
364
+ runtime.onNodeMount(node.id, node.instanceId, () => setProbing(true))
365
+ return () => runtime.onNodeUnmount(node.id, node.instanceId)
366
+ }, [active, inline, node.id, node.instanceId, runtime])
367
+
368
+ if (node.state === 'pending') {
369
+ return (
370
+ <A2uiPlaceholder
371
+ nodeId={node.componentId}
372
+ inline={inline}
373
+ tracker={runtime.placeholders}
374
+ />
375
+ )
376
+ }
377
+ if (!props || !entry) return null
378
+
379
+ return (
380
+ <A2uiNodeErrorBoundary
381
+ key={node.id}
382
+ node={node}
383
+ resetToken={props}
384
+ onDiagnostic={onDiagnostic}
385
+ onFallbackRef={inline ? undefined : setHostRef}
386
+ >
387
+ {probing ? <template ref={startRef} /> : null}
388
+ {hostElement ? cloneElement(hostElement, { ref: composedRef }) : rendered}
389
+ {probing ? (
390
+ <template
391
+ ref={end => {
392
+ if (!end) return
393
+ const start = startRef.current
394
+ if (start && start.parentNode === end.parentNode) {
395
+ const visible: HTMLElement[] = []
396
+ for (
397
+ let el = start.nextElementSibling;
398
+ el && el !== end;
399
+ el = el.nextElementSibling
400
+ ) {
401
+ if (isHtmlElement(el) && isVisibleHost(el)) visible.push(el)
402
+ }
403
+ if (visible.length > 0) {
404
+ runtime.setNodeHost(
405
+ node.id,
406
+ node.instanceId,
407
+ visible[0],
408
+ isContainer,
409
+ visible.length > 1 ? visible : undefined
410
+ )
411
+ }
412
+ }
413
+ setProbing(false)
414
+ }}
415
+ />
416
+ ) : null}
417
+ </A2uiNodeErrorBoundary>
418
+ )
419
+ })
420
+
421
+ type SurfacePhase = 'awaiting' | 'live' | 'closed'
422
+
423
+ function createSurfaceStore(
424
+ initialSurfaceId: string,
425
+ initialRegistry: A2uiRegistry,
426
+ initialMessages: readonly A2uiMessage[],
427
+ initialOnAction: ((action: A2uiActionPayload) => void) | undefined,
428
+ initialOnDiagnostic: ((diagnostic: CatalogDiagnostic) => void) | undefined,
429
+ runtime: SurfaceDomRuntime
430
+ ) {
431
+ let surfaceId = initialSurfaceId
432
+ let registry = initialRegistry
433
+ let processedMessages: A2uiMessage[] = []
434
+ let reported: readonly [string, A2uiRegistry, readonly A2uiMessage[]] | undefined
435
+ let actionHandler = initialOnAction
436
+ let diagnosticHandler = initialOnDiagnostic
437
+ let disposed = false
438
+ let processor: MessageProcessor<ComponentApi> | undefined
439
+ let resolver: NodeResolver<ComponentApi, FunctionImplementation> | undefined
440
+ let stopRootEffect: (() => void) | undefined
441
+ let stopErrors: (() => void) | undefined
442
+ let resolvedSurface: SurfaceModel<ComponentApi> | undefined
443
+ // Errors are queued during sync, dropped on an identical rebuild, and delivered directly otherwise.
444
+ let errorMode: 'direct' | 'queue' | 'suppress' = 'direct'
445
+ // `awaiting` until createSurface succeeds; `closed` after deleteSurface or a failed create.
446
+ let phase: SurfacePhase = 'awaiting'
447
+ // Updates that arrive before their createSurface wait here instead of failing.
448
+ let bufferedUpdates: A2uiMessage[] = []
449
+ // Unknown components report once per node and type for each engine build.
450
+ let reportedUnknown = new Set<string>()
451
+ const pendingDiagnostics: CatalogDiagnostic[] = []
452
+ const listeners = new Set<() => void>()
453
+
454
+ const notify = () => {
455
+ for (const listener of listeners) listener()
456
+ }
457
+
458
+ function flushDiagnostics() {
459
+ const batch = pendingDiagnostics.splice(0, pendingDiagnostics.length)
460
+ if (diagnosticHandler) for (const d of batch) diagnosticHandler(d)
461
+ }
462
+
463
+ function bindRootSignal() {
464
+ stopRootEffect?.()
465
+ stopRootEffect = undefined
466
+ if (listeners.size === 0 || !resolver) return
467
+ const rootSignal = resolver.rootNode
468
+ let initial = true
469
+ stopRootEffect = effect(() => {
470
+ getValue(rootSignal)
471
+ if (initial) {
472
+ initial = false
473
+ return
474
+ }
475
+ notify()
476
+ })
477
+ }
478
+
479
+ function teardownEngine() {
480
+ stopRootEffect?.()
481
+ stopRootEffect = undefined
482
+ stopErrors?.()
483
+ stopErrors = undefined
484
+ resolver?.dispose()
485
+ resolver = undefined
486
+ resolvedSurface = undefined
487
+ processor?.dispose()
488
+ processor = undefined
489
+ }
490
+
491
+ const makeResolver = (s: SurfaceModel<ComponentApi> | undefined) =>
492
+ s ? new NodeResolver(s as SurfaceModel<ComponentApi, FunctionImplementation>) : undefined
493
+
494
+ function withErrors(mode: typeof errorMode, run: () => void) {
495
+ const previous = errorMode
496
+ errorMode = mode
497
+ try {
498
+ run()
499
+ } finally {
500
+ errorMode = previous
501
+ }
502
+ }
503
+
504
+ // Rebinds the resolver whenever the surface model is created, deleted, or recreated.
505
+ function refreshResolver(target: MessageProcessor<ComponentApi>) {
506
+ const surface = target.getSurface(surfaceId)
507
+ if (resolver && !resolver.disposed && resolvedSurface === surface) return
508
+ resolver?.dispose()
509
+ resolvedSurface = surface
510
+ resolver = makeResolver(surface)
511
+ bindRootSignal()
512
+ }
513
+
514
+ function trackPendingText(
515
+ coerced: readonly A2uiMessage[],
516
+ diagnostics: readonly CatalogDiagnostic[]
517
+ ) {
518
+ for (const message of coerced) {
519
+ for (const component of streamedComponents(message, surfaceId)) {
520
+ if (component.component === 'Text') runtime.pendingText.delete(String(component.id))
521
+ }
522
+ }
523
+ for (const d of diagnostics) {
524
+ if (d.component === 'Text' && d.prop === 'text' && d.kind === 'defaulted') {
525
+ runtime.pendingText.add(d.nodeId)
526
+ }
527
+ }
528
+ }
529
+
530
+ function dropBuffered(reason: string) {
531
+ if (bufferedUpdates.length === 0) return
532
+ pendingDiagnostics.push({
533
+ kind: 'error',
534
+ code: 'DROPPED_UPDATES',
535
+ nodeId: '',
536
+ component: 'surface',
537
+ prop: 'message',
538
+ received: bufferedUpdates.length,
539
+ used: undefined,
540
+ reason
541
+ })
542
+ bufferedUpdates = []
543
+ }
544
+
545
+ // Each message is applied on its own so one protocol error cannot drop the rest of a batch.
546
+ function processBatch(
547
+ target: MessageProcessor<ComponentApi>,
548
+ targetRegistry: A2uiRegistry,
549
+ batch: readonly A2uiMessage[],
550
+ record: boolean
551
+ ) {
552
+ const detached = batch.map(message => cloneMessageValue(message))
553
+ const { messages: coerced, diagnostics } = coerceA2uiMessages(detached, targetRegistry)
554
+ trackPendingText(coerced, diagnostics)
555
+ if (record) {
556
+ for (const diagnostic of diagnostics) {
557
+ if (diagnostic.code === 'UNKNOWN_COMPONENT_TYPE') {
558
+ const key = `${diagnostic.nodeId}\u0000${String(diagnostic.received)}`
559
+ if (reportedUnknown.has(key)) continue
560
+ reportedUnknown.add(key)
561
+ }
562
+ pendingDiagnostics.push(diagnostic)
563
+ }
564
+ }
565
+ const apply = (message: A2uiMessage) =>
566
+ target.processMessages([message] as readonly ProcessableMessage[])
567
+ for (const message of coerced) {
568
+ if (phase === 'awaiting' && updatesSurface(message, surfaceId)) {
569
+ bufferedUpdates.push(message)
570
+ continue
571
+ }
572
+ apply(message)
573
+ if (createsSurface(message, surfaceId)) {
574
+ if (target.getSurface(surfaceId)) {
575
+ phase = 'live'
576
+ const held = bufferedUpdates.filter(update => !supersededBy(message, update))
577
+ bufferedUpdates = []
578
+ for (const update of held) apply(update)
579
+ } else if (phase === 'awaiting') {
580
+ phase = 'closed'
581
+ dropBuffered('createSurface failed; buffered updates were dropped.')
582
+ }
583
+ } else if (deletesSurface(message, surfaceId) && !target.getSurface(surfaceId)) {
584
+ phase = 'closed'
585
+ }
586
+ refreshResolver(target)
587
+ }
588
+ }
589
+
590
+ function buildEngine(
591
+ nextSurfaceId: string,
592
+ nextRegistry: A2uiRegistry,
593
+ nextMessages: readonly A2uiMessage[]
594
+ ) {
595
+ teardownEngine()
596
+ runtime.onSurfaceRebuild()
597
+ disposed = false
598
+ surfaceId = nextSurfaceId
599
+ registry = nextRegistry
600
+ bufferedUpdates = []
601
+ reportedUnknown = new Set()
602
+ runtime.pendingText.clear()
603
+ phase = 'awaiting'
604
+ const wireSnapshot = nextMessages.map(message => cloneMessageValue(message))
605
+ processedMessages = wireSnapshot
606
+ const sameBatch =
607
+ reported?.[0] === nextSurfaceId &&
608
+ reported[1] === nextRegistry &&
609
+ reported[2].length === wireSnapshot.length &&
610
+ isMessagePrefix(reported[2], wireSnapshot)
611
+ processor = new MessageProcessor(
612
+ [nextRegistry.toWebCoreCatalog()],
613
+ action => {
614
+ if (action.name === COERCED_NOOP_ACTION_NAME) return
615
+ const state = processor?.getSurface(action.surfaceId)?.dataModel.get('/')
616
+ const catalogEvent = createCatalogActionEvent({
617
+ action: action.name,
618
+ surfaceId: action.surfaceId,
619
+ nodeId: action.sourceComponentId,
620
+ state
621
+ })
622
+ const contextSnapshot = snapshotSurfaceState(action.context)
623
+ const context = (
624
+ isPlainRecord(contextSnapshot) ? contextSnapshot : Object.freeze({})
625
+ ) as Record<string, unknown>
626
+ actionHandler?.(Object.freeze({ ...action, ...catalogEvent, context }))
627
+ },
628
+ { version: A2UI_PROTOCOL_VERSION, reportErrorsOnly: true }
629
+ )
630
+ const errorSubscription = processor.model.onError.subscribe(error => {
631
+ if (errorMode === 'suppress' || (error.surfaceId && error.surfaceId !== surfaceId)) return
632
+ const diagnostic = protocolErrorDiagnostic(error)
633
+ if (errorMode === 'queue') pendingDiagnostics.push(diagnostic)
634
+ else diagnosticHandler?.(diagnostic)
635
+ })
636
+ stopErrors = () => errorSubscription.unsubscribe()
637
+ const target = processor
638
+ withErrors(sameBatch ? 'suppress' : 'queue', () => {
639
+ const before = pendingDiagnostics.length
640
+ processBatch(target, nextRegistry, wireSnapshot, Boolean(diagnosticHandler) && !sameBatch)
641
+ refreshResolver(target)
642
+ if (sameBatch) pendingDiagnostics.length = before
643
+ })
644
+ reported = [nextSurfaceId, nextRegistry, wireSnapshot]
645
+ }
646
+
647
+ buildEngine(initialSurfaceId, initialRegistry, initialMessages)
648
+
649
+ return {
650
+ subscribe(listener: () => void) {
651
+ listeners.add(listener)
652
+ if (listeners.size === 1) bindRootSignal()
653
+ return () => {
654
+ listeners.delete(listener)
655
+ if (listeners.size === 0) {
656
+ stopRootEffect?.()
657
+ stopRootEffect = undefined
658
+ }
659
+ }
660
+ },
661
+ getSnapshot() {
662
+ return resolver ? peekValue(resolver.rootNode) : undefined
663
+ },
664
+ getPhase: () => phase,
665
+ reportDiagnostic(diagnostic: CatalogDiagnostic) {
666
+ diagnosticHandler?.(diagnostic)
667
+ },
668
+ sync(
669
+ nextSurfaceId: string,
670
+ nextRegistry: A2uiRegistry,
671
+ nextMessages: readonly A2uiMessage[],
672
+ nextOnAction: ((action: A2uiActionPayload) => void) | undefined,
673
+ nextOnDiagnostic: ((diagnostic: CatalogDiagnostic) => void) | undefined
674
+ ) {
675
+ actionHandler = nextOnAction
676
+ diagnosticHandler = nextOnDiagnostic
677
+ if (!diagnosticHandler) pendingDiagnostics.length = 0
678
+ if (
679
+ disposed ||
680
+ !processor ||
681
+ surfaceId !== nextSurfaceId ||
682
+ registry !== nextRegistry ||
683
+ !isMessagePrefix(processedMessages, nextMessages)
684
+ ) {
685
+ runtime.captureFocus()
686
+ buildEngine(nextSurfaceId, nextRegistry, nextMessages)
687
+ flushDiagnostics()
688
+ notify()
689
+ return
690
+ }
691
+ if (nextMessages.length > processedMessages.length) {
692
+ runtime.captureFocus()
693
+ const delta = nextMessages
694
+ .slice(processedMessages.length)
695
+ .map(message => cloneMessageValue(message))
696
+ const target = processor
697
+ withErrors('queue', () => {
698
+ processBatch(target, nextRegistry, delta, Boolean(diagnosticHandler))
699
+ refreshResolver(target)
700
+ })
701
+ processedMessages.push(...delta)
702
+ flushDiagnostics()
703
+ notify()
704
+ return
705
+ }
706
+ flushDiagnostics()
707
+ },
708
+ dispose() {
709
+ if (disposed) return
710
+ disposed = true
711
+ teardownEngine()
712
+ }
713
+ }
714
+ }
715
+
716
+ const zeroPlaceholders = () => 0
717
+
718
+ /**
719
+ * Renders an A2UI 1.0 surface directly onto Radiant components via `@a2ui/web_core`.
720
+ * Merges appended patches incrementally by stable node ID to keep local state, focus,
721
+ * scroll position, and drags intact, animates newly added instances once, and recovers
722
+ * removed-node focus as documented in `docs/architecture.md`.
723
+ */
724
+ export function A2uiSurface({
725
+ surfaceId,
726
+ messages,
727
+ registry = radiantA2uiRegistry,
728
+ onAction,
729
+ onDiagnostic
730
+ }: A2uiSurfaceProps) {
731
+ const surfaceRef = useRef<HTMLDivElement>(null)
732
+ const motionProfile = useContext(MotionProfileContext)
733
+
734
+ const [runtime] = useState(() => createSurfaceDomRuntime(motionProfile))
735
+ const [store] = useState(() =>
736
+ createSurfaceStore(surfaceId, registry, messages, onAction, onDiagnostic, runtime)
737
+ )
738
+
739
+ useLayoutEffect(() => {
740
+ runtime.setSurfaceElement(surfaceRef.current)
741
+ return () => runtime.setSurfaceElement(null)
742
+ }, [runtime])
743
+
744
+ useLayoutEffect(() => {
745
+ runtime.setMotionProfile(motionProfile)
746
+ }, [runtime, motionProfile])
747
+
748
+ useEffect(() => {
749
+ store.sync(surfaceId, registry, messages, onAction, onDiagnostic)
750
+ }, [store, surfaceId, registry, messages, onAction, onDiagnostic])
751
+
752
+ useEffect(() => () => store.dispose(), [store])
753
+
754
+ useEffect(() => warnA2uiAccessibility(messages, registry), [messages, registry])
755
+
756
+ const rootNode = useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot)
757
+ const phase = useSyncExternalStore(store.subscribe, store.getPhase, store.getPhase)
758
+ const placeholders = useSyncExternalStore(
759
+ runtime.placeholders.subscribe,
760
+ runtime.placeholders.getSnapshot,
761
+ zeroPlaceholders
762
+ )
763
+ const waiting = !rootNode && phase !== 'closed'
764
+
765
+ return (
766
+ <div
767
+ ref={surfaceRef}
768
+ tabIndex={-1}
769
+ className={focusRingClass}
770
+ aria-busy={waiting || placeholders > 0 ? true : undefined}
771
+ data-slot="a2ui-surface"
772
+ data-surface-id={surfaceId}
773
+ >
774
+ {rootNode ? (
775
+ <A2uiNodeRenderer
776
+ node={rootNode}
777
+ registry={registry}
778
+ inline={false}
779
+ onDiagnostic={store.reportDiagnostic}
780
+ runtime={runtime}
781
+ />
782
+ ) : waiting ? (
783
+ <A2uiPlaceholder
784
+ inline={false}
785
+ tracker={runtime.placeholders}
786
+ />
787
+ ) : null}
788
+ </div>
789
+ )
790
+ }