@applicaster/zapp-react-native-utils 16.0.0-rc.31 → 16.0.0-rc.33

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.
@@ -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,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@applicaster/zapp-react-native-utils",
3
- "version": "16.0.0-rc.31",
3
+ "version": "16.0.0-rc.33",
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-rc.31",
30
+ "@applicaster/applicaster-types": "16.0.0-rc.33",
31
31
  "buffer": "^5.2.1",
32
32
  "camelize": "^1.0.0",
33
33
  "dayjs": "^1.11.10",
@@ -1,8 +1,12 @@
1
1
  /// <reference types="@applicaster/applicaster-types" />
2
2
  /* eslint-disable @typescript-eslint/no-unused-vars */
3
- import { Context, useContext, useState } from "react";
3
+ import { Context, useCallback, useContext, useEffect, useState } from "react";
4
4
  import { ActionsContext } from "@applicaster/zapp-react-native-ui-components/Contexts/ActionsContext";
5
5
 
6
+ import {
7
+ observeEntryState,
8
+ RegisteredActionValue,
9
+ } from "../../uiActionsRegistrator";
6
10
  import { reactHooksLogger } from "../logger";
7
11
 
8
12
  const logger = reactHooksLogger.addSubsystem("actions");
@@ -46,3 +50,49 @@ export function useActions<T = unknown>(plugId: string): any {
46
50
 
47
51
  return context;
48
52
  }
