@nativue/core 0.1.0 → 0.3.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.
Files changed (42) hide show
  1. package/Package.swift +26 -2
  2. package/android/build.gradle.kts +2 -2
  3. package/android/consumer-rules.pro +3 -0
  4. package/android/nativue.settings.gradle.kts +56 -0
  5. package/android/src/main/java/dev/nativue/Bridge.kt +51 -7
  6. package/android/src/main/java/dev/nativue/ModalHost.kt +2 -2
  7. package/android/src/main/java/dev/nativue/NativueActivity.kt +8 -0
  8. package/android/src/main/java/dev/nativue/Navigation.kt +32 -24
  9. package/android/src/main/java/dev/nativue/Plugins.kt +75 -0
  10. package/android/src/main/java/dev/nativue/Style.kt +5 -1
  11. package/android/src/main/java/dev/nativue/Theme.kt +61 -0
  12. package/android/src/main/java/dev/nativue/Views.kt +14 -2
  13. package/cli/config.d.mts +19 -0
  14. package/cli/config.mjs +4 -0
  15. package/cli/link.mjs +129 -0
  16. package/cli/nativue.mjs +67 -20
  17. package/cli/symbolicate.mjs +3 -5
  18. package/ios/Bridge.swift +207 -102
  19. package/ios/JavaScriptRuntime/JavaScriptRuntime.mm +231 -0
  20. package/ios/JavaScriptRuntime/include/NativueJavaScriptRuntime.h +29 -0
  21. package/ios/JavaScriptRuntime/vendor/hermes/LICENSE +21 -0
  22. package/ios/JavaScriptRuntime/vendor/hermes/Public/CrashManager.h +107 -0
  23. package/ios/JavaScriptRuntime/vendor/hermes/Public/CtorConfig.h +145 -0
  24. package/ios/JavaScriptRuntime/vendor/hermes/Public/GCConfig.h +211 -0
  25. package/ios/JavaScriptRuntime/vendor/hermes/Public/GCTripwireContext.h +40 -0
  26. package/ios/JavaScriptRuntime/vendor/hermes/Public/HermesExport.h +14 -0
  27. package/ios/JavaScriptRuntime/vendor/hermes/Public/RuntimeConfig.h +141 -0
  28. package/ios/JavaScriptRuntime/vendor/hermes/Public/SamplingProfiler.h +270 -0
  29. package/ios/JavaScriptRuntime/vendor/hermes/hermes.h +242 -0
  30. package/ios/NativeNode.swift +1 -0
  31. package/ios/NativueView.swift +10 -3
  32. package/ios/Plugins.swift +45 -0
  33. package/ios/Style.swift +14 -1
  34. package/package.json +7 -2
  35. package/src/appearance.ts +49 -0
  36. package/src/components.ts +3 -1
  37. package/src/entry.ts +2 -1
  38. package/src/globals.ts +3 -0
  39. package/src/native-functions.ts +41 -0
  40. package/src/renderer.ts +58 -1
  41. package/src/types.ts +2 -0
  42. package/src/virtual-modules.d.ts +2 -0
package/Package.swift CHANGED
@@ -8,6 +8,30 @@ let package = Package(
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: [
11
- .target(name: "Nativue", dependencies: [.product(name: "yoga", package: "yoga")], path: "ios"),
12
- ]
11
+ .target(
12
+ name: "Nativue",
13
+ dependencies: ["JavaScriptRuntime", .product(name: "yoga", package: "yoga")],
14
+ path: "ios",
15
+ exclude: ["JavaScriptRuntime"]
16
+ ),
17
+ .target(
18
+ name: "JavaScriptRuntime",
19
+ dependencies: ["hermesvm"],
20
+ path: "ios/JavaScriptRuntime",
21
+ exclude: ["vendor/hermes/LICENSE"],
22
+ cxxSettings: [
23
+ .headerSearchPath("vendor"),
24
+ .headerSearchPath("../../android/src/main/cpp/jsi"),
25
+ ]
26
+ ),
27
+ // The iOS slices of hermes-ios (Maven Central), the same Hermes version as hermes-android in
28
+ // android/build.gradle.kts and hermes-compiler in package.json: bytecode only runs on the Hermes
29
+ // that compiled it.
30
+ .binaryTarget(
31
+ name: "hermesvm",
32
+ url: "https://github.com/nativue/nativue/releases/download/hermes-260318099.0.8/hermesvm.xcframework.zip",
33
+ checksum: "9147f0187b5790e6c478cfd3de4de585666fa2af34a67dc8a0e8243ff0ff580d"
34
+ ),
35
+ ],
36
+ cxxLanguageStandard: .cxx20
13
37
  )
