react-native-live-widgets 1.1.1 → 1.2.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 (58) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +113 -10
  3. package/android/src/main/java/com/reactnativeliveactivity/bridge/LiveActivityModule.kt +5 -1
  4. package/android/src/main/java/com/reactnativeliveactivity/renderer/DynamicWidgetCanvasRenderer.kt +443 -46
  5. package/android/src/main/java/com/reactnativeliveactivity/storage/DynamicWidgetStateStore.kt +86 -24
  6. package/android/src/main/java/com/reactnativeliveactivity/widgets/DynamicHomeScreenWidgetProvider.kt +126 -56
  7. package/android/src/main/res/layout/rn_live_widget_hit_zone.xml +16 -0
  8. package/android/src/main/res/layout/rn_live_widget_host.xml +16 -87
  9. package/docs/GUIDE-EN.md +332 -7
  10. package/docs/GUIDE-VI.md +357 -7
  11. package/docs/index.html +1143 -227
  12. package/docs/llms-full.txt +46 -6
  13. package/docs/llms.txt +37 -7
  14. package/ios/Models/DynamicLayoutModels.swift +11 -1
  15. package/ios/Renderer/DynamicNodeView.swift +169 -14
  16. package/ios/Widgets/DynamicHomeScreenWidget.swift +7 -3
  17. package/lib/builder.d.ts.map +1 -1
  18. package/lib/builder.js +92 -28
  19. package/lib/builder.js.map +1 -1
  20. package/lib/dispatcher.d.ts +7 -0
  21. package/lib/dispatcher.d.ts.map +1 -1
  22. package/lib/dispatcher.js +23 -6
  23. package/lib/dispatcher.js.map +1 -1
  24. package/lib/hooks.d.ts +66 -0
  25. package/lib/hooks.d.ts.map +1 -0
  26. package/lib/hooks.js +171 -0
  27. package/lib/hooks.js.map +1 -0
  28. package/lib/index.d.ts +48 -8
  29. package/lib/index.d.ts.map +1 -1
  30. package/lib/index.js +216 -35
  31. package/lib/index.js.map +1 -1
  32. package/lib/ir.d.ts +15 -0
  33. package/lib/ir.d.ts.map +1 -0
  34. package/lib/ir.js +379 -0
  35. package/lib/ir.js.map +1 -0
  36. package/lib/jsx.d.ts +87 -0
  37. package/lib/jsx.d.ts.map +1 -0
  38. package/lib/jsx.js +243 -0
  39. package/lib/jsx.js.map +1 -0
  40. package/lib/preview.d.ts +31 -0
  41. package/lib/preview.d.ts.map +1 -0
  42. package/lib/preview.js +735 -0
  43. package/lib/preview.js.map +1 -0
  44. package/lib/types.d.ts +212 -12
  45. package/lib/types.d.ts.map +1 -1
  46. package/lib/types.js +2 -1
  47. package/lib/types.js.map +1 -1
  48. package/package.json +3 -1
  49. package/src/builder.ts +86 -21
  50. package/src/dispatcher.ts +17 -0
  51. package/src/hooks.ts +223 -0
  52. package/src/index.ts +202 -13
  53. package/src/ir.ts +430 -0
  54. package/src/jsx.tsx +326 -0
  55. package/src/preview.tsx +1043 -0
  56. package/src/react-ambient.d.ts +10 -0
  57. package/src/react-native-env.d.ts +44 -0
  58. package/src/types.ts +261 -13
