@nativue/core 0.11.1 → 0.13.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/AGENTS.md CHANGED
@@ -86,7 +86,8 @@ Import the runtime from `vue`: `ref`, `computed`, `StyleSheet`, `Animated`, `Lay
86
86
  - Official packages: `@nativue/icons` (icon components), `@nativue/tailwind`, `@nativue/haptics`,
87
87
  `@nativue/sqlite`. A package with native code needs the app rebuilt with `npm run ios` or
88
88
  `npm run android`, not just a reload.
89
- - Commands: `npm run ios` / `npm run android` build and open the app, then reload on save;
89
+ - Commands: `npm run ios` / `npm run android` build and open the app, then update it on save
90
+ (template edits keep the component's state; script edits re-create the component);
90
91
  `npm run typecheck` checks scripts and templates; `npm run build` makes the release bundle;
91
92
  `npm run format` formats with Prettier.
92
93
  - Native code the app needs (a platform API no package covers) goes in `native/<name>/ios` and
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: [
package/README.md CHANGED
@@ -17,7 +17,7 @@ This package holds:
17
17
 
18
18
  ```sh
19
19
  nativue run ios # or android: builds, opens the app on a simulator or emulator, then dev
20
- nativue dev # rebuilds on save and reloads the running app
20
+ nativue dev # updates the running app on save
21
21
  nativue build # bundles the app into ios/ and android/ (--production for releases)
