@applicaster/zapp-react-native-utils 16.0.0-alpha.2480030155 → 16.0.0-alpha.2500443242

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 (142) hide show
  1. package/actionUtils/index.ts +3 -1
  2. package/actionsExecutor/ActionExecutor.ts +50 -3
  3. package/actionsExecutor/ActionExecutorContext.tsx +99 -17
  4. package/actionsExecutor/__tests__/ActionExecutor.test.ts +71 -0
  5. package/actionsExecutor/__tests__/feedDecorator.test.ts +61 -0
  6. package/actionsExecutor/actions/__tests__/dismissBottomSheet.test.ts +25 -0
  7. package/actionsExecutor/actions/__tests__/goBack.test.ts +62 -0
  8. package/actionsExecutor/actions/__tests__/goHome.test.ts +19 -0
  9. package/actionsExecutor/actions/__tests__/loadItemsFromSource.test.ts +88 -0
  10. package/actionsExecutor/actions/__tests__/navigateToScreen.test.ts +267 -0
  11. package/actionsExecutor/actions/__tests__/openBottomSheet.customContent.test.ts +100 -0
  12. package/actionsExecutor/actions/__tests__/openBottomSheet.inlineItems.test.ts +300 -0
  13. package/actionsExecutor/actions/__tests__/presentScreen.test.ts +127 -0
  14. package/actionsExecutor/actions/__tests__/showAlert.test.ts +49 -0
  15. package/actionsExecutor/actions/__tests__/showToast.test.ts +2 -2
  16. package/actionsExecutor/actions/dismissBottomSheet.ts +23 -0
  17. package/actionsExecutor/actions/goBack.ts +60 -0
  18. package/actionsExecutor/actions/goHome.ts +31 -0
  19. package/actionsExecutor/actions/index.ts +12 -0
  20. package/actionsExecutor/actions/navigateToScreen.ts +43 -45
  21. package/actionsExecutor/actions/openBottomSheet.ts +339 -0
  22. package/actionsExecutor/actions/presentScreen.ts +78 -0
  23. package/actionsExecutor/actions/refreshComponent.ts +6 -0
  24. package/actionsExecutor/actions/sendCloudEvent.ts +6 -1
  25. package/actionsExecutor/actions/showAlert.ts +51 -0
  26. package/actionsExecutor/actions/showToast.ts +2 -2
  27. package/actionsExecutor/consts.ts +27 -0
  28. package/actionsExecutor/feedDecorator.ts +6 -6
  29. package/appUtils/HooksManager/index.ts +9 -0
  30. package/appUtils/playerManager/OverlayObserver/OverlaysObserver.ts +131 -54
  31. package/appUtils/playerManager/OverlayObserver/__tests__/getUpcomingQueue.test.ts +67 -0
  32. package/appUtils/playerManager/OverlayObserver/__tests__/liveContent.test.ts +205 -0
  33. package/appUtils/playerManager/OverlayObserver/__tests__/utils.test.ts +56 -0
  34. package/appUtils/playerManager/OverlayObserver/getUpcomingQueue.android.tv.ts +4 -0
  35. package/appUtils/playerManager/OverlayObserver/getUpcomingQueue.ios.tv.ts +4 -0
  36. package/appUtils/playerManager/OverlayObserver/getUpcomingQueue.ts +24 -0
  37. package/appUtils/playerManager/OverlayObserver/getUpcomingQueue.web.ts +4 -0
  38. package/appUtils/playerManager/OverlayObserver/utils.ts +51 -20
  39. package/appUtils/playerManager/__tests__/playerContent.test.ts +403 -0
  40. package/appUtils/playerManager/__tests__/playerNative.test.ts +114 -0
  41. package/appUtils/playerManager/__tests__/playerNativeCommand.test.ts +62 -0
  42. package/appUtils/playerManager/__tests__/playerToolbox.test.ts +97 -0
  43. package/appUtils/playerManager/__tests__/usePlayerContent.test.tsx +64 -0
  44. package/appUtils/playerManager/__tests__/usePlayerControllerSetup.test.tsx +62 -0
  45. package/appUtils/playerManager/const.ts +13 -0
  46. package/appUtils/playerManager/index.ts +7 -0
  47. package/appUtils/playerManager/player.ts +124 -2
  48. package/appUtils/playerManager/playerNative.ts +27 -3
  49. package/appUtils/playerManager/playerNativeCommand.ts +3 -6
  50. package/appUtils/playerManager/playerToolbox.ts +157 -0
  51. package/appUtils/playerManager/usePlayerContent.tsx +43 -0
  52. package/appUtils/playerManager/usePlayerControllerSetup.tsx +6 -0
  53. package/arrayUtils/__tests__/reorderByIds.test.ts +63 -0
  54. package/arrayUtils/index.ts +62 -0
  55. package/cellUtils/__tests__/getButtonsEnabled.test.ts +28 -0
  56. package/cellUtils/__tests__/getCellNavigationEnabled.test.ts +36 -0
  57. package/cellUtils/__tests__/getIsCellNavigationEnabled.test.ts +35 -0
  58. package/cellUtils/__tests__/isCellNavigationEnabled.test.ts +21 -0
  59. package/cellUtils/index.ts +104 -22
  60. package/configurationUtils/__tests__/manifestKeyParser.test.ts +21 -0
  61. package/configurationUtils/__tests__/modalBlocksParser.test.ts +392 -0
  62. package/configurationUtils/index.ts +77 -73
  63. package/configurationUtils/manifestKeyParser.ts +50 -10
  64. package/configurationUtils/modalBlocksParser.ts +252 -0
  65. package/entryActions/__tests__/buildEntryActions.test.ts +235 -0
  66. package/entryActions/aliasPresentation.ts +108 -0
  67. package/entryActions/buildEntryActions.ts +167 -0
  68. package/entryActions/index.ts +15 -0
  69. package/entryActions/types.ts +39 -0
  70. package/focusManager/FocusManager.ts +26 -0
  71. package/focusManager/__tests__/FocusManager.test.ts +9 -0
  72. package/localizationUtils/index.ts +12 -6
  73. package/logger/__tests__/xrayToolbox.test.ts +69 -0
  74. package/logger/xrayToolbox.ts +67 -0
  75. package/manifestUtils/__tests__/player.audioControls.test.js +158 -0
  76. package/manifestUtils/_internals/index.js +8 -3
  77. package/manifestUtils/defaultManifestConfigurations/generalContent.js +6 -0
  78. package/manifestUtils/defaultManifestConfigurations/player.js +338 -1
  79. package/manifestUtils/index.js +3 -0
  80. package/manifestUtils/keys.js +6 -1
  81. package/manifestUtils/mobileAction/container/__tests__/mobileActionButtonsContainer.test.js +21 -0
  82. package/manifestUtils/mobileAction/groups/__tests__/buildMobileActionButtonGroups.test.js +1 -1
  83. package/manifestUtils/mobileAction/groups/defaults.js +2 -1
  84. package/manifestUtils/modalBlocks.js +304 -0
  85. package/modalState/ContentViewModel.ts +113 -0
  86. package/modalState/EditableCollection.ts +17 -0
  87. package/modalState/EditableCollectionRegistry.ts +51 -0
  88. package/modalState/ModalOrchestrator.ts +212 -0
  89. package/modalState/RemoteEditableCollection.ts +235 -0
  90. package/modalState/__tests__/ContentViewModel.editable.test.ts +69 -0
  91. package/modalState/__tests__/ContentViewModel.test.ts +165 -0
  92. package/modalState/__tests__/EditableCollectionRegistry.test.ts +112 -0
  93. package/modalState/__tests__/ModalOrchestrator.phase3.test.ts +63 -0
  94. package/modalState/__tests__/RemoteEditableCollection.test.ts +415 -0
  95. package/modalState/__tests__/index.test.ts +30 -1
  96. package/modalState/__tests__/useBottomSheetContent.test.ts +349 -0
  97. package/modalState/__tests__/useModalStoreState.test.ts +142 -0
  98. package/modalState/index.ts +35 -83
  99. package/modalState/store.ts +109 -0
  100. package/modalState/types.ts +162 -0
  101. package/modalState/useBottomSheetContent.ts +109 -0
  102. package/navigationUtils/xrayNavigator.ts +12 -0
  103. package/package.json +2 -2
  104. package/perfTracker.ts +206 -0
  105. package/playerUtils/__tests__/contentDataKeys.test.ts +297 -0
  106. package/playerUtils/__tests__/resolvePlayerActions.test.ts +138 -0
  107. package/playerUtils/__tests__/resolvePlayerTitleSubtitle.test.ts +180 -0
  108. package/playerUtils/contentDataKeys.ts +134 -0
  109. package/playerUtils/index.ts +37 -16
  110. package/playerUtils/isAudioItem.ts +26 -0
  111. package/playerUtils/resolvePlayerActions.ts +71 -0
  112. package/playerUtils/resolvePlayerTitleSubtitle.ts +76 -0
  113. package/pluginUtils/__tests__/pluginUtils.test.js +32 -0
  114. package/pluginUtils/index.ts +29 -0
  115. package/reactHooks/__tests__/getPluginConfiguration.test.ts +82 -0
  116. package/reactHooks/actions/index.ts +67 -2
  117. package/reactHooks/cell-click/__tests__/index.test.js +64 -0
  118. package/reactHooks/cell-click/index.ts +21 -14
  119. package/reactHooks/connection/index.tsx +8 -5
  120. package/reactHooks/feed/__tests__/useMarkPipesDataStale.test.tsx +243 -0
  121. package/reactHooks/feed/useMarkPipesDataStale.ts +68 -23
  122. package/reactHooks/index.ts +2 -0
  123. package/reactHooks/navigation/__tests__/index.test.tsx +176 -1
  124. package/reactHooks/navigation/__tests__/usePresentScreen.test.ts +154 -0
  125. package/reactHooks/navigation/index.ts +2 -0
  126. package/reactHooks/navigation/usePresentScreen.ts +157 -0
  127. package/reactHooks/navigation/useRoute.ts +22 -5
  128. package/reactHooks/usePluginConfiguration.ts +88 -47
  129. package/reactHooks/utils/__tests__/index.test.js +22 -2
  130. package/reactHooks/utils/index.ts +11 -1
  131. package/riverComponetsMeasurementProvider/index.tsx +8 -1
  132. package/uiActionsRegistrator/__tests__/resolveActionIdentifiers.test.ts +93 -0
  133. package/uiActionsRegistrator/__tests__/subscribe.test.ts +133 -0
  134. package/uiActionsRegistrator/__tests__/usableActionItems.test.ts +52 -0
  135. package/uiActionsRegistrator/index.ts +25 -203
  136. package/uiActionsRegistrator/registry.ts +351 -0
  137. package/uiActionsRegistrator/resolveActionIdentifiers.ts +100 -0
  138. package/uiActionsRegistrator/usableActionItems.ts +66 -0
  139. package/appUtils/playerManager/usePlayerTitleSummaryOverlay.tsx +0 -56
  140. package/playerUtils/__tests__/getPlayerActionButtons.test.ts +0 -54
  141. package/playerUtils/getPlayerActionButtons.ts +0 -17
  142. /package/reactHooks/actions/__tests__/{index.test.js → index.test.tsx} +0 -0
