react-native-live-widgets 1.1.1 → 1.2.1

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 (58) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +113 -10
  3. package/android/src/main/java/com/reactnativeliveactivity/bridge/LiveActivityModule.kt +5 -1
  4. package/android/src/main/java/com/reactnativeliveactivity/renderer/DynamicWidgetCanvasRenderer.kt +443 -46
  5. package/android/src/main/java/com/reactnativeliveactivity/storage/DynamicWidgetStateStore.kt +86 -24
  6. package/android/src/main/java/com/reactnativeliveactivity/widgets/DynamicHomeScreenWidgetProvider.kt +126 -56
  7. package/android/src/main/res/layout/rn_live_widget_hit_zone.xml +16 -0
  8. package/android/src/main/res/layout/rn_live_widget_host.xml +16 -87
  9. package/docs/GUIDE-EN.md +332 -7
  10. package/docs/GUIDE-VI.md +357 -7
  11. package/docs/index.html +1143 -227
  12. package/docs/llms-full.txt +46 -6
  13. package/docs/llms.txt +37 -7
  14. package/ios/Models/DynamicLayoutModels.swift +11 -1
  15. package/ios/Renderer/DynamicNodeView.swift +169 -14
  16. package/ios/Widgets/DynamicHomeScreenWidget.swift +7 -3
  17. package/lib/builder.d.ts.map +1 -1
  18. package/lib/builder.js +92 -28
  19. package/lib/builder.js.map +1 -1
  20. package/lib/dispatcher.d.ts +7 -0
  21. package/lib/dispatcher.d.ts.map +1 -1
  22. package/lib/dispatcher.js +23 -6
  23. package/lib/dispatcher.js.map +1 -1
  24. package/lib/hooks.d.ts +66 -0
  25. package/lib/hooks.d.ts.map +1 -0
  26. package/lib/hooks.js +171 -0
  27. package/lib/hooks.js.map +1 -0
  28. package/lib/index.d.ts +48 -8
  29. package/lib/index.d.ts.map +1 -1
  30. package/lib/index.js +216 -35
  31. package/lib/index.js.map +1 -1
  32. package/lib/ir.d.ts +15 -0
  33. package/lib/ir.d.ts.map +1 -0
  34. package/lib/ir.js +379 -0
  35. package/lib/ir.js.map +1 -0
  36. package/lib/jsx.d.ts +87 -0
  37. package/lib/jsx.d.ts.map +1 -0
  38. package/lib/jsx.js +243 -0
  39. package/lib/jsx.js.map +1 -0
  40. package/lib/preview.d.ts +31 -0
  41. package/lib/preview.d.ts.map +1 -0
  42. package/lib/preview.js +735 -0
  43. package/lib/preview.js.map +1 -0
  44. package/lib/types.d.ts +212 -12
  45. package/lib/types.d.ts.map +1 -1
  46. package/lib/types.js +2 -1
  47. package/lib/types.js.map +1 -1
  48. package/package.json +3 -1
  49. package/src/builder.ts +86 -21
  50. package/src/dispatcher.ts +17 -0
  51. package/src/hooks.ts +223 -0
  52. package/src/index.ts +202 -13
  53. package/src/ir.ts +430 -0
  54. package/src/jsx.tsx +326 -0
  55. package/src/preview.tsx +1043 -0
  56. package/src/react-ambient.d.ts +10 -0
  57. package/src/react-native-env.d.ts +44 -0
  58. package/src/types.ts +261 -13
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,
@@ -5,11 +6,14 @@ import {
5
6
  LiveActivityPushTokens,
6
7
  StartActivityOptions,
7
8
  UpdateActivityOptions,
9
+ WidgetCapabilities,
8
10
  WidgetConfigOption,
9
11
  WidgetLayoutConfig,
10
12
  WidgetRemoteConfig,
11
13
  WidgetTimelineConfig,
14
+ WidgetIR,
12
15
  } from './types';
16
+ import { compileToIR, inspectIR } from './ir';
13
17
 
14
18
  declare const __DEV__: boolean | undefined;
15
19
 
@@ -31,9 +35,28 @@ const TOKEN_CHANGED_EVENT = 'LiveActivityTokenChanged';
31
35
  const UPDATE_TOKEN_CHANGED_EVENT = 'LiveActivityUpdateTokenChanged';
32
36
  const ACTION_CLICKED_EVENT = 'LiveActivityActionClicked';
33
37
 
