react-native-live-widgets 1.2.0 → 1.2.2

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 (87) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/README.md +129 -50
  3. package/android/src/main/AndroidManifest.xml +12 -0
  4. package/android/src/main/assets/fonts/MaterialIcons-Regular.ttf +0 -0
  5. package/android/src/main/java/com/reactnativeliveactivity/bridge/LiveActivityModule.kt +61 -1
  6. package/android/src/main/java/com/reactnativeliveactivity/liveactivity/LiveActivityNotifier.kt +153 -17
  7. package/android/src/main/java/com/reactnativeliveactivity/liveactivity/LiveActivityReceiver.kt +1 -1
  8. package/android/src/main/java/com/reactnativeliveactivity/renderer/DynamicWidgetCanvasRenderer.kt +529 -59
  9. package/android/src/main/java/com/reactnativeliveactivity/storage/DynamicWidgetImageCache.kt +53 -0
  10. package/android/src/main/java/com/reactnativeliveactivity/storage/DynamicWidgetStateStore.kt +684 -83
  11. package/android/src/main/java/com/reactnativeliveactivity/widgets/DynamicHomeScreenWidgetProvider.kt +129 -57
  12. package/android/src/main/java/com/reactnativeliveactivity/widgets/DynamicQuickSettingsTileService.kt +120 -0
  13. package/android/src/main/res/layout/rn_live_widget_hit_zone.xml +16 -0
  14. package/android/src/main/res/layout/rn_live_widget_host.xml +16 -87
  15. package/app.plugin.js +36 -0
  16. package/assets/MaterialIcons.json +2236 -0
  17. package/cli/codegen.js +789 -0
  18. package/cli/setup.js +323 -63
  19. package/docs/EXPO-GUIDE-EN.md +21 -3
  20. package/docs/EXPO-GUIDE-VI.md +21 -3
  21. package/docs/GUIDE-EN.md +444 -21
  22. package/docs/GUIDE-VI.md +473 -22
  23. package/docs/index.html +2263 -265
  24. package/docs/llms-full.txt +41 -0
  25. package/docs/llms.txt +24 -7
  26. package/ios/Bridge/LiveActivityModule.swift +333 -44
  27. package/ios/Intents/DynamicWidgetActionIntent.swift +57 -2
  28. package/ios/Models/DynamicLayoutModels.swift +120 -5
  29. package/ios/Renderer/DynamicNodeView.swift +184 -20
  30. package/ios/Storage/DynamicWidgetStateStore.swift +649 -38
  31. package/ios/Widgets/DynamicControlWidget.swift +63 -0
  32. package/ios/Widgets/DynamicHomeScreenWidget.swift +104 -26
  33. package/ios/Widgets/DynamicLiveActivityWidget.swift +25 -4
  34. package/lib/builder.d.ts +50 -7
  35. package/lib/builder.d.ts.map +1 -1
  36. package/lib/builder.js +391 -29
  37. package/lib/builder.js.map +1 -1
  38. package/lib/dispatcher.js +16 -10
  39. package/lib/dispatcher.js.map +1 -1
  40. package/lib/hooks.d.ts +13 -9
  41. package/lib/hooks.d.ts.map +1 -1
  42. package/lib/hooks.js +105 -42
  43. package/lib/hooks.js.map +1 -1
  44. package/lib/index.d.ts +96 -8
  45. package/lib/index.d.ts.map +1 -1
  46. package/lib/index.js +415 -97
  47. package/lib/index.js.map +1 -1
  48. package/lib/ir.d.ts +15 -0
  49. package/lib/ir.d.ts.map +1 -0
  50. package/lib/ir.js +386 -0
  51. package/lib/ir.js.map +1 -0
  52. package/lib/jsx.d.ts +19 -7
  53. package/lib/jsx.d.ts.map +1 -1
  54. package/lib/jsx.js +179 -95
  55. package/lib/jsx.js.map +1 -1
  56. package/lib/material-icons.generated.d.ts +8 -0
  57. package/lib/material-icons.generated.d.ts.map +1 -0
  58. package/lib/material-icons.generated.js +9 -0
  59. package/lib/material-icons.generated.js.map +1 -0
  60. package/lib/preview.d.ts +11 -27
  61. package/lib/preview.d.ts.map +1 -1
  62. package/lib/preview.js +456 -119
  63. package/lib/preview.js.map +1 -1
  64. package/lib/sf-symbols.generated.d.ts +8 -0
  65. package/lib/sf-symbols.generated.d.ts.map +1 -0
  66. package/lib/sf-symbols.generated.js +9 -0
  67. package/lib/sf-symbols.generated.js.map +1 -0
  68. package/lib/types.d.ts +506 -30
  69. package/lib/types.d.ts.map +1 -1
  70. package/lib/types.js +2 -1
  71. package/lib/types.js.map +1 -1
  72. package/package.json +7 -2
  73. package/scripts/build.js +98 -0
  74. package/scripts/generate-material-icons.js +93 -0
  75. package/scripts/generate-sf-symbols.js +95 -0
  76. package/scripts/release.js +115 -0
  77. package/scripts/test-ir-semantic.js +314 -0
  78. package/src/builder.ts +439 -26
  79. package/src/hooks.ts +88 -12
  80. package/src/index.ts +385 -57
  81. package/src/ir.ts +436 -0
  82. package/src/jsx.tsx +99 -21
  83. package/src/material-icons.generated.ts +3844 -0
  84. package/src/preview.tsx +533 -55
  85. package/src/react-native-env.d.ts +1 -0
  86. package/src/sf-symbols.generated.ts +9533 -0
  87. package/src/types.ts +601 -31
