@applicaster/zapp-react-native-ui-components 16.0.0-alpha.4342281394 → 16.0.0-alpha.4880104344

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 (41) hide show
  1. package/Components/CellRendererResolver/index.ts +2 -2
  2. package/Components/ComponentResolver/__tests__/componentResolver.test.js +1 -1
  3. package/Components/FocusableGroup/FocusableTvOS.tsx +11 -7
  4. package/Components/GeneralContentScreen/GeneralContentScreenHookAdapter.tsx +39 -0
  5. package/Components/GeneralContentScreen/__tests__/GeneralContentScreenHookAdapter.test.tsx +64 -0
  6. package/Components/GeneralContentScreen/__tests__/HookContentFocusGroup.web.test.tsx +91 -0
  7. package/Components/GeneralContentScreen/hookAdapter/__tests__/networkService.test.ts +74 -0
  8. package/Components/GeneralContentScreen/hookAdapter/__tests__/runInBackground.test.ts +139 -0
  9. package/Components/GeneralContentScreen/hookAdapter/__tests__/validationHelper.test.ts +124 -0
  10. package/Components/GeneralContentScreen/hookAdapter/logger.ts +6 -0
  11. package/Components/GeneralContentScreen/hookAdapter/networkService.ts +53 -0
  12. package/Components/GeneralContentScreen/hookAdapter/runInBackground.ts +48 -0
  13. package/Components/GeneralContentScreen/hookAdapter/validationHelper.ts +72 -0
  14. package/Components/GeneralContentScreen/hookFocus/index.tsx +13 -0
  15. package/Components/GeneralContentScreen/hookFocus/index.web.tsx +69 -0
  16. package/Components/GeneralContentScreen/index.ts +2 -0
  17. package/Components/Layout/FullWidthRow.tsx +38 -0
  18. package/Components/MasterCell/DefaultComponents/ActionButton.tsx +16 -5
  19. package/Components/MasterCell/dataAdapter.ts +15 -5
  20. package/Components/MasterCell/index.tsx +30 -5
  21. package/Components/MasterCell/utils/__tests__/resolveColor.test.js +169 -132
  22. package/Components/MasterCell/utils/__tests__/resolveColorForProp.test.js +92 -0
  23. package/Components/MasterCell/utils/index.ts +85 -46
  24. package/Components/PlayerContainer/PlayerContainer.tsx +14 -10
  25. package/Components/PlayerContainer/__tests__/PlayerContainer.test.tsx +284 -0
  26. package/Components/River/ComponentsMap/ComponentsMap.tsx +2 -2
  27. package/Components/River/__tests__/__snapshots__/componentsMap.test.js.snap +3 -15
  28. package/Components/Screen/index.tsx +8 -4
  29. package/Components/VideoModal/utils.ts +6 -1
  30. package/Components/ZappFrameworkComponents/BarView/BarView.tsx +12 -5
  31. package/Components/ZappFrameworkComponents/BarView/__tests__/BarView.test.tsx +2 -2
  32. package/Contexts/CachedDimensionsContext/__tests__/index.test.ts +154 -0
  33. package/Contexts/CachedDimensionsContext/index.ts +17 -2
  34. package/Helpers/ComponentCellSelectionHelper/index.js +0 -6
  35. package/Helpers/index.js +0 -39
  36. package/package.json +5 -5
  37. package/Components/Screen/utils.ts +0 -16
  38. package/Helpers/Analytics/index.js +0 -95
  39. /package/Components/BackgroundImage/{BackgroundImage.tv.android.tsx → BackgroundImage.android.tv.tsx} +0 -0
  40. /package/Components/BackgroundImage/{BackgroundImage.tv.ios.tsx → BackgroundImage.ios.tv.tsx} +0 -0
  41. /package/Components/MasterCell/DefaultComponents/ButtonContainerView/{index.tv.android.tsx → index.android.tv.tsx} +0 -0
@@ -265,14 +265,12 @@ const PlayerContainerComponent = (props: Props) => {
265
265
  navigator.goBack();
266
266
  }, [isModal, state.playerId, showNavBar, navigator]);
267
267
 
268
- const pluginConfiguration = React.useMemo(() => {
269
- return (
270
- playerManager.getPluginConfiguration() ||
271
- R.prop("__plugin_configuration", Player)
272
- );
273
- }, [playerManager.isRegistered()]);
268
+ const pluginConfiguration = React.useMemo(
269
+ () => player?.getPluginConfiguration(),
270
+ [player]
271
+ );
274
272
 
