@applicaster/zapp-react-native-utils 16.0.0-alpha.5402127570 → 16.0.0-alpha.5548956531

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 (114) hide show
  1. package/actionsExecutor/ActionExecutor.ts +8 -10
  2. package/actionsExecutor/ActionExecutorContext.tsx +45 -325
  3. package/actionsExecutor/actions/__tests__/dismissBottomSheet.test.ts +22 -0
  4. package/actionsExecutor/actions/__tests__/loadItemsFromSource.test.ts +88 -0
  5. package/actionsExecutor/actions/__tests__/openBottomSheet.customContent.test.ts +76 -0
  6. package/actionsExecutor/actions/__tests__/showToast.test.ts +63 -0
  7. package/actionsExecutor/actions/appRestart.ts +24 -0
  8. package/actionsExecutor/actions/confirmDialog.ts +53 -0
  9. package/actionsExecutor/actions/dismissBottomSheet.ts +22 -0
  10. package/actionsExecutor/actions/index.ts +34 -0
  11. package/actionsExecutor/actions/localStorageRemove.ts +27 -0
  12. package/actionsExecutor/actions/localStorageSet.ts +28 -0
  13. package/actionsExecutor/actions/localStorageToggleFlag.ts +28 -0
  14. package/actionsExecutor/actions/navigateToScreen.ts +123 -0
  15. package/actionsExecutor/actions/openBottomSheet.ts +318 -0
  16. package/actionsExecutor/actions/refreshComponent.ts +85 -0
  17. package/actionsExecutor/actions/screenSetVariable.ts +35 -0
  18. package/actionsExecutor/actions/screenToggleFlag.ts +38 -0
  19. package/actionsExecutor/actions/sendCloudEvent.ts +96 -0
  20. package/actionsExecutor/actions/sessionStorageRemove.ts +19 -0
  21. package/actionsExecutor/actions/sessionStorageSet.ts +20 -0
  22. package/actionsExecutor/actions/sessionStorageToggleFlag.ts +15 -0
  23. package/actionsExecutor/actions/showToast.ts +31 -0
  24. package/actionsExecutor/actions/switchLayout.ts +40 -0
  25. package/actionsExecutor/types.ts +59 -0
  26. package/analyticsUtils/PlayerAnalyticsManager.ts +1 -1
  27. package/appUtils/contextKeysManager/__tests__/getKey/failure.test.ts +1 -1
  28. package/appUtils/contextKeysManager/__tests__/removeKey/failure.test.ts +1 -1
  29. package/appUtils/contextKeysManager/__tests__/setKey/failure/invalidKey.test.ts +4 -4
  30. package/appUtils/contextKeysManager/index.ts +1 -1
  31. package/appUtils/playerManager/OverlayObserver/OverlaysObserver.ts +12 -6
  32. package/appUtils/playerManager/__tests__/playerFactory.test.ts +1 -1
  33. package/appUtils/playerManager/{conts.ts → const.ts} +20 -0
  34. package/appUtils/playerManager/index.ts +1 -1
  35. package/appUtils/playerManager/player.ts +1 -1
  36. package/appUtils/playerManager/playerFactory.ts +1 -1
  37. package/appUtils/playerManager/playerNative.ts +1 -1
  38. package/appUtils/playerManager/usePlayerControllerSetup.tsx +1 -1
  39. package/appUtils/playerManager/userLanguagePreference.ts +1 -1
  40. package/arrayUtils/__tests__/{anyThruthy.test.ts → anyTruthy.test.ts} +8 -0
  41. package/arrayUtils/__tests__/arrayUtils.test.ts +165 -108
  42. package/arrayUtils/__tests__/isEmptyArray.test.ts +11 -0
  43. package/arrayUtils/__tests__/isFilledArray.test.ts +12 -0
  44. package/arrayUtils/__tests__/isFirst.test.ts +17 -0
  45. package/arrayUtils/__tests__/isIndexInRange.test.ts +14 -0
  46. package/arrayUtils/__tests__/isLast.test.ts +31 -0
  47. package/arrayUtils/__tests__/makeListOf.test.ts +31 -0
  48. package/arrayUtils/__tests__/makeListOfIndexes.test.ts +20 -0
  49. package/arrayUtils/__tests__/sample.test.ts +61 -0
  50. package/arrayUtils/index.ts +57 -20
  51. package/bottomSheet/__tests__/scrollContext.test.tsx +35 -0
  52. package/bottomSheet/index.ts +17 -0
  53. package/cellUtils/index.ts +3 -5
  54. package/colorUtils/__tests__/isTransparentColor.test.ts +76 -0
  55. package/colorUtils/__tests__/isValidColor.test.ts +70 -0
  56. package/colorUtils/index.ts +50 -0
  57. package/manifestUtils/_internals/index.js +6 -0
  58. package/manifestUtils/defaultManifestConfigurations/player.js +19 -19
  59. package/manifestUtils/fieldUtils/__tests__/fieldUtils.test.js +84 -0
  60. package/manifestUtils/fieldUtils/index.js +125 -0
  61. package/manifestUtils/keys.js +9 -0
  62. package/manifestUtils/mobileAction/button/index.js +16 -0
  63. package/manifestUtils/mobileAction/container/index.js +3 -1
  64. package/manifestUtils/mobileAction/groups/defaults.js +3 -1
  65. package/manifestUtils/platformIsTV.js +1 -0
  66. package/modalState/ContentViewModel.ts +111 -0
  67. package/modalState/EditableCollection.ts +17 -0
  68. package/modalState/EditableCollectionRegistry.ts +51 -0
  69. package/modalState/ModalOrchestrator.ts +198 -0
  70. package/modalState/RemoteEditableCollection.ts +189 -0
  71. package/modalState/__tests__/ContentViewModel.editable.test.ts +69 -0
  72. package/modalState/__tests__/ContentViewModel.test.ts +165 -0
  73. package/modalState/__tests__/EditableCollectionRegistry.test.ts +112 -0
  74. package/modalState/__tests__/ModalOrchestrator.phase3.test.ts +28 -0
  75. package/modalState/__tests__/RemoteEditableCollection.test.ts +259 -0
  76. package/modalState/__tests__/useBottomSheetContent.test.ts +372 -0
  77. package/modalState/index.ts +30 -83
  78. package/modalState/store.ts +102 -0
  79. package/modalState/types.ts +110 -0
  80. package/modalState/useBottomSheetContent.ts +98 -0
  81. package/numberUtils/__tests__/isMinusZero.test.ts +20 -0
  82. package/numberUtils/__tests__/isZero.test.ts +27 -0
  83. package/numberUtils/__tests__/requireNumber.test.ts +50 -0
  84. package/numberUtils/__tests__/toNumber.test.ts +27 -0
  85. package/numberUtils/__tests__/toNumberWithDefault.test.ts +64 -0
  86. package/numberUtils/__tests__/toNumberWithDefaultZero.test.ts +48 -0
  87. package/numberUtils/index.ts +27 -8
  88. package/package.json +2 -2
  89. package/pipesUtils/__tests__/buildUrlWithQuery.test.ts +33 -0
  90. package/pipesUtils/__tests__/withPipesEndpoint.test.tsx +56 -0
  91. package/pipesUtils/index.ts +1 -0
  92. package/pipesUtils/withPipesEndpoint.tsx +54 -0
  93. package/reactHooks/actions/index.ts +51 -1
  94. package/reactHooks/cell-click/index.ts +3 -3
  95. package/reactHooks/feed/__mocks__/useMarkPipesDataStale.ts +4 -0
  96. package/reactHooks/feed/__tests__/useInflatedUrl.test.tsx +25 -0
  97. package/reactHooks/feed/index.ts +5 -1
  98. package/reactHooks/feed/useBatchLoading.ts +9 -1
  99. package/reactHooks/feed/{usePipesCacheReset.ts → useMarkPipesDataStale.ts} +12 -4
  100. package/reactHooks/layout/index.ts +1 -1
  101. package/reactHooks/navigation/__mocks__/index.ts +4 -0
  102. package/reactHooks/navigation/__tests__/useIsScreenActive.test.ts +42 -0
  103. package/reactHooks/navigation/index.ts +1 -1
  104. package/reactHooks/navigation/useIsScreenActive.ts +29 -8
  105. package/reactHooks/state/useComponentScreenState.ts +1 -1
  106. package/reactHooks/utils/index.ts +3 -2
  107. package/riverComponetsMeasurementProvider/index.tsx +12 -8
  108. package/stringUtils/__tests__/stringUtils.test.js +42 -0
  109. package/stringUtils/index.ts +2 -2
  110. package/uiActionsRegistrator/index.ts +203 -0
  111. package/zappFrameworkUtils/__tests__/localStorageHelper.test.ts +146 -0
  112. package/zappFrameworkUtils/localStorageHelper.ts +9 -13
  113. package/reactHooks/feed/__mocks__/usePipesCacheReset.ts +0 -1
  114. /package/reactHooks/actions/__tests__/{index.test.js → index.test.tsx} +0 -0