package/src/index.ts CHANGED
@@ -2,15 +2,21 @@ import React from 'react';
2
2
  import { AppRegistry, NativeEventEmitter, NativeModules, Platform } from 'react-native';
3
3
  import {
4
4
  ActiveActivityInfo,
5
+ ControlWidgetConfig,
5
6
  EndActivityOptions,
6
7
  LiveActivityPushTokens,
8
+ LiveActivityStateEvent,
7
9
  StartActivityOptions,
8
10
  UpdateActivityOptions,
11
+ WidgetCapabilities,
9
12
  WidgetConfigOption,
10
13
  WidgetLayoutConfig,
11
14
  WidgetRemoteConfig,
12
15
  WidgetTimelineConfig,
16
+ WidgetIR,
13
17
  } from './types';
18
+ import { compileToIR, inspectIR } from './ir';
19
+ import { UI, createDataBinding, flattenDataObject, resolveTemplateString } from './builder';
14
20
 
15
21
  declare const __DEV__: boolean | undefined;
16
22
 
@@ -31,6 +37,7 @@ const DEVICE_TOKEN_CHANGED_EVENT = 'DevicePushTokenChanged';
31
37
  const TOKEN_CHANGED_EVENT = 'LiveActivityTokenChanged';
32
38
  const UPDATE_TOKEN_CHANGED_EVENT = 'LiveActivityUpdateTokenChanged';
33
39
  const ACTION_CLICKED_EVENT = 'LiveActivityActionClicked';
40
+ const STATE_CHANGED_EVENT = 'LiveActivityStateChanged';
34
41
 