34
- import { ActionHandler, actionHandlers, registerAction, unregisterAction } from './dispatcher';
35
- export type { ActionHandler };
36
- export { registerAction, unregisterAction };
38
+ import {
39
+ ActionHandler,
40
+ GlobalActionHandler,
41
+ actionHandlers,
42
+ globalActionHandlers,
43
+ registerAction,
44
+ registerActionHandler,
45
+ unregisterAction,
46
+ } from './dispatcher';
47
+ export type { ActionHandler, GlobalActionHandler };
48
+ export { registerAction, registerActionHandler, unregisterAction };
49
+ export type {
50
+ WidgetCapabilities,
51
+ GradientProps,
52
+ ShadowProps,
53
+ BorderStyle,
54
+ TypographyStyle,
55
+ FontDesign,
56
+ } from './types';
57
+ export * from './jsx';
58
+ export * from './preview';
59
+ import { renderToWidget } from './jsx';
37
60
 
38
61
  // Tự động lắng nghe action event từ Native để dispatch tới các hàm TypeScript đã đăng ký
39
62
  if (liveActivityEmitter) {
@@ -48,6 +71,13 @@ if (liveActivityEmitter) {
48
71
  console.warn(`[react-native-live-widgets] Error executing action '${actionId}':`, e);
49
72
  }
50
73
  }
74
+ for (const globalHandler of globalActionHandlers) {
75
+ try {
76
+ await globalHandler(actionId, { actionId, activityId });
77
+ } catch (e) {
78
+ console.warn(`[react-native-live-widgets] Error in global action handler for '${actionId}':`, e);
79
+ }
80
+ }
51
81
  });
52
82
  }
53
83
 
