@applicaster/zapp-react-native-utils 15.1.6-alpha.2015591222 → 15.1.6

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 (32) hide show
  1. package/actionsExecutor/ActionExecutorContext.tsx +0 -4
  2. package/actionsExecutor/actions/__tests__/showToast.test.ts +25 -3
  3. package/actionsExecutor/actions/index.ts +0 -4
  4. package/actionsExecutor/actions/refreshComponent.ts +29 -10
  5. package/actionsExecutor/actions/sendCloudEvent.ts +0 -8
  6. package/actionsExecutor/actions/showToast.ts +7 -5
  7. package/actionsExecutor/feedDecorator.ts +6 -6
  8. package/actionsExecutor/types.ts +3 -5
  9. package/modalState/index.ts +83 -30
  10. package/package.json +2 -2
  11. package/reactHooks/actions/index.ts +51 -1
  12. package/reactHooks/layout/index.ts +1 -1
  13. package/uiActionsRegistrator/index.ts +203 -0
  14. package/actionsExecutor/actions/__tests__/dismissBottomSheet.test.ts +0 -22
  15. package/actionsExecutor/actions/__tests__/loadItemsFromSource.test.ts +0 -88
  16. package/actionsExecutor/actions/__tests__/openBottomSheet.customContent.test.ts +0 -76
  17. package/actionsExecutor/actions/dismissBottomSheet.ts +0 -22
  18. package/actionsExecutor/actions/openBottomSheet.ts +0 -318
  19. package/modalState/ContentViewModel.ts +0 -111
  20. package/modalState/EditableCollection.ts +0 -17
  21. package/modalState/EditableCollectionRegistry.ts +0 -51
  22. package/modalState/ModalOrchestrator.ts +0 -198
  23. package/modalState/RemoteEditableCollection.ts +0 -189
  24. package/modalState/__tests__/ContentViewModel.editable.test.ts +0 -69
  25. package/modalState/__tests__/ContentViewModel.test.ts +0 -165
  26. package/modalState/__tests__/EditableCollectionRegistry.test.ts +0 -112
  27. package/modalState/__tests__/ModalOrchestrator.phase3.test.ts +0 -28
  28. package/modalState/__tests__/RemoteEditableCollection.test.ts +0 -259
  29. package/modalState/__tests__/useBottomSheetContent.test.ts +0 -372
  30. package/modalState/store.ts +0 -102
  31. package/modalState/types.ts +0 -110
  32. package/modalState/useBottomSheetContent.ts +0 -98