@@ -0,0 +1,109 @@
1
+ import { createStore, useStore } from "zustand";
2
+
3
+ export interface ModalState {
4
+ visible: boolean;
5
+ screen: any;
6
+ options: Record<string, unknown>;
7
+ props: Record<string, unknown>;
8
+ }
9
+
10
+ export interface ModalStore {
11
+ modalState: ModalState;
12
+ setModalState: (newState: Partial<ModalState>) => void;
13
+ openModal: (
14
+ item: any,
15
+ options?: Record<string, unknown>,
16
+ props?: Record<string, unknown>
17
+ ) => void;
18
+ dismissModal: () => void;
19
+ }
20
+
21
+ const initialModalState: ModalState = {
22
+ visible: false,
23
+ screen: null,
24
+ options: {},
25
+ props: {},
26
+ };
27
+
28
+ export const modalStore = createStore<ModalStore>((set, get) => ({
29
+ modalState: initialModalState,
30
+ setModalState: (newState) =>
31
+ set((state) => ({
32
+ modalState: { ...state.modalState, ...newState },
33
+ })),
34
+ openModal: ({ item, options = {}, props }: OpenModalArg) => {
35
+ const resetStore = () => set({ modalState: initialModalState });
36
+ const { onDismiss, onRequestClose, ...restOptions } = options as any;
37
+
38
+ set({
39
+ modalState: {
40
+ visible: true,
41
+ screen: item,
42
+ options: {
43
+ animated: true,
44
+ animationType: "slide",
45
+ onShow: () => {},
46
+ presentationStyle: "overFullScreen",
47
+ transparent: true,
48
+ ...restOptions,
49
+ // Compose caller-provided callbacks with the store reset so both run
50
+ onDismiss: () => {
51
+ resetStore();
52
+ onDismiss?.();
53
+ },
54
+ onRequestClose: () => {
55
+ resetStore();
56
+ onRequestClose?.();
57
+ },
58
+ },
59
+ props,
60
+ },
61
+ });
62
+ },
63
+ dismissModal: () => {
64
+ const onDismiss = (get().modalState?.options as any)?.onDismiss;
65
+
66
+ if (typeof onDismiss === "function") {
67
+ onDismiss();
68
+ } else {
69
+ set({ modalState: initialModalState });
70
+ }
71
+ },
72
+ }));
73
+
74
+ export const useModalStore = <T>(selector: (state: ModalStore) => T) =>
75
+ useStore(modalStore, selector);
76
+
77
+ export const openModal = modalStore.getInitialState().openModal;
78
+
79
+ export const dismissModal = modalStore.getInitialState().dismissModal;
80
+
81
+ export const openBottomSheetModal = ({
82
+ ModalBottomSheetContent,
83
+ modalBottomSheetContentProps,
84
+ props = {},
85
+ options = {},
86
+ }: OpenModalBottomSheetArgs) => {
87
+ openModal({
88
+ item: {
89
+ ModalBottomSheetContent,
90
+ modalBottomSheetContentProps,
91
+ },
92
+ props,
93
+ options: {
94
+ animationType: "none",
95
+ animated: false,
96
+ ...options,
97
+ },
98
+ });
99
+ };
100
+
101
+ /**
102
+ * Pass `skipSubscription` from callers that render outside of a modal: the
103
+ * selector then returns the stable `initialModalState` reference, so the
104
+ * component is never re-rendered by modal state it does not read.
105
+ */
106
+ export const useModalStoreState = (skipSubscription = false): ModalState =>
107
+ useModalStore<ModalState>((state) =>
108
+ skipSubscription ? initialModalState : state.modalState
109
+ );
@@ -0,0 +1,162 @@
1
+ export interface Header {
2
+ title: string;
3
+ subtitle?: string;
4
+ icon?: string;
5
+ }
6
+
7
+ export interface Action {
8
+ type: string;
9
+ payload?: any;
10
+ options?: any;
11
+ }
12
+
13
+ // Represented as 3 dots icon on top menu (opens new second level menu on desktop
14
+ // or a new bottom sheet on mobile)
15
+ export interface PresentSubMenuAction extends Action {
16
+ menu: Menu;
17
+ }
18
+
19
+ export interface SecondaryAction {
20
+ action: Action | PresentSubMenuAction;
21
+ icon?: string;
22
+ }
23
+
24
+ /**
25
+ * A group of actions attached to an entry, keyed by a button alias
26
+ * (e.g. "remove_item", "reorder_item"). Injected by the feed decorator and
27
+ * dispatched by the remote EditableCollection when an operation runs.
28
+ */
29
+ export interface EntryActionGroup {
30
+ button?: { alias?: string };
31
+ actions?: Action[];
32
+ }
33
+
34
+ export interface MenuItem {
35
+ id: string;
36
+ title: string;
37
+ summary?: string;
38
+ icon?: string;
39
+ isSelected?: boolean;
40
+ actions?: (Action | PresentSubMenuAction)[];
41
+ /** @deprecated Use `actions` array instead. Maintained for backwards compatibility. */
42
+ action?: Action | PresentSubMenuAction;
43
+ secondaryAction?: SecondaryAction;
44
+ trailingButton?: any;
45
+ entryActions?: EntryActionGroup[];
46
+ }
47
+
48
+ export type SelectMode = "single" | "multi" | "none";
49
+
50
+ export interface SelectionBehavior {
51
+ selectMode?: SelectMode;
52
+ currentSelection?: string[];
53
+ selector?: string;
54
+ }
55
+
56
+ /**
57
+ * Operations that act on a specific item in the collection.
58
+ * Their action payloads are looked up on the item's entryActions (e.g. "remove_item", "reorder_item").
59
+ */
60
+ export type ItemScopedOperation = "remove" | "reorder";
61
+
62
+ /**
63
+ * Operations that act on the collection as a whole.
64
+ * Their action payloads are looked up on dynamicCollection.events (e.g. events.add, events.clearAll, events.delete).
65
+ */
66
+ export type CollectionScopedOperation = "add" | "clearAll" | "delete";
67
+
68
+ /**
69
+ * UI display or behavior flags that do not require action payloads.
70
+ */
71
+ export type UIOperation = "nowPlaying";
72
+
73
+ export const OPERATIONS = {
74
+ REMOVE: "remove",
75
+ REORDER: "reorder",
76
+ ADD: "add",
77
+ CLEAR_ALL: "clearAll",
78
+ DELETE: "delete",
79
+ NOW_PLAYING: "nowPlaying",
80
+ } as const;
81
+
82
+ export function hasOperation(
83
+ operations: string[] | undefined,
84
+ target: string
85
+ ): boolean {
86
+ if (!Array.isArray(operations)) return false;
87
+
88
+ const targetLower = target.toLowerCase();
89
+
90
+ return operations.some(
91
+ (op) => typeof op === "string" && op.toLowerCase() === targetLower
92
+ );
93
+ }
94
+
95
+ export type Operation =
96
+ | ItemScopedOperation
97
+ | CollectionScopedOperation
98
+ | UIOperation;
99
+
100
+ export interface DynamicCollectionOptions {
101
+ operations: Operation[];
102
+ postUrl?: string;
103
+ provider?: string;
104
+ /**
105
+ * Action handlers for CollectionScopedOperations (e.g. "add", "clearAll", "delete").
106
+ */
107
+ events?: Record<CollectionScopedOperation | string, Action[]>;
108
+ }
109
+
110
+ export interface Content {
111
+ title: string;
112
+ stickyTitle?: boolean;
113
+ items: MenuItem[];
114
+ itemsUrl?: string;
115
+ action?: Action;
116
+ role?: string;
117
+ behavior?: SelectionBehavior;
118
+ dynamicCollection?: DynamicCollectionOptions;
119
+ themePluginId?: string;
120
+ styleOverrides?: Record<string, any>;
121
+ /** Shown under Next Up when the queue sheet has no upcoming items. */
122
+ emptyMessage?: string;
123
+ context?: Record<string, any>;
124
+ }
125
+
126
+ export interface Menu {
127
+ header?: Header;
128
+ content: Content;
129
+ closeButton?: boolean;
130
+ }
131
+
132
+ export function isPresentSubMenuAction(
133
+ action: any
134
+ ): action is PresentSubMenuAction {
135
+ return !!action && typeof action === "object" && "menu" in action;
136
+ }
137
+
138
+ /**
139
+ * Normalizes an item's action/actions into an array of Action items.
140
+ * Supports canonical `actions: Action[]` and backwards-compatible `action: Action | Action[]`.
141
+ */
142
+ export function getMenuItemActions(
143
+ item?: Partial<MenuItem> | null
144
+ ): (Action | PresentSubMenuAction)[] {
145
+ if (!item) {
146
+ return [];
147
+ }
148
+
149
+ if (Array.isArray(item.actions) && item.actions.length > 0) {
150
+ return item.actions;
151
+ }
152
+
153
+ if (Array.isArray((item as any).action)) {
154
+ return (item as any).action;
155
+ }
156
+
157
+ if (item.action) {
158
+ return [item.action];
159
+ }
160
+
161
+ return [];
162
+ }
@@ -0,0 +1,109 @@
1
+ import React, { useCallback, useEffect, useState } from "react";
2
+ import { toBooleanWithDefaultFalse } from "@applicaster/zapp-react-native-utils/booleanUtils";
3
+
4
+ import { MenuItem, modalOrchestrator } from "./ModalOrchestrator";
5
+
6
+ import { ContentViewModel } from "./ContentViewModel";
7
+ import {
8
+ DynamicCollectionOptions,
9
+ getMenuItemActions,
10
+ isPresentSubMenuAction,
11
+ SelectionBehavior,
12
+ } from "./types";
13
+ import type { EditableCollection } from "./EditableCollection";
14
+
15
+ type Props = {
16
+ viewModel?: ContentViewModel | null;
17
+ onPress: (item: MenuItem) => void | Promise<void>;
18
+ };
19
+
20
+ type Return = {
21
+ items: MenuItem[];
22
+ isLoading: boolean;
23
+ error?: Error | string;
24
+ showCentralLoading: boolean;
25
+ canGoBack: boolean;
26
+ handleItemPress: (item: MenuItem) => Promise<void>;
27
+ goBackOrClose: () => void;
28
+ close: () => void;
29
+ role?: string;
30
+ behavior?: SelectionBehavior;
31
+ dynamicCollection?: DynamicCollectionOptions;
32
+ editableCollection: EditableCollection | null;
33
+ themePluginId?: string;
34
+ };
35
+
36
+ export const useBottomSheetContent = (props: Props): Return => {
37
+ const { onPress, viewModel } = props;
38
+
39
+ const [state, setState] = useState(viewModel?.getState());
40
+
41
+ const [editableItems, setEditableItems] = useState<MenuItem[]>(
42
+ () => viewModel?.getState().items || []
43
+ );
44
+
45
+ // Subscribe to the viewModel state changes
46
+ useEffect(() => {
47
+ return viewModel?.subscribe((nextState) => {
48
+ setState((state) => {
49
+ return state === nextState ? state : nextState;
50
+ });
51
+ });
52
+ }, [viewModel]);
53
+
54
+ // Subscribe to editable collection items
55
+ useEffect(() => {
56
+ if (viewModel?.editableCollection) {
57
+ const subscription =
58
+ viewModel.editableCollection.items$.subscribe(setEditableItems);
59
+
60
+ return () => subscription.unsubscribe();
61
+ }
62
+ }, [viewModel?.editableCollection]);
63
+
64
+ /**
65
+ * Handles an item press:
66
+ * - Delegates to the parent onPress (which runs the action and awaits it).
67
+ * - If the item was a leaf action (not a submenu), triggers viewModel.refetch()
68
+ * so that checkmarks (isSelected) reflect the updated server state.
69
+ */
70
+ const handleItemPress = useCallback(
71
+ async (item: MenuItem) => {
72
+ const actions = getMenuItemActions(item);
73
+ const isSubMenu = actions.some(isPresentSubMenuAction);
74
+
75
+ await onPress(item);
76
+
77
+ if (!isSubMenu) {
78
+ await viewModel?.refetch();
79
+ }
80
+ },
81
+ [onPress, viewModel]
82
+ );
83
+
84
+ const goBackOrClose = React.useCallback(() => {
85
+ if (modalOrchestrator.canGoBack) {
86
+ modalOrchestrator.back();
87
+ } else {
88
+ modalOrchestrator.close();
89
+ }
90
+ }, []);
91
+
92
+ return {
93
+ items: viewModel?.editableCollection ? editableItems : state?.items,
94
+ isLoading: toBooleanWithDefaultFalse(state?.isLoading),
95
+ error: state?.error,
96
+ showCentralLoading: toBooleanWithDefaultFalse(
97
+ state?.isLoading && state?.items.length === 0
98
+ ),
99
+ canGoBack: modalOrchestrator.canGoBack,
100
+ handleItemPress,
101
+ goBackOrClose,
102
+ close: useCallback(() => modalOrchestrator.close(), []),
103
+ role: state?.role,
104
+ behavior: state?.behavior,
105
+ dynamicCollection: state?.dynamicCollection,
106
+ editableCollection: viewModel?.editableCollection || null,
107
+ themePluginId: state?.themePluginId,
108
+ };
109
+ };
@@ -0,0 +1,12 @@
1
+ /**
2
+ * The app navigator for the X-Ray toolboxes (nav, screen), which run outside React. The
3
+ * NavigationProvider sets it after each commit; it is a plain module variable, so updating it
4
+ * never renders anything.
5
+ */
6
+ let navigator: QuickBrickAppNavigator | undefined;
7
+
8
+ export const setXrayNavigator = (value: QuickBrickAppNavigator | undefined) => {
9
+ navigator = value;
10
+ };
11
+
12
+ export const getXrayNavigator = () => navigator;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@applicaster/zapp-react-native-utils",
3
- "version": "16.0.0-alpha.2480030155",
3
+ "version": "16.0.0-alpha.2500443242",
4
4
  "description": "Applicaster Zapp React Native utilities package",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
