@applicaster/zapp-react-native-utils 17.0.0-alpha.1037440043 → 17.0.0-alpha.1201533844

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.
@@ -11,9 +11,9 @@ import {
11
11
  isSamsungPlatform,
12
12
  } from "@applicaster/zapp-react-dom-app/App/Loader/utils/platform";
13
13
 
14
- import { PLATFORM_KEYS, PLATFORMS, ZappPlatform } from "./const";
14
+ import { PLATFORM_KEYS, ZappPlatform } from "./const";
15
15
  import { createLogger, utilsLogger } from "../../logger";
16
- import { getPlatform } from "../../reactUtils";
16
+ import { getPlatform, isVizioPlatform } from "../../reactUtils";
17
17
  import { appStore } from "@applicaster/zapp-react-native-redux/AppStore";
18
18
  import { calculateReadingTime } from "@applicaster/zapp-react-native-utils/appUtils/accessibilityManager/utils";
19
19
 
@@ -47,24 +47,8 @@ export const getUserAgent = () => window?.navigator?.userAgent;
47
47
 
48
48
  /** VIZIO UTILS */
49
49
 
50
- /**
51
- * Checks if we are on the Vizio platform by using the userAgent string
52
- *
53
- * Use this method when you need to identify the platform on runtime
54
- * before the VIZIO Companion Library has loaded
55
- */
56
- export const isVizioPlatform = () => {
57
- const userAgent = getUserAgent();
58
-
59
- if (!userAgent) return false;
60
-
61
- const isVizioAgent =
62
- userAgent.includes(PLATFORMS.vizio) ||
63
- userAgent.includes(PLATFORMS.smartcast) ||
64
- userAgent.includes(PLATFORMS.conjure);
65
-
66
- return isVizioAgent;
67
- };
50
+ // One implementation, so its build-time device target guard applies here too.
51
+ export { isVizioPlatform };
68
52
 
