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/docs/GUIDE-EN.md CHANGED
@@ -68,7 +68,7 @@ git clone https://github.com/React-Native-Vu/LiveWidgetsExampleExpo.git
68
68
  cd LiveWidgetsExampleExpo
69
69
  npm install
70
70
  npx expo prebuild
71
- npm run setup:widgets
71
+ npx react-native-live-widgets init
72
72
  npx expo run:ios # or npx expo run:android
73
73
  ```
74
74
 
@@ -237,7 +237,7 @@ async function ensureAndroidNotificationPermission() {
237
237
  ```
238
238
 
239
239
  #### 5. Step 4: Adding & Resizing Home Screen Widgets on Android (`small` / `medium` / `large`)
240
- 1. After calling `Widget.update('main', { small, medium, large })` in your app, go to the Android Home Screen.
240
+ 1. After calling `Widget.setLayout('main', { small, medium, large })` (or alias `Widget.update(...)`) in your app, go to the Android Home Screen.
241
241
  2. **Long-press an empty area** on the Home Screen -> Tap **Widgets** -> Find your app -> Drag **Live Widgets** onto the Home Screen.
242
242
  3. **Responsive Family Switching (`small` / `medium` / `large`):** Long-press the placed widget and release to show the resize handles:
243
243
  - Resize to **2×2 cells** (`width < 210dp`): Automatically renders the **`small`** layout (1:1 square aspect ratio).
@@ -313,9 +313,86 @@ import { LiveActivity, Widget, SharedStorage, UI } from 'react-native-live-widge
313
313
 
314
314
  ---
315
315
 
316
- ## 4. Declarative UI Engine (`UI.*`)
316
+ ## 4. Declarative UI Engine
317
317
 
318
- ### `UI.StyleSheet` & Reusable Styling (`StyleProp`)
318
+ The library supports **2 dual UI authoring styles** side-by-side depending on your preferences:
319
+ 1. **Style 1: React JSX / TSX Components (`<VStack>`, `<Text>`, `<Button>`)** — Write widgets exactly like building standard React Native components. Fully supports the standard `style` prop, conditional style arrays, and nested hierarchies.
320
+ 2. **Style 2: Functional DSL (`UI.VStack(...)`)** — Concise and functional, with zero JSX tags to import.
321
+
322
+ Both styles compile down automatically to the exact same native engine (SwiftUI on iOS and 2D Canvas on Android).
323
+
324
+ ---
325
+
326
+ ### Style 1: Building Widgets with JSX / TSX Components
327
+
328
+ ```tsx
329
+ import React from 'react';
330
+ import { StyleSheet } from 'react-native';
331
+ import { Widget, VStack, HStack, Text, Badge, Progress, Button } from 'react-native-live-widgets';
332
+
333
+ export const MyWidgetLayout = (
334
+ <VStack style={styles.card}>
335
+ <HStack style={styles.header}>
336
+ <Text style={styles.title}>Shift Check-in</Text>
337
+ <Badge text="07:54 (Valid)" backgroundColor="#064E3B" textColor="#6EE7B7" />
338
+ </HStack>
339
+ <Progress value={0.75} style="segmented" segments={4} tintColor="#38BDF8" height={8} />
340
+ <Button title="Refresh Data" actionId="refresh" fullWidth />
341
+ </VStack>
342
+ );
343
+
344
+ const styles = StyleSheet.create({
345
+ card: {
346
+ padding: 16,
347
+ backgroundColor: '#0F172A',
348
+ borderRadius: 16,
349
+ },
350
+ header: {
351
+ justifyContent: 'space-between',
352
+ marginBottom: 8,
353
+ },
354
+ title: {
355
+ fontSize: 14,
356
+ fontWeight: 'bold',
357
+ color: '#FFFFFF',
358
+ },
359
+ });
360
+ ```
361
+
362
+ ---
363
+
364
+ ### In-App Widget Preview (`<WidgetPreview>` / `<VoltraWidgetPreview>`)
365
+
366
+ Embed a realistic, pixel-accurate widget mockup inside any app screen to test layout bounds and button click interactions without leaving your application:
367
+
368
+ ```tsx
369
+ import { WidgetPreview, VStack, HStack, Text, Button } from 'react-native-live-widgets';
370
+
371
+ export function PreviewScreen() {
372
+ return (
373
+ <WidgetPreview
374
+ size="medium" // 'small' | 'medium' | 'large' | 'lockScreen'
375
+ showBadge={true} // Shows 'Medium • 338×158'
376
+ interactiveSizeSwitch={true} // Quick tabs to switch small / medium / large
377
+ onAction={(actionId) => {
378
+ console.log('Action tapped inside preview:', actionId);
379
+ }}
380
+ >
381
+ <VStack padding={16} backgroundColor="#0F172A" borderRadius={20}>
382
+ <HStack justifyContent="spaceBetween">
383
+ <Text fontSize={14} fontWeight="bold" color="#FFFFFF">Project Progress</Text>
384
+ <Text fontSize={12} color="#38BDF8">75%</Text>
385
+ </HStack>
386
+ <Button title="Update" actionId="refresh" fullWidth />
387
+ </VStack>
388
+ </WidgetPreview>
389
+ );
390
+ }
391
+ ```
392
+
393
+ ---
394
+
395
+ ### Style 2: Functional DSL (`UI.StyleSheet` & Reusable Styling)
319
396
  Just like React Native's `StyleSheet.create`, you can define reusable styles to keep your widget layouts modular and clean, supporting conditional style arrays:
