react-native-live-widgets 0.0.0-stage → 1.1.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 (65) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/LICENSE +21 -0
  3. package/README.md +367 -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 +441 -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/app.plugin.js +114 -0
  19. package/assets/cross_platform_parity.png +0 -0
  20. package/assets/dashboard_features.png +0 -0
  21. package/assets/donate_qr.png +0 -0
  22. package/assets/dynamic_island_expanded.png +0 -0
  23. package/assets/home_widget_interactive.png +0 -0
  24. package/assets/lock_screen_live_activity.png +0 -0
  25. package/cli/setup.js +491 -0
  26. package/docs/EXPO-GUIDE-EN.md +405 -0
  27. package/docs/EXPO-GUIDE-VI.md +427 -0
  28. package/docs/GUIDE-EN.md +847 -0
  29. package/docs/GUIDE-VI.md +845 -0
  30. package/docs/widgets.md +52 -0
  31. package/ios/Bridge/LiveActivityModule.m +105 -0
  32. package/ios/Bridge/LiveActivityModule.swift +957 -0
  33. package/ios/Intents/DynamicWidgetActionIntent.swift +38 -0
  34. package/ios/Models/DynamicActivityAttributes.swift +22 -0
  35. package/ios/Models/DynamicLayoutModels.swift +243 -0
  36. package/ios/Renderer/ColorHexExtension.swift +49 -0
  37. package/ios/Renderer/DynamicNodeRegistry.swift +54 -0
  38. package/ios/Renderer/DynamicNodeView.swift +1060 -0
  39. package/ios/Storage/DynamicWidgetImageCache.swift +137 -0
  40. package/ios/Storage/DynamicWidgetStateStore.swift +162 -0
  41. package/ios/Widgets/DynamicHomeScreenWidget.swift +435 -0
  42. package/ios/Widgets/DynamicLiveActivityWidget.swift +79 -0
  43. package/lib/builder.d.ts +60 -0
  44. package/lib/builder.d.ts.map +1 -0
  45. package/lib/builder.js +292 -0
  46. package/lib/builder.js.map +1 -0
  47. package/lib/dispatcher.d.ts +16 -0
  48. package/lib/dispatcher.d.ts.map +1 -0
  49. package/lib/dispatcher.js +18 -0
  50. package/lib/dispatcher.js.map +1 -0
  51. package/lib/index.d.ts +199 -0
  52. package/lib/index.d.ts.map +1 -0
  53. package/lib/index.js +621 -0
  54. package/lib/index.js.map +1 -0
  55. package/lib/types.d.ts +489 -0
  56. package/lib/types.d.ts.map +1 -0
  57. package/lib/types.js +9 -0
  58. package/lib/types.js.map +1 -0
  59. package/package.json +85 -4
  60. package/react-native-live-widgets.podspec +38 -0
  61. package/src/builder.ts +409 -0
  62. package/src/dispatcher.ts +25 -0
  63. package/src/index.ts +689 -0
  64. package/src/react-native-env.d.ts +29 -0
  65. package/src/types.ts +595 -0
