expo-modules-core 58.0.29 → 58.1.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.
Files changed (32) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/ExpoModulesCore.podspec +6 -8
  3. package/android/build.gradle +2 -2
  4. package/android/prebuilt/metadata.json +1 -1
  5. package/android/prebuilt/native-libs.tar.xz +0 -0
  6. package/android/src/main/java/expo/modules/adapters/react/apploader/RNHeadlessAppLoader.kt +2 -3
  7. package/ios/Benchmarks/FunctionBenchmarks.swift +2 -14
  8. package/ios/Core/AppContext.swift +29 -2
  9. package/ios/Core/Arguments/Convertibles.swift +1 -24
  10. package/ios/Core/Coding/JavaScriptCodable+Color.swift +887 -0
  11. package/ios/Core/Coding/JavaScriptCodable+URL.swift +55 -0
  12. package/ios/Core/Convertibles/Convertibles+Color.swift +10 -686
  13. package/ios/Core/Events/EventEmitter.swift +194 -1
  14. package/ios/Core/ExpoModulesMacros.swift +50 -8
  15. package/ios/Core/ExpoPackage.swift +29 -0
  16. package/ios/Core/Logging/Logger.swift +8 -2
  17. package/ios/Core/ModulesProvider.swift +19 -0
  18. package/ios/Core/Records/Record.swift +18 -6
  19. package/ios/Core/SharedObjects/SharedObjectRegistry.swift +28 -16
  20. package/ios/Core/Views/SwiftUI/Convertibles+SwiftUI.swift +2 -67
  21. package/ios/Core/Views/SwiftUI/SwiftUIHostingView.swift +1 -0
  22. package/ios/Core/Views/SwiftUI/SwiftUIViewHost.swift +100 -39
  23. package/ios/Core/Views/SwiftUI/SwiftUIVirtualView.swift +1 -0
  24. package/ios/ReactDelegates/ExpoReactDelegate.swift +1 -1
  25. package/ios/ReactDelegates/ExpoRootViewController.swift +22 -0
  26. package/package.json +4 -4
  27. package/prebuilds/output/debug/xcframeworks/ExpoModulesCore.tar.gz +0 -0
  28. package/prebuilds/output/debug/xcframeworks/ExpoModulesWorklets.tar.gz +0 -0
  29. package/prebuilds/output/headers/xcframeworks/ExpoModulesCoreHeaders.tar.gz +0 -0
  30. package/prebuilds/output/release/xcframeworks/ExpoModulesCore.tar.gz +0 -0
  31. package/prebuilds/output/release/xcframeworks/ExpoModulesWorklets.tar.gz +0 -0
  32. package/spm.config.json +4 -1
