@nativue/core 0.16.0 → 0.17.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.
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/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.17.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
+ }
@@ -0,0 +1,304 @@
1
+ // backgroundImage, as CSS writes it: linear-gradient() and radial-gradient(), one or several (the first
2
+ // on top), parsed into what native draws over backgroundColor. The geometry that depends on the view's
3
+ // size (an angle's line, a corner, a radius) is worked out natively, at layout.
4
+ import { parseColor } from './colors'
5
+
6
+ /** A length: a fraction of the view's side plus points, [fraction, points]. */
7
+ type Length = [fraction: number, points: number]
8
+
9
+ export type BackgroundGradient = {
10
+ type: 'linear' | 'radial'
11
+ /** linear: degrees, 0 pointing up and 90 right; or the side or corner it goes to, e.g. ['top', 'right']. */
12
+ angle?: number
13
+ to?: string[]
14
+ /** radial: a circle or an ellipse, sized by an extent keyword or by radii, around `center`. */
15
+ shape?: 'circle' | 'ellipse'
16
+ extent?: 'closest-side' | 'closest-corner' | 'farthest-side' | 'farthest-corner'
17
+ radii?: [Length, Length]
18
+ center?: [Length, Length]
19
+ colors: number[]
20
+ /** Fractions of the gradient line, one per color. */
21
+ positions: number[]
22
+ }
23
+
24
+ const EXTENTS = new Set(['closest-side', 'closest-corner', 'farthest-side', 'farthest-corner'])
25
+ const SIDE_FRACTIONS: Record<string, number> = { left: 0, top: 0, center: 0.5, right: 1, bottom: 1 }
26
+ const DEGREES_PER_UNIT: Record<string, number> = {
27
+ deg: 1,
28
+ grad: 0.9,
29
+ rad: 180 / Math.PI,
30
+ turn: 360,
31
+ }
32
+
33
+ /** 'linear-gradient(135deg, #4af2ae, #10b39b)' as gradients native draws; [] for what it can't. */
34
+ export function processBackgroundImage(value: unknown): BackgroundGradient[] {
35
+ if (typeof value !== 'string') return []
36
+
37
+ return splitTopLevel(value, ',').flatMap((layer) => {
38
+ const gradient = parseGradient(layer.trim())
39
+
40
+ return gradient ? [gradient] : []
41
+ })
42
+ }
43
+
44
+ function parseGradient(text: string): BackgroundGradient | null {
45
+ const match = /^(linear|radial)-gradient\(([\s\S]*)\)$/i.exec(text)
46
+ if (!match) return null
47
+
48
+ const type = match[1].toLowerCase() as BackgroundGradient['type']
49
+ const [first, ...rest] = splitTopLevel(match[2], ',').map((part) => part.trim())
50
+ const firstTokens = splitTopLevel(first ?? '', ' ')
51
+ const hasSettings = firstTokens.length > 0 && parseColor(firstTokens[0]) == null
52
+ const stops = colorStops(hasSettings ? rest : [first, ...rest])
53
+ if (stops.colors.length === 0) return null
54
+
55
+ const settings = hasSettings
56
+ ? withoutColorSpace(firstTokens.map((token) => token.toLowerCase()))
57
+ : []
58
+
59
+ return type === 'linear'
60
+ ? { type, ...linearSettings(settings), ...stops }
61
+ : { type, ...radialSettings(settings), ...stops }
62
+ }
63
+
64
+ const HUE_METHODS = new Set(['shorter', 'longer', 'increasing', 'decreasing'])
65
+
66
+ /** "in oklab", "in hsl longer hue", before or after the direction: left out, colors mix in sRGB. */
67
+ function withoutColorSpace(tokens: string[]): string[] {
68
+ const start = tokens.indexOf('in')
69
+ if (start < 0) return tokens
70
+
71
+ const hasHueMethod = HUE_METHODS.has(tokens[start + 2]) && tokens[start + 3] === 'hue'
72
+
73
+ return [...tokens.slice(0, start), ...tokens.slice(start + (hasHueMethod ? 4 : 2))]
74
+ }
75
+
76
+ /** "135deg", "to top right". */
77
+ function linearSettings(tokens: string[]): Pick<BackgroundGradient, 'angle' | 'to'> {
78
+ if (tokens[0] === 'to') return { to: tokens.slice(1) }
79
+
80
+ const angle = /^(-?[\d.]+)(deg|grad|rad|turn)?$/.exec(tokens[0] ?? '')
81
+
82
+ return { angle: angle ? Number(angle[1]) * DEGREES_PER_UNIT[angle[2] ?? 'deg'] : 180 }
83
+ }
84
+
85
+ /** "circle at 30% 40%", "ellipse farthest-corner", "40px 20px at top left". */
86
+ function radialSettings(tokens: string[]): Partial<BackgroundGradient> {
87
+ const atIndex = tokens.indexOf('at')
88
+ const before = atIndex < 0 ? tokens : tokens.slice(0, atIndex)
89
+ const sizes = before.filter((token) => /^-?[\d.]/.test(token)).map(length)
90
+ const shape = before.includes('circle') || (sizes.length === 1 && !before.includes('ellipse'))
91
+ const extent = before.find((token) => EXTENTS.has(token)) as BackgroundGradient['extent']
92
+
93
+ return {
94
+ shape: shape ? 'circle' : 'ellipse',
95
+ ...(sizes.length > 0
96
+ ? { radii: [sizes[0], sizes[1] ?? sizes[0]] }
97
+ : { extent: extent ?? 'farthest-corner' }),
98
+ center: position(atIndex < 0 ? [] : tokens.slice(atIndex + 1)),
99
+ }
100
+ }
101
+
102
+ const HORIZONTAL = new Set(['left', 'right'])
103
+ const VERTICAL = new Set(['top', 'bottom'])
104
+
105
+ /**
106
+ * "at top", "at center left", "at 30% 40px", "at right 10px top 20%": x and y, a keyword naming its
107
+ * axis whatever the order, the one left out centered.
108
+ */
109
+ function position(tokens: string[]): [Length, Length] {
110
+ const isOffset = (token: string | undefined) => token !== undefined && /^-?[\d.]/.test(token)
111
+ const hasEdgeOffsets = tokens.some(
112
+ (token, index) => !isOffset(token) && token !== 'center' && isOffset(tokens[index + 1]),
113
+ )
114
+
115
+ // Edges and offsets from them: "right 10px top 20%".
116
+ if (hasEdgeOffsets) {
117
+ let x: Length = [0.5, 0]
118
+ let y: Length = [0.5, 0]
119
+
120
+ tokens.forEach((token, index) => {
121
+ if (isOffset(token)) return
122
+
123
+ const [fraction, points] = isOffset(tokens[index + 1]) ? length(tokens[index + 1]) : [0, 0]
124
+ const fromEnd = token === 'right' || token === 'bottom'
125
+ const edge: Length = fromEnd ? [1 - fraction, -points] : [fraction, points]
126
+
127
+ if (HORIZONTAL.has(token)) x = edge
128
+ else if (VERTICAL.has(token)) y = edge
129
+ })
130
+
131
+ return [x, y]
132
+ }
133
+
134
+ const [first, second = 'center'] = tokens
135
+ if (first === undefined)
136
+ return [
137
+ [0.5, 0],
138
+ [0.5, 0],
139
+ ]
140
+
141
+ const isSwapped = VERTICAL.has(first) || HORIZONTAL.has(second)
142
+
143
+ return isSwapped ? [length(second), length(first)] : [length(first), length(second)]
144
+ }
145
+
146
+ function length(token: string): Length {
147
+ if (token in SIDE_FRACTIONS) return [SIDE_FRACTIONS[token], 0]
148
+ if (token.endsWith('%')) return [Number.parseFloat(token) / 100, 0]
149
+
150
+ return [0, Number.parseFloat(token) || 0]
151
+ }
152
+
153
+ /**
154
+ * "red", "red 20%", "red 20% 40%" (two stops): colors and their positions, missing ones spread evenly
155
+ * between their neighbours, as CSS places them. Positions are percentages; a length counts as missing.
156
+ */
157
+ function colorStops(parts: string[]): Pick<BackgroundGradient, 'colors' | 'positions'> {
158
+ const colors: number[] = []
159
+ const known: (number | undefined)[] = []
160
+
161
+ for (const part of parts) {
162
+ const [colorText, ...positions] = splitTopLevel(part, ' ')
163
+ // A color hint ("red, 30%, blue") is left out: colors mix evenly.
164
+ const color = parseColor(colorText)
165
+ if (color == null) continue
166
+
167
+ const fractions = positions.map((text) =>
168
+ text.endsWith('%') ? Number.parseFloat(text) / 100 : undefined,
169
+ )
170
+
171
+ for (const fraction of fractions.length > 0 ? fractions : [undefined]) {
172
+ colors.push(color)
173
+ known.push(fraction)
174
+ }
175
+ }
176
+ if (colors.length === 1) {
177
+ colors.push(colors[0])
178
+ known.push(undefined)
179
+ }
180
+
181
+ return withoutTransparentBlack(...withinLine(colors, spreadPositions(known)))
182
+ }
183
+
184
+ /**
185
+ * Stops before 0% or past 100%, which CSS allows, cut at the ends of the line, the colors there mixed
186
+ * from their neighbours: native gradients take positions from 0 to 1.
187
+ */
188
+ function withinLine(colors: number[], positions: number[]): [number[], number[]] {
189
+ if (positions[0] >= 0 && positions[positions.length - 1] <= 1) return [colors, positions]
190
+
191
+ const colorAt = (position: number) => {
192
+ const after = positions.findIndex((stop) => stop >= position)
193
+ if (after <= 0) return colors[after < 0 ? colors.length - 1 : 0]
194
+
195
+ const span = positions[after] - positions[after - 1]
196
+
197
+ return mixColors(
198
+ colors[after - 1],
199
+ colors[after],
200
+ span === 0 ? 1 : (position - positions[after - 1]) / span,
201
+ )
202
+ }
203
+ const inside = positions.flatMap((position, index) =>
204
+ position > 0 && position < 1 ? [index] : [],
205
+ )
206
+
207
+ return [
208
+ [colorAt(0), ...inside.map((index) => colors[index]), colorAt(1)],
209
+ [0, ...inside.map((index) => positions[index]), 1],
210
+ ]
211
+ }
212
+
213
+ /** Two 0xRRGGBBAA colors mixed, `amount` of the way from the first. */
214
+ function mixColors(first: number, second: number, amount: number): number {
215
+ const channel = (color: number, shift: number) => (color >>> shift) & 0xff
216
+ const mixed = [24, 16, 8, 0].map((shift) =>
217
+ Math.round(channel(first, shift) + (channel(second, shift) - channel(first, shift)) * amount),
218
+ )
219
+
220
+ return ((mixed[0] << 24) | (mixed[1] << 16) | (mixed[2] << 8) | mixed[3]) >>> 0
221
+ }
222
+
223
+ /**
224
+ * CSS mixes a gradient's colors premultiplied: orange to transparent fades the orange out. Native mixes
225
+ * them as they are, through transparent's black, so a fully transparent stop takes its neighbours' color
226
+ * (twice, at the same place, when they differ).
227
+ */
228
+ function withoutTransparentBlack(
229
+ colors: number[],
230
+ positions: number[],
231
+ ): Pick<BackgroundGradient, 'colors' | 'positions'> {
232
+ const result: Pick<BackgroundGradient, 'colors' | 'positions'> = { colors: [], positions: [] }
233
+ const isClear = (color: number) => (color & 0xff) === 0
234
+ const add = (color: number, position: number) => {
235
+ result.colors.push(color >>> 0)
236
+ result.positions.push(position)
237
+ }
238
+
239
+ colors.forEach((color, index) => {
240
+ if (!isClear(color)) return add(color, positions[index])
241
+
242
+ const neighbours = [colors[index - 1], colors[index + 1]].filter(
243
+ (neighbour) => neighbour !== undefined && !isClear(neighbour),
244
+ )
245
+ if (neighbours.length === 0) return add(color, positions[index])
246
+
247
+ for (const neighbour of new Set(neighbours)) add(neighbour & 0xffffff00, positions[index])
248
+ })
249
+
250
+ return result
251
+ }
252
+
253
+ function spreadPositions(known: (number | undefined)[]): number[] {
254
+ const positions = [...known]
255
+
256
+ positions[0] ??= 0
257
+ positions[positions.length - 1] ??= 1
258
+
259
+ // Never before an earlier stop.
260
+ let latest = positions[0]!
261
+
262
+ for (let index = 1; index < positions.length; index++) {
263
+ if (positions[index] === undefined) continue
264
+
265
+ positions[index] = Math.max(positions[index]!, latest)
266
+ latest = positions[index]!
267
+ }
268
+ for (let index = 1; index < positions.length; index++) {
269
+ if (positions[index] !== undefined) continue
270
+
271
+ const next = positions.findIndex((position, after) => after > index && position !== undefined)
272
+ const start = positions[index - 1]!
273
+ const step = (positions[next]! - start) / (next - index + 1)
274
+
275
+ for (let missing = index; missing < next; missing++)
276
+ positions[missing] = start + step * (missing - index + 1)
277
+ }
278
+
279
+ return positions as number[]
280
+ }
281
+
282
+ /** Splits on `separator` outside parentheses: "rgb(0, 0, 0) 10%, red" by ",". */
283
+ function splitTopLevel(text: string, separator: ',' | ' '): string[] {
284
+ const parts: string[] = []
285
+ let depth = 0
286
+ let current = ''
287
+
288
+ for (const character of text) {
289
+ if (character === '(') depth++
290
+ if (character === ')') depth--
291
+
292
+ const separates = separator === ' ' ? /\s/.test(character) : character === separator
293
+
294
+ if (separates && depth === 0) {
295
+ if (current.trim()) parts.push(current.trim())
296
+ current = ''
297
+ } else {
298
+ current += character
299
+ }
300
+ }
301
+ if (current.trim()) parts.push(current.trim())
302
+
303
+ return parts
304
+ }
package/src/renderer.ts CHANGED
@@ -22,6 +22,7 @@ import { animatedEventMapping, animatedStyleBinding, isAnimatedEvent } from './a
22
22
  import { Appearance } from './appearance'
