@capgo/capacitor-widget-kit 8.1.15 → 8.2.0

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.
@@ -13,5 +13,6 @@ Pod::Spec.new do |s|
13
13
  s.source_files = 'ios/Sources/**/*.{swift,h,m,c,cc,mm,cpp}'
14
14
  s.ios.deployment_target = '16.0'
15
15
  s.dependency 'Capacitor'
16
+ s.dependency 'SwiftDraw', '~> 0.29.0'
16
17
  s.swift_version = '5.9'
17
18
  end
package/Package.swift CHANGED
@@ -15,12 +15,15 @@ let package = Package(
15
15
  )
16
16
  ],
17
17
  dependencies: [
18
- .package(url: "https://github.com/ionic-team/capacitor-swift-pm.git", from: "8.0.0")
18
+ .package(url: "https://github.com/ionic-team/capacitor-swift-pm.git", from: "8.0.0"),
19
+ .package(url: "https://github.com/swhitty/SwiftDraw.git", .upToNextMinor(from: "0.29.0"))
19
20
  ],
20
21
  targets: [
21
22
  .target(
22
23
  name: "CapgoWidgetKitShared",
23
- dependencies: [],
24
+ dependencies: [
25
+ .product(name: "SwiftDraw", package: "SwiftDraw")
26
+ ],
24
27
  path: "ios/Sources/CapgoWidgetKitPlugin",
25
28
  exclude: ["CapgoWidgetKitPlugin.swift"]
26
29
  ),
package/README.md CHANGED
@@ -74,6 +74,7 @@ bunx cap sync android
74
74
  ## iOS Requirements
75
75
 
76
76
  - Add a Widget Extension target for Home Screen / SpringBoard widgets.
77
+ - Xcode 26 or later (the Capacitor 8 baseline). The built-in SVG renderer depends on SwiftDraw, which needs a Swift 6 toolchain through both SwiftPM and CocoaPods.
77
78
  - iOS 17+ is recommended for interactive Home Screen widget and Live Activity buttons.
78
79
  - Add `NSSupportsLiveActivities` to the app `Info.plist` when using ActivityKit.
79
80
  - Add the same App Group to the app target and the widget extension target.
@@ -112,7 +113,8 @@ The plugin ships the native pieces a widget extension or Android widget can use:
112
113
  - `CapgoTemplateActionIntent` for interactive iOS template buttons
113
114
  - `CapgoTemplateWidgetTimelineProvider` and `CapgoTemplateHomeWidgetView` for real iOS Home Screen / SpringBoard widgets backed by WidgetKit timelines
114
115
  - `CapgoTemplateWidgetBridge` to load a stored SVG activity and resolve one surface into `svg + width/height + frameId + hotspots + metadata`
115
- - `CapgoTemplateSurfaceView`, `CapgoTemplateWidgetSurface`, and `CapgoTemplateLatestWidgetSurface` to place a rendered SVG view under native hotspot buttons in SwiftUI
116
+ - `CapgoTemplateSvgView` and `CapgoTemplateSvgRenderer` to render the resolved SVG natively (built-in, powered by [SwiftDraw](https://github.com/swhitty/SwiftDraw))
117
+ - `CapgoTemplateSurfaceView`, `CapgoTemplateWidgetSurface`, and `CapgoTemplateLatestWidgetSurface` to place the rendered SVG under native hotspot buttons in SwiftUI
116
118
  - `CapgoNativeWidgetBridge` to load full-native widget sessions and exchange async messages without using SVG templates
117
119
  - `CapgoTemplateActionReceiver` and `CapgoTemplateWidgetBridge` for Android template widgets
118
120
 
@@ -140,9 +142,7 @@ struct ExampleTemplateHomeWidget: Widget {
140
142
 
141
143
  var body: some WidgetConfiguration {
142
144
  StaticConfiguration(kind: kind, provider: CapgoTemplateWidgetTimelineProvider()) { entry in
143
- CapgoTemplateHomeWidgetView(entry: entry) { layout in
144
- MySvgRenderer(svg: layout.svg)
145
- } placeholder: {
145
+ CapgoTemplateHomeWidgetView(entry: entry) {
146
146
  Text("No active widget")
147
147
  }
148
148
  }
@@ -153,12 +153,20 @@ struct ExampleTemplateHomeWidget: Widget {
153
153
  }
154
154
  ```
155
155
 
156
- Use the SwiftUI surface helpers when a custom WidgetKit view should be designed from JS but rendered by native widget code:
156
+ The SVG is rendered on iOS by the built-in `CapgoTemplateSvgView`, just like Android renders it with AndroidSVG. Use the SwiftUI surface helpers to place a template designed from JS inside your own WidgetKit or Live Activity views:
157
157
 
158
158
  ```swift
159
159
  CapgoTemplateLatestWidgetSurface {
160
- layout in
161
- MySvgRenderer(svg: layout.svg)
160
+ Text("No active widget")
161
+ }
162
+ ```
163
+
164
+ Pass an `svgContent` closure to wrap or replace the built-in renderer:
165
+
166
+ ```swift
167
+ CapgoTemplateLatestWidgetSurface { layout in
168
+ CapgoTemplateSvgView(layout: layout)
169
+ .clipShape(RoundedRectangle(cornerRadius: 16))
162
170
  } placeholder: {
163
171
  Text("No active widget")
164
172
  }
@@ -166,6 +174,10 @@ CapgoTemplateLatestWidgetSurface {
166
174
 
167
175
  The helper positions `CapgoTemplateActionIntent` buttons over the resolved SVG hotspots on iOS 17+. See `example-app/widget-extension/ExampleWidgetBundle.swift` for a complete Home Screen widget and Live Activity scaffold.
168
176
 
177
+ ### iOS SVG support
178
+
179
+ The iOS renderer draws the SVG into a bitmap with CoreGraphics, so it works inside widget extensions and Live Activities where web views are not available. It supports shapes, paths, gradients, transforms, clip paths, masks, patterns, `<use>`, `<text>`, and images embedded as `data:` URIs through `xlink:href`. Text defaults to Helvetica Neue (sans-serif); bold `font-weight` values (`600` and above, or `bold`) pick the bold face of the same family. Animations and scripts are ignored, and some SVG filters are not supported. Keep templates simple and preview them on both platforms.
180
+
169
181
  ## SVG Template Usage
170
182
 
171
183
  This mode is for Home Screen, Lock Screen, Dynamic Island, and Android widgets that can render resolved SVG. Hotspot actions can switch frames, mutate state, pause/play timers, and emit events for the app to process later.
@@ -0,0 +1,315 @@
1
+ #if canImport(SwiftUI) && canImport(UIKit)
2
+ import SwiftDraw
3
+ import SwiftUI
4
+ import UIKit
5
+
6
+ /// Rasterizes resolved template SVG markup into a bitmap.
7
+ ///
8
+ /// WidgetKit archives widget views as static snapshots, so the SVG is drawn into a `UIImage`
9
+ /// with CoreGraphics instead of relying on live SwiftUI drawing.
10
+ public enum CapgoTemplateSvgRenderer {
11
+ /// Renders `svg` aspect-fit and centered inside `size` (in points).
12
+ /// Returns `nil` when the markup cannot be parsed or the target size is empty.
13
+ public static func render(svg: String, size: CGSize, scale: CGFloat = 0) -> UIImage? {
14
+ guard size.width > 0, size.height > 0, let parsed = parse(svg) else {
15
+ return nil
16
+ }
17
+ return fitted(parsed, in: size).rasterize(scale: scale)
18
+ }
19
+
20
+ /// Renders `svg` at the intrinsic size declared by its `width`/`height` or `viewBox`.
21
+ public static func render(svg: String, scale: CGFloat = 0) -> UIImage? {
22
+ guard let parsed = parse(svg), parsed.size.width > 0, parsed.size.height > 0 else {
23
+ return nil
24
+ }
25
+ return parsed.rasterize(scale: scale)
26
+ }
27
+
28
+ private static func parse(_ svg: String) -> SVG? {
29
+ SVG(xml: CapgoTemplateSvgFontNormalizer.normalize(svg))
30
+ }
31
+
32
+ private static func fitted(_ svg: SVG, in size: CGSize) -> SVG {
33
+ guard svg.size.width > 0, svg.size.height > 0 else {
34
+ return svg.sized(size)
35
+ }
36
+ let factor = min(size.width / svg.size.width, size.height / svg.size.height)
37
+ let scaled = svg.scaled(factor)
38
+ let horizontalInset = max(0, (size.width - scaled.size.width) / 2)
39
+ let verticalInset = max(0, (size.height - scaled.size.height) / 2)
40
+ return scaled.expanded(
41
+ top: verticalInset,
42
+ left: horizontalInset,
43
+ bottom: verticalInset,
44
+ right: horizontalInset
45
+ )
46
+ }
47
+ }
48
+
49
+ /// SwiftDraw resolves text fonts by face name only: it ignores `font-weight` and falls back to Times.
50
+ /// This rewrites `font-family` where a weight is declared, resolving the family inherited from ancestors,
51
+ /// so templates render sans-serif by default and bold weights pick a bold face, matching Android output.
52
+ enum CapgoTemplateSvgFontNormalizer {
53
+ static let regularFamily = "Helvetica Neue"
54
+
55
+ private static let genericFamilies: Set<String> = ["serif", "sans-serif", "monospace", "cursive", "fantasy"]
56
+ // swiftlint:disable force_try
57
+ // Comments, CDATA, and declarations match the first branch and pass through untouched; attribute
58
+ // values are matched as quoted strings so a literal `>` inside them does not end the tag.
59
+ private static let tagPattern = try! NSRegularExpression(
60
+ pattern: #"<!--[\s\S]*?-->|<!\[CDATA\[[\s\S]*?\]\]>|<[?!][^>]*>|<(/?)([A-Za-z][\w:.-]*)((?:[^>"']|"[^"]*"|'[^']*')*)>"#
61
+ )
62
+ private static let weightPattern = try! NSRegularExpression(pattern: #"\sfont-weight\s*=\s*(?:"([^"]*)"|'([^']*)')"#)
63
+ private static let familyPattern = try! NSRegularExpression(pattern: #"\sfont-family\s*=\s*(?:"([^"]*)"|'([^']*)')"#)
64
+ // swiftlint:enable force_try
65
+
66
+ /// Declared (pre-rewrite) font state in effect for an open element, inherited by its descendants.
67
+ private struct FontScope {
68
+ var families: [String]?
69
+ var isBold = false
70
+ }
71
+
72
+ static func normalize(_ svg: String) -> String {
73
+ let source = svg as NSString
74
+ var result = ""
75
+ var cursor = 0
76
+ // Weights and families inherit independently, so each element resolves its face against
77
+ // the family and weight in effect from its ancestors.
78
+ var scopes: [FontScope] = []
79
+ for match in tagPattern.matches(in: svg, range: NSRange(location: 0, length: source.length)) {
80
+ result += source.substring(with: NSRange(location: cursor, length: match.range.location - cursor))
81
+ cursor = match.range.location + match.range.length
82
+ guard match.range(at: 2).location != NSNotFound else {
83
+ result += source.substring(with: match.range)
84
+ continue
85
+ }
86
+ let name = source.substring(with: match.range(at: 2))
87
+ if match.range(at: 1).length > 0 {
88
+ _ = scopes.popLast()
89
+ result += source.substring(with: match.range)
90
+ continue
91
+ }
92
+
93
+ let attributes = source.substring(with: match.range(at: 3))
94
+ let (rewritten, scope) = rewrite(attributes, inherited: scopes.last ?? FontScope(), isRoot: name == "svg")
95
+ result += "<\(name)\(rewritten)>"
96
+ if !attributes.hasSuffix("/") {
97
+ scopes.append(scope)
98
+ }
99
+ }
100
+ result += source.substring(from: cursor)
101
+ return result
102
+ }
103
+
104
+ private static func rewrite(
105
+ _ attributes: String,
106
+ inherited: FontScope,
107
+ isRoot: Bool
108
+ ) -> (attributes: String, scope: FontScope) {
109
+ var body = attributes
110
+ var closing = ""
111
+ if body.hasSuffix("/") {
112
+ body.removeLast()
113
+ closing = "/"
114
+ }
115
+
116
+ let declaredFamilies = value(of: familyPattern, in: body).map(parseFamilies)
117
+ let declaredBold = value(of: weightPattern, in: body).map(isBold)
118
+ let scope = FontScope(
119
+ families: declaredFamilies ?? inherited.families,
120
+ isBold: declaredBold ?? inherited.isBold
121
+ )
122
+ let families = scope.families ?? [regularFamily]
123
+ let replacement: [String]?
124
+ if declaredBold != nil || (declaredFamilies != nil && scope.isBold) {
125
+ // Restating the family on regular weights keeps an ancestor's bold face from leaking in.
126
+ replacement = scope.isBold ? families.compactMap(boldFace) + families : families
127
+ } else {
128
+ replacement = isRoot && declaredFamilies == nil ? [regularFamily] : nil
129
+ }
130
+
131
+ guard let replacement else {
132
+ return (attributes, scope)
133
+ }
134
+ body = familyPattern.stringByReplacingMatches(
135
+ in: body,
136
+ range: NSRange(location: 0, length: (body as NSString).length),
137
+ withTemplate: ""
138
+ )
139
+ let serialized = unique(replacement)
140
+ .map { genericFamilies.contains($0) ? $0 : "'\($0)'" }
141
+ .joined(separator: ", ")
142
+ return ("\(body) font-family=\"\(serialized)\"\(closing)", scope)
143
+ }
144
+
145
+ private static func value(of pattern: NSRegularExpression, in text: String) -> String? {
146
+ let source = text as NSString
147
+ guard let match = pattern.firstMatch(in: text, range: NSRange(location: 0, length: source.length)) else {
148
+ return nil
149
+ }
150
+ for group in 1...2 where match.range(at: group).location != NSNotFound {
151
+ return source.substring(with: match.range(at: group))
152
+ }
153
+ return nil
154
+ }
155
+
156
+ private static func parseFamilies(_ value: String) -> [String] {
157
+ value
158
+ .split(separator: ",")
159
+ .map { $0.trimmingCharacters(in: CharacterSet.whitespaces.union(CharacterSet(charactersIn: "'\""))) }
160
+ .filter { !$0.isEmpty }
161
+ }
162
+
163
+ private static func isBold(_ weight: String) -> Bool {
164
+ let normalized = weight.trimmingCharacters(in: .whitespaces).lowercased()
165
+ if normalized == "bold" || normalized == "bolder" {
166
+ return true
167
+ }
168
+ return (Int(normalized) ?? 400) >= 600
169
+ }
170
+
171
+ private static func boldFace(for family: String) -> String? {
172
+ switch family.lowercased() {
173
+ case "sans-serif", "helvetica neue", "helveticaneue":
174
+ return "HelveticaNeue-Bold"
175
+ case "serif":
176
+ return "TimesNewRomanPS-BoldMT"
177
+ case "monospace":
178
+ return "Menlo-Bold"
179
+ case "cursive", "fantasy":
180
+ return nil
181
+ default:
182
+ return family.replacingOccurrences(of: " ", with: "") + "-Bold"
183
+ }
184
+ }
185
+
186
+ private static func unique(_ families: [String]) -> [String] {
187
+ var seen = Set<String>()
188
+ return families.filter { seen.insert($0.lowercased()).inserted }
189
+ }
190
+ }
191
+
192
+ /// SwiftUI view that renders resolved template SVG markup in Home Screen widgets,
193
+ /// Live Activities, and in-app previews.
194
+ @available(iOS 16.0, *)
195
+ public struct CapgoTemplateSvgView<Fallback: View>: View {
196
+ private let svg: String
197
+ private let fallback: () -> Fallback
198
+
199
+ @Environment(\.displayScale) private var displayScale
200
+
201
+ public init(svg: String, @ViewBuilder fallback: @escaping () -> Fallback) {
202
+ self.svg = svg
203
+ self.fallback = fallback
204
+ }
205
+
206
+ public init(layout: CapgoResolvedTemplateLayout, @ViewBuilder fallback: @escaping () -> Fallback) {
207
+ self.init(svg: layout.svg, fallback: fallback)
208
+ }
209
+
210
+ public var body: some View {
211
+ GeometryReader { proxy in
212
+ if let image = CapgoTemplateSvgRenderer.render(svg: svg, size: proxy.size, scale: displayScale) {
213
+ Image(uiImage: image)
214
+ .resizable()
215
+ .frame(width: proxy.size.width, height: proxy.size.height)
216
+ } else {
217
+ fallback()
218
+ .frame(width: proxy.size.width, height: proxy.size.height)
219
+ }
220
+ }
221
+ }
222
+ }
223
+
224
+ @available(iOS 16.0, *)
225
+ public extension CapgoTemplateSvgView where Fallback == EmptyView {
226
+ init(svg: String) {
227
+ self.init(svg: svg) { EmptyView() }
228
+ }
229
+
230
+ init(layout: CapgoResolvedTemplateLayout) {
231
+ self.init(svg: layout.svg) { EmptyView() }
232
+ }
233
+ }
234
+
235
+ // MARK: - Built-in renderer defaults
236
+ // The placeholder doubles as the fallback when the SVG markup cannot be rendered.
237
+
238
+ @available(iOS 16.0, *)
239
+ public extension CapgoTemplateSurfaceView where SVGContent == CapgoTemplateSvgView<Placeholder> {
240
+ init(
241
+ layout: CapgoResolvedTemplateLayout?,
242
+ showsHotspots: Bool = true,
243
+ @ViewBuilder placeholder: @escaping () -> Placeholder
244
+ ) {
245
+ self.init(
246
+ layout: layout,
247
+ showsHotspots: showsHotspots,
248
+ svgContent: { CapgoTemplateSvgView(layout: $0, fallback: placeholder) },
249
+ placeholder: placeholder
250
+ )
251
+ }
252
+ }
253
+
254
+ @available(iOS 16.0, *)
255
+ public extension CapgoTemplateWidgetSurface where SVGContent == CapgoTemplateSvgView<Placeholder> {
256
+ init(
257
+ activityId: String,
258
+ surface: CapgoTemplateSurface = .lockScreen,
259
+ bundle: Bundle = .main,
260
+ showsHotspots: Bool = true,
261
+ now: @escaping () -> Date = { Date() },
262
+ @ViewBuilder placeholder: @escaping () -> Placeholder
263
+ ) {
264
+ self.init(
265
+ activityId: activityId,
266
+ surface: surface,
267
+ bundle: bundle,
268
+ showsHotspots: showsHotspots,
269
+ now: now,
270
+ svgContent: { CapgoTemplateSvgView(layout: $0, fallback: placeholder) },
271
+ placeholder: placeholder
272
+ )
273
+ }
274
+ }
275
+
276
+ @available(iOS 16.0, *)
277
+ public extension CapgoTemplateLatestWidgetSurface where SVGContent == CapgoTemplateSvgView<Placeholder> {
278
+ init(
279
+ surface: CapgoTemplateSurface = .lockScreen,
280
+ status: String? = "active",
281
+ bundle: Bundle = .main,
282
+ showsHotspots: Bool = true,
283
+ now: @escaping () -> Date = { Date() },
284
+ @ViewBuilder placeholder: @escaping () -> Placeholder
285
+ ) {
286
+ self.init(
287
+ surface: surface,
288
+ status: status,
289
+ bundle: bundle,
290
+ showsHotspots: showsHotspots,
291
+ now: now,
292
+ svgContent: { CapgoTemplateSvgView(layout: $0, fallback: placeholder) },
293
+ placeholder: placeholder
294
+ )
295
+ }
296
+ }
297
+
298
+ #if canImport(WidgetKit)
299
+ @available(iOS 16.0, *)
300
+ public extension CapgoTemplateHomeWidgetView where SVGContent == CapgoTemplateSvgView<Placeholder> {
301
+ init(
302
+ entry: CapgoTemplateWidgetEntry,
303
+ showsHotspots: Bool = true,
304
+ @ViewBuilder placeholder: @escaping () -> Placeholder
305
+ ) {
306
+ self.init(
307
+ entry: entry,
308
+ showsHotspots: showsHotspots,
309
+ svgContent: { CapgoTemplateSvgView(layout: $0, fallback: placeholder) },
310
+ placeholder: placeholder
311
+ )
312
+ }
313
+ }
314
+ #endif
315
+ #endif
@@ -1,5 +1,8 @@
1
1
  import Capacitor
2
+ #if canImport(CapgoWidgetKitShared)
3
+ // SwiftPM splits the shared widget code into its own module; CocoaPods compiles it into this one.
2
4
  import CapgoWidgetKitShared
5
+ #endif
3
6
  import Foundation
4
7
 
5
8
  @objc(CapgoWidgetKitPlugin)
@@ -0,0 +1,202 @@
1
+ #if canImport(UIKit)
2
+ import UIKit
3
+ import XCTest
4
+ @testable import CapgoWidgetKitShared
5
+
6
+ final class CapgoTemplateSvgRendererTests: XCTestCase {
7
+ private let redBar = """
8
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 40">\
9
+ <rect x="0" y="0" width="100" height="40" fill="#ff0000"/>\
10
+ </svg>
11
+ """
12
+
13
+ func testRendersSvgMarkupAtRequestedSize() throws {
14
+ let image = try XCTUnwrap(
15
+ CapgoTemplateSvgRenderer.render(svg: redBar, size: CGSize(width: 200, height: 80), scale: 1)
16
+ )
17
+
18
+ XCTAssertEqual(image.size, CGSize(width: 200, height: 80))
19
+ let center = try XCTUnwrap(pixel(in: image, column: 100, row: 40))
20
+ XCTAssertEqual(center.red, 255)
21
+ XCTAssertEqual(center.alpha, 255)
22
+ }
23
+
24
+ func testAspectFitsAndCentersInsideTargetSize() throws {
25
+ let image = try XCTUnwrap(
26
+ CapgoTemplateSvgRenderer.render(svg: redBar, size: CGSize(width: 200, height: 200), scale: 1)
27
+ )
28
+
29
+ XCTAssertEqual(image.size, CGSize(width: 200, height: 200))
30
+ let letterbox = try XCTUnwrap(pixel(in: image, column: 100, row: 10))
31
+ XCTAssertEqual(letterbox.alpha, 0)
32
+ let content = try XCTUnwrap(pixel(in: image, column: 100, row: 100))
33
+ XCTAssertEqual(content.red, 255)
34
+ XCTAssertEqual(content.alpha, 255)
35
+ }
36
+
37
+ func testRendersResolvedTemplateWithText() throws {
38
+ let svg = """
39
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 40">\
40
+ <rect width="100" height="40" fill="#000000"/>\
41
+ <text x="6" y="26" font-size="20" fill="#ffffff">1:30</text>\
42
+ </svg>
43
+ """
44
+ let image = try XCTUnwrap(
45
+ CapgoTemplateSvgRenderer.render(svg: svg, size: CGSize(width: 100, height: 40), scale: 2)
46
+ )
47
+
48
+ XCTAssertEqual(image.size, CGSize(width: 100, height: 40))
49
+ var hasLightPixel = false
50
+ for column in 6..<60 {
51
+ for row in 10..<30 where (pixel(in: image, column: column, row: row)?.red ?? 0) > 128 {
52
+ hasLightPixel = true
53
+ }
54
+ }
55
+ XCTAssertTrue(hasLightPixel, "Expected the <text> element to be drawn")
56
+ }
57
+
58
+ func testReturnsNilForInvalidMarkupOrEmptySize() {
59
+ XCTAssertNil(CapgoTemplateSvgRenderer.render(svg: "not an svg", size: CGSize(width: 10, height: 10)))
60
+ XCTAssertNil(CapgoTemplateSvgRenderer.render(svg: "", size: CGSize(width: 10, height: 10)))
61
+ XCTAssertNil(CapgoTemplateSvgRenderer.render(svg: redBar, size: .zero))
62
+ }
63
+
64
+ func testRendersAtIntrinsicSize() throws {
65
+ let image = try XCTUnwrap(CapgoTemplateSvgRenderer.render(svg: redBar, scale: 1))
66
+ XCTAssertEqual(image.size, CGSize(width: 100, height: 40))
67
+ }
68
+
69
+ func testFontNormalizerDefaultsRootToSansSerif() {
70
+ let normalized = CapgoTemplateSvgFontNormalizer.normalize(#"<svg viewBox="0 0 10 10"><text>A</text></svg>"#)
71
+ XCTAssertEqual(normalized, #"<svg viewBox="0 0 10 10" font-family="'Helvetica Neue'"><text>A</text></svg>"#)
72
+ }
73
+
74
+ func testFontNormalizerMapsBoldWeightsToBoldFaces() {
75
+ let normalized = CapgoTemplateSvgFontNormalizer.normalize(
76
+ #"<svg><text font-weight="700">A</text>"#
77
+ + #"<text font-family="serif" font-weight='bold'>B</text><textPath font-weight="400"/></svg>"#
78
+ )
79
+
80
+ XCTAssertTrue(normalized.contains(#"<text font-weight="700" font-family="'HelveticaNeue-Bold', 'Helvetica Neue'">"#))
81
+ XCTAssertTrue(normalized.contains(#"<text font-weight='bold' font-family="'TimesNewRomanPS-BoldMT', serif">"#))
82
+ XCTAssertTrue(normalized.contains(#"<textPath font-weight="400" font-family="'Helvetica Neue'"/>"#))
83
+ }
84
+
85
+ func testFontNormalizerCarriesInheritedBoldThroughFamilyOverrides() {
86
+ let normalized = CapgoTemplateSvgFontNormalizer.normalize(
87
+ #"<svg><g font-weight="bold"><text font-family="Georgia">A</text>"#
88
+ + #"<text font-family="Menlo" font-weight="400">B</text></g><text font-family="Georgia">C</text></svg>"#
89
+ )
90
+
91
+ XCTAssertTrue(normalized.contains(#"<text font-family="'Georgia-Bold', 'Georgia'">A"#))
92
+ XCTAssertTrue(normalized.contains(#"<text font-weight="400" font-family="'Menlo'">B"#))
93
+ XCTAssertTrue(normalized.contains(#"</g><text font-family="Georgia">C"#))
94
+ }
95
+
96
+ func testFontNormalizerHandlesQuotedAngleBracketsAndComments() throws {
97
+ let markup = #"<?xml version="1.0"?><svg xmlns="http://www.w3.org/2000/svg" aria-label="a > b" viewBox="0 0 10 10">"#
98
+ + #"<!-- <g font-weight="bold"> --><text data-x='1 > 0' font-weight="700">A</text>"#
99
+ + ##"<rect width="10" height="10" fill="#ff0000"/></svg>"##
100
+ let normalized = CapgoTemplateSvgFontNormalizer.normalize(markup)
101
+
102
+ XCTAssertTrue(normalized.hasPrefix(
103
+ #"<?xml version="1.0"?><svg xmlns="http://www.w3.org/2000/svg" aria-label="a > b" viewBox="0 0 10 10" font-family="'Helvetica Neue'">"#
104
+ ))
105
+ XCTAssertTrue(normalized.contains(#"<!-- <g font-weight="bold"> -->"#))
106
+ XCTAssertTrue(normalized.contains(
107
+ #"<text data-x='1 > 0' font-weight="700" font-family="'HelveticaNeue-Bold', 'Helvetica Neue'">A"#
108
+ ))
109
+ XCTAssertTrue(XMLParser(data: Data(normalized.utf8)).parse())
110
+ XCTAssertNotNil(CapgoTemplateSvgRenderer.render(svg: markup, size: CGSize(width: 10, height: 10), scale: 1))
111
+ }
112
+
113
+ func testFontNormalizerKeepsGenericFallbacksFromInheritedFamilies() {
114
+ let normalized = CapgoTemplateSvgFontNormalizer.normalize(
115
+ #"<svg font-family="Avenir Next, sans-serif"><text font-weight="700">A</text><textPath font-weight="400"/></svg>"#
116
+ )
117
+
118
+ XCTAssertTrue(normalized.contains(#"<svg font-family="Avenir Next, sans-serif">"#))
119
+ XCTAssertTrue(normalized.contains(
120
+ #"<text font-weight="700" font-family="'AvenirNext-Bold', 'HelveticaNeue-Bold', 'Avenir Next', sans-serif">"#
121
+ ))
122
+ XCTAssertTrue(normalized.contains(#"<textPath font-weight="400" font-family="'Avenir Next', sans-serif"/>"#))
123
+ }
124
+
125
+ func testFontNormalizerKeepsExplicitFamiliesWithoutWeights() {
126
+ let markup = #"<svg font-family="Menlo"><rect width="1"/><text font-family="Georgia">A</text></svg>"#
127
+ XCTAssertEqual(CapgoTemplateSvgFontNormalizer.normalize(markup), markup)
128
+ }
129
+
130
+ func testFontNormalizerResolvesWeightsAgainstInheritedFamilies() {
131
+ let normalized = CapgoTemplateSvgFontNormalizer.normalize(
132
+ #"<svg font-family="Menlo"><g><text font-weight="700">A</text></g>"#
133
+ + #"<g font-family="Georgia" font-weight="bold"><text font-weight="400">B</text></g>"#
134
+ + #"<text font-weight="normal">C</text></svg>"#
135
+ )
136
+
137
+ XCTAssertTrue(normalized.contains(#"<text font-weight="700" font-family="'Menlo-Bold', 'Menlo'">A"#))
138
+ XCTAssertTrue(normalized.contains(#"<g font-weight="bold" font-family="'Georgia-Bold', 'Georgia'">"#))
139
+ XCTAssertTrue(normalized.contains(#"<text font-weight="400" font-family="'Georgia'">B"#))
140
+ XCTAssertTrue(normalized.contains(#"</g><text font-weight="normal" font-family="'Menlo'">C"#))
141
+ }
142
+
143
+ func testBoldTextRendersHeavierThanRegularText() throws {
144
+ func inkCoverage(weight: String) throws -> Int {
145
+ let svg = """
146
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 40">\
147
+ <text x="4" y="30" font-size="28" font-weight="\(weight)" fill="#000000">Hello</text>\
148
+ </svg>
149
+ """
150
+ let image = try XCTUnwrap(
151
+ CapgoTemplateSvgRenderer.render(svg: svg, size: CGSize(width: 100, height: 40), scale: 1)
152
+ )
153
+ var covered = 0
154
+ for column in 0..<100 {
155
+ for row in 0..<40 where (pixel(in: image, column: column, row: row)?.alpha ?? 0) > 128 {
156
+ covered += 1
157
+ }
158
+ }
159
+ return covered
160
+ }
161
+
162
+ XCTAssertGreaterThan(try inkCoverage(weight: "700"), try inkCoverage(weight: "400"))
163
+ }
164
+
165
+ private struct Pixel {
166
+ let red: UInt8
167
+ let green: UInt8
168
+ let blue: UInt8
169
+ let alpha: UInt8
170
+ }
171
+
172
+ /// Samples one pixel in point coordinates.
173
+ private func pixel(in image: UIImage, column: Int, row: Int) -> Pixel? {
174
+ guard let cgImage = image.cgImage else {
175
+ return nil
176
+ }
177
+ let pixelX = Int(CGFloat(column) * image.scale)
178
+ let pixelY = Int(CGFloat(row) * image.scale)
179
+ var data = [UInt8](repeating: 0, count: 4)
180
+ let drawn = data.withUnsafeMutableBytes { buffer -> Bool in
181
+ guard let context = CGContext(
182
+ data: buffer.baseAddress,
183
+ width: 1,
184
+ height: 1,
185
+ bitsPerComponent: 8,
186
+ bytesPerRow: 4,
187
+ space: CGColorSpaceCreateDeviceRGB(),
188
+ bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue
189
+ ) else {
190
+ return false
191
+ }
192
+ context.translateBy(x: CGFloat(-pixelX), y: CGFloat(pixelY - cgImage.height + 1))
193
+ context.draw(cgImage, in: CGRect(x: 0, y: 0, width: cgImage.width, height: cgImage.height))
194
+ return true
195
+ }
196
+ guard drawn else {
197
+ return nil
198
+ }
199
+ return Pixel(red: data[0], green: data[1], blue: data[2], alpha: data[3])
200
+ }
201
+ }
202
+ #endif
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capgo/capacitor-widget-kit",
3
- "version": "8.1.15",
3
+ "version": "8.2.0",
4
4
  "private": false,
5
5
  "description": "Capacitor plugin for generic iOS Home Screen widgets, WidgetKit, and Live Activities using SVG templates, declarative actions, and shared App Group persistence.",
6
6
  "main": "dist/plugin.cjs.js",