react-native-live-widgets 0.0.0-stage → 1.1.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 (65) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/LICENSE +21 -0
  3. package/README.md +367 -2
  4. package/android/build.gradle +49 -0
  5. package/android/src/main/AndroidManifest.xml +38 -0
  6. package/android/src/main/java/com/reactnativeliveactivity/bridge/LiveActivityModule.kt +441 -0
  7. package/android/src/main/java/com/reactnativeliveactivity/bridge/LiveActivityPackage.kt +17 -0
  8. package/android/src/main/java/com/reactnativeliveactivity/liveactivity/LiveActivityHeadlessTaskService.kt +24 -0
  9. package/android/src/main/java/com/reactnativeliveactivity/liveactivity/LiveActivityNotifier.kt +410 -0
  10. package/android/src/main/java/com/reactnativeliveactivity/liveactivity/LiveActivityReceiver.kt +67 -0
  11. package/android/src/main/java/com/reactnativeliveactivity/renderer/DynamicNodeRegistry.kt +64 -0
  12. package/android/src/main/java/com/reactnativeliveactivity/renderer/DynamicWidgetCanvasRenderer.kt +1223 -0
  13. package/android/src/main/java/com/reactnativeliveactivity/storage/DynamicWidgetImageCache.kt +120 -0
  14. package/android/src/main/java/com/reactnativeliveactivity/storage/DynamicWidgetStateStore.kt +281 -0
  15. package/android/src/main/java/com/reactnativeliveactivity/widgets/DynamicHomeScreenWidgetProvider.kt +229 -0
  16. package/android/src/main/res/layout/rn_live_widget_host.xml +113 -0
  17. package/android/src/main/res/xml/rn_live_widget_info.xml +14 -0
  18. package/app.plugin.js +114 -0
  19. package/assets/cross_platform_parity.png +0 -0
  20. package/assets/dashboard_features.png +0 -0
  21. package/assets/donate_qr.png +0 -0
  22. package/assets/dynamic_island_expanded.png +0 -0
  23. package/assets/home_widget_interactive.png +0 -0
  24. package/assets/lock_screen_live_activity.png +0 -0
  25. package/cli/setup.js +491 -0
  26. package/docs/EXPO-GUIDE-EN.md +405 -0
  27. package/docs/EXPO-GUIDE-VI.md +427 -0
  28. package/docs/GUIDE-EN.md +847 -0
  29. package/docs/GUIDE-VI.md +845 -0
  30. package/docs/widgets.md +52 -0
  31. package/ios/Bridge/LiveActivityModule.m +105 -0
  32. package/ios/Bridge/LiveActivityModule.swift +957 -0
  33. package/ios/Intents/DynamicWidgetActionIntent.swift +38 -0
  34. package/ios/Models/DynamicActivityAttributes.swift +22 -0
  35. package/ios/Models/DynamicLayoutModels.swift +243 -0
  36. package/ios/Renderer/ColorHexExtension.swift +49 -0
  37. package/ios/Renderer/DynamicNodeRegistry.swift +54 -0
  38. package/ios/Renderer/DynamicNodeView.swift +1060 -0
  39. package/ios/Storage/DynamicWidgetImageCache.swift +137 -0
  40. package/ios/Storage/DynamicWidgetStateStore.swift +162 -0
  41. package/ios/Widgets/DynamicHomeScreenWidget.swift +435 -0
  42. package/ios/Widgets/DynamicLiveActivityWidget.swift +79 -0
  43. package/lib/builder.d.ts +60 -0
  44. package/lib/builder.d.ts.map +1 -0
  45. package/lib/builder.js +292 -0
  46. package/lib/builder.js.map +1 -0
  47. package/lib/dispatcher.d.ts +16 -0
  48. package/lib/dispatcher.d.ts.map +1 -0
  49. package/lib/dispatcher.js +18 -0
  50. package/lib/dispatcher.js.map +1 -0
  51. package/lib/index.d.ts +199 -0
  52. package/lib/index.d.ts.map +1 -0
  53. package/lib/index.js +621 -0
  54. package/lib/index.js.map +1 -0
  55. package/lib/types.d.ts +489 -0
  56. package/lib/types.d.ts.map +1 -0
  57. package/lib/types.js +9 -0
  58. package/lib/types.js.map +1 -0
  59. package/package.json +85 -4
  60. package/react-native-live-widgets.podspec +38 -0
  61. package/src/builder.ts +409 -0
  62. package/src/dispatcher.ts +25 -0
  63. package/src/index.ts +689 -0
  64. package/src/react-native-env.d.ts +29 -0
  65. package/src/types.ts +595 -0
