@nativue/core 0.4.2 → 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.
@@ -0,0 +1,69 @@
1
+ package dev.nativue
2
+
3
+ import android.content.Context
4
+ import android.provider.Settings
5
+ import android.view.View
6
+ import android.view.ViewGroup
7
+ import android.view.accessibility.AccessibilityManager
8
+ import android.view.accessibility.AccessibilityNodeInfo
9
+
10
+ private val CLASS_NAME_BY_ROLE = mapOf(
11
+ "button" to "android.widget.Button",
12
+ "img" to "android.widget.ImageView",
13
+ "text" to "android.widget.TextView",
14
+ "switch" to "android.widget.Switch",
15
+ "checkbox" to "android.widget.CheckBox",
16
+ )
17
+
18
+ /** role, alt and aria-*, from the renderer: all of them, whenever one changes. */
19
+ fun View.applyAccessibility(attributes: Map<*, *>) {
20
+ val role = attributes["role"] as? String
21
+ val label = attributes["label"] as? String
22
+ val isHidden = attributes["hidden"] != null
23
+ val isElement = !isHidden && role != "none" && (role != null || label != null)
24
+
25
+ contentDescription = label
26
+ importantForAccessibility = when {
27
+ isHidden -> View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
28
+ role == "none" -> View.IMPORTANT_FOR_ACCESSIBILITY_NO
29
+ isElement -> View.IMPORTANT_FOR_ACCESSIBILITY_YES
30
+ else -> View.IMPORTANT_FOR_ACCESSIBILITY_AUTO
31
+ }
32
+ // TalkBack reads a focusable container as one element: the text inside it, as a <button> does on the web.
33
+ isScreenReaderFocusable = isElement && this is ViewGroup
34
+ isAccessibilityHeading = role == "heading"
35
+ accessibilityDelegate = AccessibilityAttributes(role, attributes)
36
+ }
37
+
38
+ private class AccessibilityAttributes(
39
+ private val role: String?,
40
+ private val attributes: Map<*, *>,
41
+ ) : View.AccessibilityDelegate() {
42
+ override fun onInitializeAccessibilityNodeInfo(host: View, info: AccessibilityNodeInfo) {
43
+ super.onInitializeAccessibilityNodeInfo(host, info)
44
+
45
+ CLASS_NAME_BY_ROLE[role]?.let { info.className = it }
46
+ // Where TalkBack reads a role description (androidx sets the same key).
47
+ // Limitation: Android has no link role for views; this description is English whatever the language.
48
+ if (role == "link") info.extras.putCharSequence("AccessibilityNodeInfo.roleDescription", "link")
49
+ (attributes["hint"] as? String)?.let { info.hintText = it }
50
+ if (attributes["disabled"] != null) info.isEnabled = false
51
+ if (attributes["selected"] != null) info.isSelected = true
52
+ if (role == "switch" || role == "checkbox") {
53
+ info.isCheckable = true
54
+ @Suppress("DEPRECATION") // its replacement, setChecked(Int), is API 36+
55
+ info.isChecked = attributes["checked"] != null
56
+ }
57
+ }
58
+ }
59
+
60
+ /** For AccessibilityInfo; both are safe to read off the main thread. */
61
+ fun accessibilityStatus(context: Context): Map<String, Boolean> {
62
+ val accessibilityManager = context.getSystemService(AccessibilityManager::class.java)
63
+ val animationScale = Settings.Global.getFloat(context.contentResolver, Settings.Global.ANIMATOR_DURATION_SCALE, 1f)
64
+
65
+ return mapOf(
66
+ "screenReaderEnabled" to accessibilityManager.isTouchExplorationEnabled,
67
+ "reduceMotionEnabled" to (animationScale == 0f),
68
+ )
69
+ }
@@ -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
@@ -127,8 +130,50 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
127
130
  null
128
131
  }
129
132
 