69
53
  /**
70
54
  * Checks if we are on the Vizio platform by checking for the global VIZIO object
@@ -222,30 +222,37 @@ class FocusManager {
222
222
  return () => this.unregisterFocusable(focusableId);
223
223
  }
224
224
 
225
- unregisterFocusable(focusableId: string) {
225
+ unregisterFocusable(component: string | FocusManager.TouchableReactRef) {
226
+ const focusableId = isString(component)
227
+ ? component
228
+ : getFocusableId(component);
229
+
226
230
  const node = this.tree.find(focusableId);
227
231
  const parentNode = this.tree.findParent(focusableId);
228
232
 
233
+ const removesFocusedSubtree =
234
+ this._focusedId === focusableId ||
235
+ !!(this._focusedId && node?.findNode(this._focusedId));
236
+
229
237
  this.focusableComponents = this.focusableComponents.filter(
230
- (c) => c !== node?.component
238
+ (c) => c !== node?.component && getFocusableId(c) !== focusableId
231
239
  );
232
240
 
233
241
  this.tree.remove(focusableId);
234
242
 
235
- if (this._focusedId === focusableId) {
243
+ if (removesFocusedSubtree) {
236
244
  this._focusedId = null;
237
245
  this.retainFocus(parentNode);
238
246
  }
239
247
  }
240
248
 
241
- // Empty groups drop their focusable list after the feed fails, which is
242
- // after Layout's one-shot focus pass. Land on the nearest ancestor that is
243
- // still mounted so key handlers keep a target.
249
+ // Recover before parent-first unmounts discard the focused child's ancestry.
250
+ // Land on a mounted ancestor so key handlers keep a target.
244
251
  private retainFocus(node: TreeNode | null) {
245
252
  let current = node;
246
253
 
247
254
  while (current) {
248
- const ref = current.component;
255
+ const ref = FocusManager.findFocusable(current.id);
249
256
 
250
257
  if (ref?.current?.props?.id) {
251
258
  this.setFocusLocal(ref);
@@ -1,4 +1,7 @@
1
1
  import { focusManager } from "../FocusManager";
2
+ import { Touchable } from "@applicaster/zapp-react-native-ui-components/Components/Focusable/Touchable";
3
+ import { Tree } from "../Tree";
4
+ import { TreeNode } from "../TreeNode";
2
5
 
3
6
  const isFocusableCell = true;
4
7
  const parentFocusableId = "parentFocusableId";
@@ -266,3 +269,112 @@ describe("FocusManager", () => {
266
269
  expect(focusManager.focusedId).toBe("child2");
267
270
  });
268
271
  });
272
+
273
+ describe("FocusManager subtree replacement", () => {
274
+ const createFocusable = (id: string) => ({
275
+ current: new Touchable({ id, children: null, onFocus: jest.fn() }),
276
+ });
277
+
278
+ let root: FocusManager.TouchableReactRef;
279
+ let rail: FocusManager.TouchableReactRef;
280
+ let cell: FocusManager.TouchableReactRef;
281
+ let sibling: FocusManager.TouchableReactRef;
282
+
283
+ const register = (
284
+ touchableRef: FocusManager.TouchableReactRef,
285
+ parentFocusableRef: FocusManager.TouchableReactRef
286
+ ) =>
287
+ focusManager.registerFocusable({
288
+ touchableRef,
289
+ parentFocusableRef,
290
+ isFocusableCell: true,
291
+ parentFocusableId: "",
292
+ });
293
+
294
+ beforeEach(() => {
295
+ root = createFocusable("replacement-root");
296
+ rail = createFocusable("replacement-rail");
297
+ cell = createFocusable("replacement-cell");
298
+ sibling = createFocusable("replacement-sibling");
299
+ register(root, { current: null });
300
+ register(rail, root);
301
+ register(cell, rail);
302
+ register(sibling, root);
303
+ focusManager.setFocus("replacement-cell");
304
+ });
305
+
306
+ afterEach(() => {
307
+ [
308
+ "replacement-cell",
309
+ "replacement-rail",
310
+ "replacement-sibling",
311
+ "replacement-root",
312
+ ].forEach((id) => focusManager.unregisterFocusable(id));
313
+
314
+ focusManager.resetFocus();
315
+ });
316
+
317
+ it("retains focus before a parent-first unmount removes the focused descendant's ancestry", () => {
318
+ focusManager.unregisterFocusable("replacement-rail");
319
+
320
+ expect(focusManager.focusedId).toBe("replacement-root");
321
+ expect(focusManager.focused).toBe(root.current);
322
+
323
+ focusManager.unregisterFocusable("replacement-cell");
324
+
325
+ expect(focusManager.focused).toBe(root.current);
326
+ });
327
+
328
+ it("removes descendant registrations even after their parent removed the tree nodes", () => {
329
+ focusManager.unregisterFocusable("replacement-rail");
330
+ focusManager.unregisterFocusable("replacement-cell");
331
+
332
+ expect(focusManager.focusableComponents).not.toContain(cell);
333
+ expect(focusManager.focusableComponents).not.toContain(rail);
334
+
335
+ const replacementRail = createFocusable("replacement-rail");
336
+ const replacementCell = createFocusable("replacement-cell");
337
+ register(replacementRail, root);
338
+ register(replacementCell, replacementRail);
339
+ focusManager.setFocus("replacement-cell");
340
+
341
+ expect(focusManager.focused).toBe(replacementCell.current);
342
+ expect(focusManager.isFocusableChildOf(replacementCell, root)).toBe(true);
343
+ });
344
+
345
+ it("does not move focus when an unrelated subtree unregisters", () => {
346
+ focusManager.setFocus("replacement-sibling");
347
+ focusManager.unregisterFocusable("replacement-rail");
348
+ focusManager.unregisterFocusable("replacement-cell");
349
+
350
+ expect(focusManager.focused).toBe(sibling.current);
351
+ });
352
+
353
+ it("resolves a placeholder ancestor through its mounted registration", () => {
354
+ const findParent = jest
355
+ .spyOn(Tree.prototype, "findParent")
356
+ .mockReturnValueOnce(new TreeNode(null, "replacement-root", "", false));
357
+
358
+ focusManager.unregisterFocusable("replacement-rail");
359
+ findParent.mockRestore();
360
+
361
+ expect(focusManager.focused).toBe(root.current);
362
+ });
363
+
364
+ it("retains focus through child-first cleanup", () => {
365
+ focusManager.unregisterFocusable("replacement-cell");
366
+ expect(focusManager.focused).toBe(rail.current);
367
+
368
+ focusManager.unregisterFocusable("replacement-rail");
369
+ expect(focusManager.focused).toBe(root.current);
370
+ });
371
+
372
+ it("clears focus when the entire root containing the focused cell unregisters", () => {
373
+ focusManager.unregisterFocusable("replacement-root");
374
+ focusManager.unregisterFocusable("replacement-rail");
375
+ focusManager.unregisterFocusable("replacement-cell");
376
+
377
+ expect(focusManager.focusedId).toBeNull();
378
+ expect(focusManager.focused).toBeNull();
379
+ });
380
+ });
@@ -0,0 +1,208 @@
1
+ import { registerXrayToolbox, XrayToolSpec } from "../logger/xrayToolbox";
2
+
3
+ import { focusManager } from "./FocusManager";
4
+ import { TreeNode } from "./TreeNode";
5
+ import { Tree } from "./Tree";
6
+
7
+ import type { Touchable } from "@applicaster/zapp-react-native-ui-components/Components/Focusable/Touchable";
8
+
9
+ /**
10
+ * X-Ray `focus.*` toolbox for Android TV: lets an agent read and move focus by focusable id,
11
+ * without a remote and without depending on screen size or layout. It is built on the
12
+ * class-based FocusManager that Android uses (unlike tvOS, which uses the IIFE focus manager
13
+ * with its own native focus module).
14
+ *
15
+ * The manager's `focusedId` follows the native Android focus engine (the app's own code moves
16
+ * focus through the manager, and native focus events report back into it), and `setFocus`
17
+ * moves focus the same way the app's own code does. Registered by the android focus manager
18
+ * module; skipped when the X-Ray plugin has no React toolbox API (release builds).
19
+ */
20
+
21
+ type FocusManagerApi = {
22
+ focusedId: string | null;
23
+ isFocused: (id: string | number) => boolean;
24
+ setFocus: (newFocus: string, options?: unknown, context?: unknown) => void;
25
+ focused: Touchable | null | undefined;
26
+ };
27
+
28
+ /** `Tree` keeps its roots in a private field; this is the only access point to it. */
29
+ const internalTree = (manager: FocusManagerApi): Tree | undefined => {
30
+ const holder = manager as FocusManagerApi & { tree?: Tree };
31
+
32
+ return holder.tree;
33
+ };
34
+
35
+ /** The tree's roots, through the private field. */
36
+ const treeRoots = (tree: Tree): TreeNode[] =>
37
+ (tree as unknown as { tree: TreeNode[] }).tree;
38
+
39
+ const nodeProps = (node: TreeNode | null): { testID?: unknown } =>
40
+ (node?.component?.current?.props ?? {}) as { testID?: unknown };
41
+
42
+ /**
43
+ * The focused item. On Android the manager's `focusedId` is the focused focusable itself and
44
+ * follows the native engine, so no tree walk is needed (unlike tvOS, where it only tracks
45
+ * focus across groups).
46
+ */
47
+ const describeFocused = (manager: FocusManagerApi) => {
48
+ const itemId = manager.focusedId;
49
+
50
+ if (!itemId) return null;
51
+
52
+ const tree = internalTree(manager);
53
+ const node = tree?.find(itemId) ?? null;
54
+ const groups: string[] = [];
55
+
56
+ let parent = node?.parentId ? tree?.findParent(node.parentId) : null;
57
+
58
+ while (parent?.id && groups.length < 32) {
59
+ groups.push(parent.id);
60
+ parent = parent.parentId ? tree?.findParent(parent.parentId) : null;
61
+ }
62
+
63
+ const testID = nodeProps(node).testID;
64
+
65
+ return {
66
+ itemId,
67
+ groupId: node?.parentId ?? null,
68
+ testID: typeof testID === "string" ? testID : null,
69
+ groups,
70
+ };
71
+ };
72
+
73
+ type TreeView = {
74
+ id: string;
75
+ group?: true;
76
+ focused?: true;
77
+ testID?: string;
78
+ children?: TreeView[];
79
+ };
80
+
81
+ /** A node as the agent sees it: keys only when they say something, to keep large screens short. */
82
+ const toTreeView = (manager: FocusManagerApi, node: TreeNode): TreeView => {
83
+ const testID = nodeProps(node).testID;
84
+
85
+ const children = (node.children ?? []).map((child) =>
86
+ toTreeView(manager, child)
87
+ );
88
+
89
+ return {
90
+ id: node.id,
91
+ ...(node.isFocusableCell ? {} : { group: true as const }),
92
+ ...(manager.isFocused(node.id) ? { focused: true as const } : {}),
93
+ ...(typeof testID === "string" ? { testID } : {}),
94
+ ...(children.length ? { children } : {}),
95
+ };
96
+ };
97
+
98
+ const tools = (manager: FocusManagerApi): XrayToolSpec[] => [
99
+ {
100
+ name: "current",
101
+ description:
102
+ "The focused item: itemId, groupId, testID and the ids of its enclosing groups. null when nothing is.",
103
+ handler: () => describeFocused(manager),
104
+ },
105
+ {
106
+ name: "tree",
107
+ description:
108
+ "The focus manager's tree of registered Focusables: id, group: true for groups, focused: true on " +
109
+ "the focused item, testID, children. Only rendered Focusables are registered. A screen can hold " +
110
+ "hundreds; pass groupId for one group's subtree. Item ids are what set takes.",
111
+ parameters: [
112
+ {
113
+ name: "groupId",
114
+ type: "string",
115
+ description:
116
+ "Return only this group's subtree. Default: the whole tree.",
117
+ required: false,
118
+ },
119
+ ],
120
+ handler: ({ groupId }) => {
121
+ const tree = internalTree(manager);
122
+
123
+ if (!tree) throw new Error("Focus manager tree is not available");
124
+
125
+ if (groupId === undefined || groupId === null || groupId === "") {
126
+ return treeRoots(tree).map((root) => toTreeView(manager, root));
127
+ }
128
+
129
+ const node = tree.find(String(groupId));
130
+
131
+ if (!node) throw new Error(`No Focusable group "${groupId}"`);
132
+
133
+ return toTreeView(manager, node);
134
+ },
135
+ },
136
+ {
137
+ name: "set",
138
+ description:
139
+ "Focus an item through the focus manager (setFocus), as the app's own code does. " +
140
+ "focused: false when it did not land within 3 s (unknown ids, or the item is not rendered, e.g. " +
141
+ "scrolled out of a virtualised list). It replaces a focus the app is still setting, so call it " +
142
+ "once the screen is idle (ui.waitFor idle).",
143
+ parameters: [
144
+ {
145
+ name: "itemId",
146
+ type: "string",
147
+ description: "Focusable item id (from tree).",
148
+ },
149
+ ],
150
+ handler: ({ itemId }) =>
151
+ new Promise((resolve) => {
152
+ let done = false;
153
+
154
+ const finish = (result: { focused: boolean; timedOut?: boolean }) => {
155
+ if (done) return;
156
+
157
+ done = true;
158
+ resolve({ ...result, current: describeFocused(manager) });
159
+ };
160
+
161
+ const timer = setTimeout(
162
+ () => finish({ focused: false, timedOut: true }),
163
+ 3000
164
+ );
165
+
166
+ const poll = () => {
167
+ if (done) return;
168
+
169
+ if (manager.isFocused(String(itemId))) {
170
+ clearTimeout(timer);
171
+ finish({ focused: true });
172
+ } else {
173
+ setTimeout(poll, 50);
174
+ }
175
+ };
176
+
177
+ manager.setFocus(String(itemId));
178
+ setTimeout(poll, 50);
179
+ }),
180
+ },
181
+ {
182
+ name: "select",
183
+ description:
184
+ "Press select on the focused item, as the remote's click does.",
185
+ handler: () => {
186
+ const ref = manager.focused;
187
+
188
+ if (!ref?.onPress) {
189
+ throw new Error("Nothing selectable is focused");
190
+ }
191
+
192
+ // The app's focus callbacks pass the Touchable instance (ref.props.id), so onPress gets the instance too.
193
+ ref.onPress(ref);
194
+
195
+ return { selected: describeFocused(manager) };
196
+ },
197
+ },
198
+ ];
199
+
200
+ export const registerAndroidFocusToolbox = (
201
+ manager: FocusManagerApi = focusManager
202
+ ) =>
203
+ registerXrayToolbox({
204
+ name: "focus",
205
+ description:
206
+ "Android TV focus: current item, Focusable tree, focus by id, select.",
207
+ tools: tools(manager),
208
+ });
@@ -7,6 +7,7 @@ import { toBooleanWithDefaultTrue } from "../booleanUtils";
7
7
  import { isNilOrEmpty } from "../reactUtils/helpers";