275
- const playEntry = (entry) => navigator.replaceTop(entry, { mode });
273
+ const playEntry = (entry: ZappEntry) => navigator.replaceTop(entry, { mode });
276
274
 
277
275
  const onPlayNextPerformNextVideoPlay = React.useCallback(() => {
278
276
  if (!playNextOverlayState.entry) {
@@ -346,11 +344,15 @@ const PlayerContainerComponent = (props: Props) => {
346
344
  setIsLoadingNextVideo(false);
347
345
 
348
346
  const resumeTime = Number(item?.extensions?.resumeTime);
347
+ const activePlayer = playerManager.getActivePlayer();
349
348
 
350
- // Сhecking that the player itself knows where to start playing, and there is no need to call seekTo after returning from the Сhromecast
349
+ // Сhecking that the player itself knows where to start playing, and there is no need to call seekTo after returning from the Сhromecast.
350
+ // Live streams and a missing/zero resume position are skipped: seeking to 0 on
351
+ // a live stream pulls playback off the live edge into a buffer-starvation seek loop.
351
352
  if (
352
- !playerManager.getActivePlayer()?.hasResumePosition() &&
353
- !isNaN(resumeTime)
353
+ !activePlayer?.hasResumePosition() &&
354
+ resumeTime > 0 &&
355
+ !activePlayer?.isLive()
354
356
  ) {
355
357
  player?.seekTo(resumeTime);
356
358
  }
@@ -468,6 +470,8 @@ const PlayerContainerComponent = (props: Props) => {
468
470
  if (isModal && mode === VideoModalMode.MAXIMIZED) {
469
471
  if (disableMiniPlayer) {
470
472
  navigator.closeVideoModal();
473
+ } else {
474
+ navigator.minimiseVideoModal();
471
475
  }
472
476
  }
473
477
 
@@ -0,0 +1,284 @@
1
+ import * as React from "react";
2
+ import { render } from "@testing-library/react-native";
3
+
4
+ jest.mock(
5
+ "@applicaster/zapp-react-native-utils/appUtils/playerManager",
6
+ () => ({
7
+ playerManager: {
8
+ invokeHandler: jest.fn(),
9
+ getPluginConfiguration: jest.fn(() => ({})),
10
+ isRegistered: jest.fn(() => true),
11
+ on: jest.fn().mockReturnThis(),
12
+ removeHandler: jest.fn().mockReturnThis(),
13
+ getActivePlayer: jest.fn(() => null),
14
+ closeNativePlayer: jest.fn(),
15
+ },
16
+ })
17
+ );
18
+
19
+ jest.mock("@applicaster/zapp-react-native-utils/reactUtils", () => ({
20
+ isTV: jest.fn(() => false),
21
+ isAndroidTVPlatform: jest.fn(() => false),
22
+ isTvOSPlatform: jest.fn(() => false),
23
+ platformSelect: jest.fn(({ native }) => native),
24
+ }));
25
+
26
+ jest.mock("@applicaster/zapp-react-native-utils/playerUtils", () => ({
27
+ isAudioItem: jest.fn(() => false),
28
+ isInlineTV: jest.fn(() => false),
29
+ }));
30
+
31
+ jest.mock(
32
+ "@applicaster/zapp-react-native-tvos-ui-components/Components/TVEventHandlerComponent",
33
+ () => ({
34
+ TVEventHandlerComponent: ({ children }) => children,
35
+ })
36
+ );
37
+
38
+ jest.mock("@applicaster/zapp-react-native-utils/reactHooks/utils", () => ({
39
+ usePrevious: jest.fn(),
40
+ }));
41
+
42
+ jest.mock("@applicaster/zapp-react-native-utils/reactHooks", () => {
43
+ const navigator = {
44
+ closeVideoModal: jest.fn(),
45
+ minimiseVideoModal: jest.fn(),
46
+ maximiseVideoModal: jest.fn(),
47
+ fullscreenVideoModal: jest.fn(),
48
+ isVideoModalDocked: jest.fn(() => false),
49
+ goBack: jest.fn(),
50
+ replaceTop: jest.fn(),
51
+ push: jest.fn(),
52
+ setPlayNextOverlay: jest.fn(),
53
+ currentRoute: "/playable/entry-1",
54
+ };
55
+
56
+ const backHandlerRef: { current: (() => boolean) | null } = {
57
+ current: null,
58
+ };
59
+
60
+ return {
61
+ useBackHandler: jest.fn((cb) => {
62
+ backHandlerRef.current = cb;
63
+ }),
64
+ useNavigation: jest.fn(() => navigator),
65
+ __navigator: navigator,
66
+ __backHandlerRef: backHandlerRef,
67
+ };
68
+ });
69
+
70
+ jest.mock("@applicaster/zapp-react-native-bridge/QuickBrick", () => ({
71
+ QUICK_BRICK_EVENTS: {
72
+ IDLE_TIMER_DISABLED: "IDLE_TIMER_DISABLED",
73
+ MOVE_APP_TO_BACKGROUND: "MOVE_APP_TO_BACKGROUND",
74
+ },
75
+ sendQuickBrickEvent: jest.fn(),
76
+ }));
77
+
78
+ jest.mock("../ProgramInfo", () => ({
79
+ ProgramInfo: () => null,
80
+ }));
81
+
82
+ jest.mock("../../AudioPlayer", () => ({
83
+ AudioPlayer: () => null,
84
+ }));
85
+
86
+ jest.mock("../logger", () => ({
87
+ log_debug: jest.fn(),
88
+ log_info: jest.fn(),
89
+ log_warning: jest.fn(),
90
+ playerContainerLogger: { error: jest.fn() },
91
+ }));
92
+
93
+ jest.mock(
94
+ "@applicaster/zapp-react-native-utils/appUtils/playerManager/usePlayer",
95
+ () => {
96
+ const player = {
97
+ addListener: jest.fn(),
98
+ removeListener: jest.fn(),
99
+ isPaused: jest.fn(() => false),
100
+ isAd: jest.fn(() => false),
101
+ seekTo: jest.fn(),
102
+ getPluginConfiguration: jest.fn(() => ({})),
103
+ getOverlayObservable: jest.fn(() => ({ getPlayNextEntry: () => null })),
104
+ };
105
+
106
+ return {
107
+ usePlayer: jest.fn(() => player),
108
+ __player: player,
109
+ };
110
+ }
111
+ );
112
+
113
+ jest.mock(
114
+ "@applicaster/zapp-react-native-utils/appUtils/playerManager/usePlayNextOverlay",
115
+ () => ({
116
+ usePlayNextOverlay: jest.fn(() => null),
117
+ })
118
+ );
119
+
120
+ jest.mock(
121
+ "@applicaster/zapp-react-native-utils/appUtils/playerManager/playerNativeCommand",
122
+ () => ({
123
+ PlayerNativeCommandTypes: { clearPlayerData: "clearPlayerData" },
124
+ PlayerNativeSendCommand: jest.fn(),
125
+ })
126
+ );
127
+
128
+ jest.mock(
129
+ "@applicaster/zapp-react-native-utils/reactHooks/screen/useScreenContext",
130
+ () => ({
131
+ useSetNavbarState: jest.fn(() => ({ setVisible: jest.fn() })),
132
+ })
133
+ );
134
+
135
+ jest.mock(
136
+ "@applicaster/zapp-react-native-utils/reactHooks/screen/useTargetScreenData",
137
+ () => ({
138
+ useTargetScreenData: jest.fn(() => ({ id: "screen-id", styles: {} })),
139
+ })
140
+ );
141
+
142
+ jest.mock("../PlayerContainerContext", () => {
143
+ const ReactActual = require("react");
144
+
145
+ return {
146
+ PlayerContainerContext: ReactActual.createContext({
147
+ isLanguageOverlayVisible: false,
148
+ bottomFocusableId: "bottom",
149
+ showComponentsContainer: false,
150
+ refs: null,
151
+ }),
152
+ PlayerContainerContextProvider: ({ children }) => children,
153
+ };
154
+ });
155
+
156
+ jest.mock(
157
+ "@applicaster/zapp-react-native-ui-components/Components/FocusableGroup",
158
+ () => ({
159
+ FocusableGroup: ({ children }) => children,
160
+ })
161
+ );
162
+
163
+ jest.mock("../WappersView/PlayerFocusableWrapperView", () => ({
164
+ PlayerFocusableWrapperView: ({ children }) => children,
165
+ }));
166
+
167
+ jest.mock("../WappersView/ComponentFocusableWrapperView", () => ({
168
+ ComponentFocusableWrapperView: () => null,
169
+ }));
170
+
171
+ jest.mock("../index", () => ({
172
+ FocusableGroupMainContainerId: "player-container-general",
173
+ }));
174
+
175
+ jest.mock(
176
+ "@applicaster/zapp-react-native-utils/navigationUtils/itemTypeMatchers",
177
+ () => ({
178
+ isPlayable: jest.fn(() => true),
179
+ })
180
+ );
181
+
182
+ jest.mock("../../GeneralContentScreen", () => ({
183
+ GeneralContentScreen: () => null,
184
+ }));
185
+
186
+ jest.mock("@applicaster/zapp-react-native-redux", () => ({
187
+ useAppData: jest.fn(() => ({ isTabletPortrait: false })),
188
+ }));
189
+
190
+ import { PlayerContainer, VideoModalMode } from "../PlayerContainer";
191
+
192
+ const { __navigator: mockNavigator, __backHandlerRef: mockBackHandlerRef } =
193
+ jest.requireMock("@applicaster/zapp-react-native-utils/reactHooks");
194
+
195
+ const { playerManager: mockPlayerManager } = jest.requireMock(
196
+ "@applicaster/zapp-react-native-utils/appUtils/playerManager"
197
+ );
198
+
199
+ const { __player: mockPlayer } = jest.requireMock(
200
+ "@applicaster/zapp-react-native-utils/appUtils/playerManager/usePlayer"
201
+ );
202
+
203
+ const Player = React.forwardRef(() => null);
204
+
205
+ const item = {
206
+ id: "entry-1",
207
+ title: "Test entry",
208
+ summary: "",
209
+ content: { src: "https://example.com/video.m3u8" },
210
+ extensions: {},
211
+ } as any;
212
+
213
+ const renderPlayerContainer = (props = {}) =>
214
+ render(
215
+ <PlayerContainer
216
+ Player={Player}
217
+ item={item}
218
+ style={{}}
219
+ loadPipesData={jest.fn()}
220
+ isModal={true}
221
+ mode={VideoModalMode.MAXIMIZED}
222
+ {...props}
223
+ />
224
+ );
225
+
226
+ const pressHardwareBack = () => {
227
+ if (!mockBackHandlerRef.current) {
228
+ throw new Error("back handler was not registered via useBackHandler");
229
+ }
230
+
231
+ return mockBackHandlerRef.current();
232
+ };
233
+
234
+ describe("PlayerContainer hardware back handling", () => {
235
+ beforeEach(() => {
236
+ jest.clearAllMocks();
237
+ mockBackHandlerRef.current = null;
238
+ mockPlayer.getPluginConfiguration.mockReturnValue({});
239
+ mockPlayer.isPaused.mockReturnValue(false);
240
+ mockPlayer.isAd.mockReturnValue(false);
241
+
242
+ mockPlayer.getOverlayObservable.mockReturnValue({
243
+ getPlayNextEntry: () => null,
244
+ });
245
+
246
+ mockPlayerManager.getPluginConfiguration.mockReturnValue({});
247
+ mockPlayerManager.on.mockReturnThis();
248
+ mockPlayerManager.removeHandler.mockReturnThis();
249
+ });
250
+
251
+ it("minimises the video modal on back press when mini player is enabled", () => {
252
+ renderPlayerContainer();
253
+
254
+ const handled = pressHardwareBack();
255
+
256
+ expect(mockNavigator.minimiseVideoModal).toHaveBeenCalled();
257
+ expect(mockNavigator.closeVideoModal).not.toHaveBeenCalled();
258
+ expect(handled).toBe(true);
259
+ });
260
+
261
+ it("closes the video modal on back press when mini player is disabled", () => {
262
+ mockPlayer.getPluginConfiguration.mockReturnValue({
263
+ disable_mini_player_when_inline: true,
264
+ });
265
+
266
+ renderPlayerContainer();
267
+
268
+ const handled = pressHardwareBack();
269
+
270
+ expect(mockNavigator.closeVideoModal).toHaveBeenCalled();
271
+ expect(mockNavigator.minimiseVideoModal).not.toHaveBeenCalled();
272
+ expect(handled).toBe(true);
273
+ });
274
+
275
+ it("does not handle back press when the player is already minimised", () => {
276
+ renderPlayerContainer({ mode: VideoModalMode.MINIMIZED });
277
+
278
+ const handled = pressHardwareBack();
279
+
280
+ expect(handled).toBe(false);
281
+ expect(mockNavigator.minimiseVideoModal).not.toHaveBeenCalled();
282
+ expect(mockNavigator.closeVideoModal).not.toHaveBeenCalled();
283
+ });
284
+ });
@@ -9,7 +9,7 @@ import { useScreenConfiguration } from "../useScreenConfiguration";
9
9
  import { RefreshControl } from "../RefreshControl";
10
10
  import { ifEmptyUseFallback } from "@applicaster/zapp-react-native-utils/cellUtils";
11
11
  import {
12
- usePipesCacheReset,
12
+ useMarkPipesDataStale,
13
13
  useProfilerLogging,
14
14
  } from "@applicaster/zapp-react-native-utils/reactHooks";
15
15
  import { useLoadingState } from "./hooks/useLoadingState";
@@ -154,7 +154,7 @@ function ComponentsMapComponent(props: Props) {
154
154
  [flatListHeight]
155
155
  );
156
156
 
157
- usePipesCacheReset(riverId, riverComponents);
157
+ useMarkPipesDataStale(riverId, riverComponents);
158
158
 
159
159
  const refreshControl = React.useMemo(
160
160
  () => (pullToRefreshEnabled ? <RefreshControl /> : null),
@@ -10,11 +10,7 @@ exports[`componentsMap renders renders components map correctly 1`] = `
10
10
  >
11
11
  <View
12
12
  onLayout={[Function]}
13
- style={
14
- {
15
- "flex": 1,
16
- }
17
- }
13
+ style={{}}
18
14
  >
19
15
  <RCTScrollView
20
16
  ListFooterComponent={
@@ -167,11 +163,7 @@ exports[`componentsMap renders renders components map correctly 1`] = `
167
163
  >
168
164
  <View
169
165
  onLayout={[Function]}
170
- style={
171
- {
172
- "flex": 1,
173
- }
174
- }
166
+ style={{}}
175
167
  >
176
168
  <View />
177
169
  </View>
@@ -183,11 +175,7 @@ exports[`componentsMap renders renders components map correctly 1`] = `
183
175
  >
184
176
  <View
185
177
  onLayout={[Function]}
186
- style={
187
- {
188
- "flex": 1,
189
- }
190
- }
178
+ style={{}}
191
179
  />
192
180
  </View>
193
181
  <View
@@ -18,10 +18,13 @@ import {
18
18
  useScreenData,
19
19
  } from "@applicaster/zapp-react-native-utils/reactHooks";
20
20
  import { getNavigationPluginModule } from "@applicaster/zapp-react-native-app/App/Layout/layoutHelpers";
21
+ import {
22
+ isValidColor,
23
+ isTransparentColor,
24
+ } from "@applicaster/zapp-react-native-utils/colorUtils";
21
25
 
22
26
  import { RouteManager } from "../RouteManager";
23
27
  import { useScreenConfiguration } from "../River/useScreenConfiguration";
24
- import { isValidColor } from "./utils";
25
28
  import { useWaitForValidOrientation } from "./hooks";
26
29
 
27
30
  const screenStyles = {
@@ -82,9 +85,10 @@ export function Screen(_props: Props) {
82
85
  const style = React.useMemo(
83
86
  () => ({
84
87
  ...screenStyles,
85
- backgroundColor: isValidColor(backgroundColor)
86
- ? backgroundColor
87
- : theme.app_background_color,
88
+ backgroundColor:
89
+ isValidColor(backgroundColor) && !isTransparentColor(backgroundColor)
90
+ ? backgroundColor
91
+ : theme.app_background_color,
88
92
  }),
89
93
  [theme.app_background_color, backgroundColor]
90
94
  );
@@ -10,6 +10,7 @@ import { playerManager } from "@applicaster/zapp-react-native-utils/appUtils";
10
10
  import { create } from "zustand";
11
11
  import { useRivers } from "@applicaster/zapp-react-native-utils/reactHooks";
12
12
  import { selectPluginConfigurationsByPluginId } from "@applicaster/zapp-react-native-redux";
13
+ import { usePlayer } from "@applicaster/zapp-react-native-utils/appUtils/playerManager/usePlayer";
13
14
 
14
15
  export const useConfiguration = () => {
15
16
  const {
@@ -18,6 +19,7 @@ export const useConfiguration = () => {
18
19
 
19
20
  const rivers = useRivers();
20
21
  const contentTypes = useContentTypes();
22
+ const player = usePlayer();
21
23
 
22
24
  const targetScreenId = contentTypes?.[item?.type?.value]?.screen_id;
23
25
  const targetScreenConfiguration = rivers?.[targetScreenId];
@@ -26,7 +28,10 @@ export const useConfiguration = () => {
26
28
  selectPluginConfigurationsByPluginId(state, targetScreenConfiguration?.type)
27
29
  );
28
30
 
29
- const playerPluginConfig = playerManager.getPluginConfiguration();
31
+ const playerPluginConfig =
32
+ player?.getPluginConfiguration() ??
33
+ playerManager.getInstanceController()?.getPluginConfiguration() ??
34
+ {};
30
35
 
31
36
  const config = mergeRight(playerPluginConfig, {
32
37
  ...configuration_json,
@@ -1,10 +1,11 @@
1
1
  import React from "react";
2
- import { StyleSheet, View } from "react-native";
3
-
2
+ import { StyleSheet, SafeAreaView as RNSafeAreaView } from "react-native";
3
+ import { SafeAreaView } from "react-native-safe-area-context";
4
4
  import { useIsRTL } from "@applicaster/zapp-react-native-utils/localizationUtils";
5
5
  import CloseButton from "./Buttons/CloseButton";
6
6
  import BackButton from "./Buttons/BackButton";
7
7
  import BarTitle from "./BarTitle";
8
+ import { platformSelect } from "@applicaster/zapp-react-native-utils/reactUtils";
8
9
 
9
10
  type Props = {
10
11
  screenStyles: {
@@ -23,6 +24,11 @@ const defaultState: NavBarState = {
23
24
  title: "",
24
25
  };
25
26
 
27
+ const SafeAreaViewPlatform = platformSelect({
28
+ ios: RNSafeAreaView,
29
+ android: SafeAreaView,
30
+ });
31
+
26
32
  const BarView = ({ screenStyles, barState = defaultState }: Props) => {
27
33
  const isRTL = useIsRTL();
28
34
 
@@ -44,14 +50,15 @@ const BarView = ({ screenStyles, barState = defaultState }: Props) => {
44
50
  );
45
51
 
46
52
  return (
47
- <View
53
+ <SafeAreaViewPlatform
54
+ edges={["top", "left", "right"]}
48
55
  style={[style.view, isRTL ? style.rtlStyle : {}]}
49
- testID="BarView-Container"
56
+ testID="BarView-safeAreaView"
50
57
  >
51
58
  {backButton}
52
59
  <BarTitle title={barState.title} screenStyles={screenStyles} />
53
60
  {closeButton}
54
- </View>
61
+ </SafeAreaViewPlatform>
55
62
  );
56
63
  };
57
64
 
@@ -46,7 +46,7 @@ describe("BarView", () => {
46
46
  <BarView screenStyles={screenStyles} barState={barState} />
47
47
  );
48
48
 
49
- expect(getByTestId("BarView-Container").props.style).toContainEqual({
49
+ expect(getByTestId("BarView-safeAreaView").props.style).toContainEqual({
50
50
  transform: [{ scaleX: -1 }],
51
51
  });
52
52
  });
@@ -58,7 +58,7 @@ describe("BarView", () => {
58
58
  <BarView screenStyles={screenStyles} barState={barState} />
59
59
  );
60
60
 
61
- expect(getByTestId("BarView-Container").props.style).not.toContainEqual({
61
+ expect(getByTestId("BarView-safeAreaView").props.style).not.toContainEqual({
62
62
  transform: [{ scaleX: -1 }],
63
63
  });
64
64
  });
@@ -0,0 +1,154 @@
1
+ import { renderHook, act } from "@testing-library/react-native";
2
+
3
+ type DimensionsStore = {
4
+ setState: (
5
+ partial: { dimensions: Record<string, unknown>; ids: string[] },
6
+ replace?: boolean
7
+ ) => void;
8
+ };
9
+
10
+ const createdStores: DimensionsStore[] = [];
11
+
12
+ jest.mock("zustand", () => {
13
+ const actual = jest.requireActual<typeof import("zustand")>("zustand");
14
+
15
+ return {
16
+ ...actual,
17
+ create: ((initializer: Parameters<typeof actual.create>[0]) => {
18
+ const store = actual.create(initializer);
19
+ createdStores.push(store);
20
+
21
+ return store;
22
+ }) as typeof actual.create,
23
+ };
24
+ });
25
+
26
+ import { useCachedDimensions } from "../index";
27
+
28
+ const resetStore = () => {
29
+ const store = createdStores[createdStores.length - 1];
30
+
31
+ act(() => {
32
+ store?.setState({ dimensions: {}, ids: [] });
33
+ });
34
+ };
35
+
36
+ describe("useCachedDimensions", () => {
37
+ beforeEach(() => {
38
+ resetStore();
39
+ });
40
+
41
+ describe("getCachedDimensions", () => {
42
+ it("returns default dimensions when id has no cached value", () => {
43
+ const { result } = renderHook(() => useCachedDimensions("component-1"));
44
+
45
+ expect(result.current.getCachedDimensions()).toEqual({
46
+ width: undefined,
47
+ height: undefined,
48
+ });
49
+ });
50
+
51
+ it("returns cached dimensions after setCachedDimensions", () => {
52
+ const { result } = renderHook(() => useCachedDimensions("component-1"));
53
+ const dimensions = { width: 100, height: 200 };
54
+
55
+ act(() => {
56
+ result.current.setCachedDimensions(dimensions);
57
+ });
58
+
59
+ expect(result.current.getCachedDimensions()).toEqual(dimensions);
60
+ });
61
+ });
62
+
63
+ describe("setCachedDimensions", () => {
64
+ it("updates dimensions for the hook id", () => {
65
+ const { result } = renderHook(() => useCachedDimensions("component-1"));
66
+
67
+ act(() => {
68
+ result.current.setCachedDimensions({ width: 50, height: 75 });
69
+ });
70
+
71
+ expect(result.current.getCachedDimensions()).toEqual({
72
+ width: 50,
73
+ height: 75,
74
+ });
75
+ });
76
+
77
+ it("shares cached dimensions between hook instances with the same id", () => {
78
+ const { result: first } = renderHook(() =>
79
+ useCachedDimensions("shared-id")
80
+ );
81
+
82
+ const { result: second } = renderHook(() =>
83
+ useCachedDimensions("shared-id")
84
+ );
85
+
86
+ act(() => {
87
+ first.current.setCachedDimensions({ width: 10, height: 20 });
88
+ });
89
+
90
+ expect(second.current.getCachedDimensions()).toEqual({
91
+ width: 10,
92
+ height: 20,
93
+ });
94
+ });
95
+ });
96
+
97
+ describe("getLastCachedDimensions", () => {
98
+ it("returns undefined when no dimensions have been cached", () => {
99
+ const { result } = renderHook(() => useCachedDimensions("component-1"));
100
+
101
+ expect(result.current.getLastCachedDimensions()).toBeUndefined();
102
+ });
103
+
104
+ it("returns the most recently cached dimensions across ids", () => {
105
+ const { result: first } = renderHook(() => useCachedDimensions("first"));
106
+
107
+ const { result: second } = renderHook(() =>
108
+ useCachedDimensions("second")
109
+ );
110
+
111
+ act(() => {
112
+ first.current.setCachedDimensions({ width: 100, height: 100 });
113
+ });
114
+
115
+ act(() => {
116
+ second.current.setCachedDimensions({ width: 200, height: 200 });
117
+ });
118
+
119
+ expect(first.current.getLastCachedDimensions()).toEqual({
120
+ width: 200,
121
+ height: 200,
122
+ });
123
+ });
124
+
125
+ it("returns the latest dimensions when the same id is updated multiple times", () => {
126
+ const { result } = renderHook(() => useCachedDimensions("component-1"));
127
+
128
+ act(() => {
129
+ result.current.setCachedDimensions({ width: 100, height: 100 });
130
+ });
131
+
132
+ act(() => {
133
+ result.current.setCachedDimensions({ width: 300, height: 400 });
134
+ });
135
+
136
+ expect(result.current.getLastCachedDimensions()).toEqual({
137
+ width: 300,
138
+ height: 400,
139
+ });
140
+ });
141
+ });
142
+
143
+ describe("return value", () => {
144
+ it("exposes getCachedDimensions, setCachedDimensions, and getLastCachedDimensions", () => {
145
+ const { result } = renderHook(() => useCachedDimensions("component-1"));
146
+
147
+ expect(result.current).toEqual({
148
+ getCachedDimensions: expect.any(Function),
149
+ setCachedDimensions: expect.any(Function),
150
+ getLastCachedDimensions: expect.any(Function),
151
+ });
152
+ });
153
+ });
154
+ });