react-native-live-widgets 1.2.1 → 1.2.3

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 (79) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/README.md +89 -49
  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 +86 -13
  9. package/android/src/main/java/com/reactnativeliveactivity/storage/DynamicWidgetImageCache.kt +53 -0
  10. package/android/src/main/java/com/reactnativeliveactivity/storage/DynamicWidgetStateStore.kt +647 -104
  11. package/android/src/main/java/com/reactnativeliveactivity/widgets/DynamicHomeScreenWidgetProvider.kt +3 -1
  12. package/android/src/main/java/com/reactnativeliveactivity/widgets/DynamicQuickSettingsTileService.kt +120 -0
  13. package/app.plugin.js +36 -0
  14. package/assets/MaterialIcons.json +2236 -0
  15. package/cli/codegen.js +889 -0
  16. package/cli/setup.js +323 -63
  17. package/docs/EXPO-GUIDE-EN.md +21 -3
  18. package/docs/EXPO-GUIDE-VI.md +21 -3
  19. package/docs/GUIDE-EN.md +203 -21
  20. package/docs/GUIDE-VI.md +207 -22
  21. package/docs/index.html +1461 -226
  22. package/docs/llms-full.txt +15 -0
  23. package/docs/llms.txt +16 -7
  24. package/ios/Bridge/LiveActivityModule.swift +333 -44
  25. package/ios/Intents/DynamicWidgetActionIntent.swift +57 -2
  26. package/ios/Models/DynamicLayoutModels.swift +114 -4
  27. package/ios/Renderer/DynamicNodeView.swift +15 -6
  28. package/ios/Storage/DynamicWidgetStateStore.swift +649 -38
  29. package/ios/Widgets/DynamicControlWidget.swift +63 -0
  30. package/ios/Widgets/DynamicHomeScreenWidget.swift +99 -26
  31. package/ios/Widgets/DynamicLiveActivityWidget.swift +25 -4
  32. package/lib/builder.d.ts +50 -7
  33. package/lib/builder.d.ts.map +1 -1
  34. package/lib/builder.js +326 -18
  35. package/lib/builder.js.map +1 -1
  36. package/lib/hooks.d.ts +13 -9
  37. package/lib/hooks.d.ts.map +1 -1
  38. package/lib/hooks.js +70 -12
  39. package/lib/hooks.js.map +1 -1
  40. package/lib/index.d.ts +80 -7
  41. package/lib/index.d.ts.map +1 -1
  42. package/lib/index.js +303 -59
  43. package/lib/index.js.map +1 -1
  44. package/lib/ir.d.ts.map +1 -1
  45. package/lib/ir.js +9 -2
  46. package/lib/ir.js.map +1 -1
  47. package/lib/jsx.d.ts +11 -7
  48. package/lib/jsx.d.ts.map +1 -1
  49. package/lib/jsx.js +50 -13
  50. package/lib/jsx.js.map +1 -1
  51. package/lib/material-icons.generated.d.ts +8 -0
  52. package/lib/material-icons.generated.d.ts.map +1 -0
  53. package/lib/material-icons.generated.js +9 -0
  54. package/lib/material-icons.generated.js.map +1 -0
  55. package/lib/preview.d.ts +11 -4
  56. package/lib/preview.d.ts.map +1 -1
  57. package/lib/preview.js +150 -82
  58. package/lib/preview.js.map +1 -1
  59. package/lib/sf-symbols.generated.d.ts +8 -0
  60. package/lib/sf-symbols.generated.d.ts.map +1 -0
  61. package/lib/sf-symbols.generated.js +9 -0
  62. package/lib/sf-symbols.generated.js.map +1 -0
  63. package/lib/types.d.ts +302 -18
  64. package/lib/types.d.ts.map +1 -1
  65. package/package.json +6 -2
  66. package/scripts/build.js +98 -0
  67. package/scripts/generate-material-icons.js +93 -0
  68. package/scripts/generate-sf-symbols.js +95 -0
  69. package/scripts/release.js +115 -0
  70. package/scripts/test-ir-semantic.js +314 -0
  71. package/src/builder.ts +382 -24
  72. package/src/hooks.ts +88 -12
  73. package/src/index.ts +319 -56
  74. package/src/ir.ts +8 -2
  75. package/src/jsx.tsx +69 -21
  76. package/src/material-icons.generated.ts +3844 -0
  77. package/src/preview.tsx +235 -81
  78. package/src/sf-symbols.generated.ts +9533 -0
  79. package/src/types.ts +348 -18
