orvyn-lang 0.1.1 → 0.3.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.
Files changed (74) hide show
  1. package/GUIDE.md +149 -0
  2. package/LANGUAGE.md +877 -24
  3. package/README.md +227 -131
  4. package/brand/orvyn-sunset-animated.svg +15 -0
  5. package/package.json +3 -1
  6. package/src/cli/orvyn.js +216 -489
  7. package/src/core/signal.js +104 -6
  8. package/src/devtools/runtime.js +25 -1
  9. package/src/lang/a11y.js +102 -0
  10. package/src/lang/auth.js +239 -0
  11. package/src/lang/bundle-native.js +10 -6
  12. package/src/lang/codegen.js +498 -64
  13. package/src/lang/device.js +41 -0
  14. package/src/lang/doctor.js +60 -0
  15. package/src/lang/env.js +27 -0
  16. package/src/lang/errors.js +513 -0
  17. package/src/lang/form.js +160 -0
  18. package/src/lang/index.js +2 -1
  19. package/src/lang/lexer.js +2 -0
  20. package/src/lang/list.js +44 -0
  21. package/src/lang/native/android/MainActivity.kt +43 -4
  22. package/src/lang/native/android/OrvynDevice.kt +163 -0
  23. package/src/lang/native/android/OrvynEngine.kt +154 -7
  24. package/src/lang/native/android/OrvynRenderer.kt +519 -40
  25. package/src/lang/native/android.js +74 -11
  26. package/src/lang/native/build.js +130 -60
  27. package/src/lang/native/config.js +108 -0
  28. package/src/lang/native/ios/OrvynApp.swift +6 -0
  29. package/src/lang/native/ios/OrvynEngine.swift +268 -4
  30. package/src/lang/native/ios/OrvynViews.swift +429 -31
  31. package/src/lang/native/ios.js +75 -2
  32. package/src/lang/native-runtime.js +423 -57
  33. package/src/lang/page.js +52 -0
  34. package/src/lang/parser.js +243 -15
  35. package/src/lang/prerender.js +300 -0
  36. package/src/lang/read-import.js +11 -0
  37. package/src/lang/router.js +266 -0
  38. package/src/lang/runtime-shared.js +820 -10
  39. package/src/lang/runtime.js +375 -52
  40. package/src/lang/select.js +13 -0
  41. package/src/lang/server-code.js +233 -0
  42. package/src/lang/server-export.js +78 -0
  43. package/src/lang/server-libs.js +53 -0
  44. package/src/lang/server.js +409 -0
  45. package/src/lang/test-runner.js +134 -0
  46. package/src/lang/types.js +312 -0
  47. package/src/lang/validation.js +55 -0
  48. package/src/lang/vite-plugin.js +82 -3
  49. package/src/lang/web-overlay.js +578 -0
  50. package/src/lang/widgets.js +94 -0
  51. package/src/lang/words.js +38 -0
  52. package/src/runtime/mount.js +116 -27
  53. package/src/runtime/patch.js +90 -11
  54. package/src/runtime/style.js +11 -1
  55. package/src/styling/fluid.js +91 -4
  56. package/src/styling/spec.js +306 -0
  57. package/src/core/context.js +0 -19
  58. package/src/core/lifecycle.js +0 -8
  59. package/src/core/resource.js +0 -27
  60. package/src/core/router.js +0 -20
  61. package/src/core/theme.js +0 -10
  62. package/src/devtools/devicePreview/PreviewFrame.js +0 -214
  63. package/src/devtools/devicePreview/index.js +0 -6
  64. package/src/devtools/overlay.js +0 -105
  65. package/src/runtime/createRenderer.js +0 -22
  66. package/src/runtime/h.js +0 -93
  67. package/src/runtime/hydrate.js +0 -59
  68. package/src/runtime/jsx-dev-runtime.js +0 -7
  69. package/src/runtime/jsx-runtime.js +0 -13
  70. package/src/runtime/partialHydration.js +0 -154
  71. package/src/runtime/platform.js +0 -135
  72. package/src/runtime/renderToStream.js +0 -127
  73. package/src/runtime/renderToString.js +0 -121
  74. package/src/runtime/resume.js +0 -62
@@ -5,36 +5,123 @@
5
5
 
6
6
  package dev.orvyn.runtime
7
7
 
8
+ import android.app.DatePickerDialog
9
+ import android.app.Dialog
8
10
  import android.content.Context
9
11
  import android.content.Intent
10
- import android.net.Uri
12
+ import android.graphics.Bitmap
11
13
  import android.graphics.BitmapFactory
12
14
  import android.graphics.Color
13
15
  import android.graphics.Typeface
14
16
  import android.graphics.drawable.GradientDrawable
17
+ import android.graphics.drawable.StateListDrawable
18
+ import android.net.Uri
19
+ import android.util.Base64
15
20
  import android.os.Handler
16
21
  import android.os.Looper
17
22
  import android.text.Editable
23
+ import android.text.InputType
18
24
  import android.text.TextWatcher
25
+ import android.util.LruCache
19
26
  import android.util.TypedValue