8
8
  import { isAndroidTVPlatform } from "../reactUtils";
9
9
  import { noop } from "../functionUtils";
10
+ import { registerAndroidFocusToolbox } from "./focusToolbox";
10
11
 
11
12
  export function useFocusManager() {
12
13
  return focusManager;
@@ -132,3 +133,9 @@ export const useIsFocusable = (props: Props): void => {
132
133
  hasDataError,
133
134
  ]);
134
135
  };
136
+
137
+ // The Android focus manager registers the X-Ray focus toolbox itself (mirrors the tvOS focus
138
+ // manager); it is a no-op in builds without the X-Ray React toolbox bridge.
139
+ if (isAndroidTVPlatform()) {
140
+ registerAndroidFocusToolbox(focusManager);
141
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@applicaster/zapp-react-native-utils",
3
- "version": "17.0.0-alpha.1037440043",
3
+ "version": "17.0.0-alpha.1201533844",
4
4
  "description": "Applicaster Zapp React Native utilities package",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
@@ -27,7 +27,7 @@
27
27
  },
28
28
  "homepage": "https://github.com/applicaster/quickbrick#readme",
29
29
  "dependencies": {
30
- "@applicaster/applicaster-types": "17.0.0-alpha.1037440043",
30
+ "@applicaster/applicaster-types": "17.0.0-alpha.1201533844",
31
31
  "buffer": "^5.2.1",
32
32
  "camelize": "^1.0.0",
33
33
  "dayjs": "^1.11.10",
@@ -0,0 +1,73 @@
1
+ import {
2
+ isLgPlatform,
3
+ isSamsungPlatform,
4
+ isVizioPlatform,
5
+ } from "@applicaster/zapp-react-native-utils/reactUtils";
6
+
7
+ const UA = {
8
+ lg: "Mozilla/5.0 (Web0S; Linux/SmartTV) AppleWebKit/537.36 Chrome/87.0",
9
+ samsung: "Mozilla/5.0 (SMART-TV; Linux; Tizen 6.0) AppleWebKit/537.36",
10
+ vizio: "Mozilla/5.0 (X11; Linux) Chrome/76.0 VIZIO SmartCast Conjure/MTK",
11
+ desktop: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) Chrome/120.0",
12
+ };
13
+
14
+ const originalNavigator = window.navigator;
15
+
16
+ const setUserAgent = (userAgent) => {
17
+ Object.defineProperty(window, "navigator", {
18
+ value: { userAgent },
19
+ configurable: true,
20
+ });
21
+ };
22
+
23
+ describe("web TV device checks and the build-time device target", () => {
24
+ afterEach(() => {
25
+ delete process.env.QUICK_BRICK_DEVICE_TARGET;
26
+
27
+ Object.defineProperty(window, "navigator", {
28
+ value: originalNavigator,
29
+ configurable: true,
30
+ });
31
+ });
32
+
33
+ it("detects every TV at runtime when no device target is set", () => {
34
+ setUserAgent(UA.lg);
35
+ expect(isLgPlatform()).toBe(true);
36
+
37
+ setUserAgent(UA.samsung);
38
+ expect(isSamsungPlatform()).toBe(true);
39
+
40
+ setUserAgent(UA.vizio);
41
+ expect(isVizioPlatform()).toBe(true);
42
+ });
43
+
44
+ it("rejects other TVs on a Samsung build, whatever the user agent", () => {
45
+ process.env.QUICK_BRICK_DEVICE_TARGET = "samsung_tv";
46
+
47
+ setUserAgent(UA.lg);
48
+ expect(isLgPlatform()).toBe(false);
49
+
50
+ setUserAgent(UA.vizio);
51
+ expect(isVizioPlatform()).toBe(false);
52
+ });
53
+
54
+ it("still checks its own TV at runtime, so a desktop browser is not the TV", () => {
55
+ process.env.QUICK_BRICK_DEVICE_TARGET = "samsung_tv";
56
+
57
+ setUserAgent(UA.samsung);
58
+ expect(isSamsungPlatform()).toBe(true);
59
+
60
+ setUserAgent(UA.desktop);
61
+ expect(isSamsungPlatform()).toBe(false);
62
+ });
63
+
64
+ it("keeps a Vizio build's identity separate from LG", () => {
65
+ process.env.QUICK_BRICK_DEVICE_TARGET = "vizio";
66
+
67
+ setUserAgent(UA.lg);
68
+ expect(isLgPlatform()).toBe(false);
69
+
70
+ setUserAgent(UA.vizio);
71
+ expect(isVizioPlatform()).toBe(true);
72
+ });
73
+ });
@@ -129,7 +129,21 @@ export const hasWebOS = typeof window?.webOS !== "undefined";
129
129
 
