@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/AGENTS.md CHANGED
@@ -45,10 +45,13 @@ Global, with no import: `View`, `Text`, `Image`, `ImageBackground`, `Pressable`,
45
45
  `:style="{ padding: 16, borderRadius: 12, backgroundColor: '#ffffff' }"`. Arrays merge, later wins:
46
46
  `:style="[styles.card, selected && styles.selected]"`.
47
47
  - `StyleSheet.create({...})` (from `vue`) groups and types a screen's styles.
48
+ - Gradients: `backgroundImage: 'linear-gradient(135deg, #4af2ae, #10b39b)'` or `radial-gradient(...)`,
49
+ as in CSS, on a `View`; with Tailwind, `bg-linear-to-r from-emerald-400 to-teal-600`.
48
50
  - Every view is a flexbox container stacking its children in a **column** by default; `flex: 1` takes
49
51
  the space left. Percentages (`'50%'`) work for sizes.
50
- - Text styles (`color`, `fontSize`, `fontWeight`, `textAlign`, `textDecorationLine`) go on the
51
- `<Text>` itself: native views don't inherit them from their parents.
52
+ - Text styles (`color`, `fontSize`, `fontWeight`, `fontStyle`, `textAlign`, `textDecorationLine`,
53
+ `textTransform`, `letterSpacing`, `lineHeight`, `lineClamp`) go on the `<Text>` itself: native views
54
+ don't inherit them from their parents.
52
55
  - Pressed and focused states: `pressed-style` on `Pressable`, `focused-style` on `TextInput`.
53
56
  - Dark mode: `useColorScheme()` (from `vue`) gives `'light'` or `'dark'`, live.
54
57
  - Platform: `Platform.OS` is `'ios'` or `'android'`; `Platform.select({ ios, android })`.
