@nativue/core 0.3.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/android/src/main/java/dev/nativue/Bridge.kt +75 -23
- package/android/src/main/java/dev/nativue/ModalHost.kt +8 -0
- package/android/src/main/java/dev/nativue/Navigation.kt +5 -2
- package/android/src/main/java/dev/nativue/Views.kt +39 -0
- package/cli/nativue.mjs +20 -5
- package/ios/Bridge.swift +39 -16
- package/ios/KeyboardAvoidingView.swift +12 -5
- package/ios/ModalController.swift +27 -6
- package/ios/Plugins.swift +2 -1
- package/ios/PressableView.swift +1 -1
- package/ios/VueScrollView.swift +49 -0
- package/package.json +1 -1
- package/src/components.ts +45 -9
- package/src/fetch.ts +4 -1
- package/src/native-components.ts +7 -0
- package/src/renderer.ts +53 -10
- package/src/router.ts +37 -7
|
@@ -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
|
-
|
|
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.
|
|
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
|
|
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
|
-
|
|
315
|
-
|
|
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(
|
|
@@ -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
|
-
|
|
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 (
|
|
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
|
+
// ponytail: 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 {
|
|
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 =
|
|
600
|
+
it.insetTypes = IME
|
|
559
601
|
}
|
|
560
602
|
|
|
561
603
|
"TextInput" -> NativeNode(makeTextInput(id), measuresContent = true)
|
|
562
604
|
|
|
563
605
|
"Switch" -> {
|
|
564
|
-
val toggle =
|
|
565
|
-
toggle.setOnCheckedChangeListener {
|
|
566
|
-
|
|
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 (
|
|
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
|
-
//
|
|
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
|
-
|
|
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
|
-
|
|
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?
|
|
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] ?:
|
|
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)
|
|
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(
|
|
@@ -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() = (
|
|
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() = (
|
|
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 }
|
|
@@ -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) {
|
|
@@ -468,6 +491,8 @@ class TextInputView(context: Context) : android.widget.EditText(context), ThemeA
|
|
|
468
491
|
// ponytail: 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
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
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
|
package/ios/Bridge.swift
CHANGED
|
@@ -5,11 +5,11 @@ import yoga
|
|
|
5
5
|
/// Runs the JS bundle off the main thread and applies the operations sent by the Vue renderer
|
|
6
6
|
/// (src/renderer.js) to UIKit + Yoga in batches on the main thread.
|
|
7
7
|
final class Bridge {
|
|
8
|
-
/// The simulator shares the Mac's network; a device uses the Mac's name, written into the app at build
|
|
9
|
-
/// time by the "Write Dev Server Host" build phase.
|
|
10
8
|
/// Posted by the app with a URL it was opened with (deep link); forwarded to JS (`__openURL`).
|
|
11
9
|
static let openURLNotification = Notification.Name("NativueOpenURL")
|
|
12
10
|
|
|
11
|
+
/// The simulator shares the Mac's network; a device uses the Mac's name, written into the app at build
|
|
12
|
+
/// time by the "Write Dev Server Host" build phase.
|
|
13
13
|
static let devServerURL: URL = {
|
|
14
14
|
#if targetEnvironment(simulator)
|
|
15
15
|
let host = "localhost"
|
|
@@ -29,8 +29,6 @@ final class Bridge {
|
|
|
29
29
|
// Only touched on javaScriptQueue.
|
|
30
30
|
private var runtime: JavaScriptRuntime?
|
|
31
31
|
private var pendingOperations: [() -> Void] = []
|
|
32
|
-
private var gestureReportersByNodeId: [Int: GestureReporter] = [:]
|
|
33
|
-
private let animatedGraph = AnimatedGraph()
|
|
34
32
|
private lazy var storage = KeyValueStorage(javaScriptQueue: javaScriptQueue)
|
|
35
33
|
/// Set by LayoutAnimation.configureNext in JS; animates the batch it's sent with.
|
|
36
34
|
private var nextLayoutAnimation: LayoutAnimation?
|
|
@@ -39,10 +37,13 @@ final class Bridge {
|
|
|
39
37
|
|
|
40
38
|
// Only touched on the main thread.
|
|
41
39
|
var rootView: RootView!
|
|
40
|
+
private var gestureReportersByNodeId: [Int: GestureReporter] = [:]
|
|
41
|
+
private let animatedGraph = AnimatedGraph()
|
|
42
42
|
// ponytail: children of a removed node stay in the dictionary; clean up recursively if memory leaks.
|
|
43
43
|
var nodesById: [Int: NativeNode] = [:]
|
|
44
44
|
/// Modals and screens: their content is laid out as a separate Yoga root.
|
|
45
|
-
// ponytail:
|
|
45
|
+
// ponytail: Vue removes only a subtree's root, so the modals and screens inside a removed subtree stay
|
|
46
|
+
// here and are laid out on every pass; drop the detached ones on remove if navigators come and go.
|
|
46
47
|
private var contentRootsByNodeId: [Int: ContentRoot] = [:]
|
|
47
48
|
/// Read on the main thread at start, for Dimensions.get('window').
|
|
48
49
|
private var windowSize: CGSize = .zero
|
|
@@ -136,8 +137,11 @@ final class Bridge {
|
|
|
136
137
|
}
|
|
137
138
|
}
|
|
138
139
|
|
|
139
|
-
|
|
140
|
+
/// Results reaching a runtime that has since been reloaded are dropped: call ids start over in the new one.
|
|
141
|
+
private func finishAsyncFunction(_ callId: Int, owner: JavaScriptRuntime?, value: Any?, errorMessage: String?) {
|
|
140
142
|
evaluate { [unowned self] in
|
|
143
|
+
guard runtime === owner else { return }
|
|
144
|
+
|
|
141
145
|
let arguments: [Any] = [callId, value ?? NSNull(), errorMessage ?? NSNull()]
|
|
142
146
|
runtime?.call("__asyncFunctionFinished", arguments: arguments)
|
|
143
147
|
}
|
|
@@ -235,13 +239,14 @@ final class Bridge {
|
|
|
235
239
|
for (name, function) in pluginRegistry.asyncFunctions {
|
|
236
240
|
define("pluginAsync:\(name)") { [unowned self] arguments in
|
|
237
241
|
let callId = int(arguments[0])
|
|
242
|
+
let owner = runtime
|
|
238
243
|
|
|
239
244
|
Task {
|
|
240
245
|
do {
|
|
241
246
|
let value = try await function(Array(arguments.dropFirst()))
|
|
242
|
-
finishAsyncFunction(callId, value: value, errorMessage: nil)
|
|
247
|
+
finishAsyncFunction(callId, owner: owner, value: value, errorMessage: nil)
|
|
243
248
|
} catch {
|
|
244
|
-
finishAsyncFunction(callId, value: nil, errorMessage: error.localizedDescription)
|
|
249
|
+
finishAsyncFunction(callId, owner: owner, value: nil, errorMessage: error.localizedDescription)
|
|
245
250
|
}
|
|
246
251
|
}
|
|
247
252
|
}
|
|
@@ -339,6 +344,8 @@ final class Bridge {
|
|
|
339
344
|
// MARK: - Main thread
|
|
340
345
|
|
|
341
346
|
private func resetNodeTree() {
|
|
347
|
+
// Sheets of the old tree's screen stacks too, which only their stack knows about.
|
|
348
|
+
rootView.window?.rootViewController?.dismiss(animated: false)
|
|
342
349
|
rootView.subviews.forEach { $0.removeFromSuperview() }
|
|
343
350
|
contentRootsByNodeId.values.forEach { ($0 as? ModalController)?.setVisible(false) }
|
|
344
351
|
contentRootsByNodeId = [:]
|
|
@@ -421,7 +428,10 @@ final class Bridge {
|
|
|
421
428
|
case "KeyboardAvoidingView":
|
|
422
429
|
let keyboardAvoidingView = KeyboardAvoidingView()
|
|
423
430
|
let node = NativeNode(view: keyboardAvoidingView, measuresContent: false)
|
|
424
|
-
|
|
431
|
+
// weak: a reload frees the node while a dismissing modal still shows its view.
|
|
432
|
+
keyboardAvoidingView.onKeyboardOverlapChange = { [unowned self, weak node] overlap in
|
|
433
|
+
guard let node else { return }
|
|
434
|
+
|
|
425
435
|
YGNodeStyleSetPadding(node.yogaNode, .bottom, Float(overlap))
|
|
426
436
|
rootView.setNeedsLayout()
|
|
427
437
|
rootView.layoutIfNeeded() // runs inside the keyboard animation, so frames animate with it
|
|
@@ -431,8 +441,8 @@ final class Bridge {
|
|
|
431
441
|
case "SafeAreaView":
|
|
432
442
|
let safeAreaView = SafeAreaView()
|
|
433
443
|
let node = NativeNode(view: safeAreaView, measuresContent: false)
|
|
434
|
-
safeAreaView.onSafeAreaInsetsChange = { [unowned self,
|
|
435
|
-
if node
|
|
444
|
+
safeAreaView.onSafeAreaInsetsChange = { [unowned self, weak node] in
|
|
445
|
+
if node?.applySafeAreaPadding() == true { requestLayout() }
|
|
436
446
|
}
|
|
437
447
|
return node
|
|
438
448
|
|
|
@@ -506,8 +516,13 @@ final class Bridge {
|
|
|
506
516
|
dispatchEvent("submitediting", toNodeId: id, payload: textInput.text ?? "")
|
|
507
517
|
}, for: .editingDidEndOnExit)
|
|
508
518
|
|
|
509
|
-
textInput.addAction(UIAction { [unowned
|
|
519
|
+
textInput.addAction(UIAction { [unowned self] _ in
|
|
520
|
+
dispatchEvent("focus", toNodeId: id, payload: nil)
|
|
521
|
+
}, for: .editingDidBegin)
|
|
522
|
+
|
|
523
|
+
textInput.addAction(UIAction { [unowned self, unowned textInput] _ in
|
|
510
524
|
textInput.endEditingSession()
|
|
525
|
+
dispatchEvent("blur", toNodeId: id, payload: nil)
|
|
511
526
|
}, for: .editingDidEnd)
|
|
512
527
|
|
|
513
528
|
return textInput
|
|
@@ -543,9 +558,10 @@ final class Bridge {
|
|
|
543
558
|
let (requestId, url, method) = (int(arguments[0]), string(arguments[1]), string(arguments[2]))
|
|
544
559
|
let headers = arguments[3] as? [String: String] ?? [:]
|
|
545
560
|
let bodyText = arguments[4] as? String
|
|
561
|
+
let owner = runtime
|
|
546
562
|
|
|
547
563
|
guard let url = URL(string: url) else {
|
|
548
|
-
return finishFetch(requestId, response: nil, error: "invalid URL \(url)")
|
|
564
|
+
return finishFetch(requestId, owner: owner, response: nil, error: "invalid URL \(url)")
|
|
549
565
|
}
|
|
550
566
|
|
|
551
567
|
var request = URLRequest(url: url)
|
|
@@ -555,10 +571,12 @@ final class Bridge {
|
|
|
555
571
|
|
|
556
572
|
URLSession.shared.dataTask(with: request) { [unowned self] data, response, error in
|
|
557
573
|
guard let response = response as? HTTPURLResponse, error == nil else {
|
|
558
|
-
return finishFetch(
|
|
574
|
+
return finishFetch(
|
|
575
|
+
requestId, owner: owner, response: nil, error: error?.localizedDescription ?? "no response"
|
|
576
|
+
)
|
|
559
577
|
}
|
|
560
578
|
|
|
561
|
-
finishFetch(requestId, response: [
|
|
579
|
+
finishFetch(requestId, owner: owner, response: [
|
|
562
580
|
"status": response.statusCode,
|
|
563
581
|
"headers": response.allHeaderFields,
|
|
564
582
|
"body": String(decoding: data ?? Data(), as: UTF8.self),
|
|
@@ -567,8 +585,10 @@ final class Bridge {
|
|
|
567
585
|
}
|
|
568
586
|
}
|
|
569
587
|
|
|
570
|
-
|
|
588
|
+
/// Like finishAsyncFunction, dropped if the runtime that asked has since been reloaded.
|
|
589
|
+
private func finishFetch(_ requestId: Int, owner: JavaScriptRuntime?, response: [String: Any]?, error: String?) {
|
|
571
590
|
evaluate { [unowned self] in
|
|
591
|
+
guard runtime === owner else { return }
|
|
572
592
|
let arguments: [Any] = [requestId, response ?? NSNull(), error ?? NSNull()]
|
|
573
593
|
runtime?.call("__fetchFinished", arguments: arguments)
|
|
574
594
|
}
|
|
@@ -725,6 +745,9 @@ final class Bridge {
|
|
|
725
745
|
case "showsVerticalScrollIndicator":
|
|
726
746
|
(node.view as? UIScrollView)?.showsVerticalScrollIndicator = isTruthyAttribute(value)
|
|
727
747
|
|
|
748
|
+
case "automaticallyAdjustKeyboardInsets":
|
|
749
|
+
(node.view as? VueScrollView)?.adjustsForKeyboard = isTruthyAttribute(value)
|
|
750
|
+
|
|
728
751
|
case "value":
|
|
729
752
|
(node.view as? TextInputView)?.setTextFromJavaScript(value as? String ?? "")
|
|
730
753
|
(node.view as? UISwitch)?.setOn(isTruthyAttribute(value), animated: true)
|
|
@@ -30,12 +30,19 @@ final class KeyboardAvoidingView: UIView {
|
|
|
30
30
|
let keyboardTopInView = convert(keyboardFrame, from: nil).minY
|
|
31
31
|
let overlap = max(0, bounds.maxY - keyboardTopInView)
|
|
32
32
|
|
|
33
|
-
|
|
34
|
-
let curve = (userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as? UInt) ?? 7
|
|
35
|
-
let options = UIView.AnimationOptions(rawValue: curve << 16)
|
|
36
|
-
|
|
37
|
-
UIView.animate(withDuration: duration, delay: 0, options: options) { [weak self] in
|
|
33
|
+
UIView.animateAlongsideKeyboard(notification) { [weak self] in
|
|
38
34
|
self?.onKeyboardOverlapChange?(overlap)
|
|
39
35
|
}
|
|
40
36
|
}
|
|
41
37
|
}
|
|
38
|
+
|
|
39
|
+
extension UIView {
|
|
40
|
+
/// Runs `animations` with the keyboard's own duration and curve, so the change moves in sync with it.
|
|
41
|
+
static func animateAlongsideKeyboard(_ notification: Notification, animations: @escaping () -> Void) {
|
|
42
|
+
let userInfo = notification.userInfo
|
|
43
|
+
let duration = (userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double) ?? 0.25
|
|
44
|
+
let curve = (userInfo?[UIResponder.keyboardAnimationCurveUserInfoKey] as? UInt) ?? 7
|
|
45
|
+
|
|
46
|
+
animate(withDuration: duration, delay: 0, options: UIView.AnimationOptions(rawValue: curve << 16), animations: animations)
|
|
47
|
+
}
|
|
48
|
+
}
|
|
@@ -19,6 +19,9 @@ final class ModalController: UIViewController, ContentRoot, UIAdaptivePresentati
|
|
|
19
19
|
var transparent = false
|
|
20
20
|
|
|
21
21
|
private var isPresented: Bool { presentingViewController != nil }
|
|
22
|
+
/// What JS last asked for; applied again when a running transition ends, which UIKit would ignore.
|
|
23
|
+
private var wantsVisible = false
|
|
24
|
+
private var isTransitioning = false
|
|
22
25
|
|
|
23
26
|
override func loadView() {
|
|
24
27
|
view = contentNode.view
|
|
@@ -38,14 +41,22 @@ final class ModalController: UIViewController, ContentRoot, UIAdaptivePresentati
|
|
|
38
41
|
|
|
39
42
|
/// Deferred to after the current batch, so the placeholder is already in the window when presenting.
|
|
40
43
|
func setVisible(_ visible: Bool) {
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
}
|
|
44
|
+
wantsVisible = visible
|
|
45
|
+
DispatchQueue.main.async { [self] in applyVisibility() }
|
|
44
46
|
}
|
|
45
47
|
|
|
46
48
|
/// The <Modal> left the tree (an ancestor's v-if): its content must go too.
|
|
47
49
|
func dismissIfDetached() {
|
|
48
|
-
|
|
50
|
+
guard placeholderView.window == nil else { return }
|
|
51
|
+
|
|
52
|
+
wantsVisible = false
|
|
53
|
+
applyVisibility()
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
private func applyVisibility() {
|
|
57
|
+
guard !isTransitioning else { return }
|
|
58
|
+
|
|
59
|
+
if wantsVisible { present() } else { dismissIfPresented() }
|
|
49
60
|
}
|
|
50
61
|
|
|
51
62
|
private func present() {
|
|
@@ -57,14 +68,24 @@ final class ModalController: UIViewController, ContentRoot, UIAdaptivePresentati
|
|
|
57
68
|
: Self.presentationStyles[presentationStyleName] ?? .fullScreen
|
|
58
69
|
modalTransitionStyle = animationType == "fade" ? .crossDissolve : .coverVertical
|
|
59
70
|
|
|
60
|
-
|
|
71
|
+
isTransitioning = true
|
|
72
|
+
presenter.present(self, animated: animationType != "none") { [self] in
|
|
73
|
+
isTransitioning = false
|
|
74
|
+
onEvent?("show")
|
|
75
|
+
applyVisibility()
|
|
76
|
+
}
|
|
61
77
|
presentationController?.delegate = self
|
|
62
78
|
}
|
|
63
79
|
|
|
64
80
|
private func dismissIfPresented() {
|
|
65
81
|
guard isPresented else { return }
|
|
66
82
|
|
|
67
|
-
|
|
83
|
+
isTransitioning = true
|
|
84
|
+
dismiss(animated: animationType != "none") { [self] in
|
|
85
|
+
isTransitioning = false
|
|
86
|
+
onEvent?("dismiss")
|
|
87
|
+
applyVisibility()
|
|
88
|
+
}
|
|
68
89
|
}
|
|
69
90
|
|
|
70
91
|
private func topViewController() -> UIViewController? {
|
package/ios/Plugins.swift
CHANGED
|
@@ -28,7 +28,8 @@ public final class PluginRegistry {
|
|
|
28
28
|
functions[name] = function
|
|
29
29
|
}
|
|
30
30
|
|
|
31
|
-
/// For work that takes time (a permission prompt, the camera): JavaScript gets a Promise.
|
|
31
|
+
/// For work that takes time (a permission prompt, the camera): JavaScript gets a Promise. Runs off the
|
|
32
|
+
/// main thread: use `await MainActor.run { ... }` for UIKit.
|
|
32
33
|
public func addAsyncFunction(_ name: String, _ function: @escaping AsyncFunction) {
|
|
33
34
|
asyncFunctions[name] = function
|
|
34
35
|
}
|
package/ios/PressableView.swift
CHANGED
|
@@ -55,7 +55,7 @@ final class PressableView: UIControl {
|
|
|
55
55
|
}
|
|
56
56
|
|
|
57
57
|
@objc private func handleLongPress(_ recognizer: UILongPressGestureRecognizer) {
|
|
58
|
-
guard recognizer.state == .began else { return }
|
|
58
|
+
guard recognizer.state == .began, isEnabled else { return }
|
|
59
59
|
|
|
60
60
|
didLongPress = true
|
|
61
61
|
onEvent?("longpress")
|
package/ios/VueScrollView.swift
CHANGED
|
@@ -19,6 +19,10 @@ final class VueScrollView: UIScrollView {
|
|
|
19
19
|
/// "always" / "handled" turn it off.
|
|
20
20
|
var dismissesKeyboardOnTap = true
|
|
21
21
|
|
|
22
|
+
/// automatically-adjust-keyboard-insets: the keyboard insets the content, and the focused input scrolls
|
|
23
|
+
/// above it.
|
|
24
|
+
var adjustsForKeyboard = false
|
|
25
|
+
|
|
22
26
|
/// Set when JS listens to @scroll. Called on every scroll step and size change (FlatList windowing).
|
|
23
27
|
// ponytail: one JS call per frame while scrolling; coalesce / add scrollEventThrottle if JS falls behind.
|
|
24
28
|
var onScroll: ((CGRect) -> Void)? {
|
|
@@ -47,10 +51,20 @@ final class VueScrollView: UIScrollView {
|
|
|
47
51
|
|
|
48
52
|
contentInsetAdjustmentBehavior = .never // <SafeAreaView> handles it, or the prop
|
|
49
53
|
alwaysBounceVertical = true
|
|
54
|
+
// UIKit holds a touch for 150ms to see if it scrolls: a quick tap on a device would send pressin and
|
|
55
|
+
// pressout together, and the pressed style never shows. touchesShouldCancel still lets drags scroll.
|
|
56
|
+
delaysContentTouches = false
|
|
50
57
|
|
|
51
58
|
let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:)))
|
|
52
59
|
tapRecognizer.cancelsTouchesInView = false // buttons inside still receive their taps
|
|
53
60
|
addGestureRecognizer(tapRecognizer)
|
|
61
|
+
|
|
62
|
+
NotificationCenter.default.addObserver(
|
|
63
|
+
self,
|
|
64
|
+
selector: #selector(keyboardWillChangeFrame(_:)),
|
|
65
|
+
name: UIResponder.keyboardWillChangeFrameNotification,
|
|
66
|
+
object: nil
|
|
67
|
+
)
|
|
54
68
|
}
|
|
55
69
|
|
|
56
70
|
required init?(coder: NSCoder) {
|
|
@@ -78,6 +92,41 @@ final class VueScrollView: UIScrollView {
|
|
|
78
92
|
true
|
|
79
93
|
}
|
|
80
94
|
|
|
95
|
+
@objc private func keyboardWillChangeFrame(_ notification: Notification) {
|
|
96
|
+
guard
|
|
97
|
+
adjustsForKeyboard,
|
|
98
|
+
window != nil,
|
|
99
|
+
let keyboardFrame = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
|
|
100
|
+
else { return }
|
|
101
|
+
|
|
102
|
+
// In content coordinates, like bounds. The safe area the system already insets isn't counted twice.
|
|
103
|
+
let keyboardTop = convert(keyboardFrame, from: nil).minY
|
|
104
|
+
let systemBottomInset = adjustedContentInset.bottom - contentInset.bottom
|
|
105
|
+
let keyboardInset = max(0, bounds.maxY - keyboardTop - systemBottomInset)
|
|
106
|
+
|
|
107
|
+
UIView.animateAlongsideKeyboard(notification) { [self] in
|
|
108
|
+
contentInset.bottom = keyboardInset
|
|
109
|
+
verticalScrollIndicatorInsets.bottom = keyboardInset
|
|
110
|
+
contentOffset.y = offsetRevealing(focusedInput(in: self), above: keyboardTop)
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/// Scrolls up just enough for `input` to sit above the keyboard; when the keyboard leaves, back within the content.
|
|
115
|
+
private func offsetRevealing(_ input: UIView?, above keyboardTop: CGFloat) -> CGFloat {
|
|
116
|
+
let maximumOffset = max(-adjustedContentInset.top, contentSize.height + adjustedContentInset.bottom - bounds.height)
|
|
117
|
+
guard let input else { return min(contentOffset.y, maximumOffset) }
|
|
118
|
+
|
|
119
|
+
let inputBottom = input.convert(input.bounds, to: self).maxY
|
|
120
|
+
|
|
121
|
+
return min(contentOffset.y + max(0, inputBottom - keyboardTop), maximumOffset)
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
private func focusedInput(in view: UIView) -> UIView? {
|
|
125
|
+
if view.isFirstResponder { return view }
|
|
126
|
+
|
|
127
|
+
return view.subviews.lazy.compactMap(focusedInput(in:)).first
|
|
128
|
+
}
|
|
129
|
+
|
|
81
130
|
@objc private func handleTap(_ recognizer: UITapGestureRecognizer) {
|
|
82
131
|
guard dismissesKeyboardOnTap else { return }
|
|
83
132
|
|
package/package.json
CHANGED
package/src/components.ts
CHANGED
|
@@ -3,7 +3,9 @@ import {
|
|
|
3
3
|
computed,
|
|
4
4
|
defineComponent,
|
|
5
5
|
h,
|
|
6
|
+
onBeforeUnmount,
|
|
6
7
|
ref,
|
|
8
|
+
watch,
|
|
7
9
|
type PropType,
|
|
8
10
|
type SlotsType,
|
|
9
11
|
type VNode,
|
|
@@ -12,25 +14,56 @@ import type { ScrollEvent, Style } from './types'
|
|
|
12
14
|
|
|
13
15
|
type Listener = ((payload: unknown) => void) | undefined
|
|
14
16
|
|
|
17
|
+
const MINIMUM_PRESSED_TIME = 130 // ms
|
|
18
|
+
|
|
15
19
|
// Vue's template compiler normalizes `:style`, so it can't be a function of the pressed state: the pressed
|
|
16
20
|
// look goes in `pressed-style`, merged over `style` while pressed. The slot also receives { pressed },
|
|
17
|
-
// and the class its pressed styles (Tailwind's active:).
|
|
21
|
+
// and the class its pressed styles (Tailwind's active:). A disabled one ignores touches.
|
|
18
22
|
export const Pressable = defineComponent({
|
|
19
23
|
name: 'Pressable',
|
|
20
24
|
inheritAttrs: false,
|
|
21
|
-
props: {
|
|
25
|
+
props: {
|
|
26
|
+
style: Object as PropType<Style>,
|
|
27
|
+
pressedStyle: Object as PropType<Style>,
|
|
28
|
+
disabled: Boolean,
|
|
29
|
+
},
|
|
22
30
|
slots: Object as SlotsType<{ default: { pressed: boolean } }>,
|
|
23
31
|
|
|
24
32
|
setup(props, { attrs, slots }) {
|
|
25
33
|
const pressed = ref(false)
|
|
34
|
+
let pressedAt = 0
|
|
35
|
+
let releaseTimeout: ReturnType<typeof setTimeout> | undefined
|
|
26
36
|
|
|
27
|
-
function
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
listener?.(payload)
|
|
31
|
-
}
|
|
37
|
+
function release() {
|
|
38
|
+
clearTimeout(releaseTimeout)
|
|
39
|
+
pressed.value = false
|
|
32
40
|
}
|
|
33
41
|
|
|
42
|
+
// Disabled mid-press, the native view may never send the pressout.
|
|
43
|
+
watch(
|
|
44
|
+
() => props.disabled,
|
|
45
|
+
(disabled) => {
|
|
46
|
+
if (disabled) release()
|
|
47
|
+
},
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
function handlePressIn(payload: unknown) {
|
|
51
|
+
clearTimeout(releaseTimeout)
|
|
52
|
+
pressedAt = Date.now()
|
|
53
|
+
pressed.value = true
|
|
54
|
+
;(attrs.onPressIn as Listener)?.(payload)
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// A quick tap would show the pressed style for less than a frame: keep it for a moment.
|
|
58
|
+
function handlePressOut(payload: unknown) {
|
|
59
|
+
const remainingTime = MINIMUM_PRESSED_TIME - (Date.now() - pressedAt)
|
|
60
|
+
|
|
61
|
+
releaseTimeout = setTimeout(release, Math.max(0, remainingTime))
|
|
62
|
+
;(attrs.onPressOut as Listener)?.(payload)
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
onBeforeUnmount(() => clearTimeout(releaseTimeout))
|
|
66
|
+
|
|
34
67
|
return () => {
|
|
35
68
|
const style = pressed.value ? { ...props.style, ...props.pressedStyle } : props.style
|
|
36
69
|
|
|
@@ -40,8 +73,9 @@ export const Pressable = defineComponent({
|
|
|
40
73
|
...attrs,
|
|
41
74
|
style,
|
|
42
75
|
pressed: pressed.value,
|
|
43
|
-
|
|
44
|
-
|
|
76
|
+
disabled: props.disabled || undefined, // unset, nothing to send
|
|
77
|
+
onPressIn: handlePressIn,
|
|
78
|
+
onPressOut: handlePressOut,
|
|
45
79
|
},
|
|
46
80
|
slots.default?.({ pressed: pressed.value }),
|
|
47
81
|
)
|
|
@@ -57,6 +91,8 @@ const OFFSCREEN_ROWS_RENDERED = 10
|
|
|
57
91
|
// variable heights are ever needed. Vertical only. The window ignores the header's height, which the
|
|
58
92
|
// offscreen rows absorb while the header is shorter than them; measure it if tall headers show gaps.
|
|
59
93
|
// ponytail: items are `any` in the #item slot; make FlatList generic if typed rows are wanted.
|
|
94
|
+
// ponytail: an Animated.event `:on-scroll` replaces the window's own scroll handler, and a mapped event
|
|
95
|
+
// reaches JS only when a scroll starts and ends; report frames to both natively if that's needed.
|
|
60
96
|
export const FlatList = defineComponent({
|
|
61
97
|
name: 'FlatList',
|
|
62
98
|
props: {
|
package/src/fetch.ts
CHANGED
|
@@ -96,7 +96,10 @@ function fetch(
|
|
|
96
96
|
}
|
|
97
97
|
|
|
98
98
|
globalThis.__fetchFinished = (requestId, response, errorMessage) => {
|
|
99
|
-
const
|
|
99
|
+
const request = pendingRequestsById.get(requestId)
|
|
100
|
+
if (!request) return
|
|
101
|
+
|
|
102
|
+
const { resolve, reject, url } = request
|
|
100
103
|
pendingRequestsById.delete(requestId)
|
|
101
104
|
|
|
102
105
|
if (errorMessage || !response) reject(new TypeError(`Network request failed: ${errorMessage}`))
|
package/src/native-components.ts
CHANGED
|
@@ -36,6 +36,8 @@ declare module '@vue/runtime-core' {
|
|
|
36
36
|
keyboardDismissMode?: 'none' | 'on-drag' | 'interactive'
|
|
37
37
|
keyboardShouldPersistTaps?: 'never' | 'always' | 'handled'
|
|
38
38
|
contentInsetAdjustmentBehavior?: 'automatic' | 'scrollableAxes' | 'never' | 'always'
|
|
39
|
+
/** The keyboard insets the content, and the focused input scrolls above it. */
|
|
40
|
+
automaticallyAdjustKeyboardInsets?: boolean
|
|
39
41
|
onScroll?: EventHandler<ScrollEvent>
|
|
40
42
|
onRefresh?: () => void
|
|
41
43
|
}>
|
|
@@ -46,7 +48,12 @@ declare module '@vue/runtime-core' {
|
|
|
46
48
|
keyboardType?: 'default' | 'numeric' | 'decimal-pad' | 'email-address' | 'phone-pad' | 'url'
|
|
47
49
|
secureTextEntry?: boolean
|
|
48
50
|
onChangeText?: (text: string) => void
|
|
51
|
+
disabled?: boolean
|
|
49
52
|
onSubmitEditing?: (text: string) => void
|
|
53
|
+
onFocus?: () => void
|
|
54
|
+
onBlur?: () => void
|
|
55
|
+
/** Merged over `style` while the input has focus. */
|
|
56
|
+
focusedStyle?: Style
|
|
50
57
|
}
|
|
51
58
|
>
|
|
52
59
|
Image: NativeComponent<{
|
package/src/renderer.ts
CHANGED
|
@@ -39,22 +39,28 @@ interface Node {
|
|
|
39
39
|
children: Node[]
|
|
40
40
|
text: string
|
|
41
41
|
style?: Style | null
|
|
42
|
+
/** <TextInput focused-style>: merged over `style` while the input has focus. */
|
|
43
|
+
focusedStyle?: Style | null
|
|
42
44
|
className?: string
|
|
43
|
-
/**
|
|
45
|
+
/** The states its class's styles may depend on (Tailwind's active:, focus:, disabled:). */
|
|
44
46
|
pressed?: boolean
|
|
47
|
+
focused?: boolean
|
|
48
|
+
disabled?: boolean
|
|
45
49
|
classStyle?: Style
|
|
46
50
|
}
|
|
47
51
|
|
|
52
|
+
type ElementState = Pick<Node, 'pressed' | 'focused' | 'disabled'>
|
|
53
|
+
|
|
48
54
|
type EventHandler = (payload: unknown) => void
|
|
49
|
-
type ClassStyleResolver = (className: string, state:
|
|
55
|
+
type ClassStyleResolver = (className: string, state: Required<ElementState>) => Style
|
|
50
56
|
|
|
51
57
|
const native = globalThis.__native
|
|
52
58
|
let nextNodeId = 1
|
|
53
|
-
// ponytail: handlers of removed nodes are never cleaned up; clean them on remove when it matters.
|
|
54
59
|
const eventHandlersByNodeId: Record<number, Record<string, EventHandler | undefined>> = {}
|
|
55
60
|
let resolveClassStyle: ClassStyleResolver | null = null
|
|
56
|
-
// ponytail: a removed node leaves the set, its descendants stay; track them if apps churn many.
|
|
57
61
|
const nodesWithClass = new Set<Node>()
|
|
62
|
+
// For their focus state (focus:), which arrives as events by id.
|
|
63
|
+
const textInputsById = new Map<number, Node>()
|
|
58
64
|
|
|
59
65
|
/**
|
|
60
66
|
* Gives `class` its styles, for a nativue.config plugin (@nativue/tailwind). Class styles may depend
|
|
@@ -73,6 +79,19 @@ function isNativeNode(node: Node): boolean {
|
|
|
73
79
|
return !node.type.startsWith('#')
|
|
74
80
|
}
|
|
75
81
|
|
|
82
|
+
// Vue removes only the root of an unmounted subtree: its descendants go with it.
|
|
83
|
+
function forgetSubtree(node: Node) {
|
|
84
|
+
nodesWithClass.delete(node)
|
|
85
|
+
textInputsById.delete(node.id)
|
|
86
|
+
delete eventHandlersByNodeId[node.id]
|
|
87
|
+
node.children.forEach(forgetSubtree)
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// As the native side reads boolean props: a bare attribute (`disabled`) is '', true.
|
|
91
|
+
function isTruthyAttribute(value: unknown): boolean {
|
|
92
|
+
return typeof value === 'string' ? value !== 'false' : value === true
|
|
93
|
+
}
|
|
94
|
+
|
|
76
95
|
function isEventProp(key: string): boolean {
|
|
77
96
|
return /^on[A-Z]/.test(key)
|
|
78
97
|
}
|
|
@@ -143,19 +162,27 @@ function withoutAnimatedProperties(
|
|
|
143
162
|
|
|
144
163
|
// The class's styles come first, so the style prop overrides them, as inline styles do on the web.
|
|
145
164
|
function combinedStyle(element: Node): Style | null {
|
|
146
|
-
|
|
165
|
+
const focusedStyle = element.focused ? element.focusedStyle : null
|
|
166
|
+
if (!element.classStyle && !focusedStyle) return element.style ?? null
|
|
147
167
|
|
|
148
|
-
return { ...element.classStyle, ...element.style }
|
|
168
|
+
return { ...element.classStyle, ...element.style, ...focusedStyle }
|
|
149
169
|
}
|
|
150
170
|
|
|
151
171
|
function classStyleOf(element: Node): Style | undefined {
|
|
152
172
|
if (!element.className || !resolveClassStyle) return undefined
|
|
153
173
|
|
|
154
|
-
return resolveClassStyle(element.className, {
|
|
174
|
+
return resolveClassStyle(element.className, {
|
|
175
|
+
pressed: element.pressed ?? false,
|
|
176
|
+
focused: element.focused ?? false,
|
|
177
|
+
disabled: element.disabled ?? false,
|
|
178
|
+
})
|
|
155
179
|
}
|
|
156
180
|
|
|
157
|
-
/** Applies a change to what makes up the style (style, class,
|
|
158
|
-
function updateStyle(
|
|
181
|
+
/** Applies a change to what makes up the style (style, class, state), sending only the diff. */
|
|
182
|
+
function updateStyle(
|
|
183
|
+
element: Node,
|
|
184
|
+
change: Pick<Node, 'style' | 'focusedStyle' | 'className'> & ElementState,
|
|
185
|
+
) {
|
|
159
186
|
const previousStyle = combinedStyle(element)
|
|
160
187
|
|
|
161
188
|
Object.assign(element, change)
|
|
@@ -231,6 +258,7 @@ const { createApp: createBaseApp } = createRenderer<Node, Node>({
|
|
|
231
258
|
createElement(type) {
|
|
232
259
|
const element = createNode(type)
|
|
233
260
|
native.create(element.id, type)
|
|
261
|
+
if (type === 'TextInput') textInputsById.set(element.id, element)
|
|
234
262
|
|
|
235
263
|
return element
|
|
236
264
|
},
|
|
@@ -269,7 +297,7 @@ const { createApp: createBaseApp } = createRenderer<Node, Node>({
|
|
|
269
297
|
|
|
270
298
|
remove(child) {
|
|
271
299
|
const parent = detachFromParent(child)
|
|
272
|
-
|
|
300
|
+
forgetSubtree(child)
|
|
273
301
|
|
|
274
302
|
if (isNativeNode(child)) native.remove(child.id)
|
|
275
303
|
else syncTextContent(parent)
|
|
@@ -289,6 +317,11 @@ const { createApp: createBaseApp } = createRenderer<Node, Node>({
|
|
|
289
317
|
if (key === 'style') updateStyle(element, { style: nextValue })
|
|
290
318
|
else if (key === 'class') updateStyle(element, { className: nextValue ?? undefined })
|
|
291
319
|
else if (key === 'pressed') updateStyle(element, { pressed: nextValue })
|
|
320
|
+
else if (camelize(key) === 'focusedStyle') updateStyle(element, { focusedStyle: nextValue })
|
|
321
|
+
else if (key === 'disabled') {
|
|
322
|
+
updateStyle(element, { disabled: isTruthyAttribute(nextValue) })
|
|
323
|
+
native.setProp(element.id, key, nextValue ?? null)
|
|
324
|
+
}
|
|
292
325
|
// :on-pan="..." (v-bind, used for Animated.event) arrives kebab-case.
|
|
293
326
|
else if (isEventProp(camelize(key))) {
|
|
294
327
|
patchEventHandler(element, camelize(key), previousValue, nextValue, component ?? null)
|
|
@@ -304,6 +337,8 @@ const MODEL_EVENT_BY_NATIVE_EVENT: Record<string, string> = {
|
|
|
304
337
|
}
|
|
305
338
|
|
|
306
339
|
globalThis.__dispatch = (nodeId, eventName, payload) => {
|
|
340
|
+
updateFocus(nodeId, eventName)
|
|
341
|
+
|
|
307
342
|
const handlers = eventHandlersByNodeId[nodeId]
|
|
308
343
|
if (!handlers) return
|
|
309
344
|
|
|
@@ -311,6 +346,14 @@ globalThis.__dispatch = (nodeId, eventName, payload) => {
|
|
|
311
346
|
handlers[MODEL_EVENT_BY_NATIVE_EVENT[eventName]]?.(payload)
|
|
312
347
|
}
|
|
313
348
|
|
|
349
|
+
// A <TextInput>'s focus, for its class's focus: styles and its focused-style.
|
|
350
|
+
function updateFocus(nodeId: number, eventName: string) {
|
|
351
|
+
const textInput = textInputsById.get(nodeId)
|
|
352
|
+
if (!textInput || (eventName !== 'focus' && eventName !== 'blur')) return
|
|
353
|
+
|
|
354
|
+
updateStyle(textInput, { focused: eventName === 'focus' })
|
|
355
|
+
}
|
|
356
|
+
|
|
314
357
|
const LAYOUT_ANIMATION_PRESETS = {
|
|
315
358
|
easeInEaseOut: { type: 'easeInEaseOut', duration: 300 },
|
|
316
359
|
linear: { type: 'linear', duration: 500 },
|
package/src/router.ts
CHANGED
|
@@ -250,19 +250,29 @@ function matchSegments(segments: Segment[], pathParts: string[]): Params | null
|
|
|
250
250
|
const part = pathParts[index]
|
|
251
251
|
if (part === undefined) return null
|
|
252
252
|
|
|
253
|
-
if (segment.type === 'param') params[segment.name] =
|
|
253
|
+
if (segment.type === 'param') params[segment.name] = decodeURIComponentSafely(part)
|
|
254
254
|
else if (segment.name !== part) return null
|
|
255
255
|
}
|
|
256
256
|
|
|
257
257
|
return segments.length === pathParts.length ? params : null
|
|
258
258
|
}
|
|
259
259
|
|
|
260
|
+
// Links come from other apps too: a malformed escape (%E0%A4) is kept as it is, not thrown.
|
|
261
|
+
function decodeURIComponentSafely(text: string): string {
|
|
262
|
+
try {
|
|
263
|
+
return decodeURIComponent(text.replaceAll('+', ' '))
|
|
264
|
+
} catch {
|
|
265
|
+
return text
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
260
269
|
function parseQuery(query = ''): Params {
|
|
261
270
|
const params: Params = {}
|
|
262
271
|
|
|
263
272
|
for (const pair of query.split('&').filter(Boolean)) {
|
|
264
|
-
const
|
|
265
|
-
|
|
273
|
+
const separatorIndex = pair.includes('=') ? pair.indexOf('=') : pair.length // ?token=abc== keeps its ==
|
|
274
|
+
const key = pair.slice(0, separatorIndex)
|
|
275
|
+
params[decodeURIComponentSafely(key)] = decodeURIComponentSafely(pair.slice(separatorIndex + 1))
|
|
266
276
|
}
|
|
267
277
|
|
|
268
278
|
return params
|
|
@@ -304,7 +314,10 @@ function childNodesOf(layout: RouteNode): RouteNode[] {
|
|
|
304
314
|
// Where a layout starts when opened without a destination: its index page.
|
|
305
315
|
function initialRouteOf(layout: LayoutNode): Route {
|
|
306
316
|
const descendants = pages.filter((page) => page.layouts.includes(layout))
|
|
307
|
-
const page =
|
|
317
|
+
const page =
|
|
318
|
+
descendants.find(
|
|
319
|
+
(candidate) => candidate.layouts.at(-1) === layout && candidate.name === 'index',
|
|
320
|
+
) ?? descendants[0]
|
|
308
321
|
|
|
309
322
|
return {
|
|
310
323
|
chain: [...page.layouts.slice(page.layouts.indexOf(layout) + 1), page],
|
|
@@ -467,13 +480,30 @@ export function useRouter() {
|
|
|
467
480
|
return router
|
|
468
481
|
}
|
|
469
482
|
|
|
470
|
-
|
|
483
|
+
function injectPageEntry(hookName: string): Entry {
|
|
484
|
+
const entry = inject(ENTRY_KEY, null)
|
|
485
|
+
if (!entry) throw new Error(`${hookName}() works in a page, not in a _layout.vue`)
|
|
486
|
+
|
|
487
|
+
return entry
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
// Type the params you expect: useLocalSearchParams<{ id: string }>(). Reactive: a tab opened again
|
|
491
|
+
// with other params (router.navigate('/search?q=shoes')) updates it.
|
|
471
492
|
export function useLocalSearchParams<RouteParams extends Params = Params>(): RouteParams {
|
|
472
|
-
|
|
493
|
+
const entry = injectPageEntry('useLocalSearchParams')
|
|
494
|
+
|
|
495
|
+
// Reads through to the entry's current params, which navigation may replace.
|
|
496
|
+
return new Proxy({} as RouteParams, {
|
|
497
|
+
get: (_target, key) => Reflect.get(entry.params, key),
|
|
498
|
+
has: (_target, key) => Reflect.has(entry.params, key),
|
|
499
|
+
ownKeys: () => Reflect.ownKeys(entry.params),
|
|
500
|
+
getOwnPropertyDescriptor: (_target, key) => Reflect.getOwnPropertyDescriptor(entry.params, key),
|
|
501
|
+
})
|
|
473
502
|
}
|
|
474
503
|
|
|
504
|
+
// ponytail: the path when the page opened; make it a ref if pages need to follow in-place navigation.
|
|
475
505
|
export function usePathname(): string {
|
|
476
|
-
return
|
|
506
|
+
return injectPageEntry('usePathname').href.split('?')[0]
|
|
477
507
|
}
|
|
478
508
|
|
|
479
509
|
// Whether this screen is the one on screen: on top of its stack (or the selected tab), inside a
|