react-native-live-widgets 0.0.0-stage → 1.0.0

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 (59) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/LICENSE +21 -0
  3. package/README.md +221 -2
  4. package/android/build.gradle +49 -0
  5. package/android/src/main/AndroidManifest.xml +38 -0
  6. package/android/src/main/java/com/reactnativeliveactivity/bridge/LiveActivityModule.kt +440 -0
  7. package/android/src/main/java/com/reactnativeliveactivity/bridge/LiveActivityPackage.kt +17 -0
  8. package/android/src/main/java/com/reactnativeliveactivity/liveactivity/LiveActivityHeadlessTaskService.kt +24 -0
  9. package/android/src/main/java/com/reactnativeliveactivity/liveactivity/LiveActivityNotifier.kt +410 -0
  10. package/android/src/main/java/com/reactnativeliveactivity/liveactivity/LiveActivityReceiver.kt +67 -0
  11. package/android/src/main/java/com/reactnativeliveactivity/renderer/DynamicNodeRegistry.kt +64 -0
  12. package/android/src/main/java/com/reactnativeliveactivity/renderer/DynamicWidgetCanvasRenderer.kt +1223 -0
  13. package/android/src/main/java/com/reactnativeliveactivity/storage/DynamicWidgetImageCache.kt +120 -0
  14. package/android/src/main/java/com/reactnativeliveactivity/storage/DynamicWidgetStateStore.kt +281 -0
  15. package/android/src/main/java/com/reactnativeliveactivity/widgets/DynamicHomeScreenWidgetProvider.kt +229 -0
  16. package/android/src/main/res/layout/rn_live_widget_host.xml +113 -0
  17. package/android/src/main/res/xml/rn_live_widget_info.xml +14 -0
  18. package/assets/dashboard_features.png +0 -0
  19. package/assets/dynamic_island_expanded.png +0 -0
  20. package/assets/home_widget_interactive.png +0 -0
  21. package/assets/lock_screen_live_activity.png +0 -0
  22. package/cli/setup.js +94 -0
  23. package/docs/GUIDE-EN.md +804 -0
  24. package/docs/GUIDE-VI.md +802 -0
  25. package/docs/widgets.md +52 -0
  26. package/ios/Bridge/LiveActivityModule.m +105 -0
  27. package/ios/Bridge/LiveActivityModule.swift +957 -0
  28. package/ios/Intents/DynamicWidgetActionIntent.swift +38 -0
  29. package/ios/Models/DynamicActivityAttributes.swift +22 -0
  30. package/ios/Models/DynamicLayoutModels.swift +243 -0
  31. package/ios/Renderer/ColorHexExtension.swift +49 -0
  32. package/ios/Renderer/DynamicNodeRegistry.swift +54 -0
  33. package/ios/Renderer/DynamicNodeView.swift +1060 -0
  34. package/ios/Storage/DynamicWidgetImageCache.swift +137 -0
  35. package/ios/Storage/DynamicWidgetStateStore.swift +162 -0
  36. package/ios/Widgets/DynamicHomeScreenWidget.swift +435 -0
  37. package/ios/Widgets/DynamicLiveActivityWidget.swift +79 -0
  38. package/lib/builder.d.ts +60 -0
  39. package/lib/builder.d.ts.map +1 -0
  40. package/lib/builder.js +296 -0
  41. package/lib/builder.js.map +1 -0
  42. package/lib/dispatcher.d.ts +16 -0
  43. package/lib/dispatcher.d.ts.map +1 -0
  44. package/lib/dispatcher.js +23 -0
  45. package/lib/dispatcher.js.map +1 -0
  46. package/lib/index.d.ts +199 -0
  47. package/lib/index.d.ts.map +1 -0
  48. package/lib/index.js +634 -0
  49. package/lib/index.js.map +1 -0
  50. package/lib/types.d.ts +489 -0
  51. package/lib/types.d.ts.map +1 -0
  52. package/lib/types.js +10 -0
  53. package/lib/types.js.map +1 -0
  54. package/package.json +68 -4
  55. package/react-native-live-widgets.podspec +38 -0
  56. package/src/builder.ts +409 -0
  57. package/src/dispatcher.ts +25 -0
  58. package/src/index.ts +681 -0
  59. package/src/types.ts +595 -0
