react-native-live-widgets 1.1.1 → 1.2.0

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 (46) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/README.md +73 -9
  3. package/android/src/main/java/com/reactnativeliveactivity/bridge/LiveActivityModule.kt +5 -1
  4. package/android/src/main/java/com/reactnativeliveactivity/storage/DynamicWidgetStateStore.kt +5 -1
  5. package/docs/GUIDE-EN.md +91 -7
  6. package/docs/GUIDE-VI.md +91 -7
  7. package/docs/index.html +37 -2
  8. package/docs/llms-full.txt +20 -6
  9. package/docs/llms.txt +29 -7
  10. package/ios/Models/DynamicLayoutModels.swift +5 -0
  11. package/ios/Widgets/DynamicHomeScreenWidget.swift +2 -3
  12. package/lib/builder.d.ts.map +1 -1
  13. package/lib/builder.js +29 -19
  14. package/lib/builder.js.map +1 -1
  15. package/lib/dispatcher.d.ts +7 -0
  16. package/lib/dispatcher.d.ts.map +1 -1
  17. package/lib/dispatcher.js +11 -0
  18. package/lib/dispatcher.js.map +1 -1
  19. package/lib/hooks.d.ts +66 -0
  20. package/lib/hooks.d.ts.map +1 -0
  21. package/lib/hooks.js +166 -0
  22. package/lib/hooks.js.map +1 -0
  23. package/lib/index.d.ts +32 -7
  24. package/lib/index.d.ts.map +1 -1
  25. package/lib/index.js +115 -8
  26. package/lib/index.js.map +1 -1
  27. package/lib/jsx.d.ts +79 -0
  28. package/lib/jsx.d.ts.map +1 -0
  29. package/lib/jsx.js +196 -0
  30. package/lib/jsx.js.map +1 -0
  31. package/lib/preview.d.ts +54 -0
  32. package/lib/preview.d.ts.map +1 -0
  33. package/lib/preview.js +466 -0
  34. package/lib/preview.js.map +1 -0
  35. package/lib/types.d.ts +8 -0
  36. package/lib/types.d.ts.map +1 -1
  37. package/package.json +2 -1
  38. package/src/builder.ts +29 -19
  39. package/src/dispatcher.ts +17 -0
  40. package/src/hooks.ts +223 -0
  41. package/src/index.ts +137 -13
  42. package/src/jsx.tsx +296 -0
  43. package/src/preview.tsx +719 -0
  44. package/src/react-ambient.d.ts +10 -0
  45. package/src/react-native-env.d.ts +43 -0
  46. package/src/types.ts +8 -0
package/src/builder.ts CHANGED
@@ -64,6 +64,15 @@ function isLayoutNode(item: any): item is LayoutNode {
64
64
  return item && typeof item === 'object' && typeof item.type === 'string';
65
65
  }
66
66
 
67
+ function normalizeProps<P extends object>(props?: P): P | undefined {
68
+ if (!props) return undefined;
69
+ const p = { ...props } as any;
70
+ if (p.cornerRadius !== undefined && p.borderRadius === undefined) {
71
+ p.borderRadius = p.cornerRadius;
72
+ }
73
+ return p as P;
74
+ }
75
+
67
76
  function parseContainerArgs<P extends object>(
68
77
  first?: StyleProp<P> | LayoutNode | LayoutNode[],
69
78
  rest?: LayoutNode[]
@@ -76,12 +85,12 @@ function parseContainerArgs<P extends object>(
76
85
  return { props: undefined, children: first as LayoutNode[] };
77
86
  }
78
87
  const flattened = flattenStyle<P>(first as StyleProp<P>);
79
- return { props: flattened, children: rest || [] };
88
+ return { props: normalizeProps(flattened), children: rest || [] };
80
89
  }
81
90
  if (isLayoutNode(first)) {
82
91
  return { props: undefined, children: [first, ...(rest || [])] };
83
92
  }
84
- return { props: first as P, children: rest || [] };
93
+ return { props: normalizeProps(first as P), children: rest || [] };
85
94
  }
86
95
 
