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
@@ -67,14 +67,28 @@ export interface WidgetRemoteConfig {
67
67
  - `LiveActivity.start(options: StartActivityOptions): Promise<string>`: Starts an activity, returns `activityId`.
68
68
  - `LiveActivity.update(options: { activityId?: string; layout?: WidgetNode; dynamicIsland?: ... }): Promise<void>`
69
69
  - `LiveActivity.end(options: { activityId?: string; dismissalPolicy?: 'immediate'|'default' }): Promise<void>`
70
- - `LiveActivity.endAll(): Promise<void>`
71
- - `LiveActivity.getAllPushTokens(): Promise<{ devicePushToken: string; pushToStartToken: string; activityUpdateToken: string }>`
70
+ - `LiveActivity.endAll(): Promise<boolean>`
71
+ - `LiveActivity.getAllPushTokens(activityId?: string): Promise<LiveActivityPushTokens>`
72
+ - `LiveActivity.registerAction(actionId: string, handler: ActionHandler): () => void`
72
73
  - `LiveActivity.registerActionHandler(handler: (actionId: string, payload?: any) => void): () => void`
73
- - `Widget.setLayout(widgetKey: string, config: WidgetLayoutConfig, appGroup?: string): Promise<void>`
74
- - `Widget.reload(widgetKey?: string): Promise<void>`
75
- - `Widget.reloadAll(): Promise<void>`
76
- - `Widget.setRemoteConfig(config: WidgetRemoteConfig, widgetKey?: string, appGroup?: string): Promise<void>`
74
+ - `Widget.setLayout(widgetKey: string, config: WidgetLayoutConfig, appGroup?: string): Promise<boolean>` (alias: `Widget.update`)
75
+ - `Widget.reload(widgetKey?: string): Promise<boolean>`
76
+ - `Widget.reloadAll(): Promise<boolean>`
77
+ - `Widget.setRemoteConfig(widgetKey: string, config: WidgetRemoteConfig, appGroup?: string): Promise<boolean>` (supports shorthand `Widget.setRemoteConfig(config, appGroup?)`)
78
+ - `Widget.onWidgetAction(handler: (actionId: string, payload?: any) => void): () => void`
77
79
  - `Widget.requestPin(): Promise<boolean>`: Android only.
80
+
81
+ ### React Hooks (Fast Refresh Resilient)
82
+ - `useWidgetAction(actionIdOrCallback: string | ((actionId: string, payload?: any) => void), handler?: ActionHandler): void`
83
+ - `useLiveActivity(initialActivityId?: string): UseLiveActivityResult`
84
+ - `useWidgetState<T>(key: string, initialValue: T, appGroup?: string): [T, (val: T | ((prev: T) => T)) => Promise<void>, () => Promise<void>]`
85
+
86
+ ### In-App Widget Preview Component
87
+ - `<WidgetPreview size="small"|"medium"|"large"|"lockScreen" layout={node} showBadge interactiveSizeSwitch onAction={(actionId) => ...} />` (alias: `<VoltraWidgetPreview>`)
88
+
89
+ ### Dual UI Authoring Syntax
90
+ - **JSX Components**: `<VStack>`, `<HStack>`, `<ZStack>`, `<Grid>`, `<Text>`, `<Button>`, `<Badge>`, `<Progress>`, `<Timer>`, `<Image>`, `<Spacer>`, `<Divider>`, `<Link>`, `<Equalizer>`, `<Gauge>`, `<Chart>`. Fully supports `style` props, StyleSheet objects, and conditional style arrays!
91
+ - **Functional DSL**: `UI.VStack(...)`, `UI.HStack(...)`, `UI.Text(...)`, `UI.Button(...)`, etc.
78
92
  - `SharedStorage.setAppGroup(appGroup: string): void`
79
93
  - `SharedStorage.set(key: string, value: string, appGroup?: string): Promise<void>`
80
94
  - `SharedStorage.get(key: string, appGroup?: string): Promise<string | null>`
@@ -116,3 +130,29 @@ export interface WidgetRemoteConfig {
116
130
  iOS limits daily widget reloads (~40-70/day). Android Doze Mode batches periodic tasks. Use `Widget.setRemoteConfig` for general background polling, but use Server Push (APNs / FCM) for second-by-second updates.
117
131
  3. **App Group Setup**:
118
132
  The App Group string passed to `SharedStorage.setAppGroup('group.com.yourcompany.app')` must match the entitlement configured in Xcode and `app.json`.
133
+
134
+ ---
135
+
136
+ ## 5. Architecture & Native Parity Engine (v1.2.1)
137
+
138
+ ### 1. Three Core Architectural Pillars
139
+ - **Native Semantic Coverage**: Replaced unrealistic 100% semantics with guaranteed accessibility coverage for all critical interactive nodes and graphical fallbacks (`contentDescription` for TalkBack, accessibility traits for VoiceOver).
140
+ - **Native-first, Canvas-when-needed**: Native components handle interactions and chronometers directly (`android.widget.Chronometer`, `FrameLayout` hit zones); Canvas 2D is reserved for custom graphics, sparklines, and complex vector nodes.
141
+ - **Semantic Tree Independent from Renderer (UI IR)**: Abstract Intermediate Representation (AST) containing Visual Nodes, Semantic Nodes, and Two-Way Event Bindings (`Widget.inspectIR(layout)`, `Widget.compileIR(layout)`).
142
+
143
+ ### 2. Android Exact Dynamic Hit Layer
144
+ - Replaced fixed grid layout with dynamic `FrameLayout` (`rn_hit_layer` + `rn_live_widget_hit_zone.xml`).
145
+ - Utilizes `computeCanvasMapping` to resolve `fitCenter` aspect ratio letterboxing, eliminating touch offsets and misclicks.
146
+
147
+ ### 3. Native Live Countdown Chronometer
148
+ - Integrated native `android.widget.Chronometer` with `setChronometerCountDown(true)` and `baseMillis = SystemClock.elapsedRealtime() + remainingMillis`.
149
+ - Suppresses static text rendering during active countdowns to provide 1-second continuous tick updates without Canvas bitmap redrawing.
150
+
151
+ ### 4. Dynamic Template Variable Interpolation
152
+ - Layout strings dynamically interpolate `{{id}}`, `{{title}}`, and counter values.
153
+ - `defaultChecked` persistence in `DynamicWidgetStateStore` enables toggling off pre-checked switches on the first tap.
154
+
155
+ ### 5. Swift 6 Language Mode Compatibility (iOS Xcode)
156
+ - Encapsulated `Font` resolution in `renderText()` within self-invoking closures `{ ... }()`.
157
+ - Refactored `DynamicNodeAccessibilityModifier` procedural assignments into a dedicated `buildAccessibilityView(content:) -> AnyView` helper method.
158
+ - Added fallback `else { EmptyView() }` branches to `backgroundView` and `borderOverlay` in `ContainerStyleModifier`.
package/docs/llms.txt CHANGED
@@ -26,30 +26,60 @@ Write 100% Declarative TypeScript (`UI.*`) in your React Native code. Automatica
26
26
  npx react-native-live-widgets init --group group.com.yourcompany.app
27
27
  ```
28
28
 
29
+ ### Dual UI Authoring Syntax: JSX Components & Functional DSL
30
+ Widgets can be built with **EITHER** JSX elements or Functional DSL:
31
+ - **JSX / TSX Elements**: `<VStack>`, `<HStack>`, `<ZStack>`, `<Grid>`, `<Text>`, `<Button>`, `<Badge>`, `<Progress>`, `<Timer>`, `<Equalizer>`, `<Image>`, `<Spacer>`, `<Divider>`, `<Link>`. Fully supports `style` props, StyleSheet objects, and conditional style arrays!
32
+ - **Functional DSL**: `UI.VStack(...)`, `UI.HStack(...)`, `UI.Text(...)`, `UI.Button(...)`, etc.
33
+ - **In-App Widget Preview**: `<WidgetPreview size="medium" showBadge interactiveSizeSwitch>{jsxLayout}</WidgetPreview>` (alias: `<VoltraWidgetPreview>`).
34
+
29
35
  ### Key Declarative UI DSL Methods
30
36
  - `UI.VStack(options, ...children)` / `UI.HStack(options, ...children)`: Flex containers with `spacing`, `padding`, `backgroundColor`, `borderRadius`, `alignment`.
31
37
  - `UI.Text(content, { color, fontSize, fontWeight: 'bold'|'heavy'|'medium'|'regular', maxLines })`
32
38
  - `UI.Timer(timestampMs, { mode: 'countdown'|'timer'|'relative', color, fontSize })`: Zero-battery native hardware clock.
33
39
  - `UI.Progress(options)`: Supports `style: 'bar' | 'segmented' | 'circular'`, `value` (0.0 to 1.0), `tintColor`, `trackColor`.
34
40
  - `UI.Equalizer({ isPlaying: true, barCount: 4, tintColor, height })`: Realtime animated audio waveform on Dynamic Island & lock screen.
35
- - `UI.Image({ url, base64, systemName, width, height, cornerRadius, contentMode })`: Auto-cached remote images, base64 data, or SF Symbols.
36
- - `UI.Button({ title, actionId, backgroundColor, color, fontSize })`: Interactive widget button triggering `AppIntents` (iOS 17+) and `BroadcastReceiver` (Android).
41
+ - `UI.Image({ url, base64, systemName, width, height, borderRadius, contentMode })`: Auto-cached remote images, base64 data, or SF Symbols (supports `cornerRadius` as alias).
42
+ - `UI.Button('Title', { actionId, ... })` or `UI.Button({ title, actionId, ... })`: Interactive widget button triggering `AppIntents` (iOS 17+) and `BroadcastReceiver` (Android).
43
+ - `UI.Badge('Text', { ... })` or `UI.Badge({ text, ... })`: Metric badges.
37
44
  - `UI.Gauge(value, { size, tintColor, trackColor, label, valueText })`: 240° KPI circular gauge.
38
45
  - `UI.Chart(dataPoints, { style: 'bar'|'line', labels, tintColor, height })`: Lightweight trend sparklines.
39
46
 
40
- ### Bidirectional Two-Way Action Handling
47
+ ### React Hooks (Fast Refresh Resilient)
41
48
  ```typescript
42
- import { LiveActivity, Widget } from 'react-native-live-widgets';
49
+ import { useWidgetAction, useLiveActivity, useWidgetState } from 'react-native-live-widgets';
50
+
51
+ // 1. Hook: Listen to widget button interactions (safe with Fast Refresh)
52
+ useWidgetAction('INCREMENT', () => {
53
+ setCount(c => c + 1);
54
+ });
43
55
 
44
- // Listen to widget button interactions inside App.tsx
45
- const unsubscribe = LiveActivity.registerActionHandler((actionId, payload) => {
56
+ // 2. Hook: Manage Live Activity lifecycle
57
+ const { activityId, isActive, start, update, end } = useLiveActivity();
58
+
59
+ // 3. Hook: Two-way state sync with Widget SharedStorage
60
+ const [counter, setCounter] = useWidgetState('widget_counter', 0);
61
+ ```
62
+
63
+ ### Imperative Action Handling
64
+ ```typescript
65
+ import { Widget, LiveActivity } from 'react-native-live-widgets';
66
+
67
+ // Listen to widget button interactions imperatively
68
+ const unsubscribe = Widget.onWidgetAction((actionId, payload) => {
46
69
  if (actionId === 'INCREMENT') {
47
- // Update local state and trigger widget redraw
48
70
  Widget.reload('main');
49
71
  }
50
72
  });
51
73
  ```
52
74
 
75
+ ### Architecture & Native Parity (v1.2.1 Updates)
76
+ - **Native Semantic Coverage & Accessibility**: Standard `BaseSemanticProps` (`accessible`, `accessibilityRole`, `accessibilityLabel`, `accessibilityHint`, `accessibilityValue`) with full VoiceOver and TalkBack support.
77
+ - **UI Intermediate Representation (IR)**: Inspect and compile layout trees with `Widget.inspectIR(layout)` and `Widget.compileIR(layout)`.
78
+ - **Android Exact Dynamic Hit Layer**: Dynamic `FrameLayout` overlay with `computeCanvasMapping` compensating for `fitCenter` aspect ratio letterboxing, eliminating misclicks and phantom taps.
79
+ - **Android Native Live Chronometer**: Realtime 1s countdowns driven by native `android.widget.Chronometer` without Canvas bitmap redraws.
80
+ - **Dynamic Template Variable Interpolation**: Resolves `{{id}}`, `{{title}}`, and counter values dynamically, with initial `defaultChecked` persistence in `DynamicWidgetStateStore`.
81
+ - **Swift 6 Compatibility**: Full compliance with Swift 6 language mode and `@ViewBuilder` closure encapsulation on iOS Xcode.
82
+
53
83
  ### Golden Rules for AI Agents
54
84
  1. **Never write Swift or Kotlin files manually** when a declarative `UI.*` node exists.
55
85
  2. **App Groups**: Both iOS app and Widget Extension MUST share the identical App Group name (e.g. `group.<bundle_id>`).
@@ -3,11 +3,13 @@ import Foundation
3
3
  // MARK: - Declarative Layout Models (Shared between Live Activity & Home Screen Widgets)
4
4
 
5
5
  public struct LayoutNodeDTO: Codable {
6
+ public let id: String?
6
7
  public let type: String
7
8
  public let props: [String: AnyCodable]?
8
9
  public let children: [LayoutNodeDTO]?
9
10
 
10
- public init(type: String, props: [String: AnyCodable]? = nil, children: [LayoutNodeDTO]? = nil) {
11
+ public init(id: String? = nil, type: String, props: [String: AnyCodable]? = nil, children: [LayoutNodeDTO]? = nil) {
12
+ self.id = id
11
13
  self.type = type
12
14
  self.props = props
13
15
  self.children = children
@@ -83,6 +85,9 @@ public struct WidgetSinglePageDTO: Codable {
83
85
  }
84
86
 
85
87
  public struct WidgetMultiPagePayloadDTO: Codable {
88
+ public let root: LayoutNodeDTO?
89
+ public let version: String?
90
+ public let semanticSummary: String?
86
91
  public let small: LayoutNodeDTO?
87
92
  public let medium: LayoutNodeDTO?
88
93
  public let large: LayoutNodeDTO?
@@ -119,6 +124,11 @@ public struct WidgetRemoteConfigDTO: Codable {
119
124
  public let method: String?
120
125
  public let headers: [String: String]?
121
126
  public let refreshIntervalMinutes: Int?
127
+ public let intervalMinutes: Int?
128
+
129
+ public var effectiveIntervalMinutes: Int {
130
+ return refreshIntervalMinutes ?? intervalMinutes ?? 15
131
+ }
122
132
  }
123
133
 
124
134
  public struct InteractiveWidgetState: Codable {
@@ -19,6 +19,7 @@ public struct DynamicNodeView: View {
19
19
  node.props?["privacySensitive"]?.boolValue == true,
20
20
  isRedacted: node.props?["redacted"]?.boolValue == true
21
21
  )
22
+ .modifier(DynamicNodeAccessibilityModifier(props: node.props))
22
23
  }
23
24
 
24
25
  @ViewBuilder
@@ -107,17 +108,49 @@ public struct DynamicNodeView: View {
107
108
  let fontWeightStr = node.props?["fontWeight"]?.stringValue ?? "regular"
108
109
  let numberOfLines = node.props?["numberOfLines"]?.doubleValue.map { Int($0) }
109
110
  let numericAnimation = node.props?["numericAnimation"]?.boolValue ?? false
111
+ let fontDesignStr = node.props?["fontDesign"]?.stringValue ?? "default"
112
+ let design: Font.Design = fontDesignStr == "monospaced" ? .monospaced : (fontDesignStr == "rounded" ? .rounded : (fontDesignStr == "serif" ? .serif : .default))
113
+
114
+ let font: Font = {
115
+ if let typo = node.props?["typography"]?.stringValue {
116
+ switch typo {
117
+ case "largeTitle": return .system(.largeTitle, design: design)
118
+ case "title1", "title": return .system(.title, design: design)
119
+ case "title2": return .system(.title2, design: design)
120
+ case "title3": return .system(.title3, design: design)
121
+ case "headline": return .system(.headline, design: design)
122
+ case "subheadline": return .system(.subheadline, design: design)
123
+ case "body": return .system(.body, design: design)
124
+ case "callout": return .system(.callout, design: design)
125
+ case "footnote": return .system(.footnote, design: design)
126
+ case "caption1", "caption": return .system(.caption, design: design)
127
+ case "caption2": return .system(.caption2, design: design)
128
+ default: return .system(size: CGFloat(fontSize), weight: parseFontWeight(fontWeightStr), design: design)
129
+ }
130
+ } else {
131
+ return .system(size: CGFloat(fontSize), weight: parseFontWeight(fontWeightStr), design: design)
132
+ }
133
+ }()
110
134
 
111
135
  let textNode = Text(text)
112
- .font(.system(size: CGFloat(fontSize), weight: parseFontWeight(fontWeightStr)))
136
+ .font(font)
113
137
  .foregroundColor(color)
114
138
  .lineLimit(numberOfLines)
115
139
  .minimumScaleFactor(0.85)
116
140
 
141
+ let shadowColor = Color.resolve(from: node.props?["shadowColor"], colorScheme: colorScheme)
142
+ let shadowRad = node.props?["shadowRadius"]?.doubleValue.map { CGFloat($0) } ?? (shadowColor != nil ? 2 : 0)
143
+ let shadowOffsetDict = node.props?["shadowOffset"]?.value as? [String: Any]
144
+ let shadowX = (shadowOffsetDict?["x"] as? Double).map { CGFloat($0) } ?? 0
145
+ let shadowY = (shadowOffsetDict?["y"] as? Double).map { CGFloat($0) } ?? 1
146
+
117
147
  if #available(iOS 16.0, *), numericAnimation {
118
- textNode.contentTransition(.numericText())
148
+ textNode
149
+ .contentTransition(.numericText())
150
+ .shadow(color: shadowColor ?? .clear, radius: shadowRad, x: shadowX, y: shadowY)
119
151
  } else {
120
152
  textNode
153
+ .shadow(color: shadowColor ?? .clear, radius: shadowRad, x: shadowX, y: shadowY)
121
154
  }
122
155
  }
123
156
 
@@ -878,7 +911,56 @@ public struct DynamicNodeView: View {
878
911
  }
879
912
  }
880
913
 
881
- // Container padding, background modifier
914
+ // ♿ Accessibility Semantics & Fallback Modifier (Phase 1)
915
+ struct DynamicNodeAccessibilityModifier: ViewModifier {
916
+ let props: [String: AnyCodable]?
917
+
918
+ func body(content: Content) -> some View {
919
+ buildAccessibilityView(content: content)
920
+ }
921
+
922
+ private func buildAccessibilityView(content: Content) -> AnyView {
923
+ let accessible = props?["accessible"]?.boolValue
924
+ let label = props?["accessibilityLabel"]?.stringValue
925
+ let hint = props?["accessibilityHint"]?.stringValue
926
+ let value = props?["accessibilityValue"]?.stringValue
927
+ let role = props?["accessibilityRole"]?.stringValue
928
+
929
+ if accessible == false {
930
+ return AnyView(content.accessibilityHidden(true))
931
+ }
932
+
933
+ if label == nil && hint == nil && value == nil && role == nil {
934
+ return AnyView(content)
935
+ }
936
+
937
+ var view = AnyView(content)
938
+ if let label = label {
939
+ view = AnyView(view.accessibilityLabel(Text(label)))
940
+ }
941
+ if let hint = hint {
942
+ view = AnyView(view.accessibilityHint(Text(hint)))
943
+ }
944
+ if let value = value {
945
+ view = AnyView(view.accessibilityValue(Text(value)))
946
+ }
947
+ if let role = role {
948
+ switch role {
949
+ case "header":
950
+ view = AnyView(view.accessibilityAddTraits(.isHeader))
951
+ case "button":
952
+ view = AnyView(view.accessibilityAddTraits(.isButton))
953
+ case "image":
954
+ view = AnyView(view.accessibilityAddTraits(.isImage))
955
+ default:
956
+ break
957
+ }
958
+ }
959
+ return view
960
+ }
961
+ }
962
+
963
+ // Container padding, background, gradient, border and shadow modifier
882
964
  struct ContainerStyleModifier: ViewModifier {
883
965
  @Environment(\.widgetFamily) var family
884
966
  @Environment(\.colorScheme) var colorScheme
@@ -891,22 +973,95 @@ struct ContainerStyleModifier: ViewModifier {
891
973
  return false
892
974
  }
893
975
 
976
+ @ViewBuilder
977
+ private func backgroundView(cornerRadius: CGFloat) -> some View {
978
+ if isAccessory {
979
+ EmptyView()
980
+ } else if let gradDict = props?["gradient"]?.value as? [String: Any],
981
+ let colorList = gradDict["colors"] as? [Any] {
982
+ let colors: [Color] = colorList.compactMap {
983
+ if let s = $0 as? String { return Color(hex: s) }
984
+ if let d = $0 as? [String: Any] {
985
+ let key = (colorScheme == .dark) ? "dark" : "light"
986
+ let hex = (d[key] as? String) ?? (d["light"] as? String) ?? (d["dark"] as? String) ?? (d["tinted"] as? String)
987
+ return hex.flatMap { Color(hex: $0) }
988
+ }
989
+ return nil
990
+ }
991
+ if colors.count >= 2 {
992
+ let startX = (gradDict["startPoint"] as? [String: Any])?["x"] as? Double ?? 0.0
993
+ let startY = (gradDict["startPoint"] as? [String: Any])?["y"] as? Double ?? 0.0
994
+ let endX = (gradDict["endPoint"] as? [String: Any])?["x"] as? Double ?? 1.0
995
+ let endY = (gradDict["endPoint"] as? [String: Any])?["y"] as? Double ?? 1.0
996
+ RoundedRectangle(cornerRadius: cornerRadius)
997
+ .fill(LinearGradient(
998
+ colors: colors,
999
+ startPoint: UnitPoint(x: startX, y: startY),
1000
+ endPoint: UnitPoint(x: endX, y: endY)
1001
+ ))
1002
+ } else if let firstColor = colors.first {
1003
+ RoundedRectangle(cornerRadius: cornerRadius).fill(firstColor)
1004
+ } else if let color = Color.resolve(from: props?["backgroundColor"], colorScheme: colorScheme) {
1005
+ RoundedRectangle(cornerRadius: cornerRadius).fill(color)
1006
+ } else {
1007
+ EmptyView()
1008
+ }
1009
+ } else if let color = Color.resolve(from: props?["backgroundColor"], colorScheme: colorScheme) {
1010
+ RoundedRectangle(cornerRadius: cornerRadius).fill(color)
1011
+ } else {
1012
+ EmptyView()
1013
+ }
1014
+ }
1015
+
1016
+ @ViewBuilder
1017
+ private func borderOverlay(cornerRadius: CGFloat) -> some View {
1018
+ let borderWidth = props?["borderWidth"]?.doubleValue.map { CGFloat($0) } ?? 0
1019
+ if borderWidth > 0, let borderColor = Color.resolve(from: props?["borderColor"], colorScheme: colorScheme) {
1020
+ let borderStyle = props?["borderStyle"]?.stringValue ?? "solid"
1021
+ let strokeStyle: StrokeStyle = {
1022
+ if borderStyle == "dashed" {
1023
+ return StrokeStyle(lineWidth: borderWidth, dash: [6, 4])
1024
+ } else if borderStyle == "dotted" {
1025
+ return StrokeStyle(lineWidth: borderWidth, dash: [2, 3])
1026
+ } else {
1027
+ return StrokeStyle(lineWidth: borderWidth)
1028
+ }
1029
+ }()
1030
+ RoundedRectangle(cornerRadius: cornerRadius)
1031
+ .strokeBorder(borderColor, style: strokeStyle)
1032
+ } else {
1033
+ EmptyView()
1034
+ }
1035
+ }
1036
+
894
1037
  func body(content: Content) -> some View {
895
1038
  let rawPad = props?["padding"]?.doubleValue.map { CGFloat($0) } ?? 0
896
1039
  let pad = isAccessory ? min(rawPad, 2) : rawPad
897
- // Trên Lock Screen widgets, nền luôn trong suốt để hiển thị tự nhiên trên hình nền điện thoại
898
- let bgColor = isAccessory ? nil : Color.resolve(from: props?["backgroundColor"], colorScheme: colorScheme)
899
- let cornerRadius = props?["borderRadius"]?.doubleValue.map { CGFloat($0) } ?? 0
1040
+ let cornerRadius = props?["borderRadius"]?.doubleValue.map { CGFloat($0) } ?? (props?["cornerRadius"]?.doubleValue.map { CGFloat($0) } ?? 0)
900
1041
 
901
- content
1042
+ let isRTL = (props?["isRTL"]?.boolValue == true) || (props?["direction"]?.stringValue == "rtl")
1043
+ let shadowColor = Color.resolve(from: props?["shadowColor"], colorScheme: colorScheme)
1044
+ let shadowRadius = props?["shadowRadius"]?.doubleValue.map { CGFloat($0) } ?? (shadowColor != nil ? 4 : 0)
1045
+ let shadowOpacity = props?["shadowOpacity"]?.doubleValue ?? 0.35
1046
+ let offsetDict = props?["shadowOffset"]?.value as? [String: Any]
1047
+ let shadowX = (offsetDict?["x"] as? Double).map { CGFloat($0) } ?? 0
1048
+ let shadowY = (offsetDict?["y"] as? Double).map { CGFloat($0) } ?? 2
1049
+
1050
+ let styledContent = content
902
1051
  .padding(pad)
903
- .background(
904
- Group {
905
- if let color = bgColor {
906
- RoundedRectangle(cornerRadius: cornerRadius).fill(color)
907
- }
908
- }
909
- )
1052
+ .background(backgroundView(cornerRadius: cornerRadius))
1053
+ .overlay(borderOverlay(cornerRadius: cornerRadius))
1054
+
1055
+ let withShadow = Group {
1056
+ if let sColor = shadowColor, shadowRadius > 0 {
1057
+ styledContent.shadow(color: sColor.opacity(shadowOpacity), radius: shadowRadius, x: shadowX, y: shadowY)
1058
+ } else {
1059
+ styledContent
1060
+ }
1061
+ }
1062
+
1063
+ return withShadow
1064
+ .environment(\.layoutDirection, isRTL ? .rightToLeft : .leftToRight)
910
1065
  }
911
1066
  }
912
1067
 
@@ -110,9 +110,8 @@ public struct DynamicWidgetProvider: TimelineProvider {
110
110
  let configKey = "widget_remote_config_\(widgetKey)"
111
111
  if let json = Self.readSharedString(forKey: configKey, appGroup: appGroup),
112
112
  let data = json.data(using: .utf8),
113
- let config = try? JSONDecoder().decode(WidgetRemoteConfigDTO.self, from: data),
114
- let mins = config.refreshIntervalMinutes, mins >= 1 {
115
- return mins
113
+ let config = try? JSONDecoder().decode(WidgetRemoteConfigDTO.self, from: data) {
114
+ return max(1, config.effectiveIntervalMinutes)
116
115
  }
117
116
  return 15
118
117
  }
@@ -242,6 +241,11 @@ public struct DynamicHomeScreenWidgetView: View {
242
241
  return nil
243
242
  }
244
243
 
244
+ // Hỗ trợ trực tiếp UI Intermediate Representation (IR v2.0)
245
+ if let root = payload.root {
246
+ return root
247
+ }
248
+
245
249
  if let pages = payload.pages, !pages.isEmpty {
246
250
  let state = DynamicWidgetStateStore.loadState()
247
251
  let defaultOrder = payload.pageOrder ?? Array(pages.keys).sorted()
@@ -1 +1 @@
1
- {"version":3,"file":"builder.d.ts","sourceRoot":"","sources":["../src/builder.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,SAAS,EACT,UAAU,EACV,SAAS,EACT,cAAc,EACd,UAAU,EACV,WAAW,EACX,aAAa,EACb,cAAc,EACd,SAAS,EACT,QAAQ,EACR,SAAS,EACT,UAAU,EACV,SAAS,EACT,UAAU,EACV,QAAQ,EACR,SAAS,EACT,YAAY,EACZ,UAAU,EACV,SAAS,EACT,QAAQ,EACR,SAAS,EACT,SAAS,EACT,UAAU,EACV,UAAU,EACV,UAAU,EACV,WAAW,EACZ,MAAM,SAAS,CAAC;AAKjB,wBAAgB,YAAY,CAAC,CAAC,SAAS,MAAM,EAAE,GAAG,MAAM,EAAE,SAAS,CAAC,CAAC,CAAC,EAAE,GAAG,CAAC,GAAG,SAAS,CAiBvF;AAED,MAAM,MAAM,cA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