22
22
  ```
23
23
 
@@ -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
@@ -30,6 +31,7 @@ import com.facebook.yoga.YogaDisplay
30
31
  import com.facebook.yoga.YogaEdge
31
32
  import com.facebook.yoga.YogaFlexDirection
32
33
  import com.facebook.yoga.YogaPositionType
34
+ import java.io.ByteArrayOutputStream
33
35
  import java.net.HttpURLConnection
34
36
  import java.net.URL
35
37
  import kotlin.concurrent.thread
@@ -50,6 +52,9 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
50
52
  @Volatile
51
53
  private var reloadConnection: HttpURLConnection? = null
52
54
 
55
+ /** The router's screens, reopened after a reload in development. Only touched on the JS thread. */
56
+ private var savedNavigation: String? = null
57
+
53
58
  private val javaScriptHandler = startJavaScriptThread()
54
59
  private val isDebuggable = activity.applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE != 0
55
60
  private val density = activity.resources.displayMetrics.density
@@ -75,7 +80,7 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
75
80
  private val reportedLayoutsByNodeId = mutableMapOf<Int, Map<String, Float>?>()
76
81
 
77
82
  /** The latest window insets, mid-animation while the keyboard moves. */
78
- private var windowInsets: WindowInsets? = null
83
+ private var windowInsets: WindowInsetsCompat? = null
79
84
 
80
85
  /** Whether the system back gesture has something to close or pop (NativueActivity listens). */
81
86
  var onCanGoBackChange: (canGoBack: Boolean) -> Unit = {}
@@ -83,24 +88,29 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
83
88
  /** The bundle running now, for the error screen's Reload. */
84
89
  private var bundle = ByteArray(0)
85
90
  private val errorOverlay = ErrorOverlay(activity)
91
+ private val downloadBanner = DownloadBanner(activity)
86
92
 
87
93
  fun start() {
88
94
  NativeNode.setPixelDensity(density)
89
95
  rootView.onLayoutPass = ::layout
90
96
  NativeNode.onLayoutCalculated = ::reportLayoutChanges
91
- rootView.setOnApplyWindowInsetsListener { view, insets ->
97
+ ViewCompat.setOnApplyWindowInsetsListener(rootView) { view, insets ->
92
98
  windowInsets = insets
93
99
  view.requestLayout() // safe area and keyboard paddings
94
100
  insets
95
101
  }
96
102
  // 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 {
103
+ val keyboardAnimation = object : WindowInsetsAnimationCompat.Callback(DISPATCH_MODE_CONTINUE_ON_SUBTREE) {
104
+ override fun onProgress(
105
+ insets: WindowInsetsCompat,
106
+ runningAnimations: List<WindowInsetsAnimationCompat>,
107
+ ): WindowInsetsCompat {
99
108
  windowInsets = insets
100
109
  layout()
101
110
  return insets
102
111
  }
103
- })
112
+ }
113
+ ViewCompat.setWindowInsetsAnimationCallback(rootView, keyboardAnimation)
104
114
 
105
115
  val bundle = runCatching { activity.assets.open("main.bundle.js").use { it.readBytes() } }.getOrNull()
106
116
  if (bundle != null) run(bundle)
@@ -167,7 +177,7 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
167
177
  * (tab labels) keeps its size.
168
178
  */
169
179
  private fun rescaleText(view: View, nodeViews: Set<View>, ratio: Float) {
170
- if (view is TextView && view !in nodeViews && view.textSizeUnit != TypedValue.COMPLEX_UNIT_DIP) {
180
+ if (view is TextView && view !is FixedSizeTextView && view !in nodeViews) {
171
181
  view.setTextSize(TypedValue.COMPLEX_UNIT_PX, view.textSize * ratio)
172
182
  }
173
183
  if (view !is ViewGroup) return
@@ -243,7 +253,7 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
243
253
  layoutAnimation.captureStart(nodesById.values)
244
254
  operations.forEach { it() }
245
255
  layout()
246
- layoutAnimation.animateChanges(nodesById.values)
256
+ layoutAnimation.animateChanges(nodesById.values, animatedGraph::drives)
247
257
  }
248
258
 
249
259
  private fun startJavaScriptThread(): Handler {
@@ -324,6 +334,8 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
324
334
  put("windowSize") { _ -> windowSize }
325
335
  put("platform") { _ -> "android" }
326
336
  put("colorScheme") { _ -> colorScheme() }
337
+ put("savedNavigation") { _ -> savedNavigation }
338
+ put("saveNavigation") { arguments -> savedNavigation = arguments[0] as String }
327
339
  put("accessibilityInfo") { _ -> accessibilityStatus(activity) }
328
340
  put("announce") { arguments ->
329
341
  val message = arguments[0] as String
@@ -370,9 +382,16 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
370
382
  @Volatile private var windowSize = windowSize()
371
383
 
372
384
  private fun windowSize(): Map<String, Float> {
373
- val bounds = activity.windowManager.currentWindowMetrics.bounds
385
+ val size = android.graphics.Point()
386
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
387
+ val bounds = activity.windowManager.currentWindowMetrics.bounds
388
+ size.set(bounds.width(), bounds.height())
389
+ } else {
390
+ @Suppress("DEPRECATION") // its replacement, currentWindowMetrics, is API 30+
391
+ activity.windowManager.defaultDisplay.getRealSize(size)
392
+ }
374
393
 
375
- return mapOf("width" to bounds.width() / density, "height" to bounds.height() / density)
394
+ return mapOf("width" to size.x / density, "height" to size.y / density)
376
395
  }
377
396
 
378
397
  /** A timer of a runtime that has since been reloaded doesn't fire. */
@@ -501,7 +520,7 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
501
520
  return hosts.map { "http://$it:$DEV_SERVER_PORT" }
502
521
  }
503
522
 
504
- /** The dev server sends `data: reload` on connect and after each rebuild. */
523
+ /** The dev server sends `data: reload` on connect and when the app must reload, `data: hot` with an update. */
505
524
  private fun listenForReload() {
506
525
  val candidateURLs = devServerURLs()
507
526
  var attempt = 0
@@ -514,10 +533,13 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
514
533
  reloadConnection = connection
515
534
 
516
535
  connection.inputStream.bufferedReader().useLines { lines ->
517
- lines.filter { it == "data: reload" }.forEach { _ ->
518
- val bundle = URL("$devServerURL/bundle.js").readBytes()
519
- Log.i(TAG, "reload")
520
- mainHandler.post { run(bundle) }
536
+ lines.forEach { line ->
537
+ if (line == "data: reload") {
538
+ downloadAndRun()
539
+ } else if (line.startsWith("data: hot ")) {
540
+ val update = line.removePrefix("data: hot ")
541
+ evaluate { runtime?.call("__hotUpdate", update) }
542
+ }
521
543
  }
522
544
  }
523
545
  }
@@ -526,6 +548,43 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
526
548
  }
527
549
  }
528
550
 
551
+ fun reload() {
552
+ if (isDebuggable) thread(isDaemon = true) { runCatching { downloadAndRun() } }
553
+ }
554
+
555
+ private fun downloadAndRun() {
556
+ val bundle = download(URL("$devServerURL/bundle.js"))
557
+ Log.i(TAG, "reload")
558
+ mainHandler.post { run(bundle) }
559
+ }
560
+
561
+ private fun download(url: URL): ByteArray {
562
+ val connection = url.openConnection() as HttpURLConnection
563
+ val length = connection.contentLengthLong
564
+ val bundle = ByteArrayOutputStream()
565
+ val buffer = ByteArray(64 * 1024)
566
+
567
+ mainHandler.post { downloadBanner.show(0.0) }
568
+ try {
569
+ connection.inputStream.use { input ->
570
+ while (true) {
571
+ val count = input.read(buffer)
572
+ if (count < 0) break
573
+
574
+ bundle.write(buffer, 0, count)
575
+ if (length > 0) {
576
+ val progress = bundle.size().toDouble() / length
577
+ mainHandler.post { downloadBanner.show(progress) }
578
+ }
579
+ }
580
+ }
581
+ } finally {
582
+ mainHandler.post { downloadBanner.hide() }
583
+ }
584
+
585
+ return bundle.toByteArray()
586
+ }
587
+
529
588
  // ---------- Main thread ----------
530
589
 
531
590
  /** Vue removes only a subtree's root: the nodes under it are forgotten with it. */
@@ -985,9 +1044,9 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
985
1044
  return didChange
986
1045
  }
987
1046
 
988
- private fun currentWindowInsets(): WindowInsets? = windowInsets ?: rootView.rootWindowInsets
1047
+ private fun currentWindowInsets(): WindowInsetsCompat? = windowInsets ?: ViewCompat.getRootWindowInsets(rootView)
989
1048
 
990
- private fun fitScreen(node: NativeNode, screen: ScreenView, windowInsets: WindowInsets): Boolean {
1049
+ private fun fitScreen(node: NativeNode, screen: ScreenView, windowInsets: WindowInsetsCompat): Boolean {
991
1050
  var didChange = false
992
1051
 
993
1052
  if (screen.isSheet) {
@@ -1007,7 +1066,7 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
1007
1066
  return didChange
1008
1067
  }
1009
1068
 
1010
- private fun fitTabBar(node: NativeNode, tabBar: TabBarView, windowInsets: WindowInsets): Boolean {
1069
+ private fun fitTabBar(node: NativeNode, tabBar: TabBarView, windowInsets: WindowInsetsCompat): Boolean {
1011
1070
  tabBar.bottomInset = (overlap(tabBar, windowInsets.getInsets(SYSTEM_BARS))[3] * density).toInt()
1012
1071
 
1013
1072
  var didChange = false
@@ -1063,8 +1122,8 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
1063
1122
  const val SVG_DEFAULT_COLOR = 0xFF000000.toInt()
1064
1123
  const val BUTTON_TINT = 0xFF007AFF.toInt()
1065
1124
  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()
1125
+ val SYSTEM_BARS = WindowInsetsCompat.Type.systemBars() or WindowInsetsCompat.Type.displayCutout()
1126
+ val IME = WindowInsetsCompat.Type.ime()
1068
1127
  const val SHEET_TOP_GAP = 12f
1069
1128
 
1070
1129
  val keyboardInputTypes = mapOf(
@@ -0,0 +1,45 @@
1
+ package dev.nativue
2
+
3
+ import android.app.Activity
4
+ import android.graphics.Color
5
+ import android.graphics.Typeface
6
+ import android.view.Gravity
7
+ import android.view.ViewGroup
8
+ import android.widget.FrameLayout
9
+ import android.widget.TextView
10
+ import androidx.core.view.ViewCompat
11
+ import androidx.core.view.WindowInsetsCompat
12
+
13
+ /** Development only: a strip at the top of the screen while the app downloads the dev server's bundle. Mirrors ios/DownloadBanner.swift. */
14
+ class DownloadBanner(private val activity: Activity) {
15
+ private var label: TextView? = null
16
+
17
+ fun show(progress: Double) {
18
+ val label = label ?: makeLabel().also { label = it }
19
+ label.text = "Downloading ${(progress * 100).toInt()}%"
20
+ }
21
+
22
+ fun hide() {
23
+ label?.let { (it.parent as? ViewGroup)?.removeView(it) }
24
+ label = null
25
+ }
26
+
27
+ private fun makeLabel(): TextView {
28
+ val height = (24 * activity.resources.displayMetrics.density).toInt()
29
+ val label = TextView(activity)
30
+ label.setBackgroundColor(Color.rgb(0x0B, 0x12, 0x20))
31
+ label.setTextColor(Color.rgb(0xF1, 0xF5, 0xF9))
32
+ label.textSize = 12f
33
+ label.typeface = Typeface.DEFAULT_BOLD
34
+ label.gravity = Gravity.CENTER
35
+ ViewCompat.setOnApplyWindowInsetsListener(label) { view, insets ->
36
+ val top = insets.getInsets(WindowInsetsCompat.Type.statusBars()).top
37
+ view.layoutParams = (view.layoutParams as FrameLayout.LayoutParams).apply { topMargin = top }
38
+ insets
39
+ }
40
+ activity.addContentView(label, FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, height))
41
+ ViewCompat.requestApplyInsets(label)
42
+
43
+ return label
44
+ }
45
+ }
@@ -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)
@@ -5,15 +5,19 @@ import android.content.Intent
5
5
  import android.content.res.Configuration
6
6
  import android.os.Build
7
7
  import android.os.Bundle
8
+ import android.view.KeyEvent
8
9
  import android.view.ViewGroup
9
10
  import android.view.ViewTreeObserver
11
+ import android.widget.EditText
10
12
  import android.window.OnBackInvokedCallback
11
13
  import android.window.OnBackInvokedDispatcher
14
+ import androidx.annotation.RequiresApi
12
15
  import com.facebook.soloader.SoLoader
13
16
 
14
17
  /** The app's activity: runs assets/main.bundle.js (or, in debug builds, the dev server's bundle). */
15
18
  open class NativueActivity : Activity() {
16
19
  private lateinit var bridge: Bridge
20
+ private var lastRKeyTime = 0L
17
21
 
18
22
  override fun onCreate(savedInstanceState: Bundle?) {
19
23
  super.onCreate(savedInstanceState)
@@ -60,17 +64,23 @@ open class NativueActivity : Activity() {
60
64
  bridge.onConfigurationChanged()
61
65
  }
62
66
 
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() }
67
+ /** Android 13+ takes back gestures only when registered for (predictive back); older versions call onBackPressed. */
68
+ private var predictiveBack: PredictiveBack? = null
68
69
 
69
70
  private fun setHandlesBack(handlesBack: Boolean) {
70
71
  if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) return
71
72
 
72
- if (handlesBack) onBackInvokedDispatcher.registerOnBackInvokedCallback(OnBackInvokedDispatcher.PRIORITY_DEFAULT, backCallback)
73
- else onBackInvokedDispatcher.unregisterOnBackInvokedCallback(backCallback)
73
+ val predictiveBack = predictiveBack ?: PredictiveBack(this) { bridge.goBack() }.also { predictiveBack = it }
74
+ predictiveBack.setRegistered(handlesBack)
75
+ }
76
+
77
+ override fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean {
78
+ if (keyCode != KeyEvent.KEYCODE_R || currentFocus is EditText) return super.onKeyUp(keyCode, event)
79
+
80
+ if (event.eventTime - lastRKeyTime < DOUBLE_PRESS_MS) bridge.reload()
81
+ lastRKeyTime = event.eventTime
82
+
83
+ return true
74
84
  }
75
85
 
76
86
  @Deprecated("Deprecated in Java")
@@ -83,3 +93,20 @@ open class NativueActivity : Activity() {
83
93
  super.onDestroy()
84
94
  }
85
95
  }
96
+
97
+ /**
98
+ * Its own class, created only on Android 13+: older versions can't load OnBackInvokedCallback, and a
99
+ * release build crashes on launch if the activity itself refers to it.
100
+ */
101
+ @RequiresApi(Build.VERSION_CODES.TIRAMISU)
102
+ private class PredictiveBack(private val activity: Activity, onBack: () -> Unit) {
103
+ private val callback = OnBackInvokedCallback(onBack)
104
+
105
+ fun setRegistered(isRegistered: Boolean) {
106
+ val dispatcher = activity.onBackInvokedDispatcher
107
+ if (isRegistered) dispatcher.registerOnBackInvokedCallback(OnBackInvokedDispatcher.PRIORITY_DEFAULT, callback)
108
+ else dispatcher.unregisterOnBackInvokedCallback(callback)
109
+ }
110
+ }
111
+
112
+ private const val DOUBLE_PRESS_MS = 500
@@ -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