87
96
  /**
@@ -154,15 +163,15 @@ export const UI = {
154
163
  if (typeof valueOrOptions === 'number') {
155
164
  return {
156
165
  type: 'Progress',
157
- props: {
166
+ props: normalizeProps({
158
167
  value: valueOrOptions,
159
168
  ...options,
160
- },
169
+ })!,
161
170
  };
162
171
  }
163
172
  return {
164
173
  type: 'Progress',
165
- props: valueOrOptions,
174
+ props: normalizeProps(valueOrOptions)!,
166
175
  };
167
176
  },
168
177
 
@@ -175,19 +184,19 @@ export const UI = {
175
184
  const isBase64 = urlOrOptions.startsWith('data:image/');
176
185
  return {
177
186
  type: 'Image',
178
- props: {
187
+ props: normalizeProps({
179
188
  ...(isHttp
180
189
  ? { url: urlOrOptions }
181
190
  : isBase64
182
191
  ? { base64: urlOrOptions }
183
192
  : { systemName: urlOrOptions }),
184
193
  ...options,
185
- },
194
+ })!,
186
195
  };
187
196
  }
188
197
  return {
189
198
  type: 'Image',
190
- props: urlOrOptions,
199
+ props: normalizeProps(urlOrOptions)!,
191
200
  };
192
201
  },
193
202
 
@@ -201,16 +210,17 @@ export const UI = {
201
210
  options?: Omit<ButtonNode['props'], 'title'>
202
211
  ): ButtonNode => {
203
212
  if (typeof titleOrProps === 'object' && titleOrProps !== null) {
204
- if (titleOrProps.onPress && !titleOrProps.actionId) {
213
+ const normalized = normalizeProps(titleOrProps)!;
214
+ if (normalized.onPress && !normalized.actionId) {
205
215
  autoActionCounter += 1;
206
- titleOrProps.actionId = `act_${Date.now()}_${autoActionCounter}`;
207
- registerAction(titleOrProps.actionId, titleOrProps.onPress);
208
- } else if (titleOrProps.onPress && titleOrProps.actionId) {
209
- registerAction(titleOrProps.actionId, titleOrProps.onPress);
216
+ normalized.actionId = `act_${Date.now()}_${autoActionCounter}`;
217
+ registerAction(normalized.actionId, normalized.onPress);
218
+ } else if (normalized.onPress && normalized.actionId) {
219
+ registerAction(normalized.actionId, normalized.onPress);
210
220
  }
211
221
  return {
212
222
  type: 'Button',
213
- props: titleOrProps,
223
+ props: normalized,
214
224
  };
215
225
  }
216
226
 
@@ -225,11 +235,11 @@ export const UI = {
225
235
 
226
236
  return {
227
237
  type: 'Button',
228
- props: {
238
+ props: normalizeProps({
229
239
  title: titleOrProps,
230
240
  ...options,
231
241
  actionId: finalActionId,
232
- },
242
+ })!,
233
243
  };
234
244
  },
235
245
 
@@ -350,15 +360,15 @@ export const UI = {
350
360
  if (typeof textOrOptions === 'string') {
351
361
  return {
352
362
  type: 'Badge',
353
- props: {
363
+ props: normalizeProps({
354
364
  text: textOrOptions,
355
365
  ...options,
356
- },
366
+ })!,
357
367
  };
358
368
  }
359
369
  return {
360
370
  type: 'Badge',
361
- props: textOrOptions,
371
+ props: normalizeProps(textOrOptions)!,
362
372
  };
363
373
  },
364
374
 
package/src/dispatcher.ts CHANGED
@@ -4,7 +4,13 @@ export type ActionHandler = (event: {
4
4
  [key: string]: any;
5
5
  }) => Promise<any> | any;
6
6
 
7
+ export type GlobalActionHandler = (
8
+ actionId: string,
9
+ payload?: any
10
+ ) => Promise<any> | any;
11
+
7
12
  export const actionHandlers = new Map<string, ActionHandler>();
13
+ export const globalActionHandlers = new Set<GlobalActionHandler>();
8
14
 
9
15
  /**
10
16
  * Đăng ký một hàm xử lý logic TypeScript khi người dùng bấm nút có `actionId` tương ứng ngoài Widget/Live Activity.
@@ -17,6 +23,17 @@ export function registerAction(actionId: string, handler: ActionHandler): () =>
17
23
  };
18
24
  }
19
25
 
26
+ /**
27
+ * Đăng ký hàm lắng nghe toàn bộ các sự kiện bấm nút từ Widget hoặc Live Activity.
28
+ * Trả về hàm hủy đăng ký (unsubscribe).
29
+ */
30
+ export function registerActionHandler(handler: GlobalActionHandler): () => void {
31
+ globalActionHandlers.add(handler);
32
+ return () => {
33
+ globalActionHandlers.delete(handler);
34
+ };
35
+ }
36
+
20
37
  /**
21
38
  * Hủy đăng ký action handler.
22
39
  */
