react-native-live-widgets 1.0.0 → 1.1.1

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 (37) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/README.md +197 -49
  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 +2 -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 +21 -0
  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/app.plugin.js +114 -0
  13. package/assets/cross_platform_parity.png +0 -0
  14. package/assets/donate_qr.png +0 -0
  15. package/assets/dynamic_island_expanded.png +0 -0
  16. package/assets/home_widget_interactive.png +0 -0
  17. package/assets/lock_screen_live_activity.png +0 -0
  18. package/cli/setup.js +445 -48
  19. package/docs/EXPO-GUIDE-EN.md +405 -0
  20. package/docs/EXPO-GUIDE-VI.md +427 -0
  21. package/docs/GUIDE-EN.md +75 -14
  22. package/docs/GUIDE-VI.md +75 -14
  23. package/docs/index.html +405 -0
  24. package/docs/llms-full.txt +118 -0
  25. package/docs/llms.txt +66 -0
  26. package/lib/builder.js +9 -13
  27. package/lib/builder.js.map +1 -1
  28. package/lib/dispatcher.js +6 -11
  29. package/lib/dispatcher.js.map +1 -1
  30. package/lib/index.d.ts.map +1 -1
  31. package/lib/index.js +40 -53
  32. package/lib/index.js.map +1 -1
  33. package/lib/types.js +1 -2
  34. package/lib/types.js.map +1 -1
  35. package/package.json +22 -4
  36. package/src/index.ts +12 -4
  37. package/src/react-native-env.d.ts +29 -0
