@nativue/core 0.4.3 → 0.4.4

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.
@@ -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
- enqueue { nodesById[id]?.let(::removeNode) }
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(root: NativeNode) {
540
- val removedViews = mutableSetOf<View>()
541
- collectViews(root.view, removedViews)
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
- private fun collectViews(view: View, views: MutableSet<View>) {
555
- views.add(view)
556
- if (view is ViewGroup) (0 until view.childCount).forEach { collectViews(view.getChildAt(it), views) }
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" -> NativeNode(RemoteImageView(activity), measuresContent = false)
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" -> {
@@ -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 = 17f
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
- // Limitation: Removed layout properties arrive as null and keep their last value, like on iOS.
21
-
22
- /** Receives only the properties that changed: the JS renderer diffs style objects before sending. */
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
- if (value != null) layoutPropertySetters[property]?.invoke(yogaNode, value)
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"])?.let { fontSize = it }
111
- changes["fontWeight"]?.let { weightName -> fontWeight = fontWeightOf(weightName) }
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
@@ -20,7 +21,9 @@ import android.widget.ProgressBar
20
21
  import android.widget.ScrollView
21
22
  import android.widget.Switch
22
23
  import java.net.URL
23
- import kotlin.concurrent.thread
24
+ import java.util.concurrent.Executors
25
+ import kotlin.math.min
26
+ import kotlin.math.roundToInt
24
27
  import kotlin.math.abs
25
28
 
26
29
  /**
@@ -216,6 +219,7 @@ class ScrollContainerView(context: Context) : ContainerView(context) {
216
219
  private var isPullingToRefresh = false
217
220
 
218
221
  init {
222
+ clipChildren = true // like a UIScrollView: scrolled content stays inside the list
219
223
  addView(scroller)
220
224
  addView(refreshIndicator)
221
225
  }
@@ -484,9 +488,18 @@ private fun pageOffset(offset: Int, pageSize: Int, velocity: Int): Int {
484
488
  return targetPage.toInt() * pageSize
485
489
  }
486
490
 
487
- /** Loads `data:` URIs (bundled images) and http(s) URLs off the main thread. */
491
+ /**
492
+ * Loads `data:` URIs (bundled images) and http(s) URLs off the main thread. Decoded images are kept in
493
+ * memory, so one that comes back on screen (a list row) shows at once.
494
+ */
495
+ // Limitation: No HTTP disk cache, unlike iOS's URLCache: after a relaunch images download again. Give image
496
+ // requests their own cache if that matters (a global HttpResponseCache would also cache the dev bundle).
488
497
  class RemoteImageView(context: Context) : ImageView(context) {
498
+ /** The image changed, and with it the size the view measures. */
499
+ var onImageChange: () -> Unit = {}
500
+
489
501
  private var source: String? = null
502
+ private var bitmap: Bitmap? = null
490
503
 
491
504
  init {
492
505
  scaleType = ScaleType.CENTER_CROP
@@ -496,13 +509,52 @@ class RemoteImageView(context: Context) : ImageView(context) {
496
509
  if (source == this.source) return
497
510
 
498
511
  this.source = source
499
- setImageDrawable(null)
500
- if (source == null) return
512
+ show(source?.let(decodedImages::get))
513
+ if (source == null || bitmap != null) return
514
+
515
+ loader.execute {
516
+ val bitmap = runCatching { decode(source) }.getOrNull() ?: return@execute
517
+ decodedImages.put(source, bitmap)
518
+ post { if (source == this.source) show(bitmap) }
519
+ }
520
+ }
521
+
522
+ private fun show(nextBitmap: Bitmap?) {
523
+ if (nextBitmap === bitmap) return
524
+
525
+ bitmap = nextBitmap
526
+ setImageBitmap(nextBitmap)
527
+ onImageChange()
528
+ }
501
529
 
502
- thread {
503
- val bitmap = runCatching { decode(source) }.getOrNull()
504
- post { if (source == this.source) setImageBitmap(bitmap) }
530
+ /**
531
+ * Without a width or height, the image takes its own size, a pixel per dp; given one of them, the other
532
+ * follows its aspect ratio, as on the web.
533
+ */
534
+ override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
535
+ val density = resources.displayMetrics.density
536
+ val naturalWidth = (bitmap?.width ?: 0) * density
537
+ val naturalHeight = (bitmap?.height ?: 0) * density
538
+ val widthMode = MeasureSpec.getMode(widthMeasureSpec)
539
+ val heightMode = MeasureSpec.getMode(heightMeasureSpec)
540
+ val width = MeasureSpec.getSize(widthMeasureSpec).toFloat()
541
+ val height = MeasureSpec.getSize(heightMeasureSpec).toFloat()
542
+ val maxWidth = if (widthMode == MeasureSpec.UNSPECIFIED) Float.POSITIVE_INFINITY else width
543
+ val maxHeight = if (heightMode == MeasureSpec.UNSPECIFIED) Float.POSITIVE_INFINITY else height
544
+ val aspectRatio = naturalWidth / naturalHeight
545
+
546
+ val (measuredWidth, measuredHeight) = when {
547
+ widthMode == MeasureSpec.EXACTLY && heightMode == MeasureSpec.EXACTLY -> width to height
548
+ naturalWidth == 0f || naturalHeight == 0f ->
549
+ (if (widthMode == MeasureSpec.EXACTLY) width else 0f) to (if (heightMode == MeasureSpec.EXACTLY) height else 0f)
550
+ widthMode == MeasureSpec.EXACTLY -> width to min(width / aspectRatio, maxHeight)
551
+ heightMode == MeasureSpec.EXACTLY -> min(height * aspectRatio, maxWidth) to height
552
+ else -> {
553
+ val scale = minOf(1f, maxWidth / naturalWidth, maxHeight / naturalHeight)
554
+ naturalWidth * scale to naturalHeight * scale
555
+ }
505
556
  }
557
+ setMeasuredDimension(measuredWidth.roundToInt(), measuredHeight.roundToInt())
506
558
  }
507
559
 
508
560
  private fun decode(source: String): Bitmap? {
@@ -515,6 +567,13 @@ class RemoteImageView(context: Context) : ImageView(context) {
515
567
  }
516
568
 
517
569
  companion object {
570
+ private val loader = Executors.newFixedThreadPool(4)
571
+
572
+ /** Decoded images, an eighth of the app's memory at most: one that comes back on screen shows at once. */
573
+ private val decodedImages = object : LruCache<String, Bitmap>((Runtime.getRuntime().maxMemory() / 8).toInt()) {
574
+ override fun sizeOf(key: String, value: Bitmap) = value.byteCount
575
+ }
576
+
518
577
  val scaleTypes = mapOf(
519
578
  "cover" to ScaleType.CENTER_CROP,
520
579
  "contain" to ScaleType.FIT_CENTER,
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
- enqueue { [unowned self] in removeNode(id: id) }
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.removeValue(forKey: id) else { return }
414
+ private func removeNode(id: Int, subtreeIds: [Int]) {
415
+ guard let node = nodesById[id] else { return }
415
416
 
416
- guard let screen = screenController(id) else {
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
- screen.container?.removeScreen(screen)
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
- return NativeNode(view: ImageView(frame: .zero), measuresContent: false)
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)
@@ -861,6 +902,11 @@ final class Bridge {
861
902
  case "resizeMode":
862
903
  node.view.contentMode = ImageView.resizeModes[value as? String ?? ""] ?? .scaleAspectFill
863
904
 
905
+ case "onLayout":
906
+ // A new handler on every render re-registers: only a first one waits for a report.
907
+ if !isTruthyAttribute(value) { reportedLayoutsByNodeId[id] = nil }
908
+ else if reportedLayoutsByNodeId[id] == nil { reportedLayoutsByNodeId[id] = .null }
909
+
864
910
  case "onScroll":
865
911
  (node.view as? VueScrollView)?.onScroll = isTruthyAttribute(value) ? reportScroll(toNodeId: id) : nil
866
912
 
@@ -1,9 +1,9 @@
1
1
  import UIKit
2
+ import yoga
2
3
 
3
4
  /// Image view behind <Image>. Loads `source` (an http(s) or data: url) through URLSession, which also
4
- /// gives HTTP caching through URLCache.
5
- // Limitation: No decoded-image cache and no intrinsic size; add an NSCache / measure function if lists of
6
- // images stutter or sizing by hand gets annoying.
5
+ /// gives HTTP caching through URLCache; decoded images are kept in memory, so one that comes back on
6
+ /// screen (a list row) shows at once.
7
7
  final class ImageView: UIImageView {
8
8
  static let resizeModes: [String: UIView.ContentMode] = [
9
9
  "cover": .scaleAspectFill,
@@ -12,6 +12,17 @@ final class ImageView: UIImageView {
12
12
  "center": .center,
13
13
  ]
14
14
 
15
+ /// NSCache also empties itself when memory runs low.
16
+ private static let decodedImages: NSCache<NSString, UIImage> = {
17
+ let cache = NSCache<NSString, UIImage>()
18
+ cache.totalCostLimit = 64 * 1024 * 1024
19
+
20
+ return cache
21
+ }()
22
+
23
+ /// The image changed, and with it the size the view measures.
24
+ var onImageChange: (() -> Void)?
25
+
15
26
  private var loadingTask: Task<Void, Never>?
16
27
 
17
28
  override init(frame: CGRect) {
@@ -25,19 +36,57 @@ final class ImageView: UIImageView {
25
36
  fatalError("init(coder:) is not supported")
26
37
  }
27
38
 
28
- func load(_ urlString: String?) {
39
+ func load(_ source: String?) {
29
40
  loadingTask?.cancel()
30
- image = nil
31
41
 
32
- guard let urlString, let url = URL(string: urlString) else { return }
42
+ guard let source, let url = URL(string: source) else { return show(nil) }
43
+ if let cachedImage = Self.decodedImages.object(forKey: source as NSString) { return show(cachedImage) }
33
44
 
45
+ show(nil)
34
46
  loadingTask = Task { [weak self] in
35
47
  guard
36
48
  let (data, _) = try? await URLSession.shared.data(from: url),
49
+ let image = await UIImage(data: data)?.byPreparingForDisplay(), // decoded off the main thread
37
50
  !Task.isCancelled
38
51
  else { return }
39
52
 
40
- self?.image = UIImage(data: data)
53
+ Self.decodedImages.setObject(image, forKey: source as NSString, cost: Self.byteCount(of: image))
54
+ self?.show(image)
55
+ }
56
+ }
57
+
58
+ /// Without a width or height, the image takes its own size, a pixel per point; given one of them, the
59
+ /// other follows its aspect ratio, as on the web.
60
+ func measuredSize(width: Float, widthMode: YGMeasureMode, height: Float, heightMode: YGMeasureMode) -> YGSize {
61
+ let naturalWidth = Float(image?.size.width ?? 0)
62
+ let naturalHeight = Float(image?.size.height ?? 0)
63
+ let maxWidth = widthMode == .undefined ? .infinity : width
64
+ let maxHeight = heightMode == .undefined ? .infinity : height
65
+
66
+ if widthMode == .exactly && heightMode == .exactly { return YGSize(width: width, height: height) }
67
+ if naturalWidth == 0 || naturalHeight == 0 {
68
+ return YGSize(width: widthMode == .exactly ? width : 0, height: heightMode == .exactly ? height : 0)
41
69
  }
70
+
71
+ let aspectRatio = naturalWidth / naturalHeight
72
+ if widthMode == .exactly { return YGSize(width: width, height: min(width / aspectRatio, maxHeight)) }
73
+ if heightMode == .exactly { return YGSize(width: min(height * aspectRatio, maxWidth), height: height) }
74
+
75
+ let scale = min(1, maxWidth / naturalWidth, maxHeight / naturalHeight)
76
+
77
+ return YGSize(width: naturalWidth * scale, height: naturalHeight * scale)
78
+ }
79
+
80
+ private func show(_ nextImage: UIImage?) {
81
+ guard nextImage !== image else { return }
82
+
83
+ image = nextImage
84
+ onImageChange?()
85
+ }
86
+
87
+ private static func byteCount(of image: UIImage) -> Int {
88
+ guard let cgImage = image.cgImage else { return 0 }
89
+
90
+ return cgImage.bytesPerRow * cgImage.height
42
91
  }
43
92
  }
@@ -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], !(value is NSNull) {
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 = number(changes["fontSize"] as Any) {
92
- fontSize = CGFloat(size)
90
+ if let size = changes["fontSize"] {
91
+ fontSize = number(size).map { CGFloat($0) } ?? defaultFontSize
93
92
  }
94
93
 
95
- if let weightName = changes["fontWeight"], !(weightName is NSNull) {
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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nativue/core",
3
- "version": "0.4.3",
3
+ "version": "0.4.4",
4
4
  "description": "Vue rendering real native views on iOS and Android",
5
5
  "keywords": [
6
6
  "vue",
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 type { ScrollEvent, Style } from './types'
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,15 @@ 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_HEIGHT = 50
89
93
 
90
94
  // Renders only the rows near the visible area; the rest is empty padding of the same height.
91
- // Slots: #item="{ item, index }", plus #header, #footer and #empty.
92
- // Limitation: Rows have a fixed `itemHeight`; measure rows natively if
93
- // variable heights are ever needed. Vertical only. The window ignores the header's height, which the
94
- // offscreen rows absorb while the header is shorter than them; measure it if tall headers show gaps.
95
+ // Slots: #item="{ item, index }", plus #header, #footer and #empty. With `item-height`, every row is that
96
+ // tall; without it, rows size to their content and are measured as they render. Vertical only.
97
+ // Limitation: Rows not rendered yet count as the average measured height, so jumping far (dragging the
98
+ // scroll indicator) can shift the rows a few points once they're measured; anchor the scroll position
99
+ // to the first visible row if that shows.
95
100
  // Limitation: Items are `any` in the #item slot; make FlatList generic if typed rows are wanted.
96
101
  // Limitation: An Animated.event `:on-scroll` replaces the window's own scroll handler, and a mapped event
97
102
  // reaches JS only when a scroll starts and ends; report frames to both natively if that's needed.
@@ -99,7 +104,7 @@ export const FlatList = defineComponent({
99
104
  name: 'FlatList',
100
105
  props: {
101
106
  data: { type: Array as PropType<any[]>, required: true },
102
- itemHeight: { type: Number, required: true },
107
+ itemHeight: Number,
103
108
  keyExtractor: {
104
109
  type: Function as PropType<(item: any, index: number) => string | number>,
105
110
  default: (_item: unknown, index: number) => index,
@@ -114,51 +119,74 @@ export const FlatList = defineComponent({
114
119
  }>,
115
120
 
116
121
  setup(props, { slots }) {
117
- // Whole rows, so scrolling within a row doesn't re-render (refs ignore same-value writes).
118
- const firstVisibleRow = ref(0)
119
- const visibleRowCount = ref(0)
120
-
121
- const visibleRange = computed(() => {
122
- const start = Math.max(0, firstVisibleRow.value - OFFSCREEN_ROWS_RENDERED)
123
- const end = Math.min(
124
- props.data.length,
125
- firstVisibleRow.value + visibleRowCount.value + OFFSCREEN_ROWS_RENDERED,
122
+ const scrollTop = ref(0)
123
+ const viewportHeight = ref(0)
124
+ const headerHeight = ref(0)
125
+ const measuredHeights = reactive(new Map<string | number, number>())
126
+
127
+ const offsets = computed(() => {
128
+ const estimatedHeight = averageOf(measuredHeights.values()) ?? ESTIMATED_ROW_HEIGHT
129
+ const heights = props.data.map(
130
+ (item, index) =>
131
+ props.itemHeight ??
132
+ measuredHeights.get(props.keyExtractor(item, index)) ??
133
+ estimatedHeight,
126
134
  )
127
135
 
128
- return { start, end }
136
+ return rowOffsets(heights)
137
+ })
138
+
139
+ // Numbers, so scrolling within the same rows doesn't re-render.
140
+ const start = computed(() =>
141
+ Math.max(0, rowAt(offsets.value, scrollTop.value) - OFFSCREEN_ROWS_RENDERED),
142
+ )
143
+ const end = computed(() => {
144
+ const lastVisibleRow = rowAt(offsets.value, scrollTop.value + viewportHeight.value)
145
+
146
+ return Math.min(props.data.length, lastVisibleRow + 1 + OFFSCREEN_ROWS_RENDERED)
129
147
  })
130
148
 
131
149
  // Bouncing past either edge reports offsets outside the list: clamp them, or the window (and the
132
150
  // layout) would change on every frame of the bounce.
133
151
  function handleScroll({ y, height }: ScrollEvent) {
134
- const maxScrollTop = Math.max(0, props.data.length * props.itemHeight - height)
135
- const scrollTop = Math.min(Math.max(y, 0), maxScrollTop)
152
+ const maxScrollTop = Math.max(0, offsets.value[props.data.length] - height)
136
153
 
137
- firstVisibleRow.value = Math.floor(scrollTop / props.itemHeight)
138
- visibleRowCount.value = Math.ceil(height / props.itemHeight)
154
+ scrollTop.value = Math.min(Math.max(y - headerHeight.value, 0), maxScrollTop)
155
+ viewportHeight.value = height
139
156
  }
140
157
 
141
158
  function renderRow(item: unknown, offset: number): VNode {
142
- const index = visibleRange.value.start + offset
159
+ const index = start.value + offset
160
+ const key = props.keyExtractor(item, index)
161
+ const sizing = props.itemHeight
162
+ ? { style: { height: props.itemHeight } }
163
+ : { onLayout: ({ height }: LayoutEvent) => measuredHeights.set(key, height) }
143
164
 
144
- return h(
145
- 'View',
146
- { key: props.keyExtractor(item, index), style: { height: props.itemHeight } },
147
- slots.item?.({ item, index }),
148
- )
165
+ return h('View', { key, ...sizing }, slots.item?.({ item, index }))
166
+ }
167
+
168
+ function renderHeader(): VNode | null {
169
+ if (!slots.header) return null
170
+
171
+ const onLayout = ({ height }: LayoutEvent) => (headerHeight.value = height)
172
+
173
+ return h('View', { onLayout }, slots.header({}))
149
174
  }
150
175
 
151
176
  return () => {
152
- const { start, end } = visibleRange.value
177
+ const total = offsets.value[props.data.length]
178
+ // overflow: 'scroll' tells Yoga the rows may reach past the window's box: otherwise it caps a row
179
+ // that sizes to its content at the space the paddings leave, which is none.
153
180
  const window = {
154
- paddingTop: start * props.itemHeight,
155
- paddingBottom: (props.data.length - end) * props.itemHeight,
181
+ paddingTop: offsets.value[start.value],
182
+ paddingBottom: total - offsets.value[end.value],
183
+ overflow: 'scroll' as const,
156
184
  }
157
185
 
158
186
  // Other attributes (refreshing, @refresh...) fall through to the ScrollView.
159
187
  return h('ScrollView', { style: props.style, onScroll: handleScroll }, [
160
- slots.header?.({}),
161
- h('View', { style: window }, props.data.slice(start, end).map(renderRow)),
188
+ renderHeader(),
189
+ h('View', { style: window }, props.data.slice(start.value, end.value).map(renderRow)),
162
190
  props.data.length === 0 ? slots.empty?.({}) : null,
163
191
  slots.footer?.({}),
164
192
  ])
@@ -166,6 +194,17 @@ export const FlatList = defineComponent({
166
194
  },
167
195
  })
168
196
 
197
+ function averageOf(values: Iterable<number>): number | undefined {
198
+ let sum = 0
199
+ let count = 0
200
+ for (const value of values) {
201
+ sum += value
202
+ count++
203
+ }
204
+
205
+ return count === 0 ? undefined : sum / count
206
+ }
207
+
169
208
  const SWIPE_ACTIONS_STYLE: Style = { position: 'absolute', top: 0, bottom: 0, flexDirection: 'row' }
170
209
  const SWIPE_LEFT_ACTIONS_STYLE: Style = { ...SWIPE_ACTIONS_STYLE, left: 0 }
171
210
  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
+ }
@@ -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<Props & { style?: Style } & AccessibilityProps>
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 {
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[MODEL_EVENT_BY_NATIVE_EVENT[eventName]]?.(payload)
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
- native.setProp(element.id, 'value', value ?? '')
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 !== oldValue) native.setProp(element.id, 'value', 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
- remove(id: number): void
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