@nativue/core 0.2.0 → 0.4.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.
@@ -6,3 +6,6 @@
6
6
  -keep class com.facebook.hermes.** { *; }
7
7
  -keep class com.facebook.yoga.** { *; }
8
8
  -keep class com.facebook.jni.** { *; }
9
+
10
+ # Plugins are created by class name (Plugins.kt).
11
+ -keep class * implements dev.nativue.NativuePlugin { <init>(); }
@@ -0,0 +1,56 @@
1
+ // Applied by the app's settings.gradle.kts: the Android side of the app's packages, those whose
2
+ // package.json has
3
+ // "nativue": { "android": { "sources": "android", "plugin": "dev.nativue.haptics.HapticsPlugin" } }
4
+ // becomes modules the app depends on (sources: the folder with build.gradle.kts, which depends on
5
+ // project(":nativue")). The plugin classes reach the app as the string resource nativue_plugins.
6
+ import groovy.json.JsonSlurper
7
+ import java.io.File
8
+
9
+ @Suppress("UNCHECKED_CAST")
10
+ fun readJson(file: File): Map<String, Any?> = JsonSlurper().parse(file) as Map<String, Any?>
11
+
12
+ /** node_modules/<name>, looked up the way Node does: in the app's folder, then in its parents. */
13
+ fun packageDirectory(name: String, appDirectory: File): File? =
14
+ generateSequence(appDirectory) { it.parentFile }
15
+ .map { File(it, "node_modules/$name") }
16
+ .firstOrNull { File(it, "package.json").isFile }
17
+
18
+ fun dependencyNames(appDirectory: File): List<String> {
19
+ val appPackage = readJson(File(appDirectory, "package.json"))
20
+
21
+ return listOf("dependencies", "devDependencies").flatMap { (appPackage[it] as? Map<*, *>)?.keys.orEmpty() }
22
+ .map { it.toString() }
23
+ }
24
+
25
+ data class AndroidPlugin(val projectPath: String, val pluginClass: String)
26
+
27
+ fun androidPlugin(name: String, appDirectory: File): AndroidPlugin? {
28
+ val directory = packageDirectory(name, appDirectory) ?: return null
29
+ val nativue = readJson(File(directory, "package.json"))["nativue"] as? Map<*, *>
30
+ val android = nativue?.get("android") as? Map<*, *> ?: return null
31
+ val projectPath = ":" + name.removePrefix("@").replace('/', '-')
32
+
33
+ include(projectPath)
34
+ project(projectPath).projectDir = File(directory, android["sources"] as String)
35
+
36
+ return AndroidPlugin(projectPath, android["plugin"] as String)
37
+ }
38
+
39
+ val appDirectory: File = settingsDir.parentFile
40
+ val androidPlugins = dependencyNames(appDirectory).mapNotNull { name -> androidPlugin(name, appDirectory) }
41
+
42
+ // Through Groovy's dynamic calls: the Android Gradle plugin's types aren't on a settings script's classpath.
43
+ gradle.beforeProject {
44
+ if (path != ":app") return@beforeProject
45
+
46
+ pluginManager.withPlugin("com.android.application") {
47
+ androidPlugins.forEach { plugin -> dependencies.add("implementation", project(plugin.projectPath)) }
48
+
49
+ extensions.getByName("android").withGroovyBuilder {
50
+ "getBuildFeatures"()!!.withGroovyBuilder { "setResValues"(true) }
51
+ "getDefaultConfig"()!!.withGroovyBuilder {
52
+ "resValue"("string", "nativue_plugins", androidPlugins.joinToString(",") { it.pluginClass })
53
+ }
54
+ }
55
+ }
56
+ }
@@ -4,6 +4,7 @@ import android.annotation.SuppressLint
4
4
  import android.app.Activity
5
5
  import android.content.Context
6
6
  import android.content.pm.ApplicationInfo
7
+ import android.content.res.Configuration
7
8
  import android.content.res.ColorStateList
8
9
  import android.os.Build
9
10
  import android.os.Handler
@@ -15,17 +16,20 @@ import android.util.Log
15
16
  import android.util.TypedValue
16
17
  import android.view.Gravity
17
18
  import android.view.View
19
+ import android.view.ViewGroup
18
20
  import android.view.WindowInsets
