@applicaster/zapp-react-native-utils 15.1.10 → 15.1.11-alpha.2710844646

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 (64) hide show
  1. package/actionsExecutor/ActionExecutor.ts +40 -2
  2. package/actionsExecutor/ActionExecutorContext.tsx +70 -16
  3. package/actionsExecutor/actions/__tests__/dismissBottomSheet.test.ts +22 -0
  4. package/actionsExecutor/actions/__tests__/loadItemsFromSource.test.ts +88 -0
  5. package/actionsExecutor/actions/__tests__/openBottomSheet.customContent.test.ts +76 -0
  6. package/actionsExecutor/actions/__tests__/openBottomSheet.inlineItems.test.ts +100 -0
  7. package/actionsExecutor/actions/dismissBottomSheet.ts +22 -0
  8. package/actionsExecutor/actions/index.ts +4 -0
  9. package/actionsExecutor/actions/openBottomSheet.ts +320 -0
  10. package/actionsExecutor/actions/refreshComponent.ts +6 -0
  11. package/actionsExecutor/actions/sendCloudEvent.ts +6 -1
  12. package/actionsExecutor/consts.ts +23 -0
  13. package/actionsExecutor/types.ts +1 -1
  14. package/appUtils/playerManager/OverlayObserver/OverlaysObserver.ts +5 -2
  15. package/appUtils/playerManager/OverlayObserver/__tests__/utils.test.ts +55 -2
  16. package/appUtils/playerManager/OverlayObserver/getUpcomingQueue.android.tv.ts +4 -0
  17. package/appUtils/playerManager/OverlayObserver/getUpcomingQueue.ios.tv.ts +4 -0
  18. package/appUtils/playerManager/OverlayObserver/getUpcomingQueue.ts +11 -0
  19. package/appUtils/playerManager/OverlayObserver/getUpcomingQueue.web.ts +4 -0
  20. package/appUtils/playerManager/OverlayObserver/utils.ts +51 -20
  21. package/arrayUtils/__tests__/reorderByIds.test.ts +50 -0
  22. package/arrayUtils/index.ts +79 -0
  23. package/configurationUtils/__tests__/modalBlocksParser.test.ts +107 -0
  24. package/configurationUtils/manifestKeyParser.ts +38 -9
  25. package/configurationUtils/modalBlocksParser.ts +178 -0
  26. package/entryActions/__tests__/buildEntryActions.test.ts +156 -0
  27. package/entryActions/aliasPresentation.ts +124 -0
  28. package/entryActions/buildEntryActions.ts +166 -0
  29. package/entryActions/index.ts +17 -0
  30. package/entryActions/types.ts +39 -0
  31. package/manifestUtils/defaultManifestConfigurations/player.js +22 -1
  32. package/manifestUtils/index.js +3 -0
  33. package/manifestUtils/modalBlocks.js +304 -0
  34. package/modalState/ContentViewModel.ts +113 -0
  35. package/modalState/EditableCollection.ts +17 -0
  36. package/modalState/EditableCollectionRegistry.ts +51 -0
  37. package/modalState/ModalOrchestrator.ts +199 -0
  38. package/modalState/RemoteEditableCollection.ts +227 -0
  39. package/modalState/__tests__/ContentViewModel.editable.test.ts +69 -0
  40. package/modalState/__tests__/ContentViewModel.test.ts +165 -0
  41. package/modalState/__tests__/EditableCollectionRegistry.test.ts +112 -0
  42. package/modalState/__tests__/ModalOrchestrator.phase3.test.ts +47 -0
  43. package/modalState/__tests__/RemoteEditableCollection.test.ts +326 -0
  44. package/modalState/__tests__/useBottomSheetContent.test.ts +349 -0
  45. package/modalState/index.ts +30 -83
  46. package/modalState/store.ts +102 -0
  47. package/modalState/types.ts +133 -0
  48. package/modalState/useBottomSheetContent.ts +102 -0
  49. package/package.json +2 -2
  50. package/playerUtils/__tests__/resolvePlayerActions.test.ts +138 -0
  51. package/playerUtils/index.ts +17 -1
  52. package/playerUtils/resolvePlayerActions.ts +71 -0
  53. package/reactHooks/actions/index.ts +67 -2
  54. package/reactHooks/usePluginConfiguration.ts +6 -3
  55. package/uiActionsRegistrator/__tests__/resolveActionIdentifiers.test.ts +93 -0
  56. package/uiActionsRegistrator/__tests__/subscribe.test.ts +107 -0
  57. package/uiActionsRegistrator/__tests__/usableActionItems.test.ts +52 -0
  58. package/uiActionsRegistrator/index.ts +25 -203
  59. package/uiActionsRegistrator/registry.ts +335 -0
  60. package/uiActionsRegistrator/resolveActionIdentifiers.ts +100 -0
  61. package/uiActionsRegistrator/usableActionItems.ts +66 -0
  62. package/playerUtils/__tests__/getPlayerActionButtons.test.ts +0 -54
  63. package/playerUtils/getPlayerActionButtons.ts +0 -17
  64. /package/reactHooks/actions/__tests__/{index.test.js → index.test.tsx} +0 -0