130
130
  export const getUserAgent = () => window?.navigator?.userAgent;
131
131
 
132
+ /**
133
+ * Web TV device checks return false outright when the bundle was built for another
134
+ * TV: the web template inlines `process.env.QUICK_BRICK_DEVICE_TARGET` (Zapp
135
+ * `device_target`), so the guard and the code after it fold away at build time.
136
+ * A build for this TV still checks at runtime, because the same bundle also runs
137
+ * in a desktop browser.
138
+ */
132
139
  export const isLgPlatform = () => {
140
+ if (
141
+ process.env.QUICK_BRICK_DEVICE_TARGET &&
142
+ process.env.QUICK_BRICK_DEVICE_TARGET !== "lg_tv"
143
+ ) {
144
+ return false;
145
+ }
146
+
133
147
  const userAgent = getUserAgent();
134
148
 
135
149
  if (!userAgent) {
@@ -141,6 +155,13 @@ export const isLgPlatform = () => {
141
155
  };
142
156
 
143
157
  export const isSamsungPlatform = () => {
158
+ if (
159
+ process.env.QUICK_BRICK_DEVICE_TARGET &&
160
+ process.env.QUICK_BRICK_DEVICE_TARGET !== "samsung_tv"
161
+ ) {
162
+ return false;
163
+ }
164
+
144
165
  const userAgent = getUserAgent();
145
166
 
146
167
  if (!userAgent) {
@@ -161,6 +182,13 @@ export const isSamsungPlatform = () => {
161
182
  * before the VIZIO Companion Library has loaded
162
183
  */
163
184
  export const isVizioPlatform = () => {
185
+ if (
186
+ process.env.QUICK_BRICK_DEVICE_TARGET &&
187
+ process.env.QUICK_BRICK_DEVICE_TARGET !== "vizio"
188
+ ) {
189
+ return false;
190
+ }
191
+
164
192
  const userAgent = getUserAgent();
165
193
 
166
194
  if (!userAgent) {