orvyn-lang 0.3.0 → 0.4.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.
@@ -5,13 +5,23 @@
5
5
 
6
6
  package dev.orvyn.runtime
7
7
 
8
+ import android.animation.LayoutTransition
9
+ import android.animation.ValueAnimator
8
10
  import android.app.DatePickerDialog
9
11
  import android.app.Dialog
10
12
  import android.content.Context
11
13
  import android.content.Intent
12
14
  import android.graphics.Bitmap
13
15
  import android.graphics.BitmapFactory
16
+ import android.graphics.Canvas
14
17
  import android.graphics.Color
18
+ import android.graphics.ColorFilter
19
+ import android.graphics.Outline
20
+ import android.graphics.Paint
21
+ import android.graphics.PixelFormat
22
+ import android.graphics.RectF
23
+ import android.graphics.drawable.Drawable
24
+ import android.graphics.drawable.LayerDrawable
15
25
  import android.graphics.Typeface
16
26
  import android.graphics.drawable.GradientDrawable
17
27
  import android.graphics.drawable.StateListDrawable
@@ -27,6 +37,7 @@ import android.util.TypedValue
27
37
  import android.view.Gravity
28
38
  import android.view.View
29
39
  import android.view.ViewGroup
40
+ import android.view.ViewOutlineProvider
30
41
  import android.webkit.WebView
31
42
  import android.webkit.WebViewClient
32
43
  import android.widget.AbsListView
@@ -63,64 +74,277 @@ private class Info(val type: String, val wrapped: Boolean = false) {
63
74
  var updating = false
64
75
  var disabled = false
65
76
  var loading = false
77
+ var appeared = false
78
+ var appearUntil = 0L
79
+ var bgColor: Int? = null
80
+ var abs: JSONObject? = null
81
+ var bgImage: String? = null
66
82
  }
67
83
 