package/src/hooks.ts ADDED
@@ -0,0 +1,223 @@
1
+ import { useState, useEffect, useRef, useCallback } from 'react';
2
+ import {
3
+ ActionHandler,
4
+ GlobalActionHandler,
5
+ registerAction,
6
+ registerActionHandler,
7
+ } from './dispatcher';
8
+ import { LiveActivity, SharedStorage, Widget } from './index';
9
+ import {
10
+ LiveActivityPushTokens,
11
+ StartActivityOptions,
12
+ UpdateActivityOptions,
13
+ EndActivityOptions,
14
+ } from './types';
15
+
16
+ /**
17
+ * 🎣 React Hook an toàn tuyệt đối với Fast Refresh / Hot Reloading để lắng nghe
18
+ * tương tác nút bấm trên Home Screen Widget hoặc Live Activity.
19
+ * Tự động đăng ký khi mount và hủy dọn dẹp (cleanup) khi Component unmount.
20
+ *
21
+ * Cách dùng 1 (Lắng nghe 1 actionId cụ thể):
22
+ * ```typescript
23
+ * useWidgetAction('counter:inc', (event) => {
24
+ * setCount((prev) => prev + 1);
25
+ * });
26
+ * ```
27
+ *
28
+ * Cách dùng 2 (Lắng nghe toàn cục mọi sự kiện nút bấm):
29
+ * ```typescript
30
+ * useWidgetAction((actionId, payload) => {
31
+ * console.log('Action received:', actionId, payload);
32
+ * });
33
+ * ```
34
+ */
35
+ export function useWidgetAction(
36
+ actionIdOrCallback: string | GlobalActionHandler,
37
+ handler?: ActionHandler
38
+ ): void {
39
+ const savedHandler = useRef<ActionHandler | GlobalActionHandler | undefined>(undefined);
40
+
41
+ useEffect(() => {
42
+ savedHandler.current = typeof actionIdOrCallback === 'function' ? actionIdOrCallback : handler;
43
+ });
44
+
45
+ useEffect(() => {
46
+ if (typeof actionIdOrCallback === 'function') {
47
+ const unsubscribe = registerActionHandler((actionId, payload) => {
48
+ if (typeof savedHandler.current === 'function') {
49
+ (savedHandler.current as GlobalActionHandler)(actionId, payload);
50
+ }
51
+ });
52
+ return unsubscribe;
53
+ } else if (typeof actionIdOrCallback === 'string') {
54
+ const unsubscribe = registerAction(actionIdOrCallback, (event) => {
55
+ if (typeof savedHandler.current === 'function') {
56
+ (savedHandler.current as ActionHandler)(event);
57
+ }
58
+ });
59
+ return unsubscribe;
60
+ }
61
+ }, [actionIdOrCallback]);
62
+ }
63
+
64
+ export interface UseLiveActivityResult {
65
+ /** ID định danh phiên Live Activity hiện tại */
66
+ activityId: string | null;
67
+ /** Trạng thái phiên có đang hoạt động hay không */
68
+ isActive: boolean;
69
+ /** Token cập nhật tiện ích (iOS activityUpdateToken hoặc devicePushToken) */
70
+ pushToken: string | null;
71
+ /** Toàn bộ bộ 3 loại Push Token (deviceToken, pushToStart, activityUpdateToken) */
72
+ pushTokens: LiveActivityPushTokens | null;
73
+ /** Bắt đầu một Live Activity mới */
74
+ start: (options: StartActivityOptions) => Promise<string | null>;
75
+ /** Cập nhật nội dung Live Activity hiện tại */
76
+ update: (options: Omit<UpdateActivityOptions, 'activityId'>) => Promise<boolean>;
77
+ /** Kết thúc Live Activity hiện tại */
78
+ end: (options?: EndActivityOptions) => Promise<boolean>;
79
+ }
80
+
81
+ /**
82
+ * 🎣 React Hook quản lý vòng đời trọn vẹn của một Live Activity / Android Ongoing Notification.
83
+ * Tương thích Fast Refresh và tự động dọn dẹp state khi component unmount.
84
+ *
85
+ * ```typescript
86
+ * const { activityId, isActive, start, update, end } = useLiveActivity();
87
+ *
88
+ * // Bắt đầu khi bấm nút
89
+ * await start({
90
+ * activityId: 'order_123',
91
+ * lockScreen: UI.VStack(...)
92
+ * });
93
+ * ```
94
+ */
95
+ export function useLiveActivity(initialActivityId?: string): UseLiveActivityResult {
96
+ const [currentId, setCurrentId] = useState<string | null>(initialActivityId || null);
97
+ const [isActive, setIsActive] = useState<boolean>(!!initialActivityId);
98
+ const [pushTokens, setPushTokens] = useState<LiveActivityPushTokens | null>(null);
99
+
100
+ useEffect(() => {
101
+ let mounted = true;
102
+ if (currentId) {
103
+ LiveActivity.getAllPushTokens(currentId)
104
+ .then((tokens: LiveActivityPushTokens) => {
105
+ if (mounted && tokens) {
106
+ setPushTokens(tokens);
107
+ }
108
+ })
109
+ .catch(() => {});
110
+ }
111
+ return () => {
112
+ mounted = false;
113
+ };
114
+ }, [currentId]);
115
+
116
+ const start = useCallback(
117
+ async (options: StartActivityOptions): Promise<string | null> => {
118
+ const ok = await LiveActivity.start(options);
119
+ if (ok) {
120
+ setCurrentId(options.activityId);
121
+ setIsActive(true);
122
+ try {
123
+ const tokens = await LiveActivity.getAllPushTokens(options.activityId);
124
+ setPushTokens(tokens);
125
+ } catch (_) {}
126
+ return options.activityId;
127
+ }
128
+ return null;
129
+ },
130
+ []
131
+ );
132
+
133
+ const update = useCallback(
134
+ async (options: Omit<UpdateActivityOptions, 'activityId'>): Promise<boolean> => {
135
+ if (!currentId) return false;
136
+ return await LiveActivity.update({
137
+ activityId: currentId,
138
+ ...options,
139
+ });
140
+ },
141
+ [currentId]
142
+ );
143
+
144
+ const end = useCallback(
145
+ async (options?: EndActivityOptions): Promise<boolean> => {
146
+ if (!currentId) return false;
147
+ const ok = await LiveActivity.end(currentId, options);
148
+ if (ok) {
149
+ setIsActive(false);
150
+ }
151
+ return ok;
152
+ },
153
+ [currentId]
154
+ );
155
+
156
+ return {
157
+ activityId: currentId,
158
+ isActive,
159
+ pushToken: pushTokens?.activityUpdateToken || pushTokens?.devicePushToken || null,
160
+ pushTokens,
161
+ start,
162
+ update,
163
+ end,
164
+ };
165
+ }
166
+
167
+ /**
168
+ * 🎣 React Hook liên kết state ứng dụng với Shared Storage của Home Screen Widget.
169
+ * Mỗi khi gọi `setWidgetState(...)`, widget sẽ tự động được hệ điều hành vẽ lại ngay lập tức.
170
+ *
171
+ * ```typescript
172
+ * const [counter, setCounter] = useWidgetState('counter_key', 0);
173
+ *
174
+ * // Cập nhật state + tự động yêu cầu Widget reload:
175
+ * setCounter(prev => prev + 1);
176
+ * ```
177
+ */
178
+ export function useWidgetState<T>(
179
+ key: string,
180
+ initialValue: T,
181
+ appGroup?: string
182
+ ): [T, (newValue: T | ((prev: T) => T)) => Promise<void>, () => Promise<void>] {
183
+ const [state, setState] = useState<T>(initialValue);
184
+
185
+ useEffect(() => {
186
+ let mounted = true;
187
+ SharedStorage.get<T>(key, appGroup)
188
+ .then((val: T | null) => {
189
+ if (mounted && val !== null && val !== undefined) {
190
+ setState(val);
191
+ }
192
+ })
193
+ .catch(() => {});
194
+ return () => {
195
+ mounted = false;
196
+ };
197
+ }, [key, appGroup]);
198
+
199
+ const setWidgetState = useCallback(
200
+ async (newValue: T | ((prev: T) => T)) => {
201
+ setState((prev: T) => {
202
+ const resolved =
203
+ typeof newValue === 'function' ? (newValue as (p: T) => T)(prev) : newValue;
204
+ SharedStorage.set(key, resolved, appGroup)
205
+ .then(() => {
206
+ Widget.reloadAll().catch(() => {});
207
+ })
208
+ .catch(() => {});
209
+ return resolved;
210
+ });
211
+ },
212
+ [key, appGroup]
213
+ );
214
+
215
+ const reload = useCallback(async () => {
216
+ const val = await SharedStorage.get<T>(key, appGroup);
217
+ if (val !== null && val !== undefined) {
218
+ setState(val);
219
+ }
220
+ }, [key, appGroup]);
221
+
222
+ return [state, setWidgetState, reload];
223
+ }
package/src/index.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import React from 'react';
1
2
  import { AppRegistry, NativeEventEmitter, NativeModules, Platform } from 'react-native';
