@applicaster/zapp-react-native-utils 16.0.0-alpha.1344613091 → 16.0.0-alpha.1444784746

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 (153) hide show
  1. package/actionsExecutor/ActionExecutor.ts +50 -3
  2. package/actionsExecutor/ActionExecutorContext.tsx +99 -17
  3. package/actionsExecutor/__tests__/ActionExecutor.test.ts +71 -0
  4. package/actionsExecutor/__tests__/feedDecorator.test.ts +61 -0
  5. package/actionsExecutor/actions/__tests__/dismissBottomSheet.test.ts +25 -0
  6. package/actionsExecutor/actions/__tests__/goBack.test.ts +62 -0
  7. package/actionsExecutor/actions/__tests__/goHome.test.ts +19 -0
  8. package/actionsExecutor/actions/__tests__/loadItemsFromSource.test.ts +88 -0
  9. package/actionsExecutor/actions/__tests__/navigateToScreen.test.ts +133 -0
  10. package/actionsExecutor/actions/__tests__/openBottomSheet.customContent.test.ts +76 -0
  11. package/actionsExecutor/actions/__tests__/openBottomSheet.inlineItems.test.ts +300 -0
  12. package/actionsExecutor/actions/__tests__/presentScreen.test.ts +127 -0
  13. package/actionsExecutor/actions/__tests__/showAlert.test.ts +49 -0
  14. package/actionsExecutor/actions/__tests__/showToast.test.ts +88 -0
  15. package/actionsExecutor/actions/dismissBottomSheet.ts +23 -0
  16. package/actionsExecutor/actions/goBack.ts +60 -0
  17. package/actionsExecutor/actions/goHome.ts +31 -0
  18. package/actionsExecutor/actions/index.ts +12 -0
  19. package/actionsExecutor/actions/navigateToScreen.ts +53 -47
  20. package/actionsExecutor/actions/openBottomSheet.ts +338 -0
  21. package/actionsExecutor/actions/presentScreen.ts +78 -0
  22. package/actionsExecutor/actions/refreshComponent.ts +6 -0
  23. package/actionsExecutor/actions/sendCloudEvent.ts +6 -1
  24. package/actionsExecutor/actions/showAlert.ts +51 -0
  25. package/actionsExecutor/actions/showToast.ts +64 -8
  26. package/actionsExecutor/consts.ts +27 -0
  27. package/actionsExecutor/feedDecorator.ts +6 -6
  28. package/actionsExecutor/types.ts +1 -1
  29. package/analyticsUtils/PlayerAnalyticsManager.ts +1 -1
  30. package/appUtils/HooksManager/index.ts +9 -0
  31. package/appUtils/playerManager/OverlayObserver/OverlaysObserver.ts +142 -59
  32. package/appUtils/playerManager/OverlayObserver/__tests__/getUpcomingQueue.test.ts +67 -0
  33. package/appUtils/playerManager/OverlayObserver/__tests__/liveContent.test.ts +205 -0
  34. package/appUtils/playerManager/OverlayObserver/__tests__/utils.test.ts +56 -0
  35. package/appUtils/playerManager/OverlayObserver/getUpcomingQueue.android.tv.ts +4 -0
  36. package/appUtils/playerManager/OverlayObserver/getUpcomingQueue.ios.tv.ts +4 -0
  37. package/appUtils/playerManager/OverlayObserver/getUpcomingQueue.ts +24 -0
  38. package/appUtils/playerManager/OverlayObserver/getUpcomingQueue.web.ts +4 -0
  39. package/appUtils/playerManager/OverlayObserver/utils.ts +51 -20
  40. package/appUtils/playerManager/__tests__/playerContent.test.ts +403 -0
  41. package/appUtils/playerManager/__tests__/playerFactory.test.ts +1 -1
  42. package/appUtils/playerManager/__tests__/playerNative.test.ts +114 -0
  43. package/appUtils/playerManager/__tests__/playerNativeCommand.test.ts +62 -0
  44. package/appUtils/playerManager/__tests__/playerToolbox.test.ts +97 -0
  45. package/appUtils/playerManager/__tests__/usePlayerContent.test.tsx +64 -0
  46. package/appUtils/playerManager/{conts.ts → const.ts} +33 -0
  47. package/appUtils/playerManager/index.ts +3 -1
  48. package/appUtils/playerManager/player.ts +125 -3
  49. package/appUtils/playerManager/playerFactory.ts +1 -1
  50. package/appUtils/playerManager/playerNative.ts +28 -4
  51. package/appUtils/playerManager/playerNativeCommand.ts +3 -6
  52. package/appUtils/playerManager/playerToolbox.ts +192 -0
  53. package/appUtils/playerManager/usePlayerContent.tsx +43 -0
  54. package/appUtils/playerManager/usePlayerControllerSetup.tsx +1 -1
  55. package/appUtils/playerManager/userLanguagePreference.ts +1 -1
  56. package/arrayUtils/__tests__/{anyThruthy.test.ts → anyTruthy.test.ts} +8 -0
  57. package/arrayUtils/__tests__/arrayUtils.test.ts +165 -108
  58. package/arrayUtils/__tests__/isEmptyArray.test.ts +11 -0
  59. package/arrayUtils/__tests__/isFilledArray.test.ts +12 -0
  60. package/arrayUtils/__tests__/isFirst.test.ts +17 -0
  61. package/arrayUtils/__tests__/isIndexInRange.test.ts +14 -0
  62. package/arrayUtils/__tests__/isLast.test.ts +31 -0
  63. package/arrayUtils/__tests__/makeListOf.test.ts +31 -0
  64. package/arrayUtils/__tests__/makeListOfIndexes.test.ts +20 -0
  65. package/arrayUtils/__tests__/reorderByIds.test.ts +63 -0
  66. package/arrayUtils/__tests__/sample.test.ts +61 -0
  67. package/arrayUtils/index.ts +119 -20
  68. package/bottomSheet/__tests__/scrollContext.test.tsx +35 -0
  69. package/bottomSheet/index.ts +17 -0
  70. package/cellUtils/index.ts +30 -3
  71. package/configurationUtils/__tests__/manifestKeyParser.test.ts +21 -0
  72. package/configurationUtils/__tests__/modalBlocksParser.test.ts +269 -0
  73. package/configurationUtils/manifestKeyParser.ts +50 -10
  74. package/configurationUtils/modalBlocksParser.ts +214 -0
  75. package/entryActions/__tests__/buildEntryActions.test.ts +235 -0
  76. package/entryActions/aliasPresentation.ts +108 -0
  77. package/entryActions/buildEntryActions.ts +167 -0
  78. package/entryActions/index.ts +15 -0
  79. package/entryActions/types.ts +39 -0
  80. package/manifestUtils/__tests__/player.audioControls.test.js +158 -0
  81. package/manifestUtils/_internals/index.js +8 -3
  82. package/manifestUtils/defaultManifestConfigurations/generalContent.js +6 -0
  83. package/manifestUtils/defaultManifestConfigurations/player.js +349 -20
  84. package/manifestUtils/index.js +3 -0
  85. package/manifestUtils/modalBlocks.js +304 -0
  86. package/modalState/ContentViewModel.ts +113 -0
  87. package/modalState/EditableCollection.ts +17 -0
  88. package/modalState/EditableCollectionRegistry.ts +51 -0
  89. package/modalState/ModalOrchestrator.ts +212 -0
  90. package/modalState/RemoteEditableCollection.ts +235 -0
  91. package/modalState/__tests__/ContentViewModel.editable.test.ts +69 -0
  92. package/modalState/__tests__/ContentViewModel.test.ts +165 -0
  93. package/modalState/__tests__/EditableCollectionRegistry.test.ts +112 -0
  94. package/modalState/__tests__/ModalOrchestrator.phase3.test.ts +63 -0
  95. package/modalState/__tests__/RemoteEditableCollection.test.ts +415 -0
  96. package/modalState/__tests__/index.test.ts +30 -1
  97. package/modalState/__tests__/useBottomSheetContent.test.ts +349 -0
  98. package/modalState/__tests__/useModalStoreState.test.ts +142 -0
  99. package/modalState/index.ts +35 -83
  100. package/modalState/store.ts +109 -0
  101. package/modalState/types.ts +162 -0
  102. package/modalState/useBottomSheetContent.ts +109 -0
  103. package/numberUtils/__tests__/isMinusZero.test.ts +20 -0
  104. package/numberUtils/__tests__/isZero.test.ts +27 -0
  105. package/numberUtils/__tests__/requireNumber.test.ts +50 -0
  106. package/numberUtils/__tests__/toNumber.test.ts +27 -0
  107. package/numberUtils/__tests__/toNumberWithDefault.test.ts +64 -0
  108. package/numberUtils/__tests__/toNumberWithDefaultZero.test.ts +48 -0
  109. package/numberUtils/index.ts +27 -8
  110. package/package.json +2 -2
  111. package/playerUtils/__tests__/contentDataKeys.test.ts +297 -0
  112. package/playerUtils/__tests__/resolvePlayerActions.test.ts +138 -0
  113. package/playerUtils/__tests__/resolvePlayerTitleSubtitle.test.ts +180 -0
  114. package/playerUtils/contentDataKeys.ts +134 -0
  115. package/playerUtils/index.ts +37 -16
  116. package/playerUtils/isAudioItem.ts +26 -0
  117. package/playerUtils/resolvePlayerActions.ts +71 -0
  118. package/playerUtils/resolvePlayerTitleSubtitle.ts +76 -0
  119. package/pluginUtils/__tests__/pluginUtils.test.js +32 -0
  120. package/pluginUtils/index.ts +29 -0
  121. package/reactHooks/actions/index.ts +67 -2
  122. package/reactHooks/cell-click/__tests__/index.test.js +64 -0
  123. package/reactHooks/cell-click/index.ts +21 -14
  124. package/reactHooks/connection/index.tsx +8 -5
  125. package/reactHooks/feed/__tests__/useInflatedUrl.test.tsx +25 -0
  126. package/reactHooks/feed/__tests__/useMarkPipesDataStale.test.tsx +243 -0
  127. package/reactHooks/feed/useMarkPipesDataStale.ts +68 -23
  128. package/reactHooks/index.ts +2 -0
  129. package/reactHooks/layout/index.ts +1 -1
  130. package/reactHooks/navigation/__tests__/index.test.tsx +176 -1
  131. package/reactHooks/navigation/__tests__/usePresentScreen.test.ts +154 -0
  132. package/reactHooks/navigation/index.ts +2 -0
  133. package/reactHooks/navigation/usePresentScreen.ts +157 -0
  134. package/reactHooks/navigation/useRoute.ts +22 -5
  135. package/reactHooks/state/useComponentScreenState.ts +1 -1
  136. package/reactHooks/usePluginConfiguration.ts +4 -1
  137. package/reactHooks/utils/__tests__/index.test.js +22 -2
  138. package/reactHooks/utils/index.ts +11 -1
  139. package/stringUtils/__tests__/stringUtils.test.js +42 -0
  140. package/stringUtils/index.ts +2 -2
  141. package/uiActionsRegistrator/__tests__/resolveActionIdentifiers.test.ts +93 -0
  142. package/uiActionsRegistrator/__tests__/subscribe.test.ts +133 -0
  143. package/uiActionsRegistrator/__tests__/usableActionItems.test.ts +52 -0
  144. package/uiActionsRegistrator/index.ts +25 -203
  145. package/uiActionsRegistrator/registry.ts +351 -0
  146. package/uiActionsRegistrator/resolveActionIdentifiers.ts +100 -0
  147. package/uiActionsRegistrator/usableActionItems.ts +66 -0
  148. package/zappFrameworkUtils/__tests__/localStorageHelper.test.ts +146 -0
  149. package/zappFrameworkUtils/localStorageHelper.ts +19 -15
  150. package/appUtils/playerManager/usePlayerTitleSummaryOverlay.tsx +0 -56
  151. package/playerUtils/__tests__/getPlayerActionButtons.test.ts +0 -54
  152. package/playerUtils/getPlayerActionButtons.ts +0 -17
  153. /package/reactHooks/actions/__tests__/{index.test.js → index.test.tsx} +0 -0