@@ -0,0 +1,320 @@
1
+ /// <reference types="@applicaster/applicaster-types" />
2
+ import {
3
+ PipesClientResponseHelper,
4
+ RequestBuilder,
5
+ } from "@applicaster/zapp-pipes-v2-client";
6
+ import uuidv4 from "uuid/v4";
7
+ import { modalOrchestrator } from "../../modalState/ModalOrchestrator";
8
+ import { openBottomSheetModal } from "../../modalState/store";
9
+ import {
10
+ DynamicCollectionOptions,
11
+ isPresentSubMenuAction,
12
+ Menu,
13
+ MenuItem,
14
+ Operation,
15
+ SelectionBehavior,
16
+ } from "../../modalState/types";
17
+ import { actionExecutor, ActionResult } from "../ActionExecutor";
18
+ import { createLogger } from "../../logger";
19
+
20
+ const { log_info, log_error } = createLogger({
21
+ subsystem: "ActionExecutorContext",
22
+ category: "General",
23
+ });
24
+
25
+ export type LoadedSheetContent = {
26
+ items: MenuItem[];
27
+ role?: string;
28
+ behavior?: SelectionBehavior;
29
+ dynamicCollection?: DynamicCollectionOptions;
30
+ };
31
+
32
+ /**
33
+ * Parse a raw `dynamic_collection_options` block (feed or inline content) into
34
+ * the typed `DynamicCollectionOptions`. `operations` accepts either a CSV
35
+ * string (feed) or an array (already parsed).
36
+ */
37
+ export function parseDynamicCollectionOptions(
38
+ raw:
39
+ | {
40
+ operations?: string | string[];
41
+ postUrl?: string;
42
+ provider?: string;
43
+ events?: Record<string, any[]>;
44
+ }
45
+ | undefined
46
+ ): DynamicCollectionOptions | undefined {
47
+ if (!raw) {
48
+ return undefined;
49
+ }
50
+
51
+ const operations = Array.isArray(raw.operations)
52
+ ? (raw.operations as Operation[])
53
+ : ((raw.operations || "").split(",").filter(Boolean) as Operation[]);
54
+
55
+ return {
56
+ operations,
57
+ postUrl: raw.postUrl,
58
+ provider: raw.provider,
59
+ events: raw.events,
60
+ };
61
+ }
62
+
63
+ /**
64
+ * Converts a ZappEntry from a pipes feed into a MenuItem.
65
+ * - Icon: first src found in the image media_group.
66
+ * - Primary action: taken from tap_actions.actions[0].
67
+ * - isSelected: true when entry.id is in currentSelection.
68
+ */
69
+ export function entryToMenuItem(
70
+ entry: ZappEntry,
71
+ currentSelection: string[] = []
72
+ ): MenuItem {
73
+ const imageGroup = entry.media_group?.find((g) => g.type === "image");
74
+
75
+ const firstImage = Array.isArray(imageGroup?.media_item)
76
+ ? imageGroup.media_item[0]
77
+ : imageGroup?.media_item;
78
+
79
+ // Primary action — first tap_action on the entry
80
+ const tapActions = entry.extensions?.tap_actions?.actions || [];
81
+ const primaryAction = tapActions.length > 0 ? tapActions[0] : undefined;
82
+
83
+ const summary = entry.summary as string;
84
+
85
+ const itemId = String(entry.id ?? entry.title ?? uuidv4());
86
+
87
+ return {
88
+ id: itemId,
89
+ title: entry.title as string,
90
+ summary,
91
+ icon: firstImage?.src,
92
+ isSelected: currentSelection.includes(itemId),
93
+ action: primaryAction,
94
+ entryActions: entry.extensions?.entry_action || [],
95
+ };
96
+ }
97
+
98
+ function parseCurrentSelection(rawSelection: unknown): string[] {
99
+ if (Array.isArray(rawSelection)) {
100
+ return (rawSelection as any[]).map(String);
101
+ }
102
+
103
+ if (rawSelection !== undefined && rawSelection !== null) {
104
+ return [String(rawSelection)];
105
+ }
106
+
107
+ return [];
108
+ }
109
+
110
+ function parseBehaviorFromFeed(
111
+ feed: ZappFeed | undefined,
112
+ currentSelection: string[]
113
+ ): SelectionBehavior | undefined {
114
+ const raw = feed?.extensions?.behavior;
115
+
116
+ if (!raw && currentSelection.length === 0) {
117
+ return undefined;
118
+ }
119
+
120
+ return {
121
+ selectMode: raw?.select_mode,
122
+ currentSelection,
123
+ selector: raw?.selector,
124
+ };
125
+ }
126
+
127
+ function parseBehaviorFromContentOptions(
128
+ content: Record<string, any> | undefined
129
+ ): SelectionBehavior | undefined {
130
+ const raw = content?.behavior ?? content?.extensions?.behavior;
131
+
132
+ if (!raw) {
133
+ return undefined;
134
+ }
135
+
136
+ return {
137
+ selectMode: raw.selectMode ?? raw.select_mode,
138
+ currentSelection: parseCurrentSelection(
139
+ raw.currentSelection ?? raw.current_selection
140
+ ),
141
+ selector: raw.selector,
142
+ };
143
+ }
144
+
145
+ // Exported so MultiLevelBottomSheetContent can lazy-load sub-levels
146
+ export async function loadItemsFromSource(
147
+ source: string,
148
+ context?: Record<string, any>
149
+ ): Promise<LoadedSheetContent> {
150
+ const requestBuilder = new RequestBuilder()
151
+ .setEntryContext(context?.entry || {})
152
+ .setScreenContext(context?.screenData || {})
153
+ .setUrl(source);
154
+
155
+ await requestBuilder.buildAxiosRequest();
156
+
157
+ const responseData = await requestBuilder.call<ZappFeed>();
158
+
159
+ const responseHelper = new PipesClientResponseHelper(responseData);
160
+
161
+ if (responseHelper.error) {
162
+ throw responseHelper.error;
163
+ }
164
+
165
+ const feed = responseData?.response as ZappFeed;
166
+
167
+ const currentSelection = parseCurrentSelection(
168
+ feed?.extensions?.behavior?.current_selection
169
+ );
170
+
171
+ const items = (feed?.entry || []).map((entry) =>
172
+ entryToMenuItem(entry, currentSelection)
173
+ );
174
+
175
+ const dynamicCollectionOptions = feed?.extensions?.dynamic_collection_options;
176
+
177
+ const dynamicCollection = parseDynamicCollectionOptions(
178
+ dynamicCollectionOptions
179
+ );
180
+
181
+ return {
182
+ items,
183
+ role: feed?.extensions?.role,
184
+ behavior: parseBehaviorFromFeed(feed, currentSelection),
185
+ dynamicCollection,
186
+ };
187
+ }
188
+
189
+ export async function openBottomSheetAction(
190
+ action: ActionType,
191
+ context?: Record<string, any>
192
+ ): Promise<ActionResult> {
193
+ try {
194
+ const { content, header, themePluginId, styleOverrides } =
195
+ action.options || {};
196
+
197
+ // Custom body component — keep default ModalComponent so standard header
198
+ // (dismiss x) is used; content.component is body-only (e.g. TextInputContent).
199
+ if (content?.component) {
200
+ log_info("openBottomSheet: using custom content component");
201
+
202
+ openBottomSheetModal({
203
+ modalBottomSheetContentProps: {
204
+ title: header?.title,
205
+ summary: header?.subtitle,
206
+ items: [],
207
+ onPress: () => {},
208
+ contentComponent: content.component,
209
+ contentComponentProps: content.props || {},
210
+ },
211
+ });
212
+
213
+ return ActionResult.Success;
214
+ }
215
+
216
+ const inlineItems: ZappEntry[] = content?.items;
217
+ const itemsUrl: string = content?.itemsUrl;
218
+
219
+ let items: MenuItem[];
220
+ let role: string | undefined;
221
+ let behavior: SelectionBehavior | undefined;
222
+
223
+ let dynamicCollection: DynamicCollectionOptions | undefined;
224
+
225
+ if (Array.isArray(inlineItems) && inlineItems.length > 0) {
226
+ log_info("openBottomSheet: using inline items from action options", {
227
+ count: inlineItems.length,
228
+ });
229
+
230
+ role = content?.role ?? content?.extensions?.role;
231
+ behavior = parseBehaviorFromContentOptions(content);
232
+
233
+ items = inlineItems.map((entry) =>
234
+ entryToMenuItem(entry, behavior?.currentSelection ?? [])
235
+ );
236
+
237
+ dynamicCollection = parseDynamicCollectionOptions(
238
+ content?.dynamicCollection ??
239
+ content?.extensions?.dynamic_collection_options
240
+ );
241
+ } else if (itemsUrl) {
242
+ log_info(`openBottomSheet: loading items from source: ${itemsUrl}`);
243
+
244
+ const loaded = await loadItemsFromSource(itemsUrl, context);
245
+ items = loaded.items;
246
+ role = loaded.role ?? content?.role ?? content?.extensions?.role;
247
+ behavior = loaded.behavior ?? parseBehaviorFromContentOptions(content);
248
+ dynamicCollection = loaded.dynamicCollection;
249
+
250
+ log_info(
251
+ `openBottomSheet: loaded ${items.length} items from source: ${itemsUrl}`
252
+ );
253
+ } else {
254
+ log_error(
255
+ "openBottomSheet: no itemsUrl, items, or content.component provided in action options"
256
+ );
257
+
258
+ return ActionResult.Error;
259
+ }
260
+
261
+ const menu: Menu = {
262
+ header: header
263
+ ? {
264
+ title: header.title,
265
+ subtitle: header.subtitle,
266
+ icon: header.icon,
267
+ }
268
+ : undefined,
269
+ content: {
270
+ title: content?.title ?? "",
271
+ items,
272
+ itemsUrl, // stored so the component can reload after an action
273
+ role,
274
+ behavior,
275
+ dynamicCollection,
276
+ themePluginId,
277
+ styleOverrides: styleOverrides ?? content?.styleOverrides,
278
+ },
279
+ };
280
+
281
+ /**
282
+ * Called when the user taps a menu item.
283
+ *
284
+ * - PresentSubMenuAction → handled by the orchestrator (pushes sub-menu)
285
+ * - Any other Action type → forwarded to the action executor, keeping the
286
+ * original execution context so screen/entry data is available to handlers.
287
+ * The pressed item is also added as `entry` so downstream actions can
288
+ * reference it.
289
+ */
290
+ const onItemPress = async (item: MenuItem): Promise<void> => {
291
+ if (!item.action || isPresentSubMenuAction(item.action)) {
292
+ // Submenu navigation is handled internally by the orchestrator
293
+ return;
294
+ }
295
+
296
+ await actionExecutor.handleAction(
297
+ item.action as ActionType,
298
+ {
299
+ ...context,
300
+ entry: item as any,
301
+ } as any
302
+ );
303
+ };
304
+
305
+ if (action.options?.replace) {
306
+ modalOrchestrator.replace(menu, onItemPress);
307
+ } else {
308
+ modalOrchestrator.open(menu, onItemPress);
309
+ }
310
+
311
+ return ActionResult.Success;
312
+ } catch (error) {
313
+ log_error("openBottomSheet: failed to open bottom sheet", {
314
+ error,
315
+ action,
316
+ });
317
+
318
+ return ActionResult.Error;
319
+ }
320
+ }
@@ -82,6 +82,12 @@ export const refreshComponentAction: ActionHandler = async (
82
82
  }) || source;
