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/CHANGELOG.md CHANGED
@@ -2,6 +2,40 @@
2
2
 
3
3
  All notable changes to `react-native-live-widgets` will be documented in this file.
4
4
 
5
+ ## [1.2.2] - 2026-11-18
6
+ ### Added
7
+ - **All-in-One Automated Setup Integration**: `npx react-native-live-widgets init` now automatically runs the entire icon extraction and codegen pipeline out of the box (syncing 9,500+ Apple SF Symbols and 3,800+ Google Material Icons into TypeScript auto-complete, generating `LiveWidgetsBundle.swift`, and synchronizing string catalogs).
8
+ - **Auto-Generated `app.json` & Smart Project Detection**:
9
+ - Automatically creates `app.json` with `name` and `displayName` if missing, or completes missing fields.
10
+ - Accurately distinguishes between Bare React Native projects (plain `app.json`) and Expo projects (detecting `"expo"` configuration object or `package.json` dependency), avoiding incorrect Expo plugin injection on pure React Native CLI projects.
11
+ - **Automated Entrypoint Injection (`index.js` / `index.ts` / `index.tsx`)**:
12
+ - Automatically inspects the project's root entry file and safely registers `LiveActivity.registerBackgroundActionHandler()` before `AppRegistry.registerComponent` or `registerRootComponent`.
13
+ - Automatically injects `import { name as appName } from './app.json';` when referenced by `AppRegistry` if the import statement is missing.
14
+ - **Resilient Auto-Generation for Missing Native Files**:
15
+ - Automatically regenerates `LiveWidgetsExtension/Info.plist` if missing (resolving Xcode build error 65).
16
+ - Automatically generates `widgets.config.ts` with complete English JSDoc documentation if not found in project root.
17
+ - **Type Aliases & API Ergonomics**: Exported `defineWidgetConfig` (singular) alongside `defineWidgetsConfig` (plural) in `src/index.ts`.
18
+ - **Expo Android Prebuild Trigger**: Enhanced Expo Config Plugin (`app.plugin.js`) with an Android `withDangerousMod` hook to automatically sync Android `res/values-*/strings.xml` during `npx expo prebuild`.
19
+
20
+ ### Changed & Improved
21
+ - **100% English CLI Experience**: Standardized all terminal logs, banners, prompts, and completion messages in `cli/setup.js` and `cli/codegen.js` to clean, professional English.
22
+ - **Streamlined Documentation & Official Icon Galleries**:
23
+ - Rewrote the **Quick Start (3-step setup)** and added a CLI cheat sheet across `README.md`, `docs/GUIDE-VI.md`, `docs/GUIDE-EN.md`, `docs/EXPO-GUIDE-VI.md`, and `docs/EXPO-GUIDE-EN.md`.
24
+ - Updated `docs/index.html` with official links to Apple SF Symbols and Google Material Icons galleries, alongside a dynamic language switcher (EN / VI).
25
+ - Updated `docs/llms.txt` and `docs/llms-full.txt` with latest setup commands.
26
+
27
+ ## [1.2.1] - 2026-11-17
28
+ ### Added
29
+ - **Cross-Platform System Icons (SF Symbols & Material Icons)**: Dedicated `systemNameIos` and `systemNameAndroid` props with full TypeScript autocomplete for 9,500+ Apple SF Symbols (`KnownSFSymbol`) and 3,800+ Google Material Icons (`KnownMaterialIcon`), automatically rendered across iOS WidgetKit and Android Canvas.
30
+ - **TypeScript-Driven Swift Codegen CLI (`npx react-native-live-widgets codegen`)**: Configured via `widgets.config.ts` to automatically generate `LiveWidgetsBundle.swift`, sync Apple String Catalogs (`Localizable.xcstrings`), generate Android `res/values-*/strings.xml`, and automatically ensure/generate missing `LiveWidgetsExtension/Info.plist`.
31
+ - **English CLI Output**: Standardized all Codegen CLI and icon generation terminal logs to clean, professional English.
32
+
33
+ ### Fixed
34
+ - **iOS Swift 6 Compatibility**: Resolved `@ViewBuilder` type inference and closure encapsulation for `renderText()`, `DynamicNodeAccessibilityModifier`, and `ContainerStyleModifier` to prevent `type '()' cannot conform to 'View'` compiler error.
35
+ - **Android Exact Hit Layer**: Replaced fixed grid layout with dynamic `FrameLayout` hit zones (`rn_hit_layer`), accurately mapping bitmap coordinates with launcher aspect ratio letterboxing to eliminate touch offsets and misclicks.
36
+ - **Android Live Chronometer**: Integrated native `android.widget.Chronometer` with `setChronometerCountDown(true)` for smooth, real-time 1s countdown ticking without redrawing bitmaps.
37
+ - **Dynamic Variable Interpolation**: Added dynamic template variable resolution (`{{id}}`, `{{title}}`, counter values) and `defaultChecked` persistence in `DynamicWidgetStateStore`.
38
+
5
39
  ## [1.2.0] - 2026-11-16
6
40
  ### Added