130
- /** The system may have switched between light and dark: nativue's views repaint, then JS is told. */
131
133
  fun onConfigurationChanged() {
134
+ updateFontScale()
135
+ updateColorScheme()
136
+ updateWindowSize()
137
+ }
138
+
139
+ /** Rotation and split view resize the window. */
140
+ private fun updateWindowSize() {
141
+ val nextWindowSize = windowSize()
142
+ if (nextWindowSize == windowSize) return
143
+
144
+ windowSize = nextWindowSize
145
+ evaluate { runtime?.call("__windowSizeChanged", nextWindowSize) }
146
+ }
147
+
148
+ private var fontScale = activity.resources.configuration.fontScale
149
+
150
+ /** The system's text size changed: text is sized again, and laid out again. */
151
+ private fun updateFontScale() {
152
+ val nextFontScale = activity.resources.configuration.fontScale
153
+ if (nextFontScale == fontScale) return
154
+
155
+ val nodeViews = nodesById.values.mapTo(HashSet()) { it.view }
156
+ rescaleText(activity.window.decorView, nodeViews, nextFontScale / fontScale)
157
+ fontScale = nextFontScale
158
+ nodesById.values.forEach { it.updateFontSize() }
159
+ rootView.requestLayout()
160
+ }
161
+
162
+ /**
163
+ * Headers set their text in sp once: scale it by as much as the system's text size changed. Text in dp
164
+ * (tab labels) keeps its size.
165
+ */
166
+ private fun rescaleText(view: View, nodeViews: Set<View>, ratio: Float) {
167
+ if (view is TextView && view !in nodeViews && view.textSizeUnit != TypedValue.COMPLEX_UNIT_DIP) {
168
+ view.setTextSize(TypedValue.COMPLEX_UNIT_PX, view.textSize * ratio)
169
+ }
170
+ if (view !is ViewGroup) return
171
+
172
+ for (index in 0 until view.childCount) rescaleText(view.getChildAt(index), nodeViews, ratio)
173
+ }
174
+
175
+ /** The system may have switched between light and dark: nativue's views repaint, then JS is told. */
176
+ private fun updateColorScheme() {
132
177
  if (!ThemeColors.update(activity)) return
133
178
 
134
179
  applyThemeColors(activity.window.decorView)
@@ -275,9 +320,15 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
275
320
  private fun nativeFunctions(): Map<String, NativeFunction> = buildMap {
276
321
  put("log") { arguments -> Log.i(TAG, "[JS] ${arguments[0]}") }
277
322
  put("reportError") { arguments -> reportError(arguments[0] as String, arguments[1] as String) }
278
- put("windowSize") { _ -> windowSize() }
323
+ put("windowSize") { _ -> windowSize }
279
324
  put("platform") { _ -> "android" }
280
325
  put("colorScheme") { _ -> colorScheme() }
326
+ put("accessibilityInfo") { _ -> accessibilityStatus(activity) }
327
+ put("announce") { arguments ->
328
+ val message = arguments[0] as String
329
+ @Suppress("DEPRECATION") // its replacements (live regions, pane titles) need a view to describe
330
+ mainHandler.post { rootView.announceForAccessibility(message) }
331
+ }
281
332
  // Prefixed, so a plugin can't replace nativue's own functions.
282
333
  pluginRegistry.functions.forEach { (name, function) -> put("plugin:$name", function) }
283
334
  pluginRegistry.asyncFunctions.forEach { (name, function) -> put("pluginAsync:$name", asyncCall(function)) }
@@ -292,7 +343,8 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
292
343
  }
293
344
  put("remove") { arguments ->
294
345
  val id = int(arguments[0])
295
- enqueue { nodesById[id]?.let(::removeNode) }
346
+ val subtreeIds = (arguments[1] as List<*>).map(::int)
347
+ enqueue { removeNode(id, subtreeIds) }
296
348
  }
297
349
  put("setText") { arguments ->
298
350
  val id = int(arguments[0])
@@ -312,11 +364,13 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
312
364
  putAll(fetchFunctions())
313
365
  }
314
366
 
315
- /** `windowSize` is read from JS, off the main thread: the display's size doesn't need the views. */
367
+ /** Read from JS, off the main thread: the window's size doesn't need the views. */
368
+ @Volatile private var windowSize = windowSize()
369
+
316
370
  private fun windowSize(): Map<String, Float> {
317
- val metrics = activity.resources.displayMetrics
371
+ val bounds = activity.windowManager.currentWindowMetrics.bounds
318
372
 
319
- return mapOf("width" to metrics.widthPixels / density, "height" to metrics.heightPixels / density)
373
+ return mapOf("width" to bounds.width() / density, "height" to bounds.height() / density)
320
374
  }
321
375
 
322
376
  /** A timer of a runtime that has since been reloaded doesn't fire. */
@@ -486,24 +540,20 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
486
540
  // ---------- Main thread ----------
487
541
 
488
542
  /** Vue removes only a subtree's root: the nodes under it are forgotten with it. */
489
- private fun removeNode(root: NativeNode) {
490
- val removedViews = mutableSetOf<View>()
491
- collectViews(root.view, removedViews)
492
- root.contentNode?.let { collectViews(it.view, removedViews) }
493
-
494
- // Limitation: A nested <Modal>'s content isn't under the root's views, so its nodes stay; walk the
495
- // modal hosts too if apps nest many. Hosts stay: layout dismisses the detached ones.
496
- val removedIds = nodesById.filterValues { it.view in removedViews }.keys
497
- removedIds.forEach { id ->
498
- nodesById.remove(id)
499
- gestureReportersByNodeId.remove(id)
500
- }
501
- root.removeFromParent()
543
+ private fun removeNode(id: Int, subtreeIds: List<Int>) {
544
+ nodesById[id]?.removeFromParent()
545
+ subtreeIds.forEach(::forgetNode)
502
546
  }
503
547
 
504
- private fun collectViews(view: View, views: MutableSet<View>) {
505
- views.add(view)
506
- if (view is ViewGroup) (0 until view.childCount).forEach { collectViews(view.getChildAt(it), views) }
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
+ }
507
557
  }
508
558
 
509
559
  private fun resetNodeTree() {
@@ -513,6 +563,7 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
513
563
  }
514
564
  modalHostsByNodeId.clear()
515
565
  gestureReportersByNodeId.clear() // node ids start over
566
+ reportedLayoutsByNodeId.clear()
516
567
  animatedGraph.reset()
517
568
  animatedGraph.onAnimationEnd = { animationId, finished ->
518
569
  evaluate { runtime?.call("__animationFinished", animationId, finished) }
@@ -582,7 +633,15 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
582
633
  }
583
634
  }
