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,231 @@
1
+ import { useCallback, useLayoutEffect, useRef } from "react";
2
+ import { useNativeHost } from "./nativeHostContext";
3
+ import { RokuHostError } from "../scene/sceneGraph.types";
4
+
5
+ export interface ViewToken<T = unknown> {
6
+ readonly item: T;
7
+ readonly key: string;
8
+ readonly index: number;
9
+ readonly isViewable: boolean;
10
+ }
11
+ export interface ViewabilityConfig {
12
+ readonly minimumViewTime?: number;
13
+ readonly viewAreaCoveragePercentThreshold?: number;
14
+ readonly itemVisiblePercentThreshold?: number;
15
+ readonly waitForInteraction?: boolean;
16
+ }
17
+ export interface ViewabilityInfo<T> {
18
+ readonly viewableItems: ViewToken<T>[];
19
+ readonly changed: ViewToken<T>[];
20
+ }
21
+ interface Frame {
22
+ readonly offset: number;
23
+ readonly alignmentLength: number;
24
+ readonly measured: boolean;
25
+ }
26
+ export interface ViewabilitySnapshot<T> {
27
+ readonly data: readonly T[];
28
+ readonly keys: readonly string[];
29
+ readonly frames: readonly Frame[];
30
+ readonly first: number;
31
+ readonly last: number;
32
+ readonly offset: number;
33
+ readonly viewport: number;
34
+ readonly leading: number;
35
+ }
36
+
37
+ /** Validate the bounded public config and preserve undefined-vs-authored identity
38
+ * for the same-value configuration invariant used by the pinned FlatList. */
39
+ export function viewabilityConfigIdentity(config: ViewabilityConfig | undefined): string {
40
+ if (config === undefined) return "default";
41
+ const area = config?.viewAreaCoveragePercentThreshold,
42
+ item = config?.itemVisiblePercentThreshold,
43
+ delay = config?.minimumViewTime;
44
+ if (
45
+ config == null ||
46
+ (area != null) === (item != null) ||
47
+ !Number.isFinite(area ?? item) ||
48
+ (area ?? item)! < 0 ||
49
+ (area ?? item)! > 100 ||
50
+ (delay !== undefined && (!Number.isFinite(delay) || delay < 0 || delay > 0x7fffffff)) ||
51
+ (config.waitForInteraction !== undefined && typeof config.waitForInteraction !== "boolean")
52
+ )
53
+ throw new RokuHostError(
54
+ "C05_LIST_VIEWABILITY_CONFIG",
55
+ "Viewability requires exactly one finite 0–100 threshold and an optional finite nonnegative timer delay",
56
+ );
57
+ return JSON.stringify([
58
+ area ?? null,
59
+ item ?? null,
60
+ delay ?? null,
61
+ config.waitForInteraction ?? null,
62
+ ]);
63
+ }
64
+
65
+ /** Pure geometry follows the pinned ViewabilityHelper's integer pixel and
66
+ * fully-visible rules. Only known metrics in the retained row range are read. */
67
+ export function computeViewableRows<T>(
68
+ snapshot: ViewabilitySnapshot<T>,
69
+ config: ViewabilityConfig,
70
+ ) {
71
+ const result: number[] = [],
72
+ area = config.viewAreaCoveragePercentThreshold != null,
73
+ threshold = (
74
+ area ? config.viewAreaCoveragePercentThreshold : config.itemVisiblePercentThreshold
75
+ )!;
76
+ for (let index = snapshot.first; index < snapshot.last; index++) {
77
+ const frame = snapshot.frames[index];
78
+ if (!frame?.measured) continue;
79
+ const top = Math.floor(snapshot.leading + frame.offset - snapshot.offset),
80
+ bottom = Math.floor(top + frame.alignmentLength);
81
+ if (top >= snapshot.viewport || bottom <= 0) continue;
82
+ const entire = top >= 0 && bottom <= snapshot.viewport && bottom > top,
83
+ pixels = Math.max(0, Math.min(bottom, snapshot.viewport) - Math.max(top, 0)),
84
+ percentage = (100 * pixels) / (area ? snapshot.viewport : frame.alignmentLength);
85
+ if (entire || percentage >= threshold) result.push(index);
86
+ }
87
+ return result;
88
+ }
89
+
90
+ /** A mounted collection owns every delayed set. Data/extraData replacement
91
+ * retires its pending sets, while published key identity survives replacement.
92
+ * Within a generation, timers use the pinned captured-set/current-index filter;
93
+ * they do not promise uninterrupted dwell time. */
94
+ export class ViewabilityTracker<T> {
95
+ readonly config: ViewabilityConfig;
96
+ private interacted = false;
97
+ private indices: readonly number[] = [];
98
+ private published = new Map<string, ViewToken<T>>();
99
+ private timers = new Set<ReturnType<typeof setTimeout>>();
100
+ private data: readonly T[] | undefined;
101
+ private extraData: unknown;
102
+ constructor(config: ViewabilityConfig | undefined) {
103
+ this.config = Object.freeze({ ...(config ?? { viewAreaCoveragePercentThreshold: 0 }) });
104
+ }
105
+ recordInteraction() {
106
+ this.interacted = true;
107
+ }
108
+ replaceData(data: readonly T[], extraData: unknown) {
109
+ if (this.data === data && this.extraData === extraData) return;
110
+ this.cancelTimers();
111
+ this.indices = [];
112
+ this.data = data;
113
+ this.extraData = extraData;
114
+ }
115
+ update(snapshot: ViewabilitySnapshot<T>, callback: (info: ViewabilityInfo<T>) => void) {
116
+ if (
117
+ (this.config.waitForInteraction && !this.interacted) ||
118
+ snapshot.data.length === 0 ||
119
+ !snapshot.frames[0]?.measured
120
+ )
121
+ return;
122
+ const indices = computeViewableRows(snapshot, this.config);
123
+ if (
124
+ indices.length === this.indices.length &&
125
+ indices.every((value, i) => value === this.indices[i])
126
+ )
127
+ return;
128
+ this.indices = indices;
129
+ const publish = () => {
130
+ const current = new Set(this.indices),
131
+ next = new Map<string, ViewToken<T>>();
132
+ for (const index of indices)
133
+ if (current.has(index)) {
134
+ const token = {
135
+ item: snapshot.data[index],
136
+ key: snapshot.keys[index],
137
+ index,
138
+ isViewable: true,
139
+ };
140
+ next.set(token.key, token);
141
+ }
142
+ const changed: ViewToken<T>[] = [];
143
+ for (const [key, token] of next) if (!this.published.has(key)) changed.push(token);
144
+ for (const [key, token] of this.published)
145
+ if (!next.has(key)) changed.push({ ...token, isViewable: false });
146
+ if (changed.length) {
147
+ this.published = next;
148
+ const info = { viewableItems: [...next.values()], changed, viewabilityConfig: this.config };
149
+ callback(info);
150
+ }
151
+ };
152
+ if (this.config.minimumViewTime) {
153
+ const timer = setTimeout(() => {
154
+ this.timers.delete(timer);
155
+ publish();
156
+ }, this.config.minimumViewTime);
157
+ this.timers.add(timer);
158
+ } else publish();
159
+ }
160
+ private cancelTimers() {
161
+ for (const timer of this.timers) clearTimeout(timer);
162
+ this.timers.clear();
163
+ }
164
+ dispose() {
165
+ this.cancelTimers();
166
+ this.indices = [];
167
+ this.published.clear();
168
+ this.interacted = false;
169
+ this.data = undefined;
170
+ this.extraData = undefined;
171
+ }
172
+ }
173
+
174
+ export function useCollectionViewability<T>(
175
+ config: ViewabilityConfig | undefined,
176
+ callback: ((info: ViewabilityInfo<T>) => void) | undefined,
177
+ extraData: unknown,
178
+ snapshot: ViewabilitySnapshot<T>,
179
+ ready: () => boolean,
180
+ ) {
181
+ const host = useNativeHost(),
182
+ tracker = useRef<ViewabilityTracker<T> | null>(null),
183
+ current = useRef<{
184
+ snapshot: ViewabilitySnapshot<T>;
185
+ callback: typeof callback;
186
+ ready: typeof ready;
187
+ } | null>(null),
188
+ live = useRef(false),
189
+ revision = useRef(0);
190
+ if (tracker.current == null) tracker.current = new ViewabilityTracker<T>(config);
191
+ const owner = tracker.current;
192
+ const refresh = useCallback(() => {
193
+ const request = ++revision.current;
194
+ void host.whenCommitted().then(
195
+ () => {
196
+ const committed = current.current;
197
+ if (
198
+ !live.current ||
199
+ !host.active ||
200
+ request !== revision.current ||
201
+ !committed?.callback ||
202
+ !committed.ready()
203
+ )
204
+ return;
205
+ owner.update(committed.snapshot, (info) => {
206
+ if (live.current && host.active) current.current?.callback?.(info);
207
+ });
208
+ },
209
+ () => {},
210
+ );
211
+ }, [host, owner]);
212
+ useLayoutEffect(() => {
213
+ live.current = true;
214
+ return () => {
215
+ live.current = false;
216
+ current.current = null;
217
+ revision.current++;
218
+ owner.dispose();
219
+ };
220
+ }, [owner]);
221
+ useLayoutEffect(() => {
222
+ current.current = { snapshot, callback, ready };
223
+ owner.replaceData(snapshot.data, extraData);
224
+ if (callback) refresh();
225
+ });
226
+ return useCallback(() => {
227
+ if (!live.current || !host.active) return;
228
+ owner.recordInteraction();
229
+ refresh();
230
+ }, [host, owner, refresh]);
231
+ }
@@ -0,0 +1,85 @@
1
+ import type { NativePlacement } from "./nativeHostContext";
2
+ import type { NativeViewHandle } from "./nativeViewHandle";
3
+
4
+ /** Focus observations use committed host ancestry, including clipping/portals.
5
+ * Targets are the measurable host instances used by current React Native. */
6
+ export interface NativeFocusEvent {
7
+ readonly target: NativeViewHandle;
8
+ readonly currentTarget: NativeViewHandle;
9
+ readonly nativeEvent: { readonly target: number | undefined; readonly timestamp: number };
10
+ readonly type: "focus" | "blur";
11
+ readonly timeStamp: number;
12
+ readonly bubbles: true;
13
+ readonly cancelable: false;
14
+ readonly defaultPrevented: boolean;
15
+ stopPropagation(): void;
16
+ isPropagationStopped(): boolean;
17
+ preventDefault(): void;
18
+ isDefaultPrevented(): boolean;
19
+ persist(): void;
20
+ }
21
+
22
+ export interface NativeFocusHandlers {
23
+ readonly onFocus?: (event: NativeFocusEvent) => void;
24
+ readonly onFocusCapture?: (event: NativeFocusEvent) => void;
25
+ readonly onBlur?: (event: NativeFocusEvent) => void;
26
+ readonly onBlurCapture?: (event: NativeFocusEvent) => void;
27
+ }
28
+
29
+ export type NativeFocusBinding = NativeFocusHandlers | (() => NativeFocusHandlers);
30
+
31
+ export function dispatchNativeFocus(
32
+ placements: ReadonlyMap<string, NativePlacement>,
33
+ id: string,
34
+ focused: boolean,
35
+ active: () => boolean,
36
+ ): void {
37
+ const target = placements.get(id);
38
+ if (!target?.view) return;
39
+ const path: { placement: NativePlacement; handlers: NativeFocusHandlers | undefined }[] = [],
40
+ seen = new Set<NativePlacement>();
41
+ let node: NativePlacement | undefined = target;
42
+ while (node && !seen.has(node)) {
43
+ const binding = node.focusEvents;
44
+ // Snapshot the committed handlers before capture starts. A reentrant commit
45
+ // must not replace a callback on the currently dispatching ancestry.
46
+ path.push({ placement: node, handlers: typeof binding === "function" ? binding() : binding });
47
+ seen.add(node);
48
+ node = node.parentID !== undefined ? placements.get(node.parentID) : undefined;
49
+ }
50
+ let stopped = false,
51
+ prevented = false;
52
+ const timestamp = Date.now();
53
+ const invoke = (
54
+ { placement: current, handlers }: (typeof path)[number],
55
+ key: keyof NativeFocusHandlers,
56
+ ) => {
57
+ if (stopped || !active() || !current.view) return;
58
+ const handler = handlers?.[key];
59
+ if (!handler) return;
60
+ handler({
61
+ target: target.view!,
62
+ currentTarget: current.view,
63
+ nativeEvent: { target: target.nativeTag, timestamp },
64
+ type: focused ? "focus" : "blur",
65
+ timeStamp: timestamp,
66
+ bubbles: true,
67
+ cancelable: false,
68
+ get defaultPrevented() {
69
+ return prevented;
70
+ },
71
+ stopPropagation() {
72
+ stopped = true;
73
+ },
74
+ isPropagationStopped: () => stopped,
75
+ preventDefault() {
76
+ prevented = true;
77
+ },
78
+ isDefaultPrevented: () => prevented,
79
+ persist() {},
80
+ });
81
+ };
82
+ for (const current of [...path].reverse())
83
+ invoke(current, focused ? "onFocusCapture" : "onBlurCapture");
84
+ for (const current of path) invoke(current, focused ? "onFocus" : "onBlur");
85
+ }
@@ -0,0 +1,247 @@
1
+ import {
2
+ createElement,
3
+ forwardRef,
4
+ useInsertionEffect,
5
+ useLayoutEffect,
6
+ useMemo,
7
+ useRef,
8
+ } from "react";
9
+ import { RokuHostError } from "../scene/sceneGraph.types";
10
+ import {
11
+ generatedSceneFields,
12
+ plainImageLayout,
13
+ type SceneElementProps,
14
+ } from "../renderer/SceneRoot";
15
+ import { background, useElement, View, type NativeElementProps } from "./primitives";
16
+ import { useNativeHost } from "./nativeHostContext";
17
+ import { hasRoundedCorners, uniformBorder } from "../graphics/surfaces";
18
+ import type { NativeViewHandle } from "./nativeViewHandle";
19
+
20
+ export interface ImageSource {
21
+ readonly uri: string;
22
+ readonly width?: number;
23
+ readonly height?: number;
24
+ readonly headers?: Readonly<Record<string, string>>;
25
+ }
26
+ export interface ImageLoadEvent {
27
+ readonly source: {
28
+ readonly url: string;
29
+ readonly width: number;
30
+ readonly height: number;
31
+ };
32
+ }
33
+ export interface ImageProps extends NativeElementProps {
34
+ readonly source?: ImageSource | string | null;
35
+ readonly contentFit?: "cover" | "contain" | "fill" | "none" | "scale-down";
36
+ readonly resizeMode?: "cover" | "contain" | "stretch" | "center" | "repeat";
37
+ readonly contentPosition?: string | object;
38
+ readonly blurRadius?: number;
39
+ readonly transition?: number;
40
+ readonly recyclingKey?: string | null;
41
+ readonly placeholder?: ImageSource | string;
42
+ readonly placeholderContentFit?: string;
43
+ readonly cachePolicy?: "none" | "disk" | "memory" | "memory-disk";
44
+ readonly priority?: "low" | "normal" | "high";
45
+ readonly onLoadStart?: () => void;
46
+ readonly onLoad?: (event: ImageLoadEvent) => void;
47
+ readonly onDisplay?: () => void;
48
+ readonly onLoadEnd?: () => void;
49
+ readonly onError?: (event: { readonly error: string }) => void;
50
+ }
51
+ const packagedImages = new Map<string, string>();
52
+ /** The bundler preserves source values for schema validation; only the image port resolves assets. */
53
+ export function registerPackagedImage(source: string, target: string): string {
54
+ if (
55
+ !source.startsWith("data:image/") ||
56
+ !/^pkg:\/images\/asset-[a-f0-9]{24}\.(png|jpe?g)$/.test(target)
57
+ )
58
+ throw new RokuHostError("C08_IMAGE_ASSET", "Invalid packaged raster registration");
59
+ packagedImages.set(source, target);
60
+ return source;
61
+ }
62
+ function uri(source: ImageProps["source"]): string {
63
+ if (source == null) return "";
64
+ if (typeof source === "string") return packagedImages.get(source) ?? source;
65
+ if (typeof source === "object" && typeof source.uri === "string") {
66
+ if (source.headers && Object.keys(source.headers).length)
67
+ throw new RokuHostError(
68
+ "C08_IMAGE_HEADERS",
69
+ "Authenticated image headers require the native networking adapter",
70
+ );
71
+ return packagedImages.get(source.uri) ?? source.uri;
72
+ }
73
+ throw new RokuHostError(
74
+ "C08_IMAGE_ASSET",
75
+ "Image sources require a resolved URI; numeric Metro asset IDs are not valid in the Roku bundle",
76
+ );
77
+ }
78
+ const modes = {
79
+ cover: "scaleToZoom",
80
+ contain: "scaleToFit",
81
+ fill: "scaleToFill",
82
+ none: "noScale",
83
+ "scale-down": "limitSize",
84
+ } as const;
85
+
86
+ type ImageLoadSession = Readonly<
87
+ Record<"bitmapWidth" | "bitmapHeight" | "loadStatus", (value: unknown) => void>
88
+ >;
89
+
90
+ function createImageLoadSession(
91
+ source: string,
92
+ currentProps: (session: ImageLoadSession) => ImageProps | undefined,
93
+ ): ImageLoadSession {
94
+ let width = 0,
95
+ height = 0,
96
+ ready = false,
97
+ loaded = false,
98
+ failed = false,
99
+ started = false;
100
+ const finish = (props: ImageProps) => {
101
+ if (!ready || loaded || failed || !(width > 0 && height > 0) || !currentProps(session)) return;
102
+ loaded = true;
103
+ props.onLoad?.({ source: { url: source, width, height } });
104
+ if (!currentProps(session)) return;
105
+ // Poster readiness is a loaded renderable raster, not a physical frame acknowledgement.
106
+ props.onDisplay?.();
107
+ if (!currentProps(session)) return;
108
+ props.onLoadEnd?.();
109
+ };
110
+ const session: ImageLoadSession = Object.freeze({
111
+ bitmapWidth(value) {
112
+ const props = currentProps(session);
113
+ if (!props || loaded || failed) return;
114
+ width = Number(value);
115
+ finish(props);
116
+ },
117
+ bitmapHeight(value) {
118
+ const props = currentProps(session);
119
+ if (!props || loaded || failed) return;
120
+ height = Number(value);
121
+ finish(props);
122
+ },
123
+ loadStatus(value) {
124
+ const props = currentProps(session);
125
+ if (!props || loaded || failed) return;
126
+ if (value === "loading" && !started) {
127
+ started = true;
128
+ props.onLoadStart?.();
129
+ } else if (value === "ready") {
130
+ ready = true;
131
+ finish(props);
132
+ } else if (value === "failed") {
133
+ failed = true;
134
+ props.onError?.({ error: `Native Poster failed to load ${source}` });
135
+ if (currentProps(session)) props.onLoadEnd?.();
136
+ }
137
+ },
138
+ });
139
+ return session;
140
+ }
141
+
142
+ const ImageComponent = forwardRef<NativeViewHandle, ImageProps>((props, ref) => {
143
+ const element = useElement(props, ref),
144
+ host = useNativeHost(),
145
+ source = uri(props.source),
146
+ placeholder = uri(props.placeholder);
147
+ const rounded = hasRoundedCorners(element.style),
148
+ border = rounded ? uniformBorder(element.style) : 0;
149
+ if (props.blurRadius)
150
+ throw new RokuHostError("C08_IMAGE_BLUR", "Image blur requires an admitted native shader");
151
+ if (props.transition)
152
+ throw new RokuHostError(
153
+ "C08_IMAGE_TRANSITION",
154
+ "Image transitions are owned by the shared artwork animation executor",
155
+ );
156
+ if (
157
+ props.contentPosition != null &&
158
+ props.contentPosition !== "center" &&
159
+ props.contentPosition !== "50% 50%"
160
+ )
161
+ throw new RokuHostError(
162
+ "C08_IMAGE_POSITION",
163
+ "Noncentral image positioning requires native bitmap geometry",
164
+ );
165
+ const fit =
166
+ props.contentFit ??
167
+ (props.resizeMode === "stretch"
168
+ ? "fill"
169
+ : props.resizeMode === "center"
170
+ ? "none"
171
+ : (props.resizeMode ?? "cover"));
172
+ if (!(fit in modes)) throw new RokuHostError("C08_IMAGE_FIT", `Image fit ${fit} is unavailable`);
173
+ const resourceKey = JSON.stringify([props.recyclingKey ?? "", source]);
174
+ const live = useRef(false);
175
+ useLayoutEffect(() => {
176
+ live.current = true;
177
+ return () => {
178
+ live.current = false;
179
+ };
180
+ }, []);
181
+ const committed = useRef<{ props: ImageProps; session: ImageLoadSession } | null>(null);
182
+ // The Poster key and event lifetime change together. Pending React renders
183
+ // keep the prior mounted Poster and its committed callbacks authoritative.
184
+ const session = useMemo(
185
+ () =>
186
+ createImageLoadSession(source, (current) =>
187
+ live.current && host.active && committed.current?.session === current
188
+ ? committed.current.props
189
+ : undefined,
190
+ ),
191
+ [host, resourceKey, source],
192
+ );
193
+ useInsertionEffect(() => {
194
+ committed.current = { props, session };
195
+ }, [props, session]);
196
+ return createElement(
197
+ "group",
198
+ { fields: element.fields, layout: element.layout },
199
+ ...background(element.style, host.graphics),
200
+ source
201
+ ? createElement(
202
+ "poster",
203
+ {
204
+ key: resourceKey,
205
+ fields: generatedSceneFields({
206
+ loadDisplayMode: modes[fit as keyof typeof modes],
207
+ loadingBitmapUri: placeholder,
208
+ shaderCompatible: rounded,
209
+ uri: source,
210
+ }),
211
+ layout: rounded ? { decoration: "surface", border } : plainImageLayout,
212
+ events: session,
213
+ } satisfies SceneElementProps & { key: string },
214
+ rounded
215
+ ? createElement("effect", {
216
+ fields: { borderWidth: 0 },
217
+ layout: {
218
+ resource: true,
219
+ radiusStyle: element.style,
220
+ insetBorder: border,
221
+ },
222
+ })
223
+ : null,
224
+ )
225
+ : null,
226
+ );
227
+ });
228
+ ImageComponent.displayName = "RokuImage";
229
+ export const Image = Object.assign(ImageComponent, {
230
+ // No positive cache/prefetch claim is made without a corresponding native capability.
231
+ prefetch: async (_urls: string | string[], _policy?: unknown): Promise<boolean> => false,
232
+ clearMemoryCache: async (): Promise<boolean> => false,
233
+ clearDiskCache: async (): Promise<boolean> => false,
234
+ });
235
+ export const ImageBackground = forwardRef<NativeViewHandle, ImageProps>((props, ref) =>
236
+ createElement(
237
+ View,
238
+ { style: props.style, ref },
239
+ createElement(Image, {
240
+ ...props,
241
+ children: undefined,
242
+ style: { position: "absolute", top: 0, left: 0, right: 0, bottom: 0 },
243
+ }),
244
+ props.children,
245
+ ),
246
+ );
247
+ ImageBackground.displayName = "RokuImageBackground";
@@ -0,0 +1,54 @@
1
+ export { AppRegistry } from "../application/AppRegistry";
2
+ export { View, Text, Pressable } from "./primitives";
3
+ export { StyleSheet } from "./styleSheet";
4
+ export type { NativeStyle } from "./styleSheet";
5
+ export type { NativeViewHandle } from "./nativeViewHandle";
6
+ export { findNodeHandle } from "./nativeViewHandle";
7
+ export {
8
+ UIManager,
9
+ requireNativeComponent,
10
+ NativeEventEmitter,
11
+ DeviceEventEmitter,
12
+ Keyboard,
13
+ TurboModuleRegistry,
14
+ Share,
15
+ } from "./nativeModules";
16
+ export { InteractionManager } from "./interactionManager";
17
+ export { Appearance, AppState, AccessibilityInfo } from "./environment";
18
+ export { SafeAreaView } from "./safeArea";
19
+ export { Image, ImageBackground } from "./image";
20
+ export { ScrollView } from "./scrollView";
21
+ export { FlatList } from "./flatList";
22
+ export type {
23
+ FlatListProps,
24
+ FlatListHandle,
25
+ FlatListRenderItemInfo,
26
+ FlatListSeparators,
27
+ ViewToken,
28
+ ViewabilityConfig,
29
+ ViewabilityInfo,
30
+ } from "./flatList";
31
+ export { Animated, Easing } from "../animation/legacyAnimated";
32
+ export { PanResponder } from "./panResponder";
33
+ export { ActivityIndicator } from "./activityIndicator";
34
+ export { TextInput } from "./textInput";
35
+ export { Modal } from "./modal";
36
+ export {
37
+ VirtualizedList,
38
+ Switch,
39
+ TouchableHighlight,
40
+ TouchableOpacity,
41
+ TouchableWithoutFeedback,
42
+ StatusBar,
43
+ KeyboardAvoidingView,
44
+ } from "./unsupported";
45
+ export {
46
+ Platform,
47
+ NativeModules,
48
+ Dimensions,
49
+ PixelRatio,
50
+ BackHandler,
51
+ TVEventHandler,
52
+ useTVEventHandler,
53
+ useWindowDimensions,
54
+ } from "./environment";
@@ -0,0 +1,76 @@
1
+ type Task = (() => void) | { gen(): Promise<unknown> };
2
+ let sequence = 0,
3
+ timer: ReturnType<typeof setTimeout> | undefined,
4
+ flushing = false;
5
+ const interactions = new Set<number>();
6
+ const queue: Array<{
7
+ task?: Task;
8
+ resolve(): void;
9
+ reject(error: unknown): void;
10
+ cancelled: boolean;
11
+ }> = [];
12
+ function schedule() {
13
+ if (timer != null || flushing || interactions.size || !queue.length) return;
14
+ timer = setTimeout(() => {
15
+ timer = undefined;
16
+ void flush();
17
+ }, 0);
18
+ }
19
+ async function flush() {
20
+ if (interactions.size) return;
21
+ flushing = true;
22
+ try {
23
+ while (!interactions.size && queue.length) {
24
+ const next = queue.shift()!;
25
+ if (next.cancelled) continue;
26
+ try {
27
+ if (typeof next.task === "function") next.task();
28
+ else if (next.task) await next.task.gen();
29
+ next.resolve();
30
+ } catch (error) {
31
+ next.reject(error);
32
+ }
33
+ }
34
+ } finally {
35
+ flushing = false;
36
+ schedule();
37
+ }
38
+ }
39
+ /** Real deferred JS work with explicit interaction leases and cancellation. */
40
+ export const InteractionManager = Object.freeze({
41
+ createInteractionHandle(): number {
42
+ const handle = ++sequence;
43
+ interactions.add(handle);
44
+ return handle;
45
+ },
46
+ clearInteractionHandle(handle: number): void {
47
+ interactions.delete(handle);
48
+ schedule();
49
+ },
50
+ runAfterInteractions(task?: Task) {
51
+ let entry: (typeof queue)[number];
52
+ const promise = new Promise<void>((resolve, reject) => {
53
+ entry = { task, resolve, reject, cancelled: false };
54
+ queue.push(entry);
55
+ schedule();
56
+ });
57
+ return {
58
+ then: promise.then.bind(promise),
59
+ done: (resolve?: () => void, reject?: (error: unknown) => void) => {
60
+ void promise.then(resolve, reject);
61
+ },
62
+ cancel() {
63
+ if (!entry.cancelled) {
64
+ entry.cancelled = true;
65
+ const index = queue.indexOf(entry);
66
+ if (index >= 0) queue.splice(index, 1);
67
+ entry.resolve();
68
+ }
69
+ if (!queue.length && timer != null) {
70
+ clearTimeout(timer);
71
+ timer = undefined;
72
+ }
73
+ },
74
+ };
75
+ },
76
+ });