@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,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) {
package/src/types.ts CHANGED
@@ -47,9 +47,19 @@ export type Style = {
47
47
  overflow?: 'visible' | 'hidden' | 'scroll'
48
48
 
49
49
  backgroundColor?: ColorValue
50
+ /**
51
+ * CSS gradients over backgroundColor, the first on top: 'linear-gradient(135deg, #4af2ae, #10b39b)',
52
+ * 'radial-gradient(circle at top, white, transparent 70%)'. On iOS, on a View: not on a Text or Image.
53
+ */
54
+ backgroundImage?: string
50
55
  borderColor?: ColorValue
51
56
  borderWidth?: number
52
57
  borderRadius?: number
58
+ /** One corner's radius, over borderRadius. On iOS, the rounded corners share the largest radius. */
59
+ borderTopLeftRadius?: number
60
+ borderTopRightRadius?: number
61
+ borderBottomLeftRadius?: number
62
+ borderBottomRightRadius?: number
53
63
  opacity?: number | AnimatedNode
54
64
  transform?: TransformStep[]
55
65
  shadowColor?: ColorValue
@@ -63,6 +73,14 @@ export type Style = {
63
73
  'normal' | 'bold' | '100' | '200' | '300' | '400' | '500' | '600' | '700' | '800' | '900'
64
74
  textAlign?: 'auto' | 'left' | 'right' | 'center' | 'justify'
65
75
  textDecorationLine?: 'none' | 'underline' | 'line-through' | 'underline line-through'
76
+ fontStyle?: 'normal' | 'italic'
77
+ textTransform?: 'none' | 'uppercase' | 'lowercase' | 'capitalize'
78
+ /** In points, or in ems of the font size: '0.05em'. <Text> only. */
79
+ letterSpacing?: number | `${number}em`
80
+ /** The height of a line, in points, or in ems of the font size: '1.5em'. <Text> only. */
81
+ lineHeight?: number | `${number}em`
82
+ /** At most this many lines, the last one ending in an ellipsis. */
83
+ lineClamp?: number
66
84
  }
67
85
 
68
86
  export type GestureState = 'began' | 'changed' | 'ended' | 'cancelled' | 'failed'