@c9up/orbit 0.1.0 → 0.1.2

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 (81) hide show
  1. package/Cargo.lock +9 -16
  2. package/Cargo.toml +4 -0
  3. package/README.md +7 -1
  4. package/android/src/main/java/com/c9up/orbit/OrbitEffects.kt +74 -1
  5. package/android/src/main/java/com/c9up/orbit/OrbitHost.kt +67 -4
  6. package/android/src/main/java/com/c9up/orbit/OrbitInput.kt +90 -8
  7. package/android/src/main/java/com/c9up/orbit/OrbitViews.kt +23 -4
  8. package/crates/orbit-host/Cargo.toml +1 -1
  9. package/crates/orbit-host/src/lib.rs +580 -115
  10. package/crates/orbit-host/src/motion.rs +6 -0
  11. package/crates/orbit-host/src/vector.rs +312 -56
  12. package/dist/color.d.ts.map +1 -1
  13. package/dist/color.js +3 -3
  14. package/dist/color.js.map +1 -1
  15. package/dist/commit.d.ts +38 -0
  16. package/dist/commit.d.ts.map +1 -1
  17. package/dist/commit.js +154 -13
  18. package/dist/commit.js.map +1 -1
  19. package/dist/errors.d.ts +60 -26
  20. package/dist/errors.d.ts.map +1 -1
  21. package/dist/errors.js +85 -11
  22. package/dist/errors.js.map +1 -1
  23. package/dist/host.d.ts.map +1 -1
  24. package/dist/host.js +4 -2
  25. package/dist/host.js.map +1 -1
  26. package/dist/index.d.ts +5 -2
  27. package/dist/index.d.ts.map +1 -1
  28. package/dist/index.js +6 -1
  29. package/dist/index.js.map +1 -1
  30. package/dist/motion.d.ts.map +1 -1
  31. package/dist/motion.js +7 -6
  32. package/dist/motion.js.map +1 -1
  33. package/dist/pages.d.ts.map +1 -1
  34. package/dist/pages.js +3 -3
  35. package/dist/pages.js.map +1 -1
  36. package/dist/react-native/index.d.ts +9 -1
  37. package/dist/react-native/index.d.ts.map +1 -1
  38. package/dist/react-native/index.js +55 -6
  39. package/dist/react-native/index.js.map +1 -1
  40. package/dist/report.d.ts +13 -0
  41. package/dist/report.d.ts.map +1 -0
  42. package/dist/report.js +22 -0
  43. package/dist/report.js.map +1 -0
  44. package/dist/server.d.ts +27 -3
  45. package/dist/server.d.ts.map +1 -1
  46. package/dist/server.js +15 -7
  47. package/dist/server.js.map +1 -1
  48. package/dist/stack.d.ts.map +1 -1
  49. package/dist/stack.js +3 -3
  50. package/dist/stack.js.map +1 -1
  51. package/dist/styles.d.ts.map +1 -1
  52. package/dist/styles.js +2 -2
  53. package/dist/styles.js.map +1 -1
  54. package/dist/template.d.ts.map +1 -1
  55. package/dist/template.js +56 -12
  56. package/dist/template.js.map +1 -1
  57. package/dist/textDecoder.d.ts +29 -0
  58. package/dist/textDecoder.d.ts.map +1 -0
  59. package/dist/textDecoder.js +149 -0
  60. package/dist/textDecoder.js.map +1 -0
  61. package/dist/url.d.ts.map +1 -1
  62. package/dist/url.js +4 -3
  63. package/dist/url.js.map +1 -1
  64. package/package.json +13 -7
  65. package/scripts/build-android.sh +0 -0
  66. package/src/color.ts +5 -10
  67. package/src/commit.ts +197 -18
  68. package/src/errors.ts +174 -44
  69. package/src/host.ts +4 -5
  70. package/src/index.ts +10 -1
  71. package/src/motion.ts +8 -6
  72. package/src/pages.ts +3 -6
  73. package/src/react-native/index.ts +70 -8
  74. package/src/react-native/react-native.d.ts +8 -0
  75. package/src/report.ts +25 -0
  76. package/src/server.ts +50 -14
  77. package/src/stack.ts +3 -9
  78. package/src/styles.ts +2 -5
  79. package/src/template.ts +65 -41
  80. package/src/textDecoder.ts +162 -0
  81. package/src/url.ts +10 -3
