@applicaster/zapp-react-native-ui-components 16.0.0-rc.8 → 16.0.0-rc.80

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 (131) hide show
  1. package/Components/AudioPlayer/tv/__tests__/audioPlayer.test.js +19 -0
  2. package/Components/AudioPlayer/tv/__tests__/index.test.tsx +120 -0
  3. package/Components/AudioPlayer/tv/index.tsx +5 -1
  4. package/Components/Cell/Cell.tsx +3 -6
  5. package/Components/Cell/TvOSCellComponent.tsx +0 -1
  6. package/Components/CellRendererResolver/index.ts +2 -2
  7. package/Components/ComponentResolver/__tests__/componentResolver.test.js +1 -1
  8. package/Components/FocusableGroup/FocusableTvOS.tsx +11 -7
  9. package/Components/GeneralContentScreen/GeneralContentScreenHookAdapter.tsx +39 -0
  10. package/Components/GeneralContentScreen/__tests__/GeneralContentScreenHookAdapter.test.tsx +64 -0
  11. package/Components/GeneralContentScreen/__tests__/HookContentFocusGroup.web.test.tsx +91 -0
  12. package/Components/GeneralContentScreen/hookAdapter/__tests__/networkService.test.ts +74 -0
  13. package/Components/GeneralContentScreen/hookAdapter/__tests__/runInBackground.test.ts +139 -0
  14. package/Components/GeneralContentScreen/hookAdapter/__tests__/skipExpression.test.ts +294 -0
  15. package/Components/GeneralContentScreen/hookAdapter/__tests__/validationHelper.test.ts +188 -0
  16. package/Components/GeneralContentScreen/hookAdapter/logger.ts +6 -0
  17. package/Components/GeneralContentScreen/hookAdapter/networkService.ts +53 -0
  18. package/Components/GeneralContentScreen/hookAdapter/runInBackground.ts +48 -0
  19. package/Components/GeneralContentScreen/hookAdapter/skipExpression.ts +252 -0
  20. package/Components/GeneralContentScreen/hookAdapter/validationHelper.ts +90 -0
  21. package/Components/GeneralContentScreen/hookFocus/index.tsx +13 -0
  22. package/Components/GeneralContentScreen/hookFocus/index.web.tsx +69 -0
  23. package/Components/GeneralContentScreen/index.ts +2 -0
  24. package/Components/Layout/FullWidthRow.tsx +38 -0
  25. package/Components/MasterCell/DefaultComponents/ActionButton.tsx +16 -5
  26. package/Components/MasterCell/DefaultComponents/ActionButtonsCore/__tests__/placement.test.ts +47 -21
  27. package/Components/MasterCell/DefaultComponents/ActionButtonsCore/placement.ts +34 -6
  28. package/Components/MasterCell/DefaultComponents/Image/hoc/utils/__tests__/withDimensions.test.ts +420 -125
  29. package/Components/MasterCell/DefaultComponents/Image/hoc/utils/index.ts +114 -19
  30. package/Components/MasterCell/DefaultComponents/Image/hoc/withDimensions.tsx +19 -8
  31. package/Components/MasterCell/DefaultComponents/ImageContainer/index.tsx +5 -3
  32. package/Components/MasterCell/DefaultComponents/PressableView.tsx +29 -9
  33. package/Components/MasterCell/DefaultComponents/Text/hooks/useText.ts +4 -0
  34. package/Components/MasterCell/DefaultComponents/Toggle.tsx +36 -14
  35. package/Components/MasterCell/DefaultComponents/__tests__/Toggle.test.tsx +167 -0
  36. package/Components/MasterCell/DefaultComponents/mobile/MobileActionButtons/ActionButton.tsx +154 -100
  37. package/Components/MasterCell/DefaultComponents/mobile/MobileActionButtons/AssetComponent.tsx +15 -4
  38. package/Components/MasterCell/DefaultComponents/mobile/MobileActionButtons/Button.ts +56 -22
  39. package/Components/MasterCell/DefaultComponents/mobile/MobileActionButtons/Spacer.ts +6 -4
  40. package/Components/MasterCell/DefaultComponents/mobile/MobileActionButtons/TextLabelsContainer.ts +3 -1
  41. package/Components/MasterCell/DefaultComponents/mobile/MobileActionButtons/__tests__/PressableView.test.tsx +32 -21
  42. package/Components/MasterCell/DefaultComponents/mobile/MobileActionButtons/__tests__/index.test.ts +15 -4
  43. package/Components/MasterCell/DefaultComponents/mobile/MobileActionButtons/index.ts +23 -16
  44. package/Components/MasterCell/DefaultComponents/mobile/MobileActionButtons/utils/__tests__/insertButtons.test.ts +8 -3
  45. package/Components/MasterCell/DefaultComponents/mobile/MobileActionButtons/utils/index.ts +2 -2
  46. package/Components/MasterCell/DefaultComponents/tv/TvActionButtons/utils/__tests__/insertButtonsBetweenLabels.test.ts +45 -13
  47. package/Components/MasterCell/DefaultComponents/tv/TvActionButtons/utils/index.ts +2 -2
  48. package/Components/MasterCell/contexts/PressedStateContext.ts +3 -0
  49. package/Components/MasterCell/dataAdapter.ts +15 -5
  50. package/Components/MasterCell/hooks/index.ts +2 -0
  51. package/Components/MasterCell/hooks/usePressedState.ts +4 -0
  52. package/Components/MasterCell/index.tsx +30 -5
  53. package/Components/MasterCell/utils/__tests__/resolveColor.test.js +169 -132
  54. package/Components/MasterCell/utils/__tests__/resolveColorForProp.test.js +92 -0
  55. package/Components/MasterCell/utils/index.ts +85 -46
  56. package/Components/ModalComponent/ActionsBottomSheet/ActionButton.tsx +54 -0
  57. package/Components/ModalComponent/ActionsBottomSheet/boundActionButton.tsx +21 -0
  58. package/Components/ModalComponent/ActionsBottomSheet/index.ts +9 -0
  59. package/Components/ModalComponent/ActionsBottomSheet/openActionsBottomSheet.ts +58 -0
  60. package/Components/ModalComponent/AudioPlayer/Components/Action.tsx +314 -0
  61. package/Components/ModalComponent/AudioPlayer/Components/Button.tsx +395 -0
  62. package/Components/ModalComponent/AudioPlayer/Components/Header.tsx +763 -0
  63. package/Components/ModalComponent/AudioPlayer/Components/Input.tsx +653 -0
  64. package/Components/ModalComponent/AudioPlayer/Components/Item.tsx +874 -0
  65. package/Components/ModalComponent/AudioPlayer/Components/NowPlayingHeaderSection.tsx +89 -0
  66. package/Components/ModalComponent/AudioPlayer/Components/index.ts +11 -0
  67. package/Components/ModalComponent/AudioPlayer/utils/mergeStyles.ts +199 -0
  68. package/Components/ModalComponent/BottomSheetDragArea.tsx +33 -0
  69. package/Components/ModalComponent/BottomSheetModalContent.tsx +383 -42
  70. package/Components/ModalComponent/Button/index.tsx +5 -3
  71. package/Components/ModalComponent/Header/index.tsx +20 -7
  72. package/Components/ModalComponent/Header/utils.ts +1 -1
  73. package/Components/ModalComponent/ModalBlocksStyleContext.tsx +10 -0
  74. package/Components/ModalComponent/SortableList.tsx +142 -0
  75. package/Components/ModalComponent/SortableList.web.tsx +34 -0
  76. package/Components/ModalComponent/TextInputContent.tsx +100 -0
  77. package/Components/ModalComponent/__tests__/BottomSheetDragArea.test.tsx +74 -0
  78. package/Components/ModalComponent/__tests__/BottomSheetModalContent.test.tsx +238 -0
  79. package/Components/ModalComponent/__tests__/SortableList.web.test.tsx +16 -0
  80. package/Components/ModalComponent/__tests__/TextInputContent.test.tsx +120 -0
  81. package/Components/ModalComponent/__tests__/showTextInput.test.ts +95 -0
  82. package/Components/ModalComponent/index.tsx +11 -0
  83. package/Components/ModalComponent/presets/__tests__/getCell.test.ts +66 -0
  84. package/Components/ModalComponent/presets/dynamicCollectionCell.tsx +78 -0
  85. package/Components/ModalComponent/presets/index.ts +27 -0
  86. package/Components/ModalComponent/presets/selectableCell.tsx +28 -0
  87. package/Components/ModalComponent/presets/standardCell.tsx +41 -0
  88. package/Components/ModalComponent/presets/types.ts +35 -0
  89. package/Components/ModalComponent/showTextInput.ts +43 -0
  90. package/Components/ModalComponent/utils.ts +76 -20
  91. package/Components/OfflineHandler/__tests__/__snapshots__/index.test.tsx.snap +4 -85
  92. package/Components/OfflineHandler/__tests__/index.test.tsx +78 -18
  93. package/Components/OfflineHandler/hooks.ts +123 -0
  94. package/Components/OfflineHandler/index.tsx +51 -73
  95. package/Components/OfflineHandler/utils/index.ts +1 -13
  96. package/Components/PlayerContainer/PlayerContainer.tsx +25 -17
  97. package/Components/PlayerContainer/ProgramInfo/index.tsx +3 -4
  98. package/Components/PlayerContainer/__tests__/PlayerContainer.test.tsx +337 -0
  99. package/Components/PreloaderWrapper/index.tsx +1 -1
  100. package/Components/River/ComponentsMap/ComponentsMap.tsx +2 -2
  101. package/Components/River/__tests__/__snapshots__/componentsMap.test.js.snap +3 -15
  102. package/Components/Screen/index.tsx +8 -4
  103. package/Components/ScreenFeedLoader/ScreenFeedLoader.tsx +5 -3
  104. package/Components/ScreenResolverFeedProvider/ScreenResolverFeedProvider.tsx +1 -1
  105. package/Components/ScreenRevealManager/ScreenRevealManager.ts +18 -2
  106. package/Components/ScreenRevealManager/__tests__/ScreenRevealManager.test.ts +36 -0
  107. package/Components/ScreenRevealManager/__tests__/withScreenRevealManager.test.tsx +56 -0
  108. package/Components/ScreenRevealManager/withScreenRevealManager.tsx +20 -3
  109. package/Components/TopCutoffOverlay/index.tsx +2 -2
  110. package/Components/Transitioner/Transitioner.tsx +28 -17
  111. package/Components/VideoLive/LiveImageManager.ts +1 -1
  112. package/Components/VideoModal/utils.ts +6 -1
  113. package/Components/ZappFrameworkComponents/BarView/BarView.tsx +12 -5
  114. package/Components/ZappFrameworkComponents/BarView/__tests__/BarView.test.tsx +2 -2
  115. package/Contexts/CachedDimensionsContext/__tests__/index.test.ts +154 -0
  116. package/Contexts/CachedDimensionsContext/index.ts +17 -2
  117. package/Helpers/ComponentCellSelectionHelper/index.js +0 -6
  118. package/Helpers/index.js +0 -39
  119. package/Hooks/useEntryActionsExpander.ts +63 -0
  120. package/package.json +6 -5
  121. package/Components/OfflineHandler/NotificationView/NotificationView.lg.tsx +0 -112
  122. package/Components/OfflineHandler/NotificationView/NotificationView.samsung.tsx +0 -107
  123. package/Components/OfflineHandler/NotificationView/NotificationView.tsx +0 -153
  124. package/Components/OfflineHandler/NotificationView/__tests__/index.test.tsx +0 -66
  125. package/Components/OfflineHandler/NotificationView/utils.ts +0 -34
  126. package/Components/Screen/utils.ts +0 -16
  127. package/Helpers/Analytics/index.js +0 -95
  128. /package/Components/BackgroundImage/{BackgroundImage.tv.android.tsx → BackgroundImage.android.tv.tsx} +0 -0
  129. /package/Components/BackgroundImage/{BackgroundImage.tv.ios.tsx → BackgroundImage.ios.tv.tsx} +0 -0
  130. /package/Components/MasterCell/DefaultComponents/ButtonContainerView/{index.tv.android.tsx → index.android.tv.tsx} +0 -0
  131. /package/Decorators/ZappPipesDataConnector/__tests__/{Hero.js → Hero.tsx} +0 -0
