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
package/cli/setup.js CHANGED
@@ -1,58 +1,166 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  /**
4
- * CLI setup script cho React Native thuần:
5
- * npx react-native-live-widgets init
4
+ * All-in-One CLI Setup Wizard for react-native-live-widgets
5
+ * Supports both Bare React Native CLI and Expo (CNG / Prebuild)
6
+ *
7
+ * Usage:
8
+ * npx react-native-live-widgets init
9
+ * npx react-native-live-widgets init --group group.com.yourcompany.app
6
10
  */
7
11
 
8
12
  const fs = require('fs');
9
13
  const path = require('path');
14
+ const { execSync } = require('child_process');
10
15
 
11
16
  const projectRoot = process.cwd();
12
17
  const iosDir = path.join(projectRoot, 'ios');
13
18
  const androidDir = path.join(projectRoot, 'android');
19
+ const appJsonPath = path.join(projectRoot, 'app.json');
20
+ const packageJsonPath = path.join(projectRoot, 'package.json');
14
21
 
15
- console.log('🚀 [react-native-live-widgets] Bắt đầu thiết lập dự án React Native...');
22
+ // Parse CLI arguments
23
+ const args = process.argv.slice(2);
24
+ let customAppGroup = null;
25
+ for (let i = 0; i < args.length; i++) {
26
+ if (args[i] === '--group' && args[i + 1]) {
27
+ customAppGroup = args[i + 1];
28
+ break;
29
+ }
30
+ }
31
+
32
+ console.log('\n🚀 [react-native-live-widgets] Bắt đầu thiết lập tự động...');
16
33
 
