@nativue/core 0.3.0 → 0.4.1
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/README.md +16 -5
- package/android/build.gradle.kts +2 -2
- package/android/src/main/java/dev/nativue/Bridge.kt +76 -24
- package/android/src/main/java/dev/nativue/Gestures.kt +2 -0
- package/android/src/main/java/dev/nativue/ModalHost.kt +8 -0
- package/android/src/main/java/dev/nativue/Navigation.kt +5 -2
- package/android/src/main/java/dev/nativue/Style.kt +1 -1
- package/android/src/main/java/dev/nativue/SvgView.kt +1 -1
- package/android/src/main/java/dev/nativue/Views.kt +40 -1
- package/cli/nativue.mjs +21 -5
- package/cli/run.mjs +1 -1
- package/ios/Bridge.swift +44 -20
- package/ios/ImageView.swift +1 -1
- package/ios/KeyValueStorage.swift +1 -1
- package/ios/KeyboardAvoidingView.swift +12 -5
- package/ios/ModalController.swift +27 -6
- package/ios/Plugins.swift +2 -1
- package/ios/PressableView.swift +1 -1
- package/ios/Style.swift +3 -1
- package/ios/SvgView.swift +1 -1
- package/ios/TextInputView.swift +1 -1
- package/ios/VueScrollView.swift +50 -1
- package/package.json +1 -1
- package/src/components.ts +47 -11
- package/src/fetch.ts +6 -3
- package/src/native-components.ts +7 -0
- package/src/renderer.ts +54 -11
- package/src/router.ts +37 -7
package/ios/Bridge.swift
CHANGED
|
@@ -5,11 +5,11 @@ import yoga
|
|
|
5
5
|
/// Runs the JS bundle off the main thread and applies the operations sent by the Vue renderer
|
|
6
6
|
/// (src/renderer.js) to UIKit + Yoga in batches on the main thread.
|
|
7
7
|
final class Bridge {
|
|
8
|
-
/// The simulator shares the Mac's network; a device uses the Mac's name, written into the app at build
|
|
9
|
-
/// time by the "Write Dev Server Host" build phase.
|
|
10
8
|
/// Posted by the app with a URL it was opened with (deep link); forwarded to JS (`__openURL`).
|
|
11
9
|
static let openURLNotification = Notification.Name("NativueOpenURL")
|
|
12
10
|
|
|
11
|
+
/// The simulator shares the Mac's network; a device uses the Mac's name, written into the app at build
|
|
12
|
+
/// time by the "Write Dev Server Host" build phase.
|
|
13
13
|
static let devServerURL: URL = {
|
|
14
14
|
#if targetEnvironment(simulator)
|
|
15
15
|
let host = "localhost"
|
|
@@ -22,15 +22,13 @@ final class Bridge {
|
|
|
22
22
|
return URL(string: "http://\(host):40836")!
|
|
23
23
|
}()
|
|
24
24
|
|
|
25
|
-
//
|
|
25
|
+
// Limitation: GCD threads have a 512 KB stack; move to a Thread with a bigger stack if deep trees hit
|
|
26
26
|
// "RangeError: Maximum call stack size exceeded".
|
|
27
27
|
private let javaScriptQueue = DispatchQueue(label: "dev.nativue.javascript", qos: .userInteractive)
|
|
28
28
|
|
|
29
29
|
// Only touched on javaScriptQueue.
|
|
30
30
|
private var runtime: JavaScriptRuntime?
|
|
31
31
|
private var pendingOperations: [() -> Void] = []
|
|
32
|
-
private var gestureReportersByNodeId: [Int: GestureReporter] = [:]
|
|
33
|
-
private let animatedGraph = AnimatedGraph()
|
|
34
32
|
private lazy var storage = KeyValueStorage(javaScriptQueue: javaScriptQueue)
|
|
35
33
|
/// Set by LayoutAnimation.configureNext in JS; animates the batch it's sent with.
|
|
36
34
|
private var nextLayoutAnimation: LayoutAnimation?
|
|
@@ -39,10 +37,14 @@ final class Bridge {
|
|
|
39
37
|
|
|
40
38
|
// Only touched on the main thread.
|
|
41
39
|
var rootView: RootView!
|
|
42
|
-
|
|
40
|
+
private var gestureReportersByNodeId: [Int: GestureReporter] = [:]
|
|
41
|
+
private let animatedGraph = AnimatedGraph()
|
|
42
|
+
// Limitation: Children of a removed node stay in the dictionary; clean up recursively if memory leaks.
|
|
43
43
|
var nodesById: [Int: NativeNode] = [:]
|
|
44
44
|
/// Modals and screens: their content is laid out as a separate Yoga root.
|
|
45
|
-
//
|
|
45
|
+
// Limitation: Vue removes only a subtree's root, so the modals and screens inside a removed subtree stay
|
|
46
|
+
// here and are laid out on every pass; drop the detached ones on remove if navigators come and go.
|
|
47
|
+
// Likewise a sheet a <ScreenStack> presented stays up when a v-if removes the stack (a reload closes it).
|
|
46
48
|
private var contentRootsByNodeId: [Int: ContentRoot] = [:]
|
|
47
49
|
/// Read on the main thread at start, for Dimensions.get('window').
|
|
48
50
|
private var windowSize: CGSize = .zero
|
|
@@ -136,8 +138,11 @@ final class Bridge {
|
|
|
136
138
|
}
|
|
137
139
|
}
|
|
138
140
|
|
|
139
|
-
|
|
141
|
+
/// Results reaching a runtime that has since been reloaded are dropped: call ids start over in the new one.
|
|
142
|
+
private func finishAsyncFunction(_ callId: Int, owner: JavaScriptRuntime?, value: Any?, errorMessage: String?) {
|
|
140
143
|
evaluate { [unowned self] in
|
|
144
|
+
guard runtime === owner else { return }
|
|
145
|
+
|
|
141
146
|
let arguments: [Any] = [callId, value ?? NSNull(), errorMessage ?? NSNull()]
|
|
142
147
|
runtime?.call("__asyncFunctionFinished", arguments: arguments)
|
|
143
148
|
}
|
|
@@ -219,7 +224,7 @@ final class Bridge {
|
|
|
219
224
|
reportError(message: string(arguments[0]), details: string(arguments[1]))
|
|
220
225
|
}
|
|
221
226
|
|
|
222
|
-
//
|
|
227
|
+
// Limitation: The size at launch; report rotation and split view changes if the app supports them.
|
|
223
228
|
defineGetter("windowSize") { [unowned self] _ in
|
|
224
229
|
["width": windowSize.width, "height": windowSize.height]
|
|
225
230
|
}
|
|
@@ -235,13 +240,14 @@ final class Bridge {
|
|
|
235
240
|
for (name, function) in pluginRegistry.asyncFunctions {
|
|
236
241
|
define("pluginAsync:\(name)") { [unowned self] arguments in
|
|
237
242
|
let callId = int(arguments[0])
|
|
243
|
+
let owner = runtime
|
|
238
244
|
|
|
239
245
|
Task {
|
|
240
246
|
do {
|
|
241
247
|
let value = try await function(Array(arguments.dropFirst()))
|
|
242
|
-
finishAsyncFunction(callId, value: value, errorMessage: nil)
|
|
248
|
+
finishAsyncFunction(callId, owner: owner, value: value, errorMessage: nil)
|
|
243
249
|
} catch {
|
|
244
|
-
finishAsyncFunction(callId, value: nil, errorMessage: error.localizedDescription)
|
|
250
|
+
finishAsyncFunction(callId, owner: owner, value: nil, errorMessage: error.localizedDescription)
|
|
245
251
|
}
|
|
246
252
|
}
|
|
247
253
|
}
|
|
@@ -339,6 +345,8 @@ final class Bridge {
|
|
|
339
345
|
// MARK: - Main thread
|
|
340
346
|
|
|
341
347
|
private func resetNodeTree() {
|
|
348
|
+
// Sheets of the old tree's screen stacks too, which only their stack knows about.
|
|
349
|
+
rootView.window?.rootViewController?.dismiss(animated: false)
|
|
342
350
|
rootView.subviews.forEach { $0.removeFromSuperview() }
|
|
343
351
|
contentRootsByNodeId.values.forEach { ($0 as? ModalController)?.setVisible(false) }
|
|
344
352
|
contentRootsByNodeId = [:]
|
|
@@ -421,7 +429,10 @@ final class Bridge {
|
|
|
421
429
|
case "KeyboardAvoidingView":
|
|
422
430
|
let keyboardAvoidingView = KeyboardAvoidingView()
|
|
423
431
|
let node = NativeNode(view: keyboardAvoidingView, measuresContent: false)
|
|
424
|
-
|
|
432
|
+
// weak: a reload frees the node while a dismissing modal still shows its view.
|
|
433
|
+
keyboardAvoidingView.onKeyboardOverlapChange = { [unowned self, weak node] overlap in
|
|
434
|
+
guard let node else { return }
|
|
435
|
+
|
|
425
436
|
YGNodeStyleSetPadding(node.yogaNode, .bottom, Float(overlap))
|
|
426
437
|
rootView.setNeedsLayout()
|
|
427
438
|
rootView.layoutIfNeeded() // runs inside the keyboard animation, so frames animate with it
|
|
@@ -431,8 +442,8 @@ final class Bridge {
|
|
|
431
442
|
case "SafeAreaView":
|
|
432
443
|
let safeAreaView = SafeAreaView()
|
|
433
444
|
let node = NativeNode(view: safeAreaView, measuresContent: false)
|
|
434
|
-
safeAreaView.onSafeAreaInsetsChange = { [unowned self,
|
|
435
|
-
if node
|
|
445
|
+
safeAreaView.onSafeAreaInsetsChange = { [unowned self, weak node] in
|
|
446
|
+
if node?.applySafeAreaPadding() == true { requestLayout() }
|
|
436
447
|
}
|
|
437
448
|
return node
|
|
438
449
|
|
|
@@ -506,8 +517,13 @@ final class Bridge {
|
|
|
506
517
|
dispatchEvent("submitediting", toNodeId: id, payload: textInput.text ?? "")
|
|
507
518
|
}, for: .editingDidEndOnExit)
|
|
508
519
|
|
|
509
|
-
textInput.addAction(UIAction { [unowned
|
|
520
|
+
textInput.addAction(UIAction { [unowned self] _ in
|
|
521
|
+
dispatchEvent("focus", toNodeId: id, payload: nil)
|
|
522
|
+
}, for: .editingDidBegin)
|
|
523
|
+
|
|
524
|
+
textInput.addAction(UIAction { [unowned self, unowned textInput] _ in
|
|
510
525
|
textInput.endEditingSession()
|
|
526
|
+
dispatchEvent("blur", toNodeId: id, payload: nil)
|
|
511
527
|
}, for: .editingDidEnd)
|
|
512
528
|
|
|
513
529
|
return textInput
|
|
@@ -537,15 +553,16 @@ final class Bridge {
|
|
|
537
553
|
}
|
|
538
554
|
|
|
539
555
|
/// fetch: URLSession runs the request; JS hears back through __fetchFinished(requestId, response, error).
|
|
540
|
-
///
|
|
556
|
+
/// Limitation: Text bodies only (no binary, FormData or streaming) and no abort.
|
|
541
557
|
private func defineFetch(_ define: Define) {
|
|
542
558
|
define("fetch") { [unowned self] arguments in
|
|
543
559
|
let (requestId, url, method) = (int(arguments[0]), string(arguments[1]), string(arguments[2]))
|
|
544
560
|
let headers = arguments[3] as? [String: String] ?? [:]
|
|
545
561
|
let bodyText = arguments[4] as? String
|
|
562
|
+
let owner = runtime
|
|
546
563
|
|
|
547
564
|
guard let url = URL(string: url) else {
|
|
548
|
-
return finishFetch(requestId, response: nil, error: "invalid URL \(url)")
|
|
565
|
+
return finishFetch(requestId, owner: owner, response: nil, error: "invalid URL \(url)")
|
|
549
566
|
}
|
|
550
567
|
|
|
551
568
|
var request = URLRequest(url: url)
|
|
@@ -555,10 +572,12 @@ final class Bridge {
|
|
|
555
572
|
|
|
556
573
|
URLSession.shared.dataTask(with: request) { [unowned self] data, response, error in
|
|
557
574
|
guard let response = response as? HTTPURLResponse, error == nil else {
|
|
558
|
-
return finishFetch(
|
|
575
|
+
return finishFetch(
|
|
576
|
+
requestId, owner: owner, response: nil, error: error?.localizedDescription ?? "no response"
|
|
577
|
+
)
|
|
559
578
|
}
|
|
560
579
|
|
|
561
|
-
finishFetch(requestId, response: [
|
|
580
|
+
finishFetch(requestId, owner: owner, response: [
|
|
562
581
|
"status": response.statusCode,
|
|
563
582
|
"headers": response.allHeaderFields,
|
|
564
583
|
"body": String(decoding: data ?? Data(), as: UTF8.self),
|
|
@@ -567,8 +586,10 @@ final class Bridge {
|
|
|
567
586
|
}
|
|
568
587
|
}
|
|
569
588
|
|
|
570
|
-
|
|
589
|
+
/// Like finishAsyncFunction, dropped if the runtime that asked has since been reloaded.
|
|
590
|
+
private func finishFetch(_ requestId: Int, owner: JavaScriptRuntime?, response: [String: Any]?, error: String?) {
|
|
571
591
|
evaluate { [unowned self] in
|
|
592
|
+
guard runtime === owner else { return }
|
|
572
593
|
let arguments: [Any] = [requestId, response ?? NSNull(), error ?? NSNull()]
|
|
573
594
|
runtime?.call("__fetchFinished", arguments: arguments)
|
|
574
595
|
}
|
|
@@ -725,6 +746,9 @@ final class Bridge {
|
|
|
725
746
|
case "showsVerticalScrollIndicator":
|
|
726
747
|
(node.view as? UIScrollView)?.showsVerticalScrollIndicator = isTruthyAttribute(value)
|
|
727
748
|
|
|
749
|
+
case "automaticallyAdjustKeyboardInsets":
|
|
750
|
+
(node.view as? VueScrollView)?.adjustsForKeyboard = isTruthyAttribute(value)
|
|
751
|
+
|
|
728
752
|
case "value":
|
|
729
753
|
(node.view as? TextInputView)?.setTextFromJavaScript(value as? String ?? "")
|
|
730
754
|
(node.view as? UISwitch)?.setOn(isTruthyAttribute(value), animated: true)
|
package/ios/ImageView.swift
CHANGED
|
@@ -2,7 +2,7 @@ import UIKit
|
|
|
2
2
|
|
|
3
3
|
/// Image view behind <Image>. Loads `source` (an http(s) or data: url) through URLSession, which also
|
|
4
4
|
/// gives HTTP caching through URLCache.
|
|
5
|
-
//
|
|
5
|
+
// Limitation: No decoded-image cache and no intrinsic size; add an NSCache / measure function if lists of
|
|
6
6
|
// images stutter or sizing by hand gets annoying.
|
|
7
7
|
final class ImageView: UIImageView {
|
|
8
8
|
static let resizeModes: [String: UIView.ContentMode] = [
|
|
@@ -3,7 +3,7 @@ import Foundation
|
|
|
3
3
|
/// Behind AsyncStorage. Every value lives in memory, so reads never touch the disk; changes
|
|
4
4
|
/// are saved to a file in the background, coalesced, so a burst of writes costs one save. Used only on
|
|
5
5
|
/// the JS queue; the save itself runs on its own queue with a snapshot.
|
|
6
|
-
///
|
|
6
|
+
/// Limitation: Each save rewrites the whole file; switch to SQLite or an append log if data grows large.
|
|
7
7
|
final class KeyValueStorage {
|
|
8
8
|
private let javaScriptQueue: DispatchQueue
|
|
9
9
|
private let saveQueue = DispatchQueue(label: "dev.nativue.storage", qos: .utility)
|
|
@@ -30,12 +30,19 @@ final class KeyboardAvoidingView: UIView {
|
|
|
30
30
|
let keyboardTopInView = convert(keyboardFrame, from: nil).minY
|
|
31
31
|
let overlap = max(0, bounds.maxY - keyboardTopInView)
|
|
32
32
|
|
|
33
|
-
|
|
34
|
-
let curve = (userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as? UInt) ?? 7
|
|
35
|
-
let options = UIView.AnimationOptions(rawValue: curve << 16)
|
|
36
|
-
|
|
37
|
-
UIView.animate(withDuration: duration, delay: 0, options: options) { [weak self] in
|
|
33
|
+
UIView.animateAlongsideKeyboard(notification) { [weak self] in
|
|
38
34
|
self?.onKeyboardOverlapChange?(overlap)
|
|
39
35
|
}
|
|
40
36
|
}
|
|
41
37
|
}
|
|
38
|
+
|
|
39
|
+
extension UIView {
|
|
40
|
+
/// Runs `animations` with the keyboard's own duration and curve, so the change moves in sync with it.
|
|
41
|
+
static func animateAlongsideKeyboard(_ notification: Notification, animations: @escaping () -> Void) {
|
|
42
|
+
let userInfo = notification.userInfo
|
|
43
|
+
let duration = (userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double) ?? 0.25
|
|
44
|
+
let curve = (userInfo?[UIResponder.keyboardAnimationCurveUserInfoKey] as? UInt) ?? 7
|
|
45
|
+
|
|
46
|
+
animate(withDuration: duration, delay: 0, options: UIView.AnimationOptions(rawValue: curve << 16), animations: animations)
|
|
47
|
+
}
|
|
48
|
+
}
|
|
@@ -19,6 +19,9 @@ final class ModalController: UIViewController, ContentRoot, UIAdaptivePresentati
|
|
|
19
19
|
var transparent = false
|
|
20
20
|
|
|
21
21
|
private var isPresented: Bool { presentingViewController != nil }
|
|
22
|
+
/// What JS last asked for; applied again when a running transition ends, which UIKit would ignore.
|
|
23
|
+
private var wantsVisible = false
|
|
24
|
+
private var isTransitioning = false
|
|
22
25
|
|
|
23
26
|
override func loadView() {
|
|
24
27
|
view = contentNode.view
|
|
@@ -38,14 +41,22 @@ final class ModalController: UIViewController, ContentRoot, UIAdaptivePresentati
|
|
|
38
41
|
|
|
39
42
|
/// Deferred to after the current batch, so the placeholder is already in the window when presenting.
|
|
40
43
|
func setVisible(_ visible: Bool) {
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
}
|
|
44
|
+
wantsVisible = visible
|
|
45
|
+
DispatchQueue.main.async { [self] in applyVisibility() }
|
|
44
46
|
}
|
|
45
47
|
|
|
46
48
|
/// The <Modal> left the tree (an ancestor's v-if): its content must go too.
|
|
47
49
|
func dismissIfDetached() {
|
|
48
|
-
|
|
50
|
+
guard placeholderView.window == nil else { return }
|
|
51
|
+
|
|
52
|
+
wantsVisible = false
|
|
53
|
+
applyVisibility()
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
private func applyVisibility() {
|
|
57
|
+
guard !isTransitioning else { return }
|
|
58
|
+
|
|
59
|
+
if wantsVisible { present() } else { dismissIfPresented() }
|
|
49
60
|
}
|
|
50
61
|
|
|
51
62
|
private func present() {
|
|
@@ -57,14 +68,24 @@ final class ModalController: UIViewController, ContentRoot, UIAdaptivePresentati
|
|
|
57
68
|
: Self.presentationStyles[presentationStyleName] ?? .fullScreen
|
|
58
69
|
modalTransitionStyle = animationType == "fade" ? .crossDissolve : .coverVertical
|
|
59
70
|
|
|
60
|
-
|
|
71
|
+
isTransitioning = true
|
|
72
|
+
presenter.present(self, animated: animationType != "none") { [self] in
|
|
73
|
+
isTransitioning = false
|
|
74
|
+
onEvent?("show")
|
|
75
|
+
applyVisibility()
|
|
76
|
+
}
|
|
61
77
|
presentationController?.delegate = self
|
|
62
78
|
}
|
|
63
79
|
|
|
64
80
|
private func dismissIfPresented() {
|
|
65
81
|
guard isPresented else { return }
|
|
66
82
|
|
|
67
|
-
|
|
83
|
+
isTransitioning = true
|
|
84
|
+
dismiss(animated: animationType != "none") { [self] in
|
|
85
|
+
isTransitioning = false
|
|
86
|
+
onEvent?("dismiss")
|
|
87
|
+
applyVisibility()
|
|
88
|
+
}
|
|
68
89
|
}
|
|
69
90
|
|
|
70
91
|
private func topViewController() -> UIViewController? {
|
package/ios/Plugins.swift
CHANGED
|
@@ -28,7 +28,8 @@ public final class PluginRegistry {
|
|
|
28
28
|
functions[name] = function
|
|
29
29
|
}
|
|
30
30
|
|
|
31
|
-
/// For work that takes time (a permission prompt, the camera): JavaScript gets a Promise.
|
|
31
|
+
/// For work that takes time (a permission prompt, the camera): JavaScript gets a Promise. Runs off the
|
|
32
|
+
/// main thread: use `await MainActor.run { ... }` for UIKit.
|
|
32
33
|
public func addAsyncFunction(_ name: String, _ function: @escaping AsyncFunction) {
|
|
33
34
|
asyncFunctions[name] = function
|
|
34
35
|
}
|
package/ios/PressableView.swift
CHANGED
|
@@ -55,7 +55,7 @@ final class PressableView: UIControl {
|
|
|
55
55
|
}
|
|
56
56
|
|
|
57
57
|
@objc private func handleLongPress(_ recognizer: UILongPressGestureRecognizer) {
|
|
58
|
-
guard recognizer.state == .began else { return }
|
|
58
|
+
guard recognizer.state == .began, isEnabled else { return }
|
|
59
59
|
|
|
60
60
|
didLongPress = true
|
|
61
61
|
onEvent?("longpress")
|
package/ios/Style.swift
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import UIKit
|
|
2
2
|
import yoga
|
|
3
3
|
|
|
4
|
-
//
|
|
4
|
+
// Limitation: Removed layout properties arrive as null and keep their last value; reset them to Yoga's
|
|
5
5
|
// defaults when it matters. Visual properties already fall back to UIKit's defaults on null.
|
|
6
6
|
extension NativeNode {
|
|
7
7
|
/// Receives only the properties that changed: the JS renderer diffs style objects before sending.
|
|
@@ -96,6 +96,8 @@ extension NativeNode {
|
|
|
96
96
|
fontWeight = fontWeights[String(describing: weightName)] ?? .regular
|
|
97
97
|
}
|
|
98
98
|
|
|
99
|
+
// Limitation: A fixed size on both platforms, ignoring the system's text size; scale it (UIFontMetrics,
|
|
100
|
+
// sp on Android) when accessibility sizes matter.
|
|
99
101
|
let font = UIFont.systemFont(ofSize: fontSize, weight: fontWeight)
|
|
100
102
|
(view as? UILabel)?.font = font
|
|
101
103
|
(view as? UITextField)?.font = font
|
package/ios/SvgView.swift
CHANGED
|
@@ -4,7 +4,7 @@ import UIKit
|
|
|
4
4
|
/// scaled from `viewBox` to its bounds like preserveAspectRatio="xMidYMid meet". Elements are stroked
|
|
5
5
|
/// with `color` (round caps and joins, as icon sets expect); those whose fill isn't "none" are also
|
|
6
6
|
/// filled with it.
|
|
7
|
-
///
|
|
7
|
+
/// Limitation: Only the shapes icon sets use and a single color; add per-element colors, gradients or
|
|
8
8
|
/// transforms when a real-world SVG needs them.
|
|
9
9
|
final class SvgView: UIView {
|
|
10
10
|
var viewBox = CGRect(x: 0, y: 0, width: 24, height: 24) {
|
package/ios/TextInputView.swift
CHANGED
|
@@ -16,7 +16,7 @@ final class TextInputView: UITextField {
|
|
|
16
16
|
didSet { setNeedsLayout() }
|
|
17
17
|
}
|
|
18
18
|
|
|
19
|
-
//
|
|
19
|
+
// Limitation: A value JS sets on purpose that equals text typed earlier in the same editing session is
|
|
20
20
|
// ignored too; tag each change with a counter if that ever matters.
|
|
21
21
|
private var textsSentToJavaScript: Set<String> = []
|
|
22
22
|
|
package/ios/VueScrollView.swift
CHANGED
|
@@ -19,8 +19,12 @@ final class VueScrollView: UIScrollView {
|
|
|
19
19
|
/// "always" / "handled" turn it off.
|
|
20
20
|
var dismissesKeyboardOnTap = true
|
|
21
21
|
|
|
22
|
+
/// automatically-adjust-keyboard-insets: the keyboard insets the content, and the focused input scrolls
|
|
23
|
+
/// above it.
|
|
24
|
+
var adjustsForKeyboard = false
|
|
25
|
+
|
|
22
26
|
/// Set when JS listens to @scroll. Called on every scroll step and size change (FlatList windowing).
|
|
23
|
-
//
|
|
27
|
+
// Limitation: One JS call per frame while scrolling; coalesce / add scrollEventThrottle if JS falls behind.
|
|
24
28
|
var onScroll: ((CGRect) -> Void)? {
|
|
25
29
|
didSet { lastReportedBounds = nil }
|
|
26
30
|
}
|
|
@@ -47,10 +51,20 @@ final class VueScrollView: UIScrollView {
|
|
|
47
51
|
|
|
48
52
|
contentInsetAdjustmentBehavior = .never // <SafeAreaView> handles it, or the prop
|
|
49
53
|
alwaysBounceVertical = true
|
|
54
|
+
// UIKit holds a touch for 150ms to see if it scrolls: a quick tap on a device would send pressin and
|
|
55
|
+
// pressout together, and the pressed style never shows. touchesShouldCancel still lets drags scroll.
|
|
56
|
+
delaysContentTouches = false
|
|
50
57
|
|
|
51
58
|
let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:)))
|
|
52
59
|
tapRecognizer.cancelsTouchesInView = false // buttons inside still receive their taps
|
|
53
60
|
addGestureRecognizer(tapRecognizer)
|
|
61
|
+
|
|
62
|
+
NotificationCenter.default.addObserver(
|
|
63
|
+
self,
|
|
64
|
+
selector: #selector(keyboardWillChangeFrame(_:)),
|
|
65
|
+
name: UIResponder.keyboardWillChangeFrameNotification,
|
|
66
|
+
object: nil
|
|
67
|
+
)
|
|
54
68
|
}
|
|
55
69
|
|
|
56
70
|
required init?(coder: NSCoder) {
|
|
@@ -78,6 +92,41 @@ final class VueScrollView: UIScrollView {
|
|
|
78
92
|
true
|
|
79
93
|
}
|
|
80
94
|
|
|
95
|
+
@objc private func keyboardWillChangeFrame(_ notification: Notification) {
|
|
96
|
+
guard
|
|
97
|
+
adjustsForKeyboard,
|
|
98
|
+
window != nil,
|
|
99
|
+
let keyboardFrame = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
|
|
100
|
+
else { return }
|
|
101
|
+
|
|
102
|
+
// In content coordinates, like bounds. The safe area the system already insets isn't counted twice.
|
|
103
|
+
let keyboardTop = convert(keyboardFrame, from: nil).minY
|
|
104
|
+
let systemBottomInset = adjustedContentInset.bottom - contentInset.bottom
|
|
105
|
+
let keyboardInset = max(0, bounds.maxY - keyboardTop - systemBottomInset)
|
|
106
|
+
|
|
107
|
+
UIView.animateAlongsideKeyboard(notification) { [self] in
|
|
108
|
+
contentInset.bottom = keyboardInset
|
|
109
|
+
verticalScrollIndicatorInsets.bottom = keyboardInset
|
|
110
|
+
contentOffset.y = offsetRevealing(focusedInput(in: self), above: keyboardTop)
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/// Scrolls up just enough for `input` to sit above the keyboard; when the keyboard leaves, back within the content.
|
|
115
|
+
private func offsetRevealing(_ input: UIView?, above keyboardTop: CGFloat) -> CGFloat {
|
|
116
|
+
let maximumOffset = max(-adjustedContentInset.top, contentSize.height + adjustedContentInset.bottom - bounds.height)
|
|
117
|
+
guard let input else { return min(contentOffset.y, maximumOffset) }
|
|
118
|
+
|
|
119
|
+
let inputBottom = input.convert(input.bounds, to: self).maxY
|
|
120
|
+
|
|
121
|
+
return min(contentOffset.y + max(0, inputBottom - keyboardTop), maximumOffset)
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
private func focusedInput(in view: UIView) -> UIView? {
|
|
125
|
+
if view.isFirstResponder { return view }
|
|
126
|
+
|
|
127
|
+
return view.subviews.lazy.compactMap(focusedInput(in:)).first
|
|
128
|
+
}
|
|
129
|
+
|
|
81
130
|
@objc private func handleTap(_ recognizer: UITapGestureRecognizer) {
|
|
82
131
|
guard dismissesKeyboardOnTap else { return }
|
|
83
132
|
|
package/package.json
CHANGED
package/src/components.ts
CHANGED
|
@@ -3,7 +3,9 @@ import {
|
|
|
3
3
|
computed,
|
|
4
4
|
defineComponent,
|
|
5
5
|
h,
|
|
6
|
+
onBeforeUnmount,
|
|
6
7
|
ref,
|
|
8
|
+
watch,
|
|
7
9
|
type PropType,
|
|
8
10
|
type SlotsType,
|
|
9
11
|
type VNode,
|
|
@@ -12,25 +14,56 @@ import type { ScrollEvent, Style } from './types'
|
|
|
12
14
|
|
|
13
15
|
type Listener = ((payload: unknown) => void) | undefined
|
|
14
16
|
|
|
17
|
+
const MINIMUM_PRESSED_TIME = 130 // ms
|
|
18
|
+
|
|
15
19
|
// Vue's template compiler normalizes `:style`, so it can't be a function of the pressed state: the pressed
|
|
16
20
|
// look goes in `pressed-style`, merged over `style` while pressed. The slot also receives { pressed },
|
|
17
|
-
// and the class its pressed styles (Tailwind's active:).
|
|
21
|
+
// and the class its pressed styles (Tailwind's active:). A disabled one ignores touches.
|
|
18
22
|
export const Pressable = defineComponent({
|
|
19
23
|
name: 'Pressable',
|
|
20
24
|
inheritAttrs: false,
|
|
21
|
-
props: {
|
|
25
|
+
props: {
|
|
26
|
+
style: Object as PropType<Style>,
|
|
27
|
+
pressedStyle: Object as PropType<Style>,
|
|
28
|
+
disabled: Boolean,
|
|
29
|
+
},
|
|
22
30
|
slots: Object as SlotsType<{ default: { pressed: boolean } }>,
|
|
23
31
|
|
|
24
32
|
setup(props, { attrs, slots }) {
|
|
25
33
|
const pressed = ref(false)
|
|
34
|
+
let pressedAt = 0
|
|
35
|
+
let releaseTimeout: ReturnType<typeof setTimeout> | undefined
|
|
26
36
|
|
|
27
|
-
function
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
listener?.(payload)
|
|
31
|
-
}
|
|
37
|
+
function release() {
|
|
38
|
+
clearTimeout(releaseTimeout)
|
|
39
|
+
pressed.value = false
|
|
32
40
|
}
|
|
33
41
|
|
|
42
|
+
// Disabled mid-press, the native view may never send the pressout.
|
|
43
|
+
watch(
|
|
44
|
+
() => props.disabled,
|
|
45
|
+
(disabled) => {
|
|
46
|
+
if (disabled) release()
|
|
47
|
+
},
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
function handlePressIn(payload: unknown) {
|
|
51
|
+
clearTimeout(releaseTimeout)
|
|
52
|
+
pressedAt = Date.now()
|
|
53
|
+
pressed.value = true
|
|
54
|
+
;(attrs.onPressIn as Listener)?.(payload)
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// A quick tap would show the pressed style for less than a frame: keep it for a moment.
|
|
58
|
+
function handlePressOut(payload: unknown) {
|
|
59
|
+
const remainingTime = MINIMUM_PRESSED_TIME - (Date.now() - pressedAt)
|
|
60
|
+
|
|
61
|
+
releaseTimeout = setTimeout(release, Math.max(0, remainingTime))
|
|
62
|
+
;(attrs.onPressOut as Listener)?.(payload)
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
onBeforeUnmount(() => clearTimeout(releaseTimeout))
|
|
66
|
+
|
|
34
67
|
return () => {
|
|
35
68
|
const style = pressed.value ? { ...props.style, ...props.pressedStyle } : props.style
|
|
36
69
|
|
|
@@ -40,8 +73,9 @@ export const Pressable = defineComponent({
|
|
|
40
73
|
...attrs,
|
|
41
74
|
style,
|
|
42
75
|
pressed: pressed.value,
|
|
43
|
-
|
|
44
|
-
|
|
76
|
+
disabled: props.disabled || undefined, // unset, nothing to send
|
|
77
|
+
onPressIn: handlePressIn,
|
|
78
|
+
onPressOut: handlePressOut,
|
|
45
79
|
},
|
|
46
80
|
slots.default?.({ pressed: pressed.value }),
|
|
47
81
|
)
|
|
@@ -53,10 +87,12 @@ const OFFSCREEN_ROWS_RENDERED = 10
|
|
|
53
87
|
|
|
54
88
|
// Renders only the rows near the visible area; the rest is empty padding of the same height.
|
|
55
89
|
// Slots: #item="{ item, index }", plus #header, #footer and #empty.
|
|
56
|
-
//
|
|
90
|
+
// Limitation: Rows have a fixed `itemHeight`; measure rows natively if
|
|
57
91
|
// variable heights are ever needed. Vertical only. The window ignores the header's height, which the
|
|
58
92
|
// offscreen rows absorb while the header is shorter than them; measure it if tall headers show gaps.
|
|
59
|
-
//
|
|
93
|
+
// Limitation: Items are `any` in the #item slot; make FlatList generic if typed rows are wanted.
|
|
94
|
+
// Limitation: An Animated.event `:on-scroll` replaces the window's own scroll handler, and a mapped event
|
|
95
|
+
// reaches JS only when a scroll starts and ends; report frames to both natively if that's needed.
|
|
60
96
|
export const FlatList = defineComponent({
|
|
61
97
|
name: 'FlatList',
|
|
62
98
|
props: {
|
package/src/fetch.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// fetch, Headers and Response, like the browser's: native runs the request with
|
|
2
2
|
// URLSession and calls back __fetchFinished.
|
|
3
|
-
//
|
|
3
|
+
// Limitation: Text bodies only (no Blob, FormData or streaming) and no AbortController.
|
|
4
4
|
const native = globalThis.__native
|
|
5
5
|
|
|
6
6
|
interface PendingRequest {
|
|
@@ -68,7 +68,7 @@ class FetchResponse {
|
|
|
68
68
|
return this.body
|
|
69
69
|
}
|
|
70
70
|
|
|
71
|
-
//
|
|
71
|
+
// Limitation: `any` like the DOM's json(); type it at the call site.
|
|
72
72
|
async json(): Promise<any> {
|
|
73
73
|
return JSON.parse(this.body)
|
|
74
74
|
}
|
|
@@ -96,7 +96,10 @@ function fetch(
|
|
|
96
96
|
}
|
|
97
97
|
|
|
98
98
|
globalThis.__fetchFinished = (requestId, response, errorMessage) => {
|
|
99
|
-
const
|
|
99
|
+
const request = pendingRequestsById.get(requestId)
|
|
100
|
+
if (!request) return
|
|
101
|
+
|
|
102
|
+
const { resolve, reject, url } = request
|
|
100
103
|
pendingRequestsById.delete(requestId)
|
|
101
104
|
|
|
102
105
|
if (errorMessage || !response) reject(new TypeError(`Network request failed: ${errorMessage}`))
|
package/src/native-components.ts
CHANGED
|
@@ -36,6 +36,8 @@ declare module '@vue/runtime-core' {
|
|
|
36
36
|
keyboardDismissMode?: 'none' | 'on-drag' | 'interactive'
|
|
37
37
|
keyboardShouldPersistTaps?: 'never' | 'always' | 'handled'
|
|
38
38
|
contentInsetAdjustmentBehavior?: 'automatic' | 'scrollableAxes' | 'never' | 'always'
|
|
39
|
+
/** The keyboard insets the content, and the focused input scrolls above it. */
|
|
40
|
+
automaticallyAdjustKeyboardInsets?: boolean
|
|
39
41
|
onScroll?: EventHandler<ScrollEvent>
|
|
40
42
|
onRefresh?: () => void
|
|
41
43
|
}>
|
|
@@ -46,7 +48,12 @@ declare module '@vue/runtime-core' {
|
|
|
46
48
|
keyboardType?: 'default' | 'numeric' | 'decimal-pad' | 'email-address' | 'phone-pad' | 'url'
|
|
47
49
|
secureTextEntry?: boolean
|
|
48
50
|
onChangeText?: (text: string) => void
|
|
51
|
+
disabled?: boolean
|
|
49
52
|
onSubmitEditing?: (text: string) => void
|
|
53
|
+
onFocus?: () => void
|
|
54
|
+
onBlur?: () => void
|
|
55
|
+
/** Merged over `style` while the input has focus. */
|
|
56
|
+
focusedStyle?: Style
|
|
50
57
|
}
|
|
51
58
|
>
|
|
52
59
|
Image: NativeComponent<{
|