@nativue/core 0.13.0 → 0.14.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/AGENTS.md +31 -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 +515 -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
package/AGENTS.md
CHANGED
|
@@ -70,7 +70,18 @@ Import navigation from `@nativue/core/router`:
|
|
|
70
70
|
|
|
71
71
|
Import the runtime from `vue`: `ref`, `computed`, `StyleSheet`, `Animated`, `LayoutAnimation`,
|
|
72
72
|
`Platform`, `AsyncStorage`, `Keyboard`, `Dimensions`, `useWindowDimensions`, `useColorScheme`,
|
|
73
|
-
`AccessibilityInfo`, `requireNativeFunction
|
|
73
|
+
`AccessibilityInfo`, `requireNativeFunction`, `addNativeListener`, `onOpenURL`, `AppState`,
|
|
74
|
+
`NativeError`, `usePermission`, `openSettings`.
|
|
75
|
+
|
|
76
|
+
- Native events: `addNativeListener('camera.captured', (payload) => ...)` returns a subscription;
|
|
77
|
+
in a component it's removed on unmount. `addNativeListener('app.state', (state) => ...)` and
|
|
78
|
+
`AppState.current` say whether the app is `'active'` or `'background'`.
|
|
79
|
+
- A rejected native call is a `NativeError` with a `code`: `ERR_PERMISSION_DENIED`,
|
|
80
|
+
`ERR_UNAVAILABLE`, `ERR_CANCELED`, `ERR_INVALID_ARGUMENT`.
|
|
81
|
+
- `onOpenURL((url) => true)` takes a URL the app was opened with before the router does.
|
|
82
|
+
- Permissions: `const { permission, request } = usePermission(Camera.getPermission, Camera.requestPermission)`
|
|
83
|
+
gives `{ status, granted, canAskAgain }`, re-read when the app comes back to the front. When
|
|
84
|
+
`!granted && !canAskAgain`, only `openSettings()` can help: explain why, then offer it.
|
|
74
85
|
|
|
75
86
|
- `AsyncStorage`: `getItem`, `setItem`, `removeItem`, `getAllKeys`, `multiGet`, `multiSet`,
|
|
76
87
|
`clear`; promise-based, string values. Store objects as JSON. For large data or queries, use
|
|
@@ -84,8 +95,10 @@ Import the runtime from `vue`: `ref`, `computed`, `StyleSheet`, `Animated`, `Lay
|
|
|
84
95
|
- `@/` points at `src/`. Shared components go in `src/components`, everything else in `src/lib`.
|
|
85
96
|
- Vue plugins (Pinia...) are installed in `src/app.ts`: `export default function setup(app: App)`.
|
|
86
97
|
- Official packages: `@nativue/icons` (icon components), `@nativue/tailwind`, `@nativue/haptics`,
|
|
87
|
-
`@nativue/sqlite`. A package with native code needs the app
|
|
88
|
-
`npm run android`, not just a reload.
|
|
98
|
+
`@nativue/clipboard` (copy text), `@nativue/sqlite`. A package with native code needs the app
|
|
99
|
+
rebuilt with `npm run ios` or `npm run android`, not just a reload.
|
|
100
|
+
- Copying: `const { copied, systemConfirmed } = await Clipboard.copy(text)`; show a "copied" toast
|
|
101
|
+
only when `copied && !systemConfirmed` (Android 13+ shows its own).
|
|
89
102
|
- Commands: `npm run ios` / `npm run android` build and open the app, then update it on save
|
|
90
103
|
(template edits keep the component's state; script edits re-create the component);
|
|
91
104
|
`npm run typecheck` checks scripts and templates; `npm run build` makes the release bundle;
|
|
@@ -93,7 +106,18 @@ Import the runtime from `vue`: `ref`, `computed`, `StyleSheet`, `Animated`, `Lay
|
|
|
93
106
|
- Native code the app needs (a platform API no package covers) goes in `native/<name>/ios` and
|
|
94
107
|
`native/<name>/android`, as `<Name>Plugin` classes registering functions JavaScript calls with
|
|
95
108
|
`requireNativeFunction`; libraries it uses (Swift packages, Maven) go in `native/<name>/nativue.json`.
|
|
96
|
-
See the docs' "Native code in your app". Rebuild after changing it.
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
109
|
+
See the docs' "Native code in your app". Rebuild after changing it. On Android, use
|
|
110
|
+
`registry.applicationContext`, and `registry.activity` only when needed, without keeping it. App
|
|
111
|
+
events (push token, notification taps, URLs, activity results) reach plugins implementing
|
|
112
|
+
`AppLifecycleListener` / `NotificationCenterListener` (iOS) or `ActivityListener` (Android).
|
|
113
|
+
- An iOS app extension (a widget, a Notification Service, a share extension) goes in
|
|
114
|
+
`native/extensions/<name>/`: plain Swift files, plus a `nativue.json` with its `ios.target` (`type`,
|
|
115
|
+
`bundleIdSuffix`). See the docs' "iOS app extensions". `ios.appGroups` in `nativue.config.ts`
|
|
116
|
+
shares data with it.
|
|
117
|
+
- Check changes with `npm run typecheck`.
|
|
118
|
+
- `ios/` and `android/` are generated from `nativue.config.ts` (name, scheme, ids, version,
|
|
119
|
+
buildNumber, icon, splash, `ios.infoPlist`, `ios.entitlements`, `android.permissions`,
|
|
120
|
+
`android.blockedPermissions`, `android.adaptiveIcon`, `android.signing`, `android.gradle`,
|
|
121
|
+
`resources`) by `npx nativue prebuild`, which `dev`, `build` and `run` also run: never edit them,
|
|
122
|
+
nor commit them. Prebuild stops with an error when they were changed by hand. An app with
|
|
123
|
+
`prebuild: false` in `nativue.config.ts` keeps them by hand instead.
|
package/README.md
CHANGED
|
@@ -19,6 +19,7 @@ This package holds:
|
|
|
19
19
|
nativue run ios # or android: builds, opens the app on a simulator or emulator, then dev
|
|
20
20
|
nativue dev # updates the running app on save
|
|
21
21
|
nativue build # bundles the app into ios/ and android/ (--production for releases)
|
|
22
|
+
nativue prebuild # generates ios/ and android/ from nativue.config.ts (the others run it too)
|
|
22
23
|
```
|
|
23
24
|
|
|
24
25
|
## Documentation
|
package/android/build.gradle.kts
CHANGED
|
@@ -73,4 +73,8 @@ dependencies {
|
|
|
73
73
|
implementation("com.facebook.soloader:soloader:0.10.5")
|
|
74
74
|
// Insets, system bars, fonts and accessibility the same way down to minSdk.
|
|
75
75
|
implementation("androidx.core:core:1.16.0")
|
|
76
|
+
// ComponentActivity: activity-result launchers and new-intent listeners for plugins.
|
|
77
|
+
api("androidx.activity:activity:1.13.0")
|
|
78
|
+
// AppState: whether the app, not one activity, is in front.
|
|
79
|
+
implementation("androidx.lifecycle:lifecycle-process:2.11.1")
|
|
76
80
|
}
|
|
@@ -46,6 +46,8 @@ fun pascalCase(name: String): String =
|
|
|
46
46
|
val appDirectory: File = settingsDir.parentFile
|
|
47
47
|
val androidPlugins = dependencyNames(appDirectory).mapNotNull { name -> androidPlugin(name, appDirectory) }
|
|
48
48
|
val appSourceDirectories = File(appDirectory, "native").listFiles().orEmpty()
|
|
49
|
+
// native/extensions holds iOS extension targets, not modules.
|
|
50
|
+
.filter { it.name != "extensions" }
|
|
49
51
|
.sortedBy { it.name }
|
|
50
52
|
.map { File(it, "android") }
|
|
51
53
|
.filter { it.isDirectory }
|
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
package dev.nativue
|
|
2
2
|
|
|
3
3
|
import android.annotation.SuppressLint
|
|
4
|
-
import android.
|
|
4
|
+
import android.content.ActivityNotFoundException
|
|
5
|
+
import android.content.Intent
|
|
6
|
+
import android.net.Uri
|
|
7
|
+
import android.provider.Settings
|
|
5
8
|
import android.content.pm.ApplicationInfo
|
|
6
9
|
import android.content.res.Configuration
|
|
7
10
|
import android.content.res.ColorStateList
|
|
@@ -17,7 +20,11 @@ import android.util.TypedValue
|
|
|
17
20
|
import android.view.Gravity
|
|
18
21
|
import android.view.View
|
|
19
22
|
import android.view.ViewGroup
|
|
23
|
+
import androidx.activity.ComponentActivity
|
|
20
24
|
import androidx.core.graphics.Insets
|
|
25
|
+
import androidx.lifecycle.DefaultLifecycleObserver
|
|
26
|
+
import androidx.lifecycle.LifecycleOwner
|
|
27
|
+
import androidx.lifecycle.ProcessLifecycleOwner
|
|
21
28
|
import androidx.core.view.ViewCompat
|
|
22
29
|
import androidx.core.view.WindowInsetsAnimationCompat
|
|
23
30
|
import androidx.core.view.WindowInsetsCompat
|
|
@@ -40,7 +47,7 @@ import kotlin.concurrent.thread
|
|
|
40
47
|
* Runs the JS bundle on its own thread and applies the operations sent by the Vue renderer
|
|
41
48
|
* (src/renderer.ts) to Android views + Yoga in batches on the main thread. Mirrors ios/Bridge.swift.
|
|
42
49
|
*/
|
|
43
|
-
class Bridge(private val activity:
|
|
50
|
+
class Bridge(private val activity: ComponentActivity, private val rootView: RootView) {
|
|
44
51
|
private val mainHandler = Handler(Looper.getMainLooper())
|
|
45
52
|
|
|
46
53
|
/** The dev server address that answered last (set by listenForReload, read when symbolicating). */
|
|
@@ -59,7 +66,21 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
|
|
|
59
66
|
private val isDebuggable = activity.applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE != 0
|
|
60
67
|
private val density = activity.resources.displayMetrics.density
|
|
61
68
|
private val storage = KeyValueStorage(activity)
|
|
62
|
-
private val pluginRegistry = PluginRegistry(activity)
|
|
69
|
+
private val pluginRegistry = PluginRegistry.get(activity)
|
|
70
|
+
private val sendToJavaScript: (String, Any?) -> Unit = { eventName, payload ->
|
|
71
|
+
evaluate { runtime?.call("__nativeEvent", eventName, payload) }
|
|
72
|
+
}
|
|
73
|
+
/** A URL that came before the bundle (from the dev server, in debug): sent once it has run. */
|
|
74
|
+
private var pendingURL: String? = null
|
|
75
|
+
|
|
76
|
+
/** AppState.current: "active" or "background". Only touched on the JS thread. */
|
|
77
|
+
private var appState = "active"
|
|
78
|
+
/** The whole app's, not the activity's: another activity of the app in front keeps it active. */
|
|
79
|
+
private val appStateObserver = object : DefaultLifecycleObserver {
|
|
80
|
+
override fun onResume(owner: LifecycleOwner) = appStateDidChange("active")
|
|
81
|
+
|
|
82
|
+
override fun onStop(owner: LifecycleOwner) = appStateDidChange("background")
|
|
83
|
+
}
|
|
63
84
|
|
|
64
85
|
// Only touched on the JS thread.
|
|
65
86
|
private var runtime: JavaScriptRuntime? = null
|
|
@@ -92,6 +113,9 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
|
|
|
92
113
|
|
|
93
114
|
fun start() {
|
|
94
115
|
NativeNode.setPixelDensity(density)
|
|
116
|
+
pluginRegistry.sendToJavaScript = sendToJavaScript
|
|
117
|
+
pluginRegistry.activityCreated(activity)
|
|
118
|
+
ProcessLifecycleOwner.get().lifecycle.addObserver(appStateObserver)
|
|
95
119
|
rootView.onLayoutPass = ::layout
|
|
96
120
|
NativeNode.onLayoutCalculated = ::reportLayoutChanges
|
|
97
121
|
ViewCompat.setOnApplyWindowInsetsListener(rootView) { view, insets ->
|
|
@@ -122,6 +146,10 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
|
|
|
122
146
|
/** On the main thread, when the activity is destroyed. */
|
|
123
147
|
fun destroy() {
|
|
124
148
|
isDestroyed = true
|
|
149
|
+
ProcessLifecycleOwner.get().lifecycle.removeObserver(appStateObserver)
|
|
150
|
+
// Another activity may have taken them over already.
|
|
151
|
+
if (pluginRegistry.sendToJavaScript === sendToJavaScript) pluginRegistry.sendToJavaScript = { _, _ -> }
|
|
152
|
+
pluginRegistry.activityDestroyed(activity)
|
|
125
153
|
reloadConnection?.disconnect()
|
|
126
154
|
animatedGraph.reset() // a looping animation would keep running on the dead views
|
|
127
155
|
javaScriptHandler.post {
|
|
@@ -135,14 +163,27 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
|
|
|
135
163
|
private fun asyncCall(function: AsyncFunction): NativeFunction = { arguments ->
|
|
136
164
|
val callId = int(arguments[0])
|
|
137
165
|
val owner = runtime
|
|
138
|
-
val promise = Promise { value, errorMessage ->
|
|
139
|
-
callIfStillRunning(owner, "__asyncFunctionFinished", callId, value, errorMessage)
|
|
166
|
+
val promise = Promise { value, errorMessage, errorCode ->
|
|
167
|
+
callIfStillRunning(owner, "__asyncFunctionFinished", callId, value, errorMessage, errorCode)
|
|
140
168
|
}
|
|
141
169
|
|
|
142
|
-
runCatching { function(arguments.drop(1), promise) }.onFailure {
|
|
170
|
+
runCatching { function(arguments.drop(1), promise) }.onFailure { error ->
|
|
171
|
+
val message = error.message ?: error.toString()
|
|
172
|
+
|
|
173
|
+
if (error is PluginException) promise.reject(error.code, message) else promise.reject(message)
|
|
174
|
+
}
|
|
143
175
|
null
|
|
144
176
|
}
|
|
145
177
|
|
|
178
|
+
private fun appStateDidChange(nextAppState: String) {
|
|
179
|
+
evaluate {
|
|
180
|
+
if (nextAppState == appState) return@evaluate
|
|
181
|
+
|
|
182
|
+
appState = nextAppState
|
|
183
|
+
runtime?.call("__nativeEvent", "app.state", nextAppState)
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
146
187
|
fun onConfigurationChanged() {
|
|
147
188
|
updateFontScale()
|
|
148
189
|
updateColorScheme()
|
|
@@ -205,7 +246,11 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
|
|
|
205
246
|
|
|
206
247
|
/** A URL the app was opened with (deep link), for the router (`__openURL`); after the bundle has run. */
|
|
207
248
|
fun openURL(url: String) {
|
|
208
|
-
evaluate {
|
|
249
|
+
evaluate {
|
|
250
|
+
val runningRuntime = runtime
|
|
251
|
+
|
|
252
|
+
if (runningRuntime == null) pendingURL = url else runningRuntime.call("__openURL", url)
|
|
253
|
+
}
|
|
209
254
|
}
|
|
210
255
|
|
|
211
256
|
/**
|
|
@@ -222,6 +267,8 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
|
|
|
222
267
|
runtime?.destroy()
|
|
223
268
|
runtime = JavaScriptRuntime(nativeFunctions(), ::reportError)
|
|
224
269
|
runtime?.evaluate(bundle, "main.bundle.js")
|
|
270
|
+
pendingURL?.let { url -> runtime?.call("__openURL", url) }
|
|
271
|
+
pendingURL = null
|
|
225
272
|
}
|
|
226
273
|
}
|
|
227
274
|
|
|
@@ -334,6 +381,7 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
|
|
|
334
381
|
put("windowSize") { _ -> windowSize }
|
|
335
382
|
put("platform") { _ -> "android" }
|
|
336
383
|
put("colorScheme") { _ -> colorScheme() }
|
|
384
|
+
put("appState") { _ -> appState }
|
|
337
385
|
put("savedNavigation") { _ -> savedNavigation }
|
|
338
386
|
put("saveNavigation") { arguments -> savedNavigation = arguments[0] as String }
|
|
339
387
|
put("accessibilityInfo") { _ -> accessibilityStatus(activity) }
|
|
@@ -342,6 +390,17 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
|
|
|
342
390
|
@Suppress("DEPRECATION") // its replacements (live regions, pane titles) need a view to describe
|
|
343
391
|
mainHandler.post { rootView.announceForAccessibility(message) }
|
|
344
392
|
}
|
|
393
|
+
// Google: an app details screen "may not exist" on some devices.
|
|
394
|
+
put("openSettings") { _ ->
|
|
395
|
+
val packageURI = Uri.fromParts("package", activity.packageName, null)
|
|
396
|
+
|
|
397
|
+
try {
|
|
398
|
+
activity.startActivity(Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI))
|
|
399
|
+
true
|
|
400
|
+
} catch (error: ActivityNotFoundException) {
|
|
401
|
+
false
|
|
402
|
+
}
|
|
403
|
+
}
|
|
345
404
|
// Prefixed, so a plugin can't replace nativue's own functions.
|
|
346
405
|
pluginRegistry.functions.forEach { (name, function) -> put("plugin:$name", function) }
|
|
347
406
|
pluginRegistry.asyncFunctions.forEach { (name, function) -> put("pluginAsync:$name", asyncCall(function)) }
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
package dev.nativue
|
|
2
2
|
|
|
3
|
-
import android.app.Activity
|
|
4
3
|
import android.content.Intent
|
|
5
4
|
import android.content.res.Configuration
|
|
5
|
+
import android.net.Uri
|
|
6
6
|
import android.os.Build
|
|
7
7
|
import android.os.Bundle
|
|
8
8
|
import android.view.KeyEvent
|
|
@@ -11,11 +11,12 @@ import android.view.ViewTreeObserver
|
|
|
11
11
|
import android.widget.EditText
|
|
12
12
|
import android.window.OnBackInvokedCallback
|
|
13
13
|
import android.window.OnBackInvokedDispatcher
|
|
14
|
+
import androidx.activity.ComponentActivity
|
|
14
15
|
import androidx.annotation.RequiresApi
|
|
15
16
|
import com.facebook.soloader.SoLoader
|
|
16
17
|
|
|
17
18
|
/** The app's activity: runs assets/main.bundle.js (or, in debug builds, the dev server's bundle). */
|
|
18
|
-
open class NativueActivity :
|
|
19
|
+
open class NativueActivity : ComponentActivity() {
|
|
19
20
|
private lateinit var bridge: Bridge
|
|
20
21
|
private var lastRKeyTime = 0L
|
|
21
22
|
|
|
@@ -31,7 +32,13 @@ open class NativueActivity : Activity() {
|
|
|
31
32
|
bridge = Bridge(this, rootView)
|
|
32
33
|
bridge.onCanGoBackChange = ::setHandlesBack
|
|
33
34
|
bridge.start()
|
|
34
|
-
intent.data?.let
|
|
35
|
+
intent.data?.let(::openURL)
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
private fun openURL(uri: Uri) {
|
|
39
|
+
val url = uri.toString()
|
|
40
|
+
|
|
41
|
+
if (!PluginRegistry.get(this).open(url)) bridge.openURL(url)
|
|
35
42
|
}
|
|
36
43
|
|
|
37
44
|
/**
|
|
@@ -55,7 +62,7 @@ open class NativueActivity : Activity() {
|
|
|
55
62
|
/** Deep links while running: singleTask brings this activity back instead of starting another. */
|
|
56
63
|
override fun onNewIntent(intent: Intent) {
|
|
57
64
|
super.onNewIntent(intent)
|
|
58
|
-
intent.data?.let
|
|
65
|
+
intent.data?.let(::openURL)
|
|
59
66
|
}
|
|
60
67
|
|
|
61
68
|
/** The manifest's configChanges keep the activity (and the JS state) through uiMode changes. */
|
|
@@ -99,7 +106,7 @@ open class NativueActivity : Activity() {
|
|
|
99
106
|
* release build crashes on launch if the activity itself refers to it.
|
|
100
107
|
*/
|
|
101
108
|
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
|
|
102
|
-
private class PredictiveBack(private val activity:
|
|
109
|
+
private class PredictiveBack(private val activity: ComponentActivity, onBack: () -> Unit) {
|
|
103
110
|
private val callback = OnBackInvokedCallback(onBack)
|
|
104
111
|
|
|
105
112
|
fun setRegistered(isRegistered: Boolean) {
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
package dev.nativue
|
|
2
|
+
|
|
3
|
+
import android.content.Context
|
|
4
|
+
import android.content.pm.PackageManager
|
|
5
|
+
import android.os.Handler
|
|
6
|
+
import android.os.Looper
|
|
7
|
+
import androidx.activity.ComponentActivity
|
|
8
|
+
import androidx.activity.result.ActivityResultLauncher
|
|
9
|
+
import androidx.activity.result.contract.ActivityResultContracts.RequestMultiplePermissions
|
|
10
|
+
import androidx.core.app.ActivityCompat
|
|
11
|
+
import androidx.core.content.ContextCompat
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Runtime permissions as JavaScript's PermissionResponse: `{ status, granted, canAskAgain }`, to
|
|
15
|
+
* resolve a Promise with, plus the plugin's own fields. Pass only the permissions this Android
|
|
16
|
+
* version asks for (POST_NOTIFICATIONS is Android 13+).
|
|
17
|
+
*/
|
|
18
|
+
class Permissions internal constructor(private val registry: PluginRegistry) {
|
|
19
|
+
// Android can't tell "never asked" from "denied for good": both have no rationale to show.
|
|
20
|
+
private val asked = registry.applicationContext.getSharedPreferences("dev.nativue.permissions", Context.MODE_PRIVATE)
|
|
21
|
+
private var launcher: ActivityResultLauncher<Array<String>>? = null
|
|
22
|
+
private var launcherActivity: ComponentActivity? = null
|
|
23
|
+
private val mainHandler = Handler(Looper.getMainLooper())
|
|
24
|
+
/** One system prompt at a time: the others wait their turn. */
|
|
25
|
+
private val waitingRequests = ArrayDeque<Pair<List<String>, (Map<String, Any>) -> Unit>>()
|
|
26
|
+
|
|
27
|
+
fun status(permissions: List<String>): Map<String, Any> {
|
|
28
|
+
val context = registry.applicationContext
|
|
29
|
+
val denied = permissions.filter {
|
|
30
|
+
ContextCompat.checkSelfPermission(context, it) != PackageManager.PERMISSION_GRANTED
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
if (denied.isEmpty()) return response("granted", canAskAgain = true)
|
|
34
|
+
// A rationale means it was denied once, even when another prompt asked.
|
|
35
|
+
if (denied.any { !asked.getBoolean(it, false) && !showsRationale(it) }) {
|
|
36
|
+
return response("undetermined", canAskAgain = true)
|
|
37
|
+
}
|
|
38
|
+
// Without an activity there's no rationale to read: assume it can still ask.
|
|
39
|
+
if (registry.activity == null) return response("denied", canAskAgain = true)
|
|
40
|
+
|
|
41
|
+
return response("denied", canAskAgain = denied.all(::showsRationale))
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Shows the system prompt (unless all are granted), then calls onResult on the main thread. */
|
|
45
|
+
fun request(permissions: List<String>, onResult: (Map<String, Any>) -> Unit) {
|
|
46
|
+
mainHandler.post {
|
|
47
|
+
waitingRequests.addLast(permissions to onResult)
|
|
48
|
+
if (waitingRequests.size == 1) launchNext()
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
internal fun activityCreated(activity: ComponentActivity) {
|
|
53
|
+
// A result that comes after a recreation reaches this one: the waiting requests outlive the activity.
|
|
54
|
+
launcher = activity.registerForActivityResult(RequestMultiplePermissions(), ::finishRequest)
|
|
55
|
+
launcherActivity = activity
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Finished for good, not recreated: a prompt it showed won't answer, so the waiting requests get the status. */
|
|
59
|
+
internal fun activityDestroyed(activity: ComponentActivity) {
|
|
60
|
+
if (activity !== launcherActivity || activity.isChangingConfigurations) return
|
|
61
|
+
|
|
62
|
+
launcher = null
|
|
63
|
+
launcherActivity = null
|
|
64
|
+
while (waitingRequests.isNotEmpty()) {
|
|
65
|
+
val (permissions, onResult) = waitingRequests.removeFirst()
|
|
66
|
+
|
|
67
|
+
onResult(status(permissions))
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
private fun launchNext() {
|
|
72
|
+
val (permissions, onResult) = waitingRequests.firstOrNull() ?: return
|
|
73
|
+
val launcher = launcher
|
|
74
|
+
|
|
75
|
+
if (status(permissions)["granted"] == true || launcher == null || registry.activity == null) {
|
|
76
|
+
waitingRequests.removeFirst()
|
|
77
|
+
onResult(status(permissions))
|
|
78
|
+
launchNext()
|
|
79
|
+
|
|
80
|
+
return
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
launcher.launch(permissions.toTypedArray())
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Asked only when the user answered: Android 11+ reports a prompt dismissed with back as denied,
|
|
88
|
+
* but only a real "Don't allow" shows a rationale next time.
|
|
89
|
+
*/
|
|
90
|
+
private fun finishRequest(results: Map<String, Boolean>) {
|
|
91
|
+
val (permissions, onResult) = waitingRequests.removeFirstOrNull() ?: return
|
|
92
|
+
val answered = results.filter { (permission, granted) -> granted || showsRationale(permission) }.keys
|
|
93
|
+
|
|
94
|
+
asked.edit().apply { answered.forEach { putBoolean(it, true) } }.apply()
|
|
95
|
+
onResult(status(permissions))
|
|
96
|
+
launchNext()
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
private fun showsRationale(permission: String): Boolean {
|
|
100
|
+
val activity = registry.activity ?: return false
|
|
101
|
+
|
|
102
|
+
return ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
private fun response(status: String, canAskAgain: Boolean): Map<String, Any> =
|
|
106
|
+
mapOf("status" to status, "granted" to (status == "granted"), "canAskAgain" to canAskAgain)
|
|
107
|
+
}
|
|
@@ -2,6 +2,7 @@ package dev.nativue
|
|
|
2
2
|
|
|
3
3
|
import android.content.Context
|
|
4
4
|
import android.view.View
|
|
5
|
+
import androidx.activity.ComponentActivity
|
|
5
6
|
import java.util.concurrent.atomic.AtomicBoolean
|
|
6
7
|
|
|
7
8
|
/**
|
|
@@ -16,33 +17,106 @@ interface NativuePlugin {
|
|
|
16
17
|
/** sendEvent("change", payload) reaches the element's @change; event names are lowercase. */
|
|
17
18
|
typealias SendEvent = (eventName: String, payload: Any?) -> Unit
|
|
18
19
|
|
|
19
|
-
/**
|
|
20
|
-
|
|
20
|
+
/**
|
|
21
|
+
* Settles an async function's JavaScript Promise; only the first call counts. reject's code is the
|
|
22
|
+
* JavaScript Error's `code`. Codes nativue's packages share: ERR_PERMISSION_DENIED, ERR_UNAVAILABLE,
|
|
23
|
+
* ERR_CANCELED, ERR_INVALID_ARGUMENT.
|
|
24
|
+
*/
|
|
25
|
+
class Promise internal constructor(
|
|
26
|
+
private val settle: (value: Any?, errorMessage: String?, errorCode: String?) -> Unit,
|
|
27
|
+
) {
|
|
21
28
|
private val settled = AtomicBoolean(false)
|
|
22
29
|
|
|
23
30
|
fun resolve(value: Any? = null) {
|
|
24
|
-
if (settled.compareAndSet(false, true)) settle(value, null)
|
|
31
|
+
if (settled.compareAndSet(false, true)) settle(value, null, null)
|
|
25
32
|
}
|
|
26
33
|
|
|
27
34
|
fun reject(errorMessage: String) {
|
|
28
|
-
if (settled.compareAndSet(false, true)) settle(null, errorMessage)
|
|
35
|
+
if (settled.compareAndSet(false, true)) settle(null, errorMessage, null)
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** e.g. reject(code = "ERR_CANCELED", errorMessage = "The picker was closed") */
|
|
39
|
+
fun reject(code: String, errorMessage: String) {
|
|
40
|
+
if (settled.compareAndSet(false, true)) settle(null, errorMessage, code)
|
|
29
41
|
}
|
|
30
42
|
}
|
|
31
43
|
|
|
44
|
+
/** Thrown by an async function: rejects its Promise with this code, as Promise.reject(code, message). */
|
|
45
|
+
class PluginException(val code: String, message: String) : Exception(message)
|
|
46
|
+
|
|
32
47
|
/** Called on the JavaScript thread; settles `promise` from any thread, when the work is done. */
|
|
33
48
|
typealias AsyncFunction = (arguments: List<Any?>, promise: Promise) -> Unit
|
|
34
49
|
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
50
|
+
interface ActivityListener {
|
|
51
|
+
/** Register activity-result launchers here, every time and in the same order, so results survive a recreation. */
|
|
52
|
+
fun onActivityCreated(activity: ComponentActivity) {}
|
|
53
|
+
|
|
54
|
+
fun onActivityDestroyed(activity: ComponentActivity) {}
|
|
55
|
+
|
|
56
|
+
/** A URL the app was opened with, before JavaScript's onOpenURL and the router. true: taken. */
|
|
57
|
+
fun open(url: String): Boolean = false
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** One for the whole process, so a service (a push with the app closed) reaches the plugins too. */
|
|
61
|
+
class PluginRegistry private constructor(context: Context) {
|
|
62
|
+
val applicationContext: Context = context.applicationContext
|
|
63
|
+
|
|
64
|
+
/** Never keep it: it's replaced when the activity is recreated. */
|
|
65
|
+
@Volatile
|
|
66
|
+
var activity: ComponentActivity? = null
|
|
67
|
+
private set
|
|
68
|
+
|
|
69
|
+
/** Plugins from before 0.14 cast it to Activity. */
|
|
70
|
+
@Deprecated("Use applicationContext, or activity / requireActivity() for the activity.")
|
|
71
|
+
val context: Context
|
|
72
|
+
get() = activity ?: applicationContext
|
|
73
|
+
|
|
74
|
+
/** Set by the Bridge: calls JavaScript's listeners. */
|
|
75
|
+
internal var sendToJavaScript: (eventName: String, payload: Any?) -> Unit = { _, _ -> }
|
|
76
|
+
internal var functions = mutableMapOf<String, NativeFunction>()
|
|
77
|
+
private set
|
|
78
|
+
internal var asyncFunctions = mutableMapOf<String, AsyncFunction>()
|
|
79
|
+
private set
|
|
80
|
+
internal var viewMakers = mutableMapOf<String, (SendEvent) -> View>()
|
|
81
|
+
private set
|
|
82
|
+
private val plugins = pluginClassNames(applicationContext).map { className ->
|
|
83
|
+
Class.forName(className).getDeclaredConstructor().newInstance() as NativuePlugin
|
|
84
|
+
}
|
|
85
|
+
private val activityListeners = plugins.filterIsInstance<ActivityListener>()
|
|
86
|
+
|
|
87
|
+
val permissions = Permissions(this)
|
|
88
|
+
|
|
89
|
+
fun requireActivity(): ComponentActivity =
|
|
90
|
+
activity ?: throw PluginException("ERR_UNAVAILABLE", "The app has no activity open")
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Plugins register again for each activity, as when the registry was the activity's: those that
|
|
94
|
+
* keep what register read (the activity's window) get the new one.
|
|
95
|
+
*/
|
|
96
|
+
internal fun activityCreated(activity: ComponentActivity) {
|
|
97
|
+
this.activity = activity
|
|
98
|
+
permissions.activityCreated(activity)
|
|
99
|
+
functions = mutableMapOf()
|
|
100
|
+
asyncFunctions = mutableMapOf()
|
|
101
|
+
viewMakers = mutableMapOf()
|
|
102
|
+
plugins.forEach { it.register(this) }
|
|
103
|
+
activityListeners.forEach { it.onActivityCreated(activity) }
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
internal fun activityDestroyed(activity: ComponentActivity) {
|
|
107
|
+
if (this.activity === activity) this.activity = null
|
|
108
|
+
permissions.activityDestroyed(activity)
|
|
109
|
+
activityListeners.forEach { it.onActivityDestroyed(activity) }
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
internal fun open(url: String): Boolean = activityListeners.any { it.open(url) }
|
|
113
|
+
|
|
114
|
+
companion object {
|
|
115
|
+
@Volatile
|
|
116
|
+
private var instance: PluginRegistry? = null
|
|
117
|
+
|
|
118
|
+
fun get(context: Context): PluginRegistry =
|
|
119
|
+
instance ?: synchronized(this) { instance ?: PluginRegistry(context).also { instance = it } }
|
|
46
120
|
}
|
|
47
121
|
|
|
48
122
|
/** Runs on the JavaScript thread and returns synchronously: post to the main thread for views. */
|
|
@@ -55,6 +129,15 @@ class PluginRegistry internal constructor(val context: Context) {
|
|
|
55
129
|
asyncFunctions[name] = function
|
|
56
130
|
}
|
|
57
131
|
|
|
132
|
+
/**
|
|
133
|
+
* Reaches JavaScript's addNativeListener(eventName) listeners, from any thread, e.g.
|
|
134
|
+
* sendEvent("notifications.received", payload). Dropped while no JavaScript runs: keep what must
|
|
135
|
+
* outlive it (a push token) and let JavaScript read it with a function.
|
|
136
|
+
*/
|
|
137
|
+
fun sendEvent(eventName: String, payload: Any? = null) {
|
|
138
|
+
sendToJavaScript(eventName, payload)
|
|
139
|
+
}
|
|
140
|
+
|
|
58
141
|
/** `type` is the element's tag, e.g. "MapView" for h('MapView'). Created on the main thread. */
|
|
59
142
|
fun addView(type: String, makeView: (SendEvent) -> View) {
|
|
60
143
|
viewMakers[type] = makeView
|