@nativue/core 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # @nativue/core
2
2
 
3
- Vue rendering real native views on iOS and Android: UIKit on iOS, Android views with Material 3 on
4
- Android, laid out with Yoga.
3
+ Vue for real native apps on iOS and Android: Vue components rendered as the platform's own views,
4
+ UIKit on iOS and Android views with Material 3 on Android, laid out with flexbox.
5
5
 
6
6
  Start a new app with:
7
7
 
@@ -9,8 +9,11 @@ Start a new app with:
9
9
  npm create nativue@latest my-app
10
10
  ```
11
11
 
12
- This package holds the runtime (renderer, router, Animated, AsyncStorage, fetch), the native side
13
- for iOS (a Swift package) and Android (a Gradle library), and the `nativue` CLI:
12
+ This package holds:
13
+
14
+ - the runtime: the renderer, native components, the router, `Animated`, `AsyncStorage`, `fetch`
15
+ - the native side: a Swift package for iOS and a Gradle library for Android
16
+ - the `nativue` CLI:
14
17
 
15
18
  ```sh
16
19
  nativue run ios # or android: builds, opens the app on a simulator or emulator, then dev
@@ -18,4 +21,12 @@ nativue dev # rebuilds on save and reloads the running app
18
21
  nativue build # bundles the app into ios/ and android/ (--production for releases)