@@ -0,0 +1,111 @@
1
+ package dev.nativue
2
+
3
+ import android.graphics.LinearGradient
4
+ import android.graphics.Matrix
5
+ import android.graphics.PointF
6
+ import android.graphics.RadialGradient
7
+ import android.graphics.Shader
8
+ import kotlin.math.abs
9
+ import kotlin.math.cos
10
+ import kotlin.math.hypot
11
+ import kotlin.math.max
12
+ import kotlin.math.min
13
+ import kotlin.math.sin
14
+ import kotlin.math.sqrt
15
+
16
+ /**
17
+ * backgroundImage: a CSS gradient (src/gradients.ts) as a shader for a box [width] by [height] pixels, where
18
+ * CSS puts it, as iOS's CSSGradient does. Lengths arrive in dp.
19
+ */
20
+ object BackgroundGradients {
21
+ fun shader(gradient: Map<*, *>, width: Float, height: Float, density: Float): Shader? {
22
+ val colors = (gradient["colors"] as? List<*>).orEmpty().mapNotNull(::androidColor).toIntArray()
23
+ val positions = (gradient["positions"] as? List<*>).orEmpty().mapNotNull { (it as? Number)?.toFloat() }.toFloatArray()
24
+ if (colors.size < 2 || colors.size != positions.size || width <= 0 || height <= 0) return null
25
+
26
+ if (gradient["type"] != "radial") {
27
+ val (start, end) = linear(gradient, width, height)
28
+
29
+ return LinearGradient(start.x, start.y, end.x, end.y, colors, positions, Shader.TileMode.CLAMP)
30
+ }
31
+
32
+ val (center, radii) = radial(gradient, width, height, density)
33
+ val radiusX = max(radii.x, 0.01f)
34
+
35
+ // Android's is a circle: stretched into the ellipse.
36
+ return RadialGradient(center.x, center.y, radiusX, colors, positions, Shader.TileMode.CLAMP).apply {
37
+ setLocalMatrix(Matrix().apply { setScale(1f, max(radii.y, 0.01f) / radiusX, center.x, center.y) })
38
+ }
39
+ }
40
+
41
+ /** The gradient line: through the center, as long as the box is along it, so its ends touch the corners. */
42
+ private fun linear(gradient: Map<*, *>, width: Float, height: Float): Pair<PointF, PointF> {
43
+ val sides = (gradient["to"] as? List<*>)?.map { it.toString() }
44
+ val angle = (gradient["angle"] as? Number)?.toDouble()?.let(Math::toRadians)
45
+ var directionX = 0f
46
+ var directionY = 1f
47
+
48
+ if (sides != null) {
49
+ val x = if ("right" in sides) 1f else if ("left" in sides) -1f else 0f
50
+ val y = if ("bottom" in sides) 1f else if ("top" in sides) -1f else 0f
51
+ // To a corner: perpendicular to the diagonal between the two corners next to it.
52
+ val isCorner = x != 0f && y != 0f
53
+
54
+ directionX = if (isCorner) x * height else x
55
+ directionY = if (isCorner) y * width else y
56
+ } else if (angle != null) {
57
+ // 0 points up, 90 right.
58
+ directionX = sin(angle).toFloat()
59
+ directionY = -cos(angle).toFloat()
60
+ }
61
+
62
+ val length = hypot(directionX, directionY)
63
+ if (length == 0f) return PointF(0f, 0f) to PointF(0f, height)
64
+
65
+ val unitX = directionX / length
66
+ val unitY = directionY / length
67
+ val halfLine = (abs(width * unitX) + abs(height * unitY)) / 2
68
+
69
+ return PointF(width / 2 - unitX * halfLine, height / 2 - unitY * halfLine) to
70
+ PointF(width / 2 + unitX * halfLine, height / 2 + unitY * halfLine)
71
+ }
72
+
73
+ /** The center and the radii: given, or reaching the extent keyword's side or corner. */
74
+ private fun radial(gradient: Map<*, *>, width: Float, height: Float, density: Float): Pair<PointF, PointF> {
75
+ val center = PointF(
76
+ length(gradient["center"], 0, width, density, 0.5f),
77
+ length(gradient["center"], 1, height, density, 0.5f),
78
+ )
79
+ val isCircle = gradient["shape"] == "circle"
80
+
81
+ if (gradient["radii"] != null) {
82
+ val radiusX = length(gradient["radii"], 0, width, density, 0.5f)
83
+ val radiusY = if (isCircle) radiusX else length(gradient["radii"], 1, height, density, 0.5f)
84
+
85
+ return center to PointF(radiusX, radiusY)
86
+ }
87
+
88
+ val extent = gradient["extent"] as? String ?: "farthest-corner"
89
+ val pick = { first: Float, second: Float -> if (extent.startsWith("closest")) min(first, second) else max(first, second) }
90
+ val sideX = pick(abs(center.x), abs(width - center.x))
91
+ val sideY = pick(abs(center.y), abs(height - center.y))
92
+
93
+ val radii = when {
94
+ extent.endsWith("corner") && isCircle -> hypot(sideX, sideY).let { PointF(it, it) }
95
+ // An ellipse through the corner, shaped like the one that would touch the sides.
96
+ extent.endsWith("corner") -> PointF(sideX * sqrt(2f), sideY * sqrt(2f))
97
+ isCircle -> pick(sideX, sideY).let { PointF(it, it) }
98
+ else -> PointF(sideX, sideY)
99
+ }
100
+
101
+ return center to radii
102
+ }
103
+
104
+ /** [[fraction, dp], ...][index], in pixels of a side [side] long. */
105
+ private fun length(value: Any?, index: Int, side: Float, density: Float, defaultFraction: Float): Float {
106
+ val pair = ((value as? List<*>)?.getOrNull(index) as? List<*>)?.mapNotNull { (it as? Number)?.toFloat() }
107
+ if (pair == null || pair.size != 2) return defaultFraction * side
108
+
109
+ return pair[0] * side + pair[1] * density
110
+ }
111
+ }
@@ -4,18 +4,25 @@ import android.graphics.Canvas
4
4
  import android.graphics.ColorFilter
5
5
  import android.graphics.Outline
6
6
  import android.graphics.Paint
7
+ import android.graphics.Path
7
8
  import android.graphics.PixelFormat
8
9
  import android.graphics.RectF
9
10
  import android.graphics.drawable.Drawable
11
+ import android.os.Build
10
12
  import kotlin.math.max
11
13
 
12
14
  /**
13
- * A view's box: background color, rounded corners, border and a shadow drawn like iOS layers draw
14
- * theirs (color, opacity, blur radius, offset), outside the view's bounds. Sizes in pixels.
15
+ * A view's box: background color and gradients, rounded corners, border and a shadow drawn like iOS layers
16
+ * draw theirs (color, opacity, blur radius, offset), outside the view's bounds. Sizes in pixels.
15
17
  */
