@nativue/core 0.2.0 → 0.3.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/android/consumer-rules.pro +3 -0
- package/android/nativue.settings.gradle.kts +56 -0
- package/android/src/main/java/dev/nativue/Bridge.kt +51 -7
- package/android/src/main/java/dev/nativue/ModalHost.kt +2 -2
- package/android/src/main/java/dev/nativue/NativueActivity.kt +8 -0
- package/android/src/main/java/dev/nativue/Navigation.kt +32 -24
- package/android/src/main/java/dev/nativue/Plugins.kt +75 -0
- package/android/src/main/java/dev/nativue/Style.kt +5 -1
- package/android/src/main/java/dev/nativue/Theme.kt +61 -0
- package/android/src/main/java/dev/nativue/Views.kt +14 -2
- package/cli/config.d.mts +19 -0
- package/cli/config.mjs +4 -0
- package/cli/link.mjs +129 -0
- package/cli/nativue.mjs +48 -1
- package/ios/Bridge.swift +75 -2
- package/ios/NativeNode.swift +1 -0
- package/ios/NativueView.swift +10 -3
- package/ios/Plugins.swift +45 -0
- package/ios/Style.swift +14 -1
- package/package.json +7 -2
- package/src/appearance.ts +49 -0
- package/src/components.ts +3 -1
- package/src/entry.ts +2 -1
- package/src/globals.ts +3 -0
- package/src/native-functions.ts +41 -0
- package/src/renderer.ts +58 -1
- package/src/types.ts +2 -0
- package/src/virtual-modules.d.ts +2 -0
package/cli/link.mjs
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
// Links the iOS side of the app's packages: those whose package.json has
|
|
2
|
+
// "nativue": { "ios": { "sources": "ios", "plugin": "HapticsPlugin" } }
|
|
3
|
+
// ios/NativuePlugins becomes a Swift package with a target per package (a link to its sources) and
|
|
4
|
+
// `nativuePlugins`, the list App.swift passes to NativueView. The app's Xcode project depends on it
|
|
5
|
+
// alone; it re-exports Nativue. (Android finds them itself: android/nativue.settings.gradle.kts.)
|
|
6
|
+
import {
|
|
7
|
+
existsSync,
|
|
8
|
+
mkdirSync,
|
|
9
|
+
readdirSync,
|
|
10
|
+
readFileSync,
|
|
11
|
+
readlinkSync,
|
|
12
|
+
rmSync,
|
|
13
|
+
symlinkSync,
|
|
14
|
+
writeFileSync,
|
|
15
|
+
} from 'node:fs'
|
|
16
|
+
import { dirname, join, relative, resolve } from 'node:path'
|
|
17
|
+
|
|
18
|
+
const PLUGINS_DIRECTORY = 'ios/NativuePlugins'
|
|
19
|
+
const SOURCES_DIRECTORY = `${PLUGINS_DIRECTORY}/Sources`
|
|
20
|
+
const LIST_TARGET = 'NativuePlugins'
|
|
21
|
+
|
|
22
|
+
function readJson(path) {
|
|
23
|
+
return JSON.parse(readFileSync(path, 'utf8'))
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** node_modules/<name>, looked up the way Node does: in the app's folder, then in its parents. */
|
|
27
|
+
function packageDirectory(name) {
|
|
28
|
+
for (let directory = process.cwd(); ; directory = dirname(directory)) {
|
|
29
|
+
const candidate = join(directory, 'node_modules', name)
|
|
30
|
+
if (existsSync(join(candidate, 'package.json'))) return candidate
|
|
31
|
+
if (directory === dirname(directory)) return null
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** '@nativue/haptics' -> 'NativueHaptics', the Swift module of its sources. */
|
|
36
|
+
function moduleName(packageName) {
|
|
37
|
+
return packageName
|
|
38
|
+
.split(/[^a-zA-Z0-9]+/)
|
|
39
|
+
.filter(Boolean)
|
|
40
|
+
.map((word) => word[0].toUpperCase() + word.slice(1))
|
|
41
|
+
.join('')
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function iosPlugins() {
|
|
45
|
+
const { dependencies = {}, devDependencies = {} } = readJson('package.json')
|
|
46
|
+
const names = [...Object.keys(dependencies), ...Object.keys(devDependencies)]
|
|
47
|
+
|
|
48
|
+
return names.flatMap((name) => {
|
|
49
|
+
const directory = packageDirectory(name)
|
|
50
|
+
const ios = directory && readJson(join(directory, 'package.json')).nativue?.ios
|
|
51
|
+
if (!ios) return []
|
|
52
|
+
|
|
53
|
+
return [{ module: moduleName(name), sources: join(directory, ios.sources), plugin: ios.plugin }]
|
|
54
|
+
})
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function writeIfChanged(path, content) {
|
|
58
|
+
if (existsSync(path) && readFileSync(path, 'utf8') === content) return
|
|
59
|
+
|
|
60
|
+
mkdirSync(dirname(path), { recursive: true })
|
|
61
|
+
writeFileSync(path, content)
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Sources/<module> -> the package's sources; links of packages the app no longer has are removed. */
|
|
65
|
+
function linkSources(plugins) {
|
|
66
|
+
const linkTargets = new Map(
|
|
67
|
+
plugins.map((plugin) => [plugin.module, relative(SOURCES_DIRECTORY, plugin.sources)]),
|
|
68
|
+
)
|
|
69
|
+
mkdirSync(SOURCES_DIRECTORY, { recursive: true })
|
|
70
|
+
|
|
71
|
+
for (const entry of readdirSync(SOURCES_DIRECTORY)) {
|
|
72
|
+
if (entry !== LIST_TARGET && !linkTargets.has(entry)) rmSync(join(SOURCES_DIRECTORY, entry))
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
for (const [module, target] of linkTargets) {
|
|
76
|
+
const link = join(SOURCES_DIRECTORY, module)
|
|
77
|
+
if (existsSync(link) && readlinkSync(link) === target) continue
|
|
78
|
+
|
|
79
|
+
rmSync(link, { force: true })
|
|
80
|
+
symlinkSync(target, link)
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function packageManifest(plugins, corePath) {
|
|
85
|
+
const nativue = '.product(name: "Nativue", package: "core")'
|
|
86
|
+
const pluginTargets = plugins.map(
|
|
87
|
+
({ module }) =>
|
|
88
|
+
` .target(name: "${module}", dependencies: [${nativue}], path: "Sources/${module}"),\n`,
|
|
89
|
+
)
|
|
90
|
+
const listDependencies = [nativue, ...plugins.map(({ module }) => `"${module}"`)].join(', ')
|
|
91
|
+
|
|
92
|
+
return `// swift-tools-version: 5.9
|
|
93
|
+
// Generated by nativue from the app's packages (packages/core/cli/link.mjs): rewritten on every build.
|
|
94
|
+
import PackageDescription
|
|
95
|
+
|
|
96
|
+
let package = Package(
|
|
97
|
+
name: "NativuePlugins",
|
|
98
|
+
platforms: [.iOS(.v17)],
|
|
99
|
+
products: [.library(name: "NativuePlugins", targets: ["${LIST_TARGET}"])],
|
|
100
|
+
dependencies: [.package(path: "${corePath}")],
|
|
101
|
+
targets: [
|
|
102
|
+
${pluginTargets.join('')} .target(name: "${LIST_TARGET}", dependencies: [${listDependencies}], path: "Sources/${LIST_TARGET}"),
|
|
103
|
+
]
|
|
104
|
+
)
|
|
105
|
+
`
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function pluginList(plugins) {
|
|
109
|
+
const imports = plugins.map(({ module }) => `import ${module}\n`).join('')
|
|
110
|
+
const instances = plugins.map(({ plugin }) => `${plugin}()`).join(', ')
|
|
111
|
+
|
|
112
|
+
return `// Generated by nativue from the app's packages (packages/core/cli/link.mjs): rewritten on every build.
|
|
113
|
+
@_exported import Nativue
|
|
114
|
+
${imports}
|
|
115
|
+
public let nativuePlugins: [NativuePlugin] = [${instances}]
|
|
116
|
+
`
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** coreDirectory: @nativue/core's folder, which holds its Package.swift. */
|
|
120
|
+
export function linkIosPlugins(coreDirectory) {
|
|
121
|
+
if (!existsSync('ios') || !existsSync('package.json')) return
|
|
122
|
+
|
|
123
|
+
const plugins = iosPlugins()
|
|
124
|
+
const corePath = relative(resolve(PLUGINS_DIRECTORY), coreDirectory)
|
|
125
|
+
|
|
126
|
+
linkSources(plugins)
|
|
127
|
+
writeIfChanged(`${PLUGINS_DIRECTORY}/Package.swift`, packageManifest(plugins, corePath))
|
|
128
|
+
writeIfChanged(`${SOURCES_DIRECTORY}/${LIST_TARGET}/Plugins.swift`, pluginList(plugins))
|
|
129
|
+
}
|
package/cli/nativue.mjs
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
// nativue dev rebuilds on save and tells the app (via SSE) to reload the bundle
|
|
7
7
|
// nativue run <ios | android> builds, installs and opens the app on a simulator or emulator, then
|
|
8
8
|
// keeps going as `nativue dev` (unless one is already running)
|
|
9
|
-
import { build } from 'vite'
|
|
9
|
+
import { build, loadConfigFromFile } from 'vite'
|
|
10
10
|
import vue from '@vitejs/plugin-vue'
|
|
11
11
|
import http from 'node:http'
|
|
12
12
|
import net from 'node:net'
|
|
@@ -15,6 +15,7 @@ import { copyFileSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync }
|
|
|
15
15
|
import { createRequire } from 'node:module'
|
|
16
16
|
import { dirname } from 'node:path'
|
|
17
17
|
import { fileURLToPath } from 'node:url'
|
|
18
|
+
import { linkIosPlugins } from './link.mjs'
|
|
18
19
|
import { runOnAndroid, runOnIOS } from './run.mjs'
|
|
19
20
|
import { createSymbolicator } from './symbolicate.mjs'
|
|
20
21
|
|
|
@@ -84,6 +85,49 @@ function finishBundle(mode) {
|
|
|
84
85
|
}
|
|
85
86
|
}
|
|
86
87
|
|
|
88
|
+
const CONFIG_FILES = [
|
|
89
|
+
'nativue.config.ts',
|
|
90
|
+
'nativue.config.mts',
|
|
91
|
+
'nativue.config.js',
|
|
92
|
+
'nativue.config.mjs',
|
|
93
|
+
]
|
|
94
|
+
const PLUGIN_RUNTIMES_MODULE = 'virtual:nativue/plugin-runtimes'
|
|
95
|
+
|
|
96
|
+
// nativue.config.ts, when the app has one (see config.d.mts).
|
|
97
|
+
async function loadAppConfig() {
|
|
98
|
+
const configFile = CONFIG_FILES.find((file) => existsSync(file))
|
|
99
|
+
if (!configFile) return {}
|
|
100
|
+
|
|
101
|
+
const { config } = await loadConfigFromFile(
|
|
102
|
+
{ command: 'build', mode: 'development' },
|
|
103
|
+
configFile,
|
|
104
|
+
process.cwd(),
|
|
105
|
+
'silent',
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
return config
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// The entry imports this module first: it imports each plugin's runtime module.
|
|
112
|
+
function pluginRuntimes(plugins) {
|
|
113
|
+
const resolvedId = `\0${PLUGIN_RUNTIMES_MODULE}`
|
|
114
|
+
const imports = plugins
|
|
115
|
+
.filter((plugin) => plugin.runtime)
|
|
116
|
+
.map((plugin) => `import ${JSON.stringify(plugin.runtime)}`)
|
|
117
|
+
|
|
118
|
+
return {
|
|
119
|
+
name: 'nativue-plugin-runtimes',
|
|
120
|
+
resolveId: (id) => (id === PLUGIN_RUNTIMES_MODULE ? resolvedId : null),
|
|
121
|
+
load: (id) => (id === resolvedId ? imports.join('\n') : null),
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const { plugins: appPlugins = [] } = await loadAppConfig()
|
|
126
|
+
const APP_VITE_PLUGINS = [
|
|
127
|
+
pluginRuntimes(appPlugins),
|
|
128
|
+
...appPlugins.flatMap((plugin) => plugin.vite ?? []),
|
|
129
|
+
]
|
|
130
|
+
|
|
87
131
|
function viteConfig({ mode, plugins = [], watch = null, sourcemap = false }) {
|
|
88
132
|
// Vite reads the mode from NODE_ENV: development builds keep each component's file (for errors).
|
|
89
133
|
process.env.NODE_ENV = mode
|
|
@@ -98,6 +142,7 @@ function viteConfig({ mode, plugins = [], watch = null, sourcemap = false }) {
|
|
|
98
142
|
compilerOptions: { isCustomElement: (tag) => NATIVE_COMPONENT_TAGS.includes(tag) },
|
|
99
143
|
},
|
|
100
144
|
}),
|
|
145
|
+
...APP_VITE_PLUGINS,
|
|
101
146
|
finishBundle(mode),
|
|
102
147
|
...plugins,
|
|
103
148
|
],
|
|
@@ -213,6 +258,8 @@ async function runApp(platform) {
|
|
|
213
258
|
const [command, ...args] = process.argv.slice(2)
|
|
214
259
|
|
|
215
260
|
try {
|
|
261
|
+
if (['dev', 'build', 'run'].includes(command)) linkIosPlugins(frameworkPath(''))
|
|
262
|
+
|
|
216
263
|
if (command === 'dev') {
|
|
217
264
|
await dev()
|
|
218
265
|
} else if (command === 'build') {
|
package/ios/Bridge.swift
CHANGED
|
@@ -34,6 +34,8 @@ final class Bridge {
|
|
|
34
34
|
private lazy var storage = KeyValueStorage(javaScriptQueue: javaScriptQueue)
|
|
35
35
|
/// Set by LayoutAnimation.configureNext in JS; animates the batch it's sent with.
|
|
36
36
|
private var nextLayoutAnimation: LayoutAnimation?
|
|
37
|
+
/// Appearance.getColorScheme(): read on the main thread at start, then kept up to date.
|
|
38
|
+
private var colorScheme = "light"
|
|
37
39
|
|
|
38
40
|
// Only touched on the main thread.
|
|
39
41
|
var rootView: RootView!
|
|
@@ -47,11 +49,25 @@ final class Bridge {
|
|
|
47
49
|
/// The bundle running now, for the error overlay's Reload.
|
|
48
50
|
private var bundle = Data()
|
|
49
51
|
private let errorOverlay = ErrorOverlay()
|
|
52
|
+
private let pluginRegistry: PluginRegistry
|
|
53
|
+
|
|
54
|
+
init(plugins: [NativuePlugin]) {
|
|
55
|
+
pluginRegistry = PluginRegistry(plugins: plugins)
|
|
56
|
+
}
|
|
50
57
|
|
|
51
58
|
func start(rootView: RootView) {
|
|
52
59
|
self.rootView = rootView
|
|
53
60
|
rootView.onLayoutSubviews = { [unowned self] in layout() }
|
|
54
|
-
|
|
61
|
+
let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene
|
|
62
|
+
windowSize = windowScene?.screen.bounds.size ?? .zero
|
|
63
|
+
colorScheme = Self.colorScheme(of: windowScene?.traitCollection ?? rootView.traitCollection)
|
|
64
|
+
// start runs on the main thread, from makeUIView.
|
|
65
|
+
MainActor.assumeIsolated {
|
|
66
|
+
_ = rootView.registerForTraitChanges([UITraitUserInterfaceStyle.self]) {
|
|
67
|
+
[unowned self] (rootView: RootView, _: UITraitCollection) in
|
|
68
|
+
colorSchemeDidChange(to: Self.colorScheme(of: rootView.traitCollection))
|
|
69
|
+
}
|
|
70
|
+
}
|
|
55
71
|
|
|
56
72
|
NotificationCenter.default.addObserver(forName: Self.openURLNotification, object: nil, queue: .main) {
|
|
57
73
|
[unowned self] notification in
|
|
@@ -120,6 +136,26 @@ final class Bridge {
|
|
|
120
136
|
}
|
|
121
137
|
}
|
|
122
138
|
|
|
139
|
+
private func finishAsyncFunction(_ callId: Int, value: Any?, errorMessage: String?) {
|
|
140
|
+
evaluate { [unowned self] in
|
|
141
|
+
let arguments: [Any] = [callId, value ?? NSNull(), errorMessage ?? NSNull()]
|
|
142
|
+
runtime?.call("__asyncFunctionFinished", arguments: arguments)
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
private static func colorScheme(of traits: UITraitCollection) -> String {
|
|
147
|
+
traits.userInterfaceStyle == .dark ? "dark" : "light"
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
private func colorSchemeDidChange(to nextColorScheme: String) {
|
|
151
|
+
evaluate { [unowned self] in
|
|
152
|
+
guard nextColorScheme != colorScheme else { return }
|
|
153
|
+
|
|
154
|
+
colorScheme = nextColorScheme
|
|
155
|
+
runtime?.call("__colorSchemeChanged", arguments: [nextColorScheme])
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
123
159
|
/// Queued on the JS queue, so a URL that opens the app arrives after the bundle has run.
|
|
124
160
|
private func openURL(_ url: URL) {
|
|
125
161
|
evaluate { [unowned self] in
|
|
@@ -188,6 +224,31 @@ final class Bridge {
|
|
|
188
224
|
["width": windowSize.width, "height": windowSize.height]
|
|
189
225
|
}
|
|
190
226
|
|
|
227
|
+
defineGetter("platform") { _ in "ios" }
|
|
228
|
+
|
|
229
|
+
// Prefixed, so a plugin can't replace nativue's own functions.
|
|
230
|
+
for (name, function) in pluginRegistry.functions {
|
|
231
|
+
defineGetter("plugin:\(name)", function)
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
// (callId, ...arguments): settles the call with __asyncFunctionFinished.
|
|
235
|
+
for (name, function) in pluginRegistry.asyncFunctions {
|
|
236
|
+
define("pluginAsync:\(name)") { [unowned self] arguments in
|
|
237
|
+
let callId = int(arguments[0])
|
|
238
|
+
|
|
239
|
+
Task {
|
|
240
|
+
do {
|
|
241
|
+
let value = try await function(Array(arguments.dropFirst()))
|
|
242
|
+
finishAsyncFunction(callId, value: value, errorMessage: nil)
|
|
243
|
+
} catch {
|
|
244
|
+
finishAsyncFunction(callId, value: nil, errorMessage: error.localizedDescription)
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
defineGetter("colorScheme") { [unowned self] _ in colorScheme }
|
|
251
|
+
|
|
191
252
|
define("create") { [unowned self] arguments in
|
|
192
253
|
let (id, type) = (int(arguments[0]), string(arguments[1]))
|
|
193
254
|
enqueue { [unowned self] in nodesById[id] = makeNode(type: type, id: id) }
|
|
@@ -420,7 +481,14 @@ final class Bridge {
|
|
|
420
481
|
return node
|
|
421
482
|
|
|
422
483
|
default:
|
|
423
|
-
|
|
484
|
+
guard let makeView = pluginRegistry.viewMakers[type] else {
|
|
485
|
+
return NativeNode(view: UIView(), measuresContent: false)
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
let view = makeView { [unowned self] eventName, payload in
|
|
489
|
+
dispatchEvent(eventName, toNodeId: id, payload: payload)
|
|
490
|
+
}
|
|
491
|
+
return NativeNode(view: view, measuresContent: false)
|
|
424
492
|
}
|
|
425
493
|
}
|
|
426
494
|
|
|
@@ -590,6 +658,11 @@ final class Bridge {
|
|
|
590
658
|
private func setProp(_ key: String, value: Any?, onNodeId id: Int) {
|
|
591
659
|
guard let node = nodesById[id] else { return }
|
|
592
660
|
|
|
661
|
+
if key != "style", let pluginView = node.view as? PluginView {
|
|
662
|
+
pluginView.setProp(key, value: value is NSNull ? nil : value)
|
|
663
|
+
return
|
|
664
|
+
}
|
|
665
|
+
|
|
593
666
|
switch key {
|
|
594
667
|
case "title":
|
|
595
668
|
(node.view as? UIButton)?.setTitle(value as? String, for: .normal)
|
package/ios/NativeNode.swift
CHANGED
package/ios/NativueView.swift
CHANGED
|
@@ -3,18 +3,25 @@ import SwiftUI
|
|
|
3
3
|
/// The whole app: runs main.bundle.js (or the dev server's bundle) and shows what it renders.
|
|
4
4
|
/// It fills the whole screen; <SafeAreaView> opts into the safe area.
|
|
5
5
|
public struct NativueView: View {
|
|
6
|
-
|
|
6
|
+
private let plugins: [NativuePlugin]
|
|
7
|
+
|
|
8
|
+
/// plugins: the native side of the app's packages, `nativuePlugins` from ios/NativuePlugins.
|
|
9
|
+
public init(plugins: [NativuePlugin] = []) {
|
|
10
|
+
self.plugins = plugins
|
|
11
|
+
}
|
|
7
12
|
|
|
8
13
|
public var body: some View {
|
|
9
|
-
VueRoot()
|
|
14
|
+
VueRoot(plugins: plugins)
|
|
10
15
|
.ignoresSafeArea()
|
|
11
16
|
.onOpenURL { url in NotificationCenter.default.post(name: Bridge.openURLNotification, object: url) }
|
|
12
17
|
}
|
|
13
18
|
}
|
|
14
19
|
|
|
15
20
|
struct VueRoot: UIViewRepresentable {
|
|
21
|
+
let plugins: [NativuePlugin]
|
|
22
|
+
|
|
16
23
|
func makeCoordinator() -> Bridge {
|
|
17
|
-
Bridge()
|
|
24
|
+
Bridge(plugins: plugins)
|
|
18
25
|
}
|
|
19
26
|
|
|
20
27
|
func makeUIView(context: Context) -> RootView {
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import UIKit
|
|
2
|
+
|
|
3
|
+
/// The native side of a package: functions JavaScript calls (`requireNativeFunction`) and views it
|
|
4
|
+
/// renders. Packages declare their plugin in package.json; the CLI links them into the app
|
|
5
|
+
/// (ios/NativuePlugins) and the app passes them on: `NativueView(plugins: nativuePlugins)`.
|
|
6
|
+
public protocol NativuePlugin {
|
|
7
|
+
func register(in registry: PluginRegistry)
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
public final class PluginRegistry {
|
|
11
|
+
public typealias Function = (_ arguments: [Any]) -> Any?
|
|
12
|
+
/// Its result resolves the JavaScript call's Promise; a thrown error rejects it.
|
|
13
|
+
public typealias AsyncFunction = (_ arguments: [Any]) async throws -> Any?
|
|
14
|
+
/// sendEvent("change", payload) reaches the element's @change; event names are lowercase.
|
|
15
|
+
public typealias SendEvent = (_ eventName: String, _ payload: Any?) -> Void
|
|
16
|
+
public typealias MakeView = (_ sendEvent: @escaping SendEvent) -> UIView
|
|
17
|
+
|
|
18
|
+
private(set) var functions: [String: Function] = [:]
|
|
19
|
+
private(set) var asyncFunctions: [String: AsyncFunction] = [:]
|
|
20
|
+
private(set) var viewMakers: [String: MakeView] = [:]
|
|
21
|
+
|
|
22
|
+
init(plugins: [NativuePlugin]) {
|
|
23
|
+
plugins.forEach { $0.register(in: self) }
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/// Runs on the JavaScript thread and returns synchronously: hop to the main thread for UIKit.
|
|
27
|
+
public func addFunction(_ name: String, _ function: @escaping Function) {
|
|
28
|
+
functions[name] = function
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/// For work that takes time (a permission prompt, the camera): JavaScript gets a Promise.
|
|
32
|
+
public func addAsyncFunction(_ name: String, _ function: @escaping AsyncFunction) {
|
|
33
|
+
asyncFunctions[name] = function
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/// `type` is the element's tag, e.g. "MapView" for h('MapView'). Created on the main thread.
|
|
37
|
+
public func addView(_ type: String, _ makeView: @escaping MakeView) {
|
|
38
|
+
viewMakers[type] = makeView
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/// A plugin view gets its props here, all but `style`, which nativue applies (layout included).
|
|
43
|
+
public protocol PluginView: UIView {
|
|
44
|
+
func setProp(_ key: String, value: Any?)
|
|
45
|
+
}
|
package/ios/Style.swift
CHANGED
|
@@ -35,7 +35,8 @@ extension NativeNode {
|
|
|
35
35
|
view.backgroundColor = UIColor(rgba: value)
|
|
36
36
|
|
|
37
37
|
case "borderRadius":
|
|
38
|
-
view.layer.
|
|
38
|
+
view.layer.setValue(CGFloat(number(value) ?? 0), forKey: UIView.requestedCornerRadiusKey)
|
|
39
|
+
view.applyCornerRadius()
|
|
39
40
|
|
|
40
41
|
case "borderWidth":
|
|
41
42
|
view.layer.borderWidth = CGFloat(number(value) ?? 0)
|
|
@@ -355,3 +356,15 @@ extension NativeNode {
|
|
|
355
356
|
return text.hasSuffix("deg") ? number * .pi / 180 : number
|
|
356
357
|
}
|
|
357
358
|
}
|
|
359
|
+
|
|
360
|
+
extension UIView {
|
|
361
|
+
static let requestedCornerRadiusKey = "nativueCornerRadius"
|
|
362
|
+
|
|
363
|
+
/// A radius over half the view's side (rounded-full is 9999) makes Core Animation draw nothing:
|
|
364
|
+
/// capped to a circle's, and applied again as the frame changes.
|
|
365
|
+
func applyCornerRadius() {
|
|
366
|
+
guard let requestedRadius = layer.value(forKey: Self.requestedCornerRadiusKey) as? CGFloat else { return }
|
|
367
|
+
|
|
368
|
+
layer.cornerRadius = min(requestedRadius, min(bounds.width, bounds.height) / 2)
|
|
369
|
+
}
|
|
370
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nativue/core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Vue rendering real native views on iOS and Android",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"vue",
|
|
@@ -25,7 +25,11 @@
|
|
|
25
25
|
"exports": {
|
|
26
26
|
".": "./src/renderer.ts",
|
|
27
27
|
"./router": "./src/router.ts",
|
|
28
|
-
"./tsconfig.base.json": "./tsconfig.base.json"
|
|
28
|
+
"./tsconfig.base.json": "./tsconfig.base.json",
|
|
29
|
+
"./config": {
|
|
30
|
+
"types": "./cli/config.d.mts",
|
|
31
|
+
"default": "./cli/config.mjs"
|
|
32
|
+
}
|
|
29
33
|
},
|
|
30
34
|
"scripts": {
|
|
31
35
|
"test": "(cd ../../examples/demo && nativue build) && node test/test.mjs",
|
|
@@ -50,6 +54,7 @@
|
|
|
50
54
|
"tsconfig.base.json",
|
|
51
55
|
"android/build.gradle.kts",
|
|
52
56
|
"android/consumer-rules.pro",
|
|
57
|
+
"android/nativue.settings.gradle.kts",
|
|
53
58
|
"android/src"
|
|
54
59
|
],
|
|
55
60
|
"publishConfig": {
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
// The platform the app runs on, and the system's light or dark appearance.
|
|
2
|
+
import { readonly, shallowRef, type Ref } from '@vue/runtime-core'
|
|
3
|
+
|
|
4
|
+
export type ColorScheme = 'light' | 'dark'
|
|
5
|
+
export type PlatformOS = 'ios' | 'android'
|
|
6
|
+
type ColorSchemeListener = (colorScheme: ColorScheme) => void
|
|
7
|
+
|
|
8
|
+
const colorSchemeListeners = new Set<ColorSchemeListener>()
|
|
9
|
+
let colorScheme: ColorScheme = __native.colorScheme()
|
|
10
|
+
const colorSchemeRef = shallowRef(colorScheme)
|
|
11
|
+
|
|
12
|
+
// Platform.OS === 'ios'
|
|
13
|
+
// Platform.select({ ios: 17, android: 16 })
|
|
14
|
+
export const Platform = {
|
|
15
|
+
OS: __native.platform(),
|
|
16
|
+
|
|
17
|
+
select<Value>(values: { ios?: Value; android?: Value; default?: Value }): Value | undefined {
|
|
18
|
+
return values[Platform.OS] ?? values.default
|
|
19
|
+
},
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// Appearance.getColorScheme() -> 'light' | 'dark'
|
|
23
|
+
// const stop = Appearance.addChangeListener((colorScheme) => …)
|
|
24
|
+
export const Appearance = {
|
|
25
|
+
getColorScheme(): ColorScheme {
|
|
26
|
+
return colorScheme
|
|
27
|
+
},
|
|
28
|
+
|
|
29
|
+
/** Returns a function that removes the listener. */
|
|
30
|
+
addChangeListener(listener: ColorSchemeListener): () => void {
|
|
31
|
+
colorSchemeListeners.add(listener)
|
|
32
|
+
|
|
33
|
+
return () => colorSchemeListeners.delete(listener)
|
|
34
|
+
},
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// const colorScheme = useColorScheme() 'light' | 'dark', follows the system
|
|
38
|
+
export function useColorScheme(): Readonly<Ref<ColorScheme>> {
|
|
39
|
+
return readonly(colorSchemeRef)
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// Native calls it when the system switches between light and dark.
|
|
43
|
+
globalThis.__colorSchemeChanged = (nextColorScheme) => {
|
|
44
|
+
if (nextColorScheme === colorScheme) return
|
|
45
|
+
|
|
46
|
+
colorScheme = nextColorScheme
|
|
47
|
+
colorSchemeRef.value = nextColorScheme
|
|
48
|
+
colorSchemeListeners.forEach((listener) => listener(nextColorScheme))
|
|
49
|
+
}
|
package/src/components.ts
CHANGED
|
@@ -13,7 +13,8 @@ import type { ScrollEvent, Style } from './types'
|
|
|
13
13
|
type Listener = ((payload: unknown) => void) | undefined
|
|
14
14
|
|
|
15
15
|
// Vue's template compiler normalizes `:style`, so it can't be a function of the pressed state: the pressed
|
|
16
|
-
// look goes in `pressed-style`, merged over `style` while pressed. The slot also receives { pressed }
|
|
16
|
+
// look goes in `pressed-style`, merged over `style` while pressed. The slot also receives { pressed },
|
|
17
|
+
// and the class its pressed styles (Tailwind's active:).
|
|
17
18
|
export const Pressable = defineComponent({
|
|
18
19
|
name: 'Pressable',
|
|
19
20
|
inheritAttrs: false,
|
|
@@ -38,6 +39,7 @@ export const Pressable = defineComponent({
|
|
|
38
39
|
{
|
|
39
40
|
...attrs,
|
|
40
41
|
style,
|
|
42
|
+
pressed: pressed.value,
|
|
41
43
|
onPressIn: setPressed(true, attrs.onPressIn as Listener),
|
|
42
44
|
onPressOut: setPressed(false, attrs.onPressOut as Listener),
|
|
43
45
|
},
|
package/src/entry.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// The app's entry, added by the CLI: every .vue file under the project's src/app/ is a route, so
|
|
2
|
-
// projects have no main.js.
|
|
2
|
+
// projects have no main.js. The runtime modules of nativue.config's plugins run first.
|
|
3
|
+
import 'virtual:nativue/plugin-runtimes'
|
|
3
4
|
import { createRouterApp } from './router'
|
|
4
5
|
|
|
5
6
|
createRouterApp(import.meta.glob('/src/app/**/*.vue', { eager: true })).mount()
|
package/src/globals.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// What the JavaScript engine has globally: the bridge, the hooks native calls into, and the web APIs
|
|
2
2
|
// prelude.ts (timers, console) and fetch.ts provide. No DOM.
|
|
3
|
+
import type { ColorScheme } from './appearance'
|
|
3
4
|
import type { NativeModule } from './types'
|
|
4
5
|
|
|
5
6
|
declare global {
|
|
@@ -7,6 +8,8 @@ declare global {
|
|
|
7
8
|
var __dispatch: (nodeId: number, eventName: string, payload: unknown) => void
|
|
8
9
|
var __openURL: (url: string) => void
|
|
9
10
|
var __fireTimer: (timerId: number) => void
|
|
11
|
+
var __colorSchemeChanged: (colorScheme: ColorScheme) => void
|
|
12
|
+
var __asyncFunctionFinished: (callId: number, value: unknown, errorMessage: string | null) => void
|
|
10
13
|
var __animationFinished: (animationId: number, finished: boolean) => void
|
|
11
14
|
var __fetchFinished: (
|
|
12
15
|
requestId: number,
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
// The functions packages add natively, for their JS side to call:
|
|
2
|
+
// const impact = requireNativeFunction<(style: string) => void>('haptics.impact')
|
|
3
|
+
// const takePhoto = requireNativeFunction<() => Promise<string>>('camera.takePhoto')
|
|
4
|
+
// Native addFunction ones return synchronously, addAsyncFunction ones return a Promise.
|
|
5
|
+
type AnyFunction = (...args: never[]) => unknown
|
|
6
|
+
type NativeFunctions = Record<string, ((...args: unknown[]) => unknown) | undefined>
|
|
7
|
+
type PendingCall = { resolve: (value: unknown) => void; reject: (error: Error) => void }
|
|
8
|
+
|
|
9
|
+
const pendingCalls = new Map<number, PendingCall>()
|
|
10
|
+
let nextCallId = 1
|
|
11
|
+
|
|
12
|
+
globalThis.__asyncFunctionFinished = (callId, value, errorMessage) => {
|
|
13
|
+
const call = pendingCalls.get(callId)
|
|
14
|
+
if (!call) return
|
|
15
|
+
|
|
16
|
+
pendingCalls.delete(callId)
|
|
17
|
+
if (errorMessage === null) call.resolve(value)
|
|
18
|
+
else call.reject(new Error(errorMessage))
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function asyncCaller(nativeFunction: (...args: unknown[]) => unknown) {
|
|
22
|
+
return (...args: unknown[]) =>
|
|
23
|
+
new Promise((resolve, reject) => {
|
|
24
|
+
const callId = nextCallId++
|
|
25
|
+
pendingCalls.set(callId, { resolve, reject })
|
|
26
|
+
nativeFunction(callId, ...args)
|
|
27
|
+
})
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function requireNativeFunction<Function extends AnyFunction>(name: string): Function {
|
|
31
|
+
const nativeFunctions = __native as unknown as NativeFunctions
|
|
32
|
+
const syncFunction = nativeFunctions[`plugin:${name}`]
|
|
33
|
+
const asyncFunction = nativeFunctions[`pluginAsync:${name}`]
|
|
34
|
+
|
|
35
|
+
if (syncFunction) return syncFunction as unknown as Function
|
|
36
|
+
if (asyncFunction) return asyncCaller(asyncFunction) as unknown as Function
|
|
37
|
+
|
|
38
|
+
throw new Error(
|
|
39
|
+
`The native function "${name}" isn't in the app. A package's native code is added when the app is built: rebuild it (npx nativue run ios / android).`,
|
|
40
|
+
)
|
|
41
|
+
}
|