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
package/src/builder.ts CHANGED
@@ -19,6 +19,7 @@ import {
19
19
  SpacerNode,
20
20
  StyleProp,
21
21
  TextNode,
22
+ TextNodeProps,
22
23
  TextStyle,
23
24
  TimerNode,
24
25
  ToggleNode,
@@ -64,6 +65,69 @@ function isLayoutNode(item: any): item is LayoutNode {
64
65
  return item && typeof item === 'object' && typeof item.type === 'string';
65
66
  }
66
67
 
68
+ const TYPOGRAPHY_DEFAULTS: Record<string, { fontSize: number; fontWeight: any }> = {
69
+ largeTitle: { fontSize: 34, fontWeight: 'bold' },
70
+ title1: { fontSize: 28, fontWeight: 'bold' },
71
+ title2: { fontSize: 22, fontWeight: 'bold' },
72
+ title3: { fontSize: 20, fontWeight: 'semibold' },
73
+ headline: { fontSize: 17, fontWeight: 'semibold' },
74
+ body: { fontSize: 17, fontWeight: 'regular' },
75
+ callout: { fontSize: 16, fontWeight: 'regular' },
76
+ subheadline: { fontSize: 15, fontWeight: 'regular' },
77
+ footnote: { fontSize: 13, fontWeight: 'regular' },
78
+ caption1: { fontSize: 12, fontWeight: 'regular' },
79
+ caption2: { fontSize: 11, fontWeight: 'regular' },
80
+ };
81
+
82
+ function normalizeProps<P extends object>(props?: P): P | undefined {
83
+ if (!props) return undefined;
84
+ const p = { ...props } as any;
85
+
86
+ // Bo góc alias
87
+ if (p.cornerRadius !== undefined && p.borderRadius === undefined) {
88
+ p.borderRadius = p.cornerRadius;
89
+ }
90
+
91
+ // Spacing / Gap alias chuẩn React Native
92
+ if (p.gap !== undefined && p.spacing === undefined) {
93
+ p.spacing = p.gap;
94
+ }
95
+
96
+ // Graceful Fallback cho Gradient: nếu nền tảng/OS không hỗ trợ gradient, tự lấy màu đầu tiên làm backgroundColor
97
+ if (p.gradient && Array.isArray(p.gradient.colors) && p.gradient.colors.length > 0 && !p.backgroundColor) {
98
+ p.backgroundColor = p.gradient.colors[0];
99
+ }
100
+
101
+ // Typography scale chuẩn
102
+ if (p.typography && TYPOGRAPHY_DEFAULTS[p.typography]) {
103
+ const typo = TYPOGRAPHY_DEFAULTS[p.typography];
104
+ if (p.fontSize === undefined) p.fontSize = typo.fontSize;
105
+ if (p.fontWeight === undefined) p.fontWeight = typo.fontWeight;
106
+ }
107
+
108
+ // Trợ năng / Accessibility Semantics Fallback (Phase 1):
109
+ if (p.accessible === undefined) {
110
+ if (p.text !== undefined || p.title !== undefined || p.actionId !== undefined) {
111
+ p.accessible = true;
112
+ }
113
+ }
114
+
115
+ if (p.accessibilityLabel === undefined) {
116
+ if (p.text !== undefined) p.accessibilityLabel = String(p.text);
117
+ else if (p.title !== undefined) p.accessibilityLabel = String(p.title);
118
+ }
119
+
120
+ if (p.accessibilityRole === undefined) {
121
+ if (p.title !== undefined || p.actionId !== undefined) {
122
+ p.accessibilityRole = 'button';
123
+ } else if (p.typography && (p.typography.startsWith('title') || p.typography === 'largeTitle' || p.typography === 'headline')) {
124
+ p.accessibilityRole = 'header';
125
+ }
126
+ }
127
+
128
+ return p as P;
129
+ }
130
+
67
131
  function parseContainerArgs<P extends object>(
68
132
  first?: StyleProp<P> | LayoutNode | LayoutNode[],
69
133
  rest?: LayoutNode[]
@@ -76,12 +140,12 @@ function parseContainerArgs<P extends object>(
76
140
  return { props: undefined, children: first as LayoutNode[] };
77
141
  }
78
142
  const flattened = flattenStyle<P>(first as StyleProp<P>);
79
- return { props: flattened, children: rest || [] };
143
+ return { props: normalizeProps(flattened), children: rest || [] };
80
144
  }
81
145
  if (isLayoutNode(first)) {
82
146
  return { props: undefined, children: [first, ...(rest || [])] };
83
147
  }
84
- return { props: first as P, children: rest || [] };
148
+ return { props: normalizeProps(first as P), children: rest || [] };
85
149
  }
86
150
 
