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,410 @@
1
+ package com.reactnativeliveactivity
2
+
3
+ import android.app.AlarmManager
4
+ import android.app.NotificationChannel
5
+ import android.app.NotificationManager
6
+ import android.app.PendingIntent
7
+ import android.content.Context
8
+ import android.content.Intent
9
+ import android.graphics.Bitmap
10
+ import android.graphics.Color
11
+ import android.os.Build
12
+ import android.os.SystemClock
13
+ import androidx.core.app.NotificationCompat
14
+ import org.json.JSONObject
15
+ import kotlin.math.roundToInt
16
+
17
+ data class ProgressData(
18
+ val style: String = "bar",
19
+ val startTimestamp: Double? = null,
20
+ val targetTimestamp: Double? = null,
21
+ val value: Double? = null,
22
+ val countsDown: Boolean = false,
23
+ val tintColor: String? = null,
24
+ val trackColor: String? = null,
25
+ val warningSeconds: Double? = null,
26
+ val warningTintColor: String? = null,
27
+ val segments: Int? = null,
28
+ val currentSegment: Int? = null,
29
+ val showPercentage: Boolean = false
30
+ )
31
+
32
+ data class NotificationButtonData(
33
+ val title: String,
34
+ val actionId: String
35
+ )
36
+
37
+ object LiveActivityNotifier {
38
+ const val CHANNEL_ID = "live_activity_channel"
39
+ private const val PREFS = "rn_live_widgets_prefs"
40
+ private const val EXTRA_REQUEST_PROMOTED_ONGOING = "android.requestPromotedOngoing"
41
+ private const val TICK_MILLIS = 30_000L
42
+
43
+ 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)
48
+ }
49
+
50
+ 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)
55
+ }
56
+
57
+ fun end(context: Context, activityId: String) {
58
+ prefs(context).edit().remove(activityId).apply()
59
+ cancelRefresh(context, activityId)
60
+ val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
61
+ manager.cancel(activityId.hashCode())
62
+ }
63
+
64
+ fun endAll(context: Context) {
65
+ prefs(context).edit().clear().apply()
66
+ val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
67
+ manager.cancelAll()
68
+ }
69
+
70
+ fun getActiveIds(context: Context): List<String> {
71
+ return prefs(context).all.keys.filter {
72
+ it != "last_action_id" && !it.startsWith("__")
73
+ }
74
+ }
75
+
76
+ fun refresh(context: Context, activityId: String) {
77
+ val json = prefs(context).getString(activityId, null) ?: return
78
+ showNotification(context, activityId, json)
79
+ scheduleNextRefresh(context, activityId, json)
80
+ }
81
+
82
+ fun refreshAllActive(context: Context) {
83
+ val all = prefs(context).all
84
+ for ((actId, value) in all) {
85
+ val json = value as? String ?: continue
86
+ showNotification(context, actId, json)
87
+ }
88
+ }
89
+
90
+ private fun showNotification(context: Context, activityId: String, payloadJson: String) {
91
+ val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
92
+ ensureChannel(manager)
93
+
94
+ val json = JSONObject(payloadJson)
95
+ val lockScreen = json.optJSONObject("lockScreen")
96
+ val alertTitle = json.optString("alertTitle", "")
97
+ val alertBody = json.optString("alertBody", "")
98
+
99
+ val textLines = mutableListOf<String>()
100
+ var targetTimestamp: Double? = null
101
+ var progressData: ProgressData? = null
102
+ var largeBitmap: Bitmap? = null
103
+ val buttons = mutableListOf<NotificationButtonData>()
104
+
105
+ extractData(
106
+ context = context,
107
+ node = lockScreen,
108
+ onText = { t -> textLines.add(t) },
109
+ onTimer = { ts -> targetTimestamp = ts },
110
+ onProgress = { p -> progressData = p },
111
+ onImage = { bmp -> if (largeBitmap == null) largeBitmap = bmp },
112
+ onButton = { btn -> if (buttons.size < 3) buttons.add(btn) }
113
+ )
114
+
115
+ val titleText = when {
116
+ alertTitle.isNotEmpty() -> alertTitle
117
+ textLines.isNotEmpty() -> textLines.first()
118
+ else -> "Live Activity"
119
+ }
120
+
121
+ val bodyText = when {
122
+ alertBody.isNotEmpty() -> alertBody
123
+ textLines.size > 1 -> textLines.drop(1).joinToString(" • ")
124
+ else -> ""
125
+ }
126
+
127
+ val launchIntent = context.packageManager.getLaunchIntentForPackage(context.packageName)
128
+ val contentPendingIntent = if (launchIntent != null) {
129
+ PendingIntent.getActivity(
130
+ context,
131
+ activityId.hashCode(),
132
+ launchIntent,
133
+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
134
+ )
135
+ } else null
136
+
137
+ val builder = NotificationCompat.Builder(context, CHANNEL_ID)
138
+ .setSmallIcon(context.applicationInfo.icon)
139
+ .setContentTitle(titleText)
140
+ .setContentText(bodyText)
141
+ .setOngoing(true)
142
+ .setOnlyAlertOnce(true)
143
+ .setPriority(NotificationCompat.PRIORITY_HIGH)
144
+
145
+ if (bodyText.length > 42) {
146
+ builder.setStyle(NotificationCompat.BigTextStyle().bigText(bodyText))
147
+ }
148
+
149
+ if (contentPendingIntent != null) {
150
+ builder.setContentIntent(contentPendingIntent)
151
+ }
152
+
153
+ if (largeBitmap != null) {
154
+ builder.setLargeIcon(largeBitmap)
155
+ }
156
+
157
+ // 1. Đồng hồ Chronometer tự đếm trên phần cứng
158
+ if (targetTimestamp != null && targetTimestamp!! > 0) {
159
+ val targetMillis = (targetTimestamp!! * 1000).toLong()
160
+ val timeDiff = targetMillis - System.currentTimeMillis()
161
+ builder.setUsesChronometer(true)
162
+ builder.setChronometerCountDown(timeDiff > 0)
163
+ builder.setWhen(SystemClock.elapsedRealtime() + timeDiff)
164
+ }
165
+
166
+ // 2. Xử lý thanh tiến trình đa dạng (UI.Progress)
167
+ val now = System.currentTimeMillis() / 1000.0
168
+ if (progressData != null) {
169
+ applyProgressToNotification(builder, progressData!!, now)
170
+ progressData?.tintColor?.let { hex ->
171
+ runCatching { builder.setColor(Color.parseColor(hex)) }
172
+ }
173
+ }
174
+
175
+ // 3. Các nút bấm tương tác (UI.Button) ngay trên thông báo Live Update
176
+ buttons.forEachIndexed { idx, btn ->
177
+ val actionIntent = Intent(context, LiveActivityReceiver::class.java).apply {
178
+ action = LiveActivityReceiver.ACTION_WIDGET_ACTION
179
+ putExtra("actionId", btn.actionId)
180
+ putExtra("activityId", activityId)
181
+ }
182
+ val pi = PendingIntent.getBroadcast(
183
+ context,
184
+ (activityId + "_" + btn.actionId + "_" + idx).hashCode(),
185
+ actionIntent,
186
+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
187
+ )
188
+ builder.addAction(0, btn.title, pi)
189
+ }
190
+
191
+ // 4. Android 16+ Promoted Ongoing Notification (Live Update)
192
+ if (Build.VERSION.SDK_INT >= 36) {
193
+ builder.addExtras(android.os.Bundle().apply {
194
+ putBoolean(EXTRA_REQUEST_PROMOTED_ONGOING, true)
195
+ })
196
+ }
197
+
198
+ manager.notify(activityId.hashCode(), builder.build())
199
+ }
200
+
201
+ private fun applyProgressToNotification(
202
+ builder: NotificationCompat.Builder,
203
+ progress: ProgressData,
204
+ now: Double
205
+ ) {
206
+ when (progress.style) {
207
+ "segmented" -> {
208
+ val totalSegments = (progress.segments ?: 4).coerceAtLeast(1)
209
+ val current = when {
210
+ progress.currentSegment != null -> progress.currentSegment.coerceIn(0, totalSegments)
211
+ progress.value != null -> (progress.value * totalSegments).roundToInt().coerceIn(0, totalSegments)
212
+ else -> 1
213
+ }
214
+ builder.setProgress(totalSegments, current, false)
215
+ }
216
+ "circular", "bar" -> {
217
+ if (progress.targetTimestamp != null && progress.startTimestamp != null && progress.targetTimestamp > progress.startTimestamp) {
218
+ val totalSeconds = (progress.targetTimestamp - progress.startTimestamp).toInt().coerceAtLeast(1)
219
+ val elapsed = (now - progress.startTimestamp).toInt().coerceIn(0, totalSeconds)
220
+ val finalVal = if (progress.countsDown) (totalSeconds - elapsed) else elapsed
221
+ builder.setProgress(totalSeconds, finalVal, false)
222
+ } else if (progress.value != null) {
223
+ val pct = (progress.value * 100).roundToInt().coerceIn(0, 100)
224
+ builder.setProgress(100, pct, false)
225
+ }
226
+ }
227
+ else -> {
228
+ builder.setProgress(100, 0, true)
229
+ }
230
+ }
231
+ }
232
+
233
+ private fun scheduleNextRefresh(context: Context, activityId: String, payloadJson: String) {
234
+ val json = JSONObject(payloadJson)
235
+ val phases = json.optJSONArray("phases")
236
+ val now = System.currentTimeMillis() / 1000.0
237
+
238
+ var nextTrigger: Double? = null
239
+
240
+ if (phases != null) {
241
+ for (i in 0 until phases.length()) {
242
+ val phase = phases.getJSONObject(i)
243
+ val trigger = phase.optDouble("triggerTimestamp", 0.0)
244
+ if (trigger > now) {
245
+ if (nextTrigger == null || trigger < nextTrigger) {
246
+ nextTrigger = trigger
247
+ }
248
+ }
249
+ }
250
+ }
251
+
252
+ val lockScreen = json.optJSONObject("lockScreen")
253
+ var hasTimeProgress = false
254
+ extractData(
255
+ context = context,
256
+ node = lockScreen,
257
+ onText = {},
258
+ onTimer = {},
259
+ onProgress = { p ->
260
+ if (p.targetTimestamp != null && p.targetTimestamp > now) {
261
+ hasTimeProgress = true
262
+ }
263
+ },
264
+ onImage = {},
265
+ onButton = {}
266
+ )
267
+
268
+ if (hasTimeProgress) {
269
+ val tickTrigger = now + (TICK_MILLIS / 1000.0)
270
+ if (nextTrigger == null || tickTrigger < nextTrigger) {
271
+ nextTrigger = tickTrigger
272
+ }
273
+ }
274
+
275
+ if (nextTrigger != null) {
276
+ val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
277
+ val intent = Intent(context, LiveActivityReceiver::class.java).apply {
278
+ action = LiveActivityReceiver.ACTION_REFRESH
279
+ putExtra("activityId", activityId)
280
+ }
281
+ val pendingIntent = PendingIntent.getBroadcast(
282
+ context,
283
+ activityId.hashCode(),
284
+ intent,
285
+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
286
+ )
287
+
288
+ val triggerMillis = (nextTrigger * 1000).toLong()
289
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
290
+ alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, triggerMillis, pendingIntent)
291
+ } else {
292
+ alarmManager.setExact(AlarmManager.RTC_WAKEUP, triggerMillis, pendingIntent)
293
+ }
294
+ }
295
+ }
296
+
297
+ private fun cancelRefresh(context: Context, activityId: String) {
298
+ val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
299
+ val intent = Intent(context, LiveActivityReceiver::class.java).apply {
300
+ action = LiveActivityReceiver.ACTION_REFRESH
301
+ putExtra("activityId", activityId)
302
+ }
303
+ val pendingIntent = PendingIntent.getBroadcast(
304
+ context,
305
+ activityId.hashCode(),
306
+ intent,
307
+ PendingIntent.FLAG_NO_CREATE or PendingIntent.FLAG_IMMUTABLE
308
+ )
309
+ if (pendingIntent != null) {
310
+ alarmManager.cancel(pendingIntent)
311
+ }
312
+ }
313
+
314
+ private fun extractData(
315
+ context: Context,
316
+ node: JSONObject?,
317
+ onText: (String) -> Unit,
318
+ onTimer: (Double) -> Unit,
319
+ onProgress: (ProgressData) -> Unit,
320
+ onImage: (Bitmap) -> Unit,
321
+ onButton: (NotificationButtonData) -> Unit
322
+ ) {
323
+ if (node == null) return
324
+ val type = node.optString("type")
325
+ val props = node.optJSONObject("props")
326
+
327
+ when {
328
+ type == "Text" && props != null -> {
329
+ val text = props.optString("text")
330
+ if (text.isNotEmpty()) onText(text)
331
+ }
332
+ type == "Timer" && props != null -> {
333
+ val ts = props.optDouble("targetTimestamp", 0.0)
334
+ if (ts > 0) onTimer(ts)
335
+ }
336
+ type == "Progress" && props != null -> {
337
+ val startTs = props.optDouble("startTimestamp", -1.0).takeIf { it > 0 }
338
+ val targetTs = props.optDouble("targetTimestamp", -1.0).takeIf { it > 0 }
339
+ val valDouble = props.optDouble("value", -1.0).takeIf { it >= 0 }
340
+ val style = props.optString("style", "bar")
341
+ val countsDown = props.optBoolean("countsDown", false)
342
+ val segments = props.optInt("segments", -1).takeIf { it > 0 }
343
+ val currentSeg = props.optInt("currentSegment", -1).takeIf { it > 0 }
344
+ val tint = props.optString("tintColor", "").takeIf { it.isNotEmpty() }
345
+ val track = props.optString("trackColor", "").takeIf { it.isNotEmpty() }
346
+ val warnSecs = props.optDouble("warningSeconds", -1.0).takeIf { it > 0 }
347
+ val warnTint = props.optString("warningTintColor", "").takeIf { it.isNotEmpty() }
348
+ val showPct = props.optBoolean("showPercentage", false)
349
+
350
+ onProgress(
351
+ ProgressData(
352
+ style = style,
353
+ startTimestamp = startTs,
354
+ targetTimestamp = targetTs,
355
+ value = valDouble,
356
+ countsDown = countsDown,
357
+ tintColor = tint,
358
+ trackColor = track,
359
+ warningSeconds = warnSecs,
360
+ warningTintColor = warnTint,
361
+ segments = segments,
362
+ currentSegment = currentSeg,
363
+ showPercentage = showPct
364
+ )
365
+ )
366
+ }
367
+ type == "Image" && props != null -> {
368
+ DynamicWidgetImageCache.resolveNodeBitmap(context, props)?.let { onImage(it) }
369
+ }
370
+ type == "Button" && props != null -> {
371
+ val rawTitle = props.optString("title", "Action")
372
+ val actionId = props.optString("actionId", "")
373
+ if (actionId.isNotEmpty()) {
374
+ val isToggled = if (actionId.startsWith("toggle:")) {
375
+ DynamicWidgetStateStore.isToggled(context, actionId.removePrefix("toggle:"))
376
+ } else false
377
+ val displayTitle = if (isToggled) {
378
+ props.optString("checkedTitle", rawTitle).ifEmpty { rawTitle }
379
+ } else rawTitle
380
+ onButton(NotificationButtonData(title = displayTitle, actionId = actionId))
381
+ }
382
+ }
383
+ }
384
+
385
+ val children = node.optJSONArray("children")
386
+ if (children != null) {
387
+ for (i in 0 until children.length()) {
388
+ extractData(context, children.optJSONObject(i), onText, onTimer, onProgress, onImage, onButton)
389
+ }
390
+ }
391
+ }
392
+
393
+ private fun ensureChannel(manager: NotificationManager) {
394
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
395
+ if (manager.getNotificationChannel(CHANNEL_ID) == null) {
396
+ val channel = NotificationChannel(
397
+ CHANNEL_ID,
398
+ "Live Updates",
399
+ NotificationManager.IMPORTANCE_HIGH
400
+ ).apply {
401
+ description = "Ongoing Live Activities and status updates"
402
+ }
403
+ manager.createNotificationChannel(channel)
404
+ }
405
+ }
406
+ }
407
+
408
+ private fun prefs(context: Context) =
409
+ context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
410
+ }
@@ -0,0 +1,67 @@
1
+ package com.reactnativeliveactivity
2
+
3
+ import android.content.BroadcastReceiver
4
+ import android.content.Context
5
+ import android.content.Intent
6
+ import java.util.concurrent.Executors
7
+
8
+ class LiveActivityReceiver : BroadcastReceiver() {
9
+ companion object {
10
+ const val ACTION_REFRESH = "com.reactnativeliveactivity.ACTION_REFRESH"
11
+ const val ACTION_WIDGET_ACTION = "com.reactnativeliveactivity.ACTION_WIDGET_ACTION"
12
+ const val ACTION_WIDGET_SYNC = "com.reactnativeliveactivity.ACTION_WIDGET_SYNC"
13
+ private val executor = Executors.newCachedThreadPool()
14
+ }
15
+
16
+ override fun onReceive(context: Context, intent: Intent) {
17
+ when (intent.action) {
18
+ ACTION_REFRESH -> {
19
+ val activityId = intent.getStringExtra("activityId") ?: return
20
+ LiveActivityNotifier.refresh(context, activityId)
21
+ }
22
+
23
+ ACTION_WIDGET_SYNC -> {
24
+ val widgetKey = intent.getStringExtra("widgetKey") ?: "main"
25
+ val pendingResult = goAsync()
26
+ executor.execute {
27
+ try {
28
+ DynamicWidgetStateStore.performRemoteSync(context, widgetKey)
29
+ DynamicHomeScreenWidgetProvider.updateAllWidgets(context)
30
+ } finally {
31
+ pendingResult.finish()
32
+ }
33
+ }
34
+ }
35
+
36
+ ACTION_WIDGET_ACTION -> {
37
+ val actionId = intent.getStringExtra("actionId") ?: return
38
+ val activityId = intent.getStringExtra("activityId") ?: ""
39
+ val pendingResult = goAsync()
40
+ executor.execute {
41
+ try {
42
+ if (actionId == "refresh" || actionId.startsWith("refresh:")) {
43
+ val wKey = if (actionId.startsWith("refresh:")) {
44
+ actionId.removePrefix("refresh:")
45
+ } else "main"
46
+ DynamicWidgetStateStore.performRemoteSync(context, wKey)
47
+ } else {
48
+ DynamicWidgetStateStore.handleAction(context, actionId)
49
+ }
50
+ DynamicHomeScreenWidgetProvider.updateAllWidgets(context)
51
+ LiveActivityNotifier.refreshAllActive(context)
52
+ LiveActivityModule.emitActionClicked(actionId, activityId)
53
+ try {
54
+ val headlessIntent = Intent(context, LiveActivityHeadlessTaskService::class.java).apply {
55
+ putExtra("actionId", actionId)
56
+ putExtra("activityId", activityId)
57
+ }
58
+ context.startService(headlessIntent)
59
+ } catch (_: Exception) {}
60
+ } finally {
61
+ pendingResult.finish()
62
+ }
63
+ }
64
+ }
65
+ }
66
+ }
67
+ }
@@ -0,0 +1,64 @@
1
+ package com.reactnativeliveactivity
2
+
3
+ import android.content.Context
4
+ import android.graphics.Canvas
5
+ import android.graphics.RectF
6
+ import org.json.JSONObject
7
+ import java.util.concurrent.ConcurrentHashMap
8
+
9
+ /**
10
+ * Cho phép Developer đăng ký thêm bất kỳ Custom Component nào trên Android để gọi từ React Native
11
+ * thông qua `UI.Custom("ComponentName", props)`.
12
+ *
13
+ * Ví dụ đăng ký trong `MainApplication.onCreate()`:
14
+ * ```kotlin
15
+ * DynamicNodeRegistry.register(
16
+ * componentName = "WeatherMapCard",
17
+ * heightDp = { props -> 64f },
18
+ * drawer = { context, canvas, rect, props, density ->
19
+ * // Tự vẽ lên Canvas của Widget
20
+ * }
21
+ * )
22
+ * ```
23
+ */
24
+ object DynamicNodeRegistry {
25
+
26
+ fun interface CustomCanvasDrawer {
27
+ fun draw(
28
+ context: Context,
29
+ canvas: Canvas,
30
+ rect: RectF,
31
+ props: JSONObject?,
32
+ density: Float
33
+ )
34
+ }
35
+
36
+ data class RegisteredComponent(
37
+ val heightDpProvider: (JSONObject?) -> Float,
38
+ val drawer: CustomCanvasDrawer
39
+ )
40
+
41
+ private val registry = ConcurrentHashMap<String, RegisteredComponent>()
42
+
43
+ @JvmStatic
44
+ fun register(
45
+ componentName: String,
46
+ heightDp: (JSONObject?) -> Float = { props -> (props?.optDouble("height", 48.0) ?: 48.0).toFloat() },
47
+ drawer: CustomCanvasDrawer
48
+ ) {
49
+ registry[componentName] = RegisteredComponent(heightDp, drawer)
50
+ }
51
+
52
+ fun resolve(node: JSONObject): RegisteredComponent? {
53
+ val type = node.optString("type", "")
54
+ val props = node.optJSONObject("props")
55
+ val key = if (type == "Custom") {
56
+ props?.optString("componentName", "") ?: ""
57
+ } else {
58
+ type
59
+ }
60
+ if (key.isEmpty()) return null
61
+ return registry[key]
62
+ }
63
+ }
64
+