@@ -0,0 +1,88 @@
1
+ import { showToastAction } from "../showToast";
2
+ import { postEvent } from "../../../reactHooks/useSubscriberFor";
3
+ import { ActionResult } from "../../ActionExecutor";
4
+
5
+ jest.mock("../../../reactHooks/useSubscriberFor", () => ({
6
+ postEvent: jest.fn(),
7
+ }));
8
+
9
+ describe("showToastAction", () => {
10
+ beforeEach(() => {
11
+ jest.clearAllMocks();
12
+ });
13
+
14
+ it("calls postEvent with confirmation source, default timeout, and returns Success", async () => {
15
+ const action = {
16
+ type: "showToast",
17
+ options: {
18
+ id: "toast-1",
19
+ message: "Added to queue",
20
+ extraMessage: "Extra info",
21
+ },
22
+ };
23
+
24
+ const result = await showToastAction(action);
25
+
26
+ expect(postEvent).toHaveBeenCalledTimes(1);
27
+
28
+ expect(postEvent).toHaveBeenCalledWith("showToast", [
29
+ {
30
+ id: "toast-1",
31
+ message: "Added to queue",
32
+ extraMessage: "Extra info",
33
+ style: undefined,
34
+ timeout: 5000,
35
+ source: "confirmation",
36
+ },
37
+ ]);
38
+
39
+ expect(result).toBe(ActionResult.Success);
40
+ });
41
+
42
+ it("preserves an explicit timeout and style override", async () => {
43
+ const action = {
44
+ type: "showToast",
45
+ options: {
46
+ message: "Playlist created",
47
+ timeout: 3000,
48
+ style: { backgroundColor: "#00FF00" },
49
+ },
50
+ };
51
+
52
+ await showToastAction(action);
53
+
54
+ expect(postEvent).toHaveBeenCalledWith("showToast", [
55
+ {
56
+ id: undefined,
57
+ message: "Playlist created",
58
+ extraMessage: undefined,
59
+ style: { backgroundColor: "#00FF00" },
60
+ timeout: 3000,
61
+ source: "confirmation",
62
+ },
63
+ ]);
64
+ });
65
+
66
+ it("handles missing or empty options without throwing", async () => {
67
+ const action = {
68
+ type: "showToast",
69
+ };
70
+
71
+ const result = await showToastAction(action);
72
+
73
+ expect(postEvent).toHaveBeenCalledTimes(1);
74
+
75
+ expect(postEvent).toHaveBeenCalledWith("showToast", [
76
+ {
77
+ id: undefined,
78
+ message: undefined,
79
+ extraMessage: undefined,
80
+ style: undefined,
81
+ timeout: 5000,
82
+ source: "confirmation",
83
+ },
84
+ ]);
85
+
86
+ expect(result).toBe(ActionResult.Success);
87
+ });
88
+ });
@@ -0,0 +1,23 @@
1
+ /// <reference types="@applicaster/applicaster-types" />
2
+ import { dismissModal, modalOrchestrator } from "../../modalState";
3
+ import { ActionResult } from "../ActionExecutor";
4
+ import { ActionHandler } from "../types";
5
+ import { createLogger } from "../../logger";
6
+
7
+ const { log_info } = createLogger({
8
+ subsystem: "ActionExecutorContext",
9
+ category: "General",
10
+ });
11
+
12
+ /**
13
+ * Dismisses the active bottom sheet / modal.
14
+ */
15
+ export const dismissBottomSheetAction: ActionHandler<
16
+ any
17
+ > = async (): Promise<ActionResult> => {
18
+ log_info("handleAction: dismissBottomSheet");
19
+ modalOrchestrator.close();
20
+ dismissModal();
21
+
22
+ return ActionResult.Success;
23
+ };
@@ -0,0 +1,60 @@
1
+ /// <reference types="@applicaster/applicaster-types" />
2
+ import { ActionResult } from "../ActionExecutor";
3
+ import { ActionHandler } from "../types";
4
+ import { createLogger } from "../../logger";
5
+
6
+ const { log_info } = createLogger({
7
+ subsystem: "ActionExecutorContext",
8
+ category: "General",
9
+ });
10
+
11
+ /**
12
+ * Options for the goBack action.
13
+ */
14
+ export interface GoBackOptions {
15
+ /**
16
+ * Navigate to the home screen when there is no screen to go back to.
17
+ * Defaults to true.
18
+ */
19
+ fallbackToHome?: boolean;
20
+
21
+ /**
22
+ * Go back to the first screen of the stack instead of the previous one.
23
+ * Defaults to false.
24
+ */
25
+ backToTop?: boolean;
26
+ }
27
+
28
+ /**
29
+ * Creates a go back action handler with the provided dependencies.
30
+ * This factory pattern allows the action to access navigation state at runtime.
31
+ *
32
+ * @param navigator - The app navigator performing the back navigation
33
+ * @returns An action handler that navigates back
34
+ */
35
+ export function createGoBackAction(
36
+ navigator: QuickBrickAppNavigator
37
+ ): ActionHandler<GoBackOptions> {
38
+ return async function goBackAction(action): Promise<ActionResult> {
39
+ const fallbackToHome = action.options?.fallbackToHome ?? true;
40
+ const backToTop = action.options?.backToTop ?? false;
41
+
42
+ // With fallbackToHome on, the navigator goes home on an empty stack by
43
+ // itself. The guard only matters when the caller opted out of that.
44
+ if (!fallbackToHome && !navigator.canGoBack()) {
45
+ log_info(
46
+ "goBack: no screen to go back to and fallbackToHome is disabled, ignoring"
47
+ );
48
+
49
+ return ActionResult.Error;
50
+ }
51
+
52
+ log_info(
53
+ `goBack: navigating back, fallbackToHome: ${fallbackToHome}, backToTop: ${backToTop}`
54
+ );
55
+
56
+ navigator.goBack(fallbackToHome, false, backToTop);
57
+
58
+ return ActionResult.Success;
59
+ };
60
+ }
@@ -0,0 +1,31 @@
1
+ /// <reference types="@applicaster/applicaster-types" />
2
+ import { ActionResult } from "../ActionExecutor";
3
+ import { ActionHandler } from "../types";
4
+ import { createLogger } from "../../logger";
5
+
6
+ const { log_info } = createLogger({
7
+ subsystem: "ActionExecutorContext",
8
+ category: "General",
9
+ });
10
+
11
+ /**
12
+ * Creates a go home action handler with the provided dependencies.
13
+ * This factory pattern allows the action to access navigation state at runtime.
14
+ *
15
+ * The navigator's `initialLaunch` flag is intentionally not exposed: it selects
16
+ * the offline home river during app bootstrap and is not a per-action choice.
17
+ *
18
+ * @param navigator - The app navigator performing the navigation
19
+ * @returns An action handler that navigates to the home screen
20
+ */
21
+ export function createGoHomeAction(
22
+ navigator: QuickBrickAppNavigator
23
+ ): ActionHandler {
24
+ return async function goHomeAction(): Promise<ActionResult> {
25
+ log_info("goHome: navigating to the home screen");
26
+
27
+ navigator.goHome();
28
+
29
+ return ActionResult.Success;
30
+ };
31
+ }
@@ -15,6 +15,8 @@ export { appRestartAction } from "./appRestart";
15
15
 
