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,1001 @@
1
+ import {
2
+ createElement,
3
+ forwardRef,
4
+ Fragment,
5
+ isValidElement,
6
+ memo,
7
+ useCallback,
8
+ useImperativeHandle,
9
+ useLayoutEffect,
10
+ useMemo,
11
+ useRef,
12
+ useState,
13
+ type ComponentType,
14
+ type ForwardedRef,
15
+ type ReactElement,
16
+ type RefAttributes,
17
+ } from "react";
18
+ import { View, type NativeElementProps } from "./primitives";
19
+ import {
20
+ ScrollView,
21
+ type ScrollEvent,
22
+ type ScrollViewHandle,
23
+ type ScrollViewProps,
24
+ } from "./scrollView";
25
+ import { flattenStyle, type NativeStyle } from "./styleSheet";
26
+ import { useNativeHost } from "./nativeHostContext";
27
+ import { RokuHostError } from "../scene/sceneGraph.types";
28
+ import { InteractionManager } from "./interactionManager";
29
+ import {
30
+ useCollectionViewability,
31
+ viewabilityConfigIdentity,
32
+ type ViewabilityConfig,
33
+ type ViewabilityInfo,
34
+ type ViewToken,
35
+ } from "./flatListViewability";
36
+ export type { ViewabilityConfig, ViewabilityInfo, ViewToken } from "./flatListViewability";
37
+ type Boundary = ReactElement | ComponentType<Record<string, never>> | null;
38
+ export interface FlatListSeparators {
39
+ highlight(): void;
40
+ unhighlight(): void;
41
+ updateProps(select: "leading" | "trailing", newProps: Readonly<Record<string, unknown>>): void;
42
+ }
43
+ export interface FlatListRenderItemInfo<T> {
44
+ readonly item: T;
45
+ readonly index: number;
46
+ readonly separators: FlatListSeparators;
47
+ }
48
+ export interface FlatListProps<T> extends NativeElementProps {
49
+ readonly data: readonly T[];
50
+ readonly keyExtractor?: (item: T, index: number) => string;
51
+ readonly renderItem: (info: FlatListRenderItemInfo<T>) => ReactElement | null;
52
+ readonly getItemLayout?: (
53
+ data: readonly T[] | null | undefined,
54
+ index: number,
55
+ ) => { length: number; offset: number; index?: number };
56
+ readonly ListHeaderComponent?: Boundary;
57
+ readonly ListHeaderComponentStyle?: NativeStyle;
58
+ readonly ListFooterComponent?: Boundary;
59
+ readonly ListFooterComponentStyle?: NativeStyle;
60
+ readonly ListEmptyComponent?: Boundary;
61
+ /** Component props are open, as upstream updateProps supplies consumer-authored fields.
62
+ * leadingItem is the original item, or an entire row array with numColumns > 1. */
63
+ readonly ItemSeparatorComponent?: ReactElement | ComponentType<any> | null;
64
+ /** This renderer rerenders the retained window when any prop changes. */
65
+ readonly extraData?: unknown;
66
+ readonly viewabilityConfig?: ViewabilityConfig;
67
+ readonly onViewableItemsChanged?: (info: ViewabilityInfo<T>) => void;
68
+ /** Native groups in the retained React window are always preserved. */
69
+ readonly removeClippedSubviews?: boolean;
70
+ readonly contentContainerStyle?: NativeStyle;
71
+ readonly initialNumToRender?: number;
72
+ readonly initialScrollIndex?: number;
73
+ readonly windowSize?: number;
74
+ readonly maxToRenderPerBatch?: number;
75
+ readonly updateCellsBatchingPeriod?: number;
76
+ readonly renderScrollComponent?: (props: ScrollViewProps) => ReactElement;
77
+ readonly showsVerticalScrollIndicator?: boolean;
78
+ readonly showsHorizontalScrollIndicator?: boolean;
79
+ readonly scrollEventThrottle?: number;
80
+ readonly onScroll?: (event: ScrollEvent) => void;
81
+ readonly onContentSizeChange?: (width: number, height: number) => void;
82
+ readonly onScrollToIndexFailed?: (info: {
83
+ averageItemLength: number;
84
+ index: number;
85
+ highestMeasuredFrameIndex: number;
86
+ }) => void;
87
+ readonly maintainVisibleContentPosition?: { minIndexForVisible?: number };
88
+ readonly horizontal?: boolean;
89
+ /** Vertical rows of equal-height items; geometry and scroll indices address rows. */
90
+ readonly numColumns?: number;
91
+ readonly columnWrapperStyle?: NativeStyle;
92
+ }
93
+ export interface FlatListHandle {
94
+ scrollToIndex(options: {
95
+ index: number;
96
+ animated?: boolean;
97
+ viewOffset?: number;
98
+ viewPosition?: number;
99
+ }): void;
100
+ scrollToOffset(options: { offset: number; animated?: boolean }): void;
101
+ scrollToEnd(options?: { animated?: boolean }): void;
102
+ getNativeScrollRef(): ScrollViewHandle | null;
103
+ recordInteraction(): void;
104
+ }
105
+ function boundary(value?: Boundary): ReactElement | null {
106
+ return value == null ? null : isValidElement(value) ? value : createElement(value);
107
+ }
108
+
109
+ function itemKey<T>(item: T, index: number): string {
110
+ if (typeof item === "object" && item !== null) {
111
+ const keyed = item as { key?: unknown; id?: unknown };
112
+ if (keyed.key != null) return String(keyed.key);
113
+ if (keyed.id != null) return String(keyed.id);
114
+ }
115
+ return String(index);
116
+ }
117
+
118
+ interface CollectionWindow {
119
+ readonly first: number;
120
+ readonly last: number;
121
+ }
122
+
123
+ type SeparatorUpdate = (newProps: Readonly<Record<string, unknown>>) => void;
124
+ interface CellProps<T> {
125
+ readonly item: T;
126
+ readonly index: number;
127
+ readonly cellKey: string;
128
+ readonly previousKey?: string;
129
+ readonly horizontal: boolean;
130
+ readonly separator?: FlatListProps<T>["ItemSeparatorComponent"];
131
+ readonly itemRenderer: Pick<FlatListProps<T>, "renderItem">;
132
+ readonly onLayout: NativeElementProps["onLayout"];
133
+ readonly updates: Map<string, SeparatorUpdate>;
134
+ }
135
+
136
+ // A list update from its parent supplies fresh props (including extraData).
137
+ // Internal window and measurement updates can keep the existing item subtree.
138
+ function FlatListItemBody<T>({
139
+ itemRenderer,
140
+ item,
141
+ index,
142
+ separators,
143
+ }: Pick<CellProps<T>, "itemRenderer" | "item" | "index"> & { separators: FlatListSeparators }) {
144
+ return itemRenderer.renderItem({ item, index, separators });
145
+ }
146
+ const FlatListItem = memo(FlatListItemBody) as typeof FlatListItemBody;
147
+
148
+ /** Separator state and callback authority belong to one mounted keyed cell.
149
+ * A retired callback cannot target a later cell that reuses the same key. */
150
+ function FlatListCell<T>(props: CellProps<T>) {
151
+ const host = useNativeHost(),
152
+ current = useRef(props),
153
+ live = useRef(false),
154
+ [separatorProps, setSeparatorProps] = useState<Readonly<Record<string, unknown>>>({
155
+ highlighted: false,
156
+ });
157
+ const update = useCallback<SeparatorUpdate>(
158
+ (next) => {
159
+ if (live.current && host.active) setSeparatorProps((previous) => ({ ...previous, ...next }));
160
+ },
161
+ [host],
162
+ );
163
+ useLayoutEffect(() => {
164
+ current.current = props;
165
+ });
166
+ useLayoutEffect(() => {
167
+ live.current = true;
168
+ props.updates.set(props.cellKey, update);
169
+ return () => {
170
+ live.current = false;
171
+ if (props.updates.get(props.cellKey) === update) props.updates.delete(props.cellKey);
172
+ };
173
+ }, [props.updates, props.cellKey, update]);
174
+ const separators = useMemo<FlatListSeparators>(() => {
175
+ const submit = (
176
+ keys: readonly (string | undefined)[],
177
+ next: Readonly<Record<string, unknown>>,
178
+ ) => {
179
+ const owner = current.current;
180
+ if (!live.current || !host.active || owner.updates.get(owner.cellKey) !== update) return;
181
+ host.runSync(() => {
182
+ for (const key of keys) if (key != null) owner.updates.get(key)?.(next);
183
+ });
184
+ };
185
+ return {
186
+ highlight: () =>
187
+ submit([current.current.cellKey, current.current.previousKey], { highlighted: true }),
188
+ unhighlight: () =>
189
+ submit([current.current.cellKey, current.current.previousKey], { highlighted: false }),
190
+ updateProps: (select, next) =>
191
+ submit(
192
+ [select === "leading" ? current.current.previousKey : current.current.cellKey],
193
+ next,
194
+ ),
195
+ };
196
+ }, [host, update]);
197
+ const separator =
198
+ props.separator == null
199
+ ? null
200
+ : isValidElement(props.separator)
201
+ ? props.separator
202
+ : createElement(props.separator, { ...separatorProps, leadingItem: props.item });
203
+ return createElement(
204
+ View,
205
+ {
206
+ style: props.horizontal ? { flexDirection: "row", flexShrink: 0 } : undefined,
207
+ onLayout: props.onLayout,
208
+ },
209
+ createElement(FlatListItem<T>, {
210
+ itemRenderer: props.itemRenderer,
211
+ item: props.item,
212
+ index: props.index,
213
+ separators,
214
+ }),
215
+ separator,
216
+ );
217
+ }
218
+
219
+ /** Visible rows have priority. Grow the remaining retained window in bounded
220
+ * JS batches, without replacing the existing keyed/native rows. Every queued
221
+ * task belongs to one committed data/window generation. */
222
+ function useBatchedWindow(
223
+ target: CollectionWindow,
224
+ visible: CollectionWindow,
225
+ measured: boolean,
226
+ keys: readonly string[],
227
+ batch: number,
228
+ period: number,
229
+ ) {
230
+ const host = useNativeHost();
231
+ const [retained, setRetained] = useState(target);
232
+ const committedKeys = useRef(keys);
233
+ const committedVisible = useRef<CollectionWindow | undefined>(undefined);
234
+ const trimFirst = Math.max(retained.first, target.first);
235
+ const trimLast = Math.min(retained.last, target.last);
236
+ const surplus = trimFirst - retained.first + retained.last - trimLast;
237
+ // A nearby scroll can reuse the mounted window for its visible update. One
238
+ // retiring edge row can go with the next offscreen batch instead of forcing
239
+ // two structural commits. Larger jumps and changed keys use the usual window.
240
+ const sameKeys =
241
+ keys === committedKeys.current ||
242
+ (keys.length === committedKeys.current.length &&
243
+ keys.every((key, index) => key === committedKeys.current[index]));
244
+ const mayDeferTrim = surplus === 1 && retained.last <= keys.length && sameKeys;
245
+ const previous = committedVisible.current;
246
+ const nearby =
247
+ previous &&
248
+ sameKeys &&
249
+ (visible.first !== previous.first || visible.last !== previous.last) &&
250
+ visible.first < trimLast &&
251
+ trimFirst < visible.last;
252
+ // Directional focus can only choose mounted controls. Keep the adjacent
253
+ // rows available when scrolling within the existing window, even if
254
+ // repeated scroll commits postpone the background overscan batch.
255
+ const adjacent = nearby
256
+ ? {
257
+ first: Math.max(target.first, visible.first - 1),
258
+ last: Math.min(target.last, visible.last + 1),
259
+ }
260
+ : visible;
261
+ const window = !measured
262
+ ? target
263
+ : nearby && (adjacent.first < trimFirst || adjacent.last > trimLast)
264
+ ? { first: Math.min(trimFirst, adjacent.first), last: Math.max(trimLast, adjacent.last) }
265
+ : retained.first > visible.first || retained.last < visible.last
266
+ ? visible
267
+ : mayDeferTrim
268
+ ? retained
269
+ : { first: trimFirst, last: trimLast };
270
+ const { first, last } = window;
271
+ useLayoutEffect(() => {
272
+ committedKeys.current = keys;
273
+ committedVisible.current = measured ? visible : undefined;
274
+ });
275
+ useLayoutEffect(() => {
276
+ if (retained.first !== first || retained.last !== last) {
277
+ setRetained({ first, last });
278
+ return;
279
+ }
280
+ if (!measured || (first === target.first && last === target.last)) return;
281
+ let cancelled = false;
282
+ let deferred: ReturnType<typeof InteractionManager.runAfterInteractions> | undefined;
283
+ const timer = setTimeout(() => {
284
+ deferred = InteractionManager.runAfterInteractions(() => {
285
+ if (cancelled || !host.active) return;
286
+ const insideFirst = Math.max(first, target.first);
287
+ const insideLast = Math.min(last, target.last);
288
+ const before = insideFirst - target.first,
289
+ after = target.last - insideLast;
290
+ // Split work across both edges, then use any spare allowance on the
291
+ // unfinished edge. The visible interval can never be removed here.
292
+ const leading = Math.min(before, Math.ceil(batch / 2));
293
+ const trailing = Math.min(after, batch - leading);
294
+ const extra = Math.min(before - leading, batch - leading - trailing);
295
+ host.runSync(() =>
296
+ setRetained({ first: insideFirst - leading - extra, last: insideLast + trailing }),
297
+ );
298
+ });
299
+ }, period);
300
+ return () => {
301
+ cancelled = true;
302
+ clearTimeout(timer);
303
+ deferred?.cancel();
304
+ };
305
+ }, [host, measured, first, last, target.first, target.last, retained, keys, batch, period]);
306
+ return window;
307
+ }
308
+
309
+ type WindowProps<T> = FlatListProps<T> & Pick<CellProps<T>, "itemRenderer">;
310
+
311
+ function FlatListWindow<T>(
312
+ { itemRenderer, ...props }: WindowProps<T>,
313
+ forwardedRef: ForwardedRef<FlatListHandle>,
314
+ ) {
315
+ const horizontal = props.horizontal === true,
316
+ axis = horizontal ? "x" : "y",
317
+ dimension = horizontal ? "width" : "height";
318
+ const host = useNativeHost(),
319
+ scroll = useRef<ScrollViewHandle>(null),
320
+ contentExtent = useRef<number | undefined>(undefined),
321
+ latest = useRef(props);
322
+ latest.current = props;
323
+ const batch = props.maxToRenderPerBatch ?? 10;
324
+ const period = props.updateCellsBatchingPeriod ?? 50;
325
+ if (
326
+ !Number.isSafeInteger(batch) ||
327
+ batch <= 0 ||
328
+ !Number.isFinite(period) ||
329
+ period < 0 ||
330
+ period > 0x7fffffff
331
+ )
332
+ throw new RokuHostError(
333
+ "C05_LIST_BATCH",
334
+ "Collection batches require a positive integer limit and a finite nonnegative timer delay",
335
+ );
336
+ const initialIndex = useRef(props.initialScrollIndex ?? 0).current;
337
+ const initialPending = useRef(initialIndex !== 0);
338
+ if (!Number.isSafeInteger(initialIndex) || initialIndex < 0)
339
+ throw new RokuHostError(
340
+ "C05_LIST_INDEX",
341
+ "An initial collection index must be a nonnegative integer",
342
+ );
343
+ if (
344
+ initialPending.current &&
345
+ (!props.getItemLayout || (props.data.length > 0 && initialIndex >= props.data.length))
346
+ )
347
+ throw new RokuHostError(
348
+ "C05_LIST_INITIAL_LAYOUT",
349
+ "An initial collection index requires declared geometry and an in-range item",
350
+ );
351
+ const anchorMinimum = props.maintainVisibleContentPosition?.minIndexForVisible ?? 0;
352
+ if (!Number.isSafeInteger(anchorMinimum) || anchorMinimum < 0)
353
+ throw new RokuHostError(
354
+ "C05_LIST_ANCHOR",
355
+ "A collection anchor index must be a nonnegative integer",
356
+ );
357
+ const [observedOffset, setOffset] = useState(() =>
358
+ initialPending.current && props.data.length > 0
359
+ ? props.getItemLayout!(props.data, initialIndex).offset -
360
+ props.getItemLayout!(props.data, 0).offset
361
+ : 0,
362
+ ),
363
+ [viewport, setViewport] = useState(host.viewport[dimension]),
364
+ [measuredHeader, setHeader] = useState(0),
365
+ [headerMeasured, setHeaderMeasured] = useState(props.ListHeaderComponent == null),
366
+ [measurementVersion, setMeasurementVersion] = useState(0),
367
+ [endJump, setEndJump] = useState(false);
368
+ const header = props.ListHeaderComponent == null ? 0 : measuredHeader;
369
+ const endGeneration = useRef(0),
370
+ live = useRef(true);
371
+ const [viewportMeasured, setViewportMeasured] = useState(false);
372
+ const measurements = useRef(new Map<string, number>()),
373
+ separatorUpdates = useRef(new Map<string, SeparatorUpdate>()).current,
374
+ firstRows = Math.max(1, Math.floor(props.initialNumToRender ?? 6));
375
+ const anchor = useRef<{
376
+ keys: readonly string[];
377
+ key?: string;
378
+ intra: number;
379
+ minimum: number;
380
+ enabled: boolean;
381
+ } | null>(null);
382
+ const keys = useMemo(
383
+ () =>
384
+ props.data.map((item, index) => props.keyExtractor?.(item, index) ?? itemKey(item, index)),
385
+ [props.data, props.keyExtractor],
386
+ );
387
+ if (new Set(keys).size !== keys.length)
388
+ throw new RokuHostError("C05_LIST_KEY", "Collection keys must be unique");
389
+ const style = flattenStyle(props.contentContainerStyle),
390
+ padding = Number(
391
+ (horizontal
392
+ ? (style?.paddingLeft ?? style?.paddingHorizontal)
393
+ : (style?.paddingTop ?? style?.paddingVertical)) ??
394
+ style?.padding ??
395
+ 0,
396
+ );
397
+ if (!Number.isFinite(padding) || padding < 0)
398
+ throw new RokuHostError(
399
+ "C05_LIST_INSET",
400
+ "Collection leading padding must be finite and nonnegative",
401
+ );
402
+ const layout = useMemo(() => {
403
+ const known = [...measurements.current.values()],
404
+ average = known.length
405
+ ? known.reduce((sum, value) => sum + value, 0) / known.length
406
+ : Math.max(1, host.viewport[dimension] / firstRows);
407
+ const start =
408
+ props.data.length && props.getItemLayout ? props.getItemLayout(props.data, 0).offset : 0;
409
+ let cursor = 0;
410
+ const frames = props.data.map((_item, index) => {
411
+ const declared = props.getItemLayout?.(props.data, index),
412
+ next =
413
+ props.ItemSeparatorComponent && index + 1 < props.data.length
414
+ ? props.getItemLayout?.(props.data, index + 1)
415
+ : undefined,
416
+ measured = measurements.current.get(keys[index]);
417
+ const length =
418
+ (declared && next ? next.offset - declared.offset : declared?.length) ??
419
+ measured ??
420
+ average,
421
+ position = declared ? declared.offset - start : cursor;
422
+ const alignmentLength = declared?.length ?? length;
423
+ if (
424
+ !Number.isFinite(length) ||
425
+ length < 0 ||
426
+ !Number.isFinite(alignmentLength) ||
427
+ alignmentLength < 0 ||
428
+ !Number.isFinite(position) ||
429
+ position < cursor - 0.5
430
+ )
431
+ throw new RokuHostError(
432
+ "C05_LIST_GEOMETRY",
433
+ "Collection geometry must be finite and ordered",
434
+ );
435
+ cursor = position + length;
436
+ return {
437
+ offset: position,
438
+ length,
439
+ alignmentLength,
440
+ measured: declared != null || measured != null,
441
+ };
442
+ });
443
+ return { frames, total: cursor, average };
444
+ }, [
445
+ props.data,
446
+ props.getItemLayout,
447
+ props.ItemSeparatorComponent,
448
+ keys,
449
+ measurementVersion,
450
+ firstRows,
451
+ host,
452
+ dimension,
453
+ ]);
454
+ const previousAnchor = anchor.current,
455
+ anchorFrame =
456
+ !initialPending.current &&
457
+ props.maintainVisibleContentPosition &&
458
+ previousAnchor?.enabled &&
459
+ previousAnchor.key &&
460
+ previousAnchor.keys !== keys &&
461
+ previousAnchor.minimum === anchorMinimum
462
+ ? layout.frames[keys.indexOf(previousAnchor.key)]
463
+ : undefined;
464
+ // Select the new keyed window before reconciliation retires the old one.
465
+ // The layout effect below submits the same offset to the scroll owner.
466
+ const offset = anchorFrame
467
+ ? Math.max(0, header + padding + anchorFrame.offset + previousAnchor!.intra)
468
+ : observedOffset;
469
+ const budget = Math.max(viewport, (viewport * Math.max(0, (props.windowSize ?? 5) - 1)) / 2);
470
+ const contentOffset = offset - header - padding,
471
+ relative = Math.max(0, contentOffset),
472
+ visibleExtentEnd = Math.max(0, contentOffset + viewport),
473
+ start = layout.frames.findIndex(
474
+ (frame) => frame.offset + frame.length >= Math.max(0, relative - budget),
475
+ );
476
+ const desiredFirst = endJump
477
+ ? Math.max(
478
+ 0,
479
+ props.data.length -
480
+ Math.max(firstRows, Math.ceil(viewport / layout.average) * (props.windowSize ?? 5)),
481
+ )
482
+ : !viewportMeasured
483
+ ? Math.min(initialIndex, props.data.length)
484
+ : start < 0
485
+ ? Math.max(0, props.data.length - firstRows)
486
+ : start,
487
+ end = layout.frames.findIndex((frame) => frame.offset > relative + viewport + budget);
488
+ const desiredLast = Math.min(
489
+ props.data.length,
490
+ endJump
491
+ ? props.data.length
492
+ : !viewportMeasured
493
+ ? desiredFirst + firstRows
494
+ : end < 0
495
+ ? props.data.length
496
+ : Math.max(desiredFirst + firstRows, end),
497
+ );
498
+ const visibleStart = layout.frames.findIndex((frame) => frame.offset + frame.length > relative);
499
+ const visibleEnd = layout.frames.findIndex((frame) => frame.offset >= visibleExtentEnd);
500
+ const visibleFirst = Math.max(
501
+ desiredFirst,
502
+ Math.min(desiredLast, visibleStart < 0 ? Math.max(0, props.data.length - 1) : visibleStart),
503
+ );
504
+ const visibleLast = Math.max(
505
+ visibleFirst,
506
+ Math.min(desiredLast, visibleEnd < 0 ? props.data.length : visibleEnd),
507
+ );
508
+ const { first, last } = useBatchedWindow(
509
+ { first: desiredFirst, last: desiredLast },
510
+ { first: visibleFirst, last: visibleLast },
511
+ viewportMeasured,
512
+ keys,
513
+ batch,
514
+ period,
515
+ );
516
+ const mounted = props.data.slice(first, last);
517
+ const before = layout.frames[first]?.offset ?? 0,
518
+ after = Math.max(
519
+ 0,
520
+ layout.total -
521
+ (layout.frames[last - 1]?.offset ?? 0) -
522
+ (layout.frames[last - 1]?.length ?? 0),
523
+ );
524
+ const windowState = useRef({
525
+ layout,
526
+ header,
527
+ padding,
528
+ viewport,
529
+ viewportMeasured,
530
+ offset,
531
+ first,
532
+ keys,
533
+ });
534
+ windowState.current = {
535
+ layout,
536
+ header,
537
+ padding,
538
+ viewport,
539
+ viewportMeasured,
540
+ offset,
541
+ first,
542
+ keys,
543
+ };
544
+ const pendingAnchor = useRef<number | null>(null);
545
+ const scrollToOffset = useCallback(
546
+ (options: { offset: number; animated?: boolean }, preserveAnchorWindow = false) => {
547
+ if (!Number.isFinite(options.offset) || options.offset < 0)
548
+ throw new RokuHostError(
549
+ "C05_SCROLL_OFFSET",
550
+ "Collection offsets must be finite and nonnegative",
551
+ );
552
+ pendingAnchor.current = null;
553
+ initialPending.current = false;
554
+ endGeneration.current++;
555
+ host.runSync(() => {
556
+ setEndJump(false);
557
+ if (!options.animated) {
558
+ const extent = contentExtent.current,
559
+ current = windowState.current;
560
+ // A repeated clamped native command need not emit another scroll
561
+ // event. Keep the selected window at that same committed clamp.
562
+ setOffset(
563
+ !preserveAnchorWindow && extent != null && current.viewportMeasured
564
+ ? Math.min(options.offset, Math.max(0, extent - current.viewport))
565
+ : options.offset,
566
+ );
567
+ }
568
+ scroll.current?.scrollTo({
569
+ [axis]: options.offset,
570
+ animated: options.animated,
571
+ });
572
+ });
573
+ },
574
+ [host, axis],
575
+ );
576
+ useLayoutEffect(() => {
577
+ live.current = true;
578
+ return () => {
579
+ live.current = false;
580
+ endGeneration.current++;
581
+ };
582
+ }, []);
583
+ useLayoutEffect(() => {
584
+ if (
585
+ !initialPending.current ||
586
+ !viewportMeasured ||
587
+ (props.ListHeaderComponent != null && !headerMeasured) ||
588
+ props.data.length === 0
589
+ )
590
+ return;
591
+ let cancelled = false;
592
+ // An empty list can receive data before ScrollView's new content measurement.
593
+ // Wait for that committed extent rather than clamping the initial command
594
+ // against the old empty content and retiring it prematurely.
595
+ void host.whenCommitted().then(
596
+ () => {
597
+ if (cancelled || !live.current || !host.active || !initialPending.current) return;
598
+ const current = windowState.current,
599
+ frame = current.layout.frames[initialIndex];
600
+ if (frame)
601
+ scrollToOffset({
602
+ offset: current.header + current.padding + frame.offset,
603
+ animated: false,
604
+ });
605
+ },
606
+ () => {},
607
+ );
608
+ return () => {
609
+ cancelled = true;
610
+ };
611
+ }, [
612
+ host,
613
+ viewportMeasured,
614
+ headerMeasured,
615
+ props.ListHeaderComponent,
616
+ props.data.length,
617
+ initialIndex,
618
+ layout,
619
+ header,
620
+ padding,
621
+ scrollToOffset,
622
+ ]);
623
+ useLayoutEffect(() => {
624
+ if (!endJump) return;
625
+ const token = ++endGeneration.current;
626
+ void host.whenCommitted().then(
627
+ () => {
628
+ if (
629
+ !live.current ||
630
+ token !== endGeneration.current ||
631
+ !layout.frames.slice(first, last).every((frame) => frame.measured)
632
+ )
633
+ return;
634
+ // Measured tail rows can correct the estimated total. Submit End against
635
+ // that committed content before releasing the forced destination window.
636
+ scroll.current?.scrollToEnd({ animated: false });
637
+ void host.whenCommitted().then(
638
+ () => {
639
+ if (live.current && token === endGeneration.current)
640
+ host.runSync(() => setEndJump(false));
641
+ },
642
+ () => {},
643
+ );
644
+ },
645
+ () => {},
646
+ );
647
+ }, [endJump, first, last, layout, host]);
648
+ useLayoutEffect(() => {
649
+ const currentKeys = new Set(keys);
650
+ for (const key of measurements.current.keys())
651
+ if (!currentKeys.has(key)) measurements.current.delete(key);
652
+ }, [keys]);
653
+ useLayoutEffect(() => {
654
+ const previous = anchor.current;
655
+ const visible = layout.frames.findIndex(
656
+ (frame, index) =>
657
+ index >= anchorMinimum &&
658
+ frame.offset + frame.length > relative &&
659
+ frame.offset < visibleExtentEnd,
660
+ );
661
+ anchor.current = {
662
+ keys,
663
+ key: visible < 0 ? undefined : keys[visible],
664
+ intra: offset - header - padding - (layout.frames[visible]?.offset ?? 0),
665
+ minimum: anchorMinimum,
666
+ enabled: props.maintainVisibleContentPosition != null,
667
+ };
668
+ if (
669
+ initialPending.current ||
670
+ !props.maintainVisibleContentPosition ||
671
+ !previous?.enabled ||
672
+ !previous.key ||
673
+ previous.keys === keys ||
674
+ previous.minimum !== anchorMinimum
675
+ )
676
+ return;
677
+ const index = keys.indexOf(previous.key),
678
+ frame = layout.frames[index];
679
+ if (!frame) return;
680
+ const desired = Math.max(0, header + padding + frame.offset + previous.intra);
681
+ // The selected keyed anchor already uses the arriving layout. Preserve
682
+ // that window until its new native content measurement can apply the
683
+ // pending command against the grown extent.
684
+ scrollToOffset({ offset: desired, animated: false }, true);
685
+ pendingAnchor.current = desired;
686
+ }, [
687
+ keys,
688
+ layout,
689
+ offset,
690
+ header,
691
+ padding,
692
+ relative,
693
+ visibleExtentEnd,
694
+ props.maintainVisibleContentPosition,
695
+ anchorMinimum,
696
+ viewport,
697
+ scrollToOffset,
698
+ ]);
699
+ const recordInteraction = useCollectionViewability(
700
+ props.viewabilityConfig,
701
+ props.onViewableItemsChanged,
702
+ props.extraData,
703
+ {
704
+ data: props.data,
705
+ keys,
706
+ frames: layout.frames,
707
+ first,
708
+ last,
709
+ offset,
710
+ viewport,
711
+ leading: header + padding,
712
+ },
713
+ () =>
714
+ viewportMeasured &&
715
+ (props.ListHeaderComponent == null || headerMeasured) &&
716
+ !initialPending.current &&
717
+ !endJump,
718
+ );
719
+ useImperativeHandle(
720
+ forwardedRef,
721
+ () => ({
722
+ scrollToOffset,
723
+ recordInteraction,
724
+ scrollToIndex(options) {
725
+ const { layout, header, padding, viewport } = windowState.current,
726
+ index = Math.floor(options.index),
727
+ frame = layout.frames[index];
728
+ if (!frame || !Number.isFinite(options.index) || index !== options.index)
729
+ throw new RokuHostError("C05_LIST_INDEX", "Collection index is outside the current data");
730
+ const knownThrough = layout.frames.slice(0, index + 1).every((value) => value.measured);
731
+ if (!knownThrough) {
732
+ latest.current.onScrollToIndexFailed?.({
733
+ averageItemLength: layout.average,
734
+ index,
735
+ highestMeasuredFrameIndex: layout.frames.findIndex((value) => !value.measured) - 1,
736
+ });
737
+ return;
738
+ }
739
+ scrollToOffset({
740
+ offset: Math.max(
741
+ 0,
742
+ header +
743
+ padding +
744
+ frame.offset -
745
+ (viewport - frame.alignmentLength) *
746
+ Math.min(1, Math.max(0, options.viewPosition ?? 0)) -
747
+ (options.viewOffset ?? 0),
748
+ ),
749
+ animated: options.animated,
750
+ });
751
+ },
752
+ scrollToEnd(options) {
753
+ const { layout, header, padding, viewport } = windowState.current;
754
+ pendingAnchor.current = null;
755
+ initialPending.current = false;
756
+ host.runSync(() => {
757
+ // Mount the destination window for an immediate jump, just as
758
+ // scrollToOffset does. The native host retains footer/inset clamping.
759
+ if (!options?.animated) {
760
+ setEndJump(true);
761
+ setOffset(
762
+ Math.max(0, (contentExtent.current ?? header + padding + layout.total) - viewport),
763
+ );
764
+ }
765
+ scroll.current?.scrollToEnd(options);
766
+ });
767
+ },
768
+ getNativeScrollRef: () => scroll.current,
769
+ }),
770
+ [scrollToOffset, recordInteraction],
771
+ );
772
+ const scrollProps: ScrollViewProps & { ref: typeof scroll } = {
773
+ ...props,
774
+ ref: scroll,
775
+ style: props.style,
776
+ contentContainerStyle: props.contentContainerStyle,
777
+ focusable: props.focusable,
778
+ testID: props.testID,
779
+ nativeID: props.nativeID,
780
+ showsVerticalScrollIndicator: horizontal ? false : props.showsVerticalScrollIndicator,
781
+ showsHorizontalScrollIndicator: horizontal ? props.showsHorizontalScrollIndicator : false,
782
+ scrollEventThrottle: props.scrollEventThrottle,
783
+ onLayout(event) {
784
+ const length = (event as { nativeEvent: { layout: { width: number; height: number } } })
785
+ .nativeEvent.layout[dimension];
786
+ if (length > 0) {
787
+ setViewport(length);
788
+ setViewportMeasured(true);
789
+ }
790
+ props.onLayout?.(event);
791
+ },
792
+ onScroll(event) {
793
+ host.runSync(() => setOffset(event.nativeEvent.contentOffset[axis]));
794
+ props.onScroll?.(event);
795
+ },
796
+ onContentSizeChange(width, height) {
797
+ contentExtent.current = horizontal ? width : height;
798
+ const desired = pendingAnchor.current;
799
+ if (desired != null) scrollToOffset({ offset: desired, animated: false });
800
+ props.onContentSizeChange?.(width, height);
801
+ },
802
+ children: createElement(
803
+ Fragment,
804
+ {},
805
+ props.ListHeaderComponent
806
+ ? createElement(
807
+ View,
808
+ {
809
+ style: [horizontal ? { flexShrink: 0 } : undefined, props.ListHeaderComponentStyle],
810
+ onLayout(event) {
811
+ setHeaderMeasured(true);
812
+ setHeader(
813
+ (event as { nativeEvent: { layout: { width: number; height: number } } })
814
+ .nativeEvent.layout[dimension],
815
+ );
816
+ },
817
+ },
818
+ boundary(props.ListHeaderComponent),
819
+ )
820
+ : null,
821
+ props.data.length === 0
822
+ ? boundary(props.ListEmptyComponent)
823
+ : createElement(
824
+ Fragment,
825
+ {},
826
+ createElement(View, {
827
+ key: "before",
828
+ style: { [dimension]: before, flexShrink: 0 },
829
+ onLayout(event) {
830
+ if (props.ListHeaderComponent == null) return;
831
+ // The following cell's committed origin includes the header's
832
+ // outer margins, including percentages resolved by layout.
833
+ const origin = (event as { nativeEvent: { layout: { x: number; y: number } } })
834
+ .nativeEvent.layout[axis];
835
+ setHeader(origin - padding);
836
+ setHeaderMeasured(true);
837
+ },
838
+ }),
839
+ ...mounted.map((item, local) => {
840
+ const index = first + local,
841
+ key = keys[index];
842
+ return createElement(FlatListCell<T>, {
843
+ key,
844
+ item,
845
+ index,
846
+ cellKey: key,
847
+ previousKey: keys[index - 1],
848
+ horizontal,
849
+ updates: separatorUpdates,
850
+ separator: index + 1 < props.data.length ? props.ItemSeparatorComponent : undefined,
851
+ itemRenderer,
852
+ onLayout(event) {
853
+ const length = (
854
+ event as { nativeEvent: { layout: { width: number; height: number } } }
855
+ ).nativeEvent.layout[dimension];
856
+ if (
857
+ !props.getItemLayout &&
858
+ length > 0 &&
859
+ measurements.current.get(key) !== length
860
+ ) {
861
+ measurements.current.set(key, length);
862
+ setMeasurementVersion((value) => value + 1);
863
+ }
864
+ },
865
+ });
866
+ }),
867
+ createElement(View, {
868
+ key: "after",
869
+ style: { [dimension]: after, flexShrink: 0 },
870
+ }),
871
+ ),
872
+ props.ListFooterComponent
873
+ ? createElement(
874
+ View,
875
+ { style: [horizontal ? { flexShrink: 0 } : undefined, props.ListFooterComponentStyle] },
876
+ boundary(props.ListFooterComponent),
877
+ )
878
+ : null,
879
+ ),
880
+ };
881
+ return props.renderScrollComponent
882
+ ? props.renderScrollComponent(scrollProps)
883
+ : createElement(ScrollView, scrollProps);
884
+ }
885
+
886
+ const FlatListRows = forwardRef(FlatListWindow) as <T>(
887
+ props: WindowProps<T> & RefAttributes<FlatListHandle>,
888
+ ) => ReactElement;
889
+
890
+ /** Match the pinned FlatList's row adapter: item callbacks use original indices,
891
+ * while virtualization, separators, layout and scroll commands address rows. */
892
+ function FlatListInner<T>(props: FlatListProps<T>, forwardedRef: ForwardedRef<FlatListHandle>) {
893
+ const columns = props.numColumns ?? 1;
894
+ const mountedColumns = useRef(props.numColumns).current;
895
+ const mountedHorizontal = useRef(props.horizontal === true).current;
896
+ if (mountedHorizontal !== (props.horizontal === true))
897
+ throw new RokuHostError(
898
+ "C05_LIST_AXIS_CHANGE",
899
+ "Changing the collection axis requires a new key prop on FlatList",
900
+ );
901
+ if (!Number.isSafeInteger(columns) || columns < 1)
902
+ throw new RokuHostError("C05_LIST_COLUMNS", "numColumns must be a positive safe integer");
903
+ if (mountedColumns !== props.numColumns)
904
+ throw new RokuHostError(
905
+ "C05_LIST_COLUMNS_CHANGE",
906
+ "Changing numColumns is not supported. Change the key prop on FlatList to remount it",
907
+ );
908
+ if (columns > 1 && props.horizontal)
909
+ throw new RokuHostError("C05_LIST_AXIS", "numColumns does not support horizontal grids");
910
+ if (columns === 1 && props.columnWrapperStyle)
911
+ throw new RokuHostError(
912
+ "C05_LIST_COLUMNS_STYLE",
913
+ "columnWrapperStyle is not supported for single-column lists",
914
+ );
915
+ const configIdentity = viewabilityConfigIdentity(props.viewabilityConfig),
916
+ mountedViewability = useRef({
917
+ configIdentity,
918
+ callback: props.onViewableItemsChanged != null,
919
+ }).current;
920
+ if (
921
+ configIdentity !== mountedViewability.configIdentity ||
922
+ mountedViewability.callback !== (props.onViewableItemsChanged != null)
923
+ )
924
+ throw new RokuHostError(
925
+ "C05_LIST_VIEWABILITY_CHANGE",
926
+ "Changing viewability configuration or callback nullability requires a new key prop on FlatList",
927
+ );
928
+ if (
929
+ (props as FlatListProps<T> & { viewabilityConfigCallbackPairs?: unknown })
930
+ .viewabilityConfigCallbackPairs != null
931
+ )
932
+ throw new RokuHostError(
933
+ "C05_LIST_VIEWABILITY_PAIRS",
934
+ "Multiple viewability callbacks are not supported by this collection profile",
935
+ );
936
+ const rows = useMemo(() => {
937
+ const result: (readonly T[])[] = [];
938
+ if (columns > 1)
939
+ for (let index = 0; index < props.data.length; index += columns)
940
+ result.push(props.data.slice(index, index + columns));
941
+ return result;
942
+ }, [props.data, columns]);
943
+ const keyExtractor = useCallback(
944
+ (row: readonly T[], index: number) =>
945
+ row
946
+ .map((item, column) => (props.keyExtractor ?? itemKey)(item, index * columns + column))
947
+ .join(":"),
948
+ [props.keyExtractor, columns],
949
+ );
950
+ const renderItem = useCallback(
951
+ ({ item: row, index, separators }: FlatListRenderItemInfo<readonly T[]>) =>
952
+ createElement(
953
+ View,
954
+ { style: [{ flexDirection: "row" }, props.columnWrapperStyle] },
955
+ ...row.map((item, column) => {
956
+ const element = props.renderItem({ item, index: index * columns + column, separators });
957
+ return element == null ? null : createElement(Fragment, { key: column }, element);
958
+ }),
959
+ ),
960
+ [props.renderItem, props.columnWrapperStyle, columns],
961
+ );
962
+ const getItemLayout = useMemo(
963
+ () =>
964
+ props.getItemLayout
965
+ ? (_rows: readonly (readonly T[])[] | null | undefined, index: number) =>
966
+ props.getItemLayout!(props.data, index)
967
+ : undefined,
968
+ [props.getItemLayout, props.data],
969
+ );
970
+ const onViewableItemsChanged = useCallback(
971
+ (info: ViewabilityInfo<readonly T[]>) => {
972
+ const expand = (tokens: readonly ViewToken<readonly T[]>[]): ViewToken<T>[] =>
973
+ tokens.flatMap((token) =>
974
+ token.item.map((item, column) => {
975
+ const index = token.index * columns + column;
976
+ return { ...token, item, index, key: (props.keyExtractor ?? itemKey)(item, index) };
977
+ }),
978
+ );
979
+ props.onViewableItemsChanged?.({
980
+ viewableItems: expand(info.viewableItems),
981
+ changed: expand(info.changed),
982
+ });
983
+ },
984
+ [props.onViewableItemsChanged, props.keyExtractor, columns],
985
+ );
986
+ if (columns === 1)
987
+ return createElement(FlatListRows<T>, { ...props, itemRenderer: props, ref: forwardedRef });
988
+ return createElement(FlatListRows<readonly T[]>, {
989
+ ...props,
990
+ ref: forwardedRef,
991
+ data: rows,
992
+ itemRenderer: { renderItem },
993
+ onViewableItemsChanged: props.onViewableItemsChanged ? onViewableItemsChanged : undefined,
994
+ keyExtractor,
995
+ renderItem,
996
+ getItemLayout,
997
+ });
998
+ }
999
+ export const FlatList = forwardRef(FlatListInner) as <T>(
1000
+ props: FlatListProps<T> & RefAttributes<FlatListHandle>,
1001
+ ) => ReactElement;