2
3
  import {
3
4
  ActiveActivityInfo,
@@ -31,9 +32,21 @@ const TOKEN_CHANGED_EVENT = 'LiveActivityTokenChanged';
31
32
  const UPDATE_TOKEN_CHANGED_EVENT = 'LiveActivityUpdateTokenChanged';
32
33
  const ACTION_CLICKED_EVENT = 'LiveActivityActionClicked';
33
34
 
34
- import { ActionHandler, actionHandlers, registerAction, unregisterAction } from './dispatcher';
35
- export type { ActionHandler };
36
- export { registerAction, unregisterAction };
35
+ import {
36
+ ActionHandler,
37
+ GlobalActionHandler,
38
+ actionHandlers,
39
+ globalActionHandlers,
40
+ registerAction,
41
+ registerActionHandler,
42
+ unregisterAction,
43
+ } from './dispatcher';
44
+ export type { ActionHandler, GlobalActionHandler };
45
+ export { registerAction, registerActionHandler, unregisterAction };
46
+ export * from './hooks';
47
+ export * from './jsx';
48
+ export * from './preview';
49
+ import { renderToWidget } from './jsx';
37
50
 
38
51
  // Tự động lắng nghe action event từ Native để dispatch tới các hàm TypeScript đã đăng ký
39
52
  if (liveActivityEmitter) {
@@ -48,6 +61,13 @@ if (liveActivityEmitter) {
48
61
  console.warn(`[react-native-live-widgets] Error executing action '${actionId}':`, e);
49
62
  }
50
63
  }
64
+ for (const globalHandler of globalActionHandlers) {
65
+ try {
66
+ await globalHandler(actionId, { actionId, activityId });
67
+ } catch (e) {
68
+ console.warn(`[react-native-live-widgets] Error in global action handler for '${actionId}':`, e);
69
+ }
70
+ }
51
71
  });