19
21
  import android.view.WindowInsetsAnimation
22
+ import android.view.WindowInsetsController
20
23
  import android.graphics.Insets
21
24
  import android.view.inputmethod.EditorInfo
22
25
  import android.view.inputmethod.InputMethodManager
23
26
  import android.widget.EditText
27
+ import android.widget.ImageView
24
28
  import android.widget.ProgressBar
25
- import android.widget.Switch
26
29
  import android.widget.TextView
27
30
  import com.facebook.yoga.YogaDisplay
28
31
  import com.facebook.yoga.YogaEdge
32
+ import com.facebook.yoga.YogaFlexDirection
29
33
  import com.facebook.yoga.YogaPositionType
30
34
  import java.net.HttpURLConnection
31
35
  import java.net.URL
@@ -41,11 +45,17 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
41
45
  /** The dev server address that answered last (set by listenForReload, read when symbolicating). */
42
46
  @Volatile
43
47
  private var devServerURL = ""
48
+ /** Ends listenForReload's loop: its thread would otherwise keep a destroyed activity alive. */
49
+ @Volatile
50
+ private var isDestroyed = false
51
+ @Volatile
52
+ private var reloadConnection: HttpURLConnection? = null
44
53
 
45
54
  private val javaScriptHandler = startJavaScriptThread()
46
55
  private val isDebuggable = activity.applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE != 0
47
56
  private val density = activity.resources.displayMetrics.density
48
57
  private val storage = activity.getSharedPreferences("dev.nativue.storage", Context.MODE_PRIVATE)
58
+ private val pluginRegistry = PluginRegistry(activity)
49
59
 
50
60
  // Only touched on the JS thread.
51
61
  private var runtime: JavaScriptRuntime? = null
@@ -54,7 +64,6 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
54
64
  private var nextLayoutAnimation: Map<*, *>? = null
55
65
 
56
66
  // Only touched on the main thread.
57
- // ponytail: children of a removed node stay in the map; clean up recursively if memory leaks.
58
67
  private val nodesById = HashMap<Int, NativeNode>()
59
68
  private val animatedGraph = AnimatedGraph()
60
69
  private val modalHostsByNodeId = HashMap<Int, ModalHost>()
@@ -94,7 +103,11 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
94
103
  if (isDebuggable) thread(isDaemon = true) { listenForReload() }
95
104
  }
96
105
 
106
+ /** On the main thread, when the activity is destroyed. */
97
107
  fun destroy() {
108
+ isDestroyed = true
109
+ reloadConnection?.disconnect()
110
+ animatedGraph.reset() // a looping animation would keep running on the dead views
98
111
  javaScriptHandler.post {
99
112
  runtime?.destroy()
100
113
  runtime = null
@@ -102,6 +115,38 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
102
115
  }
103
116
  }
104
117
 
118
+ /** (callId, ...arguments): settles the call with __asyncFunctionFinished; a throw rejects it. */
119
+ private fun asyncCall(function: AsyncFunction): NativeFunction = { arguments ->
120
+ val callId = int(arguments[0])
121
+ val owner = runtime
122
+ val promise = Promise { value, errorMessage ->
123
+ callIfStillRunning(owner, "__asyncFunctionFinished", callId, value, errorMessage)
124
+ }
125
+
126
+ runCatching { function(arguments.drop(1), promise) }.onFailure { promise.reject(it.message ?: it.toString()) }
127
+ null
128
+ }
129
+
130
+ /** The system may have switched between light and dark: nativue's views repaint, then JS is told. */
131
+ fun onConfigurationChanged() {
132
+ if (!ThemeColors.update(activity)) return
133
+
134
+ applyThemeColors(activity.window.decorView)
135
+ // Content not in the window now, like a hidden <Modal>'s, is repainted too.
136
+ nodesById.values.forEach { applyThemeColors(it.view) }
137
+ // The theme set them when the window was created; it isn't recreated (configChanges has uiMode).
138
+ val lightBars = WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS or
139
+ WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS
140
+ activity.window.insetsController?.setSystemBarsAppearance(if (ThemeColors.isDark) 0 else lightBars, lightBars)
141
+ evaluate { runtime?.call("__colorSchemeChanged", colorScheme()) }
142
+ }
143
+
144
+ private fun colorScheme(): String {
145
+ val nightMode = activity.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
146
+
147
+ return if (nightMode == Configuration.UI_MODE_NIGHT_YES) "dark" else "light"
148
+ }
149
+
105
150
  /** A URL the app was opened with (deep link), for the router (`__openURL`); after the bundle has run. */
