react-native-live-widgets 1.1.0 → 1.2.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 (53) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +76 -10
  3. package/android/build.gradle +14 -20
  4. package/android/src/main/AndroidManifest.xml +1 -0
  5. package/android/src/main/java/com/reactnativeliveactivity/bridge/LiveActivityModule.kt +5 -1
  6. package/android/src/main/java/com/reactnativeliveactivity/liveactivity/LiveActivityHeadlessTaskService.kt +8 -0
  7. package/android/src/main/java/com/reactnativeliveactivity/liveactivity/LiveActivityReceiver.kt +4 -1
  8. package/android/src/main/java/com/reactnativeliveactivity/renderer/DynamicWidgetCanvasRenderer.kt +29 -3
  9. package/android/src/main/java/com/reactnativeliveactivity/storage/DynamicWidgetStateStore.kt +26 -1
  10. package/android/src/main/java/com/reactnativeliveactivity/widgets/DynamicHomeScreenWidgetProvider.kt +51 -15
  11. package/android/src/main/res/layout/rn_live_widget_host.xml +64 -74
  12. package/docs/GUIDE-EN.md +109 -7
  13. package/docs/GUIDE-VI.md +109 -7
  14. package/docs/index.html +440 -0
  15. package/docs/llms-full.txt +132 -0
  16. package/docs/llms.txt +88 -0
  17. package/ios/Models/DynamicLayoutModels.swift +5 -0
  18. package/ios/Widgets/DynamicHomeScreenWidget.swift +2 -3
  19. package/lib/builder.d.ts.map +1 -1
  20. package/lib/builder.js +29 -19
  21. package/lib/builder.js.map +1 -1
  22. package/lib/dispatcher.d.ts +7 -0
  23. package/lib/dispatcher.d.ts.map +1 -1
  24. package/lib/dispatcher.js +11 -0
  25. package/lib/dispatcher.js.map +1 -1
  26. package/lib/hooks.d.ts +66 -0
  27. package/lib/hooks.d.ts.map +1 -0
  28. package/lib/hooks.js +166 -0
  29. package/lib/hooks.js.map +1 -0
  30. package/lib/index.d.ts +32 -7
  31. package/lib/index.d.ts.map +1 -1
  32. package/lib/index.js +115 -8
  33. package/lib/index.js.map +1 -1
  34. package/lib/jsx.d.ts +79 -0
  35. package/lib/jsx.d.ts.map +1 -0
  36. package/lib/jsx.js +196 -0
  37. package/lib/jsx.js.map +1 -0
  38. package/lib/preview.d.ts +54 -0
  39. package/lib/preview.d.ts.map +1 -0
  40. package/lib/preview.js +466 -0
  41. package/lib/preview.js.map +1 -0
  42. package/lib/types.d.ts +8 -0
  43. package/lib/types.d.ts.map +1 -1
  44. package/package.json +3 -1
  45. package/src/builder.ts +29 -19
  46. package/src/dispatcher.ts +17 -0
  47. package/src/hooks.ts +223 -0
  48. package/src/index.ts +137 -13
  49. package/src/jsx.tsx +296 -0
  50. package/src/preview.tsx +719 -0
  51. package/src/react-ambient.d.ts +10 -0
  52. package/src/react-native-env.d.ts +43 -0
  53. package/src/types.ts +8 -0
package/CHANGELOG.md CHANGED
@@ -2,6 +2,26 @@
2
2
 
3
3
  All notable changes to `react-native-live-widgets` will be documented in this file.
4
4
 
5
+ ## [1.2.0] - 2026-11-16
6
+ ### Added
7
+ - **JSX / TSX Declarative DSL**: Support building Widgets and Live Activities directly using intuitive React JSX syntax (`<VStack>`, `<HStack>`, `<ZStack>`, `<Grid>`, `<Text>`, `<Button>`, `<Badge>`, `<Progress>`, `<Timer>`, `<Image>`, `<Spacer>`, `<Divider>`) instead of nested function calls `UI.VStack(...)`.
8
+ - **In-App Widget Preview (`<WidgetPreview>` / `<VoltraWidgetPreview>`)**: Live component to render, preview, and test widget layouts and interactive button clicks directly inside your React Native screens with accurate device sizes (`small`, `medium`, `large`, `lockScreen`).
9
+ - **Seamless JSX Auto-Conversion**: `Widget.setLayout(...)` and `LiveActivity.start(...)` now accept JSX elements directly and convert them automatically into native `LayoutNode` JSON trees.
10
+
11
+ ## [1.1.2] - 2026-11-16
12
+ ### Added
13
+ - **React Hooks (Fast Refresh Resilient)**: Added `useWidgetAction`, `useLiveActivity`, and `useWidgetState` hooks with automatic lifecycle cleanup and Hot Reload resilience.
14
+ - **API Overload & Aliases**: Added `Widget.onWidgetAction`, `LiveActivity.registerActionHandler`, `Widget.update`, `cornerRadius` alias for `borderRadius`, and normalized `intervalMinutes` <-> `refreshIntervalMinutes` across TypeScript, Android (Kotlin), and iOS (Swift).
15
+
16
+ ### Documentation
17
+ - **Complete Documentation Synchronization**: Standardized function signatures, props, and code snippets across `README.md`, `GUIDE-VI.md`, `GUIDE-EN.md`, `docs/index.html`, `llms.txt`, and Agent Skill.
18
+
19
+ ## [1.1.1] - 2026-11-16
20
+ ### Fixed
21
+ - **Android Widget Interaction Crash**: Added `android.permission.WAKE_LOCK` and safely wrapped `HeadlessJsTaskService` wake lock acquisition to prevent `SecurityException` on widget tap events.
22
+ - **Android Hit Zone Accuracy**: Upgraded `rn_live_widget_host.xml` to a dynamic 6-row x 3-column interaction grid (`rn_hit_r0_c0` - `rn_hit_r5_c2`), mapping button physical coordinates (`yFraction`, `xFraction`) accurately to fix misaligned tap zones.
23
+ - **Background Headless Responsiveness**: Added native state store handling and `LiveActivity.registerBackgroundActionHandler()` support for zero-latency widget interactions even when the app is swiped away or force-killed.
24
+
5
25
  ## [1.1.0] - 2026-11-16