16
18
  class BoxDrawable : Drawable() {
17
19
  var backgroundColor = 0
20
+ /** backgroundImage (BackgroundGradients), the first on top; their lengths in dp, hence the density. */
21
+ var gradients: List<Map<*, *>> = emptyList()
22
+ var density = 1f
18
23
  var cornerRadius = 0f
24
+ /** Corners with their own radius, over cornerRadius: top left, top right, bottom right, bottom left. */
25
+ val cornerRadii = arrayOfNulls<Float>(4)
19
26
  var borderWidth = 0f
20
27
  var borderColor = 0
21
28
 
@@ -28,33 +35,62 @@ class BoxDrawable : Drawable() {
28
35
  private val fillPaint = Paint(Paint.ANTI_ALIAS_FLAG)
29
36
  private val borderPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE }
30
37
  private val rect = RectF()
38
+ private val boxPath = Path()
39
+ private val borderPath = Path()
40
+
41
+ /** Whether a corner has its own radius: the box is then a path, not a rounded rectangle. */
42
+ val hasCornerRadii: Boolean
43
+ get() = cornerRadii.any { it != null }
31
44
 
32
45
  override fun draw(canvas: Canvas) {
33
46
  rect.set(bounds)
47
+ val box = roundedPath(boxPath, rect, inset = 0f)
34
48
 
49
+ fillPaint.shader = null
35
50
  fillPaint.color = backgroundColor
36
- applyShadow()
37
- if (backgroundColor ushr 24 != 0) canvas.drawRoundRect(rect, cornerRadius, cornerRadius, fillPaint)
51
+ applyShadow(castsShadow = backgroundColor ushr 24 != 0)
52
+ if (backgroundColor ushr 24 != 0) canvas.drawPath(box, fillPaint)
53
+
54
+ // The bottom one casts the shadow when there's no background color.
55
+ gradients.asReversed().forEachIndexed { index, gradient ->
56
+ fillPaint.shader = BackgroundGradients.shader(gradient, rect.width(), rect.height(), density) ?: return@forEachIndexed
57
+ fillPaint.color = 0xFF000000.toInt()
58
+ applyShadow(castsShadow = index == 0 && backgroundColor ushr 24 == 0)
59
+ canvas.drawPath(box, fillPaint)
60
+ }
61
+ fillPaint.shader = null
38
62
 
39
63
  if (borderWidth > 0) {
40
64
  // The stroke is centered on the path: inset by half so it stays inside, like iOS borders.
41
65
  rect.inset(borderWidth / 2, borderWidth / 2)
42
66
  borderPaint.color = borderColor
43
67
  borderPaint.strokeWidth = borderWidth
44
- val radius = max(0f, cornerRadius - borderWidth / 2)
45
- canvas.drawRoundRect(rect, radius, radius, borderPaint)
68
+ canvas.drawPath(roundedPath(borderPath, rect, inset = borderWidth / 2), borderPaint)
46
69
  }
47
70
  }
48
71
 
72
+ /** [path] set to [bounds] with its corners rounded, each radius less [inset]. */
73
+ private fun roundedPath(path: Path, bounds: RectF, inset: Float): Path {
74
+ val radii = FloatArray(8) { index -> max(0f, (cornerRadii[index / 2] ?: cornerRadius) - inset) }
75
+
76
+ path.reset()
77
+ path.addRoundRect(bounds, radii, Path.Direction.CW)
78
+
79
+ return path
80
+ }
81
+
82
+ /** The box's shape, which a ContainerView clips its children to where its outline can't. */
83
+ fun outlinePath(): Path = roundedPath(Path(), RectF(bounds), inset = 0f)
84
+
49
85
  /**
50
86
  * Core Animation blurs with a sigma of half the shadow radius; Skia's blur radius r gives a sigma of
51
87
  * 0.57735 r + 0.5. The shadow takes the fill's alpha, like iOS (an invisible box casts none).
52
88
  */
53
- private fun applyShadow() {
89
+ private fun applyShadow(castsShadow: Boolean) {
54
90
  val sigma = shadowRadius / 2
55
91
  val alpha = ((shadowColor ushr 24) * shadowOpacity).toInt().coerceIn(0, 255)
56
92
 
57
- if (alpha == 0 || backgroundColor ushr 24 == 0) {
93
+ if (alpha == 0 || !castsShadow) {
58
94
  fillPaint.clearShadowLayer()
59
95
  return
60
96
  }
@@ -65,7 +101,11 @@ class BoxDrawable : Drawable() {
65
101
 
66
102
  /** `overflow: 'hidden'` clips to this outline, so rounded corners clip their content. */
67
103
  override fun getOutline(outline: Outline) {
68
- outline.setRoundRect(bounds, cornerRadius)
104
+ if (!hasCornerRadii) return outline.setRoundRect(bounds, cornerRadius)
105
+
106
+ val path = outlinePath()
107
+
108
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) outline.setPath(path) else @Suppress("DEPRECATION") outline.setConvexPath(path)
69
109
  }
70
110
 
71
111
  override fun setAlpha(alpha: Int) {}
@@ -880,7 +880,7 @@ class Bridge(private val activity: ComponentActivity, private val rootView: Root
880
880
  private fun setText(text: String, id: Int) {
881
881
  val node = nodesById[id] ?: return
882
882
 
883
- (node.view as? TextView)?.text = text
883
+ (node.view as? TextView)?.text = node.withLineHeight(text)
884
884
  node.markContentChanged()
885
885
  }
886
886
 
@@ -1167,7 +1167,7 @@ class Bridge(private val activity: ComponentActivity, private val rootView: Root
1167
1167
  }
1168
1168
 
1169
1169
  private companion object {
1170
- const val TAG = "Nativue"
1170
+ const val TAG = "nativue"
1171
1171
  const val JAVASCRIPT_STACK_SIZE = 8L * 1024 * 1024
1172
1172
  const val SYMBOLICATE_TIMEOUT_MS = 2000
1173
1173
  const val RECONNECT_DELAY_MS = 2000L
@@ -23,6 +23,10 @@ class NativeNode(val view: View, measuresContent: Boolean) {
23
23
 
24
24
  var fontSize = DEFAULT_FONT_SIZE
25
25
  var fontWeight = 400
26
+ var isItalic = false
27
+ /** Points, or ems of the font size ('1.5em'); null for the font's own. */
28
+ var letterSpacing: Any? = null
29
+ var lineHeight: Any? = null
26
30
 
27
31
  /** WindowInsets types that pad this node (safe area, keyboard), 0 for none, and the last padding. */
28
32
  var insetTypes = 0
@@ -3,6 +3,10 @@ package dev.nativue
3
3
  import android.content.Context
4
4
  import android.graphics.Paint
5
5
  import android.graphics.Typeface
6
+ import android.text.SpannableString
7
+ import android.text.Spanned
8
+ import android.text.TextUtils
9
+ import android.text.style.LineHeightSpan
6
10
  import android.util.TypedValue
7
11
  import android.view.Gravity
8
12
  import android.view.View
@@ -19,6 +23,7 @@ import com.facebook.yoga.YogaNode
19
23
  import com.facebook.yoga.YogaOverflow
20
24
  import com.facebook.yoga.YogaPositionType
21
25
  import com.facebook.yoga.YogaWrap
26
+ import kotlin.math.roundToInt
22
27
 
23
28
  /**
24
29
  * Receives only the properties that changed: the JS renderer diffs style objects before sending. A removed
@@ -48,7 +53,14 @@ private fun NativeNode.applyVisualProperty(property: String, value: Any?) {
48
53
 
49
54
  when (property) {
50
55
  "backgroundColor" -> updateBox { backgroundColor = androidColor(value) ?: 0 }
56
+ "backgroundImage" -> updateBox {
57
+ gradients = (value as? List<*>)?.filterIsInstance<Map<*, *>>().orEmpty()
58
+ density = view.resources.displayMetrics.density
59
+ }
51
60
  "borderRadius" -> updateBox { cornerRadius = pixels(value) }
61
+ "borderTopLeftRadius", "borderTopRightRadius", "borderBottomRightRadius", "borderBottomLeftRadius" -> updateBox {
62
+ cornerRadii[CORNERS.indexOf(property)] = value?.let { pixels(it) }
63
+ }
52
64
  "borderWidth" -> updateBox { borderWidth = pixels(value) }
53
65
  "borderColor" -> updateBox { borderColor = androidColor(value) ?: 0 }
54
66
  "shadowColor" -> updateBox { shadowColor = androidColor(value) ?: 0xFF000000.toInt() }
@@ -69,6 +81,26 @@ private fun NativeNode.applyVisualProperty(property: String, value: Any?) {
69
81
  }
70
82
  "textAlign" -> textView?.gravity = textGravities[value] ?: Gravity.START
71
83
  "textDecorationLine" -> textView?.let { it.paintFlags = decoratedPaintFlags(it.paintFlags, value as? String) }
84
+ "fontStyle" -> textView?.let {
85
+ isItalic = value == "italic"
86
+ it.typeface = typefaceOfWeight(it.context, fontWeight, isItalic)
87
+ markContentChanged()
88
+ }
89
+ "letterSpacing" -> {
90
+ letterSpacing = value
91
+ updateTextSpacing()
92
+ }
93
+ "lineHeight" -> {
94
+ lineHeight = value
95
+ updateTextSpacing()
96
+ }
97
+ "lineClamp" -> textView?.let {
98
+ val lines = number(value)?.toInt() ?: 0
99
+
100
+ it.maxLines = if (lines > 0) lines else Int.MAX_VALUE
101
+ it.ellipsize = if (lines > 0) TextUtils.TruncateAt.END else null
102
+ markContentChanged()
103
+ }
72
104
  }
73
105
  }
74
106
 
@@ -120,8 +152,8 @@ private fun degrees(value: Any?): Float {
120
152
  }
121
153
 
122
154
  /** The system font at a weight (100 to 900). */
123
- fun typefaceOfWeight(context: Context, weight: Int): Typeface =
124
- TypefaceCompat.create(context, Typeface.DEFAULT, weight, false)
155
+ fun typefaceOfWeight(context: Context, weight: Int, isItalic: Boolean = false): Typeface =
156
+ TypefaceCompat.create(context, Typeface.DEFAULT, weight, isItalic)
125
157
 
126
158
  /** Font size and weight can change independently, so the node remembers both. */
127
159
  private fun NativeNode.applyFont(changes: Map<String, Any?>) {
@@ -129,7 +161,7 @@ private fun NativeNode.applyFont(changes: Map<String, Any?>) {
129
161
  if ("fontWeight" in changes) fontWeight = changes["fontWeight"]?.let(::fontWeightOf) ?: 400
130
162
 
131
163
  val textView = view as? TextView ?: return
132
- textView.typeface = typefaceOfWeight(textView.context, fontWeight)
164
+ textView.typeface = typefaceOfWeight(textView.context, fontWeight, isItalic)
133
165
  updateFontSize()
134
166
  }
135
167
 
@@ -141,9 +173,52 @@ fun NativeNode.updateFontSize() {
141
173
  val textView = view as? TextView ?: return
142
174
  textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSize)
143
175
 
176
+ if (letterSpacing != null || lineHeight != null) updateTextSpacing()
144
177
  markContentChanged()
145
178
  }
146
179
 
180
+ /** letterSpacing and lineHeight, which can be in ems of the font size: set again when that size changes. */
181
+ private fun NativeNode.updateTextSpacing() {
182
+ val textLabel = view as? TextLabel ?: return
183
+
184
+ // Android's is in ems already.
185
+ textLabel.letterSpacing = ems(letterSpacing) ?: number(letterSpacing)?.let { pixels(it) / textLabel.textSize } ?: 0f
186
+ textLabel.text = withLineHeight(textLabel.text.toString())
187
+ markContentChanged()
188
+ }
189
+
190
+ /** A <Text>'s text, its lines as tall as lineHeight when it has one. */
191
+ fun NativeNode.withLineHeight(text: String): CharSequence {
192
+ val textSize = (view as? TextLabel)?.textSize ?: return text
193
+ val height = ems(lineHeight)?.let { it * textSize } ?: number(lineHeight)?.let { pixels(it) } ?: return text
194
+
195
+ return SpannableString(text).apply {
196
+ setSpan(CenteredLineHeightSpan(height.roundToInt()), 0, length, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
197
+ }
198
+ }
199
+
200
+ /** "1.5em" as 1.5; null for anything else. */
201
+ private fun ems(value: Any?): Float? = (value as? String)?.takeIf { it.endsWith("em") }?.dropLast(2)?.toFloatOrNull()
202
+
203
+ /** Each line [height] pixels tall, the text centered in it, as CSS lays out a line height. */
204
+ private class CenteredLineHeightSpan(private val height: Int) : LineHeightSpan {
205
+ override fun chooseHeight(
206
+ text: CharSequence,
207
+ start: Int,
208
+ end: Int,
209
+ spanStart: Int,
210
+ lineHeight: Int,
211
+ metrics: Paint.FontMetricsInt,
212
+ ) {
213
+ val extra = height - (metrics.descent - metrics.ascent)
214
+
215
+ metrics.ascent -= extra / 2
216
+ metrics.descent += extra - extra / 2
217
+ metrics.top = metrics.ascent
218
+ metrics.bottom = metrics.descent
219
+ }
220
+ }
221
+
147
222
  private fun NativeNode.pixels(value: Any?): Float = (number(value) ?: 0f) * view.resources.displayMetrics.density
148
223
 
149
224
  fun number(value: Any?): Float? = (value as? Number)?.toFloat()
@@ -157,6 +232,9 @@ fun androidColor(value: Any?): Int? {
157
232
 
158
233
  // ---------- CSS value tables ----------
159
234
 
235
+ // In BoxDrawable.cornerRadii's order.
236
+ private val CORNERS = listOf("borderTopLeftRadius", "borderTopRightRadius", "borderBottomRightRadius", "borderBottomLeftRadius")
237
+
160
238
  private val edgesBySuffix = mapOf(
161
239
  "" to YogaEdge.ALL,
162
240
  "Horizontal" to YogaEdge.HORIZONTAL,
@@ -4,7 +4,9 @@ import android.annotation.SuppressLint
4
4
  import android.content.Context
5
5
  import android.graphics.Bitmap
6
6
  import android.graphics.BitmapFactory
7
+ import android.graphics.Canvas
7
8
  import android.graphics.Rect
9
+ import android.os.Build
8
10
  import android.os.Handler
9
11
  import android.os.Looper
10
12
  import android.os.SystemClock
@@ -14,9 +16,9 @@ import android.view.MotionEvent
14
16
  import android.view.View
15
17
  import android.view.ViewConfiguration
16
18
  import android.view.ViewGroup
19
+ import android.view.inputmethod.InputMethodManager
17
20
  import android.widget.FrameLayout
18
21
  import android.widget.HorizontalScrollView
19
- import android.view.inputmethod.InputMethodManager
20
22
  import android.widget.ImageView
21
23
  import android.widget.ProgressBar
22
24
  import android.widget.ScrollView
@@ -26,9 +28,9 @@ import java.io.IOException
26
28
  import java.net.URL
27
29
  import java.security.MessageDigest
28
30
  import java.util.concurrent.Executors
31
+ import kotlin.math.abs
29
32
  import kotlin.math.min
30
33
  import kotlin.math.roundToInt
31
- import kotlin.math.abs
32
34
 
33
35
  /**
34
36
  * A view whose children Yoga places (NativeNode.applyFrames): Android's own layout passes keep them
@@ -68,6 +70,19 @@ open class ContainerView(context: Context) : ViewGroup(context) {
68
70
  override fun onInterceptTouchEvent(event: MotionEvent): Boolean =
69
71
  gestureReporter?.isRecognizing == true || super.onInterceptTouchEvent(event)
70
72
 
73
+ /** Before Android 13 only a rounded rectangle outline clips: corners with their own radius clip here. */
74
+ override fun dispatchDraw(canvas: Canvas) {
75
+ val box = background as? BoxDrawable
76
+ if (!clipToOutline || box?.hasCornerRadii != true || Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
77
+ return super.dispatchDraw(canvas)
78
+ }
79
+
80
+ canvas.save()
81
+ canvas.clipPath(box.outlinePath())
82
+ super.dispatchDraw(canvas)
83
+ canvas.restore()
84
+ }
85
+
71
86
  /** Without an exact size (inside a scroll view), the size set in its layout params. */
72
87
  override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
73
88
  setMeasuredDimension(
@@ -544,7 +544,7 @@ function nativueInfoPlist(app) {
544
544
  ],
545
545
  NSAppTransportSecurity: { NSAllowsLocalNetworking: true },
546
546
  NSLocalNetworkUsageDescription:
547
- 'Connects to the Nativue dev server on your Mac for hot reload.',
547
+ 'Connects to the nativue dev server on your Mac for hot reload.',
548
548
  UILaunchScreen: { UIColorName: 'LaunchBackground', UIImageName: 'LaunchLogo' },
549
549
  }
550
550
  }
@@ -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
+ }