package/src/index.ts ADDED
@@ -0,0 +1,689 @@
1
+ import { AppRegistry, NativeEventEmitter, NativeModules, Platform } from 'react-native';
2
+ import {
3
+ ActiveActivityInfo,
4
+ EndActivityOptions,
5
+ LiveActivityPushTokens,
6
+ StartActivityOptions,
7
+ UpdateActivityOptions,
8
+ WidgetConfigOption,
9
+ WidgetLayoutConfig,
10
+ WidgetRemoteConfig,
11
+ WidgetTimelineConfig,
12
+ } from './types';
13
+
14
+ declare const __DEV__: boolean | undefined;
15
+
16
+ const { LiveActivityModule } = NativeModules;
17
+
18
+ if (!LiveActivityModule && typeof __DEV__ !== 'undefined' && __DEV__) {
19
+ console.warn(
20
+ '[react-native-live-widgets] Native module not found. ' +
21
+ 'Please ensure you have run "npx react-native-live-widgets init" and re-compiled your app.'
22
+ );
23
+ }
24
+
25
+ const liveActivityEmitter = LiveActivityModule
26
+ ? new NativeEventEmitter(LiveActivityModule)
27
+ : null;
28
+
29
+ const DEVICE_TOKEN_CHANGED_EVENT = 'DevicePushTokenChanged';
30
+ const TOKEN_CHANGED_EVENT = 'LiveActivityTokenChanged';
31
+ const UPDATE_TOKEN_CHANGED_EVENT = 'LiveActivityUpdateTokenChanged';
32
+ const ACTION_CLICKED_EVENT = 'LiveActivityActionClicked';
33
+
34
+ import { ActionHandler, actionHandlers, registerAction, unregisterAction } from './dispatcher';
35
+ export type { ActionHandler };
36
+ export { registerAction, unregisterAction };
37
+
38
+ // Tự động lắng nghe action event từ Native để dispatch tới các hàm TypeScript đã đăng ký
39
+ if (liveActivityEmitter) {
40
+ liveActivityEmitter.addListener(ACTION_CLICKED_EVENT, async (event: any) => {
41
+ const actionId = event?.actionId || '';
42
+ const activityId = event?.activityId || '';
43
+ const handler = actionHandlers.get(actionId);
44
+ if (handler) {
45
+ try {
46
+ await handler({ actionId, activityId });
47
+ } catch (e) {
48
+ console.warn(`[react-native-live-widgets] Error executing action '${actionId}':`, e);
49
+ }
50
+ }
51
+ });
52
+ }
53
+
54
+ // ─── 1. LIVE ACTIVITY & LIVE UPDATE ──────────────────────────────────────────
55
+
56
+ export const LiveActivity = {
57
+ /**
58
+ * Khởi động một Live Activity (iOS) hoặc Live Update / Ongoing Notification (Android).
59
+ */
60
+ start: async (options: StartActivityOptions): Promise<boolean> => {
61
+ if (!LiveActivityModule?.start) return false;
62
+ try {
63
+ const payload = JSON.stringify(options);
64
+ return await LiveActivityModule.start(options.activityId, payload);
65
+ } catch (error) {
66
+ console.warn('[react-native-live-widgets] start error:', error);
67
+ return false;
68
+ }
69
+ },
70
+
71
+ /**
72
+ * Cập nhật nội dung Live Activity hiện tại.
73
+ */
74
+ update: async (options: UpdateActivityOptions): Promise<boolean> => {
75
+ if (!LiveActivityModule?.update) return false;
76
+ try {
77
+ const payload = JSON.stringify(options);
78
+ return await LiveActivityModule.update(options.activityId, payload);
79
+ } catch (error) {
80
+ console.warn('[react-native-live-widgets] update error:', error);
81
+ return false;
82
+ }
83
+ },
84
+
85
+ /**
86
+ * Kết thúc một Live Activity cụ thể theo activityId với các chính sách linh hoạt (Dismissal Policy & Final Summary Layout).
87
+ */
88
+ end: async (activityId: string, options?: EndActivityOptions): Promise<boolean> => {
89
+ try {
90
+ if (options && (LiveActivityModule?.endWithOptions || LiveActivityModule?.endActivity)) {
91
+ const payloadJson = options.finalLockScreen || options.finalDynamicIsland
92
+ ? JSON.stringify({
93
+ activityId,
94
+ lockScreen: options.finalLockScreen,
95
+ dynamicIsland: options.finalDynamicIsland,
96
+ })
97
+ : null;
98
+ const nativeOptions = {
99
+ dismissalPolicy: options.dismissalPolicy || 'immediate',
100
+ dismissalAfterSeconds: options.dismissalAfterSeconds ?? 900,
101
+ finalPayloadJson: payloadJson,
102
+ };
103
+ const endFn = LiveActivityModule.endWithOptions || LiveActivityModule.endActivity;
104
+ return await endFn.call(LiveActivityModule, activityId, nativeOptions);
105
+ }
106
+ if (LiveActivityModule?.end) {
107
+ return await LiveActivityModule.end(activityId);
108
+ }
109
+ return false;
110
+ } catch (error) {
111
+ console.warn('[react-native-live-widgets] end error:', error);
112
+ return false;
113
+ }
114
+ },
115
+
116
+ /**
117
+ * Tắt tất cả Live Activity / Live Update của ứng dụng.
118
+ */
119
+ endAll: async (): Promise<boolean> => {
120
+ if (!LiveActivityModule?.endAll) return false;
121
+ try {
122
+ return await LiveActivityModule.endAll();
123
+ } catch (error) {
124
+ console.warn('[react-native-live-widgets] endAll error:', error);
125
+ return false;
126
+ }
127
+ },
128
+
129
+ /**
130
+ * Đăng ký và lấy Push Token của thiết bị (APNs Device Token trên iOS / FCM Device Token trên Android).
131
+ */
132
+ getDevicePushToken: async (): Promise<string | undefined> => {
133
+ if (!LiveActivityModule?.getDevicePushToken) {
134
+ return undefined;
135
+ }
136
+ try {
137
+ const token = await LiveActivityModule.getDevicePushToken();
138
+ return token || undefined;
139
+ } catch {
140
+ return undefined;
141
+ }
142
+ },
143
+
144
+ /**
145
+ * Lấy Push-to-Start token để backend kích hoạt mở mới Live Activity / Live Update từ xa.
146
+ */
147
+ getPushToStartToken: async (): Promise<string | undefined> => {
148
+ if (!LiveActivityModule?.getPushToStartToken) {
149
+ return undefined;
150
+ }
151
+ try {
152
+ const token = await LiveActivityModule.getPushToStartToken();
153
+ return token || undefined;
154
+ } catch {
155
+ return undefined;
156
+ }
157
+ },
158
+
159
+ /**
160
+ * Lấy Update Push Token của một phiên Live Activity / Live Update đang chạy (theo activityId)
161
+ * để backend gửi bản cập nhật ("event": "update") hoặc kết thúc ("event": "end").
162
+ */
163
+ getActivityPushToken: async (activityId: string): Promise<string | undefined> => {
164
+ if (!LiveActivityModule?.getActivityPushToken) {
165
+ return undefined;
166
+ }
167
+ try {
168
+ const token = await LiveActivityModule.getActivityPushToken(activityId);
169
+ return token || undefined;
170
+ } catch {
171
+ return undefined;
172
+ }
173
+ },
174
+
175
+ /**
176
+ * Lấy trọn bộ cả 3 loại Push Token trong 1 lần gọi (hỗ trợ cả iOS APNs & Android):
177
+ * - `devicePushToken`: Token của máy
178
+ * - `pushToStartToken`: Token mở mới Live Activity / Live Update từ xa
179
+ * - `activityUpdateToken`: Token cập nhật phiên Live Activity đang chạy
180
+ */
181
+ getAllPushTokens: async (activityId?: string): Promise<LiveActivityPushTokens> => {
182
+ const empty: LiveActivityPushTokens = {
183
+ devicePushToken: null,
184
+ pushToStartToken: null,
185
+ activityUpdateToken: null,
186
+ allActivityUpdateTokens: {},
187
+ };
188
+ if (!LiveActivityModule?.getAllPushTokens) {
189
+ return empty;
190
+ }
191
+ try {
192
+ const res = await LiveActivityModule.getAllPushTokens(activityId || '');
193
+ return {
194
+ devicePushToken: res?.devicePushToken || null,
195
+ pushToStartToken: res?.pushToStartToken || null,
196
+ activityUpdateToken: res?.activityUpdateToken || null,
197
+ allActivityUpdateTokens: res?.allActivityUpdateTokens || {},
198
+ };
199
+ } catch {
200
+ return empty;
201
+ }
202
+ },
203
+
204
+ /**
205
+ * Lắng nghe khi hệ điều hành cấp mới hoặc thay đổi Device Push Token của máy.
206
+ */
207
+ onDevicePushTokenChange: (listener: (token: string) => void): (() => void) => {
208
+ if (!liveActivityEmitter) return () => {};
209
+ const sub = liveActivityEmitter.addListener(DEVICE_TOKEN_CHANGED_EVENT, (token: any) => {
210
+ listener(typeof token === 'string' ? token : String(token ?? ''));
211
+ });
212
+ return () => sub.remove();
213
+ },
214
+
215
+ /**
216
+ * Lắng nghe khi hệ điều hành cấp hoặc xoay Push-to-Start Token mới.
217
+ */
218
+ onPushToStartTokenChange: (listener: (token: string) => void): (() => void) => {
219
+ if (!liveActivityEmitter) return () => {};
220
+ const sub = liveActivityEmitter.addListener(TOKEN_CHANGED_EVENT, (token: any) => {
221
+ listener(typeof token === 'string' ? token : String(token ?? ''));
222
+ });
223
+ return () => sub.remove();
224
+ },
225
+
226
+ /**
227
+ * Lắng nghe khi hệ điều hành cấp hoặc xoay Update Token cho một Live Activity cụ thể.
228
+ * Trả về `{ activityId, token }` để gửi ngay lên Backend.
229
+ */
230
+ onActivityUpdateTokenChange: (
231
+ listener: (event: { activityId: string; token: string }) => void
232
+ ): (() => void) => {
233
+ if (!liveActivityEmitter) return () => {};
234
+ const sub = liveActivityEmitter.addListener(UPDATE_TOKEN_CHANGED_EVENT, (event: any) => {
235
+ listener(event as { activityId: string; token: string });
236
+ });
237
+ return () => sub.remove();
238
+ },
239
+
240
+ /**
241
+ * Đă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.
242
+ * Hoạt động mượt mà cả khi App đang mở lẫn chạy ngầm.
243
+ * Trả về hàm hủy đăng ký (unsubscribe).
244
+ */
245
+ registerAction: (actionId: string, handler: ActionHandler): (() => void) => {
246
+ actionHandlers.set(actionId, handler);
247
+ return () => {
248
+ actionHandlers.delete(actionId);
249
+ };
250
+ },
251
+
252
+ /**
253
+ * Hủy đăng ký action handler theo `actionId`.
254
+ */
255
+ unregisterAction: (actionId: string): void => {
256
+ actionHandlers.delete(actionId);
257
+ },
258
+
259
+ /**
260
+ * Lấy danh sách các phiên Live Activity đang chạy trên thiết bị (ID và Push Token).
261
+ * Giúp ứng dụng khôi phục lại trạng thái giao diện khi mở lại App.
262
+ */
263
+ getActiveActivities: async (): Promise<ActiveActivityInfo[]> => {
264
+ if (!LiveActivityModule?.getActiveActivities) {
265
+ return [];
266
+ }
267
+ try {
268
+ const list = await LiveActivityModule.getActiveActivities();
269
+ return (list || []).map((item: any) => ({
270
+ activityId: item.activityId || '',
271
+ pushToken: item.pushToken,
272
+ }));
273
+ } catch (e) {
274
+ console.warn('[react-native-live-widgets] getActiveActivities error:', e);
275
+ return [];
276
+ }
277
+ },
278
+
279
+ /**
280
+ * Kiểm tra xem người dùng có cấp quyền Hoạt động trực tiếp (Live Activities) trong Cài đặt máy hay không.
281
+ */
282
+ areActivitiesEnabled: async (): Promise<boolean> => {
283
+ if (!LiveActivityModule?.areActivitiesEnabled) {
284
+ return false;
285
+ }
286
+ try {
287
+ return await LiveActivityModule.areActivitiesEnabled();
288
+ } catch {
289
+ return false;
290
+ }
291
+ },
292
+
293
+ /**
294
+ * iOS 16.2+: Kiểm tra xem người dùng có bật tùy chọn nhận cập nhật đẩy APNs tần suất cao (Frequent Pushes) hay không.
295
+ */
296
+ areFrequentPushesEnabled: async (): Promise<boolean> => {
297
+ if (!LiveActivityModule?.areFrequentPushesEnabled) {
298
+ return false;
299
+ }
300
+ try {
301
+ return await LiveActivityModule.areFrequentPushesEnabled();
302
+ } catch {
303
+ return false;
304
+ }
305
+ },
306
+
307
+ /**
308
+ * Lắng nghe khi người dùng bấm vào một Action Button.
309
+ */
310
+ onActionClicked: (listener: (actionId: string, activityId: string) => void): (() => void) => {
311
+ if (!liveActivityEmitter) return () => {};
312
+ const sub = liveActivityEmitter.addListener(ACTION_CLICKED_EVENT, (event: any) => {
313
+ listener(event.actionId, event.activityId);
314
+ });
315
+ return () => sub.remove();
316
+ },
317
+
318
+ /**
319
+ * Android 16+: Kiểm tra quyền Promoted Ongoing Notifications.
320
+ */
321
+ canPostPromoted: async (): Promise<boolean> => {
322
+ if (Platform.OS !== 'android' || !LiveActivityModule?.canPostPromoted) {
323
+ return false;
324
+ }
325
+ return await LiveActivityModule.canPostPromoted();
326
+ },
327
+
328
+ /**
329
+ * Đăng ký tác vụ chạy ngầm xử lý tương tác nút bấm trên Widget (Headless JS / Background Action Task).
330
+ * Hoạt động ngay cả khi App chính đã bị người dùng vuốt đóng (Killed).
331
+ */
332
+ registerBackgroundActionHandler: (
333
+ handler?: (actionId: string, activityId?: string) => Promise<void> | void
334
+ ) => {
335
+ if (Platform.OS === 'android') {
336
+ try {
337
+ AppRegistry.registerHeadlessTask(
338
+ 'LiveActivityBackgroundTask',
339
+ () => async (taskData: any) => {
340
+ const actionId = taskData?.actionId || '';
341
+ const activityId = taskData?.activityId || '';
342
+ if (handler) {
343
+ await handler(actionId, activityId);
344
+ }
345
+ const registered = actionHandlers.get(actionId);
346
+ if (registered) {
347
+ await registered({ actionId, activityId });
348
+ }
349
+ }
350
+ );
351
+ } catch (e) {
352
+ console.warn('[react-native-live-widgets] registerHeadlessTask warning:', e);
353
+ }
354
+ }
355
+ },
356
+ };
357
+
358
+ // ─── 2. HOME SCREEN WIDGETS ──────────────────────────────────────────────────
359
+
360
+ export const Widget = {
361
+ /**
362
+ * Yêu cầu hệ điều hành iOS và Android vẽ lại toàn bộ Home Screen Widgets ngay lập tức.
363
+ */
364
+ reloadAll: async (): Promise<boolean> => {
365
+ if (!LiveActivityModule?.reloadAllWidgets) return false;
366
+ try {
367
+ return await LiveActivityModule.reloadAllWidgets();
368
+ } catch (error) {
369
+ console.warn('[react-native-live-widgets] reloadAll error:', error);
370
+ return false;
371
+ }
372
+ },
373
+
374
+ /**
375
+ * Yêu cầu vẽ lại một Widget cụ thể theo kind (hỗ trợ cả iOS và Android).
376
+ */
377
+ reload: async (kind: string): Promise<boolean> => {
378
+ if (!LiveActivityModule?.reloadWidget) return false;
379
+ try {
380
+ return await LiveActivityModule.reloadWidget(kind);
381
+ } catch (error) {
382
+ console.warn('[react-native-live-widgets] reload error:', error);
383
+ return false;
384
+ }
385
+ },
386
+
387
+ /**
388
+ * 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.
390
+ */
391
+ setLayout: async (
392
+ widgetKey: string,
393
+ layoutConfig: WidgetLayoutConfig,
394
+ appGroup?: string
395
+ ): Promise<boolean> => {
396
+ try {
397
+ const saved = await SharedStorage.set(`widget_layout_${widgetKey}`, layoutConfig, appGroup);
398
+ if (!saved) return false;
399
+ return await Widget.reloadAll();
400
+ } catch (error) {
401
+ console.warn('[react-native-live-widgets] setLayout error:', error);
402
+ return false;
403
+ }
404
+ },
405
+
406
+ /**
407
+ * Thiết lập dòng thời gian tự động (Timeline Entries) cho Widget.
408
+ * 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
409
+ * mà KHÔNG tốn pin, không cần ứng dụng mở hay chạy ngầm.
410
+ */
411
+ setTimeline: async (
412
+ widgetKey: string,
413
+ timelineConfig: WidgetTimelineConfig,
414
+ appGroup?: string
415
+ ): Promise<boolean> => {
416
+ try {
417
+ const formattedEntries = timelineConfig.entries.map((entry) => ({
418
+ date:
419
+ typeof entry.date === 'string'
420
+ ? new Date(entry.date).getTime() / 1000.0
421
+ : entry.date > 10000000000
422
+ ? entry.date / 1000.0
423
+ : entry.date,
424
+ layout: entry.layout,
425
+ }));
426
+ const formattedConfig = {
427
+ entries: formattedEntries,
428
+ policy: timelineConfig.policy || 'atEnd',
429
+ afterDate: timelineConfig.afterDate
430
+ ? typeof timelineConfig.afterDate === 'string'
431
+ ? new Date(timelineConfig.afterDate).getTime() / 1000.0
432
+ : timelineConfig.afterDate > 10000000000
433
+ ? timelineConfig.afterDate / 1000.0
434
+ : timelineConfig.afterDate
435
+ : undefined,
436
+ };
437
+ const saved = await SharedStorage.set(
438
+ `widget_timeline_${widgetKey}`,
439
+ formattedConfig,
440
+ appGroup
441
+ );
442
+ if (!saved) return false;
443
+ return await Widget.reloadAll();
444
+ } catch (error) {
445
+ console.warn('[react-native-live-widgets] setTimeline error:', error);
446
+ return false;
447
+ }
448
+ },
449
+
450
+ /**
451
+ * Cung cấp danh sách các tùy chọn cấu hình cho Widget (dành cho tính năng Edit Widget / AppIntent Configuration).
452
+ * Ví dụ: Danh sách các Dự án, Chi nhánh, Ca làm để người dùng chọn khi nhấn giữ Widget ngoài Home Screen.
453
+ */
454
+ setConfigurationOptions: async (
455
+ widgetKey: string,
456
+ options: WidgetConfigOption[],
457
+ appGroup?: string
458
+ ): Promise<boolean> => {
459
+ return await SharedStorage.set(`widget_config_options_${widgetKey}`, options, appGroup);
460
+ },
461
+
462
+ /**
463
+ * Lấy ID tùy chọn cấu hình đang được người dùng chọn ghim trên Widget.
464
+ */
465
+ getSelectedConfiguration: async (
466
+ widgetKey: string,
467
+ appGroup?: string
468
+ ): Promise<string | null> => {
469
+ return await SharedStorage.get<string>(`widget_selected_config_${widgetKey}`, appGroup);
470
+ },
471
+
472
+ /**
473
+ * Thiết lập lựa chọn cấu hình cho Widget từ trong ứng dụng.
474
+ */
475
+ setSelectedConfiguration: async (
476
+ widgetKey: string,
477
+ selectedId: string,
478
+ appGroup?: string
479
+ ): Promise<boolean> => {
480
+ const ok = await SharedStorage.set(
481
+ `widget_selected_config_${widgetKey}`,
482
+ selectedId,
483
+ appGroup
484
+ );
485
+ await Widget.reloadAll();
486
+ return ok;
487
+ },
488
+
489
+ /**
490
+ * 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
+ * theo chu kỳ (`getTimeline`) hoặc khi bấm nút `actionId: 'refresh'` trên mặt Widget,
492
+ * kể cả khi người dùng đã vuốt tắt (Kill) hoàn toàn ứng dụng chính!
493
+ */
494
+ setRemoteConfig: async (
495
+ widgetKey: string,
496
+ remoteConfig: WidgetRemoteConfig,
497
+ appGroup?: string
498
+ ): Promise<boolean> => {
499
+ try {
500
+ const saved = await SharedStorage.set(
501
+ `widget_remote_config_${widgetKey}`,
502
+ remoteConfig,
503
+ appGroup
504
+ );
505
+ if (!saved) return false;
506
+ return await Widget.reloadAll();
507
+ } catch (error) {
508
+ console.warn('[react-native-live-widgets] setRemoteConfig error:', error);
509
+ return false;
510
+ }
511
+ },
512
+
513
+ /**
514
+ * (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
+ * 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.
516
+ */
517
+ requestPin: async (): Promise<boolean> => {
518
+ if (!LiveActivityModule?.requestPinWidget) return false;
519
+ try {
520
+ return await LiveActivityModule.requestPinWidget();
521
+ } catch (error) {
522
+ console.warn('[react-native-live-widgets] Widget.requestPin error:', error);
523
+ return false;
524
+ }
525
+ },
526
+
527
+ /**
528
+ * Kiểm tra xem thiết bị hiện tại có hỗ trợ ghim Tiện ích trực tiếp từ trong ứng dụng hay không (Chỉ Android API 26+).
529
+ */
530
+ isPinSupported: async (): Promise<boolean> => {
531
+ if (!LiveActivityModule?.isRequestPinWidgetSupported) return false;
532
+ try {
533
+ return await LiveActivityModule.isRequestPinWidgetSupported();
534
+ } catch {
535
+ return false;
536
+ }
537
+ },
538
+ };
539
+
540
+ // ─── 3. SHARED STORAGE (App Groups & SharedPreferences) ─────────────────────
541
+
542
+ export const SharedStorage = {
543
+ /**
544
+ * Lưu dữ liệu vào App Group (iOS) hoặc SharedPreferences (Android) để Widget đọc.
545
+ */
546
+ set: async (key: string, value: any, appGroup?: string): Promise<boolean> => {
547
+ if (!LiveActivityModule?.setSharedItem) return false;
548
+ try {
549
+ const stringValue = typeof value === 'string' ? value : JSON.stringify(value);
550
+ return await LiveActivityModule.setSharedItem(key, stringValue, appGroup || '');
551
+ } catch (error) {
552
+ console.warn('[react-native-live-widgets] SharedStorage.set error:', error);
553
+ return false;
554
+ }
555
+ },
556
+
557
+ /**
558
+ * Đọc dữ liệu từ App Group hoặc SharedPreferences.
559
+ */
560
+ get: async <T = any>(key: string, appGroup?: string): Promise<T | null> => {
561
+ if (!LiveActivityModule?.getSharedItem) return null;
562
+ try {
563
+ const raw = await LiveActivityModule.getSharedItem(key, appGroup || '');
564
+ if (!raw) return null;
565
+ try {
566
+ return JSON.parse(raw) as T;
567
+ } catch {
568
+ return raw as unknown as T;
569
+ }
570
+ } catch (error) {
571
+ console.warn('[react-native-live-widgets] SharedStorage.get error:', error);
572
+ return null;
573
+ }
574
+ },
575
+
576
+ /**
577
+ * Xóa 1 giá trị theo key.
578
+ */
579
+ remove: async (key: string, appGroup?: string): Promise<boolean> => {
580
+ if (!LiveActivityModule?.removeSharedItem) return false;
581
+ try {
582
+ return await LiveActivityModule.removeSharedItem(key, appGroup || '');
583
+ } catch (error) {
584
+ console.warn('[react-native-live-widgets] SharedStorage.remove error:', error);
585
+ return false;
586
+ }
587
+ },
588
+
589
+ /**
590
+ * Xóa sạch toàn bộ dữ liệu trong App Group.
591
+ */
592
+ clear: async (appGroup?: string): Promise<boolean> => {
593
+ if (!LiveActivityModule?.clearSharedItems) return false;
594
+ try {
595
+ return await LiveActivityModule.clearSharedItems(appGroup || '');
596
+ } catch (error) {
597
+ console.warn('[react-native-live-widgets] SharedStorage.clear error:', error);
598
+ return false;
599
+ }
600
+ },
601
+ };
602
+
603
+ // ─── 4. AUDIO PLAYER (MUSIC PLAYBACK & EQUALIZER TESTING) ────────────────────
604
+
605
+ export interface AudioPlayerStatus {
606
+ isPlaying: boolean;
607
+ currentTime: number;
608
+ duration: number;
609
+ }
610
+
611
+ export interface AudioTrackMetadata {
612
+ title?: string;
613
+ artist?: string;
614
+ artworkUrl?: string;
615
+ duration?: number;
616
+ }
617
+
618
+ export const AudioPlayer = {
619
+ /**
620
+ * Phát nhạc trực tiếp từ URL (hỗ trợ stream mp3, m4a, aac, wav...)
621
+ * và đăng ký hệ thống Now Playing của iOS (hiện trên Dynamic Island & Lock Screen như Spotify).
622
+ */
623
+ play: async (url: string, metadata?: AudioTrackMetadata): Promise<boolean> => {
624
+ if (!LiveActivityModule?.playAudio) return false;
625
+ try {
626
+ return await LiveActivityModule.playAudio(url, metadata || null);
627
+ } catch (error) {
628
+ console.warn('[react-native-live-widgets] AudioPlayer.play error:', error);
629
+ return false;
630
+ }
631
+ },
632
+
633
+ /**
634
+ * Tạm dừng bài nhạc đang phát.
635
+ */
636
+ pause: async (): Promise<boolean> => {
637
+ if (!LiveActivityModule?.pauseAudio) return false;
638
+ try {
639
+ return await LiveActivityModule.pauseAudio();
640
+ } catch (error) {
641
+ console.warn('[react-native-live-widgets] AudioPlayer.pause error:', error);
642
+ return false;
643
+ }
644
+ },
645
+
646
+ /**
647
+ * Tiếp tục phát bài nhạc sau khi tạm dừng.
648
+ */
649
+ resume: async (): Promise<boolean> => {
650
+ if (!LiveActivityModule?.resumeAudio) return false;
651
+ try {
652
+ return await LiveActivityModule.resumeAudio();
653
+ } catch (error) {
654
+ console.warn('[react-native-live-widgets] AudioPlayer.resume error:', error);
655
+ return false;
656
+ }
657
+ },
658
+
659
+ /**
660
+ * Dừng hẳn bài nhạc và giải phóng tài nguyên phát.
661
+ */
662
+ stop: async (): Promise<boolean> => {
663
+ if (!LiveActivityModule?.stopAudio) return false;
664
+ try {
665
+ return await LiveActivityModule.stopAudio();
666
+ } catch (error) {
667
+ console.warn('[react-native-live-widgets] AudioPlayer.stop error:', error);
668
+ return false;
669
+ }
670
+ },
671
+
672
+ /**
673
+ * Lấy trạng thái hiện tại của trình phát nhạc (đang phát, thời lượng, vị trí phát).
674
+ */
675
+ getStatus: async (): Promise<AudioPlayerStatus> => {
676
+ if (!LiveActivityModule?.getAudioStatus) {
677
+ return { isPlaying: false, currentTime: 0, duration: 0 };
678
+ }
679
+ try {
680
+ return await LiveActivityModule.getAudioStatus();
681
+ } catch (error) {
682
+ return { isPlaying: false, currentTime: 0, duration: 0 };
683
+ }
684
+ },
685
+ };
686
+
687
+ export * from './types';
688
+ export * from './builder';
689
+ export { StyleSheet } from './builder';