@nativue/core 0.12.0 → 0.13.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 +2 -1
- package/README.md +1 -1
- package/android/src/main/java/dev/nativue/Bridge.kt +52 -5
- package/android/src/main/java/dev/nativue/DownloadBanner.kt +45 -0
- package/android/src/main/java/dev/nativue/NativueActivity.kt +14 -0
- package/cli/hot-client.js +192 -0
- package/cli/nativue.mjs +223 -53
- package/cli/symbolicate.mjs +26 -14
- package/ios/Bridge.swift +57 -5
- package/ios/DownloadBanner.swift +38 -0
- package/ios/NativueView.swift +19 -0
- package/package.json +1 -1
- package/src/globals.ts +1 -0
- package/src/renderer.ts +1 -0
- package/src/router.ts +29 -0
- package/src/types.ts +3 -0
package/AGENTS.md
CHANGED
|
@@ -86,7 +86,8 @@ Import the runtime from `vue`: `ref`, `computed`, `StyleSheet`, `Animated`, `Lay
|
|
|
86
86
|
- Official packages: `@nativue/icons` (icon components), `@nativue/tailwind`, `@nativue/haptics`,
|
|
87
87
|
`@nativue/sqlite`. A package with native code needs the app rebuilt with `npm run ios` or
|
|
88
88
|
`npm run android`, not just a reload.
|
|
89
|
-
- Commands: `npm run ios` / `npm run android` build and open the app, then
|
|
89
|
+
- Commands: `npm run ios` / `npm run android` build and open the app, then update it on save
|
|
90
|
+
(template edits keep the component's state; script edits re-create the component);
|
|
90
91
|
`npm run typecheck` checks scripts and templates; `npm run build` makes the release bundle;
|
|
91
92
|
`npm run format` formats with Prettier.
|
|
92
93
|
- Native code the app needs (a platform API no package covers) goes in `native/<name>/ios` and
|
package/README.md
CHANGED
|
@@ -17,7 +17,7 @@ This package holds:
|
|
|
17
17
|
|
|
18
18
|
```sh
|
|
19
19
|
nativue run ios # or android: builds, opens the app on a simulator or emulator, then dev
|
|
20
|
-
nativue dev #
|
|
20
|
+
nativue dev # updates the running app on save
|
|
21
21
|
nativue build # bundles the app into ios/ and android/ (--production for releases)
|
|
22
22
|
```
|
|
23
23
|
|
|
@@ -31,6 +31,7 @@ import com.facebook.yoga.YogaDisplay
|
|
|
31
31
|
import com.facebook.yoga.YogaEdge
|
|
32
32
|
import com.facebook.yoga.YogaFlexDirection
|
|
33
33
|
import com.facebook.yoga.YogaPositionType
|
|
34
|
+
import java.io.ByteArrayOutputStream
|
|
34
35
|
import java.net.HttpURLConnection
|
|
35
36
|
import java.net.URL
|
|
36
37
|
import kotlin.concurrent.thread
|
|
@@ -51,6 +52,9 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
|
|
|
51
52
|
@Volatile
|
|
52
53
|
private var reloadConnection: HttpURLConnection? = null
|
|
53
54
|
|
|
55
|
+
/** The router's screens, reopened after a reload in development. Only touched on the JS thread. */
|
|
56
|
+
private var savedNavigation: String? = null
|
|
57
|
+
|
|
54
58
|
private val javaScriptHandler = startJavaScriptThread()
|
|
55
59
|
private val isDebuggable = activity.applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE != 0
|
|
56
60
|
private val density = activity.resources.displayMetrics.density
|
|
@@ -84,6 +88,7 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
|
|
|
84
88
|
/** The bundle running now, for the error screen's Reload. */
|
|
85
89
|
private var bundle = ByteArray(0)
|
|
86
90
|
private val errorOverlay = ErrorOverlay(activity)
|
|
91
|
+
private val downloadBanner = DownloadBanner(activity)
|
|
87
92
|
|
|
88
93
|
fun start() {
|
|
89
94
|
NativeNode.setPixelDensity(density)
|
|
@@ -329,6 +334,8 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
|
|
|
329
334
|
put("windowSize") { _ -> windowSize }
|
|
330
335
|
put("platform") { _ -> "android" }
|
|
331
336
|
put("colorScheme") { _ -> colorScheme() }
|
|
337
|
+
put("savedNavigation") { _ -> savedNavigation }
|
|
338
|
+
put("saveNavigation") { arguments -> savedNavigation = arguments[0] as String }
|
|
332
339
|
put("accessibilityInfo") { _ -> accessibilityStatus(activity) }
|
|
333
340
|
put("announce") { arguments ->
|
|
334
341
|
val message = arguments[0] as String
|
|
@@ -513,7 +520,7 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
|
|
|
513
520
|
return hosts.map { "http://$it:$DEV_SERVER_PORT" }
|
|
514
521
|
}
|
|
515
522
|
|
|
516
|
-
/** The dev server sends `data: reload` on connect and
|
|
523
|
+
/** The dev server sends `data: reload` on connect and when the app must reload, `data: hot` with an update. */
|
|
517
524
|
private fun listenForReload() {
|
|
518
525
|
val candidateURLs = devServerURLs()
|
|
519
526
|
var attempt = 0
|
|
@@ -526,10 +533,13 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
|
|
|
526
533
|
reloadConnection = connection
|
|
527
534
|
|
|
528
535
|
connection.inputStream.bufferedReader().useLines { lines ->
|
|
529
|
-
lines.
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
536
|
+
lines.forEach { line ->
|
|
537
|
+
if (line == "data: reload") {
|
|
538
|
+
downloadAndRun()
|
|
539
|
+
} else if (line.startsWith("data: hot ")) {
|
|
540
|
+
val update = line.removePrefix("data: hot ")
|
|
541
|
+
evaluate { runtime?.call("__hotUpdate", update) }
|
|
542
|
+
}
|
|
533
543
|
}
|
|
534
544
|
}
|
|
535
545
|
}
|
|
@@ -538,6 +548,43 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
|
|
|
538
548
|
}
|
|
539
549
|
}
|
|
540
550
|
|
|
551
|
+
fun reload() {
|
|
552
|
+
if (isDebuggable) thread(isDaemon = true) { runCatching { downloadAndRun() } }
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
private fun downloadAndRun() {
|
|
556
|
+
val bundle = download(URL("$devServerURL/bundle.js"))
|
|
557
|
+
Log.i(TAG, "reload")
|
|
558
|
+
mainHandler.post { run(bundle) }
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
private fun download(url: URL): ByteArray {
|
|
562
|
+
val connection = url.openConnection() as HttpURLConnection
|
|
563
|
+
val length = connection.contentLengthLong
|
|
564
|
+
val bundle = ByteArrayOutputStream()
|
|
565
|
+
val buffer = ByteArray(64 * 1024)
|
|
566
|
+
|
|
567
|
+
mainHandler.post { downloadBanner.show(0.0) }
|
|
568
|
+
try {
|
|
569
|
+
connection.inputStream.use { input ->
|
|
570
|
+
while (true) {
|
|
571
|
+
val count = input.read(buffer)
|
|
572
|
+
if (count < 0) break
|
|
573
|
+
|
|
574
|
+
bundle.write(buffer, 0, count)
|
|
575
|
+
if (length > 0) {
|
|
576
|
+
val progress = bundle.size().toDouble() / length
|
|
577
|
+
mainHandler.post { downloadBanner.show(progress) }
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
} finally {
|
|
582
|
+
mainHandler.post { downloadBanner.hide() }
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
return bundle.toByteArray()
|
|
586
|
+
}
|
|
587
|
+
|
|
541
588
|
// ---------- Main thread ----------
|
|
542
589
|
|
|
543
590
|
/** Vue removes only a subtree's root: the nodes under it are forgotten with it. */
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
package dev.nativue
|
|
2
|
+
|
|
3
|
+
import android.app.Activity
|
|
4
|
+
import android.graphics.Color
|
|
5
|
+
import android.graphics.Typeface
|
|
6
|
+
import android.view.Gravity
|
|
7
|
+
import android.view.ViewGroup
|
|
8
|
+
import android.widget.FrameLayout
|
|
9
|
+
import android.widget.TextView
|
|
10
|
+
import androidx.core.view.ViewCompat
|
|
11
|
+
import androidx.core.view.WindowInsetsCompat
|
|
12
|
+
|
|
13
|
+
/** Development only: a strip at the top of the screen while the app downloads the dev server's bundle. Mirrors ios/DownloadBanner.swift. */
|
|
14
|
+
class DownloadBanner(private val activity: Activity) {
|
|
15
|
+
private var label: TextView? = null
|
|
16
|
+
|
|
17
|
+
fun show(progress: Double) {
|
|
18
|
+
val label = label ?: makeLabel().also { label = it }
|
|
19
|
+
label.text = "Downloading ${(progress * 100).toInt()}%"
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
fun hide() {
|
|
23
|
+
label?.let { (it.parent as? ViewGroup)?.removeView(it) }
|
|
24
|
+
label = null
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
private fun makeLabel(): TextView {
|
|
28
|
+
val height = (24 * activity.resources.displayMetrics.density).toInt()
|
|
29
|
+
val label = TextView(activity)
|
|
30
|
+
label.setBackgroundColor(Color.rgb(0x0B, 0x12, 0x20))
|
|
31
|
+
label.setTextColor(Color.rgb(0xF1, 0xF5, 0xF9))
|
|
32
|
+
label.textSize = 12f
|
|
33
|
+
label.typeface = Typeface.DEFAULT_BOLD
|
|
34
|
+
label.gravity = Gravity.CENTER
|
|
35
|
+
ViewCompat.setOnApplyWindowInsetsListener(label) { view, insets ->
|
|
36
|
+
val top = insets.getInsets(WindowInsetsCompat.Type.statusBars()).top
|
|
37
|
+
view.layoutParams = (view.layoutParams as FrameLayout.LayoutParams).apply { topMargin = top }
|
|
38
|
+
insets
|
|
39
|
+
}
|
|
40
|
+
activity.addContentView(label, FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, height))
|
|
41
|
+
ViewCompat.requestApplyInsets(label)
|
|
42
|
+
|
|
43
|
+
return label
|
|
44
|
+
}
|
|
45
|
+
}
|
|
@@ -5,8 +5,10 @@ import android.content.Intent
|
|
|
5
5
|
import android.content.res.Configuration
|
|
6
6
|
import android.os.Build
|
|
7
7
|
import android.os.Bundle
|
|
8
|
+
import android.view.KeyEvent
|
|
8
9
|
import android.view.ViewGroup
|
|
9
10
|
import android.view.ViewTreeObserver
|
|
11
|
+
import android.widget.EditText
|
|
10
12
|
import android.window.OnBackInvokedCallback
|
|
11
13
|
import android.window.OnBackInvokedDispatcher
|
|
12
14
|
import androidx.annotation.RequiresApi
|
|
@@ -15,6 +17,7 @@ import com.facebook.soloader.SoLoader
|
|
|
15
17
|
/** The app's activity: runs assets/main.bundle.js (or, in debug builds, the dev server's bundle). */
|
|
16
18
|
open class NativueActivity : Activity() {
|
|
17
19
|
private lateinit var bridge: Bridge
|
|
20
|
+
private var lastRKeyTime = 0L
|
|
18
21
|
|
|
19
22
|
override fun onCreate(savedInstanceState: Bundle?) {
|
|
20
23
|
super.onCreate(savedInstanceState)
|
|
@@ -71,6 +74,15 @@ open class NativueActivity : Activity() {
|
|
|
71
74
|
predictiveBack.setRegistered(handlesBack)
|
|
72
75
|
}
|
|
73
76
|
|
|
77
|
+
override fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean {
|
|
78
|
+
if (keyCode != KeyEvent.KEYCODE_R || currentFocus is EditText) return super.onKeyUp(keyCode, event)
|
|
79
|
+
|
|
80
|
+
if (event.eventTime - lastRKeyTime < DOUBLE_PRESS_MS) bridge.reload()
|
|
81
|
+
lastRKeyTime = event.eventTime
|
|
82
|
+
|
|
83
|
+
return true
|
|
84
|
+
}
|
|
85
|
+
|
|
74
86
|
@Deprecated("Deprecated in Java")
|
|
75
87
|
override fun onBackPressed() {
|
|
76
88
|
if (!bridge.goBack()) super.onBackPressed()
|
|
@@ -96,3 +108,5 @@ private class PredictiveBack(private val activity: Activity, onBack: () -> Unit)
|
|
|
96
108
|
else dispatcher.unregisterOnBackInvokedCallback(callback)
|
|
97
109
|
}
|
|
98
110
|
}
|
|
111
|
+
|
|
112
|
+
private const val DOUBLE_PRESS_MS = 500
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
// Hot module replacement in the app: runs before the dev bundle, after Rolldown's DevRuntime. The dev
|
|
2
|
+
// server fills in __NATIVUE_HOT__ ({ clientId, serverURL }). Native code calls __hotUpdate(json) for
|
|
3
|
+
// each `data: hot` line; anything that can't be applied asks Vite for a full reload.
|
|
4
|
+
;(() => {
|
|
5
|
+
const { clientId, serverURL } = __NATIVUE_HOT__
|
|
6
|
+
const acceptCallbacksById = new Map()
|
|
7
|
+
const disposersById = new Map()
|
|
8
|
+
const dataById = new Map()
|
|
9
|
+
const listenersById = new Map()
|
|
10
|
+
let lastSequence = 0
|
|
11
|
+
let isReloadPending = false
|
|
12
|
+
let queue = Promise.resolve()
|
|
13
|
+
|
|
14
|
+
function send(event, data) {
|
|
15
|
+
fetch(`${serverURL}/hot`, {
|
|
16
|
+
method: 'POST',
|
|
17
|
+
body: JSON.stringify({ clientId, message: { type: 'custom', event, data } }),
|
|
18
|
+
}).catch(() => {})
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function requestReload(reason) {
|
|
22
|
+
if (isReloadPending) return
|
|
23
|
+
|
|
24
|
+
isReloadPending = true
|
|
25
|
+
console.log(`[nativue] reload: ${reason}`)
|
|
26
|
+
send('vite:bundled-dev:reload-needed', { reason })
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function hotContext(id) {
|
|
30
|
+
if (!dataById.has(id)) dataById.set(id, {})
|
|
31
|
+
acceptCallbacksById.set(id, [])
|
|
32
|
+
listenersById.set(id, [])
|
|
33
|
+
|
|
34
|
+
const accept = (deps, callback) => acceptCallbacksById.get(id).push({ deps, callback })
|
|
35
|
+
|
|
36
|
+
return {
|
|
37
|
+
get data() {
|
|
38
|
+
return dataById.get(id)
|
|
39
|
+
},
|
|
40
|
+
|
|
41
|
+
accept(deps, callback) {
|
|
42
|
+
if (typeof deps === 'function' || !deps) accept([id], ([module]) => deps?.(module))
|
|
43
|
+
else if (typeof deps === 'string') accept([deps], ([module]) => callback?.(module))
|
|
44
|
+
else accept(deps, callback ?? (() => {}))
|
|
45
|
+
},
|
|
46
|
+
|
|
47
|
+
acceptExports(_names, callback) {
|
|
48
|
+
accept([id], ([module]) => callback?.(module))
|
|
49
|
+
},
|
|
50
|
+
|
|
51
|
+
dispose(callback) {
|
|
52
|
+
disposersById.set(id, callback)
|
|
53
|
+
},
|
|
54
|
+
|
|
55
|
+
invalidate() {
|
|
56
|
+
requestReload(`${id} invalidated itself`)
|
|
57
|
+
},
|
|
58
|
+
|
|
59
|
+
on(event, callback) {
|
|
60
|
+
listenersById.get(id).push({ event, callback })
|
|
61
|
+
},
|
|
62
|
+
|
|
63
|
+
off(event, callback) {
|
|
64
|
+
const listeners = listenersById.get(id)
|
|
65
|
+
listenersById.set(
|
|
66
|
+
id,
|
|
67
|
+
listeners.filter(
|
|
68
|
+
(listener) => listener.callback !== callback || listener.event !== event,
|
|
69
|
+
),
|
|
70
|
+
)
|
|
71
|
+
},
|
|
72
|
+
|
|
73
|
+
send(event, data) {
|
|
74
|
+
send(event, data)
|
|
75
|
+
},
|
|
76
|
+
|
|
77
|
+
prune() {},
|
|
78
|
+
decline() {},
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const acceptsDependency = (parent, id) =>
|
|
83
|
+
(acceptCallbacksById.get(parent) ?? []).some(({ deps }) => deps.includes(id))
|
|
84
|
+
|
|
85
|
+
function findBoundaries(changedIds) {
|
|
86
|
+
const boundaries = []
|
|
87
|
+
const updateSet = new Set()
|
|
88
|
+
|
|
89
|
+
function bubble(id) {
|
|
90
|
+
if (updateSet.has(id)) return
|
|
91
|
+
|
|
92
|
+
updateSet.add(id)
|
|
93
|
+
if (acceptsDependency(id, id)) return boundaries.push({ boundary: id, acceptedVia: id })
|
|
94
|
+
|
|
95
|
+
for (const parent of runtime
|
|
96
|
+
.getImporters(id)
|
|
97
|
+
.filter((parent) => runtime.isExecuted(parent))) {
|
|
98
|
+
if (acceptsDependency(parent, id)) boundaries.push({ boundary: parent, acceptedVia: id })
|
|
99
|
+
else bubble(parent)
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
for (const id of changedIds) if (runtime.isExecuted(id)) bubble(id)
|
|
104
|
+
|
|
105
|
+
return { boundaries, updateSet }
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function hasEntryWithoutBoundary({ boundaries, updateSet }) {
|
|
109
|
+
const reRun = new Set()
|
|
110
|
+
const pending = boundaries.map(({ acceptedVia }) => acceptedVia)
|
|
111
|
+
|
|
112
|
+
while (pending.length > 0) {
|
|
113
|
+
const id = pending.pop()
|
|
114
|
+
if (reRun.has(id) || !updateSet.has(id)) continue
|
|
115
|
+
|
|
116
|
+
reRun.add(id)
|
|
117
|
+
pending.push(...(runtime.staticImports.get(id)?.edges ?? []))
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
return [...updateSet].some((id) => runtime.isEntry(id) && !reRun.has(id))
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
async function apply({ changedIds, url, seq }) {
|
|
124
|
+
if (isReloadPending) return
|
|
125
|
+
if (seq !== lastSequence + 1) return requestReload('missed an update')
|
|
126
|
+
|
|
127
|
+
lastSequence = seq
|
|
128
|
+
|
|
129
|
+
const update = findBoundaries(changedIds)
|
|
130
|
+
if (update.updateSet.size === 0) return
|
|
131
|
+
if (hasEntryWithoutBoundary(update)) return requestReload(`${changedIds.join(', ')} changed`)
|
|
132
|
+
|
|
133
|
+
const patch = await (await fetch(`${serverURL}/${url}`)).text()
|
|
134
|
+
;(0, eval)(`${patch}\n//# sourceURL=${url}`)
|
|
135
|
+
|
|
136
|
+
if ([...update.updateSet].some((id) => !runtime.hasFactory(id))) {
|
|
137
|
+
return requestReload('a module is missing from the update')
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
const applies = update.boundaries.map(({ boundary, acceptedVia }) => ({
|
|
141
|
+
acceptedVia,
|
|
142
|
+
callbacks: acceptCallbacksById.get(boundary).filter(({ deps }) => deps.includes(acceptedVia)),
|
|
143
|
+
}))
|
|
144
|
+
|
|
145
|
+
for (const id of update.updateSet) runtime.removeModuleCache(id)
|
|
146
|
+
for (const { acceptedVia, callbacks } of applies) {
|
|
147
|
+
runtime.initModule(acceptedVia)
|
|
148
|
+
|
|
149
|
+
const exports = runtime.loadExports(acceptedVia)
|
|
150
|
+
for (const { deps, callback } of callbacks) {
|
|
151
|
+
callback(deps.map((dep) => (dep === acceptedVia ? exports : undefined)))
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
console.log(`[nativue] hot updated ${changedIds.join(', ')}`)
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function notifyListeners(event, data) {
|
|
159
|
+
for (const listeners of listenersById.values()) {
|
|
160
|
+
for (const listener of listeners) if (listener.event === event) listener.callback(data)
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
class NativueDevRuntime extends DevRuntime {
|
|
165
|
+
payloadDelivered(filename) {
|
|
166
|
+
send('vite:bundled-dev:payload-delivered', { filename })
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
createModuleHotContext(id) {
|
|
170
|
+
return hotContext(id)
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
const runtime = new NativueDevRuntime(clientId)
|
|
175
|
+
runtime.hooks = {
|
|
176
|
+
createModuleHotContext: (id) => runtime.createModuleHotContext(id),
|
|
177
|
+
onModuleCacheRemoval: (id) => disposersById.get(id)?.(dataById.get(id)),
|
|
178
|
+
}
|
|
179
|
+
globalThis.__rolldown_runtime__ = runtime
|
|
180
|
+
|
|
181
|
+
globalThis.__hotUpdate = (json) => {
|
|
182
|
+
const update = JSON.parse(json)
|
|
183
|
+
if (update.type === 'custom') return notifyListeners(update.event, update.data)
|
|
184
|
+
if (update.clientId !== clientId) return
|
|
185
|
+
|
|
186
|
+
send('nativue:received')
|
|
187
|
+
|
|
188
|
+
queue = queue
|
|
189
|
+
.then(() => apply(update))
|
|
190
|
+
.catch((error) => requestReload(error?.message ?? String(error)))
|
|
191
|
+
}
|
|
192
|
+
})()
|
package/cli/nativue.mjs
CHANGED
|
@@ -3,31 +3,40 @@
|
|
|
3
3
|
// nativue build bundles src/app/ into ios/App/main.bundle.js (and, with an android/
|
|
4
4
|
// folder, android/app/src/main/assets/main.bundle.js); Hermes bytecode
|
|
5
5
|
// with --production
|
|
6
|
-
// nativue dev
|
|
6
|
+
// nativue dev serves the app and updates it on save, keeping its state where it can
|
|
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
9
|
// --device for a phone, --device <name or id> for a given one;
|
|
10
10
|
// --no-dev only opens the app
|
|
11
|
-
import { build, loadConfigFromFile, transformWithOxc } from 'vite'
|
|
11
|
+
import { build, createServer, loadConfigFromFile, transformWithOxc } from 'vite'
|
|
12
12
|
import vue from '@vitejs/plugin-vue'
|
|
13
13
|
import http from 'node:http'
|
|
14
14
|
import net from 'node:net'
|
|
15
15
|
import { execFileSync } from 'node:child_process'
|
|
16
|
-
import {
|
|
16
|
+
import {
|
|
17
|
+
copyFileSync,
|
|
18
|
+
existsSync,
|
|
19
|
+
mkdirSync,
|
|
20
|
+
readdirSync,
|
|
21
|
+
readFileSync,
|
|
22
|
+
renameSync,
|
|
23
|
+
watch,
|
|
24
|
+
} from 'node:fs'
|
|
25
|
+
import { randomUUID } from 'node:crypto'
|
|
17
26
|
import { createRequire } from 'node:module'
|
|
18
27
|
import { dirname, relative } from 'node:path'
|
|
19
28
|
import { fileURLToPath } from 'node:url'
|
|
20
29
|
import { linkIosPlugins } from './link.mjs'
|
|
21
30
|
import { runOnAndroid, runOnIOS } from './run.mjs'
|
|
22
|
-
import { createSymbolicator } from './symbolicate.mjs'
|
|
31
|
+
import { createSymbolicator, framedFiles } from './symbolicate.mjs'
|
|
23
32
|
|
|
24
33
|
const PORT = 40836 // 0x9F84, from #0E9F84, the nativue green
|
|
25
34
|
const MAX_STACK_LENGTH = 1_000_000 // characters, of a stack the app posts to /symbolicate
|
|
26
35
|
const BUNDLE_DIRECTORY = 'ios/App'
|
|
27
36
|
const BUNDLE_PATH = `${BUNDLE_DIRECTORY}/main.bundle.js`
|
|
28
|
-
const SOURCE_MAP_PATH = `${BUNDLE_PATH}.map`
|
|
29
37
|
const ANDROID_ASSETS_DIRECTORY = 'android/app/src/main/assets'
|
|
30
38
|
const KEEPALIVE_INTERVAL_MS = 15000
|
|
39
|
+
const UNANSWERED_UPDATE_TIMEOUT_MS = 10000
|
|
31
40
|
|
|
32
41
|
const NATIVE_COMPONENT_TAGS = [
|
|
33
42
|
'View',
|
|
@@ -179,7 +188,7 @@ const APP_VITE_PLUGINS = [
|
|
|
179
188
|
...appPlugins.flatMap((plugin) => plugin.vite ?? []),
|
|
180
189
|
]
|
|
181
190
|
|
|
182
|
-
function viteConfig({ mode, plugins = []
|
|
191
|
+
function viteConfig({ mode, plugins = [] }) {
|
|
183
192
|
// Vite reads the mode from NODE_ENV: development builds keep each component's file (for errors).
|
|
184
193
|
process.env.NODE_ENV = mode
|
|
185
194
|
|
|
@@ -222,16 +231,124 @@ function viteConfig({ mode, plugins = [], watch = null, sourcemap = false }) {
|
|
|
222
231
|
outDir: BUNDLE_DIRECTORY,
|
|
223
232
|
emptyOutDir: false,
|
|
224
233
|
minify: mode === 'production',
|
|
225
|
-
sourcemap,
|
|
226
|
-
watch,
|
|
227
234
|
},
|
|
228
235
|
}
|
|
229
236
|
}
|
|
230
237
|
|
|
231
|
-
|
|
238
|
+
// Full bundle mode skips the plugins' handleHotUpdate. @vitejs/plugin-vue's tells a template-only change
|
|
239
|
+
// apart, so the component re-renders and keeps its state, and tells the app which file changed: run it
|
|
240
|
+
// for every change, before it's rebuilt.
|
|
241
|
+
function vueHotUpdates(sendToApps) {
|
|
242
|
+
let vuePlugin
|
|
243
|
+
|
|
244
|
+
return {
|
|
245
|
+
name: 'nativue-vue-hot-updates',
|
|
246
|
+
|
|
247
|
+
configResolved(config) {
|
|
248
|
+
vuePlugin = config.plugins.find((plugin) => plugin.name === 'vite:vue')
|
|
249
|
+
},
|
|
250
|
+
|
|
251
|
+
async watchChange(file) {
|
|
252
|
+
if (!existsSync(file)) return
|
|
253
|
+
|
|
254
|
+
await vuePlugin.handleHotUpdate({
|
|
255
|
+
file,
|
|
256
|
+
modules: [],
|
|
257
|
+
read: () => readFileSync(file, 'utf8'),
|
|
258
|
+
server: { ws: { send: sendToApps } },
|
|
259
|
+
})
|
|
260
|
+
},
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
function hotPrelude(clientId, serverURL) {
|
|
265
|
+
const viteRequire = createRequire(createRequire(import.meta.url).resolve('vite'))
|
|
266
|
+
const runtime = readFileSync(viteRequire.resolve('rolldown/experimental/runtime'), 'utf8')
|
|
267
|
+
const client = readFileSync(frameworkPath('cli/hot-client.js'), 'utf8')
|
|
268
|
+
const options = JSON.stringify({ clientId, serverURL })
|
|
269
|
+
|
|
270
|
+
return `${runtime.replace(/^export \{[^}]*\};?$/m, '')}\nvar __NATIVUE_HOT__ = ${options};\n${client}\n`
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
// Vite's full bundle mode builds the app and, on save, a patch with the changed modules. Each app
|
|
274
|
+
// runtime is a Vite client: the dev server speaks Vite's protocol for it and relays updates over SSE.
|
|
275
|
+
async function dev() {
|
|
232
276
|
const connectedApps = new Set()
|
|
233
|
-
let symbolicate = (text) => text
|
|
234
277
|
const sendToApps = (message) => connectedApps.forEach((response) => response.write(message))
|
|
278
|
+
const config = viteConfig({
|
|
279
|
+
mode: 'development',
|
|
280
|
+
plugins: [vueHotUpdates((payload) => sendToApps(`data: hot ${JSON.stringify(payload)}\n\n`))],
|
|
281
|
+
})
|
|
282
|
+
const vite = await createServer({
|
|
283
|
+
...config,
|
|
284
|
+
experimental: { bundledDev: true },
|
|
285
|
+
server: { host: '127.0.0.1', port: PORT + 1, watch: {} },
|
|
286
|
+
build: {
|
|
287
|
+
...config.build,
|
|
288
|
+
lib: false,
|
|
289
|
+
rolldownOptions: {
|
|
290
|
+
input: frameworkPath('src/entry.ts'),
|
|
291
|
+
experimental: { devMode: { lazy: false } },
|
|
292
|
+
},
|
|
293
|
+
},
|
|
294
|
+
})
|
|
295
|
+
await vite.listen()
|
|
296
|
+
|
|
297
|
+
const viteURL = `http://127.0.0.1:${vite.httpServer.address().port}`
|
|
298
|
+
const socketsByClientId = new Map()
|
|
299
|
+
const silenceTimersByClientId = new Map()
|
|
300
|
+
let reloadTimer = null
|
|
301
|
+
|
|
302
|
+
function reloadApps() {
|
|
303
|
+
clearTimeout(reloadTimer)
|
|
304
|
+
reloadTimer = setTimeout(() => {
|
|
305
|
+
socketsByClientId.forEach((socket) => socket.close())
|
|
306
|
+
socketsByClientId.clear()
|
|
307
|
+
console.log(`reload -> ${connectedApps.size} app(s)`)
|
|
308
|
+
sendToApps('data: reload\n\n')
|
|
309
|
+
}, 50)
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
function sendToVite(clientId, message) {
|
|
313
|
+
const socket = socketsByClientId.get(clientId)
|
|
314
|
+
if (!socket) return
|
|
315
|
+
|
|
316
|
+
if (socket.readyState === WebSocket.OPEN) socket.send(JSON.stringify(message))
|
|
317
|
+
else socket.addEventListener('open', () => socket.send(JSON.stringify(message)), { once: true })
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
function disconnect(clientId) {
|
|
321
|
+
socketsByClientId.get(clientId)?.close()
|
|
322
|
+
socketsByClientId.delete(clientId)
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
// A runtime replaced since (the app reopened or reconnected) never answers an update: forget its client.
|
|
326
|
+
function expectAnswer(clientId) {
|
|
327
|
+
if (silenceTimersByClientId.has(clientId)) return
|
|
328
|
+
|
|
329
|
+
silenceTimersByClientId.set(
|
|
330
|
+
clientId,
|
|
331
|
+
setTimeout(() => disconnect(clientId), UNANSWERED_UPDATE_TIMEOUT_MS),
|
|
332
|
+
)
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
function connectToVite(clientId) {
|
|
336
|
+
const socket = new WebSocket(
|
|
337
|
+
`${viteURL.replace('http', 'ws')}/?token=${vite.config.webSocketToken}`,
|
|
338
|
+
'vite-hmr',
|
|
339
|
+
)
|
|
340
|
+
socketsByClientId.set(clientId, socket)
|
|
341
|
+
socket.addEventListener('message', ({ data }) => {
|
|
342
|
+
const payload = JSON.parse(data)
|
|
343
|
+
if (payload.type === 'bundled-dev-update') {
|
|
344
|
+
expectAnswer(clientId)
|
|
345
|
+
sendToApps(`data: hot ${JSON.stringify({ ...payload, clientId })}\n\n`)
|
|
346
|
+
} else if (payload.type === 'full-reload' && !payload.ifFallback) {
|
|
347
|
+
reloadApps()
|
|
348
|
+
}
|
|
349
|
+
})
|
|
350
|
+
sendToVite(clientId, { type: 'custom', event: 'vite:client-connected', data: { clientId } })
|
|
351
|
+
}
|
|
235
352
|
|
|
236
353
|
function handleEvents(request, response) {
|
|
237
354
|
response.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache' })
|
|
@@ -240,72 +357,125 @@ function startDevServer() {
|
|
|
240
357
|
request.on('close', () => connectedApps.delete(response))
|
|
241
358
|
}
|
|
242
359
|
|
|
243
|
-
function handleBundle(response) {
|
|
244
|
-
//
|
|
245
|
-
|
|
360
|
+
async function handleBundle(request, response) {
|
|
361
|
+
// Hot updates leave the bundle Vite serves behind: a reload would run the code from before them.
|
|
362
|
+
await vite.environments.client.bundledDev.devEngine.ensureLatestBuildOutput()
|
|
363
|
+
const bundle = await fetch(`${viteURL}/assets/entry.js`)
|
|
364
|
+
if (!bundle.ok) {
|
|
246
365
|
response.writeHead(503, { 'Content-Type': 'text/plain' })
|
|
247
366
|
response.end('The bundle is still building')
|
|
248
367
|
return
|
|
249
368
|
}
|
|
250
369
|
|
|
251
|
-
|
|
252
|
-
|
|
370
|
+
const clientId = randomUUID()
|
|
371
|
+
connectToVite(clientId)
|
|
372
|
+
const body = hotPrelude(clientId, `http://${request.headers.host}`) + (await bundle.text())
|
|
373
|
+
response.writeHead(200, {
|
|
374
|
+
'Content-Type': 'application/javascript',
|
|
375
|
+
'Content-Length': Buffer.byteLength(body),
|
|
376
|
+
})
|
|
377
|
+
response.end(body)
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
async function handleHotMessage(request, response) {
|
|
381
|
+
const { clientId, message } = JSON.parse(await readBody(request))
|
|
382
|
+
clearTimeout(silenceTimersByClientId.get(clientId))
|
|
383
|
+
silenceTimersByClientId.delete(clientId)
|
|
384
|
+
if (message.event !== 'nativue:received') sendToVite(clientId, message)
|
|
385
|
+
response.writeHead(204).end()
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
// A patch: Vite serves it from memory, as an ES module the app evaluates as a script.
|
|
389
|
+
async function handlePatch(request, response) {
|
|
390
|
+
const patch = await fetch(`${viteURL}${request.url}`)
|
|
391
|
+
response.writeHead(patch.status, { 'Content-Type': 'application/javascript' })
|
|
392
|
+
response.end((await patch.text()).replace(/;\s*export \{\}\s*$/, ''))
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
async function sourceMapOf(file) {
|
|
396
|
+
if (file === 'main.bundle.js') {
|
|
397
|
+
return {
|
|
398
|
+
sourceMap: await (await fetch(`${viteURL}/assets/entry.js.map`)).json(),
|
|
399
|
+
directory: `${BUNDLE_DIRECTORY}/assets`,
|
|
400
|
+
lineOffset: hotPrelude('', '').split('\n').length - 1,
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
const sourceMap = await fetch(`${viteURL}/${file}.map`)
|
|
405
|
+
|
|
406
|
+
return sourceMap.ok ? { sourceMap: await sourceMap.json(), directory: BUNDLE_DIRECTORY } : null
|
|
253
407
|
}
|
|
254
408
|
|
|
255
409
|
// The app posts an error's stack; it gets it back pointing at the app's files.
|
|
256
410
|
async function handleSymbolicate(request, response) {
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
411
|
+
const text = await readBody(request)
|
|
412
|
+
const files = [...framedFiles(text)]
|
|
413
|
+
const sourceMaps = await Promise.all(files.map(sourceMapOf))
|
|
414
|
+
const symbolicate = createSymbolicator(
|
|
415
|
+
Object.fromEntries(
|
|
416
|
+
files.map((file, index) => [file, sourceMaps[index]]).filter(([, map]) => map),
|
|
417
|
+
),
|
|
418
|
+
)
|
|
263
419
|
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
420
|
+
response.writeHead(200, { 'Content-Type': 'text/plain' })
|
|
421
|
+
response.end(symbolicate(text))
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
const routes = {
|
|
425
|
+
'/events': handleEvents,
|
|
426
|
+
'/bundle.js': handleBundle,
|
|
427
|
+
'/hot': handleHotMessage,
|
|
428
|
+
'/symbolicate': handleSymbolicate,
|
|
269
429
|
}
|
|
270
430
|
|
|
271
431
|
http
|
|
272
432
|
.createServer((request, response) => {
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
433
|
+
const handle = routes[request.url] ?? handlePatch
|
|
434
|
+
Promise.resolve(handle(request, response)).catch(() => {
|
|
435
|
+
response.writeHead(400).end() // an aborted or oversized post: never take the server down
|
|
436
|
+
})
|
|
276
437
|
})
|
|
277
438
|
// Limitation: Every interface, so phones reach it, and anyone on the network can download the bundle.
|
|
278
439
|
.listen(PORT, () => console.log(`dev server: http://localhost:${PORT}`))
|
|
279
440
|
|
|
441
|
+
if (process.stdin.isTTY) {
|
|
442
|
+
console.log('press r to reload the app')
|
|
443
|
+
process.stdin.setRawMode(true)
|
|
444
|
+
process.stdin.on('data', (key) => {
|
|
445
|
+
if (key[0] === 3) process.exit(130) // ctrl+c, which raw mode turns into a key
|
|
446
|
+
if (key.toString() === 'r') reloadApps()
|
|
447
|
+
})
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
// The bundle only watches the files it has: one added or removed (a new route) needs a new build.
|
|
451
|
+
// Editors that save by renaming a temporary file keep the file there, which isn't a change.
|
|
452
|
+
const sourceFiles = new Set(readdirSync('src', { recursive: true }))
|
|
453
|
+
let restartTimer = null
|
|
454
|
+
watch('src', { recursive: true }, (_event, file) => {
|
|
455
|
+
if (!file || existsSync(`src/${file}`) === sourceFiles.has(file)) return
|
|
456
|
+
|
|
457
|
+
if (sourceFiles.has(file)) sourceFiles.delete(file)
|
|
458
|
+
else sourceFiles.add(file)
|
|
459
|
+
|
|
460
|
+
clearTimeout(restartTimer)
|
|
461
|
+
restartTimer = setTimeout(async () => {
|
|
462
|
+
await vite.restart()
|
|
463
|
+
reloadApps()
|
|
464
|
+
}, 100)
|
|
465
|
+
})
|
|
466
|
+
|
|
280
467
|
// Without a keepalive, URLSession drops the idle connection.
|
|
281
468
|
setInterval(() => sendToApps(':\n\n'), KEEPALIVE_INTERVAL_MS)
|
|
469
|
+
}
|
|
282
470
|
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
JSON.parse(readFileSync(SOURCE_MAP_PATH, 'utf8')),
|
|
289
|
-
BUNDLE_DIRECTORY,
|
|
290
|
-
)
|
|
291
|
-
rmSync(SOURCE_MAP_PATH)
|
|
292
|
-
|
|
293
|
-
console.log(`reload -> ${connectedApps.size} app(s)`)
|
|
294
|
-
sendToApps('data: reload\n\n')
|
|
295
|
-
},
|
|
471
|
+
async function readBody(request) {
|
|
472
|
+
let text = ''
|
|
473
|
+
for await (const chunk of request) {
|
|
474
|
+
text += chunk
|
|
475
|
+
if (text.length > MAX_STACK_LENGTH) throw new Error('body too long')
|
|
296
476
|
}
|
|
297
|
-
}
|
|
298
477
|
|
|
299
|
-
|
|
300
|
-
const reloadPlugin = startDevServer()
|
|
301
|
-
await build(
|
|
302
|
-
viteConfig({
|
|
303
|
-
mode: 'development',
|
|
304
|
-
plugins: [reloadPlugin],
|
|
305
|
-
watch: {},
|
|
306
|
-
sourcemap: 'hidden', // no comment in the bundle: the dev server serves the map
|
|
307
|
-
}),
|
|
308
|
-
)
|
|
478
|
+
return text
|
|
309
479
|
}
|
|
310
480
|
|
|
311
481
|
function isPortFree(port) {
|
package/cli/symbolicate.mjs
CHANGED
|
@@ -1,20 +1,31 @@
|
|
|
1
|
-
// Maps stack frames of the bundle back to the app's files with
|
|
2
|
-
// `at name (main.bundle.js:8161:20)` becomes `at name (src/app/index.vue:22:9)`. Consecutive
|
|
1
|
+
// Maps stack frames of the bundle (and of hot updates) back to the app's files with their source maps:
|
|
2
|
+
// Hermes' `at name (main.bundle.js:8161:20)` becomes `at name (src/app/index.vue:22:9)`. Consecutive
|
|
3
3
|
// frames from outside src/ (Vue, nativue, Hermes' native ones) collapse into one line, so the app's
|
|
4
4
|
// own frames stand out. Other lines are kept.
|
|
5
5
|
import { SourceMap } from 'node:module'
|
|
6
6
|
import { relative, resolve } from 'node:path'
|
|
7
7
|
|
|
8
|
-
// Groups: before the location, the location's line and column, after it.
|
|
9
|
-
const HERMES_FRAME = /^(\s*at .* \()(
|
|
8
|
+
// Groups: before the location, the file, the location's line and column, after it.
|
|
9
|
+
const HERMES_FRAME = /^(\s*at .* \()(?:.*\/)?([^/()]+\.js):(\d+):(\d+)(\))$/
|
|
10
10
|
const HERMES_NATIVE_FRAME = /^\s*at .* \(native\)$/
|
|
11
11
|
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
12
|
+
export function framedFiles(text) {
|
|
13
|
+
return new Set(text.split('\n').flatMap((line) => HERMES_FRAME.exec(line)?.[2] ?? []))
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
// sourceMapsByFile: for each file (main.bundle.js, a hot update), { sourceMap: the map as JSON,
|
|
17
|
+
// directory: the one its sources are relative to, lineOffset: how many lines above the file's first
|
|
18
|
+
// line the map starts }.
|
|
19
|
+
export function createSymbolicator(sourceMapsByFile) {
|
|
20
|
+
const mapsByFile = new Map(
|
|
21
|
+
Object.entries(sourceMapsByFile).map(([file, { sourceMap, directory, lineOffset = 0 }]) => [
|
|
22
|
+
file,
|
|
23
|
+
{ sourceMap: new SourceMap(sourceMap), directory, lineOffset },
|
|
24
|
+
]),
|
|
25
|
+
)
|
|
15
26
|
|
|
16
|
-
function displayPath(source) {
|
|
17
|
-
const absolutePath = resolve(
|
|
27
|
+
function displayPath(directory, source) {
|
|
28
|
+
const absolutePath = resolve(directory, source)
|
|
18
29
|
const nodeModulesIndex = absolutePath.lastIndexOf('node_modules/')
|
|
19
30
|
|
|
20
31
|
return nodeModulesIndex === -1
|
|
@@ -26,14 +37,15 @@ export function createSymbolicator(sourceMapPayload, bundleDirectory) {
|
|
|
26
37
|
function symbolicateLine(line) {
|
|
27
38
|
if (HERMES_NATIVE_FRAME.test(line)) return { text: line, isInternal: true }
|
|
28
39
|
|
|
29
|
-
const
|
|
30
|
-
|
|
40
|
+
const [, before, file, lineNumber, columnNumber, after] = HERMES_FRAME.exec(line) ?? []
|
|
41
|
+
const map = mapsByFile.get(file)
|
|
42
|
+
if (!map) return { text: line, isInternal: false }
|
|
31
43
|
|
|
32
|
-
const
|
|
33
|
-
const entry = sourceMap.findEntry(Number(lineNumber) - 1, Number(columnNumber) - 1)
|
|
44
|
+
const { sourceMap, directory, lineOffset } = map
|
|
45
|
+
const entry = sourceMap.findEntry(Number(lineNumber) - 1 - lineOffset, Number(columnNumber) - 1)
|
|
34
46
|
if (!entry.originalSource) return { text: line, isInternal: false }
|
|
35
47
|
|
|
36
|
-
const path = displayPath(entry.originalSource)
|
|
48
|
+
const path = displayPath(directory, entry.originalSource)
|
|
37
49
|
const text = `${before}${path}:${entry.originalLine + 1}:${entry.originalColumn + 1}${after}`
|
|
38
50
|
|
|
39
51
|
return { text, isInternal: !path.startsWith('src/') }
|
package/ios/Bridge.swift
CHANGED
|
@@ -36,6 +36,8 @@ final class Bridge {
|
|
|
36
36
|
private var colorScheme = "light"
|
|
37
37
|
/// Kept on the JS queue, for AccessibilityInfo.
|
|
38
38
|
private var accessibilityStatus = AccessibilityStatus()
|
|
39
|
+
/// Kept on the JS queue: the router's screens, reopened after a reload in development.
|
|
40
|
+
private var savedNavigation: String?
|
|
39
41
|
|
|
40
42
|
// Only touched on the main thread.
|
|
41
43
|
var rootView: RootView!
|
|
@@ -53,6 +55,9 @@ final class Bridge {
|
|
|
53
55
|
/// The bundle running now, for the error overlay's Reload.
|
|
54
56
|
private var bundle = Data()
|
|
55
57
|
private let errorOverlay = ErrorOverlay()
|
|
58
|
+
#if DEBUG
|
|
59
|
+
private let downloadBanner = DownloadBanner()
|
|
60
|
+
#endif
|
|
56
61
|
private let pluginRegistry: PluginRegistry
|
|
57
62
|
|
|
58
63
|
init(plugins: [NativuePlugin]) {
|
|
@@ -101,12 +106,20 @@ final class Bridge {
|
|
|
101
106
|
run(try! Data(contentsOf: bundleURL))
|
|
102
107
|
#if DEBUG
|
|
103
108
|
Task { await listenForReload() }
|
|
109
|
+
rootView.onReloadShortcut = { [unowned self] in Task { try? await reload() } }
|
|
104
110
|
#endif
|
|
105
111
|
}
|
|
106
112
|
|
|
107
113
|
/// Discards the current node tree and runtime, then runs the bundle from scratch: JavaScript, or
|
|
108
114
|
/// Hermes bytecode (production builds).
|
|
109
115
|
func run(_ bundle: Data) {
|
|
116
|
+
// UIKit ignores a dismissal while a modal is presenting or dismissing, so resetNodeTree would leave
|
|
117
|
+
// the old tree's modal up, and the new tree's couldn't present.
|
|
118
|
+
if let transition = modalTransitionInProgress() {
|
|
119
|
+
transition.animate(alongsideTransition: nil) { [unowned self] _ in run(bundle) }
|
|
120
|
+
return
|
|
121
|
+
}
|
|
122
|
+
|
|
110
123
|
self.bundle = bundle
|
|
111
124
|
errorOverlay.hide()
|
|
112
125
|
|
|
@@ -118,6 +131,16 @@ final class Bridge {
|
|
|
118
131
|
}
|
|
119
132
|
}
|
|
120
133
|
|
|
134
|
+
private func modalTransitionInProgress() -> UIViewControllerTransitionCoordinator? {
|
|
135
|
+
guard let presentedViewController = rootView.window?.rootViewController?.presentedViewController else {
|
|
136
|
+
return nil
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
return sequence(first: presentedViewController, next: \.presentedViewController)
|
|
140
|
+
.compactMap(\.transitionCoordinator)
|
|
141
|
+
.last
|
|
142
|
+
}
|
|
143
|
+
|
|
121
144
|
/// Runs `work` on the JS queue, then applies every native operation it produced, in one batch, on the
|
|
122
145
|
/// main thread. The runtime drains promise jobs after each call, so Vue's updates are included.
|
|
123
146
|
func evaluate(_ work: @escaping () -> Void) {
|
|
@@ -207,22 +230,49 @@ final class Bridge {
|
|
|
207
230
|
#if DEBUG
|
|
208
231
|
@MainActor func listenForReload() async {
|
|
209
232
|
let eventsURL = Self.devServerURL.appendingPathComponent("events")
|
|
210
|
-
let bundleURL = Self.devServerURL.appendingPathComponent("bundle.js")
|
|
211
233
|
|
|
212
234
|
while true {
|
|
213
235
|
do {
|
|
214
236
|
let (events, _) = try await URLSession.shared.bytes(from: eventsURL)
|
|
215
237
|
|
|
216
|
-
for try await line in events.lines
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
238
|
+
for try await line in events.lines {
|
|
239
|
+
if line == "data: reload" {
|
|
240
|
+
try await reload()
|
|
241
|
+
} else if line.hasPrefix("data: hot ") {
|
|
242
|
+
let update = String(line.dropFirst("data: hot ".count))
|
|
243
|
+
evaluate { [unowned self] in runtime?.call("__hotUpdate", arguments: [update]) }
|
|
244
|
+
}
|
|
220
245
|
}
|
|
221
246
|
} catch {}
|
|
222
247
|
|
|
223
248
|
try? await Task.sleep(nanoseconds: 2_000_000_000) // dev server is down: retry
|
|
224
249
|
}
|
|
225
250
|
}
|
|
251
|
+
|
|
252
|
+
@MainActor func reload() async throws {
|
|
253
|
+
let data = try await download(Self.devServerURL.appendingPathComponent("bundle.js"))
|
|
254
|
+
print("[Nativue] reload")
|
|
255
|
+
run(data)
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
@MainActor private func download(_ url: URL) async throws -> Data {
|
|
259
|
+
try await withCheckedThrowingContinuation { continuation in
|
|
260
|
+
var observation: NSKeyValueObservation?
|
|
261
|
+
let task = URLSession.shared.dataTask(with: url) { [unowned self] data, _, error in
|
|
262
|
+
DispatchQueue.main.async {
|
|
263
|
+
observation?.invalidate()
|
|
264
|
+
self.downloadBanner.hide()
|
|
265
|
+
if let data { continuation.resume(returning: data) } else { continuation.resume(throwing: error!) }
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
observation = task.observe(\.countOfBytesReceived) { [unowned self] task, _ in
|
|
269
|
+
let progress = Double(task.countOfBytesReceived) / Double(max(task.countOfBytesExpectedToReceive, 1))
|
|
270
|
+
DispatchQueue.main.async { self.downloadBanner.show(progress: progress) }
|
|
271
|
+
}
|
|
272
|
+
downloadBanner.show(progress: 0)
|
|
273
|
+
task.resume()
|
|
274
|
+
}
|
|
275
|
+
}
|
|
226
276
|
#endif
|
|
227
277
|
|
|
228
278
|
// MARK: - JS queue
|
|
@@ -291,6 +341,8 @@ final class Bridge {
|
|
|
291
341
|
}
|
|
292
342
|
|
|
293
343
|
defineGetter("colorScheme") { [unowned self] _ in colorScheme }
|
|
344
|
+
defineGetter("savedNavigation") { [unowned self] _ in savedNavigation }
|
|
345
|
+
define("saveNavigation") { [unowned self] arguments in savedNavigation = arguments[0] as? String }
|
|
294
346
|
|
|
295
347
|
define("create") { [unowned self] arguments in
|
|
296
348
|
let (id, type) = (int(arguments[0]), string(arguments[1]))
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import UIKit
|
|
2
|
+
|
|
3
|
+
/// Development only: a strip at the top of the screen while the app downloads the dev server's bundle.
|
|
4
|
+
final class DownloadBanner {
|
|
5
|
+
private var window: UIWindow?
|
|
6
|
+
private let label = UILabel()
|
|
7
|
+
|
|
8
|
+
func show(progress: Double) {
|
|
9
|
+
if window == nil { makeWindow() }
|
|
10
|
+
|
|
11
|
+
label.text = "Downloading \(Int(progress * 100))%"
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
func hide() {
|
|
15
|
+
window?.isHidden = true
|
|
16
|
+
window = nil
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
private func makeWindow() {
|
|
20
|
+
guard let scene = UIApplication.shared.connectedScenes.first as? UIWindowScene else { return }
|
|
21
|
+
|
|
22
|
+
let topInset = scene.windows.first?.safeAreaInsets.top ?? 0
|
|
23
|
+
let window = UIWindow(windowScene: scene)
|
|
24
|
+
window.frame = CGRect(x: 0, y: 0, width: scene.screen.bounds.width, height: topInset + 24)
|
|
25
|
+
window.windowLevel = .alert + 2
|
|
26
|
+
window.isUserInteractionEnabled = false
|
|
27
|
+
window.backgroundColor = UIColor(red: 0.04, green: 0.07, blue: 0.13, alpha: 1)
|
|
28
|
+
|
|
29
|
+
label.frame = CGRect(x: 0, y: topInset, width: window.frame.width, height: 24)
|
|
30
|
+
label.font = .systemFont(ofSize: 12, weight: .semibold)
|
|
31
|
+
label.textColor = UIColor(red: 0.95, green: 0.96, blue: 0.98, alpha: 1)
|
|
32
|
+
label.textAlignment = .center
|
|
33
|
+
window.addSubview(label)
|
|
34
|
+
|
|
35
|
+
window.isHidden = false
|
|
36
|
+
self.window = window
|
|
37
|
+
}
|
|
38
|
+
}
|
package/ios/NativueView.swift
CHANGED
|
@@ -48,4 +48,23 @@ final class RootView: UIView {
|
|
|
48
48
|
super.traitCollectionDidChange(previous)
|
|
49
49
|
onTraitCollectionChange?(previous)
|
|
50
50
|
}
|
|
51
|
+
|
|
52
|
+
#if DEBUG
|
|
53
|
+
var onReloadShortcut: (() -> Void)?
|
|
54
|
+
|
|
55
|
+
override var canBecomeFirstResponder: Bool { true }
|
|
56
|
+
|
|
57
|
+
override var keyCommands: [UIKeyCommand]? {
|
|
58
|
+
[UIKeyCommand(input: "r", modifierFlags: .command, action: #selector(reloadShortcutPressed))]
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
override func didMoveToWindow() {
|
|
62
|
+
super.didMoveToWindow()
|
|
63
|
+
becomeFirstResponder()
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
@objc private func reloadShortcutPressed() {
|
|
67
|
+
onReloadShortcut?()
|
|
68
|
+
}
|
|
69
|
+
#endif
|
|
51
70
|
}
|
package/package.json
CHANGED
package/src/globals.ts
CHANGED
|
@@ -5,6 +5,7 @@ import type { LayoutEvent, NativeModule, NetworkEventPayloads } from './types'
|
|
|
5
5
|
|
|
6
6
|
declare global {
|
|
7
7
|
var __native: NativeModule
|
|
8
|
+
var __NATIVUE_HOT__: { clientId: string; serverURL: string } | undefined
|
|
8
9
|
var __dispatch: (nodeId: number, eventName: string, payload: unknown) => void
|
|
9
10
|
var __layoutsChanged: (layouts: ({ id: number } & LayoutEvent)[]) => void
|
|
10
11
|
var __openURL: (url: string) => void
|
package/src/renderer.ts
CHANGED
|
@@ -83,6 +83,7 @@ const textInputsById = new Map<number, Node>()
|
|
|
83
83
|
*/
|
|
84
84
|
export function setClassStyleResolver(resolver: ClassStyleResolver): void {
|
|
85
85
|
resolveClassStyle = resolver
|
|
86
|
+
nodesWithClass.forEach((node) => updateStyle(node, {}))
|
|
86
87
|
}
|
|
87
88
|
|
|
88
89
|
function createNode(type: string): Node {
|
package/src/router.ts
CHANGED
|
@@ -832,6 +832,34 @@ export const Link = defineComponent({
|
|
|
832
832
|
})
|
|
833
833
|
|
|
834
834
|
type RouteFiles = Record<string, { default: Component }>
|
|
835
|
+
type OpenedRoute = [href: string, mode: NavigationMode]
|
|
836
|
+
|
|
837
|
+
// The routes to open again for the same screens: each stack's screens above its first, and the active
|
|
838
|
+
// tab. The tabs in the background start over.
|
|
839
|
+
function openedRoutes(entry: Entry): OpenedRoute[] {
|
|
840
|
+
const navigator = entry.navigator
|
|
841
|
+
if (!navigator) return []
|
|
842
|
+
|
|
843
|
+
if ('tabs' in navigator) {
|
|
844
|
+
const { tabs, state } = navigator as TabsNavigator
|
|
845
|
+
const activeTab = tabs[state.activeIndex]
|
|
846
|
+
|
|
847
|
+
return [[activeTab.href, 'navigate'], ...openedRoutes(activeTab)]
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
return (navigator as StackNavigator).entries.flatMap((child, index): OpenedRoute[] => [
|
|
851
|
+
...(index > 0 ? [[child.href, 'push'] as OpenedRoute] : []),
|
|
852
|
+
...openedRoutes(child),
|
|
853
|
+
])
|
|
854
|
+
}
|
|
855
|
+
|
|
856
|
+
function keepNavigationAcrossReloads() {
|
|
857
|
+
const savedRoutes = __native.savedNavigation()
|
|
858
|
+
if (savedRoutes)
|
|
859
|
+
for (const [href, mode] of JSON.parse(savedRoutes) as OpenedRoute[]) go(href, mode)
|
|
860
|
+
|
|
861
|
+
watchEffect(() => __native.saveNavigation(JSON.stringify(openedRoutes(rootEntry))))
|
|
862
|
+
}
|
|
835
863
|
|
|
836
864
|
// routeFiles: import.meta.glob('/src/app/**/*.vue', { eager: true }), see entry.ts
|
|
837
865
|
export function createRouterApp(routeFiles: RouteFiles) {
|
|
@@ -839,6 +867,7 @@ export function createRouterApp(routeFiles: RouteFiles) {
|
|
|
839
867
|
|
|
840
868
|
const { chain, target } = resolveHref('/')
|
|
841
869
|
rootEntry = createEntry(layoutsByDirectory.get('')!, chain.slice(1), target)
|
|
870
|
+
if (globalThis.__NATIVUE_HOT__) keepNavigationAcrossReloads()
|
|
842
871
|
|
|
843
872
|
return createApp(defineComponent(() => () => h(LayoutContent, { entry: rootEntry })))
|
|
844
873
|
}
|
package/src/types.ts
CHANGED
|
@@ -115,6 +115,9 @@ export interface NativeModule {
|
|
|
115
115
|
windowSize(): { width: number; height: number }
|
|
116
116
|
platform(): 'ios' | 'android'
|
|
117
117
|
colorScheme(): 'light' | 'dark'
|
|
118
|
+
/** Development: the navigation saveNavigation kept, which outlives the JavaScript runtime. */
|
|
119
|
+
savedNavigation(): string | null
|
|
120
|
+
saveNavigation(routes: string): void
|
|
118
121
|
accessibilityInfo(): { screenReaderEnabled: boolean; reduceMotionEnabled: boolean }
|
|
119
122
|
announce(message: string): void
|
|
120
123
|
create(id: number, type: string): void
|