@nativue/core 0.13.0 → 0.14.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +39 -7
- package/README.md +1 -0
- package/android/build.gradle.kts +4 -0
- package/android/nativue.settings.gradle.kts +2 -0
- package/android/src/main/java/dev/nativue/Bridge.kt +66 -7
- package/android/src/main/java/dev/nativue/NativueActivity.kt +12 -5
- package/android/src/main/java/dev/nativue/Permissions.kt +107 -0
- package/android/src/main/java/dev/nativue/Plugins.kt +98 -15
- package/cli/android-project.mjs +377 -0
- package/cli/app-config.mjs +526 -0
- package/cli/config.d.mts +162 -3
- package/cli/ios-project.mjs +652 -0
- package/cli/link.mjs +66 -71
- package/cli/nativue.mjs +39 -5
- package/cli/plugins.mjs +236 -0
- package/cli/prebuild.mjs +458 -0
- package/cli/run.mjs +2 -2
- package/cli/serialize.mjs +168 -0
- package/ios/AppLifecycle.swift +165 -0
- package/ios/Bridge.swift +53 -4
- package/ios/NativueView.swift +5 -1
- package/ios/Permissions.swift +19 -0
- package/ios/Plugins.swift +24 -0
- package/package.json +3 -2
- package/src/globals.ts +7 -1
- package/src/native-events.ts +99 -0
- package/src/native-functions.ts +16 -2
- package/src/permissions.ts +57 -0
- package/src/renderer.ts +5 -1
- package/src/router.ts +2 -1
- package/src/types.ts +3 -0
- package/template/android/app/src/debug/AndroidManifest.xml +4 -0
- package/template/android/app/src/main/java/MainActivity.kt +5 -0
- package/template/android/app/src/main/res/drawable-night-xxxhdpi/splash_logo.png +0 -0
- package/template/android/app/src/main/res/drawable-xxxhdpi/splash_logo.png +0 -0
- package/template/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml +6 -0
- package/template/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png +0 -0
- package/template/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png +0 -0
- package/template/android/app/src/main/res/values/colors.xml +4 -0
- package/template/android/app/src/main/res/values/styles.xml +15 -0
- package/template/android/app/src/main/res/values-night/styles.xml +5 -0
- package/template/android/gradle/wrapper/gradle-wrapper.jar +0 -0
- package/template/android/gradle/wrapper/gradle-wrapper.properties +9 -0
- package/template/android/gradlew +248 -0
- package/template/android/gradlew.bat +112 -0
- package/template/ios/App/App.swift +18 -0
- package/template/ios/App/Assets.xcassets/AppIcon.appiconset/Contents.json +1 -0
- package/template/ios/App/Assets.xcassets/AppIcon.appiconset/icon.png +0 -0
- package/template/ios/App/Assets.xcassets/Contents.json +1 -0
- package/template/ios/App/Assets.xcassets/LaunchLogo.imageset/Contents.json +11 -0
- package/template/ios/App/Assets.xcassets/LaunchLogo.imageset/logo-dark@1x.png +0 -0
- package/template/ios/App/Assets.xcassets/LaunchLogo.imageset/logo-dark@2x.png +0 -0
- package/template/ios/App/Assets.xcassets/LaunchLogo.imageset/logo-dark@3x.png +0 -0
- package/template/ios/App/Assets.xcassets/LaunchLogo.imageset/logo@1x.png +0 -0
- package/template/ios/App/Assets.xcassets/LaunchLogo.imageset/logo@2x.png +0 -0
- package/template/ios/App/Assets.xcassets/LaunchLogo.imageset/logo@3x.png +0 -0
- package/template/ios/App.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved +15 -0
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
import UIKit
|
|
2
|
+
import UserNotifications
|
|
3
|
+
|
|
4
|
+
/// A plugin that hears from the app: a push token, a remote notification, a URL. Implement only what
|
|
5
|
+
/// you need; the rest do nothing.
|
|
6
|
+
public protocol AppLifecycleListener: AnyObject {
|
|
7
|
+
func didFinishLaunching(options: [UIApplication.LaunchOptionsKey: Any]?)
|
|
8
|
+
func didRegisterForRemoteNotifications(deviceToken: Data)
|
|
9
|
+
func didFailToRegisterForRemoteNotifications(error: Error)
|
|
10
|
+
/// Every listener's runs at once; the app gets `newData` if any had new data.
|
|
11
|
+
func didReceiveRemoteNotification(_ userInfo: [AnyHashable: Any]) async -> UIBackgroundFetchResult
|
|
12
|
+
/// Custom schemes and universal links, before JavaScript's onOpenURL and the router. true: taken.
|
|
13
|
+
func open(url: URL) -> Bool
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
public extension AppLifecycleListener {
|
|
17
|
+
func didFinishLaunching(options: [UIApplication.LaunchOptionsKey: Any]?) {}
|
|
18
|
+
func didRegisterForRemoteNotifications(deviceToken: Data) {}
|
|
19
|
+
func didFailToRegisterForRemoteNotifications(error: Error) {}
|
|
20
|
+
func didReceiveRemoteNotification(_ userInfo: [AnyHashable: Any]) async -> UIBackgroundFetchResult { .noData }
|
|
21
|
+
func open(url: URL) -> Bool { false }
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/// nativue is the notification center's delegate, so packages share it: never set it yourself.
|
|
25
|
+
public protocol NotificationCenterListener: AnyObject {
|
|
26
|
+
/// How to show a notification while the app is open; nil leaves it to the others. The answers add up;
|
|
27
|
+
/// with none, it isn't shown.
|
|
28
|
+
func willPresent(_ notification: UNNotification) async -> UNNotificationPresentationOptions?
|
|
29
|
+
func didReceive(_ response: UNNotificationResponse) async
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
public extension NotificationCenterListener {
|
|
33
|
+
func willPresent(_ notification: UNNotification) async -> UNNotificationPresentationOptions? { nil }
|
|
34
|
+
func didReceive(_ response: UNNotificationResponse) async {}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/// The app's delegate (`@UIApplicationDelegateAdaptor` in App.swift): passes the app's events to the
|
|
38
|
+
/// plugins that listen for them.
|
|
39
|
+
public final class NativueAppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate {
|
|
40
|
+
/// Set by App.swift before any of the app's events.
|
|
41
|
+
public static var plugins: [NativuePlugin] = []
|
|
42
|
+
|
|
43
|
+
private var lifecycleListeners: [AppLifecycleListener] {
|
|
44
|
+
Self.plugins.compactMap { $0 as? AppLifecycleListener }
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
private var notificationCenterListeners: [NotificationCenterListener] {
|
|
48
|
+
Self.plugins.compactMap { $0 as? NotificationCenterListener }
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/// Before launch finishes, or a notification that opened the app is missed.
|
|
52
|
+
public func application(
|
|
53
|
+
_ application: UIApplication,
|
|
54
|
+
willFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
|
|
55
|
+
) -> Bool {
|
|
56
|
+
UNUserNotificationCenter.current().delegate = self
|
|
57
|
+
|
|
58
|
+
return true
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
public func application(
|
|
62
|
+
_ application: UIApplication,
|
|
63
|
+
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
|
|
64
|
+
) -> Bool {
|
|
65
|
+
lifecycleListeners.forEach { $0.didFinishLaunching(options: launchOptions) }
|
|
66
|
+
|
|
67
|
+
return true
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
public func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
|
|
71
|
+
lifecycleListeners.forEach { $0.didRegisterForRemoteNotifications(deviceToken: deviceToken) }
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
public func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
|
|
75
|
+
lifecycleListeners.forEach { $0.didFailToRegisterForRemoteNotifications(error: error) }
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
public func application(
|
|
79
|
+
_ application: UIApplication,
|
|
80
|
+
didReceiveRemoteNotification userInfo: [AnyHashable: Any]
|
|
81
|
+
) async -> UIBackgroundFetchResult {
|
|
82
|
+
let results = await answers(from: lifecycleListeners) { await $0.didReceiveRemoteNotification(userInfo) }
|
|
83
|
+
|
|
84
|
+
if results.contains(.newData) { return .newData }
|
|
85
|
+
if results.contains(.failed) { return .failed }
|
|
86
|
+
|
|
87
|
+
return .noData
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
public func userNotificationCenter(
|
|
91
|
+
_ center: UNUserNotificationCenter,
|
|
92
|
+
willPresent notification: UNNotification
|
|
93
|
+
) async -> UNNotificationPresentationOptions {
|
|
94
|
+
let options = await answers(from: notificationCenterListeners) { await $0.willPresent(notification) }
|
|
95
|
+
|
|
96
|
+
return options.compactMap { $0 }.reduce([]) { $0.union($1) }
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
public func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {
|
|
100
|
+
_ = await answers(from: notificationCenterListeners) { await $0.didReceive(response) }
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/// Asks the plugins first; false: JavaScript's onOpenURL and the router get it.
|
|
104
|
+
static func open(_ url: URL, plugins: [NativuePlugin]) -> Bool {
|
|
105
|
+
plugins.compactMap { $0 as? AppLifecycleListener }.contains { $0.open(url: url) }
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/// iOS ends an app that hasn't answered in 30 seconds: stop waiting at 25, with the answers in by then.
|
|
110
|
+
private let answersDeadline: UInt64 = 25_000_000_000
|
|
111
|
+
|
|
112
|
+
private func answers<Listener, Answer>(
|
|
113
|
+
from listeners: [Listener],
|
|
114
|
+
_ ask: @escaping (Listener) async -> Answer
|
|
115
|
+
) async -> [Answer] {
|
|
116
|
+
guard !listeners.isEmpty else { return [] }
|
|
117
|
+
|
|
118
|
+
let collector = AnswerCollector<Answer>(expected: listeners.count)
|
|
119
|
+
|
|
120
|
+
return await withCheckedContinuation { continuation in
|
|
121
|
+
collector.continuation = continuation
|
|
122
|
+
collector.deadline = Task {
|
|
123
|
+
try? await Task.sleep(nanoseconds: answersDeadline)
|
|
124
|
+
collector.finish()
|
|
125
|
+
}
|
|
126
|
+
// On the main thread, like the app's other events.
|
|
127
|
+
for listener in listeners {
|
|
128
|
+
Task { @MainActor in collector.add(await ask(listener)) }
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/// Not a task group: one waits for its tasks, so a listener that never returns would block the deadline.
|
|
134
|
+
private final class AnswerCollector<Answer> {
|
|
135
|
+
private let lock = NSLock()
|
|
136
|
+
private let expected: Int
|
|
137
|
+
private var collected: [Answer] = []
|
|
138
|
+
var continuation: CheckedContinuation<[Answer], Never>?
|
|
139
|
+
var deadline: Task<Void, Never>?
|
|
140
|
+
|
|
141
|
+
init(expected: Int) {
|
|
142
|
+
self.expected = expected
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
func add(_ answer: Answer) {
|
|
146
|
+
lock.lock()
|
|
147
|
+
collected.append(answer)
|
|
148
|
+
let isComplete = collected.count == expected
|
|
149
|
+
lock.unlock()
|
|
150
|
+
|
|
151
|
+
if isComplete { finish() }
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
func finish() {
|
|
155
|
+
lock.lock()
|
|
156
|
+
let continuation = continuation
|
|
157
|
+
self.continuation = nil
|
|
158
|
+
let answers = collected
|
|
159
|
+
let deadline = deadline
|
|
160
|
+
lock.unlock()
|
|
161
|
+
|
|
162
|
+
deadline?.cancel()
|
|
163
|
+
continuation?.resume(returning: answers)
|
|
164
|
+
}
|
|
165
|
+
}
|
package/ios/Bridge.swift
CHANGED
|
@@ -34,6 +34,9 @@ final class Bridge {
|
|
|
34
34
|
private var nextLayoutAnimation: LayoutAnimation?
|
|
35
35
|
/// Appearance.getColorScheme(): read on the main thread at start, then kept up to date.
|
|
36
36
|
private var colorScheme = "light"
|
|
37
|
+
/// AppState.current: "active" or "background". Set on the main thread in start(), before the bundle
|
|
38
|
+
/// runs; then only on the JS queue.
|
|
39
|
+
private var appState = "active"
|
|
37
40
|
/// Kept on the JS queue, for AccessibilityInfo.
|
|
38
41
|
private var accessibilityStatus = AccessibilityStatus()
|
|
39
42
|
/// Kept on the JS queue: the router's screens, reopened after a reload in development.
|
|
@@ -93,6 +96,23 @@ final class Bridge {
|
|
|
93
96
|
}
|
|
94
97
|
}
|
|
95
98
|
|
|
99
|
+
pluginRegistry.sendToJavaScript = { [unowned self] eventName, payload in
|
|
100
|
+
sendNativeEvent(eventName, payload)
|
|
101
|
+
}
|
|
102
|
+
// A background launch (a push) starts in the background.
|
|
103
|
+
let isInBackground = UIApplication.shared.applicationState == .background
|
|
104
|
+
|
|
105
|
+
appState = isInBackground ? "background" : "active"
|
|
106
|
+
let appStates = [
|
|
107
|
+
UIApplication.didBecomeActiveNotification: "active",
|
|
108
|
+
UIApplication.didEnterBackgroundNotification: "background",
|
|
109
|
+
]
|
|
110
|
+
for (name, nextAppState) in appStates {
|
|
111
|
+
NotificationCenter.default.addObserver(forName: name, object: nil, queue: .main) { [unowned self] _ in
|
|
112
|
+
appStateDidChange(to: nextAppState)
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
96
116
|
NotificationCenter.default.addObserver(forName: Self.openURLNotification, object: nil, queue: .main) {
|
|
97
117
|
[unowned self] notification in
|
|
98
118
|
guard let url = notification.object as? URL else { return }
|
|
@@ -180,15 +200,35 @@ final class Bridge {
|
|
|
180
200
|
}
|
|
181
201
|
|
|
182
202
|
/// Results reaching a runtime that has since been reloaded are dropped: call ids start over in the new one.
|
|
183
|
-
private func finishAsyncFunction(_ callId: Int, owner: JavaScriptRuntime?, value: Any?,
|
|
203
|
+
private func finishAsyncFunction(_ callId: Int, owner: JavaScriptRuntime?, value: Any?, error: Error?) {
|
|
184
204
|
evaluate { [unowned self] in
|
|
185
205
|
guard runtime === owner else { return }
|
|
186
206
|
|
|
187
|
-
let
|
|
207
|
+
let errorCode = (error as? PluginError)?.code
|
|
208
|
+
let arguments: [Any] = [
|
|
209
|
+
callId, value ?? NSNull(), error?.localizedDescription ?? NSNull(), errorCode ?? NSNull(),
|
|
210
|
+
]
|
|
211
|
+
|
|
188
212
|
runtime?.call("__asyncFunctionFinished", arguments: arguments)
|
|
189
213
|
}
|
|
190
214
|
}
|
|
191
215
|
|
|
216
|
+
/// For addNativeListener; dropped while no runtime runs.
|
|
217
|
+
private func sendNativeEvent(_ eventName: String, _ payload: Any?) {
|
|
218
|
+
evaluate { [unowned self] in
|
|
219
|
+
runtime?.call("__nativeEvent", arguments: [eventName, payload ?? NSNull()])
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
private func appStateDidChange(to nextAppState: String) {
|
|
224
|
+
evaluate { [unowned self] in
|
|
225
|
+
guard nextAppState != appState else { return }
|
|
226
|
+
|
|
227
|
+
appState = nextAppState
|
|
228
|
+
runtime?.call("__nativeEvent", arguments: ["app.state", nextAppState])
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
192
232
|
private static func colorScheme(of traits: UITraitCollection) -> String {
|
|
193
233
|
traits.userInterfaceStyle == .dark ? "dark" : "light"
|
|
194
234
|
}
|
|
@@ -318,6 +358,14 @@ final class Bridge {
|
|
|
318
358
|
DispatchQueue.main.async { UIAccessibility.post(notification: .announcement, argument: message) }
|
|
319
359
|
}
|
|
320
360
|
|
|
361
|
+
defineGetter("openSettings") { _ in
|
|
362
|
+
DispatchQueue.main.async {
|
|
363
|
+
UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!)
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
return true
|
|
367
|
+
}
|
|
368
|
+
|
|
321
369
|
// Prefixed, so a plugin can't replace nativue's own functions.
|
|
322
370
|
for (name, function) in pluginRegistry.functions {
|
|
323
371
|
defineGetter("plugin:\(name)", function)
|
|
@@ -332,15 +380,16 @@ final class Bridge {
|
|
|
332
380
|
Task {
|
|
333
381
|
do {
|
|
334
382
|
let value = try await function(Array(arguments.dropFirst()))
|
|
335
|
-
finishAsyncFunction(callId, owner: owner, value: value,
|
|
383
|
+
finishAsyncFunction(callId, owner: owner, value: value, error: nil)
|
|
336
384
|
} catch {
|
|
337
|
-
finishAsyncFunction(callId, owner: owner, value: nil,
|
|
385
|
+
finishAsyncFunction(callId, owner: owner, value: nil, error: error)
|
|
338
386
|
}
|
|
339
387
|
}
|
|
340
388
|
}
|
|
341
389
|
}
|
|
342
390
|
|
|
343
391
|
defineGetter("colorScheme") { [unowned self] _ in colorScheme }
|
|
392
|
+
defineGetter("appState") { [unowned self] _ in appState }
|
|
344
393
|
defineGetter("savedNavigation") { [unowned self] _ in savedNavigation }
|
|
345
394
|
define("saveNavigation") { [unowned self] arguments in savedNavigation = arguments[0] as? String }
|
|
346
395
|
|
package/ios/NativueView.swift
CHANGED
|
@@ -13,7 +13,11 @@ public struct NativueView: View {
|
|
|
13
13
|
public var body: some View {
|
|
14
14
|
VueRoot(plugins: plugins)
|
|
15
15
|
.ignoresSafeArea()
|
|
16
|
-
.onOpenURL { url in
|
|
16
|
+
.onOpenURL { url in
|
|
17
|
+
guard !NativueAppDelegate.open(url, plugins: plugins) else { return }
|
|
18
|
+
|
|
19
|
+
NotificationCenter.default.post(name: Bridge.openURLNotification, object: url)
|
|
20
|
+
}
|
|
17
21
|
}
|
|
18
22
|
}
|
|
19
23
|
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/// What JavaScript's PermissionResponse is, for an async function to return.
|
|
2
|
+
public enum PermissionStatus: String {
|
|
3
|
+
case granted, denied, undetermined
|
|
4
|
+
}
|
|
5
|
+
|
|
6
|
+
/// `{ status, granted, canAskAgain }` plus the plugin's own fields, e.g. `["accessPrivileges": "limited"]`.
|
|
7
|
+
/// canAskAgain is false only when denied: iOS shows the prompt once.
|
|
8
|
+
public func permissionResponse(
|
|
9
|
+
_ status: PermissionStatus,
|
|
10
|
+
extra: [String: Any] = [:]
|
|
11
|
+
) -> [String: Any] {
|
|
12
|
+
let response: [String: Any] = [
|
|
13
|
+
"status": status.rawValue,
|
|
14
|
+
"granted": status == .granted,
|
|
15
|
+
"canAskAgain": status != .denied,
|
|
16
|
+
]
|
|
17
|
+
|
|
18
|
+
return response.merging(extra) { _, extraValue in extraValue }
|
|
19
|
+
}
|
package/ios/Plugins.swift
CHANGED
|
@@ -15,6 +15,8 @@ public final class PluginRegistry {
|
|
|
15
15
|
public typealias SendEvent = (_ eventName: String, _ payload: Any?) -> Void
|
|
16
16
|
public typealias MakeView = (_ sendEvent: @escaping SendEvent) -> UIView
|
|
17
17
|
|
|
18
|
+
/// Set by the Bridge: calls JavaScript's listeners.
|
|
19
|
+
var sendToJavaScript: (_ eventName: String, _ payload: Any?) -> Void = { _, _ in }
|
|
18
20
|
private(set) var functions: [String: Function] = [:]
|
|
19
21
|
private(set) var asyncFunctions: [String: AsyncFunction] = [:]
|
|
20
22
|
private(set) var viewMakers: [String: MakeView] = [:]
|
|
@@ -34,12 +36,34 @@ public final class PluginRegistry {
|
|
|
34
36
|
asyncFunctions[name] = function
|
|
35
37
|
}
|
|
36
38
|
|
|
39
|
+
/// Reaches JavaScript's addNativeListener(eventName) listeners, from any thread, e.g.
|
|
40
|
+
/// sendEvent("notifications.received", payload). Dropped while no JavaScript runs: keep what must
|
|
41
|
+
/// outlive it (a push token) and let JavaScript read it with a function.
|
|
42
|
+
public func sendEvent(_ eventName: String, _ payload: Any? = nil) {
|
|
43
|
+
sendToJavaScript(eventName, payload)
|
|
44
|
+
}
|
|
45
|
+
|
|
37
46
|
/// `type` is the element's tag, e.g. "MapView" for h('MapView'). Created on the main thread.
|
|
38
47
|
public func addView(_ type: String, _ makeView: @escaping MakeView) {
|
|
39
48
|
viewMakers[type] = makeView
|
|
40
49
|
}
|
|
41
50
|
}
|
|
42
51
|
|
|
52
|
+
/// Thrown by an async function: JavaScript's Promise rejects with an Error whose `code` is this one.
|
|
53
|
+
/// Codes nativue's packages share: ERR_PERMISSION_DENIED, ERR_UNAVAILABLE, ERR_CANCELED,
|
|
54
|
+
/// ERR_INVALID_ARGUMENT.
|
|
55
|
+
public struct PluginError: LocalizedError {
|
|
56
|
+
public let code: String
|
|
57
|
+
public let message: String
|
|
58
|
+
|
|
59
|
+
public init(code: String, message: String) {
|
|
60
|
+
self.code = code
|
|
61
|
+
self.message = message
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
public var errorDescription: String? { message }
|
|
65
|
+
}
|
|
66
|
+
|
|
43
67
|
/// A plugin view gets its props here, all but `style`, which nativue applies (layout included).
|
|
44
68
|
public protocol PluginView: UIView {
|
|
45
69
|
func setProp(_ key: String, value: Any?)
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nativue/core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.14.1",
|
|
4
4
|
"description": "Vue rendering real native views on iOS and Android",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"vue",
|
|
@@ -32,7 +32,7 @@
|
|
|
32
32
|
}
|
|
33
33
|
},
|
|
34
34
|
"scripts": {
|
|
35
|
-
"test": "(cd ../../examples/demo && nativue build) && node test/test.mjs",
|
|
35
|
+
"test": "(cd ../../examples/demo && nativue build) && node test/test.mjs && node test/native-events.test.mjs && node test/prebuild.test.mjs",
|
|
36
36
|
"typecheck": "vue-tsc"
|
|
37
37
|
},
|
|
38
38
|
"dependencies": {
|
|
@@ -50,6 +50,7 @@
|
|
|
50
50
|
"files": [
|
|
51
51
|
"src",
|
|
52
52
|
"cli",
|
|
53
|
+
"template",
|
|
53
54
|
"ios",
|
|
54
55
|
"Package.swift",
|
|
55
56
|
"tsconfig.base.json",
|
package/src/globals.ts
CHANGED
|
@@ -12,7 +12,13 @@ declare global {
|
|
|
12
12
|
var __fireTimer: (timerId: number) => void
|
|
13
13
|
var __colorSchemeChanged: (colorScheme: ColorScheme) => void
|
|
14
14
|
var __windowSizeChanged: (windowSize: WindowSize) => void
|
|
15
|
-
var __asyncFunctionFinished: (
|
|
15
|
+
var __asyncFunctionFinished: (
|
|
16
|
+
callId: number,
|
|
17
|
+
value: unknown,
|
|
18
|
+
errorMessage: string | null,
|
|
19
|
+
errorCode: string | null,
|
|
20
|
+
) => void
|
|
21
|
+
var __nativeEvent: (eventName: string, payload: unknown) => void
|
|
16
22
|
var __animationFinished: (animationId: number, finished: boolean) => void
|
|
17
23
|
var __networkEvent: <Name extends keyof NetworkEventPayloads>(
|
|
18
24
|
requestId: number,
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
// What the native side tells JavaScript without being asked: a plugin's events (registry.sendEvent),
|
|
2
|
+
// the URLs the app is opened with, and whether it's in front.
|
|
3
|
+
import { getCurrentInstance, onUnmounted } from '@vue/runtime-core'
|
|
4
|
+
|
|
5
|
+
export type NativeSubscription = { remove(): void }
|
|
6
|
+
export type AppStateStatus = 'active' | 'background'
|
|
7
|
+
|
|
8
|
+
type URLListener = (url: string) => boolean | void
|
|
9
|
+
// An object per subscription: the same function added twice is removed one at a time.
|
|
10
|
+
type Entry<Listener> = { listener: Listener }
|
|
11
|
+
|
|
12
|
+
const entriesByEventName = new Map<string, Set<Entry<(payload: never) => void>>>()
|
|
13
|
+
const urlEntries = new Set<Entry<URLListener>>()
|
|
14
|
+
let navigateToURL: ((url: string) => void) | undefined
|
|
15
|
+
|
|
16
|
+
/** In a component's setup, also removed when it unmounts. */
|
|
17
|
+
function subscribe<Listener>(
|
|
18
|
+
entries: Set<Entry<Listener>>,
|
|
19
|
+
listener: Listener,
|
|
20
|
+
): NativeSubscription {
|
|
21
|
+
const entry = { listener }
|
|
22
|
+
const remove = () => entries.delete(entry)
|
|
23
|
+
|
|
24
|
+
entries.add(entry)
|
|
25
|
+
if (getCurrentInstance()) onUnmounted(remove)
|
|
26
|
+
|
|
27
|
+
return { remove }
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** In the order they were added, skipping any an earlier one removed; a throw doesn't stop the rest. */
|
|
31
|
+
function callEach<Listener>(
|
|
32
|
+
entries: Set<Entry<Listener>>,
|
|
33
|
+
call: (listener: Listener) => boolean | void,
|
|
34
|
+
) {
|
|
35
|
+
for (const entry of [...entries]) {
|
|
36
|
+
if (!entries.has(entry)) continue
|
|
37
|
+
|
|
38
|
+
try {
|
|
39
|
+
if (call(entry.listener) === true) return true
|
|
40
|
+
} catch (error) {
|
|
41
|
+
console.error(error)
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
return false
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Calls listener with the payload of each `eventName` the native side sends (registry.sendEvent),
|
|
50
|
+
* e.g. addNativeListener('notifications.received', (notification) => ...). Events sent while no
|
|
51
|
+
* JavaScript ran (the app closed, a reload) are lost.
|
|
52
|
+
*/
|
|
53
|
+
export function addNativeListener<Payload = unknown>(
|
|
54
|
+
eventName: string,
|
|
55
|
+
listener: (payload: Payload) => void,
|
|
56
|
+
): NativeSubscription {
|
|
57
|
+
const entries = entriesByEventName.get(eventName) ?? new Set()
|
|
58
|
+
|
|
59
|
+
entriesByEventName.set(eventName, entries)
|
|
60
|
+
|
|
61
|
+
return subscribe(entries, listener as (payload: never) => void)
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
globalThis.__nativeEvent = (eventName, payload) => {
|
|
65
|
+
const entries = entriesByEventName.get(eventName)
|
|
66
|
+
|
|
67
|
+
if (entries) callEach(entries, (listener) => listener(payload as never))
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Calls listener with each URL the app is opened with (deep links, OAuth redirects), before the
|
|
72
|
+
* router: returning true keeps the router from navigating to it. Listeners run in the order they
|
|
73
|
+
* were added; the first to return true stops the rest. The URL that opens the app arrives right
|
|
74
|
+
* after it starts: add the listener for it in src/app.ts or the root layout, not on a later screen.
|
|
75
|
+
*/
|
|
76
|
+
export function onOpenURL(listener: URLListener): NativeSubscription {
|
|
77
|
+
return subscribe(urlEntries, listener)
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** The router's: where a URL no onOpenURL listener took goes. */
|
|
81
|
+
export function setURLNavigation(navigate: (url: string) => void): void {
|
|
82
|
+
navigateToURL = navigate
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
globalThis.__openURL = (url) => {
|
|
86
|
+
if (callEach(urlEntries, (listener) => listener(url))) return
|
|
87
|
+
|
|
88
|
+
navigateToURL?.(url)
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Whether the app is in front ('active') or not ('background'). Changes reach
|
|
93
|
+
* addNativeListener('app.state', (state: AppStateStatus) => ...).
|
|
94
|
+
*/
|
|
95
|
+
export const AppState = {
|
|
96
|
+
get current(): AppStateStatus {
|
|
97
|
+
return __native.appState()
|
|
98
|
+
},
|
|
99
|
+
}
|
package/src/native-functions.ts
CHANGED
|
@@ -9,13 +9,27 @@ type PendingCall = { resolve: (value: unknown) => void; reject: (error: Error) =
|
|
|
9
9
|
const pendingCalls = new Map<number, PendingCall>()
|
|
10
10
|
let nextCallId = 1
|
|
11
11
|
|
|
12
|
-
|
|
12
|
+
/**
|
|
13
|
+
* An async native function's rejection. `code` is the plugin's, when it gave one:
|
|
14
|
+
* 'ERR_PERMISSION_DENIED', 'ERR_UNAVAILABLE', 'ERR_CANCELED', 'ERR_INVALID_ARGUMENT', or its own.
|
|
15
|
+
*/
|
|
16
|
+
export class NativeError extends Error {
|
|
17
|
+
readonly code: string | undefined
|
|
18
|
+
|
|
19
|
+
constructor(message: string, code: string | undefined) {
|
|
20
|
+
super(message)
|
|
21
|
+
this.name = 'NativeError'
|
|
22
|
+
this.code = code
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
globalThis.__asyncFunctionFinished = (callId, value, errorMessage, errorCode) => {
|
|
13
27
|
const call = pendingCalls.get(callId)
|
|
14
28
|
if (!call) return
|
|
15
29
|
|
|
16
30
|
pendingCalls.delete(callId)
|
|
17
31
|
if (errorMessage === null) call.resolve(value)
|
|
18
|
-
else call.reject(new
|
|
32
|
+
else call.reject(new NativeError(errorMessage, errorCode ?? undefined))
|
|
19
33
|
}
|
|
20
34
|
|
|
21
35
|
function asyncCaller(nativeFunction: (...args: unknown[]) => unknown) {
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
// Permissions as packages report them, the same on iOS and Android.
|
|
2
|
+
import { getCurrentInstance, onMounted, shallowRef, type ShallowRef } from '@vue/runtime-core'
|
|
3
|
+
import { addNativeListener } from './native-events'
|
|
4
|
+
import { NativeError } from './native-functions'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* granted: the feature works, maybe partly (limited photos), as the package's own fields say.
|
|
8
|
+
* canAskAgain false: only the system's Settings can change it now (openSettings()).
|
|
9
|
+
*/
|
|
10
|
+
export interface PermissionResponse {
|
|
11
|
+
status: 'granted' | 'denied' | 'undetermined'
|
|
12
|
+
granted: boolean
|
|
13
|
+
canAskAgain: boolean
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export type PermissionResponseWith<Extra extends object> = PermissionResponse & Extra
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* A permission's state, read on mount, after request, and when the app comes back to the front (the
|
|
20
|
+
* user may have changed it in Settings), e.g. usePermission(Camera.getPermission, Camera.requestPermission).
|
|
21
|
+
*/
|
|
22
|
+
export function usePermission<Response extends PermissionResponse, Arguments extends unknown[]>(
|
|
23
|
+
get: () => Promise<Response>,
|
|
24
|
+
request: (...args: Arguments) => Promise<Response>,
|
|
25
|
+
): { permission: ShallowRef<Response | null>; request: (...args: Arguments) => Promise<Response> } {
|
|
26
|
+
const permission: ShallowRef<Response | null> = shallowRef(null)
|
|
27
|
+
let latestRead = 0
|
|
28
|
+
|
|
29
|
+
// Only the latest read or request is kept: an older one may finish after it.
|
|
30
|
+
async function track(read: Promise<Response>) {
|
|
31
|
+
const readNumber = ++latestRead
|
|
32
|
+
const response = await read
|
|
33
|
+
|
|
34
|
+
if (readNumber === latestRead) permission.value = response
|
|
35
|
+
|
|
36
|
+
return response
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function refresh() {
|
|
40
|
+
track(get()).catch((error) => console.error(error))
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
if (getCurrentInstance()) onMounted(refresh)
|
|
44
|
+
else refresh()
|
|
45
|
+
addNativeListener('app.state', (state) => {
|
|
46
|
+
if (state === 'active') refresh()
|
|
47
|
+
})
|
|
48
|
+
|
|
49
|
+
return { permission, request: (...args) => track(request(...args)) }
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** The app's page in the system's Settings: where a permission with canAskAgain false is turned on. */
|
|
53
|
+
export async function openSettings(): Promise<void> {
|
|
54
|
+
if (!__native.openSettings()) {
|
|
55
|
+
throw new NativeError('This device has no settings page for the app', 'ERR_UNAVAILABLE')
|
|
56
|
+
}
|
|
57
|
+
}
|
package/src/renderer.ts
CHANGED
|
@@ -36,7 +36,11 @@ export {
|
|
|
36
36
|
type PlatformOS,
|
|
37
37
|
type WindowSize,
|
|
38
38
|
} from './appearance'
|
|
39
|
-
export { requireNativeFunction } from './native-functions'
|
|
39
|
+
export { NativeError, requireNativeFunction } from './native-functions'
|
|
40
|
+
export { addNativeListener, AppState, onOpenURL } from './native-events'
|
|
41
|
+
export type { AppStateStatus, NativeSubscription } from './native-events'
|
|
42
|
+
export { openSettings, usePermission } from './permissions'
|
|
43
|
+
export type { PermissionResponse, PermissionResponseWith } from './permissions'
|
|
40
44
|
export { AsyncStorage } from './storage'
|
|
41
45
|
export type * from './types'
|
|
42
46
|
export type { SvgElement, SvgIcon } from './native-components'
|
package/src/router.ts
CHANGED
|
@@ -29,6 +29,7 @@ import {
|
|
|
29
29
|
import { processColor } from './colors'
|
|
30
30
|
import { Pressable } from './components'
|
|
31
31
|
import type { SvgIcon } from './native-components'
|
|
32
|
+
import { setURLNavigation } from './native-events'
|
|
32
33
|
import { createApp } from './renderer'
|
|
33
34
|
|
|
34
35
|
export type Params = Record<string, string | string[]>
|
|
@@ -549,7 +550,7 @@ function hrefFromURL(url: string): string {
|
|
|
549
550
|
return url.replace(/^[a-z][a-z0-9+.-]*:\/\//i, '/')
|
|
550
551
|
}
|
|
551
552
|
|
|
552
|
-
|
|
553
|
+
setURLNavigation((url) => router.navigate(hrefFromURL(url)))
|
|
553
554
|
|
|
554
555
|
// ---------- Components ----------
|
|
555
556
|
|
package/src/types.ts
CHANGED
|
@@ -115,6 +115,9 @@ export interface NativeModule {
|
|
|
115
115
|
windowSize(): { width: number; height: number }
|
|
116
116
|
platform(): 'ios' | 'android'
|
|
117
117
|
colorScheme(): 'light' | 'dark'
|
|
118
|
+
appState(): 'active' | 'background'
|
|
119
|
+
/** false: the device has no settings page for the app (Android; iOS always has one). */
|
|
120
|
+
openSettings(): boolean
|
|
118
121
|
/** Development: the navigation saveNavigation kept, which outlives the JavaScript runtime. */
|
|
119
122
|
savedNavigation(): string | null
|
|
120
123
|
saveNavigation(routes: string): void
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
<?xml version="1.0" encoding="utf-8"?>
|
|
2
|
+
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
|
3
|
+
<background android:drawable="@color/ic_launcher_background" />
|
|
4
|
+
<foreground android:drawable="@mipmap/ic_launcher_foreground" />
|
|
5
|
+
<monochrome android:drawable="@mipmap/ic_launcher_foreground" />
|
|
6
|
+
</adaptive-icon>
|
|
Binary file
|
|
Binary file
|