87
151
  /**
@@ -121,10 +185,10 @@ export const UI = {
121
185
  const merged = flattenStyle(...styles);
122
186
  return {
123
187
  type: 'Text',
124
- props: {
188
+ props: normalizeProps<TextNodeProps>({
125
189
  text,
126
190
  ...(merged || {}),
127
- },
191
+ })!,
128
192
  };
129
193
  },
130
194
 
@@ -154,15 +218,15 @@ export const UI = {
154
218
  if (typeof valueOrOptions === 'number') {
155
219
  return {
156
220
  type: 'Progress',
157
- props: {
221
+ props: normalizeProps({
158
222
  value: valueOrOptions,
159
223
  ...options,
160
- },
224
+ })!,
161
225
  };
162
226
  }
163
227
  return {
164
228
  type: 'Progress',
165
- props: valueOrOptions,
229
+ props: normalizeProps(valueOrOptions)!,
166
230
  };
167
231
  },
168
232
 
@@ -175,19 +239,19 @@ export const UI = {
175
239
  const isBase64 = urlOrOptions.startsWith('data:image/');
176
240
  return {
177
241
  type: 'Image',
178
- props: {
242
+ props: normalizeProps({
179
243
  ...(isHttp
180
244
  ? { url: urlOrOptions }
181
245
  : isBase64
182
246
  ? { base64: urlOrOptions }
183
247
  : { systemName: urlOrOptions }),
184
248
  ...options,
185
- },
249
+ })!,
186
250
  };
187
251
  }
188
252
  return {
189
253
  type: 'Image',
190
- props: urlOrOptions,
254
+ props: normalizeProps(urlOrOptions)!,
191
255
  };
192
256
  },
193
257
 
@@ -201,16 +265,17 @@ export const UI = {
201
265
  options?: Omit<ButtonNode['props'], 'title'>
202
266
  ): ButtonNode => {
203
267
  if (typeof titleOrProps === 'object' && titleOrProps !== null) {
204
- if (titleOrProps.onPress && !titleOrProps.actionId) {
268
+ const normalized = normalizeProps(titleOrProps)!;
269
+ if (normalized.onPress && !normalized.actionId) {
205
270
  autoActionCounter += 1;
206
- titleOrProps.actionId = `act_${Date.now()}_${autoActionCounter}`;
207
- registerAction(titleOrProps.actionId, titleOrProps.onPress);
208
- } else if (titleOrProps.onPress && titleOrProps.actionId) {
209
- registerAction(titleOrProps.actionId, titleOrProps.onPress);
271
+ normalized.actionId = `act_${Date.now()}_${autoActionCounter}`;
272
+ registerAction(normalized.actionId, normalized.onPress);
273
+ } else if (normalized.onPress && normalized.actionId) {
274
+ registerAction(normalized.actionId, normalized.onPress);
210
275
  }
211
276
  return {
212
277
  type: 'Button',
213
- props: titleOrProps,
278
+ props: normalized,
214
279
  };
215
280
  }
216
281
 
@@ -225,11 +290,11 @@ export const UI = {
225
290
 
226
291
  return {
227
292
  type: 'Button',
228
- props: {
293
+ props: normalizeProps({
229
294
  title: titleOrProps,
230
295
  ...options,
231
296
  actionId: finalActionId,
232
- },
297
+ })!,
233
298
  };
234
299
  },
235
300
 
@@ -350,15 +415,15 @@ export const UI = {
350
415
  if (typeof textOrOptions === 'string') {
351
416
  return {
352
417
  type: 'Badge',
353
- props: {
418
+ props: normalizeProps({
354
419
  text: textOrOptions,
355
420
  ...options,
356
- },
421
+ })!,
357
422
  };
358
423
  }
359
424
  return {
360
425
  type: 'Badge',
361
- props: textOrOptions,
426
+ props: normalizeProps(textOrOptions)!,
362
427
  };
363
428
  },
364
429
 
package/src/dispatcher.ts CHANGED
@@ -4,7 +4,13 @@ export type ActionHandler = (event: {
4
4
  [key: string]: any;
5
5
  }) => Promise<any> | any;
6
6
 
7
+ export type GlobalActionHandler = (
8
+ actionId: string,
9
+ payload?: any
10
+ ) => Promise<any> | any;
11
+
7
12
  export const actionHandlers = new Map<string, ActionHandler>();
13
+ export const globalActionHandlers = new Set<GlobalActionHandler>();
8
14
 
9
15
  /**
10
16
  * Đăng ký một hàm xử lý logic TypeScript khi người dùng bấm nút có `actionId` tương ứng ngoài Widget/Live Activity.
@@ -17,6 +23,17 @@ export function registerAction(actionId: string, handler: ActionHandler): () =>
17
23
  };
18
24
  }
19
25
 
26
+ /**
27
+ * Đăng ký hàm lắng nghe toàn bộ các sự kiện bấm nút từ Widget hoặc Live Activity.
28
+ * Trả về hàm hủy đăng ký (unsubscribe).
29
+ */
30
+ export function registerActionHandler(handler: GlobalActionHandler): () => void {
31
+ globalActionHandlers.add(handler);
32
+ return () => {
33
+ globalActionHandlers.delete(handler);
34
+ };
35
+ }
36
+
20
37
  /**
21
38
  * Hủy đăng ký action handler.
22
39
  */