7
41
  - **JSX / TSX Declarative DSL**: Support building Widgets and Live Activities directly using intuitive React JSX syntax (`<VStack>`, `<HStack>`, `<ZStack>`, `<Grid>`, `<Text>`, `<Button>`, `<Badge>`, `<Progress>`, `<Timer>`, `<Image>`, `<Spacer>`, `<Divider>`) instead of nested function calls `UI.VStack(...)`.
package/README.md CHANGED
@@ -150,7 +150,7 @@ Until now, adding **Live Activities** or **Home Screen Widgets** to a React Nati
150
150
  ```
151
151
  - The native Extension fetches fresh JSON and dynamically replaces `{{variables}}` in your widget layout in the background.
152
152
 
153
- ### 5. 🔔 APNs & FCM Token Management
153
+ ### 6. 🔔 APNs & FCM Token Management
154
154
  - One-call retrieval for all push tokens:
155
155
  ```ts
156
156
  const tokens = await LiveActivity.getAllPushTokens();
@@ -159,81 +159,158 @@ Until now, adding **Live Activities** or **Home Screen Widgets** to a React Nati
159
159
  // tokens.activityUpdateToken
160
160
  ```
161
161
 
162
- ---
162
+ ### 7. 🎨 Advanced Styling Modifiers & Platform Capability Matrix
163
163
 
164
- ## ⚡ Quick Start
164
+ Build deep, rich widgets with design system foundations across both platforms:
165
165
 
166
- ### 1. Installation
166
+ - **🌈 Gradients**: Linear and radial gradients on Containers, Cards, and Buttons:
167
+ ```tsx
168
+ <VStack gradient={{ colors: ['#1E3A8A', '#3B82F6'], angle: 90 }} padding={14}>
169
+ ```
170
+ - **🔲 Borders & Dashed Lines**: Full control over width, color, and stroke styles (`'solid' | 'dashed' | 'dotted'`).
171
+ - **🌑 Shadows & Depth**: Elevate cards with `shadowColor`, `shadowRadius`, `shadowOpacity`, and `shadowOffset`.
172
+ - **🔤 Typography & Dynamic Type**: Semantic scale (`largeTitle`, `title`, `headline`, `subheadline`, `body`, `caption`, `footnote`) with auto-scaling for OS Accessibility font sizes.
173
+ - **🌗 Light, Dark & Tinted Mode**: Support for iOS 18 Tinted Home Screen icons and Android Material You dynamic coloring via `{ light: '#FFF', dark: '#0F172A', tinted: '#38BDF8' }`.
174
+ - **🌍 RTL Internationalization**: Automatic reverse row alignment (`direction: 'rtl'` or `isRTL: true`) for Arabic, Hebrew, and other RTL locales.
175
+ - **♿ Accessibility & Semantics**: First-class TalkBack & VoiceOver support via `accessible`, `accessibilityLabel`, `accessibilityHint`, `accessibilityRole`, and `accessibilityValue`. Android Canvas generates an aggregated semantic summary on the canvas and individual `contentDescription` on interactive hit-zones.
176
+
177
+ #### 📊 Platform Capability & Fallback Matrix
178
+
179
+ Rather than making unverified claims of "100% parity", the engine provides an explicit, transparent capability matrix paired with automatic **Graceful Fallbacks**:
180
+
181
+ | Feature / Modifier | iOS WidgetKit | iOS Live Activity | Android Ongoing Notification | Android Home Widget | Graceful Fallback Mechanism |
182
+ | :--- | :---: | :---: | :---: | :---: | :--- |
183
+ | **Declarative Layouts (`VStack`/`HStack`/`Grid`)** | ✅ Native | ✅ Native | ✅ Canvas | ✅ 2D Canvas | 100% pixel-aligned across all platforms |
184
+ | **Accessibility (TalkBack / VoiceOver)** | ✅ Native VoiceOver | ✅ Native VoiceOver | ✅ Notification Text | ✅ A11y Summary + Hit-Zones | Aggregated `contentDescription` ensures full screen-reader readability |
185
+ | **Linear / Radial Gradients** | ✅ SwiftUI | ✅ SwiftUI | ✅ Shader | ✅ Shader | Automatically falls back to dominant solid `backgroundColor` |
186
+ | **Card & Text Shadows** | ✅ SwiftUI | ✅ SwiftUI | ⚠️ Text Only | ✅ `setShadowLayer` | Falls back to elevation or thin border stroke |
187
+ | **Dashed / Dotted Borders** | ✅ StrokeStyle | ✅ StrokeStyle | ⚠️ Solid | ✅ `DashPathEffect` | Automatically falls back to solid border |
188
+ | **Dynamic Type (Accessibility)** | ✅ Native | ✅ Native | ✅ `fontScale` | ✅ `fontScale` | Preserves accessibility scale factor across devices |
189
+ | **RTL Layout Mirroring** | ✅ Native | ✅ Native | ✅ RTL | ✅ RTL | Reverses flex order and flips text alignment |
190
+ | **iOS 18 Tinted Mode** | ✅ Accentable | N/A | N/A | ✅ Material You | Resolves `tinted` key on iOS 18; falls back to dark/light color |
191
+ | **Interactive Background Intents** | ✅ iOS 17+ | ✅ iOS 17+ | ✅ Native Intent | ✅ Native Intent | Updates local Shared Storage and refreshes timeline |
192
+
193
+ #### 🔍 Checking Runtime Capabilities Programmatically
194
+ ```ts
195
+ const caps = await Widget.getCapabilities();
196
+ if (caps.supportsGradients) {
197
+ console.log('Device supports native gradients!');
198
+ }
199
+ ```
167
200
 
168
- ```bash
169
- # React Native CLI
170
- npm install react-native-live-widgets
201
+ ### 8. 🎯 v1.2.1 Architecture: Exact Dynamic Hit Layer, Native Chronometer & UI IR
171
202
 
