@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.
package/cli/nativue.mjs CHANGED
@@ -6,7 +6,7 @@
6
6
  // nativue dev rebuilds on save and tells the app (via SSE) to reload the bundle
7
7
  // nativue run <ios | android> builds, installs and opens the app on a simulator or emulator, then
8
8
  // keeps going as `nativue dev` (unless one is already running)
9
- import { build } from 'vite'
9
+ import { build, loadConfigFromFile } from 'vite'
10
10
  import vue from '@vitejs/plugin-vue'
11
11
  import http from 'node:http'
12
12
  import net from 'node:net'
@@ -15,10 +15,12 @@ import { copyFileSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync }
15
15
  import { createRequire } from 'node:module'
16
16
  import { dirname } from 'node:path'
17
17
  import { fileURLToPath } from 'node:url'
18
+ import { linkIosPlugins } from './link.mjs'
18
19
  import { runOnAndroid, runOnIOS } from './run.mjs'
19
20
  import { createSymbolicator } from './symbolicate.mjs'
20
21
 
21
22
  const PORT = 40836 // 0x9F84, from #0E9F84, the nativue green
23
+ const MAX_STACK_LENGTH = 1_000_000 // characters, of a stack the app posts to /symbolicate
22
24
  const BUNDLE_DIRECTORY = 'ios/App'
23
25
  const BUNDLE_PATH = `${BUNDLE_DIRECTORY}/main.bundle.js`
24
26
  const SOURCE_MAP_PATH = `${BUNDLE_PATH}.map`
@@ -84,6 +86,49 @@ function finishBundle(mode) {
84
86
  }
85
87
  }
86
88
 
89
+ const CONFIG_FILES = [
90
+ 'nativue.config.ts',
91
+ 'nativue.config.mts',
92
+ 'nativue.config.js',
93
+ 'nativue.config.mjs',
94
+ ]
95
+ const PLUGIN_RUNTIMES_MODULE = 'virtual:nativue/plugin-runtimes'
96
+
97
+ // nativue.config.ts, when the app has one (see config.d.mts).
98
+ async function loadAppConfig() {
99
+ const configFile = CONFIG_FILES.find((file) => existsSync(file))
100
+ if (!configFile) return {}
101
+
102
+ const { config } = await loadConfigFromFile(
103
+ { command: 'build', mode: 'development' },
104
+ configFile,
105
+ process.cwd(),
106
+ 'silent',
107
+ )
108
+
109
+ return config
110
+ }
111
+
112
+ // The entry imports this module first: it imports each plugin's runtime module.
113
+ function pluginRuntimes(plugins) {
114
+ const resolvedId = `\0${PLUGIN_RUNTIMES_MODULE}`
115
+ const imports = plugins
116
+ .filter((plugin) => plugin.runtime)
117
+ .map((plugin) => `import ${JSON.stringify(plugin.runtime)}`)
118
+
119
+ return {
120
+ name: 'nativue-plugin-runtimes',
121
+ resolveId: (id) => (id === PLUGIN_RUNTIMES_MODULE ? resolvedId : null),
122
+ load: (id) => (id === resolvedId ? imports.join('\n') : null),
123
+ }
124
+ }
125
+
126
+ const { plugins: appPlugins = [] } = await loadAppConfig()
127
+ const APP_VITE_PLUGINS = [
128
+ pluginRuntimes(appPlugins),
129
+ ...appPlugins.flatMap((plugin) => plugin.vite ?? []),
130
+ ]
131
+
87
132
  function viteConfig({ mode, plugins = [], watch = null, sourcemap = false }) {
88
133
  // Vite reads the mode from NODE_ENV: development builds keep each component's file (for errors).
89
134
  process.env.NODE_ENV = mode
@@ -98,6 +143,7 @@ function viteConfig({ mode, plugins = [], watch = null, sourcemap = false }) {
98
143
  compilerOptions: { isCustomElement: (tag) => NATIVE_COMPONENT_TAGS.includes(tag) },
99
144
  },
100
145
  }),
146
+ ...APP_VITE_PLUGINS,
101
147
  finishBundle(mode),
102
148
  ...plugins,
103
149
  ],
@@ -139,17 +185,31 @@ function startDevServer() {
139
185
  }