6
26
  ### Added
7
27
  - **Expo Config Plugin (`app.plugin.js`)**: Full Expo & EAS Build support (`npx expo prebuild` / `npx expo run:ios` / `npx expo run:android`). Automatically configures `NSSupportsLiveActivities` and `NSSupportsLiveActivitiesFrequentUpdates` in iOS `Info.plist`, App Groups entitlements, and Android notifications & foreground service permissions.
package/README.md CHANGED
@@ -4,6 +4,8 @@
4
4
 
5
5
  [![npm version](https://img.shields.io/npm/v/react-native-live-widgets.svg?style=for-the-badge&logo=npm&color=CB3837)](https://www.npmjs.com/package/react-native-live-widgets)
6
6
  [![Expo Ready](https://img.shields.io/badge/Expo-Config%20Plugin-000020.svg?style=for-the-badge&logo=expo)](https://expo.dev)
7
+ [![Docs Site](https://img.shields.io/badge/Docs-Website-6366F1.svg?style=for-the-badge&logo=bookstack)](https://react-native-vu.github.io/react-native-live-widgets/)
8
+ [![llms.txt](https://img.shields.io/badge/llms.txt-Standard%20Ready-10B981.svg?style=for-the-badge)](https://react-native-vu.github.io/react-native-live-widgets/llms.txt)
7
9
  [![Platforms](https://img.shields.io/badge/Platforms-iOS%2016.1+%20|%20Android%2016-orange.svg?style=for-the-badge)](https://github.com/React-Native-Vu/react-native-live-widgets)
8
10
  [![TypeScript](https://img.shields.io/badge/TypeScript-100%25-3178C6.svg?style=for-the-badge&logo=typescript)](https://www.typescriptlang.org/)
9
11
  [![License](https://img.shields.io/badge/License-MIT-green.svg?style=for-the-badge)](LICENSE)
@@ -12,7 +14,7 @@
12
14
 
13
15
  *Write 100% Declarative TypeScript. Render dynamically to Native SwiftUI (WidgetKit) & Android 2D Canvas without touching Xcode or Android Studio.*
14
16
 
15
- [📖 English Guide](docs/GUIDE-EN.md) • [🇻🇳 Hướng dẫn Tiếng Việt](docs/GUIDE-VI.md) • [⚡ Expo Guide](docs/EXPO-GUIDE-VI.md) • [📱 Bare RN Demo](https://github.com/React-Native-Vu/LiveWidgetsExample) • [⚡ Expo Demo](https://github.com/React-Native-Vu/LiveWidgetsExampleExpo) • [✨ Tính năng](#-key-features) • [⚡ Cài đặt](#-quick-start) • [☕ Ủng hộ tác giả](#-sponsor--donate-ủng-hộ-tác-giả)
17
+ [🌐 Docs Website](https://react-native-vu.github.io/react-native-live-widgets/) • [🤖 llms.txt](https://react-native-vu.github.io/react-native-live-widgets/llms.txt) • [🧠 AI Agent Skill](skills/react-native-live-widgets/SKILL.md) • [📖 English Guide](docs/GUIDE-EN.md) • [🇻🇳 Hướng dẫn Tiếng Việt](docs/GUIDE-VI.md) • [⚡ Expo Guide](docs/EXPO-GUIDE-VI.md) • [📱 Bare RN Demo](https://github.com/React-Native-Vu/LiveWidgetsExample) • [⚡ Expo Demo](https://github.com/React-Native-Vu/LiveWidgetsExampleExpo)
16
18
 
17
19
  ---
18
20
 
@@ -89,7 +91,8 @@ Until now, adding **Live Activities** or **Home Screen Widgets** to a React Nati
89
91
 
90
92
  `react-native-live-widgets` solves this with a **Declarative TypeScript UI DSL**:
91
93
  - 🚫 **No SwiftUI / Kotlin coding required** for custom screens.
92
- - 🎨 **100% Declarative UI in React Native (`UI.VStack`, `UI.HStack`, `UI.Text`, `UI.Button`, `UI.Progress`, `UI.Image`)**.
94
+ - 🎨 **Dual UI Syntax**: Choose between **React JSX/TSX (`<VStack>`, `<Text>`, `<Button>`)** or **Functional DSL (`UI.VStack(...)`)**.
95
+ - 📱 **In-App Widget Preview (`<WidgetPreview>`)**: Preview and test widget interactions directly on your app screen.
93
96
  - 🚀 **Full Expo & EAS Build Support** via automated Expo Config Plugin (`app.plugin.js`).
94
97
  - ⚡ **Interactive Buttons**: Tap buttons on the Home Screen Widget to run native Swift extensions or wake up TypeScript handlers.
95
98
  - 🔄 **Realtime Data Sync (`SharedStorage`)**: Single source of truth across Main App, Lock Screen, and Home Screen.
@@ -111,17 +114,32 @@ Until now, adding **Live Activities** or **Home Screen Widgets** to a React Nati
111
114
  - **Checklist & Toggles**: Toggle checkboxes and switch states without opening the app (`actionId: "toggle:<key>"`).
112
115
  - **Dark & Light Mode**: Declarative color tokens `{ light: '#FFF', dark: '#0F172A' }`.
113
116
 
114
- ### 3. ⚡ Bi-directional Action Dispatcher (TypeScript + Native)
115
- - Tap a widget button outside on the Home Screen to trigger a registered TypeScript function:
117
+ ### 3. ⚡ React Hooks & Fast Refresh Resilient
118
+ - **`useWidgetAction(actionId, callback)`**: Automatically registers and cleans up widget button tap listeners on unmount. 100% resilient to React Native Fast Refresh / Hot Reloading!
119
+ ```tsx
120
+ useWidgetAction('action_checkin', async (payload) => {
121
+ console.log('Action triggered from Home Screen Widget:', payload);
122
+ });
123
+ ```
124
+ - **`useLiveActivity()`**: Track activity state, push tokens, and control start / update / end directly in React components.
125
+ - **`useWidgetState(key, initialValue)`**: Synchronize local component state with Widget Shared Storage and trigger instant OS re-renders.
126
+
127
+ ### 4. ⚡ Bi-directional Action Dispatcher (TypeScript + Native)
128
+ - Imperative action registration for background services:
116
129
  ```ts
117
130
  LiveActivity.registerAction('action_checkin', async (payload) => {
118
- // Runs inside React Native JS engine!
119
- console.log('Action triggered from Home Screen Widget:', payload);
131
+ console.log('Action triggered:', payload);
132
+ });
133
+ // Or listen globally to all widget actions:
134
+ Widget.onWidgetAction((actionId, payload) => {
135
+ console.log(`Action ${actionId} received`, payload);
120
136
  });
121
137
  ```
122
- - **App-Killed Protection**: Native fallback ensures UI responds instantly and persists data even if the main app is terminated.
138
+ - **App-Killed Background Support**:
139
+ - **Android**: Supports `LiveActivity.registerBackgroundActionHandler()` via Headless JS tasks and instant native state persistence in `DynamicWidgetStateStore`.
140
+ - **iOS**: Apple sandboxes widget extensions when the main app is force-killed. Button taps update native App Group state directly; JavaScript callbacks resume automatically when the app is reopened.
123
141
 
124
- ### 4. 🌐 Background Remote API Sync (Zero Code Backend)
142
+ ### 5. 🌐 Background Remote API Sync (Zero Code Backend)
125
143
  - Configure an API endpoint with `Widget.setRemoteConfig`:
126
144
  ```ts
127
145
  await Widget.setRemoteConfig('main', {
@@ -249,7 +267,7 @@ await LiveActivity.start({
249
267
  )
250
268
  },
251
269
  lockScreen: UI.VStack(
252
- { padding: 16, backgroundColor: '#0F172A', cornerRadius: 16 },
270
+ { padding: 16, backgroundColor: '#0F172A', borderRadius: 16 },
253
271
  UI.HStack(
254
272
  { justifyContent: 'spaceBetween' },
255
273
  UI.Text('KPI Quý 4: Đạt 86% mục tiêu', { fontSize: 14, fontWeight: 'bold', color: '#FFFFFF' }),
@@ -280,7 +298,7 @@ await SharedStorage.set('revenue_month', '4.85 Tỷ đ', APP_GROUP);
280
298
  // Build Declarative Layout
281
299
  await Widget.setLayout('main', {
282
300
  large: UI.VStack(
283
- { padding: 16, backgroundColor: '#0B132B', cornerRadius: 20 },
301
+ { padding: 16, backgroundColor: '#0B132B', borderRadius: 20 },
284
302
  UI.HStack(
285
303
  { justifyContent: 'spaceBetween' },
286
304
  UI.Text('TỔNG QUAN ĐIỀU HÀNH (KPI & BIỂU ĐỒ)', { fontSize: 11, color: '#38BDF8', fontWeight: 'bold' }),
@@ -307,6 +325,54 @@ await Widget.setLayout('main', {
307
325
  await Widget.reloadAll();
308
326
  ```
309
327
 
328
+ ### 3. Build Widgets with React JSX / TSX Syntax
329
+
330
+ Prefer JSX over nested functions? Build layouts using clean, declarative JSX with full `style` prop & array flattening support:
331
+
332
+ ```tsx
333
+ import { Widget, VStack, HStack, Text, Badge, Progress, Button } from 'react-native-live-widgets';
334
+
335
+ await Widget.setLayout('main', {
336
+ medium: (
337
+ <VStack padding={16} backgroundColor="#0F172A" borderRadius={16}>
338
+ <HStack justifyContent="spaceBetween">
339
+ <Text fontSize={14} fontWeight="bold" color="#FFFFFF">Vào ca sáng</Text>
340
+ <Badge text="07:54 (Hợp lệ)" backgroundColor="#064E3B" textColor="#6EE7B7" />
341
+ </HStack>
342
+ <Progress value={0.75} style="segmented" segments={4} tintColor="#38BDF8" height={8} />
343
+ <Button title="Làm mới dữ liệu" actionId="refresh" fullWidth />
344
+ </VStack>
345
+ )
346
+ });
347
+ ```
348
+
349
+ ### 4. In-App Live Widget Preview (`<WidgetPreview>` / `<VoltraWidgetPreview>`)
350
+
351
+ Test and preview widgets directly inside your app screens with pixel-accurate OS container frames and real-time button clicks:
352
+
353
+ ```tsx
354
+ import { WidgetPreview, VStack, HStack, Text, Button } from 'react-native-live-widgets';
355
+
356
+ export function WidgetDemoScreen() {
357
+ return (
358
+ <WidgetPreview
359
+ size="medium" // 'small' | 'medium' | 'large' | 'lockScreen'
360
+ showBadge={true}
361
+ interactiveSizeSwitch={true} // Quick tabs to test small / medium / large
362
+ onAction={(actionId) => console.log('Tapped action:', actionId)}
363
+ >
364
+ <VStack padding={16} backgroundColor="#0F172A" borderRadius={20}>
365
+ <HStack justifyContent="spaceBetween">
366
+ <Text fontSize={14} fontWeight="bold" color="#FFFFFF">KPI Tuần</Text>
367
+ <Text fontSize={12} color="#38BDF8">86%</Text>
368
+ </HStack>
369
+ <Button title="Check-in ngay" actionId="checkin" fullWidth />
370
+ </VStack>
371
+ </WidgetPreview>
372
+ );
373
+ }
374
+ ```
375
+
310
376
  ---
311
377
 
312
378
  ## 📊 Platform Feature Parity Matrix
@@ -1,29 +1,17 @@
1
- buildscript {
2
- ext.kotlin_version = '1.9.22'
3
- repositories {
4
- google()
5
- mavenCentral()
6
- }
7
- dependencies {
8
- classpath "com.android.tools.build:gradle:8.2.1"
9
- classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
10
- }
1
+ def safeExtGet(prop, fallback) {
2
+ rootProject.ext.has(prop) ? rootProject.ext.get(prop) : fallback
11
3
  }
12
4
 
13
5
  apply plugin: 'com.android.library'
14
6
  apply plugin: 'kotlin-android'
15
7
 
16
- def safeExtGet(prop, fallback) {
17
- rootProject.ext.has(prop) ? rootProject.ext.get(prop) : fallback
18
- }
19
-
20
8
  android {
21
9
  namespace "com.reactnativeliveactivity"
22
- compileSdkVersion safeExtGet('compileSdkVersion', 34)
10
+ compileSdkVersion safeExtGet('compileSdkVersion', safeExtGet('compileSdk', 35))
23
11
 
24
12
  defaultConfig {
25
- minSdkVersion safeExtGet('minSdkVersion', 24)
26
- targetSdkVersion safeExtGet('targetSdkVersion', 34)
13
+ minSdkVersion safeExtGet('minSdkVersion', safeExtGet('minSdk', 24))
14
+ targetSdkVersion safeExtGet('targetSdkVersion', safeExtGet('targetSdk', 35))
27
15
  }
28
16
 
29
17
  compileOptions {
@@ -42,8 +30,14 @@ repositories {
42
30
  }
43
31
 
44
32
  dependencies {
45
- implementation 'com.facebook.react:react-android:+'
46
- implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
33
+ // Resolve react-android safely according to consumer project
34
+ if (findProject(':ReactAndroid') != null) {
35
+ implementation project(':ReactAndroid')
36
+ } else {
37
+ implementation 'com.facebook.react:react-android'
38
+ }
39
+
40
+ def kotlinVersion = safeExtGet('kotlinVersion', safeExtGet('kotlin_version', '2.1.20'))
41
+ implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion"
47
42
  implementation 'androidx.core:core-ktx:1.12.0'
48
43
  }
49
-
@@ -4,6 +4,7 @@
4
4
  <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
5
5
  <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
6
6
  <uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
7
+ <uses-permission android:name="android.permission.WAKE_LOCK" />
7
8
 
8
9
  <application>
9
10
  <!-- Receiver xử lý Live Update, Background API Sync & Interactive Widget Actions -->
@@ -289,7 +289,11 @@ class LiveActivityModule(private val reactContext: ReactApplicationContext) :
289
289
  val wKey = key.removePrefix("widget_remote_config_")
290
290
  runCatching {
291
291
  val cfg = JSONObject(value)
292
- val mins = cfg.optInt("refreshIntervalMinutes", 15).coerceAtLeast(1)
292
+ val mins = if (cfg.has("refreshIntervalMinutes")) {
293
+ cfg.optInt("refreshIntervalMinutes", 15)
294
+ } else {
295
+ cfg.optInt("intervalMinutes", 15)
296
+ }.coerceAtLeast(1)
293
297
  DynamicWidgetStateStore.scheduleBackgroundWidgetSync(reactContext, wKey, mins)
294
298
  }
295
299
  }
@@ -6,6 +6,14 @@ import com.facebook.react.bridge.Arguments
6
6
  import com.facebook.react.jstasks.HeadlessJsTaskConfig
7
7
 
8
8
  class LiveActivityHeadlessTaskService : HeadlessJsTaskService() {
9
+ override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
10
+ return try {
11
+ super.onStartCommand(intent, flags, startId)
12
+ } catch (_: Throwable) {
13
+ START_NOT_STICKY
14
+ }
15
+ }
16
+
9
17
  override fun getTaskConfig(intent: Intent?): HeadlessJsTaskConfig? {
10
18
  val actionId = intent?.getStringExtra("actionId") ?: return null
11
19
  val activityId = intent.getStringExtra("activityId") ?: ""
@@ -55,8 +55,11 @@ class LiveActivityReceiver : BroadcastReceiver() {
55
55
  putExtra("actionId", actionId)
56
56
  putExtra("activityId", activityId)
57
57
  }
58
+ try {
59
+ com.facebook.react.HeadlessJsTaskService.acquireWakeLockNow(context)
60
+ } catch (_: Throwable) {}
58
61
  context.startService(headlessIntent)
59
- } catch (_: Exception) {}
62
+ } catch (_: Throwable) {}
60
63
  } finally {
61
64
  pendingResult.finish()
62
65
  }
@@ -21,7 +21,10 @@ import kotlin.math.roundToInt
21
21
  data class ButtonActionBinding(
22
22
  val actionId: String,
23
23
  val deepLink: String?,
24
- val zone: String // "top", "mid", "bot"
24
+ val zone: String = "mid", // "top", "mid", "bot"
25
+ val xFraction: Float = 0.5f,
26
+ val yFraction: Float = 0.5f,
27
+ val widthFraction: Float = 1.0f
25
28
  )
26
29
 
27
30
  object DynamicWidgetCanvasRenderer {
@@ -576,7 +579,19 @@ object DynamicWidgetCanvasRenderer {
576
579
  top > totalHeight * 0.76f -> "bot"
577
580
  else -> "mid"
578
581
  }
579
- bindings.add(ButtonActionBinding(actionId = actionId, deepLink = deepLink, zone = zone))
582
+ val xF = ((left + btnW / 2f) / availWidth).coerceIn(0f, 1f)
583
+ val yF = ((top + btnH / 2f) / totalHeight).coerceIn(0f, 1f)
584
+ val wF = (btnW / availWidth).coerceIn(0.1f, 1f)
585
+ bindings.add(
586
+ ButtonActionBinding(
587
+ actionId = actionId,
588
+ deepLink = deepLink,
589
+ zone = zone,
590
+ xFraction = xF,
591
+ yFraction = yF,
592
+ widthFraction = if (fullWidth) 1.0f else wF
593
+ )
594
+ )
580
595
  }
581
596
  btnH + 1.5f * density
582
597
  }
@@ -912,7 +927,18 @@ object DynamicWidgetCanvasRenderer {
912
927
  top > totalHeight * 0.76f -> "bot"
913
928
  else -> "mid"
914
929
  }
915
- bindings.add(ButtonActionBinding(actionId = actionId, deepLink = deepLink, zone = zone))
930
+ val xF = ((left + availWidth / 2f) / availWidth).coerceIn(0f, 1f)
931
+ val yF = ((top + usedH / 2f) / totalHeight).coerceIn(0f, 1f)
932
+ bindings.add(
933
+ ButtonActionBinding(
934
+ actionId = actionId,
935
+ deepLink = deepLink,
936
+ zone = zone,
937
+ xFraction = xF,
938
+ yFraction = yF,
939
+ widthFraction = 1.0f
940
+ )
941
+ )
916
942
  }
917
943
  usedH
918
944
  }
@@ -161,6 +161,20 @@ object DynamicWidgetStateStore {
161
161
  val current = state.toggledItems[key] ?: false
162
162
  state.toggledItems[key] = !current
163
163
  }
164
+ actionId == "action_counter_inc" || actionId.startsWith("counter:inc") -> {
165
+ val current = (readSharedString(context, "widget_counter_value")?.toIntOrNull() ?: 10) + 1
166
+ writeSharedString(context, "widget_counter_value", current.toString())
167
+ state.remoteVariables["counter"] = current.toString()
168
+ }
169
+ actionId == "action_counter_dec" || actionId.startsWith("counter:dec") -> {
170
+ val current = (readSharedString(context, "widget_counter_value")?.toIntOrNull() ?: 10) - 1
171
+ writeSharedString(context, "widget_counter_value", current.toString())
172
+ state.remoteVariables["counter"] = current.toString()
173
+ }
174
+ actionId == "action_counter_reset" || actionId.startsWith("counter:reset") -> {
175
+ writeSharedString(context, "widget_counter_value", "0")
176
+ state.remoteVariables["counter"] = "0"
177
+ }
164
178
  }
165
179
 
166
180
  saveState(context, state)
@@ -177,6 +191,13 @@ object DynamicWidgetStateStore {
177
191
  ?: SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(Date())
178
192
  raw = raw.replace("{{_lastSyncTime}}", syncTime)
179
193
 
194
+ val counterVal = readSharedString(context, "widget_counter_value")
195
+ if (counterVal != null) {
196
+ raw = raw.replace(Regex("\"text\":\"-?\\d+\",\"props\":\\{\"fontSize\":(26|32)"), "\"text\":\"$counterVal\",\"props\":{\"fontSize\":$1")
197
+ raw = raw.replace(Regex("\"text\":\"-?\\d+ lượt\","), "\"text\":\"$counterVal lượt\",")
198
+ raw = raw.replace("{{counter}}", counterVal)
199
+ }
200
+
180
201
  for ((k, v) in state.remoteVariables) {
181
202
  val escaped = v.replace("\"", "\\\"")
182
203
  raw = raw.replace("{{$k}}", escaped)
@@ -241,7 +262,11 @@ object DynamicWidgetStateStore {
241
262
  }
242
263
  saveState(context, state)
243
264
 
244
- val intervalMins = config.optInt("refreshIntervalMinutes", 15).coerceAtLeast(1)
265
+ val intervalMins = if (config.has("refreshIntervalMinutes")) {
266
+ config.optInt("refreshIntervalMinutes", 15)
267
+ } else {
268
+ config.optInt("intervalMinutes", 15)
269
+ }.coerceAtLeast(1)
245
270
  scheduleBackgroundWidgetSync(context, widgetKey, intervalMins)
246
271
  } catch (_: Exception) {
247
272
  stampSyncTimeOnly(context)
@@ -13,6 +13,7 @@ import android.util.SizeF
13
13
  import android.widget.RemoteViews
14
14
  import org.json.JSONObject
15
15
  import kotlin.math.max
16
+ import kotlin.math.min
16
17
  import kotlin.math.roundToInt
17
18
 
18
19
  class DynamicHomeScreenWidgetProvider : AppWidgetProvider() {
@@ -163,25 +164,60 @@ class DynamicHomeScreenWidgetProvider : AppWidgetProvider() {
163
164
  appWidgetId: Int,
164
165
  bindings: List<ButtonActionBinding>
165
166
  ) {
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)
167
+ val gridIds = listOf(
168
+ listOf(R.id.rn_hit_r0_c0, R.id.rn_hit_r0_c1, R.id.rn_hit_r0_c2, R.id.rn_hit_r0_c3),
169
+ listOf(R.id.rn_hit_r1_c0, R.id.rn_hit_r1_c1, R.id.rn_hit_r1_c2),
170
+ listOf(R.id.rn_hit_r2_c0, R.id.rn_hit_r2_c1, R.id.rn_hit_r2_c2),
171
+ listOf(R.id.rn_hit_r3_c0, R.id.rn_hit_r3_c1, R.id.rn_hit_r3_c2),
172
+ listOf(R.id.rn_hit_r4_c0, R.id.rn_hit_r4_c1, R.id.rn_hit_r4_c2),
173
+ listOf(R.id.rn_hit_r5_c0, R.id.rn_hit_r5_c1, R.id.rn_hit_r5_c2)
174
+ )
175
+
176
+ val cellBindings = mutableMapOf<Int, ButtonActionBinding>()
169
177
 
170
- val topBindings = bindings.filter { it.zone == "top" }
171
- val midBindings = bindings.filter { it.zone == "mid" }
172
- val botBindings = bindings.filter { it.zone == "bot" }
178
+ val topButtons = bindings.filter { it.zone == "top" || it.yFraction < 0.20f }
179
+ val otherButtons = bindings.filter { it !in topButtons }
173
180
 
174
- for (i in topIds.indices) {
175
- val b = topBindings.getOrNull(i)
176
- views.setOnClickPendingIntent(topIds[i], createPendingIntent(context, appWidgetId * 100 + i, b))
181
+ val row0 = gridIds[0]
182
+ for (c in 0 until min(row0.size, topButtons.size)) {
183
+ cellBindings[row0[c]] = topButtons[c]
177
184
  }
178
- for (i in midIds.indices) {
179
- val b = midBindings.getOrNull(i)
180
- views.setOnClickPendingIntent(midIds[i], createPendingIntent(context, appWidgetId * 100 + 20 + i, b))
185
+
186
+ for (b in otherButtons) {
187
+ val row = when {
188
+ b.yFraction < 0.35f -> 1
189
+ b.yFraction < 0.52f -> 2
190
+ b.yFraction < 0.62f -> 3
191
+ b.yFraction < 0.75f -> 4
192
+ else -> 5
193
+ }
194
+
195
+ val rowCols = gridIds[row]
196
+ if (b.widthFraction > 0.50f) {
197
+ for (viewId in rowCols) {
198
+ cellBindings[viewId] = b
199
+ }
200
+ } else {
201
+ if (b.xFraction < 0.40f) {
202
+ cellBindings[rowCols[0]] = b
203
+ cellBindings[rowCols[1]] = b
204
+ } else {
205
+ cellBindings[rowCols[1]] = b
206
+ cellBindings[rowCols[2]] = b
207
+ }
208
+ }
181
209
  }
182
- for (i in botIds.indices) {
183
- val b = botBindings.getOrNull(i)
184
- views.setOnClickPendingIntent(botIds[i], createPendingIntent(context, appWidgetId * 100 + 40 + i, b))
210
+
211
+ var requestIdx = 0
212
+ for (r in gridIds.indices) {
213
+ for (c in gridIds[r].indices) {
214
+ val viewId = gridIds[r][c]
215
+ val b = cellBindings[viewId]
216
+ views.setOnClickPendingIntent(
217
+ viewId,
218
+ createPendingIntent(context, appWidgetId * 100 + requestIdx++, b)
219
+ )
220
+ }
185
221
  }
186
222
  }
187
223
 
@@ -12,101 +12,91 @@
12
12
  android:scaleType="fitCenter"
13
13
  android:contentDescription="Live Widget Content" />
14
14
 
15
- <!-- Lớp vùng bấm tương tác (Interactive Hit Zones) cho các UI.Button trên Widget -->
15
+ <!-- Lớp vùng bấm tương tác (Interactive Hit Zones: 6 Hàng x 3 Cột) cho mọi layout Widget -->
16
16
  <LinearLayout
17
+ android:id="@+id/rn_widget_grid_container"
17
18
  android:layout_width="match_parent"
18
19
  android:layout_height="match_parent"
19
20
  android:orientation="vertical"
20
- android:weightSum="100">
21
+ android:weightSum="6">
21
22
 
22
- <!-- Hàng trên cùng (dành cho thanh Tab Bar chuyển trang: page:shift, page:todo, page:okr, page:next) -->
23
+ <!-- Row 0 (0% - 16.7%) -->
23
24
  <LinearLayout
24
- android:id="@+id/rn_widget_row_top"
25
+ android:id="@+id/rn_grid_row_0"
25
26
  android:layout_width="match_parent"
26
27
  android:layout_height="0dp"
27
- android:layout_weight="22"
28
- android:orientation="horizontal">
29
-
30
- <TextView
31
- android:id="@+id/rn_hit_top_1"
32
- android:layout_width="0dp"
33
- android:layout_height="match_parent"
34
- android:layout_weight="1"
35
- android:background="@android:color/transparent" />
36
-
37
- <TextView
38
- android:id="@+id/rn_hit_top_2"
39
- android:layout_width="0dp"
40
- android:layout_height="match_parent"
41
- android:layout_weight="1"
42
- android:background="@android:color/transparent" />
43
-
44
- <TextView
45
- android:id="@+id/rn_hit_top_3"
46
- android:layout_width="0dp"
47
- android:layout_height="match_parent"
48
- android:layout_weight="1"
49
- android:background="@android:color/transparent" />
50
-
51
- <TextView
52
- android:id="@+id/rn_hit_top_4"
53
- android:layout_width="0dp"
54
- android:layout_height="match_parent"
55
- android:layout_weight="1"
56
- android:background="@android:color/transparent" />
28
+ android:layout_weight="1"
29
+ android:orientation="horizontal"
30
+ android:weightSum="4">
31
+ <TextView android:id="@+id/rn_hit_r0_c0" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:background="@android:color/transparent" />
32
+ <TextView android:id="@+id/rn_hit_r0_c1" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:background="@android:color/transparent" />
33
+ <TextView android:id="@+id/rn_hit_r0_c2" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:background="@android:color/transparent" />
34
+ <TextView android:id="@+id/rn_hit_r0_c3" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:background="@android:color/transparent" />
57
35
  </LinearLayout>
58
36
 
59
- <!-- Vùng giữa (dành cho danh sách các nút bấm / Todo items: toggle:todo_1, toggle:todo_2, toggle:todo_3) -->
37
+ <!-- Row 1 (16.7% - 33.3%) -->
60
38
  <LinearLayout
61
- android:id="@+id/rn_widget_row_mid"
39
+ android:id="@+id/rn_grid_row_1"
62
40
  android:layout_width="match_parent"
63
41
  android:layout_height="0dp"
64
- android:layout_weight="58"
65
- android:orientation="vertical">
66
-
67
- <TextView
68
- android:id="@+id/rn_hit_mid_1"
69
- android:layout_width="match_parent"
70
- android:layout_height="0dp"
71
- android:layout_weight="1"
72
- android:background="@android:color/transparent" />
73
-
74
- <TextView
75
- android:id="@+id/rn_hit_mid_2"
76
- android:layout_width="match_parent"
77
- android:layout_height="0dp"
78
- android:layout_weight="1"
79
- android:background="@android:color/transparent" />
42
+ android:layout_weight="1"
43
+ android:orientation="horizontal"
44
+ android:weightSum="3">
45
+ <TextView android:id="@+id/rn_hit_r1_c0" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:background="@android:color/transparent" />
46
+ <TextView android:id="@+id/rn_hit_r1_c1" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:background="@android:color/transparent" />
47
+ <TextView android:id="@+id/rn_hit_r1_c2" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:background="@android:color/transparent" />
48
+ </LinearLayout>
80
49
 
81
- <TextView
82
- android:id="@+id/rn_hit_mid_3"
83
- android:layout_width="match_parent"
84
- android:layout_height="0dp"
85
- android:layout_weight="1"
86
- android:background="@android:color/transparent" />
50
+ <!-- Row 2 (33.3% - 50.0%) -->
51
+ <LinearLayout
52
+ android:id="@+id/rn_grid_row_2"
53
+ android:layout_width="match_parent"
54
+ android:layout_height="0dp"
55
+ android:layout_weight="1"
56
+ android:orientation="horizontal"
57
+ android:weightSum="3">
58
+ <TextView android:id="@+id/rn_hit_r2_c0" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:background="@android:color/transparent" />
59
+ <TextView android:id="@+id/rn_hit_r2_c1" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:background="@android:color/transparent" />
60
+ <TextView android:id="@+id/rn_hit_r2_c2" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:background="@android:color/transparent" />
87
61
  </LinearLayout>
88
62
 
89
- <!-- Hàng dưới cùng (dành cho nút Refresh API ngầm / Điều hướng: refresh, page:prev, page:next) -->
63
+ <!-- Row 3 (50.0% - 66.7%) -->
90
64
  <LinearLayout
91
- android:id="@+id/rn_widget_row_bottom"
65
+ android:id="@+id/rn_grid_row_3"
92
66
  android:layout_width="match_parent"
93
67
  android:layout_height="0dp"
94
- android:layout_weight="20"
95
- android:orientation="horizontal">
68
+ android:layout_weight="1"
69
+ android:orientation="horizontal"
70
+ android:weightSum="3">
71
+ <TextView android:id="@+id/rn_hit_r3_c0" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:background="@android:color/transparent" />
72
+ <TextView android:id="@+id/rn_hit_r3_c1" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:background="@android:color/transparent" />
73
+ <TextView android:id="@+id/rn_hit_r3_c2" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:background="@android:color/transparent" />
74
+ </LinearLayout>
96
75
 
97
- <TextView
98
- android:id="@+id/rn_hit_bot_1"
99
- android:layout_width="0dp"
100
- android:layout_height="match_parent"
101
- android:layout_weight="1"
102
- android:background="@android:color/transparent" />
76
+ <!-- Row 4 (66.7% - 83.3%) -->
77
+ <LinearLayout
78
+ android:id="@+id/rn_grid_row_4"
79
+ android:layout_width="match_parent"
80
+ android:layout_height="0dp"
81
+ android:layout_weight="1"
82
+ android:orientation="horizontal"
83
+ android:weightSum="3">
84
+ <TextView android:id="@+id/rn_hit_r4_c0" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:background="@android:color/transparent" />
85
+ <TextView android:id="@+id/rn_hit_r4_c1" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:background="@android:color/transparent" />
86
+ <TextView android:id="@+id/rn_hit_r4_c2" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:background="@android:color/transparent" />
87
+ </LinearLayout>
103
88
 
104
- <TextView
105
- android:id="@+id/rn_hit_bot_2"
106
- android:layout_width="0dp"
107
- android:layout_height="match_parent"
108
- android:layout_weight="1"
109
- android:background="@android:color/transparent" />
89
+ <!-- Row 5 (83.3% - 100.0%) -->
90
+ <LinearLayout
91
+ android:id="@+id/rn_grid_row_5"
92
+ android:layout_width="match_parent"
93
+ android:layout_height="0dp"
94
+ android:layout_weight="1"
95
+ android:orientation="horizontal"
96
+ android:weightSum="3">
97
+ <TextView android:id="@+id/rn_hit_r5_c0" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:background="@android:color/transparent" />
98
+ <TextView android:id="@+id/rn_hit_r5_c1" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:background="@android:color/transparent" />
99
+ <TextView android:id="@+id/rn_hit_r5_c2" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:background="@android:color/transparent" />
110
100
  </LinearLayout>
111
101
  </LinearLayout>
112
102
  </FrameLayout>