@@ -1,22 +0,0 @@
1
- import { dismissBottomSheetAction } from "../dismissBottomSheet";
2
- import { dismissModal } from "../../../modalState";
3
- import { ActionResult } from "../../ActionExecutor";
4
-
5
- jest.mock("../../../modalState", () => ({
6
- dismissModal: jest.fn(),
7
- }));
8
-
9
- describe("dismissBottomSheetAction", () => {
10
- beforeEach(() => {
11
- jest.clearAllMocks();
12
- });
13
-
14
- it("calls dismissModal and returns ActionResult.Success", async () => {
15
- const result = await dismissBottomSheetAction({
16
- type: "dismissBottomSheet",
17
- });
18
-
19
- expect(dismissModal).toHaveBeenCalledTimes(1);
20
- expect(result).toBe(ActionResult.Success);
21
- });
22
- });
@@ -1,88 +0,0 @@
1
- import { loadItemsFromSource } from "../openBottomSheet";
2
-
3
- const mockCall = jest.fn();
4
-
5
- jest.mock("@applicaster/zapp-pipes-v2-client", () => ({
6
- RequestBuilder: jest.fn().mockImplementation(() => ({
7
- setEntryContext: jest.fn().mockReturnThis(),
8
- setScreenContext: jest.fn().mockReturnThis(),
9
- setUrl: jest.fn().mockReturnThis(),
10
- buildAxiosRequest: jest.fn().mockResolvedValue(undefined),
11
- call: (...args: any[]) => mockCall(...args),
12
- })),
13
- PipesClientResponseHelper: jest.fn().mockImplementation(() => ({
14
- error: null,
15
- })),
16
- }));
17
-
18
- describe("loadItemsFromSource", () => {
19
- beforeEach(() => {
20
- jest.clearAllMocks();
21
- });
22
-
23
- it("returns items plus role and behavior from feed.extensions", async () => {
24
- mockCall.mockResolvedValueOnce({
25
- response: {
26
- entry: [{ id: "a", title: "Playlist A", media_group: [] }],
27
- extensions: {
28
- role: "collection_selector",
29
- behavior: {
30
- select_mode: "multi",
31
- current_selection: ["a"],
32
- selector: "extensions.tag",
33
- },
34
- },
35
- },
36
- });
37
-
38
- const result = await loadItemsFromSource("https://example.com/feed");
39
-
40
- expect(result.role).toBe("collection_selector");
41
-
42
- expect(result.behavior).toEqual({
43
- selectMode: "multi",
44
- currentSelection: ["a"],
45
- selector: "extensions.tag",
46
- });
47
-
48
- expect(result.items).toHaveLength(1);
49
- expect(result.items[0].isSelected).toBe(true);
50
- expect(result.items[0].title).toBe("Playlist A");
51
- });
52
-
53
- it("returns undefined role/behavior when feed has no extensions", async () => {
54
- mockCall.mockResolvedValueOnce({
55
- response: {
56
- entry: [{ id: "1", title: "Plain", media_group: [] }],
57
- },
58
- });
59
-
60
- const result = await loadItemsFromSource("https://example.com/plain");
61
-
62
- expect(result.role).toBeUndefined();
63
- expect(result.behavior).toBeUndefined();
64
- expect(result.items).toHaveLength(1);
65
- });
66
-
67
- it("preserves events in dynamic_collection_options", async () => {
68
- mockCall.mockResolvedValueOnce({
69
- response: {
70
- entry: [],
71
- extensions: {
72
- dynamic_collection_options: {
73
- operations: "add,remove",
74
- events: {
75
- add: [{ type: "showTextInput", options: {} }],
76
- },
77
- },
78
- },
79
- },
80
- });
81
-
82
- const result = await loadItemsFromSource("https://example.com/feed");
83
-
84
- expect(result.dynamicCollection?.events).toEqual({
85
- add: [{ type: "showTextInput", options: {} }],
86
- });
87
- });
88
- });
@@ -1,76 +0,0 @@
1
- import { openBottomSheetAction } from "../openBottomSheet";
2
- import { ActionResult } from "../../ActionExecutor";
3
- import { openBottomSheetModal } from "../../../modalState/store";
4
- import { modalOrchestrator } from "../../../modalState/ModalOrchestrator";
5
-
6
- jest.mock("../../../modalState/store", () => ({
7
- openBottomSheetModal: jest.fn(),
8
- }));
9
-
10
- jest.mock("../../../modalState/ModalOrchestrator", () => ({
11
- modalOrchestrator: {
12
- open: jest.fn(),
13
- },
14
- isPresentSubMenuAction: jest.requireActual("../../../modalState/types")
15
- .isPresentSubMenuAction,
16
- }));
17
-
18
- describe("openBottomSheetAction custom content", () => {
19
- beforeEach(() => {
20
- jest.clearAllMocks();
21
- });
22
-
23
- it("opens default sheet with contentComponent body props", async () => {
24
- const CustomContent = function CustomContent() {
25
- return null;
26
- };
27
-
28
- const result = await openBottomSheetAction({
29
- type: "openBottomSheet",
30
- options: {
31
- header: { title: "Create Playlist" },
32
- content: {
33
- component: CustomContent,
34
- props: {
35
- inputLabel: "Name your playlist",
36
- buttonLabel: "Create",
37
- defaultValue: "",
38
- submitAction: { type: "sendCloudEvent", options: {} },
39
- },
40
- },
41
- },
42
- } as any);
43
-
44
- expect(result).toBe(ActionResult.Success);
45
- expect(openBottomSheetModal).toHaveBeenCalledTimes(1);
46
- expect(modalOrchestrator.open).not.toHaveBeenCalled();
47
-
48
- const args = (openBottomSheetModal as jest.Mock).mock.calls[0][0];
49
- // Default ModalComponent provides the standard header
50
- expect(args.ModalBottomSheetContent).toBeUndefined();
51
-
52
- expect(args.modalBottomSheetContentProps).toMatchObject({
53
- title: "Create Playlist",
54
- contentComponent: CustomContent,
55
- contentComponentProps: {
56
- inputLabel: "Name your playlist",
57
- buttonLabel: "Create",
58
- defaultValue: "",
59
- },
60
- });
61
- });
62
-
63
- it("returns Error when neither list data nor content.component is provided", async () => {
64
- const result = await openBottomSheetAction({
65
- type: "openBottomSheet",
66
- options: {
67
- header: { title: "Empty" },
68
- content: {},
69
- },
70
- } as any);
71
-
72
- expect(result).toBe(ActionResult.Error);
73
- expect(openBottomSheetModal).not.toHaveBeenCalled();
74
- expect(modalOrchestrator.open).not.toHaveBeenCalled();
75
- });
76
- });
@@ -1,22 +0,0 @@
1
- /// <reference types="@applicaster/applicaster-types" />
2
- import { dismissModal } from "../../modalState";
3
- import { ActionResult } from "../ActionExecutor";
4
- import { ActionHandler } from "../types";
5
- import { createLogger } from "../../logger";
6
-
7
- const { log_info } = createLogger({
8
- subsystem: "ActionExecutorContext",
9
- category: "General",
10
- });
11
-
12
- /**
13
- * Dismisses the active bottom sheet / modal.
14
- */
15
- export const dismissBottomSheetAction: ActionHandler<
16
- any
17
- > = async (): Promise<ActionResult> => {
18
- log_info("handleAction: dismissBottomSheet");
19
- dismissModal();
20
-
21
- return ActionResult.Success;
22
- };
@@ -1,318 +0,0 @@
1
- /// <reference types="@applicaster/applicaster-types" />
2
- import {
3
- PipesClientResponseHelper,
4
- RequestBuilder,
5
- } from "@applicaster/zapp-pipes-v2-client";
6
- import { modalOrchestrator } from "../../modalState/ModalOrchestrator";
7
- import { openBottomSheetModal } from "../../modalState/store";
8
- import {
9
- DynamicCollectionOptions,
10
- isPresentSubMenuAction,
11
- Menu,
12
- MenuItem,
13
- Operation,
14
- SelectionBehavior,
15
- } from "../../modalState/types";
16
- import { actionExecutor, ActionResult } from "../ActionExecutor";
17
- import { createLogger } from "../../logger";
18
-
19
- const { log_info, log_error } = createLogger({
20
- subsystem: "ActionExecutorContext",
21
- category: "General",
22
- });
23
-
24
- export type LoadedSheetContent = {
25
- items: MenuItem[];
26
- role?: string;
27
- behavior?: SelectionBehavior;
28
- dynamicCollection?: DynamicCollectionOptions;
29
- };
30
-
31
- /**
32
- * Parse a raw `dynamic_collection_options` block (feed or inline content) into
33
- * the typed `DynamicCollectionOptions`. `operations` accepts either a CSV
34
- * string (feed) or an array (already parsed).
35
- */
36
- export function parseDynamicCollectionOptions(
37
- raw:
38
- | {
39
- operations?: string | string[];
40
- postUrl?: string;
41
- provider?: string;
42
- events?: Record<string, any[]>;
43
- }
44
- | undefined
45
- ): DynamicCollectionOptions | undefined {
46
- if (!raw) {
47
- return undefined;
48
- }
49
-
50
- const operations = Array.isArray(raw.operations)
51
- ? (raw.operations as Operation[])
52
- : ((raw.operations || "").split(",").filter(Boolean) as Operation[]);
53
-
54
- return {
55
- operations,
56
- postUrl: raw.postUrl,
57
- provider: raw.provider,
58
- events: raw.events,
59
- };
60
- }
61
-
62
- /**
63
- * Converts a ZappEntry from a pipes feed into a MenuItem.
64
- * - Icon: first src found in the image media_group.
65
- * - Primary action: taken from tap_actions.actions[0].
66
- * - isSelected: true when entry.id is in currentSelection.
67
- */
68
- export function entryToMenuItem(
69
- entry: ZappEntry,
70
- currentSelection: string[] = []
71
- ): MenuItem {
72
- const imageGroup = entry.media_group?.find((g) => g.type === "image");
73
-
74
- const firstImage = Array.isArray(imageGroup?.media_item)
75
- ? imageGroup.media_item[0]
76
- : imageGroup?.media_item;
77
-
78
- // Primary action — first tap_action on the entry
79
- const tapActions = entry.extensions?.tap_actions?.actions || [];
80
- const primaryAction = tapActions.length > 0 ? tapActions[0] : undefined;
81
-
82
- let summary = entry.summary as string;
83
-
84
- // TODO: remove just a small logic for debugging
85
-
86
- if (
87
- !summary &&
88
- entry.extensions &&
89
- typeof entry.extensions.item_count === "number"
90
- ) {
91
- const count = entry.extensions.item_count;
92
- summary = `${count} ${count === 1 ? "Item" : "Items"}`;
93
- }
94
-
95
- return {
96
- id: entry.id as string,
97
- title: entry.title as string,
98
- summary,
99
- icon: firstImage?.src,
100
- isSelected: currentSelection.includes(String(entry.id)),
101
- action: primaryAction,
102
- entryActions: entry.extensions?.entry_action || [],
103
- };
104
- }
105
-
106
- function parseCurrentSelection(rawSelection: unknown): string[] {
107
- if (Array.isArray(rawSelection)) {
108
- return (rawSelection as any[]).map(String);
109
- }
110
-
111
- if (rawSelection !== undefined && rawSelection !== null) {
112
- return [String(rawSelection)];
113
- }
114
-
115
- return [];
116
- }
117
-
118
- function parseBehaviorFromFeed(
119
- feed: ZappFeed | undefined,
120
- currentSelection: string[]
121
- ): SelectionBehavior | undefined {
122
- const raw = feed?.extensions?.behavior;
123
-
124
- if (!raw && currentSelection.length === 0) {
125
- return undefined;
126
- }
127
-
128
- return {
129
- selectMode: raw?.select_mode,
130
- currentSelection,
131
- selector: raw?.selector,
132
- };
133
- }
134
-
135
- function parseBehaviorFromContentOptions(
136
- content: Record<string, any> | undefined
137
- ): SelectionBehavior | undefined {
138
- const raw = content?.behavior ?? content?.extensions?.behavior;
139
-
140
- if (!raw) {
141
- return undefined;
142
- }
143
-
144
- return {
145
- selectMode: raw.selectMode ?? raw.select_mode,
146
- currentSelection: parseCurrentSelection(
147
- raw.currentSelection ?? raw.current_selection
148
- ),
149
- selector: raw.selector,
150
- };
151
- }
152
-
153
- // Exported so MultiLevelBottomSheetContent can lazy-load sub-levels
154
- export async function loadItemsFromSource(
155
- source: string,
156
- context?: Record<string, any>
157
- ): Promise<LoadedSheetContent> {
158
- const requestBuilder = new RequestBuilder()
159
- .setEntryContext(context?.entry || {})
160
- .setScreenContext(context?.screenData || {})
161
- .setUrl(source);
162
-
163
- await requestBuilder.buildAxiosRequest();
164
-
165
- const responseData = await requestBuilder.call<ZappFeed>();
166
-
167
- const responseHelper = new PipesClientResponseHelper(responseData);
168
-
169
- if (responseHelper.error) {
170
- throw responseHelper.error;
171
- }
172
-
173
- const feed = responseData?.response as ZappFeed;
174
-
175
- const currentSelection = parseCurrentSelection(
176
- feed?.extensions?.behavior?.current_selection
177
- );
178
-
179
- const items = (feed?.entry || []).map((entry) =>
180
- entryToMenuItem(entry, currentSelection)
181
- );
182
-
183
- const dynamicCollectionOptions = feed?.extensions?.dynamic_collection_options;
184
-
185
- const dynamicCollection = parseDynamicCollectionOptions(
186
- dynamicCollectionOptions
187
- );
188
-
189
- return {
190
- items,
191
- role: feed?.extensions?.role,
192
- behavior: parseBehaviorFromFeed(feed, currentSelection),
193
- dynamicCollection,
194
- };
195
- }
196
-
197
- export async function openBottomSheetAction(
198
- action: ActionType,
199
- context?: Record<string, any>
200
- ): Promise<ActionResult> {
201
- try {
202
- const { content, header } = action.options || {};
203
-
204
- // Custom body component — keep default ModalComponent so standard header
205
- // (dismiss x) is used; content.component is body-only (e.g. TextInputContent).
206
- if (content?.component) {
207
- log_info("openBottomSheet: using custom content component");
208
-
209
- openBottomSheetModal({
210
- modalBottomSheetContentProps: {
211
- title: header?.title,
212
- summary: header?.subtitle,
213
- items: [],
214
- onPress: () => {},
215
- contentComponent: content.component,
216
- contentComponentProps: content.props || {},
217
- },
218
- });
219
-
220
- return ActionResult.Success;
221
- }
222
-
223
- const inlineItems: ZappEntry[] = content?.items;
224
- const itemsUrl: string = content?.itemsUrl;
225
-
226
- let items: MenuItem[];
227
- let role: string | undefined;
228
- let behavior: SelectionBehavior | undefined;
229
-
230
- let dynamicCollection: DynamicCollectionOptions | undefined;
231
-
232
- if (Array.isArray(inlineItems) && inlineItems.length > 0) {
233
- log_info("openBottomSheet: using inline items from action options", {
234
- count: inlineItems.length,
235
- });
236
-
237
- items = inlineItems.map((entry) => entryToMenuItem(entry));
238
- role = content?.role ?? content?.extensions?.role;
239
- behavior = parseBehaviorFromContentOptions(content);
240
-
241
- dynamicCollection = parseDynamicCollectionOptions(
242
- content?.dynamicCollection ??
243
- content?.extensions?.dynamic_collection_options
244
- );
245
- } else if (itemsUrl) {
246
- log_info(`openBottomSheet: loading items from source: ${itemsUrl}`);
247
-
248
- const loaded = await loadItemsFromSource(itemsUrl, context);
249
- items = loaded.items;
250
- role = loaded.role ?? content?.role ?? content?.extensions?.role;
251
- behavior = loaded.behavior ?? parseBehaviorFromContentOptions(content);
252
- dynamicCollection = loaded.dynamicCollection;
253
-
254
- log_info(
255
- `openBottomSheet: loaded ${items.length} items from source: ${itemsUrl}`
256
- );
257
- } else {
258
- log_error(
259
- "openBottomSheet: no itemsUrl, items, or content.component provided in action options"
260
- );
261
-
262
- return ActionResult.Error;
263
- }
264
-
265
- const menu: Menu = {
266
- header: header
267
- ? {
268
- title: header.title,
269
- subtitle: header.subtitle,
270
- icon: header.icon,
271
- }
272
- : undefined,
273
- content: {
274
- title: content?.title ?? "",
275
- items,
276
- itemsUrl, // stored so the component can reload after an action
277
- role,
278
- behavior,
279
- dynamicCollection,
280
- },
281
- };
282
-
283
- /**
284
- * Called when the user taps a menu item.
285
- *
286
- * - PresentSubMenuAction → handled by the orchestrator (pushes sub-menu)
287
- * - Any other Action type → forwarded to the action executor, keeping the
288
- * original execution context so screen/entry data is available to handlers.
289
- * The pressed item is also added as `entry` so downstream actions can
290
- * reference it.
291
- */
292
- const onItemPress = async (item: MenuItem): Promise<void> => {
293
- if (!item.action || isPresentSubMenuAction(item.action)) {
294
- // Submenu navigation is handled internally by the orchestrator
295
- return;
296
- }
297
-
298
- await actionExecutor.handleAction(
299
- item.action as ActionType,
300
- {
301
- ...context,
302
- entry: item as any,
303
- } as any
304
- );
305
- };
306
-
307
- modalOrchestrator.open(menu, onItemPress);
308
-
309
- return ActionResult.Success;
310
- } catch (error) {
311
- log_error("openBottomSheet: failed to open bottom sheet", {
312
- error,
313
- action,
314
- });
315
-
316
- return ActionResult.Error;
317
- }
318
- }
@@ -1,111 +0,0 @@
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
- }
@@ -1,17 +0,0 @@
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
- }
@@ -1,51 +0,0 @@
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
- }