@@ -66,8 +66,8 @@ android {
66
66
  }
67
67
 
68
68
  dependencies {
69
- // Same version as the vendored JSI headers in src/main/cpp/jsi, and as hermes-compiler in
70
- // package.json: bytecode only runs on the Hermes that compiled it.
69
+ // Same version as the vendored JSI headers in src/main/cpp/jsi, hermes-compiler in package.json
70
+ // and hermesvm in Package.swift: bytecode only runs on the Hermes that compiled it.
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")
@@ -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
@@ -17,6 +18,7 @@ import android.view.Gravity
17
18
  import android.view.View
18
19
  import android.view.WindowInsets
19
20
  import android.view.WindowInsetsAnimation
21
+ import android.view.WindowInsetsController
20
22
  import android.graphics.Insets
21
23
  import android.view.inputmethod.EditorInfo
22
24
  import android.view.inputmethod.InputMethodManager
@@ -46,6 +48,7 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
46
48
  private val isDebuggable = activity.applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE != 0
47
49
  private val density = activity.resources.displayMetrics.density
48
50
  private val storage = activity.getSharedPreferences("dev.nativue.storage", Context.MODE_PRIVATE)
51
+ private val pluginRegistry = PluginRegistry(activity)
49
52
 
50
53
  // Only touched on the JS thread.
51
54
  private var runtime: JavaScriptRuntime? = null
@@ -102,6 +105,35 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
102
105
  }
103
106
  }
104
107
 
108
+ /** (callId, ...arguments): settles the call with __asyncFunctionFinished; a throw rejects it. */
109
+ private fun asyncCall(function: AsyncFunction): NativeFunction = { arguments ->
110
+ val callId = int(arguments[0])
111
+ val promise = Promise { value, errorMessage ->
112
+ evaluate { runtime?.call("__asyncFunctionFinished", callId, value, errorMessage) }
113
+ }
114
+
115
+ runCatching { function(arguments.drop(1), promise) }.onFailure { promise.reject(it.message ?: it.toString()) }
116
+ null
117
+ }
118
+
119
+ /** The system may have switched between light and dark: nativue's views repaint, then JS is told. */
120
+ fun onConfigurationChanged() {
121
+ if (!ThemeColors.update(activity)) return
122
+
123
+ applyThemeColors(activity.window.decorView)
124
+ // The theme set them when the window was created; it isn't recreated (configChanges has uiMode).
125
+ val lightBars = WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS or
126
+ WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS
127
+ activity.window.insetsController?.setSystemBarsAppearance(if (ThemeColors.isDark) 0 else lightBars, lightBars)
128
+ evaluate { runtime?.call("__colorSchemeChanged", colorScheme()) }
129
+ }
130
+
131
+ private fun colorScheme(): String {
132
+ val nightMode = activity.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
133
+
134
+ return if (nightMode == Configuration.UI_MODE_NIGHT_YES) "dark" else "light"
135
+ }
136
+
105
137
  /** A URL the app was opened with (deep link), for the router (`__openURL`); after the bundle has run. */