17
- if (!fs.existsSync(iosDir)) {
18
- console.error('❌ Không tìm thấy thư mục ios/. Hãy chạy lệnh này ở thư mục gốc của dự án React Native.');
19
- process.exit(1);
34
+ // 1. Detect project name and bundle ID
35
+ let pkgName = 'MyApp';
36
+ if (fs.existsSync(packageJsonPath)) {
37
+ try {
38
+ const pkg = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
39
+ if (pkg.name) pkgName = pkg.name;
40
+ } catch (_e) {}
20
41
  }
21
42
 
22
- // 1. Cấu hình Info.plist iOS: NSSupportsLiveActivities = YES
23
- try {
24
- const xcodeProjects = fs.readdirSync(iosDir).filter((file) => file.endsWith('.xcodeproj'));
25
- if (xcodeProjects.length > 0) {
26
- const appName = xcodeProjects[0].replace('.xcodeproj', '');
27
- const infoPlistPath = path.join(iosDir, appName, 'Info.plist');
28
-
29
- if (fs.existsSync(infoPlistPath)) {
30
- let plistContent = fs.readFileSync(infoPlistPath, 'utf8');
31
- if (!plistContent.includes('NSSupportsLiveActivities')) {
32
- plistContent = plistContent.replace(
33
- '<dict>',
34
- '<dict>\n\t<key>NSSupportsLiveActivities</key>\n\t<true/>\n\t<key>NSSupportsLiveActivitiesFrequentUpdates</key>\n\t<true/>'
35
- );
36
- fs.writeFileSync(infoPlistPath, plistContent, 'utf8');
37
- console.log(`✅ Đã thêm NSSupportsLiveActivities vào ${appName}/Info.plist`);
38
- } else {
39
- console.log(`ℹ️ NSSupportsLiveActivities đã tồn tại trong ${appName}/Info.plist`);
40
- }
43
+ let appGroup = customAppGroup || `group.com.${pkgName.toLowerCase().replace(/[^a-z0-9]/g, '')}`;
44
+ console.log(`📦 App Group được sử dụng: ${appGroup}`);
45
+
46
+ // 2. Handle Expo project (app.json)
47
+ const isExpo = fs.existsSync(appJsonPath);
48
+ if (isExpo) {
49
+ try {
50
+ console.log('📱 Phát hiện dự án Expo. Đang cập nhật app.json...');
51
+ const appJson = JSON.parse(fs.readFileSync(appJsonPath, 'utf8'));
52
+ if (!appJson.expo) appJson.expo = {};
53
+ if (!appJson.expo.plugins) appJson.expo.plugins = [];
54
+
55
+ // Check if plugin already registered
56
+ const existingIndex = appJson.expo.plugins.findIndex(
57
+ (p) => (Array.isArray(p) ? p[0] : p) === 'react-native-live-widgets'
58
+ );
59
+
60
+ const pluginConfig = [
61
+ 'react-native-live-widgets',
62
+ {
63
+ appGroup: appGroup,
64
+ enableLiveActivities: true,
65
+ frequentUpdates: true,
66
+ },
67
+ ];
68
+
69
+ if (existingIndex >= 0) {
70
+ appJson.expo.plugins[existingIndex] = pluginConfig;
71
+ console.log('ℹ️ Đã cập nhật plugin react-native-live-widgets trong app.json');
72
+ } else {
73
+ appJson.expo.plugins.push(pluginConfig);
74
+ console.log('✅ Đã thêm plugin react-native-live-widgets vào app.json');
41
75
  }
76
+
77
+ fs.writeFileSync(appJsonPath, JSON.stringify(appJson, null, 2), 'utf8');
78
+ } catch (e) {
79
+ console.warn('⚠️ Không thể cập nhật app.json:', e.message);
42
80
  }
43
- } catch (e) {
44
- console.warn('⚠️ Không thể tự động chỉnh sửa Info.plist:', e.message);
45
81
  }
46
82
 
47
- // 2. Tạo template Widget Extension Bundle nếu chưa có
48
- const widgetTargetDir = path.join(iosDir, 'LiveWidgetsExtension');
49
- if (!fs.existsSync(widgetTargetDir)) {
50
- fs.mkdirSync(widgetTargetDir, { recursive: true });
51
-
52
- const widgetBundleContent = `import WidgetKit
83
+ // 3. Configure iOS Native Project (if ios/ folder exists)
84
+ if (fs.existsSync(iosDir)) {
85
+ console.log('\n🍎 Đang cấu hình iOS (Info.plist, Entitlements, WidgetExtension Target)...');
86
+
87
+ try {
88
+ const xcodeProjects = fs.readdirSync(iosDir).filter((file) => file.endsWith('.xcodeproj'));
89
+ if (xcodeProjects.length > 0) {
90
+ const xcodeProjName = xcodeProjects[0];
91
+ const appName = xcodeProjName.replace('.xcodeproj', '');
92
+ const pbxprojPath = path.join(iosDir, xcodeProjName, 'project.pbxproj');
93
+ const appDir = path.join(iosDir, appName);
94
+
95
+ // A. Info.plist: Inject NSSupportsLiveActivities
96
+ const infoPlistPath = path.join(appDir, 'Info.plist');
97
+ if (fs.existsSync(infoPlistPath)) {
98
+ let plistContent = fs.readFileSync(infoPlistPath, 'utf8');
99
+ if (!plistContent.includes('NSSupportsLiveActivities')) {
100
+ plistContent = plistContent.replace(
101
+ '<dict>',
102
+ '<dict>\n\t<key>NSSupportsLiveActivities</key>\n\t<true/>\n\t<key>NSSupportsLiveActivitiesFrequentUpdates</key>\n\t<true/>'
103
+ );
104
+ fs.writeFileSync(infoPlistPath, plistContent, 'utf8');
105
+ console.log(`✅ Đã thêm NSSupportsLiveActivities vào ${appName}/Info.plist`);
106
+ } else {
107
+ console.log(`ℹ️ NSSupportsLiveActivities đã tồn tại trong ${appName}/Info.plist`);
108
+ }
109
+ }
110
+
111
+ // B. Entitlements: Add App Group to Main App
112
+ const entitlementsPath = path.join(appDir, `${appName}.entitlements`);
113
+ const entitlementsXml = `<?xml version="1.0" encoding="UTF-8"?>
114
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
115
+ <plist version="1.0">
116
+ <dict>
117
+ \t<key>com.apple.security.application-groups</key>
118
+ \t<array>
119
+ \t\t<string>${appGroup}</string>
120
+ \t</array>
121
+ </dict>
122
+ </plist>
123
+ `;
124
+ if (!fs.existsSync(entitlementsPath)) {
125
+ fs.writeFileSync(entitlementsPath, entitlementsXml, 'utf8');
126
+ console.log(`✅ Đã tạo ${appName}.entitlements với App Group: ${appGroup}`);
127
+ } else {
128
+ let content = fs.readFileSync(entitlementsPath, 'utf8');
129
+ if (!content.includes(appGroup)) {
130
+ if (content.includes('com.apple.security.application-groups')) {
131
+ content = content.replace(
132
+ /<array>/,
133
+ `<array>\n\t\t<string>${appGroup}</string>`
134
+ );
135
+ } else {
136
+ content = content.replace(
137
+ '<dict>',
138
+ `<dict>\n\t<key>com.apple.security.application-groups</key>\n\t<array>\n\t\t<string>${appGroup}</string>\n\t</array>`
139
+ );
140
+ }
141
+ fs.writeFileSync(entitlementsPath, content, 'utf8');
142
+ console.log(`✅ Đã thêm App Group vào ${appName}.entitlements`);
143
+ }
144
+ }
145
+
146
+ // C. Scaffold LiveWidgetsExtension Target Directory
147
+ const widgetTargetDir = path.join(iosDir, 'LiveWidgetsExtension');
148
+ const widgetSharedDir = path.join(widgetTargetDir, 'Shared');
149
+ if (!fs.existsSync(widgetSharedDir)) {
150
+ fs.mkdirSync(widgetSharedDir, { recursive: true });
151
+ }
152
+
153
+ // Copy template LiveWidgetsBundle.swift
154
+ const widgetBundlePath = path.join(widgetTargetDir, 'LiveWidgetsBundle.swift');
155
+ if (!fs.existsSync(widgetBundlePath)) {
156
+ const bundleCode = `import WidgetKit
53
157
  import SwiftUI
158
+ #if canImport(react_native_live_widgets)
54
159
  import react_native_live_widgets
160
+ #endif
55
161
 
162
+ /// Bundle mở rộng hỗ trợ cả Live Activity (Lock Screen & Dynamic Island)
163
+ /// và Home Screen Widgets (Màn hình chính iOS 16.1 -> iOS 17/18/27+)
56
164
  @main
57
165
  struct LiveWidgetsBundle: WidgetBundle {
58
166
  var body: some Widget {
@@ -61,11 +169,24 @@ struct LiveWidgetsBundle: WidgetBundle {
61
169
  DynamicLiveActivityWidget()
62
170
  }
63
171
 
64
- // 2. Home Screen Widget (Màn hình chính)
172
+ // 2. Tiện ích chính (Dynamic / Đang chọn trong App)
65
173
  DynamicHomeScreenWidget()
174
+
175
+ // 3. Tiện ích Bộ đếm tương tác (Interactive TS Counter)
176
+ InteractiveCounterHomeScreenWidget()
177
+
178
+ // 4. Tiện ích Bảo mật & Tính năng Pro (Core 2.0)
179
+ ProFeaturesHomeScreenWidget()
180
+
181
+ // 5. Tiện ích Chấm công & Ca làm việc (Shift Attendance)
182
+ ShiftAttendanceHomeScreenWidget()
183
+
184
+ // 6. Tiện ích Không gian làm việc đa trang (Multi-Page Workspace)
185
+ MultiPageHomeScreenWidget()
66
186
  }
67
187
  }
68
188
 
189
+ // ── 1. TIỆN ÍCH CHÍNH (ĐỒNG BỘ THEO MẪU ĐANG CHỌN) ──
69
190
  struct DynamicHomeScreenWidget: Widget {
70
191
  let kind: String = "DynamicHomeScreenWidget"
71
192
 
@@ -73,22 +194,298 @@ struct DynamicHomeScreenWidget: Widget {
73
194
  StaticConfiguration(kind: kind, provider: DynamicWidgetProvider(widgetKey: "main")) { entry in
74
195
  DynamicHomeScreenWidgetView(entry: entry)
75
196
  }
76
- .configurationDisplayName("Tiện ích")
77
- .description("Hiển thị thông tin cập nhật từ ứng dụng.")
78
- .supportedFamilies([.systemSmall, .systemMedium, .systemLarge])
197
+ .configurationDisplayName("Tiện ích Live Widgets")
198
+ .description("Tự động đồng bộ và hiển thị theo mẫu giao diện bạn chọn trong ứng dụng.")
199
+ .supportedFamilies(commonFamilies)
200
+ }
201
+ }
202
+
203
+ // ── 2. TIỆN ÍCH BỘ ĐẾM TƯƠNG TÁC TYPESCRIPT ──
204
+ struct InteractiveCounterHomeScreenWidget: Widget {
205
+ let kind: String = "InteractiveCounterHomeScreenWidget"
206
+
207
+ var body: some WidgetConfiguration {
208
+ StaticConfiguration(kind: kind, provider: DynamicWidgetProvider(widgetKey: "counter")) { entry in
209
+ DynamicHomeScreenWidgetView(entry: entry)
210
+ }
211
+ .configurationDisplayName("Bộ đếm tương tác (TS)")
212
+ .description("Bấm nút [+] hoặc [-] để kích hoạt trực tiếp hàm logic TypeScript.")
213
+ .supportedFamilies(commonFamilies)
79
214
  }
80
215
  }
216
+
217
+ // ── 3. TIỆN ÍCH BẢO MẬT & KPI PRO (CORE 2.0) ──
218
+ struct ProFeaturesHomeScreenWidget: Widget {
219
+ let kind: String = "ProFeaturesHomeScreenWidget"
220
+
221
+ var body: some WidgetConfiguration {
222
+ StaticConfiguration(kind: kind, provider: DynamicWidgetProvider(widgetKey: "pro")) { entry in
223
+ DynamicHomeScreenWidgetView(entry: entry)
224
+ }
225
+ .configurationDisplayName("Bảo mật & KPI Pro")
226
+ .description("Tự che số khi khoá máy (Privacy Sensitive) và hỗ trợ chế độ StandBy.")
227
+ .supportedFamilies(commonFamilies)
228
+ }
229
+ }
230
+
231
+ // ── 4. TIỆN ÍCH CHẤM CÔNG & CA LÀM VIỆC ──
232
+ struct ShiftAttendanceHomeScreenWidget: Widget {
233
+ let kind: String = "ShiftAttendanceHomeScreenWidget"
234
+
235
+ var body: some WidgetConfiguration {
236
+ StaticConfiguration(kind: kind, provider: DynamicWidgetProvider(widgetKey: "shift")) { entry in
237
+ DynamicHomeScreenWidgetView(entry: entry)
238
+ }
239
+ .configurationDisplayName("Chấm công & Ca làm việc")
240
+ .description("Theo dõi giờ vào làm, thời gian tan ca và thanh tiến trình công việc.")
241
+ .supportedFamilies(commonFamilies)
242
+ }
243
+ }
244
+
245
+ // ── 5. TIỆN ÍCH KHÔNG GIAN ĐA TRANG (MULTI-PAGE) ──
246
+ struct MultiPageHomeScreenWidget: Widget {
247
+ let kind: String = "MultiPageHomeScreenWidget"
248
+
249
+ var body: some WidgetConfiguration {
250
+ StaticConfiguration(kind: kind, provider: DynamicWidgetProvider(widgetKey: "workspace")) { entry in
251
+ DynamicHomeScreenWidgetView(entry: entry)
252
+ }
253
+ .configurationDisplayName("Không gian đa trang")
254
+ .description("Chuyển đổi qua lại giữa Ca làm, Công việc và OKRs ngay trên mặt Widget.")
255
+ .supportedFamilies(commonFamilies)
256
+ }
257
+ }
258
+
259
+ private var commonFamilies: [WidgetFamily] {
260
+ var list: [WidgetFamily] = [.systemSmall, .systemMedium, .systemLarge]
261
+ if #available(iOS 16.0, *) {
262
+ list.append(contentsOf: [.accessoryRectangular, .accessoryCircular, .accessoryInline])
263
+ }
264
+ return list
265
+ }
266
+ `;
267
+ fs.writeFileSync(widgetBundlePath, bundleCode, 'utf8');
268
+ console.log('✅ Đã tạo template: ios/LiveWidgetsExtension/LiveWidgetsBundle.swift');
269
+ }
270
+
271
+ // Create extension Info.plist
272
+ const widgetInfoPlist = path.join(widgetTargetDir, 'Info.plist');
273
+ if (!fs.existsSync(widgetInfoPlist)) {
274
+ const extPlistCode = `<?xml version="1.0" encoding="UTF-8"?>
275
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
276
+ <plist version="1.0">
277
+ <dict>
278
+ \t<key>CFBundleDevelopmentRegion</key>
279
+ \t<string>en</string>
280
+ \t<key>CFBundleDisplayName</key>
281
+ \t<string>LiveWidgetsExtension</string>
282
+ \t<key>CFBundleExecutable</key>
283
+ \t<string>$(EXECUTABLE_NAME)</string>
284
+ \t<key>CFBundleIdentifier</key>
285
+ \t<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
286
+ \t<key>CFBundleInfoDictionaryVersion</key>
287
+ \t<string>6.0</string>
288
+ \t<key>CFBundleName</key>
289
+ \t<string>$(PRODUCT_NAME)</string>
290
+ \t<key>CFBundlePackageType</key>
291
+ \t<string>XPC!</string>
292
+ \t<key>CFBundleShortVersionString</key>
293
+ \t<string>1.0</string>
294
+ \t<key>CFBundleVersion</key>
295
+ \t<string>1</string>
296
+ \t<key>NSExtension</key>
297
+ \t<dict>
298
+ \t\t<key>NSExtensionPointIdentifier</key>
299
+ \t\t<string>com.apple.widgetkit-extension</string>
300
+ \t</dict>
301
+ </dict>
302
+ </plist>
81
303
  `;
82
- fs.writeFileSync(path.join(widgetTargetDir, 'LiveWidgetsBundle.swift'), widgetBundleContent, 'utf8');
83
- console.log('✅ Đã tạo file template: ios/LiveWidgetsExtension/LiveWidgetsBundle.swift');
304
+ fs.writeFileSync(widgetInfoPlist, extPlistCode, 'utf8');
305
+ console.log('✅ Đã tạo Info.plist cho Widget Extension');
306
+ }
307
+
308
+ // Create extension Entitlements
309
+ const widgetEntitlementsPath = path.join(widgetTargetDir, 'LiveWidgetsExtension.entitlements');
310
+ if (!fs.existsSync(widgetEntitlementsPath)) {
311
+ fs.writeFileSync(widgetEntitlementsPath, entitlementsXml, 'utf8');
312
+ console.log('✅ Đã tạo LiveWidgetsExtension.entitlements với App Group');
313
+ }
314
+
315
+ // Copy shared widget Swift files from library
316
+ const libIosDir = path.resolve(__dirname, '..', 'ios');
317
+ const subdirs = ['Renderer', 'Models', 'Storage', 'Intents', 'Widgets'];
318
+ for (const subdir of subdirs) {
319
+ const srcSubdir = path.join(libIosDir, subdir);
320
+ if (fs.existsSync(srcSubdir)) {
321
+ const swiftFiles = fs.readdirSync(srcSubdir).filter((f) => f.endsWith('.swift'));
322
+ for (const f of swiftFiles) {
323
+ fs.copyFileSync(path.join(srcSubdir, f), path.join(widgetSharedDir, f));
324
+ }
325
+ }
326
+ }
327
+ console.log('✅ Đã copy các Swift models và renderers vào LiveWidgetsExtension/Shared/');
328
+
329
+ // D. Configure Xcode Project (project.pbxproj) via 'xcode' module
330
+ let xcode;
331
+ try {
332
+ xcode = require('xcode');
333
+ } catch (_e) {
334
+ try {
335
+ const resolveFrom = require.resolve('xcode', { paths: [projectRoot, __dirname] });
336
+ xcode = require(resolveFrom);
337
+ } catch (_e2) {}
338
+ }
339
+
340
+ if (xcode && fs.existsSync(pbxprojPath)) {
341
+ const myProj = xcode.project(pbxprojPath);
342
+ myProj.parseSync();
343
+
344
+ const targetName = 'LiveWidgetsExtension';
345
+ const targetBundleId = `${appGroup.replace('group.', '')}.LiveWidgetsExtension`;
346
+
347
+ let targetExists = false;
348
+ const targets = myProj.pbxNativeTargetSection();
349
+ for (const key in targets) {
350
+ if (targets[key] && targets[key].name === targetName) {
351
+ targetExists = true;
352
+ break;
353
+ }
354
+ }
355
+
356
+ if (!targetExists) {
357
+ console.log('➕ Đang tạo Xcode Target LiveWidgetsExtension...');
358
+ const newTarget = myProj.addTarget(targetName, 'app_extension', targetName);
359
+
360
+ // Tạo các Build Phases riêng biệt cho Extension Target
361
+ myProj.addBuildPhase([], 'PBXSourcesBuildPhase', 'Sources', newTarget.uuid);
362
+ myProj.addBuildPhase([], 'PBXFrameworksBuildPhase', 'Frameworks', newTarget.uuid);
363
+ myProj.addBuildPhase([], 'PBXResourcesBuildPhase', 'Resources', newTarget.uuid);
364
+
365
+ // Thêm các file Swift CHỈ vào Sources của Extension Target (tránh xung đột @main với AppDelegate)
366
+ const filesToAdd = [
367
+ 'LiveWidgetsExtension/LiveWidgetsBundle.swift',
368
+ ...fs.readdirSync(widgetSharedDir).filter(f => f.endsWith('.swift')).map(f => `LiveWidgetsExtension/Shared/${f}`)
369
+ ];
370
+
371
+ for (const relPath of filesToAdd) {
372
+ myProj.addSourceFile(relPath, { target: newTarget.uuid });
373
+ }
374
+
375
+ myProj.addFramework('WidgetKit.framework', { target: newTarget.uuid });
376
+ myProj.addFramework('SwiftUI.framework', { target: newTarget.uuid });
377
+
378
+ // Update build settings
379
+ const configs = myProj.pbxXCBuildConfigurationSection();
380
+ for (const key in configs) {
381
+ const config = configs[key];
382
+ if (config.buildSettings && (config.buildSettings.PRODUCT_NAME === `"${targetName}"` || config.buildSettings.PRODUCT_NAME === targetName)) {
383
+ config.buildSettings.PRODUCT_BUNDLE_IDENTIFIER = `"${targetBundleId}"`;
384
+ config.buildSettings.CODE_SIGN_ENTITLEMENTS = `"LiveWidgetsExtension/LiveWidgetsExtension.entitlements"`;
385
+ config.buildSettings.INFOPLIST_FILE = `"LiveWidgetsExtension/Info.plist"`;
386
+ config.buildSettings.IPHONEOS_DEPLOYMENT_TARGET = '16.4';
387
+ config.buildSettings.SWIFT_VERSION = '5.0';
388
+ config.buildSettings.GENERATE_INFOPLIST_FILE = 'NO';
389
+ config.buildSettings.LD_RUNPATH_SEARCH_PATHS = `"$(inherited) @executable_path/Frameworks @executable_path/../../Frameworks"`;
390
+ config.buildSettings.TARGETED_DEVICE_FAMILY = '"1,2"';
391
+ }
392
+ }
393
+
394
+ // Embed in Main App
395
+ const mainTargetKey = myProj.findTargetKey(appName);
396
+ if (mainTargetKey) {
397
+ const copyPhase = myProj.addBuildPhase(
398
+ [],
399
+ 'PBXCopyFilesBuildPhase',
400
+ 'Embed App Extensions',
401
+ mainTargetKey,
402
+ 'app_extension'
403
+ );
404
+ if (copyPhase && copyPhase.buildPhase) {
405
+ copyPhase.buildPhase.dstSubfolderSpec = 13;
406
+ }
407
+ myProj.addTargetDependency(mainTargetKey, [newTarget.uuid]);
408
+ }
409
+
410
+ fs.writeFileSync(pbxprojPath, myProj.writeSync(), 'utf8');
411
+ console.log('✅ Đã nhúng LiveWidgetsExtension vào project.pbxproj thành công!');
412
+ } else {
413
+ console.log('ℹ️ LiveWidgetsExtension target đã tồn tại trong Xcode project.');
414
+ }
415
+ }
416
+
417
+ // E. Update Podfile
418
+ const podfilePath = path.join(iosDir, 'Podfile');
419
+ if (fs.existsSync(podfilePath)) {
420
+ let podContent = fs.readFileSync(podfilePath, 'utf8');
421
+ if (!podContent.includes('react-native-live-widgets')) {
422
+ podContent = podContent.replace(
423
+ `target '${appName}' do`,
424
+ `target '${appName}' do\n pod 'react-native-live-widgets', :path => '../node_modules/react-native-live-widgets'`
425
+ );
426
+ fs.writeFileSync(podfilePath, podContent, 'utf8');
427
+ console.log(`✅ Đã thêm pod 'react-native-live-widgets' vào Podfile`);
428
+ }
429
+ }
430
+
431
+ // F. Run pod install
432
+ try {
433
+ console.log('🔄 Đang chạy pod install...');
434
+ execSync('pod install', { cwd: iosDir, stdio: 'inherit' });
435
+ console.log('✅ pod install hoàn tất!');
436
+ } catch (_e) {
437
+ console.warn('⚠️ Vui lòng chạy "cd ios && pod install" thủ công.');
438
+ }
439
+ }
440
+ } catch (e) {
441
+ console.warn('⚠️ Lỗi khi cấu hình iOS:', e.message);
442
+ }
443
+ } else if (isExpo) {
444
+ console.log('\n💡 Gợi ý: Thư mục ios/ chưa được tạo. Sau khi cấu hình app.json xong, bạn chỉ cần chạy:');
445
+ console.log('👉 npx expo prebuild');
446
+ console.log('👉 npx react-native-live-widgets init (để tự động liên kết Xcode target)');
84
447
  }
85
448
 
86
- console.log('\n🎉 Thiết lập ban đầu hoàn tất!');
87
- console.log('👉 Tiếp theo:');
88
- console.log('1. Mở Xcode, chọn File -> New -> Target -> Widget Extension (đặt tên LiveWidgetsExtension, bỏ tích "Include Configuration App Intent").');
89
- console.log('2. Trong Podfile, thêm vào bên trong target chính:');
90
- console.log(` target 'LiveWidgetsExtension' do
91
- inherit! :search_paths
92
- pod 'react-native-live-widgets/Widget', :path => '../node_modules/react-native-live-widgets'
93
- end`);
94
- console.log('3. Chạy "cd ios && pod install" là sẵn sàng sử dụng!\n');
449
+ // 4. Configure Android Native Project (if android/ folder exists)
450
+ if (fs.existsSync(androidDir)) {
451
+ console.log('\n🤖 Đang kiểm tra cấu hình Android...');
452
+ const manifestPath = path.join(androidDir, 'app', 'src', 'main', 'AndroidManifest.xml');
453
+ if (fs.existsSync(manifestPath)) {
454
+ try {
455
+ let manifest = fs.readFileSync(manifestPath, 'utf8');
456
+ let changed = false;
457
+ const permissions = [
458
+ '<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />',
459
+ '<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />',
460
+ ];
461
+ for (const perm of permissions) {
462
+ if (!manifest.includes(perm)) {
463
+ manifest = manifest.replace(
464
+ '<manifest',
465
+ `<manifest\n ${perm}`
466
+ );
467
+ changed = true;
468
+ }
469
+ }
470
+ if (changed) {
471
+ fs.writeFileSync(manifestPath, manifest, 'utf8');
472
+ console.log('✅ Đã thêm permissions vào AndroidManifest.xml');
473
+ } else {
474
+ console.log('ℹ️ Permissions Android đã đầy đủ');
475
+ }
476
+ } catch (e) {
477
+ console.warn('⚠️ Không thể cập nhật AndroidManifest.xml:', e.message);
478
+ }
479
+ }
480
+ }
481
+
482
+ console.log('\n🎉 THIẾT LẬP HOÀN TẤT 100%!');
483
+ console.log('👉 Bạn có thể chạy ứng dụng ngay bây giờ:');
484
+ if (isExpo) {
485
+ console.log(' - iOS: npx expo run:ios');
486
+ console.log(' - Android: npx expo run:android');
487
+ } else {
488
+ console.log(' - iOS: npx react-native run-ios');
489
+ console.log(' - Android: npx react-native run-android');
490
+ }
491
+ console.log('');