@@ -0,0 +1,804 @@
1
+ # REACT-NATIVE-LIVE-WIDGETS — COMPLETE SETUP & DEVELOPER GUIDE 🚀
2
+
3
+ > 🌐 **Language:** [Tiếng Việt (GUIDE-VI.md)](./GUIDE-VI.md) | **English**
4
+
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
+
7
+ ---
8
+
9
+ ## TABLE OF CONTENTS
10
+ 1. [Overview & Architecture](#1-overview--architecture)
11
+ 2. [Installation & Project Setup](#2-installation--project-setup)
12
+ - [Package Installation](#package-installation)
13
+ - [iOS Setup (Xcode & Widget Extension)](#ios-setup-xcode--widget-extension)
14
+ - [Android Setup (Gradle, Manifest, MainApplication & Permissions)](#android-setup-gradle-manifest-mainapplication--permissions)
15
+ - [Native Directory Architecture (`ios/` & `android/`)](#native-directory-architecture-ios--android)
16
+ 3. [Core API Reference](#3-core-api-reference)
17
+ - [LiveActivity API (Lock Screen, Dynamic Island & 3 Push Token Types)](#1-liveactivity-api)
18
+ - [Widget API (Home Screen Widgets, Multi-Page & Background Sync)](#2-widget-api-home-screen-widgets)
19
+ - [SharedStorage API (App Groups & SharedPreferences)](#3-sharedstorage-api)
20
+ 4. [Declarative UI Engine (`UI.*`)](#4-declarative-ui-engine-ui)
21
+ - [UI.VStack & UI.HStack](#uivstack--uihstack)
22
+ - [UI.Text](#uitext)
23
+ - [UI.Timer (Zero-Battery Hardware Timer)](#uitimer-zero-battery-hardware-timer)
24
+ - [UI.Progress (Bar, Segmented & Circular Progress)](#uiprogress-bar-segmented--circular-progress)
25
+ - [UI.Equalizer (Realtime Animated Music Waveform)](#uiequalizer-realtime-animated-music-waveform)
26
+ - [UI.Image (Remote URL, Base64, File, Asset & SF Symbols)](#uiimage-remote-url-base64-file-asset--sf-symbols)
27
+ - [UI.Button (Interactive Page Switching, Task Toggle, API Refresh & Deep Links)](#uibutton-interactive-widget-buttons)
28
+ 5. [Dynamic Island Configuration (iPhone 14 Pro, 15, 16, 17)](#5-dynamic-island-configuration-iphone-14-pro-15-16-17)
29
+ 6. [Building Multi-Page & Interactive Home Screen Widgets in JavaScript](#6-building-multi-page--interactive-home-screen-widgets-in-javascript)
30
+ - [Lock Screen Widgets on iOS (accessoryRectangular, circular, inline)](#lock-screen-widgets-on-ios)
31
+ - [In-App Pin Widget on Android](#in-app-pin-widget-on-android)
32
+ 7. [Background API Auto-Sync When App Is Killed (`Widget.setRemoteConfig`)](#7-background-api-auto-sync-when-app-is-killed-widgetsetremoteconfig)
33
+ 8. [Managing All 3 Push Token Types (APNs & FCM)](#8-managing-all-3-push-token-types-apns--fcm)
34
+ 9. [State Machine & Timed Phases (`phases`)](#9-state-machine--timed-phases-phases)
35
+ 10. [Server Push Payload Structure (APNs & FCM)](#10-server-push-payload-structure-apns--fcm)
36
+ 11. [Troubleshooting](#11-troubleshooting)
37
+
38
+ ---
39
+
40
+ ## 1. Overview & Architecture
41
+
42
+ **`react-native-live-widgets`** is an all-in-one library that lets you author **100% of your Home Screen Widget and Live Activity UI directly in React Native (`App.tsx`)**, rendering natively on both iOS and Android without writing custom SwiftUI or RemoteViews XML for each screen:
43
+
44
+ - **Live Activity (iOS 16.1+ ActivityKit & Dynamic Island):** Real-time ongoing activities (attendance shifts, ride-hailing, food delivery, Pomodoro timers).
45
+ - **Live Update (Android API 24 -> Android 16 API 36 `Notification.ProgressStyle`):** Promoted ongoing notifications on Android featuring custom avatars (`LargeIcon`), multi-step segmented progress bars, chronometer countdowns, and interactive action buttons.
46
+ - **Home Screen Widgets (iOS WidgetKit & Android AppWidget High-DPI Canvas Renderer):** Home screen widgets (`small`, `medium`, `large`) supporting in-place tab/page switching (`pages`), interactive checklists (`toggle`), remote URL/Base64 images, and background API synchronization even when the app is force-killed.
47
+ - **Shared Storage:** Instant bridge between React Native and Native Widgets backed by iOS App Groups and Android `SharedPreferences`.
48
+
49
+ ---
50
+
51
+ ## 2. Installation & Project Setup
52
+
53
+ ### Package Installation
54
+ From the root directory of your React Native project:
55
+ ```bash
56
+ npm install react-native-live-widgets
57
+ # or
58
+ yarn add react-native-live-widgets
59
+
60
+ # Automatically configure Info.plist, Entitlements, AndroidManifest & Widget templates
61
+ npx react-native-live-widgets init --group group.com.yourcompany.app
62
+ ```
63
+
64
+ ---
65
+
66
+ ### iOS Setup (Xcode & Widget Extension)
67
+
68
+ #### Step 1: Enable Live Activities & App Groups
69
+ Running `npx react-native-live-widgets init` automatically configures `Info.plist` and `.entitlements`:
70
+ ```xml
71
+ <key>NSSupportsLiveActivities</key>
72
+ <true/>
73
+ <key>NSSupportsLiveActivitiesFrequentUpdates</key>
74
+ <true/>
75
+ ```
76
+ And in both `<YourApp>.entitlements` and `LiveWidgetsExtension.entitlements`:
77
+ ```xml
78
+ <key>aps-environment</key>
79
+ <string>development</string>
80
+ <key>com.apple.security.application-groups</key>
81
+ <array>
82
+ <string>group.<your_bundle_id></string>
83
+ </array>
84
+ ```
85
+
86
+ #### Step 2: Create the Widget Extension Target in Xcode (if not created yet)
87
+ 1. Open your `.xcworkspace` in Xcode.
88
+ 2. Go to **File -> New -> Target... -> Widget Extension**.
89
+ 3. Set **Product Name:** `LiveWidgets` (or `LiveWidgetsExtension`), and uncheck *Include Configuration App Intent*.
90
+ 4. Replace `LiveWidgetsBundle.swift` with:
91
+ ```swift
92
+ import WidgetKit
93
+ import SwiftUI
94
+ import react_native_live_widgets
95
+
96
+ @main
97
+ struct LiveWidgetsBundle: WidgetBundle {
98
+ var body: some Widget {
99
+ if #available(iOS 16.1, *) {
100
+ DynamicLiveActivityWidget()
101
+ }
102
+ DynamicHomeScreenWidget()
103
+ }
104
+ }
105
+ ```
106
+
107
+ #### Step 3: Configure `Podfile` & Install Pods
108
+ In `ios/Podfile`, link `react-native-live-widgets` to your Widget Extension target:
109
+ ```ruby
110
+ target 'LiveWidgetsExtension' do
111
+ use_modular_headers!
112
+ pod 'react-native-live-widgets', :path => '../node_modules/react-native-live-widgets'
113
+ end
114
+ ```
115
+ Then run:
116
+ ```bash
117
+ cd ios && pod install
118
+ ```
119
+
120
+ ---
121
+
122
+ ### Android Setup (Gradle, Manifest, MainApplication & Permissions)
123
+
124
+ On Android, most of the native setup is **handled automatically** out of the box via Gradle's **Android Manifest Merger**. Below is a complete breakdown of what is pre-configured and what you should verify in your project:
125
+
126
+ #### 1. What the Library Auto-Registers for You (Zero Manual Manifest Setup)
127
+ The library's bundled `AndroidManifest.xml` automatically merges the following into your app at build time:
128
+ - **System Permissions:**
129
+ - `android.permission.INTERNET` (downloads remote URL images & executes background Widget API calls).
130
+ - `android.permission.POST_NOTIFICATIONS` (displays Live Update Notifications on Android 13+).
131
+ - `android.permission.POST_PROMOTED_NOTIFICATIONS` (enables status-bar Live Update chips on Android 16 / API 36).
132
+ - `android.permission.VIBRATE`.
133
+ - **Home Screen Widget Provider (`DynamicHomeScreenWidgetProvider`):** Linked with `@xml/rn_live_widgets_info` supporting free horizontal & vertical resizing (`resizeMode="horizontal|vertical"`).
134
+ - **Broadcast Receiver (`LiveActivityReceiver`):** Handles interactive button taps on both Notifications and Home Screen Widgets.
135
+
136
+ #### 2. Step 1: Verify SDK Versions in `android/build.gradle`
137
+ Ensure your root `android/build.gradle` uses `minSdkVersion >= 24` and `compileSdkVersion >= 35` (or `36` for Android 16 Live Updates):
138
+ ```groovy
139
+ buildscript {
140
+ ext {
141
+ buildToolsVersion = "35.0.0"
142
+ minSdkVersion = 24
143
+ compileSdkVersion = 35 // Or 36 for Android 16
144
+ targetSdkVersion = 35
145
+ ndkVersion = "27.1.12297006"
146
+ kotlinVersion = "2.1.20"
147
+ }
148
+ }
149
+ ```
150
+
151
+ #### 3. Step 2: Verify `MainApplication.kt`
152
+ React Native 0.7x / 0.8x **Autolinking** (`PackageList(this).packages`) automatically registers `LiveActivityPackage`.
153
+ > ⚠️ **Important Note for React Native 0.80+:** Ensure `loadReactNative(this)` is called inside `MainApplication.onCreate()` so SoLoader/JSI initializes properly on launch:
154
+ ```kotlin
155
+ package com.yourcompany.app
156
+
157
+ import android.app.Application
158
+ import com.facebook.react.PackageList
159
+ import com.facebook.react.ReactApplication
160
+ import com.facebook.react.ReactHost
161
+ import com.facebook.react.ReactNativeApplicationEntryPoint.loadReactNative
162
+ import com.facebook.react.defaults.DefaultReactHost.getDefaultReactHost
163
+
164
+ class MainApplication : Application(), ReactApplication {
165
+ override val reactHost: ReactHost by lazy {
166
+ getDefaultReactHost(
167
+ context = applicationContext,
168
+ packageList = PackageList(this).packages, // LiveActivityPackage() is auto-linked here
169
+ )
170
+ }
171
+
172
+ override fun onCreate() {
173
+ super.onCreate()
174
+ loadReactNative(this) // Required on React Native 0.80+
175
+ }
176
+ }
177
+ ```
178
+
179
+ #### 4. Step 3: Request Runtime Notification Permission on Android 13+ (API 33+)
180
+ On Android 13 (API 33) and above, request `POST_NOTIFICATIONS` at runtime before starting a Live Update notification:
181
+ ```typescript
182
+ import { Platform, PermissionsAndroid } from 'react-native';
183
+ import { LiveActivity } from 'react-native-live-widgets';
184
+
185
+ async function ensureAndroidNotificationPermission() {
186
+ if (Platform.OS === 'android' && Platform.Version >= 33) {
187
+ await PermissionsAndroid.request(
188
+ PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS
189
+ );
190
+ }
191
+ // Or call the library's cross-platform helper directly:
192
+ await LiveActivity.registerForPushNotifications();
193
+ }
194
+ ```
195
+
196
+ #### 5. Step 4: Adding & Resizing Home Screen Widgets on Android (`small` / `medium` / `large`)
197
+ 1. After calling `Widget.update('main', { small, medium, large })` in your app, go to the Android Home Screen.
198
+ 2. **Long-press an empty area** on the Home Screen -> Tap **Widgets** -> Find your app -> Drag **Live Widgets** onto the Home Screen.
199
+ 3. **Responsive Family Switching (`small` / `medium` / `large`):** Long-press the placed widget and release to show the resize handles:
200
+ - Resize to **2×2 cells** (`width < 210dp`): Automatically renders the **`small`** layout (1:1 square aspect ratio).
201
+ - Resize to **4×2 cells** (default): Automatically renders the **`medium`** layout.
202
+ - Resize vertically to **4×4 cells** (`height >= 200dp`): Automatically renders the **`large`** layout.
203
+
204
+ ---
205
+
206
+ ### Native Directory Architecture (`ios/` & `android/`)
207
+
208
+ The native codebase is modularized by feature so you can easily navigate or extend it:
209
+
210
+ ```text
211
+ react-native-live-widgets/
212
+ ├── ios/
213
+ │ ├── Bridge/ # LiveActivityModule.swift/.m (React Native <-> iOS Bridge)
214
+ │ ├── Models/ # DynamicLayoutModels.swift, DynamicActivityAttributes.swift
215
+ │ ├── Storage/ # DynamicWidgetStateStore.swift, DynamicWidgetImageCache.swift
216
+ │ ├── Intents/ # DynamicWidgetActionIntent.swift (iOS 17+ interactive AppIntent)
217
+ │ ├── Renderer/ # DynamicNodeView.swift, ColorHexExtension.swift (SwiftUI JSON Renderer)
218
+ │ └── Widgets/ # DynamicHomeScreenWidget.swift, DynamicLiveActivityWidget.swift
219
+ └── android/src/main/java/com/reactnativeliveactivity/
220
+ ├── bridge/ # LiveActivityModule.kt, LiveActivityPackage.kt
221
+ ├── storage/ # DynamicWidgetStateStore.kt, DynamicWidgetImageCache.kt
222
+ ├── renderer/ # DynamicWidgetCanvasRenderer.kt (2D Canvas Renderer + HitBox Calculator)
223
+ ├── widgets/ # DynamicHomeScreenWidgetProvider.kt (Small/Medium/Large AppWidget Provider)
224
+ └── liveactivity/ # LiveActivityNotifier.kt, LiveActivityReceiver.kt (Android 8 -> 16 Live Updates)
225
+ ```
226
+
227
+ ---
228
+
229
+ ## 3. Core API Reference
230
+
231
+ ```typescript
232
+ import { LiveActivity, Widget, SharedStorage, UI } from 'react-native-live-widgets';
233
+ ```
234
+
235
+ ### 1. `LiveActivity` API
236
+ - `LiveActivity.start(options)`: Starts a Live Activity (iOS) or Live Update Notification (Android). Returns `{ activityId, activityPushToken }`.
237
+ - `LiveActivity.update(options)`: Updates the UI layout and alert state of a running `activityId`.
238
+ - `LiveActivity.end(activityId)`: Ends a specific activity session.
239
+ - `LiveActivity.endAll()`: Ends all active sessions.
240
+ - `LiveActivity.registerForPushNotifications()`: Requests notification permissions and registers for an APNs Device Token.
241
+ - `LiveActivity.getAllPushTokens(activityId?)`: Returns all 3 push tokens (`devicePushToken`, `pushToStartToken`, `activityUpdateToken`).
242
+ - `LiveActivity.getDevicePushToken()`: Gets the APNs Device Token (iOS) or stored FCM Token (Android).
243
+ - `LiveActivity.getPushToStartToken()`: Gets the APNs Push-to-Start Token (iOS 17.2+).
244
+ - `LiveActivity.getActivityPushToken(activityId?)`: Gets the APNs Activity Update Token for a running activity.
245
+ - `LiveActivity.setDevicePushToken(token)`: Stores the Android FCM token into the unified token manager.
246
+ - `LiveActivity.onDevicePushTokenChange(cb)` / `onPushToStartTokenChange(cb)` / `onActivityUpdateTokenChange(cb)`: Real-time listeners for token generation and rotation.
247
+
248
+ ### 2. `Widget` API (Home Screen & Lock Screen Widgets)
249
+ - `Widget.setLayout(widgetKey, layoutConfig, appGroup?)`: Updates the dynamic widget layout (`small`, `medium`, `large` for Home Screen; `accessoryRectangular`, `accessoryCircular`, `accessoryInline` for iOS 16+ Lock Screen; `pages`, `initialPage` for multi-page tabs). Prefetches and downscales all remote URL images automatically.
250
+ - `Widget.requestPin()`: *(Android 8.0+)* Prompts the system dialog allowing the user to pin the widget directly to their home screen with a single tap from within the app!
251
+ - `Widget.isPinSupported()`: Checks if the current Android launcher supports in-app widget pinning.
252
+ - `Widget.setRemoteConfig(config, widgetKey?, appGroup?)`: Configures a remote HTTP endpoint so the Widget automatically fetches fresh JSON data in the background even when the app is killed.
253
+ - `Widget.reloadAll()`: Forces iOS/Android to redraw all Home Screen and Lock Screen Widgets immediately.
254
+ - `Widget.reload(kind)`: Reloads a specific widget by kind.
255
+ - `Widget.getInteractiveState(widgetKey?, appGroup?)`: Reads the current interactive state (`activePage`, `toggledItems`, `lastSyncTime`, `remoteVariables`).
256
+ - `Widget.onWidgetAction(cb)`: Subscribes to button tap actions triggered from the Widget or Notification.
257
+
258
+ ### 3. `SharedStorage` API
259
+ - `SharedStorage.set(key, value, appGroup?)`: Saves a string or JSON object to App Group `UserDefaults` (iOS) or `SharedPreferences` (Android).
260
+ - `SharedStorage.get<T>(key, appGroup?)`: Reads shared data.
261
+ - `SharedStorage.remove(key, appGroup?)`: Removes a key.
262
+ - `SharedStorage.clear(appGroup?)`: Clears all shared widget data (useful on user logout).
263
+
264
+ ### 4. `AudioPlayer` API (Music Playback & Equalizer Testing)
265
+ - `AudioPlayer.play(url)`: Plays audio directly from URL (`.mp3`, `.m4a`, `.aac`, `.wav`) through system speakers (iOS `AVPlayer` / Android `MediaPlayer`).
266
+ - `AudioPlayer.pause()`: Pauses the currently playing track.
267
+ - `AudioPlayer.resume()`: Resumes playback.
268
+ - `AudioPlayer.stop()`: Stops playback and releases audio resources.
269
+ - `AudioPlayer.getStatus()`: Returns current playback status (`{ isPlaying, currentTime, duration }`).
270
+
271
+ ---
272
+
273
+ ## 4. Declarative UI Engine (`UI.*`)
274
+
275
+ ### `UI.StyleSheet` & Reusable Styling (`StyleProp`)
276
+ Just like React Native's `StyleSheet.create`, you can define reusable styles to keep your widget layouts modular and clean, supporting conditional style arrays:
277
+
278
+ ```typescript
279
+ import { UI } from 'react-native-live-widgets';
280
+
281
+ const styles = UI.StyleSheet.create({
282
+ card: {
283
+ padding: 14,
284
+ backgroundColor: '#0F172A',
285
+ borderRadius: 14,
286
+ spacing: 8,
287
+ },
288
+ headerText: {
289
+ fontSize: 10,
290
+ fontWeight: 'bold',
291
+ color: '#38BDF8',
292
+ },
293
+ titleText: {
294
+ fontSize: 15,
295
+ fontWeight: 'bold',
296
+ color: '#F8FAFC',
297
+ },
298
+ errorText: {
299
+ color: '#EF4444',
300
+ },
301
+ });
302
+
303
+ // Single style or conditional array:
304
+ UI.VStack(
305
+ styles.card,
306
+ UI.Text('REPORT TITLE', styles.headerText),
307
+ UI.Text('Current Shift Status', [styles.titleText, isError && styles.errorText])
308
+ );
309
+ ```
310
+
311
+ ### `UI.VStack` & `UI.HStack`
312
+ Vertical (`VStack`) and horizontal (`HStack`) flex-like containers:
313
+ ```typescript
314
+ UI.VStack(
315
+ {
316
+ padding: 14,
317
+ backgroundColor: '#1A1D24',
318
+ borderRadius: 16,
319
+ spacing: 8,
320
+ alignItems: 'leading', // 'leading' | 'center' | 'trailing'
321
+ },
322
+ // child nodes...
323
+ )
324
+ ```
325
+
326
+ ### `UI.Text`
327
+ Renders styled text with automatic `{{variable}}` interpolation from background API responses and automatic strikethrough when linked to an interactive checklist item:
328
+ ```typescript
329
+ UI.Text('Checked in at {{checkinTime}}', {
330
+ color: '#FFFFFF',
331
+ fontSize: 15,
332
+ fontWeight: 'bold',
333
+ maxLines: 1,
334
+ strikethroughWhenToggled: 'task_1', // Automatically strikes through and dims when 'task_1' is toggled!
335
+ })
336
+ ```
337
+
338
+ ### `UI.Timer` (Zero-Battery Hardware Timer)
339
+ Real-time `countdown` or `countup` timer rendered directly by the OS on Lock Screen, Dynamic Island, and Home Screen Widgets:
340
+ ```typescript
341
+ UI.Timer(targetTimestampInSeconds, {
342
+ mode: 'countdown',
343
+ color: '#FFA500',
344
+ fontSize: 16,
345
+ fontWeight: 'bold',
346
+ showsHours: false, // Compact MM:SS format ideal for Dynamic Island Compact
347
+ })
348
+ ```
349
+
350
+ ### `UI.Progress` (Bar, Segmented & Circular Progress)
351
+ Supports 3 visual styles: `'bar'` (continuous bar), `'segmented'` (multi-step delivery/shift stages), and `'circular'` (ring progress gauge):
352
+ ```typescript
353
+ // 1. 4-Step Segmented Progress Bar
354
+ UI.Progress({
355
+ style: 'segmented',
356
+ segments: 4,
357
+ currentSegment: 3, // Or pass value: 0.75
358
+ tintColor: '#10B981',
359
+ trackColor: '#374151',
360
+ segmentSpacing: 6,
361
+ height: 8,
362
+ })
363
+
364
+ // 2. Circular Progress Ring
365
+ UI.Progress({
366
+ style: 'circular',
367
+ value: 0.68,
368
+ tintColor: '#10B981',
369
+ trackColor: '#064E3B',
370
+ height: 64,
371
+ showPercentage: true,
372
+ })
373
+ ```
374
+
375
+ ### `UI.Equalizer` (Realtime Animated Music Waveform)
376
+ A dedicated audio equalizer and waveform visualizer. On Dynamic Island and Lock Screen Live Activities (iOS), the equalizer automatically oscillates rhythmically in real-time (using SwiftUI `TimelineView(.animation)`) with zero battery drain; on Android and Home Screen, it renders crisp audio frequency bars:
377
+ ```typescript
378
+ // 1. Used in Dynamic Island (compactTrailing or minimal)
379
+ UI.Equalizer({
380
+ isPlaying: true, // true: oscillating animated wave | false: paused
381
+ barCount: 4, // Number of wave bars (2 to 8)
382
+ tintColor: '#10B981', // Wave bar color (Spotify / Apple Music green)
383
+ height: 14, // Height in points
384
+ barWidth: 3, // Width of each bar
385
+ spacing: 2, // Spacing between bars
386
+ })
387
+
388
+ // 2. Used in Home Screen or Lock Screen Widget
389
+ UI.Equalizer({
390
+ isPlaying: true,
391
+ barCount: 5,
392
+ tintColor: '#FFFFFF',
393
+ height: 18,
394
+ })
395
+ ```
396
+
397
+ ### `UI.Image` (Remote URL, Base64, File, Asset & SF Symbols)
398
+ Supports **5 image sources** across both iOS and Android. When you pass a remote `url` (`https://...`), the library automatically downloads, downscales (`maxDimension = 360px` to stay safely below WidgetKit's 30MB memory ceiling), caches it on disk/memory, and refreshes the widget:
399
+ ```typescript
400
+ // 1. Remote URL Image (Circular Avatar with Border)
401
+ UI.Image({
402
+ url: 'https://images.unsplash.com/photo-1534528741775-53994a69daeb?w=300&q=80',
403
+ width: 44,
404
+ height: 44,
405
+ cornerRadius: 999, // 999 = Full circle mask
406
+ contentMode: 'fill', // 'fill' | 'fit'
407
+ borderColor: '#60A5FA', // Border color
408
+ borderWidth: 2, // Border width
409
+ })
410
+
411
+ // 2. Base64 Encoded Image (QR Code, Barcode, Badge...)
412
+ UI.Image({
413
+ base64: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUg...',
414
+ width: 36,
415
+ height: 36,
416
+ cornerRadius: 8,
417
+ })
418
+
419
+ // 3. System Icon (SF Symbols on iOS / Vector Mapping on Android)
420
+ UI.Image({
421
+ systemName: 'bicycle',
422
+ tintColor: '#FB923C',
423
+ width: 18,
424
+ height: 18,
425
+ })
426
+ ```
427
+
428
+ ### `UI.Button` (Interactive Widget Buttons)
429
+ Lets users interact directly on the Widget surface (via iOS 17+ `AppIntents` and Android `PendingIntent` hit zones) **without opening the app**:
430
+ ```typescript
431
+ // 1. Switch to another page/tab inside the Widget
432
+ UI.Button({
433
+ title: 'Tasks →',
434
+ actionId: 'page:tasks', // Or 'page:next' / 'page:prev'
435
+ backgroundColor: '#2563EB',
436
+ color: '#FFFFFF',
437
+ fontSize: 11,
438
+ paddingHorizontal: 10,
439
+ paddingVertical: 5,
440
+ borderRadius: 8,
441
+ })
442
+
443
+ // 2. Toggle a task item directly on the Widget
444
+ UI.Button({
445
+ title: 'Review attendance module PR',
446
+ actionId: 'toggle:task_1', // Automatically toggles [ ] <-> [✓]
447
+ backgroundColor: '#F8FAFC',
448
+ activeBackgroundColor: '#DCFCE7',
449
+ color: '#1E293B',
450
+ activeColor: '#15803D',
451
+ })
452
+
453
+ // 3. Trigger an immediate background API refresh
454
+ UI.Button({
455
+ title: '↻ Sync',
456
+ actionId: 'refresh',
457
+ backgroundColor: '#1E293B',
458
+ color: '#60A5FA',
459
+ })
460
+ ```
461
+
462
+ ### `UI.ZStack`, `UI.Grid` & `UI.Divider` (Advanced Layout Containers)
463
+ ```typescript
464
+ // 1. ZStack: Overlay layers on top of each other
465
+ UI.ZStack(
466
+ { zAlignment: 'bottomTrailing' },
467
+ UI.Image('https://images.unsplash.com/photo-1534528741775-53994a69daeb?w=200', { width: 44, height: 44, borderRadius: 22 }),
468
+ UI.Badge('●', { backgroundColor: '#10B981', textColor: '#FFFFFF', fontSize: 8 })
469
+ )
470
+
471
+ // 2. Grid: Multi-column grid layout (e.g., 2x2 KPI dashboard cards)
472
+ UI.Grid(
473
+ { columns: 2, columnSpacing: 8, rowSpacing: 8 },
474
+ UI.VStack({ padding: 8, backgroundColor: '#1E293B', borderRadius: 8 }, UI.Text('Revenue', { fontSize: 10, color: '#94A3B8' }), UI.Text('$128K', { fontSize: 14, fontWeight: 'bold', color: '#FFFFFF' })),
475
+ UI.VStack({ padding: 8, backgroundColor: '#1E293B', borderRadius: 8 }, UI.Text('Orders', { fontSize: 10, color: '#94A3B8' }), UI.Text('1,420', { fontSize: 14, fontWeight: 'bold', color: '#34D399' }))
476
+ )
477
+
478
+ // 3. Divider: Horizontal or vertical separator line
479
+ UI.Divider({ color: '#334155', thickness: 1, marginVertical: 4 })
480
+ ```
481
+
482
+ ### `UI.Gauge` & `UI.Chart` (Speedometer KPI Gauge & Bar / Line Sparkline Charts)
483
+ ```typescript
484
+ // 1. 240° Arc Speedometer / KPI Gauge
485
+ UI.Gauge(0.86, {
486
+ size: 66,
487
+ tintColor: '#38BDF8',
488
+ trackColor: '#1E293B',
489
+ textColor: '#F8FAFC',
490
+ labelColor: '#94A3B8',
491
+ valueText: '86%',
492
+ label: 'Q4 KPI',
493
+ })
494
+
495
+ // 2. Bar Chart ('bar') or Sparkline Area Chart ('line')
496
+ UI.Chart([42, 58, 51, 74, 68, 92, 108], {
497
+ style: 'bar', // 'bar' | 'line'
498
+ labels: ['M', 'T', 'W', 'T', 'F', 'S', 'S'],
499
+ tintColor: '#38BDF8',
500
+ secondaryColor: '#1E3A8A',
501
+ labelColor: '#94A3B8',
502
+ height: 48,
503
+ })
504
+ ```
505
+
506
+ ### `UI.Toggle`, `UI.Badge` & `UI.Link`
507
+ ```typescript
508
+ // 1. Toggle: Interactive Checkbox or Switch directly on the Widget surface
509
+ UI.Toggle('Approve weekly revenue report', {
510
+ actionId: 'toggle:kpi_approve',
511
+ style: 'checkbox', // 'checkbox' | 'switch'
512
+ tintColor: '#38BDF8',
513
+ textColor: '#F8FAFC',
514
+ })
515
+
516
+ // 2. Badge: Pill / Capsule status tag
517
+ UI.Badge('+18% Above Target', {
518
+ backgroundColor: '#064E3B',
519
+ textColor: '#34D399',
520
+ fontSize: 10,
521
+ })
522
+
523
+ // 3. Link: Wrap any container to open a Deep Link or trigger an interactive action
524
+ UI.Link(
525
+ { deepLink: 'livewidgets://analytics/q4', padding: 10, backgroundColor: '#1E293B', borderRadius: 10 },
526
+ UI.Text('View full analytics →', { fontSize: 12, fontWeight: 'bold', color: '#38BDF8' })
527
+ )
528
+ ```
529
+
530
+ ### `UI.Custom` & `DynamicNodeRegistry` (Register Custom Native SwiftUI / Kotlin Components)
531
+ You can register your own custom **SwiftUI View** or **Kotlin Canvas Drawer** without modifying the library's core code:
532
+
533
+ 1. **Register on iOS (Swift — inside `LiveWidgetsBundle.swift`):**
534
+ ```swift
535
+ import SwiftUI
536
+ import react_native_live_widgets
537
+
538
+ DynamicNodeRegistry.shared.registerView("WeatherCard") { node in
539
+ let city = node.props?["city"]?.stringValue ?? "Hanoi"
540
+ let temp = node.props?["temp"]?.stringValue ?? "28°C"
541
+ HStack {
542
+ Image(systemName: "sun.max.fill").foregroundColor(.yellow)
543
+ Text("\(city): \(temp)").font(.headline)
544
+ }
545
+ }
546
+ ```
547
+
548
+ 2. **Register on Android (Kotlin — inside `MainApplication.onCreate()`):**
549
+ ```kotlin
550
+ import com.reactnativeliveactivity.DynamicNodeRegistry
551
+
552
+ DynamicNodeRegistry.register(
553
+ componentName = "WeatherCard",
554
+ heightDp = { 44f },
555
+ drawer = { context, canvas, rect, props, density ->
556
+ // Draw custom graphics onto the Widget Canvas
557
+ }
558
+ )
559
+ ```
560
+
561
+ 3. **Invoke from React Native (`App.tsx`):**
562
+ ```typescript
563
+ UI.Custom('WeatherCard', { city: 'Ho Chi Minh City', temp: '31°C' })
564
+ ```
565
+
566
+ ---
567
+
568
+ ## 5. Dynamic Island Configuration (iPhone 14 Pro, 15, 16, 17)
569
+
570
+ ```typescript
571
+ dynamicIsland: {
572
+ compactLeading: UI.HStack(
573
+ { spacing: 4 },
574
+ UI.Image({
575
+ url: 'https://images.unsplash.com/photo-1534528741775-53994a69daeb?w=200&q=80',
576
+ width: 18,
577
+ height: 18,
578
+ cornerRadius: 999,
579
+ }),
580
+ UI.Text('08:02', { color: '#60A5FA', fontSize: 12, fontWeight: 'bold' })
581
+ ),
582
+ compactTrailing: UI.Timer(shiftEndTimestamp, {
583
+ mode: 'countdown',
584
+ color: '#60A5FA',
585
+ fontSize: 12,
586
+ fontWeight: 'bold',
587
+ showsHours: false,
588
+ }),
589
+ minimal: UI.Image({ systemName: 'clock.fill', tintColor: '#60A5FA', width: 14, height: 14 }),
590
+ expanded: {
591
+ leading: UI.Text('ON SHIFT', { color: '#60A5FA', fontSize: 12, fontWeight: 'bold' }),
592
+ trailing: UI.Timer(shiftEndTimestamp, { mode: 'countdown', color: '#FFFFFF', fontSize: 14, fontWeight: 'bold' }),
593
+ bottom: UI.VStack(
594
+ { spacing: 6 },
595
+ UI.Progress({ style: 'segmented', segments: 4, value: 0.75, tintColor: '#3B82F6', height: 6 }),
596
+ UI.Text('Checked in: District 1 Office', { color: '#94A3B8', fontSize: 11 })
597
+ ),
598
+ },
599
+ }
600
+ ```
601
+
602
+ ---
603
+
604
+ ## 6. Building Multi-Page & Interactive Home Screen Widgets in JavaScript
605
+
606
+ Pass a `pages` map to `Widget.setLayout` to create multiple interactive screens/tabs inside a single Widget:
607
+
608
+ ```typescript
609
+ await Widget.setLayout('main', {
610
+ initialPage: 'overview',
611
+ // Fallback default layout
612
+ medium: overviewMediumNode,
613
+ // Named pages switched via actionId: 'page:<page_name>'
614
+ pages: {
615
+ overview: {
616
+ small: overviewSmallNode,
617
+ medium: overviewMediumNode,
618
+ large: overviewLargeNode,
619
+ },
620
+ tasks: {
621
+ small: tasksSmallNode,
622
+ medium: tasksMediumNode,
623
+ large: tasksLargeNode,
624
+ },
625
+ stats: {
626
+ small: statsSmallNode,
627
+ medium: statsMediumNode,
628
+ large: statsLargeNode,
629
+ },
630
+ },
631
+ });
632
+ ```
633
+
634
+ ### Lock Screen Widgets on iOS
635
+ On iOS 16+, WidgetKit supports 3 lock screen accessory families:
636
+ - `accessoryRectangular`: Horizontal rectangle positioned below the clock.
637
+ - `accessoryCircular`: Compact circular gauge or indicator.
638
+ - `accessoryInline`: Compact single-line text row above the clock.
639
+
640
+ > [!NOTE]
641
+ > The library automatically strips opaque background colors and adapts paddings so that lock screen widgets render natively with system vibrancy against the user's wallpaper.
642
+
643
+ ```typescript
644
+ await Widget.setLayout('main', {
645
+ // Home Screen sizes
646
+ small: smallNode,
647
+ medium: mediumNode,
648
+ large: largeNode,
649
+
650
+ // Lock Screen sizes (iOS 16+)
651
+ accessoryRectangular: UI.HStack(
652
+ { spacing: 6 },
653
+ UI.VStack(
654
+ { spacing: 2 },
655
+ UI.Text('Starboy', { fontSize: 13, fontWeight: 'bold', color: '#FFFFFF' }),
656
+ UI.Text('The Weeknd', { fontSize: 11, color: '#CCCCCC' })
657
+ ),
658
+ UI.Spacer(),
659
+ UI.Equalizer({ isPlaying: true, barCount: 4, tintColor: '#FFFFFF', height: 16 })
660
+ ),
661
+ accessoryCircular: UI.VStack(
662
+ { spacing: 2 },
663
+ UI.Equalizer({ isPlaying: true, barCount: 4, tintColor: '#FFFFFF', height: 18 }),
664
+ UI.Text('MUSIC', { fontSize: 8, fontWeight: 'bold', color: '#FFFFFF' })
665
+ ),
666
+ accessoryInline: UI.Text('♪ Starboy • The Weeknd', { fontSize: 12, fontWeight: 'medium' }),
667
+ });
668
+ ```
669
+
670
+ ### In-App Pin Widget on Android
671
+ On Android 8.0+ (API 26+), you can trigger the system dialog from inside your React Native app to pin a widget to the home screen without asking users to manually search the launcher:
672
+
673
+ ```typescript
674
+ import { Widget } from 'react-native-live-widgets';
675
+
676
+ // Check if launcher supports in-app pinning
677
+ const isSupported = await Widget.isPinSupported();
678
+
679
+ if (isSupported) {
680
+ // Request system dialog to pin widget
681
+ const success = await Widget.requestPin();
682
+ if (success) {
683
+ console.log('Pin request accepted by system');
684
+ }
685
+ }
686
+ ```
687
+
688
+ ---
689
+
690
+ ## 7. Background API Auto-Sync When App Is Killed (`Widget.setRemoteConfig`)
691
+
692
+ When the user swipes away (force-kills) the main app, the React Native JS thread stops. To keep your Widget updated with live server data autonomously:
693
+
694
+ ```typescript
695
+ await Widget.setRemoteConfig({
696
+ url: 'https://api.yourcompany.com/v1/widget-summary',
697
+ method: 'GET',
698
+ headers: {
699
+ Authorization: `Bearer ${accessToken}`,
700
+ },
701
+ intervalMinutes: 15, // OS-scheduled background sync every 15 minutes
702
+ });
703
+ ```
704
+
705
+ - **How it works:**
706
+ - **iOS**: `DynamicWidgetProvider` performs an asynchronous HTTP request during its WidgetKit timeline reload (or immediately when the user taps a button with `actionId: 'refresh'`), flattens the JSON response, and injects values into `{{fieldName}}` placeholders across your UI tree.
707
+ - **Android**: `AlarmManager` schedules `LiveActivityReceiver` (`ACTION_WIDGET_SYNC`), fetches fresh JSON in the background (`goAsync()`), updates `SharedPreferences`, and redraws `DynamicHomeScreenWidgetProvider`.
708
+ - The built-in `{{_lastSyncTime}}` placeholder automatically resolves to the latest sync timestamp (`HH:mm:ss`).
709
+
710
+ ---
711
+
712
+ ## 8. Managing All 3 Push Token Types (APNs & FCM)
713
+
714
+ To control Live Activities and notifications from your backend server, the library exposes 3 token types:
715
+ 1. **`devicePushToken`**: Standard APNs Device Token (iOS) / FCM Token (Android).
716
+ 2. **`pushToStartToken` (iOS 17.2+)**: Allows your backend to remotely start a brand-new Live Activity even when the app is closed.
717
+ 3. **`activityUpdateToken`**: Unique token per active Live Activity used by your server to push real-time content updates or end that specific activity.
718
+
719
+ ```typescript
720
+ // 1. Request permission & register with APNs
721
+ await LiveActivity.registerForPushNotifications();
722
+
723
+ // 2. Fetch all 3 tokens at once
724
+ const tokens = await LiveActivity.getAllPushTokens();
725
+ console.log(tokens.devicePushToken, tokens.pushToStartToken, tokens.activityUpdateToken);
726
+
727
+ // 3. Subscribe to real-time token rotation events
728
+ const sub1 = LiveActivity.onDevicePushTokenChange(({ token }) => {
729
+ api.syncDeviceToken(token);
730
+ });
731
+ const sub2 = LiveActivity.onPushToStartTokenChange((token) => {
732
+ api.syncPushToStartToken(token);
733
+ });
734
+ const sub3 = LiveActivity.onActivityUpdateTokenChange(({ activityId, token }) => {
735
+ api.syncActivityUpdateToken(activityId, token);
736
+ });
737
+ ```
738
+
739
+ ---
740
+
741
+ ## 9. State Machine & Timed Phases (`phases`)
742
+
743
+ Declare scheduled transitions ahead of time so the native layer updates alerts and UI at exact timestamps without requiring a server push:
744
+
745
+ ```typescript
746
+ phases: [
747
+ {
748
+ id: 'warning_phase',
749
+ triggerTimestamp: targetTimestamp - 300, // 5 minutes before deadline
750
+ alertTitle: 'Shift starting soon!',
751
+ alertBody: 'Only 5 minutes left to check in.',
752
+ },
753
+ {
754
+ id: 'late_phase',
755
+ triggerTimestamp: targetTimestamp, // Deadline reached
756
+ alertTitle: 'Late for shift!',
757
+ alertBody: 'Your shift start time has passed.',
758
+ },
759
+ ]
760
+ ```
761
+
762
+ ---
763
+
764
+ ## 10. Server Push Payload Structure (APNs & FCM)
765
+
766
+ ### APNs HTTP/2 Headers (iOS Live Activity):
767
+ - `apns-push-type`: `liveactivity`
768
+ - `apns-topic`: `<your_bundle_id>.push-type.liveactivity`
769
+ - `apns-priority`: `10`
770
+
771
+ ### APNs JSON Body:
772
+ ```json
773
+ {
774
+ "aps": {
775
+ "timestamp": 1711890000,
776
+ "event": "update",
777
+ "content-state": {
778
+ "layoutJson": "{\"lockScreen\":{...},\"dynamicIsland\":{...}}"
779
+ },
780
+ "alert": {
781
+ "title": "Order Delivered!",
782
+ "body": "Enjoy your meal."
783
+ }
784
+ }
785
+ }
786
+ ```
787
+
788
+ ---
789
+
790
+ ## 11. Troubleshooting
791
+
792
+ 1. **Home Screen Widget displays the default placeholder text:**
793
+ - Verify that both the main app target and the Widget Extension target share the same App Group identifier (`group.<bundle_id>`).
794
+ - Ensure `await Widget.setLayout('main', ...)` has been called from React Native.
795
+ 2. **Dynamic Island Compact pill stretches too wide when using `UI.Timer`:**
796
+ - Pass `showsHours: false` to `UI.Timer` in `compactTrailing`. The native renderer automatically constrains the timer frame width so the Dynamic Island stays compact.
797
+ 3. **Remote images (`https://...`) do not appear immediately:**
798
+ - Ensure the URL uses `https://`. The library prefetches, downscales to `360px`, caches the image in the App Group / cache directory, and automatically triggers a widget reload once the download finishes.
799
+
800
+ ---
801
+
802
+ ## 📄 License
803
+ MIT © vu-tran
804
+