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
@@ -1,6 +1,6 @@
1
1
  # HƯỚNG DẪN TÍCH HỢP VÀ SỬ DỤNG EXPO VỚI REACT-NATIVE-LIVE-WIDGETS 🚀
2
2
 
3
- > 🌐 **Language:** **Tiếng Việt** | [English Guide (EXPO-GUIDE-EN.md)](./EXPO-GUIDE-EN.md) • [📖 Bare RN Guide (GUIDE-VI.md)](./GUIDE-VI.md) • [⚡ Kho mã nguồn mẫu Expo](https://github.com/React-Native-Vu/LiveWidgetsExampleExpo)
3
+ > 🌐 **Language:** **Tiếng Việt** | [English Guide (EXPO-GUIDE-EN.md)](./EXPO-GUIDE-EN.md) • [📖 Bare RN Guide (GUIDE-VI.md)](./GUIDE-VI.md) • [⚡ Kho mã nguồn mẫu Expo](https://github.com/React-Native-Vu/LiveWidgetsExampleExpo) • [🌐 Web Docs (Live Simulator)](https://react-native-vu.github.io/react-native-live-widgets/)
4
4
 
5
5
  Tài liệu này hướng dẫn chi tiết cách tích hợp **`react-native-live-widgets`** vào ứng dụng **Expo (SDK 50, 51, 52, 58+)**, từ cấu hình Expo Config Plugin, thiết lập iOS WidgetKit/ActivityKit tự động, chạy trên Local Simulator bằng Expo Dev Client cho đến việc đóng gói phát hành qua **EAS Build**.
6
6
 
@@ -86,7 +86,25 @@ npx expo run:android
86
86
 
87
87
  ## 3. Cài đặt & Thiết lập Từng bước
88
88
 
89
- ### Bước 1: Cài đặt package
89
+ ### Cách nhanh nhất: Tự động hoá 100% bằng 1 câu lệnh
90
+
91
+ ```bash
92
+ # 1. Cài đặt package
93
+ npx expo install react-native-live-widgets
94
+
95
+ # 2. Khởi tạo tự động (Tự chèn Config Plugin vào app.json, tạo widgets.config.ts, sync icons & Swift)
96
+ npx react-native-live-widgets init
97
+
98
+ # 3. Chạy ứng dụng trên máy ảo / thiết bị thật
99
+ npx expo run:ios
100
+ # hoặc: npx expo run:android
101
+ ```
102
+
103
+ ---
104
+
105
+ ### Quy trình thủ công (Nếu bạn muốn tự kiểm soát cấu hình)
106
+
107
+ #### Bước 1: Cài đặt package
90
108
  Tại thư mục gốc của dự án Expo:
91
109
  ```bash
92
110
  npx expo install react-native-live-widgets
@@ -94,7 +112,7 @@ npx expo install react-native-live-widgets
94
112
 
95
113
  ---
96
114
 
97
- ### Bước 2: Cấu hình `app.json` (Expo Config Plugin)
115
+ #### Bước 2: Cấu hình `app.json` (Expo Config Plugin)
98
116
  Mở file `app.json` và bổ sung plugin `react-native-live-widgets`:
99
117
 
100
118
  ```json
package/docs/GUIDE-EN.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # REACT-NATIVE-LIVE-WIDGETS — COMPLETE SETUP & DEVELOPER GUIDE 🚀
2
2
 
3
- > 🌐 **Language:** [Tiếng Việt (GUIDE-VI.md)](./GUIDE-VI.md) | **English** • [⚡ Dedicated Expo Guide (EXPO-GUIDE-EN.md)](./EXPO-GUIDE-EN.md)
3
+ > 🌐 **Language:** [Tiếng Việt (GUIDE-VI.md)](./GUIDE-VI.md) | **English** • [⚡ Dedicated Expo Guide (EXPO-GUIDE-EN.md)](./EXPO-GUIDE-EN.md) • [🌐 Web Docs & Live Simulator](https://react-native-vu.github.io/react-native-live-widgets/)
4
4
 
5
5
  Comprehensive guide covering installation, native setup (iOS & Android), and building 100% JavaScript/TypeScript declarative layouts for **Live Activities (Dynamic Island / Lock Screen / Android Live Updates)** and **Interactive Multi-Page Home Screen Widgets**.
6
6
 
@@ -37,8 +37,10 @@ Comprehensive guide covering installation, native setup (iOS & Android), and bui
37
37
  8. [Background API Auto-Sync When App Is Killed (`Widget.setRemoteConfig`)](#8-background-api-auto-sync-when-app-is-killed-widgetsetremoteconfig)
38
38
  9. [Managing All 3 Push Token Types (APNs & FCM)](#9-managing-all-3-push-token-types-apns--fcm)
39
39
  10. [State Machine & Timed Phases (`phases`)](#10-state-machine--timed-phases-phases)
40
- 11. [Server Push Payload Structure (APNs & FCM)](#11-server-push-payload-structure-apns--fcm)
41
- 12. [Troubleshooting](#12-troubleshooting)
40
+ 11. [Server Push Payload Structure (APNs & FCM)](#10-server-push-payload-structure-apns--fcm)
41
+ 12. [Troubleshooting](#11-troubleshooting)
42
+ 13. [Advanced Styling Modifiers, UI IR, Exact Hit Layer & Platform Matrix (v1.2.1)](#12-advanced-styling-modifiers--platform-capability-matrix)
43
+ 14. [TypeScript-Driven Swift Codegen & Automated i18n Sync (`widgets.config.ts`)](#14-typescript-driven-swift-codegen--automated-i18n-sync-widgetsconfigts)
42
44
 
43
45
  ---
44
46
 
@@ -76,32 +78,47 @@ npx expo run:ios # or npx expo run:android
76
78
 
77
79
  ## 3. Installation & Project Setup
78
80
 
79
- ### For Expo Projects
80
- If you are using **Expo**, the library provides an **Expo Config Plugin (`app.plugin.js`)** and **CLI Wizard** out of the box.
81
- 👉 **See the dedicated step-by-step guide: [Expo Integration Guide (EXPO-GUIDE-EN.md)](./EXPO-GUIDE-EN.md)**
81
+ ### 📋 CLI Command Cheat Sheet
82
+
83
+ | Command | Purpose | When to use |
84
+ | :--- | :--- | :--- |
85
+ | `npx react-native-live-widgets init` | **All-in-One Automated Setup**: Configures `app.json` (Expo), Xcode Extension target, Entitlements, App Groups, Podfile, `pod install`, Android permissions, default `widgets.config.ts`, SF Symbols/Material Icons sync, and Swift bundle codegen. | First time setting up the library in your project |
86
+ | `npx react-native-live-widgets codegen` | **Sync & Re-generate**: Re-reads `widgets.config.ts` and syncs `LiveWidgetsBundle.swift`, iOS `Localizable.xcstrings`, Android `strings.xml`, and type definitions. | Whenever you edit `widgets.config.ts` or add new widgets/locales |
87
+ | `npx react-native-live-widgets init --group <name>` | **Custom App Group**: Explicitly specify your App Group identifier (e.g. `group.com.mycompany.app`). | If you prefer a custom group instead of auto-detection |
88
+
89
+ ---
90
+
91
+ ### Option A: For Expo Projects (Managed / CNG)
82
92
 
83
93
  ```bash
84
94
  # 1. Install package
85
95
  npx expo install react-native-live-widgets
86
96
 
87
- # 2. Add plugin to app.json & generate native projects
88
- npx expo prebuild
97
+ # 2. Automated one-command setup (updates app.json, creates widgets.config.ts, syncs icons & bundle)
98
+ npx react-native-live-widgets init
89
99
 
90
- # 3. Automatically link and configure Widget Extension
91
- npx react-native-live-widgets init --group group.com.yourcompany.app
100
+ # 3. Launch on Simulator / Emulator
101
+ npx expo run:ios
102
+ # or: npx expo run:android
92
103
  ```
93
104
 
105
+ > 👉 **See the dedicated step-by-step guide: [Expo Integration Guide (EXPO-GUIDE-EN.md)](./EXPO-GUIDE-EN.md)**
106
+
94
107
  ---
95
108
 
96
- ### Package Installation (Bare React Native CLI)
97
- From the root directory of your React Native project:
109
+ ### Option B: For Bare React Native CLI
110
+
98
111
  ```bash
112
+ # 1. Install package
99
113
  npm install react-native-live-widgets
100
- # or
101
- yarn add react-native-live-widgets
114
+ # or: yarn add react-native-live-widgets
115
+
116
+ # 2. Automated one-command setup (links Xcode target, Podfile, pod install, Android permissions, widgets.config.ts, codegen)
117
+ npx react-native-live-widgets init
102
118
 
103
- # Automatically configure Info.plist, Entitlements, AndroidManifest & Widget templates
104
- npx react-native-live-widgets init --group group.com.yourcompany.app
119
+ # 3. Launch on Simulator / Emulator
120
+ npx react-native run-ios
121
+ # or: npx react-native run-android
105
122
  ```
106
123
 
107
124
  ---
@@ -536,15 +553,38 @@ UI.Image({
536
553
  cornerRadius: 8,
537
554
  })
538
555
 
539
- // 3. System Icon (SF Symbols on iOS / Vector Mapping on Android)
556
+ // 3. Cross-Platform System Icons (Apple SF Symbols + Google Material Icons)
557
+ // Option A: Automatically mapped on both platforms
540
558
  UI.Image({
541
- systemName: 'bicycle',
542
- tintColor: '#FB923C',
543
- width: 18,
544
- height: 18,
559
+ systemName: 'bolt',
560
+ tintColor: '#10B981',
561
+ width: 20,
562
+ height: 20,
545
563
  })
564
+
565
+ // Option B: Explicitly specify platform-dedicated icons (with 9,500+ SF Symbols & 3,800+ Material Icons Auto-Complete types)
566
+ UI.Image({
567
+ systemNameIos: 'bolt.horizontal.fill', // 9,500+ Apple SF Symbols
568
+ systemNameAndroid: 'bolt', // 3,800+ Google Material Icons (supports snake_case and kebab-case)
569
+ tintColor: '#10B981',
570
+ width: 24,
571
+ height: 24,
572
+ })
573
+
574
+ // Or using React JSX Component syntax:
575
+ <Image
576
+ systemNameIos="person.crop.circle.badge.checkmark"
577
+ systemNameAndroid="verified_user"
578
+ tintColor="#10B981"
579
+ width={24}
580
+ height={24}
581
+ />
546
582
  ```
547
583
 
584
+ > 💡 **Official Icon Catalogs & Galleriy Links:**
585
+ > - 🍏 **Apple SF Symbols (9,500+ Icons)**: Browse and preview symbols at [Apple SF Symbols Official Website](https://developer.apple.com/sf-symbols/). Fully typed via `KnownSFSymbol` auto-complete.
586
+ > - 🤖 **Google Material Icons (3,800+ Icons)**: Browse icon names at [Google Fonts Icons / Material Symbols](https://fonts.google.com/icons). Fully typed via `KnownMaterialIcon`, supporting both `snake_case` (e.g. `battery_charging_full`) and `kebab-case` (`battery-charging-full`).
587
+
548
588
  ### `UI.Button` (Interactive Widget Buttons)
549
589
  Lets users interact directly on the Widget surface (via iOS 17+ `AppIntents` and Android `PendingIntent` hit zones) **without opening the app**:
550
590
  ```typescript
@@ -944,6 +984,389 @@ phases: [
944
984
 
945
985
  ---
946
986
 
987
+ ---
988
+
989
+ ## 12. Advanced Styling Modifiers & Platform Capability Matrix
990
+
991
+ ### 12.1. Styling Modifiers Reference
992
+
993
+ Elevate your widgets and Live Activities with design system fundamentals:
994
+
995
+ 1. **🌈 Linear & Radial Gradients**:
996
+ ```tsx
997
+ <VStack
998
+ gradient={{
999
+ colors: ['#1E3A8A', '#3B82F6'],
1000
+ startPoint: { x: 0, y: 0 },
1001
+ endPoint: { x: 1, y: 1 },
1002
+ angle: 45,
1003
+ }}
1004
+ padding={16}
1005
+ >
1006
+ <Text typography="headline" color="#FFFFFF">Gradient Card</Text>
1007
+ </VStack>
1008
+ ```
1009
+ > [!TIP]
1010
+ > **Graceful Fallback**: If an older OS version or platform does not support gradient shaders, the renderer automatically uses the first color in `colors` as the solid fallback `backgroundColor`.
1011
+
1012
+ 2. **🔲 Borders & Dashed Lines**:
1013
+ ```tsx
1014
+ <VStack
1015
+ borderWidth={1.5}
1016
+ borderColor="#38BDF8"
1017
+ borderStyle="dashed"
1018
+ borderRadius={12}
1019
+ padding={12}
1020
+ >
1021
+ <Text fontSize={12} color="#94A3B8">Dashed card border</Text>
1022
+ </VStack>
1023
+ ```
1024
+
1025
+ 3. **🌑 Shadows & Elevation**:
1026
+ ```tsx
1027
+ <Button
1028
+ title="Confirm"
1029
+ backgroundColor="#2563EB"
1030
+ shadowColor="#2563EB"
1031
+ shadowRadius={6}
1032
+ shadowOpacity={0.4}
1033
+ shadowOffset={{ x: 0, y: 3 }}
1034
+ />
1035
+ ```
1036
+
1037
+ 4. **🔤 Typography & Dynamic Type (Accessibility Scaling)**:
1038
+ - Scale levels: `largeTitle` (34), `title1` (28), `title2` (22), `title3` (20), `headline` (17 bold), `body` (17 regular), `callout` (16), `subheadline` (15), `footnote` (13), `caption1` (12), `caption2` (11).
1039
+ - `fontDesign`: `'default' | 'monospaced' | 'rounded' | 'serif'`.
1040
+ - `dynamicType`: Defaults to `true` — automatically respects the user's OS Accessibility font size setting.
1041
+
1042
+ 5. **🌗 Tinted / Dark Mode (iOS 18 Accentable & Android Dynamic Theming)**:
1043
+ ```tsx
1044
+ <Text color={{ light: '#0F172A', dark: '#F8FAFC', tinted: '#38BDF8' }}>
1045
+ Theme-adaptive text
1046
+ </Text>
1047
+ ```
1048
+
1049
+ 6. **🌍 RTL Internationalization**:
1050
+ ```tsx
1051
+ <HStack direction="rtl" isRTL={true} spacing={8}>
1052
+ <Text>مرحبا بك</Text>
1053
+ </HStack>
1054
+ ```
1055
+
1056
+ ---
1057
+
1058
+ ### 12.2. Platform Capability & Fallback Matrix
1059
+
1060
+ Rather than making unverified claims of "100% parity", the engine provides an explicit, transparent capability matrix paired with automatic **Graceful Fallbacks**:
1061
+
1062
+ | Feature / Modifier | iOS WidgetKit | iOS Live Activity | Android Ongoing Notification | Android Home Widget | Graceful Fallback Strategy |
1063
+ | :--- | :---: | :---: | :---: | :---: | :--- |
1064
+ | **Declarative Layouts (`VStack`/`HStack`/`Grid`)** | ✅ SwiftUI | ✅ SwiftUI | ✅ Canvas | ✅ 2D Canvas | 100% pixel-aligned cross-platform |
1065
+ | **Linear / Radial Gradients** | ✅ SwiftUI | ✅ SwiftUI | ✅ Shader | ✅ Shader | Automatically falls back to dominant solid `backgroundColor` |
1066
+ | **Card & Text Shadows** | ✅ SwiftUI | ✅ SwiftUI | ⚠️ Text Only | ✅ `setShadowLayer` | Falls back to elevation or thin border stroke |
1067
+ | **Dashed / Dotted Borders** | ✅ StrokeStyle | ✅ StrokeStyle | ⚠️ Solid | ✅ `DashPathEffect` | Automatically falls back to solid border |
1068
+ | **Dynamic Type (Accessibility)** | ✅ Native | ✅ Native | ✅ `fontScale` | ✅ `fontScale` | Automatically scales with OS font multiplier |
1069
+ | **RTL Layout Mirroring** | ✅ Native | ✅ Native | ✅ RTL | ✅ RTL | Reverses flex order and flips text alignment |
1070
+ | **Accessibility (TalkBack / VoiceOver)** | ✅ Native VoiceOver | ✅ Native VoiceOver | ✅ Notification Text | ✅ A11y Summary + Hit-Zones | Aggregated semantic `contentDescription` ensures full screen-reader readability |
1071
+ | **iOS 18 Tinted Mode** | ✅ Accentable | N/A | N/A | ✅ Material You | Resolves `tinted` key on iOS 18; falls back to dark/light color |
1072
+ | **Interactive Background Intents** | ✅ iOS 17+ | ✅ iOS 17+ | ✅ PendingIntent | ✅ PendingIntent | Updates local Shared Storage and refreshes timeline |
1073
+
1074
+ ---
1075
+
1076
+ ### 12.3. ♿ Accessibility & Semantics (Phase 1 Fallback Layer)
1077
+
1078
+ To ensure users with visual impairments or screen-reader users (**VoiceOver on iOS**, **TalkBack on Android**) receive full context, the engine provides standard accessibility props:
1079
+
1080
+ ```tsx
1081
+ <VStack padding={16} backgroundColor="#0F172A">
1082
+ {/* Header with semantic role */}
1083
+ <Text
1084
+ typography="title2"
1085
+ accessibilityRole="header"
1086
+ accessibilityLabel="Shift Attendance Dashboard"
1087
+ >
1088
+ ATTENDANCE DASHBOARD
1089
+ </Text>
1090
+
1091
+ {/* Progress gauge with spoken percentage */}
1092
+ <Progress
1093
+ value={0.86}
1094
+ accessibilityLabel="Shift completion progress"
1095
+ accessibilityValue="86 percent"
1096
+ />
1097
+
1098
+ {/* Interactive button with action hint */}
1099
+ <Button
1100
+ title="Clock In"
1101
+ actionId="CLOCK_IN"
1102
+ accessibilityRole="button"
1103
+ accessibilityLabel="Clock in to shift"
1104
+ accessibilityHint="Double tap to confirm attendance"
1105
+ />
1106
+
1107
+ {/* Decorative element hidden from screen readers */}
1108
+ <Image systemName="sparkles" accessible={false} />
1109
+ </VStack>
1110
+ ```
1111
+
1112
+ #### How Phase 1 Accessibility Works:
1113
+ 1. **iOS (SwiftUI)**: Maps directly to native `.accessibilityLabel()`, `.accessibilityHint()`, `.accessibilityValue()`, and `.accessibilityAddTraits()`. Elements with `accessible={false}` receive `.accessibilityHidden(true)`.
1114
+ 2. **Android (Canvas 2D)**:
1115
+ - Recursively extracts an intelligent text summary (`extractAccessibilitySummary`) and binds it to the canvas `ImageView`'s `contentDescription`.
1116
+ - Each interactive hit-zone receives its own `contentDescription` and action hint so TalkBack speaks each button individually when focused.
1117
+ 3. **In-App Preview**: Maps to React Native Web/Mobile accessibility props.
1118
+
1119
+ ---
1120
+
1121
+ ### 12.4. Programmatic Capability Inspection (`Widget.getCapabilities`)
1122
+ ```typescript
1123
+ const caps = await Widget.getCapabilities();
1124
+ console.log(`Running on: ${caps.platform} (OS: ${caps.osVersion})`);
1125
+
1126
+ if (caps.supportsDynamicIsland) {
1127
+ console.log('Device has Dynamic Island hardware!');
1128
+ }
1129
+
1130
+ if (caps.supportsTintedMode) {
1131
+ console.log('Device supports iOS 18 Tinted Home Screen mode!');
1132
+ }
1133
+ ```
1134
+
1135
+ ---
1136
+
1137
+ ### 12.5. 🌲 UI Intermediate Representation (IR) & Semantic Tree (Phase 2)
1138
+
1139
+ Rather than compiling directly from `DSL ➔ Canvas Bitmap`, the engine introduces a decoupled **UI Intermediate Representation (IR v2.0)** and a **Renderer Planner**:
1140
+
1141
+ ```
1142
+ React Native DSL (JSX / UI.*)
1143
+ ↓
1144
+ UI Intermediate Representation (IR v2.0)
1145
+ ├── UI Tree (unique ID for every node)
1146
+ ├── Semantic Tree (independent of visual renderer)
1147
+ ├── State Bindings (toggle:<key>, page:<id>)
1148
+ └── Renderer Planner (classifies Native RemoteViews vs Canvas Bitmap)
1149
+ ↓
1150
+ ├── [NATIVE] RemoteViews (TextView, Button, ProgressBar)
1151
+ └── [CANVAS] Canvas 2D Bitmap (Gauge 240°, Equalizer, Shader)
1152
+ ```
1153
+
1154
+ #### Inspecting and Compiling IR:
1155
+ ```typescript
1156
+ import { Widget, UI } from 'react-native-live-widgets';
1157
+
1158
+ const layout = UI.VStack({
1159
+ padding: 16,
1160
+ backgroundColor: '#0F172A',
1161
+ children: [
1162
+ UI.Text('ATTENDANCE DASHBOARD', { typography: 'title2' }),
1163
+ UI.Progress({ value: 0.86, accessibilityLabel: 'Shift completion' }),
1164
+ UI.Button({ title: 'Clock In', actionId: 'toggle:attendance' }),
1165
+ UI.Gauge({ value: 0.92, label: 'Efficiency' })
1166
+ ]
1167
+ });
1168
+
1169
+ // 1. Inspect architectural plan and accessibility synthesis
1170
+ console.log(Widget.inspectIR(layout));
1171
+
1172
+ // 2. Compile to raw IR object
1173
+ const ir = Widget.compileIR(layout);
1174
+ console.log('Synthesized A11y Summary:', ir.semanticSummary);
1175
+ ```
1176
+
1177
+ ---
1178
+
1179
+ ### 12.6. ⚡ Native State Sync, Sub-renderer Optimization & Automated Test Suite
1180
+
1181
+ #### 1. Native State Synchronization (Phase 4):
1182
+ - Instant action & toggle responses: Native Android (`LiveActivityReceiver.kt` & `DynamicWidgetStateStore`) immediately updates `SharedPreferences` and triggers a widget redraw with zero UI lag even if the app was killed.
1183
+ - React hooks (`useWidgetStorage`, `useWidgetAction`) reconcile the latest state upon app launch.
1184
+
1185
+ #### 2. Canvas Sub-renderer Optimization (Phase 5):
1186
+ - `renderSubNodeBitmap`: Isolates bitmap allocation solely to the sub-component's bounding box (e.g. 64dp Gauge consumes only ~40KB bitmap) instead of allocating a full-screen canvas bitmap.
1187
+ - Completely avoids Android Binder IPC `TransactionTooLargeException`.
1188
+
1189
+ #### 3. Advanced JSX Components & Automated Tests (Phase 6):
1190
+ - New JSX components: `<Toggle>`, `<Switch>`, and `<Checkbox>` with `checked`/`isChecked`, `tintColor`, and `strikethroughOnCheck`.
1191
+ - Automated test suite verifying 100% assertions:
1192
+ ```bash
1193
+ npm test
1194
+ ```
1195
+
1196
+ ---
1197
+
1198
+ ### 12.7. 🎯 Exact Dynamic Hit Layer, Live Chronometer Countdown & Swift 6 Compatibility (v1.2.1)
1199
+
1200
+ Version **v1.2.1** addresses critical real-world interaction challenges on physical devices:
1201
+
1202
+ #### 1. Exact Dynamic Hit Layer
1203
+ * **Previous Issue**: With static coordinate grids, layout reflows or dynamic content caused buttons to trigger adjacent items or blank spaces to activate phantom taps.
1204
+ * **v1.2.1 Solution**:
1205
+ - Replaced the fixed grid with a dynamic `FrameLayout` container (`rn_hit_layer` paired with `rn_live_widget_hit_zone.xml`).
1206
+ - Implemented the **`computeCanvasMapping`** algorithm to calculate aspect ratio letterboxing (`fitCenter`) between the Canvas Bitmap and the Launcher Widget bounds.
1207
+ - Generates independent RemoteViews hit zones that align 100% with the rendered element bounding box. Empty areas receive no touch events.
1208
+
1209
+ #### 2. Native Live Countdown Chronometer (`android.widget.Chronometer`)
1210
+ * **Previous Issue**: Drawing countdown text directly on Canvas required broadcasting and re-rendering the bitmap every second, causing battery drain and rate-limiting from Android system schedulers.
1211
+ * **v1.2.1 Solution**:
1212
+ - Integrated native `android.widget.Chronometer` into the widget host layout.
1213
+ - Automatically configured with `setChronometerCountDown(true)` and `baseMillis = SystemClock.elapsedRealtime() + remainingMillis`.
1214
+ - The renderer suppresses static timer text when an active chronometer is present, allowing continuous 1-second countdown ticks driven natively by Android OS.
1215
+
1216
+ #### 3. Dynamic Template Variable Interpolation & Initial State Store
1217
+ * **Variable Interpolation**: Supports dynamic string templates (`{{id}}`, `{{title}}`, counter values) directly in the layout JSON, automatically resolved against action responses and local state.
1218
+ * **`defaultChecked` Persistence**: Switches and checkboxes with `checked: true` have their initial state committed to `DynamicWidgetStateStore` on initial render, allowing them to be toggled off immediately on the first tap.
1219
+
1220
+ #### 4. Swift 6 Language Mode Compatibility (iOS Xcode)
1221
+ * **Resolved `type '()' cannot conform to 'View'`**:
1222
+ - Encapsulated `Font` resolution in `renderText()` within self-invoking closures `{ ... }()`.
1223
+ - Refactored `DynamicNodeAccessibilityModifier` procedural assignments into a dedicated `buildAccessibilityView(content:) -> AnyView` helper method.
1224
+ - Added fallback `else { EmptyView() }` branches to `backgroundView` and `borderOverlay` in `ContainerStyleModifier`.
1225
+
1226
+ ---
1227
+
1228
+ ### 12.8. 📱 Extended Widget Families (`extraLarge`, `standBy`, `ControlWidget`) & Complete Live Activity Lifecycle
1229
+
1230
+ #### 1. Extended Widget Families
1231
+ Beyond `small`, `medium`, `large`, and Lock Screen (`accessoryRectangular`, `accessoryCircular`, `accessoryInline`) layouts:
1232
+ - **`extraLarge?: LayoutNode`**: Targets iPadOS (`systemExtraLarge`) and Android tablets (`widgetHeightDp >= 280dp`). Supported in `<WidgetPreview size="extraLarge">`.
1233
+ - **`standBy?: LayoutNode`**: Automatically activated in iOS 17+ StandBy Mode (`family == .systemSmall && !showsWidgetContainerBackground`), alongside `.applyStandByMargins()` and `widgetAccentable` support on `Text`, `Progress`, `Gauge`, and `Image`. Supported in `<WidgetPreview size="standBy">`.
1234
+ - **iOS 18+ Control Widgets & Android Quick Settings Tile (`ControlWidget` / `Widget.setControl`)**: Configure iOS 18 Control Center, Lock Screen controls, and Action Button widgets natively via `ios/Widgets/DynamicControlWidget.swift` (`DynamicControlWidget` & `DynamicControlToggleWidget`) and Android Quick Settings Tiles via `DynamicQuickSettingsTileService.kt`, connected directly to `DynamicWidgetStateStore` and `useWidgetAction`:
1235
+ ```typescript
1236
+ import { ControlWidget, UI, WidgetPreview } from 'react-native-live-widgets';
1237
+
1238
+ const shiftControl = ControlWidget.toggle({
1239
+ title: 'Work Shift',
1240
+ subtitle: 'Tap to clock in',
1241
+ checkedTitle: 'On Shift',
1242
+ checkedSubtitle: 'Tap to clock out',
1243
+ systemName: 'clock.badge.checkmark.fill',
1244
+ checked: true,
1245
+ actionId: 'toggle:attendance',
1246
+ });
1247
+
1248
+ await ControlWidget.set('toggle', shiftControl);
1249
+ // Also supports UI.ControlButton({ ... }) and Widget.setControl('main', ...)
1250
+ // Preview in-app: <WidgetPreview size="control" controlConfig={shiftControl} />
1251
+ ```
1252
+
1253
+ #### 2. Complete Live Activity Lifecycle API
1254
+ - **Multi-Activity Management**: `LiveActivity.getActiveActivities()`, `LiveActivity.get(activityId)`, `LiveActivity.isActive(activityId)`, and `LiveActivity.endAll()` return user-assigned `activityId`, `systemActivityId`, state flags, and tokens.
1255
+ - **Stale State (`staleTimestamp`, `staleLockScreen`, `staleDynamicIsland`)**: Automatically transitions UI to fallback views when stale (`context.isStale` on iOS 16.2+ / timestamp check on Android).
1256
+ - **Relevance Score (`relevanceScore`)**: Prioritizes ordering in Dynamic Island / Lock Screen (`ActivityContent.relevanceScore`) and Android Notification Shade (`setSortKey`).
1257
+ - **Alert Configuration (`alertConfig`)**: Supports `{ title, body, sound }` via iOS 16.2+ `AlertConfiguration` and Android notification alerts on updates.
1258
+ - **Scheduled End & Auto-Expiration (`scheduledEndTimestamp`, `autoEndAfterSeconds`, `expiredLockScreen`, `expiredDismissalPolicy`)**: Automatically updates or dismisses activities on expiration, plus `LiveActivity.cleanupExpired()` and `LiveActivity.onStateChange((ev) => ...)` emitting `'active' | 'started_by_push' | 'stale' | 'expired' | 'ended' | 'dismissed'`.
1259
+ - **Upgraded `useLiveActivity()` Hook**: Exposes `activities`, `lifecycleState`, `isStale`, `refreshActivities`, and `cleanupExpired`.
1260
+
1261
+ ---
1262
+
1263
+ ### 12.9. 🔄 Background Data Engine 2.0 & Structured Data Binding
1264
+
1265
+ `Widget.setRemoteConfig` and `Widget.createDataBinding<T>()` provide a complete native background data engine on both iOS WidgetKit Extension and Android even after the main app is force-killed:
1266
+
1267
+ | Category | Native Capabilities (iOS SwiftUI + Android) |
1268
+ | :--- | :--- |
1269
+ | **REST & Auth** | `url`, `method` (`GET`/`POST`/`PUT`), JSON `body`, custom `headers`, and **`authRefresh`** (automatically refreshes tokens on HTTP `401` and retries) |
1270
+ | **Network & Cache** | **`cacheTtlSeconds`** to avoid redundant fetches across timeline reloads, **`enableETag`** (`If-None-Match`/`If-Modified-Since` + HTTP `304 Not Modified`), **`timeoutMs`**, and **`maxRetries` + `retryDelayMs`** (Exponential Backoff) |
1271
+ | **Multi-Source & Transform** | **`sources`** to fetch & namespace multiple APIs (`<sourceKey>.<nested.path>`), recursive JSON Flattener (`user.name`, `items.0.title`), declarative **`mapping`**, and **`schema`** validation (`requiredKeys`, `types`, `defaults`) |
1272
+ | **Error State** | System tokens `{{_syncStatus}}` (`ok` / `partial` / `error`), `{{_syncError}}`, `{{_httpStatus}}`, plus **`errorFallback`** `LayoutNode` while preserving valid cached data on failures |
1273
+ | **Structured Data Binding** | `Widget.createDataBinding<T>()` & `UI.bind(path, pipes)` supporting nested paths & Native Pipes (`default`, `divide`, `multiply`, `add`, `round`, `upper`, `lower`, `currency`, `percent`, `if`) |
1274
+
1275
+ ```tsx
1276
+ const data = Widget.createDataBinding<{
1277
+ user: { name: string };
1278
+ attendance: { progress: number };
1279
+ }>({
1280
+ defaults: { user: { name: 'Employee' }, attendance: { progress: 0 } },
1281
+ });
1282
+
1283
+ await Widget.setLayout('main', {
1284
+ medium: (
1285
+ <VStack padding={14} spacing={6}>
1286
+ <Text>{data.user.name}</Text>
1287
+ <Text>{data.attendance.progress}%</Text>
1288
+ <Progress value={data.attendance.progress.divide(100)} />
1289
+ </VStack>
1290
+ ),
1291
+ });
1292
+
1293
+ await Widget.setRemoteConfig('main', {
1294
+ cacheTtlSeconds: 300,
1295
+ timeoutMs: 6000,
1296
+ enableETag: true,
1297
+ maxRetries: 2,
1298
+ retryDelayMs: 500,
1299
+ sources: {
1300
+ user: { url: 'https://api.yourapp.com/me' },
1301
+ attendance: { url: 'https://api.yourapp.com/attendance/today' },
1302
+ },
1303
+ schema: { requiredKeys: ['user.name', 'attendance.progress'], types: { 'attendance.progress': 'number' } },
1304
+ authRefresh: { url: 'https://api.yourapp.com/auth/refresh', method: 'POST', tokenPath: 'accessToken' },
1305
+ errorFallback: <Text color="#F87171">Sync error ({{_httpStatus}}): {{_syncError}}</Text>,
1306
+ refreshIntervalMinutes: 15,
1307
+ });
1308
+ ```
1309
+
1310
+ > ⚠️ **Important OS Reload Budget Disclaimer:** Exact 15-minute background intervals are **not guaranteed** when the app is terminated. **Apple WidgetKit** enforces a dynamic daily reload budget (typically ~**40–70 reloads/day** depending on user engagement; `refreshIntervalMinutes` maps to `TimelineReloadPolicy.after(...)` as an earliest hint, not an exact cron guarantee). **Android** likewise enforces Doze Mode and App Standby Buckets. For real-time second-by-second updates, pair widgets with server pushes (APNs / FCM).
1311
+
1312
+ ---
1313
+
1314
+ ## 14. TypeScript-Driven Swift Codegen & Automated i18n Sync (`widgets.config.ts`)
1315
+
1316
+ Starting from version 1.2.1, you don't need to manually modify Swift bundle source files (`LiveWidgetsBundle.swift`) or configure localization files in Xcode. The entire configuration is defined in **100% TypeScript** via `widgets.config.ts` in your project root.
1317
+
1318
+ ### 1. Sample `widgets.config.ts`:
1319
+ ```typescript
1320
+ import { defineWidgetConfig } from 'react-native-live-widgets';
1321
+
1322
+ export default defineWidgetConfig({
1323
+ bundleName: 'LiveWidgetsBundle',
1324
+ liveActivity: true, // Enable/disable Live Activity Widget
1325
+ controlWidgets: true, // Enable Control Center Widget (iOS 18+)
1326
+ defaultLocale: 'en',
1327
+ locales: {
1328
+ en: {
1329
+ 'widgets.main.title': 'Live Widgets Utility',
1330
+ 'widgets.main.desc': 'Visual KPI and attendance tracking',
1331
+ },
1332
+ vi: {
1333
+ 'widgets.main.title': 'Tiện ích Live Widgets',
1334
+ 'widgets.main.desc': 'Theo dõi KPI và chấm công trực quan',
1335
+ },
1336
+ },
1337
+ widgets: [
1338
+ {
1339
+ key: 'main',
1340
+ kind: 'LiveWidget_main',
1341
+ displayName: 'widgets.main.title',
1342
+ description: 'widgets.main.desc',
1343
+ supportedFamilies: ['systemSmall', 'systemMedium', 'systemLarge'],
1344
+ },
1345
+ ],
1346
+ });
1347
+ ```
1348
+
1349
+ ### 2. Execute Codegen CLI:
1350
+ ```bash
1351
+ npx react-native-live-widgets codegen
1352
+ ```
1353
+
1354
+ This CLI command automatically:
1355
+ 1. **Syncs System Icons**: Automatically extracts **9,500+ Apple SF Symbols** from macOS and **3,800+ Google Material Icons** into auto-complete type definition files (`sf-symbols.generated.ts` & `material-icons.generated.ts`), providing full TypeScript IntelliSense.
1356
+ 2. **Generates Swift Source Bundle**: Creates `ios/LiveWidgetsExtension/LiveWidgetsBundle.swift` registering all configured Widgets and Control Center widgets.
1357
+ 3. **Synchronizes iOS Localization**: Generates modern Apple String Catalog `ios/LiveWidgetsExtension/Localizable.xcstrings` for all defined languages.
1358
+ 4. **Synchronizes Android Localization**: Automatically updates `android/app/src/main/res/values/strings.xml` (default locale) and `values-{lang}/strings.xml` for Android AppWidget localized names.
1359
+
1360
+ ---
1361
+
1362
+ ### 🌐 Online Interactive Web Documentation
1363
+
1364
+ - **Web Documentation & Live Simulator**: [https://react-native-vu.github.io/react-native-live-widgets/](https://react-native-vu.github.io/react-native-live-widgets/)
1365
+ - **AI Agent Quick Reference (`llms.txt`)**: [https://react-native-vu.github.io/react-native-live-widgets/llms.txt](https://react-native-vu.github.io/react-native-live-widgets/llms.txt)
1366
+ - **AI Agent Full Manual (`llms-full.txt`)**: [https://react-native-vu.github.io/react-native-live-widgets/llms-full.txt](https://react-native-vu.github.io/react-native-live-widgets/llms-full.txt)
1367
+
1368
+ ---
1369
+
947
1370
  ## 📄 License
948
1371
  MIT © vu-tran
949
1372