package/CHANGELOG.md CHANGED
@@ -2,7 +2,44 @@
2
2
 
3
3
  All notable changes to `react-native-live-widgets` will be documented in this file.
4
4
 
5
+ ## [1.2.3] - 2026-11-18
6
+ ### Fixed & Improved
7
+ - **Automatic Xcode String Catalog Linking (`Localizable.xcstrings`)**:
8
+ - `codegen.js` now automatically inspects `project.pbxproj` and links `Localizable.xcstrings` into the `PBXResourcesBuildPhase` and `PBXFileReference` of the `LiveWidgetsExtension` target, preventing raw i18n keys (e.g., `widgets.main.title`, `widgets.shift.title`) from leaking into the iOS Widget Gallery.
9
+ - Automatically updates `CFBundleLocalizations` (`vi`, `en`, `ja`) inside `LiveWidgetsExtension/Info.plist` and synchronizes project `knownRegions`.
10
+ - **Full Bilingual i18n Web Documentation**:
11
+ - Completed English translations across `docs/index.html` (sidebar categories, links, exact hit layer, and quick start sections) with 101/101 dynamic `data-i18n` keys.
12
+ - **Library Peer Dependency Deduplication**:
13
+ - Sanitized library build environment to eliminate nested React instances, preventing `Cannot read property 'useRef' of null` dispatch errors in host apps.
14
+
15
+ ## [1.2.2] - 2026-11-18
16
+ ### Added
17
+ - **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).
18
+ - **Auto-Generated `app.json` & Smart Project Detection**:
19
+ - Automatically creates `app.json` with `name` and `displayName` if missing, or completes missing fields.
20
+ - 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.
21
+ - **Automated Entrypoint Injection (`index.js` / `index.ts` / `index.tsx`)**:
22
+ - Automatically inspects the project's root entry file and safely registers `LiveActivity.registerBackgroundActionHandler()` before `AppRegistry.registerComponent` or `registerRootComponent`.
23
+ - Automatically injects `import { name as appName } from './app.json';` when referenced by `AppRegistry` if the import statement is missing.
24
+ - **Resilient Auto-Generation for Missing Native Files**:
25
+ - Automatically regenerates `LiveWidgetsExtension/Info.plist` if missing (resolving Xcode build error 65).
26
+ - Automatically generates `widgets.config.ts` with complete English JSDoc documentation if not found in project root.
27
+ - **Type Aliases & API Ergonomics**: Exported `defineWidgetConfig` (singular) alongside `defineWidgetsConfig` (plural) in `src/index.ts`.
28
+ - **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`.
29
+
30
+ ### Changed & Improved
31
+ - **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.
32
+ - **Streamlined Documentation & Official Icon Galleries**:
33
+ - 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`.
34
+ - Updated `docs/index.html` with official links to Apple SF Symbols and Google Material Icons galleries, alongside a dynamic language switcher (EN / VI).
35
+ - Updated `docs/llms.txt` and `docs/llms-full.txt` with latest setup commands.
36
+
5
37
  ## [1.2.1] - 2026-11-17
38
+ ### Added
39
+ - **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.
40
+ - **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`.
41
+ - **English CLI Output**: Standardized all Codegen CLI and icon generation terminal logs to clean, professional English.
42
+
6
43
  ### Fixed
7
44
  - **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.
8
45
  - **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.
package/README.md CHANGED
@@ -198,81 +198,119 @@ if (caps.supportsGradients) {
198
198
  }
199
199
  ```
200
200
 