@@ -0,0 +1,887 @@
1
+ // Copyright 2026-present 650 Industries. All rights reserved.
2
+
3
+ import ExpoModulesJSI
4
+ import RegexBuilder
5
+ import SwiftUI
6
+
7
+ // The color types decode from a string, a number, an array of components, or a `PlatformColor` or
8
+ // `DynamicColorIOS` object, and encode as the `#rrggbbaa` string that `UIColor.string` returns. A string or a
9
+ // number is read straight from the JavaScript value. Any other value is read through `getAny()` and decoded by
10
+ // `uiColorFromAny(_:)`, which the `Convertible` conformances also call, so both paths accept the same values and
11
+ // throw the same exceptions.
12
+
13
+ extension UIColor: @retroactive JavaScriptDecodable, @retroactive JavaScriptEncodable {
14
+ public static var decodableKinds: JavaScriptValueKinds {
15
+ return [.string, .number, .object]
16
+ }
17
+
18
+ @JavaScriptActor
19
+ public static func decode(_ value: borrowing JavaScriptUnownedValue, in runtime: borrowing JavaScriptRuntime) throws
20
+ -> Self
21
+ {
22
+ // swiftlint:disable:next force_cast
23
+ return try colorFromJavaScriptValue(value, in: runtime) as! Self
24
+ }
25
+
26
+ // The parameter is `UIColor` rather than `Self` because a non-final class can't take a covariant `Self`.
27
+ @JavaScriptActor
28
+ public static func encode(_ value: UIColor, in runtime: borrowing JavaScriptRuntime) throws -> JavaScriptValue {
29
+ return try String.encode(colorToString(value), in: runtime)
30
+ }
31
+ }
32
+
33
+ extension CGColor: @retroactive JavaScriptDecodable, @retroactive JavaScriptEncodable {
34
+ public static var decodableKinds: JavaScriptValueKinds {
35
+ return UIColor.decodableKinds
36
+ }
37
+
38
+ @JavaScriptActor
39
+ public static func decode(_ value: borrowing JavaScriptUnownedValue, in runtime: borrowing JavaScriptRuntime) throws
40
+ -> Self
41
+ {
42
+ do {
43
+ // swiftlint:disable:next force_cast
44
+ return try colorFromJavaScriptValue(value, in: runtime).cgColor as! Self
45
+ } catch _ as Conversions.ConvertingException<UIColor> {
46
+ throw Conversions.ConvertingException<CGColor>(value.copied(in: runtime).getAny())
47
+ }
48
+ }
49
+
50
+ @JavaScriptActor
51
+ public static func encode(_ value: CGColor, in runtime: borrowing JavaScriptRuntime) throws -> JavaScriptValue {
52
+ #if os(macOS)
53
+ // `NSColor(cgColor:)` is failable.
54
+ guard let color = UIColor(cgColor: value) else {
55
+ return .null()
56
+ }
57
+ #else
58
+ let color = UIColor(cgColor: value)
59
+ #endif
60
+ return try UIColor.encode(color, in: runtime)
61
+ }
62
+ }
63
+
64
+ extension Color: @retroactive JavaScriptDecodable, @retroactive JavaScriptEncodable {
65
+ public static var decodableKinds: JavaScriptValueKinds {
66
+ return UIColor.decodableKinds
67
+ }
68
+
69
+ @JavaScriptActor
70
+ public static func decode(_ value: borrowing JavaScriptUnownedValue, in runtime: borrowing JavaScriptRuntime) throws
71
+ -> Color
72
+ {
73
+ // Like `swiftUIColorFromAny(_:)`, any error from the `UIColor` decode falls back to the SwiftUI color names.
74
+ if let uiColor = try? colorFromJavaScriptValue(value, in: runtime) {
75
+ return Color(uiColor)
76
+ }
77
+ if value.isString(), let color = swiftUIColorFromName(value.getString()) {
78
+ return color
79
+ }
80
+ throw Conversions.ConvertingException<Color>(value.copied(in: runtime).getAny())
81
+ }
82
+
83
+ /// Encodes the color as a `#rrggbbaa` string. A dynamic or semantic color, such as `.primary`, is resolved to
84
+ /// a fixed value for the current appearance.
85
+ @JavaScriptActor
86
+ public static func encode(_ value: Color, in runtime: borrowing JavaScriptRuntime) throws -> JavaScriptValue {
87
+ return try UIColor.encode(UIColor(value), in: runtime)
88
+ }
89
+ }
90
+
91
+ extension UIColor {
92
+ public var string: String {
93
+ return colorToString(self)
94
+ }
95
+ }
96
+
97
+ // MARK: - Conversions
98
+
99
+ @JavaScriptActor
100
+ private func colorFromJavaScriptValue(
101
+ _ value: borrowing JavaScriptUnownedValue,
102
+ in runtime: borrowing JavaScriptRuntime
103
+ ) throws -> UIColor {
104
+ if value.isString() {
105
+ return try colorFromNameOrString(value.getString())
106
+ }
107
+ if value.isNumber() {
108
+ return try colorFromNumber(value.getDouble())
109
+ }
110
+ return try uiColorFromAny(value.copied(in: runtime).getAny())
111
+ }
112
+
113
+ // Internal for the `Convertible` conformance, can become private when the Convertibles are removed.
114
+ internal func uiColorFromAny(_ value: Any?) throws -> UIColor {
115
+ if let value = value as? String {
116
+ return try colorFromNameOrString(value)
117
+ }
118
+ if let components = value as? [Double] {
119
+ return try uiColorWithComponents(components)
120
+ }
121
+ if let value = value as? Int {
122
+ return try colorFromArgb(UInt64(value))
123
+ }
124
+ if let value = value as? Double {
125
+ return try colorFromNumber(value)
126
+ }
127
+
128
+ // Handle `PlatformColor` and `DynamicColorIOS`
129
+ if let opaqueValue = value as? [String: Any] {
130
+ if let semanticName = opaqueValue["semantic"] as? String,
131
+ let color = resolveNamedColor(name: semanticName)
132
+ {
133
+ return color
134
+ }
135
+ if let semanticArray = opaqueValue["semantic"] as? [String] {
136
+ for semanticName in semanticArray {
137
+ if let color = resolveNamedColor(name: semanticName) {
138
+ return color
139
+ }
140
+ }
141
+ }
142
+ if let appearances = opaqueValue["dynamic"] as? [String: Any],
143
+ let lightColor = try appearances["light"].map({ try uiColorFromAny($0) }),
144
+ let darkColor = try appearances["dark"].map({ try uiColorFromAny($0) })
145
+ {
146
+ let highContrastLightColor = try appearances["highContrastLight"].map({ try uiColorFromAny($0) })
147
+ let highContrastDarkColor = try appearances["highContrastDark"].map({ try uiColorFromAny($0) })
148
+
149
+ #if os(iOS) || os(tvOS)
150
+ return UIColor { (traitCollection: UITraitCollection) -> UIColor in
151
+ if traitCollection.userInterfaceStyle == .dark {
152
+ if traitCollection.accessibilityContrast == .high, let highContrastDarkColor {
153
+ return highContrastDarkColor
154
+ }
155
+ return darkColor
156
+ }
157
+
158
+ if traitCollection.accessibilityContrast == .high, let highContrastLightColor {
159
+ return highContrastLightColor
160
+ }
161
+ return lightColor
162
+ }
163
+ #elseif os(macOS)
164
+ return NSColor(name: nil) { (appearance: NSAppearance) -> NSColor in
165
+ let isDarkMode = appearance.bestMatch(from: [.darkAqua, .aqua]) == .darkAqua
166
+ let isHighContrast = NSWorkspace.shared.accessibilityDisplayShouldIncreaseContrast
167
+
168
+ if isDarkMode {
169
+ if isHighContrast, let highContrastDarkColor = highContrastDarkColor {
170
+ return highContrastDarkColor
171
+ }
172
+ return darkColor
173
+ }
174
+
175
+ if isHighContrast, let highContrastLightColor = highContrastLightColor {
176
+ return highContrastLightColor
177
+ }
178
+ return lightColor
179
+ }
180
+ #endif
181
+ }
182
+ }
183
+ if let color = value as? UIColor {
184
+ return color
185
+ }
186
+ throw Conversions.ConvertingException<UIColor>(value)
187
+ }
188
+
189
+ // Internal for the `Convertible` conformance, can become private when the Convertibles are removed.
190
+ internal func cgColorFromAny(_ value: Any?) throws -> CGColor {
191
+ do {
192
+ return try uiColorFromAny(value).cgColor
193
+ } catch _ as Conversions.ConvertingException<UIColor> {
194
+ // Rethrow `ConvertingError` with proper type
195
+ throw Conversions.ConvertingException<CGColor>(value)
196
+ }
197
+ }
198
+
199
+ // Internal for the `Convertible` conformance, can become private when the Convertibles are removed.
200
+ internal func swiftUIColorFromAny(_ value: Any?) throws -> Color {
201
+ if let uiColor = try? uiColorFromAny(value) {
202
+ return Color(uiColor)
203
+ }
204
+ // Context-dependent colors
205
+ if let stringValue = value as? String, let color = swiftUIColorFromName(stringValue) {
206
+ return color
207
+ }
208
+ throw Conversions.ConvertingException<Color>(value)
209
+ }
210
+
211
+ private func swiftUIColorFromName(_ name: String) -> Color? {
212
+ switch name {
213
+ case "primary":
214
+ return .primary
215
+ case "secondary":
216
+ return .secondary
217
+ case "red":
218
+ return .red
219
+ case "orange":
220
+ return .orange
221
+ case "yellow":
222
+ return .yellow
223
+ case "green":
224
+ return .green
225
+ case "blue":
226
+ return .blue
227
+ case "purple":
228
+ return .purple
229
+ case "pink":
230
+ return .pink
231
+ case "white":
232
+ return .white
233
+ case "gray":
234
+ return .gray
235
+ case "black":
236
+ return .black
237
+ case "clear":
238
+ return .clear
239
+ case "mint":
240
+ if #available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *) {
241
+ return .mint
242
+ }
243
+ return nil
244
+ case "teal":
245
+ if #available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *) {
246
+ return .teal
247
+ }
248
+ return nil
249
+ case "cyan":
250
+ if #available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *) {
251
+ return .cyan
252
+ }
253
+ return nil
254
+ case "indigo":
255
+ if #available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *) {
256
+ return .indigo
257
+ }
258
+ return nil
259
+ case "brown":
260
+ if #available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *) {
261
+ return .brown
262
+ }
263
+ return nil
264
+ default:
265
+ return nil
266
+ }
267
+ }
268
+
269
+ private func colorFromNameOrString(_ value: String) throws -> UIColor {
270
+ if let namedColorComponents = namedColors[value] {
271
+ return try uiColorWithComponents(namedColorComponents)
272
+ }
273
+ return try colorFromString(value)
274
+ }
275
+
276
+ private func colorFromNumber(_ value: Double) throws -> UIColor {
277
+ return try colorFromArgb(UInt64(value))
278
+ }
279
+
280
+ private func colorToString(_ color: UIColor) -> String {
281
+ var r: CGFloat = 0
282
+ var g: CGFloat = 0
283
+ var b: CGFloat = 0
284
+ var a: CGFloat = 0
285
+
286
+ #if os(macOS)
287
+ // `getRed` raises for a color that isn't in an RGB color space, such as a catalog or dynamic color.
288
+ guard let rgbColor = color.usingColorSpace(.sRGB) else {
289
+ return "#00000000"
290
+ }
291
+ rgbColor.getRed(&r, green: &g, blue: &b, alpha: &a)
292
+ return String(
293
+ format: "#%02x%02x%02x%02x",
294
+ Int((r * 255).rounded()),
295
+ Int((g * 255).rounded()),
296
+ Int((b * 255).rounded()),
297
+ Int((a * 255).rounded())
298
+ )
299
+ #else
300
+ if color.getRed(&r, green: &g, blue: &b, alpha: &a) {
301
+ return String(
302
+ format: "#%02x%02x%02x%02x",
303
+ Int((r * 255).rounded()),
304
+ Int((g * 255).rounded()),
305
+ Int((b * 255).rounded()),
306
+ Int((a * 255).rounded())
307
+ )
308
+ }
309
+ return "#00000000"
310
+ #endif
311
+ }
312
+
313
+ // MARK: - Platform Color Helpers
314
+
315
+ private func resolveNamedColor(name: String) -> UIColor? {
316
+ return UIColor(named: name) ?? uiColorFromSemanticName(name: name)
317
+ }
318
+
319
+ private func uiColorFromSemanticName(name: String) -> UIColor? {
320
+ let selector: Selector
321
+ if name.hasSuffix("Color") {
322
+ selector = Selector(name)
323
+ } else {
324
+ selector = Selector("\(name)Color")
325
+ }
326
+ guard UIColor.responds(to: selector) else {
327
+ return nil
328
+ }
329
+
330
+ return UIColor.perform(selector).takeUnretainedValue() as? UIColor
331
+ }
332
+
333
+ private func uiColorWithComponents(_ components: [Double]) throws -> UIColor {
334
+ guard components.count >= 3 else {
335
+ throw InvalidColorComponentsException(components.count)
336
+ }
337
+ let alpha = components.count > 3 ? components[3] : 1.0
338
+ return UIColor(red: components[0], green: components[1], blue: components[2], alpha: alpha)
339
+ }
340
+
341
+ // MARK: - Color String Parsing
342
+
343
+ /// Parses a color string (hex, rgb, hsl, hwb) into a UIColor.
344
+ private func colorFromString(_ value: String) throws -> UIColor {
345
+ let input = value.trimmingCharacters(in: .whitespacesAndNewlines)
346
+ let lowercased = input.lowercased()
347
+
348
+ if lowercased.hasPrefix("rgb") {
349
+ return try colorFromRGBString(lowercased)
350
+ }
351
+ if lowercased.hasPrefix("hsl") {
352
+ return try colorFromHSLString(lowercased)
353
+ }
354
+ if lowercased.hasPrefix("hwb") {
355
+ return try colorFromHWBString(lowercased)
356
+ }
357
+
358
+ var hexStr = input.replacingOccurrences(of: "#", with: "")
359
+
360
+ if hexStr.count == 6 { hexStr += "FF" }
361
+ if hexStr.count == 3 { hexStr += "F" }
362
+
363
+ // Expand short form (supported by Web)
364
+ if hexStr.count == 4 {
365
+ let chars = Array(hexStr)
366
+ hexStr = [
367
+ String(repeating: chars[0], count: 2),
368
+ String(repeating: chars[1], count: 2),
369
+ String(repeating: chars[2], count: 2),
370
+ String(repeating: chars[3], count: 2),
371
+ ].joined(separator: "")
372
+ }
373
+
374
+ var rgba: UInt64 = 0
375
+
376
+ guard hexStr.range(of: #"^[0-9a-fA-F]{8}$"#, options: .regularExpression) != nil,
377
+ Scanner(string: hexStr).scanHexInt64(&rgba)
378
+ else {
379
+ throw InvalidHexColorException(input)
380
+ }
381
+ return try colorFromRgba(rgba)
382
+ }
383
+
384
+ private func colorFromArgb(_ argb: UInt64) throws -> UIColor {
385
+ guard argb <= UInt32.max else {
386
+ throw HexColorOverflowException(argb)
387
+ }
388
+ let alpha = CGFloat((argb >> 24) & 0xff) / 255.0
389
+ let red = CGFloat((argb >> 16) & 0xff) / 255.0
390
+ let green = CGFloat((argb >> 8) & 0xff) / 255.0
391
+ let blue = CGFloat(argb & 0xff) / 255.0
392
+ return UIColor(red: red, green: green, blue: blue, alpha: alpha)
393
+ }
394
+
395
+ private func colorFromRgba(_ rgba: UInt64) throws -> UIColor {
396
+ guard rgba <= UInt32.max else {
397
+ throw HexColorOverflowException(rgba)
398
+ }
399
+ let red = CGFloat((rgba >> 24) & 0xff) / 255.0
400
+ let green = CGFloat((rgba >> 16) & 0xff) / 255.0
401
+ let blue = CGFloat((rgba >> 8) & 0xff) / 255.0
402
+ let alpha = CGFloat(rgba & 0xff) / 255.0
403
+ return UIColor(red: red, green: green, blue: blue, alpha: alpha)
404
+ }
405
+
406
+ // MARK: - CSS Color Function Regex Patterns
407
+
408
+ // These are built from RegexBuilder primitives only. Composing regex-literal fragments
409
+ // (e.g. /hsla?\(\s*/) inside a builder miscompiles on some OS runtime versions
410
+ // (observed on the iOS 27.0 beta simulator) and the patterns silently stop matching.
411
+
412
+ /// A CSS number like `-12`, `+1.5`, `.5` or `100`.
413
+ nonisolated(unsafe) private let cssNumber = Regex {
414
+ Optionally {
415
+ CharacterClass.anyOf("-+")
416
+ }
417
+ ZeroOrMore(.digit)
418
+ Optionally {
419
+ "."
420
+ }
421
+ OneOrMore(.digit)
422
+ }
423
+
424
+ nonisolated(unsafe) private let cssNumberOrPercent = Regex {
425
+ cssNumber
426
+ Optionally {
427
+ "%"
428
+ }
429
+ }
430
+
431
+ nonisolated(unsafe) private let commaSeparator = Regex {
432
+ ZeroOrMore(.whitespace)
433
+ ","
434
+ ZeroOrMore(.whitespace)
435
+ }
436
+
437
+ nonisolated(unsafe) private let rgbCommaRegex = Regex {
438
+ "rgb"
439
+ Optionally {
440
+ "a"
441
+ }
442
+ "("
443
+ ZeroOrMore(.whitespace)
444
+ Capture {
445
+ cssNumberOrPercent
446
+ }
447
+ commaSeparator
448
+ Capture {
449
+ cssNumberOrPercent
450
+ }
451
+ commaSeparator
452
+ Capture {
453
+ cssNumberOrPercent
454
+ }
455
+ Optionally {
456
+ commaSeparator
457
+ Capture {
458
+ cssNumberOrPercent
459
+ }
460
+ }
461
+ ZeroOrMore(.whitespace)
462
+ ")"
463
+ }.ignoresCase()
464
+
465
+ nonisolated(unsafe) private let rgbSpaceRegex = Regex {
466
+ "rgb"
467
+ Optionally {
468
+ "a"
469
+ }
470
+ "("
471
+ ZeroOrMore(.whitespace)
472
+ Capture {
473
+ cssNumberOrPercent
474
+ }
475
+ OneOrMore(.whitespace)
476
+ Capture {
477
+ cssNumberOrPercent
478
+ }
479
+ OneOrMore(.whitespace)
480
+ Capture {
481
+ cssNumberOrPercent
482
+ }
483
+ Optionally {
484
+ ZeroOrMore(.whitespace)
485
+ "/"
486
+ ZeroOrMore(.whitespace)
487
+ Capture {
488
+ cssNumberOrPercent
489
+ }
490
+ }
491
+ ZeroOrMore(.whitespace)
492
+ ")"
493
+ }.ignoresCase()
494
+
495
+ nonisolated(unsafe) private let hslCommaRegex = Regex {
496
+ "hsl"
497
+ Optionally {
498
+ "a"
499
+ }
500
+ "("
501
+ ZeroOrMore(.whitespace)
502
+ Capture {
503
+ cssNumber
504
+ }
505
+ commaSeparator
506
+ Capture {
507
+ cssNumber
508
+ }
509
+ "%"
510
+ commaSeparator
511
+ Capture {
512
+ cssNumber
513
+ }
514
+ "%"
515
+ ZeroOrMore(.whitespace)
516
+ Optionally {
517
+ ","
518
+ ZeroOrMore(.whitespace)
519
+ Capture {
520
+ cssNumberOrPercent
521
+ }
522
+ }
523
+ ZeroOrMore(.whitespace)
524
+ ")"
525
+ }.ignoresCase()
526
+
527
+ nonisolated(unsafe) private let hslSpaceRegex = Regex {
528
+ "hsl"
529
+ Optionally {
530
+ "a"
531
+ }
532
+ "("
533
+ ZeroOrMore(.whitespace)
534
+ Capture {
535
+ cssNumber
536
+ }
537
+ OneOrMore(.whitespace)
538
+ Capture {
539
+ cssNumber
540
+ }
541
+ "%"
542
+ OneOrMore(.whitespace)
543
+ Capture {
544
+ cssNumber
545
+ }
546
+ "%"
547
+ ZeroOrMore(.whitespace)
548
+ Optionally {
549
+ "/"
550
+ ZeroOrMore(.whitespace)
551
+ Capture {
552
+ cssNumberOrPercent
553
+ }
554
+ }
555
+ ZeroOrMore(.whitespace)
556
+ ")"
557
+ }.ignoresCase()
558
+
559
+ nonisolated(unsafe) private let hwbRegex = Regex {
560
+ "hwb("
561
+ ZeroOrMore(.whitespace)
562
+ Capture {
563
+ cssNumber
564
+ }
565
+ OneOrMore(.whitespace)
566
+ Capture {
567
+ cssNumber
568
+ }
569
+ "%"
570
+ OneOrMore(.whitespace)
571
+ Capture {
572
+ cssNumber
573
+ }
574
+ "%"
575
+ ZeroOrMore(.whitespace)
576
+ Optionally {
577
+ "/"
578
+ ZeroOrMore(.whitespace)
579
+ Capture {
580
+ cssNumberOrPercent
581
+ }
582
+ }
583
+ ZeroOrMore(.whitespace)
584
+ ")"
585
+ }.ignoresCase()
586
+
587
+ // MARK: - CSS Color Function Parsers
588
+
589
+ private func parseRgbComponent(_ value: Substring) -> CGFloat {
590
+ if value.hasSuffix("%") {
591
+ let num = Double(value.dropLast()) ?? 0
592
+ return CGFloat(min(max(num / 100.0, 0), 1))
593
+ }
594
+ let num = Double(value) ?? 0
595
+ return CGFloat(min(max(num / 255.0, 0), 1))
596
+ }
597
+
598
+ private func parseCssAlpha(_ value: Substring?) -> CGFloat {
599
+ guard let value else {
600
+ return 1.0
601
+ }
602
+ if value.hasSuffix("%") {
603
+ let num = Double(value.dropLast()) ?? 0
604
+ return CGFloat(min(max(num / 100.0, 0), 1))
605
+ }
606
+ let num = Double(value) ?? 0
607
+ return CGFloat(min(max(num, 0), 1))
608
+ }
609
+
610
+ private func hueToRgb(_ p: CGFloat, _ q: CGFloat, _ t: CGFloat) -> CGFloat {
611
+ var t = t
612
+ if t < 0 { t += 1 }
613
+ if t > 1 { t -= 1 }
614
+ if t < 1.0 / 6.0 { return p + (q - p) * 6.0 * t }
615
+ if t < 1.0 / 2.0 { return q }
616
+ if t < 2.0 / 3.0 { return p + (q - p) * (2.0 / 3.0 - t) * 6.0 }
617
+ return p
618
+ }
619
+
620
+ private func hslToUIColor(h: CGFloat, s: CGFloat, l: CGFloat, a: CGFloat) -> UIColor {
621
+ let hue =
622
+ ((h.truncatingRemainder(dividingBy: 360) + 360).truncatingRemainder(dividingBy: 360)) / 360.0
623
+ let r: CGFloat
624
+ let g: CGFloat
625
+ let b: CGFloat
626
+ if s == 0 {
627
+ r = l
628
+ g = l
629
+ b = l
630
+ } else {
631
+ let q = l < 0.5 ? l * (1 + s) : l + s - l * s
632
+ let p = 2 * l - q
633
+ r = hueToRgb(p, q, hue + 1.0 / 3.0)
634
+ g = hueToRgb(p, q, hue)
635
+ b = hueToRgb(p, q, hue - 1.0 / 3.0)
636
+ }
637
+ return UIColor(
638
+ red: min(max(r, 0), 1),
639
+ green: min(max(g, 0), 1),
640
+ blue: min(max(b, 0), 1),
641
+ alpha: a
642
+ )
643
+ }
644
+
645
+ private func hwbToUIColor(h: CGFloat, w: CGFloat, b: CGFloat, a: CGFloat) -> UIColor {
646
+ let ww = min(max(w, 0), 1 as CGFloat)
647
+ let bb = min(max(b, 0), 1 as CGFloat)
648
+ let sum = ww + bb
649
+ let white = sum > 1 ? ww / sum : ww
650
+ let black = sum > 1 ? bb / sum : bb
651
+ let hue =
652
+ ((h.truncatingRemainder(dividingBy: 360) + 360).truncatingRemainder(dividingBy: 360)) / 360.0
653
+ let r = hueToRgb(0, 1, hue + 1.0 / 3.0) * (1 - white - black) + white
654
+ let g = hueToRgb(0, 1, hue) * (1 - white - black) + white
655
+ let bl = hueToRgb(0, 1, hue - 1.0 / 3.0) * (1 - white - black) + white
656
+ return UIColor(
657
+ red: min(max(r, 0), 1),
658
+ green: min(max(g, 0), 1),
659
+ blue: min(max(bl, 0), 1),
660
+ alpha: a
661
+ )
662
+ }
663
+
664
+ private func colorFromRGBString(_ rgbString: String) throws -> UIColor {
665
+ if let match = rgbString.wholeMatch(of: rgbCommaRegex) ?? rgbString.wholeMatch(of: rgbSpaceRegex) {
666
+ let r = parseRgbComponent(match.1)
667
+ let g = parseRgbComponent(match.2)
668
+ let b = parseRgbComponent(match.3)
669
+ let a = parseCssAlpha(match.4)
670
+ return UIColor(red: r, green: g, blue: b, alpha: a)
671
+ }
672
+ throw InvalidRGBColorException(rgbString)
673
+ }
674
+
675
+ private func colorFromHSLString(_ hslString: String) throws -> UIColor {
676
+ if let match = hslString.wholeMatch(of: hslCommaRegex) ?? hslString.wholeMatch(of: hslSpaceRegex) {
677
+ let h = CGFloat(Double(match.1) ?? 0)
678
+ let s = CGFloat(min(max((Double(match.2) ?? 0) / 100.0, 0), 1))
679
+ let l = CGFloat(min(max((Double(match.3) ?? 0) / 100.0, 0), 1))
680
+ let a = parseCssAlpha(match.4)
681
+ return hslToUIColor(h: h, s: s, l: l, a: a)
682
+ }
683
+ throw InvalidHSLColorException(hslString)
684
+ }
685
+
686
+ private func colorFromHWBString(_ hwbString: String) throws -> UIColor {
687
+ if let match = hwbString.wholeMatch(of: hwbRegex) {
688
+ let h = CGFloat(Double(match.1) ?? 0)
689
+ let w = CGFloat((Double(match.2) ?? 0) / 100.0)
690
+ let b = CGFloat((Double(match.3) ?? 0) / 100.0)
691
+ let a = parseCssAlpha(match.4)
692
+ return hwbToUIColor(h: h, w: w, b: b, a: a)
693
+ }
694
+ throw InvalidHWBColorException(hwbString)
695
+ }
696
+
697
+ /// Color components for named colors following the [CSS3/SVG specification](https://www.w3.org/TR/css-color-3/#svg-color)
698
+ /// and additionally the transparent color.
699
+ private let namedColors: [String: [Double]] = [
700
+ "aliceblue": [240, 248, 255, 255],
701
+ "antiquewhite": [250, 235, 215, 255],
702
+ "aqua": [0, 255, 255, 255],
703
+ "aquamarine": [127, 255, 212, 255],
704
+ "azure": [240, 255, 255, 255],
705
+ "beige": [245, 245, 220, 255],
706
+ "bisque": [255, 228, 196, 255],
707
+ "black": [0, 0, 0, 255],
708
+ "blanchedalmond": [255, 235, 205, 255],
709
+ "blue": [0, 0, 255, 255],
710
+ "blueviolet": [138, 43, 226, 255],
711
+ "brown": [165, 42, 42, 255],
712
+ "burlywood": [222, 184, 135, 255],
713
+ "cadetblue": [95, 158, 160, 255],
714
+ "chartreuse": [127, 255, 0, 255],
715
+ "chocolate": [210, 105, 30, 255],
716
+ "coral": [255, 127, 80, 255],
717
+ "cornflowerblue": [100, 149, 237, 255],
718
+ "cornsilk": [255, 248, 220, 255],
719
+ "crimson": [220, 20, 60, 255],
720
+ "cyan": [0, 255, 255, 255],
721
+ "darkblue": [0, 0, 139, 255],
722
+ "darkcyan": [0, 139, 139, 255],
723
+ "darkgoldenrod": [184, 134, 11, 255],
724
+ "darkgray": [169, 169, 169, 255],
725
+ "darkgreen": [0, 100, 0, 255],
726
+ "darkgrey": [169, 169, 169, 255],
727
+ "darkkhaki": [189, 183, 107, 255],
728
+ "darkmagenta": [139, 0, 139, 255],
729
+ "darkolivegreen": [85, 107, 47, 255],
730
+ "darkorange": [255, 140, 0, 255],
731
+ "darkorchid": [153, 50, 204, 255],
732
+ "darkred": [139, 0, 0, 255],
733
+ "darksalmon": [233, 150, 122, 255],
734
+ "darkseagreen": [143, 188, 143, 255],
735
+ "darkslateblue": [72, 61, 139, 255],
736
+ "darkslategray": [47, 79, 79, 255],
737
+ "darkslategrey": [47, 79, 79, 255],
738
+ "darkturquoise": [0, 206, 209, 255],
739
+ "darkviolet": [148, 0, 211, 255],
740
+ "deeppink": [255, 20, 147, 255],
741
+ "deepskyblue": [0, 191, 255, 255],
742
+ "dimgray": [105, 105, 105, 255],
743
+ "dimgrey": [105, 105, 105, 255],
744
+ "dodgerblue": [30, 144, 255, 255],
745
+ "firebrick": [178, 34, 34, 255],
746
+ "floralwhite": [255, 250, 240, 255],
747
+ "forestgreen": [34, 139, 34, 255],
748
+ "fuchsia": [255, 0, 255, 255],
749
+ "gainsboro": [220, 220, 220, 255],
750
+ "ghostwhite": [248, 248, 255, 255],
751
+ "gold": [255, 215, 0, 255],
752
+ "goldenrod": [218, 165, 32, 255],
753
+ "gray": [128, 128, 128, 255],
754
+ "green": [0, 128, 0, 255],
755
+ "greenyellow": [173, 255, 47, 255],
756
+ "grey": [128, 128, 128, 255],
757
+ "honeydew": [240, 255, 240, 255],
758
+ "hotpink": [255, 105, 180, 255],
759
+ "indianred": [205, 92, 92, 255],
760
+ "indigo": [75, 0, 130, 255],
761
+ "ivory": [255, 255, 240, 255],
762
+ "khaki": [240, 230, 140, 255],
763
+ "lavender": [230, 230, 250, 255],
764
+ "lavenderblush": [255, 240, 245, 255],
765
+ "lawngreen": [124, 252, 0, 255],
766
+ "lemonchiffon": [255, 250, 205, 255],
767
+ "lightblue": [173, 216, 230, 255],
768
+ "lightcoral": [240, 128, 128, 255],
769
+ "lightcyan": [224, 255, 255, 255],
770
+ "lightgoldenrodyellow": [250, 250, 210, 255],
771
+ "lightgray": [211, 211, 211, 255],
772
+ "lightgreen": [144, 238, 144, 255],
773
+ "lightgrey": [211, 211, 211, 255],
774
+ "lightpink": [255, 182, 193, 255],
775
+ "lightsalmon": [255, 160, 122, 255],
776
+ "lightseagreen": [32, 178, 170, 255],
777
+ "lightskyblue": [135, 206, 250, 255],
778
+ "lightslategray": [119, 136, 153, 255],
779
+ "lightslategrey": [119, 136, 153, 255],
780
+ "lightsteelblue": [176, 196, 222, 255],
781
+ "lightyellow": [255, 255, 224, 255],
782
+ "lime": [0, 255, 0, 255],
783
+ "limegreen": [50, 205, 50, 255],
784
+ "linen": [250, 240, 230, 255],
785
+ "magenta": [255, 0, 255, 255],
786
+ "maroon": [128, 0, 0, 255],
787
+ "mediumaquamarine": [102, 205, 170, 255],
788
+ "mediumblue": [0, 0, 205, 255],
789
+ "mediumorchid": [186, 85, 211, 255],
790
+ "mediumpurple": [147, 112, 219, 255],
791
+ "mediumseagreen": [60, 179, 113, 255],
792
+ "mediumslateblue": [123, 104, 238, 255],
793
+ "mediumspringgreen": [0, 250, 154, 255],
794
+ "mediumturquoise": [72, 209, 204, 255],
795
+ "mediumvioletred": [199, 21, 133, 255],
796
+ "midnightblue": [25, 25, 112, 255],
797
+ "mintcream": [245, 255, 250, 255],
798
+ "mistyrose": [255, 228, 225, 255],
799
+ "moccasin": [255, 228, 181, 255],
800
+ "navajowhite": [255, 222, 173, 255],
801
+ "navy": [0, 0, 128, 255],
802
+ "oldlace": [253, 245, 230, 255],
803
+ "olive": [128, 128, 0, 255],
804
+ "olivedrab": [107, 142, 35, 255],
805
+ "orange": [255, 165, 0, 255],
806
+ "orangered": [255, 69, 0, 255],
807
+ "orchid": [218, 112, 214, 255],
808
+ "palegoldenrod": [238, 232, 170, 255],
809
+ "palegreen": [152, 251, 152, 255],
810
+ "paleturquoise": [175, 238, 238, 255],
811
+ "palevioletred": [219, 112, 147, 255],
812
+ "papayawhip": [255, 239, 213, 255],
813
+ "peachpuff": [255, 218, 185, 255],
814
+ "peru": [205, 133, 63, 255],
815
+ "pink": [255, 192, 203, 255],
816
+ "plum": [221, 160, 221, 255],
817
+ "powderblue": [176, 224, 230, 255],
818
+ "purple": [128, 0, 128, 255],
819
+ "rebeccapurple": [102, 51, 153, 255],
820
+ "red": [255, 0, 0, 255],
821
+ "rosybrown": [188, 143, 143, 255],
822
+ "royalblue": [65, 105, 225, 255],
823
+ "saddlebrown": [139, 69, 19, 255],
824
+ "salmon": [250, 128, 114, 255],
825
+ "sandybrown": [244, 164, 96, 255],
826
+ "seagreen": [46, 139, 87, 255],
827
+ "seashell": [255, 245, 238, 255],
828
+ "sienna": [160, 82, 45, 255],
829
+ "silver": [192, 192, 192, 255],
830
+ "skyblue": [135, 206, 235, 255],
831
+ "slateblue": [106, 90, 205, 255],
832
+ "slategray": [112, 128, 144, 255],
833
+ "slategrey": [112, 128, 144, 255],
834
+ "snow": [255, 250, 250, 255],
835
+ "springgreen": [0, 255, 127, 255],
836
+ "steelblue": [70, 130, 180, 255],
837
+ "tan": [210, 180, 140, 255],
838
+ "teal": [0, 128, 128, 255],
839
+ "thistle": [216, 191, 216, 255],
840
+ "tomato": [255, 99, 71, 255],
841
+ "transparent": [0, 0, 0, 0],
842
+ "turquoise": [64, 224, 208, 255],
843
+ "violet": [238, 130, 238, 255],
844
+ "wheat": [245, 222, 179, 255],
845
+ "white": [255, 255, 255, 255],
846
+ "whitesmoke": [245, 245, 245, 255],
847
+ "yellow": [255, 255, 0, 255],
848
+ "yellowgreen": [154, 205, 50, 255],
849
+ ].mapValues { $0.map { $0 / 255.0 } }
850
+
851
+ // MARK: - Color Conversion Exceptions
852
+
853
+ internal class InvalidHexColorException: GenericException<String>, @unchecked Sendable {
854
+ override var reason: String {
855
+ "Provided hex color '\(param)' is invalid"
856
+ }
857
+ }
858
+
859
+ internal class InvalidRGBColorException: GenericException<String>, @unchecked Sendable {
860
+ override var reason: String {
861
+ "Provided rgb color string '\(param)' is invalid"
862
+ }
863
+ }
864
+
865
+ internal class InvalidHSLColorException: GenericException<String>, @unchecked Sendable {
866
+ override var reason: String {
867
+ "Provided hsl color string '\(param)' is invalid"
868
+ }
869
+ }
870
+
871
+ internal class InvalidHWBColorException: GenericException<String>, @unchecked Sendable {
872
+ override var reason: String {
873
+ "Provided hwb color string '\(param)' is invalid"
874
+ }
875
+ }
876
+
877
+ internal class HexColorOverflowException: GenericException<UInt64>, @unchecked Sendable {
878
+ override var reason: String {
879
+ "Provided hex color '\(param)' would result in an overflow"
880
+ }
881
+ }
882
+
883
+ internal class InvalidColorComponentsException: GenericException<Int>, @unchecked Sendable {
884
+ override var reason: String {
885
+ "Color components array must contain at least 3 values (red, green, blue), but got \(param)"
886
+ }
887
+ }