@@ -60,7 +90,11 @@ export const LiveActivity = {
60
90
  start: async (options: StartActivityOptions): Promise<boolean> => {
61
91
  if (!LiveActivityModule?.start) return false;
62
92
  try {
63
- const payload = JSON.stringify(options);
93
+ const opts = { ...options } as any;
94
+ if (React.isValidElement(opts.lockScreen)) {
95
+ opts.lockScreen = renderToWidget(opts.lockScreen);
96
+ }
97
+ const payload = JSON.stringify(opts);
64
98
  return await LiveActivityModule.start(options.activityId, payload);
65
99
  } catch (error) {
66
100
  console.warn('[react-native-live-widgets] start error:', error);
@@ -74,7 +108,11 @@ export const LiveActivity = {
74
108
  update: async (options: UpdateActivityOptions): Promise<boolean> => {
75
109
  if (!LiveActivityModule?.update) return false;
76
110
  try {
77
- const payload = JSON.stringify(options);
111
+ const opts = { ...options } as any;
112
+ if (React.isValidElement(opts.lockScreen)) {
113
+ opts.lockScreen = renderToWidget(opts.lockScreen);
114
+ }
115
+ const payload = JSON.stringify(opts);
78
116
  return await LiveActivityModule.update(options.activityId, payload);
79
117
  } catch (error) {
80
118
  console.warn('[react-native-live-widgets] update error:', error);
@@ -249,6 +287,14 @@ export const LiveActivity = {
249
287
  };
250
288
  },
251
289
 
290
+ /**
291
+ * Đă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.
292
+ * Nhận `(actionId, payload)`. Trả về hàm hủy đăng ký (unsubscribe).
293
+ */
294
+ registerActionHandler: (handler: GlobalActionHandler): (() => void) => {
295
+ return registerActionHandler(handler);
296
+ },
297
+
252
298
  /**
253
299
  * Hủy đăng ký action handler theo `actionId`.
254
300
  */
@@ -346,6 +392,13 @@ export const LiveActivity = {
346
392
  if (registered) {
347
393
  await registered({ actionId, activityId });
348
394
  }
395
+ for (const globalHandler of globalActionHandlers) {
396
+ try {
397
+ await globalHandler(actionId, { actionId, activityId });
398
+ } catch (e) {
399
+ console.warn('[react-native-live-widgets] background globalHandler error:', e);
400
+ }
401
+ }
349
402
  }
350
403
  );
351
404
  } catch (e) {
@@ -386,15 +439,53 @@ export const Widget = {
386
439
 
387
440
  /**
388
441
  * 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.
442
+ * Hỗ trợ gọi 2 hoặc 3 tham số:
443
+ * - `Widget.setLayout('main', layoutConfig, appGroup?)`
444
+ * - `Widget.setLayout(layoutConfig, appGroup?)` (tự động gán widgetKey = 'main')
445
+ * Tự động lưu vào Shared Storage và yêu cầu OS vẽ lại.
390
446
  */
391
447
  setLayout: async (
392
- widgetKey: string,
393
- layoutConfig: WidgetLayoutConfig,
394
- appGroup?: string
448
+ widgetKeyOrConfig: string | WidgetLayoutConfig,
449
+ layoutConfigOrAppGroup?: WidgetLayoutConfig | string,
450
+ maybeAppGroup?: string
395
451
  ): Promise<boolean> => {
396
452
  try {
397
- const saved = await SharedStorage.set(`widget_layout_${widgetKey}`, layoutConfig, appGroup);
453
+ let widgetKey = 'main';
454
+ let layoutConfig: WidgetLayoutConfig;
455
+ let appGroup: string | undefined;
456
+
457
+ if (typeof widgetKeyOrConfig === 'string') {
458
+ widgetKey = widgetKeyOrConfig;
459
+ layoutConfig = layoutConfigOrAppGroup as WidgetLayoutConfig;
460
+ appGroup = maybeAppGroup;
461
+ } else {
462
+ layoutConfig = widgetKeyOrConfig;
463
+ appGroup = typeof layoutConfigOrAppGroup === 'string' ? layoutConfigOrAppGroup : undefined;
464
+ }
465
+
466
+ let finalLayout: any = layoutConfig;
467
+ const convertIfJsx = (node: any) => {
468
+ if (!node) return node;
469
+ if (React.isValidElement(node) || (node as any)?.$$typeof || typeof (node as any)?.type === 'function') {
470
+ return renderToWidget(node);
471
+ }
472
+ return node;
473
+ };
474
+
475
+ if (React.isValidElement(finalLayout) || (finalLayout as any)?.$$typeof || typeof (finalLayout as any)?.type === 'function') {
476
+ finalLayout = { medium: renderToWidget(finalLayout) };
477
+ } else if (finalLayout && typeof finalLayout === 'object') {
478
+ const c = { ...finalLayout };
479
+ c.small = convertIfJsx(c.small);
480
+ c.medium = convertIfJsx(c.medium);
481
+ c.large = convertIfJsx(c.large);
482
+ c.accessoryRectangular = convertIfJsx(c.accessoryRectangular);
483
+ c.accessoryCircular = convertIfJsx(c.accessoryCircular);
484
+ c.accessoryInline = convertIfJsx(c.accessoryInline);
485
+ finalLayout = c;
486
+ }
487
+
488
+ const saved = await SharedStorage.set(`widget_layout_${widgetKey}`, finalLayout, appGroup);
398
489
  if (!saved) return false;
399
490
  return await Widget.reloadAll();
400
491
  } catch (error) {
@@ -403,6 +494,17 @@ export const Widget = {
403
494
  }
404
495
  },
405
496
 
497
+ /**
498
+ * Cập nhật layout động cho Widget (Alias tiện ích cho `Widget.setLayout`).
499
+ */
500
+ update: async (
501
+ widgetKeyOrConfig: string | WidgetLayoutConfig,
502
+ layoutConfigOrAppGroup?: WidgetLayoutConfig | string,
503
+ maybeAppGroup?: string
504
+ ): Promise<boolean> => {
505
+ return (Widget.setLayout as any)(widgetKeyOrConfig, layoutConfigOrAppGroup, maybeAppGroup);
506
+ },
507
+
406
508
  /**
407
509
  * Thiết lập dòng thời gian tự động (Timeline Entries) cho Widget.
408
510
  * 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 +592,36 @@ export const Widget = {
490
592
  * 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
593
  * theo chu kỳ (`getTimeline`) hoặc khi bấm nút `actionId: 'refresh'` trên mặt Widget,
492
594
  * kể cả khi người dùng đã vuốt tắt (Kill) hoàn toàn ứng dụng chính!
595
+ *
596
+ * Hỗ trợ gọi linh hoạt:
597
+ * - `Widget.setRemoteConfig('main', { url, refreshIntervalMinutes }, appGroup?)`
598
+ * - `Widget.setRemoteConfig({ url, intervalMinutes }, appGroup?)` (tự động gán widgetKey = 'main')
493
599
  */
494
600
  setRemoteConfig: async (
495
- widgetKey: string,
496
- remoteConfig: WidgetRemoteConfig,
497
- appGroup?: string
601
+ widgetKeyOrConfig: string | WidgetRemoteConfig,
602
+ remoteConfigOrAppGroup?: WidgetRemoteConfig | string,
603
+ maybeAppGroup?: string
498
604
  ): Promise<boolean> => {
499
605
  try {
606
+ let widgetKey = 'main';
607
+ let remoteConfig: WidgetRemoteConfig;
608
+ let appGroup: string | undefined;
609
+
610
+ if (typeof widgetKeyOrConfig === 'string') {
611
+ widgetKey = widgetKeyOrConfig;
612
+ remoteConfig = remoteConfigOrAppGroup as WidgetRemoteConfig;
613
+ appGroup = maybeAppGroup;
614
+ } else {
615
+ remoteConfig = widgetKeyOrConfig;
616
+ appGroup = typeof remoteConfigOrAppGroup === 'string' ? remoteConfigOrAppGroup : undefined;
617
+ }
618
+
619
+ if (remoteConfig.intervalMinutes !== undefined && remoteConfig.refreshIntervalMinutes === undefined) {
620
+ remoteConfig.refreshIntervalMinutes = remoteConfig.intervalMinutes;
621
+ } else if (remoteConfig.refreshIntervalMinutes !== undefined && remoteConfig.intervalMinutes === undefined) {
622
+ remoteConfig.intervalMinutes = remoteConfig.refreshIntervalMinutes;
623
+ }
624
+
500
625
  const saved = await SharedStorage.set(
501
626
  `widget_remote_config_${widgetKey}`,
502
627
  remoteConfig,
@@ -510,6 +635,15 @@ export const Widget = {
510
635
  }
511
636
  },
512
637
 
638
+ /** Đăng ký lắng nghe tương tác nút bấm từ Widget theo `actionId` */
639
+ registerAction: registerAction,
640
+
641
+ /** Đăng ký lắng nghe toàn cục tất cả tương tác nút bấm từ Widget (alias) */
642
+ onWidgetAction: registerActionHandler,
643
+
644
+ /** Đăng ký lắng nghe toàn cục tất cả tương tác nút bấm từ Widget */
645
+ registerActionHandler: registerActionHandler,
646
+
513
647
  /**
514
648
  * (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
649
  * 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.
@@ -535,6 +669,59 @@ export const Widget = {
535
669
  return false;
536
670
  }
537
671
  },
672
+
673
+ /**
674
+ * 📊 Bảng tra cứu năng lực nền tảng (Platform Capability & Fallback Matrix).
675
+ * 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.
676
+ */
677
+ getCapabilities: async (): Promise<WidgetCapabilities> => {
678
+ const isIOS = Platform.OS === 'ios';
679
+ const isAndroid = Platform.OS === 'android';
680
+ const osVerNum = parseFloat(String(Platform.Version)) || 0;
681
+
682
+ let hasIsland = false;
683
+ if (isIOS) {
684
+ try {
685
+ hasIsland = LiveActivityModule?.isDynamicIslandSupported
686
+ ? await LiveActivityModule.isDynamicIslandSupported()
687
+ : osVerNum >= 16.1;
688
+ } catch {
689
+ hasIsland = osVerNum >= 16.1;
690
+ }
691
+ }
692
+
693
+ return {
694
+ platform: isIOS ? 'ios' : 'android',
695
+ osVersion: Platform.Version,
696
+ supportsLiveActivities: isIOS ? osVerNum >= 16.1 : osVerNum >= 26,
697
+ supportsDynamicIsland: hasIsland,
698
+ supportsAndroidLiveUpdates: isAndroid && osVerNum >= 36,
699
+ supportsHomeWidgets: isIOS ? osVerNum >= 14.0 : osVerNum >= 26,
700
+ supportsInteractiveIntents: isIOS ? osVerNum >= 17.0 : true,
701
+ supportsGradients: true,
702
+ supportsShadows: true,
703
+ supportsDashedBorders: true,
704
+ supportsDynamicType: true,
705
+ supportsRTL: true,
706
+ supportsTintedMode: isIOS ? osVerNum >= 18.0 : isAndroid,
707
+ supportsNumericAnimation: isIOS && osVerNum >= 16.0,
708
+ supportsAccessibility: true,
709
+ };
710
+ },
711
+
712
+ /**
713
+ * 🌲 Biên dịch cây DSL sang UI Intermediate Representation (IR & Semantic Tree - Phase 2).
714
+ */
715
+ compileIR: (layout: any): WidgetIR => {
716
+ return compileToIR(layout);
717
+ },
718
+
719
+ /**
720
+ * 🔍 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.
721
+ */
722
+ inspectIR: (layout: any): string => {
723
+ return inspectIR(layout);
724
+ },
538
725
  };
539
726
 
540
727
  // ─── 3. SHARED STORAGE (App Groups & SharedPreferences) ─────────────────────
@@ -686,4 +873,6 @@ export const AudioPlayer = {
686
873
 
687
874
  export * from './types';
688
875
  export * from './builder';
876
+ export * from './ir';
689
877
  export { StyleSheet } from './builder';
878
+ export * from './hooks';