@@ -1,3 +1,121 @@
1
+ const { ZAPPIFEST_FIELDS } = require("../keys");
2
+ const { toCamelCase } = require("../_internals");
3
+
4
+ const SIDES = ["top", "right", "bottom", "left"];
5
+
6
+ /**
7
+ * Parses a CSS margin/padding shorthand string into [top, right, bottom, left].
8
+ *
9
+ * 1 value → all four sides
10
+ * 2 values → top/bottom, right/left
11
+ * 3 values → top, right/left, bottom
12
+ * 4 values → top, right, bottom, left
13
+ *
14
+ * @param {string} str
15
+ * @returns {[number, number, number, number]}
16
+ */
17
+ function parseShorthand(str) {
18
+ const parts = String(str).trim().split(/\s+/).map(Number);
19
+
20
+ switch (parts.length) {
21
+ case 1:
22
+ return [parts[0], parts[0], parts[0], parts[0]];
23
+ case 2:
24
+ return [parts[0], parts[1], parts[0], parts[1]];
25
+ case 3:
26
+ return [parts[0], parts[1], parts[2], parts[1]];
27
+ case 4:
28
+ return parts;
29
+ default:
30
+ throw new Error(
31
+ `Shorthand expects 1–4 space-separated values, got ${parts.length}: "${str}"`
32
+ );
33
+ }
34
+ }
35
+
36
+ function spacingFields(prefix, initialValues) {
37
+ const platforms = Object.keys(initialValues);
38
+
39
+ const parsed = Object.fromEntries(
40
+ platforms.map((p) => [p, parseShorthand(initialValues[p])])
41
+ );
42
+
43
+ return SIDES.map((side, i) => ({
44
+ suffix: `${prefix} ${side}`,
45
+ type: ZAPPIFEST_FIELDS.number_input,
46
+ initialValue: Object.fromEntries(platforms.map((p) => [p, parsed[p][i]])),
47
+ }));
48
+ }
49
+
50
+ /**
51
+ * Generates four margin field descriptors (top/right/bottom/left) from a
52
+ * per-platform CSS shorthand string.
53
+ *
54
+ * @param {string} suffix - prefix word for generated field names, e.g. "margin"
55
+ * @param {Record<string, string>} initialValues - e.g. { mobile: "0 0 20", tv: "0 0 90" }
56
+ * @returns {object[]}
57
+ */
58
+ function margin(suffix, initialValues) {
59
+ return spacingFields(suffix, initialValues);
60
+ }
61
+
62
+ /**
63
+ * Generates four padding field descriptors (top/right/bottom/left) from a
64
+ * per-platform CSS shorthand string.
65
+ *
66
+ * @param {string} suffix - prefix word for generated field names, e.g. "padding"
67
+ * @param {Record<string, string>} initialValues - e.g. { mobile: "0 20", tv: "0 124" }
68
+ * @returns {object[]}
69
+ */
70
+ function padding(suffix, initialValues) {
71
+ return spacingFields(suffix, initialValues);
72
+ }
73
+
74
+ /**
75
+ * Returns a flat camelCase defaults object for a spacing shorthand.
76
+ * e.g. marginDefaults("margin", "0 0 20") → { marginTop: 0, marginRight: 0, marginBottom: 20, marginLeft: 0 }
77
+ *
78
+ * @param {string} suffix - e.g. "margin" or "padding"
79
+ * @param {string} shorthand - CSS-like shorthand string
80
+ * @returns {Record<string, number>}
81
+ */
82
+ function spacingDefaults(suffix, shorthand) {
83
+ const values = parseShorthand(shorthand);
84
+
85
+ return Object.fromEntries(
86
+ SIDES.map((side, i) => [toCamelCase(`${suffix} ${side}`), values[i]])
87
+ );
88
+ }
89
+
90
+ function marginDefaults(suffix, shorthand) {
91
+ return spacingDefaults(suffix, shorthand);
92
+ }
93
+
94
+ function paddingDefaults(suffix, shorthand) {
95
+ return spacingDefaults(suffix, shorthand);
96
+ }
97
+
98
+ /**
99
+ * Returns four field descriptors (top/right/bottom/left) with only suffix and type — no initialValue.
100
+ * Used when defaults are stored separately in the subgroup spec.
101
+ *
102
+ * @param {string} prefix - e.g. "margin" or "padding"
103
+ * @returns {object[]}
104
+ */
105
+ function marginFields(prefix) {
106
+ return SIDES.map((side) => ({
107
+ suffix: `${prefix} ${side}`,
108
+ type: ZAPPIFEST_FIELDS.number_input,
109
+ }));
110
+ }
111
+
112
+ function paddingFields(prefix) {
113
+ return SIDES.map((side) => ({
114
+ suffix: `${prefix} ${side}`,
115
+ type: ZAPPIFEST_FIELDS.number_input,
116
+ }));
117
+ }
118
+
1
119
  /**
2
120
  * Appends new conditional_fields from conditions array
3
121
  * to config.conditional_fields
@@ -48,6 +166,13 @@ function createConditionalField(key, condition_value, category = "styles") {
48
166
  }
49
167
 
50
168
  module.exports = {
169
+ parseShorthand,
170
+ margin,
171
+ padding,
172
+ marginDefaults,
173
+ paddingDefaults,
174
+ marginFields,
175
+ paddingFields,
51
176
  withConditional,
52
177
  getConditionalKey,
53
178
  createConditionalField,
@@ -43,6 +43,7 @@ const TV_PLATFORMS = [
43
43
  "tvos_for_quickbrick",
44
44
  "samsung_tv",
45
45
  "lg_tv",
46
+ "vidaa",
46
47
  "vizio",
47
48
  ];
48
49
 
@@ -630,6 +631,14 @@ const MOBILE_ACTION_BUTTON_FIELDS = [
630
631
  type: ZAPPIFEST_FIELDS.number_input,
631
632
  suffix: "margin left",
632
633
  },
634
+ {
635
+ type: ZAPPIFEST_FIELDS.number_input,
636
+ suffix: "horizontal gutter",
637
+ },
638
+ {
639
+ type: ZAPPIFEST_FIELDS.number_input,
640
+ suffix: "vertical gutter",
641
+ },
633
642
  ];
634
643
 
635
644
  const TV_MENU_LABEL_FIELDS = [
@@ -129,6 +129,22 @@ function mobileActionButton({ label, description, defaults, isFirstButton }) {
129
129
  conditions.push(createConditionalField(labelEnabledKey, true));
130
130
  }
131
131
 
132
+ const assetAlignmentKey = keyPrefixGenerator("asset_alignment");
133
+
134
+ // horizontal_gutter fields depends on [asset_alignment: left or asset_alignment: right]
135
+ if (isKeyHasSuffix("horizontal_gutter", key)) {
136
+ conditions.push(
137
+ createConditionalField(assetAlignmentKey, ["left", "right"])
138
+ );
139
+ }
140
+
141
+ // vertical_gutter fields depends on [asset_alignment: above or asset_alignment: below]
142
+ if (isKeyHasSuffix("vertical_gutter", key)) {
143
+ conditions.push(
144
+ createConditionalField(assetAlignmentKey, ["above", "below"])
145
+ );
146
+ }
147
+
132
148
  return withConditional(conditions)(field);
133
149
  });
134
150
 
@@ -49,7 +49,9 @@ function mobileActionButtonsContainer({ label, description, defaults }) {
49
49
 
50
50
  // over_image_position depends on [positionKey: over_image]
51
51
  if (isKeyHasSuffix("over_image_position", key)) {
52
- conditions.push(createConditionalField(positionKey, "over_image"));
52
+ conditions.push(
53
+ createConditionalField(positionKey, defaults.position[0])
54
+ );
53
55
  }
54
56
 
55
57
  // horizontal_gutter depends on [stackingKey: horizontal]
@@ -33,7 +33,7 @@ const DEFAULT_MOBILE_ACTION_BUTTON_SHARED_DEFAULTS = {
33
33
  assetHeight: 24,
34
34
  assetWidth: 24,
35
35
  assetMarginTop: 0,
36
- assetMarginRight: 6,
36
+ assetMarginRight: 0,
37
37
  assetMarginBottom: 0,
38
38
  assetMarginLeft: 0,
39
39
  labelEnabled: true,
@@ -50,6 +50,8 @@ const DEFAULT_MOBILE_ACTION_BUTTON_SHARED_DEFAULTS = {
50
50
  marginRight: 0,
51
51
  marginBottom: 0,
52
52
  marginLeft: 0,
53
+ horizontalGutter: 8,
54
+ verticalGutter: 8,
53
55
  };
54
56
 
55
57
  const DEFAULT_MOBILE_ACTION_BUTTON_PRESETS = {
@@ -4,6 +4,7 @@ function platformIsTV(platform) {
4
4
  "android_tv_for_quickbrick",
5
5
  "amazon_fire_tv_for_quickbrick",
6
6
  "lg_tv",
7
+ "vidaa",
7
8
  "samsung_tv",
8
9
  "web",
9
10
  "vizio",
@@ -0,0 +1,111 @@
1
+ import { BehaviorSubject, Observable } from "rxjs";
2
+ import {
3
+ Content,
4
+ MenuItem,
5
+ SelectionBehavior,
6
+ DynamicCollectionOptions,
7
+ } from "./types";
8
+ import { loadItemsFromSource } from "../actionsExecutor/actions/openBottomSheet";
9
+ import { resolveEditableCollection } from "./EditableCollectionRegistry";
10
+ import { EditableCollection } from "./EditableCollection";
11
+
12
+ export interface ContentState {
13
+ items: MenuItem[];
14
+ isLoading: boolean;
15
+ error?: Error | string;
16
+ role?: string;
17
+ behavior?: SelectionBehavior;
18
+ dynamicCollection?: DynamicCollectionOptions;
19
+ }
20
+
21
+ export class ContentViewModel {
22
+ private state$: BehaviorSubject<ContentState>;
23
+ readonly itemsUrl?: string;
24
+ public editableCollection: EditableCollection | null = null;
25
+ private content: Content;
26
+
27
+ constructor(content: Content) {
28
+ this.content = content;
29
+ this.itemsUrl = content.itemsUrl;
30
+
31
+ this.state$ = new BehaviorSubject<ContentState>({
32
+ items: content.items || [],
33
+ isLoading: false,
34
+ role: content.role,
35
+ behavior: content.behavior,
36
+ dynamicCollection: content.dynamicCollection,
37
+ });
38
+
39
+ this.initEditableCollection(content);
40
+
41
+ if (this.itemsUrl && this.state$.value.items.length === 0) {
42
+ this.refetch();
43
+ }
44
+ }
45
+
46
+ private initEditableCollection(content: Content) {
47
+ this.editableCollection = resolveEditableCollection(content, this.refetch);
48
+ }
49
+
50
+ getState = (): ContentState => this.state$.value;
51
+
52
+ get stateObservable(): Observable<ContentState> {
53
+ return this.state$.asObservable();
54
+ }
55
+
56
+ subscribe = (listener: (state: ContentState) => void) => {
57
+ const subscription = this.state$.subscribe(listener);
58
+
59
+ return () => subscription.unsubscribe();
60
+ };
61
+
62
+ private updateState(partialState: Partial<ContentState>) {
63
+ this.state$.next({ ...this.state$.value, ...partialState });
64
+ }
65
+
66
+ refetch = async () => {
67
+ if (!this.itemsUrl) return;
68
+
69
+ this.updateState({ isLoading: true, error: undefined });
70
+
71
+ try {
72
+ const separator = this.itemsUrl.includes("?") ? "&" : "?";
73
+ const cacheBustedUrl = `${this.itemsUrl}${separator}_t=${Date.now()}`;
74
+
75
+ const { items, role, behavior, dynamicCollection } =
76
+ await loadItemsFromSource(cacheBustedUrl);
77
+
78
+ this.content = {
79
+ ...this.content,
80
+ items,
81
+ role,
82
+ behavior,
83
+ dynamicCollection,
84
+ };
85
+
86
+ this.updateState({
87
+ items,
88
+ role,
89
+ behavior,
90
+ dynamicCollection,
91
+ isLoading: false,
92
+ });
93
+
94
+ if (this.editableCollection) {
95
+ // Reuse the existing collection instance. Pushing the freshly loaded
96
+ // server items replaces any optimistic local state with the
97
+ // authoritative result (and rolls forward a successful mutation).
98
+ this.editableCollection.sync?.(items);
99
+ } else {
100
+ // The collection may only become resolvable once options arrive from
101
+ // the feed (e.g. inline content had none). Create it lazily here.
102
+ this.initEditableCollection(this.content);
103
+ }
104
+ } catch (err) {
105
+ this.updateState({
106
+ error: err?.message || "Failed to load",
107
+ isLoading: false,
108
+ });
109
+ }
110
+ };
111
+ }
@@ -0,0 +1,17 @@
1
+ import { Observable } from "rxjs";
2
+ import { MenuItem, Operation } from "./types";
3
+
4
+ export interface EditableCollection {
5
+ items$: Observable<MenuItem[]>;
6
+ operations: Operation[];
7
+ add?(item?: MenuItem): void | Promise<void>;
8
+ remove?(index: number): void | Promise<void>;
9
+ move?(itemIds: string[]): void | Promise<void>;
10
+ deleteCollection?(): void | Promise<void>;
11
+ /**
12
+ * Push authoritative items (e.g. a fresh server feed after a mutation) into
13
+ * the collection, replacing any optimistic local state. Called by the
14
+ * ContentViewModel on refetch so the instance is reused instead of recreated.
15
+ */
16
+ sync?(items: MenuItem[]): void;
17
+ }
@@ -0,0 +1,51 @@
1
+ import { Content } from "./types";
2
+ import { EditableCollection } from "./EditableCollection";
3
+ import { RemoteEditableCollection } from "./RemoteEditableCollection";
4
+ import { createLogger } from "../logger";
5
+
6
+ const { log_error } = createLogger({
7
+ subsystem: "modalState",
8
+ category: "EditableCollectionRegistry",
9
+ });
10
+
11
+ type ProviderFactory = () => EditableCollection;
12
+
13
+ export class EditableCollectionRegistry {
14
+ private static providers: Record<string, ProviderFactory> = {};
15
+
16
+ static register(token: string, factory: ProviderFactory) {
17
+ this.providers[token] = factory;
18
+ }
19
+
20
+ static getProvider(token: string): EditableCollection | null {
21
+ const factory = this.providers[token];
22
+
23
+ return factory ? factory() : null;
24
+ }
25
+ }
26
+
27
+ export function resolveEditableCollection(
28
+ content: Content,
29
+ refetch: () => Promise<void>
30
+ ): EditableCollection | null {
31
+ const options = content.dynamicCollection;
32
+ if (!options) return null;
33
+
34
+ if (options.provider) {
35
+ const provider = EditableCollectionRegistry.getProvider(options.provider);
36
+
37
+ if (!provider) {
38
+ log_error(
39
+ `No EditableCollection provider registered for token "${options.provider}"`
40
+ );
41
+ }
42
+
43
+ return provider;
44
+ }
45
+
46
+ if (options.postUrl) {
47
+ return new RemoteEditableCollection(content, refetch);
48
+ }
49
+
50
+ return null;
51
+ }
@@ -0,0 +1,198 @@
1
+ import { dismissModal, modalStore, openBottomSheetModal } from "./store";
2
+ import { isPresentSubMenuAction, Menu, MenuItem } from "./types";
3
+ import { ContentViewModel } from "./ContentViewModel";
4
+
5
+ export type { Menu, MenuItem };
6
+
7
+ export { isPresentSubMenuAction };
8
+
9
+ /**
10
+ * Converts a Menu model into the props expected by BottomSheetModalContent.
11
+ * - Maps MenuItem.title → label (required by BottomSheetModalContent)
12
+ * - Maps MenuItem.icon → image src
13
+ * - Flattens header.title / header.subtitle into top-level title / summary
14
+ */
15
+ interface StackEntry {
16
+ menu: Menu;
17
+ onItemPress?: (item: MenuItem) => void | Promise<void>;
18
+ viewModel: ContentViewModel;
19
+ }
20
+
21
+ function menuToModalArgs(
22
+ menu: Menu,
23
+ viewModel: ContentViewModel,
24
+ onItemPress: (item: MenuItem) => void | Promise<void>,
25
+ key: string
26
+ ): OpenModalBottomSheetArgs {
27
+ const items = menu.content.items.map((item) => ({
28
+ ...item,
29
+ // BottomSheetModalContent renders `theme[item.label] ?? item.label`
30
+ label: item.title,
31
+ }));
32
+
33
+ return {
34
+ modalBottomSheetContentProps: {
35
+ key,
36
+ items,
37
+ itemsUrl: menu.content.itemsUrl,
38
+ title: menu.header?.title ?? menu.content.title,
39
+ summary: menu.header?.subtitle,
40
+ onPress: onItemPress,
41
+ viewModel,
42
+ },
43
+ options: {},
44
+ };
45
+ }
46
+
47
+ /**
48
+ * ModalOrchestrator manages a stack of Menu modals, enabling push/pop
49
+ * navigation between bottom sheet screens.
50
+ *
51
+ * Usage:
52
+ * modalOrchestrator.open(menu);
53
+ * modalOrchestrator.back(); // go to previous modal in the stack
54
+ * modalOrchestrator.close(); // dismiss all and clear the stack
55
+ */
56
+ class ModalOrchestrator {
57
+ private _stack: StackEntry[] = [];
58
+
59
+ /** Number of entries currently in the stack. */
60
+ get stackSize(): number {
61
+ return this._stack.length;
62
+ }
63
+
64
+ /** Whether there is a previous modal to go back to. */
65
+ get canGoBack(): boolean {
66
+ return this._stack.length > 1;
67
+ }
68
+
69
+ /** The Menu currently shown, or null if the stack is empty. */
70
+ get current(): Menu | null {
71
+ return this._stack[this._stack.length - 1]?.menu ?? null;
72
+ }
73
+
74
+ /**
75
+ * Push a new Menu onto the stack and display it.
76
+ * If a menu item carries a PresentSubMenuAction it will automatically
77
+ * push the sub-menu when pressed; all other items delegate to
78
+ * the optional `onItemPress` callback.
79
+ */
80
+ open(
81
+ menu: Menu,
82
+ onItemPress?: (item: MenuItem) => void | Promise<void>
83
+ ): void {
84
+ const viewModel = new ContentViewModel(menu.content);
85
+ this._stack.push({ menu, onItemPress, viewModel });
86
+ this._present(menu, viewModel, onItemPress);
87
+ }
88
+
89
+ /**
90
+ * Pop the current modal and return to the previous one.
91
+ * If the stack has only one entry, closes entirely.
92
+ */
93
+ back(): void {
94
+ if (this._stack.length === 0) {
95
+ return;
96
+ }
97
+
98
+ this._stack.pop();
99
+
100
+ const previous = this._stack[this._stack.length - 1];
101
+
102
+ if (previous) {
103
+ this._present(previous.menu, previous.viewModel, previous.onItemPress);
104
+ } else {
105
+ dismissModal();
106
+ }
107
+ }
108
+
109
+ /**
110
+ * Close all modals and clear the entire stack.
111
+ */
112
+ close(): void {
113
+ this._stack = [];
114
+ dismissModal();
115
+ }
116
+
117
+ /**
118
+ * Replace the current top of the stack without adding a new history entry.
119
+ */
120
+ replace(
121
+ menu: Menu,
122
+ onItemPress?: (item: MenuItem) => void | Promise<void>
123
+ ): void {
124
+ if (this._stack.length === 0) {
125
+ this.open(menu, onItemPress);
126
+
127
+ return;
128
+ }
129
+
130
+ const viewModel = new ContentViewModel(menu.content);
131
+ this._stack[this._stack.length - 1] = { menu, onItemPress, viewModel };
132
+ this._present(menu, viewModel, onItemPress);
133
+ }
134
+
135
+ private _buildOnPress(
136
+ onItemPress?: (item: MenuItem) => void | Promise<void>
137
+ ): (item: MenuItem) => void | Promise<void> {
138
+ return (item: MenuItem) => {
139
+ if (isPresentSubMenuAction(item.action)) {
140
+ // Navigate deeper into the sub-menu
141
+ this.open(item.action.menu, onItemPress);
142
+
143
+ return;
144
+ }
145
+
146
+ return onItemPress?.(item);
147
+ };
148
+ }
149
+
150
+ /**
151
+ * Called when the UI dismisses the modal (swipe / overlay tap).
152
+ * Clears the stack without calling dismissModal() again to avoid
153
+ * a feedback loop with the store reset.
154
+ */
155
+ private _onUIDismiss(): void {
156
+ this._stack = [];
157
+ }
158
+
159
+ /**
160
+ * True when the Zustand modal store already has a visible bottom sheet.
161
+ * Used to skip the slide-in animation when navigating to a deeper level.
162
+ */
163
+ private get _isOpen(): boolean {
164
+ return modalStore.getState().modalState.visible;
165
+ }
166
+
167
+ private _present(
168
+ menu: Menu,
169
+ viewModel: ContentViewModel,
170
+ onItemPress?: (item: MenuItem) => void | Promise<void>
171
+ ): void {
172
+ const key = `menu-level-${this._stack.length}`;
173
+
174
+ const args = menuToModalArgs(
175
+ menu,
176
+ viewModel,
177
+ this._buildOnPress(onItemPress),
178
+ key
179
+ );
180
+
181
+ const alreadyOpen = this._isOpen;
182
+
183
+ openBottomSheetModal({
184
+ ...args,
185
+ options: {
186
+ ...args.options,
187
+ // Skip the slide-in when updating an already-visible sheet (sub-level nav)
188
+ animated: !alreadyOpen,
189
+ animationType: alreadyOpen ? "none" : "slide",
190
+ // Keep the stack in sync when the user dismisses via swipe or overlay
191
+ onDismiss: () => this._onUIDismiss(),
192
+ onRequestClose: () => this._onUIDismiss(),
193
+ },
194
+ });
195
+ }
196
+ }
197
+
198
+ export const modalOrchestrator = new ModalOrchestrator();