584
635
 
585
- "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
+ }
586
645
 
587
646
  "SwipeableView" -> NativeNode(SwipeableView(activity), measuresContent = false)
588
647
 
@@ -627,14 +686,14 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
627
686
 
628
687
  private fun makeTextView() = TextLabel(activity).apply {
629
688
  applyThemeColors()
630
- setTextSize(TypedValue.COMPLEX_UNIT_DIP, 17f)
689
+ setTextSize(TypedValue.COMPLEX_UNIT_SP, 17f)
631
690
  includeFontPadding = false
632
691
  }
633
692
 
634
693
  private fun makeTextInput(id: Int): TextInputView {
635
694
  val textInput = TextInputView(activity)
636
695
  textInput.background = null
637
- textInput.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 17f)
696
+ textInput.setTextSize(TypedValue.COMPLEX_UNIT_SP, 17f)
638
697
  textInput.applyThemeColors()
639
698
  textInput.isSingleLine = true
640
699
  textInput.gravity = Gravity.CENTER_VERTICAL
@@ -672,6 +731,31 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
672
731
  node.yogaNode.setHeight(side)
673
732
  }
674
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
+
675
759
  private fun dispatchEvent(eventName: String, id: Int, payload: Any? = null) {
676
760
  evaluate { runtime?.call("__dispatch", id, eventName, payload) }
677
761
  }
@@ -757,6 +841,10 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
757
841
 
758
842
  "showsVerticalScrollIndicator" -> (view as? ScrollContainerView)?.showsVerticalScrollIndicator = isTruthyAttribute(value)
759
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
+
760
848
  "onScroll" -> (view as? ScrollContainerView)?.onScroll = if (isTruthyAttribute(value)) reportScroll(node, id) else null
761
849
 