package/Cargo.lock CHANGED
@@ -2,18 +2,6 @@
2
2
  # It is not intended for manual editing.
3
3
  version = 4
4
4
 
5
- [[package]]
6
- name = "arrayvec"
7
- version = "0.7.8"
8
- source = "registry+https://github.com/rust-lang/crates.io-index"
9
- checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56"
10
-
11
- [[package]]
12
- name = "grid"
13
- version = "1.0.1"
14
- source = "registry+https://github.com/rust-lang/crates.io-index"
15
- checksum = "b40ca9252762c466af32d0b1002e91e4e1bc5398f77455e55474deb466355ff5"
16
-
17
5
  [[package]]
18
6
  name = "itoa"
19
7
  version = "1.0.19"
@@ -104,6 +92,12 @@ dependencies = [
104
92
  "version_check",
105
93
  ]
106
94
 
95
+ [[package]]
96
+ name = "smallvec"
97
+ version = "1.16.5"
98
+ source = "registry+https://github.com/rust-lang/crates.io-index"
99
+ checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46"
100
+
107
101
  [[package]]
108
102
  name = "syn"
109
103
  version = "3.0.10"
@@ -117,14 +111,13 @@ dependencies = [
117
111
 
118
112
  [[package]]
119
113
  name = "taffy"
120
- version = "0.9.2"
114
+ version = "0.15.1"
121
115
  source = "registry+https://github.com/rust-lang/crates.io-index"
122
- checksum = "41ba83ebaf2954d31d05d67340fd46cebe99da2b7133b0dd68d70c65473a437b"
116
+ checksum = "31f7bd2d97198df05186f93a3a3c306845f40e8b3c22bf9279cdd7e5cf5fea7d"
123
117
  dependencies = [
124
- "arrayvec",
125
- "grid",
126
118
  "serde",
127
119
  "slotmap",
120
+ "smallvec",
128
121
  ]
129
122
 
130
123
  [[package]]
package/Cargo.toml CHANGED
@@ -10,6 +10,10 @@ repository = "https://github.com/C9up/orbit"
10
10
  # The host is linked into the app's native library (a static library behind a
11
11
  # C ABI, called from the JSI module). No `panic = "abort"`: every exported
12
12
  # function wraps its body in `catch_unwind`, and abort would kill the app.
13
+ # `catch_unwind` stops panics only: a stack overflow is not one and ends the
14
+ # app whatever this says. The layout recurses once per level of the tree, so
15
+ # the host refuses a tree deeper than `MAX_DEPTH` (crates/orbit-host/src/lib.rs)
16
+ # before it lays it out.
13
17
  [profile.release]
14
18
  opt-level = 3
15
19
  lto = "fat"
package/README.md CHANGED
@@ -76,7 +76,10 @@ default, as in CSS), `rounded-*` clips it and a border is drawn over it.
76
76
  with the node, so a decrypted media stays out of storage. orbit reads the
77
77
  array when it commits: keep it unchanged until the image shows.
78
78
 
79
- Any other scheme (`data:`, `javascript:`…) throws `E_ORBIT_IMAGE_SOURCE`.
79
+ Any other scheme (`data:`, `javascript:`…), or none (`//host/a.png`), throws
80
+ `E_ORBIT_IMAGE_SOURCE`. That is for an address written in the template; one
81
+ that comes from data (`src=${user.avatar}`) shows nothing for that image and
82
+ goes to `mount`'s `onError`, so one bad row does not take its list down.
80
83
  Images are decoded at the size their box is laid out to, never above the
81
84
  source's own size nor 4096 px a side, and kept decoded in a memory cache
82
85
  bounded to an eighth of the app's heap; a download or a file over 64 MB is
@@ -218,6 +221,9 @@ session cookie, the `XSRF-TOKEN` echoed on mutations), `json` (comet's
218
221
  transport), `stream` (server-sent events over React Native's streaming XHR,
219
222
  for `configureRelay({ stream, fetch })`) and `authorize(token)` (a Bearer
220
223
  token on every request and stream). Pass it as `serverPages({ server })`.
224
+ With a `tokenStore` (`{ get, set }`, e.g. over `@c9up/orbit-secure-store`),
225
+ `authorize` keeps the token and `restore()` authorizes again at the next
226
+ launch.
221
227
 