package/src/hooks.ts ADDED
@@ -0,0 +1,223 @@
1
+ import { useState, useEffect, useRef, useCallback } from 'react';
2
+ import {
3
+ ActionHandler,
4
+ GlobalActionHandler,
5
+ registerAction,
6
+ registerActionHandler,
7
+ } from './dispatcher';
8
+ import { LiveActivity, SharedStorage, Widget } from './index';
9
+ import {
10
+ LiveActivityPushTokens,
11
+ StartActivityOptions,
12
+ UpdateActivityOptions,
13
+ EndActivityOptions,
14
+ } from './types';
15
+
16
+ /**
17
+ * 🎣 React Hook an toàn tuyệt đối với Fast Refresh / Hot Reloading để lắng nghe
18
+ * tương tác nút bấm trên Home Screen Widget hoặc Live Activity.
19
+ * Tự động đăng ký khi mount và hủy dọn dẹp (cleanup) khi Component unmount.
20
+ *
21
+ * Cách dùng 1 (Lắng nghe 1 actionId cụ thể):
22
+ * ```typescript
23
+ * useWidgetAction('counter:inc', (event) => {
24
+ * setCount((prev) => prev + 1);
25
+ * });
26
+ * ```
27
+ *
28
+ * Cách dùng 2 (Lắng nghe toàn cục mọi sự kiện nút bấm):
29
+ * ```typescript
30
+ * useWidgetAction((actionId, payload) => {
31
+ * console.log('Action received:', actionId, payload);
32
+ * });
33
+ * ```
34
+ */
35
+ export function useWidgetAction(
36
+ actionIdOrCallback: string | GlobalActionHandler,
37
+ handler?: ActionHandler
38
+ ): void {
39
+ const savedHandler = useRef<ActionHandler | GlobalActionHandler | undefined>(undefined);
40
+
41
+ useEffect(() => {
42
+ savedHandler.current = typeof actionIdOrCallback === 'function' ? actionIdOrCallback : handler;
43
+ });
44
+
45
+ useEffect(() => {
46
+ if (typeof actionIdOrCallback === 'function') {
47
+ const unsubscribe = registerActionHandler((actionId, payload) => {
48
+ if (typeof savedHandler.current === 'function') {
49
+ (savedHandler.current as GlobalActionHandler)(actionId, payload);
50
+ }
51
+ });
52
+ return unsubscribe;
53
+ } else if (typeof actionIdOrCallback === 'string') {
54
+ const unsubscribe = registerAction(actionIdOrCallback, (event) => {
55
+ if (typeof savedHandler.current === 'function') {
56
+ (savedHandler.current as ActionHandler)(event);
57
+ }
58
+ });
59
+ return unsubscribe;
60
+ }
61
+ }, [actionIdOrCallback]);
62
+ }
63
+
64
+ export interface UseLiveActivityResult {
65
+ /** ID định danh phiên Live Activity hiện tại */
66
+ activityId: string | null;
67
+ /** Trạng thái phiên có đang hoạt động hay không */
68
+ isActive: boolean;
69
+ /** Token cập nhật tiện ích (iOS activityUpdateToken hoặc devicePushToken) */
70
+ pushToken: string | null;
71
+ /** Toàn bộ bộ 3 loại Push Token (deviceToken, pushToStart, activityUpdateToken) */
72
+ pushTokens: LiveActivityPushTokens | null;
73
+ /** Bắt đầu một Live Activity mới */
74
+ start: (options: StartActivityOptions) => Promise<string | null>;
75
+ /** Cập nhật nội dung Live Activity hiện tại */
76
+ update: (options: Omit<UpdateActivityOptions, 'activityId'>) => Promise<boolean>;
77
+ /** Kết thúc Live Activity hiện tại */
78
+ end: (options?: EndActivityOptions) => Promise<boolean>;
79
+ }
80
+
81
+ /**
82
+ * 🎣 React Hook quản lý vòng đời trọn vẹn của một Live Activity / Android Ongoing Notification.
83
+ * Tương thích Fast Refresh và tự động dọn dẹp state khi component unmount.
84
+ *
85
+ * ```typescript
86
+ * const { activityId, isActive, start, update, end } = useLiveActivity();
87
+ *
88
+ * // Bắt đầu khi bấm nút
89
+ * await start({
90
+ * activityId: 'order_123',
91
+ * lockScreen: UI.VStack(...)
92
+ * });
93
+ * ```
94
+ */
95
+ export function useLiveActivity(initialActivityId?: string): UseLiveActivityResult {
96
+ const [currentId, setCurrentId] = useState<string | null>(initialActivityId || null);
97
+ const [isActive, setIsActive] = useState<boolean>(!!initialActivityId);
98
+ const [pushTokens, setPushTokens] = useState<LiveActivityPushTokens | null>(null);
99
+
100
+ useEffect(() => {
101
+ let mounted = true;
102
+ if (currentId) {
103
+ LiveActivity.getAllPushTokens(currentId)
104
+ .then((tokens: LiveActivityPushTokens) => {
105
+ if (mounted && tokens) {
106
+ setPushTokens(tokens);
107
+ }
108
+ })
109
+ .catch(() => {});
110
+ }
111
+ return () => {
112
+ mounted = false;
113
+ };
114
+ }, [currentId]);
115
+
116
+ const start = useCallback(
117
+ async (options: StartActivityOptions): Promise<string | null> => {
118
+ const ok = await LiveActivity.start(options);
119
+ if (ok) {
120
+ setCurrentId(options.activityId);
121
+ setIsActive(true);
122
+ try {
123
+ const tokens = await LiveActivity.getAllPushTokens(options.activityId);
124
+ setPushTokens(tokens);
125
+ } catch (_) {}
126
+ return options.activityId;
127
+ }
128
+ return null;
129
+ },
130
+ []
131
+ );
132
+
133
+ const update = useCallback(
134
+ async (options: Omit<UpdateActivityOptions, 'activityId'>): Promise<boolean> => {
135
+ if (!currentId) return false;
136
+ return await LiveActivity.update({
137
+ activityId: currentId,
138
+ ...options,
139
+ });
140
+ },
141
+ [currentId]
142
+ );
143
+
144
+ const end = useCallback(
145
+ async (options?: EndActivityOptions): Promise<boolean> => {
146
+ if (!currentId) return false;
147
+ const ok = await LiveActivity.end(currentId, options);
148
+ if (ok) {
149
+ setIsActive(false);
150
+ }
151
+ return ok;
152
+ },
153
+ [currentId]
154
+ );
155
+
156
+ return {
157
+ activityId: currentId,
158
+ isActive,
159
+ pushToken: pushTokens?.activityUpdateToken || pushTokens?.devicePushToken || null,
160
+ pushTokens,
161
+ start,
162
+ update,
163
+ end,
164
+ };
165
+ }
166
+
167
+ /**
168
+ * 🎣 React Hook liên kết state ứng dụng với Shared Storage của Home Screen Widget.
169
+ * Mỗi khi gọi `setWidgetState(...)`, widget sẽ tự động được hệ điều hành vẽ lại ngay lập tức.
170
+ *
171
+ * ```typescript
172
+ * const [counter, setCounter] = useWidgetState('counter_key', 0);
173
+ *
174
+ * // Cập nhật state + tự động yêu cầu Widget reload:
175
+ * setCounter(prev => prev + 1);
176
+ * ```
177
+ */
178
+ export function useWidgetState<T>(
179
+ key: string,
180
+ initialValue: T,
181
+ appGroup?: string
182
+ ): [T, (newValue: T | ((prev: T) => T)) => Promise<void>, () => Promise<void>] {
183
+ const [state, setState] = useState<T>(initialValue);
184
+
185
+ useEffect(() => {
186
+ let mounted = true;
187
+ SharedStorage.get<T>(key, appGroup)
188
+ .then((val: T | null) => {
189
+ if (mounted && val !== null && val !== undefined) {
190
+ setState(val);
191
+ }
192
+ })
193
+ .catch(() => {});
194
+ return () => {
195
+ mounted = false;
196
+ };
197
+ }, [key, appGroup]);
198
+
199
+ const setWidgetState = useCallback(
200
+ async (newValue: T | ((prev: T) => T)) => {
201
+ setState((prev: T) => {
202
+ const resolved =
203
+ typeof newValue === 'function' ? (newValue as (p: T) => T)(prev) : newValue;
204
+ SharedStorage.set(key, resolved, appGroup)
205
+ .then(() => {
206
+ Widget.reloadAll().catch(() => {});
207
+ })
208
+ .catch(() => {});
209
+ return resolved;
210
+ });
211
+ },
212
+ [key, appGroup]
213
+ );
214
+
215
+ const reload = useCallback(async () => {
216
+ const val = await SharedStorage.get<T>(key, appGroup);
217
+ if (val !== null && val !== undefined) {
218
+ setState(val);
219
+ }
220
+ }, [key, appGroup]);
221
+
222
+ return [state, setWidgetState, reload];
223
+ }