16
16
  export { confirmDialogAction } from "./confirmDialog";
17
17
 
18
+ export { showAlertAction } from "./showAlert";
19
+
18
20
  export { sendCloudEventAction } from "./sendCloudEvent";
19
21
 
20
22
  export { sessionStorageToggleFlagAction } from "./sessionStorageToggleFlag";
@@ -27,4 +29,14 @@ export { screenToggleFlagAction } from "./screenToggleFlag";
27
29
 
28
30
  export { createNavigateToScreenAction } from "./navigateToScreen";
29
31
 
32
+ export { createPresentScreenAction } from "./presentScreen";
33
+
34
+ export { createGoBackAction } from "./goBack";
35
+
36
+ export { createGoHomeAction } from "./goHome";
37
+
30
38
  export { showToastAction } from "./showToast";
39
+
40
+ export { openBottomSheetAction } from "./openBottomSheet";
41
+
42
+ export { dismissBottomSheetAction } from "./dismissBottomSheet";
@@ -25,6 +25,19 @@ export interface NavigateToScreenOptions {
25
25
  * - undefined to navigate to screen without entry
26
26
  */
27
27
  entry?: "@{entry/}" | ZappEntry;
28
+
29
+ /**
30
+ * Arbitrary values passed through to the destination screen.
31
+ *
32
+ * They are stored on the navigation route as `NavigationScreenData.options`
33
+ * and read on the target screen via `useNavigation().data?.options`. Use this
34
+ * to hand per-navigation parameters to a screen instead of routing them
35
+ * through module-level state.
36
+ *
37
+ * Note: `legacyScreenData()` does not carry these values, so they are not
38
+ * visible through `useCurrentScreenData()` / `useRoute()`.
39
+ */
40
+ navigationOptions?: Record<string, unknown>;
28
41
  }