83
83
  }
84
84
 
85
+ if (!dataSource) {
86
+ log_info("handleAction: refreshComponent skipped: no dataSource found");
87
+
88
+ return ActionResult.Success;
89
+ }
90
+
85
91
  log_info(`handleAction: refreshComponent for dataSource:${dataSource}`, {
86
92
  source,
87
93
  inflatedUrl: dataSource,
@@ -62,10 +62,15 @@ export const sendCloudEventAction: ActionHandler<
62
62
  subject: options.subject || String((entry as ZappEntry)?.id || ""),
63
63
  });
64
64
 
65
- log_info("handleAction: sendCloudEvent event", { cloudEvent });
65
+ log_info("handleAction: sending sendCloudEvent to URL", {
66
+ url: options.url,
67
+ cloudEvent,
68
+ });
66
69
 
67
70
  const { error, code } = await sendCloudEvent(cloudEvent, options.url);
68
71
 
72
+ log_info("handleAction: sendCloudEvent result", { code, error });
73
+
69
74
  if (error) {
70
75
  log_error("sendCloudEvent: error sending cloud event", { error });
71
76
 
@@ -2,3 +2,26 @@ export const TOGGLE_FLAG_MAX_ITEMS_REACHED_EVENT =
2
2
  "action.localStorageToggleFlag.maxItemsReached";
3
3
 
4
4
  export const ACTION_EXECUTOR_EVENT_SOURCE = "ActionExecutor";
5
+
6
+ export const ACTION_TYPES = {
7
+ OPEN_BOTTOM_SHEET: "openBottomSheet",
8
+ DISMISS_BOTTOM_SHEET: "dismissBottomSheet",
9
+ PRESENT_SUB_MENU: "presentSubMenu",
10
+ SEND_CLOUD_EVENT: "sendCloudEvent",
11
+ NAVIGATE_TO_SCREEN: "navigateToScreen",
12
+ SHOW_TOAST: "showToast",
13
+ LOCAL_STORAGE_SET: "localStorageSet",
14
+ LOCAL_STORAGE_REMOVE: "localStorageRemove",
15
+ LOCAL_STORAGE_TOGGLE_FLAG: "localStorageToggleFlag",
16
+ SESSION_STORAGE_SET: "sessionStorageSet",
17
+ SESSION_STORAGE_REMOVE: "sessionStorageRemove",
18
+ SESSION_STORAGE_TOGGLE_FLAG: "sessionStorageToggleFlag",
19
+ REFRESH_COMPONENT: "refreshComponent",
20
+ SWITCH_LAYOUT: "switchLayout",
21
+ APP_RESTART: "appRestart",
22
+ CONFIRM_DIALOG: "confirmDialog",
23
+ SCREEN_SET_VARIABLE: "screenSetVariable",
24
+ SCREEN_TOGGLE_FLAG: "screenToggleFlag",
25
+ } as const;
26
+
27
+ export type KnownActionType = (typeof ACTION_TYPES)[keyof typeof ACTION_TYPES];
@@ -31,7 +31,7 @@ export interface ActionExecutionContext {
31
31
  /** Callback function for action completion */
32
32
  callback?: (result: { success: boolean; error: any; abort: boolean }) => void;
33
33
 
34
- screenState: Record<any, any>;
34
+ screenState?: Record<any, any>;
35
35
  }
36
36
 
37
37
  /**
@@ -3,8 +3,8 @@ import { distinctUntilChanged } from "rxjs/operators";
3
3
  import { Player } from "../player";
4
4
  import { createLogger, utilsLogger } from "../../../logger";
5
5
  import { appStore } from "@applicaster/zapp-react-native-redux/AppStore";
6
+ import { findPluginByIdentifier } from "../../../pluginUtils";
6
7
  import {
7
- findPluginByIdentifier,
8
8
  loadFeedEntry,
9
9
  loadFeedAndPrefetchThumbnailImage,
10
10
  parseTimeToSeconds,
@@ -252,7 +252,10 @@ export class OverlaysObserver {
252
252
  return;
253
253
  }
254
254
 
255
- const playNextFeedUrl: string = retrieveFeedUrl(this.entry);
255
+ const playNextFeedUrl: string = await retrieveFeedUrl(
256
+ this.entry,
257
+ plugins
258
+ );
256
259
 
257
260
  if (!playNextFeedUrl || typeof playNextFeedUrl !== "string") {
258
261
  log_debug(
@@ -1,13 +1,66 @@
1
+ const mockGetUpcomingQueue = jest.fn();
2
+
3
+ jest.mock("../getUpcomingQueue", () => ({
4
+ getUpcomingQueue: (...args: unknown[]) => mockGetUpcomingQueue(...args),
5
+ }));
6
+
1
7
  import { retrieveFeedUrl, retrievePlayPreviousFeedUrl } from "../utils";
2
8
 
3
9
  const entryWith = (extensions: Record<string, unknown>): ZappEntry =>
4
10
  ({ id: "1", type: { value: "video" }, extensions }) as ZappEntry;
5
11
 
12
+ const queuePlugin = { identifier: "queue-action" } as ZappPlugin;
13
+
6
14
  describe("playlist feed url accessors", () => {
7
- it("returns the next feed url when present", () => {
15
+ beforeEach(() => {
16
+ mockGetUpcomingQueue.mockReset();
17
+ });
18
+
19
+ it("returns the next feed url when present", async () => {
20
+ const entry = entryWith({ play_next_feed_url: "https://feeds/next.json" });
21
+
22
+ await expect(retrieveFeedUrl(entry, [])).resolves.toBe(
23
+ "https://feeds/next.json"
24
+ );
25
+ });
26
+
27
+ it("resolves to null for a missing entry", async () => {
28
+ await expect(
29
+ retrieveFeedUrl(undefined as unknown as ZappEntry, [])
30
+ ).resolves.toBeNull();
31
+ });
32
+
33
+ it("returns a queue play-next url when upcoming items exist", async () => {
34
+ mockGetUpcomingQueue.mockResolvedValue([{ id: "next-item" }]);
35
+
36
+ const entry = entryWith({
37
+ play_next_feed_url: "https://feeds/next.json",
38
+ queueItemId: "queue-1",
39
+ });
40
+
41
+ await expect(retrieveFeedUrl(entry, [queuePlugin])).resolves.toBe(
42
+ "pipesv2://queue-action/play-next?queueItemId=queue-1"
43
+ );
44
+ });
45
+
46
+ it("falls back to the next feed url when the upcoming queue is empty", async () => {
47
+ mockGetUpcomingQueue.mockResolvedValue([]);
48
+
49
+ const entry = entryWith({ play_next_feed_url: "https://feeds/next.json" });
50
+
51
+ await expect(retrieveFeedUrl(entry, [queuePlugin])).resolves.toBe(
52
+ "https://feeds/next.json"
53
+ );
54
+ });
55
+
56
+ it("falls back to the next feed url when QueueManager cannot be resolved", async () => {
57
+ mockGetUpcomingQueue.mockRejectedValue(new Error("not available"));
58
+
8
59
  const entry = entryWith({ play_next_feed_url: "https://feeds/next.json" });
9
60
 
10
- expect(retrieveFeedUrl(entry)).toBe("https://feeds/next.json");
61
+ await expect(retrieveFeedUrl(entry, [queuePlugin])).resolves.toBe(
62
+ "https://feeds/next.json"
63
+ );
11
64
  });
12
65
 
13
66
  it("returns the previous feed url when present", () => {
@@ -0,0 +1,4 @@
1
+ /** `queue-action` is not supported on this platform. See getUpcomingQueue.ts */
2
+ export const getUpcomingQueue = async (
3
+ _plugin?: QuickBrickPlugin | ZappPlugin
4
+ ): Promise<unknown[] | null> => null;
@@ -0,0 +1,4 @@
1
+ /** `queue-action` is not supported on this platform. See getUpcomingQueue.ts */
2
+ export const getUpcomingQueue = async (
3
+ _plugin?: QuickBrickPlugin | ZappPlugin
4
+ ): Promise<unknown[] | null> => null;
@@ -0,0 +1,11 @@
1
+ export const getUpcomingQueue = async (
2
+ plugin?: QuickBrickPlugin | ZappPlugin
3
+ ): Promise<unknown[] | null> => {
4
+ const QueueManager = (plugin as any)?.module?.QueueManager;
5
+
6
+ if (!QueueManager?.instance) {
7
+ return null;
8
+ }
9
+
10
+ return QueueManager.instance.getUpcomingQueue();
11
+ };
@@ -0,0 +1,4 @@
1
+ /** `queue-action` is not supported on this platform. See getUpcomingQueue.ts */
2
+ export const getUpcomingQueue = async (
3
+ _plugin?: QuickBrickPlugin | ZappPlugin
4
+ ): Promise<unknown[] | null> => null;
@@ -3,10 +3,13 @@ import {
3
3
  PipesClientResponseHelper,
4
4
  RequestBuilder,
5
5
  } from "@applicaster/zapp-pipes-v2-client";
6
+ import { appStore } from "@applicaster/zapp-react-native-redux/AppStore";
6
7
  import { log_error, log_info } from "./OverlaysObserver";
7
- import * as R from "ramda";
8
8
  import { toNumber, toNumberWithDefault } from "../../../numberUtils";
9
9
 
10
+ import { findPluginByIdentifier } from "../../../pluginUtils";
11
+ import { getUpcomingQueue } from "./getUpcomingQueue";
12
+
10
13
  export const parseTimeToSeconds = (timeStr: string): number => {
11
14
  const validationError = new Error("Invalid time format");
12
15
 
@@ -40,14 +43,58 @@ export const parseTimeToSeconds = (timeStr: string): number => {
40
43
  }
41
44
  };
42
45
 
43
- export const retrieveFeedUrl = (entry: ZappEntry) =>
44
- entry?.extensions?.play_next_feed_url;
46
+ /**
47
+ * HACK / TEMPORARY WORKAROUND:
48
+ * Resolves the play_next_feed_url dynamically for OverlaysObserver.
49
+ *
50
+ * WHY THIS IS HACKED HERE:
51
+ * OverlaysObserver was originally designed as a Recommendation Overlay engine (fetching static
52
+ * play_next_feed_url for overlay UI visuals). However, for dynamic queue & continuous audio playback,
53
+ * modifying feeds via `decorateFeed` at load time doesn't work (due to feed caching and mid-playback queue mutations).
54
+ * To avoid mutating feed payloads across the app, we temporarily intercept play_next_feed_url here
55
+ * at runtime to check if QueueManager has active/upcoming queue items.
56
+ *
57
+ * FUTURE ARCHITECTURE / TODO:
58
+ * Move queue/playlist resolution into a dedicated Player/Queue Provider module (or Handler Chain)
59
+ * on playerManager, decoupling Queue playback logic entirely from OverlaysObserver (which should
60
+ * strictly focus on recommendation visuals and chapter markers).
61
+ */
62
+ export const retrieveFeedUrl = async (
63
+ entry: ZappEntry,
64
+ plugins?: ZappPlugin[]
65
+ ): Promise<string> => {
66
+ if (!entry) return null;
67
+
68
+ const availablePlugins = plugins || appStore.get("plugins");
69
+
70
+ const queuePlugin = findPluginByIdentifier(
71
+ "queue-action",
72
+ availablePlugins,
73
+ true
74
+ );
75
+
76
+ if (queuePlugin) {
77
+ try {
78
+ const upcomingQueue = await getUpcomingQueue(queuePlugin);
79
+
80
+ if (upcomingQueue && upcomingQueue.length > 0) {
81
+ const queueItemId = entry?.extensions?.queueItemId || entry?.id;
82
+
83
+ return `pipesv2://queue-action/play-next?queueItemId=${queueItemId}`;
84
+ }
85
+ } catch (e) {
86
+ log_error("retrieveFeedUrl: Failed to resolve QueueManager", e);
87
+ }
88
+ }
89
+
90
+ return entry?.extensions?.play_next_feed_url;
91
+ };
45
92
 
46
93
  export const retrievePlayPreviousFeedUrl = (entry: ZappEntry) =>
47
94
  entry?.extensions?.play_previous_feed_url;
48
95
 
49
96
  export const retrieveOverlayDuration = (plugin) =>
50
- toNumberWithDefault(plugin?.configuration?.overlay_duration, 15);
97
+ toNumberWithDefault(15, plugin?.configuration?.overlay_duration);
51
98
 
52
99
  export const retrieveOverlayTriggerOffset = (item: ZappEntry) => {
53
100
  return item && item.extensions && item.extensions.overlay_timestamp
@@ -153,19 +200,3 @@ export const loadFeedAndPrefetchThumbnailImage = async (
153
200
 
154
201
  return playNextEntry;
155
202
  };
156
-
157
- export const findPluginByIdentifier = (
158
- identifier: string,
159
- plugins: ZappPlugin[]
160
- ): ZappPlugin => {
161
- if (!identifier) {
162
- return undefined;
163
- }
164
-
165
- const plugin = R.compose(
166
- R.find(R.propEq("identifier", identifier)),
167
- R.values
168
- )(plugins);
169
-
170
- return plugin;
171
- };
@@ -0,0 +1,50 @@
1
+ import { reorderByIds } from "../index";
2
+
3
+ describe("reorderByIds", () => {
4
+ const items = [
5
+ { id: "1", title: "Track 1" },
6
+ { id: "2", title: "Track 2" },
7
+ { id: "3", title: "Track 3" },
8
+ { id: "4", title: "Track 4" },
9
+ ];
10
+
11
+ it("returns an empty array if items is empty or nullish", () => {
12
+ expect(reorderByIds([], ["1"])).toEqual([]);
13
+ expect(reorderByIds(null as any, ["1"])).toEqual([]);
14
+ });
15
+
16
+ it("returns a copy of items if orderedIds is empty or nullish", () => {
17
+ expect(reorderByIds(items, [])).toEqual(items);
18
+ expect(reorderByIds(items, null as any)).toEqual(items);
19
+ });
20
+
21
+ it("reorders items based on the provided orderedIds sequence", () => {
22
+ const result = reorderByIds(items, ["3", "1", "4", "2"]);
23
+
24
+ expect(result.map((i) => i.id)).toEqual(["3", "1", "4", "2"]);
25
+ });
26
+
27
+ it("replaces items in their original slots when reordering a subset", () => {
28
+ const result = reorderByIds(items, ["4", "2"]);
29
+
30
+ expect(result.map((i) => i.id)).toEqual(["1", "4", "3", "2"]);
31
+ });
32
+
33
+ it("ignores IDs in orderedIds that do not exist in items", () => {
34
+ const result = reorderByIds(items, ["unknown", "3", "99", "1"]);
35
+
36
+ expect(result.map((i) => i.id)).toEqual(["3", "2", "1", "4"]);
37
+ });
38
+
39
+ it("supports custom getId selector function", () => {
40
+ const customItems = [
41
+ { key: "a", name: "Alpha" },
42
+ { key: "b", name: "Beta" },
43
+ { key: "c", name: "Gamma" },
44
+ ];
45
+
46
+ const result = reorderByIds(customItems, ["c", "a"], (item) => item.key);
47
+
48
+ expect(result.map((i) => i.key)).toEqual(["c", "b", "a"]);
49
+ });
50
+ });