53
+
54
+ export type UseEntryActionState = {
55
+ state: CellActionEntryState | undefined;
56
+ invokeAction: (options?: InvokeArgsOptions) => void;
57
+ };
58
+
59
+ /**
60
+ * Subscribes a component to a single action's state for a given `entry`.
61
+ *
62
+ * It observes state changes reactively via `observeEntryState` (which is backed
63
+ * by the action's `addListener`), seeds the initial value synchronously from
64
+ * `initialEntryState`, and returns a memoized `invokeAction` that forwards
65
+ * optimistic `updateState` updates back into local state.
66
+ *
67
+ * This is the single, unified way to drive an action button - it works the same
68
+ * for registry actions, legacy context-provider actions and entry actions.
69
+ */
70
+ export function useEntryActionState(
71
+ action: RegisteredActionValue | undefined,
72
+ entry: ZappEntry | ZappFeed
73
+ ): UseEntryActionState {
74
+ const [state, setState] = useState<CellActionEntryState | undefined>(() =>
75
+ action?.initialEntryState?.(entry)
76
+ );
77
+
78
+ const entryId = (entry as ZappEntry)?.id;
79
+
80
+ useEffect(() => {
81
+ if (!action) return undefined;
82
+
83
+ const subscription = observeEntryState(action, entry).subscribe(setState);
84
+
85
+ return () => subscription.unsubscribe();
86
+ // eslint-disable-next-line @wogns3623/better-exhaustive-deps/exhaustive-deps
87
+ }, [action, entryId]);
88
+
89
+ const invokeAction = useCallback(
90
+ (options: InvokeArgsOptions = {}) => {
91
+ action?.invokeAction?.(entry, { updateState: setState, ...options });
92
+ },
93
+ // eslint-disable-next-line @wogns3623/better-exhaustive-deps/exhaustive-deps
94
+ [action, entryId]
95
+ );
96
+
97
+ return { state, invokeAction };
98
+ }
@@ -0,0 +1,203 @@
1
+ /* eslint-disable no-dupe-class-members */
2
+ import { Observable } from "rxjs";
3
+ import { createLogger } from "../logger";
4
+
5
+ const { log_debug, log_warning, log_verbose } = 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
+ export type RegisteredAction = {
44
+ identifier: string; // Plugin identifier or synthetic name
45
+ action: RegisteredActionValue;
46
+ };
47
+
48
+ /**
49
+ * A function that, given an optional context (currently just the `entry`),
50
+ * returns the list of actions it wants to contribute.
51
+ *
52
+ * Returning an array is what allows a single provider (plugin or otherwise) to
53
+ * expose more than one action, and to compute those actions based on the entry.
54
+ */
55
+ export type UIActionProvider = (params: {
56
+ entry?: ZappEntry | ZappFeed;
57
+ }) => RegisteredAction[];
58
+
59
+ /**
60
+ * Returns an RX `Observable` that emits the action state for `entry`.
61
+ *
62
+ * If the action already exposes its own `observeEntryState`, it is used as-is.
63
+ * Otherwise we build the stream from the legacy imperative API:
64
+ * - it immediately emits `initialEntryState(entry)` (if available), and
65
+ * - it subscribes to further changes via `addListener(entryId, listener)`,
66
+ * unsubscribing automatically when the observable is torn down.
67
+ *
68
+ * This lets every action - old or new - be consumed reactively through a single
69
+ * mechanism, without each consumer having to wire up `addListener` manually.
70
+ */
71
+ export function observeEntryState(
72
+ action: RegisteredActionValue | undefined,
73
+ entry: ZappEntry | ZappFeed
74
+ ): Observable<CellActionEntryState> {
75
+ if (typeof action?.observeEntryState === "function") {
76
+ return action.observeEntryState(entry);
77
+ }
78
+
79
+ return new Observable<CellActionEntryState>((subscriber) => {
80
+ const initialState = action?.initialEntryState?.(entry);
81
+
82
+ if (initialState !== undefined) {
83
+ subscriber.next(initialState);
84
+ }
85
+
86
+ const removeListener = action?.addListener?.(
87
+ String((entry as ZappEntry)?.id),
88
+ (state: CellActionEntryState) => subscriber.next(state)
89
+ );
90
+
91
+ return () => removeListener?.();
92
+ });
93
+ }
94
+
95
+ class UIActionsRegistry {
96
+ private registeredActions: Record<string, UIActionProvider> = {};
97
+
98
+ /**
99
+ * Register a dynamic action provider under a unique `name`.
100
+ * The provider can return one or more actions and may use the passed `entry`.
101
+ * Returns an unregister function.
102
+ */
103
+ registerActionProvider(
104
+ name: string,
105
+ actionProvider: UIActionProvider
106
+ ): () => void {
107
+ const isOverride = Boolean(this.registeredActions[name]);
108
+
109
+ if (isOverride) {
110
+ log_warning(
111
+ `registerActionProvider: overriding existing provider for "${name}"`,
112
+ { name }
113
+ );
114
+ } else {
115
+ log_debug(`registerActionProvider: registered "${name}"`, { name });
116
+ }
117
+
118
+ this.registeredActions[name] = actionProvider;
119
+
120
+ return () => {
121
+ // Only remove if it's still the same provider to avoid races where a
122
+ // newer registration replaced this one.
123
+ if (this.registeredActions[name] === actionProvider) {
124
+ delete this.registeredActions[name];
125
+ log_debug(`registerActionProvider: unregistered "${name}"`, { name });
126
+ } else {
127
+ log_debug(
128
+ `registerActionProvider: skipped unregister for "${name}" – newer provider is active`,
129
+ { name }
130
+ );
131
+ }
132
+ };
133
+ }
134
+
135
+ /**
136
+ * Convenience helper to register a single, static action from anywhere in the
137
+ * app (it does not need to be a plugin). Returns an unregister function.
138
+ */
139
+ registerAction(
140
+ identifier: string,
141
+ action: RegisteredActionValue
142
+ ): () => void {
143
+ log_debug(`registerAction: registering single action "${identifier}"`, {
144
+ identifier,
145
+ });
146
+
147
+ return this.registerActionProvider(identifier, () => [
148
+ { identifier, action },
149
+ ]);
150
+ }
151
+
152
+ getEntryActions(entry: ZappEntry): RegisteredAction[] {
153
+ const results = Object.keys(this.registeredActions)
154
+ .map((key) => this.registeredActions[key]({ entry }))
155
+ .flatMap((a) => a);
156
+
157
+ log_verbose(
158
+ `getEntryActions: resolved ${results.length} action(s) for entry "${entry?.id}"`,
159
+ { entryId: entry?.id, identifiers: results.map((r) => r.identifier) }
160
+ );
161
+
162
+ return results;
163
+ }
164
+
165
+ getActions(name: string, entry?: ZappEntry | ZappFeed): RegisteredAction[] {
166
+ if (!this.registeredActions[name]) {
167
+ log_warning(`getActions: no provider found for "${name}"`, { name });
168
+
169
+ return [];
170
+ }
171
+
172
+ const results = this.registeredActions[name]({ entry }) ?? [];
173
+
174
+ log_verbose(
175
+ `getActions: resolved ${results.length} action(s) for "${name}"`,
176
+ {
177
+ name,
178
+ entryId: (entry as ZappEntry)?.id,
179
+ identifiers: results.map((r) => r.identifier),
180
+ }
181
+ );
182
+
183
+ return results;
184
+ }
185
+
186
+ /**
187
+ * Returns the runtime value of the first action registered under `name`, or
188
+ * `undefined`. This mirrors the shape returned by the legacy `useActions`
189
+ * hook, easing migration of single-action consumers.
190
+ */
191
+ getAction(
192
+ name: string,
193
+ entry?: ZappEntry | ZappFeed
194
+ ): RegisteredActionValue | undefined {
195
+ return this.getActions(name, entry)[0]?.action;
196
+ }
197
+
198
+ hasAction(name: string): boolean {
199
+ return Boolean(this.registeredActions[name]);
200
+ }
201
+ }
202
+
203
+ export const uiActionsRegistry = new UIActionsRegistry();