20
27
  import android.view.Gravity
21
28
  import android.view.View
22
29
  import android.view.ViewGroup
30
+ import android.webkit.WebView
31
+ import android.webkit.WebViewClient
32
+ import android.widget.AbsListView
33
+ import android.widget.AdapterView
34
+ import android.widget.ArrayAdapter
35
+ import android.widget.CheckBox
36
+ import android.widget.CompoundButton
37
+ import android.widget.Spinner
38
+ import android.widget.Switch
39
+ import android.widget.BaseAdapter
40
+ import android.widget.Button
23
41
  import android.widget.EditText
42
+ import android.widget.FrameLayout
43
+ import android.widget.ListView
44
+ import android.widget.HorizontalScrollView
24
45
  import android.widget.ImageView
25
46
  import android.widget.LinearLayout
47
+ import android.widget.ScrollView
26
48
  import android.widget.TextView
49
+ import org.json.JSONArray
27
50
  import org.json.JSONObject
28
51
  import java.net.URL
52
+ import java.util.Calendar
53
+ import java.util.Locale
29
54
  import kotlin.concurrent.thread
55
+ import kotlin.math.min
30
56
 
31
- private class Info(val type: String) {
57
+ private class Info(val type: String, val wrapped: Boolean = false) {
32
58
  var tap: Int? = null
33
59
  var change: Int? = null
34
60
  var value: String? = null
35
61
  var src: String? = null
36
62
  var href: String? = null
37
63
  var updating = false
64
+ var disabled = false
65
+ var loading = false
66
+ }
67
+
68
+ // Simple wrapping row container so `Row wrap: true` behaves like CSS flex-wrap.
69
+ private class WrapLayout(context: Context) : ViewGroup(context) {
70
+ var gapPx: Int = 0
71
+
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)
76
+
77
+ var x = 0
78
+ var y = paddingTop
79
+ var rowHeight = 0
80
+ var maxRowWidth = 0
81
+
82
+ for (i in 0 until childCount) {
83
+ val child = getChildAt(i)
84
+ if (child.visibility == View.GONE) continue
85
+ measureChild(child, widthMeasureSpec, heightMeasureSpec)
86
+ val cw = child.measuredWidth
87
+ val ch = child.measuredHeight
88
+
89
+ if (x > 0 && x + cw > available) {
90
+ maxRowWidth = maxOf(maxRowWidth, x)
91
+ x = 0
92
+ y += rowHeight + gapPx
93
+ rowHeight = 0
94
+ }
95
+ x += cw + gapPx
96
+ rowHeight = maxOf(rowHeight, ch)
97
+ }
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))
102
+ }
103
+
104
+ override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
105
+ val available = (r - l - paddingLeft - paddingRight).coerceAtLeast(0)
106
+ var x = paddingLeft
107
+ 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
119
+ }
120
+ child.layout(x, y, x + cw, y + ch)
121
+ x += cw + gapPx
122
+ rowHeight = maxOf(rowHeight, ch)
123
+ }
124
+ }
38
125
  }
39
126
 
