@applicaster/zapp-react-native-utils 16.0.0-alpha.1042942411 → 16.0.0-alpha.1052711356

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/actionsExecutor/ActionExecutorContext.tsx +4 -0
  2. package/actionsExecutor/actions/__tests__/dismissBottomSheet.test.ts +22 -0
  3. package/actionsExecutor/actions/__tests__/loadItemsFromSource.test.ts +88 -0
  4. package/actionsExecutor/actions/__tests__/openBottomSheet.customContent.test.ts +76 -0
  5. package/actionsExecutor/actions/__tests__/showToast.test.ts +63 -0
  6. package/actionsExecutor/actions/dismissBottomSheet.ts +22 -0
  7. package/actionsExecutor/actions/index.ts +4 -0
  8. package/actionsExecutor/actions/openBottomSheet.ts +318 -0
  9. package/actionsExecutor/actions/refreshComponent.ts +6 -0
  10. package/actionsExecutor/actions/sendCloudEvent.ts +8 -0
  11. package/actionsExecutor/actions/showToast.ts +7 -7
  12. package/arrayUtils/__tests__/{anyThruthy.test.ts → anyTruthy.test.ts} +8 -0
  13. package/arrayUtils/__tests__/arrayUtils.test.ts +165 -108
  14. package/arrayUtils/__tests__/isEmptyArray.test.ts +11 -0
  15. package/arrayUtils/__tests__/isFilledArray.test.ts +12 -0
  16. package/arrayUtils/__tests__/isFirst.test.ts +17 -0
  17. package/arrayUtils/__tests__/isIndexInRange.test.ts +14 -0
  18. package/arrayUtils/__tests__/isLast.test.ts +31 -0
  19. package/arrayUtils/__tests__/makeListOf.test.ts +31 -0
  20. package/arrayUtils/__tests__/makeListOfIndexes.test.ts +20 -0
  21. package/arrayUtils/__tests__/sample.test.ts +61 -0
  22. package/arrayUtils/index.ts +57 -20
  23. package/modalState/ContentViewModel.ts +111 -0
  24. package/modalState/EditableCollection.ts +17 -0
  25. package/modalState/EditableCollectionRegistry.ts +51 -0
  26. package/modalState/ModalOrchestrator.ts +198 -0
  27. package/modalState/RemoteEditableCollection.ts +189 -0
  28. package/modalState/__tests__/ContentViewModel.editable.test.ts +69 -0
  29. package/modalState/__tests__/ContentViewModel.test.ts +165 -0
  30. package/modalState/__tests__/EditableCollectionRegistry.test.ts +112 -0
  31. package/modalState/__tests__/ModalOrchestrator.phase3.test.ts +28 -0
  32. package/modalState/__tests__/RemoteEditableCollection.test.ts +259 -0
  33. package/modalState/__tests__/useBottomSheetContent.test.ts +372 -0
  34. package/modalState/index.ts +30 -83
  35. package/modalState/store.ts +102 -0
  36. package/modalState/types.ts +110 -0
  37. package/modalState/useBottomSheetContent.ts +98 -0
  38. package/package.json +2 -2
  39. package/zappFrameworkUtils/__tests__/localStorageHelper.test.ts +146 -0
  40. package/zappFrameworkUtils/localStorageHelper.ts +9 -13
  41. /package/reactHooks/actions/__tests__/{index.test.js → index.test.tsx} +0 -0
@@ -3,17 +3,16 @@ import * as R from "ramda";
3
3
  import { invariant } from "@applicaster/zapp-react-native-utils/errorUtils";
4
4
 
5
5
  /**
6
- * shifts an array by the given offset. a negative offset will take items
7
- * from the end of the array and add them at the beginning, while a positive offset
8
- * will take an item at the beginning and shift it to the end
9
- * shiftArray(-1, [1,2,3,4]) => [4, 1, 2, 3]
10
- * shiftArray(1, [1,2,3,4]) => [2, 3, 4, 1]
11
- * an offset of 0 leaves the array unchanged
12
- * this function returns a new array and doesn't mutate the original one
13
- * curried function which can be invoked like offset => array => result
14
- * @param {Number} offset offset to shift the array
15
- * @param {Array<T>} array array to shift
16
- * @returns {Array<T>}
6
+ * Shifts an array by the given offset and returns a new array (does not mutate).
7
+ * A positive offset moves items from the head to the tail;
8
+ * a negative offset moves items from the tail to the head.
9
+ * An offset of `0` leaves the order unchanged.
10
+ *
11
+ * Curried (Ramda): `shiftArray(offset)(array)` or `shiftArray(offset, array)`.
12
+ *
13
+ * @example
14
+ * shiftArray(-1, [1, 2, 3, 4]) // => [4, 1, 2, 3]
15
+ * shiftArray(1, [1, 2, 3, 4]) // => [2, 3, 4, 1]
17
16
  */
