@nativue/core 0.17.0 → 0.19.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 +11 -1
- package/android/build.gradle.kts +2 -0
- package/android/src/main/java/dev/nativue/Bridge.kt +3 -1
- package/android/src/main/java/dev/nativue/NativueActivity.kt +2 -1
- package/android/src/main/java/dev/nativue/Views.kt +26 -1
- package/cli/hot-client.js +63 -0
- package/cli/nativue.mjs +60 -9
- package/ios/Bridge.swift +45 -1
- package/ios/Plugins.swift +9 -0
- package/package.json +2 -2
- package/src/console.ts +249 -0
- package/src/globals.ts +4 -6
- package/src/prelude.ts +7 -5
- package/src/types.ts +2 -1
package/AGENTS.md
CHANGED
|
@@ -109,7 +109,17 @@ Import the runtime from `vue`: `ref`, `computed`, `StyleSheet`, `Animated`, `Lay
|
|
|
109
109
|
- Tab and header icons (`tabBarIcon`, a header item's `icon`): an `@nativue/icons` component,
|
|
110
110
|
`svgIcon(viewBox, elements)` from `@nativue/svg`, an image `{ uri }`, or an SF Symbol name (iOS).
|
|
111
111
|
- Official packages: `@nativue/svg`, `@nativue/icons` (icon components), `@nativue/tailwind`, `@nativue/haptics`,
|
|
112
|
-
`@nativue/clipboard` (copy text), `@nativue/notifications` (local notifications), `@nativue/sqlite
|
|
112
|
+
`@nativue/clipboard` (copy text), `@nativue/notifications` (local notifications), `@nativue/sqlite`,
|
|
113
|
+
`@nativue/image-picker` (`ImagePicker.pick({ limit, mediaTypes })`,
|
|
114
|
+
`openCamera({ mediaTypes, videoMaxDuration, videoQuality })`; call `getPendingResult()` on start, for
|
|
115
|
+
what was picked or taken while Android closed the app),
|
|
116
|
+
`@nativue/secure-store` (secrets: `SecureStore.setItem(key, value)`, `getItem`, `deleteItem`),
|
|
117
|
+
`@nativue/file-system` (`FileSystem.readText`/`writeText`/`download`/`upload` with `file://` URIs from
|
|
118
|
+
`Paths.document` and `Paths.cache`),
|
|
119
|
+
`@nativue/network` (`useNetworkState()`: `{ isConnected, isInternetReachable, type, isExpensive }`, live),
|
|
120
|
+
`@nativue/share` (`Share.share({ text, url, files })` opens the system's share sheet),
|
|
121
|
+
`@nativue/auth-session` (OAuth: `AuthSession.open(url, 'myapp://oauth')` with `createPKCE()`; keep tokens in secure-store),
|
|
122
|
+
`@nativue/biometrics` (`Biometrics.authenticate({ reason })` resolves `{ success }` or `{ success: false, error }`).
|
|
113
123
|
A package with native code needs the app
|
|
114
124
|
rebuilt with `npm run ios` or `npm run android`, not just a reload.
|
|
115
125
|
- Notifications: `Notifications.schedule({ title, body, data }, { seconds } | { date } | { hour, minute } | null)`
|
package/android/build.gradle.kts
CHANGED
|
@@ -75,6 +75,8 @@ dependencies {
|
|
|
75
75
|
implementation("androidx.core:core:1.16.0")
|
|
76
76
|
// ComponentActivity: activity-result launchers and new-intent listeners for plugins.
|
|
77
77
|
api("androidx.activity:activity:1.13.0")
|
|
78
|
+
// FragmentActivity, which NativueActivity is, as SDKs ask for: androidx.biometric's prompt, payment sheets.
|
|
79
|
+
api("androidx.fragment:fragment:1.9.1")
|
|
78
80
|
// AppState: whether the app, not one activity, is in front.
|
|
79
81
|
implementation("androidx.lifecycle:lifecycle-process:2.11.1")
|
|
80
82
|
}
|
|
@@ -382,7 +382,7 @@ class Bridge(private val activity: ComponentActivity, private val rootView: Root
|
|
|
382
382
|
}
|
|
383
383
|
|
|
384
384
|
private fun nativeFunctions(): Map<String, NativeFunction> = buildMap {
|
|
385
|
-
put("log") { arguments -> Log.
|
|
385
|
+
put("log") { arguments -> Log.println(LOG_PRIORITIES[arguments[1]] ?: Log.INFO, TAG, "[JS] ${arguments[0]}") }
|
|
386
386
|
put("reportError") { arguments -> reportError(arguments[0] as String, arguments[1] as String) }
|
|
387
387
|
put("windowSize") { _ -> windowSize }
|
|
388
388
|
put("platform") { _ -> "android" }
|
|
@@ -1168,6 +1168,8 @@ class Bridge(private val activity: ComponentActivity, private val rootView: Root
|
|
|
1168
1168
|
|
|
1169
1169
|
private companion object {
|
|
1170
1170
|
const val TAG = "nativue"
|
|
1171
|
+
/** The console's levels as logcat's; log and info are INFO. */
|
|
1172
|
+
val LOG_PRIORITIES = mapOf("debug" to Log.DEBUG, "warn" to Log.WARN, "error" to Log.ERROR)
|
|
1171
1173
|
const val JAVASCRIPT_STACK_SIZE = 8L * 1024 * 1024
|
|
1172
1174
|
const val SYMBOLICATE_TIMEOUT_MS = 2000
|
|
1173
1175
|
const val RECONNECT_DELAY_MS = 2000L
|
|
@@ -13,10 +13,11 @@ import android.window.OnBackInvokedCallback
|
|
|
13
13
|
import android.window.OnBackInvokedDispatcher
|
|
14
14
|
import androidx.activity.ComponentActivity
|
|
15
15
|
import androidx.annotation.RequiresApi
|
|
16
|
+
import androidx.fragment.app.FragmentActivity
|
|
16
17
|
import com.facebook.soloader.SoLoader
|
|
17
18
|
|
|
18
19
|
/** The app's activity: runs assets/main.bundle.js (or, in debug builds, the dev server's bundle). */
|
|
19
|
-
open class NativueActivity :
|
|
20
|
+
open class NativueActivity : FragmentActivity() {
|
|
20
21
|
private lateinit var bridge: Bridge
|
|
21
22
|
private var lastRKeyTime = 0L
|
|
22
23
|
|
|
@@ -5,7 +5,9 @@ import android.content.Context
|
|
|
5
5
|
import android.graphics.Bitmap
|
|
6
6
|
import android.graphics.BitmapFactory
|
|
7
7
|
import android.graphics.Canvas
|
|
8
|
+
import android.graphics.Matrix
|
|
8
9
|
import android.graphics.Rect
|
|
10
|
+
import android.media.ExifInterface
|
|
9
11
|
import android.os.Build
|
|
10
12
|
import android.os.Handler
|
|
11
13
|
import android.os.Looper
|
|
@@ -629,7 +631,7 @@ class RemoteImageView(context: Context) : ImageView(context) {
|
|
|
629
631
|
val cachedBytes = if (readsDisk) diskCache.read(source) else null
|
|
630
632
|
val downloadedBytes = if (cachedBytes == null) runCatching { download(source) }.getOrNull() else null
|
|
631
633
|
val bytes = cachedBytes ?: downloadedBytes
|
|
632
|
-
val bitmap = bytes?.let
|
|
634
|
+
val bitmap = bytes?.let(::decodeUpright)
|
|
633
635
|
if (bitmap == null) {
|
|
634
636
|
mainThread.post(onFailed)
|
|
635
637
|
return@execute
|
|
@@ -642,6 +644,29 @@ class RemoteImageView(context: Context) : ImageView(context) {
|
|
|
642
644
|
}
|
|
643
645
|
}
|
|
644
646
|
|
|
647
|
+
/** Turned as its EXIF orientation says, as cameras save photos sideways and leave the turn to the viewer. */
|
|
648
|
+
private fun decodeUpright(bytes: ByteArray): Bitmap? {
|
|
649
|
+
val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size) ?: return null
|
|
650
|
+
val orientation = runCatching {
|
|
651
|
+
ExifInterface(bytes.inputStream()).getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL)
|
|
652
|
+
}.getOrDefault(ExifInterface.ORIENTATION_NORMAL)
|
|
653
|
+
val turn = Matrix().apply {
|
|
654
|
+
when (orientation) {
|
|
655
|
+
ExifInterface.ORIENTATION_FLIP_HORIZONTAL -> postScale(-1f, 1f)
|
|
656
|
+
ExifInterface.ORIENTATION_ROTATE_180 -> postRotate(180f)
|
|
657
|
+
ExifInterface.ORIENTATION_FLIP_VERTICAL -> postScale(1f, -1f)
|
|
658
|
+
ExifInterface.ORIENTATION_TRANSPOSE -> postRotate(90f).also { postScale(-1f, 1f) }
|
|
659
|
+
ExifInterface.ORIENTATION_ROTATE_90 -> postRotate(90f)
|
|
660
|
+
ExifInterface.ORIENTATION_TRANSVERSE -> postRotate(270f).also { postScale(-1f, 1f) }
|
|
661
|
+
ExifInterface.ORIENTATION_ROTATE_270 -> postRotate(270f)
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
if (turn.isIdentity) return bitmap
|
|
666
|
+
|
|
667
|
+
return Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, turn, true)
|
|
668
|
+
}
|
|
669
|
+
|
|
645
670
|
private fun store(bitmap: Bitmap, downloadedBytes: ByteArray?, source: String, diskCache: ImageDiskCache, cachePolicy: String) {
|
|
646
671
|
if (cachePolicy == "none") return
|
|
647
672
|
|
package/cli/hot-client.js
CHANGED
|
@@ -18,6 +18,69 @@
|
|
|
18
18
|
}).catch(() => {})
|
|
19
19
|
}
|
|
20
20
|
|
|
21
|
+
// What the console prints, also in the dev server's terminal: one request at a time, so it keeps
|
|
22
|
+
// the order, with what was printed meanwhile. Each stays well under what the server reads
|
|
23
|
+
// (MAX_POST_LENGTH), escaping included.
|
|
24
|
+
const MAX_LOG_LENGTH = 100_000
|
|
25
|
+
const MAX_BATCH_LENGTH = 300_000
|
|
26
|
+
const pendingLogs = []
|
|
27
|
+
let isSendingLogs = false
|
|
28
|
+
let isCallingFetch = false
|
|
29
|
+
|
|
30
|
+
function nextBatch() {
|
|
31
|
+
let length = 0
|
|
32
|
+
let count = 0
|
|
33
|
+
|
|
34
|
+
while (
|
|
35
|
+
count < pendingLogs.length &&
|
|
36
|
+
length + pendingLogs[count].text.length <= MAX_BATCH_LENGTH
|
|
37
|
+
) {
|
|
38
|
+
length += pendingLogs[count].text.length
|
|
39
|
+
count++
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
return pendingLogs.splice(0, count)
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// An app that wraps fetch to log its requests would log this one, and send that log, forever: what's
|
|
46
|
+
// printed while it's called stays on the device.
|
|
47
|
+
function postLogs(entries) {
|
|
48
|
+
isCallingFetch = true
|
|
49
|
+
try {
|
|
50
|
+
return fetch(`${serverURL}/log`, {
|
|
51
|
+
method: 'POST',
|
|
52
|
+
body: JSON.stringify({ platform: __native.platform(), entries }),
|
|
53
|
+
})
|
|
54
|
+
} finally {
|
|
55
|
+
isCallingFetch = false
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function sendLogs() {
|
|
60
|
+
if (isSendingLogs || pendingLogs.length === 0) return
|
|
61
|
+
|
|
62
|
+
isSendingLogs = true
|
|
63
|
+
Promise.resolve()
|
|
64
|
+
.then(() => postLogs(nextBatch()))
|
|
65
|
+
.catch(() => {})
|
|
66
|
+
.finally(() => {
|
|
67
|
+
isSendingLogs = false
|
|
68
|
+
sendLogs()
|
|
69
|
+
})
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
globalThis.__nativueOnLog = (level, text) => {
|
|
73
|
+
if (isCallingFetch) return
|
|
74
|
+
|
|
75
|
+
const hidden = text.length - MAX_LOG_LENGTH
|
|
76
|
+
|
|
77
|
+
pendingLogs.push({
|
|
78
|
+
level,
|
|
79
|
+
text: hidden > 0 ? `${text.slice(0, MAX_LOG_LENGTH)}... ${hidden} more characters` : text,
|
|
80
|
+
})
|
|
81
|
+
sendLogs()
|
|
82
|
+
}
|
|
83
|
+
|
|
21
84
|
function requestReload(reason) {
|
|
22
85
|
if (isReloadPending) return
|
|
23
86
|
|
package/cli/nativue.mjs
CHANGED
|
@@ -19,6 +19,7 @@ import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, watch }
|
|
|
19
19
|
import { randomUUID } from 'node:crypto'
|
|
20
20
|
import { relative } from 'node:path'
|
|
21
21
|
import { fileURLToPath } from 'node:url'
|
|
22
|
+
import { styleText } from 'node:util'
|
|
22
23
|
import { compileToBytecode } from './hermes.mjs'
|
|
23
24
|
import { hotPrelude } from './hot-prelude.mjs'
|
|
24
25
|
import { resolvePlugins } from './plugins.mjs'
|
|
@@ -27,7 +28,9 @@ import { runOnAndroid, runOnIOS } from './run.mjs'
|
|
|
27
28
|
import { createSymbolicator, framedFiles } from './symbolicate.mjs'
|
|
28
29
|
|
|
29
30
|
const PORT = 40836 // 0x9F84, from #0E9F84, the nativue green
|
|
30
|
-
const
|
|
31
|
+
const MAX_POST_LENGTH = 1_000_000 // characters, of what the app posts: a stack, console output
|
|
32
|
+
const LOG_COLORS = { info: 'blue', debug: 'gray', warn: 'yellow', error: 'red' }
|
|
33
|
+
const PLATFORM_WIDTH = 'android'.length
|
|
31
34
|
const BUNDLE_DIRECTORY = 'ios/App'
|
|
32
35
|
const BUNDLE_PATH = `${BUNDLE_DIRECTORY}/main.bundle.js`
|
|
33
36
|
const ANDROID_ASSETS_DIRECTORY = 'android/app/src/main/assets'
|
|
@@ -241,7 +244,13 @@ function vueHotUpdates(sendToApps) {
|
|
|
241
244
|
// runtime is a Vite client: the dev server speaks Vite's protocol for it and relays updates over SSE.
|
|
242
245
|
async function dev() {
|
|
243
246
|
const connectedApps = new Set()
|
|
244
|
-
|
|
247
|
+
// A source map, read once until the code changes: every message to the apps is a reload, an update
|
|
248
|
+
// or a keepalive.
|
|
249
|
+
const sourceMapsByFile = new Map()
|
|
250
|
+
const sendToApps = (message) => {
|
|
251
|
+
sourceMapsByFile.clear()
|
|
252
|
+
connectedApps.forEach((response) => response.write(message))
|
|
253
|
+
}
|
|
245
254
|
const config = viteConfig({
|
|
246
255
|
mode: 'development',
|
|
247
256
|
plugins: [vueHotUpdates((payload) => sendToApps(`data: hot ${JSON.stringify(payload)}\n\n`))],
|
|
@@ -373,19 +382,50 @@ async function dev() {
|
|
|
373
382
|
return sourceMap.ok ? { sourceMap: await sourceMap.json(), directory: BUNDLE_DIRECTORY } : null
|
|
374
383
|
}
|
|
375
384
|
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
385
|
+
function cachedSourceMapOf(file) {
|
|
386
|
+
if (!sourceMapsByFile.has(file)) {
|
|
387
|
+
const sourceMap = sourceMapOf(file)
|
|
388
|
+
|
|
389
|
+
sourceMapsByFile.set(file, sourceMap)
|
|
390
|
+
sourceMap.catch(() => sourceMapsByFile.delete(file))
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
return sourceMapsByFile.get(file)
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/** The text with its stack frames pointing at the app's files. */
|
|
397
|
+
async function symbolicate(text) {
|
|
379
398
|
const files = [...framedFiles(text)]
|
|
380
|
-
|
|
381
|
-
|
|
399
|
+
|
|
400
|
+
if (files.length === 0) return text
|
|
401
|
+
|
|
402
|
+
const sourceMaps = await Promise.all(files.map(cachedSourceMapOf))
|
|
403
|
+
const symbolicateFrames = createSymbolicator(
|
|
382
404
|
Object.fromEntries(
|
|
383
405
|
files.map((file, index) => [file, sourceMaps[index]]).filter(([, map]) => map),
|
|
384
406
|
),
|
|
385
407
|
)
|
|
386
408
|
|
|
409
|
+
return symbolicateFrames(text)
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
// The app posts an error's stack; it gets it back pointing at the app's files.
|
|
413
|
+
async function handleSymbolicate(request, response) {
|
|
414
|
+
const text = await symbolicate(await readBody(request))
|
|
415
|
+
|
|
387
416
|
response.writeHead(200, { 'Content-Type': 'text/plain' })
|
|
388
|
-
response.end(
|
|
417
|
+
response.end(text)
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
// What the app's console prints (hot-client.js).
|
|
421
|
+
async function handleLog(request, response) {
|
|
422
|
+
const { platform, entries } = JSON.parse(await readBody(request))
|
|
423
|
+
|
|
424
|
+
// Without a source map (Vite restarting), a stack prints as the app sent it.
|
|
425
|
+
for (const { level, text } of entries) {
|
|
426
|
+
printLog(platform, level, await symbolicate(text).catch(() => text))
|
|
427
|
+
}
|
|
428
|
+
response.writeHead(204).end()
|
|
389
429
|
}
|
|
390
430
|
|
|
391
431
|
const routes = {
|
|
@@ -393,6 +433,7 @@ async function dev() {
|
|
|
393
433
|
'/bundle.js': handleBundle,
|
|
394
434
|
'/hot': handleHotMessage,
|
|
395
435
|
'/symbolicate': handleSymbolicate,
|
|
436
|
+
'/log': handleLog,
|
|
396
437
|
}
|
|
397
438
|
|
|
398
439
|
http
|
|
@@ -435,11 +476,21 @@ async function dev() {
|
|
|
435
476
|
setInterval(() => sendToApps(':\n\n'), KEEPALIVE_INTERVAL_MS)
|
|
436
477
|
}
|
|
437
478
|
|
|
479
|
+
/** Each line after the first starts under the first's text, past the platform. */
|
|
480
|
+
function printLog(platform, level, text) {
|
|
481
|
+
const color = LOG_COLORS[level]
|
|
482
|
+
const aligned = text.replaceAll('\n', `\n${' '.repeat(PLATFORM_WIDTH + 1)}`)
|
|
483
|
+
|
|
484
|
+
console.log(
|
|
485
|
+
`${styleText('dim', platform.padEnd(PLATFORM_WIDTH))} ${color ? styleText(color, aligned) : aligned}`,
|
|
486
|
+
)
|
|
487
|
+
}
|
|
488
|
+
|
|
438
489
|
async function readBody(request) {
|
|
439
490
|
let text = ''
|
|
440
491
|
for await (const chunk of request) {
|
|
441
492
|
text += chunk
|
|
442
|
-
if (text.length >
|
|
493
|
+
if (text.length > MAX_POST_LENGTH) throw new Error('body too long')
|
|
443
494
|
}
|
|
444
495
|
|
|
445
496
|
return text
|
package/ios/Bridge.swift
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import UIKit
|
|
2
2
|
import JavaScriptRuntime
|
|
3
|
+
import os
|
|
3
4
|
import yoga
|
|
4
5
|
|
|
5
6
|
/// Runs the JS bundle off the main thread and applies the operations sent by the Vue renderer
|
|
@@ -345,7 +346,7 @@ final class Bridge {
|
|
|
345
346
|
}
|
|
346
347
|
}
|
|
347
348
|
|
|
348
|
-
define("log") { arguments in
|
|
349
|
+
define("log") { arguments in logFromJavaScript(string(arguments[0]), level: string(arguments[1])) }
|
|
349
350
|
|
|
350
351
|
define("reportError") { [unowned self] arguments in
|
|
351
352
|
reportError(message: string(arguments[0]), details: string(arguments[1]))
|
|
@@ -1108,6 +1109,49 @@ private func double(_ argument: Any) -> Double {
|
|
|
1108
1109
|
(argument as? NSNumber)?.doubleValue ?? 0
|
|
1109
1110
|
}
|
|
1110
1111
|
|
|
1112
|
+
private let javaScriptLogger = Logger(subsystem: Bundle.main.bundleIdentifier ?? "nativue", category: "JavaScript")
|
|
1113
|
+
/// The system log cuts a message at 1 KB: a longer one goes in parts of this many bytes, in order.
|
|
1114
|
+
private let maxLogPartBytes = 1000
|
|
1115
|
+
|
|
1116
|
+
/// The console's levels as the system log's, which Xcode and Console.app show and filter. Release builds
|
|
1117
|
+
/// keep the text private, as anyone with the device can read the system log.
|
|
1118
|
+
private func logFromJavaScript(_ message: String, level: String) {
|
|
1119
|
+
let type: OSLogType = switch level {
|
|
1120
|
+
case "debug": .debug
|
|
1121
|
+
case "info": .info
|
|
1122
|
+
case "warn", "error": .error
|
|
1123
|
+
default: .default
|
|
1124
|
+
}
|
|
1125
|
+
|
|
1126
|
+
for part in logParts(of: message) {
|
|
1127
|
+
#if DEBUG
|
|
1128
|
+
javaScriptLogger.log(level: type, "\(part, privacy: .public)")
|
|
1129
|
+
#else
|
|
1130
|
+
javaScriptLogger.log(level: type, "\(part, privacy: .private)")
|
|
1131
|
+
#endif
|
|
1132
|
+
}
|
|
1133
|
+
}
|
|
1134
|
+
|
|
1135
|
+
private func logParts(of message: String) -> [String] {
|
|
1136
|
+
var parts: [String] = []
|
|
1137
|
+
var part = ""
|
|
1138
|
+
var partBytes = 0
|
|
1139
|
+
|
|
1140
|
+
for character in message {
|
|
1141
|
+
let characterBytes = character.utf8.count
|
|
1142
|
+
|
|
1143
|
+
if partBytes + characterBytes > maxLogPartBytes {
|
|
1144
|
+
parts.append(part)
|
|
1145
|
+
part = ""
|
|
1146
|
+
partBytes = 0
|
|
1147
|
+
}
|
|
1148
|
+
part.append(character)
|
|
1149
|
+
partBytes += characterBytes
|
|
1150
|
+
}
|
|
1151
|
+
|
|
1152
|
+
return parts + [part]
|
|
1153
|
+
}
|
|
1154
|
+
|
|
1111
1155
|
private func string(_ argument: Any) -> String {
|
|
1112
1156
|
argument as? String ?? ""
|
|
1113
1157
|
}
|
package/ios/Plugins.swift
CHANGED
|
@@ -50,6 +50,15 @@ public final class PluginRegistry {
|
|
|
50
50
|
viewMakers[type] = makeView
|
|
51
51
|
}
|
|
52
52
|
|
|
53
|
+
/// The view controller on top, the app's or what it presents, to present a system screen from (a photo
|
|
54
|
+
/// picker, the camera). nil before the app shows its window.
|
|
55
|
+
@MainActor public var topViewController: UIViewController? {
|
|
56
|
+
let windows = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.flatMap(\.windows)
|
|
57
|
+
guard let root = (windows.first { $0.isKeyWindow } ?? windows.first)?.rootViewController else { return nil }
|
|
58
|
+
|
|
59
|
+
return sequence(first: root, next: \.presentedViewController).reduce(root) { _, presented in presented }
|
|
60
|
+
}
|
|
61
|
+
|
|
53
62
|
/// Draws the tab bar and header icons whose `drawnIcon.drawer` is `drawer` (see router.ts's DrawnIcon).
|
|
54
63
|
/// The image is tinted, like an SF Symbol: only its shape counts.
|
|
55
64
|
public func addIconDrawer(_ drawer: String, _ draw: @escaping DrawIcon) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nativue/core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.19.0",
|
|
4
4
|
"description": "Vue rendering real native views on iOS and Android",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"vue",
|
|
@@ -32,7 +32,7 @@
|
|
|
32
32
|
}
|
|
33
33
|
},
|
|
34
34
|
"scripts": {
|
|
35
|
-
"test": "(cd ../../examples/demo && nativue build) && node test/test.mjs && node test/gradients.test.mjs && node test/native-events.test.mjs && node test/hermes.test.mjs && node test/prebuild.test.mjs",
|
|
35
|
+
"test": "(cd ../../examples/demo && nativue build) && node test/test.mjs && node test/gradients.test.mjs && node test/console.test.mjs && node test/native-events.test.mjs && node test/hermes.test.mjs && node test/prebuild.test.mjs",
|
|
36
36
|
"typecheck": "vue-tsc"
|
|
37
37
|
},
|
|
38
38
|
"dependencies": {
|
package/src/console.ts
ADDED
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
// console as on the web, for engines without one: values formatted as Node and browsers do, %
|
|
2
|
+
// substitutions, table, group and assert. The rest of the web's console does nothing, so libraries
|
|
3
|
+
// calling it keep working.
|
|
4
|
+
|
|
5
|
+
export type LogLevel = 'log' | 'info' | 'debug' | 'warn' | 'error'
|
|
6
|
+
|
|
7
|
+
/** How deep nested objects show; deeper ones read [Object] and [Array], as in Node. */
|
|
8
|
+
const MAX_DEPTH = 2
|
|
9
|
+
/** An object or array longer than this on one line shows one entry per line. */
|
|
10
|
+
const MAX_LINE_LENGTH = 72
|
|
11
|
+
/** Past this, an array, Map, Set or object shows '... N more items', and a string '... N more characters', as in Node. */
|
|
12
|
+
const MAX_ITEMS = 100
|
|
13
|
+
const MAX_STRING_LENGTH = 10_000
|
|
14
|
+
const INDENT = ' '
|
|
15
|
+
const SUBSTITUTION = /%[sdifoOc%]/g
|
|
16
|
+
|
|
17
|
+
export function createConsole(write: (level: LogLevel, text: string) => void) {
|
|
18
|
+
let groupDepth = 0
|
|
19
|
+
|
|
20
|
+
function emit(level: LogLevel, text: string) {
|
|
21
|
+
write(level, text.replace(/^/gm, INDENT.repeat(groupDepth)))
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const printer =
|
|
25
|
+
(level: LogLevel) =>
|
|
26
|
+
(...values: unknown[]) =>
|
|
27
|
+
emit(level, formatValues(values))
|
|
28
|
+
|
|
29
|
+
function group(...labels: unknown[]) {
|
|
30
|
+
if (labels.length > 0) emit('log', formatValues(labels))
|
|
31
|
+
groupDepth++
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// Typed to take what the web's console takes: console.time('label') type-checks.
|
|
35
|
+
const doNothing: (...values: unknown[]) => void = () => {}
|
|
36
|
+
|
|
37
|
+
return {
|
|
38
|
+
log: printer('log'),
|
|
39
|
+
info: printer('info'),
|
|
40
|
+
debug: printer('debug'),
|
|
41
|
+
warn: printer('warn'),
|
|
42
|
+
error: printer('error'),
|
|
43
|
+
|
|
44
|
+
trace(...values: unknown[]) {
|
|
45
|
+
// The stack's first lines are the Error's and this function's frame.
|
|
46
|
+
const stack = (new Error().stack ?? '').split('\n').slice(2).join('\n')
|
|
47
|
+
|
|
48
|
+
emit('log', `Trace: ${formatValues(values)}\n${stack}`)
|
|
49
|
+
},
|
|
50
|
+
|
|
51
|
+
table(data: unknown, columns?: string[]) {
|
|
52
|
+
if (typeof data !== 'object' || data === null) return emit('log', formatValues([data]))
|
|
53
|
+
|
|
54
|
+
emit('log', formatTable(data, columns))
|
|
55
|
+
},
|
|
56
|
+
|
|
57
|
+
group,
|
|
58
|
+
// A terminal can't fold a group: it shows open.
|
|
59
|
+
groupCollapsed: group,
|
|
60
|
+
|
|
61
|
+
groupEnd() {
|
|
62
|
+
groupDepth = Math.max(0, groupDepth - 1)
|
|
63
|
+
},
|
|
64
|
+
|
|
65
|
+
assert(condition?: unknown, ...values: unknown[]) {
|
|
66
|
+
if (condition) return
|
|
67
|
+
|
|
68
|
+
emit(
|
|
69
|
+
'error',
|
|
70
|
+
values.length > 0 ? `Assertion failed: ${formatValues(values)}` : 'Assertion failed',
|
|
71
|
+
)
|
|
72
|
+
},
|
|
73
|
+
|
|
74
|
+
clear: doNothing,
|
|
75
|
+
count: doNothing,
|
|
76
|
+
countReset: doNothing,
|
|
77
|
+
dir: doNothing,
|
|
78
|
+
dirxml: doNothing,
|
|
79
|
+
profile: doNothing,
|
|
80
|
+
profileEnd: doNothing,
|
|
81
|
+
time: doNothing,
|
|
82
|
+
timeEnd: doNothing,
|
|
83
|
+
timeLog: doNothing,
|
|
84
|
+
timeStamp: doNothing,
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Strings as they are, the rest inspected; a first string with % takes the next values in. */
|
|
89
|
+
export function formatValues(values: unknown[]): string {
|
|
90
|
+
const [first, ...rest] = values
|
|
91
|
+
|
|
92
|
+
if (typeof first !== 'string' || !first.includes('%')) return values.map(formatValue).join(' ')
|
|
93
|
+
|
|
94
|
+
const remaining = [...rest]
|
|
95
|
+
const substituted = first.replace(SUBSTITUTION, (token) => {
|
|
96
|
+
if (token === '%%') return '%'
|
|
97
|
+
if (remaining.length === 0) return token
|
|
98
|
+
|
|
99
|
+
return substitute(token, remaining.shift())
|
|
100
|
+
})
|
|
101
|
+
|
|
102
|
+
return [substituted, ...remaining.map(formatValue)].join(' ')
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function substitute(token: string, value: unknown) {
|
|
106
|
+
switch (token) {
|
|
107
|
+
case '%s':
|
|
108
|
+
return formatValue(value)
|
|
109
|
+
case '%d':
|
|
110
|
+
return String(Number(asNumber(value)))
|
|
111
|
+
case '%i':
|
|
112
|
+
return String(parseInt(String(asNumber(value)), 10))
|
|
113
|
+
case '%f':
|
|
114
|
+
return String(parseFloat(String(asNumber(value))))
|
|
115
|
+
case '%c':
|
|
116
|
+
return '' // CSS, which a terminal can't apply
|
|
117
|
+
default:
|
|
118
|
+
return inspect(value)
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** Objects and symbols, which can't be turned into numbers (or would throw), are NaN. */
|
|
123
|
+
function asNumber(value: unknown) {
|
|
124
|
+
return typeof value === 'symbol' || (typeof value === 'object' && value !== null) ? NaN : value
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function formatValue(value: unknown) {
|
|
128
|
+
return typeof value === 'string' ? value : inspect(value)
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export function inspect(value: unknown, depth = 0, seen = new Set<object>()): string {
|
|
132
|
+
switch (typeof value) {
|
|
133
|
+
case 'string':
|
|
134
|
+
return `'${truncate(value).replaceAll("'", "\\'")}'`
|
|
135
|
+
case 'bigint':
|
|
136
|
+
return `${value}n`
|
|
137
|
+
case 'symbol':
|
|
138
|
+
return value.toString()
|
|
139
|
+
case 'function':
|
|
140
|
+
return `[Function: ${value.name || '(anonymous)'}]`
|
|
141
|
+
case 'object':
|
|
142
|
+
return value === null ? 'null' : inspectObject(value, depth, seen)
|
|
143
|
+
default:
|
|
144
|
+
return String(value)
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function inspectObject(value: object, depth: number, seen: Set<object>): string {
|
|
149
|
+
if (value instanceof Error) return value.stack ?? `${value.name}: ${value.message}`
|
|
150
|
+
if (value instanceof Date) return isNaN(value.getTime()) ? 'Invalid Date' : value.toISOString()
|
|
151
|
+
if (value instanceof RegExp) return String(value)
|
|
152
|
+
if (seen.has(value)) return '[Circular]'
|
|
153
|
+
if (depth > MAX_DEPTH) return Array.isArray(value) ? '[Array]' : '[Object]'
|
|
154
|
+
|
|
155
|
+
seen.add(value)
|
|
156
|
+
try {
|
|
157
|
+
const inspectNested = (nested: unknown) => inspect(nested, depth + 1, seen)
|
|
158
|
+
|
|
159
|
+
if (Array.isArray(value)) return wrap('[', formatItems(value, inspectNested), ']')
|
|
160
|
+
if (value instanceof Map) {
|
|
161
|
+
const entries = formatItems(
|
|
162
|
+
[...value],
|
|
163
|
+
([key, item]) => `${inspectNested(key)} => ${inspectNested(item)}`,
|
|
164
|
+
)
|
|
165
|
+
|
|
166
|
+
return wrap(`Map(${value.size}) {`, entries, '}')
|
|
167
|
+
}
|
|
168
|
+
if (value instanceof Set) {
|
|
169
|
+
return wrap(`Set(${value.size}) {`, formatItems([...value], inspectNested), '}')
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
const entries = formatItems(
|
|
173
|
+
Object.entries(value),
|
|
174
|
+
([key, item]) => `${formatKey(key)}: ${inspectNested(item)}`,
|
|
175
|
+
)
|
|
176
|
+
|
|
177
|
+
return wrap(`${className(value)}{`, entries, '}')
|
|
178
|
+
} finally {
|
|
179
|
+
seen.delete(value)
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function formatItems<Item>(items: Item[], format: (item: Item) => string) {
|
|
184
|
+
const shown = items.slice(0, MAX_ITEMS).map(format)
|
|
185
|
+
const hidden = items.length - shown.length
|
|
186
|
+
|
|
187
|
+
return hidden > 0 ? [...shown, `... ${hidden} more item${hidden === 1 ? '' : 's'}`] : shown
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function truncate(text: string) {
|
|
191
|
+
const hidden = text.length - MAX_STRING_LENGTH
|
|
192
|
+
|
|
193
|
+
return hidden > 0 ? `${text.slice(0, MAX_STRING_LENGTH)}... ${hidden} more characters` : text
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** 'Point ' for a class's instance, nothing for a plain object. */
|
|
197
|
+
function className(value: object) {
|
|
198
|
+
const name = Object.getPrototypeOf(value)?.constructor?.name
|
|
199
|
+
|
|
200
|
+
return name && name !== 'Object' ? `${name} ` : ''
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function formatKey(key: string) {
|
|
204
|
+
return /^[A-Za-z_$][\w$]*$/.test(key) ? key : inspect(key)
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function wrap(open: string, entries: string[], close: string) {
|
|
208
|
+
if (entries.length === 0) return `${open}${close}`
|
|
209
|
+
|
|
210
|
+
const oneLine = `${open} ${entries.join(', ')} ${close}`
|
|
211
|
+
|
|
212
|
+
if (oneLine.length <= MAX_LINE_LENGTH && !oneLine.includes('\n')) return oneLine
|
|
213
|
+
|
|
214
|
+
return `${open}\n${entries.map((entry) => entry.replace(/^/gm, INDENT)).join(',\n')}\n${close}`
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** A row per entry, a column per key of the entries that are objects, and Values for the others. */
|
|
218
|
+
export function formatTable(data: object, columns?: string[]) {
|
|
219
|
+
const rows = data instanceof Map ? [...data] : Object.entries(data)
|
|
220
|
+
const keys = columns ?? [
|
|
221
|
+
...new Set(rows.flatMap(([, row]) => (isTableRow(row) ? Object.keys(row) : []))),
|
|
222
|
+
]
|
|
223
|
+
const hasValues = rows.some(([, row]) => !isTableRow(row))
|
|
224
|
+
const header = ['(index)', ...keys, ...(hasValues ? ['Values'] : [])]
|
|
225
|
+
const body = rows.map(([index, row]) => [
|
|
226
|
+
String(index),
|
|
227
|
+
...keys.map((key) => (isTableRow(row) && key in row ? inspect(row[key], MAX_DEPTH) : '')),
|
|
228
|
+
...(hasValues ? [isTableRow(row) ? '' : inspect(row, MAX_DEPTH)] : []),
|
|
229
|
+
])
|
|
230
|
+
const widths = header.map((title, column) =>
|
|
231
|
+
Math.max(title.length, ...body.map((cells) => cells[column].length)),
|
|
232
|
+
)
|
|
233
|
+
const line = (left: string, middle: string, right: string) =>
|
|
234
|
+
left + widths.map((width) => '─'.repeat(width + 2)).join(middle) + right
|
|
235
|
+
const row = (cells: string[]) =>
|
|
236
|
+
`│ ${cells.map((cell, column) => cell.padEnd(widths[column])).join(' │ ')} │`
|
|
237
|
+
|
|
238
|
+
return [
|
|
239
|
+
line('┌', '┬', '┐'),
|
|
240
|
+
row(header),
|
|
241
|
+
line('├', '┼', '┤'),
|
|
242
|
+
...body.map(row),
|
|
243
|
+
line('└', '┴', '┘'),
|
|
244
|
+
].join('\n')
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
function isTableRow(value: unknown): value is Record<string, unknown> {
|
|
248
|
+
return typeof value === 'object' && value !== null
|
|
249
|
+
}
|
package/src/globals.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
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
3
|
import type { ColorScheme, WindowSize } from './appearance'
|
|
4
|
+
import type { createConsole, LogLevel } from './console'
|
|
4
5
|
import type { LayoutEvent, NativeModule, NetworkEventPayloads } from './types'
|
|
5
6
|
|
|
6
7
|
declare global {
|
|
@@ -28,12 +29,9 @@ declare global {
|
|
|
28
29
|
/** From the runtime (not __native): an object whose garbage collection releases the blob's bytes. */
|
|
29
30
|
var __blobCollector: ((blobId: string) => object) | undefined
|
|
30
31
|
|
|
31
|
-
var console:
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
warn(...values: unknown[]): void
|
|
35
|
-
error(...values: unknown[]): void
|
|
36
|
-
}
|
|
32
|
+
var console: ReturnType<typeof createConsole>
|
|
33
|
+
/** Development: the hot client's, sending what the console prints to the dev server. */
|
|
34
|
+
var __nativueOnLog: ((level: LogLevel, text: string) => void) | undefined
|
|
37
35
|
|
|
38
36
|
function setTimeout<Args extends unknown[]>(
|
|
39
37
|
callback: (...args: Args) => void,
|
package/src/prelude.ts
CHANGED
|
@@ -1,12 +1,10 @@
|
|
|
1
1
|
// The web APIs JavaScript engines don't have, built on the native bridge: console and timers. Runs
|
|
2
2
|
// first, before any other module. Engines (and Node, in tests) that have them keep theirs.
|
|
3
|
+
import { createConsole } from './console'
|
|
4
|
+
|
|
3
5
|
const timerCallbacks = new Map<number, () => void>()
|
|
4
6
|
let nextTimerId = 1
|
|
5
7
|
|
|
6
|
-
function log(...values: unknown[]) {
|
|
7
|
-
__native.log(values.map(String).join(' '))
|
|
8
|
-
}
|
|
9
|
-
|
|
10
8
|
function armTimer(timerId: number, callback: () => void, delay: number) {
|
|
11
9
|
timerCallbacks.set(timerId, callback)
|
|
12
10
|
__native.setTimer(timerId, delay)
|
|
@@ -16,7 +14,11 @@ function millisecondsOf(delay: number | undefined) {
|
|
|
16
14
|
return Math.max(0, Math.round(delay ?? 0))
|
|
17
15
|
}
|
|
18
16
|
|
|
19
|
-
|
|
17
|
+
// In development, the dev server's hot client also prints it in the terminal.
|
|
18
|
+
globalThis.console ??= createConsole((level, text) => {
|
|
19
|
+
__native.log(text, level)
|
|
20
|
+
globalThis.__nativueOnLog?.(level, text)
|
|
21
|
+
})
|
|
20
22
|
|
|
21
23
|
globalThis.setTimeout ??= (callback, delay, ...args) => {
|
|
22
24
|
const timerId = nextTimerId++
|
package/src/types.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// Types shared by the framework and apps: styles, native events and the bridge to the native side.
|
|
2
2
|
import type { AnimatedNode } from './animated'
|
|
3
|
+
import type { LogLevel } from './console'
|
|
3
4
|
|
|
4
5
|
type Dimension = number | 'auto' | `${number}%`
|
|
5
6
|
type Edge = '' | 'Top' | 'Right' | 'Bottom' | 'Left' | 'Horizontal' | 'Vertical' | 'Start' | 'End'
|
|
@@ -128,7 +129,7 @@ export interface LayoutAnimationConfig {
|
|
|
128
129
|
|
|
129
130
|
/** Functions the native side exposes as globalThis.__native (see Bridge.swift). */
|
|
130
131
|
export interface NativeModule {
|
|
131
|
-
log(message: string): void
|
|
132
|
+
log(message: string, level: LogLevel): void
|
|
132
133
|
reportError(message: string, details: string): void
|
|
133
134
|
windowSize(): { width: number; height: number }
|
|
134
135
|
platform(): 'ios' | 'android'
|