react-native-roku 0.0.0-stage → 0.2.0-preview.1

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 (200) hide show
  1. package/CHANGELOG.md +318 -0
  2. package/CONTRIBUTING.md +34 -0
  3. package/LICENSE +21 -0
  4. package/NOTICE.md +10 -0
  5. package/README.md +66 -2
  6. package/bin/react-native-roku.mjs +91 -0
  7. package/build/assets.cjs +311 -0
  8. package/build/assets.d.cts +50 -0
  9. package/build/compatibility.d.mts +40 -0
  10. package/build/compatibility.mjs +272 -0
  11. package/build/dev.d.mts +34 -0
  12. package/build/dev.mjs +297 -0
  13. package/build/devWorkspace.d.mts +11 -0
  14. package/build/devWorkspace.mjs +86 -0
  15. package/build/device.d.mts +47 -0
  16. package/build/device.mjs +310 -0
  17. package/build/environment.d.mts +29 -0
  18. package/build/environment.mjs +144 -0
  19. package/build/esbuild.d.mts +5 -0
  20. package/build/esbuild.mjs +118 -0
  21. package/build/fontVariants.d.mts +27 -0
  22. package/build/fontVariants.mjs +424 -0
  23. package/build/frontend.d.mts +52 -0
  24. package/build/frontend.mjs +75 -0
  25. package/build/identity.mjs +45 -0
  26. package/build/index.d.mts +22 -0
  27. package/build/index.mjs +87 -0
  28. package/build/intl.mjs +121 -0
  29. package/build/metro.cjs +38 -0
  30. package/build/metro.d.cts +37 -0
  31. package/build/metroFrontend.mjs +222 -0
  32. package/build/metroMetadata.mjs +119 -0
  33. package/build/metroModules.mjs +397 -0
  34. package/build/metroRefresh.d.mts +64 -0
  35. package/build/metroRefresh.mjs +346 -0
  36. package/build/metroTransformer.cjs +146 -0
  37. package/build/nativeTextMemo.mjs +296 -0
  38. package/build/nativewind.d.mts +9 -0
  39. package/build/nativewind.mjs +92 -0
  40. package/build/project.d.mts +111 -0
  41. package/build/project.mjs +615 -0
  42. package/build/reactCompiler.mjs +113 -0
  43. package/build/reactProfile.cjs +35 -0
  44. package/build/refreshRuntime.mjs +187 -0
  45. package/build/refreshSourceMap.mjs +53 -0
  46. package/build/release.mjs +99 -0
  47. package/build/resolution.d.mts +3 -0
  48. package/build/resolution.mjs +25 -0
  49. package/build/surfaces.d.mts +1 -0
  50. package/build/surfaces.mjs +42 -0
  51. package/build/testing/node.d.mts +29 -0
  52. package/build/testing/node.mjs +106 -0
  53. package/build/yoga.d.mts +8 -0
  54. package/build/yoga.mjs +186 -0
  55. package/compatibility/public-api.json +327 -0
  56. package/compatibility/registry.json +2258 -0
  57. package/config/release.json +15 -0
  58. package/config/toolchain.json +34 -0
  59. package/docs/compatibility.md +813 -0
  60. package/docs/getting-started.md +460 -0
  61. package/docs/maintenance.md +362 -0
  62. package/docs/qualification.md +241 -0
  63. package/docs/standalone-testing.md +56 -0
  64. package/examples/hello-roku/README.md +35 -0
  65. package/examples/hello-roku/package.template.json +31 -0
  66. package/examples/hello-roku/pnpm-workspace.yaml +11 -0
  67. package/examples/hello-roku/roku.config.json +22 -0
  68. package/examples/hello-roku/src/App.tsx +54 -0
  69. package/examples/hello-roku/src/Catalog.tsx +200 -0
  70. package/examples/hello-roku/src/assets.d.ts +16 -0
  71. package/examples/hello-roku/src/catalog-cover.png +0 -0
  72. package/examples/hello-roku/tsconfig.json +1 -0
  73. package/examples/hello-roku/tsconfig.react.json +1 -0
  74. package/native/components/RNRAppControl.brs +215 -0
  75. package/native/components/RNRAppControl.xml +13 -0
  76. package/native/components/RNRDeviceFacts.brs +19 -0
  77. package/native/components/RNRDeviceFacts.xml +9 -0
  78. package/native/components/RNRDeviceFactsTask.brs +74 -0
  79. package/native/components/RNRDeviceFactsTask.xml +9 -0
  80. package/native/components/RNRTextRaster.brs +15 -0
  81. package/native/components/RNRTextRaster.xml +9 -0
  82. package/native/components/RNRTextRasterTask.brs +77 -0
  83. package/native/components/RNRTextRasterTask.xml +9 -0
  84. package/native/manifest.json +7 -0
  85. package/package.json +183 -3
  86. package/src/animation/clock.ts +10 -0
  87. package/src/animation/derivedValue.ts +163 -0
  88. package/src/animation/legacyAnimated.ts +255 -0
  89. package/src/animation/reanimated.ts +243 -0
  90. package/src/animation/sharedValue.ts +285 -0
  91. package/src/animation/worklets.ts +23 -0
  92. package/src/application/AppRegistry.ts +31 -0
  93. package/src/application/mountApplication.ts +136 -0
  94. package/src/graphics/BitmapLayer.tsx +68 -0
  95. package/src/graphics/RoundedBorder.tsx +116 -0
  96. package/src/graphics/TextRasterCache.ts +259 -0
  97. package/src/graphics/gradient.ts +37 -0
  98. package/src/graphics/inlineRaster.ts +85 -0
  99. package/src/graphics/png.ts +77 -0
  100. package/src/graphics/rasterPixels.ts +89 -0
  101. package/src/graphics/surfaces.ts +105 -0
  102. package/src/graphics/textRaster.types.ts +60 -0
  103. package/src/graphics/textRasterGeometry.ts +116 -0
  104. package/src/host/host.types.ts +57 -0
  105. package/src/index.ts +22 -0
  106. package/src/interop/nativewind.ts +2 -0
  107. package/src/layout/FontResources.ts +252 -0
  108. package/src/layout/affine.ts +89 -0
  109. package/src/layout/flexLayout.ts +398 -0
  110. package/src/layout/fontFaces.d.mts +19 -0
  111. package/src/layout/fontFaces.mjs +85 -0
  112. package/src/layout/fontVariants.d.mts +2 -0
  113. package/src/layout/fontVariants.mjs +8 -0
  114. package/src/layout/inlineParagraph.ts +158 -0
  115. package/src/layout/inlineText.ts +68 -0
  116. package/src/layout/layoutReuse.ts +117 -0
  117. package/src/layout/nativeNodeFields.ts +179 -0
  118. package/src/layout/preparedFields.ts +78 -0
  119. package/src/layout/textLayout.ts +138 -0
  120. package/src/layout/transform.ts +113 -0
  121. package/src/media/SceneGraphAudio.ts +161 -0
  122. package/src/media/SceneGraphVideo.ts +167 -0
  123. package/src/media/audioSession.ts +84 -0
  124. package/src/media/index.ts +2 -0
  125. package/src/media/videoErrorDetails.ts +40 -0
  126. package/src/media/videoSession.ts +136 -0
  127. package/src/navigation/RouterStore.ts +244 -0
  128. package/src/navigation/expoRouter.ts +115 -0
  129. package/src/react-native/NativeInput.ts +494 -0
  130. package/src/react-native/NativeSystemState.ts +95 -0
  131. package/src/react-native/accessibility.ts +265 -0
  132. package/src/react-native/activityIndicator.ts +72 -0
  133. package/src/react-native/compilerPressable.ts +26 -0
  134. package/src/react-native/createNativeRoot.ts +2126 -0
  135. package/src/react-native/directionalFocus.ts +55 -0
  136. package/src/react-native/environment.ts +275 -0
  137. package/src/react-native/flatList.ts +1001 -0
  138. package/src/react-native/flatListViewability.ts +231 -0
  139. package/src/react-native/focusEvents.ts +85 -0
  140. package/src/react-native/image.ts +247 -0
  141. package/src/react-native/index.ts +54 -0
  142. package/src/react-native/interactionManager.ts +76 -0
  143. package/src/react-native/keyboard.ts +60 -0
  144. package/src/react-native/linearGradient.ts +94 -0
  145. package/src/react-native/modal.tsx +148 -0
  146. package/src/react-native/nativeHostContext.ts +80 -0
  147. package/src/react-native/nativeModules.ts +86 -0
  148. package/src/react-native/nativeRoot.types.ts +22 -0
  149. package/src/react-native/nativeViewHandle.ts +191 -0
  150. package/src/react-native/nativewindPressable.ts +38 -0
  151. package/src/react-native/panResponder.ts +73 -0
  152. package/src/react-native/primitives.ts +685 -0
  153. package/src/react-native/safeArea.ts +76 -0
  154. package/src/react-native/scrollView.ts +289 -0
  155. package/src/react-native/styleInterop.ts +8 -0
  156. package/src/react-native/styleSheet.ts +54 -0
  157. package/src/react-native/textInput.ts +334 -0
  158. package/src/react-native/unsupported.ts +25 -0
  159. package/src/renderer/SceneRoot.ts +1006 -0
  160. package/src/scene/SdkDeviceFacts.ts +151 -0
  161. package/src/scene/SdkDeviceServices.ts +72 -0
  162. package/src/scene/SdkSceneGraph.ts +124 -0
  163. package/src/scene/SdkTextEntry.ts +321 -0
  164. package/src/scene/SdkTextMetrics.ts +136 -0
  165. package/src/scene/SdkTextRasterTransport.ts +191 -0
  166. package/src/scene/SdkWebTransport.ts +122 -0
  167. package/src/scene/createRokuHost.ts +213 -0
  168. package/src/scene/sceneGraph.types.ts +38 -0
  169. package/src/services/DeviceServices.ts +53 -0
  170. package/src/services/RegistryStorage.ts +85 -0
  171. package/src/services/RokuKeySession.ts +29 -0
  172. package/src/services/asyncStorage.ts +23 -0
  173. package/src/services/base64.ts +52 -0
  174. package/src/services/crypto.ts +18 -0
  175. package/src/services/expoConstants.ts +11 -0
  176. package/src/services/expoLinking.ts +12 -0
  177. package/src/services/expoStatusBar.ts +4 -0
  178. package/src/services/installWebRuntime.ts +105 -0
  179. package/src/services/intlEnglish.ts +54 -0
  180. package/src/services/languageRuntime.ts +65 -0
  181. package/src/services/nativeTimers.ts +96 -0
  182. package/src/services/secureStore.ts +23 -0
  183. package/src/services/textEntryRequest.ts +22 -0
  184. package/src/services/utf8.ts +57 -0
  185. package/src/services/webRuntime.ts +346 -0
  186. package/src/testing/CanvasResources.ts +141 -0
  187. package/src/testing/CanvasSceneGraph.ts +496 -0
  188. package/src/testing/CanvasTextEntry.ts +237 -0
  189. package/src/testing/PreviewTextObservations.ts +82 -0
  190. package/src/testing/RecordingSceneGraph.ts +136 -0
  191. package/src/types/normalize-colors.d.ts +4 -0
  192. package/src/vector/dynamicSvg.tsx +226 -0
  193. package/src/vector/svg.ts +222 -0
  194. package/src/vector/svg.types.ts +4 -0
  195. package/src/vector/svgElements.ts +58 -0
  196. package/src/vector/svgKey.d.mts +4 -0
  197. package/src/vector/svgKey.mjs +16 -0
  198. package/src/vector/svgPath.ts +157 -0
  199. package/src/vector/svgPixels.ts +133 -0
  200. package/tsconfig.consumer.json +29 -0
