@applicaster/zapp-react-native-utils 16.0.0-rc.98 → 17.0.0-alpha.1037440043

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 (152) hide show
  1. package/actionUtils/index.ts +3 -1
  2. package/actionsExecutor/ActionExecutor.ts +2 -2
  3. package/actionsExecutor/ActionExecutorContext.tsx +2 -2
  4. package/actionsExecutor/__tests__/StorageActions.test.ts +98 -0
  5. package/actionsExecutor/__tests__/feedDecorator.test.ts +30 -0
  6. package/actionsExecutor/__tests__/screenToggleFlag.test.ts +90 -0
  7. package/actionsExecutor/actions/__tests__/navigateToScreen.test.ts +186 -5
  8. package/actionsExecutor/actions/__tests__/openBottomSheet.customContent.test.ts +24 -0
  9. package/actionsExecutor/actions/__tests__/openBottomSheet.inlineItems.test.ts +72 -0
  10. package/actionsExecutor/actions/appRestart.ts +2 -2
  11. package/actionsExecutor/actions/confirmDialog.ts +2 -2
  12. package/actionsExecutor/actions/dismissBottomSheet.ts +2 -2
  13. package/actionsExecutor/actions/goBack.ts +2 -2
  14. package/actionsExecutor/actions/goHome.ts +2 -2
  15. package/actionsExecutor/actions/navigateToScreen.ts +35 -45
  16. package/actionsExecutor/actions/openBottomSheet.ts +4 -2
  17. package/actionsExecutor/actions/presentScreen.ts +2 -2
  18. package/actionsExecutor/actions/refreshComponent.ts +2 -2
  19. package/actionsExecutor/actions/screenToggleFlag.ts +1 -3
  20. package/actionsExecutor/actions/sendCloudEvent.ts +2 -2
  21. package/actionsExecutor/actions/showAlert.ts +2 -2
  22. package/actionsExecutor/actions/switchLayout.ts +2 -2
  23. package/actionsExecutor/feedDecorator.ts +8 -2
  24. package/actionsExecutor/types.ts +7 -0
  25. package/analyticsUtils/__tests__/playerAnalyticsSafeguard.test.ts +62 -0
  26. package/analyticsUtils/logger.ts +9 -4
  27. package/analyticsUtils/playerAnalyticsTracker.ts +1 -0
  28. package/appUtils/HooksManager/logger.ts +5 -2
  29. package/appUtils/accessibilityManager/logger.ts +2 -4
  30. package/appUtils/accessibilityManager/utils.ts +1 -1
  31. package/appUtils/contextKeysManager/__tests__/getKey/failure.test.ts +1 -22
  32. package/appUtils/contextKeysManager/__tests__/getKey/success/fullSearch.test.ts +1 -25
  33. package/appUtils/contextKeysManager/__tests__/getKey/success/searchInSecure.test.ts +1 -7
  34. package/appUtils/contextKeysManager/__tests__/removeKey/failure.test.ts +0 -25
  35. package/appUtils/contextKeysManager/__tests__/removeKey/success.test.ts +0 -6
  36. package/appUtils/contextKeysManager/__tests__/setKey/failure/failedToSaveInStorage.test.ts +0 -40
  37. package/appUtils/contextKeysManager/__tests__/setKey/{success/saveItemAndReference.test.ts → success.test.ts} +2 -42
  38. package/appUtils/contextKeysManager/index.ts +30 -131
  39. package/appUtils/focusManager/__tests__/focusManager.test.js +33 -0
  40. package/appUtils/focusManager/__tests__/focusToolbox.test.ts +357 -0
  41. package/appUtils/focusManager/focusToolbox.ts +223 -0
  42. package/appUtils/focusManager/index.ios.ts +7 -1
  43. package/appUtils/focusManager/index.ts +3 -3
  44. package/appUtils/focusManager/logger.ts +2 -2
  45. package/appUtils/focusManagerAux/index.ts +2 -2
  46. package/appUtils/orientationHelper.ts +2 -2
  47. package/appUtils/platform/platformUtils.ts +2 -2
  48. package/appUtils/playerManager/OverlayObserver/OverlaysObserver.ts +1 -1
  49. package/appUtils/playerManager/__tests__/playerDiagnostics.test.ts +62 -0
  50. package/appUtils/playerManager/__tests__/playerNative.test.ts +76 -0
  51. package/appUtils/playerManager/__tests__/playerNativeCommand.test.ts +62 -0
  52. package/appUtils/playerManager/__tests__/playerToolbox.test.ts +281 -0
  53. package/appUtils/playerManager/__tests__/usePlayerControllerSetup.test.tsx +62 -0
  54. package/appUtils/playerManager/const.ts +13 -0
  55. package/appUtils/playerManager/index.ts +9 -2
  56. package/appUtils/playerManager/player.ts +26 -1
  57. package/appUtils/playerManager/playerNative.ts +23 -1
  58. package/appUtils/playerManager/playerNativeCommand.ts +3 -6
  59. package/appUtils/playerManager/playerToolbox.ts +196 -0
  60. package/appUtils/playerManager/usePlayNextOverlay.tsx +2 -2
  61. package/appUtils/playerManager/usePlayerControllerSetup.tsx +6 -0
  62. package/appUtils/playerManager/userCellPlayerMutedPreference.ts +1 -1
  63. package/appUtils/playerManager/userLanguagePreference.ts +1 -1
  64. package/arrayUtils/__tests__/reorderByIds.test.ts +13 -0
  65. package/arrayUtils/index.ts +26 -43
  66. package/cellUtils/__tests__/getButtonsEnabled.test.ts +28 -0
  67. package/cellUtils/__tests__/getCellNavigationEnabled.test.ts +36 -0
  68. package/cellUtils/__tests__/getIsCellNavigationEnabled.test.ts +35 -0
  69. package/cellUtils/__tests__/isCellNavigationEnabled.test.ts +21 -0
  70. package/cellUtils/index.ts +40 -0
  71. package/cellUtils/logger.ts +2 -2
  72. package/configurationUtils/__tests__/modalBlocksParser.test.ts +134 -0
  73. package/configurationUtils/modalBlocksParser.ts +38 -0
  74. package/domUtils/logger.ts +2 -2
  75. package/entryActions/aliasPresentation.ts +1 -0
  76. package/entryActions/buildEntryActions.ts +1 -1
  77. package/focusManager/FocusManager.ts +26 -0
  78. package/focusManager/__tests__/FocusManager.test.ts +9 -0
  79. package/focusManager/logger.ts +2 -6
  80. package/headersUtils/index.ts +2 -2
  81. package/localizationUtils/index.ts +12 -6
  82. package/logger/__tests__/subsystems.test.ts +148 -0
  83. package/logger/__tests__/xrayToolbox.test.ts +69 -0
  84. package/logger/index.ts +48 -9
  85. package/logger/subsystems.ts +112 -0
  86. package/logger/xrayToolbox.ts +69 -0
  87. package/manifestUtils/__tests__/createConfig.test.js +17 -7
  88. package/manifestUtils/_internals/getDefaultConfiguration.js +9 -11
  89. package/manifestUtils/defaultManifestConfigurations/player.js +8 -0
  90. package/manifestUtils/keys.js +7 -2
  91. package/manifestUtils/mobileAction/container/__tests__/mobileActionButtonsContainer.test.js +21 -0
  92. package/manifestUtils/mobileAction/groups/__tests__/buildMobileActionButtonGroups.test.js +1 -1
  93. package/manifestUtils/mobileAction/groups/defaults.js +2 -1
  94. package/modalState/EditableCollectionRegistry.ts +1 -1
  95. package/modalState/ModalOrchestrator.ts +1 -0
  96. package/modalState/RemoteEditableCollection.ts +1 -1
  97. package/modalState/__tests__/ModalOrchestrator.phase3.test.ts +23 -0
  98. package/modalState/index.ts +2 -0
  99. package/modalState/types.ts +11 -0
  100. package/navigationUtils/index.ts +5 -2
  101. package/navigationUtils/xrayNavigator.ts +12 -0
  102. package/numberUtils/index.ts +2 -2
  103. package/package.json +3 -2
  104. package/playerUtils/PlayerTTS/PlayerTTS.ts +1 -1
  105. package/playerUtils/imaScriptDom.ts +1 -1
  106. package/playerUtils/useValidatePlayerConfig.tsx +1 -1
  107. package/pluginUtils/logger.ts +2 -2
  108. package/quickBrickAssets/__tests__/index.test.ts +18 -0
  109. package/quickBrickAssets/index.ts +35 -0
  110. package/reactHooks/__tests__/getPluginConfiguration.test.ts +82 -0
  111. package/reactHooks/actions/index.ts +29 -23
  112. package/reactHooks/cell-click/__tests__/index.test.js +67 -1
  113. package/reactHooks/cell-click/index.ts +10 -2
  114. package/reactHooks/connection/index.tsx +8 -5
  115. package/reactHooks/feed/__tests__/feedInvalidation.test.tsx +338 -0
  116. package/reactHooks/feed/__tests__/useBatchLoading.test.tsx +8 -2
  117. package/reactHooks/feed/__tests__/useMarkPipesDataStale.test.tsx +243 -0
  118. package/reactHooks/feed/useBuildPipesUrl.ts +5 -2
  119. package/reactHooks/feed/useFeedLoader.tsx +30 -3
  120. package/reactHooks/feed/useLoadPipesDataDispatch.ts +12 -11
  121. package/reactHooks/feed/useMarkPipesDataStale.ts +68 -23
  122. package/reactHooks/hookModal/hooks/useHookModalScreenData.ts +5 -2
  123. package/reactHooks/logger.ts +5 -2
  124. package/reactHooks/navigation/usePresentScreen.ts +2 -2
  125. package/reactHooks/player/TVSeekControlller/TVSeekController.ts +2 -2
  126. package/reactHooks/screen/useScreenData.ts +2 -2
  127. package/reactHooks/usePluginConfiguration.ts +84 -46
  128. package/reactHooks/videoModal/hooks/useChangeOrientation.ts +2 -7
  129. package/reactHooks/videoModal/hooks/useVideoModalScreenData.tsx +1 -1
  130. package/reactUtils/createContext/helpers.ts +2 -2
  131. package/reactUtils/logger.ts +2 -2
  132. package/riverComponetsMeasurementProvider/index.tsx +5 -5
  133. package/storage/ScreenSingleValueProvider.ts +1 -1
  134. package/storage/ScreenStateMultiSelectProvider.ts +1 -1
  135. package/storage/StorageMultiSelectProvider.ts +1 -1
  136. package/storage/StorageSingleSelectProvider.ts +1 -1
  137. package/stylesUtils/logger.ts +2 -2
  138. package/uiActionsRegistrator/__tests__/subscribe.test.ts +26 -0
  139. package/uiActionsRegistrator/registry.ts +17 -1
  140. package/uiActionsRegistrator/resolveActionIdentifiers.ts +1 -1
  141. package/uiActionsRegistrator/usableActionItems.ts +1 -1
  142. package/zappFrameworkUtils/HookCallback/callbackNavigationAction.ts +2 -1
  143. package/zappFrameworkUtils/loginPluginUtils.ts +2 -1
  144. package/zappFrameworkUtils/presentPluginOneTime.ts +2 -1
  145. package/appUtils/contextKeysManager/__tests__/getKey/success/byReference.test.ts +0 -56
  146. package/appUtils/contextKeysManager/__tests__/getKeyByReference/failure.test.ts +0 -265
  147. package/appUtils/contextKeysManager/__tests__/getKeyByReference/success.test.ts +0 -303
  148. package/appUtils/contextKeysManager/__tests__/removeReferenceForKey/failure.test.ts +0 -82
  149. package/appUtils/contextKeysManager/__tests__/removeReferenceForKey/success.test.ts +0 -41
  150. package/appUtils/contextKeysManager/__tests__/setKey/success/saveItemButNotReference.test.ts +0 -208
  151. package/appUtils/contextKeysManager/__tests__/setReferenceForKey/failure.test.ts +0 -93
  152. package/appUtils/contextKeysManager/__tests__/setReferenceForKey/success.test.ts +0 -45
