@nativue/core 0.4.5 → 0.6.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/src/main/cpp/bridge.cpp +49 -0
- package/android/src/main/java/dev/nativue/BlobStore.kt +72 -0
- package/android/src/main/java/dev/nativue/Bridge.kt +30 -38
- package/android/src/main/java/dev/nativue/Networking.kt +323 -0
- package/android/src/main/java/dev/nativue/Views.kt +33 -2
- package/cli/nativue.mjs +46 -6
- package/cli/run.mjs +156 -48
- package/ios/BlobStore.swift +74 -0
- package/ios/Bridge.swift +42 -31
- package/ios/ImageView.swift +14 -2
- package/ios/JavaScriptRuntime/JavaScriptRuntime.mm +35 -0
- package/ios/Networking.swift +321 -0
- package/ios/VueScrollView.swift +25 -2
- package/package.json +4 -2
- package/src/blob.ts +204 -0
- package/src/components.ts +82 -27
- package/src/entry.ts +10 -2
- package/src/events.ts +119 -0
- package/src/fetch.ts +97 -102
- package/src/globals.ts +6 -4
- package/src/native-components.ts +4 -1
- package/src/networking.ts +24 -0
- package/src/renderer.ts +3 -2
- package/src/streams.ts +206 -0
- package/src/types.ts +59 -7
- package/src/url.ts +282 -0
- package/src/xhr.ts +414 -0
package/cli/nativue.mjs
CHANGED
|
@@ -5,8 +5,10 @@
|
|
|
5
5
|
// with --production
|
|
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
|
-
// keeps going as `nativue dev` (unless one is already running)
|
|
9
|
-
|
|
8
|
+
// keeps going as `nativue dev` (unless one is already running);
|
|
9
|
+
// --device for a phone, --device <name or id> for a given one;
|
|
10
|
+
// --no-dev only opens the app
|
|
11
|
+
import { build, loadConfigFromFile, transformWithOxc } from 'vite'
|
|
10
12
|
import vue from '@vitejs/plugin-vue'
|
|
11
13
|
import http from 'node:http'
|
|
12
14
|
import net from 'node:net'
|
|
@@ -110,6 +112,30 @@ function ignoreStyleBlocks() {
|
|
|
110
112
|
}
|
|
111
113
|
}
|
|
112
114
|
|
|
115
|
+
// `async function*` or an `async *method()`.
|
|
116
|
+
const ASYNC_GENERATOR = /\basync\s+function\s*\*|\basync\s*\*\s*[\w$[#"']/
|
|
117
|
+
|
|
118
|
+
// Hermes runs no async generators (libraries like axios have them): a file that has one is lowered to
|
|
119
|
+
// ES2017, where Oxc rewrites them on top of plain generators. Only those files, so the rest keeps its
|
|
120
|
+
// modern syntax.
|
|
121
|
+
function lowerAsyncGenerators() {
|
|
122
|
+
return {
|
|
123
|
+
name: 'nativue-lower-async-generators',
|
|
124
|
+
enforce: 'post',
|
|
125
|
+
async transform(code, id) {
|
|
126
|
+
if (!ASYNC_GENERATOR.test(code)) return null
|
|
127
|
+
|
|
128
|
+
const { code: lowered, map } = await transformWithOxc(code, id.split('?')[0], {
|
|
129
|
+
lang: 'js',
|
|
130
|
+
target: 'es2017',
|
|
131
|
+
sourcemap: true,
|
|
132
|
+
})
|
|
133
|
+
|
|
134
|
+
return { code: lowered, map }
|
|
135
|
+
},
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
113
139
|
const CONFIG_FILES = [
|
|
114
140
|
'nativue.config.ts',
|
|
115
141
|
'nativue.config.mts',
|
|
@@ -168,6 +194,7 @@ function viteConfig({ mode, plugins = [], watch = null, sourcemap = false }) {
|
|
|
168
194
|
},
|
|
169
195
|
}),
|
|
170
196
|
ignoreStyleBlocks(),
|
|
197
|
+
lowerAsyncGenerators(),
|
|
171
198
|
...APP_VITE_PLUGINS,
|
|
172
199
|
finishBundle(mode),
|
|
173
200
|
...plugins,
|
|
@@ -287,10 +314,21 @@ function isPortFree(port) {
|
|
|
287
314
|
|
|
288
315
|
const RUNNERS = { ios: runOnIOS, android: runOnAndroid }
|
|
289
316
|
|
|
290
|
-
|
|
317
|
+
// `--device` alone is true; followed by a name or id, that.
|
|
318
|
+
function deviceOption(args) {
|
|
319
|
+
const index = args.indexOf('--device')
|
|
320
|
+
if (index === -1) return undefined
|
|
321
|
+
|
|
322
|
+
const value = args[index + 1]
|
|
323
|
+
|
|
324
|
+
return value === undefined || value.startsWith('--') ? true : value
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
async function runApp(platform, args) {
|
|
291
328
|
await build(viteConfig({ mode: 'development' }))
|
|
292
|
-
await RUNNERS[platform]()
|
|
329
|
+
await RUNNERS[platform]({ device: deviceOption(args), port: PORT })
|
|
293
330
|
|
|
331
|
+
if (args.includes('--no-dev')) return
|
|
294
332
|
if (await isPortFree(PORT)) return dev()
|
|
295
333
|
|
|
296
334
|
console.log('\nA dev server is already running: the app reloads from it.')
|
|
@@ -310,9 +348,11 @@ try {
|
|
|
310
348
|
}),
|
|
311
349
|
)
|
|
312
350
|
} else if (command === 'run' && RUNNERS[args[0]]) {
|
|
313
|
-
await runApp(args[0])
|
|
351
|
+
await runApp(args[0], args.slice(1))
|
|
314
352
|
} else {
|
|
315
|
-
console.log(
|
|
353
|
+
console.log(
|
|
354
|
+
'usage: nativue <dev | build [--production] | run <ios | android> [--device [name or id]] [--no-dev]>',
|
|
355
|
+
)
|
|
316
356
|
process.exitCode = 1
|
|
317
357
|
}
|
|
318
358
|
} catch (error) {
|
package/cli/run.mjs
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
|
-
// `nativue run ios | android`: builds the app's debug build, opens a simulator
|
|
2
|
-
// is running, then installs and launches the app on it.
|
|
1
|
+
// `nativue run ios | android [--device [name or id]]`: builds the app's debug build, opens a simulator
|
|
2
|
+
// or emulator when none is running, then installs and launches the app on it. `--device` picks one by
|
|
3
|
+
// name or id (a simulator, an emulator or a phone), or alone, the first phone connected.
|
|
3
4
|
import { execFileSync, spawn } from 'node:child_process'
|
|
4
|
-
import { existsSync, readFileSync } from 'node:fs'
|
|
5
|
-
import { homedir } from 'node:os'
|
|
5
|
+
import { existsSync, readFileSync, rmSync } from 'node:fs'
|
|
6
|
+
import { homedir, tmpdir } from 'node:os'
|
|
7
|
+
import { join } from 'node:path'
|
|
6
8
|
|
|
7
9
|
const IOS_BUILD_DIRECTORY = 'ios/build'
|
|
8
|
-
const
|
|
10
|
+
const iOSAppPath = (sdk) => `${IOS_BUILD_DIRECTORY}/Build/Products/Debug-${sdk}/App.app`
|
|
9
11
|
const BOOT_POLL_INTERVAL_MS = 2000
|
|
10
12
|
|
|
11
13
|
function run(command, args, options = {}) {
|
|
@@ -29,7 +31,7 @@ function simulators() {
|
|
|
29
31
|
}
|
|
30
32
|
|
|
31
33
|
/** An iPhone, the newest iOS first: one already booted if there is one. */
|
|
32
|
-
function
|
|
34
|
+
function defaultSimulator() {
|
|
33
35
|
const iOSVersion = (device) => Number(device.runtime.match(/iOS-(\d+)/)?.[1] ?? 0)
|
|
34
36
|
const iPhones = simulators()
|
|
35
37
|
.filter((device) => device.name.startsWith('iPhone') && iOSVersion(device))
|
|
@@ -55,45 +57,121 @@ function openSimulatorApp() {
|
|
|
55
57
|
}
|
|
56
58
|
}
|
|
57
59
|
|
|
58
|
-
|
|
59
|
-
|
|
60
|
+
/** iPhones and iPads paired with this Mac, by Xcode's devicectl. */
|
|
61
|
+
function physicalIOSDevices() {
|
|
62
|
+
const outputFile = join(tmpdir(), `nativue-devices-${process.pid}.json`)
|
|
63
|
+
|
|
64
|
+
try {
|
|
65
|
+
run('xcrun', ['devicectl', 'list', 'devices', '--json-output', outputFile], { stdio: 'ignore' })
|
|
66
|
+
const { result } = JSON.parse(readFileSync(outputFile, 'utf8'))
|
|
67
|
+
|
|
68
|
+
return result.devices
|
|
69
|
+
.filter((device) => device.hardwareProperties.reality === 'physical')
|
|
70
|
+
.map((device) => ({
|
|
71
|
+
name: device.deviceProperties.name,
|
|
72
|
+
udid: device.hardwareProperties.udid,
|
|
73
|
+
}))
|
|
74
|
+
} finally {
|
|
75
|
+
rmSync(outputFile, { force: true })
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** `--device` alone: the first phone. `--device <name or id>`: that simulator or phone. */
|
|
80
|
+
function pickIOSDevice(requested) {
|
|
81
|
+
if (requested === undefined) return { ...defaultSimulator(), isSimulator: true }
|
|
82
|
+
|
|
83
|
+
const phones = physicalIOSDevices().map((device) => ({ ...device, isSimulator: false }))
|
|
84
|
+
if (requested === true) {
|
|
85
|
+
if (phones.length === 0) throw new Error('No iPhone connected: plug it in and trust this Mac.')
|
|
60
86
|
|
|
61
|
-
|
|
62
|
-
step(`Booting ${simulator.name}`)
|
|
63
|
-
run('xcrun', ['simctl', 'boot', simulator.udid])
|
|
87
|
+
return phones[0]
|
|
64
88
|
}
|
|
65
|
-
openSimulatorApp()
|
|
66
89
|
|
|
90
|
+
const candidates = [
|
|
91
|
+
...phones,
|
|
92
|
+
...simulators().map((device) => ({ ...device, isSimulator: true })),
|
|
93
|
+
]
|
|
94
|
+
const device = candidates.find(({ name, udid }) => name === requested || udid === requested)
|
|
95
|
+
if (!device)
|
|
96
|
+
throw new Error(
|
|
97
|
+
noDeviceMessage(
|
|
98
|
+
requested,
|
|
99
|
+
candidates.map(({ name, udid }) => `${name} (${udid})`),
|
|
100
|
+
),
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
return device
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function noDeviceMessage(requested, available) {
|
|
107
|
+
return `No device named or with the id "${requested}". Available:\n ${available.join('\n ')}`
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function buildIOSApp(destination, isSimulator) {
|
|
67
111
|
step('Building the iOS app')
|
|
68
|
-
run(
|
|
69
|
-
'xcodebuild',
|
|
70
|
-
[
|
|
71
|
-
'-project',
|
|
72
|
-
'ios/App.xcodeproj',
|
|
73
|
-
'-scheme',
|
|
74
|
-
'App',
|
|
75
|
-
'-configuration',
|
|
76
|
-
'Debug',
|
|
77
|
-
'-destination',
|
|
78
|
-
`id=${simulator.udid}`,
|
|
79
|
-
'-derivedDataPath',
|
|
80
|
-
IOS_BUILD_DIRECTORY,
|
|
81
|
-
'-quiet',
|
|
82
|
-
'build',
|
|
83
|
-
],
|
|
84
|
-
{ stdio: 'inherit' },
|
|
85
|
-
)
|
|
86
112
|
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
113
|
+
try {
|
|
114
|
+
run(
|
|
115
|
+
'xcodebuild',
|
|
116
|
+
[
|
|
117
|
+
'-project',
|
|
118
|
+
'ios/App.xcodeproj',
|
|
119
|
+
'-scheme',
|
|
120
|
+
'App',
|
|
121
|
+
'-configuration',
|
|
122
|
+
'Debug',
|
|
123
|
+
'-destination',
|
|
124
|
+
`id=${destination}`,
|
|
125
|
+
'-derivedDataPath',
|
|
126
|
+
IOS_BUILD_DIRECTORY,
|
|
127
|
+
// A phone needs a signed app: Xcode creates its provisioning profile.
|
|
128
|
+
...(isSimulator ? [] : ['-allowProvisioningUpdates']),
|
|
129
|
+
'-quiet',
|
|
130
|
+
'build',
|
|
131
|
+
],
|
|
132
|
+
{ stdio: 'inherit' },
|
|
133
|
+
)
|
|
134
|
+
} catch (error) {
|
|
135
|
+
if (isSimulator) throw error
|
|
136
|
+
|
|
137
|
+
throw new Error(
|
|
138
|
+
'The build for the phone failed. If it says signing needs a development team, open ios/App.xcodeproj in Xcode and pick your team under Signing & Capabilities.',
|
|
139
|
+
)
|
|
140
|
+
}
|
|
141
|
+
}
|
|
93
142
|
|
|
94
|
-
|
|
95
|
-
run('
|
|
96
|
-
|
|
143
|
+
function bundleIdentifier(appPath) {
|
|
144
|
+
return run('plutil', ['-extract', 'CFBundleIdentifier', 'raw', `${appPath}/Info.plist`]).trim()
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export function runOnIOS({ device: requested } = {}) {
|
|
148
|
+
const device = pickIOSDevice(requested)
|
|
149
|
+
|
|
150
|
+
if (device.isSimulator && device.state !== 'Booted') {
|
|
151
|
+
step(`Booting ${device.name}`)
|
|
152
|
+
run('xcrun', ['simctl', 'boot', device.udid])
|
|
153
|
+
}
|
|
154
|
+
if (device.isSimulator) openSimulatorApp()
|
|
155
|
+
|
|
156
|
+
buildIOSApp(device.udid, device.isSimulator)
|
|
157
|
+
|
|
158
|
+
const appPath = iOSAppPath(device.isSimulator ? 'iphonesimulator' : 'iphoneos')
|
|
159
|
+
const bundleId = bundleIdentifier(appPath)
|
|
160
|
+
step(`Opening ${bundleId} on ${device.name}`)
|
|
161
|
+
|
|
162
|
+
if (device.isSimulator) {
|
|
163
|
+
run('xcrun', ['simctl', 'install', device.udid, appPath])
|
|
164
|
+
run('xcrun', ['simctl', 'launch', device.udid, bundleId])
|
|
165
|
+
return
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const devicectl = (subcommand, ...args) =>
|
|
169
|
+
run('xcrun', ['devicectl', 'device', ...subcommand, '--device', device.udid, ...args], {
|
|
170
|
+
stdio: 'ignore',
|
|
171
|
+
})
|
|
172
|
+
|
|
173
|
+
devicectl(['install', 'app'], appPath)
|
|
174
|
+
devicectl(['process', 'launch'], '--terminate-existing', bundleId)
|
|
97
175
|
}
|
|
98
176
|
|
|
99
177
|
// ---------- Android ----------
|
|
@@ -125,17 +203,44 @@ function javaHome() {
|
|
|
125
203
|
return existsSync(androidStudioJdk) ? androidStudioJdk : undefined
|
|
126
204
|
}
|
|
127
205
|
|
|
206
|
+
/** Serials and models of what adb sees: emulators and phones. */
|
|
128
207
|
function connectedDevices(adb) {
|
|
129
|
-
return run(adb, ['devices'])
|
|
208
|
+
return run(adb, ['devices', '-l'])
|
|
130
209
|
.split('\n')
|
|
131
|
-
.filter((line) => line
|
|
132
|
-
.map((line) => line.split(
|
|
210
|
+
.filter((line) => /\sdevice\s/.test(`${line} `))
|
|
211
|
+
.map((line) => ({ serial: line.split(/\s+/)[0], model: line.match(/model:(\S+)/)?.[1] ?? '' }))
|
|
133
212
|
}
|
|
134
213
|
|
|
135
|
-
|
|
136
|
-
|
|
214
|
+
const isEmulator = (serial) => serial.startsWith('emulator-')
|
|
215
|
+
|
|
216
|
+
/** `--device` alone: the first phone. `--device <serial or model>`: that one. */
|
|
217
|
+
function pickRequestedDevice(adb, requested) {
|
|
218
|
+
const devices = connectedDevices(adb)
|
|
219
|
+
|
|
220
|
+
if (requested === true) {
|
|
221
|
+
const phone = devices.find(({ serial }) => !isEmulator(serial))
|
|
222
|
+
if (!phone) throw new Error('No Android phone connected: plug it in with USB debugging on.')
|
|
223
|
+
|
|
224
|
+
return phone.serial
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
const device = devices.find(({ serial, model }) => serial === requested || model === requested)
|
|
228
|
+
if (!device)
|
|
229
|
+
throw new Error(
|
|
230
|
+
noDeviceMessage(
|
|
231
|
+
requested,
|
|
232
|
+
devices.map(({ serial, model }) => `${model} (${serial})`),
|
|
233
|
+
),
|
|
234
|
+
)
|
|
235
|
+
|
|
236
|
+
return device.serial
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
async function pickDevice(sdkPath, adb, requested) {
|
|
240
|
+
if (requested !== undefined) return pickRequestedDevice(adb, requested)
|
|
241
|
+
|
|
137
242
|
const [device] = connectedDevices(adb)
|
|
138
|
-
if (device) return device
|
|
243
|
+
if (device) return device.serial
|
|
139
244
|
|
|
140
245
|
const emulator = `${sdkPath}/emulator/emulator`
|
|
141
246
|
const [emulatorName] = run(emulator, ['-list-avds']).split('\n').filter(Boolean)
|
|
@@ -150,7 +255,7 @@ async function pickDevice(sdkPath, adb) {
|
|
|
150
255
|
await sleep(BOOT_POLL_INTERVAL_MS)
|
|
151
256
|
}
|
|
152
257
|
|
|
153
|
-
return connectedDevices(adb)[0]
|
|
258
|
+
return connectedDevices(adb)[0].serial
|
|
154
259
|
}
|
|
155
260
|
|
|
156
261
|
function applicationId() {
|
|
@@ -159,10 +264,13 @@ function applicationId() {
|
|
|
159
264
|
return gradleFile.match(/applicationId\s*=\s*"([^"]+)"/)[1]
|
|
160
265
|
}
|
|
161
266
|
|
|
162
|
-
export async function runOnAndroid() {
|
|
267
|
+
export async function runOnAndroid({ device: requested, port } = {}) {
|
|
163
268
|
const sdkPath = androidSdkPath()
|
|
164
269
|
const adb = `${sdkPath}/platform-tools/adb`
|
|
165
|
-
const device = await pickDevice(sdkPath, adb)
|
|
270
|
+
const device = await pickDevice(sdkPath, adb, requested)
|
|
271
|
+
|
|
272
|
+
// A phone on USB reaches the dev server on this computer through adb, whatever its network.
|
|
273
|
+
if (!isEmulator(device)) run(adb, ['-s', device, 'reverse', `tcp:${port}`, `tcp:${port}`])
|
|
166
274
|
|
|
167
275
|
step('Building the Android app')
|
|
168
276
|
const gradlew = process.platform === 'win32' ? 'gradlew.bat' : './gradlew'
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// The bytes behind JS's Blobs, by id. JS holds only the id; the runtime releases it when the garbage
|
|
4
|
+
/// collector collects the last Blob pointing to it. Used from the JS queue and from Networking's.
|
|
5
|
+
final class BlobStore {
|
|
6
|
+
/// One for the app: <Image> reads `blob:` URLs from it too.
|
|
7
|
+
static let shared = BlobStore()
|
|
8
|
+
|
|
9
|
+
private var dataById: [String: Data] = [:]
|
|
10
|
+
private let lock = NSLock()
|
|
11
|
+
|
|
12
|
+
func store(_ data: Data) -> String {
|
|
13
|
+
let blobId = UUID().uuidString
|
|
14
|
+
lock.withLock { dataById[blobId] = data }
|
|
15
|
+
|
|
16
|
+
return blobId
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/// A slice of a blob's bytes; nil if it's been released.
|
|
20
|
+
func data(blobId: String, offset: Int, size: Int) -> Data? {
|
|
21
|
+
lock.withLock {
|
|
22
|
+
guard let data = dataById[blobId], offset >= 0, size >= 0, offset + size <= data.count else { return nil }
|
|
23
|
+
|
|
24
|
+
return data.subdata(in: offset..<(offset + size))
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/// `{ blobId, offset, size }`, as JS describes the bytes it sends.
|
|
29
|
+
func data(of blob: [String: Any]) -> Data? {
|
|
30
|
+
guard let blobId = blob["blobId"] as? String else { return nil }
|
|
31
|
+
|
|
32
|
+
return data(blobId: blobId, offset: integer(blob["offset"]), size: integer(blob["size"]))
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/// A `blob:<id>?offset=…&size=…` URL, from URL.createObjectURL.
|
|
36
|
+
func data(forURL url: String) -> Data? {
|
|
37
|
+
guard let components = URLComponents(string: url), components.scheme == "blob" else { return nil }
|
|
38
|
+
|
|
39
|
+
let number = { (name: String) in Int(components.queryItems?.first { $0.name == name }?.value ?? "") ?? 0 }
|
|
40
|
+
|
|
41
|
+
return data(blobId: components.path, offset: number("offset"), size: number("size"))
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
func remove(blobId: String) {
|
|
45
|
+
lock.withLock { _ = dataById.removeValue(forKey: blobId) }
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/// On reload: the Blobs' JS is gone.
|
|
49
|
+
func removeAll() {
|
|
50
|
+
lock.withLock { dataById = [:] }
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/// Joins `{ string }`, `{ base64 }` and `{ blob }` parts into a new blob.
|
|
54
|
+
func create(parts: [[String: Any]]) throws -> (blobId: String, size: Int) {
|
|
55
|
+
var joined = Data()
|
|
56
|
+
|
|
57
|
+
for part in parts {
|
|
58
|
+
if let text = part["string"] as? String {
|
|
59
|
+
joined.append(Data(text.utf8))
|
|
60
|
+
} else if let base64 = part["base64"] as? String {
|
|
61
|
+
joined.append(Data(base64Encoded: base64) ?? Data())
|
|
62
|
+
} else if let blob = part["blob"] as? [String: Any] {
|
|
63
|
+
guard let data = data(of: blob) else { throw NetworkingError("The blob has been released") }
|
|
64
|
+
joined.append(data)
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
return (store(joined), joined.count)
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
private func integer(_ value: Any?) -> Int {
|
|
72
|
+
(value as? NSNumber)?.intValue ?? 0
|
|
73
|
+
}
|
|
74
|
+
}
|
package/ios/Bridge.swift
CHANGED
|
@@ -44,6 +44,8 @@ final class Bridge {
|
|
|
44
44
|
var nodesById: [Int: NativeNode] = [:]
|
|
45
45
|
/// Views with @layout, and the box they last reported.
|
|
46
46
|
private var reportedLayoutsByNodeId: [Int: CGRect] = [:]
|
|
47
|
+
private let blobStore = BlobStore.shared
|
|
48
|
+
private lazy var networking = Networking(blobStore: blobStore)
|
|
47
49
|
/// Modals and screens: their content is laid out as a separate Yoga root.
|
|
48
50
|
private var contentRootsByNodeId: [Int: ContentRoot] = [:]
|
|
49
51
|
/// For Dimensions.get('window'): the screen's at start, then the root view's, kept on the JS queue.
|
|
@@ -61,6 +63,9 @@ final class Bridge {
|
|
|
61
63
|
self.rootView = rootView
|
|
62
64
|
rootView.onLayoutSubviews = { [unowned self] in layout() }
|
|
63
65
|
NativeNode.onLayoutCalculated = { [unowned self] in reportLayoutChanges() }
|
|
66
|
+
networking.onEvent = { [unowned self] owner, requestId, eventName, payload in
|
|
67
|
+
sendNetworkEvent(owner: owner, requestId: requestId, eventName: eventName, payload: payload)
|
|
68
|
+
}
|
|
64
69
|
let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene
|
|
65
70
|
windowSize = windowScene?.screen.bounds.size ?? .zero
|
|
66
71
|
colorScheme = Self.colorScheme(of: windowScene?.traitCollection ?? rootView.traitCollection)
|
|
@@ -315,7 +320,8 @@ final class Bridge {
|
|
|
315
320
|
|
|
316
321
|
defineAnimatedFunctions(define)
|
|
317
322
|
defineStorageFunctions(define, defineGetter)
|
|
318
|
-
|
|
323
|
+
defineNetworking(define)
|
|
324
|
+
defineBlobFunctions(define, defineGetter)
|
|
319
325
|
|
|
320
326
|
define("setTimer") { [unowned self] arguments in
|
|
321
327
|
let (timerId, delayInMilliseconds) = (int(arguments[0]), int(arguments[1]))
|
|
@@ -384,6 +390,8 @@ final class Bridge {
|
|
|
384
390
|
contentRootsByNodeId.values.forEach { ($0 as? ModalController)?.setVisible(false) }
|
|
385
391
|
contentRootsByNodeId = [:]
|
|
386
392
|
gestureReportersByNodeId = [:] // node ids start over
|
|
393
|
+
networking.abortAll() // and so do request ids
|
|
394
|
+
blobStore.removeAll() // and the Blobs that held them are gone
|
|
387
395
|
reportedLayoutsByNodeId = [:]
|
|
388
396
|
animatedGraph.reset()
|
|
389
397
|
animatedGraph.onAnimationEnd = { [unowned self] animationId, finished in
|
|
@@ -637,46 +645,46 @@ final class Bridge {
|
|
|
637
645
|
}
|
|
638
646
|
}
|
|
639
647
|
|
|
640
|
-
///
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
let bodyText = arguments[4] as? String
|
|
647
|
-
let owner = runtime
|
|
648
|
+
/// XMLHttpRequest's native side (Networking); fetch is built on it in JS.
|
|
649
|
+
private func defineNetworking(_ define: Define) {
|
|
650
|
+
define("sendRequest") { [unowned self] arguments in
|
|
651
|
+
let query = arguments[1] as? [String: Any] ?? [:]
|
|
652
|
+
networking.send(requestId: int(arguments[0]), query: query, owner: runtime)
|
|
653
|
+
}
|
|
648
654
|
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
655
|
+
define("abortRequest") { [unowned self] arguments in
|
|
656
|
+
networking.abort(requestId: int(arguments[0]))
|
|
657
|
+
}
|
|
658
|
+
}
|
|
652
659
|
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
660
|
+
/// The bytes behind JS's Blobs (BlobStore). blobRelease is also what the runtime calls when a Blob is
|
|
661
|
+
/// garbage collected.
|
|
662
|
+
private func defineBlobFunctions(_ define: Define, _ defineGetter: DefineGetter) {
|
|
663
|
+
// nil when a part's blob has been released.
|
|
664
|
+
defineGetter("blobCreate") { [unowned self] arguments in
|
|
665
|
+
guard let blob = try? blobStore.create(parts: arguments[0] as? [[String: Any]] ?? []) else { return nil }
|
|
657
666
|
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
667
|
+
return ["blobId": blob.blobId, "size": blob.size]
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
defineGetter("blobRead") { [unowned self] arguments in
|
|
671
|
+
let blob = ["blobId": arguments[0], "offset": arguments[1], "size": arguments[2]]
|
|
672
|
+
guard let data = blobStore.data(of: blob) else { return nil }
|
|
664
673
|
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
674
|
+
return string(arguments[3]) == "base64" ? data.base64EncodedString() : String(decoding: data, as: UTF8.self)
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
// Not through self: the runtime may collect Blobs as it's destroyed, with the Bridge.
|
|
678
|
+
define("blobRelease") { [blobStore] arguments in
|
|
679
|
+
blobStore.remove(blobId: arguments[0] as? String ?? "")
|
|
671
680
|
}
|
|
672
681
|
}
|
|
673
682
|
|
|
674
683
|
/// Like finishAsyncFunction, dropped if the runtime that asked has since been reloaded.
|
|
675
|
-
private func
|
|
684
|
+
private func sendNetworkEvent(owner: AnyObject?, requestId: Int, eventName: String, payload: [String: Any]) {
|
|
676
685
|
evaluate { [unowned self] in
|
|
677
686
|
guard runtime === owner else { return }
|
|
678
|
-
|
|
679
|
-
runtime?.call("__fetchFinished", arguments: arguments)
|
|
687
|
+
runtime?.call("__networkEvent", arguments: [requestId, eventName, payload])
|
|
680
688
|
}
|
|
681
689
|
}
|
|
682
690
|
|
|
@@ -825,6 +833,9 @@ final class Bridge {
|
|
|
825
833
|
case "pagingEnabled":
|
|
826
834
|
(node.view as? UIScrollView)?.isPagingEnabled = isTruthyAttribute(value)
|
|
827
835
|
|
|
836
|
+
case "scrollEventThrottle":
|
|
837
|
+
(node.view as? VueScrollView)?.scrollEventThrottle = (value as? NSNumber)?.doubleValue ?? 0
|
|
838
|
+
|
|
828
839
|
case "showsHorizontalScrollIndicator":
|
|
829
840
|
(node.view as? UIScrollView)?.showsHorizontalScrollIndicator = isTruthyAttribute(value)
|
|
830
841
|
|
package/ios/ImageView.swift
CHANGED
|
@@ -60,7 +60,7 @@ final class ImageView: UIImageView {
|
|
|
60
60
|
let readsDisk = cachePolicy == "disk"
|
|
61
61
|
loadingTask = Task { [weak self] in
|
|
62
62
|
let cachedData = readsDisk ? await Task.detached { ImageDiskCache.data(for: source) }.value : nil
|
|
63
|
-
let downloadedData = cachedData == nil ?
|
|
63
|
+
let downloadedData = cachedData == nil ? await Self.download(source, from: url) : nil
|
|
64
64
|
guard
|
|
65
65
|
let data = cachedData ?? downloadedData,
|
|
66
66
|
let image = await UIImage(data: data)?.byPreparingForDisplay(), // decoded off the main thread
|
|
@@ -78,7 +78,7 @@ final class ImageView: UIImageView {
|
|
|
78
78
|
|
|
79
79
|
Self.decodedImages.setObject(image, forKey: source as NSString, cost: Self.byteCount(of: image))
|
|
80
80
|
|
|
81
|
-
guard cachePolicy == "disk", let downloadedData, !
|
|
81
|
+
guard cachePolicy == "disk", let downloadedData, !Self.isInMemory(source) else { return }
|
|
82
82
|
Task.detached(priority: .utility) { ImageDiskCache.store(downloadedData, for: source) }
|
|
83
83
|
}
|
|
84
84
|
|
|
@@ -111,6 +111,18 @@ final class ImageView: UIImageView {
|
|
|
111
111
|
onImageChange?()
|
|
112
112
|
}
|
|
113
113
|
|
|
114
|
+
/// A blob: URL's bytes are in the BlobStore; URLSession reads data: URLs itself.
|
|
115
|
+
private static func download(_ source: String, from url: URL) async -> Data? {
|
|
116
|
+
if source.hasPrefix("blob:") { return BlobStore.shared.data(forURL: source) }
|
|
117
|
+
|
|
118
|
+
return try? await session.data(from: url).0
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/// data: and blob: images are already on the device: nothing to keep on disk.
|
|
122
|
+
private static func isInMemory(_ source: String) -> Bool {
|
|
123
|
+
source.hasPrefix("data:") || source.hasPrefix("blob:")
|
|
124
|
+
}
|
|
125
|
+
|
|
114
126
|
private static func byteCount(of image: UIImage) -> Int {
|
|
115
127
|
guard let cgImage = image.cgImage else { return 0 }
|
|
116
128
|
|
|
@@ -139,6 +139,38 @@ class DataBuffer : public jsi::Buffer {
|
|
|
139
139
|
NSData *data_;
|
|
140
140
|
};
|
|
141
141
|
|
|
142
|
+
// ---------- Blobs ----------
|
|
143
|
+
|
|
144
|
+
// What __blobCollector returns: when the garbage collector collects it (with the last Blob that holds it),
|
|
145
|
+
// it releases the blob's native bytes.
|
|
146
|
+
class BlobCollector : public jsi::HostObject {
|
|
147
|
+
public:
|
|
148
|
+
BlobCollector(NativueNativeFunction release, NSString *blobId) : release_(release), blobId_(blobId) {}
|
|
149
|
+
|
|
150
|
+
~BlobCollector() override {
|
|
151
|
+
release_(@[ blobId_ ]);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
private:
|
|
155
|
+
NativueNativeFunction release_;
|
|
156
|
+
NSString *blobId_;
|
|
157
|
+
};
|
|
158
|
+
|
|
159
|
+
void installBlobCollector(jsi::Runtime &runtime, NativueNativeFunction release) {
|
|
160
|
+
auto collector = [release](jsi::Runtime &runtime, const jsi::Value &, const jsi::Value *arguments, size_t count) {
|
|
161
|
+
if (count < 1 || !arguments[0].isString()) throw jsi::JSError(runtime, "__blobCollector needs a blob id");
|
|
162
|
+
|
|
163
|
+
NSString *blobId = toObjectiveCString(runtime, arguments[0].getString(runtime));
|
|
164
|
+
|
|
165
|
+
return jsi::Value(runtime, jsi::Object::createFromHostObject(runtime, std::make_shared<BlobCollector>(release, blobId)));
|
|
166
|
+
};
|
|
167
|
+
|
|
168
|
+
runtime.global().setProperty(
|
|
169
|
+
runtime,
|
|
170
|
+
"__blobCollector",
|
|
171
|
+
jsi::Function::createFromHostFunction(runtime, jsi::PropNameID::forAscii(runtime, "__blobCollector"), 1, collector));
|
|
172
|
+
}
|
|
173
|
+
|
|
142
174
|
} // namespace
|
|
143
175
|
|
|
144
176
|
@implementation NativueJavaScriptRuntime {
|
|
@@ -182,6 +214,9 @@ class DataBuffer : public jsi::Buffer {
|
|
|
182
214
|
}
|
|
183
215
|
|
|
184
216
|
runtime.global().setProperty(runtime, "__native", nativeModule);
|
|
217
|
+
|
|
218
|
+
NativueNativeFunction releaseBlob = functions[@"blobRelease"];
|
|
219
|
+
if (releaseBlob) installBlobCollector(runtime, releaseBlob);
|
|
185
220
|
}
|
|
186
221
|
|
|
187
222
|
- (void)evaluate:(NSData *)bundle sourceURL:(NSString *)sourceURL {
|