762
850
  "value" -> {
@@ -764,6 +852,8 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
764
852
  (view as? ToggleSwitch)?.setCheckedFromJavaScript(isTruthyAttribute(value))
765
853
  }
766
854
 
855
+ "accessibility" -> view.applyAccessibility(value as? Map<*, *> ?: emptyMap<Any, Any>())
856
+
767
857
  "disabled" -> {
768
858
  view.isEnabled = !isTruthyAttribute(value)
769
859
  if (view is TextView && view !is EditText) view.alpha = if (view.isEnabled) 1f else 0.38f
@@ -781,7 +871,7 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
781
871
 
782
872
  "keyboardShouldPersistTaps" -> (view as? ScrollContainerView)?.dismissesKeyboardOnTap = (value as? String ?: "never") == "never"
783
873
 
784
- "onPan", "onPinch", "onRotate" -> gestureReporter(id, view).setReporting(key.drop(2).lowercase(), isTruthyAttribute(value))
874
+ "onPan", "onPinch", "onRotate" -> gestureReporter(id, view)?.setReporting(key.drop(2).lowercase(), isTruthyAttribute(value))
785
875
 
786
876
  "animating" -> view.visibility = if (isTruthyAttribute(value)) View.VISIBLE else View.INVISIBLE
787
877
 
@@ -836,7 +926,8 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
836
926
  val scrollView = view as? ScrollContainerView
837
927
  if (scrollView == null || eventName != "scroll") {
838
928
  val fieldsToNodeIds = mapping?.entries?.associate { (field, nodeId) -> field.toString() to int(nodeId) }
839
- return gestureReporter(viewId, view).setAnimatedMapping(eventName, fieldsToNodeIds)
929
+ gestureReporter(viewId, view)?.setAnimatedMapping(eventName, fieldsToNodeIds)
930
+ return
840
931
  }
841
932
 
842
933
  if (mapping == null) {
@@ -852,13 +943,19 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
852
943
  }
853
944
  }
854
945
 
855
- private fun gestureReporter(id: Int, view: View): GestureReporter = gestureReportersByNodeId.getOrPut(id) {
946
+ /** Gestures are on <View>s, which are containers. */
947
+ private fun gestureReporter(id: Int, view: View): GestureReporter? {
948
+ if (view !is ContainerView) return null
949
+
950
+ return gestureReportersByNodeId.getOrPut(id) { makeGestureReporter(id, view) }
951
+ }
952
+
953
+ private fun makeGestureReporter(id: Int, view: ContainerView) =
856
954
  GestureReporter(
857
955
  view,
858
956
  report = { eventName, payload -> dispatchEvent(eventName, id, payload) },
859
957
  setAnimatedValue = { nodeId, value -> animatedGraph.setValue(value, nodeId) },
860
958
  )
861
- }
862
959
 