68
- // Simple wrapping row container so `Row wrap: true` behaves like CSS flex-wrap.
84
+ // position: "absolute" children are taken out of the flow and placed by
85
+ // top / left / right / bottom (points, or "40%" of the parent), like the web
86
+ private fun absoluteSpec(view: View): JSONObject? = (view.tag as? Info)?.abs
87
+
88
+ private fun edge(spec: JSONObject, key: String, size: Int, density: Float): Int? {
89
+ val value = spec.opt(key) ?: return null
90
+ return when (value) {
91
+ is Number -> (value.toFloat() * density).toInt()
92
+ is String -> {
93
+ val text = value.trim()
94
+ val amount = text.removeSuffix("%").toFloatOrNull() ?: return null
95
+ if (text.endsWith("%")) (size * amount / 100f).toInt() else (amount * density).toInt()
96
+ }
97
+ else -> null
98
+ }
99
+ }
100
+
101
+ private fun measureAbsolute(parent: ViewGroup, width: Int) {
102
+ for (i in 0 until parent.childCount) {
103
+ val child = parent.getChildAt(i)
104
+ if (absoluteSpec(child) == null || child.visibility == View.GONE) continue
105
+ val lp = child.layoutParams
106
+ val ws = if (lp.width > 0) View.MeasureSpec.makeMeasureSpec(lp.width, View.MeasureSpec.EXACTLY)
107
+ else View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.AT_MOST)
108
+ val hs = if (lp.height > 0) View.MeasureSpec.makeMeasureSpec(lp.height, View.MeasureSpec.EXACTLY)
109
+ else View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
110
+ child.measure(ws, hs)
111
+ }
112
+ }
113
+
114
+ private fun placeAbsolute(parent: ViewGroup, width: Int, height: Int) {
115
+ val density = parent.resources.displayMetrics.density
116
+ for (i in 0 until parent.childCount) {
117
+ val child = parent.getChildAt(i)
118
+ val spec = absoluteSpec(child) ?: continue
119
+ if (child.visibility == View.GONE) continue
120
+ val cw = child.measuredWidth
121
+ val ch = child.measuredHeight
122
+ val x = edge(spec, "left", width, density) ?: edge(spec, "right", width, density)?.let { width - it - cw } ?: parent.paddingLeft
123
+ val y = edge(spec, "top", height, density) ?: edge(spec, "bottom", height, density)?.let { height - it - ch } ?: parent.paddingTop
124
+ child.layout(x, y, x + cw, y + ch)
125
+ }
126
+ }
127
+
128
+ // justify: between / around / evenly: where the first item starts and the
129
+ // extra space after each item
130
+ private fun spreadSpace(justify: String, free: Int, count: Int): Pair<Float, Float>? {
131
+ if (free <= 0 || count == 0) return null
132
+ return when (justify.removePrefix("space-")) {
133
+ "between" -> if (count == 1) 0f to 0f else 0f to free.toFloat() / (count - 1)
134
+ "around" -> free / (2f * count) to free.toFloat() / count
135
+ "evenly" -> free / (count + 1f) to free / (count + 1f)
136
+ else -> null
137
+ }
138
+ }
139
+
140
+ // A background photo drawn to cover the box (like CSS background-size: cover),
141
+ // darkened by `dim` so text on top stays readable
142
+ private class CoverDrawable(private val bitmap: Bitmap, private val dim: Float) : Drawable() {
143
+ private val paint = Paint(Paint.FILTER_BITMAP_FLAG or Paint.ANTI_ALIAS_FLAG)
144
+ override fun draw(canvas: Canvas) {
145
+ val b = bounds
146
+ if (b.isEmpty || bitmap.width == 0 || bitmap.height == 0) return
147
+ val scale = maxOf(b.width() / bitmap.width.toFloat(), b.height() / bitmap.height.toFloat())
148
+ val w = bitmap.width * scale
149
+ val h = bitmap.height * scale
150
+ val left = b.left + (b.width() - w) / 2
151
+ val top = b.top + (b.height() - h) / 2
152
+ canvas.save()
153
+ canvas.clipRect(b)
154
+ canvas.drawBitmap(bitmap, null, RectF(left, top, left + w, top + h), paint)
155
+ if (dim > 0f) canvas.drawColor(Color.argb((dim * 255).toInt().coerceIn(0, 255), 0, 0, 0))
156
+ canvas.restore()
157
+ }
158
+ override fun setAlpha(alpha: Int) { paint.alpha = alpha }
159
+ override fun setColorFilter(colorFilter: ColorFilter?) { paint.colorFilter = colorFilter }
160
+ @Deprecated("Deprecated in Java")
161
+ override fun getOpacity() = PixelFormat.TRANSLUCENT
162
+ }
163
+
164
+ // marquee: "left 30s": the row keeps its natural width and slides in an
165
+ // endless loop. The row is drawn again right after itself, so there is no gap.
166
+ private class MarqueeLayout(context: Context) : ViewGroup(context) {
167
+ var seconds = 30f
168
+ var toRight = false
169
+ private var offset = 0f
170
+ private var animator: ValueAnimator? = null
171
+
172
+ init { setWillNotDraw(false) }
173
+
174
+ override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
175
+ val child = getChildAt(0)
176
+ child?.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), heightMeasureSpec)
177
+ val width = MeasureSpec.getSize(widthMeasureSpec)
178
+ setMeasuredDimension(width, resolveSize(child?.measuredHeight ?: 0, heightMeasureSpec))
179
+ }
180
+
181
+ override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
182
+ val child = getChildAt(0) ?: return
183
+ child.layout(0, 0, child.measuredWidth, child.measuredHeight)
184
+ restart(child.measuredWidth)
185
+ }
186
+
187
+ private fun restart(span: Int) {
188
+ val running = animator
189
+ // keep sliding smoothly across re-renders unless the width or speed changed
190
+ if (running != null && running.isRunning && running.duration == (seconds * 1000).toLong() && lastSpan == span) return
191
+ running?.cancel()
192
+ lastSpan = span
193
+ if (span <= 0) return
194
+ animator = ValueAnimator.ofFloat(0f, span.toFloat()).apply {
195
+ duration = (seconds * 1000).toLong()
196
+ repeatCount = ValueAnimator.INFINITE
197
+ interpolator = android.view.animation.LinearInterpolator()
198
+ addUpdateListener {
199
+ offset = it.animatedValue as Float
200
+ invalidate()
201
+ }
202
+ start()
203
+ }
204
+ }
205
+ private var lastSpan = -1
206
+
207
+ override fun onDetachedFromWindow() {
208
+ super.onDetachedFromWindow()
209
+ animator?.cancel()
210
+ animator = null
211
+ lastSpan = -1
212
+ }
213
+
214
+ override fun dispatchDraw(canvas: Canvas) {
215
+ val child = getChildAt(0) ?: return
216
+ val span = child.measuredWidth
217
+ if (span <= 0) return
218
+ val start = if (toRight) offset - span else -offset
219
+ canvas.save()
220
+ canvas.translate(start, 0f)
221
+ var drawn = start
222
+ while (drawn < width) {
223
+ drawChild(canvas, child, drawingTime)
224
+ canvas.translate(span.toFloat(), 0f)
225
+ drawn += span
226
+ }
227
+ canvas.restore()
228
+ }
229
+ }
230
+
231
+ // Rows and columns: LinearLayout plus justify: between and absolute children
232
+ private class FlowLayout(context: Context) : LinearLayout(context) {
233
+ var justify = ""
234
+
235
+ // like the web, a child placed at top: -10 can stick out of its box
236
+ init { clipChildren = false; clipToPadding = false }
237
+
238
+ // absolute children are detached while LinearLayout measures and places
239
+ // the rest, so they take no space (detaching does not ask for a new layout)
240
+ private fun withoutAbsolute(block: () -> Unit) {
241
+ val hidden = (0 until childCount).map { it to getChildAt(it) }.filter { absoluteSpec(it.second) != null }
242
+ for ((index, _) in hidden.reversed()) detachViewFromParent(index)
243
+ try {
244
+ block()
245
+ } finally {
246
+ for ((index, child) in hidden) attachViewToParent(child, index, child.layoutParams)
247
+ }
248
+ }
249
+
250
+ override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
251
+ withoutAbsolute { super.onMeasure(widthMeasureSpec, heightMeasureSpec) }
252
+ measureAbsolute(this, measuredWidth)
253
+ }
254
+
255
+ override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
256
+ withoutAbsolute {
257
+ super.onLayout(changed, l, t, r, b)
258
+ spread()
259
+ }
260
+ placeAbsolute(this, r - l, b - t)
261
+ }
262
+
263
+ private fun spread() {
264
+ val kids = (0 until childCount).map { getChildAt(it) }.filter { it.visibility != View.GONE }
265
+ val horizontal = orientation == HORIZONTAL
266
+ val inner = if (horizontal) width - paddingLeft - paddingRight else height - paddingTop - paddingBottom
267
+ val used = kids.sumOf {
268
+ val lp = it.layoutParams as MarginLayoutParams
269
+ if (horizontal) it.measuredWidth + lp.leftMargin + lp.rightMargin else it.measuredHeight + lp.topMargin + lp.bottomMargin
270
+ }
271
+ val (lead, step) = spreadSpace(justify, inner - used, kids.size) ?: return
272
+ kids.forEachIndexed { i, child ->
273
+ val offset = (lead + step * i).toInt()
274
+ if (horizontal) child.offsetLeftAndRight(offset) else child.offsetTopAndBottom(offset)
275
+ }
276
+ }
277
+ }
278
+
279
+ // `Row wrap: true` behaves like CSS flex-wrap, with justify and align per line
69
280
  private class WrapLayout(context: Context) : ViewGroup(context) {
70
281
  var gapPx: Int = 0
282
+ var justify = ""
283
+ var align = ""
71
284
 
72
- override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
73
- val maxWidth = MeasureSpec.getSize(widthMeasureSpec)
74
- val widthMode = MeasureSpec.getMode(widthMeasureSpec)
75
- val available = if (widthMode == MeasureSpec.UNSPECIFIED) Int.MAX_VALUE else (maxWidth - paddingLeft - paddingRight).coerceAtLeast(0)
285
+ init { clipChildren = false; clipToPadding = false }
76
286
 
77
- var x = 0
78
- var y = paddingTop
79
- var rowHeight = 0
80
- var maxRowWidth = 0
287
+ private fun flowChildren() = (0 until childCount).map { getChildAt(it) }
288
+ .filter { it.visibility != View.GONE && absoluteSpec(it) == null }
81
289
 
82
- for (i in 0 until childCount) {
83
- val child = getChildAt(i)
84
- if (child.visibility == View.GONE) continue
85
- measureChild(child, widthMeasureSpec, heightMeasureSpec)
290
+ private fun lines(available: Int): List<List<View>> {
291
+ val result = mutableListOf<MutableList<View>>()
292
+ var x = 0
293
+ for (child in flowChildren()) {
86
294
  val cw = child.measuredWidth
87
- val ch = child.measuredHeight
88
-
89
- if (x > 0 && x + cw > available) {
90
- maxRowWidth = maxOf(maxRowWidth, x)
295
+ if (result.isEmpty() || (x > 0 && x + cw > available)) {
296
+ result.add(mutableListOf())
91
297
  x = 0
92
- y += rowHeight + gapPx
93
- rowHeight = 0
94
298
  }
299
+ result.last().add(child)
95
300
  x += cw + gapPx
96
- rowHeight = maxOf(rowHeight, ch)
97
301
  }
98
- maxRowWidth = maxOf(maxRowWidth, (x - gapPx).coerceAtLeast(0))
99
- val desiredWidth = if (widthMode == MeasureSpec.EXACTLY) maxWidth else maxRowWidth + paddingLeft + paddingRight
100
- val desiredHeight = y + rowHeight + paddingBottom
101
- setMeasuredDimension(desiredWidth, resolveSize(desiredHeight, heightMeasureSpec))
302
+ return result
303
+ }
304
+
305
+ override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
306
+ val maxWidth = MeasureSpec.getSize(widthMeasureSpec)
307
+ val widthMode = MeasureSpec.getMode(widthMeasureSpec)
308
+ val available = if (widthMode == MeasureSpec.UNSPECIFIED) Int.MAX_VALUE else (maxWidth - paddingLeft - paddingRight).coerceAtLeast(0)
309
+ for (child in flowChildren()) measureChild(child, widthMeasureSpec, heightMeasureSpec)
310
+
311
+ val rows = lines(available)
312
+ val widest = rows.maxOfOrNull { row -> row.sumOf { it.measuredWidth } + gapPx * (row.size - 1) } ?: 0
313
+ val tall = rows.sumOf { row -> row.maxOf { it.measuredHeight } } + gapPx * (rows.size - 1).coerceAtLeast(0)
314
+ val desiredWidth = if (widthMode == MeasureSpec.EXACTLY) maxWidth else widest + paddingLeft + paddingRight
315
+ setMeasuredDimension(desiredWidth, resolveSize(tall + paddingTop + paddingBottom, heightMeasureSpec))
316
+ measureAbsolute(this, measuredWidth)
102
317
  }
103
318
 
104
319
  override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
105
320
  val available = (r - l - paddingLeft - paddingRight).coerceAtLeast(0)
106
- var x = paddingLeft
107
321
  var y = paddingTop
108
- var rowHeight = 0
109
-
110
- for (i in 0 until childCount) {
111
- val child = getChildAt(i)
112
- if (child.visibility == View.GONE) continue
113
- val cw = child.measuredWidth
114
- val ch = child.measuredHeight
115
- if (x > paddingLeft && x + cw - paddingLeft > available) {
116
- x = paddingLeft
117
- y += rowHeight + gapPx
118
- rowHeight = 0
322
+ for (row in lines(available)) {
323
+ val rowWidth = row.sumOf { it.measuredWidth } + gapPx * (row.size - 1)
324
+ val rowHeight = row.maxOf { it.measuredHeight }
325
+ val free = available - rowWidth
326
+ val (lead, extra) = spreadSpace(justify, free, row.size) ?: when (justify) {
327
+ "center" -> (free / 2f).coerceAtLeast(0f) to 0f
328
+ "end", "flex-end" -> free.toFloat().coerceAtLeast(0f) to 0f
329
+ else -> 0f to 0f
119
330
  }
120
- child.layout(x, y, x + cw, y + ch)
121
- x += cw + gapPx
122
- rowHeight = maxOf(rowHeight, ch)
331
+ // margin: "0 auto" on an item alone on its line centres it
332
+ val centredAlone = row.size == 1 && (row[0].layoutParams as? LinearLayout.LayoutParams)?.gravity == Gravity.CENTER_HORIZONTAL
333
+ var x = paddingLeft + if (centredAlone) (free / 2f).coerceAtLeast(0f) else lead
334
+ for (child in row) {
335
+ val cw = child.measuredWidth
336
+ val ch = child.measuredHeight
337
+ val dy = when (align) {
338
+ "end", "flex-end", "bottom", "baseline" -> rowHeight - ch
339
+ "center" -> (rowHeight - ch) / 2
340
+ else -> 0
341
+ }
342
+ child.layout(x.toInt(), y + dy, x.toInt() + cw, y + dy + ch)
343
+ x += cw + gapPx + extra
344
+ }
345
+ y += rowHeight + gapPx
123
346
  }
347
+ placeAbsolute(this, r - l, b - t)
124
348
  }
125
349
  }
126
350
 
@@ -133,7 +357,7 @@ class OrvynRenderer(
133
357
  private var accent = Color.parseColor("#1A73E8")
134
358
  private var defaultTextColor = Color.BLACK
135
359
  private var defaultBorderColor = Color.parseColor("#CBD5E1")
136
- private var dangerColor = Color.parseColor("#EF4444")
360
+ private var dangerColor = Color.parseColor("#B91C1C")
137
361
 
138
362
  fun dp(value: Float): Int = (value * density).toInt()
139
363
 
@@ -167,7 +391,10 @@ class OrvynRenderer(
167
391
  else -> null
168
392
  }
169
393
 
394
+ val marqueeSpec = if (type == "row" && !wrapped) style.optString("marquee", "").trim() else ""
170
395
  val innerExisting = when {
396
+ existing is MarqueeLayout -> if (marqueeSpec.isNotEmpty() && existing.childCount > 0) existing.getChildAt(0) else null
397
+ marqueeSpec.isNotEmpty() -> null
171
398
  scrollMode == "vertical" && existing is ScrollView && existing.childCount > 0 -> existing.getChildAt(0)
172
399
  scrollMode == "horizontal" && existing is HorizontalScrollView && existing.childCount > 0 -> existing.getChildAt(0)
173
400
  existing is ScrollView || existing is HorizontalScrollView -> null
@@ -200,12 +427,27 @@ class OrvynRenderer(
200
427
  if (label == "") View.IMPORTANT_FOR_ACCESSIBILITY_NO else View.IMPORTANT_FOR_ACCESSIBILITY_AUTO
201
428
 
202
429
  applyBox(view, type, style)
430
+ // overflow: "hidden" clips children; otherwise they may stick out, like the web
431
+ if (view is FlowLayout || view is WrapLayout) {
432
+ val hidden = style.optString("overflow") == "hidden"
433
+ (view as ViewGroup).clipChildren = hidden
434
+ view.clipToPadding = hidden
435
+ if (hidden) view.clipToOutline = true
436
+ }
437
+ info.abs = if (style.optString("position") == "absolute") JSONObject().apply {
438
+ for (side in listOf("top", "left", "right", "bottom")) style.opt(side)?.let { put(side, it) }
439
+ } else null
440
+ // zIndex lifts absolute decorations above the content they float over
441
+ view.translationZ = if (info.abs != null) dp(number(style.opt("zIndex")) ?: 0f).toFloat() else 0f
442
+ playAppear(view, info, style, events?.let { if (it.has("visible")) it.getInt("visible") else null })
203
443
  val params = layoutParams(type, style, parentType, availableWidthPx)
204
444
  // the screen, scroll areas and pop-ups are FrameLayouts and crash when
205
445
  // given another container's layout settings on the next update
446
+ val before = view.layoutParams
206
447
  view.layoutParams = if (parentType == "root" || scrollMode != null) {
207
448
  FrameLayout.LayoutParams(params as ViewGroup.MarginLayoutParams)
208
449
  } else params
450
+ animateSize(view, before, animationMs(style))
209
451
 
210
452
  val maxW = number(style.opt("maxWidth"))?.let { dp(it) }
211
453
  val resolvedWidth = when {
@@ -227,6 +469,22 @@ class OrvynRenderer(
227
469
  is LinearLayout -> updateChildren(view, type, node, style, childWidth)
228
470
  }
229
471
 
472
+ if (marqueeSpec.isNotEmpty()) {
473
+ val box = (existing as? MarqueeLayout) ?: MarqueeLayout(context)
474
+ val parts = marqueeSpec.split(" ")
475
+ box.toRight = parts[0] == "right"
476
+ box.seconds = parts.getOrNull(1)?.removeSuffix("s")?.toFloatOrNull() ?: 30f
477
+ box.layoutParams = view.layoutParams
478
+ view.layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
479
+ if (view.parent !== box) {
480
+ (view.parent as? ViewGroup)?.removeView(view)
481
+ box.removeAllViews()
482
+ box.addView(view)
483
+ }
484
+ box.tag = Info("marquee")
485
+ return box
486
+ }
487
+
230
488
  if (scrollMode == "horizontal") {
231
489
  val scroller = (existing as? HorizontalScrollView) ?: HorizontalScrollView(context)
232
490
  if (view.parent !== scroller) {
@@ -372,11 +630,11 @@ class OrvynRenderer(
372
630
  val info = Info(type, wrapped)
373
631
  val view: View = when {
374
632
  wrapped -> WrapLayout(context)
375
- type == "row" -> LinearLayout(context).apply {
633
+ type == "row" -> FlowLayout(context).apply {
376
634
  orientation = LinearLayout.HORIZONTAL
377
635
  gravity = Gravity.CENTER_VERTICAL
378
636
  }
379
- type == "col" || type == "box" -> LinearLayout(context).apply { orientation = LinearLayout.VERTICAL }
637
+ type == "col" || type == "box" -> FlowLayout(context).apply { orientation = LinearLayout.VERTICAL }
380
638
  type == "input" -> EditText(context).apply {
381
639
  setSingleLine(true)
382
640
  addTextChangedListener(object : TextWatcher {
@@ -438,6 +696,14 @@ class OrvynRenderer(
438
696
  }
439
697
  view.setTypeface(baseTypeface, styleBits)
440
698
 
699
+ // letterSpacing: points, or "-0.04em" (a share of the text size)
700
+ val tracking = style.opt("letterSpacing")
701
+ view.letterSpacing = when {
702
+ tracking is String && tracking.trim().endsWith("em") -> tracking.trim().removeSuffix("em").toFloatOrNull() ?: 0f
703
+ number(tracking) != null -> number(tracking)!! / size
704
+ else -> 0f
705
+ }
706
+
441
707
  number(style.opt("lineHeight"))?.let { lh ->
442
708
  if (lh <= 4f) view.setLineSpacing(0f, lh)
443
709
  else view.setLineSpacing((dp(lh) - view.lineHeight).coerceAtLeast(0).toFloat(), 1f)
@@ -445,6 +711,7 @@ class OrvynRenderer(
445
711
 
446
712
  val align = style.optString("textAlign", if (style.optBoolean("center", false)) "center" else "")
447
713
  view.gravity = when (align) {
714
+ "" -> if (isButton) Gravity.CENTER else Gravity.START
448
715
  "center" -> Gravity.CENTER_HORIZONTAL
449
716
  "right", "end" -> Gravity.END
450
717
  else -> Gravity.START
@@ -536,6 +803,44 @@ class OrvynRenderer(
536
803
  override fun sizeOf(key: String, value: Bitmap) = value.byteCount
537
804
  }
538
805
 
806
+ // asset:/ (from public/), data: (picked photos) or a web address
807
+ private fun loadBitmap(src: String): Bitmap? = try {
808
+ if (src.startsWith("asset:/")) {
809
+ context.assets.open("public/" + src.removePrefix("asset:/")).use { BitmapFactory.decodeStream(it) }
810
+ } else if (src.startsWith("data:")) {
811
+ val bytes = Base64.decode(src.substringAfter(","), Base64.DEFAULT)
812
+ BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
813
+ } else URL(src).openStream().use { BitmapFactory.decodeStream(it) }
814
+ } catch (_: Exception) {
815
+ null
816
+ }
817
+
818
+ // bg: "linear-gradient(...), url(photo.jpg)": the photo covers the box under its
819
+ // colour; a gradient on top becomes a dark tint (bgDim) so text stays readable
820
+ private fun applyBackgroundPhoto(view: View, style: JSONObject, radius: Float?) {
821
+ val info = view.tag as? Info ?: return
822
+ val src = style.optString("bgImage", "").ifEmpty { null }
823
+ info.bgImage = src
824
+ if (src == null) return
825
+ val dim = number(style.opt("bgDim")) ?: 0f
826
+ val corner = dp(radius ?: 0f).toFloat()
827
+ view.outlineProvider = object : ViewOutlineProvider() {
828
+ override fun getOutline(v: View, outline: Outline) = outline.setRoundRect(0, 0, v.width, v.height, corner)
829
+ }
830
+ view.clipToOutline = true
831
+ fun show(bitmap: Bitmap) {
832
+ val base = view.background
833
+ val photo = CoverDrawable(bitmap, dim)
834
+ view.background = if (base != null) LayerDrawable(arrayOf(base, photo)) else photo
835
+ }
836
+ images.get(src)?.let { show(it); return }
837
+ thread {
838
+ val bitmap = loadBitmap(src) ?: return@thread
839
+ images.put(src, bitmap)
840
+ main.post { if (info.bgImage == src) show(bitmap) }
841
+ }
842
+ }
843
+
539
844
  private fun updateImage(view: ImageView, info: Info, node: JSONObject) {
540
845
  val src = node.optString("src", "")
541
846
  if (src.isEmpty() || src == info.src) return
@@ -551,7 +856,10 @@ class OrvynRenderer(
551
856
  thread {
552
857
  try {
553
858
  // picked photos arrive as data: text, which URL can't open
554
- val bitmap = (if (src.startsWith("data:")) {
859
+ val bitmap = (if (src.startsWith("asset:/")) {
860
+ // an image from public/, shipped in the app's assets
861
+ view.context.assets.open("public/" + src.removePrefix("asset:/")).use { BitmapFactory.decodeStream(it) }
862
+ } else if (src.startsWith("data:")) {
555
863
  val bytes = Base64.decode(src.substringAfter(","), Base64.DEFAULT)
556
864
  BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
557
865
  } else URL(src).openStream().use { BitmapFactory.decodeStream(it) }) ?: return@thread
@@ -569,6 +877,8 @@ class OrvynRenderer(
569
877
 
570
878
  private fun updateWrapChildren(layout: WrapLayout, type: String, node: JSONObject, style: JSONObject, childWidth: Int) {
571
879
  layout.gapPx = dp(number(style.opt("gap")) ?: 0f)
880
+ layout.justify = style.optString("justify")
881
+ layout.align = style.optString("align")
572
882
  val children = node.optJSONArray("c")
573
883
  val count = children?.length() ?: 0
574
884
  for (i in 0 until count) {
@@ -613,20 +923,26 @@ class OrvynRenderer(
613
923
  }
614
924
  layout.gravity = hGravity or vGravity
615
925
  }
926
+ (layout as? FlowLayout)?.justify = if (centered) "" else justify
616
927
 
617
928
  val children = node.optJSONArray("c")
618
929
  val count = children?.length() ?: 0
619
930
  val gap = dp(number(style.opt("gap")) ?: 0f)
620
931
 
932
+ var inFlow = 0
621
933
  for (i in 0 until count) {
622
934
  val childNode = children!!.getJSONObject(i)
623
935
  val existing = if (i < layout.childCount) layout.getChildAt(i) else null
624
936
  val child = render(childNode, existing, type, childWidth)
625
937
 
626
- (child.layoutParams as? LinearLayout.LayoutParams)?.let { params ->
627
- if (i > 0) {
628
- if (type == "row") params.leftMargin += gap else params.topMargin += gap
938
+ // absolute children take no space, so no gap before or after them
939
+ if ((child.tag as? Info)?.abs == null) {
940
+ (child.layoutParams as? LinearLayout.LayoutParams)?.let { params ->
941
+ if (inFlow > 0) {
942
+ if (type == "row") params.leftMargin += gap else params.topMargin += gap
943
+ }
629
944
  }
945
+ inFlow++
630
946
  }
631
947
 
632
948
  if (child !== existing) {
@@ -648,8 +964,11 @@ class OrvynRenderer(
648
964
  val padding = number(style.opt("padding"))
649
965
  val px = number(style.opt("paddingX")) ?: padding ?: 0f
650
966
  val py = number(style.opt("paddingY")) ?: padding ?: 0f
651
- if (type != "input" || padding != null) {
652
- view.setPadding(dp(px), dp(py), dp(px), dp(py))
967
+ // paddingTop/Right/Bottom/Left come from shorthands like "20px 5% 0"
968
+ fun side(key: String, fallback: Float) = dp(number(style.opt(key)) ?: fallback)
969
+ val hasSides = listOf("paddingTop", "paddingRight", "paddingBottom", "paddingLeft").any { style.has(it) }
970
+ if (type != "input" || padding != null || hasSides) {
971
+ view.setPadding(side("paddingLeft", px), side("paddingTop", py), side("paddingRight", px), side("paddingBottom", py))
653
972
  }
654
973
 
655
974
  number(style.opt("minHeight"))?.let { view.minimumHeight = dp(it) }
@@ -658,9 +977,30 @@ class OrvynRenderer(
658
977
  val radius = number(style.opt("radius"))
659
978
  val border = style.opt("border") as? String
660
979
 
980
+ val info = view.tag as? Info
981
+ val animateMs = animationMs(style)
982
+ // with animate:, children that grow or shrink push the others smoothly
983
+ if (view is ViewGroup && view !is AdapterView<*>) {
984
+ view.layoutTransition = animateMs?.let { ms ->
985
+ (view.layoutTransition ?: LayoutTransition()).apply {
986
+ enableTransitionType(LayoutTransition.CHANGING)
987
+ setDuration(ms)
988
+ }
989
+ }
990
+ }
661
991
  if (bg != null || border != null || (radius != null && type != "input")) {
992
+ val previousBg = info?.bgColor
993
+ info?.bgColor = bg
662
994
  val normal = GradientDrawable().apply {
663
- setColor(bg ?: Color.TRANSPARENT)
995
+ setColor(if (animateMs != null && previousBg != null && bg != null && previousBg != bg) previousBg else bg ?: Color.TRANSPARENT)
996
+ if (animateMs != null && previousBg != null && bg != null && previousBg != bg) {
997
+ val drawable = this
998
+ ValueAnimator.ofArgb(previousBg, bg).apply {
999
+ duration = animateMs
1000
+ addUpdateListener { drawable.setColor(it.animatedValue as Int) }
1001
+ start()
1002
+ }
1003
+ }
664
1004
  cornerRadius = dp(radius ?: 0f).toFloat()
665
1005
  if (border != null) {
666
1006
  val parts = border.split(" ")
@@ -690,14 +1030,118 @@ class OrvynRenderer(
690
1030
  view.background = null
691
1031
  }
692
1032
 
1033
+ applyBackgroundPhoto(view, style, radius)
1034
+
693
1035
  view.elevation = dp((number(style.opt("shadow")) ?: 0f) * 2f).toFloat()
694
1036
  val disabled = style.optBoolean("disabled", false)
695
1037
  val loading = style.optBoolean("loading", false)
696
- view.alpha = when {
1038
+ val targetAlpha = when {
697
1039
  disabled -> 0.5f
698
1040
  loading -> 0.75f
699
1041
  else -> number(style.opt("opacity")) ?: 1f
700
1042
  }
1043
+ // an appear: animation that is still playing owns the alpha
1044
+ val appearing = style.optString("appear").isNotEmpty() &&
1045
+ (info?.appeared != true || android.os.SystemClock.uptimeMillis() < (info?.appearUntil ?: 0L))
1046
+ if (appearing) return
1047
+ if (animateMs != null) view.animate().alpha(targetAlpha).setDuration(animateMs).start()
1048
+ else view.alpha = targetAlpha
1049
+ }
1050
+
1051
+ // animate: "spring 0.4s" with a new width or height: grow to it instead of jumping
1052
+ private fun animateSize(view: View, before: ViewGroup.LayoutParams?, ms: Long?) {
1053
+ if (ms == null || before == null) return
1054
+ val after = view.layoutParams
1055
+ fun tween(from: Int, to: Int, set: (Int) -> Unit) {
1056
+ if (from > 0 && to > 0 && from != to) {
1057
+ set(from)
1058
+ ValueAnimator.ofInt(from, to).apply {
1059
+ duration = ms
1060
+ addUpdateListener {
1061
+ set(it.animatedValue as Int)
1062
+ view.requestLayout()
1063
+ }
1064
+ start()
1065
+ }
1066
+ }
1067
+ }
1068
+ tween(before.height, after.height) { after.height = it }
1069
+ tween(before.width, after.width) { after.width = it }
1070
+ }
1071
+
1072
+ // "ease 0.4s" -> 400
1073
+ private fun animationMs(style: JSONObject): Long? {
1074
+ val animate = style.optString("animate", "")
1075
+ if (animate.isEmpty()) return null
1076
+ val seconds = animate.split(" ").getOrNull(1)?.removeSuffix("s")?.toFloatOrNull() ?: 0.3f
1077
+ return (seconds * 1000).toLong()
1078
+ }
1079
+
1080
+ // runs `show` once, the first time any part of the view is on screen
1081
+ // (checked as the page scrolls and before each frame is drawn)
1082
+ private fun whenOnScreen(view: View, show: () -> Unit) {
1083
+ val rect = android.graphics.Rect()
1084
+ var done = false
1085
+ var scroll: android.view.ViewTreeObserver.OnScrollChangedListener? = null
1086
+ var draw: android.view.ViewTreeObserver.OnPreDrawListener? = null
1087
+ val check = {
1088
+ if (!done && view.isAttachedToWindow && view.isShown && view.getGlobalVisibleRect(rect)) {
1089
+ done = true
1090
+ view.viewTreeObserver.removeOnScrollChangedListener(scroll)
1091
+ view.viewTreeObserver.removeOnPreDrawListener(draw)
1092
+ main.post(show)
1093
+ }
1094
+ }
1095
+ scroll = android.view.ViewTreeObserver.OnScrollChangedListener { check() }
1096
+ draw = android.view.ViewTreeObserver.OnPreDrawListener { check(); true }
1097
+ view.viewTreeObserver.addOnScrollChangedListener(scroll)
1098
+ view.viewTreeObserver.addOnPreDrawListener(draw)
1099
+ }
1100
+
1101
+ // appear: "fade-up 0.6s 0.2s" plays once, when the view scrolls into sight;
1102
+ // onVisible: runs at the same moment (like the web)
1103
+ private fun playAppear(view: View, info: Info, style: JSONObject, visible: Int?) {
1104
+ if (info.appeared) return
1105
+ val spec = style.optString("appear", "")
1106
+ if (spec.isEmpty() && visible == null) return
1107
+ info.appeared = true
1108
+ val reduceMotion = android.provider.Settings.Global.getFloat(
1109
+ view.context.contentResolver, android.provider.Settings.Global.ANIMATOR_DURATION_SCALE, 1f) == 0f
1110
+ val animated = spec.isNotEmpty() && !reduceMotion
1111
+ val parts = spec.split(" ")
1112
+ val ms = ((parts.getOrNull(1)?.removeSuffix("s")?.toFloatOrNull() ?: 0.5f) * 1000).toLong()
1113
+ val delay = ((parts.getOrNull(2)?.removeSuffix("s")?.toFloatOrNull() ?: 0f) * 1000).toLong()
1114
+ val distance = dp(24f).toFloat()
1115
+ val targetAlpha = number(style.opt("opacity")) ?: 1f
1116
+ if (animated) {
1117
+ // hidden and waiting until it is scrolled to; re-renders leave it alone
1118
+ info.appearUntil = Long.MAX_VALUE
1119
+ view.alpha = 0f
1120
+ // animation pop { opacity: 0, y: 30, scale: 0.8, rotate: -6 }: start there
1121
+ val custom = style.optJSONObject("appearFrom")
1122
+ if (custom != null) {
1123
+ view.alpha = number(custom.opt("opacity")) ?: targetAlpha
1124
+ view.translationX = dp(number(custom.opt("x")) ?: 0f).toFloat()
1125
+ view.translationY = dp(number(custom.opt("y")) ?: 0f).toFloat()
1126
+ (number(custom.opt("scale")) ?: 1f).let { view.scaleX = it; view.scaleY = it }
1127
+ view.rotation = number(custom.opt("rotate")) ?: 0f
1128
+ } else when (parts[0]) {
1129
+ "fade-up" -> view.translationY = distance
1130
+ "fade-down" -> view.translationY = -distance
1131
+ "slide-left" -> view.translationX = distance
1132
+ "slide-right" -> view.translationX = -distance
1133
+ "scale" -> { view.scaleX = 0.9f; view.scaleY = 0.9f }
1134
+ }
1135
+ }
1136
+ whenOnScreen(view) {
1137
+ visible?.let { fire(it, null) }
1138
+ if (!animated) return@whenOnScreen
1139
+ info.appearUntil = android.os.SystemClock.uptimeMillis() + delay + ms
1140
+ view.animate().alpha(targetAlpha).translationX(0f).translationY(0f).scaleX(1f).scaleY(1f).rotation(0f)
1141
+ .setDuration(ms).setStartDelay(delay)
1142
+ .setInterpolator(android.view.animation.PathInterpolator(0.2f, 0.8f, 0.2f, 1f))
1143
+ .start()
1144
+ }
701
1145
  }
702
1146
 
703
1147
  private fun layoutParams(type: String, style: JSONObject, parentType: String, availableWidthPx: Int): ViewGroup.LayoutParams {
@@ -734,6 +1178,8 @@ class OrvynRenderer(
734
1178
 
735
1179
  val params = LinearLayout.LayoutParams(width, height, weight)
736
1180
  params.setMargins(margin, margin, margin, margin)
1181
+ // margin: "0 auto" centres the element in its column, like the web
1182
+ if (style.optBoolean("centerSelf", false)) params.gravity = Gravity.CENTER_HORIZONTAL
737
1183
  return params
738
1184
  }
739
1185