react-native-live-widgets 1.2.0 → 1.2.2

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 (87) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/README.md +129 -50
  3. package/android/src/main/AndroidManifest.xml +12 -0
  4. package/android/src/main/assets/fonts/MaterialIcons-Regular.ttf +0 -0
  5. package/android/src/main/java/com/reactnativeliveactivity/bridge/LiveActivityModule.kt +61 -1
  6. package/android/src/main/java/com/reactnativeliveactivity/liveactivity/LiveActivityNotifier.kt +153 -17
  7. package/android/src/main/java/com/reactnativeliveactivity/liveactivity/LiveActivityReceiver.kt +1 -1
  8. package/android/src/main/java/com/reactnativeliveactivity/renderer/DynamicWidgetCanvasRenderer.kt +529 -59
  9. package/android/src/main/java/com/reactnativeliveactivity/storage/DynamicWidgetImageCache.kt +53 -0
  10. package/android/src/main/java/com/reactnativeliveactivity/storage/DynamicWidgetStateStore.kt +684 -83
  11. package/android/src/main/java/com/reactnativeliveactivity/widgets/DynamicHomeScreenWidgetProvider.kt +129 -57
  12. package/android/src/main/java/com/reactnativeliveactivity/widgets/DynamicQuickSettingsTileService.kt +120 -0
  13. package/android/src/main/res/layout/rn_live_widget_hit_zone.xml +16 -0
  14. package/android/src/main/res/layout/rn_live_widget_host.xml +16 -87
  15. package/app.plugin.js +36 -0
  16. package/assets/MaterialIcons.json +2236 -0
  17. package/cli/codegen.js +789 -0
  18. package/cli/setup.js +323 -63
  19. package/docs/EXPO-GUIDE-EN.md +21 -3
  20. package/docs/EXPO-GUIDE-VI.md +21 -3
  21. package/docs/GUIDE-EN.md +444 -21
  22. package/docs/GUIDE-VI.md +473 -22
  23. package/docs/index.html +2263 -265
  24. package/docs/llms-full.txt +41 -0
  25. package/docs/llms.txt +24 -7
  26. package/ios/Bridge/LiveActivityModule.swift +333 -44
  27. package/ios/Intents/DynamicWidgetActionIntent.swift +57 -2
  28. package/ios/Models/DynamicLayoutModels.swift +120 -5
  29. package/ios/Renderer/DynamicNodeView.swift +184 -20
  30. package/ios/Storage/DynamicWidgetStateStore.swift +649 -38
  31. package/ios/Widgets/DynamicControlWidget.swift +63 -0
  32. package/ios/Widgets/DynamicHomeScreenWidget.swift +104 -26
  33. package/ios/Widgets/DynamicLiveActivityWidget.swift +25 -4
  34. package/lib/builder.d.ts +50 -7
  35. package/lib/builder.d.ts.map +1 -1
  36. package/lib/builder.js +391 -29
  37. package/lib/builder.js.map +1 -1
  38. package/lib/dispatcher.js +16 -10
  39. package/lib/dispatcher.js.map +1 -1
  40. package/lib/hooks.d.ts +13 -9
  41. package/lib/hooks.d.ts.map +1 -1
  42. package/lib/hooks.js +105 -42
  43. package/lib/hooks.js.map +1 -1
  44. package/lib/index.d.ts +96 -8
  45. package/lib/index.d.ts.map +1 -1
  46. package/lib/index.js +415 -97
  47. package/lib/index.js.map +1 -1
  48. package/lib/ir.d.ts +15 -0
  49. package/lib/ir.d.ts.map +1 -0
  50. package/lib/ir.js +386 -0
  51. package/lib/ir.js.map +1 -0
  52. package/lib/jsx.d.ts +19 -7
  53. package/lib/jsx.d.ts.map +1 -1
  54. package/lib/jsx.js +179 -95
  55. package/lib/jsx.js.map +1 -1
  56. package/lib/material-icons.generated.d.ts +8 -0
  57. package/lib/material-icons.generated.d.ts.map +1 -0
  58. package/lib/material-icons.generated.js +9 -0
  59. package/lib/material-icons.generated.js.map +1 -0
  60. package/lib/preview.d.ts +11 -27
  61. package/lib/preview.d.ts.map +1 -1
  62. package/lib/preview.js +456 -119
  63. package/lib/preview.js.map +1 -1
  64. package/lib/sf-symbols.generated.d.ts +8 -0
  65. package/lib/sf-symbols.generated.d.ts.map +1 -0
  66. package/lib/sf-symbols.generated.js +9 -0
  67. package/lib/sf-symbols.generated.js.map +1 -0
  68. package/lib/types.d.ts +506 -30
  69. package/lib/types.d.ts.map +1 -1
  70. package/lib/types.js +2 -1
  71. package/lib/types.js.map +1 -1
  72. package/package.json +7 -2
  73. package/scripts/build.js +98 -0
  74. package/scripts/generate-material-icons.js +93 -0
  75. package/scripts/generate-sf-symbols.js +95 -0
  76. package/scripts/release.js +115 -0
  77. package/scripts/test-ir-semantic.js +314 -0
  78. package/src/builder.ts +439 -26
  79. package/src/hooks.ts +88 -12
  80. package/src/index.ts +385 -57
  81. package/src/ir.ts +436 -0
  82. package/src/jsx.tsx +99 -21
  83. package/src/material-icons.generated.ts +3844 -0
  84. package/src/preview.tsx +533 -55
  85. package/src/react-native-env.d.ts +1 -0
  86. package/src/sf-symbols.generated.ts +9533 -0
  87. package/src/types.ts +601 -31