172
- # Expo (Managed or Bare)
173
- npx expo install react-native-live-widgets
174
- ```
203
+ Version **1.2.1** introduces an industry-grade architecture built on three core pillars:
204
+ - **Native Semantic Coverage**: Guaranteed accessibility metadata (`BaseSemanticProps`: `accessible`, `accessibilityRole`, `accessibilityLabel`, `accessibilityHint`, `accessibilityValue`) on all interactive controls plus aggregated `contentDescription` descriptions for graphical Canvas components (`Gauge`, `Chart`, `Equalizer`).
205
+ - **Native-first, Canvas-when-needed**: Native OS components handle interactions (`FrameLayout` Exact Hit Layer via `computeCanvasMapping` compensating for `fitCenter` letterboxing) and hardware timers (`android.widget.Chronometer` with `setChronometerCountDown(true)` for smooth 1s ticks without bitmap redraws); Canvas 2D draws rich visual elements only.
206
+ - **Renderer-Independent Semantic Tree (UI IR)**: Clean separation of Visual Nodes, Semantic Nodes, and State Bindings (`Widget.inspectIR(layout)`, `Widget.compileIR(layout)`).
207
+ - **Dynamic Variables & Swift 6 Ready**: Built-in template variable interpolation (`{{id}}`, `{{title}}`, counter values), `defaultChecked` initial switch state persistence, and full Swift 6 language mode compliance on Xcode.
208
+
209
+ ### 9. 🔣 Cross-Platform System Icons & 13,000+ Vector Symbols
210
+ - **Cross-Platform Auto-Mapping**: `<Image systemName="bolt" tintColor="#10B981" width={24} height={24} />` works on both iOS and Android.
211
+ - **Platform-Dedicated Props**: Specify dedicated icons for iOS and Android with full TypeScript auto-complete:
212
+ ```tsx
213
+ <Image
214
+ systemNameIos="bolt.horizontal.fill" // 9,500+ Apple SF Symbols (`KnownSFSymbol`)
215
+ systemNameAndroid="bolt" // 3,800+ Google Material Icons (`KnownMaterialIcon`)
216
+ tintColor="#10B981"
217
+ width={24}
218
+ height={24}
219
+ />
220
+ ```
221
+ - **Official Icon Catalogs**:
222
+ - 🍏 [Apple SF Symbols Official Gallery (9,500+ Icons)](https://developer.apple.com/sf-symbols/)
223
+ - 🤖 [Google Fonts Material Icons / Symbols (3,800+ Icons)](https://fonts.google.com/icons)
224
+
225
+ ### 10. ⚙️ TypeScript-Driven Codegen & Automated i18n (`widgets.config.ts`)
226
+ - Zero manual Swift coding. Define your widgets, bundle name, and multi-language catalogs in `widgets.config.ts`.
227
+ - Run `npx react-native-live-widgets codegen` to automatically generate:
228
+ - `LiveWidgetsBundle.swift` registering all widgets and Control Center toggles.
229
+ - Apple String Catalog (`Localizable.xcstrings`).
230
+ - Android resource strings (`android/app/src/main/res/values-*/strings.xml`).
231
+ - Latest system SF Symbols & Material Icons type definitions.
175
232
 
176
233
  ---
177
234
 
178
- ### 2. Configuration
179
-
180
- #### A. If using Expo (Config Plugin)
181
-
182
- Add `react-native-live-widgets` to your `app.json` or `app.config.js`:
183
-
184
- ```json
185
- {
186
- "expo": {
187
- "name": "My Expo App",
188
- "plugins": [
189
- [
190
- "react-native-live-widgets",
191
- {
192
- "appGroup": "group.com.yourcompany.app",
193
- "enableLiveActivities": true,
194
- "frequentUpdates": true
195
- }
196
- ]
197
- ]
198
- }
199
- }
200
- ```
235
+ ## ⚡ Quick Start: Essential Commands & Setup
236
+
237
+ Get Live Activities and Interactive Home Screen Widgets running in **less than 2 minutes** with zero manual native code.
201
238
 
202
- Then generate native projects or run with Expo Dev Client:
239
+ ### 📋 CLI Command Cheat Sheet
240
+
241
+ | Command | Purpose | When to use |
242
+ | :--- | :--- | :--- |
243
+ | `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 |
244
+ | `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 |
245
+ | `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 |
246
+
247
+ ---
248
+
249
+ ### Option A: Expo (SDK 50, 51, 52, 58+ CNG & EAS Build)
203
250
 