@@ -0,0 +1,2126 @@
1
+ import { createElement, type ReactNode } from "react";
2
+ import {
3
+ calculateFlexLayout,
4
+ type LayoutInput,
5
+ type LayoutRect,
6
+ type LayoutStyle,
7
+ type TextMeasure,
8
+ } from "../layout/flexLayout";
9
+ import {
10
+ labelText,
11
+ nativeInlineTextLines,
12
+ nativeNodeFields,
13
+ type MeasuredLabel,
14
+ } from "../layout/nativeNodeFields";
15
+ import { PreparedFieldCache } from "../layout/preparedFields";
16
+ import { layoutText, type RetainedFontMetrics } from "../layout/textLayout";
17
+ import {
18
+ captureLayoutStyle,
19
+ hasOnlyBuiltinObjectPrototypeFields,
20
+ sameLayoutStyle,
21
+ type LayoutStyleSnapshot,
22
+ } from "../layout/layoutReuse";
23
+ import {
24
+ createPreparedSceneRoot,
25
+ hasGeneratedSceneFields,
26
+ reuseSceneGeometry,
27
+ tryUpdateCommittedOpacity,
28
+ trySubmitFocusPresentation,
29
+ type FocusPresentationWrite,
30
+ type SceneRoot,
31
+ type SceneTreeElement,
32
+ plainBackgroundLayout,
33
+ plainImageLayout,
34
+ } from "../renderer/SceneRoot";
35
+ import {
36
+ RokuHostError,
37
+ type SceneFields,
38
+ type SceneGraphPort,
39
+ type SceneNodeRef,
40
+ type SceneValue,
41
+ } from "../scene/sceneGraph.types";
42
+ import {
43
+ NativeHostContext,
44
+ type NativeHostContextValue,
45
+ type FocusPresentation,
46
+ type NativePlacement,
47
+ } from "./nativeHostContext";
48
+ import { bindNativeEnvironment } from "./environment";
49
+ import { roundedMask, surfaceRadii } from "../graphics/surfaces";
50
+ import { gradientFields, type GradientSpec } from "../graphics/gradient";
51
+ import type { TextRasterLease } from "../graphics/textRaster.types";
52
+ import { inlineTextRuns, measureInlineText } from "../layout/inlineText";
53
+ import { layoutInlineParagraph } from "../layout/inlineParagraph";
54
+ import { affineBounds, identityAffine, sceneWorld, type Affine } from "../layout/affine";
55
+ import { flattenStyle, rokuColor, type NativeStyle } from "./styleSheet";
56
+ import { directionalFocusTarget } from "./directionalFocus";
57
+
58
+ import type { NativeRootOptions } from "./nativeRoot.types";
59
+ import { dispatchNativeFocus } from "./focusEvents";
60
+ import { accessibilitySpeech, type AccessibilitySemantics } from "./accessibility";
61
+ export type { NativeRootOptions } from "./nativeRoot.types";
62
+
63
+ interface PlacementAncestor extends PlacementScroll {
64
+ parent?: SceneTreeElement;
65
+ pointerEvents: unknown;
66
+ importance: unknown;
67
+ accessibilityElementsHidden: unknown;
68
+ accessible: unknown;
69
+ }
70
+ interface PlacementScroll {
71
+ scrollX?: number;
72
+ scrollY?: number;
73
+ }
74
+ type PlacementParents = Map<SceneTreeElement, PlacementAncestor>;
75
+ interface PlacementWalk {
76
+ rectangles: ReadonlyMap<SceneTreeElement, LayoutRect>;
77
+ callbacks: readonly LayoutDelivery[];
78
+ fields: Map<SceneTreeElement, SceneFields>;
79
+ bases: Map<SceneTreeElement, SceneFields>;
80
+ parents: PlacementParents;
81
+ contentLabels: Map<SceneTreeElement, string>;
82
+ local?: {
83
+ bases: ReadonlyMap<SceneTreeElement, SceneFields>;
84
+ labels: ReadonlyMap<SceneTreeElement, string>;
85
+ visited: ReadonlySet<SceneTreeElement>;
86
+ scrollChanges?: ReadonlyMap<SceneTreeElement, PlacementScroll>;
87
+ };
88
+ retained?: RetainedPlacement;
89
+ }
90
+
91
+ type LayoutDependency = {
92
+ element: SceneTreeElement;
93
+ style: LayoutStyleSnapshot;
94
+ text?: string;
95
+ measured: boolean;
96
+ lines: unknown;
97
+ children: readonly SceneTreeElement[];
98
+ };
99
+
100
+ type LayoutDelivery = {
101
+ id: string;
102
+ rect: LayoutRect;
103
+ callback: (event: unknown) => void;
104
+ };
105
+
106
+ type IsolatedLabel = {
107
+ element: SceneTreeElement;
108
+ index: number;
109
+ rect: LayoutRect;
110
+ text: string;
111
+ measured: boolean;
112
+ };
113
+
114
+ function sameRect(a: LayoutRect | undefined, b: LayoutRect): boolean {
115
+ return a?.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height;
116
+ }
117
+
118
+ interface RetainedPlacement {
119
+ readLineHeight(font: SceneNodeRef): number;
120
+ text: RetainedFontMetrics;
121
+ fonts: ReadonlyMap<SceneNodeRef, number>;
122
+ }
123
+
124
+ const emptyStyle: LayoutStyle = {};
125
+ const fontStyleKeys = ["fontFamily", "fontSize", "fontStyle", "fontWeight", "fontVariant"] as const;
126
+
127
+ function fixedLabel(dependency: LayoutDependency, style: LayoutStyle, committed?: LayoutRect) {
128
+ return (
129
+ dependency.element.type === "label" &&
130
+ dependency.text !== undefined &&
131
+ !dependency.measured &&
132
+ typeof style.height === "number" &&
133
+ style.height > 0 &&
134
+ ((typeof style.width === "number" &&
135
+ style.width > 0 &&
136
+ (!committed || Object.hasOwn(style, "width"))) ||
137
+ // A retained Yoga solve can constrain the width through flex stretch.
138
+ // No measure call means glyphs did not contribute to that geometry.
139
+ (style.width == null &&
140
+ !!committed &&
141
+ Object.hasOwn(style, "height") &&
142
+ committed.width > 0 &&
143
+ committed.height === Math.fround(style.height) &&
144
+ hasOnlyBuiltinObjectPrototypeFields()))
145
+ );
146
+ }
147
+
148
+ // A single child of a fixed absolute box can be laid out independently
149
+ // when the rest of the layout inputs haven't changed.
150
+ const isolatedBoxStyle = new Set([
151
+ "position",
152
+ "left",
153
+ "top",
154
+ "right",
155
+ "bottom",
156
+ "width",
157
+ "height",
158
+ "opacity",
159
+ "backgroundColor",
160
+ ]);
161
+
162
+ function isolatedBox(style: LayoutStyle, rect: LayoutRect | undefined): rect is LayoutRect {
163
+ return (
164
+ !!rect &&
165
+ style.position === "absolute" &&
166
+ typeof style.width === "number" &&
167
+ typeof style.height === "number" &&
168
+ Math.fround(style.width) === rect.width &&
169
+ Math.fround(style.height) === rect.height &&
170
+ rect.width > 0 &&
171
+ rect.height > 0 &&
172
+ Object.getOwnPropertyNames(style).every((key) => isolatedBoxStyle.has(key))
173
+ );
174
+ }
175
+
176
+ const fixedScrollBoxSpacing =
177
+ /^(?:margin|padding)(?:Left|Top|Right|Bottom|Start|End|Horizontal|Vertical)?$/;
178
+
179
+ function fixedScrollBox(input: LayoutInput, rect: LayoutRect): boolean {
180
+ const { style, children } = input;
181
+ return (
182
+ input.text === undefined &&
183
+ children.length > 0 &&
184
+ children.every((child) => child.children.length === 0) &&
185
+ typeof style.width === "number" &&
186
+ typeof style.height === "number" &&
187
+ rect.width > 0 &&
188
+ rect.height > 0 &&
189
+ Math.fround(style.width) === rect.width &&
190
+ Math.fround(style.height) === rect.height &&
191
+ Object.getOwnPropertyNames(style).every((key) => {
192
+ if (key === "width" || key === "height" || key === "opacity" || key === "backgroundColor")
193
+ return true;
194
+ const value = style[key];
195
+ return typeof value === "number" && Number.isFinite(value) && fixedScrollBoxSpacing.test(key);
196
+ })
197
+ );
198
+ }
199
+
200
+ const fixedWidthTextStyle = new Set([
201
+ "width",
202
+ "color",
203
+ "fontFamily",
204
+ "fontSize",
205
+ "fontStyle",
206
+ "fontWeight",
207
+ "fontVariant",
208
+ "lineHeight",
209
+ "letterSpacing",
210
+ "opacity",
211
+ "textAlign",
212
+ "textTransform",
213
+ ]);
214
+
215
+ function intrinsicLabelRect(
216
+ input: LayoutInput,
217
+ before: LayoutRect,
218
+ measure: TextMeasure,
219
+ ): LayoutRect | undefined {
220
+ // A single fixed-width label in a default column has no flex, alignment,
221
+ // padding or margin constraints. Its auto height is its measured height.
222
+ const { width } = input.style;
223
+ if (
224
+ typeof width !== "number" ||
225
+ !Object.hasOwn(input.style, "width") ||
226
+ before.x !== 0 ||
227
+ before.y !== 0 ||
228
+ before.width <= 0 ||
229
+ Math.fround(width) !== before.width ||
230
+ !Object.getOwnPropertyNames(input.style).every((key) => fixedWidthTextStyle.has(key))
231
+ )
232
+ return undefined;
233
+ const text = measure(input, before.width, undefined);
234
+ const height = Math.fround(text.height);
235
+ if (!Number.isFinite(text.width) || text.width < 0 || !Number.isFinite(height)) return undefined;
236
+ return { ...before, height };
237
+ }
238
+
239
+ function retainPlacementInputs(
240
+ dependencies: readonly LayoutDependency[],
241
+ bases: ReadonlyMap<SceneTreeElement, SceneFields>,
242
+ preparedFields: PreparedFieldCache,
243
+ text: RetainedFontMetrics,
244
+ ): RetainedPlacement | undefined {
245
+ const readLineHeight = text.readRetainedFontLineHeight;
246
+ if (!readLineHeight) return undefined;
247
+ const fonts = new Map<SceneNodeRef, number>();
248
+ for (const dependency of dependencies) {
249
+ const { element } = dependency;
250
+ const prepared = preparedFields.retained(element, bases.get(element));
251
+ if (!prepared) return undefined;
252
+ if (element.type !== "label") continue;
253
+ const { font, lineHeight } = prepared;
254
+ // Coercions and variant collections stay on the ordinary font resolution path.
255
+ if (
256
+ !font ||
257
+ lineHeight === undefined ||
258
+ fontStyleKeys.some((key) => {
259
+ const value = dependency.style.values[key];
260
+ return value != null && typeof value !== "string" && typeof value !== "number";
261
+ })
262
+ )
263
+ return undefined;
264
+ fonts.set(font, lineHeight);
265
+ }
266
+ return { readLineHeight: readLineHeight.bind(text), text, fonts };
267
+ }
268
+
269
+ function hasLocalPlacement(node: SceneTreeElement): boolean {
270
+ if (!hasGeneratedSceneFields(node)) return false;
271
+ const layout = node.props.layout;
272
+ if (node.type === "rectangle") return layout === plainBackgroundLayout;
273
+ if (node.type === "poster") return layout === plainImageLayout;
274
+ if (
275
+ typeof layout?.id !== "string" ||
276
+ layout.resource ||
277
+ layout.decoration ||
278
+ layout.paintWrapper ||
279
+ layout.textRaster ||
280
+ layout.maskReadiness != null
281
+ )
282
+ return false;
283
+ const semantics = layout.accessibility as AccessibilitySemantics | undefined;
284
+ return (
285
+ !semantics ||
286
+ (!semantics.modal && !semantics.labelledBy.length && !semantics.describedBy.length)
287
+ );
288
+ }
289
+
290
+ function indexPlacementParents(
291
+ fields: ReadonlyMap<SceneTreeElement, SceneFields>,
292
+ readyFonts: boolean,
293
+ ): PlacementParents | undefined {
294
+ const parents = new Map<SceneTreeElement, PlacementAncestor>();
295
+ const record = (node: SceneTreeElement, parent?: SceneTreeElement): PlacementAncestor => ({
296
+ parent,
297
+ pointerEvents: node.props.layout?.pointerEvents,
298
+ importance: node.props.layout?.importantForAccessibility,
299
+ accessibilityElementsHidden: node.props.layout?.accessibilityElementsHidden,
300
+ accessible: node.props.layout?.accessible,
301
+ scrollX: (node.props.layout?.scrollTranslation as readonly number[] | undefined)?.[0],
302
+ scrollY: (node.props.layout?.scrollTranslation as readonly number[] | undefined)?.[1],
303
+ });
304
+ for (const node of fields.keys()) {
305
+ if (!hasLocalPlacement(node) || (node.type === "label" && !readyFonts)) return undefined;
306
+ if (!parents.has(node)) parents.set(node, record(node));
307
+ for (const child of node.children)
308
+ if (child.kind === "element" && fields.has(child)) parents.set(child, record(child, node));
309
+ }
310
+ return parents;
311
+ }
312
+
313
+ export function createNativeRoot(port: SceneGraphPort, options: NativeRootOptions): SceneRoot {
314
+ const preparedFields = new PreparedFieldCache();
315
+ let layoutCache:
316
+ | {
317
+ dependencies: LayoutDependency[];
318
+ rectangles: Map<SceneTreeElement, LayoutRect>;
319
+ width: number;
320
+ height: number;
321
+ }
322
+ | undefined;
323
+ const inlineLines = new WeakMap<SceneTreeElement, readonly SceneFields[]>();
324
+ let placements = new Map<string, NativePlacement>();
325
+ let committedWalk: PlacementWalk | undefined;
326
+ const placementWalks = new WeakMap<readonly SceneTreeElement[], PlacementWalk>();
327
+ let retired = false,
328
+ publication = 0;
329
+ const pendingCleanup = new Set<() => void>();
330
+ let unmounting = false;
331
+ let focusRequest = 0;
332
+ let admittedFocusRequest = 0;
333
+ let lastFocusSpeech: { id: string; handle: NativePlacement["handle"]; text: string } | undefined;
334
+ const liveSpeech = new Map<string, { handle: NativePlacement["handle"]; text: string }>();
335
+ const speak = (id: string, queue = false) => {
336
+ const placement = placements.get(id);
337
+ if (
338
+ retired ||
339
+ !systemAllowsInput() ||
340
+ !placement ||
341
+ placement.accessibilityHidden ||
342
+ options.system?.getSnapshot().screenReader !== true
343
+ )
344
+ return;
345
+ const message = placement.accessibility
346
+ ? accessibilitySpeech(placement.accessibility, placement.accessibilityLabel)
347
+ : (placement.accessibilityLabel ?? "");
348
+ if (!message) return;
349
+ const previous = queue
350
+ ? liveSpeech.get(id)
351
+ : lastFocusSpeech?.id === id
352
+ ? lastFocusSpeech
353
+ : undefined;
354
+ if (previous?.handle === placement.handle && previous.text === message) return;
355
+ options.system.announceForAccessibility(message, { queue });
356
+ if (queue) liveSpeech.set(id, { handle: placement.handle, text: message });
357
+ else lastFocusSpeech = { id, handle: placement.handle, text: message };
358
+ };
359
+ const focusOverrides = new Map<
360
+ string,
361
+ Partial<Record<"up" | "right" | "down" | "left", number | null>>
362
+ >();
363
+ const opacityOverrides = new Map<
364
+ string,
365
+ { value: number; baseline: unknown; initialized: boolean }
366
+ >();
367
+ const dimensionOverrides = new Map<
368
+ string,
369
+ {
370
+ values: Partial<Record<"width" | "height", number>>;
371
+ baseline: LayoutStyle;
372
+ initialized: boolean;
373
+ }
374
+ >();
375
+ type Presentation = {
376
+ pointerEvents?: string;
377
+ importantForAccessibility?: string;
378
+ accessibilityElementsHidden?: boolean;
379
+ };
380
+ const presentationOverrides = new Map<
381
+ string,
382
+ { values: Presentation; baseline: Presentation; initialized: boolean }
383
+ >();
384
+ const declarativePresentation = new Map<string, Presentation>();
385
+ const declarativeStyles = new Map<string, LayoutStyle>();
386
+ let placedTags = new Map<number, string>();
387
+ let layoutDelivery: Promise<void> = Promise.resolve();
388
+ const deliveredLayouts = new Map<string, NativePlacement>();
389
+ let rasterGeneration = 0;
390
+ let committedRasterGeneration = 0;
391
+ let committedRasters = new Set<TextRasterLease>(),
392
+ preparingRasters = new Set<TextRasterLease>();
393
+ const rasterLeases = new WeakMap<readonly SceneTreeElement[], Set<TextRasterLease>>();
394
+ async function whenNativeCommitted(): Promise<void> {
395
+ let delivery: Promise<void>;
396
+ do {
397
+ await root.whenCommitted();
398
+ delivery = layoutDelivery;
399
+ await delivery;
400
+ await root.whenCommitted();
401
+ } while (delivery !== layoutDelivery);
402
+ }
403
+ const pending = new WeakMap<
404
+ readonly SceneTreeElement[],
405
+ { entries: Map<string, NativePlacement>; local: boolean; isolated?: IsolatedLabel }
406
+ >();
407
+ const deliveries = new WeakMap<readonly SceneTreeElement[], LayoutDelivery[]>();
408
+ const systemAllowsInput = () => {
409
+ const state = options.system?.getSnapshot().appState;
410
+ return state !== "background" && state !== "inactive";
411
+ };
412
+ const mediaCommand = (
413
+ kind: "video" | "audio",
414
+ id: string,
415
+ fields: Readonly<Record<string, string | number | boolean>>,
416
+ ) => {
417
+ const code = kind === "video" ? "C30_VIDEO" : "C31_AUDIO";
418
+ const ref = placements.get(id)?.handle.nativeRef;
419
+ if (retired || !ref || ref.type !== kind)
420
+ throw new RokuHostError(`${code}_RETIRED`, `The ${kind} surface is not mounted`);
421
+ for (const [field, value] of Object.entries(fields)) {
422
+ if (
423
+ field === "control" &&
424
+ ["play", "prebuffer", "pause", "resume", "stop"].includes(String(value))
425
+ )
426
+ continue;
427
+ if (field === "seek" && typeof value === "number" && Number.isFinite(value) && value >= 0)
428
+ continue;
429
+ if (field === "mute" && typeof value === "boolean") continue;
430
+ if (kind === "audio" && field === "autoplayAfterSeek" && typeof value === "boolean") continue;
431
+ throw new RokuHostError(`${code}_COMMAND`, `Unsupported ${kind} command ${field}`);
432
+ }
433
+ port.batch(() => {
434
+ for (const [field, value] of Object.entries(fields)) port.set(ref, field, value);
435
+ });
436
+ };
437
+ const submitDirectionalPresentation = (id: string): boolean => {
438
+ const planPublication = publication;
439
+ const source = options.input?.focusedID;
440
+ const old = source ? placements.get(source)?.node : undefined;
441
+ const next = placements.get(id)?.node;
442
+ const from = old?.props.layout?.focusPresentation as FocusPresentation | undefined;
443
+ const to = next?.props.layout?.focusPresentation as FocusPresentation | undefined;
444
+ if (
445
+ !old ||
446
+ !next ||
447
+ !from ||
448
+ !to ||
449
+ !committedWalk?.retained ||
450
+ !layoutCache ||
451
+ rasterGeneration !== committedRasterGeneration ||
452
+ opacityOverrides.size ||
453
+ dimensionOverrides.size ||
454
+ presentationOverrides.size
455
+ )
456
+ return false;
457
+ const background = (node: SceneTreeElement) =>
458
+ node.children.find(
459
+ (child): child is SceneTreeElement =>
460
+ child.kind === "element" && child.props.layout === plainBackgroundLayout,
461
+ );
462
+ const oldPaint = background(old),
463
+ nextPaint = background(next);
464
+ if (
465
+ !oldPaint ||
466
+ !nextPaint ||
467
+ oldPaint.hidden ||
468
+ nextPaint.hidden ||
469
+ !hasGeneratedSceneFields(oldPaint) ||
470
+ !hasGeneratedSceneFields(nextPaint)
471
+ )
472
+ return false;
473
+ const oldColor = rokuColor(from.restingColor),
474
+ nextColor = rokuColor(to.focusedColor);
475
+ if (
476
+ oldPaint.props.fields?.color !== rokuColor(from.focusedColor) ||
477
+ nextPaint.props.fields?.color !== rokuColor(to.restingColor)
478
+ )
479
+ return false;
480
+ const writes: FocusPresentationWrite[] = [
481
+ { node: oldPaint, fields: { color: oldColor } },
482
+ { node: nextPaint, fields: { color: nextColor } },
483
+ ];
484
+ if (to.label) {
485
+ const placement = placements.get(to.label.nativeID);
486
+ const label = placement?.node;
487
+ const dependency = layoutCache.dependencies.find(({ element }) => element === label);
488
+ const style = (label?.props.layout?.style ?? emptyStyle) as LayoutStyle;
489
+ if (
490
+ !label ||
491
+ !placement ||
492
+ placement.visible === false ||
493
+ placement.modalBlocked ||
494
+ !dependency ||
495
+ !fixedLabel(dependency, style) ||
496
+ !sameLayoutStyle(style, dependency.style, false) ||
497
+ !Object.is(label.props.layout?.numberOfLines, dependency.lines)
498
+ )
499
+ return false;
500
+ const prepared = preparedFields.retained(label, committedWalk.bases.get(label));
501
+ if (!prepared?.font || options.text.preparedFieldFont?.(style) !== prepared.font)
502
+ return false;
503
+ const metrics = options.text.metrics(style);
504
+ if (!Object.is(metrics.lineHeight, prepared.lineHeight)) return false;
505
+ const planned = layoutText(
506
+ to.label.text,
507
+ style,
508
+ metrics,
509
+ placement.local.width,
510
+ Number(dependency.lines ?? 0),
511
+ );
512
+ writes.push({ node: label, fields: { text: planned.text, numLines: planned.lines.length } });
513
+ }
514
+ return publication === planPublication && trySubmitFocusPresentation(root, next, writes);
515
+ };
516
+ const host: NativeHostContextValue = {
517
+ get active() {
518
+ return !retired;
519
+ },
520
+ input: options.input,
521
+ svgAtlas: options.svgAtlas,
522
+ graphics: options.graphics,
523
+ raster: options.textRaster,
524
+ textEntry: options.textEntry ?? options.services?.textEntry,
525
+ portal: (element, key) => root.portal(element, key),
526
+ viewport: options.viewport,
527
+ placement: (id) => placements.get(id),
528
+ whenCommitted: whenNativeCommitted,
529
+ runSync: (work) => root.runSync(work),
530
+ cancelInput() {
531
+ admittedFocusRequest = ++focusRequest;
532
+ options.input?.cancelPendingInput();
533
+ },
534
+ dispatchFocus: (id, focused) => {
535
+ if (!focused && lastFocusSpeech?.id === id) lastFocusSpeech = undefined;
536
+ dispatchNativeFocus(placements, id, focused, () => !retired);
537
+ },
538
+ requestFocus(id, view, isCurrent, origin) {
539
+ if (retired || !systemAllowsInput()) return;
540
+ const generation = ++focusRequest;
541
+ const eligible = () => {
542
+ const placement = placements.get(id);
543
+ return !retired &&
544
+ generation >= admittedFocusRequest &&
545
+ systemAllowsInput() &&
546
+ isCurrent?.() !== false &&
547
+ (!view || placement?.view === view) &&
548
+ placement?.modalBlocked !== true &&
549
+ placement?.visible !== false &&
550
+ placement?.focusable !== false
551
+ ? placement?.handle.nativeRef
552
+ : undefined;
553
+ };
554
+ const submit = () => {
555
+ const ref = eligible();
556
+ if (!ref) return;
557
+ // Refused attempts cannot cancel a held press or supersede an admitted
558
+ // request. Fence input only when a native command can actually be sent.
559
+ admittedFocusRequest = generation;
560
+ options.input?.requestFocus(id, origin, (from, confirm) => {
561
+ const previous = from ? placements.get(from)?.handle.nativeRef : undefined;
562
+ if (eligible() !== ref) return;
563
+ port.sampleFocus?.(previous && previous !== ref ? [ref, previous] : [ref], (observed) => {
564
+ if (eligible() !== ref) return;
565
+ const observedID = observed === ref ? id : from;
566
+ if (
567
+ observedID &&
568
+ placements.get(observedID)?.handle.nativeRef === observed &&
569
+ options.input?.isTargetEnabled(observedID)
570
+ )
571
+ confirm(observedID);
572
+ });
573
+ });
574
+ // Input cancellation callbacks may retire this root or request focus again.
575
+ if (generation !== admittedFocusRequest || eligible() !== ref) return;
576
+ // Only a device observation may acknowledge focus ownership.
577
+ if (origin !== "directional" || !submitDirectionalPresentation(id))
578
+ port.batch(() => port.set(ref, "gainFocus", true));
579
+ };
580
+ if (eligible() && rasterGeneration === committedRasterGeneration) submit();
581
+ else {
582
+ // Layout effects can still see the previous native eligibility. Recheck
583
+ // after attachment, modal dismissal and asynchronous text preparation.
584
+ void whenNativeCommitted().then(submit, () => undefined);
585
+ }
586
+ },
587
+ announceFocus(id) {
588
+ speak(id);
589
+ },
590
+ setNativeProps(id, props) {
591
+ const next = { ...focusOverrides.get(id) };
592
+ let opacity: number | undefined;
593
+ let opacityOnly = true;
594
+ const dimensions: Partial<Record<"width" | "height", number>> = {};
595
+ const prior = presentationOverrides.get(id);
596
+ const presentation = { ...prior?.values };
597
+ const baseline = { ...prior?.baseline };
598
+ for (const [key, value] of Object.entries(props)) {
599
+ if (key !== "style") opacityOnly = false;
600
+ if (key === "accessibilityElementsHidden") {
601
+ if (typeof value !== "boolean")
602
+ throw new RokuHostError("C03_ACCESSIBILITY", "Invalid accessibility exposure");
603
+ presentation.accessibilityElementsHidden = value;
604
+ baseline.accessibilityElementsHidden =
605
+ declarativePresentation.get(id)?.accessibilityElementsHidden;
606
+ continue;
607
+ }
608
+ if (key === "pointerEvents") {
609
+ if (!["auto", "none", "box-none", "box-only"].includes(String(value)))
610
+ throw new RokuHostError("C03_POINTER_EVENTS", "Invalid imperative pointer exposure");
611
+ presentation.pointerEvents = String(value);
612
+ baseline.pointerEvents = declarativePresentation.get(id)?.pointerEvents;
613
+ continue;
614
+ }
615
+ if (key === "importantForAccessibility") {
616
+ if (!["auto", "yes", "no", "no-hide-descendants"].includes(String(value)))
617
+ throw new RokuHostError("C03_ACCESSIBILITY", "Invalid accessibility exposure");
618
+ presentation.importantForAccessibility = String(value);
619
+ baseline.importantForAccessibility =
620
+ declarativePresentation.get(id)?.importantForAccessibility;
621
+ continue;
622
+ }
623
+ if (key === "style") {
624
+ for (const [name, field] of Object.entries(flattenStyle(value as NativeStyle) ?? {})) {
625
+ if (name !== "opacity") opacityOnly = false;
626
+ if (
627
+ name === "opacity" &&
628
+ typeof field === "number" &&
629
+ Number.isFinite(field) &&
630
+ field >= 0 &&
631
+ field <= 1
632
+ )
633
+ opacity = field;
634
+ else if (
635
+ (name === "width" || name === "height") &&
636
+ typeof field === "number" &&
637
+ Number.isFinite(field) &&
638
+ field >= 0
639
+ )
640
+ dimensions[name] = field;
641
+ else if (
642
+ name === "pointerEvents" &&
643
+ ["auto", "none", "box-none", "box-only"].includes(String(field))
644
+ ) {
645
+ presentation.pointerEvents = String(field);
646
+ baseline.pointerEvents = declarativePresentation.get(id)?.pointerEvents;
647
+ } else
648
+ throw new RokuHostError(
649
+ "C03_IMPERATIVE_PROPS",
650
+ `Imperative style ${name} needs a renderer binding`,
651
+ );
652
+ }
653
+ continue;
654
+ }
655
+ const direction = {
656
+ nextFocusUp: "up",
657
+ nextFocusRight: "right",
658
+ nextFocusDown: "down",
659
+ nextFocusLeft: "left",
660
+ }[key] as "up" | "right" | "down" | "left" | undefined;
661
+ if (!direction)
662
+ throw new RokuHostError(
663
+ "C03_IMPERATIVE_PROPS",
664
+ `Imperative prop ${key} needs a renderer binding`,
665
+ );
666
+ if (
667
+ value !== null &&
668
+ (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0)
669
+ )
670
+ throw new RokuHostError(
671
+ "C07_FOCUS_TAG",
672
+ "Directional targets require a stable view tag or null",
673
+ );
674
+ next[direction] = value as number | null;
675
+ }
676
+ focusOverrides.set(id, next);
677
+ presentationOverrides.set(id, {
678
+ values: presentation,
679
+ baseline,
680
+ initialized: declarativePresentation.has(id),
681
+ });
682
+ if (Object.keys(dimensions).length) {
683
+ const previous = dimensionOverrides.get(id),
684
+ declared = declarativeStyles.get(id);
685
+ dimensionOverrides.set(id, {
686
+ values: { ...previous?.values, ...dimensions },
687
+ baseline: {
688
+ ...previous?.baseline,
689
+ ...Object.fromEntries(Object.keys(dimensions).map((name) => [name, declared?.[name]])),
690
+ },
691
+ initialized: !!declared,
692
+ });
693
+ }
694
+ if (opacity !== undefined)
695
+ opacityOverrides.set(id, {
696
+ value: opacity,
697
+ baseline: declarativeStyles.get(id)?.opacity,
698
+ initialized: declarativeStyles.has(id),
699
+ });
700
+ const placement = placements.get(id);
701
+ if (
702
+ opacityOnly &&
703
+ opacity !== undefined &&
704
+ placement &&
705
+ tryUpdateCommittedOpacity(root, placement.handle, opacity)
706
+ )
707
+ return;
708
+ const ref = placement?.handle.nativeRef;
709
+ if (ref && opacity !== undefined) port.batch(() => port.set(ref, "opacity", opacity));
710
+ if (
711
+ ref &&
712
+ (opacity !== undefined ||
713
+ Object.keys(presentation).length ||
714
+ Object.keys(dimensions).length)
715
+ )
716
+ root.refreshNative();
717
+ },
718
+ videoCommand(id, fields) {
719
+ mediaCommand("video", id, fields);
720
+ },
721
+ audioCommand(id, fields) {
722
+ mediaCommand("audio", id, fields);
723
+ },
724
+ };
725
+ const root = createPreparedSceneRoot(port, options.onError, {
726
+ strictMode: options.strictMode,
727
+ inlineTextLines: (node) => inlineLines.get(node) ?? [],
728
+ prepareFields(tree, reactCommit, changes) {
729
+ const generation = ++rasterGeneration;
730
+ for (const lease of preparingRasters) lease.release();
731
+ preparingRasters = new Set();
732
+ const retained = new Set<TextRasterLease>();
733
+ let preparationFailed = false;
734
+ const failPreparation = (error: unknown): never => {
735
+ preparationFailed = true;
736
+ for (const lease of retained) {
737
+ preparingRasters.delete(lease);
738
+ lease.release();
739
+ }
740
+ retained.clear();
741
+ throw error;
742
+ };
743
+ rasterLeases.set(tree, retained);
744
+ const canRetainPlacement = () =>
745
+ !opacityOverrides.size && !dimensionOverrides.size && !presentationOverrides.size;
746
+ const placementFor = (
747
+ rectangles: ReadonlyMap<SceneTreeElement, LayoutRect>,
748
+ scrollChanges?: Map<SceneTreeElement, PlacementScroll>,
749
+ ) => {
750
+ const previous = committedWalk;
751
+ if (
752
+ !previous ||
753
+ previous.rectangles !== rectangles ||
754
+ !changes ||
755
+ !canRetainPlacement() ||
756
+ previous.callbacks.some(
757
+ ({ id, rect }) => !sameRect(deliveredLayouts.get(id)?.local, rect),
758
+ )
759
+ )
760
+ return undefined;
761
+ for (const node of changes) {
762
+ const context = previous.parents.get(node);
763
+ const layout = node.props.layout;
764
+ const scroll = layout?.scrollTranslation as readonly number[] | undefined;
765
+ if (
766
+ !context ||
767
+ !hasLocalPlacement(node) ||
768
+ context.pointerEvents !== layout?.pointerEvents ||
769
+ context.importance !== layout?.importantForAccessibility ||
770
+ context.accessibilityElementsHidden !== layout?.accessibilityElementsHidden ||
771
+ context.accessible !== layout?.accessible
772
+ )
773
+ return undefined;
774
+ if (
775
+ !Object.is(context.scrollX, scroll?.[0]) ||
776
+ !Object.is(context.scrollY, scroll?.[1])
777
+ ) {
778
+ if (!scrollChanges) return undefined;
779
+ scrollChanges.set(node, { scrollX: scroll?.[0], scrollY: scroll?.[1] });
780
+ }
781
+ const id = layout?.id;
782
+ if (typeof id === "string" && placements.get(id)?.handle !== node.handle)
783
+ return undefined;
784
+ }
785
+ return previous;
786
+ };
787
+ const retainedLayout = () => {
788
+ const settledLayout = layoutCache;
789
+ if (
790
+ !reactCommit ||
791
+ !changes ||
792
+ !settledLayout ||
793
+ settledLayout.width !== options.viewport.width ||
794
+ settledLayout.height !== options.viewport.height ||
795
+ fontStyleKeys.some((key) => Object.hasOwn(Object.prototype, key))
796
+ )
797
+ return undefined;
798
+ const scrollChanges = new Map<SceneTreeElement, PlacementScroll>();
799
+ const placement = placementFor(settledLayout.rectangles, scrollChanges);
800
+ const retained = placement?.retained;
801
+ if (!placement || !retained || retained.text !== options.text) return undefined;
802
+ const changedBases = new Set<SceneTreeElement>();
803
+ let textChange:
804
+ | { index: number; element: SceneTreeElement; input: LayoutInput & { text: string } }
805
+ | undefined;
806
+ for (const [index, dependency] of settledLayout.dependencies.entries()) {
807
+ const { element } = dependency;
808
+ const authored = element.props.layout;
809
+ const style = (authored?.style ?? emptyStyle) as LayoutStyle;
810
+ if (
811
+ !Object.is(authored?.numberOfLines, dependency.lines) ||
812
+ !sameLayoutStyle(style, dependency.style, element.type === "group")
813
+ )
814
+ return undefined;
815
+ const base = placement.bases.get(element);
816
+ const opacity = typeof style.opacity === "number" ? style.opacity : undefined;
817
+ if (!Object.is(opacity, base?.opacity)) changedBases.add(element);
818
+ if (element.type !== "label" || !changes.has(element)) continue;
819
+ const text = labelText(element);
820
+ if (text === preparedFields.retained(element, base)?.content) continue;
821
+ changedBases.add(element);
822
+ if (!fixedLabel(dependency, style, settledLayout.rectangles.get(element))) {
823
+ if (textChange) return undefined;
824
+ textChange = { index, element, input: { text, style, children: [] } };
825
+ }
826
+ }
827
+ let box: { input: LayoutInput; rect: LayoutRect } | undefined;
828
+ if (textChange) {
829
+ const { element } = textChange;
830
+ const parent = placement.parents.get(element)?.parent;
831
+ const dependency = settledLayout.dependencies.find(({ element }) => element === parent);
832
+ if (
833
+ parent?.type !== "group" ||
834
+ dependency?.children.length !== 1 ||
835
+ dependency.children[0] !== element
836
+ )
837
+ return undefined;
838
+ const style = (parent.props.layout?.style ?? emptyStyle) as LayoutStyle;
839
+ const rect = settledLayout.rectangles.get(parent);
840
+ if (!isolatedBox(style, rect)) return undefined;
841
+ box = { input: { style, children: [textChange.input] }, rect };
842
+ }
843
+ for (const [font, height] of retained.fonts)
844
+ if (!Object.is(retained.readLineHeight(font), height)) return undefined;
845
+ return { changedBases, placement, layout: settledLayout, textChange, box, scrollChanges };
846
+ };
847
+ // React owns structural edits. Validate authored geometry and live fonts
848
+ // before retaining the committed placements of a nonstructural edit.
849
+ const settled = retainedLayout();
850
+ const inputs = new Map<SceneTreeElement, LayoutInput>();
851
+ const elements = new Map<LayoutInput, SceneTreeElement>();
852
+ const styles = new Map<SceneTreeElement, LayoutStyle>();
853
+ let scrollPositionedByYoga: Set<SceneTreeElement> | undefined;
854
+ const preparations: Promise<void>[] = [];
855
+ let reusableLayout = true;
856
+ const buildChildren = (
857
+ entry: SceneTreeElement,
858
+ baselineAlignment: boolean,
859
+ result: LayoutInput[] = [],
860
+ ): LayoutInput[] => {
861
+ for (const child of entry.children) {
862
+ if (child.kind !== "element") continue;
863
+ const props = child.props.layout;
864
+ if (props?.paintWrapper) buildChildren(child, baselineAlignment, result);
865
+ else if (!props?.decoration && !props?.resource)
866
+ result.push(build(child, baselineAlignment));
867
+ }
868
+ return result;
869
+ };
870
+ const build = (entry: SceneTreeElement, ancestorBaseline: boolean): LayoutInput => {
871
+ // Complex inline/raster measurement has additional run/lease dependencies.
872
+ // Keep its existing path until separately characterized.
873
+ if (
874
+ entry.type === "multiStyleLabel" ||
875
+ entry.type === "inlineText" ||
876
+ entry.props.layout?.textRaster
877
+ )
878
+ reusableLayout = false;
879
+ let style = (entry.props.layout?.style ?? {}) as LayoutStyle;
880
+ const id = entry.props.layout?.id;
881
+ if (typeof id === "string") {
882
+ declarativeStyles.set(id, style);
883
+ const dimensions = dimensionOverrides.get(id);
884
+ if (dimensions) {
885
+ if (!dimensions.initialized) {
886
+ dimensions.baseline = { ...style };
887
+ dimensions.initialized = true;
888
+ }
889
+ for (const name of ["width", "height"] as const)
890
+ if (name in dimensions.values) {
891
+ if (Object.is(style[name], dimensions.baseline[name]))
892
+ style = { ...style, [name]: dimensions.values[name] };
893
+ else delete dimensions.values[name];
894
+ }
895
+ }
896
+ const override = opacityOverrides.get(id);
897
+ if (override) {
898
+ if (!override.initialized) {
899
+ override.baseline = style.opacity;
900
+ override.initialized = true;
901
+ }
902
+ if (Object.is(style.opacity, override.baseline))
903
+ style = { ...style, opacity: override.value };
904
+ else opacityOverrides.delete(id);
905
+ }
906
+ }
907
+ const baselineAlignment =
908
+ ancestorBaseline || style.alignItems === "baseline" || style.alignSelf === "baseline";
909
+ if (baselineAlignment && entry.props.layout?.scrollTranslation) {
910
+ // Yoga can derive an ancestor's baseline from this child's position.
911
+ const [x, y] = entry.props.layout.scrollTranslation as readonly [number, number];
912
+ style = {
913
+ ...style,
914
+ ...(typeof style.left === "number" ? { left: style.left + x } : {}),
915
+ ...(typeof style.top === "number" ? { top: style.top + y } : {}),
916
+ };
917
+ (scrollPositionedByYoga ??= new Set()).add(entry);
918
+ }
919
+ styles.set(entry, style);
920
+ const input: LayoutInput = {
921
+ style,
922
+ children:
923
+ entry.type === "label" ||
924
+ entry.type === "multiStyleLabel" ||
925
+ entry.type === "inlineText" ||
926
+ entry.props.layout?.textRaster
927
+ ? []
928
+ : buildChildren(entry, baselineAlignment),
929
+ ...(entry.type === "multiStyleLabel" ||
930
+ entry.type === "inlineText" ||
931
+ entry.props.layout?.inlineRaster
932
+ ? {
933
+ text: inlineTextRuns(entry)
934
+ .map((run) => run.text)
935
+ .join(""),
936
+ }
937
+ : entry.type === "label" || entry.props.layout?.textRaster
938
+ ? { text: labelText(entry) }
939
+ : {}),
940
+ };
941
+ inputs.set(entry, input);
942
+ elements.set(input, entry);
943
+ if (
944
+ entry.type === "label" ||
945
+ entry.type === "multiStyleLabel" ||
946
+ entry.type === "inlineText" ||
947
+ entry.props.layout?.textRaster
948
+ )
949
+ for (const fontStyle of entry.type === "multiStyleLabel" ||
950
+ entry.type === "inlineText" ||
951
+ entry.props.layout?.inlineRaster
952
+ ? inlineTextRuns(entry).map((run) => run.style)
953
+ : [style]) {
954
+ const preparation = options.text.prepare(fontStyle);
955
+ if (preparation) {
956
+ preparations.push(preparation);
957
+ // A later synchronous build failure may prevent Promise.all.
958
+ // Keep every already-started operation observed either way.
959
+ void preparation.catch(() => undefined);
960
+ }
961
+ }
962
+ return input;
963
+ };
964
+ const sceneInput: LayoutInput | undefined = settled
965
+ ? undefined
966
+ : { style: {}, children: tree.map((entry) => build(entry, false)) };
967
+ const styleFor = settled
968
+ ? (entry: SceneTreeElement) => (entry.props.layout?.style ?? emptyStyle) as LayoutStyle
969
+ : (entry: SceneTreeElement) => styles.get(entry) ?? emptyStyle;
970
+ const finish = () => {
971
+ if (retired || generation !== rasterGeneration)
972
+ return new Map<SceneTreeElement, SceneFields>();
973
+ const entries = [...inputs.entries()];
974
+ const measured = new Set<LayoutInput>();
975
+ const previousLayout = layoutCache;
976
+ let changedText: LayoutInput | undefined;
977
+ let changedTextIndex = -1;
978
+ let severalTextChanges = false;
979
+ const sameInputs =
980
+ !settled &&
981
+ reactCommit &&
982
+ reusableLayout &&
983
+ !preparations.length &&
984
+ previousLayout &&
985
+ previousLayout.width === options.viewport.width &&
986
+ previousLayout.height === options.viewport.height &&
987
+ entries.length === previousLayout.dependencies.length &&
988
+ entries.every(([element, input], index) => {
989
+ const previous = previousLayout.dependencies[index];
990
+ if (
991
+ input.text !== previous.text &&
992
+ !(
993
+ input.text !== undefined &&
994
+ fixedLabel(previous, input.style, previousLayout.rectangles.get(element))
995
+ )
996
+ ) {
997
+ severalTextChanges ||= changedText !== undefined;
998
+ changedText = input;
999
+ changedTextIndex = index;
1000
+ }
1001
+ return (
1002
+ element === previous.element &&
1003
+ input.children.length === previous.children.length &&
1004
+ input.children.every(
1005
+ (child, index) => elements.get(child) === previous.children[index],
1006
+ ) &&
1007
+ Object.is(element.props.layout?.numberOfLines, previous.lines) &&
1008
+ sameLayoutStyle(input.style, previous.style, element.type === "group")
1009
+ );
1010
+ });
1011
+ const reuse = (settled && !settled.textChange) || (sameInputs && !changedText);
1012
+ let measuredLabel: MeasuredLabel | undefined;
1013
+ const measure: TextMeasure = (input, width) => {
1014
+ measured.add(input);
1015
+ const element = elements.get(input)!;
1016
+ if (element.type === "inlineText")
1017
+ return layoutInlineParagraph(
1018
+ inlineTextRuns(element),
1019
+ options.text,
1020
+ width,
1021
+ Number(element.props.layout?.numberOfLines ?? 0),
1022
+ );
1023
+ if (element.type === "multiStyleLabel" || element.props.layout?.inlineRaster)
1024
+ return measureInlineText(
1025
+ inlineTextRuns(element),
1026
+ options.text,
1027
+ width,
1028
+ Number(element.props.layout?.numberOfLines ?? 0),
1029
+ element.props.layout?.inlineRaster === true,
1030
+ );
1031
+ const metrics = options.text.metrics(input.style);
1032
+ const result = layoutText(
1033
+ input.text ?? "",
1034
+ input.style,
1035
+ metrics,
1036
+ width,
1037
+ Number(element.props.layout?.numberOfLines ?? 0),
1038
+ );
1039
+ // The retained font keeps glyph widths stable. Reuse the wrapped
1040
+ // text only when Yoga commits exactly the measured constraint.
1041
+ if (input === settled?.textChange?.input)
1042
+ measuredLabel = { width, lineHeight: metrics.lineHeight, layout: result };
1043
+ return { width: result.width, height: result.height };
1044
+ };
1045
+ let isolated: IsolatedLabel | undefined;
1046
+ if (settled?.textChange && settled.box) {
1047
+ const { element, index, input } = settled.textChange;
1048
+ elements.set(input, element);
1049
+ const previous = settled.layout.rectangles.get(element)!;
1050
+ const rect =
1051
+ intrinsicLabelRect(input, previous, measure) ??
1052
+ calculateFlexLayout(settled.box.input, settled.box.rect, measure).get(input)!;
1053
+ isolated = {
1054
+ element,
1055
+ index,
1056
+ rect,
1057
+ text: input.text,
1058
+ measured: measured.has(input),
1059
+ };
1060
+ } else if (
1061
+ sameInputs &&
1062
+ options.text.preparedFieldFont &&
1063
+ changedText?.text !== undefined &&
1064
+ !severalTextChanges
1065
+ ) {
1066
+ const box = entries.find(
1067
+ ([element, input]) =>
1068
+ element.type === "group" &&
1069
+ input.children.length === 1 &&
1070
+ input.children[0] === changedText,
1071
+ );
1072
+ if (box) {
1073
+ const [element, input] = box;
1074
+ const rect = previousLayout!.rectangles.get(element);
1075
+ if (isolatedBox(input.style, rect)) {
1076
+ const solved = calculateFlexLayout(input, rect, measure);
1077
+ isolated = {
1078
+ element: elements.get(changedText)!,
1079
+ index: changedTextIndex,
1080
+ rect: solved.get(changedText)!,
1081
+ text: changedText.text,
1082
+ measured: measured.has(changedText),
1083
+ };
1084
+ }
1085
+ }
1086
+ }
1087
+ // Retain local child rectangles only for a fixed, unchanged box under
1088
+ // scroll content. Yoga still places every box in current sibling order.
1089
+ const retainFixedChildren = () => {
1090
+ const walk = committedWalk;
1091
+ const retained = walk?.retained;
1092
+ if (
1093
+ !sceneInput ||
1094
+ !reactCommit ||
1095
+ changes ||
1096
+ !reusableLayout ||
1097
+ preparations.length ||
1098
+ !previousLayout ||
1099
+ previousLayout.rectangles !== walk?.rectangles ||
1100
+ previousLayout.width !== options.viewport.width ||
1101
+ previousLayout.height !== options.viewport.height ||
1102
+ retained?.text !== options.text ||
1103
+ !hasOnlyBuiltinObjectPrototypeFields()
1104
+ )
1105
+ return undefined;
1106
+ const dependencies = new Map(
1107
+ previousLayout.dependencies.map((dep) => [dep.element, dep]),
1108
+ );
1109
+ const retainedBoxes = new Map<
1110
+ LayoutInput,
1111
+ {
1112
+ rect: LayoutRect;
1113
+ children: { input: LayoutInput; rect: LayoutRect; measured: boolean }[];
1114
+ }
1115
+ >();
1116
+ const visit = (input: LayoutInput, scroll: boolean) => {
1117
+ if (input.style.alignItems === "baseline" || input.style.alignSelf === "baseline")
1118
+ return;
1119
+ const element = elements.get(input);
1120
+ const dependency = element && dependencies.get(element);
1121
+ const rect = element && previousLayout.rectangles.get(element);
1122
+ if (
1123
+ scroll &&
1124
+ element?.type === "group" &&
1125
+ dependency &&
1126
+ rect &&
1127
+ fixedScrollBox(input, rect) &&
1128
+ input.children.length === dependency.children.length &&
1129
+ sameLayoutStyle(input.style, dependency.style, true)
1130
+ ) {
1131
+ const children = [];
1132
+ for (const [index, child] of input.children.entries()) {
1133
+ const childElement = elements.get(child)!;
1134
+ const before = dependencies.get(childElement);
1135
+ const rect = previousLayout.rectangles.get(childElement);
1136
+ if (
1137
+ childElement !== dependency.children[index] ||
1138
+ !before ||
1139
+ !rect ||
1140
+ before.children.length ||
1141
+ before.text !== child.text ||
1142
+ !Object.is(before.lines, childElement.props.layout?.numberOfLines) ||
1143
+ !sameLayoutStyle(child.style, before.style, childElement.type === "group")
1144
+ )
1145
+ break;
1146
+ children.push({ input: child, rect, measured: before.measured });
1147
+ }
1148
+ if (children.length === input.children.length) {
1149
+ retainedBoxes.set(input, { rect, children });
1150
+ return;
1151
+ }
1152
+ }
1153
+ const content = scroll || element?.props.layout?.scrollTranslation != null;
1154
+ for (const child of input.children) visit(child, content);
1155
+ };
1156
+ visit(sceneInput, false);
1157
+ if (
1158
+ retainedBoxes.size &&
1159
+ [...retained.fonts].every(([font, height]) =>
1160
+ Object.is(retained.readLineHeight(font), height),
1161
+ )
1162
+ )
1163
+ return retainedBoxes;
1164
+ };
1165
+ const retainedBoxes = reuse || isolated ? undefined : retainFixedChildren();
1166
+ let layout =
1167
+ reuse || isolated
1168
+ ? undefined
1169
+ : calculateFlexLayout(sceneInput!, options.viewport, measure, retainedBoxes);
1170
+ if (layout && retainedBoxes) {
1171
+ const solved = layout;
1172
+ if (
1173
+ [...retainedBoxes].some(([input, { rect }]) => {
1174
+ const current = solved.get(input)!;
1175
+ return current.width !== rect.width || current.height !== rect.height;
1176
+ })
1177
+ ) {
1178
+ measured.clear();
1179
+ layout = calculateFlexLayout(sceneInput!, options.viewport, measure);
1180
+ } else {
1181
+ for (const { children } of retainedBoxes.values())
1182
+ for (const child of children) {
1183
+ solved.set(child.input, child.rect);
1184
+ if (child.measured) measured.add(child.input);
1185
+ }
1186
+ }
1187
+ }
1188
+ const reusedRectangles =
1189
+ settled?.layout.rectangles ?? (reuse || isolated ? layoutCache!.rectangles : undefined);
1190
+ if (layout) {
1191
+ layoutCache = undefined;
1192
+ if (reusableLayout && !preparations.length) {
1193
+ const dependencies = entries.map(([element, input]) => ({
1194
+ element,
1195
+ style: captureLayoutStyle(input.style, element.type === "group"),
1196
+ text: input.text,
1197
+ measured: measured.has(input),
1198
+ lines: element.props.layout?.numberOfLines,
1199
+ children: input.children.map((child) => elements.get(child)!),
1200
+ }));
1201
+ if (dependencies.every((entry) => entry.style !== undefined))
1202
+ layoutCache = {
1203
+ dependencies: dependencies as LayoutDependency[],
1204
+ rectangles: new Map(entries.map(([entry, input]) => [entry, layout.get(input)!])),
1205
+ width: options.viewport.width,
1206
+ height: options.viewport.height,
1207
+ };
1208
+ }
1209
+ }
1210
+ // An isolated solve changes one label's geometry. The other rectangles
1211
+ // and field dependencies were validated against the previous layout.
1212
+ const prepareNode = preparedFields.begin(
1213
+ Boolean(reuse || isolated),
1214
+ options.text,
1215
+ isolated?.element,
1216
+ );
1217
+ const canRetainWalk = !!layoutCache && !scrollPositionedByYoga && canRetainPlacement();
1218
+ const previous =
1219
+ reusedRectangles && canRetainWalk
1220
+ ? (settled?.placement ?? placementFor(reusedRectangles))
1221
+ : undefined;
1222
+ const retainedPlacement = previous?.retained;
1223
+ const isolatedWalk = !!(
1224
+ !settled &&
1225
+ isolated &&
1226
+ retainedPlacement &&
1227
+ retainedPlacement.text === options.text &&
1228
+ [...retainedPlacement.fonts].every(([font, height]) =>
1229
+ Object.is(retainedPlacement.readLineHeight(font), height),
1230
+ )
1231
+ );
1232
+ const sparseWalk = !!settled || isolatedWalk;
1233
+ const bases = new Map<SceneTreeElement, SceneFields>();
1234
+ const invalidatedBases = sparseWalk
1235
+ ? (settled?.changedBases ?? new Set<SceneTreeElement>())
1236
+ : undefined;
1237
+ const visited = previous ? new Set<SceneTreeElement>() : undefined;
1238
+ const placementChanges = new Map<string, NativePlacement>();
1239
+ if (previous && visited && changes) {
1240
+ // A changed child's content can supply an ancestor's accessible
1241
+ // name. Include the ancestry of every changed field and host prop.
1242
+ const includeAncestry = (node: SceneTreeElement) => {
1243
+ let current: SceneTreeElement | undefined = node;
1244
+ while (current && !visited.has(current)) {
1245
+ visited.add(current);
1246
+ current = previous.parents.get(current)?.parent;
1247
+ }
1248
+ };
1249
+ if (sparseWalk) {
1250
+ // React host props are current even when a sibling keeps its rectangle.
1251
+ // Only content and paint changes need the placement walk.
1252
+ for (const node of settled?.changedBases ?? []) includeAncestry(node);
1253
+ if (settled?.scrollChanges.size)
1254
+ for (const node of settled.scrollChanges.keys()) includeAncestry(node);
1255
+ for (const [node, input] of entries) {
1256
+ const base = previous.bases.get(node);
1257
+ const opacity =
1258
+ typeof input.style.opacity === "number" ? input.style.opacity : undefined;
1259
+ const textChanged =
1260
+ node.type === "label" &&
1261
+ input.text !== preparedFields.retained(node, base)?.content;
1262
+ if (textChanged || !Object.is(opacity, base?.opacity)) {
1263
+ invalidatedBases!.add(node);
1264
+ includeAncestry(node);
1265
+ }
1266
+ }
1267
+ for (const node of changes) {
1268
+ if (
1269
+ node.props.layout === plainBackgroundLayout ||
1270
+ node.props.layout === plainImageLayout
1271
+ )
1272
+ continue;
1273
+ const layout = node.props.layout!;
1274
+ const id = layout.id as string;
1275
+ const old = placements.get(id)!;
1276
+ const accessibility = layout.accessibility as AccessibilitySemantics | undefined;
1277
+ const focusable = node.props.fields?.focusable ?? layout.focusable;
1278
+ declarativeStyles.set(id, styleFor(node));
1279
+ if (
1280
+ accessibility?.label !== old.accessibility?.label ||
1281
+ (typeof focusable === "boolean" ? focusable : undefined) !== old.focusable
1282
+ ) {
1283
+ includeAncestry(node);
1284
+ } else {
1285
+ placementChanges.set(id, {
1286
+ ...old,
1287
+ view: layout.view as NativePlacement["view"],
1288
+ nativeTag: layout.nativeTag as NativePlacement["nativeTag"],
1289
+ focusEvents: layout.focusEvents as NativePlacement["focusEvents"],
1290
+ focusTargets: layout.focusTargets as NativePlacement["focusTargets"],
1291
+ accessibility,
1292
+ });
1293
+ }
1294
+ }
1295
+ } else for (const node of changes) includeAncestry(node);
1296
+ if (!sparseWalk) {
1297
+ for (const [node, input] of entries) {
1298
+ // Other providers may replace fonts or change metrics without
1299
+ // a React mutation. Validate their normal field plans.
1300
+ const fields = prepareNode(
1301
+ node,
1302
+ input.style,
1303
+ node === isolated?.element ? isolated.rect : reusedRectangles!.get(node)!,
1304
+ input.text,
1305
+ );
1306
+ bases.set(node, fields);
1307
+ if (fields !== previous.bases.get(node)) includeAncestry(node);
1308
+ }
1309
+ }
1310
+ }
1311
+ // A settled walk writes only visited fields. The renderer uses the
1312
+ // already-committed map for the rest and publishes its delta after writes.
1313
+ let fieldBase = sparseWalk ? previous?.fields : undefined;
1314
+ let fields = new Map<SceneTreeElement, SceneFields>(
1315
+ fieldBase ? undefined : previous?.fields,
1316
+ );
1317
+ const originalPlacements = sparseWalk ? placements : undefined;
1318
+ let next = sparseWalk
1319
+ ? placementChanges
1320
+ : new Map<string, NativePlacement>(previous ? placements : undefined);
1321
+ let modal: { id: string; paintPath: readonly number[] } | undefined;
1322
+ const references: string[] = [];
1323
+ const paintedAbove = (left: readonly number[], right: readonly number[]) => {
1324
+ for (let index = 0; index < Math.min(left.length, right.length); index++) {
1325
+ const difference = left[index] - right[index];
1326
+ if (!Number.isNaN(difference) && difference !== 0) return difference > 0;
1327
+ }
1328
+ return left.length >= right.length;
1329
+ };
1330
+ // A changed child already marks its ancestry for placement. Recompute
1331
+ // text on that path and reuse the committed contribution of other children.
1332
+ const contentLabels = canRetainWalk
1333
+ ? new Map<SceneTreeElement, string>(sparseWalk ? undefined : previous?.contentLabels)
1334
+ : undefined;
1335
+ if (!sparseWalk && visited && contentLabels)
1336
+ for (const node of visited) contentLabels.delete(node);
1337
+ const readContentText = (entry: SceneTreeElement): string => {
1338
+ if (
1339
+ entry.hidden ||
1340
+ entry.props.layout?.accessibilityElementsHidden ||
1341
+ entry.props.layout?.importantForAccessibility === "no-hide-descendants"
1342
+ )
1343
+ return "";
1344
+ const authored = entry.props.layout?.accessibility as AccessibilitySemantics | undefined;
1345
+ if (authored?.label !== undefined) return authored.label;
1346
+ const scalar = entry.props.layout?.scalarText;
1347
+ if (typeof scalar === "string") return scalar.trim();
1348
+ return entry.children
1349
+ .map((child) =>
1350
+ child.kind === "text" ? (child.hidden ? "" : child.text) : contentText(child),
1351
+ )
1352
+ .join(" ")
1353
+ .trim();
1354
+ };
1355
+ const contentText = (entry: SceneTreeElement): string => {
1356
+ const retained =
1357
+ contentLabels?.get(entry) ??
1358
+ (sparseWalk && !visited?.has(entry) ? previous?.contentLabels.get(entry) : undefined);
1359
+ if (retained !== undefined) return retained;
1360
+ const text = readContentText(entry);
1361
+ contentLabels?.set(entry, text);
1362
+ return text;
1363
+ };
1364
+ const rasters: Promise<void>[] = [];
1365
+ const callbacks: LayoutDelivery[] = [];
1366
+ let lastBackground: SceneFields | undefined;
1367
+ // A retained scroll changes world coordinates without changing the
1368
+ // descendants' local fields, accessibility relationships or layout.
1369
+ const relocate = (entry: SceneTreeElement, parentWorld: Affine) => {
1370
+ if (
1371
+ entry.props.layout === plainBackgroundLayout ||
1372
+ entry.props.layout === plainImageLayout
1373
+ )
1374
+ return;
1375
+ const id = entry.props.layout!.id as string;
1376
+ const placement = next.get(id) ?? originalPlacements!.get(id)!;
1377
+ const world = sceneWorld(parentWorld, previous!.fields.get(entry)!);
1378
+ next.set(id, {
1379
+ ...placement,
1380
+ world,
1381
+ global: affineBounds(world, placement.local.width, placement.local.height),
1382
+ });
1383
+ for (const child of entry.children) if (child.kind === "element") relocate(child, world);
1384
+ };
1385
+ const walk = (
1386
+ entry: SceneTreeElement,
1387
+ parentWorld: Affine,
1388
+ parent?: LayoutRect,
1389
+ parentAccessibilityHidden = false,
1390
+ parentPointerHidden = false,
1391
+ parentID?: string,
1392
+ parentPaintPath: readonly number[] = [],
1393
+ siblingIndex = 0,
1394
+ parentVisible = true,
1395
+ scrolled = false,
1396
+ ) => {
1397
+ if (visited && !visited.has(entry)) {
1398
+ if (scrolled) relocate(entry, parentWorld);
1399
+ return;
1400
+ }
1401
+ if (
1402
+ parent &&
1403
+ entry.type === "rectangle" &&
1404
+ entry.props.layout === plainBackgroundLayout &&
1405
+ entry.children.length === 0 &&
1406
+ typeof entry.props.fields?.focusable !== "boolean"
1407
+ ) {
1408
+ const width = Math.max(0, parent.width),
1409
+ height = Math.max(0, parent.height);
1410
+ if (
1411
+ !lastBackground ||
1412
+ lastBackground.width !== width ||
1413
+ lastBackground.height !== height
1414
+ )
1415
+ lastBackground = nativeNodeFields(
1416
+ entry,
1417
+ {},
1418
+ { x: 0, y: 0, width, height },
1419
+ options.text,
1420
+ );
1421
+ fields.set(entry, lastBackground);
1422
+ return;
1423
+ }
1424
+ // SceneGraph sorts siblings by z-index, then authored order. A child
1425
+ // paints within its parent's position, not at a global z-index.
1426
+ const paintPath = [...parentPaintPath, Number(styleFor(entry).zIndex ?? 0), siblingIndex];
1427
+ const id = entry.props.layout?.id;
1428
+ const declared = {
1429
+ pointerEvents: entry.props.layout?.pointerEvents as string | undefined,
1430
+ importantForAccessibility: entry.props.layout?.importantForAccessibility as
1431
+ string | undefined,
1432
+ accessibilityElementsHidden: entry.props.layout?.accessibilityElementsHidden as
1433
+ boolean | undefined,
1434
+ };
1435
+ const override = typeof id === "string" ? presentationOverrides.get(id) : undefined;
1436
+ if (override && !override.initialized) {
1437
+ override.baseline = { ...declared };
1438
+ override.initialized = true;
1439
+ }
1440
+ if (typeof id === "string") declarativePresentation.set(id, declared);
1441
+ if (override)
1442
+ for (const key of [
1443
+ "pointerEvents",
1444
+ "importantForAccessibility",
1445
+ "accessibilityElementsHidden",
1446
+ ] as const)
1447
+ if (!Object.is(declared[key], override.baseline[key])) delete override.values[key];
1448
+ const presentation = override?.values;
1449
+ const importance =
1450
+ presentation?.importantForAccessibility ?? declared.importantForAccessibility;
1451
+ const pointerEvents =
1452
+ presentation?.pointerEvents ??
1453
+ (entry.props.layout?.pointerEvents as string | undefined);
1454
+ const pointerHidden =
1455
+ parentPointerHidden || pointerEvents === "none" || pointerEvents === "box-none";
1456
+ const pointerChildrenHidden =
1457
+ parentPointerHidden || pointerEvents === "none" || pointerEvents === "box-only";
1458
+ const visible =
1459
+ parentVisible && entry.hidden !== true && styleFor(entry).display !== "none";
1460
+ const hideDescendants =
1461
+ parentAccessibilityHidden ||
1462
+ !visible ||
1463
+ importance === "no-hide-descendants" ||
1464
+ (presentation?.accessibilityElementsHidden ?? declared.accessibilityElementsHidden) ===
1465
+ true;
1466
+ const decoration = entry.props.layout?.decoration;
1467
+ const thickness = Math.min(
1468
+ Number(entry.props.layout?.thickness ?? 0),
1469
+ decoration === "Top" || decoration === "Bottom"
1470
+ ? (parent?.height ?? 0)
1471
+ : (parent?.width ?? 0),
1472
+ );
1473
+ const border = decoration === "surface" ? Number(entry.props.layout?.border ?? 0) : 0;
1474
+ const solvedRect =
1475
+ entry.props.layout?.resource && parent
1476
+ ? { x: 0, y: 0, width: parent.width, height: parent.height }
1477
+ : decoration && parent
1478
+ ? {
1479
+ x: decoration === "Right" ? parent.width - thickness : border,
1480
+ y: decoration === "Bottom" ? parent.height - thickness : border,
1481
+ width:
1482
+ decoration === "Left" || decoration === "Right"
1483
+ ? thickness
1484
+ : Math.max(0, parent.width - 2 * border),
1485
+ height:
1486
+ decoration === "Top" || decoration === "Bottom"
1487
+ ? thickness
1488
+ : Math.max(0, parent.height - 2 * border),
1489
+ }
1490
+ : entry === isolated?.element
1491
+ ? isolated.rect
1492
+ : reusedRectangles
1493
+ ? reusedRectangles.get(entry)!
1494
+ : layout!.get(inputs.get(entry)!)!;
1495
+ const focusable = entry.props.fields?.focusable ?? entry.props.layout?.focusable;
1496
+ const base =
1497
+ bases.get(entry) ??
1498
+ (sparseWalk && !invalidatedBases?.has(entry)
1499
+ ? previous?.bases.get(entry)
1500
+ : undefined) ??
1501
+ prepareNode(
1502
+ entry,
1503
+ styleFor(entry),
1504
+ solvedRect,
1505
+ settled && entry.type === "label" ? labelText(entry) : inputs.get(entry)?.text,
1506
+ entry === settled?.textChange?.element ? measuredLabel : undefined,
1507
+ );
1508
+ if (canRetainWalk) bases.set(entry, base);
1509
+ const native: Record<string, SceneValue> = {
1510
+ ...base,
1511
+ ...(typeof focusable === "boolean" ? { focusable } : {}),
1512
+ };
1513
+ const scrollTranslation = entry.props.layout?.scrollTranslation as
1514
+ readonly [number, number] | undefined;
1515
+ let rect = solvedRect;
1516
+ if (
1517
+ scrollTranslation &&
1518
+ visible &&
1519
+ !scrollPositionedByYoga?.has(entry) &&
1520
+ (scrollTranslation[0] || scrollTranslation[1])
1521
+ ) {
1522
+ const [x, y] = scrollTranslation;
1523
+ rect = {
1524
+ ...solvedRect,
1525
+ x: Math.fround(solvedRect.x + Math.fround(x)),
1526
+ y: Math.fround(solvedRect.y + Math.fround(y)),
1527
+ };
1528
+ const translation = native.translation as readonly number[];
1529
+ native.translation = [
1530
+ translation[0] + (rect.x - solvedRect.x),
1531
+ translation[1] + (rect.y - solvedRect.y),
1532
+ ];
1533
+ }
1534
+ if (entry.type === "inlineText")
1535
+ inlineLines.set(
1536
+ entry,
1537
+ nativeInlineTextLines(entry, styleFor(entry), rect, options.text),
1538
+ );
1539
+ // Measurements describe the semantic view's transformed bounds, not
1540
+ // a text raster's extra shadow pixels or a mask's internal geometry.
1541
+ const world = sceneWorld(parentWorld, native);
1542
+ if (
1543
+ entry.type !== "multiStyleLabel" &&
1544
+ entry.type !== "inlineText" &&
1545
+ entry.props.layout?.textRaster &&
1546
+ rect.width > 0 &&
1547
+ rect.height > 0
1548
+ ) {
1549
+ if (!options.textRaster)
1550
+ throw new RokuHostError(
1551
+ "C04_TEXT_RASTER",
1552
+ "Tracked/shadowed text requires an installed raster provider",
1553
+ );
1554
+ const style = styleFor(entry),
1555
+ metrics = options.text.metrics(style);
1556
+ const value = layoutText(
1557
+ inputs.get(entry)?.text ?? "",
1558
+ style,
1559
+ metrics,
1560
+ rect.width,
1561
+ Number(entry.props.layout?.numberOfLines ?? 0),
1562
+ );
1563
+ const preparation = (
1564
+ entry.props.layout?.inlineRaster
1565
+ ? (() => {
1566
+ if (!options.textRaster!.acquireInline)
1567
+ throw new RokuHostError(
1568
+ "C04_INLINE_RASTER",
1569
+ "Mixed tracking requires the inline raster port",
1570
+ );
1571
+ return options.textRaster!.acquireInline({
1572
+ width: rect.width,
1573
+ height: rect.height,
1574
+ runs: inlineTextRuns(entry).map((run) => ({
1575
+ ...run,
1576
+ style: {
1577
+ ...run.style,
1578
+ fontFamily:
1579
+ options.text.fontFamily?.(run.style) ??
1580
+ run.style.fontFamily ??
1581
+ "RokuDefault",
1582
+ },
1583
+ metrics: options.text.metrics(run.style),
1584
+ })),
1585
+ });
1586
+ })()
1587
+ : options.textRaster.acquire({
1588
+ style: {
1589
+ ...style,
1590
+ fontFamily:
1591
+ options.text.fontFamily?.(style) ?? style.fontFamily ?? "RokuDefault",
1592
+ },
1593
+ metrics,
1594
+ layout: value,
1595
+ width: rect.width,
1596
+ height: rect.height,
1597
+ })
1598
+ ).then((lease) => {
1599
+ if (preparationFailed || retired || generation !== rasterGeneration) {
1600
+ lease.release();
1601
+ return;
1602
+ }
1603
+ retained.add(lease);
1604
+ preparingRasters.add(lease);
1605
+ native.uri = lease.image.uri;
1606
+ native.loadDisplayMode = "scaleToFill";
1607
+ native.width = lease.image.width;
1608
+ native.height = lease.image.height;
1609
+ const translation = native.translation as number[];
1610
+ native.translation = [
1611
+ translation[0] - lease.image.inset,
1612
+ translation[1] - lease.image.inset,
1613
+ ];
1614
+ if (native.scaleRotateCenter)
1615
+ native.scaleRotateCenter = (native.scaleRotateCenter as number[]).map(
1616
+ (value) => value + lease.image.inset,
1617
+ );
1618
+ if (native.clippingRect)
1619
+ native.clippingRect = [
1620
+ lease.image.inset,
1621
+ lease.image.inset,
1622
+ rect.width,
1623
+ rect.height,
1624
+ ];
1625
+ });
1626
+ rasters.push(preparation);
1627
+ // A later walk failure can bypass the normal raster join.
1628
+ void preparation.catch(() => undefined);
1629
+ }
1630
+ if (entry.type === "effect" && entry.props.layout?.radiusStyle) {
1631
+ const inset = Number(entry.props.layout?.insetBorder ?? 0);
1632
+ native.borderRadius = surfaceRadii(
1633
+ entry.props.layout.radiusStyle as LayoutStyle,
1634
+ rect.width + 2 * inset,
1635
+ rect.height + 2 * inset,
1636
+ ).map((radius) => Math.max(0, radius - inset));
1637
+ }
1638
+ if (entry.type === "effect" && entry.props.layout?.gradient)
1639
+ Object.assign(
1640
+ native,
1641
+ gradientFields(entry.props.layout.gradient as GradientSpec, rect.width, rect.height),
1642
+ );
1643
+ if (entry.type === "maskGroup" && parent && entry.props.layout?.composedMask) {
1644
+ const provider = options.textRaster;
1645
+ if (!provider?.acquirePixels)
1646
+ throw new RokuHostError(
1647
+ "C03_ROUNDED_CLIP",
1648
+ "Rounded clipping requires a native bitmap provider",
1649
+ );
1650
+ const mask = roundedMask(
1651
+ entry.props.layout.radiusStyle as LayoutStyle,
1652
+ rect.width,
1653
+ rect.height,
1654
+ );
1655
+ const preparation = provider.acquirePixels(mask).then((lease) => {
1656
+ if (preparationFailed || retired || generation !== rasterGeneration) {
1657
+ lease.release();
1658
+ return;
1659
+ }
1660
+ retained.add(lease);
1661
+ preparingRasters.add(lease);
1662
+ native.maskUri = lease.image.uri;
1663
+ native.maskSize = [rect.width, rect.height];
1664
+ });
1665
+ rasters.push(preparation);
1666
+ void preparation.catch(() => undefined);
1667
+ }
1668
+ if (entry.type === "maskGroup" && parent && entry.props.layout?.corner != null) {
1669
+ const corner = Number(entry.props.layout?.corner),
1670
+ radius = surfaceRadii(
1671
+ entry.props.layout?.radiusStyle as LayoutStyle,
1672
+ rect.width,
1673
+ rect.height,
1674
+ )[corner];
1675
+ native.maskSize = [(257 * radius) / 256, (257 * radius) / 256];
1676
+ native.maskOffset = [
1677
+ corner === 1 || corner === 2 ? rect.width - radius : 0,
1678
+ corner === 2 || corner === 3 ? rect.height - radius : 0,
1679
+ ];
1680
+ // A zero-radius corner samples the opaque clamped half-plane.
1681
+ // Keep its bitmap loaded so later radius changes preserve readiness.
1682
+ if (!radius)
1683
+ native.maskOffset = [
1684
+ corner === 1 || corner === 2 ? rect.width + 257 : -rect.width - 257,
1685
+ corner === 2 || corner === 3 ? rect.height + 257 : -rect.height - 257,
1686
+ ];
1687
+ }
1688
+ if (entry.props.layout?.maskReadiness != null)
1689
+ native.visible = entry.props.layout.maskReadiness === true;
1690
+ // pointerEvents controls touch hit testing, not non-touch/TV focus.
1691
+ if (!visible && native.focusable === true) native.focusable = false;
1692
+ fields.set(entry, native);
1693
+ if (typeof id === "string") {
1694
+ const global = affineBounds(world, rect.width, rect.height);
1695
+ const existing = next.get(id) ?? originalPlacements?.get(id);
1696
+ if (existing && (!previous || existing.handle !== entry.handle))
1697
+ throw new RokuHostError("C03_VIEW_ID", `Duplicate native view identity ${id}`);
1698
+ const accessibility = entry.props.layout?.accessibility as
1699
+ AccessibilitySemantics | undefined;
1700
+ if (
1701
+ accessibility &&
1702
+ (accessibility.labelledBy.length || accessibility.describedBy.length)
1703
+ )
1704
+ references.push(id);
1705
+ if (accessibility?.modal && !hideDescendants && !entry.hidden) {
1706
+ if (!modal || paintedAbove(paintPath, modal.paintPath)) modal = { id, paintPath };
1707
+ }
1708
+ next.set(id, {
1709
+ parentID,
1710
+ visible,
1711
+ modalBlocked: false,
1712
+ focusable: typeof native.focusable === "boolean" ? native.focusable : undefined,
1713
+ view: entry.props.layout?.view as NativePlacement["view"],
1714
+ focusEvents: entry.props.layout?.focusEvents as NativePlacement["focusEvents"],
1715
+ local: rect,
1716
+ global,
1717
+ accessibilityHidden:
1718
+ entry.hidden ||
1719
+ hideDescendants ||
1720
+ importance === "no" ||
1721
+ entry.props.layout?.accessible === false,
1722
+ accessibility,
1723
+ accessibilityLabel: accessibility?.label ?? contentText(entry),
1724
+ pointerEvents: pointerHidden ? "none" : pointerEvents,
1725
+ world,
1726
+ handle: entry.handle,
1727
+ node: entry,
1728
+ nativeTag: entry.props.layout?.nativeTag as number | undefined,
1729
+ focusTargets: entry.props.layout?.focusTargets as NativePlacement["focusTargets"],
1730
+ });
1731
+ const callback = entry.props.layout?.onLayout;
1732
+ if (typeof callback === "function")
1733
+ callbacks.push({
1734
+ id,
1735
+ rect,
1736
+ callback: callback as (event: unknown) => void,
1737
+ });
1738
+ }
1739
+ if (
1740
+ entry.type !== "label" &&
1741
+ entry.type !== "multiStyleLabel" &&
1742
+ entry.type !== "inlineText" &&
1743
+ !entry.props.layout?.textRaster
1744
+ )
1745
+ for (const [index, child] of entry.children.entries())
1746
+ if (child.kind === "element")
1747
+ walk(
1748
+ child,
1749
+ world,
1750
+ rect,
1751
+ hideDescendants,
1752
+ pointerChildrenHidden,
1753
+ typeof id === "string" ? id : parentID,
1754
+ paintPath,
1755
+ index,
1756
+ visible,
1757
+ scrolled || settled?.scrollChanges.has(entry),
1758
+ );
1759
+ };
1760
+ for (const [index, entry] of tree.entries())
1761
+ walk(entry, identityAffine, undefined, false, false, undefined, [], index);
1762
+ const inside = (id: string, ancestor: string): boolean => {
1763
+ let current: string | undefined = id;
1764
+ while (current !== undefined) {
1765
+ if (current === ancestor) return true;
1766
+ current = next.get(current)?.parentID;
1767
+ }
1768
+ return false;
1769
+ };
1770
+ // Cross-tree accessibility passes use the complete proposed layout.
1771
+ const local = !!originalPlacements && !modal && references.length === 0;
1772
+ if (originalPlacements && !local) {
1773
+ const complete = new Map(originalPlacements);
1774
+ for (const [id, placement] of next) complete.set(id, placement);
1775
+ next = complete;
1776
+ }
1777
+ if (modal) {
1778
+ const scopeAncestors = new Set<string>();
1779
+ for (let id = next.get(modal.id)?.parentID; id !== undefined; id = next.get(id)?.parentID)
1780
+ scopeAncestors.add(id);
1781
+ for (const [id, placement] of next) {
1782
+ if (inside(id, modal.id)) continue;
1783
+ next.set(id, {
1784
+ ...placement,
1785
+ accessibilityHidden: true,
1786
+ modalBlocked: true,
1787
+ containsActiveModalScope: scopeAncestors.has(id),
1788
+ pointerEvents: "none",
1789
+ });
1790
+ }
1791
+ }
1792
+ // Resolve against one fully exposed, unmodified snapshot. Following a
1793
+ // referenced node's own labelled-by again would chain cycles and make
1794
+ // names depend on native tree order. Hidden/modal-excluded sources keep
1795
+ // the host's explicit exposure boundary, independently of HTML naming.
1796
+ if (references.length) {
1797
+ const labelSources = new Map(
1798
+ [...next].flatMap(([id, placement]) =>
1799
+ !placement.accessibilityHidden
1800
+ ? [[id, placement.accessibilityLabel ?? ""] as const]
1801
+ : [],
1802
+ ),
1803
+ );
1804
+ for (const id of references) {
1805
+ const placement = next.get(id)!;
1806
+ const labels = placement.accessibility?.labelledBy.flatMap((target) => {
1807
+ const label = labelSources.get(target);
1808
+ return label ? [label] : [];
1809
+ });
1810
+ if (labels?.length)
1811
+ next.set(id, {
1812
+ ...placement,
1813
+ accessibilityLabel: labels.join(" "),
1814
+ accessibility: { ...placement.accessibility!, label: labels.join(" ") },
1815
+ });
1816
+ const descriptions = placement.accessibility?.describedBy.flatMap((target) => {
1817
+ const value = labelSources.get(target);
1818
+ return value === undefined ? [] : [value];
1819
+ });
1820
+ if (descriptions?.length) {
1821
+ const current = next.get(id)!;
1822
+ next.set(id, {
1823
+ ...current,
1824
+ accessibility: { ...current.accessibility!, hint: descriptions.join(" ").trim() },
1825
+ });
1826
+ }
1827
+ }
1828
+ }
1829
+ if (fieldBase && modal) {
1830
+ const complete = new Map(fieldBase);
1831
+ for (const [entry, native] of fields) complete.set(entry, native);
1832
+ fields = complete;
1833
+ fieldBase = undefined;
1834
+ }
1835
+ if (modal)
1836
+ for (const [entry, native] of fields) {
1837
+ const id = entry.props.layout?.id;
1838
+ if (typeof id === "string" && !inside(id, modal.id) && native.focusable === true)
1839
+ fields.set(entry, { ...native, focusable: false });
1840
+ }
1841
+ pending.set(tree, { entries: next, local, isolated });
1842
+ deliveries.set(tree, callbacks);
1843
+ if (rasters.length) return Promise.all(rasters).then(() => fields);
1844
+ if (canRetainWalk) {
1845
+ const parents =
1846
+ previous?.parents ?? indexPlacementParents(fields, !!options.text.preparedFieldFont);
1847
+ if (parents)
1848
+ placementWalks.set(tree, {
1849
+ rectangles: layoutCache!.rectangles,
1850
+ callbacks,
1851
+ fields: fieldBase ?? fields,
1852
+ bases: sparseWalk ? previous!.bases : bases,
1853
+ parents,
1854
+ contentLabels: sparseWalk ? previous!.contentLabels : contentLabels!,
1855
+ local: sparseWalk
1856
+ ? {
1857
+ bases,
1858
+ labels: contentLabels!,
1859
+ visited: visited!,
1860
+ scrollChanges: settled?.scrollChanges,
1861
+ }
1862
+ : undefined,
1863
+ retained: sparseWalk
1864
+ ? previous?.retained
1865
+ : retainPlacementInputs(
1866
+ layoutCache!.dependencies,
1867
+ bases,
1868
+ preparedFields,
1869
+ options.text,
1870
+ ),
1871
+ });
1872
+ }
1873
+ if ((reuse || sparseWalk) && changes) reuseSceneGeometry(fields, fieldBase);
1874
+ return fields;
1875
+ };
1876
+ try {
1877
+ const prepared = preparations.length ? Promise.all(preparations).then(finish) : finish();
1878
+ return prepared instanceof Promise ? prepared.catch(failPreparation) : prepared;
1879
+ } catch (error) {
1880
+ return failPreparation(error);
1881
+ }
1882
+ },
1883
+ afterCommit(tree) {
1884
+ committedWalk = placementWalks.get(tree);
1885
+ // A discarded or failed native commit never updates the committed layout.
1886
+ if (committedWalk?.local) {
1887
+ const { bases, labels, visited, scrollChanges } = committedWalk.local;
1888
+ if (scrollChanges)
1889
+ for (const [node, scroll] of scrollChanges)
1890
+ Object.assign(committedWalk.parents.get(node)!, scroll);
1891
+ for (const [node, fields] of bases) committedWalk.bases.set(node, fields);
1892
+ for (const node of visited) committedWalk.contentLabels.delete(node);
1893
+ for (const [node, label] of labels) committedWalk.contentLabels.set(node, label);
1894
+ committedWalk.local = undefined;
1895
+ }
1896
+ committedRasterGeneration = rasterGeneration;
1897
+ const retained = rasterLeases.get(tree) ?? new Set<TextRasterLease>();
1898
+ for (const lease of committedRasters) lease.release();
1899
+ committedRasters = retained;
1900
+ for (const lease of retained) preparingRasters.delete(lease);
1901
+ const update = pending.get(tree);
1902
+ if (update?.isolated && layoutCache) {
1903
+ const { element, index, rect, text, measured } = update.isolated;
1904
+ layoutCache.rectangles.set(element, rect);
1905
+ layoutCache.dependencies[index] = { ...layoutCache.dependencies[index], text, measured };
1906
+ }
1907
+ let rebuildTags = true;
1908
+ if (update?.local) {
1909
+ rebuildTags = false;
1910
+ for (const [id, placement] of update.entries) {
1911
+ if (placements.get(id)?.nativeTag !== placement.nativeTag) rebuildTags = true;
1912
+ placements.set(id, placement);
1913
+ }
1914
+ } else placements = update?.entries ?? new Map();
1915
+ for (const [id, previous] of liveSpeech)
1916
+ if (placements.get(id)?.handle !== previous.handle) liveSpeech.delete(id);
1917
+ if (lastFocusSpeech && placements.get(lastFocusSpeech.id)?.handle !== lastFocusSpeech.handle)
1918
+ lastFocusSpeech = undefined;
1919
+ for (const [id, previous] of deliveredLayouts)
1920
+ if (placements.get(id)?.handle !== previous.handle) deliveredLayouts.delete(id);
1921
+ if (rebuildTags)
1922
+ placedTags = new Map(
1923
+ [...placements].flatMap(([id, placement]) =>
1924
+ placement.nativeTag == null ? [] : [[placement.nativeTag, id] as const],
1925
+ ),
1926
+ );
1927
+ for (const id of focusOverrides.keys()) if (!placements.has(id)) focusOverrides.delete(id);
1928
+ for (const map of [
1929
+ opacityOverrides,
1930
+ dimensionOverrides,
1931
+ presentationOverrides,
1932
+ declarativeStyles,
1933
+ declarativePresentation,
1934
+ ])
1935
+ for (const id of map.keys()) if (!placements.has(id)) map.delete(id);
1936
+ const generation = ++publication;
1937
+ const callbacks = deliveries.get(tree) ?? [];
1938
+ layoutDelivery = Promise.resolve()
1939
+ .then(() => {
1940
+ if (retired || generation !== publication) return;
1941
+ options.input?.reconcileTargets();
1942
+ if (retired || generation !== publication) return;
1943
+ const focused = options.input?.focusedID;
1944
+ if (focused && lastFocusSpeech?.id === focused) speak(focused);
1945
+ for (const [id, placement] of placements) {
1946
+ if (retired || generation !== publication) return;
1947
+ const semantics = placement.accessibility;
1948
+ if (
1949
+ id === focused ||
1950
+ !semantics ||
1951
+ semantics.live === "none" ||
1952
+ semantics.state.busy ||
1953
+ placement.accessibilityHidden
1954
+ )
1955
+ continue;
1956
+ // Live de-duplication is independent of focus de-duplication, even
1957
+ // when an assertive update interrupts the speech queue.
1958
+ const message = accessibilitySpeech(semantics, placement.accessibilityLabel);
1959
+ const previous = liveSpeech.get(id);
1960
+ if (
1961
+ !message ||
1962
+ (previous?.handle === placement.handle && previous.text === message) ||
1963
+ !systemAllowsInput() ||
1964
+ options.system?.getSnapshot().screenReader !== true
1965
+ )
1966
+ continue;
1967
+ options.system.announceForAccessibility(message, {
1968
+ queue: semantics.live === "polite",
1969
+ });
1970
+ // Native ports may synchronously retire or replace this committed
1971
+ // tree. Its remaining regions and de-duplication state then retire.
1972
+ if (retired || generation !== publication) return;
1973
+ liveSpeech.set(id, { handle: placement.handle, text: message });
1974
+ }
1975
+ for (const { id, rect, callback } of callbacks) {
1976
+ if (retired || generation !== publication) return;
1977
+ const old = deliveredLayouts.get(id)?.local;
1978
+ if (!sameRect(old, rect)) {
1979
+ deliveredLayouts.set(id, placements.get(id)!);
1980
+ root.runSync(() =>
1981
+ callback({
1982
+ nativeEvent: {
1983
+ layout: {
1984
+ x: rect.x,
1985
+ y: rect.y,
1986
+ width: rect.width,
1987
+ height: rect.height,
1988
+ },
1989
+ },
1990
+ }),
1991
+ );
1992
+ }
1993
+ }
1994
+ })
1995
+ .catch((error) => {
1996
+ options.onError?.(error instanceof Error ? error : new Error(String(error)), "uncaught");
1997
+ throw error;
1998
+ });
1999
+ void layoutDelivery.catch(() => undefined);
2000
+ },
2001
+ });
2002
+ const releaseEnvironment = bindNativeEnvironment(options);
2003
+ let releaseInput: (() => void) | undefined;
2004
+ let releaseNavigation: (() => void) | undefined;
2005
+ try {
2006
+ releaseInput = options.input?.bindRenderer(root.runSync);
2007
+ releaseNavigation = options.input?.bindNavigation((direction) => {
2008
+ const id = options.input?.navigationFocusID;
2009
+ if (!id || !options.input?.isTargetEnabled(id)) return false;
2010
+ const placement = placements.get(id),
2011
+ overrides = focusOverrides.get(id);
2012
+ const tag =
2013
+ overrides && Object.hasOwn(overrides, direction)
2014
+ ? overrides[direction]
2015
+ : placement?.focusTargets?.[direction];
2016
+ if (tag === null) return true;
2017
+ if (tag === undefined) {
2018
+ if (!placement) return false;
2019
+ const target = directionalFocusTarget(
2020
+ placement.global,
2021
+ direction,
2022
+ placements,
2023
+ (candidate) => candidate !== id && options.input?.isTargetEnabled(candidate) === true,
2024
+ );
2025
+ if (!target) return false;
2026
+ host.requestFocus(target, undefined, undefined, "directional");
2027
+ return true;
2028
+ }
2029
+ const target = placedTags.get(tag);
2030
+ if (!target || !options.input?.isTargetEnabled(target)) return false;
2031
+ if (target !== id) host.requestFocus(target, undefined, undefined, "directional");
2032
+ return true;
2033
+ });
2034
+ } catch (error) {
2035
+ releaseInput?.();
2036
+ releaseNavigation?.();
2037
+ releaseEnvironment();
2038
+ throw error;
2039
+ }
2040
+ const syncActivity = () => {
2041
+ const active = systemAllowsInput();
2042
+ if (!active) admittedFocusRequest = ++focusRequest;
2043
+ options.input?.setActive(active);
2044
+ };
2045
+ syncActivity();
2046
+ const releaseActivity = options.system?.subscribe((event) => {
2047
+ if (event.type === "appState") syncActivity();
2048
+ });
2049
+ return {
2050
+ render(element: ReactNode) {
2051
+ root.render(createElement(NativeHostContext.Provider, { value: host }, element));
2052
+ },
2053
+ runSync: root.runSync,
2054
+ flush: root.flush,
2055
+ refreshNative: root.refreshNative,
2056
+ whenCommitted: whenNativeCommitted,
2057
+ portal: root.portal,
2058
+ unmount() {
2059
+ if (unmounting || (retired && pendingCleanup.size === 0)) return;
2060
+ unmounting = true;
2061
+ const failures: unknown[] = [];
2062
+ const attempt = (work: () => void, retain = true) => {
2063
+ try {
2064
+ work();
2065
+ pendingCleanup.delete(work);
2066
+ } catch (error) {
2067
+ failures.push(error);
2068
+ if (retain) pendingCleanup.add(work);
2069
+ }
2070
+ };
2071
+ try {
2072
+ if (!retired) {
2073
+ // Revoke host authority before React cleanup can reenter retirement.
2074
+ // The renderer owns its one unmount attempt; provider/resource cleanup
2075
+ // remains independently retryable if that attempt reports an error.
2076
+ retired = true;
2077
+ publication++;
2078
+ admittedFocusRequest = ++focusRequest;
2079
+ rasterGeneration++;
2080
+ attempt(() => root.unmount(), false);
2081
+ if (releaseInput) pendingCleanup.add(releaseInput);
2082
+ if (releaseNavigation) pendingCleanup.add(releaseNavigation);
2083
+ if (releaseActivity) pendingCleanup.add(releaseActivity);
2084
+ pendingCleanup.add(releaseEnvironment);
2085
+ placements.clear();
2086
+ layoutCache = undefined;
2087
+ placedTags.clear();
2088
+ focusOverrides.clear();
2089
+ opacityOverrides.clear();
2090
+ dimensionOverrides.clear();
2091
+ presentationOverrides.clear();
2092
+ declarativePresentation.clear();
2093
+ declarativeStyles.clear();
2094
+ deliveredLayouts.clear();
2095
+ liveSpeech.clear();
2096
+ lastFocusSpeech = undefined;
2097
+ pendingCleanup.add(() => options.text.dispose?.());
2098
+ pendingCleanup.add(() => {
2099
+ const errors: unknown[] = [];
2100
+ for (const lease of new Set([...committedRasters, ...preparingRasters])) {
2101
+ try {
2102
+ lease.release();
2103
+ committedRasters.delete(lease);
2104
+ preparingRasters.delete(lease);
2105
+ } catch (error) {
2106
+ errors.push(error);
2107
+ }
2108
+ }
2109
+ if (errors.length) throw errors[0];
2110
+ });
2111
+ pendingCleanup.add(() => options.textRaster?.dispose());
2112
+ }
2113
+ // One failing owner cannot prevent another owner from retiring. Only
2114
+ // failed actions remain for a later unmount() call; successful cleanup
2115
+ // is never replayed, including during reentrant provider callbacks.
2116
+ for (const work of [...pendingCleanup]) attempt(work);
2117
+ } finally {
2118
+ unmounting = false;
2119
+ }
2120
+ if (failures.length) throw failures[0];
2121
+ },
2122
+ get mounted() {
2123
+ return root.mounted;
2124
+ },
2125
+ };
2126
+ }