201
+ ### 8. 🎯 v1.2.1 Architecture: Exact Dynamic Hit Layer, Native Chronometer & UI IR
202
+
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.
232
+
201
233
  ---
202
234
 
203
- ## ⚡ Quick Start
235
+ ## ⚡ Quick Start: Essential Commands & Setup
204
236
 
205
- ### 1. Installation
237
+ Get Live Activities and Interactive Home Screen Widgets running in **less than 2 minutes** with zero manual native code.
206
238
 
207
- ```bash
208
- # React Native CLI
209
- npm install react-native-live-widgets
239
+ ### 📋 CLI Command Cheat Sheet
210
240
 
211
- # Expo (Managed or Bare)
212
- npx expo install react-native-live-widgets
213
- ```
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 |
214
246
 
215
247
  ---
216
248
 
217
- ### 2. Configuration
218
-
219
- #### A. If using Expo (Config Plugin)
220
-
221
- Add `react-native-live-widgets` to your `app.json` or `app.config.js`:
222
-
223
- ```json
224
- {
225
- "expo": {
226
- "name": "My Expo App",
227
- "plugins": [
228
- [
229
- "react-native-live-widgets",
230
- {
231
- "appGroup": "group.com.yourcompany.app",
232
- "enableLiveActivities": true,
233
- "frequentUpdates": true
234
- }
235
- ]
236
- ]
237
- }
238
- }
239
- ```
240
-
241
- Then generate native projects or run with Expo Dev Client:
249
+ ### Option A: Expo (SDK 50, 51, 52, 58+ CNG & EAS Build)
242
250
 
243
251
  ```bash
244
- # 1. Generate native folders
245
- npx expo prebuild
252
+ # 1. Install package
253
+ npx expo install react-native-live-widgets
246
254
 
247
- # 2. Automatically scaffold & link Xcode Widget Extension target
248
- 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
249
257
 
250
- # 3. Run on iOS Simulator & Android Emulator:
258
+ # 3. Launch on Simulator / Emulator
251
259
  npx expo run:ios
260
+ # or
252
261
  npx expo run:android
253
262
  ```
254
263
 
255
- > 📖 **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)
256
271
 
257
- #### B. If using Bare React Native CLI
272
+ ---
258
273
 
259
- Run the automated scaffolding script in your React Native project root:
274
+ ### Option B: Bare React Native CLI
260
275
 
261
276
  ```bash
262
- 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
263
288
  ```
264
289
 
265
- This will automatically:
266
- - Inject `NSSupportsLiveActivities` and `NSSupportsLiveActivitiesFrequentUpdates` into `Info.plist`.
267
- - Scaffold the `LiveWidgetsExtension` bundle in your `ios/` folder.
268
- - 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`.
297
+
298
+ ---
269
299
 
270
- And install CocoaPods dependencies:
300
+ ### 🔄 Updating Widgets or Translations (`widgets.config.ts`)
301
+
302
+ Whenever you add or modify widgets in `widgets.config.ts`:
271
303
 
272
304
  ```bash
273
- cd ios && pod install
305
+ npx react-native-live-widgets codegen
274
306
  ```
275
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
+
276
314
  ---
277
315
 
278
316
  ## 💻 Code Example
@@ -454,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ạ
454
492
 
455
493
  ## 📚 Documentation & Guides
456
494
 
457
- - 📱 **[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.
458
498
  - 🇬🇧 **[Full English Developer Guide](docs/GUIDE-EN.md)**: Architecture, DSL specs, push notification server configuration, and best practices.
459
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.
460
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(
@@ -43,7 +43,7 @@ class LiveActivityReceiver : BroadcastReceiver() {
43
43
  val wKey = if (actionId.startsWith("refresh:")) {
44
44
  actionId.removePrefix("refresh:")
45
45
  } else "main"
46
- DynamicWidgetStateStore.performRemoteSync(context, wKey)
46
+ DynamicWidgetStateStore.performRemoteSync(context, wKey, forceRefresh = true)
47
47
  } else {
48
48
  DynamicWidgetStateStore.handleAction(context, actionId)
49
49
  }