@@ -0,0 +1,120 @@
1
+ package com.reactnativeliveactivity
2
+
3
+ import android.content.Context
4
+ import android.graphics.Bitmap
5
+ import android.graphics.BitmapFactory
6
+ import android.util.Base64
7
+ import android.util.LruCache
8
+ import org.json.JSONObject
9
+ import java.io.File
10
+ import java.io.FileOutputStream
11
+ import java.net.HttpURLConnection
12
+ import java.net.URL
13
+ import java.util.regex.Pattern
14
+ import kotlin.math.max
15
+ import kotlin.math.roundToInt
16
+
17
+ object DynamicWidgetImageCache {
18
+ private val memCache = object : LruCache<String, Bitmap>(16 * 1024 * 1024) {
19
+ override fun sizeOf(key: String, value: Bitmap): Int = value.byteCount
20
+ }
21
+
22
+ fun cacheKey(urlStr: String): String {
23
+ var hash = 5381L
24
+ for (b in urlStr.toByteArray(Charsets.UTF_8)) {
25
+ hash = ((hash shl 5) + hash) + (b.toLong() and 0xFF)
26
+ }
27
+ return String.format("img_%016x", hash)
28
+ }
29
+
30
+ fun getCachedBitmap(context: Context, urlStr: String): Bitmap? {
31
+ val key = cacheKey(urlStr)
32
+ memCache.get(key)?.let { return it }
33
+
34
+ val file = File(context.cacheDir, "rn_live_widgets_$key.png")
35
+ if (file.exists()) {
36
+ BitmapFactory.decodeFile(file.absolutePath)?.let { bmp ->
37
+ memCache.put(key, bmp)
38
+ return bmp
39
+ }
40
+ }
41
+ return null
42
+ }
43
+
44
+ fun prefetchUrlsSync(context: Context, jsonString: String) {
45
+ if (!jsonString.contains("http")) return
46
+ val pattern = Pattern.compile("\"url\"\\s*:\\s*\"(https?://[^\"]+)\"")
47
+ val matcher = pattern.matcher(jsonString)
48
+ val urls = mutableSetOf<String>()
49
+ while (matcher.find()) {
50
+ matcher.group(1)?.let { urls.add(it) }
51
+ }
52
+ for (urlStr in urls) {
53
+ if (getCachedBitmap(context, urlStr) != null) continue
54
+ try {
55
+ val conn = (URL(urlStr).openConnection() as HttpURLConnection).apply {
56
+ connectTimeout = 6000
57
+ readTimeout = 6000
58
+ instanceFollowRedirects = true
59
+ }
60
+ val bytes = conn.inputStream.use { it.readBytes() }
61
+ conn.disconnect()
62
+ val rawBmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.size) ?: continue
63
+ val scaled = downscaleBitmap(rawBmp, 360)
64
+ val key = cacheKey(urlStr)
65
+ memCache.put(key, scaled)
66
+ val file = File(context.cacheDir, "rn_live_widgets_$key.png")
67
+ FileOutputStream(file).use { out ->
68
+ scaled.compress(Bitmap.CompressFormat.PNG, 90, out)
69
+ }
70
+ } catch (_: Exception) {
71
+ }
72
+ }
73
+ }
74
+
75
+ fun resolveNodeBitmap(context: Context, props: JSONObject?): Bitmap? {
76
+ if (props == null) return null
77
+
78
+ val urlStr = props.optString("url", "")
79
+ if (urlStr.isNotEmpty()) {
80
+ getCachedBitmap(context, urlStr)?.let { return it }
81
+ }
82
+
83
+ val base64Str = props.optString("base64", "")
84
+ if (base64Str.isNotEmpty()) {
85
+ try {
86
+ val clean = base64Str.substringAfter(",", base64Str)
87
+ val bytes = Base64.decode(clean, Base64.DEFAULT)
88
+ BitmapFactory.decodeByteArray(bytes, 0, bytes.size)?.let { return it }
89
+ } catch (_: Exception) {
90
+ }
91
+ }
92
+
93
+ val filePath = props.optString("filePath", "")
94
+ if (filePath.isNotEmpty()) {
95
+ BitmapFactory.decodeFile(filePath)?.let { return it }
96
+ }
97
+
98
+ val assetName = props.optString("assetName", "")
99
+ if (assetName.isNotEmpty()) {
100
+ val resId = context.resources.getIdentifier(assetName, "drawable", context.packageName)
101
+ .takeIf { it != 0 }
102
+ ?: context.resources.getIdentifier(assetName, "mipmap", context.packageName)
103
+ if (resId != 0) {
104
+ BitmapFactory.decodeResource(context.resources, resId)?.let { return it }
105
+ }
106
+ }
107
+
108
+ return null
109
+ }
110
+
111
+ private fun downscaleBitmap(bmp: Bitmap, maxDimension: Int): Bitmap {
112
+ val maxSide = max(bmp.width, bmp.height)
113
+ if (maxSide <= maxDimension) return bmp
114
+ val ratio = maxDimension.toFloat() / maxSide.toFloat()
115
+ val w = (bmp.width * ratio).roundToInt().coerceAtLeast(1)
116
+ val h = (bmp.height * ratio).roundToInt().coerceAtLeast(1)
117
+ return Bitmap.createScaledBitmap(bmp, w, h, true)
118
+ }
119
+ }
120
+
@@ -0,0 +1,281 @@
1
+ package com.reactnativeliveactivity
2
+
3
+ import android.app.AlarmManager
4
+ import android.app.PendingIntent
5
+ import android.content.Context
6
+ import android.content.Intent
7
+ import android.os.Build
8
+ import org.json.JSONArray
9
+ import org.json.JSONObject
10
+ import java.net.HttpURLConnection
11
+ import java.net.URL
12
+ import java.text.SimpleDateFormat
13
+ import java.util.Date
14
+ import java.util.Locale
15
+ import kotlin.random.Random
16
+
17
+ data class InteractiveWidgetState(
18
+ var activePage: String? = null,
19
+ var pageOrder: List<String> = emptyList(),
20
+ var toggledItems: MutableMap<String, Boolean> = mutableMapOf(),
21
+ var lastActionId: String? = null,
22
+ var lastSyncTime: String? = null,
23
+ var remoteVariables: MutableMap<String, String> = mutableMapOf(),
24
+ var updatedAt: Long = System.currentTimeMillis()
25
+ )
26
+
27
+ object DynamicWidgetStateStore {
28
+ const val SHARED_PREFS_NAME = "rn_live_widgets_shared"
29
+ private const val STATE_KEY = "interactive_state"
30
+
31
+ fun getPrefs(context: Context, customGroup: String = "") =
32
+ context.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE)
33
+
34
+ fun readSharedString(context: Context, key: String): String? {
35
+ return getPrefs(context).getString(key, null)
36
+ }
37
+
38
+ fun writeSharedString(context: Context, key: String, value: String) {
39
+ getPrefs(context).edit().putString(key, value).apply()
40
+ }
41
+
42
+ fun loadState(context: Context): InteractiveWidgetState {
43
+ val raw = readSharedString(context, STATE_KEY) ?: return InteractiveWidgetState()
44
+ return try {
45
+ val obj = JSONObject(raw)
46
+ val orderList = mutableListOf<String>()
47
+ obj.optJSONArray("pageOrder")?.let { arr ->
48
+ for (i in 0 until arr.length()) {
49
+ orderList.add(arr.optString(i))
50
+ }
51
+ }
52
+ val toggled = mutableMapOf<String, Boolean>()
53
+ obj.optJSONObject("toggledItems")?.let { tObj ->
54
+ val keys = tObj.keys()
55
+ while (keys.hasNext()) {
56
+ val k = keys.next()
57
+ toggled[k] = tObj.optBoolean(k, false)
58
+ }
59
+ }
60
+ val vars = mutableMapOf<String, String>()
61
+ obj.optJSONObject("remoteVariables")?.let { vObj ->
62
+ val keys = vObj.keys()
63
+ while (keys.hasNext()) {
64
+ val k = keys.next()
65
+ vars[k] = vObj.optString(k, "")
66
+ }
67
+ }
68
+ InteractiveWidgetState(
69
+ activePage = obj.optString("activePage", "").ifEmpty { null },
70
+ pageOrder = orderList,
71
+ toggledItems = toggled,
72
+ lastActionId = obj.optString("lastActionId", "").ifEmpty { null },
73
+ lastSyncTime = obj.optString("lastSyncTime", "").ifEmpty { null },
74
+ remoteVariables = vars,
75
+ updatedAt = obj.optLong("updatedAt", System.currentTimeMillis())
76
+ )
77
+ } catch (_: Exception) {
78
+ InteractiveWidgetState()
79
+ }
80
+ }
81
+
82
+ fun saveState(context: Context, state: InteractiveWidgetState) {
83
+ try {
84
+ val obj = JSONObject()
85
+ state.activePage?.let { obj.put("activePage", it) }
86
+ obj.put("pageOrder", JSONArray(state.pageOrder))
87
+
88
+ val tObj = JSONObject()
89
+ for ((k, v) in state.toggledItems) {
90
+ tObj.put(k, v)
91
+ }
92
+ obj.put("toggledItems", tObj)
93
+
94
+ state.lastActionId?.let { obj.put("lastActionId", it) }
95
+ state.lastSyncTime?.let { obj.put("lastSyncTime", it) }
96
+
97
+ val vObj = JSONObject()
98
+ for ((k, v) in state.remoteVariables) {
99
+ vObj.put(k, v)
100
+ }
101
+ obj.put("remoteVariables", vObj)
102
+ obj.put("updatedAt", state.updatedAt)
103
+
104
+ writeSharedString(context, STATE_KEY, obj.toString())
105
+ } catch (_: Exception) {
106
+ }
107
+ }
108
+
109
+ fun initializeFromLayoutJson(context: Context, layoutJson: String) {
110
+ try {
111
+ val dto = JSONObject(layoutJson)
112
+ val state = loadState(context)
113
+ val initial = dto.optString("initialPage", "")
114
+ if (initial.isNotEmpty()) {
115
+ state.activePage = initial
116
+ }
117
+ val orderArr = dto.optJSONArray("pageOrder")
118
+ if (orderArr != null && orderArr.length() > 0) {
119
+ val list = mutableListOf<String>()
120
+ for (i in 0 until orderArr.length()) {
121
+ list.add(orderArr.optString(i))
122
+ }
123
+ state.pageOrder = list
124
+ } else {
125
+ val pagesObj = dto.optJSONObject("pages")
126
+ if (pagesObj != null) {
127
+ val keys = mutableListOf<String>()
128
+ val iter = pagesObj.keys()
129
+ while (iter.hasNext()) keys.add(iter.next())
130
+ state.pageOrder = keys.sorted()
131
+ }
132
+ }
133
+ saveState(context, state)
134
+ } catch (_: Exception) {
135
+ }
136
+ }
137
+
138
+ fun handleAction(context: Context, actionId: String) {
139
+ val state = loadState(context)
140
+ state.lastActionId = actionId
141
+ state.updatedAt = System.currentTimeMillis()
142
+
143
+ when {
144
+ actionId.startsWith("page:") -> {
145
+ val target = actionId.removePrefix("page:")
146
+ val order = state.pageOrder
147
+ if (target == "next" && order.isNotEmpty()) {
148
+ val current = state.activePage ?: order.first()
149
+ val idx = order.indexOf(current)
150
+ state.activePage = if (idx >= 0) order[(idx + 1) % order.size] else order.first()
151
+ } else if (target == "prev" && order.isNotEmpty()) {
152
+ val current = state.activePage ?: order.first()
153
+ val idx = order.indexOf(current)
154
+ state.activePage = if (idx >= 0) order[(idx - 1 + order.size) % order.size] else order.first()
155
+ } else {
156
+ state.activePage = target
157
+ }
158
+ }
159
+ actionId.startsWith("toggle:") -> {
160
+ val key = actionId.removePrefix("toggle:")
161
+ val current = state.toggledItems[key] ?: false
162
+ state.toggledItems[key] = !current
163
+ }
164
+ }
165
+
166
+ saveState(context, state)
167
+ }
168
+
169
+ fun isToggled(context: Context, key: String): Boolean {
170
+ return loadState(context).toggledItems[key] ?: false
171
+ }
172
+
173
+ fun resolveLayoutJsonWithVariables(context: Context, widgetKey: String): String? {
174
+ var raw = readSharedString(context, "widget_layout_$widgetKey") ?: return null
175
+ val state = loadState(context)
176
+ val syncTime = state.lastSyncTime
177
+ ?: SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(Date())
178
+ raw = raw.replace("{{_lastSyncTime}}", syncTime)
179
+
180
+ for ((k, v) in state.remoteVariables) {
181
+ val escaped = v.replace("\"", "\\\"")
182
+ raw = raw.replace("{{$k}}", escaped)
183
+ }
184
+ return raw
185
+ }
186
+
187
+ /**
188
+ * Đồng bộ API chạy ngầm trực tiếp từ BroadcastReceiver / AppWidgetProvider
189
+ * kể cả khi ứng dụng React Native đã bị Kill hoàn toàn!
190
+ */
191
+ fun performRemoteSync(context: Context, widgetKey: String = "main") {
192
+ val configJson = readSharedString(context, "widget_remote_config_$widgetKey")
193
+ if (configJson.isNullOrEmpty()) {
194
+ stampSyncTimeOnly(context)
195
+ return
196
+ }
197
+
198
+ try {
199
+ val config = JSONObject(configJson)
200
+ val rawUrl = config.optString("url", "")
201
+ if (rawUrl.isEmpty()) {
202
+ stampSyncTimeOnly(context)
203
+ return
204
+ }
205
+
206
+ val randomId = Random.nextInt(1, 21)
207
+ val resolvedUrl = rawUrl.replace("{{_randomId}}", randomId.toString())
208
+ val conn = (URL(resolvedUrl).openConnection() as HttpURLConnection).apply {
209
+ requestMethod = config.optString("method", "GET")
210
+ connectTimeout = 8000
211
+ readTimeout = 8000
212
+ config.optJSONObject("headers")?.let { headers ->
213
+ val keys = headers.keys()
214
+ while (keys.hasNext()) {
215
+ val k = keys.next()
216
+ setRequestProperty(k, headers.optString(k))
217
+ }
218
+ }
219
+ }
220
+
221
+ val responseText = conn.inputStream.bufferedReader().use { it.readText() }
222
+ conn.disconnect()
223
+
224
+ val state = loadState(context)
225
+ state.lastSyncTime = SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(Date())
226
+ state.updatedAt = System.currentTimeMillis()
227
+
228
+ val jsonObj = JSONObject(responseText)
229
+ if (jsonObj.has("small") || jsonObj.has("medium") || jsonObj.has("large") || jsonObj.has("pages")) {
230
+ writeSharedString(context, "widget_layout_$widgetKey", responseText)
231
+ DynamicWidgetImageCache.prefetchUrlsSync(context, responseText)
232
+ }
233
+
234
+ val keys = jsonObj.keys()
235
+ while (keys.hasNext()) {
236
+ val k = keys.next()
237
+ val v = jsonObj.opt(k)
238
+ if (v is String || v is Number || v is Boolean) {
239
+ state.remoteVariables[k] = v.toString()
240
+ }
241
+ }
242
+ saveState(context, state)
243
+
244
+ val intervalMins = config.optInt("refreshIntervalMinutes", 15).coerceAtLeast(1)
245
+ scheduleBackgroundWidgetSync(context, widgetKey, intervalMins)
246
+ } catch (_: Exception) {
247
+ stampSyncTimeOnly(context)
248
+ }
249
+ }
250
+
251
+ fun scheduleBackgroundWidgetSync(context: Context, widgetKey: String, intervalMinutes: Int) {
252
+ try {
253
+ val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
254
+ val intent = Intent(context, LiveActivityReceiver::class.java).apply {
255
+ action = LiveActivityReceiver.ACTION_WIDGET_SYNC
256
+ putExtra("widgetKey", widgetKey)
257
+ }
258
+ val pendingIntent = PendingIntent.getBroadcast(
259
+ context,
260
+ ("widget_sync_$widgetKey").hashCode(),
261
+ intent,
262
+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
263
+ )
264
+ val triggerAt = System.currentTimeMillis() + intervalMinutes * 60_000L
265
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
266
+ alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, triggerAt, pendingIntent)
267
+ } else {
268
+ alarmManager.setExact(AlarmManager.RTC_WAKEUP, triggerAt, pendingIntent)
269
+ }
270
+ } catch (_: Exception) {
271
+ }
272
+ }
273
+
274
+ private fun stampSyncTimeOnly(context: Context) {
275
+ val state = loadState(context)
276
+ state.lastSyncTime = SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(Date())
277
+ state.updatedAt = System.currentTimeMillis()
278
+ saveState(context, state)
279
+ }
280
+ }
281
+
@@ -0,0 +1,229 @@
1
+ package com.reactnativeliveactivity
2
+
3
+ import android.app.PendingIntent
4
+ import android.appwidget.AppWidgetManager
5
+ import android.appwidget.AppWidgetProvider
6
+ import android.content.ComponentName
7
+ import android.content.Context
8
+ import android.content.Intent
9
+ import android.net.Uri
10
+ import android.os.Build
11
+ import android.os.Bundle
12
+ import android.util.SizeF
13
+ import android.widget.RemoteViews
14
+ import org.json.JSONObject
15
+ import kotlin.math.max
16
+ import kotlin.math.roundToInt
17
+
18
+ class DynamicHomeScreenWidgetProvider : AppWidgetProvider() {
19
+
20
+ override fun onUpdate(
21
+ context: Context,
22
+ appWidgetManager: AppWidgetManager,
23
+ appWidgetIds: IntArray
24
+ ) {
25
+ for (appWidgetId in appWidgetIds) {
26
+ val options = appWidgetManager.getAppWidgetOptions(appWidgetId)
27
+ updateSingleWidget(context, appWidgetManager, appWidgetId, options)
28
+ }
29
+ }
30
+
31
+ override fun onAppWidgetOptionsChanged(
32
+ context: Context,
33
+ appWidgetManager: AppWidgetManager,
34
+ appWidgetId: Int,
35
+ newOptions: Bundle
36
+ ) {
37
+ super.onAppWidgetOptionsChanged(context, appWidgetManager, appWidgetId, newOptions)
38
+ updateSingleWidget(context, appWidgetManager, appWidgetId, newOptions)
39
+ }
40
+
41
+ companion object {
42
+ fun updateAllWidgets(context: Context) {
43
+ try {
44
+ val manager = AppWidgetManager.getInstance(context)
45
+ val component = ComponentName(context, DynamicHomeScreenWidgetProvider::class.java)
46
+ val ids = manager.getAppWidgetIds(component)
47
+ for (id in ids) {
48
+ val opts = manager.getAppWidgetOptions(id)
49
+ updateSingleWidget(context, manager, id, opts)
50
+ }
51
+ } catch (_: Exception) {
52
+ }
53
+ }
54
+
55
+ private fun resolvePortraitWidgetSizeDp(options: Bundle?): Pair<Float, Float> {
56
+ if (options == null) return Pair(320f, 240f)
57
+
58
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
59
+ @Suppress("DEPRECATION")
60
+ val sizes = options.getParcelableArrayList<SizeF>(AppWidgetManager.OPTION_APPWIDGET_SIZES)
61
+ if (!sizes.isNullOrEmpty()) {
62
+ val portrait = sizes.minByOrNull { it.width } ?: sizes[0]
63
+ if (portrait.width > 0f && portrait.height > 0f) {
64
+ return Pair(portrait.width, portrait.height)
65
+ }
66
+ }
67
+ }
68
+
69
+ val minW = options.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH, 0).takeIf { it > 0 } ?: 320
70
+ val minH = options.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT, 0).takeIf { it > 0 } ?: 200
71
+ val maxH = options.getInt(AppWidgetManager.OPTION_APPWIDGET_MAX_HEIGHT, 0).takeIf { it > 0 } ?: minH
72
+ return Pair(minW.toFloat(), max(minH, maxH).toFloat())
73
+ }
74
+
75
+ fun updateSingleWidget(
76
+ context: Context,
77
+ appWidgetManager: AppWidgetManager,
78
+ appWidgetId: Int,
79
+ options: Bundle?
80
+ ) {
81
+ val views = RemoteViews(context.packageName, R.layout.rn_live_widget_host)
82
+ val screenDensity = context.resources.displayMetrics.density.coerceAtLeast(2.0f)
83
+
84
+ val (rawWidthDp, rawHeightDp) = resolvePortraitWidgetSizeDp(options)
85
+ val widgetWidthDp = rawWidthDp.coerceIn(110f, 460f)
86
+ val widgetHeightDp = rawHeightDp.coerceIn(110f, 520f)
87
+
88
+ val family = when {
89
+ widgetWidthDp < 245f -> "small"
90
+ widgetHeightDp < 235f -> "medium"
91
+ else -> "large"
92
+ }
93
+
94
+ val rawJson = DynamicWidgetStateStore.resolveLayoutJsonWithVariables(context, "main")
95
+ val activeNode = selectActiveNode(context, rawJson, family)
96
+
97
+ val logicalWidthDp = when (family) {
98
+ "small" -> 164f
99
+ "medium" -> 330f
100
+ else -> 340f
101
+ }
102
+ val aspectRatio = when (family) {
103
+ "small" -> 1.02f
104
+ "medium" -> (widgetHeightDp / widgetWidthDp).coerceIn(0.45f, 0.62f)
105
+ else -> (widgetHeightDp / widgetWidthDp).coerceIn(0.78f, 1.45f)
106
+ }
107
+ val logicalHeightDp = logicalWidthDp * aspectRatio
108
+
109
+ val renderDensity = max(screenDensity, (widgetWidthDp * screenDensity) / logicalWidthDp)
110
+ val widthPx = (logicalWidthDp * renderDensity).roundToInt().coerceAtLeast(320)
111
+ val heightPx = (logicalHeightDp * renderDensity).roundToInt().coerceAtLeast(220)
112
+
113
+ val bindings = mutableListOf<ButtonActionBinding>()
114
+ val bmp = DynamicWidgetCanvasRenderer.renderWidgetBitmap(
115
+ context = context,
116
+ rootNode = activeNode,
117
+ widthPx = widthPx,
118
+ heightPx = heightPx,
119
+ baseDensity = renderDensity,
120
+ family = family,
121
+ bindings = bindings
122
+ )
123
+ views.setImageViewBitmap(R.id.rn_widget_canvas, bmp)
124
+
125
+ bindHitZones(context, views, appWidgetId, bindings)
126
+ appWidgetManager.updateAppWidget(appWidgetId, views)
127
+ }
128
+
129
+ private fun selectActiveNode(context: Context, rawJson: String?, family: String): JSONObject? {
130
+ if (rawJson.isNullOrEmpty()) return null
131
+ return try {
132
+ val payload = JSONObject(rawJson)
133
+ val pages = payload.optJSONObject("pages")
134
+ if (pages != null && pages.length() > 0) {
135
+ val state = DynamicWidgetStateStore.loadState(context)
136
+ val initial = payload.optString("initialPage", "")
137
+ val activePageId = when {
138
+ !state.activePage.isNullOrEmpty() && pages.has(state.activePage!!) -> state.activePage!!
139
+ initial.isNotEmpty() && pages.has(initial) -> initial
140
+ else -> pages.keys().next()
141
+ }
142
+ val pageObj = pages.optJSONObject(activePageId) ?: return null
143
+ selectFamilyFromObject(pageObj, family)
144
+ } else {
145
+ selectFamilyFromObject(payload, family)
146
+ }
147
+ } catch (_: Exception) {
148
+ null
149
+ }
150
+ }
151
+
152
+ private fun selectFamilyFromObject(obj: JSONObject, family: String): JSONObject? {
153
+ return when (family) {
154
+ "small" -> obj.optJSONObject("small") ?: obj.optJSONObject("medium") ?: obj.optJSONObject("large")
155
+ "medium" -> obj.optJSONObject("medium") ?: obj.optJSONObject("large") ?: obj.optJSONObject("small")
156
+ else -> obj.optJSONObject("large") ?: obj.optJSONObject("medium") ?: obj.optJSONObject("small")
157
+ }
158
+ }
159
+
160
+ private fun bindHitZones(
161
+ context: Context,
162
+ views: RemoteViews,
163
+ appWidgetId: Int,
164
+ bindings: List<ButtonActionBinding>
165
+ ) {
166
+ val topIds = listOf(R.id.rn_hit_top_1, R.id.rn_hit_top_2, R.id.rn_hit_top_3, R.id.rn_hit_top_4)
167
+ val midIds = listOf(R.id.rn_hit_mid_1, R.id.rn_hit_mid_2, R.id.rn_hit_mid_3)
168
+ val botIds = listOf(R.id.rn_hit_bot_1, R.id.rn_hit_bot_2)
169
+
170
+ val topBindings = bindings.filter { it.zone == "top" }
171
+ val midBindings = bindings.filter { it.zone == "mid" }
172
+ val botBindings = bindings.filter { it.zone == "bot" }
173
+
174
+ for (i in topIds.indices) {
175
+ val b = topBindings.getOrNull(i)
176
+ views.setOnClickPendingIntent(topIds[i], createPendingIntent(context, appWidgetId * 100 + i, b))
177
+ }
178
+ for (i in midIds.indices) {
179
+ val b = midBindings.getOrNull(i)
180
+ views.setOnClickPendingIntent(midIds[i], createPendingIntent(context, appWidgetId * 100 + 20 + i, b))
181
+ }
182
+ for (i in botIds.indices) {
183
+ val b = botBindings.getOrNull(i)
184
+ views.setOnClickPendingIntent(botIds[i], createPendingIntent(context, appWidgetId * 100 + 40 + i, b))
185
+ }
186
+ }
187
+
188
+ private fun createPendingIntent(
189
+ context: Context,
190
+ requestCode: Int,
191
+ binding: ButtonActionBinding?
192
+ ): PendingIntent? {
193
+ if (binding == null) {
194
+ val launchIntent = context.packageManager.getLaunchIntentForPackage(context.packageName)
195
+ ?: return null
196
+ return PendingIntent.getActivity(
197
+ context,
198
+ requestCode,
199
+ launchIntent,
200
+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
201
+ )
202
+ }
203
+
204
+ if (!binding.deepLink.isNullOrEmpty()) {
205
+ val deepIntent = Intent(Intent.ACTION_VIEW, Uri.parse(binding.deepLink)).apply {
206
+ flags = Intent.FLAG_ACTIVITY_NEW_TASK
207
+ }
208
+ return PendingIntent.getActivity(
209
+ context,
210
+ requestCode,
211
+ deepIntent,
212
+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
213
+ )
214
+ }
215
+
216
+ val intent = Intent(context, LiveActivityReceiver::class.java).apply {
217
+ action = LiveActivityReceiver.ACTION_WIDGET_ACTION
218
+ putExtra("actionId", binding.actionId)
219
+ }
220
+ return PendingIntent.getBroadcast(
221
+ context,
222
+ requestCode,
223
+ intent,
224
+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
225
+ )
226
+ }
227
+ }
228
+ }
229
+