204
251
  ```bash
205
- # 1. Generate native folders
206
- npx expo prebuild
252
+ # 1. Install package
253
+ npx expo install react-native-live-widgets
207
254
 
208
- # 2. Automatically scaffold & link Xcode Widget Extension target
209
- npx react-native-live-widgets init --group group.com.yourcompany.app
255
+ # 2. Run automated setup (auto-updates app.json, creates widgets.config.ts, syncs icons & bundle)
256
+ npx react-native-live-widgets init
210
257
 
211
- # 3. Run on iOS Simulator & Android Emulator:
258
+ # 3. Launch on Simulator / Emulator
212
259
  npx expo run:ios
260
+ # or
213
261
  npx expo run:android
214
262
  ```
215
263
 
216
- > 📖 **Detailed Step-by-Step Expo Guide**: [English](docs/EXPO-GUIDE-EN.md) • [Tiếng Việt](docs/EXPO-GUIDE-VI.md)
264
+ > 💡 **What happens automatically:**
265
+ > - Injects the `react-native-live-widgets` Config Plugin into `app.json`.
266
+ > - Enables `NSSupportsLiveActivities` and `frequentUpdates` for iOS.
267
+ > - Auto-configures App Group Entitlements.
268
+ > - Injects Android notification & foreground service permissions.
269
+ > - Creates `widgets.config.ts` and triggers Swift Codegen.
270
+ > - 📖 [Read the Detailed Step-by-Step Expo Guide](docs/EXPO-GUIDE-EN.md) • [Hướng dẫn Expo Tiếng Việt](docs/EXPO-GUIDE-VI.md)
217
271
 
218
- #### B. If using Bare React Native CLI
272
+ ---
219
273
 
220
- Run the automated scaffolding script in your React Native project root:
274
+ ### Option B: Bare React Native CLI
221
275
 
222
276
  ```bash
223
- npx react-native-live-widgets init --group group.com.yourcompany.app
277
+ # 1. Install package
278
+ npm install react-native-live-widgets
279
+ # or: yarn add react-native-live-widgets
280
+
281
+ # 2. Run automated setup (links Xcode target, Podfile, pod install, Android permissions, codegen)
282
+ npx react-native-live-widgets init
283
+
284
+ # 3. Launch on Simulator / Emulator
285
+ npx react-native run-ios
286
+ # or
287
+ npx react-native run-android
224
288
  ```
225
289
 
226
- This will automatically:
227
- - Inject `NSSupportsLiveActivities` and `NSSupportsLiveActivitiesFrequentUpdates` into `Info.plist`.
228
- - Scaffold the `LiveWidgetsExtension` bundle in your `ios/` folder.
229
- - Configure `AndroidManifest.xml` with required notification permissions.
290
+ > 💡 **What happens automatically:**
291
+ > - Creates and links the `LiveWidgetsExtension` target in `ios/*.xcodeproj/project.pbxproj` with separate build phases.
292
+ > - Adds `NSSupportsLiveActivities` to `Info.plist` and creates `.entitlements` with App Group.
293
+ > - Copies native Swift models & UI renderers into `LiveWidgetsExtension/Shared/`.
294
+ > - Appends `pod 'react-native-live-widgets'` to `ios/Podfile` and executes `pod install`.
295
+ > - Verifies and updates `android/app/src/main/AndroidManifest.xml` permissions.
296
+ > - Creates `widgets.config.ts`, extracts 13,000+ vector icons, and compiles `LiveWidgetsBundle.swift`.
230
297
 
231
- And install CocoaPods dependencies:
298
+ ---
299
+
300
+ ### 🔄 Updating Widgets or Translations (`widgets.config.ts`)
301
+
302
+ Whenever you add or modify widgets in `widgets.config.ts`:
232
303
 
233
304
  ```bash
234
- cd ios && pod install
305
+ npx react-native-live-widgets codegen
235
306
  ```
236
307
 
308
+ This single command synchronizes:
309
+ 1. `ios/LiveWidgetsExtension/LiveWidgetsBundle.swift`
310
+ 2. `ios/LiveWidgetsExtension/Localizable.xcstrings` (iOS String Catalog)
311
+ 3. `android/app/src/main/res/values-*/strings.xml` (Android String Resources)
312
+ 4. Apple SF Symbols & Google Material Icons auto-completion definitions.
313
+
237
314
  ---
238
315
 
239
316
  ## 💻 Code Example
@@ -415,7 +492,9 @@ Nếu thư viện này giúp ích cho dự án hoặc công ty của bạn, bạ
415
492
 
416
493
  ## 📚 Documentation & Guides
417
494
 
