@nativue/core 0.11.1 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/Package.swift CHANGED
@@ -4,7 +4,7 @@ import PackageDescription
4
4
  // The native side of nativue, consumed by the app's Xcode project as a local package.
5
5
  let package = Package(
6
6
  name: "Nativue",
7
- platforms: [.iOS(.v17)],
7
+ platforms: [.iOS("15.1")],
8
8
  products: [.library(name: "Nativue", targets: ["Nativue"])],
9
9
  dependencies: [.package(url: "https://github.com/facebook/yoga.git", .upToNextMinor(from: "3.2.2"))],
10
10
  targets: [
@@ -20,12 +20,12 @@ fun localNetworkAddress(): String? = NetworkInterface.getNetworkInterfaces().toL
20
20
 
21
21
  android {
22
22
  namespace = "dev.nativue"
23
- compileSdk = 36
23
+ compileSdk = 37
24
24
  ndkVersion = "27.1.12297006"
25
25
 
26
26
  defaultConfig {
27
- // Limitation: 30 for the WindowInsets.Type API (safe area, keyboard); lower it with the compat insets if needed.
28
- minSdk = 30
27
+ // Hermes's own minimum.
28
+ minSdk = 24
29
29
  consumerProguardFiles("consumer-rules.pro")
30
30
 
31
31
  externalNativeBuild {
@@ -71,4 +71,6 @@ dependencies {
71
71
  implementation("com.facebook.hermes:hermes-android:260318099.0.8")
72
72
  implementation("com.facebook.yoga:yoga:3.2.1")
73
73
  implementation("com.facebook.soloader:soloader:0.10.5")
74
+ // Insets, system bars, fonts and accessibility the same way down to minSdk.
75
+ implementation("androidx.core:core:1.16.0")
74
76
  }
@@ -6,6 +6,8 @@ import android.view.View
6
6
  import android.view.ViewGroup
7
7
  import android.view.accessibility.AccessibilityManager
8
8
  import android.view.accessibility.AccessibilityNodeInfo
9
+ import androidx.core.view.ViewCompat
10
+ import androidx.core.view.accessibility.AccessibilityNodeInfoCompat
9
11
 
10
12
  private val CLASS_NAME_BY_ROLE = mapOf(
11
13
  "button" to "android.widget.Button",
@@ -30,8 +32,8 @@ fun View.applyAccessibility(attributes: Map<*, *>) {
30
32
  else -> View.IMPORTANT_FOR_ACCESSIBILITY_AUTO
31
33
  }
32
34
  // 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
+ ViewCompat.setScreenReaderFocusable(this, isElement && this is ViewGroup)
36
+ ViewCompat.setAccessibilityHeading(this, role == "heading")
35
37
  accessibilityDelegate = AccessibilityAttributes(role, attributes)
36
38
  }
37
39
 
@@ -46,7 +48,7 @@ private class AccessibilityAttributes(
46
48
  // Where TalkBack reads a role description (androidx sets the same key).
47
49
  // Limitation: Android has no link role for views; this description is English whatever the language.
48
50
  if (role == "link") info.extras.putCharSequence("AccessibilityNodeInfo.roleDescription", "link")
49
- (attributes["hint"] as? String)?.let { info.hintText = it }
51
+ (attributes["hint"] as? String)?.let { AccessibilityNodeInfoCompat.wrap(info).hintText = it }
50
52
  if (attributes["disabled"] != null) info.isEnabled = false
51
53
  if (attributes["selected"] != null) info.isSelected = true
52
54
  if (role == "switch" || role == "checkbox") {
@@ -89,6 +89,8 @@ class AnimatedGraph {
89
89
  updateBoundViews()
90
90
  }
91
91
 
92
+ fun drives(view: View): Boolean = bindingsByViewId.values.any { it.view.get() === view }
93
+
92
94
  // ---------- Animations ----------
93
95
 
94
96
  fun startAnimation(animationId: Int, nodeId: Int, config: Map<*, *>) {
@@ -17,9 +17,10 @@ import android.util.TypedValue
17
17
  import android.view.Gravity
18
18
  import android.view.View
19
19
  import android.view.ViewGroup
20
- import android.view.WindowInsets
21
- import android.view.WindowInsetsAnimation
22
- import android.graphics.Insets
20
+ import androidx.core.graphics.Insets
21
+ import androidx.core.view.ViewCompat
22
+ import androidx.core.view.WindowInsetsAnimationCompat
23
+ import androidx.core.view.WindowInsetsCompat
23
24
  import android.view.inputmethod.EditorInfo
24
25
  import android.view.inputmethod.InputMethodManager
25
26
  import android.widget.EditText
@@ -75,7 +76,7 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
75
76
  private val reportedLayoutsByNodeId = mutableMapOf<Int, Map<String, Float>?>()
76
77
 
77
78
  /** The latest window insets, mid-animation while the keyboard moves. */
78
- private var windowInsets: WindowInsets? = null
79
+ private var windowInsets: WindowInsetsCompat? = null
79
80
 
80
81
  /** Whether the system back gesture has something to close or pop (NativueActivity listens). */
81
82
  var onCanGoBackChange: (canGoBack: Boolean) -> Unit = {}
@@ -88,19 +89,23 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
88
89
  NativeNode.setPixelDensity(density)
89
90
  rootView.onLayoutPass = ::layout
90
91
  NativeNode.onLayoutCalculated = ::reportLayoutChanges
91
- rootView.setOnApplyWindowInsetsListener { view, insets ->
92
+ ViewCompat.setOnApplyWindowInsetsListener(rootView) { view, insets ->
92
93
  windowInsets = insets
93
94
  view.requestLayout() // safe area and keyboard paddings
94
95
  insets
95
96
  }
96
97
  // Keyboard avoiding views follow the keyboard frame by frame, like on iOS.
97
- rootView.setWindowInsetsAnimationCallback(object : WindowInsetsAnimation.Callback(DISPATCH_MODE_CONTINUE_ON_SUBTREE) {
98
- override fun onProgress(insets: WindowInsets, animations: List<WindowInsetsAnimation>): WindowInsets {
98
+ val keyboardAnimation = object : WindowInsetsAnimationCompat.Callback(DISPATCH_MODE_CONTINUE_ON_SUBTREE) {
99
+ override fun onProgress(
100
+ insets: WindowInsetsCompat,
101
+ runningAnimations: List<WindowInsetsAnimationCompat>,
102
+ ): WindowInsetsCompat {
99
103
  windowInsets = insets
100
104
  layout()
101
105
  return insets
102
106
  }
103
- })
107
+ }
108
+ ViewCompat.setWindowInsetsAnimationCallback(rootView, keyboardAnimation)
104
109
 
105
110
  val bundle = runCatching { activity.assets.open("main.bundle.js").use { it.readBytes() } }.getOrNull()
106
111
  if (bundle != null) run(bundle)
@@ -167,7 +172,7 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
167
172
  * (tab labels) keeps its size.
168
173
  */
169
174
  private fun rescaleText(view: View, nodeViews: Set<View>, ratio: Float) {
170
- if (view is TextView && view !in nodeViews && view.textSizeUnit != TypedValue.COMPLEX_UNIT_DIP) {
175
+ if (view is TextView && view !is FixedSizeTextView && view !in nodeViews) {
171
176
  view.setTextSize(TypedValue.COMPLEX_UNIT_PX, view.textSize * ratio)
172
177
  }
173
178
  if (view !is ViewGroup) return
@@ -243,7 +248,7 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
243
248
  layoutAnimation.captureStart(nodesById.values)
244
249
  operations.forEach { it() }
245
250
  layout()
246
- layoutAnimation.animateChanges(nodesById.values)
251
+ layoutAnimation.animateChanges(nodesById.values, animatedGraph::drives)
247
252
  }
248
253
 
249
254
  private fun startJavaScriptThread(): Handler {
@@ -370,9 +375,16 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
370
375
  @Volatile private var windowSize = windowSize()
371
376
 
372
377
  private fun windowSize(): Map<String, Float> {
373
- val bounds = activity.windowManager.currentWindowMetrics.bounds
378
+ val size = android.graphics.Point()
379
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
380
+ val bounds = activity.windowManager.currentWindowMetrics.bounds
381
+ size.set(bounds.width(), bounds.height())
382
+ } else {
383
+ @Suppress("DEPRECATION") // its replacement, currentWindowMetrics, is API 30+
384
+ activity.windowManager.defaultDisplay.getRealSize(size)
385
+ }
374
386
 
375
- return mapOf("width" to bounds.width() / density, "height" to bounds.height() / density)
387
+ return mapOf("width" to size.x / density, "height" to size.y / density)
376
388
  }
377
389
 
378
390
  /** A timer of a runtime that has since been reloaded doesn't fire. */
@@ -985,9 +997,9 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
985
997
  return didChange
986
998
  }
987
999
 
988
- private fun currentWindowInsets(): WindowInsets? = windowInsets ?: rootView.rootWindowInsets
1000
+ private fun currentWindowInsets(): WindowInsetsCompat? = windowInsets ?: ViewCompat.getRootWindowInsets(rootView)
989
1001
 
990
- private fun fitScreen(node: NativeNode, screen: ScreenView, windowInsets: WindowInsets): Boolean {
1002
+ private fun fitScreen(node: NativeNode, screen: ScreenView, windowInsets: WindowInsetsCompat): Boolean {
991
1003
  var didChange = false
992
1004
 
993
1005
  if (screen.isSheet) {
@@ -1007,7 +1019,7 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
1007
1019
  return didChange
1008
1020
  }
1009
1021
 
1010
- private fun fitTabBar(node: NativeNode, tabBar: TabBarView, windowInsets: WindowInsets): Boolean {
1022
+ private fun fitTabBar(node: NativeNode, tabBar: TabBarView, windowInsets: WindowInsetsCompat): Boolean {
1011
1023
  tabBar.bottomInset = (overlap(tabBar, windowInsets.getInsets(SYSTEM_BARS))[3] * density).toInt()
1012
1024
 
1013
1025
  var didChange = false
@@ -1063,8 +1075,8 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
1063
1075
  const val SVG_DEFAULT_COLOR = 0xFF000000.toInt()
1064
1076
  const val BUTTON_TINT = 0xFF007AFF.toInt()
1065
1077
  val EDGES = listOf(YogaEdge.LEFT, YogaEdge.TOP, YogaEdge.RIGHT, YogaEdge.BOTTOM)
1066
- val SYSTEM_BARS = WindowInsets.Type.systemBars() or WindowInsets.Type.displayCutout()
1067
- val IME = WindowInsets.Type.ime()
1078
+ val SYSTEM_BARS = WindowInsetsCompat.Type.systemBars() or WindowInsetsCompat.Type.displayCutout()
1079
+ val IME = WindowInsetsCompat.Type.ime()
1068
1080
  const val SHEET_TOP_GAP = 12f
1069
1081
 
1070
1082
  val keyboardInputTypes = mapOf(
@@ -7,11 +7,12 @@ import android.graphics.drawable.GradientDrawable
7
7
  import android.util.TypedValue
8
8
  import android.view.Gravity
9
9
  import android.view.ViewGroup
10
- import android.view.WindowInsets
11
10
  import android.widget.FrameLayout
12
11
  import android.widget.LinearLayout
13
12
  import android.widget.ScrollView
14
13
  import android.widget.TextView
14
+ import androidx.core.view.ViewCompat
15
+ import androidx.core.view.WindowInsetsCompat
15
16
 
16
17
  /**
17
18
  * Development only: shows a JS error over the whole app, modals included. The first error stays until
@@ -42,8 +43,8 @@ class ErrorOverlay(private val activity: Activity) {
42
43
  layout.orientation = LinearLayout.VERTICAL
43
44
  layout.setBackgroundColor(BACKGROUND)
44
45
  layout.isClickable = true // keeps touches from reaching the app below
45
- layout.setOnApplyWindowInsetsListener { view, insets ->
46
- val bars = insets.getInsets(WindowInsets.Type.systemBars())
46
+ ViewCompat.setOnApplyWindowInsetsListener(layout) { view, insets ->
47
+ val bars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
47
48
  view.setPadding(bars.left + dp(20), bars.top + dp(24), bars.right + dp(20), bars.bottom + dp(16))
48
49
  insets
49
50
  }
@@ -99,7 +100,7 @@ class ErrorOverlay(private val activity: Activity) {
99
100
  setTextSize(TypedValue.COMPLEX_UNIT_SP, size)
100
101
  setTextColor(Color.WHITE)
101
102
  this.alpha = alpha
102
- typeface = Typeface.create(Typeface.DEFAULT, weight, false)
103
+ typeface = typefaceOfWeight(context, weight)
103
104
  }
104
105
 
105
106
  private fun rounded(color: Int) = GradientDrawable().apply {
@@ -46,7 +46,7 @@ class LayoutAnimation(config: Map<*, *>) {
46
46
  }
47
47
 
48
48
  /** Call after the batch is applied and laid out: animates every view from where it was. */
49
- fun animateChanges(nodes: Collection<NativeNode>) {
49
+ fun animateChanges(nodes: Collection<NativeNode>, isDrivenByAnimated: (View) -> Boolean) {
50
50
  val changes = nodes.mapNotNull { node ->
51
51
  val start = statesByView[node.view]?.takeIf { it.isPlaced }
52
52
  val end = State(node.view, node.view.background as? BoxDrawable)
@@ -54,23 +54,24 @@ class LayoutAnimation(config: Map<*, *>) {
54
54
  }
55
55
  if (changes.isEmpty()) return
56
56
 
57
- changes.forEach { (view, start, end) -> apply(view, start, end, 0f) }
57
+ val drivenViews = changes.map { it.first }.filterTo(HashSet(), isDrivenByAnimated)
58
+ changes.forEach { (view, start, end) -> apply(view, start, end, 0f, view in drivenViews) }
58
59
 
59
60
  ValueAnimator.ofFloat(0f, 1f).apply {
60
61
  duration = this@LayoutAnimation.duration
61
62
  interpolator = interpolator()
62
63
  addUpdateListener { animator ->
63
64
  val progress = animator.animatedValue as Float
64
- changes.forEach { (view, start, end) -> apply(view, start, end, progress) }
65
+ changes.forEach { (view, start, end) -> apply(view, start, end, progress, view in drivenViews) }
65
66
  }
66
67
  start()
67
68
  }
68
69
  }
69
70
 
70
71
  /** A view without a start state (new, or never placed) only fades in. */
71
- private fun apply(view: View, start: State?, end: State, progress: Float) {
72
+ private fun apply(view: View, start: State?, end: State, progress: Float, isDrivenByAnimated: Boolean) {
72
73
  if (start == null) {
73
- view.alpha = end.alpha * progress
74
+ if (!isDrivenByAnimated) view.alpha = end.alpha * progress
74
75
  return
75
76
  }
76
77
 
@@ -83,12 +84,14 @@ class LayoutAnimation(config: Map<*, *>) {
83
84
  view.layout(left, top, right, bottom)
84
85
  }
85
86
 
86
- view.alpha = lerp(start.alpha, end.alpha, progress)
87
- view.translationX = lerp(start.translationX, end.translationX, progress)
88
- view.translationY = lerp(start.translationY, end.translationY, progress)
89
- view.scaleX = lerp(start.scaleX, end.scaleX, progress)
90
- view.scaleY = lerp(start.scaleY, end.scaleY, progress)
91
- view.rotation = lerp(start.rotation, end.rotation, progress)
87
+ if (!isDrivenByAnimated) {
88
+ view.alpha = lerp(start.alpha, end.alpha, progress)
89
+ view.translationX = lerp(start.translationX, end.translationX, progress)
90
+ view.translationY = lerp(start.translationY, end.translationY, progress)
91
+ view.scaleX = lerp(start.scaleX, end.scaleX, progress)
92
+ view.scaleY = lerp(start.scaleY, end.scaleY, progress)
93
+ view.rotation = lerp(start.rotation, end.rotation, progress)
94
+ }
92
95
 
93
96
  end.box?.takeIf { start.backgroundColor != end.backgroundColor }?.let { box ->
94
97
  box.backgroundColor = argbEvaluator.evaluate(progress.coerceIn(0f, 1f), start.backgroundColor, end.backgroundColor) as Int
@@ -2,7 +2,7 @@ package dev.nativue
2
2
 
3
3
  import android.view.View
4
4
  import android.view.ViewGroup
5
- import android.widget.EditText
5
+ import android.widget.TextView
6
6
  import com.facebook.yoga.YogaConfigFactory
7
7
  import com.facebook.yoga.YogaEdge
8
8
  import com.facebook.yoga.YogaMeasureMode
@@ -96,7 +96,7 @@ class NativeNode(val view: View, measuresContent: Boolean) {
96
96
  scrollView.setContentSize(pixels(width), pixels(height))
97
97
  }
98
98
 
99
- (view as? EditText)?.setPadding(
99
+ (view as? TextView)?.setPadding(
100
100
  pixels(yogaNode.getLayoutPadding(YogaEdge.LEFT)),
101
101
  pixels(yogaNode.getLayoutPadding(YogaEdge.TOP)),
102
102
  pixels(yogaNode.getLayoutPadding(YogaEdge.RIGHT)),
@@ -130,13 +130,18 @@ class NativeNode(val view: View, measuresContent: Boolean) {
130
130
  height: Float,
131
131
  heightMode: YogaMeasureMode,
132
132
  ): Long {
133
- view.measure(measureSpec(width, widthMode), measureSpec(height, heightMode))
133
+ val horizontalPadding = view.paddingLeft + view.paddingRight
134
+ val verticalPadding = view.paddingTop + view.paddingBottom
135
+ view.measure(measureSpec(width, widthMode, horizontalPadding), measureSpec(height, heightMode, verticalPadding))
134
136
 
135
- return YogaMeasureOutput.make(view.measuredWidth / density, view.measuredHeight / density)
137
+ return YogaMeasureOutput.make(
138
+ (view.measuredWidth - horizontalPadding) / density,
139
+ (view.measuredHeight - verticalPadding) / density,
140
+ )
136
141
  }
137
142
 
138
- private fun measureSpec(size: Float, mode: YogaMeasureMode): Int {
139
- val pixels = if (size.isNaN()) 0 else (size * density).toInt()
143
+ private fun measureSpec(size: Float, mode: YogaMeasureMode, padding: Int): Int {
144
+ val pixels = if (size.isNaN()) 0 else (size * density).toInt() + padding
140
145
 
141
146
  return when (mode) {
142
147
  YogaMeasureMode.EXACTLY -> View.MeasureSpec.makeMeasureSpec(pixels, View.MeasureSpec.EXACTLY)
@@ -9,6 +9,7 @@ import android.view.ViewGroup
9
9
  import android.view.ViewTreeObserver
10
10
  import android.window.OnBackInvokedCallback
11
11
  import android.window.OnBackInvokedDispatcher
12
+ import androidx.annotation.RequiresApi
12
13
  import com.facebook.soloader.SoLoader
13
14
 
14
15
  /** The app's activity: runs assets/main.bundle.js (or, in debug builds, the dev server's bundle). */
@@ -60,17 +61,14 @@ open class NativueActivity : Activity() {
60
61
  bridge.onConfigurationChanged()
61
62
  }
62
63
 
63
- /**
64
- * Android 13+ takes back gestures only when registered for (predictive back); older versions call
65
- * onBackPressed.
66
- */
67
- private val backCallback = OnBackInvokedCallback { bridge.goBack() }
64
+ /** Android 13+ takes back gestures only when registered for (predictive back); older versions call onBackPressed. */
65
+ private var predictiveBack: PredictiveBack? = null
68
66
 
69
67
  private fun setHandlesBack(handlesBack: Boolean) {
70
68
  if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) return
71
69
 
72
- if (handlesBack) onBackInvokedDispatcher.registerOnBackInvokedCallback(OnBackInvokedDispatcher.PRIORITY_DEFAULT, backCallback)
73
- else onBackInvokedDispatcher.unregisterOnBackInvokedCallback(backCallback)
70
+ val predictiveBack = predictiveBack ?: PredictiveBack(this) { bridge.goBack() }.also { predictiveBack = it }
71
+ predictiveBack.setRegistered(handlesBack)
74
72
  }
75
73
 
76
74
  @Deprecated("Deprecated in Java")
@@ -83,3 +81,18 @@ open class NativueActivity : Activity() {
83
81
  super.onDestroy()
84
82
  }
85
83
  }
84
+
85
+ /**
86
+ * Its own class, created only on Android 13+: older versions can't load OnBackInvokedCallback, and a
87
+ * release build crashes on launch if the activity itself refers to it.
88
+ */
89
+ @RequiresApi(Build.VERSION_CODES.TIRAMISU)
90
+ private class PredictiveBack(private val activity: Activity, onBack: () -> Unit) {
91
+ private val callback = OnBackInvokedCallback(onBack)
92
+
93
+ fun setRegistered(isRegistered: Boolean) {
94
+ val dispatcher = activity.onBackInvokedDispatcher
95
+ if (isRegistered) dispatcher.registerOnBackInvokedCallback(OnBackInvokedDispatcher.PRIORITY_DEFAULT, callback)
96
+ else dispatcher.unregisterOnBackInvokedCallback(callback)
97
+ }
98
+ }
@@ -318,7 +318,7 @@ class ScreenHeader(context: Context) : LinearLayout(context), ThemeAware {
318
318
  private fun textView(size: Float, style: Int) = TextView(context).apply {
319
319
  setTextSize(TypedValue.COMPLEX_UNIT_SP, size)
320
320
  setTextColor(ThemeColors.onSurface)
321
- typeface = Typeface.create(Typeface.DEFAULT, if (style == Typeface.BOLD) 500 else 400, false)
321
+ typeface = typefaceOfWeight(context, if (style == Typeface.BOLD) 500 else 400)
322
322
  isSingleLine = true
323
323
  ellipsize = android.text.TextUtils.TruncateAt.END
324
324
  includeFontPadding = false
@@ -633,12 +633,15 @@ fun ScreenStackView.popToFirst() {
633
633
  for (index in childCount - 1 downTo 1) (getChildAt(index) as? ScreenView)?.onEvent?.invoke("dismissed", null)
634
634
  }
635
635
 
636
+ /** Text in dp, which keeps its size whatever the system's text size (tab labels, like iOS's). */
637
+ class FixedSizeTextView(context: Context) : TextView(context)
638
+
636
639
  /** One destination of the navigation bar: an icon in a pill when selected, a label and a badge. */
637
640
  private class TabItemView(context: Context) : LinearLayout(context) {
638
641
  private val indicator = FrameLayout(context)
639
642
  private val icon = SvgView(context)
640
- private val label = TextView(context)
641
- private val badge = TextView(context)
643
+ private val label = FixedSizeTextView(context)
644
+ private val badge = FixedSizeTextView(context)
642
645
 
643
646
  init {
644
647
  orientation = VERTICAL
@@ -665,7 +668,7 @@ private class TabItemView(context: Context) : LinearLayout(context) {
665
668
  addView(indicator, LayoutParams(dp(64f), dp(32f)))
666
669
 
667
670
  label.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12f)
668
- label.typeface = Typeface.create(Typeface.DEFAULT, 500, false)
671
+ label.typeface = typefaceOfWeight(context, 500)
669
672
  label.gravity = Gravity.CENTER
670
673
  label.isSingleLine = true
671
674
  addView(label, LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT).apply { topMargin = dp(4f) })
@@ -1,5 +1,6 @@
1
1
  package dev.nativue
2
2
 
3
+ import android.content.Context
3
4
  import android.graphics.Paint
4
5
  import android.graphics.Typeface
5
6
  import android.util.TypedValue
@@ -7,6 +8,7 @@ import android.view.Gravity
7
8
  import android.view.View
8
9
  import android.view.ViewGroup
9
10
  import android.widget.TextView
11
+ import androidx.core.graphics.TypefaceCompat
10
12
  import com.facebook.yoga.YogaAlign
11
13
  import com.facebook.yoga.YogaDisplay
12
14
  import com.facebook.yoga.YogaEdge
@@ -117,13 +119,17 @@ private fun degrees(value: Any?): Float {
117
119
  return if (text.endsWith("rad")) Math.toDegrees(amount.toDouble()).toFloat() else amount
118
120
  }
119
121
 
122
+ /** The system font at a weight (100 to 900). */
123
+ fun typefaceOfWeight(context: Context, weight: Int): Typeface =
124
+ TypefaceCompat.create(context, Typeface.DEFAULT, weight, false)
125
+
120
126
  /** Font size and weight can change independently, so the node remembers both. */
121
127
  private fun NativeNode.applyFont(changes: Map<String, Any?>) {
122
128
  if ("fontSize" in changes) fontSize = number(changes["fontSize"]) ?: DEFAULT_FONT_SIZE
123
129
  if ("fontWeight" in changes) fontWeight = changes["fontWeight"]?.let(::fontWeightOf) ?: 400
124
130
 
125
131
  val textView = view as? TextView ?: return
126
- textView.typeface = Typeface.create(Typeface.DEFAULT, fontWeight, false)
132
+ textView.typeface = typefaceOfWeight(textView.context, fontWeight)
127
133
  updateFontSize()
128
134
  }
129
135
 
@@ -2,10 +2,9 @@ package dev.nativue
2
2
 
3
3
  import android.graphics.Color
4
4
  import android.os.Build
5
- import android.view.View
6
5
  import android.view.Window
7
- import android.view.WindowInsetsController
8
6
  import android.view.WindowManager
7
+ import androidx.core.view.WindowCompat
9
8
 
10
9
  /** The status and navigation bars: transparent, over the screens, with icons that contrast with them. */
11
10
  @Suppress("DEPRECATION") // the APIs older Android versions need
@@ -17,24 +16,23 @@ object SystemBars {
17
16
  fun drawBehind(window: Window) {
18
17
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.VANILLA_ICE_CREAM) return
19
18
 
20
- window.setDecorFitsSystemWindows(false)
19
+ WindowCompat.setDecorFitsSystemWindows(window, false)
21
20
  window.statusBarColor = Color.TRANSPARENT
22
- window.navigationBarColor = Color.TRANSPARENT
23
- window.attributes.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS
21
+ // Before Android 8 the navigation bar's icons are always light: a scrim keeps them readable.
22
+ window.navigationBarColor = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) Color.TRANSPARENT else NAVIGATION_BAR_SCRIM
23
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
24
+ window.attributes.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS
25
+ } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
26
+ window.attributes.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
27
+ }
24
28
  }
25
29
 
26
30
  /** Dark icons on light screens, light icons on dark ones. */
27
31
  fun setLight(window: Window, isLight: Boolean) {
28
- val lightBars = WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS or
29
- WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS
30
- window.insetsController?.setSystemBarsAppearance(if (isLight) lightBars else 0, lightBars)
31
-
32
- // Android 11 keeps the theme's light-bar flags over setSystemBarsAppearance: they're set too.
33
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) return
34
-
35
- val decorView = window.decorView
36
- val flags = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR or View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR
37
- decorView.systemUiVisibility =
38
- if (isLight) decorView.systemUiVisibility or flags else decorView.systemUiVisibility and flags.inv()
32
+ val controller = WindowCompat.getInsetsController(window, window.decorView)
33
+ controller.isAppearanceLightStatusBars = isLight
34
+ controller.isAppearanceLightNavigationBars = isLight
39
35
  }
36
+
37
+ private const val NAVIGATION_BAR_SCRIM = 0x80000000.toInt()
40
38
  }
package/cli/link.mjs CHANGED
@@ -154,7 +154,7 @@ import PackageDescription
154
154
 
155
155
  let package = Package(
156
156
  name: "NativuePlugins",
157
- platforms: [.iOS(.v17)],
157
+ platforms: [.iOS("15.1")],
158
158
  products: [.library(name: "NativuePlugins", targets: ["${LIST_TARGET}"])],
159
159
  dependencies: [
160
160
  .package(path: "${corePath}"),
package/cli/nativue.mjs CHANGED
@@ -190,7 +190,11 @@ function viteConfig({ mode, plugins = [], watch = null, sourcemap = false }) {
190
190
  plugins: [
191
191
  vue({
192
192
  template: {
193
- compilerOptions: { isCustomElement: (tag) => NATIVE_COMPONENT_TAGS.includes(tag) },
193
+ compilerOptions: {
194
+ isCustomElement: (tag) => NATIVE_COMPONENT_TAGS.includes(tag),
195
+ // Long static runs would become an HTML string for innerHTML, which native views can't take.
196
+ hoistStatic: false,
197
+ },
194
198
  },
195
199
  }),
196
200
  ignoreStyleBlocks(),
@@ -7,10 +7,17 @@ extension NativeNode {
7
7
  "heading": .header,
8
8
  "img": .image,
9
9
  "text": .staticText,
10
- "switch": .toggleButton,
11
- "checkbox": .toggleButton,
10
+ "switch": toggleTraits,
11
+ "checkbox": toggleTraits,
12
12
  ]
13
13
 
14
+ /// Before iOS 17, VoiceOver has no toggle trait: a button that says its state is the closest.
15
+ private static var toggleTraits: UIAccessibilityTraits {
16
+ if #available(iOS 17, *) { return .toggleButton }
17
+
18
+ return .button
19
+ }
20
+
14
21
  /// role, alt and aria-*, from the renderer: all of them, whenever one changes.
15
22
  func applyAccessibility(_ attributes: [String: Any]) {
16
23
  let role = attributes["role"] as? String
@@ -24,9 +31,15 @@ extension NativeNode {
24
31
  view.accessibilityHint = attributes["hint"] as? String
25
32
  view.accessibilityTraits = traits(role: role, attributes: attributes)
26
33
  // A container read as one element says the text inside it, as a <button> does on the web.
27
- view.accessibilityLabelBlock = isElement && label == nil && !defaultAccessibility.isElement
28
- ? { [weak view] in view.map { Self.labels(inside: $0).joined(separator: ", ") } }
29
- : nil
34
+ let readsTextInside = isElement && label == nil && !defaultAccessibility.isElement
35
+ if #available(iOS 17, *) {
36
+ view.accessibilityLabelBlock = readsTextInside
37
+ ? { [weak view] in view.map { Self.labels(inside: $0).joined(separator: ", ") } }
38
+ : nil
39
+ } else if readsTextInside {
40
+ // ponytail: before iOS 17 the label is read once, here: text changed later inside keeps the old one.
41
+ view.accessibilityLabel = Self.labels(inside: view).joined(separator: ", ")
42
+ }
30
43
 
31
44
  if role == "switch" || role == "checkbox" {
32
45
  view.accessibilityValue = attributes["checked"] != nil ? "1" : "0"
@@ -81,6 +81,10 @@ final class AnimatedGraph {
81
81
  updateBoundViews()
82
82
  }
83
83
 
84
+ func drives(_ view: UIView) -> Bool {
85
+ bindingsByViewId.values.contains { $0.view === view }
86
+ }
87
+
84
88
  // MARK: - Animations
85
89
 
86
90
  func startAnimation(id: Int, nodeId: Int, config: [String: Any]) {
@@ -124,19 +128,23 @@ final class AnimatedGraph {
124
128
 
125
129
  // MARK: - Views
126
130
 
131
+ /// Never animated by UIKit: a binding made in a layout animation's batch would hold the view at
132
+ /// its first value until the layout animation ends.
127
133
  private func updateBoundViews() {
128
- for (viewId, binding) in bindingsByViewId {
129
- guard let view = binding.view else {
130
- bindingsByViewId[viewId] = nil
131
- continue
132
- }
133
-
134
- if let opacityNodeId = binding.opacityNodeId {
135
- view.alpha = CGFloat(value(ofNode: opacityNodeId))
136
- }
137
- if let steps = binding.transformSteps {
138
- let resolvedSteps = steps.map { step in [step.name: step.nodeId.map(value(ofNode:)) ?? step.value] }
139
- view.transform = NativeNode.affineTransform(resolvedSteps)
134
+ UIView.performWithoutAnimation {
135
+ for (viewId, binding) in bindingsByViewId {
136
+ guard let view = binding.view else {
137
+ bindingsByViewId[viewId] = nil
138
+ continue
139
+ }
140
+
141
+ if let opacityNodeId = binding.opacityNodeId {
142
+ view.alpha = CGFloat(value(ofNode: opacityNodeId))
143
+ }
144
+ if let steps = binding.transformSteps {
145
+ let resolvedSteps = steps.map { step in [step.name: step.nodeId.map(value(ofNode:)) ?? step.value] }
146
+ view.transform = NativeNode.affineTransform(resolvedSteps)
147
+ }
140
148
  }
141
149
  }
142
150
  }
package/ios/Bridge.swift CHANGED
@@ -63,20 +63,19 @@ final class Bridge {
63
63
  self.rootView = rootView
64
64
  rootView.onLayoutSubviews = { [unowned self] in layout() }
65
65
  NativeNode.onLayoutCalculated = { [unowned self] in reportLayoutChanges() }
66
+ NativeNode.isDrivenByAnimated = { [unowned self] view in animatedGraph.drives(view) }
66
67
  networking.onEvent = { [unowned self] owner, requestId, eventName, payload in
67
68
  sendNetworkEvent(owner: owner, requestId: requestId, eventName: eventName, payload: payload)
68
69
  }
69
70
  let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene
70
71
  windowSize = windowScene?.screen.bounds.size ?? .zero
71
72
  colorScheme = Self.colorScheme(of: windowScene?.traitCollection ?? rootView.traitCollection)
72
- // start runs on the main thread, from makeUIView.
73
- MainActor.assumeIsolated {
74
- _ = rootView.registerForTraitChanges([UITraitUserInterfaceStyle.self]) {
75
- [unowned self] (rootView: RootView, _: UITraitCollection) in
76
- colorSchemeDidChange(to: Self.colorScheme(of: rootView.traitCollection))
73
+ rootView.onTraitCollectionChange = { [unowned self, unowned rootView] previous in
74
+ let traits = rootView.traitCollection
75
+ if traits.userInterfaceStyle != previous?.userInterfaceStyle {
76
+ colorSchemeDidChange(to: Self.colorScheme(of: traits))
77
77
  }
78
- _ = rootView.registerForTraitChanges([UITraitPreferredContentSizeCategory.self]) {
79
- [unowned self] (rootView: RootView, _: UITraitCollection) in
78
+ if traits.preferredContentSizeCategory != previous?.preferredContentSizeCategory {
80
79
  nodesById.values.forEach { $0.updateFont() }
81
80
  rootView.setNeedsLayout()
82
81
  }
@@ -202,12 +201,13 @@ final class Bridge {
202
201
  /// UIKit coalesces these requests, so the layout pass runs once per batch.
203
202
  func requestLayout() {
204
203
  rootView.setNeedsLayout()
204
+ if rootView.window == nil { rootView.layoutIfNeeded() }
205
205
  }
206
206
 
207
207
  #if DEBUG
208
208
  @MainActor func listenForReload() async {
209
- let eventsURL = Self.devServerURL.appending(path: "events")
210
- let bundleURL = Self.devServerURL.appending(path: "bundle.js")
209
+ let eventsURL = Self.devServerURL.appendingPathComponent("events")
210
+ let bundleURL = Self.devServerURL.appendingPathComponent("bundle.js")
211
211
 
212
212
  while true {
213
213
  do {
@@ -220,7 +220,7 @@ final class Bridge {
220
220
  }
221
221
  } catch {}
222
222
 
223
- try? await Task.sleep(for: .seconds(2)) // dev server is down: retry
223
+ try? await Task.sleep(nanoseconds: 2_000_000_000) // dev server is down: retry
224
224
  }
225
225
  }
226
226
  #endif
@@ -368,7 +368,7 @@ final class Bridge {
368
368
  /// The dev server maps main.bundle.js lines back to the app's files with the bundle's source map.
369
369
  /// Without a dev server, the stack stays as it is.
370
370
  private func symbolicated(_ text: String) async -> String {
371
- var request = URLRequest(url: Self.devServerURL.appending(path: "symbolicate"), timeoutInterval: 2)
371
+ var request = URLRequest(url: Self.devServerURL.appendingPathComponent("symbolicate"), timeoutInterval: 2)
372
372
  request.httpMethod = "POST"
373
373
  request.httpBody = Data(text.utf8)
374
374
 
@@ -487,7 +487,7 @@ final class Bridge {
487
487
  private func makeUnstyledNode(type: String, id: Int) -> NativeNode {
488
488
  switch type {
489
489
  case "Text":
490
- let label = UILabel()
490
+ let label = TextLabel()
491
491
  label.numberOfLines = 0
492
492
  return NativeNode(view: label, measuresContent: true)
493
493
 
@@ -55,7 +55,7 @@ final class KeyValueStorage {
55
55
  }
56
56
 
57
57
  private func load() -> [String: String] {
58
- let path = directory.appending(path: "async-storage.db").path
58
+ let path = directory.appendingPathComponent("async-storage.db").path
59
59
  guard sqlite3_open(path, &database) == SQLITE_OK else { return [:] }
60
60
 
61
61
  execute("PRAGMA journal_mode = WAL")
@@ -72,7 +72,7 @@ final class KeyValueStorage {
72
72
 
73
73
  /// Before SQLite, values were saved to a JSON file: moved into the table once, then deleted.
74
74
  private func importJSONFile() {
75
- let fileURL = directory.appending(path: "async-storage.json")
75
+ let fileURL = directory.appendingPathComponent("async-storage.json")
76
76
  guard let data = try? Data(contentsOf: fileURL),
77
77
  let saved = try? JSONDecoder().decode([String: String].self, from: data)
78
78
  else { return }
@@ -85,6 +85,8 @@ final class NativeNode {
85
85
  /// After every layout pass, of the root or of a screen's or modal's content: for @layout.
86
86
  static var onLayoutCalculated: (() -> Void)?
87
87
 
88
+ static var isDrivenByAnimated: (UIView) -> Bool = { _ in false }
89
+
88
90
  func calculateLayout(width: CGFloat, height: CGFloat) {
89
91
  YGNodeCalculateLayout(yogaNode, Float(width), Float(height), .LTR)
90
92
  Self.applyFrames(of: yogaNode)
@@ -93,14 +95,25 @@ final class NativeNode {
93
95
 
94
96
  /// A view inserted during a layout animation would grow from the corner: it fades in where it lands.
95
97
  private static func appearWithoutMoving(_ view: UIView, at frame: CGRect) {
98
+ let fades = !isDrivenByAnimated(view)
96
99
  let finalAlpha = view.alpha
97
100
 
98
101
  UIView.performWithoutAnimation {
99
- view.frame = frame
100
- view.alpha = 0
102
+ place(view, at: frame)
103
+ if fades { view.alpha = 0 }
101
104
  view.layoutIfNeeded()
102
105
  }
103
- view.alpha = finalAlpha
106
+ if fades { view.alpha = finalAlpha }
107
+ }
108
+
109
+ private static func place(_ view: UIView, at frame: CGRect) {
110
+ if view.transform == .identity {
111
+ if view.frame != frame { view.frame = frame }
112
+ } else {
113
+ // With a transform, `frame` is the transformed box: place the untransformed one.
114
+ view.bounds.size = frame.size
115
+ view.center = CGPoint(x: frame.midX, y: frame.midY)
116
+ }
104
117
  }
105
118
 
106
119
  /// Only visits subtrees Yoga laid out again; untouched subtrees keep their frames.
@@ -121,14 +134,12 @@ final class NativeNode {
121
134
 
122
135
  // Yoga flags whole dirty paths as new layout. Reassigning a scroll view's frame or content
123
136
  // size, even unchanged, makes UIKit readjust its offset and shakes a bounce, so skip no-ops.
124
- if childView.frame == .zero, UIView.inheritedAnimationDuration > 0 {
137
+ // Never placed: a transform moves `frame`, so check its untransformed box.
138
+ let isNew = childView.bounds.size == .zero && childView.center == .zero
139
+ if isNew, UIView.inheritedAnimationDuration > 0 {
125
140
  appearWithoutMoving(childView, at: frame)
126
- } else if childView.transform == .identity {
127
- if childView.frame != frame { childView.frame = frame }
128
141
  } else {
129
- // With a transform, `frame` is the transformed box: place the untransformed one.
130
- childView.bounds.size = frame.size
131
- childView.center = CGPoint(x: frame.midX, y: frame.midY)
142
+ place(childView, at: frame)
132
143
  }
133
144
  childView.applyCornerRadius()
134
145
 
@@ -142,6 +153,9 @@ final class NativeNode {
142
153
  if let textInput = childView as? TextInputView {
143
154
  textInput.contentPadding = padding(of: child)
144
155
  }
156
+ if let label = childView as? TextLabel {
157
+ label.contentPadding = padding(of: child)
158
+ }
145
159
  }
146
160
  }
147
161
 
@@ -37,9 +37,15 @@ struct VueRoot: UIViewRepresentable {
37
37
  /// Root of the native tree; runs the Yoga layout pass whenever UIKit lays it out.
38
38
  final class RootView: UIView {
39
39
  var onLayoutSubviews: (() -> Void)?
40
+ var onTraitCollectionChange: ((_ previous: UITraitCollection?) -> Void)?
40
41
 
41
42
  override func layoutSubviews() {
42
43
  super.layoutSubviews()
43
44
  onLayoutSubviews?()
44
45
  }
46
+
47
+ override func traitCollectionDidChange(_ previous: UITraitCollection?) {
48
+ super.traitCollectionDidChange(previous)
49
+ onTraitCollectionChange?(previous)
50
+ }
45
51
  }
@@ -0,0 +1,14 @@
1
+ import UIKit
2
+
3
+ /// <Text>: its text starts at the top of a taller box, as on Android and the web (UILabel centers it).
4
+ final class TextLabel: UILabel {
5
+ var contentPadding: UIEdgeInsets = .zero {
6
+ didSet { setNeedsDisplay() }
7
+ }
8
+
9
+ override func drawText(in bounds: CGRect) {
10
+ let rect = bounds.inset(by: contentPadding)
11
+ let textHeight = textRect(forBounds: rect, limitedToNumberOfLines: numberOfLines).height
12
+ super.drawText(in: CGRect(x: rect.minX, y: rect.minY, width: rect.width, height: min(textHeight, rect.height)))
13
+ }
14
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nativue/core",
3
- "version": "0.11.1",
3
+ "version": "0.12.0",
4
4
  "description": "Vue rendering real native views on iOS and Android",
5
5
  "keywords": [
6
6
  "vue",