35
42
  import {
36
43
  ActionHandler,
@@ -43,7 +50,14 @@ import {
43
50
  } from './dispatcher';
44
51
  export type { ActionHandler, GlobalActionHandler };
45
52
  export { registerAction, registerActionHandler, unregisterAction };
46
- export * from './hooks';
53
+ export type {
54
+ WidgetCapabilities,
55
+ GradientProps,
56
+ ShadowProps,
57
+ BorderStyle,
58
+ TypographyStyle,
59
+ FontDesign,
60
+ } from './types';
47
61
  export * from './jsx';
48
62
  export * from './preview';
49
63
  import { renderToWidget } from './jsx';
@@ -53,17 +67,18 @@ if (liveActivityEmitter) {
53
67
  liveActivityEmitter.addListener(ACTION_CLICKED_EVENT, async (event: any) => {
54
68
  const actionId = event?.actionId || '';
55
69
  const activityId = event?.activityId || '';
70
+ const payload = { ...(event || {}), actionId, activityId };
56
71
  const handler = actionHandlers.get(actionId);
57
72
  if (handler) {
58
73
  try {
59
- await handler({ actionId, activityId });
74
+ await handler(payload);
60
75
  } catch (e) {
61
76
  console.warn(`[react-native-live-widgets] Error executing action '${actionId}':`, e);
62
77
  }
63
78
  }
64
79
  for (const globalHandler of globalActionHandlers) {
65
80
  try {
66
- await globalHandler(actionId, { actionId, activityId });
81
+ await globalHandler(actionId, payload);
67
82
  } catch (e) {
68
83
  console.warn(`[react-native-live-widgets] Error in global action handler for '${actionId}':`, e);
69
84
  }
@@ -71,6 +86,106 @@ if (liveActivityEmitter) {
71
86
  });
72
87
  }
73
88
 
89
+ function convertIfJsx(node: any): any {
90
+ if (!node) return node;
91
+ if (React.isValidElement(node) || (node as any)?.$$typeof || typeof (node as any)?.type === 'function') {
92
+ return renderToWidget(node);
93
+ }
94
+ return node;
95
+ }
96
+
97
+ function normalizeDynamicIsland(island: any): any {
98
+ if (!island || typeof island !== 'object') return island;
99
+ const normalized: any = { ...island };
100
+ if (normalized.compactLeading) normalized.compactLeading = convertIfJsx(normalized.compactLeading);
101
+ if (normalized.compactTrailing) normalized.compactTrailing = convertIfJsx(normalized.compactTrailing);
102
+ if (normalized.minimal) normalized.minimal = convertIfJsx(normalized.minimal);
103
+ if (normalized.expanded && typeof normalized.expanded === 'object') {
104
+ normalized.expanded = {
105
+ ...normalized.expanded,
106
+ leading: convertIfJsx(normalized.expanded.leading),
107
+ trailing: convertIfJsx(normalized.expanded.trailing),
108
+ center: convertIfJsx(normalized.expanded.center),
109
+ bottom: convertIfJsx(normalized.expanded.bottom),
110
+ };
111
+ }
112
+ return normalized;
113
+ }
114
+
115
+ function normalizeActivityPayload(options: any): any {
116
+ const opts: any = { ...options };
117
+ if (opts.lockScreen) opts.lockScreen = convertIfJsx(opts.lockScreen);
118
+ if (opts.staleLockScreen) opts.staleLockScreen = convertIfJsx(opts.staleLockScreen);
119
+ if (opts.expiredLockScreen) opts.expiredLockScreen = convertIfJsx(opts.expiredLockScreen);
120
+ if (opts.dynamicIsland) opts.dynamicIsland = normalizeDynamicIsland(opts.dynamicIsland);
121
+ if (opts.staleDynamicIsland) opts.staleDynamicIsland = normalizeDynamicIsland(opts.staleDynamicIsland);
122
+
123
+ if (opts.alertConfig && typeof opts.alertConfig === 'object') {
124
+ if (opts.alertConfig.title && !opts.alertTitle) opts.alertTitle = opts.alertConfig.title;
125
+ if (opts.alertConfig.body && !opts.alertBody) opts.alertBody = opts.alertConfig.body;
126
+ if (opts.alertConfig.sound && !opts.alertSound) opts.alertSound = opts.alertConfig.sound;
127
+ }
128
+
129
+ if (typeof opts.autoEndAfterSeconds === 'number' && opts.autoEndAfterSeconds > 0 && !opts.scheduledEndTimestamp) {
130
+ opts.scheduledEndTimestamp = Date.now() / 1000.0 + opts.autoEndAfterSeconds;
131
+ }
132
+ return opts;
133
+ }
134
+
135
+ function normalizeSinglePageConfig(cfg: any): any {
136
+ if (!cfg || typeof cfg !== 'object') return cfg;
137
+ return {
138
+ ...cfg,
139
+ small: convertIfJsx(cfg.small),
140
+ medium: convertIfJsx(cfg.medium),
141
+ large: convertIfJsx(cfg.large),
142
+ extraLarge: convertIfJsx(cfg.extraLarge),
143
+ standBy: convertIfJsx(cfg.standBy),
144
+ accessoryRectangular: convertIfJsx(cfg.accessoryRectangular),
145
+ accessoryCircular: convertIfJsx(cfg.accessoryCircular),
146
+ accessoryInline: convertIfJsx(cfg.accessoryInline),
147
+ };
148
+ }
149
+
150
+ function normalizeWidgetLayoutConfig(layoutConfig: any): any {
151
+ let finalLayout: any = layoutConfig;
152
+ if (
153
+ React.isValidElement(finalLayout) ||
154
+ (finalLayout as any)?.$$typeof ||
155
+ typeof (finalLayout as any)?.type === 'function'
156
+ ) {
157
+ finalLayout = { medium: renderToWidget(finalLayout) };
158
+ } else if (finalLayout && typeof finalLayout === 'object') {
159
+ const c = normalizeSinglePageConfig(finalLayout);
160
+ if (c.pages && typeof c.pages === 'object') {
161
+ const convertedPages: Record<string, any> = {};
162
+ for (const [pageKey, pageCfg] of Object.entries(c.pages)) {
163
+ convertedPages[pageKey] = normalizeSinglePageConfig(pageCfg);
164
+ }
165
+ c.pages = convertedPages;
166
+ }
167
+ finalLayout = c;
168
+ }
169
+ return finalLayout;
170
+ }
171
+
172
+ function resolveLayoutObjectTemplates(value: any, flatVars: Record<string, string>): any {
173
+ if (typeof value === 'string') {
174
+ return resolveTemplateString(value, flatVars);
175
+ }
176
+ if (Array.isArray(value)) {
177
+ return value.map((item) => resolveLayoutObjectTemplates(item, flatVars));
178
+ }
179
+ if (value && typeof value === 'object') {
180
+ const out: Record<string, any> = {};
181
+ for (const [k, v] of Object.entries(value)) {
182
+ out[k] = resolveLayoutObjectTemplates(v, flatVars);
183
+ }
184
+ return out;
185
+ }
186
+ return value;
187
+ }
188
+
74
189
  // ─── 1. LIVE ACTIVITY & LIVE UPDATE ──────────────────────────────────────────
75
190
 
76
191
  export const LiveActivity = {
@@ -80,11 +195,7 @@ export const LiveActivity = {
80
195
  start: async (options: StartActivityOptions): Promise<boolean> => {
81
196
  if (!LiveActivityModule?.start) return false;
82
197
  try {
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);
198
+ const payload = JSON.stringify(normalizeActivityPayload(options));
88
199
  return await LiveActivityModule.start(options.activityId, payload);
89
200
  } catch (error) {
90
201
  console.warn('[react-native-live-widgets] start error:', error);
@@ -98,11 +209,7 @@ export const LiveActivity = {
98
209
  update: async (options: UpdateActivityOptions): Promise<boolean> => {
99
210
  if (!LiveActivityModule?.update) return false;
100
211
  try {
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);
212
+ const payload = JSON.stringify(normalizeActivityPayload(options));
106
213
  return await LiveActivityModule.update(options.activityId, payload);
107
214
  } catch (error) {
108
215
  console.warn('[react-native-live-widgets] update error:', error);
@@ -116,11 +223,13 @@ export const LiveActivity = {
116
223
  end: async (activityId: string, options?: EndActivityOptions): Promise<boolean> => {
117
224
  try {
118
225
  if (options && (LiveActivityModule?.endWithOptions || LiveActivityModule?.endActivity)) {
119
- const payloadJson = options.finalLockScreen || options.finalDynamicIsland
226
+ const finalLock = options.finalLockScreen ? convertIfJsx(options.finalLockScreen) : undefined;
227
+ const finalIsland = options.finalDynamicIsland ? normalizeDynamicIsland(options.finalDynamicIsland) : undefined;
228
+ const payloadJson = finalLock || finalIsland
120
229
  ? JSON.stringify({
121
230
  activityId,
122
- lockScreen: options.finalLockScreen,
123
- dynamicIsland: options.finalDynamicIsland,
231
+ lockScreen: finalLock,
232
+ dynamicIsland: finalIsland,
124
233
  })
125
234
  : null;
126
235
  const nativeOptions = {
@@ -293,7 +402,7 @@ export const LiveActivity = {
293
402
  },
294
403
 
295
404
  /**
296
- * Lấy danh sách các phiên Live Activity đang chạy trên thiết bị (ID và Push Token).
405
+ * Lấy danh sách các phiên Live Activity đang chạy trên thiết bị (kèm trạng thái Stale, RelevanceScore, ScheduledEnd và Push Token).
297
406
  * Giúp ứng dụng khôi phục lại trạng thái giao diện khi mở lại App.
298
407
  */
299
408
  getActiveActivities: async (): Promise<ActiveActivityInfo[]> => {
@@ -304,6 +413,12 @@ export const LiveActivity = {
304
413
  const list = await LiveActivityModule.getActiveActivities();
305
414
  return (list || []).map((item: any) => ({
306
415
  activityId: item.activityId || '',
416
+ systemActivityId: item.systemActivityId,
417
+ activityState: item.activityState,
418
+ isStale: Boolean(item.isStale ?? item.activityState === 'stale'),
419
+ relevanceScore: typeof item.relevanceScore === 'number' ? item.relevanceScore : undefined,
420
+ staleTimestamp: typeof item.staleTimestamp === 'number' ? item.staleTimestamp : undefined,
421
+ scheduledEndTimestamp: typeof item.scheduledEndTimestamp === 'number' ? item.scheduledEndTimestamp : undefined,
307
422
  pushToken: item.pushToken,
308
423
  }));
309
424
  } catch (e) {
@@ -312,6 +427,61 @@ export const LiveActivity = {
312
427
  }
313
428
  },
314
429
 
430
+ /**
431
+ * Lấy thông tin chi tiết của một Live Activity cụ thể theo activityId.
432
+ */
433
+ get: async (activityId: string): Promise<ActiveActivityInfo | null> => {
434
+ const list = await LiveActivity.getActiveActivities();
435
+ return list.find((a) => a.activityId === activityId || a.systemActivityId === activityId) ?? null;
436
+ },
437
+
438
+ /**
439
+ * Kiểm tra nhanh xem một Live Activity cụ thể có đang chạy trên thiết bị hay không.
440
+ */
441
+ isActive: async (activityId: string): Promise<boolean> => {
442
+ const info = await LiveActivity.get(activityId);
443
+ return Boolean(info && info.activityState !== 'ended' && info.activityState !== 'dismissed' && info.activityState !== 'expired');
444
+ },
445
+
446
+ /**
447
+ * Lắng nghe sự kiện chuyển đổi vòng đời Live Activity (`active`, `started_by_push`, `stale`, `expired`, `ended`, `dismissed`).
448
+ */
449
+ onStateChange: (listener: (event: LiveActivityStateEvent) => void): (() => void) => {
450
+ if (!liveActivityEmitter) return () => {};
451
+ const sub = liveActivityEmitter.addListener(STATE_CHANGED_EVENT, (event: any) => {
452
+ if (!event) return;
453
+ listener({
454
+ activityId: event.activityId || '',
455
+ systemActivityId: event.systemActivityId,
456
+ state: event.state || 'active',
457
+ timestamp: typeof event.timestamp === 'number' ? event.timestamp : Date.now() / 1000.0,
458
+ pushToken: event.pushToken,
459
+ });
460
+ });
461
+ return () => sub.remove();
462
+ },
463
+
464
+ /**
465
+ * Kiểm tra và tự động kết thúc các Live Activity đã quá hạn `scheduledEndTimestamp` (dọn dẹp các phiên bị kẹt).
466
+ * Trả về danh sách các `activityId` đã được dọn dẹp.
467
+ */
468
+ cleanupExpired: async (): Promise<string[]> => {
469
+ const list = await LiveActivity.getActiveActivities();
470
+ const nowSec = Date.now() / 1000.0;
471
+ const cleaned: string[] = [];
472
+ for (const item of list) {
473
+ const endTs = item.scheduledEndTimestamp;
474
+ if (typeof endTs === 'number' && endTs > 0) {
475
+ const normalizedEnd = endTs > 10_000_000_000 ? endTs / 1000.0 : endTs;
476
+ if (nowSec >= normalizedEnd) {
477
+ await LiveActivity.end(item.activityId, { dismissalPolicy: 'immediate' });
478
+ cleaned.push(item.activityId);
479
+ }
480
+ }
481
+ }
482
+ return cleaned;
483
+ },
484
+
315
485
  /**
316
486
  * 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.
317
487
  */
@@ -453,27 +623,7 @@ export const Widget = {
453
623
  appGroup = typeof layoutConfigOrAppGroup === 'string' ? layoutConfigOrAppGroup : undefined;
454
624
  }
455
625
 
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
- }
626
+ const finalLayout = normalizeWidgetLayoutConfig(layoutConfig);
477
627
 
478
628
  const saved = await SharedStorage.set(`widget_layout_${widgetKey}`, finalLayout, appGroup);
479
629
  if (!saved) return false;
@@ -506,15 +656,22 @@ export const Widget = {
506
656
  appGroup?: string
507
657
  ): Promise<boolean> => {
508
658
  try {
509
- const formattedEntries = timelineConfig.entries.map((entry) => ({
510
- date:
511
- typeof entry.date === 'string'
512
- ? new Date(entry.date).getTime() / 1000.0
513
- : entry.date > 10000000000
514
- ? entry.date / 1000.0
515
- : entry.date,
516
- layout: entry.layout,
517
- }));
659
+ const formattedEntries = timelineConfig.entries.map((entry) => {
660
+ let entryLayout = normalizeWidgetLayoutConfig(entry.layout);
661
+ if (entry.data && typeof entry.data === 'object') {
662
+ const flatVars = flattenDataObject(entry.data);
663
+ entryLayout = resolveLayoutObjectTemplates(entryLayout, flatVars);
664
+ }
665
+ return {
666
+ date:
667
+ typeof entry.date === 'string'
668
+ ? new Date(entry.date).getTime() / 1000.0
669
+ : entry.date > 10000000000
670
+ ? entry.date / 1000.0
671
+ : entry.date,
672
+ layout: entryLayout,
673
+ };
674
+ });
518
675
  const formattedConfig = {
519
676
  entries: formattedEntries,
520
677
  policy: timelineConfig.policy || 'atEnd',
@@ -579,13 +736,17 @@ export const Widget = {
579
736
  },
580
737
 
581
738
  /**
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
583
- * theo chu kỳ (`getTimeline`) hoặc khi bấm nút `actionId: 'refresh'` trên mặt Widget,
584
- * kể cả khi người dùng đã vuốt tắt (Kill) hoàn toàn ứng dụng chính!
739
+ * Cấu hình Background Data Engine 2.0 để Widget Extension tự gọi API ngầm (REST, Custom Headers,
740
+ * Cache TTL, ETag/304, Retry/Backoff, Timeout, Multiple Sources, Data Transform, Schema Validation,
741
+ * Auth Token Refresh & Error State) kể cả khi App chính đã bị đóng hoàn toàn.
742
+ *
743
+ * Lưu ý hệ điều hành: Apple WidgetKit quản lý ngân sách reload động (~40–70 lần/ngày tùy mức sử dụng,
744
+ * `refreshIntervalMinutes` chỉ là mốc sớm nhất đề xuất chứ không cam kết chạy đúng mỗi 15 phút khi app đóng);
745
+ * Android cũng áp dụng Doze Mode / App Standby cho background task.
585
746
  *
586
747
  * 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')
748
+ * - `Widget.setRemoteConfig('main', config, appGroup?)`
749
+ * - `Widget.setRemoteConfig(config, appGroup?)` (tự động gán widgetKey = 'main')
589
750
  */
590
751
  setRemoteConfig: async (
591
752
  widgetKeyOrConfig: string | WidgetRemoteConfig,
@@ -606,15 +767,25 @@ export const Widget = {
606
767
  appGroup = typeof remoteConfigOrAppGroup === 'string' ? remoteConfigOrAppGroup : undefined;
607
768
  }
608
769
 
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;
770
+ const finalConfig: WidgetRemoteConfig = { ...remoteConfig };
771
+ if (
772
+ finalConfig.intervalMinutes !== undefined &&
773
+ finalConfig.refreshIntervalMinutes === undefined
774
+ ) {
775
+ finalConfig.refreshIntervalMinutes = finalConfig.intervalMinutes;
776
+ } else if (
777
+ finalConfig.refreshIntervalMinutes !== undefined &&
778
+ finalConfig.intervalMinutes === undefined
779
+ ) {
780
+ finalConfig.intervalMinutes = finalConfig.refreshIntervalMinutes;
781
+ }
782
+ if (finalConfig.errorFallback) {
783
+ finalConfig.errorFallback = convertIfJsx(finalConfig.errorFallback);
613
784
  }
614
785
 
615
786
  const saved = await SharedStorage.set(
616
787
  `widget_remote_config_${widgetKey}`,
617
- remoteConfig,
788
+ finalConfig,
618
789
  appGroup
619
790
  );
620
791
  if (!saved) return false;
@@ -625,6 +796,53 @@ export const Widget = {
625
796
  }
626
797
  },
627
798
 
799
+ /**
800
+ * Đẩy dữ liệu có cấu trúc (Structured Data Binding) từ JS/TS xuống Native Shared Storage
801
+ * để Home Screen Widget cập nhật tức thì mà không cần dựng lại toàn bộ cây layout.
802
+ *
803
+ * Hỗ trợ gọi linh hoạt:
804
+ * - `Widget.setData('main', data, appGroup?)`
805
+ * - `Widget.setData(data, appGroup?)` (tự động gán widgetKey = 'main')
806
+ */
807
+ setData: async (
808
+ widgetKeyOrData: string | Record<string, any>,
809
+ dataOrAppGroup?: Record<string, any> | string,
810
+ maybeAppGroup?: string
811
+ ): Promise<boolean> => {
812
+ try {
813
+ let widgetKey = 'main';
814
+ let dataObj: Record<string, any>;
815
+ let appGroup: string | undefined;
816
+
817
+ if (typeof widgetKeyOrData === 'string') {
818
+ widgetKey = widgetKeyOrData;
819
+ dataObj = (dataOrAppGroup as Record<string, any>) || {};
820
+ appGroup = maybeAppGroup;
821
+ } else {
822
+ dataObj = widgetKeyOrData || {};
823
+ appGroup = typeof dataOrAppGroup === 'string' ? dataOrAppGroup : undefined;
824
+ }
825
+
826
+ const flattened = flattenDataObject(dataObj);
827
+ const saved = await SharedStorage.set(`widget_bound_data_${widgetKey}`, flattened, appGroup);
828
+ if (!saved) return false;
829
+ return await Widget.reloadAll();
830
+ } catch (error) {
831
+ console.warn('[react-native-live-widgets] setData error:', error);
832
+ return false;
833
+ }
834
+ },
835
+
836
+ /**
837
+ * Tạo Proxy Data Binding có cấu trúc & gợi ý kiểu TypeScript cho JSX/DSL Widget (`data.user.name`, `data.attendance.progress.divide(100)`).
838
+ */
839
+ createDataBinding,
840
+
841
+ /**
842
+ * Tạo chuỗi token binding (`{{path|pipe}}`) cho hệ thống Background Data Engine 2.0.
843
+ */
844
+ bind: UI.bind,
845
+
628
846
  /** Đăng ký lắng nghe tương tác nút bấm từ Widget theo `actionId` */
629
847
  registerAction: registerAction,
630
848
 
@@ -659,6 +877,100 @@ export const Widget = {
659
877
  return false;
660
878
  }
661
879
  },
880
+
881
+ /**
882
+ * 📊 Bảng tra cứu năng lực nền tảng (Platform Capability & Fallback Matrix).
883
+ * Giúp ứng dụng xác định chính xác tính năng nào được hỗ trợ thực tế trên thiết bị đang chạy.
884
+ */
885
+ getCapabilities: async (): Promise<WidgetCapabilities> => {
886
+ const isIOS = Platform.OS === 'ios';
887
+ const isAndroid = Platform.OS === 'android';
888
+ const osVerNum = parseFloat(String(Platform.Version)) || 0;
889
+
890
+ let hasIsland = false;
891
+ if (isIOS) {
892
+ try {
893
+ hasIsland = LiveActivityModule?.isDynamicIslandSupported
894
+ ? await LiveActivityModule.isDynamicIslandSupported()
895
+ : osVerNum >= 16.1;
896
+ } catch {
897
+ hasIsland = osVerNum >= 16.1;
898
+ }
899
+ }
900
+
901
+ return {
902
+ platform: isIOS ? 'ios' : 'android',
903
+ osVersion: Platform.Version,
904
+ supportsLiveActivities: isIOS ? osVerNum >= 16.1 : osVerNum >= 26,
905
+ supportsDynamicIsland: hasIsland,
906
+ supportsAndroidLiveUpdates: isAndroid && osVerNum >= 36,
907
+ supportsHomeWidgets: isIOS ? osVerNum >= 14.0 : osVerNum >= 26,
908
+ supportsInteractiveIntents: isIOS ? osVerNum >= 17.0 : true,
909
+ supportsGradients: true,
910
+ supportsShadows: true,
911
+ supportsDashedBorders: true,
912
+ supportsDynamicType: true,
913
+ supportsRTL: true,
914
+ supportsTintedMode: isIOS ? osVerNum >= 18.0 : isAndroid,
915
+ supportsNumericAnimation: isIOS && osVerNum >= 16.0,
916
+ supportsAccessibility: true,
917
+ };
918
+ },
919
+
920
+ /**
921
+ * 🎛️ Cấu hình Control Widget (iOS 18+ Control Center / Lock Screen Controls / Action Button & Android Quick Settings).
922
+ */
923
+ setControl: async (
924
+ controlId: string,
925
+ config: ControlWidgetConfig,
926
+ appGroup?: string
927
+ ): Promise<boolean> => {
928
+ try {
929
+ return await SharedStorage.set(`widget_control_${controlId}`, config, appGroup);
930
+ } catch (error) {
931
+ console.warn('[react-native-live-widgets] setControl error:', error);
932
+ return false;
933
+ }
934
+ },
935
+
936
+ /**
937
+ * Đọc cấu hình và trạng thái hiện tại của Control Widget từ Shared Storage.
938
+ */
939
+ getControlState: async (
940
+ controlId: string,
941
+ appGroup?: string
942
+ ): Promise<ControlWidgetConfig | null> => {
943
+ try {
944
+ return await SharedStorage.get<ControlWidgetConfig>(`widget_control_${controlId}`, appGroup);
945
+ } catch {
946
+ return null;
947
+ }
948
+ },
949
+
950
+ /**
951
+ * 🌲 Biên dịch cây DSL sang UI Intermediate Representation (IR & Semantic Tree - Phase 2).
952
+ */
953
+ compileIR: (layout: any): WidgetIR => {
954
+ return compileToIR(layout);
955
+ },
956
+
957
+ /**
958
+ * 🔍 Phân tích và in ra bản đồ kiến trúc IR, Semantic Tree và Kế hoạch phân bổ Renderer Planner.
959
+ */
960
+ inspectIR: (layout: any): string => {
961
+ return inspectIR(layout);
962
+ },
963
+ };
964
+
965
+ /**
966
+ * 🎛️ Namespace cấu hình & quản lý Control Widget đa nền tảng
967
+ * (iOS 18+ Control Center / Lock Screen Controls / Action Button & Android Quick Settings Tile).
968
+ */
969
+ export const ControlWidget = {
970
+ set: Widget.setControl,
971
+ getState: Widget.getControlState,
972
+ button: UI.ControlButton,
973
+ toggle: UI.ControlToggle,
662
974
  };
663
975
 
664
976
  // ─── 3. SHARED STORAGE (App Groups & SharedPreferences) ─────────────────────
@@ -810,4 +1122,20 @@ export const AudioPlayer = {
810
1122
 
811
1123
  export * from './types';
812
1124
  export * from './builder';
1125
+ export * from './ir';
813
1126
  export { StyleSheet } from './builder';
1127
+ export * from './hooks';
1128
+
1129
+ /**
1130
+ * Định nghĩa cấu hình các Widget cho ứng dụng với đầy đủ Type Safety và gợi ý thuộc tính IDE.
1131
+ * Cấu hình này được công cụ Codegen (`npx react-native-live-widgets codegen`) đọc
1132
+ * để tự động tạo file LiveWidgetsBundle.swift cho iOS WidgetKit.
1133
+ */
1134
+ export function defineWidgetsConfig<T extends import('./types').WidgetsProjectConfig>(config: T): T {
1135
+ return config;
1136
+ }
1137
+
1138
+ /**
1139
+ * Alias cho `defineWidgetsConfig` (hỗ trợ cả dạng số ít và số nhiều)
1140
+ */
1141
+ export const defineWidgetConfig = defineWidgetsConfig;