23
23
  import { COLOR_PROPERTIES, processColor } from './colors'
24
24
  import { FlatListComponent, ImageBackground, Pressable, Swipeable } from './components'
25
+ import { processBackgroundImage } from './gradients'
25
26
  import type { LayoutAnimationConfig, Style } from './types'
26
27
  export * from '@vue/runtime-core'
27
28
  export { AccessibilityInfo } from './accessibility'
@@ -259,7 +260,25 @@ function syncTextContent(parent: Node | null) {
259
260
  .map((child) => child.text)
260
261
  .join('')
261
262
  .trim()
262
- native.setText(parent.id, text)
263
+ native.setText(parent.id, transformedText(text, combinedStyle(parent)?.textTransform))
264
+ }
265
+
266
+ /** textTransform, applied to what's sent: the same on both platforms. */
267
+ function transformedText(text: string, textTransform: Style['textTransform']): string {
268
+ switch (textTransform) {
269
+ case 'uppercase':
270
+ return text.toUpperCase()
271
+ case 'lowercase':
272
+ return text.toLowerCase()
273
+ case 'capitalize':
274
+ // A word starts after anything but a letter, a digit or an apostrophe: "(hello)" is "(Hello)".
275
+ return text.replace(
276
+ /(^|[^\p{L}\p{N}'’])(\p{L})/gu,
277
+ (_, before: string, letter: string) => before + letter.toUpperCase(),
278
+ )
279
+ default:
280
+ return text
281
+ }
263
282
  }
264
283
 
265
284
  function detachFromParent(node: Node): Node | null {
@@ -277,6 +296,8 @@ function nativeIndexBefore(parent: Node, childIndex: number): number {
277
296
  }
278
297
 
279
298
  function nativeStyleValue(property: string, value: unknown): unknown {
299
+ if (property === 'backgroundImage') return processBackgroundImage(value)
300
+
280
301
  return COLOR_PROPERTIES.has(property) ? processColor(value) : value
281
302
  }
282
303
 
@@ -345,7 +366,10 @@ function updateStyle(
345
366
  if (element.className) nodesWithClass.add(element)
346
367
  else nodesWithClass.delete(element)
347
368
 
348
- patchStyle(element, previousStyle, combinedStyle(element))
369
+ const nextStyle = combinedStyle(element)
370
+
371
+ patchStyle(element, previousStyle, nextStyle)
372
+ if (previousStyle?.textTransform !== nextStyle?.textTransform) syncTextContent(element)
349
373
  }
350
374
 
351
375
  Appearance.addChangeListener(() => nodesWithClass.forEach((node) => updateStyle(node, {})))
@@ -456,12 +480,14 @@ const { createApp: createBaseApp } = createRenderer<Node, Node>({
456
480
  },
457
481
 
458
482
  setElementText(element, text) {
459
- element.children = []
460
- if (element.type === 'Text') native.setText(element.id, text.trim())
461
- if (drawnViewsByPartTag.has(element.type)) {
462
- element.children = [{ ...createNode('#text'), text, parent: element }]
463
- redraw(element)
464
- }
483
+ const isText = element.type === 'Text'
484
+ const isDrawnPart = drawnViewsByPartTag.has(element.type)
485
+
486
+ // Kept as a child: a later textTransform, or a drawing, reads it again.
487
+ element.children =
488
+ isText || isDrawnPart ? [{ ...createNode('#text'), text, parent: element }] : []
489
+ if (isText) syncTextContent(element)
490
+ if (isDrawnPart) redraw(element)
465
491
  },
466
492
 
467
493
  insert(child, parent, anchor) {