@applicaster/zapp-react-native-utils 16.0.0-rc.70 → 16.0.0-rc.72

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.
@@ -0,0 +1,245 @@
1
+ /* eslint-disable no-dupe-class-members */
2
+ import { Observable } from "rxjs";
3
+ import { createLogger } from "../logger";
4
+
5
+ const { log_debug, log_warning } = createLogger({
6
+ subsystem: "UIActionsRegistry",
7
+ category: "ActionRegistration",
8
+ });
9
+
10
+ /**
11
+ * The runtime value of a UI action.
12
+ *
13
+ * This is the object that consumers interact with (render buttons for,
14
+ * invoke on press, read initial state from, etc.). It intentionally keeps an
15
+ * open shape (`[K: string]: any`) so that both the modern registry-based
16
+ * actions and the legacy context-provider based actions can be represented by
17
+ * the same structure.
18
+ */
19
+ export type RegisteredActionValue = {
20
+ state?: any;
21
+ getInitialState?: () => Promise<void>;
22
+ initialEntryState?: (item: ZappEntry | ZappFeed) => CellActionEntryState;
23
+ invokeAction: (
24
+ item: ZappEntry | ZappFeed,
25
+ options?: InvokeArgsOptions
26
+ ) => void;
27
+ isActionAvailable?: (item: ZappEntry | ZappFeed) => boolean;
28
+ addListener?: (
29
+ entryId: string,
30
+ listener: CellActionStateListenerFunction
31
+ ) => CellActionStateRemoveListenerFunction;
32
+ /**
33
+ * Optional RX stream of the action state for a given entry. When not
34
+ * provided, `observeEntryState` derives one from `initialEntryState` +
35
+ * `addListener` (see below).
36
+ */
37
+ observeEntryState?: (
38
+ entry: ZappEntry | ZappFeed
39
+ ) => Observable<CellActionEntryState>;
40
+ [K: string]: any;
41
+ };
42
+
43
+ /**
44
+ * Where an action came from.
45
+ *
46
+ * `"entry"` marks actions inflated from `entry.extensions.entry_action`, which
47
+ * exist only for the entry being shown. Consumers that rank actions - the
48
+ * player picks a non-entry action as the overflow companion when it can - read
49
+ * this instead of pattern-matching the identifier.
50
+ */
51
+ export type RegisteredActionSource = "entry";
52
+
53
+ export type RegisteredAction = {
54
+ identifier: string; // Plugin identifier or synthetic name
55
+ action: RegisteredActionValue;
56
+ source?: RegisteredActionSource;
57
+ };
58
+
59
+ /**
60
+ * A function that, given an optional context (currently just the `entry`),
61
+ * returns the list of actions it wants to contribute.
62
+ *
63
+ * Returning an array is what allows a single provider (plugin or otherwise) to
64
+ * expose more than one action, and to compute those actions based on the entry.
65
+ */
66
+ export type UIActionProvider = (params: {
67
+ entry?: ZappEntry | ZappFeed;
68
+ }) => RegisteredAction[];
69
+
70
+ /**
71
+ * Returns an RX `Observable` that emits the action state for `entry`.
72
+ *
73
+ * If the action already exposes its own `observeEntryState`, it is used as-is.
74
+ * Otherwise we build the stream from the legacy imperative API:
75
+ * - it immediately emits `initialEntryState(entry)` (if available), and
76
+ * - it subscribes to further changes via `addListener(entryId, listener)`,
77
+ * unsubscribing automatically when the observable is torn down.
78
+ *
79
+ * This lets every action - old or new - be consumed reactively through a single
80
+ * mechanism, without each consumer having to wire up `addListener` manually.
81
+ */
82
+ export function observeEntryState(
83
+ action: RegisteredActionValue | undefined,
84
+ entry: ZappEntry | ZappFeed
85
+ ): Observable<CellActionEntryState> {
86
+ if (typeof action?.observeEntryState === "function") {
87
+ return action.observeEntryState(entry);
88
+ }
89
+
90
+ return new Observable<CellActionEntryState>((subscriber) => {
91
+ const initialState = action?.initialEntryState?.(entry);
92
+
93
+ if (initialState !== undefined) {
94
+ subscriber.next(initialState);
95
+ }
96
+
97
+ const removeListener = action?.addListener?.(
98
+ String((entry as ZappEntry)?.id),
99
+ (state: CellActionEntryState) => subscriber.next(state)
100
+ );
101
+
102
+ return () => removeListener?.();
103
+ });
104
+ }
105
+
106
+ /** Called whenever a provider is added to or removed from the registry. */
107
+ export type RegistryChangeListener = () => void;
108
+
109
+ /**
110
+ * Whether an action wants to be shown for this entry.
111
+ *
112
+ * Plugins express this through one of three historical names; the first one
113
+ * they define answers, and an action that defines none is always shown. It
114
+ * lives here so that every surface - the player overlay, the bottom sheet, a
115
+ * cell - gives the same answer for the same action. Two surfaces disagreeing
116
+ * means an action the user can reach from one place and not another.
117
+ */
118
+ export function isActionAvailableFor(
119
+ action: RegisteredActionValue | undefined,
120
+ entry: ZappEntry | ZappFeed
121
+ ): boolean {
122
+ const predicate =
123
+ action?.isSupportDownloads ??
124
+ action?.isActionSupported ??
125
+ action?.isActionAvailable;
126
+
127
+ return typeof predicate === "function" ? Boolean(predicate(entry)) : true;
128
+ }
129
+
130
+ class UIActionsRegistry {
131
+ private registeredActions: Record<string, UIActionProvider> = {};
132
+
133
+ private changeListeners: RegistryChangeListener[] = [];
134
+
135
+ /**
136
+ * Subscribes to provider registrations and unregistrations.
137
+ *
138
+ * Providers can appear after the UI that wants them has already rendered -
139
+ * the audio player registers playback speed only once its controller has
140
+ * state - so consumers need to be told rather than poll for it.
141
+ *
142
+ * Returns an unsubscribe function.
143
+ */
144
+ subscribe(listener: RegistryChangeListener): () => void {
145
+ this.changeListeners.push(listener);
146
+
147
+ return () => {
148
+ this.changeListeners = this.changeListeners.filter(
149
+ (registered) => registered !== listener
150
+ );
151
+ };
152
+ }
153
+
154
+ private notifyChanged(): void {
155
+ // Copied so a listener that unsubscribes itself does not disturb this pass.
156
+ this.changeListeners.slice().forEach((listener) => listener());
157
+ }
158
+
159
+ /**
160
+ * Register a dynamic action provider under a unique `name`.
161
+ * The provider can return one or more actions and may use the passed `entry`.
162
+ * Returns an unregister function.
163
+ */
164
+ registerActionProvider(
165
+ name: string,
166
+ actionProvider: UIActionProvider
167
+ ): () => void {
168
+ const isOverride = Boolean(this.registeredActions[name]);
169
+
170
+ if (isOverride) {
171
+ log_warning(
172
+ `registerActionProvider: overriding existing provider for "${name}"`,
173
+ { name }
174
+ );
175
+ } else {
176
+ log_debug(`registerActionProvider: registered "${name}"`, { name });
177
+ }
178
+
179
+ this.registeredActions[name] = actionProvider;
180
+ this.notifyChanged();
181
+
182
+ return () => {
183
+ // Only remove if it's still the same provider to avoid races where a
184
+ // newer registration replaced this one.
185
+ if (this.registeredActions[name] === actionProvider) {
186
+ delete this.registeredActions[name];
187
+ log_debug(`registerActionProvider: unregistered "${name}"`, { name });
188
+ this.notifyChanged();
189
+ } else {
190
+ log_debug(
191
+ `registerActionProvider: skipped unregister for "${name}" – newer provider is active`,
192
+ { name }
193
+ );
194
+ }
195
+ };
196
+ }
197
+
198
+ /**
199
+ * Convenience helper to register a single, static action from anywhere in the
200
+ * app (it does not need to be a plugin). Returns an unregister function.
201
+ */
202
+ registerAction(
203
+ identifier: string,
204
+ action: RegisteredActionValue
205
+ ): () => void {
206
+ return this.registerActionProvider(identifier, () => [
207
+ { identifier, action },
208
+ ]);
209
+ }
210
+
211
+ getActions(name: string, entry?: ZappEntry | ZappFeed): RegisteredAction[] {
212
+ if (!this.registeredActions[name]) {
213
+ // Not necessarily a misconfiguration: consumers legitimately probe for
214
+ // providers that register late - the audio player asks for its own
215
+ // playback-speed action before the controller has state. Only the layer
216
+ // that knows the identifier was *configured* can call this a fault, so
217
+ // `resolveActionIdentifiers` is where that warning lives.
218
+ log_debug(`getActions: no provider registered for "${name}"`, { name });
219
+
220
+ return [];
221
+ }
222
+
223
+ // Resolution runs on every render of every surface that shows actions, so
224
+ // there is deliberately no log of the resolved list here.
225
+ return this.registeredActions[name]({ entry }) ?? [];
226
+ }
227
+
228
+ /**
229
+ * Returns the runtime value of the first action registered under `name`, or
230
+ * `undefined`. This mirrors the shape returned by the legacy `useActions`
231
+ * hook, easing migration of single-action consumers.
232
+ */
233
+ getAction(
234
+ name: string,
235
+ entry?: ZappEntry | ZappFeed
236
+ ): RegisteredActionValue | undefined {
237
+ return this.getActions(name, entry)[0]?.action;
238
+ }
239
+
240
+ hasAction(name: string): boolean {
241
+ return Boolean(this.registeredActions[name]);
242
+ }
243
+ }
244
+
245
+ export const uiActionsRegistry = new UIActionsRegistry();
@@ -0,0 +1,100 @@
1
+ import { createLogger } from "../logger";
2
+
3
+ import { RegisteredAction, uiActionsRegistry } from "./registry";
4
+
5
+ const { log_warning } = createLogger({
6
+ subsystem: "UIActionsRegistry",
7
+ category: "ActionRegistration",
8
+ });
9
+
10
+ /** Identifier that stands for "whatever this entry declares", not a provider. */
11
+ export const ENTRY_ACTIONS_IDENTIFIER = "entry_actions";
12
+
13
+ export type ResolveActionIdentifiersParams = {
14
+ identifiers: string | string[];
15
+ entry: ZappEntry | ZappFeed;
16
+ /**
17
+ * Expands the `entry_actions` token.
18
+ *
19
+ * The registry maps an identifier to a provider, which is the right shape for
20
+ * a plugin: one installation, one implementation, looked up by id. Entry
21
+ * actions are not that - they are data on the entry being shown, and their
22
+ * execution context belongs to whoever is showing it. So the caller expands
23
+ * them, rather than the registry holding one global provider whose context
24
+ * was captured wherever it happened to be registered.
25
+ */
26
+ expandEntryActions?: (entry: ZappEntry | ZappFeed) => RegisteredAction[];
27
+ };
28
+
29
+ /**
30
+ * Identifiers already reported as having no provider.
31
+ *
32
+ * Resolution runs on every render of every surface that shows actions, so one
33
+ * uninstalled plugin would otherwise repeat its warning forever. An identifier
34
+ * is forgotten again as soon as it does resolve, so a provider that appears
35
+ * late and later disappears is still reported.
36
+ */
37
+ const reportedMissingProviders = new Set<string>();
38
+
39
+ export function parseActionIdentifiers(
40
+ config?: string | string[] | null
41
+ ): string[] {
42
+ // Deliberately not using the `utils` barrel: this module sits underneath the
43
+ // registry, and pulling that barrel in creates an import cycle.
44
+ if (config === null || config === undefined) {
45
+ return [];
46
+ }
47
+
48
+ return (Array.isArray(config) ? config : config.split(","))
49
+ .map((identifier) => identifier.trim())
50
+ .filter(Boolean);
51
+ }
52
+
53
+ /**
54
+ * Resolves a *configured* list of action identifiers against the registry.
55
+ *
56
+ * Everything reaching this function was typed into an app configuration
57
+ * (`player_action_buttons`, `modal_bottom_sheet_actions`), so an identifier
58
+ * with no provider at all means a button the app was configured to show will
59
+ * not appear - a typo, or a plugin that is not installed. A provider that runs
60
+ * and returns nothing is a different matter: that is the action opting out for
61
+ * this entry, which is expected and stays silent.
62
+ */
63
+ export function resolveActionIdentifiers({
64
+ identifiers,
65
+ entry,
66
+ expandEntryActions,
67
+ }: ResolveActionIdentifiersParams): RegisteredAction[] {
68
+ return parseActionIdentifiers(identifiers).flatMap((identifier) => {
69
+ if (identifier === ENTRY_ACTIONS_IDENTIFIER) {
70
+ if (expandEntryActions) {
71
+ return expandEntryActions(entry);
72
+ }
73
+
74
+ log_warning(
75
+ `resolveActionIdentifiers: "${ENTRY_ACTIONS_IDENTIFIER}" is configured but this caller cannot expand it - the entry's own actions will not be shown`,
76
+ { entryId: (entry as ZappEntry)?.id }
77
+ );
78
+
79
+ return [];
80
+ }
81
+
82
+ const actions = uiActionsRegistry.getActions(identifier, entry);
83
+
84
+ // `hasAction` is only read to decide what to say; resolution itself is
85
+ // unchanged, so an identifier with no provider still resolves to nothing
86
+ // exactly as before.
87
+ if (uiActionsRegistry.hasAction(identifier)) {
88
+ reportedMissingProviders.delete(identifier);
89
+ } else if (!reportedMissingProviders.has(identifier)) {
90
+ reportedMissingProviders.add(identifier);
91
+
92
+ log_warning(
93
+ `resolveActionIdentifiers: configured action "${identifier}" has no registered provider - its button will not be shown`,
94
+ { identifier, entryId: (entry as ZappEntry)?.id }
95
+ );
96
+ }
97
+
98
+ return actions;
99
+ });
100
+ }
@@ -0,0 +1,66 @@
1
+ import { createLogger } from "../logger";
2
+
3
+ import { RegisteredAction } from "./registry";
4
+
5
+ const { log_warning } = createLogger({
6
+ subsystem: "UIActionsRegistry",
7
+ category: "ActionRegistration",
8
+ });
9
+
10
+ /**
11
+ * Identifiers already reported as unusable. This runs on every render of the
12
+ * player overlay, so the warning is emitted once per identifier and forgotten
13
+ * again as soon as that action becomes invokable.
14
+ */
15
+ const reportedUnusable = new Set<string>();
16
+
17
+ function isInvokableAction(
18
+ item: RegisteredAction | undefined
19
+ ): item is RegisteredAction {
20
+ return typeof item?.action?.invokeAction === "function";
21
+ }
22
+
23
+ /**
24
+ * Narrows a resolved action list to what can actually be shown and invoked:
25
+ * anything without a usable `invokeAction` is dropped, and a repeated
26
+ * identifier keeps only its first occurrence. Order is preserved.
27
+ *
28
+ * Both the player overflow and the bottom sheet plugin build their list this
29
+ * way, and the player resolver applies it to `player_action_buttons` too - a
30
+ * hand-typed config string can name the same action twice.
31
+ */
32
+ export function usableActionItems(
33
+ items: RegisteredAction[]
34
+ ): RegisteredAction[] {
35
+ const seen = new Set<string>();
36
+ const result: RegisteredAction[] = [];
37
+
38
+ for (const item of items ?? []) {
39
+ const identifier = item?.identifier;
40
+
41
+ // A duplicate is expected - a config string may name the same action twice
42
+ // - and an action with no identifier cannot be named in a log anyway.
43
+ if (!identifier || seen.has(identifier)) {
44
+ continue;
45
+ }
46
+
47
+ if (!isInvokableAction(item)) {
48
+ if (!reportedUnusable.has(identifier)) {
49
+ reportedUnusable.add(identifier);
50
+
51
+ log_warning(
52
+ `usableActionItems: dropping action "${identifier}" - its provider returned no invokeAction, so it cannot be shown`,
53
+ { identifier }
54
+ );
55
+ }
56
+
57
+ continue;
58
+ }
59
+
60
+ reportedUnusable.delete(identifier);
61
+ seen.add(identifier);
62
+ result.push(item);
63
+ }
64
+
65
+ return result;
66
+ }
@@ -1,54 +0,0 @@
1
- import { getPlayerActionButtons } from "../getPlayerActionButtons";
2
- import { selectActionButtons } from "../../conf/player/selectors";
3
-
4
- jest.mock("../../conf/player/selectors", () => ({
5
- selectActionButtons: jest.fn(),
6
- }));
7
-
8
- describe("getPlayerActionButtons", () => {
9
- afterEach(() => {
10
- jest.clearAllMocks();
11
- });
12
-
13
- it("returns an empty array if selectActionButtons returns undefined", () => {
14
- (selectActionButtons as jest.Mock).mockReturnValue(undefined);
15
- const result = getPlayerActionButtons({});
16
- expect(result).toEqual([]);
17
- });
18
-
19
- it("returns an empty array if selectActionButtons returns null", () => {
20
- (selectActionButtons as jest.Mock).mockReturnValue(null);
21
- const result = getPlayerActionButtons({});
22
- expect(result).toEqual([]);
23
- });
24
-
25
- it("returns an empty array if selectActionButtons returns empty string", () => {
26
- (selectActionButtons as jest.Mock).mockReturnValue("");
27
- const result = getPlayerActionButtons({});
28
- expect(result).toEqual([]);
29
- });
30
-
31
- it("returns the first two trimmed action buttons", () => {
32
- (selectActionButtons as jest.Mock).mockReturnValue(" play , pause , stop ");
33
- const result = getPlayerActionButtons({});
34
- expect(result).toEqual(["play", "pause"]);
35
- });
36
-
37
- it("returns only one button if only one is present", () => {
38
- (selectActionButtons as jest.Mock).mockReturnValue(" play ");
39
- const result = getPlayerActionButtons({});
40
- expect(result).toEqual(["play"]);
41
- });
42
-
43
- it("trims whitespace from button names", () => {
44
- (selectActionButtons as jest.Mock).mockReturnValue(" play , pause ");
45
- const result = getPlayerActionButtons({});
46
- expect(result).toEqual(["play", "pause"]);
47
- });
48
-
49
- it("returns an empty array if selectActionButtons returns only commas", () => {
50
- (selectActionButtons as jest.Mock).mockReturnValue(" , , ");
51
- const result = getPlayerActionButtons({});
52
- expect(result).toEqual(["", ""]);
53
- });
54
- });
@@ -1,17 +0,0 @@
1
- import { map, take, trim } from "../utils";
2
- import { selectActionButtons } from "../conf/player/selectors";
3
-
4
- /**
5
- * Returns the first two action buttons from the configuration.
6
- * @param {Object} configuration - The player configuration object.
7
- * @returns {Array} An array containing the first two action buttons.
8
- */
9
- export const getPlayerActionButtons = (configuration: any) => {
10
- const buttonsString = selectActionButtons(configuration);
11
-
12
- if (!buttonsString) {
13
- return [];
14
- }
15
-
16
- return take(2, map(buttonsString.split(","), trim));
17
- };