222
228
  ## Long lists
223
229
 
@@ -93,11 +93,78 @@ object OrbitEffects {
93
93
  box.invalidate()
94
94
  }
95
95
 
96
- /** Something under a glass may have moved: scrolled, mounted or animated. */
96
+ /** Something under a glass may have moved: scrolled or mounted. */
97
97
  fun invalidateBackdrops() {
98
98
  for (glass in glasses.keys) glass.invalidate()
99
99
  }
100
100
 
101
+ /**
102
+ * An animation moves `view` (called before and after): only the glasses
103
+ * whose backdrop shows it redraw. Invalidating every glass on every tick
104
+ * made a looping animation anywhere redraw the whole screen each frame —
105
+ * the damage of a header and a bottom card is one rect, the screen —
106
+ * where it redrew only the animated view.
107
+ */
108
+ fun moving(view: View) {
109
+ for (glass in glasses.keys) {
110
+ if (!glass.isDirty && shows(glass, view)) glass.invalidate()
111
+ }
112
+ }
113
+
114
+ private val moved = RectF()
115
+ private val covered = RectF()
116
+
117
+ /** Whether `view` is drawn in `glass`'s backdrop (under it in its parent and over its box), or is the glass. */
118
+ private fun shows(glass: OrbitBox, view: View): Boolean {
119
+ if (view === glass) return true
120
+ val parent = glass.parent as? ViewGroup ?: return false
121
+ // The view's ancestor among the glass's siblings, drawn before the glass.
122
+ var sibling = view
123
+ while (sibling.parent !== parent) sibling = sibling.parent as? View ?: return false
124
+ if (sibling === glass || parent.indexOfChild(sibling) > parent.indexOfChild(glass)) return false
125
+ drawnIn(view, parent, moved)
126
+ coveredBy(glass, covered)
127
+ return RectF.intersects(moved, covered)
128
+ }
129
+
130
+ /** What `view` draws (see [reach]), in the coordinates of its ancestor `parent`. */
131
+ private fun drawnIn(view: View, parent: View, out: RectF) {
132
+ out.setEmpty()
133
+ reach(view, out)
134
+ var at = view
135
+ while (at !== parent) {
136
+ at.matrix.mapRect(out)
137
+ out.offset(at.left.toFloat(), at.top.toFloat())
138
+ val up = at.parent as View
139
+ out.offset(-up.scrollX.toFloat(), -up.scrollY.toFloat())
140
+ at = up
141
+ }
142
+ }
143
+
144
+ /** The box `glass` covers, in its parent's coordinates. */
145
+ private fun coveredBy(glass: View, out: RectF) {
146
+ out.set(0f, 0f, glass.width.toFloat(), glass.height.toFloat())
147
+ glass.matrix.mapRect(out)
148
+ out.offset(glass.left.toFloat(), glass.top.toFloat())
149
+ }
150
+
151
+ /** What `view` draws, in its own coordinates: its box and, where it does not clip, its children's. */
152
+ private fun reach(view: View, out: RectF) {
153
+ out.union(0f, 0f, view.width.toFloat(), view.height.toFloat())
154
+ val group = view as? ViewGroup ?: return
155
+ if (group is OrbitScroll || group.clipChildren) return
156
+ val child = RectF()
157
+ for (i in 0 until group.childCount) {
158
+ val kid = group.getChildAt(i)
159
+ if (kid.visibility == View.GONE) continue
160
+ child.setEmpty()
161
+ reach(kid, child)
162
+ kid.matrix.mapRect(child)
163
+ child.offset(kid.left.toFloat(), kid.top.toFloat())
164
+ out.union(child)
165
+ }
166
+ }
167
+
101
168
  private fun listen(view: View) {
102
169
  val observer = view.viewTreeObserver
103
170
  if (!observer.isAlive || listened.containsKey(observer)) return
@@ -257,10 +324,16 @@ object OrbitEffects {
257
324
  recording.scale(BACKDROP_SCALE, BACKDROP_SCALE)
258
325
  recording.translate(-(glass.left + glass.translationX), -(glass.top + glass.translationY))
259
326
  parent.background?.draw(recording)
327
+ coveredBy(glass, covered)
260
328
  for (i in 0 until parent.childCount) {
261
329
  val sibling = parent.getChildAt(i)
262
330
  if (sibling === glass) break
263
331
  if (sibling.visibility != View.VISIBLE) continue
332
+ // A sibling away from the glass is left out: recorded, its every
333
+ // change (an animation looping in a header far above) would make
334
+ // the blurred layer redraw, and the glass's whole box with it.
335
+ drawnIn(sibling, parent, moved)
336
+ if (!RectF.intersects(moved, covered)) continue
264
337
  recording.save()
265
338
  recording.translate(sibling.left + sibling.translationX, sibling.top + sibling.translationY)
266
339
  // A scrolling sibling shows only its viewport; its content is offset by its scroll.
@@ -1,8 +1,10 @@
1
1
  package com.c9up.orbit
2
2
 
3
3
  import android.app.Activity
4
+ import android.content.res.Resources
4
5
  import android.os.Handler
5
6
  import android.os.Looper
7
+ import android.util.DisplayMetrics
6
8
  import android.view.Choreographer
7
9
  import android.view.View
8
10
  import android.view.ViewGroup
@@ -63,7 +65,6 @@ object OrbitHost {
63
65
  root?.let { OrbitPress.apply(it, nativeGestureTick(frameTimeNanos)) }
64
66
  val out = nativeTick(frameTimeNanos, tags, ys)
65
67
  val buf = ByteBuffer.wrap(out, 1, out.size - 1).order(ByteOrder.LITTLE_ENDIAN)
66
- if (buf.remaining() >= 9) OrbitEffects.invalidateBackdrops()
67
68
  while (buf.remaining() >= 9) {
68
69
  val tag = buf.int
69
70
  val prop = buf.get().toInt()
@@ -75,15 +76,34 @@ object OrbitHost {
75
76
  early.getOrPut(tag) { HashMap() }[prop] = value
76
77
  continue
77
78
  }
79
+ // The host sends a bound value every tick, changed or not.
80
+ if (!changes(view, prop, value)) continue
81
+ // Where it was and where it goes: a glass over either redraws its backdrop.
82
+ OrbitEffects.moving(view)
78
83
  applyMotion(view, prop, value)
84
+ OrbitEffects.moving(view)
79
85
  }
80
86
  Choreographer.getInstance().postFrameCallback(this)
81
87
  }
82
88
  }
83
89
 
90
+ /** A recreated activity's fields and scroll views take these back at creation, by tag. */
91
+ private val keptInputs = HashMap<Int, OrbitInput.Kept>()
92
+ private val keptScrolls = HashMap<Int, Int>()
93
+ private val restoring = ArrayList<OrbitScroll>()
94
+
84
95
  /** Motion values that reached a view before its creation, by tag then prop. */
85
96
  private val early = HashMap<Int, HashMap<Int, Float>>()
86
97
 
98
+ private fun changes(view: View, prop: Int, value: Float) = when (prop) {
99
+ PROP_OPACITY -> view.alpha != value
100
+ PROP_TRANSLATE_X -> view.translationX != value * density
101
+ PROP_TRANSLATE_Y -> view.translationY != value * density
102
+ PROP_SCALE -> view.scaleX != value || view.scaleY != value
103
+ PROP_VISIBLE -> view.visibility != (if (value > 0.5f) View.VISIBLE else View.INVISIBLE)
104
+ else -> true
105
+ }
106
+
87
107
  private fun applyMotion(view: View, prop: Int, value: Float) {
88
108
  when (prop) {
89
109
  PROP_OPACITY -> view.alpha = value
@@ -102,14 +122,45 @@ object OrbitHost {
102
122
  var density = 1f
103
123
  private set
104
124
 
125
+ /**
126
+ * The display metrics texts are measured and drawn with: density and the
127
+ * user's font size. The application's, which Android updates in place when
128
+ * the configuration changes, before it recreates the activity: React Native
129
+ * starts the new activity's surface, and JS remounts and measures, before
130
+ * `attach` runs. The last activity's metrics measured the first texts of
131
+ * that remount at the old font size.
132
+ */
133
+ @Volatile
134
+ private var resources: Resources = Resources.getSystem()
135
+ val metrics: DisplayMetrics
136
+ get() = resources.displayMetrics
137
+
105
138
  /** `animate`: tick animations into views on vsync (view host); the self-drawn host ticks them while drawing. */
106
139
  fun attach(activity: Activity, animate: Boolean = true): View {
140
+ resources = activity.applicationContext.resources
107
141
  density = activity.resources.displayMetrics.density
108
142
  // The C++ side lives in libappmodules; make sure it is loaded before binding.
109
143
  com.facebook.soloader.SoLoader.loadLibrary("appmodules")
110
144
  nativeInit()
145
+ // A recreated activity (font size, language, display size…) attaches
146
+ // again: the last one's views die with it. JS asks the host to mount every
147
+ // view again (`Root.remount`); images keep their bytes, by tag.
148
+ // What the user typed and how far a list was scrolled live in those
149
+ // views, not in the tree: carried over to the views of the same tags.
150
+ keptInputs.clear()
151
+ keptScrolls.clear()
152
+ restoring.clear()
153
+ for ((tag, old) in views) {
154
+ when (old) {
155
+ is OrbitInput -> keptInputs[tag] = old.keep()
156
+ is OrbitScroll -> if (old.scrollY > 0) keptScrolls[tag] = old.scrollY
157
+ }
158
+ }
159
+ views.clear()
160
+ early.clear()
111
161
  val view = OrbitRoot(activity)
112
162
  root = view
163
+ Choreographer.getInstance().removeFrameCallback(frame)
113
164
  if (animate) Choreographer.getInstance().postFrameCallback(frame)
114
165
  return view
115
166
  }
@@ -144,7 +195,10 @@ object OrbitHost {
144
195
  /** Text size in dp, packed as two float bit patterns (width high, height low). */
145
196
  @JvmStatic
146
197
  fun measureText(spans: ByteArray, maxWidth: Float): Long {
147
- val text = OrbitText.decode(spans, density)
198
+ // One read: the measure and its dp agree even if the configuration changes now.
199
+ val metrics = metrics
200
+ val density = metrics.density
201
+ val text = OrbitText.decode(spans, metrics)
148
202
  val maxPx = if (maxWidth.isInfinite() || maxWidth > 1e6f) Int.MAX_VALUE / 2 else (maxWidth * density).toInt()
149
203
  val (w, h) = text.measure(maxPx)
150
204
  // The width in whole dp, rounded up: the layout rounds frames to whole dp,
@@ -160,6 +214,9 @@ object OrbitHost {
160
214
  val root = root ?: return
161
215
  val buf = ByteBuffer.wrap(ops).order(ByteOrder.LITTLE_ENDIAN)
162
216
  val context = root.context
217
+ // Values bound before their view existed, set once the batch has given
218
+ // the view its look: OP_LOOK sets the static opacity, which they override.
219
+ val bound = ArrayList<Pair<View, HashMap<Int, Float>>>()
163
220
  while (buf.hasRemaining()) {
164
221
  val code = buf.get().toInt()
165
222
  val tag = buf.int
@@ -175,7 +232,11 @@ object OrbitHost {
175
232
  }
176
233
  view.tag = tag
177
234
  views[tag] = view
178
- early.remove(tag)?.forEach { (prop, value) -> applyMotion(view, prop, value) }
235
+ keptInputs.remove(tag)?.let { (view as? OrbitInput)?.restore(it) }
236
+ keptScrolls.remove(tag)?.let { y ->
237
+ (view as? OrbitScroll)?.let { it.restoreY = y; restoring.add(it) }
238
+ }
239
+ early.remove(tag)?.let { bound.add(view to it) }
179
240
  }
180
241
  OP_DELETE -> {
181
242
  early.remove(tag)
@@ -201,7 +262,7 @@ object OrbitHost {
201
262
  OP_TEXT -> {
202
263
  val bytes = ByteArray(buf.int)
203
264
  buf.get(bytes)
204
- (views[tag] as? OrbitTextView)?.setText(OrbitText.decode(bytes, density))
265
+ (views[tag] as? OrbitTextView)?.setText(OrbitText.decode(bytes, metrics))
205
266
  }
206
267
  OP_INPUT -> {
207
268
  val bytes = ByteArray(buf.int)
@@ -230,6 +291,8 @@ object OrbitHost {
230
291
  else -> throw IllegalStateException("unknown op $code")
231
292
  }
232
293
  }
294
+ for ((view, values) in bound) values.forEach { (prop, value) -> applyMotion(view, prop, value) }
295
+ if (restoring.isNotEmpty()) restoring.removeAll { it.restore() }
233
296
  }
234
297
 
235
298
  /** Make `parent`'s children exactly `wanted`, moving only what is out of place. */
@@ -5,12 +5,14 @@ import android.graphics.Typeface
5
5
  import android.text.Editable
6
6
  import android.text.InputFilter
7
7
  import android.text.InputType
8
+ import android.text.Spanned
8
9
  import android.text.TextWatcher
9
10
  import android.util.TypedValue
10
11
  import android.view.Gravity
11
12
  import android.view.KeyEvent
12
13
  import android.view.ViewGroup
13
14
  import android.view.inputmethod.EditorInfo
15
+ import android.view.inputmethod.InputMethodManager
14
16
  import android.widget.EditText
15
17
  import org.json.JSONObject
16
18
  import kotlin.math.ceil
@@ -26,6 +28,7 @@ class OrbitInput(context: Context) : EditText(context), Framed {
26
28
  private var appliedVersion = -1
27
29
  private var muted = false
28
30
  private var lastJson = ""
31
+ private var keyboardRestartPosted = false
29
32
 
30
33
  init {
31
34
  // orbit-host sends a field's props before it attaches the field to its
@@ -62,9 +65,29 @@ class OrbitInput(context: Context) : EditText(context), Framed {
62
65
  OrbitHost.nativeDispatchText(tag, type, text?.toString() ?: "")
63
66
  }
64
67
 
68
+ /** What the user typed, the caret and the focus, carried to a recreated activity's field. */
69
+ class Kept(val text: String, val version: Int, val start: Int, val end: Int, val focused: Boolean)
70
+
71
+ fun keep() = Kept(text?.toString() ?: "", appliedVersion, selectionStart, selectionEnd, hasFocus())
72
+
73
+ /** Before its first payload: the payload's value is the one the old field had applied. */
74
+ fun restore(kept: Kept) {
75
+ appliedVersion = kept.version
76
+ muted = true
77
+ setValue(kept.text)
78
+ muted = false
79
+ // After the first payload, whose input type moves the caret, and once in
80
+ // the window: the keyboard comes back with the focus.
81
+ post {
82
+ val length = text?.length ?: 0
83
+ setSelection(kept.start.coerceIn(0, length), kept.end.coerceIn(0, length))
84
+ if (kept.focused) requestFocus()
85
+ }
86
+ }
87
+
65
88
  private fun isMultiline() = inputType and InputType.TYPE_TEXT_FLAG_MULTI_LINE != 0
66
89
 
67
- /** Apply orbit-host's INPUT payload (JSON); sizes in dp. */
90
+ /** Apply orbit-host's INPUT payload (JSON); sizes in dp, the font size in sp. */
68
91
  fun apply(json: String, density: Float) {
69
92
  if (json == lastJson) return
70
93
  lastJson = json
@@ -72,11 +95,11 @@ class OrbitInput(context: Context) : EditText(context), Framed {
72
95
  hint = p.optString("placeholder", "")
73
96
  if (p.has("placeholderColor")) setHintTextColor(p.getInt("placeholderColor"))
74
97
  if (p.has("color")) setTextColor(p.getInt("color"))
75
- setTextSize(TypedValue.COMPLEX_UNIT_DIP, p.optDouble("fontSize", 14.0).toFloat())
98
+ // sp: the user's font size, as the texts measured by OrbitText.decode.
99
+ setTextSize(TypedValue.COMPLEX_UNIT_SP, p.optDouble("fontSize", 14.0).toFloat())
76
100
  val weight = p.optString("fontWeight", "400")
77
101
  val bold = weight == "bold" || (weight.toIntOrNull() ?: 400) >= 600
78
102
  val italic = p.optString("fontStyle") == "italic"
79
- setTypeface(Typeface.DEFAULT, (if (bold) Typeface.BOLD else 0) or (if (italic) Typeface.ITALIC else 0))
80
103
 
81
104
  val multiline = p.optBoolean("multiline", false)
82
105
  var type = when (p.optString("keyboard", "text")) {
@@ -90,18 +113,23 @@ class OrbitInput(context: Context) : EditText(context), Framed {
90
113
  if (p.optBoolean("secure", false)) type = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
91
114
  if (multiline) type = type or InputType.TYPE_TEXT_FLAG_MULTI_LINE
92
115
  if (inputType != type) inputType = type
116
+ // The input type alone makes the field single- or multi-line. Not
117
+ // `isSingleLine`: `setSingleLine` swaps the transformation method for
118
+ // SingleLineTransformationMethod, which drops a password's masking and
119
+ // shows it in clear.
120
+ // After the type: a password type sets a monospace typeface, which HTML
121
+ // does not.
122
+ setTypeface(Typeface.DEFAULT, (if (bold) Typeface.BOLD else 0) or (if (italic) Typeface.ITALIC else 0))
93
123
  val rows = p.optInt("rows", 1).coerceAtLeast(1)
94
124
  if (multiline) {
95
125
  minLines = rows
96
126
  gravity = Gravity.TOP or Gravity.START
97
- isSingleLine = false
98
127
  } else {
99
- isSingleLine = true
100
128
  gravity = Gravity.CENTER_VERTICAL or Gravity.START
101
129
  imeOptions = EditorInfo.IME_ACTION_SEND
102
130
  }
103
131
  val max = p.optInt("maxLength", 0)
104
- filters = if (max > 0) arrayOf(InputFilter.LengthFilter(max)) else arrayOf()
132
+ filters = if (max > 0) arrayOf(MaxLength(max, ::restartKeyboard)) else arrayOf()
105
133
  val editable = p.optBoolean("editable", true)
106
134
  isEnabled = editable
107
135
  isFocusableInTouchMode = editable
@@ -118,13 +146,48 @@ class OrbitInput(context: Context) : EditText(context), Framed {
118
146
  appliedVersion = version
119
147
  if (next != text?.toString()) {
120
148
  muted = true
121
- setText(next)
122
- setSelection(next.length)
149
+ setValue(next)
123
150
  muted = false
124
151
  }
125
152
  }
126
153
  }
127
154
 
155
+ /**
156
+ * The value the app sets, kept whole as HTML keeps a value set by script:
157
+ * `maxlength` limits what the user types, so the length filter is left out
158
+ * while the value goes in. The caret goes to the end of the text the field
159
+ * holds — never past it, which Android refuses with an exception.
160
+ */
161
+ private fun setValue(value: String) {
162
+ val kept = filters
163
+ filters = arrayOf()
164
+ try {
165
+ setText(value)
166
+ } finally {
167
+ filters = kept
168
+ }
169
+ setSelection(text?.length ?: 0)
170
+ }
171
+
172
+ /**
173
+ * After `maxlength` refused part of an edit. A keyboard that composes the
174
+ * current word (SwiftKey, Gboard) keeps its own copy of it: it asked for
175
+ * "Bx", the field kept "B", and since the caret and the composing region did
176
+ * not move, Android tells it nothing. It would go on composing "Bxy", and its
177
+ * next deletions would only remove letters the field never had. Restarting
178
+ * the input makes it read the field's text again. Once the edit is over:
179
+ * the keyboard is in the middle of its batch.
180
+ */
181
+ private fun restartKeyboard() {
182
+ if (keyboardRestartPosted) return
183
+ keyboardRestartPosted = true
184
+ post {
185
+ keyboardRestartPosted = false
186
+ val keyboard = context.getSystemService(InputMethodManager::class.java)
187
+ if (keyboard != null && keyboard.isActive(this)) keyboard.restartInput(this)
188
+ }
189
+ }
190
+
128
191
  override fun setFrame(x: Float, y: Float, w: Float, h: Float) {
129
192
  frame[0] = x; frame[1] = y; frame[2] = w; frame[3] = h
130
193
  measure(
@@ -143,3 +206,22 @@ class OrbitInput(context: Context) : EditText(context), Framed {
143
206
  MeasureSpec.makeMeasureSpec(frame[3].toInt(), MeasureSpec.EXACTLY))
144
207
  }
145
208
  }
209
+
210
+ /**
211
+ * `maxlength` as HTML keeps it: an edit may not make the value longer than
212
+ * `max`, nor longer than it already is when the app set it longer. Android's
213
+ * LengthFilter caps at `max` alone: over it, it turns any replacement into
214
+ * "", and a keyboard that composes the current word (SwiftKey replaces "B"
215
+ * by "Bx") erased the "B". `refused` runs when part of an edit is left out.
216
+ */
217
+ internal class MaxLength(private val max: Int, private val refused: () -> Unit) : InputFilter {
218
+ override fun filter(source: CharSequence, start: Int, end: Int, dest: Spanned, dstart: Int, dend: Int): CharSequence? {
219
+ val room = maxOf(max, dest.length) - (dest.length - (dend - dstart))
220
+ if (room >= end - start) return null
221
+ refused()
222
+ if (room <= 0) return ""
223
+ var keep = start + room
224
+ if (Character.isHighSurrogate(source[keep - 1])) keep--
225
+ return source.subSequence(start, keep)
226
+ }
227
+ }
@@ -16,6 +16,8 @@ import android.text.style.ForegroundColorSpan
16
16
  import android.text.style.LineHeightSpan
17
17
  import android.text.style.StyleSpan
18
18
  import android.text.style.TypefaceSpan
19
+ import android.util.DisplayMetrics
20
+ import android.util.TypedValue
19
21
  import android.view.MotionEvent
20
22
  import android.view.View
21
23
  import android.view.ViewGroup
@@ -81,6 +83,18 @@ class OrbitScroll(context: Context) : ScrollView(context), Framed {
81
83
  }
82
84
  }
83
85
 
86
+ /** The last activity's offset in px, taken back once the content is placed; -1 for none. */
87
+ var restoreY = -1
88
+
89
+ /** Scroll back to [restoreY] once the content has its frame; true when done. */
90
+ fun restore(): Boolean {
91
+ val content = getChildAt(0) ?: return false
92
+ if (content.height <= 0) return false
93
+ scrollTo(0, restoreY)
94
+ restoreY = -1
95
+ return true
96
+ }
97
+
84
98
  override fun setFrame(x: Float, y: Float, w: Float, h: Float) {
85
99
  frame[0] = x; frame[1] = y; frame[2] = w; frame[3] = h
86
100
  applyFrame(frame)
@@ -286,7 +300,12 @@ class OrbitText(val text: CharSequence, private val align: Layout.Alignment, pri
286
300
  }
287
301
 
288
302
  companion object {
289
- fun decode(bytes: ByteArray, density: Float): OrbitText {
303
+ /**
304
+ * Sizes and line heights are CSS px, drawn as sp: they follow the user's
305
+ * font size (Android 14+ scales large text less), as React Native's Text.
306
+ */
307
+ fun decode(bytes: ByteArray, metrics: DisplayMetrics): OrbitText {
308
+ val sp = { value: Float -> TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, value, metrics) }
290
309
  val buf = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN)
291
310
  val align = when (buf.get().toInt()) {
292
311
  1 -> Layout.Alignment.ALIGN_CENTER
@@ -305,10 +324,10 @@ class OrbitText(val text: CharSequence, private val align: Layout.Alignment, pri
305
324
  out.append(String(raw, Charsets.UTF_8))
306
325
  val end = out.length
307
326
  if (index == 0) {
308
- paint.textSize = size * density
327
+ paint.textSize = sp(size)
309
328
  paint.color = color
310
329
  }
311
- out.setSpan(AbsoluteSizeSpan((size * density).toInt()), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
330
+ out.setSpan(AbsoluteSizeSpan(sp(size).toInt()), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
312
331
  out.setSpan(ForegroundColorSpan(color), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
313
332
  val italic = flags and 2 != 0
314
333
  val weight = flags shr 4
@@ -323,7 +342,7 @@ class OrbitText(val text: CharSequence, private val align: Layout.Alignment, pri
323
342
  }
324
343
  }
325
344
  if (lineHeight > 0f && out.isNotEmpty()) {
326
- out.setSpan(CssLineHeight(Math.round(lineHeight * density)), 0, out.length, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
345
+ out.setSpan(CssLineHeight(Math.round(sp(lineHeight))), 0, out.length, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
327
346
  }
328
347
  return OrbitText(out, align, paint)
329
348
  }
@@ -10,5 +10,5 @@ description = "Orbit's native host: the tree aurora commits, laid out with taffy
10
10
  crate-type = ["staticlib", "rlib"]
11
11
 
12
12
  [dependencies]
13
- taffy = "0.9"
13
+ taffy = "0.15"
14
14
  serde_json = "1"