@nativue/core 0.4.3 → 0.4.5
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 +57 -18
- package/android/src/main/java/dev/nativue/NativeNode.kt +8 -1
- package/android/src/main/java/dev/nativue/Style.kt +23 -6
- package/android/src/main/java/dev/nativue/Views.kt +137 -13
- package/ios/Bridge.swift +60 -11
- package/ios/ImageView.swift +133 -10
- package/ios/NativeNode.swift +10 -0
- package/ios/ScreenStackView.swift +7 -0
- package/ios/Style.swift +24 -8
- package/package.json +1 -1
- package/src/components.ts +103 -39
- package/src/globals.ts +2 -1
- package/src/list-window.ts +23 -0
- package/src/native-components.ts +6 -2
- package/src/renderer.ts +66 -7
- package/src/types.ts +10 -1
|
@@ -68,6 +68,8 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
|
|
|
68
68
|
private val animatedGraph = AnimatedGraph()
|
|
69
69
|
private val modalHostsByNodeId = HashMap<Int, ModalHost>()
|
|
70
70
|
private val gestureReportersByNodeId = HashMap<Int, GestureReporter>()
|
|
71
|
+
/** Views with @layout, and the box they last reported. */
|
|
72
|
+
private val reportedLayoutsByNodeId = mutableMapOf<Int, Map<String, Float>?>()
|
|
71
73
|
|
|
72
74
|
/** The latest window insets, mid-animation while the keyboard moves. */
|
|
73
75
|
private var windowInsets: WindowInsets? = null
|
|
@@ -82,6 +84,7 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
|
|
|
82
84
|
fun start() {
|
|
83
85
|
NativeNode.setPixelDensity(density)
|
|
84
86
|
rootView.onLayoutPass = ::layout
|
|
87
|
+
NativeNode.onLayoutCalculated = ::reportLayoutChanges
|
|
85
88
|
rootView.setOnApplyWindowInsetsListener { view, insets ->
|
|
86
89
|
windowInsets = insets
|
|
87
90
|
view.requestLayout() // safe area and keyboard paddings
|
|
@@ -340,7 +343,8 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
|
|
|
340
343
|
}
|
|
341
344
|
put("remove") { arguments ->
|
|
342
345
|
val id = int(arguments[0])
|
|
343
|
-
|
|
346
|
+
val subtreeIds = (arguments[1] as List<*>).map(::int)
|
|
347
|
+
enqueue { removeNode(id, subtreeIds) }
|
|
344
348
|
}
|
|
345
349
|
put("setText") { arguments ->
|
|
346
350
|
val id = int(arguments[0])
|
|
@@ -536,24 +540,20 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
|
|
|
536
540
|
// ---------- Main thread ----------
|
|
537
541
|
|
|
538
542
|
/** Vue removes only a subtree's root: the nodes under it are forgotten with it. */
|
|
539
|
-
private fun removeNode(
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
root.contentNode?.let { collectViews(it.view, removedViews) }
|
|
543
|
-
|
|
544
|
-
// Limitation: A nested <Modal>'s content isn't under the root's views, so its nodes stay; walk the
|
|
545
|
-
// modal hosts too if apps nest many. Hosts stay: layout dismisses the detached ones.
|
|
546
|
-
val removedIds = nodesById.filterValues { it.view in removedViews }.keys
|
|
547
|
-
removedIds.forEach { id ->
|
|
548
|
-
nodesById.remove(id)
|
|
549
|
-
gestureReportersByNodeId.remove(id)
|
|
550
|
-
}
|
|
551
|
-
root.removeFromParent()
|
|
543
|
+
private fun removeNode(id: Int, subtreeIds: List<Int>) {
|
|
544
|
+
nodesById[id]?.removeFromParent()
|
|
545
|
+
subtreeIds.forEach(::forgetNode)
|
|
552
546
|
}
|
|
553
547
|
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
548
|
+
/** Its view left the tree: what refers to it by id goes too, and a modal inside closes. */
|
|
549
|
+
private fun forgetNode(id: Int) {
|
|
550
|
+
nodesById.remove(id)
|
|
551
|
+
gestureReportersByNodeId.remove(id)
|
|
552
|
+
reportedLayoutsByNodeId.remove(id)
|
|
553
|
+
modalHostsByNodeId.remove(id)?.let {
|
|
554
|
+
it.onEvent = {} // its "dismiss" would reach a node JS has forgotten
|
|
555
|
+
it.setVisible(false)
|
|
556
|
+
}
|
|
557
557
|
}
|
|
558
558
|
|
|
559
559
|
private fun resetNodeTree() {
|
|
@@ -563,6 +563,7 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
|
|
|
563
563
|
}
|
|
564
564
|
modalHostsByNodeId.clear()
|
|
565
565
|
gestureReportersByNodeId.clear() // node ids start over
|
|
566
|
+
reportedLayoutsByNodeId.clear()
|
|
566
567
|
animatedGraph.reset()
|
|
567
568
|
animatedGraph.onAnimationEnd = { animationId, finished ->
|
|
568
569
|
evaluate { runtime?.call("__animationFinished", animationId, finished) }
|
|
@@ -632,7 +633,15 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
|
|
|
632
633
|
}
|
|
633
634
|
}
|
|
634
635
|
|
|
635
|
-
"Image" ->
|
|
636
|
+
"Image" -> {
|
|
637
|
+
val imageView = RemoteImageView(activity)
|
|
638
|
+
NativeNode(imageView, measuresContent = true).also { node ->
|
|
639
|
+
imageView.onImageChange = {
|
|
640
|
+
node.markContentChanged()
|
|
641
|
+
rootView.requestLayout()
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
}
|
|
636
645
|
|
|
637
646
|
"SwipeableView" -> NativeNode(SwipeableView(activity), measuresContent = false)
|
|
638
647
|
|
|
@@ -722,6 +731,31 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
|
|
|
722
731
|
node.yogaNode.setHeight(side)
|
|
723
732
|
}
|
|
724
733
|
|
|
734
|
+
/**
|
|
735
|
+
* @layout fires for the views whose box changed: { x, y, width, height }, in dp, in its parent.
|
|
736
|
+
* All of a layout pass's changes go in one call, so JS re-renders once for them, not once per view.
|
|
737
|
+
*/
|
|
738
|
+
private fun reportLayoutChanges() {
|
|
739
|
+
val changedLayouts = mutableListOf<Map<String, Any>>()
|
|
740
|
+
|
|
741
|
+
for ((id, reportedLayout) in reportedLayoutsByNodeId) {
|
|
742
|
+
val yogaNode = nodesById[id]?.yogaNode ?: continue
|
|
743
|
+
val layout = mapOf(
|
|
744
|
+
"x" to yogaNode.layoutX,
|
|
745
|
+
"y" to yogaNode.layoutY,
|
|
746
|
+
"width" to yogaNode.layoutWidth,
|
|
747
|
+
"height" to yogaNode.layoutHeight,
|
|
748
|
+
)
|
|
749
|
+
if (yogaNode.layoutWidth.isNaN() || layout == reportedLayout) continue
|
|
750
|
+
|
|
751
|
+
reportedLayoutsByNodeId[id] = layout
|
|
752
|
+
changedLayouts.add(layout + ("id" to id))
|
|
753
|
+
}
|
|
754
|
+
if (changedLayouts.isEmpty()) return
|
|
755
|
+
|
|
756
|
+
evaluate { runtime?.call("__layoutsChanged", changedLayouts) }
|
|
757
|
+
}
|
|
758
|
+
|
|
725
759
|
private fun dispatchEvent(eventName: String, id: Int, payload: Any? = null) {
|
|
726
760
|
evaluate { runtime?.call("__dispatch", id, eventName, payload) }
|
|
727
761
|
}
|
|
@@ -807,6 +841,10 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
|
|
|
807
841
|
|
|
808
842
|
"showsVerticalScrollIndicator" -> (view as? ScrollContainerView)?.showsVerticalScrollIndicator = isTruthyAttribute(value)
|
|
809
843
|
|
|
844
|
+
// A new handler on every render re-registers: only a first one waits for a report.
|
|
845
|
+
"onLayout" -> if (!isTruthyAttribute(value)) reportedLayoutsByNodeId.remove(id)
|
|
846
|
+
else if (id !in reportedLayoutsByNodeId) reportedLayoutsByNodeId[id] = null
|
|
847
|
+
|
|
810
848
|
"onScroll" -> (view as? ScrollContainerView)?.onScroll = if (isTruthyAttribute(value)) reportScroll(node, id) else null
|
|
811
849
|
|
|
812
850
|
"value" -> {
|
|
@@ -856,6 +894,7 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
|
|
|
856
894
|
|
|
857
895
|
"source" -> (view as? RemoteImageView)?.load(value as? String)
|
|
858
896
|
|
|
897
|
+
"cache" -> (view as? RemoteImageView)?.cachePolicy = value as? String ?: "disk"
|
|
859
898
|
"resizeMode" -> (view as? RemoteImageView)?.scaleType = RemoteImageView.scaleTypes[value] ?: ImageView.ScaleType.CENTER_CROP
|
|
860
899
|
|
|
861
900
|
"onLongPress" -> (view as? PressableView)?.reportsLongPress = isTruthyAttribute(value)
|
|
@@ -21,7 +21,7 @@ class NativeNode(val view: View, measuresContent: Boolean) {
|
|
|
21
21
|
/** Where children go when it isn't this node: a <Modal>'s live in a separate Yoga root. */
|
|
22
22
|
var contentNode: NativeNode? = null
|
|
23
23
|
|
|
24
|
-
var fontSize =
|
|
24
|
+
var fontSize = DEFAULT_FONT_SIZE
|
|
25
25
|
var fontWeight = 400
|
|
26
26
|
|
|
27
27
|
/** WindowInsets types that pad this node (safe area, keyboard), 0 for none, and the last padding. */
|
|
@@ -61,6 +61,7 @@ class NativeNode(val view: View, measuresContent: Boolean) {
|
|
|
61
61
|
fun calculateLayout(width: Float, height: Float) {
|
|
62
62
|
yogaNode.calculateLayout(width, height)
|
|
63
63
|
applyFrames()
|
|
64
|
+
onLayoutCalculated()
|
|
64
65
|
}
|
|
65
66
|
|
|
66
67
|
/** Only visits subtrees Yoga laid out again; untouched subtrees keep their frames. */
|
|
@@ -150,7 +151,13 @@ class NativeNode(val view: View, measuresContent: Boolean) {
|
|
|
150
151
|
companion object {
|
|
151
152
|
private val yogaConfig = YogaConfigFactory.create()
|
|
152
153
|
|
|
154
|
+
/** After every layout pass, of the root or of a modal's content: for @layout. */
|
|
155
|
+
var onLayoutCalculated: () -> Unit = {}
|
|
156
|
+
|
|
153
157
|
/** Rounds layouts to whole pixels; set before the first node is laid out. */
|
|
154
158
|
fun setPixelDensity(density: Float) = yogaConfig.setPointScaleFactor(density)
|
|
155
159
|
}
|
|
156
160
|
}
|
|
161
|
+
|
|
162
|
+
/** The platform's body text size, which a removed fontSize goes back to. */
|
|
163
|
+
const val DEFAULT_FONT_SIZE = 17f
|
|
@@ -17,14 +17,15 @@ import com.facebook.yoga.YogaOverflow
|
|
|
17
17
|
import com.facebook.yoga.YogaPositionType
|
|
18
18
|
import com.facebook.yoga.YogaWrap
|
|
19
19
|
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
20
|
+
/**
|
|
21
|
+
* Receives only the properties that changed: the JS renderer diffs style objects before sending. A removed
|
|
22
|
+
* property arrives as null and goes back to its default, as in CSS.
|
|
23
|
+
*/
|
|
23
24
|
fun NativeNode.applyStyle(changes: Map<String, Any?>) {
|
|
24
25
|
for ((property, value) in changes) {
|
|
25
26
|
if (isDrivenByInsets(property)) continue
|
|
26
27
|
|
|
27
|
-
|
|
28
|
+
layoutPropertySetters[property]?.invoke(yogaNode, value ?: layoutDefaults[property] ?: Float.NaN)
|
|
28
29
|
// Some properties are both: overflow also clips the view.
|
|
29
30
|
applyVisualProperty(property, value)
|
|
30
31
|
}
|
|
@@ -107,8 +108,8 @@ private fun degrees(value: Any?): Float {
|
|
|
107
108
|
|
|
108
109
|
/** Font size and weight can change independently, so the node remembers both. */
|
|
109
110
|
private fun NativeNode.applyFont(changes: Map<String, Any?>) {
|
|
110
|
-
number(changes["fontSize"])
|
|
111
|
-
|
|
111
|
+
if ("fontSize" in changes) fontSize = number(changes["fontSize"]) ?: DEFAULT_FONT_SIZE
|
|
112
|
+
if ("fontWeight" in changes) fontWeight = changes["fontWeight"]?.let(::fontWeightOf) ?: 400
|
|
112
113
|
|
|
113
114
|
val textView = view as? TextView ?: return
|
|
114
115
|
textView.typeface = Typeface.create(Typeface.DEFAULT, fontWeight, false)
|
|
@@ -220,6 +221,22 @@ private val textGravities = mapOf(
|
|
|
220
221
|
|
|
221
222
|
private typealias LayoutPropertySetter = (YogaNode, Any) -> Unit
|
|
222
223
|
|
|
224
|
+
/** What a removed property goes back to: Yoga's defaults. The others are undefined (NaN, unset). */
|
|
225
|
+
private val layoutDefaults = mapOf(
|
|
226
|
+
"flexDirection" to "column",
|
|
227
|
+
"justifyContent" to "flex-start",
|
|
228
|
+
"alignItems" to "stretch",
|
|
229
|
+
"alignSelf" to "auto",
|
|
230
|
+
"alignContent" to "flex-start",
|
|
231
|
+
"flexWrap" to "nowrap",
|
|
232
|
+
"position" to "relative",
|
|
233
|
+
"display" to "flex",
|
|
234
|
+
"overflow" to "visible",
|
|
235
|
+
"flexBasis" to "auto",
|
|
236
|
+
"width" to "auto",
|
|
237
|
+
"height" to "auto",
|
|
238
|
+
)
|
|
239
|
+
|
|
223
240
|
private val layoutPropertySetters: Map<String, LayoutPropertySetter> = buildMap {
|
|
224
241
|
put("flexDirection", enumSetter(flexDirections, YogaNode::setFlexDirection))
|
|
225
242
|
put("justifyContent", enumSetter(justifications, YogaNode::setJustifyContent))
|
|
@@ -8,6 +8,7 @@ import android.graphics.Rect
|
|
|
8
8
|
import android.os.Handler
|
|
9
9
|
import android.os.Looper
|
|
10
10
|
import android.util.Base64
|
|
11
|
+
import android.util.LruCache
|
|
11
12
|
import android.view.MotionEvent
|
|
12
13
|
import android.view.View
|
|
13
14
|
import android.view.ViewConfiguration
|
|
@@ -19,8 +20,12 @@ import android.widget.ImageView
|
|
|
19
20
|
import android.widget.ProgressBar
|
|
20
21
|
import android.widget.ScrollView
|
|
21
22
|
import android.widget.Switch
|
|
23
|
+
import java.io.File
|
|
22
24
|
import java.net.URL
|
|
23
|
-
import
|
|
25
|
+
import java.security.MessageDigest
|
|
26
|
+
import java.util.concurrent.Executors
|
|
27
|
+
import kotlin.math.min
|
|
28
|
+
import kotlin.math.roundToInt
|
|
24
29
|
import kotlin.math.abs
|
|
25
30
|
|
|
26
31
|
/**
|
|
@@ -216,6 +221,7 @@ class ScrollContainerView(context: Context) : ContainerView(context) {
|
|
|
216
221
|
private var isPullingToRefresh = false
|
|
217
222
|
|
|
218
223
|
init {
|
|
224
|
+
clipChildren = true // like a UIScrollView: scrolled content stays inside the list
|
|
219
225
|
addView(scroller)
|
|
220
226
|
addView(refreshIndicator)
|
|
221
227
|
}
|
|
@@ -484,9 +490,20 @@ private fun pageOffset(offset: Int, pageSize: Int, velocity: Int): Int {
|
|
|
484
490
|
return targetPage.toInt() * pageSize
|
|
485
491
|
}
|
|
486
492
|
|
|
487
|
-
/**
|
|
493
|
+
/**
|
|
494
|
+
* Image view behind <Image>. Loads `data:` URIs (bundled images) and http(s) URLs off the main thread.
|
|
495
|
+
* Mirrors ios/ImageView.swift: with `cache` "disk" (the default), downloads are kept on disk and decoded
|
|
496
|
+
* images in memory; "memory" keeps only the decoded images; "none" keeps nothing.
|
|
497
|
+
*/
|
|
488
498
|
class RemoteImageView(context: Context) : ImageView(context) {
|
|
499
|
+
/** The image changed, and with it the size the view measures. */
|
|
500
|
+
var onImageChange: () -> Unit = {}
|
|
501
|
+
|
|
502
|
+
/** "disk", "memory" or "none". Read when a download finishes, so it applies even when set after `source`. */
|
|
503
|
+
var cachePolicy = "disk"
|
|
504
|
+
|
|
489
505
|
private var source: String? = null
|
|
506
|
+
private var bitmap: Bitmap? = null
|
|
490
507
|
|
|
491
508
|
init {
|
|
492
509
|
scaleType = ScaleType.CENTER_CROP
|
|
@@ -496,25 +513,85 @@ class RemoteImageView(context: Context) : ImageView(context) {
|
|
|
496
513
|
if (source == this.source) return
|
|
497
514
|
|
|
498
515
|
this.source = source
|
|
499
|
-
|
|
500
|
-
if (source == null) return
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
516
|
+
show(if (source != null && cachePolicy != "none") decodedImages.get(source) else null)
|
|
517
|
+
if (source == null || bitmap != null) return
|
|
518
|
+
|
|
519
|
+
val diskCache = ImageDiskCache(context.cacheDir)
|
|
520
|
+
val readsDisk = cachePolicy == "disk"
|
|
521
|
+
loader.execute {
|
|
522
|
+
val cachedBytes = if (readsDisk) diskCache.read(source) else null
|
|
523
|
+
val downloadedBytes = if (cachedBytes == null) runCatching { download(source) }.getOrNull() else null
|
|
524
|
+
val bytes = cachedBytes ?: downloadedBytes ?: return@execute
|
|
525
|
+
val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size) ?: return@execute
|
|
526
|
+
|
|
527
|
+
post {
|
|
528
|
+
store(bitmap, downloadedBytes, source, diskCache)
|
|
529
|
+
if (source == this.source) show(bitmap)
|
|
530
|
+
}
|
|
505
531
|
}
|
|
506
532
|
}
|
|
507
533
|
|
|
508
|
-
private fun
|
|
509
|
-
if (
|
|
510
|
-
|
|
511
|
-
|
|
534
|
+
private fun store(bitmap: Bitmap, downloadedBytes: ByteArray?, source: String, diskCache: ImageDiskCache) {
|
|
535
|
+
if (cachePolicy == "none") return
|
|
536
|
+
|
|
537
|
+
decodedImages.put(source, bitmap)
|
|
538
|
+
if (cachePolicy != "disk" || downloadedBytes == null || source.startsWith("data:")) return
|
|
539
|
+
|
|
540
|
+
loader.execute { diskCache.write(source, downloadedBytes) }
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
private fun show(nextBitmap: Bitmap?) {
|
|
544
|
+
if (nextBitmap === bitmap) return
|
|
545
|
+
|
|
546
|
+
bitmap = nextBitmap
|
|
547
|
+
setImageBitmap(nextBitmap)
|
|
548
|
+
onImageChange()
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
/**
|
|
552
|
+
* Without a width or height, the image takes its own size, a pixel per dp; given one of them, the other
|
|
553
|
+
* follows its aspect ratio, as on the web.
|
|
554
|
+
*/
|
|
555
|
+
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
|
|
556
|
+
val density = resources.displayMetrics.density
|
|
557
|
+
val naturalWidth = (bitmap?.width ?: 0) * density
|
|
558
|
+
val naturalHeight = (bitmap?.height ?: 0) * density
|
|
559
|
+
val widthMode = MeasureSpec.getMode(widthMeasureSpec)
|
|
560
|
+
val heightMode = MeasureSpec.getMode(heightMeasureSpec)
|
|
561
|
+
val width = MeasureSpec.getSize(widthMeasureSpec).toFloat()
|
|
562
|
+
val height = MeasureSpec.getSize(heightMeasureSpec).toFloat()
|
|
563
|
+
val maxWidth = if (widthMode == MeasureSpec.UNSPECIFIED) Float.POSITIVE_INFINITY else width
|
|
564
|
+
val maxHeight = if (heightMode == MeasureSpec.UNSPECIFIED) Float.POSITIVE_INFINITY else height
|
|
565
|
+
val aspectRatio = naturalWidth / naturalHeight
|
|
566
|
+
|
|
567
|
+
val (measuredWidth, measuredHeight) = when {
|
|
568
|
+
widthMode == MeasureSpec.EXACTLY && heightMode == MeasureSpec.EXACTLY -> width to height
|
|
569
|
+
naturalWidth == 0f || naturalHeight == 0f ->
|
|
570
|
+
(if (widthMode == MeasureSpec.EXACTLY) width else 0f) to (if (heightMode == MeasureSpec.EXACTLY) height else 0f)
|
|
571
|
+
widthMode == MeasureSpec.EXACTLY -> width to min(width / aspectRatio, maxHeight)
|
|
572
|
+
heightMode == MeasureSpec.EXACTLY -> min(height * aspectRatio, maxWidth) to height
|
|
573
|
+
else -> {
|
|
574
|
+
val scale = minOf(1f, maxWidth / naturalWidth, maxHeight / naturalHeight)
|
|
575
|
+
naturalWidth * scale to naturalHeight * scale
|
|
576
|
+
}
|
|
512
577
|
}
|
|
578
|
+
setMeasuredDimension(measuredWidth.roundToInt(), measuredHeight.roundToInt())
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
private fun download(source: String): ByteArray {
|
|
582
|
+
if (source.startsWith("data:")) return Base64.decode(source.substringAfter(","), Base64.DEFAULT)
|
|
513
583
|
|
|
514
|
-
return URL(source).openStream().use(
|
|
584
|
+
return URL(source).openStream().use { it.readBytes() }
|
|
515
585
|
}
|
|
516
586
|
|
|
517
587
|
companion object {
|
|
588
|
+
private val loader = Executors.newFixedThreadPool(4)
|
|
589
|
+
|
|
590
|
+
/** Decoded images, an eighth of the app's memory at most: one that comes back on screen shows at once. */
|
|
591
|
+
private val decodedImages = object : LruCache<String, Bitmap>((Runtime.getRuntime().maxMemory() / 8).toInt()) {
|
|
592
|
+
override fun sizeOf(key: String, value: Bitmap) = value.byteCount
|
|
593
|
+
}
|
|
594
|
+
|
|
518
595
|
val scaleTypes = mapOf(
|
|
519
596
|
"cover" to ScaleType.CENTER_CROP,
|
|
520
597
|
"contain" to ScaleType.FIT_CENTER,
|
|
@@ -524,6 +601,53 @@ class RemoteImageView(context: Context) : ImageView(context) {
|
|
|
524
601
|
}
|
|
525
602
|
}
|
|
526
603
|
|
|
604
|
+
/**
|
|
605
|
+
* Downloaded images by url, in the app's cache folder, which Android may empty when storage runs low. Past
|
|
606
|
+
* its limit, the images used least recently go first.
|
|
607
|
+
*/
|
|
608
|
+
private class ImageDiskCache(cacheDirectory: File) {
|
|
609
|
+
private val directory = File(cacheDirectory, "nativue-images")
|
|
610
|
+
|
|
611
|
+
fun read(source: String): ByteArray? {
|
|
612
|
+
val file = fileFor(source)
|
|
613
|
+
if (!file.exists()) return null
|
|
614
|
+
|
|
615
|
+
file.setLastModified(System.currentTimeMillis())
|
|
616
|
+
|
|
617
|
+
return runCatching { file.readBytes() }.getOrNull()
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
fun write(source: String, bytes: ByteArray) {
|
|
621
|
+
directory.mkdirs()
|
|
622
|
+
val partialFile = File(directory, "${fileFor(source).name}.partial")
|
|
623
|
+
partialFile.writeBytes(bytes)
|
|
624
|
+
partialFile.renameTo(fileFor(source)) // whole files only: a reader never sees half an image
|
|
625
|
+
trim()
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
private fun fileFor(source: String): File {
|
|
629
|
+
val hash = MessageDigest.getInstance("SHA-256").digest(source.toByteArray())
|
|
630
|
+
|
|
631
|
+
return File(directory, hash.joinToString("") { "%02x".format(it) })
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
private fun trim() {
|
|
635
|
+
val files = directory.listFiles()?.sortedBy(File::lastModified) ?: return
|
|
636
|
+
var totalSize = files.sumOf(File::length)
|
|
637
|
+
|
|
638
|
+
for (file in files) {
|
|
639
|
+
if (totalSize <= MAX_BYTE_COUNT) break
|
|
640
|
+
|
|
641
|
+
totalSize -= file.length()
|
|
642
|
+
file.delete()
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
companion object {
|
|
647
|
+
const val MAX_BYTE_COUNT = 100L * 1024 * 1024
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
|
|
527
651
|
/** Single-line text field behind <TextInput>. Mirrors ios/TextInputView.swift. */
|
|
528
652
|
class TextInputView(context: Context) : android.widget.EditText(context), ThemeAware {
|
|
529
653
|
/** Without a `color` style, the text follows the theme. */
|
package/ios/Bridge.swift
CHANGED
|
@@ -41,12 +41,10 @@ final class Bridge {
|
|
|
41
41
|
var rootView: RootView!
|
|
42
42
|
private var gestureReportersByNodeId: [Int: GestureReporter] = [:]
|
|
43
43
|
private let animatedGraph = AnimatedGraph()
|
|
44
|
-
// Limitation: Children of a removed node stay in the dictionary; clean up recursively if memory leaks.
|
|
45
44
|
var nodesById: [Int: NativeNode] = [:]
|
|
45
|
+
/// Views with @layout, and the box they last reported.
|
|
46
|
+
private var reportedLayoutsByNodeId: [Int: CGRect] = [:]
|
|
46
47
|
/// Modals and screens: their content is laid out as a separate Yoga root.
|
|
47
|
-
// Limitation: Vue removes only a subtree's root, so the modals and screens inside a removed subtree stay
|
|
48
|
-
// here and are laid out on every pass; drop the detached ones on remove if navigators come and go.
|
|
49
|
-
// Likewise a sheet a <ScreenStack> presented stays up when a v-if removes the stack (a reload closes it).
|
|
50
48
|
private var contentRootsByNodeId: [Int: ContentRoot] = [:]
|
|
51
49
|
/// For Dimensions.get('window'): the screen's at start, then the root view's, kept on the JS queue.
|
|
52
50
|
private var windowSize: CGSize = .zero
|
|
@@ -62,6 +60,7 @@ final class Bridge {
|
|
|
62
60
|
func start(rootView: RootView) {
|
|
63
61
|
self.rootView = rootView
|
|
64
62
|
rootView.onLayoutSubviews = { [unowned self] in layout() }
|
|
63
|
+
NativeNode.onLayoutCalculated = { [unowned self] in reportLayoutChanges() }
|
|
65
64
|
let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene
|
|
66
65
|
windowSize = windowScene?.screen.bounds.size ?? .zero
|
|
67
66
|
colorScheme = Self.colorScheme(of: windowScene?.traitCollection ?? rootView.traitCollection)
|
|
@@ -300,7 +299,8 @@ final class Bridge {
|
|
|
300
299
|
|
|
301
300
|
define("remove") { [unowned self] arguments in
|
|
302
301
|
let id = int(arguments[0])
|
|
303
|
-
|
|
302
|
+
let subtreeIds = (arguments[1] as? [Any] ?? []).map(int)
|
|
303
|
+
enqueue { [unowned self] in removeNode(id: id, subtreeIds: subtreeIds) }
|
|
304
304
|
}
|
|
305
305
|
|
|
306
306
|
define("setText") { [unowned self] arguments in
|
|
@@ -384,6 +384,7 @@ final class Bridge {
|
|
|
384
384
|
contentRootsByNodeId.values.forEach { ($0 as? ModalController)?.setVisible(false) }
|
|
385
385
|
contentRootsByNodeId = [:]
|
|
386
386
|
gestureReportersByNodeId = [:] // node ids start over
|
|
387
|
+
reportedLayoutsByNodeId = [:]
|
|
387
388
|
animatedGraph.reset()
|
|
388
389
|
animatedGraph.onAnimationEnd = { [unowned self] animationId, finished in
|
|
389
390
|
evaluate { [unowned self] in
|
|
@@ -410,16 +411,49 @@ final class Bridge {
|
|
|
410
411
|
}
|
|
411
412
|
|
|
412
413
|
/// A screen leaves through its stack, so the navigation controller animates it out.
|
|
413
|
-
private func removeNode(id: Int) {
|
|
414
|
-
guard let node = nodesById
|
|
414
|
+
private func removeNode(id: Int, subtreeIds: [Int]) {
|
|
415
|
+
guard let node = nodesById[id] else { return }
|
|
415
416
|
|
|
416
|
-
|
|
417
|
+
if let screen = screenController(id) {
|
|
418
|
+
screen.container?.removeScreen(screen)
|
|
419
|
+
} else {
|
|
417
420
|
node.removeFromParent()
|
|
418
|
-
return
|
|
419
421
|
}
|
|
422
|
+
subtreeIds.forEach(forgetNode)
|
|
423
|
+
}
|
|
420
424
|
|
|
425
|
+
/// Its view left the tree: what refers to it by id goes too, and a modal or sheet inside closes.
|
|
426
|
+
private func forgetNode(id: Int) {
|
|
427
|
+
let node = nodesById.removeValue(forKey: id)
|
|
428
|
+
(node?.view as? ScreenStackView)?.dismissPresentedScreens()
|
|
429
|
+
modalController(id)?.dismissIfDetached()
|
|
421
430
|
contentRootsByNodeId[id] = nil
|
|
422
|
-
|
|
431
|
+
gestureReportersByNodeId[id] = nil
|
|
432
|
+
reportedLayoutsByNodeId[id] = nil
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
/// @layout fires for the views whose box changed: { x, y, width, height }, in points, in its parent.
|
|
436
|
+
/// All of a layout pass's changes go in one call, so JS re-renders once for them, not once per view.
|
|
437
|
+
private func reportLayoutChanges() {
|
|
438
|
+
var changedLayouts: [[String: Any]] = []
|
|
439
|
+
|
|
440
|
+
for (id, reportedLayout) in reportedLayoutsByNodeId {
|
|
441
|
+
guard let yogaNode = nodesById[id]?.yogaNode else { continue }
|
|
442
|
+
|
|
443
|
+
let layout = CGRect(
|
|
444
|
+
x: CGFloat(YGNodeLayoutGetLeft(yogaNode)),
|
|
445
|
+
y: CGFloat(YGNodeLayoutGetTop(yogaNode)),
|
|
446
|
+
width: CGFloat(YGNodeLayoutGetWidth(yogaNode)),
|
|
447
|
+
height: CGFloat(YGNodeLayoutGetHeight(yogaNode))
|
|
448
|
+
)
|
|
449
|
+
guard !layout.width.isNaN, layout != reportedLayout else { continue }
|
|
450
|
+
|
|
451
|
+
reportedLayoutsByNodeId[id] = layout
|
|
452
|
+
changedLayouts.append(["id": id, "x": layout.minX, "y": layout.minY, "width": layout.width, "height": layout.height])
|
|
453
|
+
}
|
|
454
|
+
guard !changedLayouts.isEmpty else { return }
|
|
455
|
+
|
|
456
|
+
evaluate { [unowned self] in runtime?.call("__layoutsChanged", arguments: [changedLayouts]) }
|
|
423
457
|
}
|
|
424
458
|
|
|
425
459
|
private func modalController(_ id: Int) -> ModalController? {
|
|
@@ -434,6 +468,7 @@ final class Bridge {
|
|
|
434
468
|
private func makeNode(type: String, id: Int) -> NativeNode {
|
|
435
469
|
let node = makeUnstyledNode(type: type, id: id)
|
|
436
470
|
if let button = node.view as? UIButton, let systemFont = button.titleLabel?.font {
|
|
471
|
+
node.defaultFontSize = systemFont.pointSize
|
|
437
472
|
node.fontSize = systemFont.pointSize
|
|
438
473
|
}
|
|
439
474
|
node.updateFont()
|
|
@@ -457,7 +492,13 @@ final class Bridge {
|
|
|
457
492
|
return NativeNode(view: VueScrollView(), measuresContent: false)
|
|
458
493
|
|
|
459
494
|
case "Image":
|
|
460
|
-
|
|
495
|
+
let imageView = ImageView(frame: .zero)
|
|
496
|
+
let node = NativeNode(view: imageView, measuresContent: true)
|
|
497
|
+
imageView.onImageChange = { [unowned self, weak node] in
|
|
498
|
+
node?.markContentChanged()
|
|
499
|
+
rootView.setNeedsLayout()
|
|
500
|
+
}
|
|
501
|
+
return node
|
|
461
502
|
|
|
462
503
|
case "SwipeableView":
|
|
463
504
|
return NativeNode(view: SwipeableView(frame: .zero), measuresContent: false)
|
|
@@ -858,9 +899,17 @@ final class Bridge {
|
|
|
858
899
|
case "source":
|
|
859
900
|
(node.view as? ImageView)?.load(value as? String)
|
|
860
901
|
|
|
902
|
+
case "cache":
|
|
903
|
+
(node.view as? ImageView)?.cachePolicy = value as? String ?? "disk"
|
|
904
|
+
|
|
861
905
|
case "resizeMode":
|
|
862
906
|
node.view.contentMode = ImageView.resizeModes[value as? String ?? ""] ?? .scaleAspectFill
|
|
863
907
|
|
|
908
|
+
case "onLayout":
|
|
909
|
+
// A new handler on every render re-registers: only a first one waits for a report.
|
|
910
|
+
if !isTruthyAttribute(value) { reportedLayoutsByNodeId[id] = nil }
|
|
911
|
+
else if reportedLayoutsByNodeId[id] == nil { reportedLayoutsByNodeId[id] = .null }
|
|
912
|
+
|
|
864
913
|
case "onScroll":
|
|
865
914
|
(node.view as? VueScrollView)?.onScroll = isTruthyAttribute(value) ? reportScroll(toNodeId: id) : nil
|
|
866
915
|
|
package/ios/ImageView.swift
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
|
+
import CryptoKit
|
|
1
2
|
import UIKit
|
|
3
|
+
import yoga
|
|
2
4
|
|
|
3
|
-
/// Image view behind <Image>. Loads `source` (an http(s) or data: url)
|
|
4
|
-
///
|
|
5
|
-
|
|
6
|
-
// images stutter or sizing by hand gets annoying.
|
|
5
|
+
/// Image view behind <Image>. Loads `source` (an http(s) or data: url). With `cache` "disk" (the default),
|
|
6
|
+
/// downloads are kept on disk and decoded images in memory; "memory" keeps only the decoded images, so
|
|
7
|
+
/// one that comes back on screen (a list row) shows at once; "none" keeps nothing.
|
|
7
8
|
final class ImageView: UIImageView {
|
|
8
9
|
static let resizeModes: [String: UIView.ContentMode] = [
|
|
9
10
|
"cover": .scaleAspectFill,
|
|
@@ -12,6 +13,28 @@ final class ImageView: UIImageView {
|
|
|
12
13
|
"center": .center,
|
|
13
14
|
]
|
|
14
15
|
|
|
16
|
+
/// NSCache also empties itself when memory runs low.
|
|
17
|
+
private static let decodedImages: NSCache<NSString, UIImage> = {
|
|
18
|
+
let cache = NSCache<NSString, UIImage>()
|
|
19
|
+
cache.totalCostLimit = 64 * 1024 * 1024
|
|
20
|
+
|
|
21
|
+
return cache
|
|
22
|
+
}()
|
|
23
|
+
|
|
24
|
+
/// Its own cache only: URLCache would keep a second copy of each download.
|
|
25
|
+
private static let session = URLSession(configuration: {
|
|
26
|
+
let configuration = URLSessionConfiguration.ephemeral
|
|
27
|
+
configuration.urlCache = nil
|
|
28
|
+
|
|
29
|
+
return configuration
|
|
30
|
+
}())
|
|
31
|
+
|
|
32
|
+
/// The image changed, and with it the size the view measures.
|
|
33
|
+
var onImageChange: (() -> Void)?
|
|
34
|
+
|
|
35
|
+
/// "disk", "memory" or "none". Read when a download finishes, so it applies even when set after `source`.
|
|
36
|
+
var cachePolicy = "disk"
|
|
37
|
+
|
|
15
38
|
private var loadingTask: Task<Void, Never>?
|
|
16
39
|
|
|
17
40
|
override init(frame: CGRect) {
|
|
@@ -25,19 +48,119 @@ final class ImageView: UIImageView {
|
|
|
25
48
|
fatalError("init(coder:) is not supported")
|
|
26
49
|
}
|
|
27
50
|
|
|
28
|
-
func load(_
|
|
51
|
+
func load(_ source: String?) {
|
|
29
52
|
loadingTask?.cancel()
|
|
30
|
-
image = nil
|
|
31
53
|
|
|
32
|
-
guard let
|
|
54
|
+
guard let source, let url = URL(string: source) else { return show(nil) }
|
|
55
|
+
if cachePolicy != "none", let cachedImage = Self.decodedImages.object(forKey: source as NSString) {
|
|
56
|
+
return show(cachedImage)
|
|
57
|
+
}
|
|
33
58
|
|
|
59
|
+
show(nil)
|
|
60
|
+
let readsDisk = cachePolicy == "disk"
|
|
34
61
|
loadingTask = Task { [weak self] in
|
|
62
|
+
let cachedData = readsDisk ? await Task.detached { ImageDiskCache.data(for: source) }.value : nil
|
|
63
|
+
let downloadedData = cachedData == nil ? try? await Self.session.data(from: url).0 : nil
|
|
35
64
|
guard
|
|
36
|
-
let
|
|
37
|
-
|
|
65
|
+
let data = cachedData ?? downloadedData,
|
|
66
|
+
let image = await UIImage(data: data)?.byPreparingForDisplay(), // decoded off the main thread
|
|
67
|
+
!Task.isCancelled,
|
|
68
|
+
let self
|
|
38
69
|
else { return }
|
|
39
70
|
|
|
40
|
-
|
|
71
|
+
store(image, downloadedData: downloadedData, for: source)
|
|
72
|
+
show(image)
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
private func store(_ image: UIImage, downloadedData: Data?, for source: String) {
|
|
77
|
+
guard cachePolicy != "none" else { return }
|
|
78
|
+
|
|
79
|
+
Self.decodedImages.setObject(image, forKey: source as NSString, cost: Self.byteCount(of: image))
|
|
80
|
+
|
|
81
|
+
guard cachePolicy == "disk", let downloadedData, !source.hasPrefix("data:") else { return }
|
|
82
|
+
Task.detached(priority: .utility) { ImageDiskCache.store(downloadedData, for: source) }
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/// Without a width or height, the image takes its own size, a pixel per point; given one of them, the
|
|
86
|
+
/// other follows its aspect ratio, as on the web.
|
|
87
|
+
func measuredSize(width: Float, widthMode: YGMeasureMode, height: Float, heightMode: YGMeasureMode) -> YGSize {
|
|
88
|
+
let naturalWidth = Float(image?.size.width ?? 0)
|
|
89
|
+
let naturalHeight = Float(image?.size.height ?? 0)
|
|
90
|
+
let maxWidth = widthMode == .undefined ? .infinity : width
|
|
91
|
+
let maxHeight = heightMode == .undefined ? .infinity : height
|
|
92
|
+
|
|
93
|
+
if widthMode == .exactly && heightMode == .exactly { return YGSize(width: width, height: height) }
|
|
94
|
+
if naturalWidth == 0 || naturalHeight == 0 {
|
|
95
|
+
return YGSize(width: widthMode == .exactly ? width : 0, height: heightMode == .exactly ? height : 0)
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
let aspectRatio = naturalWidth / naturalHeight
|
|
99
|
+
if widthMode == .exactly { return YGSize(width: width, height: min(width / aspectRatio, maxHeight)) }
|
|
100
|
+
if heightMode == .exactly { return YGSize(width: min(height * aspectRatio, maxWidth), height: height) }
|
|
101
|
+
|
|
102
|
+
let scale = min(1, maxWidth / naturalWidth, maxHeight / naturalHeight)
|
|
103
|
+
|
|
104
|
+
return YGSize(width: naturalWidth * scale, height: naturalHeight * scale)
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
private func show(_ nextImage: UIImage?) {
|
|
108
|
+
guard nextImage !== image else { return }
|
|
109
|
+
|
|
110
|
+
image = nextImage
|
|
111
|
+
onImageChange?()
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
private static func byteCount(of image: UIImage) -> Int {
|
|
115
|
+
guard let cgImage = image.cgImage else { return 0 }
|
|
116
|
+
|
|
117
|
+
return cgImage.bytesPerRow * cgImage.height
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/// Downloaded images by url, in the system's caches folder, which iOS may empty when storage runs low. Past
|
|
122
|
+
/// its limit, the images used least recently go first.
|
|
123
|
+
private enum ImageDiskCache {
|
|
124
|
+
static let maxByteCount = 100 * 1024 * 1024
|
|
125
|
+
|
|
126
|
+
private static let directory = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0]
|
|
127
|
+
.appendingPathComponent("nativue-images", isDirectory: true)
|
|
128
|
+
|
|
129
|
+
static func data(for source: String) -> Data? {
|
|
130
|
+
let file = fileURL(for: source)
|
|
131
|
+
guard let data = try? Data(contentsOf: file) else { return nil }
|
|
132
|
+
|
|
133
|
+
try? FileManager.default.setAttributes([.modificationDate: Date()], ofItemAtPath: file.path)
|
|
134
|
+
|
|
135
|
+
return data
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
static func store(_ data: Data, for source: String) {
|
|
139
|
+
try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
|
|
140
|
+
try? data.write(to: fileURL(for: source), options: .atomic)
|
|
141
|
+
trim()
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
private static func fileURL(for source: String) -> URL {
|
|
145
|
+
let hash = SHA256.hash(data: Data(source.utf8)).map { String(format: "%02x", $0) }.joined()
|
|
146
|
+
|
|
147
|
+
return directory.appendingPathComponent(hash)
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
private static func trim() {
|
|
151
|
+
let keys: Set<URLResourceKey> = [.contentModificationDateKey, .fileSizeKey]
|
|
152
|
+
guard let files = try? FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: Array(keys)) else { return }
|
|
153
|
+
|
|
154
|
+
let entries = files.compactMap { file -> (file: URL, usedAt: Date, size: Int)? in
|
|
155
|
+
guard let values = try? file.resourceValues(forKeys: keys) else { return nil }
|
|
156
|
+
|
|
157
|
+
return (file, values.contentModificationDate ?? .distantPast, values.fileSize ?? 0)
|
|
158
|
+
}
|
|
159
|
+
var totalSize = entries.reduce(0) { $0 + $1.size }
|
|
160
|
+
|
|
161
|
+
for entry in entries.sorted(by: { $0.usedAt < $1.usedAt }) where totalSize > maxByteCount {
|
|
162
|
+
try? FileManager.default.removeItem(at: entry.file)
|
|
163
|
+
totalSize -= entry.size
|
|
41
164
|
}
|
|
42
165
|
}
|
|
43
166
|
}
|
package/ios/NativeNode.swift
CHANGED
|
@@ -20,6 +20,8 @@ final class NativeNode {
|
|
|
20
20
|
/// The view's own, before role and aria-* change them: read the first time they're applied.
|
|
21
21
|
lazy var defaultAccessibility = (isElement: view.isAccessibilityElement, traits: view.accessibilityTraits)
|
|
22
22
|
|
|
23
|
+
/// The view's own size, which a removed fontSize goes back to.
|
|
24
|
+
var defaultFontSize: CGFloat = UIFont.labelFontSize
|
|
23
25
|
var fontSize: CGFloat = UIFont.labelFontSize
|
|
24
26
|
var fontWeight: UIFont.Weight = .regular
|
|
25
27
|
|
|
@@ -78,9 +80,13 @@ final class NativeNode {
|
|
|
78
80
|
}
|
|
79
81
|
|
|
80
82
|
/// Computes the layout for this subtree and applies the resulting frames to the views.
|
|
83
|
+
/// After every layout pass, of the root or of a screen's or modal's content: for @layout.
|
|
84
|
+
static var onLayoutCalculated: (() -> Void)?
|
|
85
|
+
|
|
81
86
|
func calculateLayout(width: CGFloat, height: CGFloat) {
|
|
82
87
|
YGNodeCalculateLayout(yogaNode, Float(width), Float(height), .LTR)
|
|
83
88
|
Self.applyFrames(of: yogaNode)
|
|
89
|
+
Self.onLayoutCalculated?()
|
|
84
90
|
}
|
|
85
91
|
|
|
86
92
|
/// A view inserted during a layout animation would grow from the corner: it fades in where it lands.
|
|
@@ -180,6 +186,10 @@ private func measureView(
|
|
|
180
186
|
let maxHeight = heightMode == .undefined ? CGFloat.greatestFiniteMagnitude : CGFloat(height)
|
|
181
187
|
|
|
182
188
|
let view = NativeNode.view(of: yogaNode!)
|
|
189
|
+
if let imageView = view as? ImageView {
|
|
190
|
+
return imageView.measuredSize(width: width, widthMode: widthMode, height: height, heightMode: heightMode)
|
|
191
|
+
}
|
|
192
|
+
|
|
183
193
|
let singleLineLabelSize = (view as? UILabel).flatMap { singleLineSize(of: $0, maxWidth: maxWidth) }
|
|
184
194
|
let fittingSize = singleLineLabelSize ?? view.sizeThatFits(CGSize(width: maxWidth, height: maxHeight))
|
|
185
195
|
|
|
@@ -170,6 +170,13 @@ final class ScreenStackView: UIView, ScreenContainer, UINavigationControllerDele
|
|
|
170
170
|
}
|
|
171
171
|
}
|
|
172
172
|
|
|
173
|
+
/// The stack left the tree: the screens it presented close with it.
|
|
174
|
+
func dismissPresentedScreens() {
|
|
175
|
+
guard !modalNavigationControllers.isEmpty else { return }
|
|
176
|
+
|
|
177
|
+
dismissModals(from: 0)
|
|
178
|
+
}
|
|
179
|
+
|
|
173
180
|
private func dismissModals(from index: Int) {
|
|
174
181
|
let presenter = modalNavigationControllers[index].presentingViewController
|
|
175
182
|
modalNavigationControllers.removeSubrange(index...)
|
package/ios/Style.swift
CHANGED
|
@@ -1,16 +1,15 @@
|
|
|
1
1
|
import UIKit
|
|
2
2
|
import yoga
|
|
3
3
|
|
|
4
|
-
// Limitation: Removed layout properties arrive as null and keep their last value; reset them to Yoga's
|
|
5
|
-
// defaults when it matters. Visual properties already fall back to UIKit's defaults on null.
|
|
6
4
|
extension NativeNode {
|
|
7
|
-
/// Receives only the properties that changed: the JS renderer diffs style objects before sending.
|
|
5
|
+
/// Receives only the properties that changed: the JS renderer diffs style objects before sending. A
|
|
6
|
+
/// removed property arrives as null and goes back to its default, as in CSS.
|
|
8
7
|
func applyStyle(_ changes: [String: Any]) {
|
|
9
8
|
for (property, value) in changes {
|
|
10
9
|
if isDrivenByNativeView(property) { continue }
|
|
11
10
|
|
|
12
|
-
if let applyLayoutProperty = layoutPropertySetters[property]
|
|
13
|
-
applyLayoutProperty(yogaNode, value)
|
|
11
|
+
if let applyLayoutProperty = layoutPropertySetters[property] {
|
|
12
|
+
applyLayoutProperty(yogaNode, value is NSNull ? layoutDefaults[property] ?? undefinedLayoutValue : value)
|
|
14
13
|
}
|
|
15
14
|
// Some properties are both: overflow also clips the view.
|
|
16
15
|
applyVisualProperty(property, value)
|
|
@@ -88,11 +87,11 @@ extension NativeNode {
|
|
|
88
87
|
|
|
89
88
|
/// Font size and weight can change independently, so the node remembers both.
|
|
90
89
|
private func applyFont(_ changes: [String: Any]) {
|
|
91
|
-
if let size =
|
|
92
|
-
fontSize =
|
|
90
|
+
if let size = changes["fontSize"] {
|
|
91
|
+
fontSize = number(size).map { CGFloat($0) } ?? defaultFontSize
|
|
93
92
|
}
|
|
94
93
|
|
|
95
|
-
if let weightName = changes["fontWeight"]
|
|
94
|
+
if let weightName = changes["fontWeight"] {
|
|
96
95
|
fontWeight = fontWeights[String(describing: weightName)] ?? .regular
|
|
97
96
|
}
|
|
98
97
|
|
|
@@ -117,6 +116,23 @@ extension NativeNode {
|
|
|
117
116
|
|
|
118
117
|
private typealias LayoutPropertySetter = (YGNodeRef, Any) -> Void
|
|
119
118
|
|
|
119
|
+
/// What a removed property goes back to: Yoga's defaults. The others are undefined (unset).
|
|
120
|
+
private let layoutDefaults: [String: Any] = [
|
|
121
|
+
"flexDirection": "column",
|
|
122
|
+
"justifyContent": "flex-start",
|
|
123
|
+
"alignItems": "stretch",
|
|
124
|
+
"alignSelf": "auto",
|
|
125
|
+
"alignContent": "flex-start",
|
|
126
|
+
"flexWrap": "nowrap",
|
|
127
|
+
"position": "relative",
|
|
128
|
+
"display": "flex",
|
|
129
|
+
"overflow": "visible",
|
|
130
|
+
"flexBasis": "auto",
|
|
131
|
+
"width": "auto",
|
|
132
|
+
"height": "auto",
|
|
133
|
+
]
|
|
134
|
+
private let undefinedLayoutValue = NSNumber(value: Float.nan)
|
|
135
|
+
|
|
120
136
|
private let layoutPropertySetters: [String: LayoutPropertySetter] = {
|
|
121
137
|
var setters: [String: LayoutPropertySetter] = [
|
|
122
138
|
"flexDirection": enumSetter(flexDirections, YGNodeStyleSetFlexDirection),
|
package/package.json
CHANGED
package/src/components.ts
CHANGED
|
@@ -4,13 +4,15 @@ import {
|
|
|
4
4
|
defineComponent,
|
|
5
5
|
h,
|
|
6
6
|
onBeforeUnmount,
|
|
7
|
+
reactive,
|
|
7
8
|
ref,
|
|
8
9
|
watch,
|
|
9
10
|
type PropType,
|
|
10
11
|
type SlotsType,
|
|
11
12
|
type VNode,
|
|
12
13
|
} from '@vue/runtime-core'
|
|
13
|
-
import
|
|
14
|
+
import { rowAt, rowOffsets } from './list-window'
|
|
15
|
+
import type { LayoutEvent, ScrollEvent, Style } from './types'
|
|
14
16
|
|
|
15
17
|
type Listener = ((payload: unknown) => void) | undefined
|
|
16
18
|
|
|
@@ -86,12 +88,16 @@ export const Pressable = defineComponent({
|
|
|
86
88
|
})
|
|
87
89
|
|
|
88
90
|
const OFFSCREEN_ROWS_RENDERED = 10
|
|
91
|
+
// What a row not yet measured counts as, until some are: then their average.
|
|
92
|
+
const ESTIMATED_ROW_LENGTH = 50
|
|
89
93
|
|
|
90
|
-
// Renders only the rows near the visible area; the rest is empty padding of the same
|
|
91
|
-
// Slots: #item="{ item, index }", plus #header, #footer and #empty.
|
|
92
|
-
//
|
|
93
|
-
//
|
|
94
|
-
//
|
|
94
|
+
// Renders only the rows near the visible area; the rest is empty padding of the same length.
|
|
95
|
+
// Slots: #item="{ item, index }", plus #header, #footer and #empty. Vertical by default, sideways with
|
|
96
|
+
// `horizontal`. With `item-height` (or `item-width` when horizontal), every row is that long; without
|
|
97
|
+
// it, rows size to their content and are measured as they render.
|
|
98
|
+
// Limitation: Rows not rendered yet count as the average measured length, so jumping far (dragging the
|
|
99
|
+
// scroll indicator) can shift the rows a few points once they're measured; anchor the scroll position
|
|
100
|
+
// to the first visible row if that shows.
|
|
95
101
|
// Limitation: Items are `any` in the #item slot; make FlatList generic if typed rows are wanted.
|
|
96
102
|
// Limitation: An Animated.event `:on-scroll` replaces the window's own scroll handler, and a mapped event
|
|
97
103
|
// reaches JS only when a scroll starts and ends; report frames to both natively if that's needed.
|
|
@@ -99,7 +105,9 @@ export const FlatList = defineComponent({
|
|
|
99
105
|
name: 'FlatList',
|
|
100
106
|
props: {
|
|
101
107
|
data: { type: Array as PropType<any[]>, required: true },
|
|
102
|
-
|
|
108
|
+
horizontal: Boolean,
|
|
109
|
+
itemHeight: Number,
|
|
110
|
+
itemWidth: Number,
|
|
103
111
|
keyExtractor: {
|
|
104
112
|
type: Function as PropType<(item: any, index: number) => string | number>,
|
|
105
113
|
default: (_item: unknown, index: number) => index,
|
|
@@ -114,58 +122,114 @@ export const FlatList = defineComponent({
|
|
|
114
122
|
}>,
|
|
115
123
|
|
|
116
124
|
setup(props, { slots }) {
|
|
117
|
-
|
|
118
|
-
const
|
|
119
|
-
const
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
125
|
+
const scrollPosition = ref(0)
|
|
126
|
+
const viewportLength = ref(0)
|
|
127
|
+
const headerLength = ref(0)
|
|
128
|
+
const measuredLengths = reactive(new Map<string | number, number>())
|
|
129
|
+
|
|
130
|
+
// Along the scroll direction: heights for a vertical list, widths for a horizontal one.
|
|
131
|
+
const fixedLength = computed(() => (props.horizontal ? props.itemWidth : props.itemHeight))
|
|
132
|
+
const lengthOf = ({ width, height }: { width: number; height: number }) =>
|
|
133
|
+
props.horizontal ? width : height
|
|
134
|
+
|
|
135
|
+
const offsets = computed(() => {
|
|
136
|
+
const estimatedLength = averageOf(measuredLengths.values()) ?? ESTIMATED_ROW_LENGTH
|
|
137
|
+
const lengths = props.data.map(
|
|
138
|
+
(item, index) =>
|
|
139
|
+
fixedLength.value ??
|
|
140
|
+
measuredLengths.get(props.keyExtractor(item, index)) ??
|
|
141
|
+
estimatedLength,
|
|
126
142
|
)
|
|
127
143
|
|
|
128
|
-
return
|
|
144
|
+
return rowOffsets(lengths)
|
|
145
|
+
})
|
|
146
|
+
|
|
147
|
+
// Numbers, so scrolling within the same rows doesn't re-render.
|
|
148
|
+
const start = computed(() =>
|
|
149
|
+
Math.max(0, rowAt(offsets.value, scrollPosition.value) - OFFSCREEN_ROWS_RENDERED),
|
|
150
|
+
)
|
|
151
|
+
const end = computed(() => {
|
|
152
|
+
const lastVisibleRow = rowAt(offsets.value, scrollPosition.value + viewportLength.value)
|
|
153
|
+
|
|
154
|
+
return Math.min(props.data.length, lastVisibleRow + 1 + OFFSCREEN_ROWS_RENDERED)
|
|
129
155
|
})
|
|
130
156
|
|
|
131
157
|
// Bouncing past either edge reports offsets outside the list: clamp them, or the window (and the
|
|
132
158
|
// layout) would change on every frame of the bounce.
|
|
133
|
-
function handleScroll(
|
|
134
|
-
const
|
|
135
|
-
const
|
|
159
|
+
function handleScroll(event: ScrollEvent) {
|
|
160
|
+
const offset = props.horizontal ? event.x : event.y
|
|
161
|
+
const length = lengthOf(event)
|
|
162
|
+
const maxScrollPosition = Math.max(0, offsets.value[props.data.length] - length)
|
|
136
163
|
|
|
137
|
-
|
|
138
|
-
|
|
164
|
+
scrollPosition.value = Math.min(Math.max(offset - headerLength.value, 0), maxScrollPosition)
|
|
165
|
+
viewportLength.value = length
|
|
139
166
|
}
|
|
140
167
|
|
|
141
168
|
function renderRow(item: unknown, offset: number): VNode {
|
|
142
|
-
const index =
|
|
169
|
+
const index = start.value + offset
|
|
170
|
+
const key = props.keyExtractor(item, index)
|
|
171
|
+
const sizing = fixedLength.value
|
|
172
|
+
? { style: props.horizontal ? { width: fixedLength.value } : { height: fixedLength.value } }
|
|
173
|
+
: { onLayout: (layout: LayoutEvent) => measuredLengths.set(key, lengthOf(layout)) }
|
|
143
174
|
|
|
144
|
-
return h(
|
|
145
|
-
'View',
|
|
146
|
-
{ key: props.keyExtractor(item, index), style: { height: props.itemHeight } },
|
|
147
|
-
slots.item?.({ item, index }),
|
|
148
|
-
)
|
|
175
|
+
return h('View', { key, ...sizing }, slots.item?.({ item, index }))
|
|
149
176
|
}
|
|
150
177
|
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
178
|
+
function renderHeader(): VNode | null {
|
|
179
|
+
if (!slots.header) return null
|
|
180
|
+
|
|
181
|
+
const onLayout = (layout: LayoutEvent) => (headerLength.value = lengthOf(layout))
|
|
182
|
+
|
|
183
|
+
return h('View', { onLayout }, slots.header({}))
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// overflow: 'scroll' tells Yoga the rows may reach past the window's box: otherwise it caps a row
|
|
187
|
+
// that sizes to its content at the space the paddings leave, which is none.
|
|
188
|
+
function windowStyle(): Style {
|
|
189
|
+
const before = offsets.value[start.value]
|
|
190
|
+
const after = offsets.value[props.data.length] - offsets.value[end.value]
|
|
191
|
+
|
|
192
|
+
if (props.horizontal) {
|
|
193
|
+
return {
|
|
194
|
+
flexDirection: 'row',
|
|
195
|
+
paddingLeft: before,
|
|
196
|
+
paddingRight: after,
|
|
197
|
+
overflow: 'scroll',
|
|
198
|
+
}
|
|
156
199
|
}
|
|
157
200
|
|
|
201
|
+
return { paddingTop: before, paddingBottom: after, overflow: 'scroll' }
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
return () => {
|
|
205
|
+
const rows = props.data.slice(start.value, end.value).map(renderRow)
|
|
206
|
+
|
|
158
207
|
// Other attributes (refreshing, @refresh...) fall through to the ScrollView.
|
|
159
|
-
return h(
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
208
|
+
return h(
|
|
209
|
+
'ScrollView',
|
|
210
|
+
{ style: props.style, horizontal: props.horizontal, onScroll: handleScroll },
|
|
211
|
+
[
|
|
212
|
+
renderHeader(),
|
|
213
|
+
h('View', { style: windowStyle() }, rows),
|
|
214
|
+
props.data.length === 0 ? slots.empty?.({}) : null,
|
|
215
|
+
slots.footer?.({}),
|
|
216
|
+
],
|
|
217
|
+
)
|
|
165
218
|
}
|
|
166
219
|
},
|
|
167
220
|
})
|
|
168
221
|
|
|
222
|
+
function averageOf(values: Iterable<number>): number | undefined {
|
|
223
|
+
let sum = 0
|
|
224
|
+
let count = 0
|
|
225
|
+
for (const value of values) {
|
|
226
|
+
sum += value
|
|
227
|
+
count++
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
return count === 0 ? undefined : sum / count
|
|
231
|
+
}
|
|
232
|
+
|
|
169
233
|
const SWIPE_ACTIONS_STYLE: Style = { position: 'absolute', top: 0, bottom: 0, flexDirection: 'row' }
|
|
170
234
|
const SWIPE_LEFT_ACTIONS_STYLE: Style = { ...SWIPE_ACTIONS_STYLE, left: 0 }
|
|
171
235
|
const SWIPE_RIGHT_ACTIONS_STYLE: Style = { ...SWIPE_ACTIONS_STYLE, right: 0 }
|
package/src/globals.ts
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
// What the JavaScript engine has globally: the bridge, the hooks native calls into, and the web APIs
|
|
2
2
|
// prelude.ts (timers, console) and fetch.ts provide. No DOM.
|
|
3
3
|
import type { ColorScheme, WindowSize } from './appearance'
|
|
4
|
-
import type { NativeModule } from './types'
|
|
4
|
+
import type { LayoutEvent, NativeModule } from './types'
|
|
5
5
|
|
|
6
6
|
declare global {
|
|
7
7
|
var __native: NativeModule
|
|
8
8
|
var __dispatch: (nodeId: number, eventName: string, payload: unknown) => void
|
|
9
|
+
var __layoutsChanged: (layouts: ({ id: number } & LayoutEvent)[]) => void
|
|
9
10
|
var __openURL: (url: string) => void
|
|
10
11
|
var __fireTimer: (timerId: number) => void
|
|
11
12
|
var __colorSchemeChanged: (colorScheme: ColorScheme) => void
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
// FlatList's windowing math: where each row starts, and which rows a scroll position shows.
|
|
2
|
+
|
|
3
|
+
/** Where each row starts, plus where the last one ends: `heights.length + 1` offsets. */
|
|
4
|
+
export function rowOffsets(heights: number[]): number[] {
|
|
5
|
+
const offsets = [0]
|
|
6
|
+
for (const height of heights) offsets.push(offsets[offsets.length - 1] + height)
|
|
7
|
+
|
|
8
|
+
return offsets
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** The row at `position`, clamped to the rows there are: a bounce past either end stays on them. */
|
|
12
|
+
export function rowAt(offsets: number[], position: number): number {
|
|
13
|
+
let low = 0
|
|
14
|
+
let high = offsets.length - 2
|
|
15
|
+
|
|
16
|
+
while (low < high) {
|
|
17
|
+
const middle = Math.ceil((low + high) / 2)
|
|
18
|
+
if (offsets[middle] <= position) low = middle
|
|
19
|
+
else high = middle - 1
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
return Math.max(low, 0)
|
|
23
|
+
}
|
package/src/native-components.ts
CHANGED
|
@@ -3,9 +3,11 @@
|
|
|
3
3
|
import type { DefineComponent } from '@vue/runtime-core'
|
|
4
4
|
import type { AnimatedEvent } from './animated'
|
|
5
5
|
import type { FlatList, Pressable, Swipeable } from './components'
|
|
6
|
-
import type { PanEvent, PinchEvent, RotateEvent, ScrollEvent, Style } from './types'
|
|
6
|
+
import type { LayoutEvent, PanEvent, PinchEvent, RotateEvent, ScrollEvent, Style } from './types'
|
|
7
7
|
|
|
8
|
-
type NativeComponent<Props = {}> = DefineComponent<
|
|
8
|
+
type NativeComponent<Props = {}> = DefineComponent<
|
|
9
|
+
Props & { style?: Style; onLayout?: (event: LayoutEvent) => void } & AccessibilityProps
|
|
10
|
+
>
|
|
9
11
|
type BooleanAttribute = boolean | 'true' | 'false'
|
|
10
12
|
// As on the web: what a screen reader says about the view. See docs/accessibility.md.
|
|
11
13
|
export interface AccessibilityProps {
|
|
@@ -76,6 +78,8 @@ declare module '@vue/runtime-core' {
|
|
|
76
78
|
/** What the image shows, for screen readers. Leave it out for decorative images. */
|
|
77
79
|
alt?: string
|
|
78
80
|
resizeMode?: 'cover' | 'contain' | 'stretch' | 'center'
|
|
81
|
+
/** Where downloads are kept: on disk and in memory (the default), in memory only, or not at all. */
|
|
82
|
+
cache?: 'disk' | 'memory' | 'none'
|
|
79
83
|
}>
|
|
80
84
|
Switch: NativeComponent<
|
|
81
85
|
ModelProps<boolean> & { value?: boolean; onValueChange?: (value: boolean) => void }
|
package/src/renderer.ts
CHANGED
|
@@ -57,8 +57,13 @@ interface Node {
|
|
|
57
57
|
disabled?: boolean
|
|
58
58
|
classStyle?: Style
|
|
59
59
|
accessibility?: AccessibilityAttributes
|
|
60
|
+
/** <TextInput v-model.trim>: its modifiers, and the text typed last. */
|
|
61
|
+
modelModifiers?: ModelModifiers
|
|
62
|
+
typedText?: string
|
|
60
63
|
}
|
|
61
64
|
|
|
65
|
+
type ModelModifiers = { trim?: boolean; number?: boolean; lazy?: boolean }
|
|
66
|
+
|
|
62
67
|
type ElementState = Pick<Node, 'pressed' | 'focused' | 'disabled'>
|
|
63
68
|
|
|
64
69
|
type EventHandler = (payload: unknown) => void
|
|
@@ -84,6 +89,13 @@ function createNode(type: string): Node {
|
|
|
84
89
|
return { id: nextNodeId++, type, parent: null, children: [], text: '' }
|
|
85
90
|
}
|
|
86
91
|
|
|
92
|
+
// What native forgets with a removed subtree: Vue removes only its root.
|
|
93
|
+
function nativeIdsIn(node: Node): number[] {
|
|
94
|
+
const ownId = isNativeNode(node) ? [node.id] : []
|
|
95
|
+
|
|
96
|
+
return [...ownId, ...node.children.flatMap(nativeIdsIn)]
|
|
97
|
+
}
|
|
98
|
+
|
|
87
99
|
// '#text' and '#comment' nodes only exist in JS (Vue anchors / raw text); native never sees them.
|
|
88
100
|
function isNativeNode(node: Node): boolean {
|
|
89
101
|
return !node.type.startsWith('#')
|
|
@@ -317,7 +329,7 @@ const { createApp: createBaseApp } = createRenderer<Node, Node>({
|
|
|
317
329
|
const parent = detachFromParent(child)
|
|
318
330
|
forgetSubtree(child)
|
|
319
331
|
|
|
320
|
-
if (isNativeNode(child)) native.remove(child.id)
|
|
332
|
+
if (isNativeNode(child)) native.remove(child.id, nativeIdsIn(child))
|
|
321
333
|
else syncTextContent(parent)
|
|
322
334
|
},
|
|
323
335
|
|
|
@@ -362,7 +374,41 @@ globalThis.__dispatch = (nodeId, eventName, payload) => {
|
|
|
362
374
|
if (!handlers) return
|
|
363
375
|
|
|
364
376
|
handlers[eventName]?.(payload)
|
|
365
|
-
handlers[
|
|
377
|
+
updateModel(nodeId, eventName, payload, handlers['update:modelvalue'])
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
// One call per layout pass: the handlers' changes then render together, once.
|
|
381
|
+
globalThis.__layoutsChanged = (layouts) => {
|
|
382
|
+
for (const { id, ...layout } of layouts) globalThis.__dispatch(id, 'layout', layout)
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
// v-model's modifiers, as on the web: .lazy updates when editing ends rather than on every keystroke;
|
|
386
|
+
// .trim and .number change the value the model gets.
|
|
387
|
+
function updateModel(nodeId: number, eventName: string, payload: unknown, update?: EventHandler) {
|
|
388
|
+
const textInput = textInputsById.get(nodeId)
|
|
389
|
+
if (textInput && eventName === 'changetext') textInput.typedText = payload as string
|
|
390
|
+
if (!update) return
|
|
391
|
+
|
|
392
|
+
const modifiers = textInput?.modelModifiers ?? {}
|
|
393
|
+
if (!modifiers.lazy) {
|
|
394
|
+
if (MODEL_EVENT_BY_NATIVE_EVENT[eventName]) update(modelValue(modifiers, payload))
|
|
395
|
+
return
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
const editingEnded = eventName === 'blur' || eventName === 'submitediting'
|
|
399
|
+
const typedText = textInput?.typedText
|
|
400
|
+
if (editingEnded && typedText !== undefined) update(modelValue(modifiers, typedText))
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
function modelValue(modifiers: ModelModifiers, value: unknown): unknown {
|
|
404
|
+
if (typeof value !== 'string') return value
|
|
405
|
+
|
|
406
|
+
const text = modifiers.trim ? value.trim() : value
|
|
407
|
+
if (!modifiers.number) return text
|
|
408
|
+
|
|
409
|
+
const number = parseFloat(text)
|
|
410
|
+
|
|
411
|
+
return Number.isNaN(number) ? text : number
|
|
366
412
|
}
|
|
367
413
|
|
|
368
414
|
// A <TextInput>'s focus, for its class's focus: styles and its focused-style.
|
|
@@ -407,17 +453,30 @@ export const Keyboard = {
|
|
|
407
453
|
|
|
408
454
|
// Replaces Vue's DOM-only vModelText, which the template compiler emits for v-model on
|
|
409
455
|
// <TextInput> and <Switch>.
|
|
410
|
-
// Limitation: v-model modifiers (.trim, .number, .lazy) are not supported yet.
|
|
411
456
|
export const vModelText: Directive<Node> = {
|
|
412
|
-
created(element, { value }) {
|
|
413
|
-
|
|
457
|
+
created(element, { value, modifiers }) {
|
|
458
|
+
element.modelModifiers = modifiers
|
|
459
|
+
native.setProp(element.id, 'value', nativeModelValue(value))
|
|
414
460
|
},
|
|
415
461
|
|
|
416
|
-
beforeUpdate(element, { value, oldValue }) {
|
|
417
|
-
if (value
|
|
462
|
+
beforeUpdate(element, { value, oldValue, modifiers }) {
|
|
463
|
+
if (value === oldValue || showsModelValue(element, value, modifiers)) return
|
|
464
|
+
|
|
465
|
+
native.setProp(element.id, 'value', nativeModelValue(value))
|
|
418
466
|
},
|
|
419
467
|
}
|
|
420
468
|
|
|
469
|
+
// The field keeps what was typed when it already gives the model's value: with .trim, "hello " stays
|
|
470
|
+
// as typed instead of losing its space mid-word.
|
|
471
|
+
function showsModelValue(element: Node, value: unknown, modifiers: ModelModifiers): boolean {
|
|
472
|
+
return element.typedText !== undefined && modelValue(modifiers, element.typedText) === value
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
// A <TextInput> shows text, so a v-model.number's number goes as text; a <Switch> takes its boolean.
|
|
476
|
+
function nativeModelValue(value: unknown): unknown {
|
|
477
|
+
return typeof value === 'number' ? String(value) : (value ?? '')
|
|
478
|
+
}
|
|
479
|
+
|
|
421
480
|
const rootNode: Node = { id: 0, type: 'root', parent: null, children: [], text: '' }
|
|
422
481
|
|
|
423
482
|
// Errors in templates, setup, hooks and handlers: shown natively, with where they happened (in
|
package/src/types.ts
CHANGED
|
@@ -66,6 +66,14 @@ export type Style = {
|
|
|
66
66
|
|
|
67
67
|
export type GestureState = 'began' | 'changed' | 'ended' | 'cancelled' | 'failed'
|
|
68
68
|
|
|
69
|
+
// @layout: the view's box in its parent, in points.
|
|
70
|
+
export interface LayoutEvent {
|
|
71
|
+
x: number
|
|
72
|
+
y: number
|
|
73
|
+
width: number
|
|
74
|
+
height: number
|
|
75
|
+
}
|
|
76
|
+
|
|
69
77
|
export interface ScrollEvent {
|
|
70
78
|
x: number
|
|
71
79
|
y: number
|
|
@@ -110,7 +118,8 @@ export interface NativeModule {
|
|
|
110
118
|
announce(message: string): void
|
|
111
119
|
create(id: number, type: string): void
|
|
112
120
|
insert(parentId: number, childId: number, index: number): void
|
|
113
|
-
|
|
121
|
+
/** Detaches the view `id`; `subtreeIds` (it and every native descendant) are forgotten. */
|
|
122
|
+
remove(id: number, subtreeIds: number[]): void
|
|
114
123
|
setProp(id: number, key: string, value: unknown): void
|
|
115
124
|
setText(id: number, text: string): void
|
|
116
125
|
setTimer(timerId: number, delay: number): void
|