418
- - 📱 **[LiveWidgetsExample Demo Project](https://github.com/React-Native-Vu/LiveWidgetsExample)**: Complete working sample app demonstrating all 5 presets with bidirectional sync on iOS & Android.
495
+ - 🌐 **[Official Interactive Web Documentation & Live Simulator](https://react-native-vu.github.io/react-native-live-widgets/)**: `https://react-native-vu.github.io/react-native-live-widgets/` — Full API reference, JSX/DSL examples, and interactive Dynamic Island simulator.
496
+ - 🤖 **[LLM & AI Agent Reference (`llms.txt` & `llms-full.txt`)](https://react-native-vu.github.io/react-native-live-widgets/llms.txt)**: `https://react-native-vu.github.io/react-native-live-widgets/llms-full.txt`
497
+ - 📱 **[LiveWidgetsExample Demo Project](https://github.com/React-Native-Vu/LiveWidgetsExample)**: Complete working sample app demonstrating all presets with bidirectional sync on iOS & Android.
419
498
  - 🇬🇧 **[Full English Developer Guide](docs/GUIDE-EN.md)**: Architecture, DSL specs, push notification server configuration, and best practices.
420
499
  - 🇻🇳 **[Hướng dẫn Chi tiết bằng Tiếng Việt](docs/GUIDE-VI.md)**: Hướng dẫn tích hợp từng bước, thiết lập App Group, giải quyết lỗi thường gặp.
421
500
 
@@ -35,5 +35,17 @@
35
35
  android:name="android.appwidget.provider"
36
36
  android:resource="@xml/rn_live_widget_info" />
37
37
  </receiver>
38
+
39
+ <!-- Android Quick Settings Tile (Control Widget tương đương iOS 18 Control Center) -->
40
+ <service
41
+ android:name=".DynamicQuickSettingsTileService"
42
+ android:label="Live Widgets Control"
43
+ android:icon="@android:drawable/ic_lock_power_off"
44
+ android:permission="android.permission.BIND_QUICK_SETTINGS_TILE"
45
+ android:exported="true">
46
+ <intent-filter>
47
+ <action android:name="android.service.quicksettings.action.QS_TILE" />
48
+ </intent-filter>
49
+ </service>
38
50
  </application>
39
51
  </manifest>
@@ -64,6 +64,21 @@ class LiveActivityModule(private val reactContext: ReactApplicationContext) :
64
64
  .emit("DevicePushTokenChanged", token)
65
65
  }
66
66
  }
67
+
68
+ @JvmStatic
69
+ fun emitStateChanged(activityId: String, state: String, pushToken: String? = null) {
70
+ val ctx = currentReactContext ?: return
71
+ if (!ctx.hasActiveReactInstance()) return
72
+ val map = Arguments.createMap().apply {
73
+ putString("activityId", activityId)
74
+ putString("state", state)
75
+ putDouble("timestamp", System.currentTimeMillis() / 1000.0)
76
+ val tok = pushToken ?: activityUpdateTokens[activityId]
77
+ if (tok != null) putString("pushToken", tok)
78
+ }
79
+ ctx.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
80
+ .emit("LiveActivityStateChanged", map)
81
+ }
67
82
  }
68
83
 
69
84
  @ReactMethod
@@ -88,6 +103,7 @@ class LiveActivityModule(private val reactContext: ReactApplicationContext) :
88
103
  putString("activityId", activityId)
89
104
  putString("token", tok)
90
105
  })