140
186
 
141
187
  function handleBundle(response) {
188
+ // An installed app can ask before Vite's first build has written it.
189
+ if (!existsSync(BUNDLE_PATH)) {
190
+ response.writeHead(503, { 'Content-Type': 'text/plain' })
191
+ response.end('The bundle is still building')
192
+ return
193
+ }
194
+
142
195
  response.writeHead(200, { 'Content-Type': 'application/javascript' })
143
196
  response.end(readFileSync(BUNDLE_PATH))
144
197
  }
145
198
 
146
199
  // The app posts an error's stack; it gets it back pointing at the app's files.
147
200
  async function handleSymbolicate(request, response) {
148
- let text = ''
149
- for await (const chunk of request) text += chunk
201
+ try {
202
+ let text = ''
203
+ for await (const chunk of request) {
204
+ text += chunk
205
+ if (text.length > MAX_STACK_LENGTH) throw new Error('stack too long')
206
+ }
150
207
 
151
- response.writeHead(200, { 'Content-Type': 'text/plain' })
152
- response.end(symbolicate(text))
208
+ response.writeHead(200, { 'Content-Type': 'text/plain' })
209
+ response.end(symbolicate(text))
210
+ } catch {
211
+ response.writeHead(400).end() // an aborted or oversized post: never take the server down
212
+ }
153
213
  }
154
214
 
155
215
  http