@@ -27,7 +27,7 @@
27
27
  },
28
28
  "homepage": "https://github.com/applicaster/quickbrick#readme",
29
29
  "dependencies": {
30
- "@applicaster/applicaster-types": "16.0.0-alpha.2480030155",
30
+ "@applicaster/applicaster-types": "16.0.0-alpha.2500443242",
31
31
  "buffer": "^5.2.1",
32
32
  "camelize": "^1.0.0",
33
33
  "dayjs": "^1.11.10",
package/perfTracker.ts ADDED
@@ -0,0 +1,206 @@
1
+ import { createLogger } from "./logger";
2
+ import { NativeModules } from "react-native";
3
+
4
+ const { ProfilerBridge } = NativeModules;
5
+
6
+ const loggerObj = createLogger({
7
+ category: "PerfTracker",
8
+ subsystem: "PerfTelemetry",
9
+ });
10
+
11
+ const renderCounts: Record<string, number> = {};
12
+ const cellRenderCounts: Record<string, number> = {};
13
+
14
+ const timingStats: Record<
15
+ string,
16
+ { totalMs: number; count: number; maxMs: number; minMs: number }
17
+ > = {};
18
+
19
+ const t0 = Date.now();
20
+
21
+ /** True only where the native profiler is registered; lets always-on logs skip the perf lines without it. */
22
+ export const isProfilerAvailable = (): boolean => Boolean(ProfilerBridge);
23
+
24
+ export function getDelta(): number {
25
+ return Date.now() - t0;
26
+ }
27
+
28
+ export function recordTiming(
29
+ name: string,
30
+ durationMs: number,
31
+ details?: Record<string, any>
32
+ ): void {
33
+ const rounded = Math.round(durationMs * 100) / 100;
34
+
35
+ if (!timingStats[name]) {
36
+ timingStats[name] = {
37
+ totalMs: rounded,
38
+ count: 1,
39
+ maxMs: rounded,
40
+ minMs: rounded,
41
+ };
42
+ } else {
43
+ const s = timingStats[name];
44
+ s.totalMs = Math.round((s.totalMs + rounded) * 100) / 100;
45
+ s.count += 1;
46
+ if (rounded > s.maxMs) s.maxMs = rounded;
47
+ if (rounded < s.minMs) s.minMs = rounded;
48
+ }
49
+
50
+ const stat = timingStats[name];
51
+ const avg = Math.round((stat.totalMs / stat.count) * 100) / 100;
52
+ const delta = getDelta();
53
+
54
+ if (ProfilerBridge?.updateTimer) {
55
+ try {
56
+ ProfilerBridge.updateTimer("timings", name, rounded);
57
+ } catch (e) {}
58
+ }
59
+
60
+ if (stat.count <= 3 || rounded >= 3 || stat.count % 10 === 0) {
61
+ const msg = `[PERF TIMING #${stat.count}] ${name}: ${rounded}ms (avg: ${avg}ms, max: ${stat.maxMs}ms, total: ${stat.totalMs}ms) (+${delta}ms)`;
62
+
63
+ loggerObj.log_info(msg, {
64
+ timingName: name,
65
+ durationMs: rounded,
66
+ avgMs: avg,
67
+ maxMs: stat.maxMs,
68
+ minMs: stat.minMs,
69
+ totalMs: stat.totalMs,
70
+ count: stat.count,
71
+ deltaMs: delta,
72
+ ...(details || {}),
73
+ });
74
+ }
75
+ }
76
+
77
+ export function measureSync<T>(
78
+ name: string,
79
+ fn: () => T,
80
+ details?: Record<string, any>
81
+ ): T {
82
+ const start =
83
+ typeof performance !== "undefined" && performance.now
84
+ ? performance.now()
85
+ : Date.now();
86
+
87
+ try {
88
+ return fn();
89
+ } finally {
90
+ const end =
91
+ typeof performance !== "undefined" && performance.now
92
+ ? performance.now()
93
+ : Date.now();
94
+
95
+ recordTiming(name, end - start, details);
96
+ }
97
+ }
98
+
99
+ export function startTimer(
100
+ name: string,
101
+ details?: Record<string, any>
102
+ ): (additionalDetails?: Record<string, any>) => number {
103
+ const start =
104
+ typeof performance !== "undefined" && performance.now
105
+ ? performance.now()
106
+ : Date.now();
107
+
108
+ return (additionalDetails?: Record<string, any>) => {
109
+ const end =
110
+ typeof performance !== "undefined" && performance.now
111
+ ? performance.now()
112
+ : Date.now();
113
+
114
+ const duration = end - start;
115
+
116
+ recordTiming(name, duration, {
117
+ ...(details || {}),
118
+ ...(additionalDetails || {}),
119
+ });
120
+
121
+ return duration;
122
+ };
123
+ }
124
+
125
+ export function countRender(
126
+ componentName: string,
127
+ details?: Record<string, any>
128
+ ): number {
129
+ renderCounts[componentName] = (renderCounts[componentName] || 0) + 1;
130
+ const count = renderCounts[componentName];
131
+ const delta = getDelta();
132
+
133
+ if (ProfilerBridge?.updateCounter) {
134
+ try {
135
+ ProfilerBridge.updateCounter("render_count", componentName, count);
136
+ } catch (e) {}
137
+ }
138
+
139
+ const msg = `[PERF RENDER #${count}] ${componentName} (+${delta}ms)`;
140
+
141
+ loggerObj.log_info(msg, {
142
+ component: componentName,
143
+ count,
144
+ deltaMs: delta,
145
+ ...(details || {}),
146
+ });
147
+
148
+ return count;
149
+ }
150
+
151
+ export function countCellRender(
152
+ cellType: string,
153
+ itemId: string | number,
154
+ details?: Record<string, any>
155
+ ): number {
156
+ const key = `${cellType}:${itemId || "unknown"}`;
157
+ cellRenderCounts[key] = (cellRenderCounts[key] || 0) + 1;
158
+ const count = cellRenderCounts[key];
159
+
160
+ renderCounts[cellType] = (renderCounts[cellType] || 0) + 1;
161
+ const totalForType = renderCounts[cellType];
162
+ const delta = getDelta();
163
+
164
+ if (ProfilerBridge?.updateCounter) {
165
+ try {
166
+ ProfilerBridge.updateCounter("cell_render_count", cellType, totalForType);
167
+ } catch (e) {}
168
+ }
169
+
170
+ if (count > 1 || totalForType <= 12 || totalForType % 10 === 0) {
171
+ const msg = `[PERF CELL ${
172
+ count > 1 ? "RE-RENDER" : "RENDER"
173
+ } #${count}] ${cellType} item:${itemId} (total ${cellType}: #${totalForType}) (+${delta}ms)`;
174
+
175
+ loggerObj.log_info(msg, {
176
+ cellType,
177
+ itemId,
178
+ itemRenderCount: count,
179
+ totalForCellType: totalForType,
180
+ deltaMs: delta,
181
+ ...(details || {}),
182
+ });
183
+ }
184
+
185
+ return count;
186
+ }
187
+
188
+ export function dumpSummary(checkpoint: string): void {
189
+ const delta = getDelta();
190
+ let totalRenders = 0;
191
+
192
+ for (const k in renderCounts) {
193
+ totalRenders += renderCounts[k];
194
+ }
195
+
196
+ const summaryMsg = `=== [PERF SUMMARY at ${checkpoint}] total renders: ${totalRenders} (+${delta}ms) ===`;
197
+
198
+ loggerObj.log_info(summaryMsg, {
199
+ checkpoint,
200
+ elapsedMs: delta,
201
+ totalRenders,
202
+ renderCounts,
203
+ cellRenderCounts,
204
+ timingStats,
205
+ });
206
+ }