19
22
  ```
20
23
 
21
- Docs and source: https://github.com/nativue/nativue
24
+ ## Documentation
25
+
26
+ - [Getting started](https://github.com/nativue/nativue/blob/main/docs/getting-started.md)
27
+ - [Components](https://github.com/nativue/nativue/blob/main/docs/components/README.md)
28
+ - [Styling](https://github.com/nativue/nativue/blob/main/docs/styling.md)
29
+ - [Navigation](https://github.com/nativue/nativue/blob/main/docs/navigation.md)
30
+ - [Animations and gestures](https://github.com/nativue/nativue/blob/main/docs/animations.md)
31
+ - [APIs](https://github.com/nativue/nativue/blob/main/docs/apis.md)
32
+ - [Packages](https://github.com/nativue/nativue/blob/main/docs/packages.md)
@@ -10,7 +10,7 @@ plugins {
10
10
  * This computer's address on the local network (Wi-Fi or Ethernet first), for a physical device to
11
11
  * reach the dev server.
12
12
  */
13
- // ponytail: fixed at build time, like the iOS app's host; rebuild after switching networks.
13
+ // Limitation: Fixed at build time, like the iOS app's host; rebuild after switching networks.
14
14
  fun localNetworkAddress(): String? = NetworkInterface.getNetworkInterfaces().toList()
15
15
  .filter { it.isUp && !it.isLoopback && !it.isVirtual }
16
16
  .sortedBy { if (it.name.startsWith("en") || it.name.startsWith("eth") || it.name.startsWith("wlan")) 0 else 1 }
@@ -24,7 +24,7 @@ android {
24
24
  ndkVersion = "27.1.12297006"
25
25
 
26
26
  defaultConfig {
27
- // ponytail: 30 for the WindowInsets.Type API (safe area, keyboard); lower it with the compat insets if needed.
27
+ // Limitation: 30 for the WindowInsets.Type API (safe area, keyboard); lower it with the compat insets if needed.
28
28
  minSdk = 30
29
29
  consumerProguardFiles("consumer-rules.pro")
30
30
 
@@ -16,6 +16,7 @@ import android.util.Log
16
16
  import android.util.TypedValue
17
17
  import android.view.Gravity
18
18
  import android.view.View
19
+ import android.view.ViewGroup
19
20
  import android.view.WindowInsets
20
21
  import android.view.WindowInsetsAnimation
21
22
  import android.view.WindowInsetsController
@@ -23,11 +24,12 @@ import android.graphics.Insets
23
24
  import android.view.inputmethod.EditorInfo
24
25
  import android.view.inputmethod.InputMethodManager
25
26
  import android.widget.EditText
27
+ import android.widget.ImageView
26
28
  import android.widget.ProgressBar
27
- import android.widget.Switch
28
29
  import android.widget.TextView
29
30
  import com.facebook.yoga.YogaDisplay
30
31
  import com.facebook.yoga.YogaEdge
32
+ import com.facebook.yoga.YogaFlexDirection
31
33
  import com.facebook.yoga.YogaPositionType
32
34
  import java.net.HttpURLConnection
33
35
  import java.net.URL
@@ -43,6 +45,11 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
43
45
  /** The dev server address that answered last (set by listenForReload, read when symbolicating). */
44
46
  @Volatile
45
47
  private var devServerURL = ""
48
+ /** Ends listenForReload's loop: its thread would otherwise keep a destroyed activity alive. */
49
+ @Volatile
50
+ private var isDestroyed = false
51
+ @Volatile
52
+ private var reloadConnection: HttpURLConnection? = null
46
53
 
47
54
  private val javaScriptHandler = startJavaScriptThread()
48
55
  private val isDebuggable = activity.applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE != 0
@@ -57,7 +64,6 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
57
64
  private var nextLayoutAnimation: Map<*, *>? = null
58
65
 
59
66
  // Only touched on the main thread.
60
- // ponytail: children of a removed node stay in the map; clean up recursively if memory leaks.
61
67
  private val nodesById = HashMap<Int, NativeNode>()
62
68
  private val animatedGraph = AnimatedGraph()
63
69
  private val modalHostsByNodeId = HashMap<Int, ModalHost>()
@@ -97,7 +103,11 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
97
103
  if (isDebuggable) thread(isDaemon = true) { listenForReload() }
98
104
  }
99
105
 
106
+ /** On the main thread, when the activity is destroyed. */
100
107
  fun destroy() {
108
+ isDestroyed = true
109
+ reloadConnection?.disconnect()
110
+ animatedGraph.reset() // a looping animation would keep running on the dead views
101
111
  javaScriptHandler.post {
102
112
  runtime?.destroy()
103
113
  runtime = null
@@ -108,8 +118,9 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
108
118
  /** (callId, ...arguments): settles the call with __asyncFunctionFinished; a throw rejects it. */
109
119
  private fun asyncCall(function: AsyncFunction): NativeFunction = { arguments ->
110
120
  val callId = int(arguments[0])
121
+ val owner = runtime
111
122
  val promise = Promise { value, errorMessage ->
112
- evaluate { runtime?.call("__asyncFunctionFinished", callId, value, errorMessage) }
123
+ callIfStillRunning(owner, "__asyncFunctionFinished", callId, value, errorMessage)
113
124
  }
114
125
 
115
126
  runCatching { function(arguments.drop(1), promise) }.onFailure { promise.reject(it.message ?: it.toString()) }
@@ -121,6 +132,8 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
121
132
  if (!ThemeColors.update(activity)) return
122
133
 
123
134
  applyThemeColors(activity.window.decorView)
135
+ // Content not in the window now, like a hidden <Modal>'s, is repainted too.
136
+ nodesById.values.forEach { applyThemeColors(it.view) }
124
137
  // The theme set them when the window was created; it isn't recreated (configChanges has uiMode).
125
138
  val lightBars = WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS or
126
139
  WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS
@@ -228,7 +241,7 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
228
241
 
229
242
  /** System back: closes the top <Modal>, else pops the innermost visible stack. */
230
243
  fun goBack(): Boolean {
231
- modalHostsByNodeId.values.lastOrNull { it.isShowing }?.let {
244
+ modalHostsByNodeId.values.filter { it.isShowing }.maxByOrNull { it.presentationOrder }?.let {
232
245
  it.requestClose()
233
246
  return true
234
247
  }
@@ -279,7 +292,7 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
279
292
  }
280
293
  put("remove") { arguments ->
281
294
  val id = int(arguments[0])
282
- enqueue { nodesById.remove(id)?.removeFromParent() }
295
+ enqueue { nodesById[id]?.let(::removeNode) }
283
296
  }
284
297
  put("setText") { arguments ->
285
298
  val id = int(arguments[0])
@@ -310,9 +323,12 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
310
323
  private fun setTimer(timerId: Int, delay: Int) {
311
324
  val owner = runtime
312
325
 
313
- javaScriptHandler.postDelayed({
314
- if (runtime === owner) evaluate { runtime?.call("__fireTimer", timerId) }
315
- }, delay.toLong())
326
+ javaScriptHandler.postDelayed({ callIfStillRunning(owner, "__fireTimer", timerId) }, delay.toLong())
327
+ }
328
+
329
+ /** For results that arrive later: a reloaded runtime starts its timer, request and call ids over. */
330
+ private fun callIfStillRunning(owner: JavaScriptRuntime?, function: String, vararg arguments: Any?) {
331
+ evaluate { if (runtime === owner) runtime?.call(function, *arguments) }
316
332
  }
317
333
 
318
334
  private fun storageFunctions(): Map<String, NativeFunction> = mapOf(
@@ -362,7 +378,7 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
362
378
  * fetch: HttpURLConnection runs the request; JS hears back through
363
379
  * __fetchFinished(requestId, response, error).
364
380
  */
365
- // ponytail: text bodies only (no binary, FormData or streaming) and no abort, like on iOS.
381
+ // Limitation: Text bodies only (no binary, FormData or streaming) and no abort, like on iOS.
366
382
  private fun fetchFunctions(): Map<String, NativeFunction> = mapOf(
367
383
  "fetch" to { arguments ->
368
384
  val requestId = arguments[0]
@@ -370,11 +386,12 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
370
386
  val method = arguments[2] as String
371
387
  val headers = arguments[3] as? Map<*, *> ?: emptyMap<String, String>()
372
388
  val body = arguments[4] as? String
389
+ val owner = runtime
373
390
 
374
391
  thread {
375
392
  val (response, error) = runCatching { request(url, method, headers, body) }
376
393
  .fold({ Pair(it, null) }, { Pair(null, it.message ?: it.toString()) })
377
- evaluate { runtime?.call("__fetchFinished", requestId, response, error) }
394
+ callIfStillRunning(owner, "__fetchFinished", requestId, response, error)
378
395
  }
379
396
  },
380
397
  )
@@ -446,11 +463,12 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
446
463
  val candidateURLs = devServerURLs()
447
464
  var attempt = 0
448
465
 
449
- while (true) {
466
+ while (!isDestroyed) {
450
467
  devServerURL = candidateURLs[attempt++ % candidateURLs.size]
451
468
  runCatching {
452
469
  val connection = URL("$devServerURL/events").openConnection() as HttpURLConnection
453
470
  connection.readTimeout = 0
471
+ reloadConnection = connection
454
472
 
455
473
  connection.inputStream.bufferedReader().useLines { lines ->
456
474
  lines.filter { it == "data: reload" }.forEach { _ ->
@@ -467,8 +485,32 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
467
485
 
468
486
  // ---------- Main thread ----------
469
487
 
488
+ /** Vue removes only a subtree's root: the nodes under it are forgotten with it. */
489
+ private fun removeNode(root: NativeNode) {
490
+ val removedViews = mutableSetOf<View>()
491
+ collectViews(root.view, removedViews)
492
+ root.contentNode?.let { collectViews(it.view, removedViews) }
493
+
494
+ // Limitation: A nested <Modal>'s content isn't under the root's views, so its nodes stay; walk the
495
+ // modal hosts too if apps nest many. Hosts stay: layout dismisses the detached ones.
496
+ val removedIds = nodesById.filterValues { it.view in removedViews }.keys
497
+ removedIds.forEach { id ->
498
+ nodesById.remove(id)
499
+ gestureReportersByNodeId.remove(id)
500
+ }
501
+ root.removeFromParent()
502
+ }
503
+
504
+ private fun collectViews(view: View, views: MutableSet<View>) {
505
+ views.add(view)
506
+ if (view is ViewGroup) (0 until view.childCount).forEach { collectViews(view.getChildAt(it), views) }
507
+ }
508
+
470
509
  private fun resetNodeTree() {
471
- modalHostsByNodeId.values.forEach { it.setVisible(false) }
510
+ modalHostsByNodeId.values.forEach {
511
+ it.onEvent = {} // its "dismiss" would reach the new tree's node with the same id
512
+ it.setVisible(false)
513
+ }
472
514
  modalHostsByNodeId.clear()
473
515
  gestureReportersByNodeId.clear() // node ids start over
474
516
  animatedGraph.reset()
@@ -555,15 +597,16 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
555
597
  }
556
598
 
557
599
  "KeyboardAvoidingView" -> NativeNode(KeyboardAvoidingView(activity), measuresContent = false).also {
558
- it.insetTypes = WindowInsets.Type.ime()
600
+ it.insetTypes = IME
559
601
  }
560
602
 
561
603
  "TextInput" -> NativeNode(makeTextInput(id), measuresContent = true)
562
604
 
563
605
  "Switch" -> {
564
- val toggle = Switch(activity)
565
- toggle.setOnCheckedChangeListener { view, isChecked ->
566
- if (view.isPressed) dispatchEvent("valuechange", id, isChecked) // not when set from JS
606
+ val toggle = ToggleSwitch(activity)
607
+ toggle.setOnCheckedChangeListener { _, isChecked ->
608
+ // Every change but JS's own: touch, keyboard and accessibility toggles alike.
609
+ if (!toggle.isSettingFromJavaScript) dispatchEvent("valuechange", id, isChecked)
567
610
  }
568
611
  NativeNode(toggle, measuresContent = true)
569
612
  }
@@ -601,17 +644,19 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
601
644
  override fun onTextChanged(text: CharSequence?, start: Int, before: Int, count: Int) {}
602
645
 
603
646
  override fun afterTextChanged(text: Editable?) {
604
- if (!textInput.hasFocus()) return // set from JS
647
+ if (textInput.isSettingTextFromJavaScript) return // autofill and accessibility do count
605
648
 
606
649
  textInput.recordTextSentToJavaScript()
607
650
  dispatchEvent("changetext", id, text.toString())
608
651
  }
609
652
  })
610
- // Returning false lets the action close the keyboard, as single-line inputs are expected to.
653
+ // The return key closes the keyboard and ends editing, as single-line inputs do on iOS too.
611
654
  textInput.setOnEditorActionListener { _, _, _ ->
612
655
  dispatchEvent("submitediting", id, textInput.text.toString())
613
- false
656
+ hideKeyboard(textInput)
657
+ true
614
658
  }
659
+ textInput.setOnFocusChangeListener { _, hasFocus -> dispatchEvent(if (hasFocus) "focus" else "blur", id, null) }
615
660
 
616
661
  return textInput
617
662
  }
@@ -694,7 +739,14 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
694
739
 
695
740
  // A scroll view pads its scrollable area by the system bars it's under, unless "never".
696
741
  "contentInsetAdjustmentBehavior" -> if (view is ScrollContainerView) {
697
- node.insetTypes = if (value == null || value == "never") 0 else SYSTEM_BARS
742
+ val systemBars = if (value == null || value == "never") 0 else SYSTEM_BARS
743
+ node.insetTypes = (node.insetTypes and IME) or systemBars
744
+ }
745
+
746
+ // The keyboard pads it too, and the focused input scrolls above it.
747
+ "automaticallyAdjustKeyboardInsets" -> if (view is ScrollContainerView) {
748
+ val keyboard = if (isTruthyAttribute(value)) IME else 0
749
+ node.insetTypes = (node.insetTypes and IME.inv()) or keyboard
698
750
  }
699
751
 
700
752
  "horizontal" -> setScrollDirection(node, isTruthyAttribute(value))
@@ -709,7 +761,7 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
709
761
 
710
762
  "value" -> {
711
763
  (view as? TextInputView)?.setTextFromJavaScript(value as? String ?: "")
712
- (view as? Switch)?.isChecked = isTruthyAttribute(value)
764
+ (view as? ToggleSwitch)?.setCheckedFromJavaScript(isTruthyAttribute(value))
713
765
  }
714
766
 
715
767
  "disabled" -> {
@@ -752,7 +804,7 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
752
804
 
753
805
  "source" -> (view as? RemoteImageView)?.load(value as? String)
754
806
 
755
- "resizeMode" -> (view as? RemoteImageView)?.scaleType = RemoteImageView.scaleTypes[value] ?: android.widget.ImageView.ScaleType.CENTER_CROP
807
+ "resizeMode" -> (view as? RemoteImageView)?.scaleType = RemoteImageView.scaleTypes[value] ?: ImageView.ScaleType.CENTER_CROP
756
808
 
757
809
  "onLongPress" -> (view as? PressableView)?.reportsLongPress = isTruthyAttribute(value)
758
810
 
@@ -771,7 +823,7 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
771
823
  private fun setScrollDirection(node: NativeNode, horizontal: Boolean) {
772
824
  val scrollView = node.view as? ScrollContainerView ?: return
773
825
 
774
- node.yogaNode.setFlexDirection(if (horizontal) com.facebook.yoga.YogaFlexDirection.ROW else com.facebook.yoga.YogaFlexDirection.COLUMN)
826
+ node.yogaNode.setFlexDirection(if (horizontal) YogaFlexDirection.ROW else YogaFlexDirection.COLUMN)
775
827
  scrollView.setHorizontal(horizontal)
776
828
  }
777
829
 
@@ -787,7 +839,6 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
787
839
  return gestureReporter(viewId, view).setAnimatedMapping(eventName, fieldsToNodeIds)
788
840
  }
789
841
 
790
-
791
842
  if (mapping == null) {
792
843
  scrollView.onOffsetChange = null
793
844
  return
@@ -923,6 +974,7 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
923
974
  const val BUTTON_TINT = 0xFF007AFF.toInt()
924
975
  val EDGES = listOf(YogaEdge.LEFT, YogaEdge.TOP, YogaEdge.RIGHT, YogaEdge.BOTTOM)
925
976
  val SYSTEM_BARS = WindowInsets.Type.systemBars() or WindowInsets.Type.displayCutout()
977
+ val IME = WindowInsets.Type.ime()
926
978
  const val SHEET_TOP_GAP = 12f
927
979
 
928
980
  val keyboardInputTypes = mapOf(
@@ -17,6 +17,8 @@ import kotlin.math.hypot
17
17
  * gesture's state ("began", "changed", "ended", "cancelled"), so it can move the view through its
18
18
  * style; with Animated.event the values move natively and JS only hears the start and the end.
19
19
  * Numbers are in dp (and dp per second); rotation in radians. Mirrors ios/GestureReporter.swift.
20
+ * Limitation: Unlike on iOS, a parent doesn't see touches a child consumes (a <Pressable> inside a draggable
21
+ * card); intercept moves past the touch slop if that's needed.
20
22
  */
21
23
  class GestureReporter(
22
24
  private val view: View,
@@ -62,11 +62,19 @@ class ModalHost(private val activity: Activity) {
62
62
  val isShowing: Boolean
63
63
  get() = isPresented
64
64
 
65
+ /** Back closes the modal presented last. */
66
+ var presentationOrder = 0L
67
+ private set
68
+
65
69
  private fun present() {
66
70
  if (isPresented) return
67
71
 
68
72
  isPresented = true
73
+ presentationOrder = System.nanoTime()
69
74
  val content = contentNode.view
75
+ // Shown again while still animating out: that dismissal's end would remove it.
76
+ content.animate().cancel()
77
+ (overlay.parent as? ViewGroup)?.removeView(overlay)
70
78
  content.background = when {
71
79
  transparent -> null
72
80
  isSheet -> GradientDrawable().apply {
@@ -380,7 +380,7 @@ fun ripple(cornerRadius: Float): RippleDrawable {
380
380
  */
381
381
  class ScreenStackView(context: Context) : ContainerView(context) {
382
382
  private val screens: List<ScreenView>
383
- get() = (0 until childCount).mapNotNull { getChildAt(it) as? ScreenView }
383
+ get() = screenChildren()
384
384
 
385
385
  init {
386
386
  clipChildren = true
@@ -553,7 +553,7 @@ class TabBarView(context: Context) : ContainerView(context), ThemeAware {
553
553
  private val bar = LinearLayout(context)
554
554
 
555
555
  private val screens: List<ScreenView>
556
- get() = (0 until childCount).mapNotNull { getChildAt(it) as? ScreenView }
556
+ get() = screenChildren()
557
557
 
558
558
  init {
559
559
  clipChildren = true
@@ -694,3 +694,6 @@ private class TabItemView(context: Context) : LinearLayout(context) {
694
694
  badge.visibility = if (badgeText.isNullOrEmpty()) View.GONE else View.VISIBLE
695
695
  }
696
696
  }
697
+
698
+ /** The screens among a container's children, in order. */
699
+ private fun ViewGroup.screenChildren(): List<ScreenView> = (0 until childCount).mapNotNull { getChildAt(it) as? ScreenView }
@@ -17,7 +17,7 @@ import com.facebook.yoga.YogaOverflow
17
17
  import com.facebook.yoga.YogaPositionType
18
18
  import com.facebook.yoga.YogaWrap
19
19
 
20
- // ponytail: removed layout properties arrive as null and keep their last value, like on iOS.
20
+ // Limitation: Removed layout properties arrive as null and keep their last value, like on iOS.
21
21
 
22
22
  /** Receives only the properties that changed: the JS renderer diffs style objects before sending. */
23
23
  fun NativeNode.applyStyle(changes: Map<String, Any?>) {
@@ -25,7 +25,7 @@ import kotlin.math.tan
25
25
  * with `color` (round caps and joins, as icon sets expect); those whose fill isn't "none" are also
26
26
  * filled with it. Mirrors ios/SvgView.swift.
27
27
  */
28
- // ponytail: only the shapes icon sets use and a single color; add per-element colors, gradients or
28
+ // Limitation: Only the shapes icon sets use and a single color; add per-element colors, gradients or
29
29
  // transforms when a real-world SVG needs them.
30
30
  class SvgView(context: Context) : View(context) {
31
31
  var viewBox = RectF(0f, 0f, 24f, 24f)
@@ -4,6 +4,7 @@ import android.annotation.SuppressLint
4
4
  import android.content.Context
5
5
  import android.graphics.Bitmap
6
6
  import android.graphics.BitmapFactory
7
+ import android.graphics.Rect
7
8
  import android.os.Handler
8
9
  import android.os.Looper
9
10
  import android.util.Base64
@@ -17,6 +18,7 @@ import android.view.inputmethod.InputMethodManager
17
18
  import android.widget.ImageView
18
19
  import android.widget.ProgressBar
19
20
  import android.widget.ScrollView
21
+ import android.widget.Switch
20
22
  import java.net.URL
21
23
  import kotlin.concurrent.thread
22
24
  import kotlin.math.abs
@@ -81,6 +83,9 @@ class PressableView(context: Context) : ContainerView(context) {
81
83
 
82
84
  @SuppressLint("ClickableViewAccessibility")
83
85
  override fun onTouchEvent(event: MotionEvent): Boolean {
86
+ // Consumed but ignored, as disabled Android buttons do: the touch doesn't reach a parent.
87
+ if (!isEnabled) return true
88
+
84
89
  when (event.actionMasked) {
85
90
  MotionEvent.ACTION_DOWN -> pressIn()
86
91
  MotionEvent.ACTION_UP -> pressOut(pressed = isInside(event))
@@ -111,6 +116,11 @@ class PressableView(context: Context) : ContainerView(context) {
111
116
  if (pressed && !didLongPress) onEvent("press")
112
117
  }
113
118
 
119
+ override fun setEnabled(enabled: Boolean) {
120
+ super.setEnabled(enabled)
121
+ if (!enabled) longPressHandler.removeCallbacksAndMessages(null)
122
+ }
123
+
114
124
  private fun isInside(event: MotionEvent) = event.x in 0f..width.toFloat() && event.y in 0f..height.toFloat()
115
125
  }
116
126
 
@@ -258,8 +268,21 @@ class ScrollContainerView(context: Context) : ContainerView(context) {
258
268
  val (left, top, right, bottom) = contentInsets
259
269
  if (scroller.paddingLeft == left && scroller.paddingTop == top && scroller.paddingRight == right && scroller.paddingBottom == bottom) return
260
270
 
271
+ val bottomGrew = bottom > scroller.paddingBottom
261
272
  scroller.clipToPadding = false
262
273
  scroller.setPadding(left, top, right, bottom)
274
+ if (bottomGrew) revealFocusedInput()
275
+ }
276
+
277
+ /** When the keyboard pads the bottom, scrolls up just enough for the focused input to sit above it. */
278
+ private fun revealFocusedInput() {
279
+ val focusedView = scroller.findFocus() ?: return
280
+ val inputRect = Rect()
281
+ focusedView.getDrawingRect(inputRect)
282
+ scroller.offsetDescendantRectToMyCoords(focusedView, inputRect)
283
+
284
+ val visibleBottom = scroller.scrollY + scroller.height - scroller.paddingBottom
285
+ if (inputRect.bottom > visibleBottom) scroller.scrollBy(0, inputRect.bottom - visibleBottom)
263
286
  }
264
287
 
265
288
  fun setContentSize(width: Int, height: Int) {
@@ -465,9 +488,11 @@ class TextInputView(context: Context) : android.widget.EditText(context), ThemeA
465
488
  applyThemeColors()
466
489
  }
467
490
 
468
- // ponytail: a value JS sets on purpose that equals text typed earlier in the same editing session is
491
+ // Limitation: A value JS sets on purpose that equals text typed earlier in the same editing session is
469
492
  // ignored too; tag each change with a counter if that ever matters.
470
493
  private val textsSentToJavaScript = mutableSetOf<String>()
494
+ var isSettingTextFromJavaScript = false
495
+ private set
471
496
 
472
497
  override fun applyThemeColors() {
473
498
  setTextColor(styleColor ?: ThemeColors.text)
@@ -490,7 +515,21 @@ class TextInputView(context: Context) : android.widget.EditText(context), ThemeA
490
515
  fun setTextFromJavaScript(newText: String) {
491
516
  if (newText == text.toString() || newText in textsSentToJavaScript) return
492
517
 
518
+ isSettingTextFromJavaScript = true
493
519
  setText(newText)
494
520
  setSelection(newText.length)
521
+ isSettingTextFromJavaScript = false
522
+ }
523
+ }
524
+
525
+ /** A Switch that tells JS's own changes (v-model) apart from the user's. */
526
+ class ToggleSwitch(context: Context) : Switch(context) {
527
+ var isSettingFromJavaScript = false
528
+ private set
529
+
530
+ fun setCheckedFromJavaScript(checked: Boolean) {
531
+ isSettingFromJavaScript = true
532
+ isChecked = checked
533
+ isSettingFromJavaScript = false
495
534
  }
496
535
  }
package/cli/nativue.mjs CHANGED
@@ -20,6 +20,7 @@ import { runOnAndroid, runOnIOS } from './run.mjs'
20
20
  import { createSymbolicator } from './symbolicate.mjs'
21
21
 
22
22
  const PORT = 40836 // 0x9F84, from #0E9F84, the nativue green
23
+ const MAX_STACK_LENGTH = 1_000_000 // characters, of a stack the app posts to /symbolicate
23
24
  const BUNDLE_DIRECTORY = 'ios/App'
24
25
  const BUNDLE_PATH = `${BUNDLE_DIRECTORY}/main.bundle.js`
25
26
  const SOURCE_MAP_PATH = `${BUNDLE_PATH}.map`
@@ -184,17 +185,31 @@ function startDevServer() {
184
185
  }
185
186
 
186
187
  function handleBundle(response) {
188
+ // An installed app can ask before Vite's first build has written it.
189
+ if (!existsSync(BUNDLE_PATH)) {
190
+ response.writeHead(503, { 'Content-Type': 'text/plain' })
191
+ response.end('The bundle is still building')
192
+ return
193
+ }
194
+
187
195
  response.writeHead(200, { 'Content-Type': 'application/javascript' })
188
196
  response.end(readFileSync(BUNDLE_PATH))
189
197
  }
190
198
 
191
199
  // The app posts an error's stack; it gets it back pointing at the app's files.
192
200
  async function handleSymbolicate(request, response) {
193
- let text = ''
194
- for await (const chunk of request) text += chunk
195
-
196
- response.writeHead(200, { 'Content-Type': 'text/plain' })
197
- response.end(symbolicate(text))
201
+ try {
202
+ let text = ''
203
+ for await (const chunk of request) {
204
+ text += chunk
205
+ if (text.length > MAX_STACK_LENGTH) throw new Error('stack too long')
206
+ }
207
+
208
+ response.writeHead(200, { 'Content-Type': 'text/plain' })
209
+ response.end(symbolicate(text))
210
+ } catch {
211
+ response.writeHead(400).end() // an aborted or oversized post: never take the server down
212
+ }
198
213
  }
199
214
 
200
215
  http
@@ -203,6 +218,7 @@ function startDevServer() {
203
218
  else if (request.url === '/symbolicate') handleSymbolicate(request, response)
204
219
  else handleBundle(response)
205
220
  })
221
+ // Limitation: Every interface, so phones reach it, and anyone on the network can download the bundle.
206
222
  .listen(PORT, () => console.log(`dev server: http://localhost:${PORT}`))
207
223
 
208
224
  // Without a keepalive, URLSession drops the idle connection.
package/cli/run.mjs CHANGED
@@ -132,7 +132,7 @@ function connectedDevices(adb) {
132
132
  .map((line) => line.split('\t')[0])
133
133
  }
134
134
 
135
- // ponytail: the first device or emulator wins; a --device option when people run several at once.
135
+ // Limitation: The first device or emulator wins; a --device option when people run several at once.
136
136
  async function pickDevice(sdkPath, adb) {
137
137
  const [device] = connectedDevices(adb)
138
138
  if (device) return device