863
960
  private fun reportScroll(node: NativeNode, id: Int): (Int, Int) -> Unit = { x, y ->
864
961
  val payload = mapOf(
@@ -17,14 +17,14 @@ import kotlin.math.hypot
17
17
  * gesture's state ("began", "changed", "ended", "cancelled"), so it can move the view through its
18
18
  * style; with Animated.event the values move natively and JS only hears the start and the end.
19
19
  * Numbers are in dp (and dp per second); rotation in radians. Mirrors ios/GestureReporter.swift.
20
- * Limitation: Unlike on iOS, a parent doesn't see touches a child consumes (a <Pressable> inside a draggable
21
- * card); intercept moves past the touch slop if that's needed.
20
+ * It sees every touch on its view, children's included (see ContainerView.dispatchTouchEvent), so a
21
+ * <Pressable> inside a draggable card still lets the card be dragged.
22
22
  */
23
23
  class GestureReporter(
24
- private val view: View,
24
+ private val view: ContainerView,
25
25
  private val report: (eventName: String, payload: Map<String, Any>) -> Unit,
26
26
  private val setAnimatedValue: (nodeId: Int, value: Double) -> Unit,
27
- ) : View.OnTouchListener {
27
+ ) {
28
28
  private val reportedEvents = mutableSetOf<String>()
29
29
 
30
30
  /** From Animated.event: event field -> animated value id. */
@@ -50,17 +50,19 @@ class GestureReporter(
50
50
  private var lastRotation = 0f
51
51
  private var lastTime = 0L
52
52
 
53
+ /** Once a gesture is recognized, the view takes the touch from its children. */
54
+ val isRecognizing get() = isPanning || isPinching || isRotating
55
+
53
56
  fun setReporting(eventName: String, isReporting: Boolean) {
54
57
  if (isReporting) reportedEvents.add(eventName) else reportedEvents.remove(eventName)
55
- view.setOnTouchListener(if (reportedEvents.isEmpty()) null else this)
58
+ view.gestureReporter = if (reportedEvents.isEmpty()) null else this
56
59
  }
57
60
 
58
61
  fun setAnimatedMapping(eventName: String, mapping: Map<String, Int>?) {
59
62
  if (mapping == null) animatedMappingsByEvent.remove(eventName) else animatedMappingsByEvent[eventName] = mapping
60
63
  }
61
64
 
62
- @SuppressLint("ClickableViewAccessibility")
63
- override fun onTouch(touchedView: View, event: MotionEvent): Boolean {
65
+ fun handle(event: MotionEvent) {
64
66
  val tracker = velocityTracker ?: VelocityTracker.obtain().also { velocityTracker = it }
65
67
  // Raw coordinates: moving the view with a transform doesn't skew the numbers.
66
68
  val rawEvent = MotionEvent.obtain(event).apply { setLocation(event.rawX, event.rawY) }
@@ -74,8 +76,6 @@ class GestureReporter(
74
76
  MotionEvent.ACTION_UP -> finish("ended")
75
77
  MotionEvent.ACTION_CANCEL -> finish("cancelled")
76
78
  }
77
-
78
- return true
79
79
  }
80
80
 
81
81
  private fun track(event: MotionEvent) {
@@ -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
@@ -647,7 +647,8 @@ private class TabItemView(context: Context) : LinearLayout(context) {
647
647
  clipChildren = false
648
648
 
649
649
  indicator.addView(icon, FrameLayout.LayoutParams(dp(24f), dp(24f), Gravity.CENTER))
650
- badge.setTextSize(TypedValue.COMPLEX_UNIT_SP, 11f)
650
+ // In dp: like iOS's, tab labels keep their size whatever the system's text size, so they fit the bar.
651
+ badge.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 11f)
651
652
  badge.setTextColor(0xFFFFFFFF.toInt())
652
653
  badge.gravity = Gravity.CENTER
653
654
  badge.setPadding(dp(4f), 0, dp(4f), 0)
@@ -663,7 +664,7 @@ private class TabItemView(context: Context) : LinearLayout(context) {
663
664
  indicator.clipChildren = false
664
665
  addView(indicator, LayoutParams(dp(64f), dp(32f)))
665
666
 
666
- label.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12f)
667
+ label.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12f)
667
668
  label.typeface = Typeface.create(Typeface.DEFAULT, 500, false)
668
669
  label.gravity = Gravity.CENTER
669
670
  label.isSingleLine = true
@@ -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,12 +108,21 @@ 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
- textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, fontSize)
115
115
  textView.typeface = Typeface.create(Typeface.DEFAULT, fontWeight, false)
116
+ updateFontSize()
117
+ }
118
+
119
+ /**
120
+ * In sp: scaled to the system's text size, like the platform's own text. Android converts sp when it's
121
+ * set, so this runs again when that size changes.
122
+ */
123
+ fun NativeNode.updateFontSize() {
124
+ val textView = view as? TextView ?: return
125
+ textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSize)
116
126
 
117
127
  markContentChanged()
118
128
  }
@@ -211,6 +221,22 @@ private val textGravities = mapOf(
211
221
 
212
222
  private typealias LayoutPropertySetter = (YogaNode, Any) -> Unit
213
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
+
214
240
  private val layoutPropertySetters: Map<String, LayoutPropertySetter> = buildMap {
215
241
  put("flexDirection", enumSetter(flexDirections, YogaNode::setFlexDirection))
216
242
  put("justifyContent", enumSetter(justifications, YogaNode::setJustifyContent))