@nativue/core 0.16.0 → 0.18.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.
@@ -0,0 +1,191 @@
1
+ import UIKit
2
+
3
+ /// backgroundImage: CSS gradients (src/gradients.ts) under a view's content and over its backgroundColor,
4
+ /// in a layer that follows its bounds and corners. The first gradient is on top, as in CSS.
5
+ final class BackgroundGradientsLayer: CALayer {
6
+ private var gradients: [[String: Any]] = []
7
+
8
+ func setGradients(_ gradients: [[String: Any]]) {
9
+ self.gradients = gradients
10
+ sublayers = gradients.reversed().map(GradientLayer.init)
11
+ }
12
+
13
+ /// Their geometry depends on the size: an angle's line, a corner, a radius.
14
+ func layoutGradients() {
15
+ for layer in sublayers ?? [] where layer.frame != bounds {
16
+ layer.frame = bounds
17
+ layer.setNeedsDisplay()
18
+ }
19
+ }
20
+ }
21
+
22
+ /// One gradient, drawn in points: CAGradientLayer works in a unit square stretched to the layer, which
23
+ /// tilts an angle on a box that isn't square.
24
+ private final class GradientLayer: CALayer {
25
+ private let gradient: [String: Any]
26
+
27
+ init(_ gradient: [String: Any]) {
28
+ self.gradient = gradient
29
+ super.init()
30
+ contentsScale = UIScreen.main.scale
31
+ needsDisplayOnBoundsChange = true
32
+ }
33
+
34
+ override init(layer: Any) {
35
+ gradient = (layer as? GradientLayer)?.gradient ?? [:]
36
+ super.init(layer: layer)
37
+ }
38
+
39
+ required init?(coder: NSCoder) {
40
+ fatalError("init(coder:) is not supported")
41
+ }
42
+
43
+ override func draw(in context: CGContext) {
44
+ CSSGradient.draw(gradient, in: context, size: bounds.size)
45
+ }
46
+ }
47
+
48
+ extension UIView {
49
+ /// The gradients layer, created under the view's subviews the first time it's needed. A label or an image
50
+ /// view draws its content in its own layer, which the gradients would cover: they get none.
51
+ func setBackgroundGradients(_ gradients: [[String: Any]]) {
52
+ guard !(self is UILabel || self is UIImageView) else { return }
53
+
54
+ let existing = layer.sublayers?.first { $0 is BackgroundGradientsLayer } as? BackgroundGradientsLayer
55
+ guard !gradients.isEmpty else {
56
+ existing?.removeFromSuperlayer()
57
+ return
58
+ }
59
+
60
+ let gradientsLayer = existing ?? BackgroundGradientsLayer()
61
+ if existing == nil {
62
+ // Behind the subviews' layers, wherever they're inserted.
63
+ gradientsLayer.zPosition = -1
64
+ layer.insertSublayer(gradientsLayer, at: 0)
65
+ }
66
+ gradientsLayer.setGradients(gradients)
67
+ applyBackgroundGradients()
68
+ }
69
+
70
+ /// Fitted to the view's bounds and corners, again as its frame changes: at once, or along with a
71
+ /// LayoutAnimation. A scroll view's bounds move as it scrolls, keeping the gradients in place.
72
+ func applyBackgroundGradients() {
73
+ guard let gradientsLayer = layer.sublayers?.first(where: { $0 is BackgroundGradientsLayer }) as? BackgroundGradientsLayer
74
+ else { return }
75
+
76
+ let animationDuration = UIView.inheritedAnimationDuration
77
+
78
+ CATransaction.begin()
79
+ CATransaction.setDisableActions(animationDuration == 0)
80
+ CATransaction.setAnimationDuration(animationDuration)
81
+ gradientsLayer.frame = bounds
82
+ gradientsLayer.cornerRadius = layer.cornerRadius
83
+ gradientsLayer.maskedCorners = layer.maskedCorners
84
+ gradientsLayer.masksToBounds = true
85
+ gradientsLayer.layoutGradients()
86
+ CATransaction.commit()
87
+ }
88
+ }
89
+
90
+ /// Where CSS puts a gradient in a box of `size`, as Android's BackgroundGradients does.
91
+ enum CSSGradient {
92
+ static func draw(_ gradient: [String: Any], in context: CGContext, size: CGSize) {
93
+ let colors = (gradient["colors"] as? [Any] ?? []).compactMap { UIColor(rgba: $0)?.cgColor }
94
+ let locations = (gradient["positions"] as? [NSNumber] ?? []).map { CGFloat($0.doubleValue) }
95
+ guard
96
+ size.width > 0, size.height > 0, colors.count == locations.count,
97
+ let cgGradient = CGGradient(colorsSpace: CGColorSpace(name: CGColorSpace.sRGB), colors: colors as CFArray, locations: locations)
98
+ else { return }
99
+
100
+ // Past the ends, the end colors, as CSS pads them.
101
+ let extend: CGGradientDrawingOptions = [.drawsBeforeStartLocation, .drawsAfterEndLocation]
102
+
103
+ if gradient["type"] as? String == "radial" {
104
+ let (center, radii) = radial(gradient, size: size)
105
+ let radius = max(radii.width, 0.01)
106
+
107
+ // A circle, stretched into the ellipse.
108
+ context.translateBy(x: center.x, y: center.y)
109
+ context.scaleBy(x: 1, y: max(radii.height, 0.01) / radius)
110
+ context.drawRadialGradient(
111
+ cgGradient, startCenter: .zero, startRadius: 0, endCenter: .zero, endRadius: radius, options: extend
112
+ )
113
+ } else {
114
+ let (start, end) = linear(gradient, size: size)
115
+
116
+ context.drawLinearGradient(cgGradient, start: start, end: end, options: extend)
117
+ }
118
+ }
119
+
120
+ /// The gradient line: through the center, as long as the box is along it, so its ends touch the corners.
121
+ static func linear(_ gradient: [String: Any], size: CGSize) -> (start: CGPoint, end: CGPoint) {
122
+ var direction = CGVector(dx: 0, dy: 1)
123
+
124
+ if let sides = gradient["to"] as? [String] {
125
+ let x: CGFloat = sides.contains("right") ? 1 : sides.contains("left") ? -1 : 0
126
+ let y: CGFloat = sides.contains("bottom") ? 1 : sides.contains("top") ? -1 : 0
127
+ // To a corner: perpendicular to the diagonal between the two corners next to it.
128
+ direction = x != 0 && y != 0 ? CGVector(dx: x * size.height, dy: y * size.width) : CGVector(dx: x, dy: y)
129
+ } else if let angle = (gradient["angle"] as? NSNumber).map({ CGFloat($0.doubleValue) * .pi / 180 }) {
130
+ // 0 points up, 90 right.
131
+ direction = CGVector(dx: sin(angle), dy: -cos(angle))
132
+ }
133
+
134
+ let length = hypot(direction.dx, direction.dy)
135
+ guard length > 0 else { return (.zero, CGPoint(x: 0, y: size.height)) }
136
+
137
+ let unitDirection = CGVector(dx: direction.dx / length, dy: direction.dy / length)
138
+ let halfLine = (abs(size.width * unitDirection.dx) + abs(size.height * unitDirection.dy)) / 2
139
+ let center = CGPoint(x: size.width / 2, y: size.height / 2)
140
+
141
+ return (
142
+ CGPoint(x: center.x - unitDirection.dx * halfLine, y: center.y - unitDirection.dy * halfLine),
143
+ CGPoint(x: center.x + unitDirection.dx * halfLine, y: center.y + unitDirection.dy * halfLine)
144
+ )
145
+ }
146
+
147
+ /// The center and the radii: given, or reaching the extent keyword's side or corner.
148
+ static func radial(_ gradient: [String: Any], size: CGSize) -> (center: CGPoint, radii: CGSize) {
149
+ let center = CGPoint(
150
+ x: length(gradient["center"], index: 0, of: size.width, default: 0.5),
151
+ y: length(gradient["center"], index: 1, of: size.height, default: 0.5)
152
+ )
153
+ let isCircle = gradient["shape"] as? String == "circle"
154
+
155
+ if gradient["radii"] != nil {
156
+ let radiusX = length(gradient["radii"], index: 0, of: size.width, default: 0.5)
157
+ let radiusY = isCircle ? radiusX : length(gradient["radii"], index: 1, of: size.height, default: 0.5)
158
+
159
+ return (center, CGSize(width: radiusX, height: radiusY))
160
+ }
161
+
162
+ let horizontal = [center.x, size.width - center.x].map(abs)
163
+ let vertical = [center.y, size.height - center.y].map(abs)
164
+ let extent = gradient["extent"] as? String ?? "farthest-corner"
165
+ let pick = extent.hasPrefix("closest") ? { (values: [CGFloat]) in values.min() ?? 0 } : { $0.max() ?? 0 }
166
+ let (sideX, sideY) = (pick(horizontal), pick(vertical))
167
+
168
+ switch (extent.hasSuffix("corner"), isCircle) {
169
+ case (true, true):
170
+ let radius = hypot(sideX, sideY)
171
+ return (center, CGSize(width: radius, height: radius))
172
+ case (true, false):
173
+ // An ellipse through the corner, shaped like the one that would touch the sides.
174
+ return (center, CGSize(width: sideX * sqrt(2), height: sideY * sqrt(2)))
175
+ case (false, true):
176
+ let radius = pick([sideX, sideY])
177
+ return (center, CGSize(width: radius, height: radius))
178
+ case (false, false):
179
+ return (center, CGSize(width: sideX, height: sideY))
180
+ }
181
+ }
182
+
183
+ /// [[fraction, points], ...][index], in points of a side `side` long.
184
+ private static func length(_ value: Any?, index: Int, of side: CGFloat, default fraction: CGFloat) -> CGFloat {
185
+ guard let lengths = value as? [[NSNumber]], index < lengths.count, lengths[index].count == 2 else {
186
+ return fraction * side
187
+ }
188
+
189
+ return CGFloat(lengths[index][0].doubleValue) * side + CGFloat(lengths[index][1].doubleValue)
190
+ }
191
+ }
package/ios/Bridge.swift CHANGED
@@ -297,7 +297,7 @@ final class Bridge {
297
297
 
298
298
  @MainActor func reload() async throws {
299
299
  let data = try await download(Self.devServerURL.appendingPathComponent("bundle.js"))
300
- print("[Nativue] reload")
300
+ print("[nativue] reload")
301
301
  run(data)
302
302
  }
303
303
 
@@ -461,7 +461,7 @@ final class Bridge {
461
461
 
462
462
  /// Logged always; shown over the app in development builds.
463
463
  private func reportError(message: String, details: String) {
464
- print("[Nativue] JS error:", message, "\n" + details)
464
+ print("[nativue] JS error:", message, "\n" + details)
465
465
 
466
466
  #if DEBUG
467
467
  Task { @MainActor [unowned self] in
@@ -510,7 +510,7 @@ final class Bridge {
510
510
  guard let parent = nodesById[parentId], let child = nodesById[childId] else { return }
511
511
 
512
512
  guard parent.canHaveChildren else {
513
- print("[Nativue] <\(type(of: parent.view))> can't have native children; use <View>")
513
+ print("[nativue] <\(type(of: parent.view))> can't have native children; use <View>")
514
514
  return
515
515
  }
516
516
 
@@ -898,7 +898,7 @@ final class Bridge {
898
898
  guard let node = nodesById[id] else { return }
899
899
 
900
900
  (node.view as? UILabel)?.text = text
901
- if node.textDecorationLine != "none" { node.updateTextDecoration() }
901
+ if node.hasTextAttributes { node.updateTextAttributes() }
902
902
  node.markContentChanged()
903
903
  }
904
904
 
@@ -24,8 +24,17 @@ final class NativeNode {
24
24
  var defaultFontSize: CGFloat = UIFont.labelFontSize
25
25
  var fontSize: CGFloat = UIFont.labelFontSize
26
26
  var fontWeight: UIFont.Weight = .regular
27
+ var isItalic = false
28
+ /// The text's attributes a label keeps in its attributed text (updateTextAttributes).
27
29
  /// textDecorationLine: 'none', 'underline', 'line-through' or both.
28
30
  var textDecorationLine = "none"
31
+ /// letterSpacing and lineHeight: points, or ems of the font size ('1.5em'); nil for the font's own.
32
+ var letterSpacing: Any?
33
+ var lineHeight: Any?
34
+
35
+ var hasTextAttributes: Bool {
36
+ textDecorationLine != "none" || letterSpacing != nil || lineHeight != nil
37
+ }
29
38
 
30
39
  /// Leaf nodes (Text, Button) measure their own content; containers are sized by their children.
31
40
  init(view: UIView, measuresContent: Bool) {
@@ -142,6 +151,7 @@ final class NativeNode {
142
151
  place(childView, at: frame)
143
152
  }
144
153
  childView.applyCornerRadius()
154
+ childView.applyBackgroundGradients()
145
155
 
146
156
  applyFrames(of: child)
147
157
 
@@ -221,10 +231,17 @@ private func measureView(
221
231
  @MainActor private func singleLineSize(of label: UILabel, maxWidth: CGFloat) -> CGSize? {
222
232
  guard let text = label.text, !text.contains(where: \.isNewline) else { return nil }
223
233
 
224
- let attributedText = NSAttributedString(string: text, attributes: [.font: label.font!])
234
+ // Its attributes too: letter spacing widens the line, a line height sets its height.
235
+ let attributedText = label.attributedText ?? NSAttributedString(string: text, attributes: [.font: label.font!])
225
236
  let line = CTLineCreateWithAttributedString(attributedText)
226
237
  let width = ceil(CTLineGetTypographicBounds(line, nil, nil, nil))
227
238
  guard width <= maxWidth else { return nil }
228
239
 
229
- return CGSize(width: width, height: ceil(label.font.lineHeight))
240
+ let paragraphStyle = attributedText.length > 0
241
+ ? attributedText.attribute(.paragraphStyle, at: 0, effectiveRange: nil) as? NSParagraphStyle
242
+ : nil
243
+
244
+ let lineHeight = paragraphStyle.map(\.minimumLineHeight).flatMap { $0 > 0 ? $0 : nil } ?? label.font.lineHeight
245
+
246
+ return CGSize(width: width, height: ceil(lineHeight))
230
247
  }
package/ios/Plugins.swift CHANGED
@@ -50,6 +50,15 @@ public final class PluginRegistry {
50
50
  viewMakers[type] = makeView
51
51
  }
52
52
 
53
+ /// The view controller on top, the app's or what it presents, to present a system screen from (a photo
54
+ /// picker, the camera). nil before the app shows its window.
55
+ @MainActor public var topViewController: UIViewController? {
56
+ let windows = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.flatMap(\.windows)
57
+ guard let root = (windows.first { $0.isKeyWindow } ?? windows.first)?.rootViewController else { return nil }
58
+
59
+ return sequence(first: root, next: \.presentedViewController).reduce(root) { _, presented in presented }
60
+ }
61
+
53
62
  /// Draws the tab bar and header icons whose `drawnIcon.drawer` is `drawer` (see router.ts's DrawnIcon).
54
63
  /// The image is tinted, like an SF Symbol: only its shape counts.
55
64
  public func addIconDrawer(_ drawer: String, _ draw: @escaping DrawIcon) {
package/ios/Style.swift CHANGED
@@ -33,9 +33,15 @@ extension NativeNode {
33
33
  case "backgroundColor":
34
34
  view.backgroundColor = UIColor(rgba: value)
35
35
 
36
- case "borderRadius":
37
- view.layer.setValue(CGFloat(number(value) ?? 0), forKey: UIView.requestedCornerRadiusKey)
36
+ case "backgroundImage":
37
+ view.setBackgroundGradients(value as? [[String: Any]] ?? [])
38
+
39
+ case "borderRadius", "borderTopLeftRadius", "borderTopRightRadius", "borderBottomLeftRadius", "borderBottomRightRadius":
40
+ var radii = view.layer.value(forKey: UIView.requestedCornerRadiiKey) as? [String: CGFloat] ?? [:]
41
+ radii[property] = number(value).map { CGFloat($0) }
42
+ view.layer.setValue(radii, forKey: UIView.requestedCornerRadiiKey)
38
43
  view.applyCornerRadius()
44
+ view.applyBackgroundGradients()
39
45
 
40
46
  case "borderWidth":
41
47
  view.layer.borderWidth = CGFloat(number(value) ?? 0)
@@ -82,31 +88,69 @@ extension NativeNode {
82
88
 
83
89
  case "textDecorationLine":
84
90
  textDecorationLine = value as? String ?? "none"
85
- updateTextDecoration()
91
+ updateTextAttributes()
92
+
93
+ case "letterSpacing":
94
+ letterSpacing = value is NSNull ? nil : value
95
+ updateTextAttributes()
96
+
97
+ case "lineHeight":
98
+ lineHeight = value is NSNull ? nil : value
99
+ updateTextAttributes()
100
+
101
+ case "fontStyle":
102
+ isItalic = value as? String == "italic"
103
+ updateFont()
104
+
105
+ case "lineClamp":
106
+ let lines = Int(number(value) ?? 0)
107
+
108
+ (view as? UILabel)?.numberOfLines = lines
109
+ markContentChanged()
86
110
 
87
111
  default:
88
112
  break
89
113
  }
90
114
  }
91
115
 
92
- /// UILabel has no underline or strikethrough of its own: they're attributes of its text, which setting
93
- /// `text` drops, so setText calls this again. Later font, color and alignment changes keep them.
94
- func updateTextDecoration() {
116
+ /// UILabel has no underline, letter spacing or line height of its own: they're attributes of its text,
117
+ /// which setting `text` drops, so setText calls this again. Later color and alignment changes keep them;
118
+ /// a font change calls it, as ems depend on the font's size.
119
+ func updateTextAttributes() {
95
120
  guard let label = view as? UILabel, let text = label.text else { return }
96
121
 
122
+ let font = label.font ?? UIFont.systemFont(ofSize: fontSize)
97
123
  let paragraphStyle = NSMutableParagraphStyle()
98
124
  paragraphStyle.alignment = label.textAlignment
99
- paragraphStyle.lineBreakMode = label.lineBreakMode
100
125
 
101
126
  var attributes: [NSAttributedString.Key: Any] = [
102
- .font: label.font as Any,
127
+ .font: font,
103
128
  .foregroundColor: label.textColor as Any,
104
129
  .paragraphStyle: paragraphStyle,
105
130
  ]
106
131
  if textDecorationLine.contains("underline") { attributes[.underlineStyle] = NSUnderlineStyle.single.rawValue }
107
132
  if textDecorationLine.contains("line-through") { attributes[.strikethroughStyle] = NSUnderlineStyle.single.rawValue }
133
+ if let spacing = points(letterSpacing, font: font) { attributes[.kern] = spacing }
134
+ if let height = points(lineHeight, font: font) {
135
+ paragraphStyle.minimumLineHeight = height
136
+ paragraphStyle.maximumLineHeight = height
137
+ // The extra space goes above the text: half of it below instead, as CSS centers a line.
138
+ attributes[.baselineOffset] = (height - font.lineHeight) / 2
139
+ }
108
140
 
141
+ let lineBreakMode = label.lineBreakMode
109
142
  label.attributedText = NSAttributedString(string: text, attributes: attributes)
143
+ label.lineBreakMode = lineBreakMode
144
+ markContentChanged()
145
+ }
146
+
147
+ /// A number of points, or ems of the font's size ("1.5em").
148
+ private func points(_ value: Any?, font: UIFont) -> CGFloat? {
149
+ if let text = value as? String, text.hasSuffix("em") {
150
+ return Double(text.dropLast(2)).map { CGFloat($0) * font.pointSize }
151
+ }
152
+
153
+ return number(value as Any).map { CGFloat($0) }
110
154
  }
111
155
 
112
156
  /// Font size and weight can change independently, so the node remembers both.
@@ -127,11 +171,17 @@ extension NativeNode {
127
171
  func updateFont() {
128
172
  guard view is UILabel || view is UITextField || view is UIButton else { return }
129
173
 
130
- let font = UIFontMetrics.default.scaledFont(for: UIFont.systemFont(ofSize: fontSize, weight: fontWeight))
174
+ let systemFont = UIFont.systemFont(ofSize: fontSize, weight: fontWeight)
175
+ let italicTraits = systemFont.fontDescriptor.symbolicTraits.union(.traitItalic)
176
+ let styledFont = isItalic
177
+ ? systemFont.fontDescriptor.withSymbolicTraits(italicTraits).map { UIFont(descriptor: $0, size: fontSize) } ?? systemFont
178
+ : systemFont
179
+ let font = UIFontMetrics.default.scaledFont(for: styledFont)
131
180
  (view as? UILabel)?.font = font
132
181
  (view as? UITextField)?.font = font
133
182
  (view as? UIButton)?.titleLabel?.font = font
134
183
 
184
+ if hasTextAttributes { updateTextAttributes() }
135
185
  markContentChanged()
136
186
  }
137
187
  }
@@ -406,13 +456,25 @@ extension NativeNode {
406
456
  }
407
457
 
408
458
  extension UIView {
409
- static let requestedCornerRadiusKey = "nativueCornerRadius"
459
+ /// borderRadius and the corners' own, as styles set them.
460
+ static let requestedCornerRadiiKey = "nativueCornerRadii"
410
461
 
411
462
  /// A radius over half the view's side (rounded-full is 9999) makes Core Animation draw nothing:
412
- /// capped to a circle's, and applied again as the frame changes.
463
+ /// capped to a circle's, and applied again as the frame changes. Core Animation rounds every chosen
464
+ /// corner alike: corners with their own radius share the largest.
413
465
  func applyCornerRadius() {
414
- guard let requestedRadius = layer.value(forKey: Self.requestedCornerRadiusKey) as? CGFloat else { return }
466
+ guard let radii = layer.value(forKey: Self.requestedCornerRadiiKey) as? [String: CGFloat] else { return }
467
+
468
+ let radius = radii["borderRadius"] ?? 0
469
+ let corners: [(CACornerMask, CGFloat)] = [
470
+ (.layerMinXMinYCorner, radii["borderTopLeftRadius"] ?? radius),
471
+ (.layerMaxXMinYCorner, radii["borderTopRightRadius"] ?? radius),
472
+ (.layerMinXMaxYCorner, radii["borderBottomLeftRadius"] ?? radius),
473
+ (.layerMaxXMaxYCorner, radii["borderBottomRightRadius"] ?? radius),
474
+ ]
475
+ let largest = corners.map(\.1).max() ?? 0
415
476
 
416
- layer.cornerRadius = min(requestedRadius, min(bounds.width, bounds.height) / 2)
477
+ layer.cornerRadius = min(largest, min(bounds.width, bounds.height) / 2)
478
+ layer.maskedCorners = CACornerMask(corners.filter { $0.1 > 0 }.map(\.0))
417
479
  }
418
480
  }
@@ -83,6 +83,7 @@ final class VueScrollView: UIScrollView {
83
83
  override func layoutSubviews() {
84
84
  super.layoutSubviews()
85
85
 
86
+ applyBackgroundGradients()
86
87
  onOffsetChange?(contentOffset)
87
88
  reportScrollThrottled()
88
89
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nativue/core",
3
- "version": "0.16.0",
3
+ "version": "0.18.0",
4
4
  "description": "Vue rendering real native views on iOS and Android",
5
5
  "keywords": [
6
6
  "vue",
@@ -32,7 +32,7 @@
32
32
  }
33
33
  },
34
34
  "scripts": {
35
- "test": "(cd ../../examples/demo && nativue build) && node test/test.mjs && node test/native-events.test.mjs && node test/hermes.test.mjs && node test/prebuild.test.mjs",
35
+ "test": "(cd ../../examples/demo && nativue build) && node test/test.mjs && node test/gradients.test.mjs && node test/native-events.test.mjs && node test/hermes.test.mjs && node test/prebuild.test.mjs",
36
36
  "typecheck": "vue-tsc"
37
37
  },
38
38
  "dependencies": {
package/src/colors.ts CHANGED
@@ -186,13 +186,17 @@ function parseRgbFunction(color: string) {
186
186
  export function processColor(color: unknown): number | null {
187
187
  if (color == null) return null
188
188
 
189
- const normalized =
190
- NAMED_COLORS[String(color).trim().toLowerCase()] ?? String(color).trim().toLowerCase()
191
- const rgba = normalized.startsWith('#')
192
- ? parseHex(normalized.slice(1))
193
- : parseRgbFunction(normalized)
189
+ const rgba = parseColor(color)
194
190
 
195
- if (rgba === null) console.warn(`[Nativue] unsupported color: ${color}`)
191
+ if (rgba === null) console.warn(`[nativue] unsupported color: ${color}`)
196
192
 
197
193
  return rgba
198
194
  }
195
+
196
+ /** The color as 0xRRGGBBAA, or null, quietly: for telling a color from something else. */
197
+ export function parseColor(color: unknown): number | null {
198
+ const normalized =
199
+ NAMED_COLORS[String(color).trim().toLowerCase()] ?? String(color).trim().toLowerCase()
200
+
201
+ return normalized.startsWith('#') ? parseHex(normalized.slice(1)) : parseRgbFunction(normalized)
202
+ }