106
151
  fun openURL(url: String) {
107
152
  evaluate { runtime?.call("__openURL", url) }
@@ -196,7 +241,7 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
196
241
 
197
242
  /** System back: closes the top <Modal>, else pops the innermost visible stack. */
198
243
  fun goBack(): Boolean {
199
- modalHostsByNodeId.values.lastOrNull { it.isShowing }?.let {
244
+ modalHostsByNodeId.values.filter { it.isShowing }.maxByOrNull { it.presentationOrder }?.let {
200
245
  it.requestClose()
201
246
  return true
202
247
  }
@@ -231,6 +276,11 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
231
276
  put("log") { arguments -> Log.i(TAG, "[JS] ${arguments[0]}") }
232
277
  put("reportError") { arguments -> reportError(arguments[0] as String, arguments[1] as String) }
233
278
  put("windowSize") { _ -> windowSize() }
279
+ put("platform") { _ -> "android" }
280
+ put("colorScheme") { _ -> colorScheme() }
281
+ // Prefixed, so a plugin can't replace nativue's own functions.
282
+ pluginRegistry.functions.forEach { (name, function) -> put("plugin:$name", function) }
283
+ pluginRegistry.asyncFunctions.forEach { (name, function) -> put("pluginAsync:$name", asyncCall(function)) }
234
284
  put("create") { arguments ->
235
285
  val id = int(arguments[0])
236
286
  val type = arguments[1] as String
@@ -242,7 +292,7 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
242
292
  }
243
293
  put("remove") { arguments ->
244
294
  val id = int(arguments[0])
245
- enqueue { nodesById.remove(id)?.removeFromParent() }
295
+ enqueue { nodesById[id]?.let(::removeNode) }
246
296
  }
247
297
  put("setText") { arguments ->
248
298
  val id = int(arguments[0])
@@ -273,9 +323,12 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
273
323
  private fun setTimer(timerId: Int, delay: Int) {
274
324
  val owner = runtime
275
325
 
276
- javaScriptHandler.postDelayed({
277
- if (runtime === owner) evaluate { runtime?.call("__fireTimer", timerId) }
278
- }, delay.toLong())
326
+ javaScriptHandler.postDelayed({ callIfStillRunning(owner, "__fireTimer", timerId) }, delay.toLong())
327
+ }
328
+
329
+ /** For results that arrive later: a reloaded runtime starts its timer, request and call ids over. */
330
+ private fun callIfStillRunning(owner: JavaScriptRuntime?, function: String, vararg arguments: Any?) {
331
+ evaluate { if (runtime === owner) runtime?.call(function, *arguments) }
279
332
  }
280
333
 
281
334
  private fun storageFunctions(): Map<String, NativeFunction> = mapOf(
@@ -333,11 +386,12 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
333
386
  val method = arguments[2] as String
334
387
  val headers = arguments[3] as? Map<*, *> ?: emptyMap<String, String>()
335
388
  val body = arguments[4] as? String
389
+ val owner = runtime
336
390
 
337
391
  thread {
338
392
  val (response, error) = runCatching { request(url, method, headers, body) }
339
393
  .fold({ Pair(it, null) }, { Pair(null, it.message ?: it.toString()) })
340
- evaluate { runtime?.call("__fetchFinished", requestId, response, error) }
394
+ callIfStillRunning(owner, "__fetchFinished", requestId, response, error)
341
395
  }
342
396
  },
343
397
  )
@@ -409,11 +463,12 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
409
463
  val candidateURLs = devServerURLs()
410
464
  var attempt = 0
411
465
 
412
- while (true) {
466
+ while (!isDestroyed) {
413
467
  devServerURL = candidateURLs[attempt++ % candidateURLs.size]
414
468
  runCatching {
415
469
  val connection = URL("$devServerURL/events").openConnection() as HttpURLConnection
416
470
  connection.readTimeout = 0
471
+ reloadConnection = connection
417
472
 
418
473
  connection.inputStream.bufferedReader().useLines { lines ->
419
474
  lines.filter { it == "data: reload" }.forEach { _ ->
@@ -430,8 +485,32 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
430
485
 
431
486
  // ---------- Main thread ----------
432
487
 
488
+ /** 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
+ // ponytail: 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()
502
+ }
503
+
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) }
507
+ }
508
+
433
509
  private fun resetNodeTree() {
434
- modalHostsByNodeId.values.forEach { it.setVisible(false) }
510
+ modalHostsByNodeId.values.forEach {
511
+ it.onEvent = {} // its "dismiss" would reach the new tree's node with the same id
512
+ it.setVisible(false)
513
+ }
435
514
  modalHostsByNodeId.clear()
436
515
  gestureReportersByNodeId.clear() // node ids start over
437
516
  animatedGraph.reset()
@@ -461,7 +540,7 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
461
540
  // A text button: tinted title, a ripple on press, faded when disabled.
462
541
  "Button" -> {
463
542
  val button = makeTextView()
464
- button.setTextColor(BUTTON_TINT)
543
+ button.styleColor = BUTTON_TINT
465
544
  button.gravity = Gravity.CENTER
466
545
  button.foreground = ripple(button.dp(8f).toFloat())
467
546
  button.setOnClickListener { dispatchEvent("press", id) }
@@ -518,15 +597,16 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
518
597
  }
519
598
 
520
599
  "KeyboardAvoidingView" -> NativeNode(KeyboardAvoidingView(activity), measuresContent = false).also {
521
- it.insetTypes = WindowInsets.Type.ime()
600
+ it.insetTypes = IME
522
601
  }
523
602
 
524
603
  "TextInput" -> NativeNode(makeTextInput(id), measuresContent = true)
525
604
 
526
605
  "Switch" -> {
527
- val toggle = Switch(activity)
528
- toggle.setOnCheckedChangeListener { view, isChecked ->
529
- if (view.isPressed) dispatchEvent("valuechange", id, isChecked) // not when set from JS
606
+ val toggle = ToggleSwitch(activity)
607
+ toggle.setOnCheckedChangeListener { _, isChecked ->
608
+ // Every change but JS's own: touch, keyboard and accessibility toggles alike.
609
+ if (!toggle.isSettingFromJavaScript) dispatchEvent("valuechange", id, isChecked)
530
610
  }
531
611
  NativeNode(toggle, measuresContent = true)
532
612
  }
@@ -537,11 +617,16 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
537
617
 
538
618
  "Svg" -> NativeNode(SvgView(activity), measuresContent = false)
539
619
 
540
- else -> NativeNode(ContainerView(activity), measuresContent = false)
620
+ else -> {
621
+ val makeView = pluginRegistry.viewMakers[type]
622
+ val view = makeView?.invoke { eventName, payload -> dispatchEvent(eventName, id, payload) }
623
+
624
+ NativeNode(view ?: ContainerView(activity), measuresContent = false)
625
+ }
541
626
  }
542
627
 
543
- private fun makeTextView() = TextView(activity).apply {
544
- setTextColor(DEFAULT_TEXT_COLOR)
628
+ private fun makeTextView() = TextLabel(activity).apply {
629
+ applyThemeColors()
545
630
  setTextSize(TypedValue.COMPLEX_UNIT_DIP, 17f)
546
631
  includeFontPadding = false
547
632
  }
@@ -550,7 +635,7 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
550
635
  val textInput = TextInputView(activity)
551
636
  textInput.background = null
552
637
  textInput.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 17f)
553
- textInput.setTextColor(DEFAULT_TEXT_COLOR)
638
+ textInput.applyThemeColors()
554
639
  textInput.isSingleLine = true
555
640
  textInput.gravity = Gravity.CENTER_VERTICAL
556
641
  textInput.addTextChangedListener(object : TextWatcher {
@@ -559,17 +644,19 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
559
644
  override fun onTextChanged(text: CharSequence?, start: Int, before: Int, count: Int) {}
560
645
 
561
646
  override fun afterTextChanged(text: Editable?) {
562
- if (!textInput.hasFocus()) return // set from JS
647
+ if (textInput.isSettingTextFromJavaScript) return // autofill and accessibility do count
563
648
 
564
649
  textInput.recordTextSentToJavaScript()
565
650
  dispatchEvent("changetext", id, text.toString())
566
651
  }
567
652
  })
568
- // Returning false lets the action close the keyboard, as single-line inputs are expected to.
653
+ // The return key closes the keyboard and ends editing, as single-line inputs do on iOS too.
569
654
  textInput.setOnEditorActionListener { _, _, _ ->
570
655
  dispatchEvent("submitediting", id, textInput.text.toString())
571
- false
656
+ hideKeyboard(textInput)
657
+ true
572
658
  }
659
+ textInput.setOnFocusChangeListener { _, hasFocus -> dispatchEvent(if (hasFocus) "focus" else "blur", id, null) }
573
660
 
574
661
  return textInput
575
662
  }
@@ -606,6 +693,8 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
606
693
  val node = nodesById[id] ?: return
607
694
  val view = node.view
608
695
 
696
+ if (key != "style" && view is PluginView) return view.setProp(key, value)
697
+
609
698
  when (key) {
610
699
  "style" -> {
611
700
  @Suppress("UNCHECKED_CAST")
@@ -650,7 +739,14 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
650
739
 
651
740
  // A scroll view pads its scrollable area by the system bars it's under, unless "never".
652
741
  "contentInsetAdjustmentBehavior" -> if (view is ScrollContainerView) {
653
- node.insetTypes = if (value == null || value == "never") 0 else SYSTEM_BARS
742
+ val systemBars = if (value == null || value == "never") 0 else SYSTEM_BARS
743
+ node.insetTypes = (node.insetTypes and IME) or systemBars
744
+ }
745
+
746
+ // The keyboard pads it too, and the focused input scrolls above it.
747
+ "automaticallyAdjustKeyboardInsets" -> if (view is ScrollContainerView) {
748
+ val keyboard = if (isTruthyAttribute(value)) IME else 0
749
+ node.insetTypes = (node.insetTypes and IME.inv()) or keyboard
654
750
  }
655
751
 
656
752
  "horizontal" -> setScrollDirection(node, isTruthyAttribute(value))
@@ -665,7 +761,7 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
665
761
 
666
762
  "value" -> {
667
763
  (view as? TextInputView)?.setTextFromJavaScript(value as? String ?: "")
668
- (view as? Switch)?.isChecked = isTruthyAttribute(value)
764
+ (view as? ToggleSwitch)?.setCheckedFromJavaScript(isTruthyAttribute(value))
669
765
  }
670
766
 
671
767
  "disabled" -> {
@@ -693,7 +789,7 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
693
789
 
694
790
  "color" -> {
695
791
  (view as? ProgressBar)?.indeterminateTintList = androidColor(value)?.let(ColorStateList::valueOf)
696
- (view as? SvgView)?.color = androidColor(value) ?: DEFAULT_TEXT_COLOR
792
+ (view as? SvgView)?.color = androidColor(value) ?: SVG_DEFAULT_COLOR
697
793
  }
698
794
 
699
795
  "viewBox" -> SvgView.rect(value)?.let { (view as? SvgView)?.viewBox = it }
@@ -708,7 +804,7 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
708
804
 
709
805
  "source" -> (view as? RemoteImageView)?.load(value as? String)
710
806
 
711
- "resizeMode" -> (view as? RemoteImageView)?.scaleType = RemoteImageView.scaleTypes[value] ?: android.widget.ImageView.ScaleType.CENTER_CROP
807
+ "resizeMode" -> (view as? RemoteImageView)?.scaleType = RemoteImageView.scaleTypes[value] ?: ImageView.ScaleType.CENTER_CROP
712
808
 
713
809
  "onLongPress" -> (view as? PressableView)?.reportsLongPress = isTruthyAttribute(value)
714
810
 
@@ -727,7 +823,7 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
727
823
  private fun setScrollDirection(node: NativeNode, horizontal: Boolean) {
728
824
  val scrollView = node.view as? ScrollContainerView ?: return
729
825
 
730
- node.yogaNode.setFlexDirection(if (horizontal) com.facebook.yoga.YogaFlexDirection.ROW else com.facebook.yoga.YogaFlexDirection.COLUMN)
826
+ node.yogaNode.setFlexDirection(if (horizontal) YogaFlexDirection.ROW else YogaFlexDirection.COLUMN)
731
827
  scrollView.setHorizontal(horizontal)
732
828
  }
733
829
 
@@ -743,7 +839,6 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
743
839
  return gestureReporter(viewId, view).setAnimatedMapping(eventName, fieldsToNodeIds)
744
840
  }
745
841
 
746
-
747
842
  if (mapping == null) {
748
843
  scrollView.onOffsetChange = null
749
844
  return
@@ -875,10 +970,11 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
875
970
  const val JAVASCRIPT_STACK_SIZE = 8L * 1024 * 1024
876
971
  const val SYMBOLICATE_TIMEOUT_MS = 2000
877
972
  const val RECONNECT_DELAY_MS = 2000L
878
- const val DEFAULT_TEXT_COLOR = 0xFF000000.toInt()
973
+ const val SVG_DEFAULT_COLOR = 0xFF000000.toInt()
879
974
  const val BUTTON_TINT = 0xFF007AFF.toInt()
880
975
  val EDGES = listOf(YogaEdge.LEFT, YogaEdge.TOP, YogaEdge.RIGHT, YogaEdge.BOTTOM)
881
976
  val SYSTEM_BARS = WindowInsets.Type.systemBars() or WindowInsets.Type.displayCutout()
977
+ val IME = WindowInsets.Type.ime()
882
978
  const val SHEET_TOP_GAP = 12f
883
979
 
884
980
  val keyboardInputTypes = mapOf(
@@ -62,19 +62,27 @@ class ModalHost(private val activity: Activity) {
62
62
  val isShowing: Boolean
63
63
  get() = isPresented
64
64
 
65
+ /** Back closes the modal presented last. */
66
+ var presentationOrder = 0L
67
+ private set
68
+
65
69
  private fun present() {
66
70
  if (isPresented) return
67
71
 
68
72
  isPresented = true
73
+ presentationOrder = System.nanoTime()
69
74
  val content = contentNode.view
75
+ // Shown again while still animating out: that dismissal's end would remove it.
76
+ content.animate().cancel()
77
+ (overlay.parent as? ViewGroup)?.removeView(overlay)
70
78
  content.background = when {
71
79
  transparent -> null
72
80
  isSheet -> GradientDrawable().apply {
73
- setColor(0xFFFFFFFF.toInt())
81
+ setColor(ThemeColors.surface)
74
82
  val radius = overlay.dp(28f).toFloat()
75
83
  cornerRadii = floatArrayOf(radius, radius, radius, radius, 0f, 0f, 0f, 0f)
76
84
  }
77
- else -> GradientDrawable().apply { setColor(0xFFFFFFFF.toInt()) }
85
+ else -> GradientDrawable().apply { setColor(ThemeColors.surface) }
78
86
  }
79
87
  content.clipToOutline = isSheet
80
88
  (content.parent as? ViewGroup)?.removeView(content)
@@ -2,6 +2,7 @@ package dev.nativue
2
2
 
3
3
  import android.app.Activity
4
4
  import android.content.Intent
5
+ import android.content.res.Configuration
5
6
  import android.os.Build
6
7
  import android.os.Bundle
7
8
  import android.view.ViewGroup
@@ -17,6 +18,7 @@ open class NativueActivity : Activity() {
17
18
  override fun onCreate(savedInstanceState: Bundle?) {
18
19
  super.onCreate(savedInstanceState)
19
20
  SoLoader.init(this, false) // Yoga loads its native library through it
21
+ ThemeColors.update(this)
20
22
 
21
23
  val rootView = RootView(this)
22
24
  setContentView(rootView)
@@ -51,6 +53,12 @@ open class NativueActivity : Activity() {
51
53
  intent.data?.let { bridge.openURL(it.toString()) }
52
54
  }
53
55
 
56
+ /** The manifest's configChanges keep the activity (and the JS state) through uiMode changes. */
57
+ override fun onConfigurationChanged(newConfig: Configuration) {
58
+ super.onConfigurationChanged(newConfig)
59
+ bridge.onConfigurationChanged()
60
+ }
61
+
54
62
  /**
55
63
  * Android 13+ takes back gestures only when registered for (predictive back); older versions call
56
64
  * onBackPressed.