18
17
  export const shiftArray = R.curry(
19
18
  <T extends unknown>(offset: number, array: T[]): T[] => {
@@ -25,10 +24,9 @@ export const shiftArray = R.curry(
25
24
  );
26
25
 
27
26
  /**
28
- * Tries to remove an item from an array, and returns the array if the item is not found
29
- * @param {any} item to remove
30
- * @param {Array<any>} list to remove the item from
31
- * @returns {Array<any>}
27
+ * Removes the first item equal to `item` from `list` (Ramda `equals` / deep equality).
28
+ * If the item is not found, returns the same list reference; otherwise returns a new
29
+ * array without that element.
32
30
  */
33
31
  export function removeItemFromList<T extends unknown>(item: T, list: T[]): T[] {
34
32
  return R.compose(
@@ -37,6 +35,12 @@ export function removeItemFromList<T extends unknown>(item: T, list: T[]): T[] {
37
35
  )(list);
38
36
  }
39
37
 
38
+ /**
39
+ * Maps each value to a promise and resolves them all in parallel via `Promise.all`.
40
+ * The mapper receives `(value, index)`.
41
+ *
42
+ * Curried (Ramda): `mapPromises(fn)(values)` or `mapPromises(fn, values)`.
43
+ */
40
44
  export const mapPromises = R.curry(
41
45
  <T extends unknown, S extends unknown>(
42
46
  fn: (value: T, index?: number) => Promise<S>,
@@ -44,6 +48,10 @@ export const mapPromises = R.curry(
44
48
  ): Promise<S[]> => Promise.all(R.addIndex(R.map)(R.nAry(2, fn), values))
45
49
  );
46
50
 
51
+ /**
52
+ * Awaits `previousPromise`, then runs `fn(currentValue, previousValue, index)`.
53
+ * Used internally by `reducePromises` as a Ramda-indexed reducer step.
54
+ */
47
55
  const waitForPromiseAndRun = R.curryN(
48
56
  3,
49
57
  async <T extends unknown, S extends unknown>(
@@ -58,6 +66,14 @@ const waitForPromiseAndRun = R.curryN(
58
66
  }
59
67
  );
60
68
 
69
+ /**
70
+ * Reduces a list by applying an async function sequentially.
71
+ * Each step awaits the previous result, then calls `fn(current, previous, index)`.
72
+ * An empty list resolves to `initialValue` without calling `fn`.
73
+ *
74
+ * Curried (Ramda): `reducePromises(fn)(initialValue)(values)` or
75
+ * `reducePromises(fn, initialValue, values)`.
76
+ */
61
77
  export const reducePromises = R.curry(
62
78
  <T extends unknown, S extends unknown>(
63
79
  fn: (current: T, previous: S, index?: number) => Promise<S>,
@@ -71,18 +87,32 @@ export const reducePromises = R.curry(
71
87
  )
72
88
  );
73
89
 
90
+ /**
91
+ * Returns a function that maps a list with `mapperFn`, then splits the result
92
+ * into chunks of size `chunks` (`R.splitEvery`).
93
+ *
94
+ * Curried (Ramda): `mapAndSplit(mapperFn, chunks)(values)`.
95
+ */
74
96
  export const mapAndSplit = R.curry(
75
97
  <T extends unknown, S extends unknown>(
76
- mapperFn: (T) => S,
98
+ mapperFn: (value: T) => S,
77
99
  chunks: number
78
- ): S[][] => R.compose(R.splitEvery(chunks), R.map(mapperFn))
100
+ ): ((values: T[]) => S[][]) =>
101
+ (values: T[]) =>
102
+ R.splitEvery(chunks, R.map(mapperFn, values))
79
103
  );
80
104
 
105
+ /** Returns `true` when `index` is at or past the last position (`length - 1`). */
81
106
  export const isLast = (index: number, length: number): boolean =>
82
107
  index >= length - 1;
83
108
 
109
+ /** Returns `true` when `index` is `0` or negative. */
84
110
  export const isFirst = (index: number): boolean => index <= 0;
85
111
 
112
+ /**
113
+ * Returns `true` when `index` is a valid zero-based index for a list of the
114
+ * given `length`. Returns `false` for empty/negative lengths or negative indexes.
115
+ */
86
116
  export const isIndexInRange = (index: number, length: number): boolean => {
87
117
  if (length <= 0) return false;
88
118
  if (index < 0) return false;
@@ -90,24 +120,29 @@ export const isIndexInRange = (index: number, length: number): boolean => {
90
120
  return index + 1 <= length;
91
121
  };
92
122
 
123
+ /** Builds `[0, 1, ..., size - 1]`. Negative or zero `size` yields `[]`. */
93
124
  export const makeListOfIndexes = (size: number): number[] =>
94
125
  Array.from({ length: size }, (_, index) => index);
95
126
 
127
+ /** Builds an array of the given `size` filled with `value`. */
96
128
  export const makeListOf = <T>(value: T, size: number): T[] => {
97
129
  return Array(size).fill(value);
98
130
  };
99
131
 
100
- /** Checks if a value is a non-empty array */
132
+ /** Checks if a value is a non-empty array. */
101
133
  export function isFilledArray(value: unknown): boolean {
102
134
  return Array.isArray(value) && value.length > 0;
103
135
  }
104
136
 
105
- /** Checks if a value is a empty array */
137
+ /** Checks if a value is an empty array. */
106
138
  export function isEmptyArray(value: unknown): boolean {
107
139
  return Array.isArray(value) && value.length === 0;
108
140
  }
109
141
 
110
- // get random item from the list
142
+ /**
143
+ * Returns a random item from a non-empty array.
144
+ * Throws (in development via `invariant`) if the input is not an array or is empty.
145
+ */
111
146
  export const sample = (xs: unknown[]): unknown => {
112
147
  invariant(Array.isArray(xs), `input value is not an array: ${xs}`);
113
148
  invariant(isFilledArray(xs), `input array is empty: ${xs}`);
@@ -117,7 +152,9 @@ export const sample = (xs: unknown[]): unknown => {
117
152
  return xs[index];
118
153
  };
119
154
 
155
+ /** Returns `true` when `xs` is non-empty and every value is truthy. */
120
156
  export const allTruthy = (xs: boolean[]) =>
121
157
  isFilledArray(xs) && xs.every(Boolean);
122
158
 
159
+ /** Returns `true` when at least one value in `xs` is truthy. */
123
160
  export const anyTruthy = (xs: boolean[]) => xs.some(Boolean);
@@ -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();