@@ -0,0 +1,427 @@
1
+ # HƯỚNG DẪN TÍCH HỢP VÀ SỬ DỤNG EXPO VỚI REACT-NATIVE-LIVE-WIDGETS 🚀
2
+
3
+ > 🌐 **Language:** **Tiếng Việt** | [English Guide (EXPO-GUIDE-EN.md)](./EXPO-GUIDE-EN.md) • [📖 Bare RN Guide (GUIDE-VI.md)](./GUIDE-VI.md) • [⚡ Kho mã nguồn mẫu Expo](https://github.com/React-Native-Vu/LiveWidgetsExampleExpo)
4
+
5
+ Tài liệu này hướng dẫn chi tiết cách tích hợp **`react-native-live-widgets`** vào ứng dụng **Expo (SDK 50, 51, 52, 58+)**, từ cấu hình Expo Config Plugin, thiết lập iOS WidgetKit/ActivityKit tự động, chạy trên Local Simulator bằng Expo Dev Client cho đến việc đóng gói phát hành qua **EAS Build**.
6
+
7
+ ---
8
+
9
+ ## MỤC LỤC
10
+ 1. [Hiểu về Kiến trúc Expo & Native Widgets](#1-hiểu-về-kiến-trúc-expo--native-widgets)
11
+ 2. [Kho Mã Nguồn Demo Chính Thức (LiveWidgetsExampleExpo)](#2-kho-mã-nguồn-demo-chính-thức-livewidgetsexampleexpo)
12
+ 3. [Cài đặt & Thiết lập Từng bước](#3-cài-đặt--thiết-lập-từng-bước)
13
+ - [Bước 1: Cài đặt package](#bước-1-cài-đặt-package)
14
+ - [Bước 2: Cấu hình app.json (Expo Config Plugin)](#bước-2-cấu-hình-appjson-expo-config-plugin)
15
+ - [Bước 3: Chạy Expo Prebuild](#bước-3-chạy-expo-prebuild)
16
+ - [Bước 4: Chạy CLI Wizard cấu hình Widget Extension](#bước-4-chạy-cli-wizard-cấu-hình-widget-extension)
17
+ 4. [Chạy và Kiểm thử trên Thiết bị & Giả lập](#4-chạy-và-kiểm-thử-trên-thiết-bị--giả-lập)
18
+ - [Chạy trên iOS Simulator](#chạy-trên-ios-simulator)
19
+ - [Chạy trên Android Emulator](#chạy-trên-android-emulator)
20
+ - [Cách ghim Widget và bật Live Activity trên Simulator](#cách-ghim-widget-và-bật-live-activity-trên-simulator)
21
+ 5. [Cấu hình EAS Build (Expo Application Services)](#5-cấu-hình-eas-build-expo-application-services)
22
+ - [Đăng ký App Group & Extension trên Apple Developer](#đăng-ký-app-group--extension-trên-apple-developer)
23
+ - [Cấu hình eas.json](#cấu-hình-easjson)
24
+ - [Cung cấp Provisioning Profile cho Extension](#cung-cấp-provisioning-profile-cho-extension)
25
+ 6. [Ví dụ Viết Widget & Live Activity bằng TypeScript trong Expo](#6-ví-dụ-viết-widget--live-activity-bằng-typescript-trong-expo)
26
+ 7. [Xử lý Sự cố Thường gặp trên Expo (Troubleshooting)](#7-xử-lý-sự-cố-thường-gặp-trên-expo-troubleshooting)
27
+
28
+ ---
29
+
30
+ ## 1. Hiểu về Kiến trúc Expo & Native Widgets
31
+
32
+ ### ⚠️ Tại sao không dùng được Expo Go?
33
+ - **Expo Go** là một ứng dụng native đóng gói sẵn các module cơ bản của Expo.
34
+ - **WidgetKit** (Home Screen Widgets) và **ActivityKit** (Live Activities & Dynamic Island) của iOS đòi hỏi phải có một tiến trình native độc lập gọi là **App Extension Target (`.appex`)**.
35
+ - Tương tự, Android yêu cầu cấu hình `AppWidgetProvider` và Service tùy chỉnh trong `AndroidManifest.xml`.
36
+ - Do đó, **Expo Go không hỗ trợ Widget native**. Bạn cần sử dụng **Expo Prebuild** hoặc **Expo Dev Client (`npx expo run:ios` / `npx expo run:android`)** hoặc **EAS Build**.
37
+
38
+ ### 🌟 Giải pháp: Expo Config Plugin & Continuous Native Generation (CNG)
39
+ `react-native-live-widgets` cung cấp sẵn **Expo Config Plugin (`app.plugin.js`)** và **CLI Wizard**:
40
+ - Tự động chèn quyền `NSSupportsLiveActivities` và `NSSupportsLiveActivitiesFrequentUpdates` vào `Info.plist`.
41
+ - Tự động cấu hình `com.apple.security.application-groups` vào file Entitlements của iOS.
42
+ - Tự động bổ sung các quyền thông báo thời gian thực (`POST_NOTIFICATIONS`) trên Android.
43
+ - Tự động sinh và cấu hình target Xcode `LiveWidgetsExtension` chứa các template Swift và renderers mà **không cần mở Xcode thủ công**.
44
+
45
+ ---
46
+
47
+ ## 2. Kho Mã Nguồn Demo Chính Thức (LiveWidgetsExampleExpo)
48
+
49
+ Nếu bạn muốn trải nghiệm ngay một dự án mẫu Expo chuẩn mực đã được cấu hình sẵn 100%, hãy sử dụng kho mã nguồn:
50
+
51
+ 👉 **GitHub Repository:** **[https://github.com/React-Native-Vu/LiveWidgetsExampleExpo](https://github.com/React-Native-Vu/LiveWidgetsExampleExpo)**
52
+
53
+ ### ✨ Các Tính Năng Đã Tích Hợp Sẵn trong Repo Demo:
54
+ - 🚀 **Expo SDK 58 + React Native 0.88 + TypeScript 100%**.
55
+ - 🛠️ **Cấu hình sẵn Config Plugin & App Groups**: `group.com.reactnativevu.livewidgetsexampleexpo`.
56
+ - 🎨 **5 Mẫu Giao Diện Presets thực tế**:
57
+ 1. **📊 Executive KPI Dashboard**: Vòng tròn tiến độ doanh thu, biểu đồ tuần và đồng bộ dữ liệu thời gian thực.
58
+ 2. **☕ Coffee Delivery Tracker**: Đồng hồ đếm ngược giao hàng trên Dynamic Island và thẻ trạng thái Lock Screen.
59
+ 3. **✅ Interactive Task Checklist**: Tương tác tick chọn hoàn thành công việc trực tiếp ngay trên mặt Widget mà không cần mở app.
60
+ 4. **🎵 Music & Audio Player**: Sóng nhạc chuyển động liên tục (Equalizer Waveform) trên Dynamic Island.
61
+ 5. **✈️ Flight Status**: Tiến trình chuyến bay, cổng khởi hành và đếm ngược giờ cất cánh.
62
+ - 🔄 **Action Dispatcher 2 chiều**: Nhấn nút `[+]` hoặc `[-]` trên Home Widget để kích hoạt trực tiếp hàm TypeScript trong Expo App và render lại giao diện tức thì.
63
+
64
+ ### ⚡ Cách Clone và Chạy Thử Ngay Lập Tức:
65
+ ```bash
66
+ # 1. Clone repository
67
+ git clone https://github.com/React-Native-Vu/LiveWidgetsExampleExpo.git
68
+ cd LiveWidgetsExampleExpo
69
+
70
+ # 2. Cài đặt dependencies
71
+ npm install
72
+
73
+ # 3. Tạo thư mục native bằng Expo Prebuild
74
+ npx expo prebuild
75
+
76
+ # 4. Chạy script thiết lập Widget Extension tự động
77
+ npm run setup:widgets
78
+
79
+ # 5. Khởi chạy trên iOS Simulator hoặc Android Emulator
80
+ npx expo run:ios
81
+ # hoặc
82
+ npx expo run:android
83
+ ```
84
+
85
+ ---
86
+
87
+ ## 3. Cài đặt & Thiết lập Từng bước
88
+
89
+ ### Bước 1: Cài đặt package
90
+ Tại thư mục gốc của dự án Expo:
91
+ ```bash
92
+ npx expo install react-native-live-widgets
93
+ ```
94
+
95
+ ---
96
+
97
+ ### Bước 2: Cấu hình `app.json` (Expo Config Plugin)
98
+ Mở file `app.json` và bổ sung plugin `react-native-live-widgets`:
99
+
100
+ ```json
101
+ {
102
+ "expo": {
103
+ "name": "MyExpoApp",
104
+ "slug": "my-expo-app",
105
+ "version": "1.0.0",
106
+ "ios": {
107
+ "bundleIdentifier": "com.yourcompany.myexpoapp",
108
+ "supportsTablet": true
109
+ },
110
+ "android": {
111
+ "package": "com.yourcompany.myexpoapp"
112
+ },
113
+ "plugins": [
114
+ [
115
+ "react-native-live-widgets",
116
+ {
117
+ "appGroup": "group.com.yourcompany.myexpoapp",
118
+ "enableLiveActivities": true,
119
+ "frequentUpdates": true
120
+ }
121
+ ]
122
+ ]
123
+ }
124
+ }
125
+ ```
126
+
127
+ #### Bảng tham số cấu hình Plugin:
128
+ | Thuộc tính | Kiểu dữ liệu | Bắt buộc | Mặc định | Mô tả |
129
+ | :--- | :--- | :---: | :---: | :--- |
130
+ | `appGroup` | `string` | **Có** | `group.<bundleId>` | Tên App Group dùng để chia sẻ dữ liệu giữa App chính và WidgetKit |
131
+ | `enableLiveActivities` | `boolean` | Không | `true` | Cho phép khởi chạy Live Activity trên màn hình khoá và Dynamic Island |
132
+ | `frequentUpdates` | `boolean` | Không | `true` | Bật tần suất cập nhật cao cho Live Activity (iOS 16.2+) |
133
+
134
+ ---
135
+
136
+ ### Bước 3: Chạy Expo Prebuild
137
+ Sinh mã nguồn native cho iOS và Android:
138
+ ```bash
139
+ npx expo prebuild
140
+ ```
141
+ > [!NOTE]
142
+ > Lệnh này sẽ tạo thư mục `ios/` và `android/` với đầy đủ các cấu hình từ `app.json`.
143
+
144
+ ---
145
+
146
+ ### Bước 4: Chạy CLI Wizard cấu hình Widget Extension
147
+ Chạy công cụ tự động của thư viện để cấu hình target Extension trong Xcode:
148
+ ```bash
149
+ npx react-native-live-widgets init --group group.com.yourcompany.myexpoapp
150
+ ```
151
+
152
+ **CLI Wizard sẽ tự động thực hiện:**
153
+ 1. Cấu hình App Group vào `<AppName>.entitlements`.
154
+ 2. Tạo thư mục `ios/LiveWidgetsExtension/` chứa:
155
+ - `LiveWidgetsBundle.swift` (tích hợp sẵn 5 mẫu giao diện tiện ích).
156
+ - `Info.plist` (cho Extension).
157
+ - `LiveWidgetsExtension.entitlements` (cho Extension).
158
+ - Copy các Swift models và UI Renderers vào thư mục `Shared/`.
159
+ 3. Nhúng target `LiveWidgetsExtension` vào file `project.pbxproj` của Xcode một cách chuẩn xác:
160
+ - Thiết lập `PBXSourcesBuildPhase` riêng biệt (tránh hoàn toàn xung đột `@main` với `AppDelegate.swift`).
161
+ - Liên kết các framework cần thiết (`WidgetKit.framework`, `SwiftUI.framework`).
162
+ - Đặt target deployment là iOS 16.4+.
163
+ - Nhúng extension vào ứng dụng chính (`Embed App Extensions`).
164
+ 4. Thêm pod vào `Podfile` và tự động thực thi `pod install`.
165
+ 5. Đảm bảo quyền thông báo trên Android (`POST_NOTIFICATIONS`).
166
+
167
+ > [!TIP]
168
+ > Bạn có thể thêm script tiện lợi vào `package.json` của dự án để tái sử dụng bất cứ lúc nào:
169
+ > ```json
170
+ > "scripts": {
171
+ > "setup:widgets": "npx react-native-live-widgets init --group group.com.yourcompany.myexpoapp"
172
+ > }
173
+ > ```
174
+
175
+ ---
176
+
177
+ ## 3. Chạy và Kiểm thử trên Thiết bị & Giả lập
178
+
179
+ ### Chạy trên iOS Simulator
180
+ ```bash
181
+ npx expo run:ios
182
+ ```
183
+ > [!IMPORTANT]
184
+ > - Đối với Dynamic Island: Hãy chọn Simulator có Dynamic Island như **iPhone 14 Pro, iPhone 15, iPhone 16 hoặc iPhone 17**.
185
+ > - Đối với Live Activities: Yêu cầu iOS 16.1 trở lên.
186
+
187
+ ### Chạy trên Android Emulator
188
+ ```bash
189
+ npx expo run:android
190
+ ```
191
+
192
+ ---
193
+
194
+ ### Cách ghim Widget và bật Live Activity trên Simulator
195
+
196
+ #### 1. Thêm Home Screen Widget trên iOS Simulator:
197
+ 1. Sau khi app khởi động thành công, nhấn phím `Cmd + Shift + H` để quay ra màn hình chính Simulator.
198
+ 2. Nhấn và giữ một vùng trống trên màn hình cho đến khi các icon lắc lư.
199
+ 3. Bấm vào nút dấu **[+]** ở góc trên bên trái màn hình.
200
+ 4. Tìm kiếm tên ứng dụng của bạn (ví dụ: `LiveWidgetsExampleExpo`).
201
+ 5. Chọn kiểu tiện ích mong muốn (`Tiện ích Live Widgets`, `Bộ đếm tương tác (TS)`, `Bảo mật & KPI Pro`, `Chấm công & Ca làm việc`, hoặc `Không gian đa trang`) rồi bấm **Thêm tiện ích (Add Widget)**.
202
+
203
+ #### 2. Kích hoạt Live Activity & Dynamic Island:
204
+ - Mở ứng dụng, bấm nút **"Bật Live Activity"**.
205
+ - Kéo từ trên màn hình xuống hoặc khoá máy (`Cmd + L`) để chiêm ngưỡng giao diện Live Activity trên Lock Screen và Dynamic Island!
206
+
207
+ ---
208
+
209
+ ## 4. Cấu hình EAS Build (Expo Application Services)
210
+
211
+ Khi đưa ứng dụng lên TestFlight, App Store hoặc phân phối nội bộ qua EAS Build, bạn cần lưu ý cấu hình signing cho cả App chính và App Extension.
212
+
213
+ ### Đăng ký App Group & Extension trên Apple Developer
214
+ 1. Đăng nhập vào [Apple Developer Portal (Certificates, Identifiers & Profiles)](https://developer.apple.com/account/resources/identifiers/list).
215
+ 2. **App Groups**:
216
+ - Chọn mục **App Groups** -> Bấm **[+]** để tạo mới (ví dụ: `group.com.yourcompany.myexpoapp`).
217
+ 3. **App Identifiers**:
218
+ - Vào **Identifiers** -> Chọn App ID chính của bạn (ví dụ: `com.yourcompany.myexpoapp`) -> Tích chọn **App Groups** -> Chọn App Group vừa tạo -> Bật **Live Activities**.
219
+ - Bấm **[+]** để tạo thêm một Identifier mới cho Extension:
220
+ - **Description:** `LiveWidgetsExtension`
221
+ - **Bundle ID:** `Explicit` -> Đặt là `com.yourcompany.myexpoapp.LiveWidgetsExtension`.
222
+ - Tích chọn **App Groups** và liên kết với App Group ở trên.
223
+
224
+ ---
225
+
226
+ ### Cấu hình `eas.json`
227
+ Một file `eas.json` chuẩn dành cho dự án có Widget Extension:
228
+
229
+ ```json
230
+ {
231
+ "cli": {
232
+ "version": ">= 10.0.0"
233
+ },
234
+ "build": {
235
+ "development": {
236
+ "developmentClient": true,
237
+ "distribution": "internal",
238
+ "ios": {
239
+ "simulator": true
240
+ }
241
+ },
242
+ "preview": {
243
+ "distribution": "internal",
244
+ "ios": {
245
+ "simulator": false
246
+ }
247
+ },
248
+ "production": {
249
+ "autoIncrement": true
250
+ }
251
+ },
252
+ "submit": {
253
+ "production": {}
254
+ }
255
+ }
256
+ ```
257
+
258
+ ---
259
+
260
+ ### Cung cấp Provisioning Profile cho Extension
261
+ Khi chạy lệnh build trên EAS:
262
+ ```bash
263
+ eas build --platform ios --profile production
264
+ ```
265
+ EAS CLI sẽ tự động phát hiện target phụ `LiveWidgetsExtension` trong Xcode project và hỏi bạn có muốn EAS tự động sinh chứng chỉ / Provisioning Profile cho target đó hay không:
266
+ - Hãy chọn **Yes** để EAS tự động tạo và quản lý hồ sơ ký số cho cả Main App và Widget Extension.
267
+
268
+ ---
269
+
270
+ ## 5. Ví dụ Viết Widget & Live Activity bằng TypeScript trong Expo
271
+
272
+ Toàn bộ code giao diện và logic đều được viết bằng TypeScript trong dự án Expo (`App.tsx`):
273
+
274
+ ```tsx
275
+ import React, { useEffect, useState } from 'react';
276
+ import { View, Text, TouchableOpacity, StyleSheet } from 'react-native';
277
+ import {
278
+ LiveActivity,
279
+ Widget,
280
+ UI,
281
+ SharedStorage,
282
+ } from 'react-native-live-widgets';
283
+
284
+ const APP_GROUP = 'group.com.yourcompany.myexpoapp';
285
+
286
+ export default function App() {
287
+ const [counter, setCounter] = useState(0);
288
+
289
+ useEffect(() => {
290
+ // Khởi tạo App Group
291
+ SharedStorage.setAppGroup(APP_GROUP);
292
+
293
+ // Đăng ký nhận sự kiện bấm nút hai chiều từ Widget
294
+ const unsubscribe = LiveActivity.registerActionHandler((action, payload) => {
295
+ console.log('User tương tác từ Widget:', action, payload);
296
+ if (action === 'INCREMENT') {
297
+ setCounter((prev) => {
298
+ const next = prev + 1;
299
+ updateHomeScreenWidget(next);
300
+ return next;
301
+ });
302
+ }
303
+ });
304
+
305
+ return () => unsubscribe();
306
+ }, []);
307
+
308
+ const updateHomeScreenWidget = (val: number) => {
309
+ Widget.reload('main', {
310
+ layout: UI.VStack({
311
+ alignment: 'center',
312
+ padding: 16,
313
+ background: '#0F172A',
314
+ children: [
315
+ UI.Text('BỘ ĐẾM EXPO', { color: '#94A3B8', fontSize: 12, fontWeight: 'bold' }),
316
+ UI.Text(`${val}`, { color: '#38BDF8', fontSize: 40, fontWeight: 'heavy' }),
317
+ UI.HStack({
318
+ spacing: 12,
319
+ children: [
320
+ UI.Button('+1 TĂNG', {
321
+ action: 'INCREMENT',
322
+ backgroundColor: '#0284C7',
323
+ textColor: '#FFFFFF',
324
+ }),
325
+ ],
326
+ }),
327
+ ],
328
+ }),
329
+ });
330
+ };
331
+
332
+ const startLiveActivity = async () => {
333
+ await LiveActivity.start({
334
+ activityName: 'ExpoLiveTask',
335
+ appGroup: APP_GROUP,
336
+ layout: UI.VStack({
337
+ padding: 16,
338
+ background: '#020617',
339
+ children: [
340
+ UI.Text('🚀 Live Activity từ Expo SDK!', { color: '#F8FAFC', fontSize: 16, fontWeight: 'bold' }),
341
+ UI.Text('Đồng bộ thời gian thực không cần đụng mã Swift.', { color: '#94A3B8', fontSize: 13 }),
342
+ UI.Progress(0.75, { style: 'bar', tintColor: '#38BDF8', height: 6 }),
343
+ ],
344
+ }),
345
+ dynamicIsland: {
346
+ compactLeading: UI.Text('🚀', { fontSize: 14 }),
347
+ compactTrailing: UI.Text('75%', { color: '#38BDF8', fontSize: 12, fontWeight: 'bold' }),
348
+ expanded: {
349
+ leading: UI.Text('EXPO LIVE', { color: '#94A3B8', fontSize: 11 }),
350
+ trailing: UI.Text('75%', { color: '#38BDF8', fontSize: 18, fontWeight: 'bold' }),
351
+ center: UI.Progress(0.75, { style: 'bar', tintColor: '#38BDF8', height: 6 }),
352
+ },
353
+ },
354
+ });
355
+ };
356
+
357
+ return (
358
+ <View style={styles.container}>
359
+ <Text style={styles.title}>Expo Live Widgets Demo</Text>
360
+ <Text style={styles.counter}>Giá trị: {counter}</Text>
361
+
362
+ <TouchableOpacity style={styles.btn} onPress={() => updateHomeScreenWidget(counter + 1)}>
363
+ <Text style={styles.btnText}>Cập nhật Home Widget</Text>
364
+ </TouchableOpacity>
365
+
366
+ <TouchableOpacity style={[styles.btn, styles.btnLive]} onPress={startLiveActivity}>
367
+ <Text style={styles.btnText}>Bật Live Activity</Text>
368
+ </TouchableOpacity>
369
+ </View>
370
+ );
371
+ }
372
+
373
+ const styles = StyleSheet.create({
374
+ container: { flex: 1, backgroundColor: '#090D16', justifyContent: 'center', alignItems: 'center', padding: 20 },
375
+ title: { fontSize: 24, fontWeight: 'bold', color: '#FFFFFF', marginBottom: 12 },
376
+ counter: { fontSize: 18, color: '#38BDF8', marginBottom: 24 },
377
+ btn: { backgroundColor: '#2563EB', paddingHorizontal: 24, paddingVertical: 14, borderRadius: 12, marginVertical: 8, width: '100%', alignItems: 'center' },
378
+ btnLive: { backgroundColor: '#059669' },
379
+ btnText: { color: '#FFFFFF', fontWeight: 'bold', fontSize: 16 },
380
+ });
381
+ ```
382
+
383
+ ---
384
+
385
+ ## 6. Xử lý Sự cố Thường gặp trên Expo (Troubleshooting)
386
+
387
+ ### 1. `[react-native-live-widgets] Native module not found`
388
+ - **Nguyên nhân:** Đang chạy ứng dụng bằng **Expo Go**.
389
+ - **Giải pháp:** Live Activities và Widgets bắt buộc phải dùng native code. Hãy chạy `npx expo prebuild` và khởi động bằng `npx expo run:ios` hoặc `npx expo run:android`.
390
+
391
+ ### 2. `client is not entitled` hoặc `container_create_or_lookup_app_group_path_by_app_group_identifier`
392
+ - **Nguyên nhân:** Thiếu cấu hình App Group trong file Entitlements hoặc sai tên App Group.
393
+ - **Giải pháp:**
394
+ 1. Kiểm tra tên App Group trong `app.json` phải trùng khớp với lệnh `npx react-native-live-widgets init --group group.your.app`.
395
+ 2. Đảm bảo file `ios/<AppName>/<AppName>.entitlements` và `ios/LiveWidgetsExtension/LiveWidgetsExtension.entitlements` đều có chứa `com.apple.security.application-groups`.
396
+
397
+ ### 3. `'main' attribute can only apply to one type in a module`
398
+ - **Nguyên nhân:** File `LiveWidgetsBundle.swift` vô tình bị thêm vào build phase của target chính (`LiveWidgetsExampleExpo`), dẫn đến xung đột `@main` giữa `AppDelegate.swift` và `LiveWidgetsBundle.swift`.
399
+ - **Giải pháp:** Bản cập nhật CLI `react-native-live-widgets init` mới nhất đã tự động cô lập build phase `PBXSourcesBuildPhase` của target `LiveWidgetsExtension`. Chỉ cần chạy lại `npx react-native-live-widgets init` để tự động sửa.
400
+
401
+ ### 4. Metro Bundler: `Unable to resolve module react-native/asset-registry`
402
+ - **Nguyên nhân:** Trong môi trường liên kết package cục bộ (`file:../react-native-live-widgets`) hoặc monorepo, Metro có thể quét nhầm `node_modules` lồng nhau.
403
+ - **Giải pháp:** Tạo file `metro.config.js` tại thư mục gốc của dự án Expo với nội dung sau:
404
+ ```javascript
405
+ const { getDefaultConfig } = require('expo/metro-config');
406
+ const path = require('path');
407
+
408
+ const config = getDefaultConfig(__dirname);
409
+ config.resolver.nodeModulesPaths = [
410
+ path.resolve(__dirname, 'node_modules'),
411
+ ];
412
+ config.resolver.disableHierarchicalLookup = true;
413
+
414
+ module.exports = config;
415
+ ```
416
+
417
+ ### 5. Cảnh báo `@ExpoModule class 'CoreModule' is internal` khi build Xcode
418
+ - **Hiện tượng:** Xuất hiện cảnh báo từ `expo-modules-core` trong log build.
419
+ - **Ảnh hưởng:** Đây chỉ là cảnh báo nội bộ của hệ thống module Expo, hoàn toàn không gây crash ứng dụng và bản build vẫn ra kết quả `** BUILD SUCCEEDED **`.
420
+
421
+ ---
422
+
423
+ ## 7. Tài nguyên & Liên kết
424
+ - ⚡ **Dự án mẫu Expo hoàn chỉnh:** [LiveWidgetsExampleExpo trên GitHub](https://github.com/React-Native-Vu/LiveWidgetsExampleExpo)
425
+ - ⚛️ **Dự án mẫu Bare React Native:** [LiveWidgetsExample trên GitHub](https://github.com/React-Native-Vu/LiveWidgetsExample)
426
+ - 📖 **Tài liệu hướng dẫn Tiếng Việt đầy đủ:** [GUIDE-VI.md](./GUIDE-VI.md)
427
+ - 🌐 **Tài liệu tiếng Anh:** [GUIDE-EN.md](./GUIDE-EN.md)
package/docs/GUIDE-EN.md CHANGED
@@ -1,23 +1,28 @@
1
1
  # REACT-NATIVE-LIVE-WIDGETS — COMPLETE SETUP & DEVELOPER GUIDE 🚀
2
2
 
3
- > 🌐 **Language:** [Tiếng Việt (GUIDE-VI.md)](./GUIDE-VI.md) | **English**
3
+ > 🌐 **Language:** [Tiếng Việt (GUIDE-VI.md)](./GUIDE-VI.md) | **English** • [⚡ Dedicated Expo Guide (EXPO-GUIDE-EN.md)](./EXPO-GUIDE-EN.md)
4
4
 
5
5
  Comprehensive guide covering installation, native setup (iOS & Android), and building 100% JavaScript/TypeScript declarative layouts for **Live Activities (Dynamic Island / Lock Screen / Android Live Updates)** and **Interactive Multi-Page Home Screen Widgets**.
6
6
 
7
+ > [!TIP]
8
+ > **Using Expo (SDK 50, 51, 52, 58+)?** Check out the [Dedicated Expo Integration Guide (EXPO-GUIDE-EN.md)](./EXPO-GUIDE-EN.md) for full details on Expo Config Plugins and EAS Build!
9
+
7
10
  ---
8
11
 
9
12
  ## TABLE OF CONTENTS
10
13
  1. [Overview & Architecture](#1-overview--architecture)
11
- 2. [Installation & Project Setup](#2-installation--project-setup)
12
- - [Package Installation](#package-installation)
14
+ 2. [Official Live Demo Repositories (Expo & Bare RN)](#2-official-live-demo-repositories-expo--bare-rn)
15
+ 3. [Installation & Project Setup](#3-installation--project-setup)
16
+ - [For Expo Projects](#for-expo-projects)
17
+ - [Package Installation (Bare React Native)](#package-installation)
13
18
  - [iOS Setup (Xcode & Widget Extension)](#ios-setup-xcode--widget-extension)
14
19
  - [Android Setup (Gradle, Manifest, MainApplication & Permissions)](#android-setup-gradle-manifest-mainapplication--permissions)
15
20
  - [Native Directory Architecture (`ios/` & `android/`)](#native-directory-architecture-ios--android)
16
- 3. [Core API Reference](#3-core-api-reference)
21
+ 4. [Core API Reference](#4-core-api-reference)
17
22
  - [LiveActivity API (Lock Screen, Dynamic Island & 3 Push Token Types)](#1-liveactivity-api)
18
23
  - [Widget API (Home Screen Widgets, Multi-Page & Background Sync)](#2-widget-api-home-screen-widgets)
19
24
  - [SharedStorage API (App Groups & SharedPreferences)](#3-sharedstorage-api)
20
- 4. [Declarative UI Engine (`UI.*`)](#4-declarative-ui-engine-ui)
25
+ 5. [Declarative UI Engine (`UI.*`)](#5-declarative-ui-engine-ui)
21
26
  - [UI.VStack & UI.HStack](#uivstack--uihstack)
22
27
  - [UI.Text](#uitext)
23
28
  - [UI.Timer (Zero-Battery Hardware Timer)](#uitimer-zero-battery-hardware-timer)
@@ -25,15 +30,15 @@ Comprehensive guide covering installation, native setup (iOS & Android), and bui
25
30
  - [UI.Equalizer (Realtime Animated Music Waveform)](#uiequalizer-realtime-animated-music-waveform)
26
31
  - [UI.Image (Remote URL, Base64, File, Asset & SF Symbols)](#uiimage-remote-url-base64-file-asset--sf-symbols)
27
32
  - [UI.Button (Interactive Page Switching, Task Toggle, API Refresh & Deep Links)](#uibutton-interactive-widget-buttons)
28
- 5. [Dynamic Island Configuration (iPhone 14 Pro, 15, 16, 17)](#5-dynamic-island-configuration-iphone-14-pro-15-16-17)
29
- 6. [Building Multi-Page & Interactive Home Screen Widgets in JavaScript](#6-building-multi-page--interactive-home-screen-widgets-in-javascript)
33
+ 6. [Dynamic Island Configuration (iPhone 14 Pro, 15, 16, 17)](#6-dynamic-island-configuration-iphone-14-pro-15-16-17)
34
+ 7. [Building Multi-Page & Interactive Home Screen Widgets in JavaScript](#7-building-multi-page--interactive-home-screen-widgets-in-javascript)
30
35
  - [Lock Screen Widgets on iOS (accessoryRectangular, circular, inline)](#lock-screen-widgets-on-ios)
31
36
  - [In-App Pin Widget on Android](#in-app-pin-widget-on-android)
32
- 7. [Background API Auto-Sync When App Is Killed (`Widget.setRemoteConfig`)](#7-background-api-auto-sync-when-app-is-killed-widgetsetremoteconfig)
33
- 8. [Managing All 3 Push Token Types (APNs & FCM)](#8-managing-all-3-push-token-types-apns--fcm)
34
- 9. [State Machine & Timed Phases (`phases`)](#9-state-machine--timed-phases-phases)
35
- 10. [Server Push Payload Structure (APNs & FCM)](#10-server-push-payload-structure-apns--fcm)
36
- 11. [Troubleshooting](#11-troubleshooting)
37
+ 8. [Background API Auto-Sync When App Is Killed (`Widget.setRemoteConfig`)](#8-background-api-auto-sync-when-app-is-killed-widgetsetremoteconfig)
38
+ 9. [Managing All 3 Push Token Types (APNs & FCM)](#9-managing-all-3-push-token-types-apns--fcm)
39
+ 10. [State Machine & Timed Phases (`phases`)](#10-state-machine--timed-phases-phases)
40
+ 11. [Server Push Payload Structure (APNs & FCM)](#11-server-push-payload-structure-apns--fcm)
41
+ 12. [Troubleshooting](#12-troubleshooting)
37
42
 
38
43
  ---
39
44
 
@@ -48,9 +53,47 @@ Comprehensive guide covering installation, native setup (iOS & Android), and bui
48
53
 
49
54
  ---
50
55
 
51
- ## 2. Installation & Project Setup
56
+ ## 2. Official Live Demo Repositories (Expo & Bare RN)
57
+
58
+ To inspect real-world implementation patterns and test immediately on a simulator or device, check out the two official demo projects:
59
+
60
+ | Architecture | GitHub Repository | Highlights |
61
+ | :--- | :--- | :--- |
62
+ | **🚀 Expo (SDK 58 / CNG)** | 👉 **[https://github.com/React-Native-Vu/LiveWidgetsExampleExpo](https://github.com/React-Native-Vu/LiveWidgetsExampleExpo)** | Continuous Native Generation with Expo Config Plugin (`app.plugin.js`), zero manual Xcode/Gradle editing required. |
63
+ | **⚛️ Bare React Native CLI** | 👉 **[https://github.com/React-Native-Vu/LiveWidgetsExample](https://github.com/React-Native-Vu/LiveWidgetsExample)** | Full Xcode Widget Extension and Android Studio project structure for standard React Native CLI setups. |
64
+
65
+ ### ⚡ Quick Start with Expo Demo (LiveWidgetsExampleExpo):
66
+ ```bash
67
+ git clone https://github.com/React-Native-Vu/LiveWidgetsExampleExpo.git
68
+ cd LiveWidgetsExampleExpo
69
+ npm install
70
+ npx expo prebuild
71
+ npm run setup:widgets
72
+ npx expo run:ios # or npx expo run:android
73
+ ```
74
+
75
+ ---
76
+
77
+ ## 3. Installation & Project Setup
78
+
79
+ ### For Expo Projects
80
+ If you are using **Expo**, the library provides an **Expo Config Plugin (`app.plugin.js`)** and **CLI Wizard** out of the box.
81
+ 👉 **See the dedicated step-by-step guide: [Expo Integration Guide (EXPO-GUIDE-EN.md)](./EXPO-GUIDE-EN.md)**
82
+
83
+ ```bash
84
+ # 1. Install package
85
+ npx expo install react-native-live-widgets
52
86
 
53
- ### Package Installation
87
+ # 2. Add plugin to app.json & generate native projects
88
+ npx expo prebuild
89
+
90
+ # 3. Automatically link and configure Widget Extension
91
+ npx react-native-live-widgets init --group group.com.yourcompany.app
92
+ ```
93
+
94
+ ---
95
+
96
+ ### Package Installation (Bare React Native CLI)
54
97
  From the root directory of your React Native project:
55
98
  ```bash
56
99
  npm install react-native-live-widgets
@@ -459,6 +502,12 @@ UI.Button({
459
502
  })
460
503
  ```
461
504
 
505
+ > [!IMPORTANT]
506
+ > **Architectural Recommendation for Terminated (Force-Killed) Apps:**
507
+ > - **iOS:** When the main app is force-killed by the user, the JavaScript engine (Hermes/JSC) is terminated. Widget button taps are handled natively by Swift (`AppIntent`) and stored in App Groups. JavaScript callbacks (`registerActionHandler`) **cannot run** until the app is reopened.
508
+ > - **Android:** While `HeadlessJsTaskService` can wake the JS runtime in the background, aggressive OEM battery savers (MIUI, ColorOS, OneUI) may delay or suppress headless execution.
509
+ > - **Production Rule:** For mission-critical actions (e.g., employee attendance check-ins or financial authorizations), adopt an **Offline-First & Local State Queue** pattern: Native widgets record the action in `SharedStorage`, and `App.tsx` reads and synchronizes the queue when the app is next launched.
510
+
462
511
  ### `UI.ZStack`, `UI.Grid` & `UI.Divider` (Advanced Layout Containers)
463
512
  ```typescript
464
513
  // 1. ZStack: Overlay layers on top of each other
@@ -567,6 +616,11 @@ UI.Custom('WeatherCard', { city: 'Ho Chi Minh City', temp: '31°C' })
567
616
 
568
617
  ## 5. Dynamic Island Configuration (iPhone 14 Pro, 15, 16, 17)
569
618
 
619
+ > [!NOTE]
620
+ > **Platform Differences: iOS Dynamic Island vs. Android Live Updates:**
621
+ > - **iOS:** The `dynamicIsland` configuration maps directly to Apple's hardware Dynamic Island pill (iPhone 14 Pro+) via ActivityKit and SwiftUI (`compactLeading`, `compactTrailing`, `minimal`, `expanded`).
622
+ > - **Android:** Because standard Android devices do not feature Apple's hardware island cutout, this configuration is mapped to an **Ongoing Promoted Notification (`Notification.ProgressStyle`)** with an avatar icon, progress segments, and action buttons on the notification bar.
623
+
570
624
  ```typescript
571
625
  dynamicIsland: {
572
626
  compactLeading: UI.HStack(
@@ -707,6 +761,13 @@ await Widget.setRemoteConfig({
707
761
  - **Android**: `AlarmManager` schedules `LiveActivityReceiver` (`ACTION_WIDGET_SYNC`), fetches fresh JSON in the background (`goAsync()`), updates `SharedPreferences`, and redraws `DynamicHomeScreenWidgetProvider`.
708
762
  - The built-in `{{_lastSyncTime}}` placeholder automatically resolves to the latest sync timestamp (`HH:mm:ss`).
709
763
 
764
+ > [!NOTE]
765
+ > **Understanding Polling Intervals & OS Widget Budget:**
766
+ > - The `intervalMinutes: 15` option specifies the *desired* refresh cadence. Both iOS and Android apply strict battery and resource policies:
767
+ > - **iOS WidgetKit Budget:** Apple enforces a daily budget (~40 to 70 reloads per day). If the device is in Low Power Mode or the daily quota is exhausted, reloads may be delayed.
768
+ > - **Android Doze Mode:** Batches recurring background alarms to preserve battery health.
769
+ > - **Recommendation:** If your application requires precise, second-by-second updates (e.g., driver location or emergency shifts), always rely on **Server Push Notifications (APNs / FCM)** as the primary transport and treat background polling as a fallback.
770
+
710
771
  ---
711
772
 
712
773
  ## 8. Managing All 3 Push Token Types (APNs & FCM)