29
42
 
30
43
  /**
@@ -46,15 +59,9 @@ export function createNavigateToScreenAction(
46
59
  context?: ActionExecutionContext
47
60
  ): Promise<ActionResult> {
48
61
  const screenType = action.options?.typeMapping;
49
-
50
- if (!screenType) {
51
- log_error("navigateToScreen: typeMapping option is missing");
52
-
53
- return ActionResult.Error;
54
- }
55
-
56
62
  const navigationAction = action.options?.navigationAction;
57
63
  const entrySource = action.options?.entry;
64
+ const navigationOptions = action.options?.navigationOptions;
58
65
 
59
66
  const entry = entrySource
60
67
  ? entrySource === "@{entry/}"
@@ -62,61 +69,60 @@ export function createNavigateToScreenAction(
62
69
  : entrySource
63
70
  : null;
64
71
 
72
+ let navigate =
73
+ navigationAction === "push" ? navigator.push : navigator.replace;
74
+
75
+ let navigaingEntry = entry;
76
+
65
77
  if (entry) {
66
- if (typeof entry !== "object") {
67
- log_error(
68
- `navigateToScreen: entry option is not an object, entry: ${entry}`
78
+ if (screenType) {
79
+ log_info(
80
+ `navigateToScreen: navigating to screen type: ${screenType} with entry id: ${entry.id}`
69
81
  );
70
82
 
71
- return ActionResult.Error;
83
+ navigaingEntry = {
84
+ ...entry,
85
+ type: {
86
+ value: screenType,
87
+ },
88
+ };
89
+
90
+ if (navigationAction === "push") {
91
+ navigate = navigator.push;
92
+ } else {
93
+ // Use replaceTop for entries since replace() only accepts ZappRiver
94
+ navigate = navigator.replaceTop;
95
+ }
72
96
  }
97
+ } else {
98
+ if (!screenType) {
99
+ log_error("navigateToScreen: typeMapping and entry option is missing");
73
100
 
74
- log_info(
75
- `navigateToScreen: navigating to screen type: ${screenType} with entry id: ${entry.id}`
76
- );
77
-
78
- const overriddenEntry: ZappEntry = {
79
- ...entry,
80
- type: {
81
- value: screenType,
82
- },
83
- };
84
-
85
- if (navigationAction === "push") {
86
- navigator.push(overriddenEntry);
87
- } else {
88
- // Use replaceTop for entries since replace() only accepts ZappRiver
89
- navigator.replaceTop(overriddenEntry);
101
+ return ActionResult.Error;
90
102
  }
91
103
 
92
- return ActionResult.Success;
93
- }
94
-
95
- const screenId = contentTypes?.[screenType]?.screen_id || null;
104
+ const screenId = contentTypes?.[screenType]?.screen_id || null;
105
+ const river = rivers?.[screenId];
96
106
 
97
- if (!screenId) {
98
- log_error(
99
- `navigateToScreen: can not resolve screen type mapping: ${screenType}`
100
- );
107
+ if (!screenId) {
108
+ log_error(
109
+ `navigateToScreen: can not resolve screen type mapping: ${screenType}`
110
+ );
101
111
 
102
- return ActionResult.Error;
103
- }
112
+ return ActionResult.Error;
113
+ }
104
114
 
105
- const river = rivers[screenId];
115
+ if (!river) {
116
+ log_error("navigateToScreen: can not resolve river");
106
117
 
107
- if (!river) {
108
- log_error("navigateToScreen: can not resolve river");
118
+ return ActionResult.Error;
119
+ }
109
120
 
110
- return ActionResult.Error;
121
+ navigaingEntry = river;
111
122
  }
112
123
 
113
124
  context?.callback?.({ success: false, error: null, abort: true });
114
-
115
- if (navigationAction === "push") {
116
- navigator.push(river);
117
- } else {
118
- navigator.replace(river);
119
- }
125
+ navigate(navigaingEntry, navigationOptions);
120
126
 
121
127
  return ActionResult.Success;
122
128
  };
@@ -0,0 +1,338 @@
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
+ getMenuItemActions,
12
+ isPresentSubMenuAction,
13
+ Menu,
14
+ MenuItem,
15
+ Operation,
16
+ SelectionBehavior,
17
+ } from "../../modalState/types";
18
+ import { actionExecutor, ActionResult } from "../ActionExecutor";
19
+ import { createLogger } from "../../logger";
20
+
21
+ const { log_info, log_error } = createLogger({
22
+ subsystem: "ActionExecutorContext",
23
+ category: "General",
24
+ });
25
+
26
+ export type LoadedSheetContent = {
27
+ items: MenuItem[];
28
+ role?: string;
29
+ behavior?: SelectionBehavior;
30
+ dynamicCollection?: DynamicCollectionOptions;
31
+ };
32
+
33
+ /**
34
+ * Parse a raw `dynamic_collection_options` block (feed or inline content) into
35
+ * the typed `DynamicCollectionOptions`. `operations` accepts either a CSV
36
+ * string (feed) or an array (already parsed).
37
+ */
38
+ export function parseDynamicCollectionOptions(
39
+ raw:
40
+ | {
41
+ operations?: string | string[];
42
+ postUrl?: string;
43
+ provider?: string;
44
+ events?: Record<string, any[]>;
45
+ }
46
+ | undefined
47
+ ): DynamicCollectionOptions | undefined {
48
+ if (!raw) {
49
+ return undefined;
50
+ }
51
+
52
+ const operations = Array.isArray(raw.operations)
53
+ ? (raw.operations as Operation[])
54
+ : ((raw.operations || "").split(",").filter(Boolean) as Operation[]);
55
+
56
+ return {
57
+ operations,
58
+ postUrl: raw.postUrl,
59
+ provider: raw.provider,
60
+ events: raw.events,
61
+ };
62
+ }
63
+
64
+ /**
65
+ * Converts a ZappEntry from a pipes feed into a MenuItem.
66
+ * - Icon: first src found in the image media_group.
67
+ * - Primary action: taken from tap_actions.actions[0].
68
+ * - isSelected: true when entry.id is in currentSelection.
69
+ */
70
+ export function entryToMenuItem(
71
+ entry: ZappEntry,
72
+ currentSelection: string[] = []
73
+ ): MenuItem {
74
+ const imageGroup = entry.media_group?.find((g) => g.type === "image");
75
+
76
+ const firstImage = Array.isArray(imageGroup?.media_item)
77
+ ? imageGroup.media_item[0]
78
+ : imageGroup?.media_item;
79
+
80
+ // Primary action — first tap_action on the entry
81
+ const tapActions = entry.extensions?.tap_actions?.actions || [];
82
+ const primaryAction = tapActions.length > 0 ? tapActions[0] : undefined;
83
+
84
+ const summary = entry.summary as string;
85
+
86
+ const itemId = String(entry.id ?? entry.title ?? uuidv4());
87
+
88
+ return {
89
+ id: itemId,
90
+ title: entry.title as string,
91
+ summary,
92
+ icon: firstImage?.src,
93
+ isSelected: currentSelection.includes(itemId),
94
+ action: primaryAction,
95
+ actions: tapActions,
96
+ entryActions: entry.extensions?.entry_action || [],
97
+ };
98
+ }
99
+
100
+ function parseCurrentSelection(rawSelection: unknown): string[] {
101
+ if (Array.isArray(rawSelection)) {
102
+ return (rawSelection as any[]).map(String);
103
+ }
104
+
105
+ if (rawSelection !== undefined && rawSelection !== null) {
106
+ return [String(rawSelection)];
107
+ }
108
+
109
+ return [];
110
+ }
111
+
112
+ function parseBehaviorFromFeed(
113
+ feed: ZappFeed | undefined,
114
+ currentSelection: string[]
115
+ ): SelectionBehavior | undefined {
116
+ const raw = feed?.extensions?.behavior;
117
+
118
+ if (!raw && currentSelection.length === 0) {
119
+ return undefined;
120
+ }
121
+
122
+ return {
123
+ selectMode: raw?.select_mode,
124
+ currentSelection,
125
+ selector: raw?.selector,
126
+ };
127
+ }
128
+
129
+ function parseBehaviorFromContentOptions(
130
+ content: Record<string, any> | undefined
131
+ ): SelectionBehavior | undefined {
132
+ const raw = content?.behavior ?? content?.extensions?.behavior;
133
+
134
+ if (!raw) {
135
+ return undefined;
136
+ }
137
+
138
+ return {
139
+ selectMode: raw.selectMode ?? raw.select_mode,
140
+ currentSelection: parseCurrentSelection(
141
+ raw.currentSelection ?? raw.current_selection
142
+ ),
143
+ selector: raw.selector,
144
+ };
145
+ }
146
+
147
+ // Exported so MultiLevelBottomSheetContent can lazy-load sub-levels
148
+ export async function loadItemsFromSource(
149
+ source: string,
150
+ context?: Record<string, any>
151
+ ): Promise<LoadedSheetContent> {
152
+ const requestBuilder = new RequestBuilder()
153
+ .setEntryContext(context?.entry || {})
154
+ .setScreenContext(context?.screenData || {})
155
+ .setUrl(source);
156
+
157
+ await requestBuilder.buildAxiosRequest();
158
+
159
+ const responseData = await requestBuilder.call<ZappFeed>();
160
+
161
+ const responseHelper = new PipesClientResponseHelper(responseData);
162
+
163
+ if (responseHelper.error) {
164
+ throw responseHelper.error;
165
+ }
166
+
167
+ const feed = responseData?.response as ZappFeed;
168
+
169
+ const currentSelection = parseCurrentSelection(
170
+ feed?.extensions?.behavior?.current_selection
171
+ );
172
+
173
+ const items = (feed?.entry || []).map((entry) =>
174
+ entryToMenuItem(entry, currentSelection)
175
+ );
176
+
177
+ const dynamicCollectionOptions = feed?.extensions?.dynamic_collection_options;
178
+
179
+ const dynamicCollection = parseDynamicCollectionOptions(
180
+ dynamicCollectionOptions
181
+ );
182
+
183
+ return {
184
+ items,
185
+ role: feed?.extensions?.role,
186
+ behavior: parseBehaviorFromFeed(feed, currentSelection),
187
+ dynamicCollection,
188
+ };
189
+ }
190
+
191
+ export async function openBottomSheetAction(
192
+ action: ActionType,
193
+ context?: Record<string, any>
194
+ ): Promise<ActionResult> {
195
+ try {
196
+ const { content, header, themePluginId, styleOverrides } =
197
+ action.options || {};
198
+
199
+ // Custom body component — keep default ModalComponent so standard header
200
+ // (dismiss x) is used; content.component is body-only (e.g. TextInputContent).
201
+ if (content?.component) {
202
+ log_info("openBottomSheet: using custom content component");
203
+
204
+ openBottomSheetModal({
205
+ modalBottomSheetContentProps: {
206
+ title: header?.title,
207
+ summary: header?.subtitle,
208
+ items: [],
209
+ onPress: () => {},
210
+ contentComponent: content.component,
211
+ contentComponentProps: {
212
+ ...(content.props || {}),
213
+ actionContext: context,
214
+ },
215
+ },
216
+ });
217
+
218
+ return ActionResult.Success;
219
+ }
220
+
221
+ const inlineItems: ZappEntry[] = content?.items;
222
+ const itemsUrl: string = content?.itemsUrl;
223
+
224
+ let items: MenuItem[];
225
+ let role: string | undefined;
226
+ let behavior: SelectionBehavior | undefined;
227
+
228
+ let dynamicCollection: DynamicCollectionOptions | undefined;
229
+
230
+ const rawDynamicCollection =
231
+ content?.dynamicCollection ??
232
+ content?.extensions?.dynamic_collection_options;
233
+
234
+ // An empty items array is a valid starting state for a provider-backed or
235
+ // offline collection. A sheet with neither items nor a source still errors.
236
+ const hasDynamicCollection = Boolean(rawDynamicCollection);
237
+
238
+ if (
239
+ Array.isArray(inlineItems) &&
240
+ (inlineItems.length > 0 || hasDynamicCollection)
241
+ ) {
242
+ log_info("openBottomSheet: using inline items from action options", {
243
+ count: inlineItems.length,
244
+ });
245
+
246
+ role = content?.role ?? content?.extensions?.role;
247
+ behavior = parseBehaviorFromContentOptions(content);
248
+
249
+ items = inlineItems.map((entry) =>
250
+ entryToMenuItem(entry, behavior?.currentSelection ?? [])
251
+ );
252
+
253
+ dynamicCollection = parseDynamicCollectionOptions(rawDynamicCollection);
254
+ } else if (itemsUrl) {
255
+ log_info(`openBottomSheet: loading items from source: ${itemsUrl}`);
256
+
257
+ const loaded = await loadItemsFromSource(itemsUrl, context);
258
+ items = loaded.items;
259
+ role = loaded.role ?? content?.role ?? content?.extensions?.role;
260
+ behavior = loaded.behavior ?? parseBehaviorFromContentOptions(content);
261
+ dynamicCollection = loaded.dynamicCollection;
262
+
263
+ log_info(
264
+ `openBottomSheet: loaded ${items.length} items from source: ${itemsUrl}`
265
+ );
266
+ } else {
267
+ log_error(
268
+ "openBottomSheet: no itemsUrl, items, or content.component provided in action options"
269
+ );
270
+
271
+ return ActionResult.Error;
272
+ }
273
+
274
+ const menu: Menu = {
275
+ header: header
276
+ ? {
277
+ title: header.title,
278
+ subtitle: header.subtitle,
279
+ icon: header.icon,
280
+ }
281
+ : undefined,
282
+ content: {
283
+ title: content?.title ?? "",
284
+ items,
285
+ itemsUrl, // stored so the component can reload after an action
286
+ role,
287
+ behavior,
288
+ dynamicCollection,
289
+ themePluginId,
290
+ styleOverrides: styleOverrides ?? content?.styleOverrides,
291
+ emptyMessage: content?.emptyMessage,
292
+ context,
293
+ },
294
+ };
295
+
296
+ /**
297
+ * Called when the user taps a menu item.
298
+ *
299
+ * - PresentSubMenuAction → handled by the orchestrator (pushes sub-menu)
300
+ * - Any other Action type → forwarded to the action executor, keeping the
301
+ * original execution context so screen/entry data is available to handlers.
302
+ * The pressed item is also added as `entry` so downstream actions can
303
+ * reference it.
304
+ */
305
+ const onItemPress = async (item: MenuItem): Promise<void> => {
306
+ const actions = getMenuItemActions(item);
307
+
308
+ const executableActions = actions.filter(
309
+ (action) => !isPresentSubMenuAction(action)
310
+ );
311
+
312
+ if (executableActions.length > 0) {
313
+ await actionExecutor.handleActions(
314
+ executableActions as ActionType[],
315
+ {
316
+ ...context,
317
+ entry: item as any,
318
+ } as any
319
+ );
320
+ }
321
+ };
322
+
323
+ if (action.options?.replace) {
324
+ modalOrchestrator.replace(menu, onItemPress);
325
+ } else {
326
+ modalOrchestrator.open(menu, onItemPress);
327
+ }
328
+
329
+ return ActionResult.Success;
330
+ } catch (error) {
331
+ log_error("openBottomSheet: failed to open bottom sheet", {
332
+ error,
333
+ action,
334
+ });
335
+
336
+ return ActionResult.Error;
337
+ }
338
+ }