52
72
  }
53
73
 
@@ -60,7 +80,11 @@ export const LiveActivity = {
60
80
  start: async (options: StartActivityOptions): Promise<boolean> => {
61
81
  if (!LiveActivityModule?.start) return false;
62
82
  try {
63
- const payload = JSON.stringify(options);
83
+ const opts = { ...options } as any;
84
+ if (React.isValidElement(opts.lockScreen)) {
85
+ opts.lockScreen = renderToWidget(opts.lockScreen);
86
+ }
87
+ const payload = JSON.stringify(opts);
64
88
  return await LiveActivityModule.start(options.activityId, payload);
65
89
  } catch (error) {
66
90
  console.warn('[react-native-live-widgets] start error:', error);
@@ -74,7 +98,11 @@ export const LiveActivity = {
74
98
  update: async (options: UpdateActivityOptions): Promise<boolean> => {
75
99
  if (!LiveActivityModule?.update) return false;
76
100
  try {
77
- const payload = JSON.stringify(options);
101
+ const opts = { ...options } as any;
102
+ if (React.isValidElement(opts.lockScreen)) {
103
+ opts.lockScreen = renderToWidget(opts.lockScreen);
104
+ }
105
+ const payload = JSON.stringify(opts);
78
106
  return await LiveActivityModule.update(options.activityId, payload);
79
107
  } catch (error) {
80
108
  console.warn('[react-native-live-widgets] update error:', error);
@@ -249,6 +277,14 @@ export const LiveActivity = {
249
277
  };
250
278
  },
251
279
 
280
+ /**
281
+ * Đăng ký hàm lắng nghe toàn cục tất cả các sự kiện bấm nút từ Live Activity hoặc Widget.
282
+ * Nhận `(actionId, payload)`. Trả về hàm hủy đăng ký (unsubscribe).
283
+ */
284
+ registerActionHandler: (handler: GlobalActionHandler): (() => void) => {
285
+ return registerActionHandler(handler);
286
+ },
287
+
252
288
  /**
253
289
  * Hủy đăng ký action handler theo `actionId`.
254
290
  */
@@ -346,6 +382,13 @@ export const LiveActivity = {
346
382
  if (registered) {
347
383
  await registered({ actionId, activityId });
348
384
  }
385
+ for (const globalHandler of globalActionHandlers) {
386
+ try {
387
+ await globalHandler(actionId, { actionId, activityId });
388
+ } catch (e) {
389
+ console.warn('[react-native-live-widgets] background globalHandler error:', e);
390
+ }
391
+ }
349
392
  }
350
393
  );
351
394
  } catch (e) {
@@ -386,15 +429,53 @@ export const Widget = {
386
429
 
387
430
  /**
388
431
  * Thiết lập layout động cho Home Screen Widget (hỗ trợ small, medium, large).
389
- * Tự động lưu vào Shared Storage và yêu cầu vẽ lại.
432
+ * Hỗ trợ gọi 2 hoặc 3 tham số:
433
+ * - `Widget.setLayout('main', layoutConfig, appGroup?)`
434
+ * - `Widget.setLayout(layoutConfig, appGroup?)` (tự động gán widgetKey = 'main')
435
+ * Tự động lưu vào Shared Storage và yêu cầu OS vẽ lại.
390
436
  */
391
437
  setLayout: async (
392
- widgetKey: string,
393
- layoutConfig: WidgetLayoutConfig,
394
- appGroup?: string
438
+ widgetKeyOrConfig: string | WidgetLayoutConfig,
439
+ layoutConfigOrAppGroup?: WidgetLayoutConfig | string,
440
+ maybeAppGroup?: string
395
441
  ): Promise<boolean> => {
396
442
  try {
397
- const saved = await SharedStorage.set(`widget_layout_${widgetKey}`, layoutConfig, appGroup);
443
+ let widgetKey = 'main';
444
+ let layoutConfig: WidgetLayoutConfig;
445
+ let appGroup: string | undefined;
446
+
447
+ if (typeof widgetKeyOrConfig === 'string') {
448
+ widgetKey = widgetKeyOrConfig;
449
+ layoutConfig = layoutConfigOrAppGroup as WidgetLayoutConfig;
450
+ appGroup = maybeAppGroup;
451
+ } else {
452
+ layoutConfig = widgetKeyOrConfig;
453
+ appGroup = typeof layoutConfigOrAppGroup === 'string' ? layoutConfigOrAppGroup : undefined;
454
+ }
455
+
456
+ let finalLayout: any = layoutConfig;
457
+ const convertIfJsx = (node: any) => {
458
+ if (!node) return node;
459
+ if (React.isValidElement(node) || (node as any)?.$$typeof || typeof (node as any)?.type === 'function') {
460
+ return renderToWidget(node);
461
+ }
462
+ return node;
463
+ };
464
+
465
+ if (React.isValidElement(finalLayout) || (finalLayout as any)?.$$typeof || typeof (finalLayout as any)?.type === 'function') {
466
+ finalLayout = { medium: renderToWidget(finalLayout) };
467
+ } else if (finalLayout && typeof finalLayout === 'object') {
468
+ const c = { ...finalLayout };
469
+ c.small = convertIfJsx(c.small);
470
+ c.medium = convertIfJsx(c.medium);
471
+ c.large = convertIfJsx(c.large);
472
+ c.accessoryRectangular = convertIfJsx(c.accessoryRectangular);
473
+ c.accessoryCircular = convertIfJsx(c.accessoryCircular);
474
+ c.accessoryInline = convertIfJsx(c.accessoryInline);
475
+ finalLayout = c;
476
+ }
477
+
478
+ const saved = await SharedStorage.set(`widget_layout_${widgetKey}`, finalLayout, appGroup);
398
479
  if (!saved) return false;
399
480
  return await Widget.reloadAll();
400
481
  } catch (error) {
@@ -403,6 +484,17 @@ export const Widget = {
403
484
  }
404
485
  },
405
486
 
487
+ /**
488
+ * Cập nhật layout động cho Widget (Alias tiện ích cho `Widget.setLayout`).
489
+ */
490
+ update: async (
491
+ widgetKeyOrConfig: string | WidgetLayoutConfig,
492
+ layoutConfigOrAppGroup?: WidgetLayoutConfig | string,
493
+ maybeAppGroup?: string
494
+ ): Promise<boolean> => {
495
+ return (Widget.setLayout as any)(widgetKeyOrConfig, layoutConfigOrAppGroup, maybeAppGroup);
496
+ },
497
+
406
498
  /**
407
499
  * Thiết lập dòng thời gian tự động (Timeline Entries) cho Widget.
408
500
  * Hệ điều hành iOS/Android sẽ tự động chuyển đổi giữa các layout theo từng mốc thời gian
@@ -490,13 +582,36 @@ export const Widget = {
490
582
  * Cấu hình Endpoint API để bản thân Widget Extension tự chạy ngầm lấy dữ liệu mới
491
583
  * theo chu kỳ (`getTimeline`) hoặc khi bấm nút `actionId: 'refresh'` trên mặt Widget,
492
584
  * kể cả khi người dùng đã vuốt tắt (Kill) hoàn toàn ứng dụng chính!
585
+ *
586
+ * Hỗ trợ gọi linh hoạt:
587
+ * - `Widget.setRemoteConfig('main', { url, refreshIntervalMinutes }, appGroup?)`
588
+ * - `Widget.setRemoteConfig({ url, intervalMinutes }, appGroup?)` (tự động gán widgetKey = 'main')
493
589
  */
494
590
  setRemoteConfig: async (
495
- widgetKey: string,
496
- remoteConfig: WidgetRemoteConfig,
497
- appGroup?: string
591
+ widgetKeyOrConfig: string | WidgetRemoteConfig,
592
+ remoteConfigOrAppGroup?: WidgetRemoteConfig | string,
593
+ maybeAppGroup?: string
498
594
  ): Promise<boolean> => {
499
595
  try {
596
+ let widgetKey = 'main';
597
+ let remoteConfig: WidgetRemoteConfig;
598
+ let appGroup: string | undefined;
599
+
600
+ if (typeof widgetKeyOrConfig === 'string') {
601
+ widgetKey = widgetKeyOrConfig;
602
+ remoteConfig = remoteConfigOrAppGroup as WidgetRemoteConfig;
603
+ appGroup = maybeAppGroup;
604
+ } else {
605
+ remoteConfig = widgetKeyOrConfig;
606
+ appGroup = typeof remoteConfigOrAppGroup === 'string' ? remoteConfigOrAppGroup : undefined;
607
+ }
608
+
609
+ if (remoteConfig.intervalMinutes !== undefined && remoteConfig.refreshIntervalMinutes === undefined) {
610
+ remoteConfig.refreshIntervalMinutes = remoteConfig.intervalMinutes;
611
+ } else if (remoteConfig.refreshIntervalMinutes !== undefined && remoteConfig.intervalMinutes === undefined) {
612
+ remoteConfig.intervalMinutes = remoteConfig.refreshIntervalMinutes;
613
+ }
614
+
500
615
  const saved = await SharedStorage.set(
501
616
  `widget_remote_config_${widgetKey}`,
502
617
  remoteConfig,
@@ -510,6 +625,15 @@ export const Widget = {
510
625
  }
511
626
  },
512
627
 
628
+ /** Đăng ký lắng nghe tương tác nút bấm từ Widget theo `actionId` */
629
+ registerAction: registerAction,
630
+
631
+ /** Đăng ký lắng nghe toàn cục tất cả tương tác nút bấm từ Widget (alias) */
632
+ onWidgetAction: registerActionHandler,
633
+
634
+ /** Đăng ký lắng nghe toàn cục tất cả tương tác nút bấm từ Widget */
635
+ registerActionHandler: registerActionHandler,
636
+
513
637
  /**
514
638
  * (Android 8.0+) Mở hộp thoại hệ thống cho phép người dùng ghim trực tiếp Tiện ích ra màn hình chính ngay từ trong ứng dụng.
515
639
  * Trên iOS, hàm trả về false vì Apple chỉ cho phép người dùng tự thêm tiện ích từ thư viện Widget của hệ điều hành.