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

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 +328 -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 +368 -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,68 @@
1
+ import type { SceneTreeElement } from "../renderer/SceneRoot";
2
+ import type { LayoutStyle } from "./flexLayout";
3
+ import { layoutText, type TextMetricProvider } from "./textLayout";
4
+ import { RokuHostError } from "../scene/sceneGraph.types";
5
+ export interface InlineTextRun {
6
+ readonly text: string;
7
+ readonly style: LayoutStyle;
8
+ }
9
+ export function inlineTextRuns(
10
+ node: SceneTreeElement,
11
+ inherited: LayoutStyle = {},
12
+ ): InlineTextRun[] {
13
+ if (!["label", "multiStyleLabel", "inlineText", "poster"].includes(node.type))
14
+ throw new RokuHostError("C04_INLINE_CONTENT", "Inline text admits text runs only");
15
+ const style = {
16
+ ...inherited,
17
+ ...((node.props.layout?.style as LayoutStyle) ?? {}),
18
+ },
19
+ runs: InlineTextRun[] = [];
20
+ const scalar = node.props.layout?.scalarText;
21
+ if (typeof scalar === "string" && scalar !== "") return [{ text: scalar, style }];
22
+ for (const child of node.children) {
23
+ if (child.kind === "text") {
24
+ if (!child.hidden) runs.push({ text: child.text, style });
25
+ } else runs.push(...inlineTextRuns(child, style));
26
+ }
27
+ return runs;
28
+ }
29
+ export function measureInlineText(
30
+ runs: readonly InlineTextRun[],
31
+ text: TextMetricProvider,
32
+ maximumWidth: number | undefined,
33
+ numberOfLines: number,
34
+ raster = false,
35
+ ) {
36
+ let width = 0,
37
+ height = 0;
38
+ for (const [index, run] of runs.entries()) {
39
+ if (
40
+ !raster &&
41
+ (Number(run.style.letterSpacing ?? 0) ||
42
+ run.style.textShadowColor != null ||
43
+ run.style.textShadowRadius != null)
44
+ )
45
+ throw new RokuHostError(
46
+ "C04_INLINE_RASTER",
47
+ "Tracked or shadowed mixed text requires the multi-run raster adapter",
48
+ );
49
+ if (run.text.includes("\n"))
50
+ throw new RokuHostError(
51
+ "C04_INLINE_WRAP",
52
+ "Multiline mixed text requires inline line shaping",
53
+ );
54
+ const metrics = text.metrics(run.style);
55
+ width += raster
56
+ ? layoutText(run.text, run.style, metrics, Infinity, 1).width +
57
+ (index < runs.length - 1 ? Number(run.style.letterSpacing ?? 0) : 0)
58
+ : metrics.width(run.text);
59
+ height = Math.max(height, Number(run.style.lineHeight ?? metrics.lineHeight));
60
+ }
61
+ if (
62
+ (raster || numberOfLines !== 1) &&
63
+ maximumWidth != null &&
64
+ Math.fround(width) > Math.fround(maximumWidth)
65
+ )
66
+ throw new RokuHostError("C04_INLINE_WRAP", "Wrapped mixed text requires inline line shaping");
67
+ return { width: Math.min(width, maximumWidth ?? Infinity), height };
68
+ }
@@ -0,0 +1,117 @@
1
+ import type { LayoutStyle } from "./flexLayout";
2
+
3
+ const unsupported = Symbol("uncacheable layout value");
4
+ const builtinObjectProperties = new Set([
5
+ "constructor",
6
+ "__defineGetter__",
7
+ "__defineSetter__",
8
+ "hasOwnProperty",
9
+ "__lookupGetter__",
10
+ "__lookupSetter__",
11
+ "isPrototypeOf",
12
+ "propertyIsEnumerable",
13
+ "toString",
14
+ "valueOf",
15
+ "__proto__",
16
+ "toLocaleString",
17
+ ]);
18
+
19
+ export function hasOnlyBuiltinObjectPrototypeFields() {
20
+ for (const key of Object.getOwnPropertyNames(Object.prototype))
21
+ if (!builtinObjectProperties.has(key)) return false;
22
+ return true;
23
+ }
24
+
25
+ /** Preserve numeric/type distinctions and detached nested style values. JSON
26
+ * would confuse null with NaN and could bypass the ordinary layout validator. */
27
+ function capture(value: unknown, depth = 0): unknown {
28
+ if (depth > 16) return unsupported;
29
+ if (value === null || ["undefined", "string", "number", "boolean"].includes(typeof value))
30
+ return value;
31
+ if (Array.isArray(value)) {
32
+ const items = value.map((item) => capture(item, depth + 1));
33
+ return items.includes(unsupported) ? unsupported : items;
34
+ }
35
+ if (typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype) {
36
+ const entries = Object.entries(value).map(
37
+ ([key, item]) => [key, capture(item, depth + 1)] as const,
38
+ );
39
+ return entries.some(([, item]) => item === unsupported)
40
+ ? unsupported
41
+ : Object.fromEntries(entries);
42
+ }
43
+ return unsupported;
44
+ }
45
+
46
+ function same(left: unknown, right: unknown, depth = 0): boolean {
47
+ if (Object.is(left, right)) return true;
48
+ if (depth > 16 || !left || !right || typeof left !== "object" || typeof right !== "object")
49
+ return false;
50
+ if (Array.isArray(left) || Array.isArray(right))
51
+ return (
52
+ Array.isArray(left) &&
53
+ Array.isArray(right) &&
54
+ left.length === right.length &&
55
+ left.every((item, index) => same(item, right[index], depth + 1))
56
+ );
57
+ if (
58
+ Object.getPrototypeOf(left) !== Object.prototype ||
59
+ Object.getPrototypeOf(right) !== Object.prototype
60
+ )
61
+ return false;
62
+ const entries = Object.entries(left);
63
+ return (
64
+ entries.length === Object.keys(right).length &&
65
+ entries.every(
66
+ ([key, value]) =>
67
+ Object.hasOwn(right, key) &&
68
+ same(value, (right as Record<string, unknown>)[key], depth + 1),
69
+ )
70
+ );
71
+ }
72
+
73
+ // Views paint their background after Yoga. Text metric providers may inspect
74
+ // the complete text style, including its background.
75
+ export interface LayoutStyleSnapshot {
76
+ readonly values: LayoutStyle;
77
+ readonly count: number;
78
+ }
79
+ function plainStyle(style: LayoutStyle) {
80
+ const proto = Object.getPrototypeOf(style);
81
+ return proto === Object.prototype || proto === null;
82
+ }
83
+ export function captureLayoutStyle(
84
+ style: LayoutStyle,
85
+ view: boolean,
86
+ ): LayoutStyleSnapshot | undefined {
87
+ if (!plainStyle(style)) return undefined;
88
+ const values: Record<string, unknown> = Object.create(null);
89
+ let count = 0;
90
+ for (const key of Object.getOwnPropertyNames(style)) {
91
+ if (key === "opacity" || (view && key === "backgroundColor")) continue;
92
+ const item = capture(style[key]);
93
+ if (item === unsupported) return undefined;
94
+ values[key] = item;
95
+ count++;
96
+ }
97
+ return { values, count };
98
+ }
99
+ export function sameLayoutStyle(
100
+ style: LayoutStyle,
101
+ captured: LayoutStyleSnapshot,
102
+ view: boolean,
103
+ ): boolean {
104
+ if (!plainStyle(style)) return false;
105
+ let count = 0;
106
+ for (const key of Object.getOwnPropertyNames(style)) {
107
+ if (key === "opacity" || (view && key === "backgroundColor")) continue;
108
+ const previous = captured.values[key];
109
+ if (
110
+ (previous === undefined && !Object.hasOwn(captured.values, key)) ||
111
+ !same(style[key], previous)
112
+ )
113
+ return false;
114
+ count++;
115
+ }
116
+ return count === captured.count;
117
+ }
@@ -0,0 +1,179 @@
1
+ import type { LayoutRect, LayoutStyle } from "./flexLayout";
2
+ import { layoutText, type TextLayout, type TextMetricProvider } from "./textLayout";
3
+ import type { SceneTreeElement } from "../renderer/SceneRoot";
4
+ import { RokuHostError, type SceneFields, type SceneValue } from "../scene/sceneGraph.types";
5
+ import { rokuColor } from "../react-native/styleSheet";
6
+ import { sceneTransform } from "./transform";
7
+ import { sceneNodeReference } from "../renderer/SceneRoot";
8
+ import { inlineTextRuns } from "./inlineText";
9
+ import { layoutInlineParagraph } from "./inlineParagraph";
10
+
11
+ export function labelText(node: SceneTreeElement): string {
12
+ const scalar = node.props.layout?.scalarText;
13
+ if (typeof scalar === "string") return scalar;
14
+ if (node.children.some((child) => child.kind === "element"))
15
+ throw new RokuHostError("C04_TEXT_RUNS", "Nested styled text requires an inline-text renderer");
16
+ return node.children.length
17
+ ? node.children
18
+ .map((child) => (child.kind === "text" && !child.hidden ? child.text : ""))
19
+ .join("")
20
+ : String(node.props.fields?.text ?? "");
21
+ }
22
+
23
+ export interface MeasuredLabel {
24
+ readonly width: number | undefined;
25
+ readonly lineHeight: number;
26
+ readonly layout: TextLayout;
27
+ }
28
+
29
+ export function nativeNodeFields(
30
+ node: SceneTreeElement,
31
+ style: LayoutStyle,
32
+ rect: LayoutRect,
33
+ text: TextMetricProvider,
34
+ measuredLabel?: MeasuredLabel,
35
+ ): SceneFields {
36
+ const content =
37
+ node.type === "video" || node.type === "audio"
38
+ ? node.children.find((child) => child.kind === "element" && child.type === "contentNode")
39
+ : undefined;
40
+ const mediaFields: SceneFields =
41
+ node.type === "video" || node.type === "audio"
42
+ ? { content: content?.kind === "element" ? sceneNodeReference(content.handle) : null }
43
+ : {};
44
+ if (node.props.layout?.resource) return mediaFields;
45
+ const fields: Record<string, SceneValue> = {
46
+ ...mediaFields,
47
+ translation: [rect.x, rect.y],
48
+ visible: style.display !== "none",
49
+ };
50
+ if (typeof style.opacity === "number") fields.opacity = style.opacity;
51
+ if (style.overflow === "hidden") fields.clippingRect = [0, 0, rect.width, rect.height];
52
+ if (style.transform != null || style.transformOrigin != null)
53
+ Object.assign(fields, sceneTransform(style.transform ?? [], rect, style.transformOrigin));
54
+ if (["rectangle", "poster", "label", "multiStyleLabel", "video"].includes(node.type)) {
55
+ if (rect.width <= 0 || rect.height <= 0) fields.visible = false;
56
+ fields.width = rect.width;
57
+ fields.height = rect.height;
58
+ }
59
+ const effect = node.children.find((child) => child.kind === "element" && child.type === "effect");
60
+ if (effect?.kind === "element") fields.effect = sceneNodeReference(effect.handle);
61
+ if (node.type === "label") {
62
+ if (style.letterSpacing != null && style.letterSpacing !== 0)
63
+ throw new RokuHostError("C04_LETTER_SPACING", "Letter spacing requires a glyph-run renderer");
64
+ const metrics = text.metrics(style);
65
+ const value =
66
+ measuredLabel &&
67
+ Object.is(measuredLabel.width, rect.width) &&
68
+ Object.is(measuredLabel.lineHeight, metrics.lineHeight)
69
+ ? measuredLabel.layout
70
+ : layoutText(
71
+ labelText(node),
72
+ style,
73
+ metrics,
74
+ rect.width,
75
+ Number(node.props.layout?.numberOfLines ?? 0),
76
+ );
77
+ fields.text = value.text;
78
+ fields.color = rokuColor(style.color ?? "white");
79
+ fields.horizAlign =
80
+ typeof style.textAlign === "string" && style.textAlign !== "auto" ? style.textAlign : "left";
81
+ fields.vertAlign = "top";
82
+ fields.wrap = true;
83
+ fields.numLines = value.lines.length;
84
+ fields.lineSpacing = 0;
85
+ if (typeof style.lineHeight === "number") {
86
+ fields.lineSpacing = style.lineHeight - metrics.lineHeight;
87
+ // Yoga owns the authored line box. Keep glyphs visible when Roku's
88
+ // native font line box extends beyond that height.
89
+ fields.displayPartialLines = true;
90
+ }
91
+ const font = text.font?.(style);
92
+ if (font) fields.font = font;
93
+ }
94
+ if (node.type === "multiStyleLabel") {
95
+ const runs = inlineTextRuns(node),
96
+ styles: Record<string, unknown> = {};
97
+ const escape = (value: string) =>
98
+ value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
99
+ fields.text = runs
100
+ .map((run, index) => {
101
+ const uri = text.fontAsset?.(run.style);
102
+ if (!uri)
103
+ throw new RokuHostError(
104
+ "C04_INLINE_FONT",
105
+ "Mixed text requires the exact packaged font URI",
106
+ );
107
+ styles[`s${index}`] = {
108
+ fontUri: uri,
109
+ fontSize: Number(run.style.fontSize ?? 14),
110
+ color: rokuColor(run.style.color ?? "white"),
111
+ };
112
+ return `<s${index}>${escape(run.text)}</s${index}>`;
113
+ })
114
+ .join("");
115
+ fields.drawingStyles = styles;
116
+ fields.wrap = false;
117
+ fields.numLines = 1;
118
+ fields.maxLines = 1;
119
+ fields.ellipsisText = "…";
120
+ fields.horizAlign = String(style.textAlign ?? "left");
121
+ fields.vertAlign = "top";
122
+ }
123
+ if (node.type === "inlineText" && (rect.width <= 0 || rect.height <= 0)) fields.visible = false;
124
+ return fields;
125
+ }
126
+
127
+ /** A paragraph is a measured group of one-line native styled labels. Keeping
128
+ * each line independent preserves authored line heights without inventing a
129
+ * MultiStyleLabel lineSpacing field. Nested React Text nodes stay virtual. */
130
+ export function nativeInlineTextLines(
131
+ node: SceneTreeElement,
132
+ style: LayoutStyle,
133
+ rect: LayoutRect,
134
+ text: TextMetricProvider,
135
+ ): readonly SceneFields[] {
136
+ if (rect.width <= 0 || rect.height <= 0) return [];
137
+ const runs = inlineTextRuns(node);
138
+ const layout = layoutInlineParagraph(
139
+ runs,
140
+ text,
141
+ rect.width,
142
+ Number(node.props.layout?.numberOfLines ?? 0),
143
+ );
144
+ const keys = new Map<LayoutStyle, string>();
145
+ const drawingStyles: Record<string, SceneValue> = {};
146
+ for (const run of runs) {
147
+ if (keys.has(run.style)) continue;
148
+ const key = `s${keys.size}`,
149
+ uri = text.fontAsset?.(run.style);
150
+ if (!uri)
151
+ throw new RokuHostError("C04_INLINE_FONT", "Mixed text requires the exact packaged font URI");
152
+ keys.set(run.style, key);
153
+ drawingStyles[key] = {
154
+ fontUri: uri,
155
+ fontSize: Number(run.style.fontSize ?? 14),
156
+ color: rokuColor(run.style.color ?? "white"),
157
+ };
158
+ }
159
+ const escape = (value: string) =>
160
+ value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
161
+ return layout.lines.map((line) => ({
162
+ translation: [0, line.y],
163
+ width: rect.width,
164
+ height: line.paintHeight,
165
+ text: line.runs
166
+ .map((run) => {
167
+ const key = keys.get(run.style)!;
168
+ return `<${key}>${escape(run.text)}</${key}>`;
169
+ })
170
+ .join(""),
171
+ drawingStyles,
172
+ wrap: false,
173
+ numLines: 1,
174
+ maxLines: 1,
175
+ ellipsisText: "…",
176
+ horizAlign: String(style.textAlign === "auto" ? "left" : (style.textAlign ?? "left")),
177
+ vertAlign: "top",
178
+ }));
179
+ }
@@ -0,0 +1,78 @@
1
+ import type { LayoutRect, LayoutStyle } from "./flexLayout";
2
+ import { nativeNodeFields, type MeasuredLabel } from "./nativeNodeFields";
3
+ import type { TextMetricProvider } from "./textLayout";
4
+ import type { SceneTreeElement } from "../renderer/SceneRoot";
5
+ import type { SceneFields, SceneNodeRef } from "../scene/sceneGraph.types";
6
+
7
+ interface PreparedFields {
8
+ fields: SceneFields;
9
+ opacity: LayoutStyle["opacity"];
10
+ content?: string;
11
+ font?: SceneNodeRef;
12
+ lineHeight?: number;
13
+ effect?: SceneTreeElement;
14
+ }
15
+
16
+ /** The owner replaces this cache on each Yoga solve. During reuse it has already
17
+ * compared layout rectangles, label styles and line limits against that solve.
18
+ * Paint, native font readiness and resource children can change independently. */
19
+ export class PreparedFieldCache {
20
+ private values = new WeakMap<SceneTreeElement, PreparedFields>();
21
+
22
+ retained(node: SceneTreeElement, fields: SceneFields | undefined) {
23
+ const prepared = this.values.get(node);
24
+ return prepared?.fields === fields ? prepared : undefined;
25
+ }
26
+
27
+ begin(sameGeometry: boolean, text: TextMetricProvider, changedGeometry?: SceneTreeElement) {
28
+ if (!sameGeometry) this.values = new WeakMap();
29
+ else if (changedGeometry) this.values.delete(changedGeometry);
30
+ const heights = new Map<SceneNodeRef, number>();
31
+ return (
32
+ node: SceneTreeElement,
33
+ style: LayoutStyle,
34
+ rect: LayoutRect,
35
+ content?: string,
36
+ measuredLabel?: MeasuredLabel,
37
+ ) => {
38
+ const layout = node.props.layout;
39
+ if (
40
+ style.transform != null ||
41
+ style.transformOrigin != null ||
42
+ layout?.resource ||
43
+ layout?.decoration ||
44
+ layout?.paintWrapper ||
45
+ layout?.textRaster ||
46
+ (node.type !== "group" && node.type !== "rectangle" && node.type !== "label") ||
47
+ (node.type === "label" && (!text.preparedFieldFont || content === undefined))
48
+ )
49
+ return nativeNodeFields(node, style, rect, text);
50
+
51
+ let font: SceneNodeRef | undefined, lineHeight: number | undefined;
52
+ if (node.type === "label") {
53
+ font = text.preparedFieldFont!(style);
54
+ lineHeight = heights.get(font);
55
+ if (lineHeight === undefined) {
56
+ lineHeight = text.metrics(style).lineHeight;
57
+ heights.set(font, lineHeight);
58
+ }
59
+ }
60
+ const effect = node.children.find(
61
+ (child): child is SceneTreeElement => child.kind === "element" && child.type === "effect",
62
+ );
63
+ const previous = this.values.get(node);
64
+ if (
65
+ previous &&
66
+ Object.is(style.opacity, previous.opacity) &&
67
+ content === previous.content &&
68
+ font === previous.font &&
69
+ Object.is(lineHeight, previous.lineHeight) &&
70
+ effect === previous.effect
71
+ )
72
+ return previous.fields;
73
+ const fields = nativeNodeFields(node, style, rect, text, measuredLabel);
74
+ this.values.set(node, { fields, opacity: style.opacity, content, font, lineHeight, effect });
75
+ return fields;
76
+ };
77
+ }
78
+ }
@@ -0,0 +1,138 @@
1
+ import { RokuHostError } from "../scene/sceneGraph.types";
2
+ import type { LayoutStyle } from "./flexLayout";
3
+
4
+ export interface TextMetrics {
5
+ readonly lineHeight: number;
6
+ width(text: string): number;
7
+ }
8
+ export interface TextLayout {
9
+ readonly text: string;
10
+ readonly lines: readonly string[];
11
+ readonly width: number;
12
+ readonly height: number;
13
+ }
14
+ /** Internal capability for providers that keep ready font refs stable until disposal. */
15
+ export type RetainedFontMetrics = TextMetricProvider & {
16
+ readRetainedFontLineHeight?(font: import("../scene/sceneGraph.types").SceneNodeRef): number;
17
+ };
18
+
19
+ export interface TextMetricProvider {
20
+ prepare(style: LayoutStyle): void | Promise<void>;
21
+ metrics(style: LayoutStyle): TextMetrics;
22
+ font?(style: LayoutStyle): import("../scene/sceneGraph.types").SceneNodeRef;
23
+ /** Ready native font whose measured glyph widths are stable for its lifetime. */
24
+ preparedFieldFont?(style: LayoutStyle): import("../scene/sceneGraph.types").SceneNodeRef;
25
+ fontFamily?(style: LayoutStyle): string;
26
+ fontAsset?(style: LayoutStyle): string;
27
+ dispose?(): void;
28
+ }
29
+
30
+ /** Yoga/SceneGraph frames use float32. A double-precision natural width can
31
+ * exceed its own committed frame by a few millionths and falsely wrap a glyph. */
32
+ const fitsMeasuredWidth = (measured: number, available: number) =>
33
+ Math.fround(measured) <= Math.fround(available);
34
+
35
+ function fittingPrefix(text: string, width: number, metrics: TextMetrics, suffix = ""): string {
36
+ // UTF-16 offsets are already code-point boundaries when there are no
37
+ // surrogates. Keep full code-point slicing for other strings.
38
+ const points = /[\uD800-\uDFFF]/.test(text) ? Array.from(text) : undefined;
39
+ const prefix = (length: number) =>
40
+ points ? points.slice(0, length).join("") : text.slice(0, length);
41
+ let low = 0,
42
+ high = points?.length ?? text.length;
43
+ while (low < high) {
44
+ const middle = Math.ceil((low + high) / 2);
45
+ if (fitsMeasuredWidth(metrics.width(prefix(middle) + suffix), width)) low = middle;
46
+ else high = middle - 1;
47
+ }
48
+ return prefix(low);
49
+ }
50
+
51
+ function ellipsize(text: string, width: number, metrics: TextMetrics): string {
52
+ if (fitsMeasuredWidth(metrics.width(text), width)) return text;
53
+ if (!fitsMeasuredWidth(metrics.width("…"), width)) return "";
54
+ return fittingPrefix(text, width, metrics, "…") + "…";
55
+ }
56
+
57
+ /** Uses the renderer's real font widths; it never estimates glyph widths from character count. */
58
+ export function layoutText(
59
+ text: string,
60
+ style: LayoutStyle,
61
+ metrics: TextMetrics,
62
+ maxWidth = Infinity,
63
+ numberOfLines = 0,
64
+ ): TextLayout {
65
+ const spacing = Number(style.letterSpacing ?? 0);
66
+ if (!Number.isFinite(spacing))
67
+ throw new RokuHostError("C04_LETTER_SPACING", "Letter spacing must be finite");
68
+ if (spacing) {
69
+ const original = metrics;
70
+ metrics = {
71
+ lineHeight: original.lineHeight,
72
+ width: (value) =>
73
+ Math.max(0, original.width(value) + Math.max(0, Array.from(value).length - 1) * spacing),
74
+ };
75
+ }
76
+ if (style.textTransform === "uppercase") text = text.toUpperCase();
77
+ else if (style.textTransform === "lowercase") text = text.toLowerCase();
78
+ else if (style.textTransform === "capitalize")
79
+ text = text.replace(
80
+ /(^|\s)(\S)/gu,
81
+ (_match, space: string, character: string) => space + character.toUpperCase(),
82
+ );
83
+ else if (style.textTransform != null && style.textTransform !== "none")
84
+ throw new RokuHostError(
85
+ "C04_TEXT_TRANSFORM",
86
+ `Text transform ${String(style.textTransform)} needs conformance`,
87
+ );
88
+ const lineHeight = typeof style.lineHeight === "number" ? style.lineHeight : metrics.lineHeight;
89
+ if (!(lineHeight > 0) || !Number.isFinite(lineHeight) || maxWidth < 0 || Number.isNaN(maxWidth))
90
+ throw new RokuHostError("C04_TEXT_METRICS", "Text requires valid width and line height");
91
+ if (!Number.isInteger(numberOfLines) || numberOfLines < 0)
92
+ throw new RokuHostError("C04_TEXT_LINES", "numberOfLines must be a nonnegative integer");
93
+ const paragraphs = text.replaceAll("\r\n", "\n").split("\n");
94
+ const lines: string[] = [];
95
+ for (const paragraph of paragraphs) {
96
+ if (!Number.isFinite(maxWidth) || fitsMeasuredWidth(metrics.width(paragraph), maxWidth)) {
97
+ lines.push(paragraph);
98
+ continue;
99
+ }
100
+ if (numberOfLines === 1) {
101
+ lines.push(ellipsize(paragraphs.join(" "), maxWidth, metrics));
102
+ break;
103
+ }
104
+ let remaining = paragraph;
105
+ while (remaining.length) {
106
+ const fitting = fittingPrefix(remaining, maxWidth, metrics);
107
+ if (!fitting) {
108
+ lines.push("");
109
+ break;
110
+ }
111
+ const boundary = fitting.search(/\s+\S*$/u);
112
+ const line =
113
+ boundary > 0 && fitting.length < remaining.length ? fitting.slice(0, boundary) : fitting;
114
+ lines.push(line.trimEnd());
115
+ remaining = remaining.slice(line.length).trimStart();
116
+ }
117
+ }
118
+ if (numberOfLines && lines.length > numberOfLines) {
119
+ const truncated = lines.slice(0, numberOfLines);
120
+ // The omitted continuation requires an ellipsis even if this line happened to fit.
121
+ truncated[numberOfLines - 1] = ellipsize(
122
+ truncated[numberOfLines - 1] + " …",
123
+ maxWidth,
124
+ metrics,
125
+ );
126
+ return result(truncated, lineHeight, metrics);
127
+ }
128
+ return result(lines, lineHeight, metrics);
129
+ }
130
+
131
+ function result(lines: string[], lineHeight: number, metrics: TextMetrics): TextLayout {
132
+ return {
133
+ text: lines.join("\n"),
134
+ lines,
135
+ width: Math.max(0, ...lines.map((line) => metrics.width(line))),
136
+ height: Math.max(1, lines.length) * lineHeight,
137
+ };
138
+ }