@nativue/core 0.12.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 +33 -8
- package/README.md +2 -1
- package/android/build.gradle.kts +4 -0
- package/android/nativue.settings.gradle.kts +2 -0
- package/android/src/main/java/dev/nativue/Bridge.kt +118 -12
- package/android/src/main/java/dev/nativue/DownloadBanner.kt +45 -0
- package/android/src/main/java/dev/nativue/NativueActivity.kt +26 -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/hot-client.js +192 -0
- package/cli/ios-project.mjs +652 -0
- package/cli/link.mjs +66 -71
- package/cli/nativue.mjs +262 -58
- 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/cli/symbolicate.mjs +26 -14
- package/ios/AppLifecycle.swift +165 -0
- package/ios/Bridge.swift +110 -9
- package/ios/DownloadBanner.swift +38 -0
- package/ios/NativueView.swift +24 -1
- package/ios/Permissions.swift +19 -0
- package/ios/Plugins.swift +24 -0
- package/package.json +3 -2
- package/src/globals.ts +8 -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 +6 -1
- package/src/router.ts +31 -1
- package/src/types.ts +6 -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/cli/run.mjs
CHANGED
|
@@ -150,7 +150,7 @@ function signingSettings() {
|
|
|
150
150
|
? 'No Apple Development certificate on this Mac: sign in to your Apple account in Xcode > Settings > Accounts,'
|
|
151
151
|
: 'Your certificates belong to several teams:'
|
|
152
152
|
throw new Error(
|
|
153
|
-
`${reason} then
|
|
153
|
+
`${reason} then set your team id in nativue.config.ts: ios: { appleTeamId: 'ABCDE12345' } (it's under Signing & Capabilities in Xcode). With prebuild: false, pick the team in ios/App.xcodeproj instead.`,
|
|
154
154
|
)
|
|
155
155
|
}
|
|
156
156
|
|
|
@@ -184,7 +184,7 @@ function buildIOSApp(destination, isSimulator) {
|
|
|
184
184
|
if (isSimulator) throw error
|
|
185
185
|
|
|
186
186
|
throw new Error(
|
|
187
|
-
'The build for the phone failed. If it is about signing,
|
|
187
|
+
'The build for the phone failed. If it is about signing, check ios.appleTeamId in nativue.config.ts, and your account in Xcode > Settings > Accounts.',
|
|
188
188
|
)
|
|
189
189
|
}
|
|
190
190
|
}
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
// Writers for the native files prebuild generates from plain objects: plists, the Xcode project
|
|
2
|
+
// (an OpenStep plist) and Android XML. Only writers: nativue builds these files, it never reads them.
|
|
3
|
+
|
|
4
|
+
const PLIST_HEADER = `<?xml version="1.0" encoding="UTF-8"?>
|
|
5
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
6
|
+
<plist version="1.0">
|
|
7
|
+
`
|
|
8
|
+
|
|
9
|
+
export function escapeXml(text) {
|
|
10
|
+
return text.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>')
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function escapeXmlAttribute(text) {
|
|
14
|
+
return escapeXml(text).replaceAll('"', '"')
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function plistValue(value, depth) {
|
|
18
|
+
const indent = '\t'.repeat(depth)
|
|
19
|
+
|
|
20
|
+
if (typeof value === 'boolean') return `${indent}<${value}/>`
|
|
21
|
+
if (typeof value === 'number') {
|
|
22
|
+
const type = Number.isInteger(value) ? 'integer' : 'real'
|
|
23
|
+
|
|
24
|
+
return `${indent}<${type}>${value}</${type}>`
|
|
25
|
+
}
|
|
26
|
+
if (typeof value === 'string') return `${indent}<string>${escapeXml(value)}</string>`
|
|
27
|
+
if (Array.isArray(value)) {
|
|
28
|
+
if (value.length === 0) return `${indent}<array/>`
|
|
29
|
+
|
|
30
|
+
const items = value.map((item) => plistValue(item, depth + 1))
|
|
31
|
+
|
|
32
|
+
return [`${indent}<array>`, ...items, `${indent}</array>`].join('\n')
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const keys = Object.keys(value)
|
|
36
|
+
.filter((key) => value[key] !== undefined)
|
|
37
|
+
.sort()
|
|
38
|
+
if (keys.length === 0) return `${indent}<dict/>`
|
|
39
|
+
|
|
40
|
+
const entries = keys.flatMap((key) => [
|
|
41
|
+
`${indent}\t<key>${escapeXml(key)}</key>`,
|
|
42
|
+
plistValue(value[key], depth + 1),
|
|
43
|
+
])
|
|
44
|
+
|
|
45
|
+
return [`${indent}<dict>`, ...entries, `${indent}</dict>`].join('\n')
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** An XML property list (Info.plist, entitlements). Keys are sorted, as Xcode writes them. */
|
|
49
|
+
export function plist(dictionary) {
|
|
50
|
+
return `${PLIST_HEADER}${plistValue(dictionary, 0)}\n</plist>\n`
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// Strings the OpenStep format leaves unquoted; anything else is quoted and escaped.
|
|
54
|
+
const OPENSTEP_BARE_STRING = /^[A-Za-z0-9_$./]+$/
|
|
55
|
+
// Objects Xcode writes on a single line.
|
|
56
|
+
const SINGLE_LINE_ISAS = new Set(['PBXBuildFile', 'PBXFileReference'])
|
|
57
|
+
|
|
58
|
+
function openStepString(text) {
|
|
59
|
+
if (OPENSTEP_BARE_STRING.test(text)) return text
|
|
60
|
+
|
|
61
|
+
const escaped = text.replaceAll('\\', '\\\\').replaceAll('"', '\\"').replaceAll('\n', '\\n')
|
|
62
|
+
|
|
63
|
+
return `"${escaped}"`
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** isa first, then the rest in alphabetical order: Xcode's own order, so saving in Xcode changes nothing. */
|
|
67
|
+
function sortedKeys(dictionary) {
|
|
68
|
+
const keys = Object.keys(dictionary).filter(
|
|
69
|
+
(key) => key !== 'isa' && dictionary[key] !== undefined,
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
keys.sort()
|
|
73
|
+
|
|
74
|
+
return 'isa' in dictionary ? ['isa', ...keys] : keys
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* The Xcode project file, from `{ objectVersion, objects, rootObject, comments }`: objects by id,
|
|
79
|
+
* and the comment Xcode writes after each id that has one ("App", "Project object"...).
|
|
80
|
+
*/
|
|
81
|
+
export function pbxproj({ objectVersion, objects, rootObject, comments }) {
|
|
82
|
+
const reference = (id) => (comments[id] ? `${id} /* ${comments[id]} */` : id)
|
|
83
|
+
const value = (item) => (typeof item === 'string' && item in objects ? reference(item) : item)
|
|
84
|
+
|
|
85
|
+
function render(item, depth) {
|
|
86
|
+
const indent = '\t'.repeat(depth)
|
|
87
|
+
|
|
88
|
+
if (Array.isArray(item)) {
|
|
89
|
+
const lines = item.map((element) => `${indent}\t${render(element, depth + 1)},\n`)
|
|
90
|
+
|
|
91
|
+
return `(\n${lines.join('')}${indent})`
|
|
92
|
+
}
|
|
93
|
+
if (typeof item === 'object') {
|
|
94
|
+
const lines = sortedKeys(item).map(
|
|
95
|
+
(key) => `${indent}\t${openStepString(key)} = ${render(item[key], depth + 1)};\n`,
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
return `{\n${lines.join('')}${indent}}`
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
return value(item) === item ? openStepString(String(item)) : value(item)
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function renderObject(id, object) {
|
|
105
|
+
if (!SINGLE_LINE_ISAS.has(object.isa)) return `\t\t${reference(id)} = ${render(object, 2)};\n`
|
|
106
|
+
|
|
107
|
+
const entries = sortedKeys(object).map((key) => `${key} = ${render(object[key], 3)}; `)
|
|
108
|
+
|
|
109
|
+
return `\t\t${reference(id)} = {${entries.join('')}};\n`
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const isas = [...new Set(Object.values(objects).map((object) => object.isa))].sort()
|
|
113
|
+
const sections = isas.map((isa) => {
|
|
114
|
+
const ids = Object.keys(objects)
|
|
115
|
+
.filter((id) => objects[id].isa === isa)
|
|
116
|
+
.sort()
|
|
117
|
+
|
|
118
|
+
return `/* Begin ${isa} section */\n${ids.map((id) => renderObject(id, objects[id])).join('')}/* End ${isa} section */\n`
|
|
119
|
+
})
|
|
120
|
+
|
|
121
|
+
return `// !$*UTF8*$!
|
|
122
|
+
{
|
|
123
|
+
\tarchiveVersion = 1;
|
|
124
|
+
\tclasses = {
|
|
125
|
+
\t};
|
|
126
|
+
\tobjectVersion = ${objectVersion};
|
|
127
|
+
\tobjects = {
|
|
128
|
+
|
|
129
|
+
${sections.join('\n')}\t};
|
|
130
|
+
\trootObject = ${reference(rootObject)};
|
|
131
|
+
}
|
|
132
|
+
`
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Android XML from `{ tag, attributes, children }`. Attribute names keep their prefix
|
|
137
|
+
* ('android:name', 'tools:node'). One attribute stays on the element's line; more go one per line.
|
|
138
|
+
*/
|
|
139
|
+
export function xml(element) {
|
|
140
|
+
return `<?xml version="1.0" encoding="utf-8"?>\n${xmlElement(element, 0)}\n`
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function xmlElement({ tag, attributes = {}, children = [], text }, depth) {
|
|
144
|
+
const indent = ' '.repeat(depth)
|
|
145
|
+
const pairs = Object.entries(attributes).map(
|
|
146
|
+
([name, value]) => `${name}="${escapeXmlAttribute(value)}"`,
|
|
147
|
+
)
|
|
148
|
+
const opening =
|
|
149
|
+
pairs.length <= 1
|
|
150
|
+
? `${indent}<${[tag, ...pairs].join(' ')}`
|
|
151
|
+
: `${indent}<${tag}\n${pairs.map((pair) => `${indent} ${pair}`).join('\n')}`
|
|
152
|
+
|
|
153
|
+
if (text !== undefined) return `${opening}>${escapeXml(text)}</${tag}>`
|
|
154
|
+
if (children.length === 0) return `${opening} />`
|
|
155
|
+
|
|
156
|
+
const content = children.map((child) => xmlElement(child, depth + 1)).join('\n')
|
|
157
|
+
|
|
158
|
+
return `${opening}>\n${content}\n${indent}</${tag}>`
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** A string resource's text: Android reads quotes, backslashes and a leading @ or ? specially. */
|
|
162
|
+
export function androidString(text) {
|
|
163
|
+
return text
|
|
164
|
+
.replaceAll('\\', '\\\\')
|
|
165
|
+
.replaceAll("'", "\\'")
|
|
166
|
+
.replaceAll('"', '\\"')
|
|
167
|
+
.replace(/^([@?])/, '\\$1')
|
|
168
|
+
}
|
package/cli/symbolicate.mjs
CHANGED
|
@@ -1,20 +1,31 @@
|
|
|
1
|
-
// Maps stack frames of the bundle back to the app's files with
|
|
2
|
-
// `at name (main.bundle.js:8161:20)` becomes `at name (src/app/index.vue:22:9)`. Consecutive
|
|
1
|
+
// Maps stack frames of the bundle (and of hot updates) back to the app's files with their source maps:
|
|
2
|
+
// Hermes' `at name (main.bundle.js:8161:20)` becomes `at name (src/app/index.vue:22:9)`. Consecutive
|
|
3
3
|
// frames from outside src/ (Vue, nativue, Hermes' native ones) collapse into one line, so the app's
|
|
4
4
|
// own frames stand out. Other lines are kept.
|
|
5
5
|
import { SourceMap } from 'node:module'
|
|
6
6
|
import { relative, resolve } from 'node:path'
|
|
7
7
|
|
|
8
|
-
// Groups: before the location, the location's line and column, after it.
|
|
9
|
-
const HERMES_FRAME = /^(\s*at .* \()(
|
|
8
|
+
// Groups: before the location, the file, the location's line and column, after it.
|
|
9
|
+
const HERMES_FRAME = /^(\s*at .* \()(?:.*\/)?([^/()]+\.js):(\d+):(\d+)(\))$/
|
|
10
10
|
const HERMES_NATIVE_FRAME = /^\s*at .* \(native\)$/
|
|
11
11
|
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
12
|
+
export function framedFiles(text) {
|
|
13
|
+
return new Set(text.split('\n').flatMap((line) => HERMES_FRAME.exec(line)?.[2] ?? []))
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
// sourceMapsByFile: for each file (main.bundle.js, a hot update), { sourceMap: the map as JSON,
|
|
17
|
+
// directory: the one its sources are relative to, lineOffset: how many lines above the file's first
|
|
18
|
+
// line the map starts }.
|
|
19
|
+
export function createSymbolicator(sourceMapsByFile) {
|
|
20
|
+
const mapsByFile = new Map(
|
|
21
|
+
Object.entries(sourceMapsByFile).map(([file, { sourceMap, directory, lineOffset = 0 }]) => [
|
|
22
|
+
file,
|
|
23
|
+
{ sourceMap: new SourceMap(sourceMap), directory, lineOffset },
|
|
24
|
+
]),
|
|
25
|
+
)
|
|
15
26
|
|
|
16
|
-
function displayPath(source) {
|
|
17
|
-
const absolutePath = resolve(
|
|
27
|
+
function displayPath(directory, source) {
|
|
28
|
+
const absolutePath = resolve(directory, source)
|
|
18
29
|
const nodeModulesIndex = absolutePath.lastIndexOf('node_modules/')
|
|
19
30
|
|
|
20
31
|
return nodeModulesIndex === -1
|
|
@@ -26,14 +37,15 @@ export function createSymbolicator(sourceMapPayload, bundleDirectory) {
|
|
|
26
37
|
function symbolicateLine(line) {
|
|
27
38
|
if (HERMES_NATIVE_FRAME.test(line)) return { text: line, isInternal: true }
|
|
28
39
|
|
|
29
|
-
const
|
|
30
|
-
|
|
40
|
+
const [, before, file, lineNumber, columnNumber, after] = HERMES_FRAME.exec(line) ?? []
|
|
41
|
+
const map = mapsByFile.get(file)
|
|
42
|
+
if (!map) return { text: line, isInternal: false }
|
|
31
43
|
|
|
32
|
-
const
|
|
33
|
-
const entry = sourceMap.findEntry(Number(lineNumber) - 1, Number(columnNumber) - 1)
|
|
44
|
+
const { sourceMap, directory, lineOffset } = map
|
|
45
|
+
const entry = sourceMap.findEntry(Number(lineNumber) - 1 - lineOffset, Number(columnNumber) - 1)
|
|
34
46
|
if (!entry.originalSource) return { text: line, isInternal: false }
|
|
35
47
|
|
|
36
|
-
const path = displayPath(entry.originalSource)
|
|
48
|
+
const path = displayPath(directory, entry.originalSource)
|
|
37
49
|
const text = `${before}${path}:${entry.originalLine + 1}:${entry.originalColumn + 1}${after}`
|
|
38
50
|
|
|
39
51
|
return { text, isInternal: !path.startsWith('src/') }
|
|
@@ -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,8 +34,13 @@ 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()
|
|
42
|
+
/// Kept on the JS queue: the router's screens, reopened after a reload in development.
|
|
43
|
+
private var savedNavigation: String?
|
|
39
44
|
|
|
40
45
|
// Only touched on the main thread.
|
|
41
46
|
var rootView: RootView!
|
|
@@ -53,6 +58,9 @@ final class Bridge {
|
|
|
53
58
|
/// The bundle running now, for the error overlay's Reload.
|
|
54
59
|
private var bundle = Data()
|
|
55
60
|
private let errorOverlay = ErrorOverlay()
|
|
61
|
+
#if DEBUG
|
|
62
|
+
private let downloadBanner = DownloadBanner()
|
|
63
|
+
#endif
|
|
56
64
|
private let pluginRegistry: PluginRegistry
|
|
57
65
|
|
|
58
66
|
init(plugins: [NativuePlugin]) {
|
|
@@ -88,6 +96,23 @@ final class Bridge {
|
|
|
88
96
|
}
|
|
89
97
|
}
|
|
90
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
|
+
|
|
91
116
|
NotificationCenter.default.addObserver(forName: Self.openURLNotification, object: nil, queue: .main) {
|
|
92
117
|
[unowned self] notification in
|
|
93
118
|
guard let url = notification.object as? URL else { return }
|
|
@@ -101,12 +126,20 @@ final class Bridge {
|
|
|
101
126
|
run(try! Data(contentsOf: bundleURL))
|
|
102
127
|
#if DEBUG
|
|
103
128
|
Task { await listenForReload() }
|
|
129
|
+
rootView.onReloadShortcut = { [unowned self] in Task { try? await reload() } }
|
|
104
130
|
#endif
|
|
105
131
|
}
|
|
106
132
|
|
|
107
133
|
/// Discards the current node tree and runtime, then runs the bundle from scratch: JavaScript, or
|
|
108
134
|
/// Hermes bytecode (production builds).
|
|
109
135
|
func run(_ bundle: Data) {
|
|
136
|
+
// UIKit ignores a dismissal while a modal is presenting or dismissing, so resetNodeTree would leave
|
|
137
|
+
// the old tree's modal up, and the new tree's couldn't present.
|
|
138
|
+
if let transition = modalTransitionInProgress() {
|
|
139
|
+
transition.animate(alongsideTransition: nil) { [unowned self] _ in run(bundle) }
|
|
140
|
+
return
|
|
141
|
+
}
|
|
142
|
+
|
|
110
143
|
self.bundle = bundle
|
|
111
144
|
errorOverlay.hide()
|
|
112
145
|
|
|
@@ -118,6 +151,16 @@ final class Bridge {
|
|
|
118
151
|
}
|
|
119
152
|
}
|
|
120
153
|
|
|
154
|
+
private func modalTransitionInProgress() -> UIViewControllerTransitionCoordinator? {
|
|
155
|
+
guard let presentedViewController = rootView.window?.rootViewController?.presentedViewController else {
|
|
156
|
+
return nil
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
return sequence(first: presentedViewController, next: \.presentedViewController)
|
|
160
|
+
.compactMap(\.transitionCoordinator)
|
|
161
|
+
.last
|
|
162
|
+
}
|
|
163
|
+
|
|
121
164
|
/// Runs `work` on the JS queue, then applies every native operation it produced, in one batch, on the
|
|
122
165
|
/// main thread. The runtime drains promise jobs after each call, so Vue's updates are included.
|
|
123
166
|
func evaluate(_ work: @escaping () -> Void) {
|
|
@@ -157,15 +200,35 @@ final class Bridge {
|
|
|
157
200
|
}
|
|
158
201
|
|
|
159
202
|
/// Results reaching a runtime that has since been reloaded are dropped: call ids start over in the new one.
|
|
160
|
-
private func finishAsyncFunction(_ callId: Int, owner: JavaScriptRuntime?, value: Any?,
|
|
203
|
+
private func finishAsyncFunction(_ callId: Int, owner: JavaScriptRuntime?, value: Any?, error: Error?) {
|
|
161
204
|
evaluate { [unowned self] in
|
|
162
205
|
guard runtime === owner else { return }
|
|
163
206
|
|
|
164
|
-
let
|
|
207
|
+
let errorCode = (error as? PluginError)?.code
|
|
208
|
+
let arguments: [Any] = [
|
|
209
|
+
callId, value ?? NSNull(), error?.localizedDescription ?? NSNull(), errorCode ?? NSNull(),
|
|
210
|
+
]
|
|
211
|
+
|
|
165
212
|
runtime?.call("__asyncFunctionFinished", arguments: arguments)
|
|
166
213
|
}
|
|
167
214
|
}
|
|
168
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
|
+
|
|
169
232
|
private static func colorScheme(of traits: UITraitCollection) -> String {
|
|
170
233
|
traits.userInterfaceStyle == .dark ? "dark" : "light"
|
|
171
234
|
}
|
|
@@ -207,22 +270,49 @@ final class Bridge {
|
|
|
207
270
|
#if DEBUG
|
|
208
271
|
@MainActor func listenForReload() async {
|
|
209
272
|
let eventsURL = Self.devServerURL.appendingPathComponent("events")
|
|
210
|
-
let bundleURL = Self.devServerURL.appendingPathComponent("bundle.js")
|
|
211
273
|
|
|
212
274
|
while true {
|
|
213
275
|
do {
|
|
214
276
|
let (events, _) = try await URLSession.shared.bytes(from: eventsURL)
|
|
215
277
|
|
|
216
|
-
for try await line in events.lines
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
278
|
+
for try await line in events.lines {
|
|
279
|
+
if line == "data: reload" {
|
|
280
|
+
try await reload()
|
|
281
|
+
} else if line.hasPrefix("data: hot ") {
|
|
282
|
+
let update = String(line.dropFirst("data: hot ".count))
|
|
283
|
+
evaluate { [unowned self] in runtime?.call("__hotUpdate", arguments: [update]) }
|
|
284
|
+
}
|
|
220
285
|
}
|
|
221
286
|
} catch {}
|
|
222
287
|
|
|
223
288
|
try? await Task.sleep(nanoseconds: 2_000_000_000) // dev server is down: retry
|
|
224
289
|
}
|
|
225
290
|
}
|
|
291
|
+
|
|
292
|
+
@MainActor func reload() async throws {
|
|
293
|
+
let data = try await download(Self.devServerURL.appendingPathComponent("bundle.js"))
|
|
294
|
+
print("[Nativue] reload")
|
|
295
|
+
run(data)
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
@MainActor private func download(_ url: URL) async throws -> Data {
|
|
299
|
+
try await withCheckedThrowingContinuation { continuation in
|
|
300
|
+
var observation: NSKeyValueObservation?
|
|
301
|
+
let task = URLSession.shared.dataTask(with: url) { [unowned self] data, _, error in
|
|
302
|
+
DispatchQueue.main.async {
|
|
303
|
+
observation?.invalidate()
|
|
304
|
+
self.downloadBanner.hide()
|
|
305
|
+
if let data { continuation.resume(returning: data) } else { continuation.resume(throwing: error!) }
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
observation = task.observe(\.countOfBytesReceived) { [unowned self] task, _ in
|
|
309
|
+
let progress = Double(task.countOfBytesReceived) / Double(max(task.countOfBytesExpectedToReceive, 1))
|
|
310
|
+
DispatchQueue.main.async { self.downloadBanner.show(progress: progress) }
|
|
311
|
+
}
|
|
312
|
+
downloadBanner.show(progress: 0)
|
|
313
|
+
task.resume()
|
|
314
|
+
}
|
|
315
|
+
}
|
|
226
316
|
#endif
|
|
227
317
|
|
|
228
318
|
// MARK: - JS queue
|
|
@@ -268,6 +358,14 @@ final class Bridge {
|
|
|
268
358
|
DispatchQueue.main.async { UIAccessibility.post(notification: .announcement, argument: message) }
|
|
269
359
|
}
|
|
270
360
|
|
|
361
|
+
defineGetter("openSettings") { _ in
|
|
362
|
+
DispatchQueue.main.async {
|
|
363
|
+
UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!)
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
return true
|
|
367
|
+
}
|
|
368
|
+
|
|
271
369
|
// Prefixed, so a plugin can't replace nativue's own functions.
|
|
272
370
|
for (name, function) in pluginRegistry.functions {
|
|
273
371
|
defineGetter("plugin:\(name)", function)
|
|
@@ -282,15 +380,18 @@ final class Bridge {
|
|
|
282
380
|
Task {
|
|
283
381
|
do {
|
|
284
382
|
let value = try await function(Array(arguments.dropFirst()))
|
|
285
|
-
finishAsyncFunction(callId, owner: owner, value: value,
|
|
383
|
+
finishAsyncFunction(callId, owner: owner, value: value, error: nil)
|
|
286
384
|
} catch {
|
|
287
|
-
finishAsyncFunction(callId, owner: owner, value: nil,
|
|
385
|
+
finishAsyncFunction(callId, owner: owner, value: nil, error: error)
|
|
288
386
|
}
|
|
289
387
|
}
|
|
290
388
|
}
|
|
291
389
|
}
|
|
292
390
|
|
|
293
391
|
defineGetter("colorScheme") { [unowned self] _ in colorScheme }
|
|
392
|
+
defineGetter("appState") { [unowned self] _ in appState }
|
|
393
|
+
defineGetter("savedNavigation") { [unowned self] _ in savedNavigation }
|
|
394
|
+
define("saveNavigation") { [unowned self] arguments in savedNavigation = arguments[0] as? String }
|
|
294
395
|
|
|
295
396
|
define("create") { [unowned self] arguments in
|
|
296
397
|
let (id, type) = (int(arguments[0]), string(arguments[1]))
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import UIKit
|
|
2
|
+
|
|
3
|
+
/// Development only: a strip at the top of the screen while the app downloads the dev server's bundle.
|
|
4
|
+
final class DownloadBanner {
|
|
5
|
+
private var window: UIWindow?
|
|
6
|
+
private let label = UILabel()
|
|
7
|
+
|
|
8
|
+
func show(progress: Double) {
|
|
9
|
+
if window == nil { makeWindow() }
|
|
10
|
+
|
|
11
|
+
label.text = "Downloading \(Int(progress * 100))%"
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
func hide() {
|
|
15
|
+
window?.isHidden = true
|
|
16
|
+
window = nil
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
private func makeWindow() {
|
|
20
|
+
guard let scene = UIApplication.shared.connectedScenes.first as? UIWindowScene else { return }
|
|
21
|
+
|
|
22
|
+
let topInset = scene.windows.first?.safeAreaInsets.top ?? 0
|
|
23
|
+
let window = UIWindow(windowScene: scene)
|
|
24
|
+
window.frame = CGRect(x: 0, y: 0, width: scene.screen.bounds.width, height: topInset + 24)
|
|
25
|
+
window.windowLevel = .alert + 2
|
|
26
|
+
window.isUserInteractionEnabled = false
|
|
27
|
+
window.backgroundColor = UIColor(red: 0.04, green: 0.07, blue: 0.13, alpha: 1)
|
|
28
|
+
|
|
29
|
+
label.frame = CGRect(x: 0, y: topInset, width: window.frame.width, height: 24)
|
|
30
|
+
label.font = .systemFont(ofSize: 12, weight: .semibold)
|
|
31
|
+
label.textColor = UIColor(red: 0.95, green: 0.96, blue: 0.98, alpha: 1)
|
|
32
|
+
label.textAlignment = .center
|
|
33
|
+
window.addSubview(label)
|
|
34
|
+
|
|
35
|
+
window.isHidden = false
|
|
36
|
+
self.window = window
|
|
37
|
+
}
|
|
38
|
+
}
|