@@ -0,0 +1,82 @@
1
+ import { renderHook } from "@testing-library/react-native";
2
+
3
+ const plugin = {
4
+ identifier: "cast",
5
+ configuration: {
6
+ title: "Configured",
7
+ localizations: { fr: { close: "Fermer" } },
8
+ },
9
+ };
10
+
11
+ jest.mock("@applicaster/zapp-react-native-redux/hooks", () => ({
12
+ usePlugins: () => [plugin],
13
+ }));
14
+
15
+ jest.mock(
16
+ "@applicaster/zapp-react-native-utils/appUtils/localizationsHelper",
17
+ () => ({ getUILanguage: () => "fr" })
18
+ );
19
+
20
+ import {
21
+ getPluginConfiguration,
22
+ mergeLocalizations,
23
+ usePluginConfiguration,
24
+ } from "../usePluginConfiguration";
25
+
26
+ const manifest = {
27
+ custom_configuration_fields: [
28
+ { key: "title", initial_value: "Default" },
29
+ { key: "color", initial_value: "red" },
30
+ ],
31
+ localizations: {
32
+ fields: [
33
+ { key: "close", initial_value: "Close" },
34
+ { key: "cancel", initial_value: "Cancel" },
35
+ ],
36
+ },
37
+ };
38
+
39
+ it("matches usePluginConfiguration outside React", () => {
40
+ const { result } = renderHook(() => usePluginConfiguration("cast", manifest));
41
+
42
+ expect(getPluginConfiguration(plugin, manifest)).toEqual(result.current);
43
+ });
44
+
45
+ // Expected values are what R.mergeDeepWith((l, r) => (isNil(l) ? r : l)) returned before ramda was removed
46
+ describe("mergeLocalizations", () => {
47
+ const defaults = { en: { close: "Close", cancel: "Cancel" } };
48
+
49
+ it("returns the defaults when nothing is configured", () => {
50
+ expect(mergeLocalizations(undefined, defaults)).toEqual(defaults);
51
+ });
52
+
53
+ it("keeps configured values, fills nil ones and missing keys from defaults", () => {
54
+ expect(
55
+ mergeLocalizations(
56
+ { en: { close: null, extra: "X" }, fr: { close: "Fermer" } },
57
+ defaults
58
+ )
59
+ ).toEqual({
60
+ en: { close: "Close", extra: "X", cancel: "Cancel" },
61
+ fr: { close: "Fermer" },
62
+ });
63
+ });
64
+
65
+ it("does not merge arrays", () => {
66
+ expect(
67
+ mergeLocalizations(
68
+ { en: { close: ["a"] } },
69
+ { en: { close: ["b"], cancel: "C" } }
70
+ )
71
+ ).toEqual({ en: { close: ["a"], cancel: "C" } });
72
+ });
73
+ });
74
+
75
+ it("keeps configured languages first, so the fallback language stays the configured one", () => {
76
+ const merged = mergeLocalizations(
77
+ { he: { close: "סגור" }, en: { close: "Close it" } },
78
+ { en: { close: "Close" } }
79
+ );
80
+
81
+ expect(Object.keys(merged)).toEqual(["he", "en"]);
82
+ });
@@ -21,17 +21,45 @@ type ActionContexts<T = unknown> = {
21
21
  };