320
397
 
321
398
  ```typescript
@@ -746,14 +823,21 @@ if (isSupported) {
746
823
  When the user swipes away (force-kills) the main app, the React Native JS thread stops. To keep your Widget updated with live server data autonomously:
747
824
 
748
825
  ```typescript
749
- await Widget.setRemoteConfig({
826
+ // Full standard signature:
827
+ await Widget.setRemoteConfig('main', {
750
828
  url: 'https://api.yourcompany.com/v1/widget-summary',
751
829
  method: 'GET',
752
830
  headers: {
753
831
  Authorization: `Bearer ${accessToken}`,
754
832
  },
755
- intervalMinutes: 15, // OS-scheduled background sync every 15 minutes
756
- });
833
+ refreshIntervalMinutes: 15, // OS-scheduled background sync (alias: intervalMinutes)
834
+ }, APP_GROUP);
835
+
836
+ // Or convenient shorthand (defaults to widgetKey = 'main'):
837
+ await Widget.setRemoteConfig({
838
+ url: 'https://api.yourcompany.com/v1/widget-summary',
839
+ refreshIntervalMinutes: 15,
840
+ }, APP_GROUP);
757
841
  ```
758
842
 
759
843
  - **How it works:**
@@ -860,6 +944,247 @@ phases: [
860
944
 
861
945
  ---
862
946
 
947
+ ---
948
+
949
+ ## 12. Advanced Styling Modifiers & Platform Capability Matrix
950
+
951
+ ### 12.1. Styling Modifiers Reference
952
+
953
+ Elevate your widgets and Live Activities with design system fundamentals:
954
+
955
+ 1. **🌈 Linear & Radial Gradients**:
956
+ ```tsx
957
+ <VStack
958
+ gradient={{
959
+ colors: ['#1E3A8A', '#3B82F6'],
960
+ startPoint: { x: 0, y: 0 },
961
+ endPoint: { x: 1, y: 1 },
962
+ angle: 45,
963
+ }}
964
+ padding={16}
965
+ >
966
+ <Text typography="headline" color="#FFFFFF">Gradient Card</Text>
967
+ </VStack>
968
+ ```
969
+ > [!TIP]
970
+ > **Graceful Fallback**: If an older OS version or platform does not support gradient shaders, the renderer automatically uses the first color in `colors` as the solid fallback `backgroundColor`.
971
+
972
+ 2. **🔲 Borders & Dashed Lines**:
973
+ ```tsx
974
+ <VStack
975
+ borderWidth={1.5}
976
+ borderColor="#38BDF8"
977
+ borderStyle="dashed"
978
+ borderRadius={12}
979
+ padding={12}
980
+ >
981
+ <Text fontSize={12} color="#94A3B8">Dashed card border</Text>
982
+ </VStack>
983
+ ```
984
+
985
+ 3. **🌑 Shadows & Elevation**:
986
+ ```tsx
987
+ <Button
988
+ title="Confirm"
989
+ backgroundColor="#2563EB"
990
+ shadowColor="#2563EB"
991
+ shadowRadius={6}
992
+ shadowOpacity={0.4}
993
+ shadowOffset={{ x: 0, y: 3 }}
994
+ />
995
+ ```
996
+
997
+ 4. **🔤 Typography & Dynamic Type (Accessibility Scaling)**:
998
+ - Scale levels: `largeTitle` (34), `title1` (28), `title2` (22), `title3` (20), `headline` (17 bold), `body` (17 regular), `callout` (16), `subheadline` (15), `footnote` (13), `caption1` (12), `caption2` (11).
999
+ - `fontDesign`: `'default' | 'monospaced' | 'rounded' | 'serif'`.
1000
+ - `dynamicType`: Defaults to `true` — automatically respects the user's OS Accessibility font size setting.
1001
+
1002
+ 5. **🌗 Tinted / Dark Mode (iOS 18 Accentable & Android Dynamic Theming)**:
1003
+ ```tsx
1004
+ <Text color={{ light: '#0F172A', dark: '#F8FAFC', tinted: '#38BDF8' }}>
1005
+ Theme-adaptive text
1006
+ </Text>
1007
+ ```
1008
+
1009
+ 6. **🌍 RTL Internationalization**:
1010
+ ```tsx
1011
+ <HStack direction="rtl" isRTL={true} spacing={8}>
1012
+ <Text>مرحبا بك</Text>
1013
+ </HStack>
1014
+ ```
1015
+
1016
+ ---
1017
+
1018
+ ### 12.2. Platform Capability & Fallback Matrix
1019
+
1020
+ Rather than making unverified claims of "100% parity", the engine provides an explicit, transparent capability matrix paired with automatic **Graceful Fallbacks**:
1021
+
1022
+ | Feature / Modifier | iOS WidgetKit | iOS Live Activity | Android Ongoing Notification | Android Home Widget | Graceful Fallback Strategy |
1023
+ | :--- | :---: | :---: | :---: | :---: | :--- |
1024
+ | **Declarative Layouts (`VStack`/`HStack`/`Grid`)** | ✅ SwiftUI | ✅ SwiftUI | ✅ Canvas | ✅ 2D Canvas | 100% pixel-aligned cross-platform |
1025
+ | **Linear / Radial Gradients** | ✅ SwiftUI | ✅ SwiftUI | ✅ Shader | ✅ Shader | Automatically falls back to dominant solid `backgroundColor` |
1026
+ | **Card & Text Shadows** | ✅ SwiftUI | ✅ SwiftUI | ⚠️ Text Only | ✅ `setShadowLayer` | Falls back to elevation or thin border stroke |
1027
+ | **Dashed / Dotted Borders** | ✅ StrokeStyle | ✅ StrokeStyle | ⚠️ Solid | ✅ `DashPathEffect` | Automatically falls back to solid border |
1028
+ | **Dynamic Type (Accessibility)** | ✅ Native | ✅ Native | ✅ `fontScale` | ✅ `fontScale` | Automatically scales with OS font multiplier |
1029
+ | **RTL Layout Mirroring** | ✅ Native | ✅ Native | ✅ RTL | ✅ RTL | Reverses flex order and flips text alignment |
1030
+ | **Accessibility (TalkBack / VoiceOver)** | ✅ Native VoiceOver | ✅ Native VoiceOver | ✅ Notification Text | ✅ A11y Summary + Hit-Zones | Aggregated semantic `contentDescription` ensures full screen-reader readability |
1031
+ | **iOS 18 Tinted Mode** | ✅ Accentable | N/A | N/A | ✅ Material You | Resolves `tinted` key on iOS 18; falls back to dark/light color |
1032
+ | **Interactive Background Intents** | ✅ iOS 17+ | ✅ iOS 17+ | ✅ PendingIntent | ✅ PendingIntent | Updates local Shared Storage and refreshes timeline |
1033
+
1034
+ ---
1035
+
1036
+ ### 12.3. ♿ Accessibility & Semantics (Phase 1 Fallback Layer)
1037
+
1038
+ To ensure users with visual impairments or screen-reader users (**VoiceOver on iOS**, **TalkBack on Android**) receive full context, the engine provides standard accessibility props:
1039
+
1040
+ ```tsx
1041
+ <VStack padding={16} backgroundColor="#0F172A">
1042
+ {/* Header with semantic role */}
1043
+ <Text
1044
+ typography="title2"
1045
+ accessibilityRole="header"
1046
+ accessibilityLabel="Shift Attendance Dashboard"
1047
+ >
1048
+ ATTENDANCE DASHBOARD
1049
+ </Text>
1050
+
1051
+ {/* Progress gauge with spoken percentage */}
1052
+ <Progress
1053
+ value={0.86}
1054
+ accessibilityLabel="Shift completion progress"
1055
+ accessibilityValue="86 percent"
1056
+ />
1057
+
1058
+ {/* Interactive button with action hint */}
1059
+ <Button
1060
+ title="Clock In"
1061
+ actionId="CLOCK_IN"
1062
+ accessibilityRole="button"
1063
+ accessibilityLabel="Clock in to shift"
1064
+ accessibilityHint="Double tap to confirm attendance"
1065
+ />
1066
+
1067
+ {/* Decorative element hidden from screen readers */}
1068
+ <Image systemName="sparkles" accessible={false} />
1069
+ </VStack>
1070
+ ```
1071
+
1072
+ #### How Phase 1 Accessibility Works:
1073
+ 1. **iOS (SwiftUI)**: Maps directly to native `.accessibilityLabel()`, `.accessibilityHint()`, `.accessibilityValue()`, and `.accessibilityAddTraits()`. Elements with `accessible={false}` receive `.accessibilityHidden(true)`.
1074
+ 2. **Android (Canvas 2D)**:
1075
+ - Recursively extracts an intelligent text summary (`extractAccessibilitySummary`) and binds it to the canvas `ImageView`'s `contentDescription`.
1076
+ - Each interactive hit-zone receives its own `contentDescription` and action hint so TalkBack speaks each button individually when focused.
1077
+ 3. **In-App Preview**: Maps to React Native Web/Mobile accessibility props.
1078
+
1079
+ ---
1080
+
1081
+ ### 12.4. Programmatic Capability Inspection (`Widget.getCapabilities`)
1082
+ ```typescript
1083
+ const caps = await Widget.getCapabilities();
1084
+ console.log(`Running on: ${caps.platform} (OS: ${caps.osVersion})`);
1085
+
1086
+ if (caps.supportsDynamicIsland) {
1087
+ console.log('Device has Dynamic Island hardware!');
1088
+ }
1089
+
1090
+ if (caps.supportsTintedMode) {
1091
+ console.log('Device supports iOS 18 Tinted Home Screen mode!');
1092
+ }
1093
+ ```
1094
+
1095
+ ---
1096
+
1097
+ ### 12.5. 🌲 UI Intermediate Representation (IR) & Semantic Tree (Phase 2)
1098
+
1099
+ Rather than compiling directly from `DSL ➔ Canvas Bitmap`, the engine introduces a decoupled **UI Intermediate Representation (IR v2.0)** and a **Renderer Planner**:
1100
+
1101
+ ```
1102
+ React Native DSL (JSX / UI.*)
1103
+ ↓
1104
+ UI Intermediate Representation (IR v2.0)
1105
+ ├── UI Tree (unique ID for every node)
1106
+ ├── Semantic Tree (independent of visual renderer)
1107
+ ├── State Bindings (toggle:<key>, page:<id>)
1108
+ └── Renderer Planner (classifies Native RemoteViews vs Canvas Bitmap)
1109
+ ↓
1110
+ ├── [NATIVE] RemoteViews (TextView, Button, ProgressBar)
1111
+ └── [CANVAS] Canvas 2D Bitmap (Gauge 240°, Equalizer, Shader)
1112
+ ```
1113
+
1114
+ #### Inspecting and Compiling IR:
1115
+ ```typescript
1116
+ import { Widget, UI } from 'react-native-live-widgets';
1117
+
1118
+ const layout = UI.VStack({
1119
+ padding: 16,
1120
+ backgroundColor: '#0F172A',
1121
+ children: [
1122
+ UI.Text('ATTENDANCE DASHBOARD', { typography: 'title2' }),
1123
+ UI.Progress({ value: 0.86, accessibilityLabel: 'Shift completion' }),
1124
+ UI.Button({ title: 'Clock In', actionId: 'toggle:attendance' }),
1125
+ UI.Gauge({ value: 0.92, label: 'Efficiency' })
1126
+ ]
1127
+ });
1128
+
1129
+ // 1. Inspect architectural plan and accessibility synthesis
1130
+ console.log(Widget.inspectIR(layout));
1131
+
1132
+ // 2. Compile to raw IR object
1133
+ const ir = Widget.compileIR(layout);
1134
+ console.log('Synthesized A11y Summary:', ir.semanticSummary);
1135
+ ```
1136
+
1137
+ ---
1138
+
1139
+ ### 12.6. ⚡ Native State Sync, Sub-renderer Optimization & Automated Test Suite
1140
+
1141
+ #### 1. Native State Synchronization (Phase 4):
1142
+ - Instant action & toggle responses: Native Android (`LiveActivityReceiver.kt` & `DynamicWidgetStateStore`) immediately updates `SharedPreferences` and triggers a widget redraw with zero UI lag even if the app was killed.
1143
+ - React hooks (`useWidgetStorage`, `useWidgetAction`) reconcile the latest state upon app launch.
1144
+
1145
+ #### 2. Canvas Sub-renderer Optimization (Phase 5):
1146
+ - `renderSubNodeBitmap`: Isolates bitmap allocation solely to the sub-component's bounding box (e.g. 64dp Gauge consumes only ~40KB bitmap) instead of allocating a full-screen canvas bitmap.
1147
+ - Completely avoids Android Binder IPC `TransactionTooLargeException`.
1148
+
1149
+ #### 3. Advanced JSX Components & Automated Tests (Phase 6):
1150
+ - New JSX components: `<Toggle>`, `<Switch>`, and `<Checkbox>` with `checked`/`isChecked`, `tintColor`, and `strikethroughOnCheck`.
1151
+ - Automated test suite verifying 100% assertions:
1152
+ ```bash
1153
+ npm test
1154
+ ```
1155
+
1156
+ ---
1157
+
1158
+ ### 12.7. 🎯 Exact Dynamic Hit Layer, Live Chronometer Countdown & Swift 6 Compatibility (v1.2.1)
1159
+
1160
+ Version **v1.2.1** addresses critical real-world interaction challenges on physical devices:
1161
+
1162
+ #### 1. Exact Dynamic Hit Layer
1163
+ * **Previous Issue**: With static coordinate grids, layout reflows or dynamic content caused buttons to trigger adjacent items or blank spaces to activate phantom taps.
1164
+ * **v1.2.1 Solution**:
1165
+ - Replaced the fixed grid with a dynamic `FrameLayout` container (`rn_hit_layer` paired with `rn_live_widget_hit_zone.xml`).
1166
+ - Implemented the **`computeCanvasMapping`** algorithm to calculate aspect ratio letterboxing (`fitCenter`) between the Canvas Bitmap and the Launcher Widget bounds.
1167
+ - Generates independent RemoteViews hit zones that align 100% with the rendered element bounding box. Empty areas receive no touch events.
1168
+
1169
+ #### 2. Native Live Countdown Chronometer (`android.widget.Chronometer`)
1170
+ * **Previous Issue**: Drawing countdown text directly on Canvas required broadcasting and re-rendering the bitmap every second, causing battery drain and rate-limiting from Android system schedulers.
1171
+ * **v1.2.1 Solution**:
1172
+ - Integrated native `android.widget.Chronometer` into the widget host layout.
1173
+ - Automatically configured with `setChronometerCountDown(true)` and `baseMillis = SystemClock.elapsedRealtime() + remainingMillis`.
1174
+ - The renderer suppresses static timer text when an active chronometer is present, allowing continuous 1-second countdown ticks driven natively by Android OS.
1175
+
1176
+ #### 3. Dynamic Template Variable Interpolation & Initial State Store
1177
+ * **Variable Interpolation**: Supports dynamic string templates (`{{id}}`, `{{title}}`, counter values) directly in the layout JSON, automatically resolved against action responses and local state.
1178
+ * **`defaultChecked` Persistence**: Switches and checkboxes with `checked: true` have their initial state committed to `DynamicWidgetStateStore` on initial render, allowing them to be toggled off immediately on the first tap.
1179
+
1180
+ #### 4. Swift 6 Language Mode Compatibility (iOS Xcode)
1181
+ * **Resolved `type '()' cannot conform to 'View'`**:
1182
+ - Encapsulated `Font` resolution in `renderText()` within self-invoking closures `{ ... }()`.
1183
+ - Refactored `DynamicNodeAccessibilityModifier` procedural assignments into a dedicated `buildAccessibilityView(content:) -> AnyView` helper method.
1184
+ - Added fallback `else { EmptyView() }` branches to `backgroundView` and `borderOverlay` in `ContainerStyleModifier`.
1185
+
1186
+ ---
1187
+
863
1188
  ## 📄 License
864
1189
  MIT © vu-tran
865
1190