106
+ emitStateChanged(activityId, "active", tok)
91
107
  }.onSuccess {
92
108
  promise.resolve(true)
93
109
  }.onFailure {
@@ -112,6 +128,7 @@ class LiveActivityModule(private val reactContext: ReactApplicationContext) :
112
128
  @ReactMethod
113
129
  fun end(activityId: String, promise: Promise) {
114
130
  LiveActivityNotifier.end(reactContext, activityId)
131
+ emitStateChanged(activityId, "ended")
115
132
  activityUpdateTokens.remove(activityId)
116
133
  promise.resolve(true)
117
134
  }
@@ -128,6 +145,7 @@ class LiveActivityModule(private val reactContext: ReactApplicationContext) :
128
145
  if (seconds > 0) {
129
146
  android.os.Handler(android.os.Looper.getMainLooper()).postDelayed({
130
147
  LiveActivityNotifier.end(reactContext, activityId)
148
+ emitStateChanged(activityId, "ended")
131
149
  activityUpdateTokens.remove(activityId)
132
150
  }, seconds * 1000)
133
151
  promise.resolve(true)
@@ -138,7 +156,11 @@ class LiveActivityModule(private val reactContext: ReactApplicationContext) :
138
156
 
139
157
  @ReactMethod
140
158
  fun endAll(promise: Promise) {
159
+ val activeIds = LiveActivityNotifier.getActiveIds(reactContext)
141
160
  LiveActivityNotifier.endAll(reactContext)
161
+ for (id in activeIds) {
162
+ emitStateChanged(id, "ended")
163
+ }
142
164
  activityUpdateTokens.clear()
143
165
  promise.resolve(true)
144
166
  }
@@ -155,9 +177,14 @@ class LiveActivityModule(private val reactContext: ReactApplicationContext) :
155
177
  val activeIds = LiveActivityNotifier.getActiveIds(reactContext)
156
178
  val array = Arguments.createArray()
157
179
  for (id in activeIds) {
180
+ val meta = LiveActivityNotifier.getActivityMetadata(reactContext, id)
158
181
  val map = Arguments.createMap().apply {
159
182
  putString("activityId", id)
160
- putString("activityState", "active")
183
+ putString("activityState", if (meta.isStale) "stale" else "active")
184
+ putBoolean("isStale", meta.isStale)
185
+ meta.relevanceScore?.let { putDouble("relevanceScore", it) }
186
+ meta.staleTimestamp?.let { putDouble("staleTimestamp", it) }
187
+ meta.scheduledEndTimestamp?.let { putDouble("scheduledEndTimestamp", it) }
161
188
  activityUpdateTokens[id]?.let { putString("pushToken", it) }
162
189
  }
163
190
  array.pushMap(map)
@@ -285,8 +312,36 @@ class LiveActivityModule(private val reactContext: ReactApplicationContext) :
285
312
  DynamicWidgetStateStore.initializeFromLayoutJson(reactContext, value)
286
313
  }
287
314
 
315
+ if (key.startsWith("widget_bound_data_")) {
316
+ val wKey = key.removePrefix("widget_bound_data_")
317
+ DynamicWidgetStateStore.getPrefs(reactContext, appGroup)
318
+ .edit()
319
+ .remove("widget_remote_config_$wKey")
320
+ .apply()
321
+ runCatching {
322
+ val state = DynamicWidgetStateStore.loadState(reactContext)
323
+ val jsonObj = JSONObject(value)
324
+ DynamicWidgetStateStore.flattenJson(jsonObj, "", state.remoteVariables)
325
+ val syncTime = state.remoteVariables["_lastSyncTime"]
326
+ if (!syncTime.isNullOrEmpty()) {
327
+ state.lastSyncTime = syncTime
328
+ }
329
+ val status = state.remoteVariables["_syncStatus"]?.takeIf { it.isNotEmpty() } ?: "ok"
330
+ state.syncStatus = status
331
+ state.remoteVariables["_syncStatus"] = status
332
+ state.lastSyncError = null
333
+ state.remoteVariables["_syncError"] = ""
334
+ state.updatedAt = System.currentTimeMillis()
335
+ DynamicWidgetStateStore.saveState(reactContext, state)
336
+ }
337
+ }
338
+
288
339
  if (key.startsWith("widget_remote_config_")) {
289
340
  val wKey = key.removePrefix("widget_remote_config_")
341
+ DynamicWidgetStateStore.getPrefs(reactContext, appGroup)
342
+ .edit()
343
+ .remove("widget_bound_data_$wKey")
344
+ .apply()
290
345
  runCatching {
291
346
  val cfg = JSONObject(value)
292
347
  val mins = if (cfg.has("refreshIntervalMinutes")) {
@@ -296,6 +351,11 @@ class LiveActivityModule(private val reactContext: ReactApplicationContext) :
296
351
  }.coerceAtLeast(1)
297
352
  DynamicWidgetStateStore.scheduleBackgroundWidgetSync(reactContext, wKey, mins)
298
353
  }
354
+ DynamicWidgetStateStore.performRemoteSync(reactContext, wKey, forceRefresh = true)
355
+ }
356
+
357
+ if (key.startsWith("widget_control_")) {
358
+ DynamicQuickSettingsTileService.requestTileUpdate(reactContext)
299
359
  }
300
360
 
301
361
  DynamicWidgetImageCache.prefetchUrlsSync(reactContext, value)
@@ -34,24 +34,88 @@ data class NotificationButtonData(
34
34
  val actionId: String
35
35
  )
36
36
 
37
+ data class ActivityMetadata(
38
+ val isStale: Boolean,
39
+ val relevanceScore: Double?,
40
+ val staleTimestamp: Double?,
41
+ val scheduledEndTimestamp: Double?
42
+ )
43
+
37
44
  object LiveActivityNotifier {
38
45
  const val CHANNEL_ID = "live_activity_channel"
39
46
  private const val PREFS = "rn_live_widgets_prefs"
40
47
  private const val EXTRA_REQUEST_PROMOTED_ONGOING = "android.requestPromotedOngoing"
41
48
  private const val TICK_MILLIS = 30_000L
42
49
 
50
+ private fun normalizeEpochSeconds(ts: Double?): Double? {
51
+ if (ts == null || ts <= 0.0 || ts.isNaN()) return null
52
+ return if (ts > 10_000_000_000.0) ts / 1000.0 else ts
53
+ }
54
+
55
+ private fun enrichPayloadWithResolvedTimestamps(payloadJson: String): String {
56
+ return runCatching {
57
+ val json = JSONObject(payloadJson)
58
+ val now = System.currentTimeMillis() / 1000.0
59
+ if (json.has("scheduledEndTimestamp")) {
60
+ normalizeEpochSeconds(json.optDouble("scheduledEndTimestamp", -1.0))?.let {
61
+ json.put("__resolvedScheduledEnd", it)
62
+ }
63
+ } else if (json.has("autoEndAfterSeconds")) {
64
+ val secs = json.optDouble("autoEndAfterSeconds", -1.0)
65
+ if (secs > 0.0 && !secs.isNaN()) {
66
+ json.put("__resolvedScheduledEnd", now + secs)
67
+ }
68
+ }
69
+ if (json.has("staleTimestamp")) {
70
+ normalizeEpochSeconds(json.optDouble("staleTimestamp", -1.0))?.let {
71
+ json.put("__resolvedStaleTimestamp", it)
72
+ }
73
+ }
74
+ json.toString()
75
+ }.getOrElse { payloadJson }
76
+ }
77
+
78
+ fun getActivityMetadata(context: Context, activityId: String): ActivityMetadata {
79
+ val raw = prefs(context).getString(activityId, null)
80
+ ?: return ActivityMetadata(false, null, null, null)
81
+ return runCatching {
82
+ val json = JSONObject(raw)
83
+ val now = System.currentTimeMillis() / 1000.0
84
+ val staleTs = if (json.has("__resolvedStaleTimestamp")) {
85
+ json.optDouble("__resolvedStaleTimestamp", -1.0).takeIf { it > 0 }
86
+ } else if (json.has("staleTimestamp")) {
87
+ normalizeEpochSeconds(json.optDouble("staleTimestamp", -1.0))
88
+ } else null
89
+ val schedEndTs = if (json.has("__resolvedScheduledEnd")) {
90
+ json.optDouble("__resolvedScheduledEnd", -1.0).takeIf { it > 0 }
91
+ } else if (json.has("scheduledEndTimestamp")) {
92
+ normalizeEpochSeconds(json.optDouble("scheduledEndTimestamp", -1.0))
93
+ } else null
94
+ val score = if (json.has("relevanceScore")) json.optDouble("relevanceScore") else null
95
+ val isStale = staleTs != null && now >= staleTs
96
+ ActivityMetadata(
97
+ isStale = isStale,
98
+ relevanceScore = score,
99
+ staleTimestamp = staleTs,
100
+ scheduledEndTimestamp = schedEndTs
101
+ )
102
+ }.getOrElse { ActivityMetadata(false, null, null, null) }
103
+ }
104
+
43
105
  fun start(context: Context, activityId: String, payloadJson: String) {
44
- prefs(context).edit().putString(activityId, payloadJson).apply()
45
- DynamicWidgetImageCache.prefetchUrlsSync(context, payloadJson)
46
- showNotification(context, activityId, payloadJson)
47
- scheduleNextRefresh(context, activityId, payloadJson)
106
+ val enriched = enrichPayloadWithResolvedTimestamps(payloadJson)
107
+ prefs(context).edit().putString(activityId, enriched).apply()
108
+ DynamicWidgetImageCache.prefetchUrlsSync(context, enriched)
109
+ showNotification(context, activityId, enriched, isUpdate = false)
110
+ scheduleNextRefresh(context, activityId, enriched)
48
111
  }
49
112
 
50
113
  fun update(context: Context, activityId: String, payloadJson: String) {
51
- prefs(context).edit().putString(activityId, payloadJson).apply()
52
- DynamicWidgetImageCache.prefetchUrlsSync(context, payloadJson)
53
- showNotification(context, activityId, payloadJson)
54
- scheduleNextRefresh(context, activityId, payloadJson)
114
+ val enriched = enrichPayloadWithResolvedTimestamps(payloadJson)
115
+ prefs(context).edit().putString(activityId, enriched).apply()
116
+ DynamicWidgetImageCache.prefetchUrlsSync(context, enriched)
117
+ showNotification(context, activityId, enriched, isUpdate = true)
118
+ scheduleNextRefresh(context, activityId, enriched)
55
119
  }
56
120
 
57
121
  fun end(context: Context, activityId: String) {
@@ -75,7 +139,7 @@ object LiveActivityNotifier {
75
139
 
76
140
  fun refresh(context: Context, activityId: String) {
77
141
  val json = prefs(context).getString(activityId, null) ?: return
78
- showNotification(context, activityId, json)
142
+ showNotification(context, activityId, json, isUpdate = false)
79
143
  scheduleNextRefresh(context, activityId, json)
80
144
  }
81
145
 
@@ -83,18 +147,60 @@ object LiveActivityNotifier {
83
147
  val all = prefs(context).all
84
148
  for ((actId, value) in all) {
85
149
  val json = value as? String ?: continue
86
- showNotification(context, actId, json)
150
+ showNotification(context, actId, json, isUpdate = false)
87
151
  }
88
152
  }
89
153
 
90
- private fun showNotification(context: Context, activityId: String, payloadJson: String) {
154
+ private fun showNotification(
155
+ context: Context,
156
+ activityId: String,
157
+ payloadJson: String,
158
+ isUpdate: Boolean = false
159
+ ) {
91
160
  val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
92
161
  ensureChannel(manager)
93
162
 
94
163
  val json = JSONObject(payloadJson)
95
- val lockScreen = json.optJSONObject("lockScreen")
96
- val alertTitle = json.optString("alertTitle", "")
97
- val alertBody = json.optString("alertBody", "")
164
+ val now = System.currentTimeMillis() / 1000.0
165
+
166
+ val resolvedEnd = if (json.has("__resolvedScheduledEnd")) {
167
+ json.optDouble("__resolvedScheduledEnd", -1.0).takeIf { it > 0 }
168
+ } else if (json.has("scheduledEndTimestamp")) {
169
+ normalizeEpochSeconds(json.optDouble("scheduledEndTimestamp", -1.0))
170
+ } else null
171
+
172
+ val isExpired = resolvedEnd != null && now >= resolvedEnd
173
+ if (isExpired) {
174
+ val dismissal = json.optString("expiredDismissalPolicy", "immediate")
175
+ val expiredNode = json.optJSONObject("expiredLockScreen")
176
+ LiveActivityModule.emitStateChanged(activityId, "expired")
177
+ if (expiredNode == null || dismissal == "immediate") {
178
+ end(context, activityId)
179
+ return
180
+ }
181
+ }
182
+
183
+ val resolvedStale = if (json.has("__resolvedStaleTimestamp")) {
184
+ json.optDouble("__resolvedStaleTimestamp", -1.0).takeIf { it > 0 }
185
+ } else if (json.has("staleTimestamp")) {
186
+ normalizeEpochSeconds(json.optDouble("staleTimestamp", -1.0))
187
+ } else null
188
+ val isStale = resolvedStale != null && now >= resolvedStale
189
+ if (isStale && !isExpired) {
190
+ LiveActivityModule.emitStateChanged(activityId, "stale")
191
+ }
192
+
193
+ val lockScreen = when {
194
+ isExpired && json.has("expiredLockScreen") -> json.optJSONObject("expiredLockScreen")
195
+ isStale && json.has("staleLockScreen") -> json.optJSONObject("staleLockScreen")
196
+ else -> json.optJSONObject("lockScreen")
197
+ }
198
+
199
+ val alertObj = json.optJSONObject("alertConfig")
200
+ val alertTitle = alertObj?.optString("title", "")?.ifEmpty { null }
201
+ ?: json.optString("alertTitle", "")
202
+ val alertBody = alertObj?.optString("body", "")?.ifEmpty { null }
203
+ ?: json.optString("alertBody", "")
98
204
 
99
205
  val textLines = mutableListOf<String>()
100
206
  var targetTimestamp: Double? = null
@@ -134,14 +240,22 @@ object LiveActivityNotifier {
134
240
  )
135
241
  } else null
136
242
 
243
+ val shouldAlertOnUpdate = isUpdate && (alertTitle.isNotEmpty() || alertBody.isNotEmpty())
244
+
137
245
  val builder = NotificationCompat.Builder(context, CHANNEL_ID)
138
246
  .setSmallIcon(context.applicationInfo.icon)
139
247
  .setContentTitle(titleText)
140
248
  .setContentText(bodyText)
141
- .setOngoing(true)
142
- .setOnlyAlertOnce(true)
249
+ .setOngoing(!isExpired)
250
+ .setOnlyAlertOnce(!shouldAlertOnUpdate)
143
251
  .setPriority(NotificationCompat.PRIORITY_HIGH)
144
252
 
253
+ if (json.has("relevanceScore")) {
254
+ val score = json.optDouble("relevanceScore", 0.0).coerceIn(0.0, 1000.0)
255
+ val invertedKey = (100000.0 - score * 100.0).toInt().coerceAtLeast(0)
256
+ builder.setSortKey(String.format("%06d", invertedKey))
257
+ }
258
+
145
259
  if (bodyText.length > 42) {
146
260
  builder.setStyle(NotificationCompat.BigTextStyle().bigText(bodyText))
147
261
  }
@@ -164,7 +278,6 @@ object LiveActivityNotifier {
164
278
  }
165
279
 
166
280
  // 2. Xử lý thanh tiến trình đa dạng (UI.Progress)
167
- val now = System.currentTimeMillis() / 1000.0
168
281
  if (progressData != null) {
169
282
  applyProgressToNotification(builder, progressData!!, now)
170
283
  progressData?.tintColor?.let { hex ->
@@ -196,6 +309,11 @@ object LiveActivityNotifier {
196
309
  }
197
310
 
198
311
  manager.notify(activityId.hashCode(), builder.build())
312
+
313
+ if (isExpired) {
314
+ prefs(context).edit().remove(activityId).apply()
315
+ cancelRefresh(context, activityId)
316
+ }
199
317
  }
200
318
 
201
319
  private fun applyProgressToNotification(
@@ -249,6 +367,24 @@ object LiveActivityNotifier {
249
367
  }
250
368
  }
251
369
 
370
+ val resolvedStale = if (json.has("__resolvedStaleTimestamp")) {
371
+ json.optDouble("__resolvedStaleTimestamp", -1.0).takeIf { it > 0 }
372
+ } else normalizeEpochSeconds(json.optDouble("staleTimestamp", -1.0).takeIf { it > 0 })
373
+ if (resolvedStale != null && resolvedStale > now) {
374
+ if (nextTrigger == null || resolvedStale < nextTrigger) {
375
+ nextTrigger = resolvedStale
376
+ }
377
+ }
378
+
379
+ val resolvedEnd = if (json.has("__resolvedScheduledEnd")) {
380
+ json.optDouble("__resolvedScheduledEnd", -1.0).takeIf { it > 0 }
381
+ } else normalizeEpochSeconds(json.optDouble("scheduledEndTimestamp", -1.0).takeIf { it > 0 })
382
+ if (resolvedEnd != null && resolvedEnd > now) {
383
+ if (nextTrigger == null || resolvedEnd < nextTrigger) {
384
+ nextTrigger = resolvedEnd
385
+ }
386
+ }
387
+
252
388
  val lockScreen = json.optJSONObject("lockScreen")
253
389
  var hasTimeProgress = false
254
390
  extractData(