package/cli/codegen.js ADDED
@@ -0,0 +1,789 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * TypeScript-Driven WidgetKit Codegen for react-native-live-widgets
5
+ *
6
+ * Tự động đọc file cấu hình widgets.config.ts (hoặc .js / .json)
7
+ * và sinh ra:
8
+ * 1. File mã nguồn Swift hoàn chỉnh (LiveWidgetsBundle.swift)
9
+ * 2. Tự động liên kết thư mục đa ngôn ngữ i18n (locales/*.json)
10
+ * và sinh ra các file Localizable.strings / Localizable.xcstrings cho iOS Extension.
11
+ *
12
+ * Usage:
13
+ * npx react-native-live-widgets codegen
14
+ * npx live-widgets-codegen
15
+ */
16
+
17
+ const fs = require('fs');
18
+ const path = require('path');
19
+
20
+ function toPascalCase(text) {
21
+ if (!text) return 'Dynamic';
22
+ return text
23
+ .replace(/(?:^\w|[A-Z]|\b\w)/g, (letter) => letter.toUpperCase())
24
+ .replace(/[\s_-]+/g, '');
25
+ }
26
+
27
+ function escapeSwiftString(str) {
28
+ if (!str) return '';
29
+ return str.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
30
+ }
31
+
32
+ /**
33
+ * Làm phẳng object lồng nhau (flatten JSON):
34
+ * { widgets: { counter: { title: "A" } } } -> { "widgets.counter.title": "A" }
35
+ */
36
+ function flattenObject(obj, prefix = '') {
37
+ const result = {};
38
+ if (!obj || typeof obj !== 'object') return result;
39
+ for (const [key, val] of Object.entries(obj)) {
40
+ const fullKey = prefix ? `${prefix}.${key}` : key;
41
+ if (val && typeof val === 'object' && !Array.isArray(val)) {
42
+ Object.assign(result, flattenObject(val, fullKey));
43
+ } else if (val !== undefined && val !== null) {
44
+ result[fullKey] = String(val);
45
+ }
46
+ }
47
+ return result;
48
+ }
49
+
50
+ /**
51
+ * Trình tải cấu hình (TypeScript / JavaScript / JSON)
52
+ */
53
+ function loadWidgetsConfig(projectRoot, customConfigPath = null) {
54
+ let targetPath = null;
55
+ if (customConfigPath) {
56
+ targetPath = path.isAbsolute(customConfigPath)
57
+ ? customConfigPath
58
+ : path.join(projectRoot, customConfigPath);
59
+ } else {
60
+ const candidates = [
61
+ 'widgets.config.ts',
62
+ 'widgets.config.js',
63
+ 'widgets.config.mjs',
64
+ 'widgets.config.cjs',
65
+ 'widgets.config.json',
66
+ ];
67
+ for (const cand of candidates) {
68
+ const fullPath = path.join(projectRoot, cand);
69
+ if (fs.existsSync(fullPath)) {
70
+ targetPath = fullPath;
71
+ break;
72
+ }
73
+ }
74
+ }
75
+
76
+ if (!targetPath || !fs.existsSync(targetPath)) {
77
+ targetPath = path.join(projectRoot, 'widgets.config.ts');
78
+ const defaultTemplate = `import { defineWidgetConfig } from 'react-native-live-widgets';
79
+
80
+ /**
81
+ * ==============================================================================
82
+ * react-native-live-widgets Configuration (widgets.config.ts)
83
+ * ==============================================================================
84
+ *
85
+ * This configuration file drives the TypeScript codegen engine.
86
+ * Run the following command whenever you modify this file:
87
+ *
88
+ * npx react-native-live-widgets codegen
89
+ *
90
+ * It will automatically:
91
+ * 1. Generate 'LiveWidgetsBundle.swift' for iOS WidgetKit Extension.
92
+ * 2. Generate modern Apple String Catalog ('Localizable.xcstrings').
93
+ * 3. Synchronize Android string resources ('res/values-{lang}/strings.xml').
94
+ * 4. Synchronize SF Symbols (iOS) & Material Icons (Android) type definitions.
95
+ * ==============================================================================
96
+ */
97
+ export default defineWidgetConfig({
98
+ /**
99
+ * The name of the Swift WidgetBundle struct generated in the iOS extension.
100
+ * Default: 'LiveWidgetsBundle'
101
+ */
102
+ bundleName: 'LiveWidgetsBundle',
103
+
104
+ /**
105
+ * Enable or disable iOS Lock Screen Live Activities & Dynamic Island.
106
+ * Set to 'false' if your application only uses Home Screen widgets.
107
+ */
108
+ liveActivity: true,
109
+
110
+ /**
111
+ * Enable or disable iOS 18+ Interactive Control Center widgets.
112
+ */
113
+ controlWidgets: true,
114
+
115
+ /**
116
+ * Default fallback locale for widget titles, descriptions, and static labels.
117
+ */
118
+ defaultLocale: 'vi',
119
+
120
+ /**
121
+ * Multi-language translation catalog.
122
+ * Keys defined here are automatically mapped to:
123
+ * - iOS: Localizable.xcstrings (LocalizedStringKey in Swift)
124
+ * - Android: res/values-{lang}/strings.xml (R.string in Kotlin/Java)
125
+ */
126
+ locales: {
127
+ vi: {
128
+ 'widgets.main.title': 'Tiện ích Live Widgets',
129
+ 'widgets.main.desc': 'Tự động đồng bộ và hiển thị theo mẫu giao diện bạn chọn trong ứng dụng.',
130
+ },
131
+ en: {
132
+ 'widgets.main.title': 'Live Widgets Utility',
133
+ 'widgets.main.desc': 'Automatically syncs and displays layouts defined in your React Native app.',
134
+ },
135
+ },
136
+
137
+ /**
138
+ * List of registered Home Screen widgets.
139
+ * Each entry maps to a distinct timeline provider and widget kind.
140
+ */
141
+ widgets: [
142
+ {
143
+ /** Unique key identifier used in Widget.setLayout('<key>', ...) */
144
+ key: 'main',
145
+
146
+ /** Native Swift struct kind name generated in WidgetBundle */
147
+ kind: 'DynamicHomeScreenWidget',
148
+
149
+ /** Display name shown in the iOS & Android Widget Gallery picker */
150
+ displayName: 'widgets.main.title',
151
+
152
+ /** Description shown below the widget preview in the Widget Gallery */
153
+ description: 'widgets.main.desc',
154
+
155
+ /** Supported widget sizes for this widget */
156
+ supportedFamilies: ['systemSmall', 'systemMedium', 'systemLarge'],
157
+ },
158
+ ],
159
+ });
160
+ `;
161
+ fs.writeFileSync(targetPath, defaultTemplate, 'utf8');
162
+ console.log(`✨ Created default widget configuration at: widgets.config.ts`);
163
+ }
164
+
165
+ console.log(`📄 Reading widget configuration from: ${path.relative(projectRoot, targetPath)}`);
166
+
167
+ if (targetPath.endsWith('.json')) {
168
+ const raw = fs.readFileSync(targetPath, 'utf8');
169
+ return { config: JSON.parse(raw), configPath: targetPath };
170
+ }
171
+
172
+ // Đối với .ts / .js
173
+ let rawCode = fs.readFileSync(targetPath, 'utf8');
174
+ let jsCode = rawCode;
175
+
176
+ if (targetPath.endsWith('.ts')) {
177
+ let tsCompiler = null;
178
+ try {
179
+ tsCompiler = require(require.resolve('typescript', { paths: [projectRoot, __dirname] }));
180
+ } catch (_) {}
181
+
182
+ if (tsCompiler) {
183
+ jsCode = tsCompiler.transpileModule(rawCode, {
184
+ compilerOptions: {
185
+ module: tsCompiler.ModuleKind.CommonJS,
186
+ target: tsCompiler.ScriptTarget.ES2020,
187
+ allowJs: true,
188
+ },
189
+ }).outputText;
190
+ } else {
191
+ // Fallback: Loại bỏ type annotations cơ bản nếu không có typescript module
192
+ jsCode = rawCode
193
+ .replace(/import\s+[^;]+;?/g, '')
194
+ .replace(/export\s+default\s+/g, 'module.exports = ')
195
+ .replace(/export\s+const\s+/g, 'const ');
196
+ }
197
+ }
198
+
199
+ // Chạy mã đã chuyển đổi trong môi trường module giả lập
200
+ const moduleContext = { exports: {} };
201
+ const mockRequire = (id) => {
202
+ if (id === 'react-native-live-widgets') {
203
+ return {
204
+ defineWidgetsConfig: (c) => c,
205
+ defineWidgetConfig: (c) => c,
206
+ };
207
+ }
208
+ try {
209
+ return require(require.resolve(id, { paths: [projectRoot, __dirname] }));
210
+ } catch (_err) {
211
+ return {};
212
+ }
213
+ };
214
+
215
+ try {
216
+ const executeFn = new Function('module', 'exports', 'require', '__dirname', '__filename', jsCode);
217
+ executeFn(
218
+ moduleContext,
219
+ moduleContext.exports,
220
+ mockRequire,
221
+ path.dirname(targetPath),
222
+ targetPath
223
+ );
224
+ } catch (err) {
225
+ throw new Error(`Failed to execute config file (${path.basename(targetPath)}): ${err.message}`);
226
+ }
227
+
228
+ const loadedConfig = moduleContext.exports.default || moduleContext.exports.config || moduleContext.exports;
229
+ if (!loadedConfig || typeof loadedConfig !== 'object') {
230
+ throw new Error(
231
+ `Config file (${path.basename(targetPath)}) does not export a valid configuration object.`
232
+ );
233
+ }
234
+
235
+ return { config: loadedConfig, configPath: targetPath };
236
+ }
237
+
238
+ /**
239
+ * Xây dựng Catalog bản dịch i18n từ thư mục locales JSON và inline translations
240
+ */
241
+ function buildI18nCatalog(projectRoot, config) {
242
+ const i18nConfig = config.i18n || {};
243
+ const defaultLocale = i18nConfig.defaultLocale || 'vi';
244
+ const catalog = {};
245
+
246
+ const ensureLocale = (loc) => {
247
+ if (!catalog[loc]) catalog[loc] = {};
248
+ };
249
+
250
+ ensureLocale(defaultLocale);
251
+
252
+ // 1. Đọc từ thư mục localesDir
253
+ if (i18nConfig.localesDir) {
254
+ const localesFullPath = path.isAbsolute(i18nConfig.localesDir)
255
+ ? i18nConfig.localesDir
256
+ : path.join(projectRoot, i18nConfig.localesDir);
257
+
258
+ if (fs.existsSync(localesFullPath)) {
259
+ const files = fs.readdirSync(localesFullPath);
260
+ for (const file of files) {
261
+ if (file.endsWith('.json')) {
262
+ const locale = path.basename(file, '.json');
263
+ ensureLocale(locale);
264
+ try {
265
+ const raw = fs.readFileSync(path.join(localesFullPath, file), 'utf8');
266
+ const parsed = JSON.parse(raw);
267
+ const flat = flattenObject(parsed);
268
+ Object.assign(catalog[locale], flat);
269
+ } catch (e) {
270
+ console.warn(`⚠️ [i18n] Failed to read locale file ${file}:`, e.message);
271
+ }
272
+ }
273
+ }
274
+ }
275
+ }
276
+
277
+ // 2. Đọc từ translations inline
278
+ if (i18nConfig.translations) {
279
+ for (const [loc, dict] of Object.entries(i18nConfig.translations)) {
280
+ ensureLocale(loc);
281
+ const flat = flattenObject(dict);
282
+ Object.assign(catalog[loc], flat);
283
+ }
284
+ }
285
+
286
+ // 3. Đọc từ từng widget nếu khai báo object inline: { vi: '...', en: '...' }
287
+ const widgets = Array.isArray(config.widgets) ? config.widgets : [];
288
+ for (const w of widgets) {
289
+ const key = w.key || 'main';
290
+
291
+ if (w.displayName && typeof w.displayName === 'object') {
292
+ const transKey = `widget.${key}.title`;
293
+ for (const [loc, val] of Object.entries(w.displayName)) {
294
+ ensureLocale(loc);
295
+ catalog[loc][transKey] = String(val);
296
+ }
297
+ w._resolvedDisplayNameKey = transKey;
298
+ }
299
+
300
+ if (w.description && typeof w.description === 'object') {
301
+ const descKey = `widget.${key}.desc`;
302
+ for (const [loc, val] of Object.entries(w.description)) {
303
+ ensureLocale(loc);
304
+ catalog[loc][descKey] = String(val);
305
+ }
306
+ w._resolvedDescriptionKey = descKey;
307
+ }
308
+ }
309
+
310
+ return { catalog, defaultLocale };
311
+ }
312
+
313
+ /**
314
+ * Xuất các file Localizable.strings và Localizable.xcstrings cho iOS Extension target
315
+ */
316
+ function writeI18nFiles(targetDir, catalog, defaultLocale) {
317
+ const locales = Object.keys(catalog);
318
+ if (locales.length === 0) return;
319
+
320
+ // 1. Tạo các thư mục {lang}.lproj/Localizable.strings
321
+ for (const loc of locales) {
322
+ const lprojDir = path.join(targetDir, `${loc}.lproj`);
323
+ if (!fs.existsSync(lprojDir)) {
324
+ fs.mkdirSync(lprojDir, { recursive: true });
325
+ }
326
+ const stringsPath = path.join(lprojDir, 'Localizable.strings');
327
+ const lines = [
328
+ '/*',
329
+ ' * Localizable.strings',
330
+ ' * Generated automatically by react-native-live-widgets. DO NOT EDIT DIRECTLY.',
331
+ ` * Language: ${loc}`,
332
+ ' */',
333
+ '',
334
+ ];
335
+
336
+ const entries = Object.entries(catalog[loc]);
337
+ for (const [key, value] of entries) {
338
+ const escapedKey = escapeSwiftString(key);
339
+ const escapedVal = escapeSwiftString(value);
340
+ lines.push(`"${escapedKey}" = "${escapedVal}";`);
341
+ }
342
+ lines.push('');
343
+ fs.writeFileSync(stringsPath, lines.join('\n'), 'utf8');
344
+ }
345
+
346
+ // 2. Tạo file String Catalog: Localizable.xcstrings (Chuẩn Apple hiện đại iOS 16+)
347
+ const allKeys = new Set();
348
+ for (const loc of locales) {
349
+ Object.keys(catalog[loc]).forEach((k) => allKeys.add(k));
350
+ }
351
+
352
+ const xcstringsData = {
353
+ sourceLanguage: defaultLocale,
354
+ strings: {},
355
+ version: '1.0',
356
+ };
357
+
358
+ for (const key of allKeys) {
359
+ const localizations = {};
360
+ for (const loc of locales) {
361
+ if (catalog[loc] && catalog[loc][key] !== undefined) {
362
+ localizations[loc] = {
363
+ stringUnit: {
364
+ state: 'translated',
365
+ value: catalog[loc][key],
366
+ },
367
+ };
368
+ }
369
+ }
370
+ xcstringsData.strings[key] = {
371
+ localizations,
372
+ };
373
+ }
374
+
375
+ const xcstringsPath = path.join(targetDir, 'Localizable.xcstrings');
376
+ fs.writeFileSync(xcstringsPath, JSON.stringify(xcstringsData, null, 2), 'utf8');
377
+
378
+ console.log(`🌐 Successfully generated iOS localizations (${locales.join(', ')})`);
379
+ console.log(` - String Catalog: ${path.basename(targetDir)}/Localizable.xcstrings`);
380
+ }
381
+
382
+ /**
383
+ * Chuyển đổi key sang tên tài nguyên Android hợp lệ:
384
+ * 'widgets.counter.title' -> 'widgets_counter_title'
385
+ */
386
+ function toAndroidStringName(key) {
387
+ if (!key) return 'rn_live_widget_str';
388
+ let clean = key
389
+ .toLowerCase()
390
+ .replace(/[^a-z0-9_]+/g, '_')
391
+ .replace(/^_+|_+$/g, '');
392
+ if (/^[0-9]/.test(clean)) {
393
+ clean = 'str_' + clean;
394
+ }
395
+ return clean;
396
+ }
397
+
398
+ /**
399
+ * Escape chuỗi đặc biệt cho Android XML
400
+ */
401
+ function escapeAndroidXmlString(str) {
402
+ if (!str) return '';
403
+ return str
404
+ .replace(/&/g, '&amp;')
405
+ .replace(/</g, '&lt;')
406
+ .replace(/>/g, '&gt;')
407
+ .replace(/"/g, '\\"')
408
+ .replace(/'/g, "\\'");
409
+ }
410
+
411
+ /**
412
+ * Tự động tạo và cập nhật các file strings.xml cho Android
413
+ * Thư mục: android/app/src/main/res/values/ (mặc định) và values-{lang}/ (các ngôn ngữ khác)
414
+ */
415
+ function writeAndroidI18nFiles(projectRoot, catalog, defaultLocale) {
416
+ const resDir = path.join(projectRoot, 'android', 'app', 'src', 'main', 'res');
417
+ if (!fs.existsSync(resDir)) {
418
+ return;
419
+ }
420
+
421
+ const locales = Object.keys(catalog);
422
+ if (locales.length === 0) return;
423
+
424
+ for (const loc of locales) {
425
+ // Với defaultLocale -> res/values/strings.xml
426
+ // Với các ngôn ngữ khác -> res/values-{loc}/strings.xml (ví dụ: values-vi, values-en, values-ja)
427
+ const folderName = loc === defaultLocale ? 'values' : `values-${loc}`;
428
+ const valuesDir = path.join(resDir, folderName);
429
+ if (!fs.existsSync(valuesDir)) {
430
+ fs.mkdirSync(valuesDir, { recursive: true });
431
+ }
432
+
433
+ const stringsXmlPath = path.join(valuesDir, 'strings.xml');
434
+ const existingStrings = new Map();
435
+
436
+ if (fs.existsSync(stringsXmlPath)) {
437
+ const existingContent = fs.readFileSync(stringsXmlPath, 'utf8');
438
+ const regex = /<string\s+name="([^"]+)">([\s\S]*?)<\/string>/g;
439
+ let match;
440
+ while ((match = regex.exec(existingContent)) !== null) {
441
+ existingStrings.set(match[1], match[2]);
442
+ }
443
+ }
444
+
445
+ // Merge các bản dịch vào file
446
+ const dict = catalog[loc] || {};
447
+ for (const [key, value] of Object.entries(dict)) {
448
+ const androidName = toAndroidStringName(key);
449
+ const escaped = escapeAndroidXmlString(value);
450
+ existingStrings.set(androidName, escaped);
451
+ }
452
+
453
+ const lines = [
454
+ '<?xml version="1.0" encoding="utf-8"?>',
455
+ '<resources>',
456
+ ];
457
+ for (const [name, val] of existingStrings.entries()) {
458
+ lines.push(` <string name="${name}">${val}</string>`);
459
+ }
460
+ lines.push('</resources>');
461
+ lines.push('');
462
+
463
+ fs.writeFileSync(stringsXmlPath, lines.join('\n'), 'utf8');
464
+ }
465
+
466
+ console.log(`🤖 Successfully synced Android localizations (${locales.join(', ')})`);
467
+ console.log(` - Directory: android/app/src/main/res/values-*/strings.xml`);
468
+ }
469
+
470
+ /**
471
+ * Sinh mã nguồn Swift từ cấu hình
472
+ */
473
+ function generateSwiftSource(config, catalog = {}, defaultLocale = 'vi') {
474
+ const bundleName = config.bundleName || 'LiveWidgetsBundle';
475
+ const enableLiveActivity = config.liveActivity !== false;
476
+ const enableControlWidgets = config.controlWidgets !== false;
477
+ const widgets = Array.isArray(config.widgets) ? config.widgets : [];
478
+
479
+ const defaultDict = catalog[defaultLocale] || {};
480
+
481
+ const processedWidgets = widgets.map((w, index) => {
482
+ const key = w.key || (index === 0 ? 'main' : `widget_${index}`);
483
+ let kind = w.kind;
484
+ if (!kind) {
485
+ const base = toPascalCase(key);
486
+ kind = base.endsWith('HomeScreenWidget') ? base : `${base}HomeScreenWidget`;
487
+ }
488
+
489
+ // Process displayName (i18n key or plain string)
490
+ let displayNameKey = w._resolvedDisplayNameKey || w.displayName || `Widget ${key}`;
491
+ if (typeof displayNameKey === 'object') {
492
+ displayNameKey = displayNameKey[defaultLocale] || Object.values(displayNameKey)[0] || `Widget ${key}`;
493
+ }
494
+
495
+ // Process description (i18n key or plain string)
496
+ let descriptionKey = w._resolvedDescriptionKey || w.description || '';
497
+ if (typeof descriptionKey === 'object') {
498
+ descriptionKey = descriptionKey[defaultLocale] || Object.values(descriptionKey)[0] || '';
499
+ }
500
+
501
+ const standbyMargins = Boolean(w.standbyMargins);
502
+
503
+ let supportedFamiliesCode = 'commonFamilies';
504
+ if (Array.isArray(w.supportedFamilies) && w.supportedFamilies.length > 0) {
505
+ const familiesList = w.supportedFamilies
506
+ .map((f) => `.${f.trim()}`)
507
+ .join(', ');
508
+ supportedFamiliesCode = `[${familiesList}]`;
509
+ }
510
+
511
+ // Lấy tiêu đề hiển thị cho comment code Swift
512
+ const commentTitle = defaultDict[displayNameKey] || displayNameKey;
513
+
514
+ return {
515
+ key,
516
+ kind,
517
+ displayNameKey: escapeSwiftString(displayNameKey),
518
+ descriptionKey: escapeSwiftString(descriptionKey),
519
+ commentTitle: escapeSwiftString(commentTitle),
520
+ supportedFamiliesCode,
521
+ standbyMargins,
522
+ };
523
+ });
524
+
525
+ const lines = [];
526
+
527
+ // 1. Header
528
+ lines.push('//');
529
+ lines.push('// LiveWidgetsBundle.swift');
530
+ lines.push('// Generated automatically by react-native-live-widgets. DO NOT EDIT DIRECTLY.');
531
+ lines.push('// Source config: widgets.config.ts');
532
+ lines.push('//');
533
+ lines.push('');
534
+ lines.push('import WidgetKit');
535
+ lines.push('import SwiftUI');
536
+ lines.push('#if canImport(react_native_live_widgets)');
537
+ lines.push('import react_native_live_widgets');
538
+ lines.push('#endif');
539
+ lines.push('');
540
+ lines.push('/// Bundle extension supporting both Live Activities (Dynamic Island / Lock Screen)');
541
+ lines.push('/// and Home Screen Widgets (iOS 16.1 -> iOS 17/18+)');
542
+ lines.push('@main');
543
+ lines.push(`struct ${bundleName}: WidgetBundle {`);
544
+ lines.push(' var body: some Widget {');
545
+
546
+ // Live Activity
547
+ if (enableLiveActivity) {
548
+ lines.push(' // 1. Live Activity & Dynamic Island (iOS 16.1+)');
549
+ lines.push(' if #available(iOS 16.1, *) {');
550
+ lines.push(' DynamicLiveActivityWidget()');
551
+ lines.push(' }');
552
+ lines.push('');
553
+ }
554
+
555
+ // Home Screen Widgets
556
+ if (processedWidgets.length > 0) {
557
+ lines.push(' // 2. Home Screen Widgets registered from TypeScript configuration');
558
+ for (const w of processedWidgets) {
559
+ lines.push(` ${w.kind}()`);
560
+ }
561
+ }
562
+
563
+ // Control Center Widgets (iOS 18+)
564
+ if (enableControlWidgets) {
565
+ lines.push('');
566
+ lines.push(' // 3. iOS 18+ Interactive Control Center Widgets');
567
+ lines.push(' if #available(iOS 18.0, *) {');
568
+ lines.push(' DynamicControlWidget()');
569
+ lines.push(' DynamicControlToggleWidget()');
570
+ lines.push(' }');
571
+ }
572
+
573
+ lines.push(' }');
574
+ lines.push('}');
575
+ lines.push('');
576
+
577
+ // 2. Định nghĩa từng Widget struct
578
+ processedWidgets.forEach((w, idx) => {
579
+ lines.push(`// ── ${idx + 1}. TIỆN ÍCH: ${w.commentTitle.toUpperCase()} (KEY: "${w.key}") ──`);
580
+ lines.push(`struct ${w.kind}: Widget {`);
581
+ lines.push(` let kind: String = "${w.kind}"`);
582
+ lines.push('');
583
+ lines.push(' var body: some WidgetConfiguration {');
584
+ lines.push(` StaticConfiguration(kind: kind, provider: DynamicWidgetProvider(widgetKey: "${w.key}")) { entry in`);
585
+ lines.push(' DynamicHomeScreenWidgetView(entry: entry)');
586
+ lines.push(' }');
587
+ lines.push(` .configurationDisplayName(LocalizedStringKey("${w.displayNameKey}"))`);
588
+ if (w.descriptionKey) {
589
+ lines.push(` .description(LocalizedStringKey("${w.descriptionKey}"))`);
590
+ }
591
+ lines.push(` .supportedFamilies(${w.supportedFamiliesCode})`);
592
+ if (w.standbyMargins) {
593
+ lines.push(' .applyStandByMargins()');
594
+ }
595
+ lines.push(' }');
596
+ lines.push('}');
597
+ lines.push('');
598
+ });
599
+
600
+ // 3. Helper commonFamilies
601
+ lines.push('private var commonFamilies: [WidgetFamily] {');
602
+ lines.push(' var list: [WidgetFamily] = [.systemSmall, .systemMedium, .systemLarge, .systemExtraLarge]');
603
+ lines.push(' if #available(iOS 16.0, *) {');
604
+ lines.push(' list.append(contentsOf: [.accessoryRectangular, .accessoryCircular, .accessoryInline])');
605
+ lines.push(' }');
606
+ lines.push(' return list');
607
+ lines.push('}');
608
+ lines.push('');
609
+
610
+ return lines.join('\n');
611
+ }
612
+
613
+ /**
614
+ * Tìm kiếm đường dẫn file LiveWidgetsBundle.swift trên dự án iOS
615
+ */
616
+ function findBundleSwiftPath(projectRoot) {
617
+ const iosDir = path.join(projectRoot, 'ios');
618
+ if (!fs.existsSync(iosDir)) {
619
+ return null;
620
+ }
621
+
622
+ // 1. Tìm file *Bundle.swift sẵn có
623
+ const entries = fs.readdirSync(iosDir, { withFileTypes: true });
624
+ for (const entry of entries) {
625
+ if (entry.isDirectory() && entry.name.toLowerCase().includes('widget')) {
626
+ const widgetDir = path.join(iosDir, entry.name);
627
+ const subEntries = fs.readdirSync(widgetDir);
628
+ for (const file of subEntries) {
629
+ if (file.endsWith('Bundle.swift')) {
630
+ return path.join(widgetDir, file);
631
+ }
632
+ }
633
+ }
634
+ }
635
+
636
+ // 2. Mặc định là ios/LiveWidgetsExtension/LiveWidgetsBundle.swift
637
+ const defaultDir = path.join(iosDir, 'LiveWidgetsExtension');
638
+ return path.join(defaultDir, 'LiveWidgetsBundle.swift');
639
+ }
640
+
641
+ /**
642
+ * Đảm bảo file Info.plist cho Widget Extension luôn tồn tại
643
+ */
644
+ function ensureExtensionInfoPlist(targetDir) {
645
+ const infoPlistPath = path.join(targetDir, 'Info.plist');
646
+ if (!fs.existsSync(infoPlistPath)) {
647
+ const defaultInfoPlist = `<?xml version="1.0" encoding="UTF-8"?>
648
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
649
+ <plist version="1.0">
650
+ <dict>
651
+ \t<key>CFBundleDevelopmentRegion</key>
652
+ \t<string>en</string>
653
+ \t<key>CFBundleDisplayName</key>
654
+ \t<string>${path.basename(targetDir)}</string>
655
+ \t<key>CFBundleExecutable</key>
656
+ \t<string>$(EXECUTABLE_NAME)</string>
657
+ \t<key>CFBundleIdentifier</key>
658
+ \t<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
659
+ \t<key>CFBundleInfoDictionaryVersion</key>
660
+ \t<string>6.0</string>
661
+ \t<key>CFBundleName</key>
662
+ \t<string>$(PRODUCT_NAME)</string>
663
+ \t<key>CFBundlePackageType</key>
664
+ \t<string>XPC!</string>
665
+ \t<key>CFBundleShortVersionString</key>
666
+ \t<string>1.0</string>
667
+ \t<key>CFBundleVersion</key>
668
+ \t<string>1</string>
669
+ \t<key>NSExtension</key>
670
+ \t<dict>
671
+ \t\t<key>NSExtensionPointIdentifier</key>
672
+ \t\t<string>com.apple.widgetkit-extension</string>
673
+ \t</dict>
674
+ \t<key>RCTNewArchEnabled</key>
675
+ \t<true/>
676
+ </dict>
677
+ </plist>
678
+ `;
679
+ fs.writeFileSync(infoPlistPath, defaultInfoPlist, 'utf8');
680
+ console.log(`🛡️ Ensured WidgetKit Extension Info.plist at: ${path.basename(targetDir)}/Info.plist`);
681
+ }
682
+ }
683
+
684
+ /**
685
+ * Thực thi lệnh Codegen
686
+ */
687
+ function runCodegen(projectRoot = process.cwd(), customConfigPath = null) {
688
+ console.log('\n⚙️ [react-native-live-widgets] Starting WidgetKit Swift & Android Codegen...');
689
+
690
+ // Sync SF Symbols from Apple system if available
691
+ try {
692
+ const symbolsScript = path.join(__dirname, '..', 'scripts', 'generate-sf-symbols.js');
693
+ if (fs.existsSync(symbolsScript)) {
694
+ const { generateSFSymbolsFile } = require(symbolsScript);
695
+ const targetGenerated = path.join(__dirname, '..', 'src', 'sf-symbols.generated.ts');
696
+ const count = generateSFSymbolsFile(targetGenerated);
697
+ if (count) {
698
+ console.log(`🍎 Synced ${count} SF Symbols from Apple system into TypeScript Auto-Complete.`);
699
+ }
700
+ }
701
+ } catch (_e) {}
702
+
703
+ // Sync Google Material Icons if available
704
+ try {
705
+ const materialScript = path.join(__dirname, '..', 'scripts', 'generate-material-icons.js');
706
+ if (fs.existsSync(materialScript)) {
707
+ const { generateMaterialIconsFile } = require(materialScript);
708
+ const targetGenerated = path.join(__dirname, '..', 'src', 'material-icons.generated.ts');
709
+ const count = generateMaterialIconsFile(targetGenerated);
710
+ if (count) {
711
+ console.log(`🤖 Synced ${count} Google Material Icons into TypeScript Auto-Complete.`);
712
+ }
713
+ }
714
+ } catch (_e) {}
715
+
716
+ const { config, configPath } = loadWidgetsConfig(projectRoot, customConfigPath);
717
+ const { catalog, defaultLocale } = buildI18nCatalog(projectRoot, config);
718
+
719
+ const bundleSwiftPath = findBundleSwiftPath(projectRoot);
720
+ if (bundleSwiftPath) {
721
+ const targetDir = path.dirname(bundleSwiftPath);
722
+ if (!fs.existsSync(targetDir)) {
723
+ fs.mkdirSync(targetDir, { recursive: true });
724
+ }
725
+
726
+ // Ensure extension Info.plist exists (auto-generate if missing)
727
+ ensureExtensionInfoPlist(targetDir);
728
+
729
+ // 1. Generate i18n Localizable if catalog exists
730
+ if (Object.keys(catalog).length > 0) {
731
+ writeI18nFiles(targetDir, catalog, defaultLocale);
732
+ }
733
+
734
+ // 2. Generate Swift source code
735
+ const swiftCode = generateSwiftSource(config, catalog, defaultLocale);
736
+ fs.writeFileSync(bundleSwiftPath, swiftCode, 'utf8');
737
+
738
+ console.log(`✅ Successfully generated Swift source bundle!`);
739
+ console.log(`📍 Destination: ${path.relative(projectRoot, bundleSwiftPath)}`);
740
+ console.log(`📊 Registered Widgets: ${(config.widgets || []).length}`);
741
+ if (config.widgets && config.widgets.length > 0) {
742
+ const defaultDict = catalog[defaultLocale] || {};
743
+ config.widgets.forEach((w, i) => {
744
+ const rawName = w.displayName;
745
+ const keyName = typeof rawName === 'object' ? rawName[defaultLocale] : rawName;
746
+ const resolved = defaultDict[keyName] || keyName;
747
+ console.log(` ${i + 1}. [${w.key || 'main'}] ${resolved} (${keyName})`);
748
+ });
749
+ }
750
+ } else {
751
+ console.log("ℹ️ Native iOS directory 'ios/' not found yet (will be generated upon 'npx expo prebuild').");
752
+ }
753
+
754
+ // Generate Android i18n if android/ exists
755
+ if (Object.keys(catalog).length > 0) {
756
+ writeAndroidI18nFiles(projectRoot, catalog, defaultLocale);
757
+ }
758
+
759
+ console.log('🎉 All set! No manual Swift editing required.\n');
760
+ return bundleSwiftPath;
761
+ }
762
+
763
+ if (require.main === module) {
764
+ const args = process.argv.slice(2);
765
+ let configArg = null;
766
+ for (let i = 0; i < args.length; i++) {
767
+ if (args[i] === '--config' && args[i + 1]) {
768
+ configArg = args[i + 1];
769
+ break;
770
+ }
771
+ }
772
+ try {
773
+ runCodegen(process.cwd(), configArg);
774
+ } catch (error) {
775
+ console.error(`\n❌ [Codegen Error]: ${error.message}\n`);
776
+ process.exit(1);
777
+ }
778
+ }
779
+
780
+ module.exports = {
781
+ runCodegen,
782
+ generateSwiftSource,
783
+ loadWidgetsConfig,
784
+ buildI18nCatalog,
785
+ flattenObject,
786
+ toAndroidStringName,
787
+ writeAndroidI18nFiles,
788
+ ensureExtensionInfoPlist,
789
+ };