@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.
@@ -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
  /**
@@ -377,7 +380,7 @@ fun ripple(cornerRadius: Float): RippleDrawable {
377
380
  */
378
381
  class ScreenStackView(context: Context) : ContainerView(context) {
379
382
  private val screens: List<ScreenView>
380
- get() = (0 until childCount).mapNotNull { getChildAt(it) as? ScreenView }
383
+ get() = screenChildren()
381
384
 
382
385
  init {
383
386
  clipChildren = true
@@ -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. */
@@ -550,14 +553,19 @@ class TabBarView(context: Context) : ContainerView(context) {
550
553
  private val bar = LinearLayout(context)
551
554
 
552
555
  private val screens: List<ScreenView>
553
- get() = (0 until childCount).mapNotNull { getChildAt(it) as? ScreenView }
556
+ get() = screenChildren()
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>()
@@ -686,3 +694,6 @@ private class TabItemView(context: Context) : LinearLayout(context) {
686
694
  badge.visibility = if (badgeText.isNullOrEmpty()) View.GONE else View.VISIBLE
687
695
  }
688
696
  }
697
+
698
+ /** The screens among a container's children, in order. */
699
+ private fun ViewGroup.screenChildren(): List<ScreenView> = (0 until childCount).mapNotNull { getChildAt(it) as? ScreenView }
@@ -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
+ }
@@ -4,6 +4,7 @@ import android.annotation.SuppressLint
4
4
  import android.content.Context
5
5
  import android.graphics.Bitmap
6
6
  import android.graphics.BitmapFactory
7
+ import android.graphics.Rect
7
8
  import android.os.Handler
8
9
  import android.os.Looper
9
10
  import android.util.Base64
@@ -17,6 +18,7 @@ import android.view.inputmethod.InputMethodManager
17
18
  import android.widget.ImageView
18
19
  import android.widget.ProgressBar
19
20
  import android.widget.ScrollView
21
+ import android.widget.Switch
20
22
  import java.net.URL
21
23
  import kotlin.concurrent.thread
22
24
  import kotlin.math.abs
@@ -81,6 +83,9 @@ class PressableView(context: Context) : ContainerView(context) {
81
83
 
82
84
  @SuppressLint("ClickableViewAccessibility")
83
85
  override fun onTouchEvent(event: MotionEvent): Boolean {
86
+ // Consumed but ignored, as disabled Android buttons do: the touch doesn't reach a parent.
87
+ if (!isEnabled) return true
88
+
84
89
  when (event.actionMasked) {
85
90
  MotionEvent.ACTION_DOWN -> pressIn()
86
91
  MotionEvent.ACTION_UP -> pressOut(pressed = isInside(event))
@@ -111,6 +116,11 @@ class PressableView(context: Context) : ContainerView(context) {
111
116
  if (pressed && !didLongPress) onEvent("press")
112
117
  }
113
118
 
119
+ override fun setEnabled(enabled: Boolean) {
120
+ super.setEnabled(enabled)
121
+ if (!enabled) longPressHandler.removeCallbacksAndMessages(null)
122
+ }
123
+
114
124
  private fun isInside(event: MotionEvent) = event.x in 0f..width.toFloat() && event.y in 0f..height.toFloat()
115
125
  }
116
126
 
@@ -258,8 +268,21 @@ class ScrollContainerView(context: Context) : ContainerView(context) {
258
268
  val (left, top, right, bottom) = contentInsets
259
269
  if (scroller.paddingLeft == left && scroller.paddingTop == top && scroller.paddingRight == right && scroller.paddingBottom == bottom) return
260
270
 
271
+ val bottomGrew = bottom > scroller.paddingBottom
261
272
  scroller.clipToPadding = false
262
273
  scroller.setPadding(left, top, right, bottom)
274
+ if (bottomGrew) revealFocusedInput()
275
+ }
276
+
277
+ /** When the keyboard pads the bottom, scrolls up just enough for the focused input to sit above it. */
278
+ private fun revealFocusedInput() {
279
+ val focusedView = scroller.findFocus() ?: return
280
+ val inputRect = Rect()
281
+ focusedView.getDrawingRect(inputRect)
282
+ scroller.offsetDescendantRectToMyCoords(focusedView, inputRect)
283
+
284
+ val visibleBottom = scroller.scrollY + scroller.height - scroller.paddingBottom
285
+ if (inputRect.bottom > visibleBottom) scroller.scrollBy(0, inputRect.bottom - visibleBottom)
263
286
  }
264
287
 
265
288
  fun setContentSize(width: Int, height: Int) {
@@ -318,7 +341,7 @@ private class RefreshIndicator(context: Context) : FrameLayout(context) {
318
341
  init {
319
342
  background = android.graphics.drawable.GradientDrawable().apply {
320
343
  shape = android.graphics.drawable.GradientDrawable.OVAL
321
- setColor(0xFFFFFFFF.toInt())
344
+ setColor(ThemeColors.surface)
322
345
  }
323
346
  elevation = dp(6f).toFloat()
324
347
  val spinnerSize = dp(24f)
@@ -457,10 +480,24 @@ class RemoteImageView(context: Context) : ImageView(context) {
457
480
  }
458
481
 
459
482
  /** Single-line text field behind <TextInput>. Mirrors ios/TextInputView.swift. */
460
- class TextInputView(context: Context) : android.widget.EditText(context) {
483
+ class TextInputView(context: Context) : android.widget.EditText(context), ThemeAware {
484
+ /** Without a `color` style, the text follows the theme. */
485
+ var styleColor: Int? = null
486
+ set(value) {
487
+ field = value
488
+ applyThemeColors()
489
+ }
490
+
461
491
  // ponytail: a value JS sets on purpose that equals text typed earlier in the same editing session is
462
492
  // ignored too; tag each change with a counter if that ever matters.
463
493
  private val textsSentToJavaScript = mutableSetOf<String>()
494
+ var isSettingTextFromJavaScript = false
495
+ private set
496
+
497
+ override fun applyThemeColors() {
498
+ setTextColor(styleColor ?: ThemeColors.text)
499
+ setHintTextColor(ThemeColors.placeholder)
500
+ }
464
501
 
465
502
  fun recordTextSentToJavaScript() {
466
503
  textsSentToJavaScript.add(text.toString())
@@ -478,7 +515,21 @@ class TextInputView(context: Context) : android.widget.EditText(context) {
478
515
  fun setTextFromJavaScript(newText: String) {
479
516
  if (newText == text.toString() || newText in textsSentToJavaScript) return
480
517
 
518
+ isSettingTextFromJavaScript = true
481
519
  setText(newText)
482
520
  setSelection(newText.length)
521
+ isSettingTextFromJavaScript = false
522
+ }
523
+ }
524
+
525
+ /** A Switch that tells JS's own changes (v-model) apart from the user's. */
526
+ class ToggleSwitch(context: Context) : Switch(context) {
527
+ var isSettingFromJavaScript = false
528
+ private set
529
+
530
+ fun setCheckedFromJavaScript(checked: Boolean) {
531
+ isSettingFromJavaScript = true
532
+ isChecked = checked
533
+ isSettingFromJavaScript = false
483
534
  }
484
535
  }
@@ -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
package/cli/config.mjs ADDED
@@ -0,0 +1,4 @@
1
+ // `import { defineConfig } from '@nativue/core/config'` in nativue.config.ts: only types the config.
2
+ export function defineConfig(config) {
3
+ return config
4
+ }
package/cli/link.mjs ADDED
@@ -0,0 +1,129 @@
1
+ // Links the iOS side of the app's packages: those whose package.json has
2
+ // "nativue": { "ios": { "sources": "ios", "plugin": "HapticsPlugin" } }
3
+ // ios/NativuePlugins becomes a Swift package with a target per package (a link to its sources) and
4
+ // `nativuePlugins`, the list App.swift passes to NativueView. The app's Xcode project depends on it
5
+ // alone; it re-exports Nativue. (Android finds them itself: android/nativue.settings.gradle.kts.)
6
+ import {
7
+ existsSync,
8
+ mkdirSync,
9
+ readdirSync,
10
+ readFileSync,
11
+ readlinkSync,
12
+ rmSync,
13
+ symlinkSync,
14
+ writeFileSync,
15
+ } from 'node:fs'
16
+ import { dirname, join, relative, resolve } from 'node:path'
17
+
18
+ const PLUGINS_DIRECTORY = 'ios/NativuePlugins'
19
+ const SOURCES_DIRECTORY = `${PLUGINS_DIRECTORY}/Sources`
20
+ const LIST_TARGET = 'NativuePlugins'
21
+
22
+ function readJson(path) {
23
+ return JSON.parse(readFileSync(path, 'utf8'))
24
+ }
25
+
26
+ /** node_modules/<name>, looked up the way Node does: in the app's folder, then in its parents. */
27
+ function packageDirectory(name) {
28
+ for (let directory = process.cwd(); ; directory = dirname(directory)) {
29
+ const candidate = join(directory, 'node_modules', name)
30
+ if (existsSync(join(candidate, 'package.json'))) return candidate
31
+ if (directory === dirname(directory)) return null
32
+ }
33
+ }
34
+
35
+ /** '@nativue/haptics' -> 'NativueHaptics', the Swift module of its sources. */
36
+ function moduleName(packageName) {
37
+ return packageName
38
+ .split(/[^a-zA-Z0-9]+/)
39
+ .filter(Boolean)
40
+ .map((word) => word[0].toUpperCase() + word.slice(1))
41
+ .join('')
42
+ }
43
+
44
+ function iosPlugins() {
45
+ const { dependencies = {}, devDependencies = {} } = readJson('package.json')
46
+ const names = [...Object.keys(dependencies), ...Object.keys(devDependencies)]
47
+
48
+ return names.flatMap((name) => {
49
+ const directory = packageDirectory(name)
50
+ const ios = directory && readJson(join(directory, 'package.json')).nativue?.ios
51
+ if (!ios) return []
52
+
53
+ return [{ module: moduleName(name), sources: join(directory, ios.sources), plugin: ios.plugin }]
54
+ })
55
+ }
56
+
57
+ function writeIfChanged(path, content) {
58
+ if (existsSync(path) && readFileSync(path, 'utf8') === content) return
59
+
60
+ mkdirSync(dirname(path), { recursive: true })
61
+ writeFileSync(path, content)
62
+ }
63
+
64
+ /** Sources/<module> -> the package's sources; links of packages the app no longer has are removed. */
65
+ function linkSources(plugins) {
66
+ const linkTargets = new Map(
67
+ plugins.map((plugin) => [plugin.module, relative(SOURCES_DIRECTORY, plugin.sources)]),
68
+ )
69
+ mkdirSync(SOURCES_DIRECTORY, { recursive: true })
70
+
71
+ for (const entry of readdirSync(SOURCES_DIRECTORY)) {
72
+ if (entry !== LIST_TARGET && !linkTargets.has(entry)) rmSync(join(SOURCES_DIRECTORY, entry))
73
+ }
74
+
75
+ for (const [module, target] of linkTargets) {
76
+ const link = join(SOURCES_DIRECTORY, module)
77
+ if (existsSync(link) && readlinkSync(link) === target) continue
78
+
79
+ rmSync(link, { force: true })
80
+ symlinkSync(target, link)
81
+ }
82
+ }
83
+
84
+ function packageManifest(plugins, corePath) {
85
+ const nativue = '.product(name: "Nativue", package: "core")'
86
+ const pluginTargets = plugins.map(
87
+ ({ module }) =>
88
+ ` .target(name: "${module}", dependencies: [${nativue}], path: "Sources/${module}"),\n`,
89
+ )
90
+ const listDependencies = [nativue, ...plugins.map(({ module }) => `"${module}"`)].join(', ')
91
+
92
+ return `// swift-tools-version: 5.9
93
+ // Generated by nativue from the app's packages (packages/core/cli/link.mjs): rewritten on every build.
94
+ import PackageDescription
95
+
96
+ let package = Package(
97
+ name: "NativuePlugins",
98
+ platforms: [.iOS(.v17)],
99
+ products: [.library(name: "NativuePlugins", targets: ["${LIST_TARGET}"])],
100
+ dependencies: [.package(path: "${corePath}")],
101
+ targets: [
102
+ ${pluginTargets.join('')} .target(name: "${LIST_TARGET}", dependencies: [${listDependencies}], path: "Sources/${LIST_TARGET}"),
103
+ ]
104
+ )
105
+ `
106
+ }
107
+
108
+ function pluginList(plugins) {
109
+ const imports = plugins.map(({ module }) => `import ${module}\n`).join('')
110
+ const instances = plugins.map(({ plugin }) => `${plugin}()`).join(', ')
111
+
112
+ return `// Generated by nativue from the app's packages (packages/core/cli/link.mjs): rewritten on every build.
113
+ @_exported import Nativue
114
+ ${imports}
115
+ public let nativuePlugins: [NativuePlugin] = [${instances}]
116
+ `
117
+ }
118
+
119
+ /** coreDirectory: @nativue/core's folder, which holds its Package.swift. */
120
+ export function linkIosPlugins(coreDirectory) {
121
+ if (!existsSync('ios') || !existsSync('package.json')) return
122
+
123
+ const plugins = iosPlugins()
124
+ const corePath = relative(resolve(PLUGINS_DIRECTORY), coreDirectory)
125
+
126
+ linkSources(plugins)
127
+ writeIfChanged(`${PLUGINS_DIRECTORY}/Package.swift`, packageManifest(plugins, corePath))
128
+ writeIfChanged(`${SOURCES_DIRECTORY}/${LIST_TARGET}/Plugins.swift`, pluginList(plugins))
129
+ }