@@ -1,15 +1,85 @@
1
- import {
2
- toFiniteNumberWithDefault,
3
- toNumber,
4
- } from "@applicaster/zapp-react-native-utils/numberUtils";
1
+ import { toFiniteNumberWithDefault } from "@applicaster/zapp-react-native-utils/numberUtils";
5
2
  import { isNil } from "ramda";
3
+ import { coreLogger } from "@applicaster/zapp-react-native-utils/logger";
6
4
 
7
- const dimensionRegex = /\b(width|height)=(\d+)\b/gi;
5
+ const imageResizingLogger = coreLogger
6
+ ?.addSubsystem("components")
7
+ ?.addSubsystem("ImageResizing");
8
8
 
9
+ const TEMPLATE_REGEX = /{{(width|height)}}/gi;
10
+ const UNRESOLVED_PLACEHOLDER_REGEX = /{{[^}]*}}?/;
11
+ const INVALID_PLACEHOLDER_EXTRACT_REGEX = /{{([^}]*)}}?/g;
12
+ const ALLOWED_PLACEHOLDERS = ["width", "height"];
13
+
14
+ /**
15
+ * Merges query-param string `paramsString` into `baseUrl`.
16
+ * Params from `paramsString` override any existing params with the same key.
17
+ */
18
+ export const mergeQueryParams = (
19
+ baseUrl: string,
20
+ paramsString: string
21
+ ): string => {
22
+ try {
23
+ const urlObj = new URL(baseUrl);
24
+ const newParams = new URLSearchParams(paramsString);
25
+
26
+ newParams.forEach((value, key) => {
27
+ urlObj.searchParams.set(key, value);
28
+ });
29
+
30
+ return urlObj.toString();
31
+ } catch {
32
+ // If URL parsing fails, return original
33
+ return baseUrl;
34
+ }
35
+ };
36
+
37
+ /**
38
+ * Extracts unresolved placeholder names from a param pair and logs a warning.
39
+ */
40
+ const logInvalidPlaceholders = (pair: string): void => {
41
+ const invalidNames: string[] = [];
42
+ let match: RegExpExecArray | null;
43
+
44
+ // Reset lastIndex before using the global regex
45
+ INVALID_PLACEHOLDER_EXTRACT_REGEX.lastIndex = 0;
46
+
47
+ while ((match = INVALID_PLACEHOLDER_EXTRACT_REGEX.exec(pair)) !== null) {
48
+ const name = match[1];
49
+
50
+ if (!ALLOWED_PLACEHOLDERS.includes(name?.toLowerCase())) {
51
+ invalidNames.push(name);
52
+ }
53
+ }
54
+
55
+ if (invalidNames.length > 0) {
56
+ imageResizingLogger?.warning({
57
+ message: `Image resizing: invalid placeholder(s) found: ${invalidNames.map((n) => `{{${n}}}`).join(", ")}. Allowed placeholders are: {{width}}, {{height}}. The param "${pair}" was ignored.`,
58
+ data: { pair, invalidNames, allowedPlaceholders: ALLOWED_PLACEHOLDERS },
59
+ });
60
+ }
61
+ };
62
+
63
+ /**
64
+ * Parses a dimension mapping template string (query param format) and injects
65
+ * the resolved width/height values into the given URL.
66
+ *
67
+ * The template uses `{{width}}` and `{{height}}` placeholders.
68
+ * It is treated as query-param key=value pairs (e.g. "w={{width}}&h={{height}}"
69
+ * or "size={{width}}x{{height}}").
70
+ *
71
+ * Resolved params are **merged** into the original URL – existing params with
72
+ * the same key are replaced; new ones are appended.
73
+ *
74
+ * Invalid mappings (containing unresolved placeholders like `{{heit}}` or
75
+ * malformed `{{heit}`) are silently dropped and logged as warnings.
76
+ * A leading `?` in the template is stripped.
77
+ */
9
78
  export const withDimensions = (
10
79
  url: Option<string>,
11
80
  width: Option<number | string>,
12
- height: Option<number | string>
81
+ height: Option<number | string>,
82
+ dimensionMappingTemplate?: Option<string>
13
83
  ) => {
14
84
  if (isNil(url)) {
15
85
  return url;
@@ -22,23 +92,48 @@ export const withDimensions = (
22
92
  const newWidth = Math.trunc(toFiniteNumberWithDefault(0, width));
23
93
  const newHeight = Math.trunc(toFiniteNumberWithDefault(0, height));
24
94
 
25
- return url.replace(dimensionRegex, (match, name, originalValue) => {
26
- if (name.toLocaleLowerCase() === "width" && newWidth > 0) {
27
- const originalWidth = toNumber(originalValue);
95
+ if (newWidth <= 0 && newHeight <= 0) {
96
+ return url;
97
+ }
98
+
99
+ // Strip leading `?` and whitespace from the template
100
+ const template = dimensionMappingTemplate?.trim()?.replace(/^\?/, "");
28
101
 
29
- if (originalWidth > 0 && originalWidth > newWidth) {
30
- return `${name}=${newWidth}`;
31
- }
32
- }
102
+ if (!template) {
103
+ return url;
104
+ }
33
105
 
34
- if (name.toLocaleLowerCase() === "height" && newHeight > 0) {
35
- const originalHeight = toNumber(originalValue);
106
+ // Replace {{width}} / {{height}} placeholders in the template
107
+ const resolvedTemplate = template.replace(TEMPLATE_REGEX, (_match, name) => {
108
+ if (name.toLowerCase() === "width") {
109
+ return newWidth > 0 ? String(newWidth) : _match;
110
+ }
36
111
 
37
- if (originalHeight > 0 && originalHeight > newHeight) {
38
- return `${name}=${newHeight}`;
39
- }
112
+ if (name.toLowerCase() === "height") {
113
+ return newHeight > 0 ? String(newHeight) : _match;
40
114
  }
41
115
 
42
- return match;
116
+ return _match;
43
117
  });
118
+
119
+ // Filter out param pairs that still contain unresolved / malformed placeholders
120
+ const cleanedParams = resolvedTemplate
121
+ .split("&")
122
+ .filter((pair) => {
123
+ if (UNRESOLVED_PLACEHOLDER_REGEX.test(pair)) {
124
+ logInvalidPlaceholders(pair);
125
+
126
+ return false;
127
+ }
128
+
129
+ return true;
130
+ })
131
+ .join("&");
132
+
133
+ if (!cleanedParams) {
134
+ return url;
135
+ }
136
+
137
+ // Parse the resolved template as query params and merge into URL
138
+ return mergeQueryParams(url, cleanedParams);
44
139
  };
@@ -14,25 +14,36 @@ type Style = {
14
14
  height: Option<number | string>;
15
15
  };
16
16
 
17
- const withAppliedDimensions = (style: Style) => (source: Source) => ({
18
- ...source,
19
- uri: withDimensions(source?.uri, style?.width, style?.height),
20
- });
17
+ const withAppliedDimensions =
18
+ (style: Style, dimensionMappingTemplate: string) => (source: Source) => ({
19
+ ...source,
20
+ uri: withDimensions(
21
+ source?.uri,
22
+ style?.width,
23
+ style?.height,
24
+ dimensionMappingTemplate
25
+ ),
26
+ });
21
27
 
22
28
  export const withDimensionsHOC = (Component) => {
23
29
  return function WithDimensions(props: Record<string, unknown>) {
24
30
  const theme = useTheme<BaseThemePropertiesMobile>();
25
31
 
26
- const useDownScalingImages = toBooleanWithDefaultFalse(
27
- theme.use_downscaling_images
32
+ const useImageResizing = toBooleanWithDefaultFalse(
33
+ theme.use_image_resizing ?? theme.use_downscaling_images
28
34
  );
29
35
 
36
+ const dimensionMappingTemplate = theme.image_resizing_template;
37
+
30
38
  return (
31
39
  <Component
32
40
  {...props}
33
41
  withDimensions={
34
- useDownScalingImages
35
- ? withAppliedDimensions((props?.style || {}) as Style)
42
+ useImageResizing
43
+ ? withAppliedDimensions(
44
+ (props?.style || {}) as Style,
45
+ dimensionMappingTemplate
46
+ )
36
47
  : identity
37
48
  }
38
49
  />
@@ -1,13 +1,15 @@
1
- import React from "react";
1
+ import React, { PropsWithChildren } from "react";
2
2
  import { isVideoPreviewEnabled } from "@applicaster/zapp-react-native-ui-components/Components/MasterCell/utils";
3
3
  import { LiveImage } from "../LiveImage";
4
4
  import PureImage from "../Image";
5
5
  import { useIsScreenActive } from "@applicaster/zapp-react-native-utils/reactHooks";
6
6
 
7
- type Props = {
7
+ type Props = PropsWithChildren<{
8
8
  enable_video_preview: boolean;
9
9
  player_screen_id: string;
10
- };
10
+ uri?: string;
11
+ [key: string]: any;
12
+ }>;
11
13
 
12
14
  export const ImageContainer = (props: Props) => {
13
15
  const isActive = useIsScreenActive();
@@ -1,34 +1,54 @@
1
- import React from "react";
2
- import { TouchableOpacity } from "react-native";
1
+ import React, { useCallback } from "react";
2
+ import { Pressable, ViewStyle } from "react-native";
3
+ import { PressedStateContext } from "../contexts/PressedStateContext";
3
4
 
4
5
  type Props = {
5
6
  children?: React.ReactNode;
6
- style?: Record<string, unknown>;
7
+ style?: ViewStyle | ViewStyle[];
8
+ pressedStyle?: ViewStyle | ViewStyle[];
7
9
  testID?: string;
8
10
  accessibilityLabel?: string;
9
11
  accessibilityHint?: string;
10
12
  onPress?: () => void;
13
+ testOnly_pressed?: boolean;
11
14
  };
12
15
 
13
16
  export function PressableView({
14
17
  children,
15
- style = {},
18
+ style,
16
19
  testID,
17
20
  accessibilityLabel,
18
21
  accessibilityHint,
22
+ pressedStyle,
19
23
  onPress,
24
+ testOnly_pressed = false,
20
25
  }: Props) {
21
26
  return (
22
- <TouchableOpacity
23
- activeOpacity={1}
27
+ <Pressable
28
+ testOnly_pressed={testOnly_pressed}
24
29
  onPress={onPress}
25
30
  testID={testID}
26
31
  accessibilityLabel={accessibilityLabel}
27
32
  accessibilityHint={accessibilityHint}
28
33
  accessible={!!(testID || accessibilityLabel)}
29
- style={style}
34
+ style={useCallback(
35
+ ({ pressed }) => [
36
+ style,
37
+ pressed && {
38
+ opacity: 1,
39
+ },
40
+ pressed && pressedStyle,
41
+ ],
42
+ [style, pressedStyle]
43
+ )}
30
44
  >
31
- {children}
32
- </TouchableOpacity>
45
+ {({ pressed }) => {
46
+ return (
47
+ <PressedStateContext.Provider value={pressed}>
48
+ {children}
49
+ </PressedStateContext.Provider>
50
+ );
51
+ }}
52
+ </Pressable>
33
53
  );
34
54
  }
@@ -83,6 +83,10 @@ export const useTextLabel = ({ label, entry }): string => {
83
83
  return prepareHebrewText(label, isRTL);
84
84
  };
85
85
 
86
+ /**
87
+ * Uses `otherProps.state` ("focused" | "default") to select between `focusedStyles` and `normalStyles`.
88
+ * For mobile action buttons, map `usePressedState()` (boolean) to this state value (e.g. pressed ? "focused" : "default").
89
+ */
86
90
  export const withFocusedStyles = ({ style, otherProps }) => {
87
91
  const state = R.path(["state"], otherProps);
88
92
 
@@ -1,6 +1,7 @@
1
- import React, { useState, useCallback } from "react";
1
+ import React, { useCallback, useState } from "react";
2
2
  import { Switch } from "react-native";
3
3
  import { useActions } from "@applicaster/zapp-react-native-utils/reactHooks/actions";
4
+ import { useCellClick } from "@applicaster/zapp-react-native-utils/reactHooks/cell-click";
4
5
 
5
6
  type Props = {
6
7
  item: ZappEntry | ZappFeed;
@@ -15,36 +16,57 @@ type Props = {
15
16
  export const Toggle = (props: Props) => {
16
17
  const { style, item, action, cellState } = props;
17
18
 
18
- const {
19
- trackColor,
20
- trackColorActive,
21
- thumbColor,
22
- thumbColorActive,
23
- iosBackgroundColor,
24
- } = style;
19
+ const { trackColor, trackColorActive, thumbColor, thumbColorActive } = style;
25
20
 
21
+ // `focused_selected` is the selected state with a finger on the row, so the
22
+ // switch has to read as on for both. Leaving it out reads a pressed selected
23
+ // row as off, which flips the thumb for the duration of the press.
26
24
  const isSelected = React.useMemo(
27
- () => cellState === "selected",
25
+ () => cellState === "selected" || cellState === "focused_selected",
28
26
  [item?.id, cellState]
29
27
  );
30
28
 
31
29
  const actionContext = useActions(action?.identifier);
30
+ const onCellClick = useCellClick({ item: item as ZappEntry });
32
31
 
33
- const [actionState, setActionState] = useState(
34
- actionContext.initialEntryState(item)
32
+ // A form toggle has no action plugin behind the switch: it reflects the cell
33
+ // selection state and writes through the entry's tap actions, the same path a
34
+ // tap on the row takes.
35
+ //
36
+ // An empty identifier is the way to ask for that, which is why the cell
37
+ // manifest declares no initial_value for `toggle_action_identifier`:
38
+ // `castOrDefault` substitutes the default whenever the configured value is
39
+ // empty - and an empty string counts as empty - so any default there would be
40
+ // uncleanable and would force every toggle onto that plugin.
41
+ //
42
+ // The route is still decided on whether the identifier resolves to an
43
+ // installed action plugin rather than on the string being non-empty. App
44
+ // configurations saved while the old default was in the manifest still carry
45
+ // it, and a mistyped plugin id has to fall back the same way.
46
+ const hasActionPlugin = Boolean(
47
+ action?.identifier && actionContext?.invokeAction
48
+ );
49
+
50
+ const [actionState, setActionState] = useState(() =>
51
+ hasActionPlugin ? actionContext?.initialEntryState?.(item) : undefined
35
52
  );
36
53
 
37
54
  const onPress = useCallback(() => {
38
- actionContext.invokeAction(item, {
55
+ if (!hasActionPlugin) {
56
+ onCellClick();
57
+
58
+ return;
59
+ }
60
+
61
+ actionContext?.invokeAction?.(item, {
39
62
  updateState: setActionState,
40
63
  });
41
- }, [actionState, actionContext?.state]);
64
+ }, [hasActionPlugin, onCellClick, actionState, actionContext?.state]);
42
65
 
43
66
  return (
44
67
  <Switch
45
68
  trackColor={{ false: trackColor, true: trackColorActive }}
46
69
  thumbColor={isSelected ? thumbColorActive : thumbColor}
47
- ios_backgroundColor={iosBackgroundColor}
48
70
  onValueChange={onPress}
49
71
  value={isSelected}
50
72
  />
@@ -0,0 +1,167 @@
1
+ import React from "react";
2
+ import { fireEvent, render } from "@testing-library/react-native";
3
+ import { Switch } from "react-native";
4
+ import { useActions } from "@applicaster/zapp-react-native-utils/reactHooks/actions";
5
+
6
+ import { Toggle } from "../Toggle";
7
+
8
+ const mockOnCellClick = jest.fn();
9
+ const mockInvokeAction = jest.fn();
10
+ const mockInitialEntryState = jest.fn().mockReturnValue({ state: 0 });
11
+
12
+ jest.mock("@applicaster/zapp-react-native-utils/reactHooks/cell-click", () => ({
13
+ useCellClick: jest.fn(() => mockOnCellClick),
14
+ }));
15
+
16
+ jest.mock("@applicaster/zapp-react-native-utils/reactHooks/actions", () => ({
17
+ useActions: jest.fn(() => ({
18
+ invokeAction: mockInvokeAction,
19
+ initialEntryState: mockInitialEntryState,
20
+ })),
21
+ }));
22
+
23
+ const style = {
24
+ trackColor: "rgba(0,0,0,1)",
25
+ trackColorActive: "rgba(4,207,153,1)",
26
+ thumbColor: "rgba(255,255,255,1)",
27
+ thumbColorActive: "rgba(255,255,255,1)",
28
+ } as any;
29
+
30
+ const item = { id: "true", title: "I agree" } as any;
31
+
32
+ const renderToggle = (identifier: string, cellState) =>
33
+ render(
34
+ <Toggle
35
+ item={item}
36
+ action={{ identifier }}
37
+ style={style}
38
+ cellState={cellState}
39
+ />
40
+ );
41
+
42
+ describe("Toggle with an empty action identifier", () => {
43
+ beforeEach(() => {
44
+ jest.clearAllMocks();
45
+ });
46
+
47
+ it("is on when the cell is selected", () => {
48
+ const { getByRole } = renderToggle("", "selected");
49
+
50
+ expect(getByRole("switch").props.value).toBe(true);
51
+ });
52
+
53
+ it("is off when the cell is not selected", () => {
54
+ const { getByRole } = renderToggle("", "default");
55
+
56
+ expect(getByRole("switch").props.value).toBe(false);
57
+ });
58
+
59
+ // A finger on a selected row resolves the cell to focused_selected. Reading
60
+ // that as unselected flipped the thumb for the duration of the press and let
61
+ // it jump back on release, which reads as a second tap.
62
+ it("stays on while a selected cell is pressed", () => {
63
+ const { getByRole } = renderToggle("", "focused_selected");
64
+
65
+ expect(getByRole("switch").props.value).toBe(true);
66
+ });
67
+
68
+ it("is off while an unselected cell is pressed", () => {
69
+ const { getByRole } = renderToggle("", "focused");
70
+
71
+ expect(getByRole("switch").props.value).toBe(false);
72
+ });
73
+
74
+ it("routes a change through the cell click path", () => {
75
+ const { getByRole } = renderToggle("", "default");
76
+
77
+ fireEvent(getByRole("switch"), "valueChange", true);
78
+
79
+ expect(mockOnCellClick).toHaveBeenCalledTimes(1);
80
+ expect(mockInvokeAction).not.toHaveBeenCalled();
81
+ });
82
+
83
+ it("does not read the action plugin state", () => {
84
+ renderToggle("", "default");
85
+
86
+ expect(mockInitialEntryState).not.toHaveBeenCalled();
87
+ });
88
+
89
+ // Asserted on the Switch element rather than the rendered host component:
90
+ // what Toggle owns is the props it hands to Switch, and React Native rewrites
91
+ // them into platform-specific ones (tintColor, a style entry) underneath.
92
+ it("forwards every configured color to the switch", () => {
93
+ const { UNSAFE_getByType } = renderToggle("", "default");
94
+
95
+ expect(UNSAFE_getByType(Switch).props).toMatchObject({
96
+ trackColor: { false: style.trackColor, true: style.trackColorActive },
97
+ thumbColor: style.thumbColor,
98
+ });
99
+ });
100
+
101
+ // ios_backgroundColor paints an opaque layer behind the track that the track
102
+ // color cannot cover, which on iOS reads as a halo around the switch. The
103
+ // switch is left on its platform default instead, so the prop must stay
104
+ // unset even if a style happens to carry a color for it.
105
+ it("does not set an iOS background color on the switch", () => {
106
+ const { UNSAFE_getByType } = renderToggle("", "default");
107
+
108
+ expect(UNSAFE_getByType(Switch).props.ios_backgroundColor).toBeUndefined();
109
+ });
110
+ });
111
+
112
+ describe("Toggle with an action plugin identifier", () => {
113
+ beforeEach(() => {
114
+ jest.clearAllMocks();
115
+ });
116
+
117
+ it("routes a change through the action plugin", () => {
118
+ const { getByRole } = renderToggle("firebase-push-topic-action", "default");
119
+
120
+ fireEvent(getByRole("switch"), "valueChange", true);
121
+
122
+ expect(mockInvokeAction).toHaveBeenCalledWith(
123
+ item,
124
+ expect.objectContaining({ updateState: expect.any(Function) })
125
+ );
126
+
127
+ expect(mockOnCellClick).not.toHaveBeenCalled();
128
+ });
129
+ });
130
+
131
+ describe("Toggle with an identifier whose action plugin is not installed", () => {
132
+ // The cell manifest no longer defaults toggle_action_identifier, but app
133
+ // configurations saved while it did still carry "firebase-push-topic-action",
134
+ // and a mistyped id is always possible. A toggle can therefore still arrive
135
+ // with a non-empty identifier it never asked for - the presence of a real
136
+ // action context, not the identifier string, is what decides the route.
137
+ beforeEach(() => {
138
+ jest.clearAllMocks();
139
+
140
+ (useActions as jest.Mock).mockReturnValue(undefined);
141
+ });
142
+
143
+ afterEach(() => {
144
+ (useActions as jest.Mock).mockReturnValue({
145
+ invokeAction: mockInvokeAction,
146
+ initialEntryState: mockInitialEntryState,
147
+ });
148
+ });
149
+
150
+ it("routes a change through the cell click path", () => {
151
+ const { getByRole } = renderToggle("firebase-push-topic-action", "default");
152
+
153
+ fireEvent(getByRole("switch"), "valueChange", true);
154
+
155
+ expect(mockOnCellClick).toHaveBeenCalledTimes(1);
156
+ expect(mockInvokeAction).not.toHaveBeenCalled();
157
+ });
158
+
159
+ it("still reflects the cell selection state", () => {
160
+ const { getByRole } = renderToggle(
161
+ "firebase-push-topic-action",
162
+ "selected"
163
+ );
164
+
165
+ expect(getByRole("switch").props.value).toBe(true);
166
+ });
167
+ });