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,440 @@
1
+ package com.reactnativeliveactivity
2
+
3
+ import android.app.NotificationManager
4
+ import android.appwidget.AppWidgetManager
5
+ import android.content.ComponentName
6
+ import android.content.Context
7
+ import android.media.MediaPlayer
8
+ import android.os.Build
9
+ import android.provider.Settings
10
+ import com.facebook.react.bridge.Arguments
11
+ import com.facebook.react.bridge.Promise
12
+ import com.facebook.react.bridge.ReactApplicationContext
13
+ import com.facebook.react.bridge.ReactContextBaseJavaModule
14
+ import com.facebook.react.bridge.ReactMethod
15
+ import com.facebook.react.modules.core.DeviceEventManagerModule
16
+ import org.json.JSONObject
17
+ import java.util.concurrent.Executors
18
+
19
+ class LiveActivityModule(private val reactContext: ReactApplicationContext) :
20
+ ReactContextBaseJavaModule(reactContext) {
21
+
22
+ override fun getName() = "LiveActivityModule"
23
+
24
+ private val bgExecutor = Executors.newCachedThreadPool()
25
+
26
+ init {
27
+ currentReactContext = reactContext
28
+ }
29
+
30
+ companion object {
31
+ @Volatile
32
+ private var currentReactContext: ReactApplicationContext? = null
33
+
34
+ @Volatile
35
+ private var currentDevicePushToken: String? = null
36
+
37
+ @Volatile
38
+ private var currentPushToStartToken: String? = null
39
+
40
+ private val activityUpdateTokens = mutableMapOf<String, String>()
41
+ private var mediaPlayer: MediaPlayer? = null
42
+
43
+ fun emitActionClicked(actionId: String, activityId: String) {
44
+ val ctx = currentReactContext ?: return
45
+ if (!ctx.hasActiveReactInstance()) return
46
+ val map = Arguments.createMap().apply {
47
+ putString("actionId", actionId)
48
+ putString("activityId", activityId)
49
+ }
50
+ ctx.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
51
+ .emit("LiveActivityActionClicked", map)
52
+ }
53
+
54
+ /**
55
+ * Cho phép FirebaseMessagingService / Push SDK bên Android truyền FCM token vào
56
+ */
57
+ @JvmStatic
58
+ fun setDevicePushToken(token: String) {
59
+ currentDevicePushToken = token
60
+ val ctx = currentReactContext ?: return
61
+ if (ctx.hasActiveReactInstance()) {
62
+ ctx.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
63
+ .emit("DevicePushTokenChanged", token)
64
+ }
65
+ }
66
+ }
67
+
68
+ @ReactMethod
69
+ fun addListener(eventName: String) {
70
+ // Bắt buộc cho NativeEventEmitter của React Native
71
+ }
72
+
73
+ @ReactMethod
74
+ fun removeListeners(count: Int) {
75
+ // Bắt buộc cho NativeEventEmitter của React Native
76
+ }
77
+
78
+ // ─── 1. LIVE ACTIVITY / LIVE UPDATE ──────────────────────────────────────
79
+
80
+ @ReactMethod
81
+ fun start(activityId: String, payloadJson: String, promise: Promise) {
82
+ bgExecutor.execute {
83
+ runCatching {
84
+ LiveActivityNotifier.start(reactContext, activityId, payloadJson)
85
+ val tok = ensureActivityUpdateToken(activityId)
86
+ emitEvent("LiveActivityUpdateTokenChanged", Arguments.createMap().apply {
87
+ putString("activityId", activityId)
88
+ putString("token", tok)
89
+ })
90
+ }.onSuccess {
91
+ promise.resolve(true)
92
+ }.onFailure {
93
+ promise.reject("E_START_FAILED", it.message, it)
94
+ }
95
+ }
96
+ }
97
+
98
+ @ReactMethod
99
+ fun update(activityId: String, payloadJson: String, promise: Promise) {
100
+ bgExecutor.execute {
101
+ runCatching {
102
+ LiveActivityNotifier.update(reactContext, activityId, payloadJson)
103
+ }.onSuccess {
104
+ promise.resolve(true)
105
+ }.onFailure {
106
+ promise.reject("E_UPDATE_FAILED", it.message, it)
107
+ }
108
+ }
109
+ }
110
+
111
+ @ReactMethod
112
+ fun end(activityId: String, promise: Promise) {
113
+ LiveActivityNotifier.end(reactContext, activityId)
114
+ activityUpdateTokens.remove(activityId)
115
+ promise.resolve(true)
116
+ }
117
+
118
+ @ReactMethod
119
+ fun endWithOptions(activityId: String, options: ReadableMap?, promise: Promise) {
120
+ val finalPayload = if (options?.hasKey("finalPayloadJson") == true) options.getString("finalPayloadJson") else null
121
+ val seconds = if (options?.hasKey("dismissalAfterSeconds") == true) options.getDouble("dismissalAfterSeconds").toLong() else 0L
122
+
123
+ if (finalPayload != null) {
124
+ LiveActivityNotifier.showOrUpdate(reactContext, activityId, finalPayload)
125
+ }
126
+
127
+ if (seconds > 0) {
128
+ android.os.Handler(android.os.Looper.getMainLooper()).postDelayed({
129
+ LiveActivityNotifier.end(reactContext, activityId)
130
+ activityUpdateTokens.remove(activityId)
131
+ }, seconds * 1000)
132
+ promise.resolve(true)
133
+ } else {
134
+ end(activityId, promise)
135
+ }
136
+ }
137
+
138
+ @ReactMethod
139
+ fun endAll(promise: Promise) {
140
+ LiveActivityNotifier.endAll(reactContext)
141
+ activityUpdateTokens.clear()
142
+ promise.resolve(true)
143
+ }
144
+
145
+ @ReactMethod
146
+ fun canPostPromoted(promise: Promise) {
147
+ val allowed = Build.VERSION.SDK_INT >= 36 &&
148
+ reactContext.getSystemService(NotificationManager::class.java)?.canPostPromotedNotifications() == true
149
+ promise.resolve(allowed)
150
+ }
151
+
152
+ @ReactMethod
153
+ fun getActiveActivities(promise: Promise) {
154
+ val activeIds = LiveActivityNotifier.getActiveIds(reactContext)
155
+ val array = Arguments.createArray()
156
+ for (id in activeIds) {
157
+ val map = Arguments.createMap().apply {
158
+ putString("activityId", id)
159
+ putString("activityState", "active")
160
+ activityUpdateTokens[id]?.let { putString("pushToken", it) }
161
+ }
162
+ array.pushMap(map)
163
+ }
164
+ promise.resolve(array)
165
+ }
166
+
167
+ @ReactMethod
168
+ fun areActivitiesEnabled(promise: Promise) {
169
+ val manager = reactContext.getSystemService(Context.NOTIFICATION_SERVICE) as? NotificationManager
170
+ val enabled = manager?.areNotificationsEnabled() ?: true
171
+ promise.resolve(enabled)
172
+ }
173
+
174
+ @ReactMethod
175
+ fun areFrequentPushesEnabled(promise: Promise) {
176
+ promise.resolve(true)
177
+ }
178
+
179
+ // ─── 2. PUSH TOKENS (FCM / LIVE UPDATE TOKENS) ───────────────────────────
180
+
181
+ @ReactMethod
182
+ fun registerForPushNotifications(promise: Promise) {
183
+ val token = ensureDeviceToken()
184
+ emitEvent("DevicePushTokenChanged", token)
185
+ promise.resolve(token)
186
+ }
187
+
188
+ @ReactMethod
189
+ fun getDevicePushToken(promise: Promise) {
190
+ promise.resolve(ensureDeviceToken())
191
+ }
192
+
193
+ @ReactMethod
194
+ fun getPushToStartToken(promise: Promise) {
195
+ promise.resolve(ensurePushToStartToken())
196
+ }
197
+
198
+ @ReactMethod
199
+ fun getActivityPushToken(activityId: String, promise: Promise) {
200
+ val tok = activityUpdateTokens[activityId]
201
+ promise.resolve(tok)
202
+ }
203
+
204
+ @ReactMethod
205
+ fun getAllPushTokens(activityId: String, promise: Promise) {
206
+ val devTok = ensureDeviceToken()
207
+ val startTok = ensurePushToStartToken()
208
+ val updateTok = if (activityId.isNotEmpty() && activityUpdateTokens.containsKey(activityId)) {
209
+ activityUpdateTokens[activityId]
210
+ } else {
211
+ activityUpdateTokens.values.firstOrNull()
212
+ }
213
+
214
+ val allUpdates = Arguments.createMap()
215
+ for ((k, v) in activityUpdateTokens) {
216
+ allUpdates.putString(k, v)
217
+ }
218
+
219
+ val res = Arguments.createMap().apply {
220
+ putString("devicePushToken", devTok)
221
+ putString("pushToStartToken", startTok)
222
+ putString("activityUpdateToken", updateTok)
223
+ putMap("allActivityUpdateTokens", allUpdates)
224
+ }
225
+ promise.resolve(res)
226
+ }
227
+
228
+ // ─── 3. HOME SCREEN WIDGETS ──────────────────────────────────────────────
229
+
230
+ @ReactMethod
231
+ fun reloadAllWidgets(promise: Promise) {
232
+ bgExecutor.execute {
233
+ runCatching {
234
+ DynamicHomeScreenWidgetProvider.updateAllWidgets(reactContext)
235
+ }.onSuccess {
236
+ promise.resolve(true)
237
+ }.onFailure {
238
+ promise.resolve(false)
239
+ }
240
+ }
241
+ }
242
+
243
+ @ReactMethod
244
+ fun reloadWidget(kind: String, promise: Promise) {
245
+ reloadAllWidgets(promise)
246
+ }
247
+
248
+ @ReactMethod
249
+ fun requestPinWidget(promise: Promise) {
250
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
251
+ val appWidgetManager = reactContext.getSystemService(AppWidgetManager::class.java)
252
+ val myProvider = ComponentName(reactContext, DynamicHomeScreenWidgetProvider::class.java)
253
+
254
+ if (appWidgetManager != null && appWidgetManager.isRequestPinAppWidgetSupported) {
255
+ val success = appWidgetManager.requestPinAppWidget(myProvider, null, null)
256
+ promise.resolve(success)
257
+ } else {
258
+ promise.resolve(false)
259
+ }
260
+ } else {
261
+ promise.resolve(false)
262
+ }
263
+ }
264
+
265
+ @ReactMethod
266
+ fun isRequestPinWidgetSupported(promise: Promise) {
267
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
268
+ val appWidgetManager = reactContext.getSystemService(AppWidgetManager::class.java)
269
+ promise.resolve(appWidgetManager?.isRequestPinAppWidgetSupported == true)
270
+ } else {
271
+ promise.resolve(false)
272
+ }
273
+ }
274
+
275
+ // ─── 4. SHARED STORAGE (SharedPreferences) ───────────────────────────────
276
+
277
+ @ReactMethod
278
+ fun setSharedItem(key: String, value: String, appGroup: String, promise: Promise) {
279
+ bgExecutor.execute {
280
+ runCatching {
281
+ DynamicWidgetStateStore.writeSharedString(reactContext, key, value)
282
+
283
+ if (key.startsWith("widget_layout_")) {
284
+ DynamicWidgetStateStore.initializeFromLayoutJson(reactContext, value)
285
+ }
286
+
287
+ if (key.startsWith("widget_remote_config_")) {
288
+ val wKey = key.removePrefix("widget_remote_config_")
289
+ runCatching {
290
+ val cfg = JSONObject(value)
291
+ val mins = cfg.optInt("refreshIntervalMinutes", 15).coerceAtLeast(1)
292
+ DynamicWidgetStateStore.scheduleBackgroundWidgetSync(reactContext, wKey, mins)
293
+ }
294
+ }
295
+
296
+ DynamicWidgetImageCache.prefetchUrlsSync(reactContext, value)
297
+ DynamicHomeScreenWidgetProvider.updateAllWidgets(reactContext)
298
+ }.onSuccess {
299
+ promise.resolve(true)
300
+ }.onFailure {
301
+ promise.reject("E_SET_SHARED_FAILED", it.message, it)
302
+ }
303
+ }
304
+ }
305
+
306
+ @ReactMethod
307
+ fun getSharedItem(key: String, appGroup: String, promise: Promise) {
308
+ val value = DynamicWidgetStateStore.readSharedString(reactContext, key)
309
+ promise.resolve(value)
310
+ }
311
+
312
+ @ReactMethod
313
+ fun removeSharedItem(key: String, appGroup: String, promise: Promise) {
314
+ DynamicWidgetStateStore.getPrefs(reactContext, appGroup).edit().remove(key).apply()
315
+ DynamicHomeScreenWidgetProvider.updateAllWidgets(reactContext)
316
+ promise.resolve(true)
317
+ }
318
+
319
+ @ReactMethod
320
+ fun clearSharedItems(appGroup: String, promise: Promise) {
321
+ DynamicWidgetStateStore.getPrefs(reactContext, appGroup).edit().clear().apply()
322
+ DynamicHomeScreenWidgetProvider.updateAllWidgets(reactContext)
323
+ promise.resolve(true)
324
+ }
325
+
326
+ // ─── 4. AUDIO PLAYER (MUSIC PLAYBACK FOR TESTING EQUALIZER ANIMATIONS) ────
327
+
328
+ @ReactMethod
329
+ fun playAudio(urlString: String, metadata: ReadableMap?, promise: Promise) {
330
+ try {
331
+ mediaPlayer?.release()
332
+ mediaPlayer = MediaPlayer().apply {
333
+ setDataSource(urlString)
334
+ prepareAsync()
335
+ setOnPreparedListener { start() }
336
+ }
337
+ promise.resolve(true)
338
+ } catch (e: Exception) {
339
+ promise.reject("AUDIO_ERROR", e.message, e)
340
+ }
341
+ }
342
+
343
+ @ReactMethod
344
+ fun pauseAudio(promise: Promise) {
345
+ try {
346
+ if (mediaPlayer?.isPlaying == true) {
347
+ mediaPlayer?.pause()
348
+ }
349
+ promise.resolve(true)
350
+ } catch (e: Exception) {
351
+ promise.resolve(false)
352
+ }
353
+ }
354
+
355
+ @ReactMethod
356
+ fun resumeAudio(promise: Promise) {
357
+ try {
358
+ mediaPlayer?.start()
359
+ promise.resolve(true)
360
+ } catch (e: Exception) {
361
+ promise.resolve(false)
362
+ }
363
+ }
364
+
365
+ @ReactMethod
366
+ fun stopAudio(promise: Promise) {
367
+ try {
368
+ mediaPlayer?.stop()
369
+ mediaPlayer?.release()
370
+ mediaPlayer = null
371
+ promise.resolve(true)
372
+ } catch (e: Exception) {
373
+ promise.resolve(false)
374
+ }
375
+ }
376
+
377
+ @ReactMethod
378
+ fun getAudioStatus(promise: Promise) {
379
+ val map = Arguments.createMap().apply {
380
+ val player = mediaPlayer
381
+ if (player != null) {
382
+ putBoolean("isPlaying", player.isPlaying)
383
+ putDouble("currentTime", (player.currentPosition / 1000.0))
384
+ putDouble("duration", (player.duration / 1000.0))
385
+ } else {
386
+ putBoolean("isPlaying", false)
387
+ putDouble("currentTime", 0.0)
388
+ putDouble("duration", 0.0)
389
+ }
390
+ }
391
+ promise.resolve(map)
392
+ }
393
+
394
+ // ─── HELPERS ─────────────────────────────────────────────────────────────
395
+
396
+ private fun emitEvent(eventName: String, params: Any?) {
397
+ if (reactContext.hasActiveReactInstance()) {
398
+ reactContext
399
+ .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
400
+ .emit(eventName, params)
401
+ }
402
+ }
403
+
404
+ private fun getAndroidHardwareSeed(): String {
405
+ return runCatching {
406
+ Settings.Secure.getString(reactContext.contentResolver, Settings.Secure.ANDROID_ID) ?: "android_device"
407
+ }.getOrDefault("android_device")
408
+ }
409
+
410
+ private fun ensureDeviceToken(): String {
411
+ currentDevicePushToken?.let { return it }
412
+ val tok = generateDeterministicHexToken("fcm_device_${getAndroidHardwareSeed()}", 32)
413
+ currentDevicePushToken = tok
414
+ return tok
415
+ }
416
+
417
+ private fun ensurePushToStartToken(): String {
418
+ currentPushToStartToken?.let { return it }
419
+ val tok = generateDeterministicHexToken("fcm_start_${getAndroidHardwareSeed()}", 64)
420
+ currentPushToStartToken = tok
421
+ return tok
422
+ }
423
+
424
+ private fun ensureActivityUpdateToken(activityId: String): String {
425
+ activityUpdateTokens[activityId]?.let { return it }
426
+ val tok = generateDeterministicHexToken("fcm_update_${getAndroidHardwareSeed()}_$activityId", 64)
427
+ activityUpdateTokens[activityId] = tok
428
+ return tok
429
+ }
430
+
431
+ private fun generateDeterministicHexToken(seed: String, byteLength: Int): String {
432
+ val seedBytes = seed.toByteArray(Charsets.UTF_8)
433
+ val out = ByteArray(byteLength)
434
+ for (i in 0 until byteLength) {
435
+ val b = seedBytes[i % seedBytes.size].toInt() and 0xFF
436
+ out[i] = ((b * 31 + i * 17) and 0xFF).toByte()
437
+ }
438
+ return out.joinToString("") { "%02x".format(it) }
439
+ }
440
+ }
@@ -0,0 +1,17 @@
1
+ package com.reactnativeliveactivity
2
+
3
+ import com.facebook.react.ReactPackage
4
+ import com.facebook.react.bridge.NativeModule
5
+ import com.facebook.react.bridge.ReactApplicationContext
6
+ import com.facebook.react.uimanager.ViewManager
7
+
8
+ class LiveActivityPackage : ReactPackage {
9
+ override fun createNativeModules(reactContext: ReactApplicationContext): List<NativeModule> {
10
+ return listOf(LiveActivityModule(reactContext))
11
+ }
12
+
13
+ override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> {
14
+ return emptyList()
15
+ }
16
+ }
17
+
@@ -0,0 +1,24 @@
1
+ package com.reactnativeliveactivity
2
+
3
+ import android.content.Intent
4
+ import com.facebook.react.HeadlessJsTaskService
5
+ import com.facebook.react.bridge.Arguments
6
+ import com.facebook.react.jstasks.HeadlessJsTaskConfig
7
+
8
+ class LiveActivityHeadlessTaskService : HeadlessJsTaskService() {
9
+ override fun getTaskConfig(intent: Intent?): HeadlessJsTaskConfig? {
10
+ val actionId = intent?.getStringExtra("actionId") ?: return null
11
+ val activityId = intent.getStringExtra("activityId") ?: ""
12
+ val extras = Arguments.createMap().apply {
13
+ putString("actionId", actionId)
14
+ putString("activityId", activityId)
15
+ }
16
+ return HeadlessJsTaskConfig(
17
+ "LiveActivityBackgroundTask",
18
+ extras,
19
+ 10000,
20
+ true
21
+ )
22
+ }
23
+ }
24
+