@@ -0,0 +1,1043 @@
1
+ import React, { useEffect, useState } from 'react';
2
+ import {
3
+ View,
4
+ Text as RNText,
5
+ Image as RNImage,
6
+ TouchableOpacity,
7
+ StyleSheet,
8
+ ViewStyle,
9
+ TextStyle as RNTextStyle,
10
+ } from 'react-native';
11
+ import {
12
+ LayoutNode,
13
+ WidgetSinglePageConfig,
14
+ VStackNode,
15
+ HStackNode,
16
+ TextNode,
17
+ ButtonNode,
18
+ BadgeNode,
19
+ ProgressNode,
20
+ TimerNode,
21
+ ImageNode,
22
+ } from './types';
23
+ import { renderToWidget, extractPropsAndStyle } from './jsx';
24
+ import { actionHandlers, globalActionHandlers } from './dispatcher';
25
+
26
+ export type WidgetPreviewSize = 'small' | 'medium' | 'large' | 'lockScreen' | 'dynamicIsland';
27
+
28
+ export interface WidgetPreviewProps {
29
+ /**
30
+ * Kích thước tiện ích cần xem trước:
31
+ * - 'small' (158 × 158 dp)
32
+ * - 'medium' (338 × 158 dp)
33
+ * - 'large' (338 × 354 dp)
34
+ * - 'lockScreen' (350 × 80 dp)
35
+ * - 'dynamicIsland' (350 × 160 dp)
36
+ * Mặc định là 'medium'.
37
+ */
38
+ size?: WidgetPreviewSize;
39
+ /** Cây LayoutNode hoặc đối tượng chứa { small, medium, large } */
40
+ layout?: LayoutNode | WidgetSinglePageConfig;
41
+ /** Cú pháp JSX trực tiếp truyền vào bên trong thẻ `<WidgetPreview>` */
42
+ children?: React.ReactNode;
43
+ /** Bắt sự kiện khi người dùng bấm vào các nút tương tác trên Widget xem trước */
44
+ onAction?: (actionId: string) => void;
45
+ /** Hiển thị nhãn kích thước chuẩn ở góc (mặc định true) */
46
+ showBadge?: boolean;
47
+ /** Cho phép bấm thanh tab nhỏ ở trên để chuyển nhanh qua lại giữa các kích thước (mặc định false) */
48
+ interactiveSizeSwitch?: boolean;
49
+ /** Style tùy biến cho wrapper bên ngoài */
50
+ style?: ViewStyle;
51
+ }
52
+
53
+ const SIZE_DIMENSIONS: Record<WidgetPreviewSize, { width: number; height: number; label: string }> = {
54
+ small: { width: 158, height: 158, label: 'Small • 158×158' },
55
+ medium: { width: 338, height: 158, label: 'Medium • 338×158' },
56
+ large: { width: 338, height: 354, label: 'Large • 338×354' },
57
+ lockScreen: { width: 350, height: 80, label: 'Lock Screen • 350×80' },
58
+ dynamicIsland: { width: 350, height: 160, label: 'Dynamic Island' },
59
+ };
60
+
61
+ function parseDynamicColor(c: any, mode: 'light' | 'dark' | 'tinted' = 'dark'): string | undefined {
62
+ if (!c) return undefined;
63
+ if (typeof c === 'string') return c;
64
+ if (typeof c === 'object') {
65
+ if (mode === 'tinted' && c.tinted) return c.tinted;
66
+ if (mode === 'light' && c.light) return c.light;
67
+ return c.dark || c.light || c.tinted;
68
+ }
69
+ return undefined;
70
+ }
71
+
72
+ function extractShadowStyle(p: any): ViewStyle {
73
+ if (!p) return {};
74
+ const shadowColor = parseDynamicColor(p.shadowColor);
75
+ if (!shadowColor) return {};
76
+ const rad = p.shadowRadius ?? 4;
77
+ return {
78
+ shadowColor,
79
+ shadowOffset: p.shadowOffset
80
+ ? { width: p.shadowOffset.x ?? 0, height: p.shadowOffset.y ?? 2 }
81
+ : { width: 0, height: 2 },
82
+ shadowOpacity: p.shadowOpacity ?? 0.35,
83
+ shadowRadius: rad,
84
+ elevation: Math.min(8, Math.max(1, Math.round(rad))),
85
+ };
86
+ }
87
+
88
+ /**
89
+ * 📱 Bộ Component xem trước tiện ích trực tiếp trong ứng dụng React Native (In-App Widget Preview).
90
+ * Cho phép lập trình viên và người dùng trải nghiệm giao diện & bấm thử tương tác của Widget
91
+ * ngay trong màn hình App mà không cần ra ngoài Home Screen.
92
+ *
93
+ * Cách dùng 1 (Truyền layout prop):
94
+ * ```tsx
95
+ * <WidgetPreview size="medium" layout={myLayout} onAction={(act) => alert(act)} />
96
+ * ```
97
+ *
98
+ * Cách dùng 2 (Truyền JSX children trực tiếp):
99
+ * ```tsx
100
+ * <WidgetPreview size="medium">
101
+ * <VStack padding={16} backgroundColor="#0F172A" borderRadius={16}>
102
+ * <HStack justifyContent="spaceBetween">
103
+ * <Text fontSize={14} fontWeight="bold" color="#FFFFFF">Vào ca sáng</Text>
104
+ * <Badge text="07:54" backgroundColor="#064E3B" textColor="#6EE7B7" />
105
+ * </HStack>
106
+ * <Button title="Làm mới" actionId="refresh" />
107
+ * </VStack>
108
+ * </WidgetPreview>
109
+ * ```
110
+ */
111
+ type PreviewSyncVars = {
112
+ _lastSyncTime: string;
113
+ id: string;
114
+ title: string;
115
+ };
116
+
117
+ export const WidgetPreview: React.FC<WidgetPreviewProps> = ({
118
+ size: initialSize = 'medium',
119
+ layout,
120
+ children,
121
+ onAction,
122
+ showBadge = true,
123
+ interactiveSizeSwitch = false,
124
+ style,
125
+ }: WidgetPreviewProps) => {
126
+ const [activeSize, setActiveSize] = useState<WidgetPreviewSize>(initialSize);
127
+
128
+ const pageConfigObj =
129
+ !children && layout && typeof layout === 'object' && (layout as any).pages
130
+ ? (layout as any)
131
+ : null;
132
+ const pageOrder: string[] = pageConfigObj
133
+ ? Array.isArray(pageConfigObj.pageOrder) && pageConfigObj.pageOrder.length > 0
134
+ ? pageConfigObj.pageOrder
135
+ : Object.keys(pageConfigObj.pages)
136
+ : [];
137
+ const defaultPage: string = pageConfigObj
138
+ ? pageConfigObj.initialPage || pageOrder[0] || ''
139
+ : '';
140
+
141
+ const [activePage, setActivePage] = useState<string>(defaultPage);
142
+ const [syncVars, setSyncVars] = useState<PreviewSyncVars>(() => ({
143
+ _lastSyncTime: new Date().toLocaleTimeString('en-GB', { hour12: false }),
144
+ id: '2026',
145
+ title: 'Hoàn thành kế hoạch quý 4',
146
+ }));
147
+
148
+ useEffect(() => {
149
+ if (defaultPage) {
150
+ setActivePage((prev) => (pageConfigObj?.pages?.[prev] ? prev : defaultPage));
151
+ }
152
+ }, [defaultPage, pageConfigObj]);
153
+
154
+ // Trích xuất LayoutNode từ props hoặc JSX children
155
+ let rootNode: LayoutNode | null = null;
156
+ let rawTarget: any = null;
157
+ const currentPageKey =
158
+ pageConfigObj && pageConfigObj.pages
159
+ ? pageConfigObj.pages[activePage]
160
+ ? activePage
161
+ : defaultPage
162
+ : '';
163
+
164
+ if (children) {
165
+ rawTarget = children;
166
+ } else if (layout) {
167
+ if (React.isValidElement(layout) || (layout as any)?.$$typeof) {
168
+ rawTarget = layout;
169
+ } else if ((layout as any).type && typeof (layout as any).type === 'string' && (layout as any).props !== undefined) {
170
+ rawTarget = layout;
171
+ } else if (pageConfigObj && currentPageKey) {
172
+ const pageConfig = pageConfigObj.pages[currentPageKey] || {};
173
+ rawTarget =
174
+ pageConfig[activeSize] ||
175
+ pageConfig.medium ||
176
+ pageConfig.large ||
177
+ pageConfig.small ||
178
+ pageConfig.accessoryRectangular ||
179
+ null;
180
+ } else {
181
+ const pageConfig = layout as WidgetSinglePageConfig;
182
+ rawTarget =
183
+ (pageConfig as any)[activeSize] ||
184
+ pageConfig.medium ||
185
+ pageConfig.large ||
186
+ pageConfig.small ||
187
+ pageConfig.accessoryRectangular ||
188
+ null;
189
+ }
190
+ }
191
+
192
+ const handlePreviewAction = (actionId: string) => {
193
+ if (actionId.startsWith('page:') && pageConfigObj && pageOrder.length > 0) {
194
+ const target = actionId.slice('page:'.length);
195
+ if (target === 'next') {
196
+ const idx = pageOrder.indexOf(currentPageKey);
197
+ const nextPage = idx >= 0 ? pageOrder[(idx + 1) % pageOrder.length] : pageOrder[0];
198
+ setActivePage(nextPage);
199
+ } else if (target === 'prev') {
200
+ const idx = pageOrder.indexOf(currentPageKey);
201
+ const prevPage =
202
+ idx >= 0 ? pageOrder[(idx - 1 + pageOrder.length) % pageOrder.length] : pageOrder[0];
203
+ setActivePage(prevPage);
204
+ } else if (pageConfigObj.pages[target]) {
205
+ setActivePage(target);
206
+ }
207
+ } else if (actionId === 'refresh' || actionId.startsWith('refresh:')) {
208
+ const nowTime = new Date().toLocaleTimeString('en-GB', { hour12: false });
209
+ const sampleNotes = [
210
+ 'Đồng bộ báo cáo tiến độ OKRs',
211
+ 'Kiểm tra chấm công ca hành chính',
212
+ 'Rà soát task Sprint tuần này',
213
+ 'Cập nhật số liệu Realtime API',
214
+ ];
215
+ const nextId = String(Math.floor(Math.random() * 90) + 10);
216
+ setSyncVars({
217
+ _lastSyncTime: nowTime,
218
+ id: nextId,
219
+ title: sampleNotes[Number(nextId) % sampleNotes.length],
220
+ });
221
+ }
222
+ if (onAction) {
223
+ onAction(actionId);
224
+ }
225
+ };
226
+
227
+ if (rawTarget) {
228
+ if (React.isValidElement(rawTarget) || (rawTarget as any)?.$$typeof || typeof (rawTarget as any)?.type === 'function') {
229
+ rootNode = renderToWidget(rawTarget);
230
+ } else {
231
+ rootNode = rawTarget as LayoutNode;
232
+ }
233
+ }
234
+
235
+ const dim =
236
+ SIZE_DIMENSIONS[(activeSize as WidgetPreviewSize) || 'medium'] || SIZE_DIMENSIONS.medium;
237
+
238
+ return (
239
+ <View style={[styles.container, style]}>
240
+ {interactiveSizeSwitch && (
241
+ <View style={styles.tabBar}>
242
+ {(['small', 'medium', 'large'] as WidgetPreviewSize[]).map((s) => (
243
+ <TouchableOpacity
244
+ key={s}
245
+ onPress={() => setActiveSize(s)}
246
+ style={[styles.tabItem, activeSize === s && styles.tabItemActive]}
247
+ >
248
+ <RNText style={[styles.tabText, activeSize === s && styles.tabTextActive]}>
249
+ {s.toUpperCase()}
250
+ </RNText>
251
+ </TouchableOpacity>
252
+ ))}
253
+ </View>
254
+ )}
255
+
256
+ {showBadge && (
257
+ <View style={styles.badgeRow}>
258
+ <View style={styles.specBadge}>
259
+ <RNText style={styles.specBadgeText}>{dim.label}</RNText>
260
+ </View>
261
+ </View>
262
+ )}
263
+
264
+ {/* Khung mô phỏng Widget iOS Continuous Curve */}
265
+ <View
266
+ style={[
267
+ styles.widgetFrame,
268
+ {
269
+ width: dim.width,
270
+ height: dim.height,
271
+ },
272
+ ]}
273
+ >
274
+ {rootNode ? (
275
+ renderPreviewNode(rootNode, handlePreviewAction, true, 'column', syncVars)
276
+ ) : (
277
+ <View style={styles.emptyContainer}>
278
+ <RNText style={styles.emptyText}>Chưa có cấu hình layout cho kích thước {activeSize}</RNText>
279
+ </View>
280
+ )}
281
+ </View>
282
+ </View>
283
+ );
284
+ };
285
+
286
+ /** Alias tương thích */
287
+ export const VoltraWidgetPreview = WidgetPreview;
288
+
289
+ // ─── RECURSIVE NODE RENDERER ─────────────────────────────────────────────────
290
+
291
+ const PreviewToggleItem: React.FC<{
292
+ node: any;
293
+ onAction?: (actionId: string) => void;
294
+ }> = ({ node, onAction }) => {
295
+ const p = node.props || {};
296
+ const [isChecked, setIsChecked] = useState<boolean>(!!p.checked || !!p.isChecked);
297
+ const tint = parseDynamicColor(p.tintColor) || '#38BDF8';
298
+ const isSwitch = p.style === 'switch';
299
+
300
+ const handlePress = () => {
301
+ const nextVal = !isChecked;
302
+ setIsChecked(nextVal);
303
+ if (p.actionId) {
304
+ if (onAction) {
305
+ onAction(p.actionId);
306
+ }
307
+ const registered = actionHandlers.get(p.actionId);
308
+ if (registered) {
309
+ try {
310
+ registered({ actionId: p.actionId, isChecked: nextVal });
311
+ } catch (e) {
312
+ console.warn(`[WidgetPreview] Action '${p.actionId}' error:`, e);
313
+ }
314
+ }
315
+ for (const globalHandler of globalActionHandlers) {
316
+ try {
317
+ globalHandler(p.actionId, { isChecked: nextVal });
318
+ } catch (e) {
319
+ console.warn(`[WidgetPreview] Global action handler error:`, e);
320
+ }
321
+ }
322
+ }
323
+ };
324
+
325
+ return (
326
+ <TouchableOpacity
327
+ accessible={p.accessible !== false}
328
+ accessibilityLabel={p.accessibilityLabel || p.label}
329
+ accessibilityHint={p.accessibilityHint}
330
+ accessibilityRole="switch"
331
+ accessibilityValue={{ text: isChecked ? 'Đã chọn' : 'Chưa chọn' }}
332
+ activeOpacity={0.7}
333
+ onPress={handlePress}
334
+ style={{
335
+ flexDirection: 'row',
336
+ alignItems: 'center',
337
+ gap: 8,
338
+ paddingVertical: 6,
339
+ paddingHorizontal: 2,
340
+ width: '100%',
341
+ alignSelf: 'stretch',
342
+ }}
343
+ >
344
+ {isSwitch ? (
345
+ <View
346
+ style={{
347
+ width: 34,
348
+ height: 20,
349
+ borderRadius: 10,
350
+ backgroundColor: isChecked ? tint : '#475569',
351
+ justifyContent: 'center',
352
+ paddingHorizontal: 3,
353
+ }}
354
+ >
355
+ <View
356
+ style={{
357
+ width: 14,
358
+ height: 14,
359
+ borderRadius: 7,
360
+ backgroundColor: '#FFFFFF',
361
+ alignSelf: isChecked ? 'flex-end' : 'flex-start',
362
+ }}
363
+ />
364
+ </View>
365
+ ) : (
366
+ <View
367
+ style={{
368
+ width: 18,
369
+ height: 18,
370
+ borderRadius: 4,
371
+ borderWidth: 1.5,
372
+ borderColor: isChecked ? tint : '#64748B',
373
+ backgroundColor: isChecked ? tint : 'transparent',
374
+ alignItems: 'center',
375
+ justifyContent: 'center',
376
+ }}
377
+ >
378
+ {isChecked && (
379
+ <RNText style={{ color: '#FFFFFF', fontSize: 11, fontWeight: 'bold' }}>✓</RNText>
380
+ )}
381
+ </View>
382
+ )}
383
+ <RNText
384
+ style={{
385
+ flex: 1,
386
+ color:
387
+ isChecked && p.strikethroughOnCheck
388
+ ? '#64748B'
389
+ : parseDynamicColor(p.textColor) || '#F8FAFC',
390
+ fontSize: p.fontSize ?? 13,
391
+ textDecorationLine:
392
+ isChecked && p.strikethroughOnCheck ? 'line-through' : 'none',
393
+ }}
394
+ >
395
+ {p.label}
396
+ </RNText>
397
+ </TouchableOpacity>
398
+ );
399
+ };
400
+
401
+ const PreviewTimerText: React.FC<{
402
+ nodeProps: any;
403
+ parentDirection: 'row' | 'column';
404
+ }> = ({ nodeProps: p, parentDirection }) => {
405
+ const formatRemaining = () => {
406
+ const target = Number(p.targetTimestamp ?? 0);
407
+ if (!target) return '00:00';
408
+ const diff = Math.max(0, Math.round(Math.abs(target - Date.now() / 1000)));
409
+ const hrs = Math.floor(diff / 3600);
410
+ const mins = Math.floor((diff % 3600) / 60);
411
+ const secs = diff % 60;
412
+ const pad = (n: number) => (n < 10 ? `0${n}` : `${n}`);
413
+ return hrs > 0 ? `${hrs}:${pad(mins)}:${pad(secs)}` : `${pad(mins)}:${pad(secs)}`;
414
+ };
415
+
416
+ const [display, setDisplay] = useState<string>(formatRemaining);
417
+
418
+ useEffect(() => {
419
+ setDisplay(formatRemaining());
420
+ const id = setInterval(() => {
421
+ setDisplay(formatRemaining());
422
+ }, 1000);
423
+ return () => clearInterval(id);
424
+ }, [p.targetTimestamp, p.mode]);
425
+
426
+ return (
427
+ <RNText
428
+ style={[
429
+ { color: parseDynamicColor(p.color) || '#2563EB', fontSize: p.fontSize ?? 14, fontWeight: 'bold' },
430
+ parentDirection === 'row' ? { flexShrink: 0 } : undefined,
431
+ ]}
432
+ >
433
+ {p.prefix || ''}{display}{p.suffix || ''}
434
+ </RNText>
435
+ );
436
+ };
437
+
438
+ function renderPreviewNode(
439
+ node: any,
440
+ onAction?: (actionId: string) => void,
441
+ isRoot: boolean = false,
442
+ parentDirection: 'row' | 'column' = 'column',
443
+ syncVars?: PreviewSyncVars
444
+ ): React.ReactNode {
445
+ if (!node) return null;
446
+
447
+ if (React.isValidElement(node) || (node as any)?.$$typeof || typeof (node as any)?.type === 'function') {
448
+ const converted = renderToWidget(node);
449
+ if (!converted) return null;
450
+ return renderPreviewNode(converted, onAction, isRoot, parentDirection, syncVars);
451
+ }
452
+
453
+ switch (node.type) {
454
+ case 'VStack': {
455
+ const vnode = node as VStackNode;
456
+ const p = extractPropsAndStyle(vnode.props);
457
+ const bg = p.gradient?.colors?.[0]
458
+ ? parseDynamicColor(p.gradient.colors[0])
459
+ : parseDynamicColor(p.backgroundColor) || 'transparent';
460
+
461
+ const containerStyle: ViewStyle = {
462
+ flexDirection: 'column',
463
+ padding: p.padding ?? (p.paddingHorizontal || p.paddingVertical ? undefined : 0),
464
+ paddingHorizontal: p.paddingHorizontal,
465
+ paddingVertical: p.paddingVertical,
466
+ backgroundColor: bg,
467
+ borderRadius: p.borderRadius ?? p.cornerRadius ?? 0,
468
+ borderWidth: p.borderWidth,
469
+ borderColor: parseDynamicColor(p.borderColor),
470
+ borderStyle: p.borderStyle || 'solid',
471
+ rowGap: p.spacing ?? 0,
472
+ alignItems:
473
+ p.alignment === 'center'
474
+ ? 'center'
475
+ : p.alignment === 'trailing' || p.alignment === 'end'
476
+ ? 'flex-end'
477
+ : 'flex-start',
478
+ justifyContent:
479
+ p.justifyContent === 'center'
480
+ ? 'center'
481
+ : p.justifyContent === 'spaceBetween'
482
+ ? 'space-between'
483
+ : p.justifyContent === 'spaceAround'
484
+ ? 'space-around'
485
+ : p.justifyContent === 'spaceEvenly'
486
+ ? 'space-evenly'
487
+ : p.justifyContent === 'flexEnd'
488
+ ? 'flex-end'
489
+ : 'flex-start',
490
+ ...extractShadowStyle(p),
491
+ };
492
+
493
+ if (isRoot) {
494
+ containerStyle.width = '100%';
495
+ containerStyle.height = '100%';
496
+ containerStyle.flex = 1;
497
+ } else if (parentDirection === 'row') {
498
+ if (p.flex !== undefined) {
499
+ containerStyle.flex = p.flex;
500
+ }
501
+ } else {
502
+ containerStyle.alignSelf = 'stretch';
503
+ }
504
+
505
+ return (
506
+ <View style={containerStyle}>
507
+ {vnode.children?.map((child, idx) => (
508
+ <React.Fragment key={idx}>
509
+ {renderPreviewNode(child, onAction, false, 'column', syncVars)}
510
+ </React.Fragment>
511
+ ))}
512
+ </View>
513
+ );
514
+ }
515
+
516
+ case 'HStack': {
517
+ const hnode = node as HStackNode;
518
+ const p = extractPropsAndStyle(hnode.props);
519
+ const isRtl = p.direction === 'rtl' || p.isRTL;
520
+ const bg = p.gradient?.colors?.[0]
521
+ ? parseDynamicColor(p.gradient.colors[0])
522
+ : parseDynamicColor(p.backgroundColor) || 'transparent';
523
+
524
+ const containerStyle: ViewStyle = {
525
+ flexDirection: isRtl ? 'row-reverse' : 'row',
526
+ padding: p.padding,
527
+ paddingHorizontal: p.paddingHorizontal,
528
+ paddingVertical: p.paddingVertical,
529
+ backgroundColor: bg,
530
+ borderRadius: p.borderRadius ?? p.cornerRadius ?? 0,
531
+ borderWidth: p.borderWidth,
532
+ borderColor: parseDynamicColor(p.borderColor),
533
+ borderStyle: p.borderStyle || 'solid',
534
+ columnGap: p.spacing ?? 0,
535
+ alignItems:
536
+ p.alignment === 'center'
537
+ ? 'center'
538
+ : p.alignment === 'trailing' || p.alignment === 'bottom'
539
+ ? 'flex-end'
540
+ : p.alignment === 'top'
541
+ ? 'flex-start'
542
+ : 'center',
543
+ justifyContent:
544
+ p.justifyContent === 'center'
545
+ ? 'center'
546
+ : p.justifyContent === 'spaceBetween'
547
+ ? 'space-between'
548
+ : p.justifyContent === 'spaceAround'
549
+ ? 'space-around'
550
+ : p.justifyContent === 'spaceEvenly'
551
+ ? 'space-evenly'
552
+ : p.justifyContent === 'flexEnd'
553
+ ? 'flex-end'
554
+ : 'flex-start',
555
+ ...extractShadowStyle(p),
556
+ };
557
+
558
+ if (isRoot) {
559
+ containerStyle.width = '100%';
560
+ containerStyle.height = '100%';
561
+ } else if (parentDirection === 'column') {
562
+ containerStyle.alignSelf = 'stretch';
563
+ } else if (p.flex !== undefined) {
564
+ containerStyle.flex = p.flex;
565
+ }
566
+
567
+ return (
568
+ <View style={containerStyle}>
569
+ {hnode.children?.map((child, idx) => (
570
+ <React.Fragment key={idx}>
571
+ {renderPreviewNode(child, onAction, false, 'row', syncVars)}
572
+ </React.Fragment>
573
+ ))}
574
+ </View>
575
+ );
576
+ }
577
+
578
+ case 'ZStack': {
579
+ const znode = node as any;
580
+ const p = extractPropsAndStyle(znode.props);
581
+ return (
582
+ <View
583
+ style={{
584
+ position: 'relative',
585
+ width: isRoot ? '100%' : undefined,
586
+ height: isRoot ? '100%' : undefined,
587
+ alignSelf: isRoot ? undefined : 'stretch',
588
+ alignItems: 'center',
589
+ justifyContent: 'center',
590
+ backgroundColor: parseDynamicColor(p.backgroundColor) || 'transparent',
591
+ borderRadius: p.borderRadius ?? p.cornerRadius ?? 0,
592
+ }}
593
+ >
594
+ {znode.children?.map((child: any, idx: number) => (
595
+ <View
596
+ key={idx}
597
+ style={
598
+ idx === 0
599
+ ? { width: '100%', height: '100%' }
600
+ : { ...StyleSheet.absoluteFillObject, alignItems: 'center', justifyContent: 'center' }
601
+ }
602
+ >
603
+ {renderPreviewNode(child, onAction, false, parentDirection, syncVars)}
604
+ </View>
605
+ ))}
606
+ </View>
607
+ );
608
+ }
609
+
610
+ case 'Grid': {
611
+ const gnode = node as any;
612
+ const p = extractPropsAndStyle(gnode.props);
613
+ const cols = p.columns ?? 2;
614
+ return (
615
+ <View
616
+ style={{
617
+ flexDirection: 'row',
618
+ flexWrap: 'wrap',
619
+ gap: p.spacing ?? 6,
620
+ width: '100%',
621
+ alignSelf: 'stretch',
622
+ }}
623
+ >
624
+ {gnode.children?.map((child: any, idx: number) => (
625
+ <View key={idx} style={{ flexBasis: `${Math.floor(100 / cols) - 3}%` }}>
626
+ {renderPreviewNode(child, onAction, false, 'column', syncVars)}
627
+ </View>
628
+ ))}
629
+ </View>
630
+ );
631
+ }
632
+
633
+ case 'Text': {
634
+ const tnode = node as TextNode;
635
+ const p = extractPropsAndStyle(tnode.props);
636
+ const isRtl = p.direction === 'rtl' || p.isRTL;
637
+ const shadowColor = parseDynamicColor(p.shadowColor);
638
+
639
+ const rawText = String(p.text ?? '');
640
+ const resolvedText = syncVars
641
+ ? rawText
642
+ .replace(/\{\{_lastSyncTime\}\}/g, syncVars._lastSyncTime)
643
+ .replace(/\{\{id\}\}/g, syncVars.id)
644
+ .replace(/\{\{title\}\}/g, syncVars.title)
645
+ : rawText;
646
+ const isRedacted = Boolean(p.redacted);
647
+
648
+ const textStyle: RNTextStyle = {
649
+ color: parseDynamicColor(p.color) || '#FFFFFF',
650
+ fontSize: p.fontSize ?? 14,
651
+ fontWeight:
652
+ p.fontWeight === 'bold' || p.fontWeight === 'heavy'
653
+ ? 'bold'
654
+ : p.fontWeight === 'semibold'
655
+ ? '600'
656
+ : p.fontWeight === 'medium'
657
+ ? '500'
658
+ : 'normal',
659
+ fontFamily: p.fontDesign === 'monospaced' ? 'monospace' : undefined,
660
+ textAlign: p.textAlign ?? (isRtl ? 'right' : 'left'),
661
+ lineHeight: p.lineHeight,
662
+ letterSpacing: p.letterSpacing,
663
+ opacity: isRedacted ? 0.45 : undefined,
664
+ textShadowColor: shadowColor,
665
+ textShadowOffset: p.shadowOffset
666
+ ? { width: p.shadowOffset.x ?? 0, height: p.shadowOffset.y ?? 1 }
667
+ : undefined,
668
+ textShadowRadius: p.shadowRadius,
669
+ };
670
+ return (
671
+ <RNText
672
+ accessible={p.accessible !== false}
673
+ accessibilityLabel={p.accessibilityLabel || resolvedText}
674
+ accessibilityHint={p.accessibilityHint}
675
+ accessibilityRole={p.accessibilityRole as any}
676
+ numberOfLines={p.numberOfLines}
677
+ style={[
678
+ textStyle,
679
+ parentDirection === 'row' ? { flexShrink: 1 } : undefined,
680
+ ]}
681
+ >
682
+ {isRedacted ? '••••••••' : resolvedText}
683
+ </RNText>
684
+ );
685
+ }
686
+
687
+ case 'Button': {
688
+ const bnode = node as ButtonNode;
689
+ const p = bnode.props;
690
+ const bg = p.gradient?.colors?.[0]
691
+ ? parseDynamicColor(p.gradient.colors[0])
692
+ : parseDynamicColor(p.backgroundColor) || '#2563EB';
693
+
694
+ const btnStyle: ViewStyle = {
695
+ backgroundColor: bg,
696
+ borderRadius: p.borderRadius ?? p.cornerRadius ?? 8,
697
+ borderWidth: p.borderWidth,
698
+ borderColor: parseDynamicColor(p.borderColor),
699
+ borderStyle: p.borderStyle || 'solid',
700
+ paddingHorizontal: p.paddingHorizontal ?? p.padding ?? 12,
701
+ paddingVertical: p.paddingVertical ?? p.padding ?? 6,
702
+ alignItems: 'center',
703
+ justifyContent: 'center',
704
+ alignSelf: p.fullWidth ? 'stretch' : 'auto',
705
+ ...(p.fullWidth ? (parentDirection === 'row' ? { flex: 1 } : { width: '100%' }) : {}),
706
+ ...extractShadowStyle(p),
707
+ };
708
+ const textStyle: RNTextStyle = {
709
+ color: parseDynamicColor(p.textColor) || '#FFFFFF',
710
+ fontSize: p.fontSize ?? 12,
711
+ fontWeight: (p.fontWeight as any) ?? '600',
712
+ fontFamily: p.fontDesign === 'monospaced' ? 'monospace' : undefined,
713
+ };
714
+
715
+ return (
716
+ <TouchableOpacity
717
+ accessible={p.accessible !== false}
718
+ accessibilityLabel={p.accessibilityLabel || p.title}
719
+ accessibilityHint={p.accessibilityHint}
720
+ accessibilityRole="button"
721
+ activeOpacity={0.7}
722
+ onPress={() => {
723
+ if (p.actionId) {
724
+ if (onAction) {
725
+ onAction(p.actionId);
726
+ }
727
+ const registered = actionHandlers.get(p.actionId);
728
+ if (registered) {
729
+ try {
730
+ registered({ actionId: p.actionId });
731
+ } catch (e) {
732
+ console.warn(`[WidgetPreview] Action '${p.actionId}' error:`, e);
733
+ }
734
+ }
735
+ for (const globalHandler of globalActionHandlers) {
736
+ try {
737
+ globalHandler(p.actionId);
738
+ } catch (e) {
739
+ console.warn(`[WidgetPreview] Global action handler error:`, e);
740
+ }
741
+ }
742
+ }
743
+ }}
744
+ style={btnStyle}
745
+ >
746
+ <RNText numberOfLines={1} style={textStyle}>
747
+ {p.title}
748
+ </RNText>
749
+ </TouchableOpacity>
750
+ );
751
+ }
752
+
753
+ case 'Badge': {
754
+ const bnode = node as BadgeNode;
755
+ const p = bnode.props;
756
+ return (
757
+ <View
758
+ style={{
759
+ backgroundColor: parseDynamicColor(p.backgroundColor) || '#064E3B',
760
+ borderRadius: p.borderRadius ?? p.cornerRadius ?? 6,
761
+ paddingHorizontal: p.paddingHorizontal ?? 6,
762
+ paddingVertical: p.paddingVertical ?? 2,
763
+ flexShrink: 0,
764
+ alignSelf: 'center',
765
+ }}
766
+ >
767
+ <RNText
768
+ numberOfLines={1}
769
+ style={{
770
+ color: parseDynamicColor(p.textColor) || '#6EE7B7',
771
+ fontSize: p.fontSize ?? 10,
772
+ fontWeight: '600',
773
+ }}
774
+ >
775
+ {p.text}
776
+ </RNText>
777
+ </View>
778
+ );
779
+ }
780
+
781
+ case 'Progress': {
782
+ const pnode = node as ProgressNode;
783
+ const p = pnode.props || {};
784
+ const val = Math.max(0, Math.min(1, p.value ?? 0.5));
785
+ const height = p.height ?? 6;
786
+ const tint = parseDynamicColor(p.tintColor) || '#2563EB';
787
+ const track = parseDynamicColor(p.trackColor) || '#334155';
788
+
789
+ if (p.style === 'segmented' && (p.segments ?? 4) > 1) {
790
+ const segs = p.segments ?? 4;
791
+ const filled = Math.round(val * segs);
792
+ return (
793
+ <View style={{ flexDirection: 'row', gap: 4, width: '100%', height, alignSelf: 'stretch' }}>
794
+ {Array.from({ length: segs }).map((_, idx) => (
795
+ <View
796
+ key={idx}
797
+ style={{
798
+ flex: 1,
799
+ height,
800
+ backgroundColor: idx < filled ? tint : track,
801
+ borderRadius: height / 2,
802
+ }}
803
+ />
804
+ ))}
805
+ </View>
806
+ );
807
+ }
808
+
809
+ return (
810
+ <View style={{ width: '100%', height, backgroundColor: track, borderRadius: height / 2, alignSelf: 'stretch' }}>
811
+ <View
812
+ style={{
813
+ width: `${val * 100}%`,
814
+ height,
815
+ backgroundColor: tint,
816
+ borderRadius: height / 2,
817
+ }}
818
+ />
819
+ </View>
820
+ );
821
+ }
822
+
823
+ case 'Timer': {
824
+ const tnode = node as TimerNode;
825
+ const p = tnode.props || {};
826
+ return <PreviewTimerText nodeProps={p} parentDirection={parentDirection} />;
827
+ }
828
+
829
+ case 'Image': {
830
+ const inode = node as ImageNode;
831
+ const p = inode.props || {};
832
+ const width = p.width ?? 32;
833
+ const height = p.height ?? 32;
834
+ const uri = p.url || (p.base64 ? `data:image/png;base64,${p.base64}` : null);
835
+
836
+ if (uri) {
837
+ return (
838
+ <RNImage
839
+ source={{ uri }}
840
+ style={{
841
+ width,
842
+ height,
843
+ borderRadius: p.borderRadius ?? p.cornerRadius ?? 0,
844
+ }}
845
+ />
846
+ );
847
+ }
848
+ return (
849
+ <View
850
+ style={{
851
+ width,
852
+ height,
853
+ backgroundColor: '#334155',
854
+ borderRadius: p.borderRadius ?? p.cornerRadius ?? 4,
855
+ alignItems: 'center',
856
+ justifyContent: 'center',
857
+ }}
858
+ >
859
+ <RNText style={{ color: '#94A3B8', fontSize: 10 }}>IMG</RNText>
860
+ </View>
861
+ );
862
+ }
863
+
864
+ case 'Spacer': {
865
+ const snode = node as any;
866
+ const p = snode.props || {};
867
+ const minLen = p?.minLength ?? 4;
868
+ return (
869
+ <View
870
+ style={
871
+ parentDirection === 'row'
872
+ ? { minWidth: minLen, flex: 1 }
873
+ : { minHeight: minLen, flex: 1 }
874
+ }
875
+ />
876
+ );
877
+ }
878
+
879
+ case 'Divider': {
880
+ const p = (node as any).props || {};
881
+ const color = parseDynamicColor(p.color) || '#334155';
882
+ return (
883
+ <View
884
+ style={
885
+ parentDirection === 'row'
886
+ ? { width: 1, height: '100%', backgroundColor: color }
887
+ : { width: '100%', height: 1, backgroundColor: color, alignSelf: 'stretch' }
888
+ }
889
+ />
890
+ );
891
+ }
892
+
893
+ case 'Link': {
894
+ const lnode = node as any;
895
+ const p = lnode.props || {};
896
+ return (
897
+ <TouchableOpacity
898
+ activeOpacity={0.7}
899
+ onPress={() => {
900
+ if (p.url && onAction) onAction(p.url);
901
+ }}
902
+ style={{ flexDirection: 'row', alignItems: 'center' }}
903
+ >
904
+ {lnode.children?.map((child: any, idx: number) => (
905
+ <React.Fragment key={idx}>
906
+ {renderPreviewNode(child, onAction, false, parentDirection, syncVars)}
907
+ </React.Fragment>
908
+ ))}
909
+ </TouchableOpacity>
910
+ );
911
+ }
912
+
913
+ case 'Equalizer': {
914
+ const enode = node as any;
915
+ const p = enode.props || {};
916
+ const tint = parseDynamicColor(p.color) || '#38BDF8';
917
+ return (
918
+ <View style={{ flexDirection: 'row', gap: 3, alignItems: 'flex-end', height: 16 }}>
919
+ {[12, 16, 8, 14].map((h, i) => (
920
+ <View key={i} style={{ width: 3, height: h, backgroundColor: tint, borderRadius: 1.5 }} />
921
+ ))}
922
+ </View>
923
+ );
924
+ }
925
+
926
+ case 'Gauge': {
927
+ const gnode = node as any;
928
+ const p = gnode.props || {};
929
+ const val = Math.round((p.value ?? 0.75) * 100);
930
+ const tint = parseDynamicColor(p.tintColor) || '#10B981';
931
+ return (
932
+ <View style={{ alignItems: 'center', justifyContent: 'center' }}>
933
+ <RNText style={{ color: tint, fontSize: 13, fontWeight: 'bold' }}>{val}%</RNText>
934
+ </View>
935
+ );
936
+ }
937
+
938
+ case 'Chart': {
939
+ const cnode = node as any;
940
+ const p = cnode.props || {};
941
+ const values: number[] = Array.isArray(p.values) ? p.values : [20, 45, 60, 80, 50];
942
+ const maxVal = Math.max(...values, 1);
943
+ const tint = parseDynamicColor(p.color) || '#38BDF8';
944
+ return (
945
+ <View style={{ flexDirection: 'row', gap: 4, alignItems: 'flex-end', height: 28, width: '100%', alignSelf: 'stretch' }}>
946
+ {values.map((v, i) => (
947
+ <View
948
+ key={i}
949
+ style={{
950
+ flex: 1,
951
+ height: `${Math.max(15, (v / maxVal) * 100)}%`,
952
+ backgroundColor: tint,
953
+ borderRadius: 2,
954
+ }}
955
+ />
956
+ ))}
957
+ </View>
958
+ );
959
+ }
960
+
961
+ case 'Toggle': {
962
+ return (
963
+ <PreviewToggleItem
964
+ key={`toggle-${(node as any).id || (node as any).props?.actionId || Math.random()}`}
965
+ node={node}
966
+ onAction={onAction}
967
+ />
968
+ );
969
+ }
970
+
971
+ default:
972
+ return null;
973
+ }
974
+ }
975
+
976
+ const styles = StyleSheet.create({
977
+ container: {
978
+ alignItems: 'center',
979
+ marginVertical: 12,
980
+ },
981
+ tabBar: {
982
+ flexDirection: 'row',
983
+ backgroundColor: '#1E293B',
984
+ borderRadius: 8,
985
+ padding: 3,
986
+ marginBottom: 8,
987
+ },
988
+ tabItem: {
989
+ paddingHorizontal: 12,
990
+ paddingVertical: 4,
991
+ borderRadius: 6,
992
+ },
993
+ tabItemActive: {
994
+ backgroundColor: '#2563EB',
995
+ },
996
+ tabText: {
997
+ color: '#94A3B8',
998
+ fontSize: 11,
999
+ fontWeight: 'bold',
1000
+ },
1001
+ tabTextActive: {
1002
+ color: '#FFFFFF',
1003
+ },
1004
+ badgeRow: {
1005
+ marginBottom: 6,
1006
+ },
1007
+ specBadge: {
1008
+ backgroundColor: 'rgba(15, 23, 42, 0.6)',
1009
+ paddingHorizontal: 8,
1010
+ paddingVertical: 2,
1011
+ borderRadius: 10,
1012
+ borderWidth: 1,
1013
+ borderColor: 'rgba(255, 255, 255, 0.1)',
1014
+ },
1015
+ specBadgeText: {
1016
+ color: '#94A3B8',
1017
+ fontSize: 10,
1018
+ fontWeight: '600',
1019
+ },
1020
+ widgetFrame: {
1021
+ borderRadius: 22,
1022
+ overflow: 'hidden',
1023
+ backgroundColor: '#0F172A',
1024
+ shadowColor: '#000',
1025
+ shadowOffset: { width: 0, height: 6 },
1026
+ shadowOpacity: 0.25,
1027
+ shadowRadius: 12,
1028
+ elevation: 8,
1029
+ borderWidth: 1,
1030
+ borderColor: 'rgba(255, 255, 255, 0.12)',
1031
+ },
1032
+ emptyContainer: {
1033
+ flex: 1,
1034
+ alignItems: 'center',
1035
+ justifyContent: 'center',
1036
+ padding: 16,
1037
+ },
1038
+ emptyText: {
1039
+ color: '#64748B',
1040
+ fontSize: 12,
1041
+ textAlign: 'center',
1042
+ },
1043
+ });