@@ -213,6 +273,8 @@ async function runApp(platform) {
213
273
  const [command, ...args] = process.argv.slice(2)
214
274
 
215
275
  try {
276
+ if (['dev', 'build', 'run'].includes(command)) linkIosPlugins(frameworkPath(''))
277
+
216
278
  if (command === 'dev') {
217
279
  await dev()
218
280
  } else if (command === 'build') {
package/ios/Bridge.swift CHANGED
@@ -5,11 +5,11 @@ import yoga
5
5
  /// Runs the JS bundle off the main thread and applies the operations sent by the Vue renderer
6
6
  /// (src/renderer.js) to UIKit + Yoga in batches on the main thread.
7
7
  final class Bridge {
8
- /// The simulator shares the Mac's network; a device uses the Mac's name, written into the app at build
9
- /// time by the "Write Dev Server Host" build phase.
10
8
  /// Posted by the app with a URL it was opened with (deep link); forwarded to JS (`__openURL`).
11
9
  static let openURLNotification = Notification.Name("NativueOpenURL")
12
10
 
11
+ /// The simulator shares the Mac's network; a device uses the Mac's name, written into the app at build
12
+ /// time by the "Write Dev Server Host" build phase.
13
13
  static let devServerURL: URL = {
14
14
  #if targetEnvironment(simulator)
15
15
  let host = "localhost"
@@ -29,29 +29,46 @@ final class Bridge {
29
29
  // Only touched on javaScriptQueue.
30
30
  private var runtime: JavaScriptRuntime?
31
31
  private var pendingOperations: [() -> Void] = []
32
- private var gestureReportersByNodeId: [Int: GestureReporter] = [:]
33
- private let animatedGraph = AnimatedGraph()
34
32
  private lazy var storage = KeyValueStorage(javaScriptQueue: javaScriptQueue)
35
33
  /// Set by LayoutAnimation.configureNext in JS; animates the batch it's sent with.
36
34
  private var nextLayoutAnimation: LayoutAnimation?
35
+ /// Appearance.getColorScheme(): read on the main thread at start, then kept up to date.
36
+ private var colorScheme = "light"
37
37
 
38
38
  // Only touched on the main thread.
39
39
  var rootView: RootView!
40
+ private var gestureReportersByNodeId: [Int: GestureReporter] = [:]
41
+ private let animatedGraph = AnimatedGraph()
40
42
  // ponytail: children of a removed node stay in the dictionary; clean up recursively if memory leaks.
41
43
  var nodesById: [Int: NativeNode] = [:]
42
44
  /// Modals and screens: their content is laid out as a separate Yoga root.
43
- // ponytail: controllers of removed modals stay here; drop them on remove if many modals come and go.
45
+ // ponytail: Vue removes only a subtree's root, so the modals and screens inside a removed subtree stay
46
+ // here and are laid out on every pass; drop the detached ones on remove if navigators come and go.
44
47
  private var contentRootsByNodeId: [Int: ContentRoot] = [:]
45
48
  /// Read on the main thread at start, for Dimensions.get('window').
46
49
  private var windowSize: CGSize = .zero
47
50
  /// The bundle running now, for the error overlay's Reload.
48
51
  private var bundle = Data()
49
52
  private let errorOverlay = ErrorOverlay()
53
+ private let pluginRegistry: PluginRegistry
54
+
55
+ init(plugins: [NativuePlugin]) {
56
+ pluginRegistry = PluginRegistry(plugins: plugins)
57
+ }
50
58
 
51
59
  func start(rootView: RootView) {
52
60
  self.rootView = rootView
53
61
  rootView.onLayoutSubviews = { [unowned self] in layout() }
54
- windowSize = (UIApplication.shared.connectedScenes.first as? UIWindowScene)?.screen.bounds.size ?? .zero
62
+ let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene
63
+ windowSize = windowScene?.screen.bounds.size ?? .zero
64
+ colorScheme = Self.colorScheme(of: windowScene?.traitCollection ?? rootView.traitCollection)
65
+ // start runs on the main thread, from makeUIView.
66
+ MainActor.assumeIsolated {
67
+ _ = rootView.registerForTraitChanges([UITraitUserInterfaceStyle.self]) {
68
+ [unowned self] (rootView: RootView, _: UITraitCollection) in
69
+ colorSchemeDidChange(to: Self.colorScheme(of: rootView.traitCollection))
70
+ }
71
+ }
55
72
 
56
73
  NotificationCenter.default.addObserver(forName: Self.openURLNotification, object: nil, queue: .main) {
57
74
  [unowned self] notification in
@@ -120,6 +137,29 @@ final class Bridge {
120
137
  }
121
138
  }
122
139
 
140
+ /// Results reaching a runtime that has since been reloaded are dropped: call ids start over in the new one.
141
+ private func finishAsyncFunction(_ callId: Int, owner: JavaScriptRuntime?, value: Any?, errorMessage: String?) {
142
+ evaluate { [unowned self] in
143
+ guard runtime === owner else { return }
144
+
145
+ let arguments: [Any] = [callId, value ?? NSNull(), errorMessage ?? NSNull()]
146
+ runtime?.call("__asyncFunctionFinished", arguments: arguments)
147
+ }
148
+ }
149
+
150
+ private static func colorScheme(of traits: UITraitCollection) -> String {
151
+ traits.userInterfaceStyle == .dark ? "dark" : "light"
152
+ }
153
+
154
+ private func colorSchemeDidChange(to nextColorScheme: String) {
155
+ evaluate { [unowned self] in
156
+ guard nextColorScheme != colorScheme else { return }
157
+
158
+ colorScheme = nextColorScheme
159
+ runtime?.call("__colorSchemeChanged", arguments: [nextColorScheme])
160
+ }
161
+ }
162
+
123
163
  /// Queued on the JS queue, so a URL that opens the app arrives after the bundle has run.
124
164
  private func openURL(_ url: URL) {
125
165
  evaluate { [unowned self] in
@@ -188,6 +228,32 @@ final class Bridge {
188
228
  ["width": windowSize.width, "height": windowSize.height]
189
229
  }
190
230
 
231
+ defineGetter("platform") { _ in "ios" }
232
+
233
+ // Prefixed, so a plugin can't replace nativue's own functions.
234
+ for (name, function) in pluginRegistry.functions {
235
+ defineGetter("plugin:\(name)", function)
236
+ }
237
+
238
+ // (callId, ...arguments): settles the call with __asyncFunctionFinished.
239
+ for (name, function) in pluginRegistry.asyncFunctions {
240
+ define("pluginAsync:\(name)") { [unowned self] arguments in
241
+ let callId = int(arguments[0])
242
+ let owner = runtime
243
+
244
+ Task {
245
+ do {
246
+ let value = try await function(Array(arguments.dropFirst()))
247
+ finishAsyncFunction(callId, owner: owner, value: value, errorMessage: nil)
248
+ } catch {
249
+ finishAsyncFunction(callId, owner: owner, value: nil, errorMessage: error.localizedDescription)
250
+ }
251
+ }
252
+ }
253
+ }
254
+
255
+ defineGetter("colorScheme") { [unowned self] _ in colorScheme }
256
+
191
257
  define("create") { [unowned self] arguments in
192
258
  let (id, type) = (int(arguments[0]), string(arguments[1]))
193
259
  enqueue { [unowned self] in nodesById[id] = makeNode(type: type, id: id) }
@@ -278,6 +344,8 @@ final class Bridge {
278
344
  // MARK: - Main thread
279
345
 
280
346
  private func resetNodeTree() {
347
+ // Sheets of the old tree's screen stacks too, which only their stack knows about.
348
+ rootView.window?.rootViewController?.dismiss(animated: false)
281
349
  rootView.subviews.forEach { $0.removeFromSuperview() }
282
350
  contentRootsByNodeId.values.forEach { ($0 as? ModalController)?.setVisible(false) }
283
351
  contentRootsByNodeId = [:]
@@ -360,7 +428,10 @@ final class Bridge {
360
428
  case "KeyboardAvoidingView":
361
429
  let keyboardAvoidingView = KeyboardAvoidingView()
362
430
  let node = NativeNode(view: keyboardAvoidingView, measuresContent: false)
363
- keyboardAvoidingView.onKeyboardOverlapChange = { [unowned self, unowned node] overlap in
431
+ // weak: a reload frees the node while a dismissing modal still shows its view.
432
+ keyboardAvoidingView.onKeyboardOverlapChange = { [unowned self, weak node] overlap in
433
+ guard let node else { return }
434
+
364
435
  YGNodeStyleSetPadding(node.yogaNode, .bottom, Float(overlap))
365
436
  rootView.setNeedsLayout()
366
437
  rootView.layoutIfNeeded() // runs inside the keyboard animation, so frames animate with it
@@ -370,8 +441,8 @@ final class Bridge {
370
441
  case "SafeAreaView":
371
442
  let safeAreaView = SafeAreaView()
372
443
  let node = NativeNode(view: safeAreaView, measuresContent: false)
373
- safeAreaView.onSafeAreaInsetsChange = { [unowned self, unowned node] in
374
- if node.applySafeAreaPadding() { requestLayout() }
444
+ safeAreaView.onSafeAreaInsetsChange = { [unowned self, weak node] in
445
+ if node?.applySafeAreaPadding() == true { requestLayout() }
375
446
  }
376
447
  return node
377
448
 
@@ -420,7 +491,14 @@ final class Bridge {
420
491
  return node
421
492
 
422
493
  default:
423
- return NativeNode(view: UIView(), measuresContent: false)
494
+ guard let makeView = pluginRegistry.viewMakers[type] else {
495
+ return NativeNode(view: UIView(), measuresContent: false)
496
+ }
497
+
498
+ let view = makeView { [unowned self] eventName, payload in
499
+ dispatchEvent(eventName, toNodeId: id, payload: payload)
500
+ }
501
+ return NativeNode(view: view, measuresContent: false)
424
502
  }
425
503
  }
426
504
 
@@ -438,8 +516,13 @@ final class Bridge {
438
516
  dispatchEvent("submitediting", toNodeId: id, payload: textInput.text ?? "")
439
517
  }, for: .editingDidEndOnExit)
440
518
 
441
- textInput.addAction(UIAction { [unowned textInput] _ in
519
+ textInput.addAction(UIAction { [unowned self] _ in
520
+ dispatchEvent("focus", toNodeId: id, payload: nil)
521
+ }, for: .editingDidBegin)
522
+
523
+ textInput.addAction(UIAction { [unowned self, unowned textInput] _ in
442
524
  textInput.endEditingSession()
525
+ dispatchEvent("blur", toNodeId: id, payload: nil)
443
526
  }, for: .editingDidEnd)
444
527
 
445
528
  return textInput
@@ -475,9 +558,10 @@ final class Bridge {
475
558
  let (requestId, url, method) = (int(arguments[0]), string(arguments[1]), string(arguments[2]))
476
559
  let headers = arguments[3] as? [String: String] ?? [:]
477
560
  let bodyText = arguments[4] as? String
561
+ let owner = runtime
478
562
 
479
563
  guard let url = URL(string: url) else {
480
- return finishFetch(requestId, response: nil, error: "invalid URL \(url)")
564
+ return finishFetch(requestId, owner: owner, response: nil, error: "invalid URL \(url)")
481
565
  }
482
566
 
483
567
  var request = URLRequest(url: url)
@@ -487,10 +571,12 @@ final class Bridge {
487
571
 
488
572
  URLSession.shared.dataTask(with: request) { [unowned self] data, response, error in
489
573
  guard let response = response as? HTTPURLResponse, error == nil else {
490
- return finishFetch(requestId, response: nil, error: error?.localizedDescription ?? "no response")
574
+ return finishFetch(
575
+ requestId, owner: owner, response: nil, error: error?.localizedDescription ?? "no response"
576
+ )
491
577
  }
492
578
 
493
- finishFetch(requestId, response: [
579
+ finishFetch(requestId, owner: owner, response: [
494
580
  "status": response.statusCode,
495
581
  "headers": response.allHeaderFields,
496
582
  "body": String(decoding: data ?? Data(), as: UTF8.self),
@@ -499,8 +585,10 @@ final class Bridge {
499
585
  }
500
586
  }
501
587
 
502
- private func finishFetch(_ requestId: Int, response: [String: Any]?, error: String?) {
588
+ /// Like finishAsyncFunction, dropped if the runtime that asked has since been reloaded.
589
+ private func finishFetch(_ requestId: Int, owner: JavaScriptRuntime?, response: [String: Any]?, error: String?) {
503
590
  evaluate { [unowned self] in
591
+ guard runtime === owner else { return }
504
592
  let arguments: [Any] = [requestId, response ?? NSNull(), error ?? NSNull()]
505
593
  runtime?.call("__fetchFinished", arguments: arguments)
506
594
  }
@@ -590,6 +678,11 @@ final class Bridge {
590
678
  private func setProp(_ key: String, value: Any?, onNodeId id: Int) {
591
679
  guard let node = nodesById[id] else { return }
592
680
 
681
+ if key != "style", let pluginView = node.view as? PluginView {
682
+ pluginView.setProp(key, value: value is NSNull ? nil : value)
683
+ return
684
+ }
685
+
593
686
  switch key {
594
687
  case "title":
595
688
  (node.view as? UIButton)?.setTitle(value as? String, for: .normal)
@@ -652,6 +745,9 @@ final class Bridge {
652
745
  case "showsVerticalScrollIndicator":
653
746
  (node.view as? UIScrollView)?.showsVerticalScrollIndicator = isTruthyAttribute(value)
654
747
 
748
+ case "automaticallyAdjustKeyboardInsets":
749
+ (node.view as? VueScrollView)?.adjustsForKeyboard = isTruthyAttribute(value)
750
+
655
751
  case "value":
656
752
  (node.view as? TextInputView)?.setTextFromJavaScript(value as? String ?? "")
657
753
  (node.view as? UISwitch)?.setOn(isTruthyAttribute(value), animated: true)
@@ -30,12 +30,19 @@ final class KeyboardAvoidingView: UIView {
30
30
  let keyboardTopInView = convert(keyboardFrame, from: nil).minY
31
31
  let overlap = max(0, bounds.maxY - keyboardTopInView)
32
32
 
33
- let duration = (userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double) ?? 0.25
34
- let curve = (userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as? UInt) ?? 7
35
- let options = UIView.AnimationOptions(rawValue: curve << 16)
36
-
37
- UIView.animate(withDuration: duration, delay: 0, options: options) { [weak self] in
33
+ UIView.animateAlongsideKeyboard(notification) { [weak self] in
38
34
  self?.onKeyboardOverlapChange?(overlap)
39
35
  }
40
36
  }
41
37
  }
38
+
39
+ extension UIView {
40
+ /// Runs `animations` with the keyboard's own duration and curve, so the change moves in sync with it.
41
+ static func animateAlongsideKeyboard(_ notification: Notification, animations: @escaping () -> Void) {
42
+ let userInfo = notification.userInfo
43
+ let duration = (userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double) ?? 0.25
44
+ let curve = (userInfo?[UIResponder.keyboardAnimationCurveUserInfoKey] as? UInt) ?? 7
45
+
46
+ animate(withDuration: duration, delay: 0, options: UIView.AnimationOptions(rawValue: curve << 16), animations: animations)
47
+ }
48
+ }
@@ -19,6 +19,9 @@ final class ModalController: UIViewController, ContentRoot, UIAdaptivePresentati
19
19
  var transparent = false
20
20
 
21
21
  private var isPresented: Bool { presentingViewController != nil }
22
+ /// What JS last asked for; applied again when a running transition ends, which UIKit would ignore.
23
+ private var wantsVisible = false
24
+ private var isTransitioning = false
22
25
 
23
26
  override func loadView() {
24
27
  view = contentNode.view
@@ -38,14 +41,22 @@ final class ModalController: UIViewController, ContentRoot, UIAdaptivePresentati
38
41
 
39
42
  /// Deferred to after the current batch, so the placeholder is already in the window when presenting.
40
43
  func setVisible(_ visible: Bool) {
41
- DispatchQueue.main.async { [self] in
42
- if visible { present() } else { dismissIfPresented() }
43
- }
44
+ wantsVisible = visible
45
+ DispatchQueue.main.async { [self] in applyVisibility() }
44
46
  }
45
47
 
46
48
  /// The <Modal> left the tree (an ancestor's v-if): its content must go too.
47
49
  func dismissIfDetached() {
48
- if placeholderView.window == nil { dismissIfPresented() }
50
+ guard placeholderView.window == nil else { return }
51
+
52
+ wantsVisible = false
53
+ applyVisibility()
54
+ }
55
+
56
+ private func applyVisibility() {
57
+ guard !isTransitioning else { return }
58
+
59
+ if wantsVisible { present() } else { dismissIfPresented() }
49
60
  }
50
61
 
51
62
  private func present() {
@@ -57,14 +68,24 @@ final class ModalController: UIViewController, ContentRoot, UIAdaptivePresentati
57
68
  : Self.presentationStyles[presentationStyleName] ?? .fullScreen
58
69
  modalTransitionStyle = animationType == "fade" ? .crossDissolve : .coverVertical
59
70
 
60
- presenter.present(self, animated: animationType != "none") { [self] in onEvent?("show") }
71
+ isTransitioning = true
72
+ presenter.present(self, animated: animationType != "none") { [self] in
73
+ isTransitioning = false
74
+ onEvent?("show")
75
+ applyVisibility()
76
+ }
61
77
  presentationController?.delegate = self
62
78
  }
63
79
 
64
80
  private func dismissIfPresented() {
65
81
  guard isPresented else { return }
66
82
 
67
- dismiss(animated: animationType != "none") { [self] in onEvent?("dismiss") }
83
+ isTransitioning = true
84
+ dismiss(animated: animationType != "none") { [self] in
85
+ isTransitioning = false
86
+ onEvent?("dismiss")
87
+ applyVisibility()
88
+ }
68
89
  }
69
90
 
70
91
  private func topViewController() -> UIViewController? {
@@ -119,6 +119,7 @@ final class NativeNode {
119
119
  childView.bounds.size = frame.size
120
120
  childView.center = CGPoint(x: frame.midX, y: frame.midY)
121
121
  }
122
+ childView.applyCornerRadius()
122
123
 
123
124
  applyFrames(of: child)
124
125
 
@@ -3,18 +3,25 @@ import SwiftUI
3
3
  /// The whole app: runs main.bundle.js (or the dev server's bundle) and shows what it renders.
4
4
  /// It fills the whole screen; <SafeAreaView> opts into the safe area.
5
5
  public struct NativueView: View {
6
- public init() {}
6
+ private let plugins: [NativuePlugin]
7
+
8
+ /// plugins: the native side of the app's packages, `nativuePlugins` from ios/NativuePlugins.
9
+ public init(plugins: [NativuePlugin] = []) {
10
+ self.plugins = plugins
11
+ }
7
12
 
8
13
  public var body: some View {
9
- VueRoot()
14
+ VueRoot(plugins: plugins)
10
15
  .ignoresSafeArea()
11
16
  .onOpenURL { url in NotificationCenter.default.post(name: Bridge.openURLNotification, object: url) }
12
17
  }
13
18
  }
14
19
 
15
20
  struct VueRoot: UIViewRepresentable {
21
+ let plugins: [NativuePlugin]
22
+
16
23
  func makeCoordinator() -> Bridge {
17
- Bridge()
24
+ Bridge(plugins: plugins)
18
25
  }
19
26
 
20
27
  func makeUIView(context: Context) -> RootView {
@@ -0,0 +1,46 @@
1
+ import UIKit
2
+
3
+ /// The native side of a package: functions JavaScript calls (`requireNativeFunction`) and views it
4
+ /// renders. Packages declare their plugin in package.json; the CLI links them into the app
5
+ /// (ios/NativuePlugins) and the app passes them on: `NativueView(plugins: nativuePlugins)`.
6
+ public protocol NativuePlugin {
7
+ func register(in registry: PluginRegistry)
8
+ }
9
+
10
+ public final class PluginRegistry {
11
+ public typealias Function = (_ arguments: [Any]) -> Any?
12
+ /// Its result resolves the JavaScript call's Promise; a thrown error rejects it.
13
+ public typealias AsyncFunction = (_ arguments: [Any]) async throws -> Any?
14
+ /// sendEvent("change", payload) reaches the element's @change; event names are lowercase.
15
+ public typealias SendEvent = (_ eventName: String, _ payload: Any?) -> Void
16
+ public typealias MakeView = (_ sendEvent: @escaping SendEvent) -> UIView
17
+
18
+ private(set) var functions: [String: Function] = [:]
19
+ private(set) var asyncFunctions: [String: AsyncFunction] = [:]
20
+ private(set) var viewMakers: [String: MakeView] = [:]
21
+
22
+ init(plugins: [NativuePlugin]) {
23
+ plugins.forEach { $0.register(in: self) }
24
+ }
25
+
26
+ /// Runs on the JavaScript thread and returns synchronously: hop to the main thread for UIKit.
27
+ public func addFunction(_ name: String, _ function: @escaping Function) {
28
+ functions[name] = function
29
+ }
30
+
31
+ /// For work that takes time (a permission prompt, the camera): JavaScript gets a Promise. Runs off the
32
+ /// main thread: use `await MainActor.run { ... }` for UIKit.
33
+ public func addAsyncFunction(_ name: String, _ function: @escaping AsyncFunction) {
34
+ asyncFunctions[name] = function
35
+ }
36
+
37
+ /// `type` is the element's tag, e.g. "MapView" for h('MapView'). Created on the main thread.
38
+ public func addView(_ type: String, _ makeView: @escaping MakeView) {
39
+ viewMakers[type] = makeView
40
+ }
41
+ }
42
+
43
+ /// A plugin view gets its props here, all but `style`, which nativue applies (layout included).
44
+ public protocol PluginView: UIView {
45
+ func setProp(_ key: String, value: Any?)
46
+ }
@@ -55,7 +55,7 @@ final class PressableView: UIControl {
55
55
  }
56
56
 
57
57
  @objc private func handleLongPress(_ recognizer: UILongPressGestureRecognizer) {
58
- guard recognizer.state == .began else { return }
58
+ guard recognizer.state == .began, isEnabled else { return }
59
59
 
60
60
  didLongPress = true
61
61
  onEvent?("longpress")
package/ios/Style.swift CHANGED
@@ -35,7 +35,8 @@ extension NativeNode {
35
35
  view.backgroundColor = UIColor(rgba: value)
36
36
 
37
37
  case "borderRadius":
38
- view.layer.cornerRadius = CGFloat(number(value) ?? 0)
38
+ view.layer.setValue(CGFloat(number(value) ?? 0), forKey: UIView.requestedCornerRadiusKey)
39
+ view.applyCornerRadius()
39
40
 
40
41
  case "borderWidth":
41
42
  view.layer.borderWidth = CGFloat(number(value) ?? 0)
@@ -355,3 +356,15 @@ extension NativeNode {
355
356
  return text.hasSuffix("deg") ? number * .pi / 180 : number
356
357
  }
357
358
  }
359
+
360
+ extension UIView {
361
+ static let requestedCornerRadiusKey = "nativueCornerRadius"
362
+
363
+ /// A radius over half the view's side (rounded-full is 9999) makes Core Animation draw nothing:
364
+ /// capped to a circle's, and applied again as the frame changes.
365
+ func applyCornerRadius() {
366
+ guard let requestedRadius = layer.value(forKey: Self.requestedCornerRadiusKey) as? CGFloat else { return }
367
+
368
+ layer.cornerRadius = min(requestedRadius, min(bounds.width, bounds.height) / 2)
369
+ }
370
+ }
@@ -19,6 +19,10 @@ final class VueScrollView: UIScrollView {
19
19
  /// "always" / "handled" turn it off.
20
20
  var dismissesKeyboardOnTap = true
21
21
 
22
+ /// automatically-adjust-keyboard-insets: the keyboard insets the content, and the focused input scrolls
23
+ /// above it.
24
+ var adjustsForKeyboard = false
25
+
22
26
  /// Set when JS listens to @scroll. Called on every scroll step and size change (FlatList windowing).
23
27
  // ponytail: one JS call per frame while scrolling; coalesce / add scrollEventThrottle if JS falls behind.
24
28
  var onScroll: ((CGRect) -> Void)? {
@@ -47,10 +51,20 @@ final class VueScrollView: UIScrollView {
47
51
 
48
52
  contentInsetAdjustmentBehavior = .never // <SafeAreaView> handles it, or the prop
49
53
  alwaysBounceVertical = true
54
+ // UIKit holds a touch for 150ms to see if it scrolls: a quick tap on a device would send pressin and
55
+ // pressout together, and the pressed style never shows. touchesShouldCancel still lets drags scroll.
56
+ delaysContentTouches = false
50
57
 
51
58
  let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:)))
52
59
  tapRecognizer.cancelsTouchesInView = false // buttons inside still receive their taps
53
60
  addGestureRecognizer(tapRecognizer)
61
+
62
+ NotificationCenter.default.addObserver(
63
+ self,
64
+ selector: #selector(keyboardWillChangeFrame(_:)),
65
+ name: UIResponder.keyboardWillChangeFrameNotification,
66
+ object: nil
67
+ )
54
68
  }
55
69
 
56
70
  required init?(coder: NSCoder) {
@@ -78,6 +92,41 @@ final class VueScrollView: UIScrollView {
78
92
  true
79
93
  }
80
94
 
95
+ @objc private func keyboardWillChangeFrame(_ notification: Notification) {
96
+ guard
97
+ adjustsForKeyboard,
98
+ window != nil,
99
+ let keyboardFrame = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
100
+ else { return }
101
+
102
+ // In content coordinates, like bounds. The safe area the system already insets isn't counted twice.
103
+ let keyboardTop = convert(keyboardFrame, from: nil).minY
104
+ let systemBottomInset = adjustedContentInset.bottom - contentInset.bottom
105
+ let keyboardInset = max(0, bounds.maxY - keyboardTop - systemBottomInset)
106
+
107
+ UIView.animateAlongsideKeyboard(notification) { [self] in
108
+ contentInset.bottom = keyboardInset
109
+ verticalScrollIndicatorInsets.bottom = keyboardInset
110
+ contentOffset.y = offsetRevealing(focusedInput(in: self), above: keyboardTop)
111
+ }
112
+ }
113
+
114
+ /// Scrolls up just enough for `input` to sit above the keyboard; when the keyboard leaves, back within the content.
115
+ private func offsetRevealing(_ input: UIView?, above keyboardTop: CGFloat) -> CGFloat {
116
+ let maximumOffset = max(-adjustedContentInset.top, contentSize.height + adjustedContentInset.bottom - bounds.height)
117
+ guard let input else { return min(contentOffset.y, maximumOffset) }
118
+
119
+ let inputBottom = input.convert(input.bounds, to: self).maxY
120
+
121
+ return min(contentOffset.y + max(0, inputBottom - keyboardTop), maximumOffset)
122
+ }
123
+
124
+ private func focusedInput(in view: UIView) -> UIView? {
125
+ if view.isFirstResponder { return view }
126
+
127
+ return view.subviews.lazy.compactMap(focusedInput(in:)).first
128
+ }
129
+
81
130
  @objc private func handleTap(_ recognizer: UITapGestureRecognizer) {
82
131
  guard dismissesKeyboardOnTap else { return }
83
132