106
138
  fun openURL(url: String) {
107
139
  evaluate { runtime?.call("__openURL", url) }
@@ -231,6 +263,11 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
231
263
  put("log") { arguments -> Log.i(TAG, "[JS] ${arguments[0]}") }
232
264
  put("reportError") { arguments -> reportError(arguments[0] as String, arguments[1] as String) }
233
265
  put("windowSize") { _ -> windowSize() }
266
+ put("platform") { _ -> "android" }
267
+ put("colorScheme") { _ -> colorScheme() }
268
+ // Prefixed, so a plugin can't replace nativue's own functions.
269
+ pluginRegistry.functions.forEach { (name, function) -> put("plugin:$name", function) }
270
+ pluginRegistry.asyncFunctions.forEach { (name, function) -> put("pluginAsync:$name", asyncCall(function)) }
234
271
  put("create") { arguments ->
235
272
  val id = int(arguments[0])
236
273
  val type = arguments[1] as String
@@ -461,7 +498,7 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
461
498
  // A text button: tinted title, a ripple on press, faded when disabled.
462
499
  "Button" -> {
463
500
  val button = makeTextView()
464
- button.setTextColor(BUTTON_TINT)
501
+ button.styleColor = BUTTON_TINT
465
502
  button.gravity = Gravity.CENTER
466
503
  button.foreground = ripple(button.dp(8f).toFloat())
467
504
  button.setOnClickListener { dispatchEvent("press", id) }
@@ -537,11 +574,16 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
537
574
 
538
575
  "Svg" -> NativeNode(SvgView(activity), measuresContent = false)
539
576
 
540
- else -> NativeNode(ContainerView(activity), measuresContent = false)
577
+ else -> {
578
+ val makeView = pluginRegistry.viewMakers[type]
579
+ val view = makeView?.invoke { eventName, payload -> dispatchEvent(eventName, id, payload) }
580
+
581
+ NativeNode(view ?: ContainerView(activity), measuresContent = false)
582
+ }
541
583
  }
542
584
 
543
- private fun makeTextView() = TextView(activity).apply {
544
- setTextColor(DEFAULT_TEXT_COLOR)
585
+ private fun makeTextView() = TextLabel(activity).apply {
586
+ applyThemeColors()
545
587
  setTextSize(TypedValue.COMPLEX_UNIT_DIP, 17f)
546
588
  includeFontPadding = false
547
589
  }
@@ -550,7 +592,7 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
550
592
  val textInput = TextInputView(activity)
551
593
  textInput.background = null
552
594
  textInput.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 17f)
553
- textInput.setTextColor(DEFAULT_TEXT_COLOR)
595
+ textInput.applyThemeColors()
554
596
  textInput.isSingleLine = true
555
597
  textInput.gravity = Gravity.CENTER_VERTICAL
556
598
  textInput.addTextChangedListener(object : TextWatcher {
@@ -606,6 +648,8 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
606
648
  val node = nodesById[id] ?: return
607
649
  val view = node.view
608
650
 
651
+ if (key != "style" && view is PluginView) return view.setProp(key, value)
652
+
609
653
  when (key) {
610
654
  "style" -> {
611
655
  @Suppress("UNCHECKED_CAST")
@@ -693,7 +737,7 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
693
737
 
694
738
  "color" -> {
695
739
  (view as? ProgressBar)?.indeterminateTintList = androidColor(value)?.let(ColorStateList::valueOf)
696
- (view as? SvgView)?.color = androidColor(value) ?: DEFAULT_TEXT_COLOR
740
+ (view as? SvgView)?.color = androidColor(value) ?: SVG_DEFAULT_COLOR
697
741
  }
698
742
 
699
743
  "viewBox" -> SvgView.rect(value)?.let { (view as? SvgView)?.viewBox = it }
@@ -875,7 +919,7 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
875
919
  const val JAVASCRIPT_STACK_SIZE = 8L * 1024 * 1024
876
920
  const val SYMBOLICATE_TIMEOUT_MS = 2000
877
921
  const val RECONNECT_DELAY_MS = 2000L
878
- const val DEFAULT_TEXT_COLOR = 0xFF000000.toInt()
922
+ const val SVG_DEFAULT_COLOR = 0xFF000000.toInt()
879
923
  const val BUTTON_TINT = 0xFF007AFF.toInt()
880
924
  val EDGES = listOf(YogaEdge.LEFT, YogaEdge.TOP, YogaEdge.RIGHT, YogaEdge.BOTTOM)
881
925
  val SYSTEM_BARS = WindowInsets.Type.systemBars() or WindowInsets.Type.displayCutout()
@@ -70,11 +70,11 @@ class ModalHost(private val activity: Activity) {
70
70
  content.background = when {
71
71
  transparent -> null
72
72
  isSheet -> GradientDrawable().apply {
73
- setColor(0xFFFFFFFF.toInt())
73
+ setColor(ThemeColors.surface)
74
74
  val radius = overlay.dp(28f).toFloat()
75
75
  cornerRadii = floatArrayOf(radius, radius, radius, radius, 0f, 0f, 0f, 0f)
76
76
  }
77
- else -> GradientDrawable().apply { setColor(0xFFFFFFFF.toInt()) }
77
+ else -> GradientDrawable().apply { setColor(ThemeColors.surface) }
78
78
  }
79
79
  content.clipToOutline = isSheet
80
80
  (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.
@@ -29,11 +29,7 @@ import kotlin.math.roundToInt
29
29
 
30
30
  private const val TRANSITION_DURATION_MS = 350L
31
31
  private val emphasizedInterpolator = PathInterpolator(0.2f, 0f, 0f, 1f)
32
- private const val ON_SURFACE = 0xFF1D1B20.toInt()
33
- private const val ON_SURFACE_VARIANT = 0xFF49454F.toInt()
34
- private const val SURFACE = 0xFFFFFFFF.toInt()
35
32
  private const val SCRIM = 0x52000000
36
- private const val BAR_BACKGROUND = 0xFFF3EDF7.toInt() // Material 3 surface container
37
33
 
38
34
  fun View.dp(value: Float): Int = (value * resources.displayMetrics.density).roundToInt()
39
35
 
@@ -60,7 +56,7 @@ fun View.offsetIn(ancestor: View): Pair<Int, Int> {
60
56
  * The screen's Yoga node is padded by the header's height, so the content starts below it.
61
57
  */
62
58
  @SuppressLint("ViewConstructor")
63
- class ScreenView(context: Context) : ContainerView(context) {
59
+ class ScreenView(context: Context) : ContainerView(context), ThemeAware {
64
60
  val content = ContainerView(context)
65
61
  val header = ScreenHeader(context)
66
62
 
@@ -102,13 +98,17 @@ class ScreenView(context: Context) : ContainerView(context) {
102
98
  private val sheetDrag = SheetDrag(this) { onEvent("dismissed", null) }
103
99
 
104
100
  init {
105
- background = GradientDrawable().apply { setColor(SURFACE) }
101
+ applyThemeColors()
106
102
  clipChildren = true
107
103
  addView(content)
108
104
  addView(header)
109
105
  header.onEvent = { eventName, payload -> onEvent(eventName, payload) }
110
106
  }
111
107
 
108
+ override fun applyThemeColors() {
109
+ background = GradientDrawable().apply { setColor(ThemeColors.surface) }
110
+ }
111
+
112
112
  /** dp the content starts at: below the header, or at the top without one. */
113
113
  val contentTop: Float
114
114
  get() = if (headerShown) (topInset + header.barHeight) / resources.displayMetrics.density else 0f
@@ -197,7 +197,7 @@ class SheetDrag(private val sheet: View, private val onDismiss: () -> Unit) {
197
197
  }
198
198
 
199
199
  /** Material 3's small top app bar (large with `headerLargeTitle`): back arrow, title and text actions. */
200
- class ScreenHeader(context: Context) : LinearLayout(context) {
200
+ class ScreenHeader(context: Context) : LinearLayout(context), ThemeAware {
201
201
  var onEvent: (eventName: String, payload: Any?) -> Unit = { _, _ -> }
202
202
 
203
203
  private val dragHandle = View(context)
@@ -211,14 +211,14 @@ class ScreenHeader(context: Context) : LinearLayout(context) {
211
211
  var tintColor: Int? = null
212
212
  set(value) {
213
213
  field = value
214
- navigationButton.color = value ?: ON_SURFACE
214
+ navigationButton.color = value ?: ThemeColors.onSurface
215
215
  listOf(leftItems, rightItems).forEach { items ->
216
216
  for (index in 0 until items.childCount) tint(items.getChildAt(index))
217
217
  }
218
218
  }
219
219
 
220
220
  private val actionColor: Int
221
- get() = tintColor ?: ON_SURFACE_VARIANT
221
+ get() = tintColor ?: ThemeColors.onSurfaceVariant
222
222
 
223
223
  var showsDragHandle = false
224
224
  set(value) {
@@ -239,12 +239,8 @@ class ScreenHeader(context: Context) : LinearLayout(context) {
239
239
 
240
240
  init {
241
241
  orientation = VERTICAL
242
- setBackgroundColor(SURFACE)
243
-
244
- dragHandle.background = GradientDrawable().apply {
245
- setColor(ON_SURFACE_VARIANT and 0x66FFFFFF)
246
- cornerRadius = dp(2f).toFloat()
247
- }
242
+ dragHandle.background = GradientDrawable().apply { cornerRadius = dp(2f).toFloat() }
243
+ applyThemeColors()
248
244
  dragHandle.visibility = View.GONE
249
245
  addView(dragHandle, LayoutParams(dp(32f), dp(4f)).apply {
250
246
  gravity = Gravity.CENTER_HORIZONTAL
@@ -267,6 +263,13 @@ class ScreenHeader(context: Context) : LinearLayout(context) {
267
263
  addView(largeTitle, LayoutParams(LayoutParams.MATCH_PARENT, dp(88f)))
268
264
  }
269
265
 
266
+ override fun applyThemeColors() {
267
+ setBackgroundColor(ThemeColors.surface)
268
+ (dragHandle.background as GradientDrawable).setColor(ThemeColors.onSurfaceVariant and 0x66FFFFFF)
269
+ listOf(title, largeTitle).forEach { it.setTextColor(ThemeColors.onSurface) }
270
+ tintColor = tintColor // repaints the navigation button and the items
271
+ }
272
+
270
273
  fun setTitle(text: String?) {
271
274
  title.text = text
272
275
  largeTitle.text = text
@@ -314,7 +317,7 @@ class ScreenHeader(context: Context) : LinearLayout(context) {
314
317
 
315
318
  private fun textView(size: Float, style: Int) = TextView(context).apply {
316
319
  setTextSize(TypedValue.COMPLEX_UNIT_SP, size)
317
- setTextColor(ON_SURFACE)
320
+ setTextColor(ThemeColors.onSurface)
318
321
  typeface = Typeface.create(Typeface.DEFAULT, if (style == Typeface.BOLD) 500 else 400, false)
319
322
  isSingleLine = true
320
323
  ellipsize = android.text.TextUtils.TruncateAt.END
@@ -323,7 +326,7 @@ class ScreenHeader(context: Context) : LinearLayout(context) {
323
326
 
324
327
  private fun iconButton(elements: List<List<Any>>) = IconButton(context).apply {
325
328
  this.elements = elements
326
- color = ON_SURFACE
329
+ color = ThemeColors.onSurface
327
330
  }
328
331
 
329
332
  companion object {
@@ -367,7 +370,7 @@ fun ripple(cornerRadius: Float): RippleDrawable {
367
370
  this.cornerRadius = cornerRadius
368
371
  }
369
372
 
370
- return RippleDrawable(ColorStateList.valueOf(0x1F000000), null, mask)
373
+ return RippleDrawable(ColorStateList.valueOf(ThemeColors.ripple), null, mask)
371
374
  }
372
375
 
373
376
  /**
@@ -505,7 +508,7 @@ private fun ValueAnimator.doOnEnd(action: () -> Unit) {
505
508
  * showing. A tap on the bar is reported so JS switches; a tap on the selected tab goes back to its first
506
509
  * screen, or scrolls it to the top.
507
510
  */
508
- class TabBarView(context: Context) : ContainerView(context) {
511
+ class TabBarView(context: Context) : ContainerView(context), ThemeAware {
509
512
  var onTabChange: (index: Int) -> Unit = {}
510
513
 
511
514
  var selectedIndex = 0
@@ -531,7 +534,7 @@ class TabBarView(context: Context) : ContainerView(context) {
531
534
  var barBackgroundColor: Int? = null
532
535
  set(value) {
533
536
  field = value
534
- bar.setBackgroundColor(value ?: BAR_BACKGROUND)
537
+ bar.setBackgroundColor(value ?: ThemeColors.barBackground)
535
538
  }
536
539
 
537
540
  /** Pixels the system navigation bar covers; the bar extends under it. */
@@ -554,10 +557,15 @@ class TabBarView(context: Context) : ContainerView(context) {
554
557
 
555
558
  init {
556
559
  clipChildren = true
557
- bar.setBackgroundColor(BAR_BACKGROUND)
560
+ bar.setBackgroundColor(ThemeColors.barBackground)
558
561
  addView(bar)
559
562
  }
560
563
 
564
+ override fun applyThemeColors() {
565
+ barBackgroundColor = barBackgroundColor
566
+ updateItems()
567
+ }
568
+
561
569
  override fun onViewAdded(child: View) {
562
570
  if (child === bar) return
563
571
 
@@ -661,13 +669,13 @@ private class TabItemView(context: Context) : LinearLayout(context) {
661
669
  label.isSingleLine = true
662
670
  addView(label, LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT).apply { topMargin = dp(4f) })
663
671
 
664
- background = RippleDrawable(ColorStateList.valueOf(0x1F000000), null, null)
672
+ background = RippleDrawable(ColorStateList.valueOf(ThemeColors.ripple), null, null)
665
673
  }
666
674
 
667
675
  /** Only svg icons (@nativue/icons) draw on Android; SF Symbol names are iOS-only. */
668
676
  fun update(item: Map<*, *>, isSelected: Boolean, activeTintColor: Int?, inactiveTintColor: Int?) {
669
- val activeColor = activeTintColor ?: ON_SURFACE
670
- val color = if (isSelected) activeColor else inactiveTintColor ?: ON_SURFACE_VARIANT
677
+ val activeColor = activeTintColor ?: ThemeColors.onSurface
678
+ val color = if (isSelected) activeColor else inactiveTintColor ?: ThemeColors.onSurfaceVariant
671
679
  val svg = item["svg"] as? Map<*, *>
672
680
 
673
681
  icon.elements = svg?.get("elements") as? List<*> ?: emptyList<Any>()
@@ -0,0 +1,75 @@
1
+ package dev.nativue
2
+
3
+ import android.content.Context
4
+ import android.view.View
5
+ import java.util.concurrent.atomic.AtomicBoolean
6
+
7
+ /**
8
+ * The native side of a package: functions JavaScript calls (`requireNativeFunction`) and views it
9
+ * renders. Packages declare their Gradle module and plugin class in package.json;
10
+ * nativue.settings.gradle.kts adds them to the app.
11
+ */
12
+ interface NativuePlugin {
13
+ fun register(registry: PluginRegistry)
14
+ }
15
+
16
+ /** sendEvent("change", payload) reaches the element's @change; event names are lowercase. */
17
+ typealias SendEvent = (eventName: String, payload: Any?) -> Unit
18
+
19
+ /** Settles an async function's JavaScript Promise; only the first call counts. */
20
+ class Promise internal constructor(private val settle: (value: Any?, errorMessage: String?) -> Unit) {
21
+ private val settled = AtomicBoolean(false)
22
+
23
+ fun resolve(value: Any? = null) {
24
+ if (settled.compareAndSet(false, true)) settle(value, null)
25
+ }
26
+
27
+ fun reject(errorMessage: String) {
28
+ if (settled.compareAndSet(false, true)) settle(null, errorMessage)
29
+ }
30
+ }
31
+
32
+ /** Called on the JavaScript thread; settles `promise` from any thread, when the work is done. */
33
+ typealias AsyncFunction = (arguments: List<Any?>, promise: Promise) -> Unit
34
+
35
+ /** `context` is the app's activity. */
36
+ class PluginRegistry internal constructor(val context: Context) {
37
+ internal val functions = mutableMapOf<String, NativeFunction>()
38
+ internal val asyncFunctions = mutableMapOf<String, AsyncFunction>()
39
+ internal val viewMakers = mutableMapOf<String, (SendEvent) -> View>()
40
+
41
+ init {
42
+ pluginClassNames(context).forEach { className ->
43
+ val plugin = Class.forName(className).getDeclaredConstructor().newInstance() as NativuePlugin
44
+ plugin.register(this)
45
+ }
46
+ }
47
+
48
+ /** Runs on the JavaScript thread and returns synchronously: post to the main thread for views. */
49
+ fun addFunction(name: String, function: NativeFunction) {
50
+ functions[name] = function
51
+ }
52
+
53
+ /** For work that takes time (a permission prompt, the camera): JavaScript gets a Promise. */
54
+ fun addAsyncFunction(name: String, function: AsyncFunction) {
55
+ asyncFunctions[name] = function
56
+ }
57
+
58
+ /** `type` is the element's tag, e.g. "MapView" for h('MapView'). Created on the main thread. */
59
+ fun addView(type: String, makeView: (SendEvent) -> View) {
60
+ viewMakers[type] = makeView
61
+ }
62
+ }
63
+
64
+ /** The string resource nativue.settings.gradle.kts writes: the plugin classes, comma-separated. */
65
+ private fun pluginClassNames(context: Context): List<String> {
66
+ val resourceId = context.resources.getIdentifier("nativue_plugins", "string", context.packageName)
67
+ if (resourceId == 0) return emptyList()
68
+
69
+ return context.getString(resourceId).split(',').filter { it.isNotEmpty() }
70
+ }
71
+
72
+ /** A plugin view gets its props here, all but `style`, which nativue applies (layout included). */
73
+ interface PluginView {
74
+ fun setProp(key: String, value: Any?)
75
+ }
@@ -58,7 +58,11 @@ private fun NativeNode.applyVisualProperty(property: String, value: Any?) {
58
58
  "opacity" -> view.alpha = number(value) ?: 1f
59
59
  "transform" -> view.applyTransform(value)
60
60
  "overflow" -> setClipsContent(value == "hidden")
61
- "color" -> androidColor(value)?.let { textView?.setTextColor(it) }
61
+ "color" -> when (val view = textView) {
62
+ is TextLabel -> view.styleColor = androidColor(value)
63
+ is TextInputView -> view.styleColor = androidColor(value)
64
+ else -> androidColor(value)?.let { view?.setTextColor(it) }
65
+ }
62
66
  "textAlign" -> textView?.gravity = textGravities[value] ?: Gravity.START
63
67
  }
64
68
  }
@@ -0,0 +1,61 @@
1
+ package dev.nativue
2
+
3
+ import android.content.Context
4
+ import android.content.res.Configuration
5
+ import android.view.View
6
+ import android.view.ViewGroup
7
+
8
+ /**
9
+ * The colors of nativue's own views (headers, tab bars, sheets, text without a color) when the app
10
+ * sets none: Material 3's, light or dark with the system, as UIKit's are on iOS. The activity isn't
11
+ * recreated when the system switches (configChanges has uiMode), so views that use them implement
12
+ * ThemeAware and are told by applyThemeColors.
13
+ */
14
+ internal object ThemeColors {
15
+ var isDark = false
16
+ private set
17
+
18
+ val text get() = pick(light = 0xFF000000, dark = 0xFFFFFFFF)
19
+ val placeholder get() = pick(light = 0x4C3C3C43, dark = 0x4CEBEBF5)
20
+ val onSurface get() = pick(light = 0xFF1D1B20, dark = 0xFFE6E0E9)
21
+ val onSurfaceVariant get() = pick(light = 0xFF49454F, dark = 0xFFCAC4D0)
22
+ val surface get() = pick(light = 0xFFFFFFFF, dark = 0xFF141218)
23
+ val barBackground get() = pick(light = 0xFFF3EDF7, dark = 0xFF211F26)
24
+ val ripple get() = pick(light = 0x1F000000, dark = 0x1FFFFFFF)
25
+
26
+ /** Reads the system's mode; true when it changed. */
27
+ fun update(context: Context): Boolean {
28
+ val nightMode = context.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
29
+ val wasDark = isDark
30
+ isDark = nightMode == Configuration.UI_MODE_NIGHT_YES
31
+
32
+ return isDark != wasDark
33
+ }
34
+
35
+ private fun pick(light: Long, dark: Long) = (if (isDark) dark else light).toInt()
36
+ }
37
+
38
+ internal interface ThemeAware {
39
+ fun applyThemeColors()
40
+ }
41
+
42
+ /** After a switch between light and dark: every ThemeAware view under [view] repaints. */
43
+ internal fun applyThemeColors(view: View) {
44
+ (view as? ThemeAware)?.applyThemeColors()
45
+ if (view !is ViewGroup) return
46
+
47
+ for (index in 0 until view.childCount) applyThemeColors(view.getChildAt(index))
48
+ }
49
+
50
+ /** <Text>'s view: without a `color` style, it follows the theme. */
51
+ internal class TextLabel(context: Context) : android.widget.TextView(context), ThemeAware {
52
+ var styleColor: Int? = null
53
+ set(value) {
54
+ field = value
55
+ applyThemeColors()
56
+ }
57
+
58
+ override fun applyThemeColors() {
59
+ setTextColor(styleColor ?: ThemeColors.text)
60
+ }
61
+ }
@@ -318,7 +318,7 @@ private class RefreshIndicator(context: Context) : FrameLayout(context) {
318
318
  init {
319
319
  background = android.graphics.drawable.GradientDrawable().apply {
320
320
  shape = android.graphics.drawable.GradientDrawable.OVAL
321
- setColor(0xFFFFFFFF.toInt())
321
+ setColor(ThemeColors.surface)
322
322
  }
323
323
  elevation = dp(6f).toFloat()
324
324
  val spinnerSize = dp(24f)
@@ -457,11 +457,23 @@ class RemoteImageView(context: Context) : ImageView(context) {
457
457
  }
458
458
 
459
459
  /** Single-line text field behind <TextInput>. Mirrors ios/TextInputView.swift. */
460
- class TextInputView(context: Context) : android.widget.EditText(context) {
460
+ class TextInputView(context: Context) : android.widget.EditText(context), ThemeAware {
461
+ /** Without a `color` style, the text follows the theme. */
462
+ var styleColor: Int? = null
463
+ set(value) {
464
+ field = value
465
+ applyThemeColors()
466
+ }
467
+
461
468
  // ponytail: a value JS sets on purpose that equals text typed earlier in the same editing session is
462
469
  // ignored too; tag each change with a counter if that ever matters.
463
470
  private val textsSentToJavaScript = mutableSetOf<String>()
464
471
 
472
+ override fun applyThemeColors() {
473
+ setTextColor(styleColor ?: ThemeColors.text)
474
+ setHintTextColor(ThemeColors.placeholder)
475
+ }
476
+
465
477
  fun recordTextSentToJavaScript() {
466
478
  textsSentToJavaScript.add(text.toString())
467
479
  }
@@ -0,0 +1,19 @@
1
+ import type { Plugin as VitePlugin } from 'vite'
2
+
3
+ /**
4
+ * A plugin of nativue.config.ts, e.g. @nativue/tailwind: build-time work through Vite plugins, and a
5
+ * module the app imports before it runs.
6
+ */
7
+ export interface NativuePlugin {
8
+ name: string
9
+ /** Added to the bundler's (Vite's) plugins. */
10
+ vite?: VitePlugin | VitePlugin[]
11
+ /** Imported before the app runs, resolved from the app: a package path or a virtual module. */
12
+ runtime?: string
13
+ }
14
+
15
+ export interface NativueConfig {
16
+ plugins?: NativuePlugin[]
17
+ }
18
+
19
+ export function defineConfig(config: NativueConfig): NativueConfig