22
22
 
23
23
  /**
24
- * React Hook to subscribe to the custom action context
24
+ * A value that changes whenever a provider is added to or removed from
25
+ * `uiActionsRegistry`.
26
+ *
27
+ * Providers can register after the UI that wants them has rendered - the audio
28
+ * player registers playback speed only once its controller has state, and
29
+ * plugin-backed actions are bridged in from an effect. Put this in the
30
+ * dependency list of anything that resolves actions, so the list is re-read
31
+ * instead of being frozen at first paint.
32
+ */
33
+ export function useRegistryRevision(): number {
34
+ const [revision, setRevision] = useState(0);
35
+
36
+ useEffect(
37
+ () =>
38
+ uiActionsRegistry.subscribe(() => setRevision((current) => current + 1)),
39
+ []
40
+ );
41
+
42
+ return revision;
43
+ }
44
+
45
+ /**
46
+ * Resolves a legacy action context or falls back to the UI action registry.
25
47
  * @param {*} plugId - subscribes to the context of that action plugin
26
48
  * @return {*} - global action provider context or context for specific action plugin
27
49
  */
28
50
  export function useActions<T = unknown>(plugId: string): any {
29
51
  const [logged, setLogged] = useState(false);
30
52
  const context = useContext<ActionContexts<T>>(ActionsContext);
53
+ useRegistryRevision();
54
+
31
55
  const actionContext = context?.actions?.[plugId]?.module?.context;
32
56
 
33
57
  if (plugId) {
34
58
  if (!actionContext) {
59
+ const registeredAction = uiActionsRegistry.getAction(plugId);
60
+
61
+ if (registeredAction) return registeredAction;
62
+
35
63
  if (!logged) {
36
64
  logger.warning({
37
65
  message: `useActions: Couldn't find an action for ${plugId} plugin`,
@@ -139,25 +167,3 @@ export function useEntryActionState(
139
167
 
140
168
  return { state, invokeAction };
141
169
  }
142
-
143
- /**
144
- * A value that changes whenever a provider is added to or removed from
145
- * `uiActionsRegistry`.
146
- *
147
- * Providers can register after the UI that wants them has rendered - the audio
148
- * player registers playback speed only once its controller has state, and
149
- * plugin-backed actions are bridged in from an effect. Put this in the
150
- * dependency list of anything that resolves actions, so the list is re-read
151
- * instead of being frozen at first paint.
152
- */
153
- export function useRegistryRevision(): number {
154
- const [revision, setRevision] = useState(0);
155
-
156
- useEffect(
157
- () =>
158
- uiActionsRegistry.subscribe(() => setRevision((current) => current + 1)),
159
- []
160
- );
161
-
162
- return revision;
163
- }
@@ -33,12 +33,14 @@ jest.mock("@applicaster/zapp-react-native-utils/reactHooks/screen", () => ({
33
33
  useScreenContext: jest.fn(() => ({})),
34
34
  }));
35
35
 
36
+ const mockSetEntryContext = jest.fn();
37
+
36
38
  jest.mock("@applicaster/zapp-react-native-ui-components/Contexts", () => ({
37
39
  ...jest.requireActual(
38
40
  "@applicaster/zapp-react-native-ui-components/Contexts"
39
41
  ),
40
42
  ZappPipesEntryContext: {
41
- useZappPipesContext: jest.fn(() => [undefined, jest.fn()]),
43
+ useZappPipesContext: jest.fn(() => [undefined, mockSetEntryContext]),
42
44
  },
43
45
  }));
44
46
 
@@ -159,4 +161,68 @@ describe("useCellClick", () => {
159
161
 
160
162
  cleanup();
161
163
  });
164
+
165
+ describe("entry context", () => {
166
+ const tapWith = async (item) => {
167
+ mockSetEntryContext.mockClear();
168
+ actionExecutor.handleEntryActions.mockClear();
169
+
170
+ const { result } = renderHook(() => useCellClick({ item }), {
171
+ wrapper: actionExecutorWrapper,
172
+ });
173
+
174
+ await result.current();
175
+ cleanup();
176
+ };
177
+
178
+ it("is not set on a tap of an action cell", async () => {
179
+ await tapWith({
180
+ id: "team-1",
181
+ type: { value: "action" },
182
+ extensions: {
183
+ tap_actions: {
184
+ actions: [
185
+ { type: "localStorageToggleFlag" },
186
+ { type: "sendCloudEvent" },
187
+ ],
188
+ },
189
+ },
190
+ });
191
+
192
+ expect(mockSetEntryContext).not.toHaveBeenCalled();
193
+ });
194
+
195
+ it("is handed to the actions so an action can set it", async () => {
196
+ await tapWith({
197
+ id: "link-1",
198
+ type: { value: "action" },
199
+ extensions: {
200
+ tap_actions: { actions: [{ type: "navigateToScreen" }] },
201
+ },
202
+ });
203
+
204
+ expect(actionExecutor.handleEntryActions).toHaveBeenCalledWith(
205
+ expect.objectContaining({ id: "link-1" }),
206
+ expect.objectContaining({ setEntryContext: mockSetEntryContext })
207
+ );
208
+ });
209
+
210
+ it("is set after the actions for any other cell", async () => {
211
+ await tapWith({
212
+ id: "episode-2",
213
+ type: { value: "feed" },
214
+ extensions: {
215
+ tap_actions: { actions: [{ type: "localStorageToggleFlag" }] },
216
+ },
217
+ });
218
+
219
+ expect(mockSetEntryContext).toHaveBeenCalledWith(
220
+ expect.objectContaining({ id: "episode-2" })
221
+ );
222
+
223
+ expect(
224
+ actionExecutor.handleEntryActions.mock.invocationCallOrder[0]
225
+ ).toBeLessThan(mockSetEntryContext.mock.invocationCallOrder[0]);
226
+ });
227
+ });
162
228
  });
@@ -71,7 +71,6 @@ export const useCellClick = ({
71
71
  // Making sure we are not getting GestureResponderEvent in here.
72
72
  const isZappEntry = _item?.id && _item?.type;
73
73
  const selectedItem = isZappEntry ? _item : item;
74
- setEntryContext?.(selectedItem);
75
74
 
76
75
  if (!selectedItem?.type?.value) {
77
76
  warnEmptyContentType(selectedItem);
@@ -91,6 +90,7 @@ export const useCellClick = ({
91
90
 
92
91
  if (selectedItem) {
93
92
  await actionExecutor?.handleEntryActions(selectedItem, {
93
+ setEntryContext,
94
94
  component,
95
95
  screenData,
96
96
  screenState,
@@ -107,7 +107,15 @@ export const useCellClick = ({
107
107
  url: selectedItem.link.href,
108
108
  });
109
109
  }
110
- } else if (isFunction(onCellTap)) {
110
+
111
+ // An action cell does not open a screen by itself: the actions that do
112
+ // (navigateToScreen) set the entry context for it.
113
+ return;
114
+ }
115
+
116
+ setEntryContext?.(selectedItem);
117
+
118
+ if (isFunction(onCellTap)) {
111
119
  onCellTap?.(selectedItem, _index);
112
120
  } else if (!finishesHook) {
113
121
  // finishHook already completes the hook and navigates to the original
@@ -4,6 +4,11 @@ import { NetInfoState } from "@react-native-community/netinfo";
4
4
  import { NetworkStatusContext } from "@applicaster/zapp-react-native-ui-components/Contexts/NetworkStatusContext";
5
5
  import { isOnline } from "@applicaster/quick-brick-core/App/NetworkStatusProvider/utils";
6
6
 
7
+ type ConnectionInfo = NetInfoState & {
8
+ deviceStatus: NetStatus;
9
+ stillOfflineAfterResumeCount?: number;
10
+ };
11
+
7
12
  /**
8
13
  * This hook returns connection type from RN NetInfo component or boolean for iConnected if justOnlineStatus flag is set
9
14
  * @param {boolean} justOnlineStatus - flag if to return boolean for isConnected
@@ -12,16 +17,14 @@ import { isOnline } from "@applicaster/quick-brick-core/App/NetworkStatusProvide
12
17
 
13
18
  export function useConnectionInfo(justOnlineStatus: true): boolean;
14
19
 
15
- export function useConnectionInfo(
16
- justOnlineStatus: false
17
- ): NetInfoState & { deviceStatus: NetStatus };
20
+ export function useConnectionInfo(justOnlineStatus: false): ConnectionInfo;
18
21
 
19
22
  export function useConnectionInfo(
20
23
  justOnlineStatus: boolean
21
- ): boolean | (NetInfoState & { deviceStatus: NetStatus }) {
24
+ ): boolean | ConnectionInfo {
22
25
  const connectionInfo = React.useContext(
23
26
  NetworkStatusContext
24
- ) as NetInfoState & { deviceStatus: NetStatus };
27
+ ) as ConnectionInfo;
25
28
 
26
29
  return justOnlineStatus ? isOnline(connectionInfo) === true : connectionInfo;
27
30
  }
@@ -0,0 +1,338 @@
1
+ import React from "react";
2
+ import { Provider } from "react-redux";
3
+ import { configureStore } from "@reduxjs/toolkit";
4
+ import { act, renderHook } from "@testing-library/react-native";
5
+ import reducer, {
6
+ loadPipesData,
7
+ unsubscribeFromDataSource,
8
+ zappPipesClear,
9
+ } from "@applicaster/zapp-react-native-redux/ZappPipes";
10
+ import { zappPipesMiddleware } from "../../../../zapp-react-native-redux/ZappPipes/middleware";
11
+ import { useFeedLoader } from "../useFeedLoader";
12
+
13
+ const mockGet = jest.fn();
14
+ const mockPost = jest.fn();
15
+ const mockSubscribe = jest.fn();
16
+ const mockRelease = jest.fn();
17
+ let mockChange: () => void;
18
+ let mockLoad: ReturnType<typeof jest.fn>;
19
+
20
+ jest.mock("@applicaster/zapp-pipes-v2-client", () => ({
21
+ __esModule: true,
22
+ default: jest.fn(() => ({
23
+ get: (...args) => mockGet(...args),
24
+ post: (...args) => mockPost(...args),
25
+ })),
26
+ RequestBuilder: jest.fn(() => ({
27
+ setResolvers() {
28
+ return this;
29
+ },
30
+ build: async () => ({}),
31
+ })),
32
+ subscribeForUrlContextKeyChanges: (...args) => mockSubscribe(...args),
33
+ }));
34
+
35
+ jest.mock("../useInflatedUrl", () => ({
36
+ useInflatedUrl: ({ feedUrl }) => feedUrl,
37
+ }));
38
+
39
+ jest.mock("../useLoadPipesDataDispatch", () => ({
40
+ useLoadPipesDataDispatch: () => mockLoad,
41
+ }));
42
+
43
+ const url = "https://example.test/feed";
44
+ const data = { id: "feed", type: { value: "feed" }, entry: [] };
45
+
46
+ const settle = async () => {
47
+ for (let index = 0; index < 30; index++) await Promise.resolve();
48
+ };
49
+
50
+ const createHarness = (plugins: QuickBrickPlugin[] = []) => {
51
+ const store = configureStore({
52
+ reducer: {
53
+ zappPipes: reducer,
54
+ appData: () => ({ layoutVersion: "v2" }),
55
+ plugins: () => plugins,
56
+ },
57
+ middleware: (defaults) =>
58
+ defaults({ serializableCheck: false }).concat(zappPipesMiddleware),
59
+ });
60
+
61
+ mockLoad = jest.fn((feedUrl, options) =>
62
+ store.dispatch(loadPipesData(feedUrl, options))
63
+ );
64
+
65
+ const wrapper = ({ children }) => (
66
+ <Provider store={store}>{children}</Provider>
67
+ );
68
+
69
+ return { store, wrapper };
70
+ };
71
+
72
+ describe("dependency-driven feed invalidation", () => {
73
+ beforeEach(() => {
74
+ jest.clearAllMocks();
75
+ mockGet.mockResolvedValue({ response: data, code: 200 });
76
+ mockPost.mockResolvedValue({ response: data, code: 200 });
77
+
78
+ mockSubscribe.mockImplementation((_url, _options, onChange) => {
79
+ mockChange = onChange;
80
+
81
+ return mockRelease;
82
+ });
83
+ });
84
+
85
+ afterEach(() => unsubscribeFromDataSource());
86
+
87
+ it("silently revalidates a shared mounted feed once and keeps its content", async () => {
88
+ const { store, wrapper } = createHarness();
89
+
90
+ const first = renderHook(() => useFeedLoader({ feedUrl: url }), {
91
+ wrapper,
92
+ });
93
+
94
+ const second = renderHook(() => useFeedLoader({ feedUrl: url }), {
95
+ wrapper,
96
+ });
97
+
98
+ await act(settle);
99
+
100
+ expect(mockGet).toHaveBeenCalledTimes(1);
101
+ expect(mockSubscribe).toHaveBeenCalledTimes(1);
102
+ let finish;
103
+
104
+ mockGet.mockImplementationOnce(
105
+ () =>
106
+ new Promise((resolve) => {
107
+ finish = resolve;
108
+ })
109
+ );
110
+
111
+ await act(async () => {
112
+ mockChange();
113
+ await settle();
114
+ });
115
+
116
+ expect(mockGet).toHaveBeenCalledTimes(2);
117
+ expect(first.result.current.data).toEqual(data);
118
+ expect(first.result.current.loading).toBe(false);
119
+ expect(store.getState().zappPipes[url].refreshing).toBe(true);
120
+
121
+ await act(async () => {
122
+ finish({ response: data, code: 200 });
123
+ await settle();
124
+ });
125
+
126
+ expect(store.getState().zappPipes[url].stale).toBeUndefined();
127
+ first.unmount();
128
+ second.unmount();
129
+ expect(mockRelease).not.toHaveBeenCalled();
130
+ });
131
+
132
+ it("invalidates an unmounted cache without fetching and revalidates on remount", async () => {
133
+ const { store, wrapper } = createHarness();
134
+
135
+ const first = renderHook(() => useFeedLoader({ feedUrl: url }), {
136
+ wrapper,
137
+ });
138
+
139
+ await act(settle);
140
+ first.unmount();
141
+
142
+ mockChange();
143
+ mockChange();
144
+ await settle();
145
+
146
+ expect(mockGet).toHaveBeenCalledTimes(1);
147
+
148
+ expect(store.getState().zappPipes[url]).toMatchObject({
149
+ stale: true,
150
+ invalidationVersion: 2,
151
+ data,
152
+ });
153
+
154
+ const second = renderHook(() => useFeedLoader({ feedUrl: url }), {
155
+ wrapper,
156
+ });
157
+
158
+ await act(settle);
159
+
160
+ expect(mockGet).toHaveBeenCalledTimes(2);
161
+ expect(store.getState().zappPipes[url].stale).toBeUndefined();
162
+ second.unmount();
163
+ });
164
+
165
+ it("runs one follow-up when invalidated repeatedly during a request", async () => {
166
+ const { store, wrapper } = createHarness();
167
+ let finish;
168
+
169
+ mockGet.mockImplementationOnce(
170
+ () =>
171
+ new Promise((resolve) => {
172
+ finish = resolve;
173
+ })
174
+ );
175
+
176
+ const hook = renderHook(() => useFeedLoader({ feedUrl: url }), { wrapper });
177
+ await act(settle);
178
+
179
+ await act(async () => {
180
+ mockChange();
181
+ mockChange();
182
+ await settle();
183
+ });
184
+
185
+ expect(mockGet).toHaveBeenCalledTimes(1);
186
+
187
+ await act(async () => {
188
+ finish({ response: data, code: 200 });
189
+ await settle();
190
+ });
191
+
192
+ expect(mockGet).toHaveBeenCalledTimes(2);
193
+ expect(store.getState().zappPipes[url].stale).toBeUndefined();
194
+ hook.unmount();
195
+ });
196
+
197
+ it("stops a failed revalidation until another dependency change", async () => {
198
+ const { wrapper } = createHarness();
199
+ const hook = renderHook(() => useFeedLoader({ feedUrl: url }), { wrapper });
200
+ await act(settle);
201
+ mockGet.mockRejectedValueOnce(new Error("network unavailable"));
202
+
203
+ await act(async () => {
204
+ mockChange();
205
+ await settle();
206
+ });
207
+
208
+ expect(mockGet).toHaveBeenCalledTimes(2);
209
+ expect(hook.result.current.error).toBeDefined();
210
+
211
+ await act(async () => {
212
+ mockChange();
213
+ await settle();
214
+ });
215
+
216
+ expect(mockGet).toHaveBeenCalledTimes(3);
217
+ expect(hook.result.current.error).toBeUndefined();
218
+ hook.unmount();
219
+ });
220
+
221
+ it("releases cache subscriptions for direct clear actions", async () => {
222
+ const { store } = createHarness();
223
+ await store.dispatch(loadPipesData(url));
224
+ await store.dispatch(loadPipesData(`${url}/two`));
225
+ store.dispatch(zappPipesClear(url));
226
+ expect(mockRelease).toHaveBeenCalledTimes(1);
227
+ store.dispatch(zappPipesClear());
228
+ expect(mockRelease).toHaveBeenCalledTimes(2);
229
+ });
230
+
231
+ it("preserves POST method and body when revalidating", async () => {
232
+ const { wrapper } = createHarness();
233
+ const bodyParams = { filter: "recent" };
234
+
235
+ const hook = renderHook(
236
+ () =>
237
+ useFeedLoader({
238
+ feedUrl: url,
239
+ pipesOptions: { method: "post", bodyParams },
240
+ }),
241
+ { wrapper }
242
+ );
243
+
244
+ await act(settle);
245
+
246
+ await act(async () => {
247
+ mockChange();
248
+ await settle();
249
+ });
250
+
251
+ expect(mockSubscribe).toHaveBeenCalledWith(
252
+ url,
253
+ { method: "post" },
254
+ expect.any(Function)
255
+ );
256
+
257
+ expect(mockPost).toHaveBeenCalledTimes(2);
258
+ expect(mockPost).toHaveBeenLastCalledWith(url, bodyParams);
259
+ expect(mockGet).not.toHaveBeenCalled();
260
+ hook.unmount();
261
+ });
262
+
263
+ it("does not revalidate a skipped mounted feed until loading is enabled", async () => {
264
+ const { store, wrapper } = createHarness();
265
+ await store.dispatch(loadPipesData(url));
266
+
267
+ const hook = renderHook(
268
+ ({ skipLoading }) =>
269
+ useFeedLoader({
270
+ feedUrl: url,
271
+ pipesOptions: { skipLoading },
272
+ }),
273
+ { wrapper, initialProps: { skipLoading: true } }
274
+ );
275
+
276
+ await act(async () => {
277
+ mockChange();
278
+ await settle();
279
+ });
280
+
281
+ expect(mockGet).toHaveBeenCalledTimes(1);
282
+ expect(store.getState().zappPipes[url].stale).toBe(true);
283
+
284
+ hook.rerender({ skipLoading: false });
285
+ await act(settle);
286
+ expect(mockGet).toHaveBeenCalledTimes(2);
287
+ expect(store.getState().zappPipes[url].stale).toBeUndefined();
288
+ hook.unmount();
289
+ });
290
+
291
+ it("shares GET revalidation with an omitted or empty unused request body", async () => {
292
+ const { store } = createHarness();
293
+ await store.dispatch(loadPipesData(url));
294
+ mockChange();
295
+ mockGet.mockClear();
296
+
297
+ await Promise.all([
298
+ store.dispatch(loadPipesData(url)),
299
+ store.dispatch(loadPipesData(url, { method: "get", bodyParams: {} })),
300
+ ]);
301
+
302
+ expect(mockGet).toHaveBeenCalledTimes(1);
303
+ });
304
+
305
+ it("keeps plugin observation until its cache is cleared", async () => {
306
+ const release = jest.fn();
307
+ let changed;
308
+
309
+ const addDataSourceListener = jest.fn((callback) => {
310
+ changed = callback;
311
+
312
+ return release;
313
+ });
314
+
315
+ const { store, wrapper } = createHarness([
316
+ {
317
+ identifier: "generic-provider",
318
+ module: { addDataSourceListener },
319
+ } as QuickBrickPlugin,
320
+ ]);
321
+
322
+ const pluginUrl = "pipesv2://generic-provider/feed";
323
+
324
+ const hook = renderHook(() => useFeedLoader({ feedUrl: pluginUrl }), {
325
+ wrapper,
326
+ });
327
+
328
+ await act(settle);
329
+ hook.unmount();
330
+ changed();
331
+ await settle();
332
+ expect(mockGet).toHaveBeenCalledTimes(1);
333
+ expect(store.getState().zappPipes[pluginUrl].stale).toBe(true);
334
+ expect(release).not.toHaveBeenCalled();
335
+ store.dispatch(zappPipesClear(pluginUrl));
336
+ expect(release).toHaveBeenCalledTimes(1);
337
+ });
338
+ });
@@ -2,6 +2,7 @@ import { renderHook, waitFor } from "@testing-library/react-native";
2
2
  import { allFeedsIsReady, useBatchLoading } from "../useBatchLoading";
3
3
  import { WrappedWithProviders } from "@applicaster/zapp-react-native-utils/testUtils";
4
4
  import { appStore } from "@applicaster/zapp-react-native-redux/AppStore";
5
+ import * as ZappPipes from "@applicaster/zapp-react-native-redux/ZappPipes";
5
6
 
6
7
  jest.mock("../../navigation");
7
8
 
@@ -32,11 +33,16 @@ describe("useBatchLoading", () => {
32
33
  // ... more items
33
34
  ];
34
35
 
35
- beforeAll(() => {
36
- jest.useFakeTimers();
36
+ beforeEach(() => {
37
+ jest
38
+ .spyOn(ZappPipes, "loadPipesData")
39
+ .mockImplementation((url, options) => async (dispatch) => {
40
+ dispatch(ZappPipes.zappPipesRequestStart(url, options));
41
+ });
37
42
  });
38
43
 
39
44
  afterEach(() => {
45
+ jest.restoreAllMocks();
40
46
  jest.clearAllMocks();
41
47
  });
42
48