40
127
  class OrvynRenderer(
@@ -43,44 +130,254 @@ class OrvynRenderer(
43
130
  ) {
44
131
  private val density = context.resources.displayMetrics.density
45
132
  private val main = Handler(Looper.getMainLooper())
46
- private val accent = Color.parseColor("#1A73E8")
133
+ private var accent = Color.parseColor("#1A73E8")
134
+ private var defaultTextColor = Color.BLACK
135
+ private var defaultBorderColor = Color.parseColor("#CBD5E1")
136
+ private var dangerColor = Color.parseColor("#EF4444")
137
+
138
+ fun dp(value: Float): Int = (value * density).toInt()
139
+
140
+ fun setTheme(theme: JSONObject?) {
141
+ if (theme == null) return
142
+ color(theme.opt("primary"))?.let { accent = it }
143
+ color(theme.opt("text"))?.let { defaultTextColor = it }
144
+ color(theme.opt("border"))?.let { defaultBorderColor = it }
145
+ color(theme.opt("danger"))?.let { dangerColor = it }
146
+ }
147
+
148
+ fun render(
149
+ node: JSONObject,
150
+ existing: View?,
151
+ parentType: String,
152
+ availableWidthPx: Int = context.resources.displayMetrics.widthPixels
153
+ ): View {
154
+ var type = node.optString("t", "box")
155
+ if (type == "toggle") type = "toggle-" + node.optString("inputType", "checkbox")
156
+ val style = node.optJSONObject("s") ?: JSONObject()
157
+ if (type == "modal") return renderModal(node, existing, availableWidthPx)
158
+ if (type == "input" && node.optString("inputType") == "date") return renderDate(node, existing)
159
+ if (type == "map") return renderMap(node, style, existing, parentType, availableWidthPx)
160
+ if (type == "list") return renderList(node, style, existing, parentType, availableWidthPx)
161
+ val wrapped = type == "row" && style.optBoolean("wrap", false)
162
+ val scrollVal = style.opt("scroll")
163
+ val scrollMode = when {
164
+ scrollVal == true || scrollVal == "vertical" -> if (type == "row") "horizontal" else "vertical"
165
+ scrollVal == "horizontal" -> "horizontal"
166
+ scrollVal == "both" -> if (type == "row") "horizontal" else "vertical"
167
+ else -> null
168
+ }
47
169
 
48
- private fun dp(value: Float): Int = (value * density).toInt()
170
+ val innerExisting = when {
171
+ scrollMode == "vertical" && existing is ScrollView && existing.childCount > 0 -> existing.getChildAt(0)
172
+ scrollMode == "horizontal" && existing is HorizontalScrollView && existing.childCount > 0 -> existing.getChildAt(0)
173
+ existing is ScrollView || existing is HorizontalScrollView -> null
174
+ else -> existing
175
+ }
49
176
 
50
- fun render(node: JSONObject, existing: View?, parentType: String): View {
51
- val type = node.optString("t", "box")
52
- val view = if (existing != null && (existing.tag as? Info)?.type == type) existing else create(type)
177
+ val existingInfo = innerExisting?.tag as? Info
178
+ val view = if (innerExisting != null && existingInfo?.type == type && existingInfo.wrapped == wrapped) {
179
+ innerExisting
180
+ } else {
181
+ create(type, wrapped)
182
+ }
53
183
  val info = view.tag as Info
54
- val style = node.optJSONObject("s") ?: JSONObject()
55
184
 
56
185
  val events = node.optJSONObject("e")
57
186
  info.tap = if (events?.has("tap") == true) events.getInt("tap") else null
58
187
  info.change = if (events?.has("change") == true) events.getInt("change") else null
59
188
  info.href = if (node.has("href")) node.optString("href") else null
189
+ info.disabled = style.optBoolean("disabled", false)
190
+ info.loading = style.optBoolean("loading", false)
191
+
192
+ if (style.has("rtl")) {
193
+ view.layoutDirection = if (style.optBoolean("rtl", false)) View.LAYOUT_DIRECTION_RTL else View.LAYOUT_DIRECTION_LTR
194
+ }
195
+
196
+ // label: is what TalkBack says; label: "" hides a decorative element
197
+ val label = if (node.has("a")) node.optString("a") else null
198
+ view.contentDescription = label?.ifEmpty { null }
199
+ view.importantForAccessibility =
200
+ if (label == "") View.IMPORTANT_FOR_ACCESSIBILITY_NO else View.IMPORTANT_FOR_ACCESSIBILITY_AUTO
60
201
 
61
202
  applyBox(view, type, style)
62
- view.layoutParams = layoutParams(type, style, parentType)
203
+ val params = layoutParams(type, style, parentType, availableWidthPx)
204
+ // the screen, scroll areas and pop-ups are FrameLayouts and crash when
205
+ // given another container's layout settings on the next update
206
+ view.layoutParams = if (parentType == "root" || scrollMode != null) {
207
+ FrameLayout.LayoutParams(params as ViewGroup.MarginLayoutParams)
208
+ } else params
209
+
210
+ val maxW = number(style.opt("maxWidth"))?.let { dp(it) }
211
+ val resolvedWidth = when {
212
+ params.width > 0 -> params.width
213
+ maxW != null -> min(availableWidthPx, maxW)
214
+ else -> availableWidthPx
215
+ }
216
+ val px = dp(number(style.opt("paddingX")) ?: number(style.opt("padding")) ?: 0f)
217
+ val childWidth = (resolvedWidth - px * 2).coerceAtLeast(0)
63
218
 
64
219
  when (view) {
220
+ // CheckBox and Switch are TextViews too, so they come first
221
+ is CompoundButton -> updateToggle(view, info, node, style)
222
+ is Spinner -> updateSelect(view, info, node)
65
223
  is EditText -> updateInput(view, info, node, style)
66
- is TextView -> updateText(view, type, node, style)
224
+ is TextView -> updateText(view, info, type, node, style)
67
225
  is ImageView -> updateImage(view, info, node)
68
- is LinearLayout -> updateChildren(view, type, node, style)
226
+ is WrapLayout -> updateWrapChildren(view, type, node, style, childWidth)
227
+ is LinearLayout -> updateChildren(view, type, node, style, childWidth)
228
+ }
229
+
230
+ if (scrollMode == "horizontal") {
231
+ val scroller = (existing as? HorizontalScrollView) ?: HorizontalScrollView(context)
232
+ if (view.parent !== scroller) {
233
+ scroller.removeAllViews()
234
+ scroller.addView(view)
235
+ }
236
+ return scroller
237
+ }
238
+ if (scrollMode == "vertical") {
239
+ val scroller = (existing as? ScrollView) ?: ScrollView(context)
240
+ if (view.parent !== scroller) {
241
+ scroller.removeAllViews()
242
+ scroller.addView(view)
243
+ }
244
+ return scroller
69
245
  }
70
246
  return view
71
247
  }
72
248
 
249
+ // ------------------------------------------------------- pop-ups and dates
250
+
251
+ private class Popup(var dialog: Dialog, var close: Int? = null, var showing: Boolean = true)
252
+
253
+ // an invisible view in the layout owns the dialog; removing it closes it
254
+ private fun renderModal(node: JSONObject, existing: View?, widthPx: Int): View {
255
+ val anchor = existing?.takeIf { it.tag is Popup } ?: View(context).also { view ->
256
+ val popup = Popup(Dialog(context))
257
+ view.tag = popup
258
+ popup.dialog.setOnCancelListener { popup.close?.let { fire(it, null) } }
259
+ view.addOnAttachStateChangeListener(object : View.OnAttachStateChangeListener {
260
+ override fun onViewAttachedToWindow(v: View) {
261
+ popup.dialog.show()
262
+ }
263
+
264
+ override fun onViewDetachedFromWindow(v: View) {
265
+ popup.dialog.dismiss()
266
+ }
267
+ })
268
+ }
269
+ val popup = anchor.tag as Popup
270
+ popup.close = node.optJSONObject("e")?.let { if (it.has("tap")) it.getInt("tap") else null }
271
+ val card = node.optJSONArray("c")?.optJSONObject(0) ?: JSONObject()
272
+ val holder = popup.dialog.findViewById<ViewGroup>(android.R.id.content)
273
+ val old = holder?.getChildAt(0)
274
+ val view = render(card, old, "root", (widthPx * 0.9f).toInt())
275
+ if (view !== old) popup.dialog.setContentView(view)
276
+ anchor.layoutParams = layoutParams("box", JSONObject(), "col", 0)
277
+ return anchor
278
+ }
279
+
280
+ // a button that opens the system date picker; the value is "2000-01-31"
281
+ private fun renderDate(node: JSONObject, existing: View?): View {
282
+ val button = (existing as? Button) ?: Button(context)
283
+ val value = node.optString("v", "")
284
+ val change = node.optJSONObject("e")?.let { if (it.has("change")) it.getInt("change") else null }
285
+ button.text = value.ifEmpty { node.optString("ph", "Choose a date") }
286
+ button.layoutParams = layoutParams("input", JSONObject(), "col", context.resources.displayMetrics.widthPixels)
287
+ button.setOnClickListener {
288
+ val parts = value.split("-").mapNotNull { it.toIntOrNull() }
289
+ val now = Calendar.getInstance()
290
+ DatePickerDialog(
291
+ context,
292
+ { _, year, month, day -> change?.let { fire(it, "%04d-%02d-%02d".format(Locale.US, year, month + 1, day)) } },
293
+ parts.getOrNull(0) ?: now.get(Calendar.YEAR),
294
+ parts.getOrNull(1)?.minus(1) ?: now.get(Calendar.MONTH),
295
+ parts.getOrNull(2) ?: now.get(Calendar.DAY_OF_MONTH)
296
+ ).show()
297
+ }
298
+ return button
299
+ }
300
+
301
+ // -------------------------------------------------------------------- maps
302
+
303
+ // the same OpenStreetMap page as the web, so no map key is needed
304
+ private fun renderMap(node: JSONObject, style: JSONObject, existing: View?, parentType: String, widthPx: Int): View {
305
+ val map = (existing as? WebView) ?: WebView(context).apply {
306
+ settings.javaScriptEnabled = true
307
+ webViewClient = WebViewClient()
308
+ }
309
+ val url = node.optString("src")
310
+ if (map.tag != url) {
311
+ map.tag = url
312
+ map.loadUrl(url)
313
+ }
314
+ map.contentDescription = node.optString("a")
315
+ val params = layoutParams("col", style, parentType, widthPx)
316
+ params.height = dp(number(style.opt("height")) ?: 240f)
317
+ map.layoutParams = if (parentType == "root") FrameLayout.LayoutParams(params as ViewGroup.MarginLayoutParams) else params
318
+ return map
319
+ }
320
+
321
+ // ------------------------------------------------------------------- lists
322
+
323
+ // ListView recycles row views, so only the rows on screen exist
324
+ private class Rows(val renderer: OrvynRenderer) : BaseAdapter() {
325
+ var rows: JSONArray = JSONArray()
326
+ var rowHeight = 48f
327
+ var widthPx = 0
328
+
329
+ override fun getCount() = rows.length()
330
+ override fun getItem(position: Int): Any = rows.getJSONObject(position)
331
+ override fun getItemId(position: Int) = position.toLong()
332
+
333
+ override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
334
+ val holder = (convertView as? LinearLayout) ?: LinearLayout(parent.context).apply {
335
+ orientation = LinearLayout.VERTICAL
336
+ }
337
+ holder.layoutParams = AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, renderer.dp(rowHeight))
338
+ val existing = if (holder.childCount > 0) holder.getChildAt(0) else null
339
+ val child = renderer.render(rows.getJSONObject(position), existing, "col", widthPx)
340
+ if (child !== existing) {
341
+ holder.removeAllViews()
342
+ holder.addView(child)
343
+ }
344
+ return holder
345
+ }
346
+ }
347
+
348
+ private fun renderList(node: JSONObject, style: JSONObject, existing: View?, parentType: String, widthPx: Int): View {
349
+ val list = (existing as? ListView) ?: ListView(context).apply {
350
+ divider = null
351
+ adapter = Rows(this@OrvynRenderer)
352
+ // the app's own scroll view must not steal the swipe
353
+ setOnTouchListener { view, _ ->
354
+ view.parent?.requestDisallowInterceptTouchEvent(true)
355
+ false
356
+ }
357
+ }
358
+ val rows = list.adapter as Rows
359
+ rows.rows = node.optJSONArray("c") ?: JSONArray()
360
+ rows.rowHeight = node.optDouble("rh", 48.0).toFloat()
361
+ rows.widthPx = widthPx
362
+ val params = layoutParams("col", style, parentType, widthPx)
363
+ params.height = dp(number(style.opt("height")) ?: 480f)
364
+ list.layoutParams = params
365
+ rows.notifyDataSetChanged()
366
+ return list
367
+ }
368
+
73
369
  // ------------------------------------------------------------------ create
74
370
 
75
- private fun create(type: String): View {
76
- val info = Info(type)
77
- val view: View = when (type) {
78
- "row" -> LinearLayout(context).apply {
371
+ private fun create(type: String, wrapped: Boolean): View {
372
+ val info = Info(type, wrapped)
373
+ val view: View = when {
374
+ wrapped -> WrapLayout(context)
375
+ type == "row" -> LinearLayout(context).apply {
79
376
  orientation = LinearLayout.HORIZONTAL
80
377
  gravity = Gravity.CENTER_VERTICAL
81
378
  }
82
- "col", "box" -> LinearLayout(context).apply { orientation = LinearLayout.VERTICAL }
83
- "input" -> EditText(context).apply {
379
+ type == "col" || type == "box" -> LinearLayout(context).apply { orientation = LinearLayout.VERTICAL }
380
+ type == "input" -> EditText(context).apply {
84
381
  setSingleLine(true)
85
382
  addTextChangedListener(object : TextWatcher {
86
383
  override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
@@ -93,7 +390,10 @@ class OrvynRenderer(
93
390
  }
94
391
  })
95
392
  }
96
- "image" -> ImageView(context).apply {
393
+ type == "toggle-checkbox" -> CheckBox(context)
394
+ type == "toggle-switch" -> Switch(context)
395
+ type == "select" -> Spinner(context)
396
+ type == "image" -> ImageView(context).apply {
97
397
  adjustViewBounds = true
98
398
  scaleType = ImageView.ScaleType.FIT_CENTER
99
399
  }
@@ -102,6 +402,7 @@ class OrvynRenderer(
102
402
  if (type == "button" || type == "link") {
103
403
  view.isClickable = true
104
404
  view.setOnClickListener {
405
+ if (info.disabled || info.loading) return@setOnClickListener
105
406
  val tap = info.tap
106
407
  val href = info.href
107
408
  if (tap != null) {
@@ -117,8 +418,9 @@ class OrvynRenderer(
117
418
 
118
419
  // ------------------------------------------------------------------ update
119
420
 
120
- private fun updateText(view: TextView, type: String, node: JSONObject, style: JSONObject) {
121
- val text = node.optString("x", "")
421
+ private fun updateText(view: TextView, info: Info, type: String, node: JSONObject, style: JSONObject) {
422
+ val raw = node.optString("x", "")
423
+ val text = if (type == "button" && info.loading) "… $raw" else raw
122
424
  if (view.text.toString() != text) view.text = text
123
425
 
124
426
  val isHeading = type == "heading"
@@ -126,14 +428,89 @@ class OrvynRenderer(
126
428
  val size = number(style.opt("size")) ?: if (isHeading) 28f else 17f
127
429
  view.setTextSize(TypedValue.COMPLEX_UNIT_SP, size)
128
430
 
129
- val weight = weight(style.opt("weight")) ?: if (isHeading) 700 else if (isButton) 600 else 400
130
- view.typeface = if (weight >= 600) Typeface.DEFAULT_BOLD else Typeface.DEFAULT
431
+ val weight = weight(style.opt("weight") ?: style.opt("fontWeight")) ?: if (isHeading) 700 else if (isButton) 600 else 400
432
+ val styleBits = if (weight >= 600) Typeface.BOLD else Typeface.NORMAL
433
+ val baseTypeface = when ((style.optString("font")).trim()) {
434
+ "mono" -> Typeface.MONOSPACE
435
+ "serif" -> Typeface.SERIF
436
+ "sans", "" -> Typeface.SANS_SERIF
437
+ else -> Typeface.create(style.optString("font"), styleBits)
438
+ }
439
+ view.setTypeface(baseTypeface, styleBits)
440
+
441
+ number(style.opt("lineHeight"))?.let { lh ->
442
+ if (lh <= 4f) view.setLineSpacing(0f, lh)
443
+ else view.setLineSpacing((dp(lh) - view.lineHeight).coerceAtLeast(0).toFloat(), 1f)
444
+ }
445
+
446
+ val align = style.optString("textAlign", if (style.optBoolean("center", false)) "center" else "")
447
+ view.gravity = when (align) {
448
+ "center" -> Gravity.CENTER_HORIZONTAL
449
+ "right", "end" -> Gravity.END
450
+ else -> Gravity.START
451
+ }
452
+
453
+ view.isEnabled = !(info.disabled || info.loading)
454
+ view.isClickable = isButton && !(info.disabled || info.loading)
455
+ view.setTextColor(color(style.opt("color")) ?: if (isButton) accent else defaultTextColor)
456
+ }
457
+
458
+ private fun updateToggle(view: CompoundButton, info: Info, node: JSONObject, style: JSONObject) {
459
+ view.setOnCheckedChangeListener(null)
460
+ view.text = node.optString("x", "")
461
+ view.setTextColor(color(style.opt("color")) ?: defaultTextColor)
462
+ view.isChecked = node.optString("v") == "true"
463
+ view.isEnabled = !info.disabled
464
+ view.setOnCheckedChangeListener { _, on -> info.change?.let { fire(it, on.toString()) } }
465
+ }
131
466
 
132
- view.setTextColor(color(style.opt("color")) ?: if (isButton) accent else Color.BLACK)
467
+ private fun updateSelect(view: Spinner, info: Info, node: JSONObject) {
468
+ val options = node.optJSONArray("o") ?: JSONArray()
469
+ val labels = mutableListOf(node.optString("ph", ""))
470
+ for (i in 0 until options.length()) labels.add(options.getString(i))
471
+ val signature = labels.joinToString("\u0000")
472
+ if (info.src != signature) {
473
+ info.src = signature
474
+ view.adapter = ArrayAdapter(context, android.R.layout.simple_spinner_dropdown_item, labels)
475
+ }
476
+ val selected = labels.indexOf(node.optString("v")).coerceAtLeast(0)
477
+ info.value = if (selected == 0) "" else labels[selected]
478
+ if (view.selectedItemPosition != selected) view.setSelection(selected, false)
479
+ view.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
480
+ override fun onItemSelected(parent: AdapterView<*>?, item: View?, position: Int, id: Long) {
481
+ val value = if (position == 0) "" else labels[position]
482
+ // also called when the app sets the choice: only report real changes
483
+ if (value == info.value) return
484
+ info.value = value
485
+ info.change?.let { fire(it, value) }
486
+ }
487
+
488
+ override fun onNothingSelected(parent: AdapterView<*>?) {}
489
+ }
133
490
  }
134
491
 
135
492
  private fun updateInput(view: EditText, info: Info, node: JSONObject, style: JSONObject) {
136
493
  view.hint = node.optString("ph", "")
494
+ view.isEnabled = !info.disabled
495
+ view.setTextColor(color(style.opt("color")) ?: defaultTextColor)
496
+ val kind = node.optString("inputType")
497
+ val inputType = when (kind) {
498
+ "email" -> InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS
499
+ // never show what is typed
500
+ "password" -> InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
501
+ "number" -> InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_FLAG_DECIMAL or InputType.TYPE_NUMBER_FLAG_SIGNED
502
+ "tel" -> InputType.TYPE_CLASS_PHONE
503
+ "multiline" -> InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_MULTI_LINE or InputType.TYPE_TEXT_FLAG_CAP_SENTENCES
504
+ else -> InputType.TYPE_CLASS_TEXT
505
+ }
506
+ if (view.inputType != inputType) {
507
+ view.inputType = inputType
508
+ if (kind == "multiline") {
509
+ view.isSingleLine = false
510
+ view.minLines = 4
511
+ view.gravity = Gravity.TOP or Gravity.START
512
+ }
513
+ }
137
514
  val value = if (node.has("v")) node.optString("v", "") else null
138
515
  if (value != null && value != view.text.toString()) {
139
516
  info.updating = true
@@ -144,34 +521,97 @@ class OrvynRenderer(
144
521
  if (!style.has("padding")) {
145
522
  view.setPadding(dp(10f), dp(10f), dp(10f), dp(10f))
146
523
  }
147
- if (!style.has("border") && !style.has("bg")) {
524
+ val hasError = style.has("error") && style.opt("error") != false
525
+ if (hasError || (!style.has("border") && !style.has("bg"))) {
148
526
  view.background = GradientDrawable().apply {
527
+ color(style.opt("bg"))?.let { setColor(it) }
149
528
  cornerRadius = dp(number(style.opt("radius")) ?: 8f).toFloat()
150
- setStroke(dp(1f), Color.parseColor("#CBD5E1"))
529
+ setStroke(dp(if (hasError) 2f else 1f), if (hasError) dangerColor else defaultBorderColor)
151
530
  }
152
531
  }
153
532
  }
154
533
 
534
+ // an eighth of the app's memory for pictures already loaded
535
+ private val images = object : LruCache<String, Bitmap>((Runtime.getRuntime().maxMemory() / 8).toInt()) {
536
+ override fun sizeOf(key: String, value: Bitmap) = value.byteCount
537
+ }
538
+
155
539
  private fun updateImage(view: ImageView, info: Info, node: JSONObject) {
156
540
  val src = node.optString("src", "")
157
541
  if (src.isEmpty() || src == info.src) return
158
542
  info.src = src
543
+ images.get(src)?.let {
544
+ view.background = null
545
+ view.setImageBitmap(it)
546
+ return
547
+ }
548
+ // a quiet placeholder while it loads, and no picture left over from another row
549
+ view.setImageDrawable(null)
550
+ view.setBackgroundColor(Color.parseColor("#14808080"))
159
551
  thread {
160
552
  try {
161
- val bitmap = URL(src).openStream().use { BitmapFactory.decodeStream(it) }
162
- main.post { if (info.src == src) view.setImageBitmap(bitmap) }
553
+ // picked photos arrive as data: text, which URL can't open
554
+ val bitmap = (if (src.startsWith("data:")) {
555
+ val bytes = Base64.decode(src.substringAfter(","), Base64.DEFAULT)
556
+ BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
557
+ } else URL(src).openStream().use { BitmapFactory.decodeStream(it) }) ?: return@thread
558
+ images.put(src, bitmap)
559
+ main.post {
560
+ if (info.src == src) {
561
+ view.background = null
562
+ view.setImageBitmap(bitmap)
563
+ }
564
+ }
163
565
  } catch (_: Exception) {
164
566
  }
165
567
  }
166
568
  }
167
569
 
168
- private fun updateChildren(layout: LinearLayout, type: String, node: JSONObject, style: JSONObject) {
169
- if (type != "row") {
170
- layout.gravity = when (style.optString("align")) {
570
+ private fun updateWrapChildren(layout: WrapLayout, type: String, node: JSONObject, style: JSONObject, childWidth: Int) {
571
+ layout.gapPx = dp(number(style.opt("gap")) ?: 0f)
572
+ val children = node.optJSONArray("c")
573
+ val count = children?.length() ?: 0
574
+ for (i in 0 until count) {
575
+ val childNode = children!!.getJSONObject(i)
576
+ val existing = if (i < layout.childCount) layout.getChildAt(i) else null
577
+ val child = render(childNode, existing, type, childWidth)
578
+ if (child !== existing) {
579
+ if (existing != null) layout.removeViewAt(i)
580
+ layout.addView(child, i)
581
+ }
582
+ }
583
+ while (layout.childCount > count) {
584
+ layout.removeViewAt(layout.childCount - 1)
585
+ }
586
+ }
587
+
588
+ private fun updateChildren(layout: LinearLayout, type: String, node: JSONObject, style: JSONObject, childWidth: Int) {
589
+ val centered = style.optBoolean("center", false)
590
+ val justify = style.optString("justify")
591
+ if (type == "row") {
592
+ val vGravity = when (style.optString("align")) {
593
+ "start", "flex-start", "top" -> Gravity.TOP
594
+ "end", "flex-end", "bottom" -> Gravity.BOTTOM
595
+ else -> Gravity.CENTER_VERTICAL
596
+ }
597
+ val hGravity = when {
598
+ centered || justify == "center" -> Gravity.CENTER_HORIZONTAL
599
+ justify == "end" || justify == "flex-end" -> Gravity.END
600
+ else -> Gravity.START
601
+ }
602
+ layout.gravity = vGravity or hGravity
603
+ } else {
604
+ val hGravity = when (if (centered) "center" else style.optString("align")) {
171
605
  "center" -> Gravity.CENTER_HORIZONTAL
172
606
  "end", "flex-end", "right" -> Gravity.END
173
607
  else -> Gravity.START
174
608
  }
609
+ val vGravity = when {
610
+ centered || justify == "center" -> Gravity.CENTER_VERTICAL
611
+ justify == "end" || justify == "flex-end" -> Gravity.BOTTOM
612
+ else -> Gravity.TOP
613
+ }
614
+ layout.gravity = hGravity or vGravity
175
615
  }
176
616
 
177
617
  val children = node.optJSONArray("c")
@@ -181,7 +621,7 @@ class OrvynRenderer(
181
621
  for (i in 0 until count) {
182
622
  val childNode = children!!.getJSONObject(i)
183
623
  val existing = if (i < layout.childCount) layout.getChildAt(i) else null
184
- val child = render(childNode, existing, type)
624
+ val child = render(childNode, existing, type, childWidth)
185
625
 
186
626
  (child.layoutParams as? LinearLayout.LayoutParams)?.let { params ->
187
627
  if (i > 0) {
@@ -212,12 +652,14 @@ class OrvynRenderer(
212
652
  view.setPadding(dp(px), dp(py), dp(px), dp(py))
213
653
  }
214
654
 
655
+ number(style.opt("minHeight"))?.let { view.minimumHeight = dp(it) }
656
+
215
657
  val bg = color(style.opt("bg"))
216
658
  val radius = number(style.opt("radius"))
217
659
  val border = style.opt("border") as? String
218
660
 
219
661
  if (bg != null || border != null || (radius != null && type != "input")) {
220
- view.background = GradientDrawable().apply {
662
+ val normal = GradientDrawable().apply {
221
663
  setColor(bg ?: Color.TRANSPARENT)
222
664
  cornerRadius = dp(radius ?: 0f).toFloat()
223
665
  if (border != null) {
@@ -227,33 +669,70 @@ class OrvynRenderer(
227
669
  setStroke(dp(width), borderColor)
228
670
  }
229
671
  }
672
+ if (type == "button") {
673
+ val pressed = style.optJSONObject("pressed") ?: style.optJSONObject("active")
674
+ val pressedBg = color(pressed?.opt("bg")) ?: bg
675
+ val states = StateListDrawable()
676
+ if (pressedBg != null) {
677
+ val down = GradientDrawable().apply {
678
+ setColor(pressedBg)
679
+ cornerRadius = dp(radius ?: 0f).toFloat()
680
+ }
681
+ states.addState(intArrayOf(android.R.attr.state_pressed), down)
682
+ }
683
+ states.addState(intArrayOf(), normal)
684
+ view.background = states
685
+ } else {
686
+ view.background = normal
687
+ }
230
688
  view.clipToOutline = radius != null
231
689
  } else if (type != "input") {
232
690
  view.background = null
233
691
  }
234
692
 
235
693
  view.elevation = dp((number(style.opt("shadow")) ?: 0f) * 2f).toFloat()
236
- view.alpha = number(style.opt("opacity")) ?: 1f
694
+ val disabled = style.optBoolean("disabled", false)
695
+ val loading = style.optBoolean("loading", false)
696
+ view.alpha = when {
697
+ disabled -> 0.5f
698
+ loading -> 0.75f
699
+ else -> number(style.opt("opacity")) ?: 1f
700
+ }
237
701
  }
238
702
 
239
- private fun layoutParams(type: String, style: JSONObject, parentType: String): ViewGroup.LayoutParams {
703
+ private fun layoutParams(type: String, style: JSONObject, parentType: String, availableWidthPx: Int): ViewGroup.LayoutParams {
240
704
  val widthValue = style.opt("width")
241
705
  val isContainer = type == "col" || type == "row" || type == "box" || type == "input"
706
+ val margin = dp(number(style.opt("margin")) ?: 0f)
242
707
 
243
708
  var width = when {
244
- widthValue is String && widthValue.endsWith("%") -> ViewGroup.LayoutParams.MATCH_PARENT
709
+ widthValue is String && widthValue.trim() == "100%" -> ViewGroup.LayoutParams.MATCH_PARENT
710
+ widthValue is String && widthValue.trim().endsWith("%") -> {
711
+ val pct = widthValue.trim().removeSuffix("%").toFloatOrNull()
712
+ if (pct != null && availableWidthPx > 0) ((availableWidthPx - margin * 2) * (pct / 100f)).toInt().coerceAtLeast(0)
713
+ else ViewGroup.LayoutParams.MATCH_PARENT
714
+ }
245
715
  number(widthValue) != null -> dp(number(widthValue)!!)
246
716
  parentType != "row" && isContainer -> ViewGroup.LayoutParams.MATCH_PARENT
247
717
  else -> ViewGroup.LayoutParams.WRAP_CONTENT
248
718
  }
719
+ number(style.opt("maxWidth"))?.let { maxW ->
720
+ val maxPx = dp(maxW)
721
+ if (width == ViewGroup.LayoutParams.MATCH_PARENT) width = min(availableWidthPx, maxPx)
722
+ else if (width > maxPx) width = maxPx
723
+ }
249
724
  val height = number(style.opt("height"))?.let { dp(it) } ?: ViewGroup.LayoutParams.WRAP_CONTENT
250
725
 
251
- // inputs in a row take the free space, like the web
252
- val weight = if (parentType == "row" && type == "input" && widthValue == null) 1f else 0f
253
- if (weight > 0f) width = 0
726
+ val growVal = style.opt("grow")
727
+ var weight = when {
728
+ growVal == true -> 1f
729
+ number(growVal) != null -> number(growVal)!!
730
+ parentType == "row" && type == "input" && widthValue == null -> 1f
731
+ else -> 0f
732
+ }
733
+ if (weight > 0f && parentType == "row" && widthValue == null) width = 0
254
734
 
255
735
  val params = LinearLayout.LayoutParams(width, height, weight)
256
- val margin = dp(number(style.opt("margin")) ?: 0f)
257
736
  params.setMargins(margin, margin, margin, margin)
258
737
  return params
259
738
  }
@@ -261,7 +740,7 @@ class OrvynRenderer(
261
740
  private fun number(value: Any?): Float? = when (value) {
262
741
  is Boolean -> null
263
742
  is Number -> value.toFloat()
264
- is String -> value.replace("px", "").trim().toFloatOrNull()
743
+ is String -> if (value.contains("%")) null else value.replace("px", "").trim().toFloatOrNull()
265
744
  else -> null
266
745
  }
267
746