@nativue/core 0.15.3 → 0.16.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/ios/Bridge.swift CHANGED
@@ -200,7 +200,7 @@ final class Bridge {
200
200
  windowSizeDidChange(to: rootView.bounds.size)
201
201
 
202
202
  for contentRoot in contentRootsByNodeId.values {
203
- (contentRoot as? ModalController)?.dismissIfDetached()
203
+ (contentRoot as? ModalController)?.followPlaceholder()
204
204
  contentRoot.layoutContent()
205
205
  }
206
206
  }
@@ -491,8 +491,7 @@ final class Bridge {
491
491
  // MARK: - Main thread
492
492
 
493
493
  private func resetNodeTree() {
494
- // Sheets of the old tree's screen stacks too, which only their stack knows about.
495
- rootView.hostWindow?.rootViewController?.dismiss(animated: false)
494
+ dismissPresentedControllers()
496
495
  rootView.subviews.forEach { $0.removeFromSuperview() }
497
496
  contentRootsByNodeId.values.forEach { ($0 as? ModalController)?.setVisible(false) }
498
497
  contentRootsByNodeId = [:]
@@ -539,7 +538,7 @@ final class Bridge {
539
538
  private func forgetNode(id: Int) {
540
539
  let node = nodesById.removeValue(forKey: id)
541
540
  (node?.view as? ScreenStackView)?.dismissPresentedScreens()
542
- modalController(id)?.dismissIfDetached()
541
+ modalController(id)?.detach()
543
542
  contentRootsByNodeId[id] = nil
544
543
  gestureReportersByNodeId[id] = nil
545
544
  reportedLayoutsByNodeId[id] = nil
@@ -569,6 +568,29 @@ final class Bridge {
569
568
  evaluate { [unowned self] in runtime?.call("__layoutsChanged", arguments: [changedLayouts]) }
570
569
  }
571
570
 
571
+ /// What's presented over the controller holding the root view: an app's own sheet holding the
572
+ /// NativueView stays.
573
+ private func dismissPresentedControllers() {
574
+ guard let root = rootView.hostWindow?.rootViewController else { return }
575
+
576
+ let presentations = Array(sequence(first: root, next: \.presentedViewController))
577
+ guard let holderIndex = presentations.lastIndex(where: { rootView.isDescendant(of: $0.view) }),
578
+ holderIndex < presentations.count - 1 else { return }
579
+
580
+ presentations[holderIndex].dismiss(animated: false)
581
+ }
582
+
583
+ /// In the window, or under a full-screen modal that the controller holding it presented: UIKit takes
584
+ /// the views under one out of the window. A screen pushed under another, or an unselected tab, is not.
585
+ private func isOnScreen(_ view: UIView) -> Bool {
586
+ if view.window != nil { return true }
587
+
588
+ let holder = sequence(first: view, next: { $0.superview }).compactMap { $0.next as? UIViewController }.last
589
+ guard let holder, let presented = holder.presentedViewController else { return false }
590
+
591
+ return presented.presentingViewController === holder
592
+ }
593
+
572
594
  private func modalController(_ id: Int) -> ModalController? {
573
595
  contentRootsByNodeId[id] as? ModalController
574
596
  }
@@ -616,9 +638,6 @@ final class Bridge {
616
638
  case "SwipeableView":
617
639
  return NativeNode(view: SwipeableView(frame: .zero), measuresContent: false)
618
640
 
619
- case "Svg":
620
- return NativeNode(view: SvgView(frame: .zero), measuresContent: false)
621
-
622
641
  case "PressableView":
623
642
  let pressableView = PressableView()
624
643
  pressableView.onEvent = { [unowned self] eventName in dispatchEvent(eventName, toNodeId: id) }
@@ -682,6 +701,10 @@ final class Bridge {
682
701
  case "Modal":
683
702
  let modalController = ModalController()
684
703
  modalController.onEvent = { [unowned self] eventName in dispatchEvent(eventName, toNodeId: id) }
704
+ modalController.hostWindow = { [unowned self] in rootView.hostWindow }
705
+ modalController.isPlaceholderOnScreen = { [unowned self, unowned modalController] in
706
+ isOnScreen(modalController.placeholderView)
707
+ }
685
708
  contentRootsByNodeId[id] = modalController
686
709
 
687
710
  let node = NativeNode(view: modalController.placeholderView, measuresContent: false)
@@ -879,10 +902,13 @@ final class Bridge {
879
902
  node.markContentChanged()
880
903
  }
881
904
 
905
+ /// What nativue applies to any view, plugin views included: style, accessibility, layout and gestures.
906
+ private static let viewProps: Set<String> = ["style", "accessibility", "onLayout", "onPan", "onPinch", "onRotate"]
907
+
882
908
  private func setProp(_ key: String, value: Any?, onNodeId id: Int) {
883
909
  guard let node = nodesById[id] else { return }
884
910
 
885
- if key != "style", let pluginView = node.view as? PluginView {
911
+ if !Self.viewProps.contains(key), let pluginView = node.view as? PluginView {
886
912
  pluginView.setProp(key, value: value is NSNull ? nil : value)
887
913
  return
888
914
  }
@@ -910,9 +936,13 @@ final class Bridge {
910
936
 
911
937
  case "tabBarItem":
912
938
  let item = value as? [String: Any] ?? [:]
913
- screenController(id)?.setTabBarItem(
939
+ let screen = screenController(id)
940
+ let image = screen.flatMap { screen in
941
+ NavigationIcons.image(item, size: 25, for: screen) { [weak screen] image in screen?.tabBarItem.image = image }
942
+ }
943
+ screen?.setTabBarItem(
914
944
  label: item["label"] as? String,
915
- image: SvgView.iconImage(item),
945
+ image: image,
916
946
  badge: (item["badge"] as? CustomStringConvertible)?.description
917
947
  )
918
948
 
@@ -975,16 +1005,6 @@ final class Bridge {
975
1005
 
976
1006
  case "color":
977
1007
  (node.view as? UIActivityIndicatorView)?.color = UIColor(rgba: value as Any)
978
- (node.view as? SvgView)?.color = UIColor(rgba: value as Any) ?? .black
979
-
980
- case "viewBox":
981
- if let viewBox = SvgView.rect(fromViewBox: value) { (node.view as? SvgView)?.viewBox = viewBox }
982
-
983
- case "elements":
984
- (node.view as? SvgView)?.elements = value as? [[Any]] ?? []
985
-
986
- case "strokeWidth":
987
- (node.view as? SvgView)?.strokeWidth = CGFloat((value as? NSNumber)?.doubleValue ?? 2)
988
1008
 
989
1009
  case "visible":
990
1010
  modalController(id)?.setVisible(isTruthyAttribute(value))
@@ -32,7 +32,7 @@ final class ImageView: UIImageView {
32
32
  /// The image changed, and with it the size the view measures.
33
33
  var onImageChange: (() -> Void)?
34
34
 
35
- /// "disk", "memory" or "none". Read when a download finishes, so it applies even when set after `source`.
35
+ /// "disk", "memory" or "none". Read once loading starts, so it applies even when set after `source`.
36
36
  var cachePolicy = "disk"
37
37
 
38
38
  private var loadingTask: Task<Void, Never>?
@@ -57,28 +57,45 @@ final class ImageView: UIImageView {
57
57
  }
58
58
 
59
59
  show(nil)
60
- let readsDisk = cachePolicy == "disk"
61
60
  loadingTask = Task { [weak self] in
62
- let cachedData = readsDisk ? await Task.detached { ImageDiskCache.data(for: source) }.value : nil
63
- let downloadedData = cachedData == nil ? await Self.download(source, from: url) : nil
64
61
  guard
65
- let data = cachedData ?? downloadedData,
66
- let image = await UIImage(data: data)?.byPreparingForDisplay(), // decoded off the main thread
62
+ let cachePolicy = self?.cachePolicy,
63
+ let image = await Self.image(for: source, from: url, cachePolicy: cachePolicy),
67
64
  !Task.isCancelled,
68
65
  let self
69
66
  else { return }
70
67
 
71
- store(image, downloadedData: downloadedData, for: source)
72
68
  show(image)
73
69
  }
74
70
  }
75
71
 
76
- private func store(_ image: UIImage, downloadedData: Data?, for source: String) {
72
+ /// An image as <Image> loads it: from memory, the disk cache or its url, then kept as `cachePolicy` says.
73
+ static func image(for source: String, cachePolicy: String = "disk") async -> UIImage? {
74
+ if cachePolicy != "none", let cachedImage = decodedImages.object(forKey: source as NSString) { return cachedImage }
75
+ guard let url = URL(string: source) else { return nil }
76
+
77
+ return await image(for: source, from: url, cachePolicy: cachePolicy)
78
+ }
79
+
80
+ private static func image(for source: String, from url: URL, cachePolicy: String) async -> UIImage? {
81
+ let cachedData = cachePolicy == "disk" ? await Task.detached { ImageDiskCache.data(for: source) }.value : nil
82
+ let downloadedData = cachedData == nil ? await download(source, from: url) : nil
83
+ guard
84
+ let data = cachedData ?? downloadedData,
85
+ let image = await UIImage(data: data)?.byPreparingForDisplay() // decoded off the main thread
86
+ else { return nil }
87
+
88
+ store(image, downloadedData: downloadedData, for: source, cachePolicy: cachePolicy)
89
+
90
+ return image
91
+ }
92
+
93
+ private static func store(_ image: UIImage, downloadedData: Data?, for source: String, cachePolicy: String) {
77
94
  guard cachePolicy != "none" else { return }
78
95
 
79
- Self.decodedImages.setObject(image, forKey: source as NSString, cost: Self.byteCount(of: image))
96
+ decodedImages.setObject(image, forKey: source as NSString, cost: byteCount(of: image))
80
97
 
81
- guard cachePolicy == "disk", let downloadedData, !Self.isInMemory(source) else { return }
98
+ guard cachePolicy == "disk", let downloadedData, !isInMemory(source) else { return }
82
99
  Task.detached(priority: .utility) { ImageDiskCache.store(downloadedData, for: source) }
83
100
  }
84
101
 
@@ -130,6 +147,11 @@ final class ImageView: UIImageView {
130
147
  }
131
148
  }
132
149
 
150
+ /// An image loaded and cached as <Image> does it: for a package's views.
151
+ public func loadImage(_ source: String) async -> UIImage? {
152
+ await ImageView.image(for: source)
153
+ }
154
+
133
155
  /// Downloaded images by url, in the system's caches folder, which iOS may empty when storage runs low. Past
134
156
  /// its limit, the images used least recently go first.
135
157
  private enum ImageDiskCache {
@@ -14,6 +14,11 @@ final class ModalController: UIViewController, ContentRoot, UIAdaptivePresentati
14
14
  let placeholderView = UIView()
15
15
 
16
16
  var onEvent: ((String) -> Void)?
17
+ /// The app's window: the placeholder's is nil while a full-screen modal covers it.
18
+ var hostWindow: () -> UIWindow? = { nil }
19
+ /// The placeholder is in the window, or covered by a full-screen modal: not in a screen pushed under
20
+ /// another, an unselected tab or a deactivated <KeepAlive>.
21
+ var isPlaceholderOnScreen: () -> Bool = { false }
17
22
  var animationType = "none"
18
23
  var presentationStyleName = "fullScreen"
19
24
  var transparent = false
@@ -39,20 +44,26 @@ final class ModalController: UIViewController, ContentRoot, UIAdaptivePresentati
39
44
  contentNode.calculateLayout(width: view.bounds.width, height: view.bounds.height)
40
45
  }
41
46
 
42
- /// Deferred to after the current batch, so the placeholder is already in the window when presenting.
47
+ /// Deferred to after the current batch, so the placeholder is already on screen when presenting.
43
48
  func setVisible(_ visible: Bool) {
44
49
  wantsVisible = visible
45
50
  DispatchQueue.main.async { [self] in applyVisibility() }
46
51
  }
47
52
 
48
53
  /// The <Modal> left the tree (an ancestor's v-if): its content must go too.
49
- func dismissIfDetached() {
50
- guard placeholderView.window == nil else { return }
51
-
54
+ func detach() {
52
55
  wantsVisible = false
53
56
  applyVisibility()
54
57
  }
55
58
 
59
+ /// Closed while its placeholder is off screen (a tab switched, a <KeepAlive> deactivated), and shown
60
+ /// again when it's back, if JS still wants it.
61
+ func followPlaceholder() {
62
+ guard !isTransitioning else { return }
63
+
64
+ if !isPlaceholderOnScreen() { dismissIfPresented() } else if wantsVisible && !isPresented { present() }
65
+ }
66
+
56
67
  private func applyVisibility() {
57
68
  guard !isTransitioning else { return }
58
69
 
@@ -60,7 +71,7 @@ final class ModalController: UIViewController, ContentRoot, UIAdaptivePresentati
60
71
  }
61
72
 
62
73
  private func present() {
63
- guard !isPresented, let presenter = topViewController() else { return }
74
+ guard !isPresented, isPlaceholderOnScreen(), let presenter = topViewController() else { return }
64
75
 
65
76
  view.backgroundColor = transparent ? .clear : .systemBackground
66
77
  modalPresentationStyle = transparent
@@ -89,7 +100,7 @@ final class ModalController: UIViewController, ContentRoot, UIAdaptivePresentati
89
100
  }
90
101
 
91
102
  private func topViewController() -> UIViewController? {
92
- var top = placeholderView.window?.rootViewController
103
+ var top = hostWindow()?.rootViewController
93
104
 
94
105
  while let presented = top?.presentedViewController, presented !== self {
95
106
  top = presented
@@ -0,0 +1,49 @@
1
+ import UIKit
2
+
3
+ /// The icons of tab bars and headers: an SF Symbol (`systemImage`), an image (`image`, a url), or one a
4
+ /// package draws (`drawnIcon`, registered with PluginRegistry.addIconDrawer). Tinted by what shows them.
5
+ enum NavigationIcons {
6
+ static var drawersByName: [String: PluginRegistry.DrawIcon] = [:]
7
+ /// The url each item (a tab, a header button) shows last: a slower load of an earlier one is dropped.
8
+ private static let sourcesByOwner = NSMapTable<AnyObject, NSString>.weakToStrongObjects()
9
+
10
+ /// The icon now, or nil with `update` called (on the main thread) once an image loads, if `owner` still
11
+ /// shows that image then.
12
+ static func image(
13
+ _ item: [String: Any], size: CGFloat, for owner: AnyObject, update: @escaping (UIImage) -> Void
14
+ ) -> UIImage? {
15
+ sourcesByOwner.setObject((item["image"] as? String) as NSString?, forKey: owner)
16
+ if let name = item["systemImage"] as? String { return UIImage(systemName: name) }
17
+ if let source = item["image"] as? String {
18
+ Task { @MainActor [weak owner] in
19
+ guard
20
+ let image = await loadImage(source),
21
+ let owner,
22
+ sourcesByOwner.object(forKey: owner) as String? == source
23
+ else { return }
24
+
25
+ update(fitted(image, size: size))
26
+ }
27
+
28
+ return nil
29
+ }
30
+ guard
31
+ let icon = item["drawnIcon"] as? [String: Any],
32
+ let drawer = icon["drawer"] as? String,
33
+ let draw = drawersByName[drawer]
34
+ else { return nil }
35
+
36
+ return draw(icon, size)?.withRenderingMode(.alwaysTemplate)
37
+ }
38
+
39
+ /// Scaled to fit a square of `size` points, as the bar expects.
40
+ private static func fitted(_ image: UIImage, size: CGFloat) -> UIImage {
41
+ let scale = min(size / max(image.size.width, 1), size / max(image.size.height, 1))
42
+ let fittedSize = CGSize(width: image.size.width * scale, height: image.size.height * scale)
43
+ let fittedImage = UIGraphicsImageRenderer(size: fittedSize).image { _ in
44
+ image.draw(in: CGRect(origin: .zero, size: fittedSize))
45
+ }
46
+
47
+ return fittedImage.withRenderingMode(.alwaysTemplate)
48
+ }
49
+ }
package/ios/Plugins.swift CHANGED
@@ -14,6 +14,8 @@ public final class PluginRegistry {
14
14
  /// sendEvent("change", payload) reaches the element's @change; event names are lowercase.
15
15
  public typealias SendEvent = (_ eventName: String, _ payload: Any?) -> Void
16
16
  public typealias MakeView = (_ sendEvent: @escaping SendEvent) -> UIView
17
+ /// An icon JS describes ({ drawer, ... }) drawn at `size` points, for a tab bar or a header.
18
+ public typealias DrawIcon = (_ icon: [String: Any], _ size: CGFloat) -> UIImage?
17
19
 
18
20
  /// Set by the Bridge: calls JavaScript's listeners.
19
21
  var sendToJavaScript: (_ eventName: String, _ payload: Any?) -> Void = { _, _ in }
@@ -47,8 +49,18 @@ public final class PluginRegistry {
47
49
  public func addView(_ type: String, _ makeView: @escaping MakeView) {
48
50
  viewMakers[type] = makeView
49
51
  }
52
+
53
+ /// Draws the tab bar and header icons whose `drawnIcon.drawer` is `drawer` (see router.ts's DrawnIcon).
54
+ /// The image is tinted, like an SF Symbol: only its shape counts.
55
+ public func addIconDrawer(_ drawer: String, _ draw: @escaping DrawIcon) {
56
+ NavigationIcons.drawersByName[drawer] = draw
57
+ }
50
58
  }
51
59
 
60
+ /// A plugin view that takes its own touches where `point(inside:with:)` says, which a <Pressable> around it
61
+ /// leaves to it.
62
+ public protocol InteractiveView: UIView {}
63
+
52
64
  /// Thrown by an async function: JavaScript's Promise rejects with an Error whose `code` is this one.
53
65
  /// Codes nativue's packages share: ERR_PERMISSION_DENIED, ERR_UNAVAILABLE, ERR_CANCELED,
54
66
  /// ERR_INVALID_ARGUMENT.
@@ -64,7 +76,7 @@ public struct PluginError: LocalizedError {
64
76
  public var errorDescription: String? { message }
65
77
  }
66
78
 
67
- /// A plugin view gets its props here, all but `style`, which nativue applies (layout included).
79
+ /// A plugin view gets its props here, all but `style`, `accessibility`, `@layout` and the gestures (`@pan`...), which nativue applies.
68
80
  public protocol PluginView: UIView {
69
81
  func setProp(_ key: String, value: Any?)
70
82
  }
@@ -51,7 +51,9 @@ final class PressableView: UIControl {
51
51
  private func isInteractiveChild(_ view: UIView) -> Bool {
52
52
  sequence(first: view, next: \.superview)
53
53
  .prefix { $0 !== self }
54
- .contains { $0 is UIControl || $0 is UIScrollView || !($0.gestureRecognizers ?? []).isEmpty }
54
+ .contains {
55
+ $0 is UIControl || $0 is UIScrollView || $0 is InteractiveView || !($0.gestureRecognizers ?? []).isEmpty
56
+ }
55
57
  }
56
58
 
57
59
  /// VoiceOver's double tap: a press, even when something interactive sits under the activation point.
@@ -111,12 +111,15 @@ final class ScreenController: UIViewController, ContentRoot {
111
111
 
112
112
  private func makeBarButtonItem(_ description: [String: Any], side: String, index: Int) -> UIBarButtonItem {
113
113
  let title = description["title"] as? String ?? ""
114
- let image = SvgView.iconImage(description, size: 22)
114
+ let barButtonItem = UIBarButtonItem()
115
+ let image = NavigationIcons.image(description, size: 22, for: barButtonItem) { [weak barButtonItem] image in
116
+ barButtonItem?.image = image
117
+ }
115
118
 
116
- let action = UIAction(title: title, image: image) { [unowned self] _ in
119
+ barButtonItem.primaryAction = UIAction(title: title, image: image) { [unowned self] _ in
117
120
  onEvent?("headeritempress", ["side": side, "index": index])
118
121
  }
119
122
 
120
- return UIBarButtonItem(primaryAction: action)
123
+ return barButtonItem
121
124
  }
122
125
  }
package/ios/Style.swift CHANGED
@@ -357,7 +357,7 @@ private let fontWeights: [String: UIFont.Weight] = [
357
357
 
358
358
  extension UIColor {
359
359
  /// Colors arrive as 0xRRGGBBAA numbers: the JS side (src/colors.js) parses every CSS format.
360
- convenience init?(rgba value: Any) {
360
+ public convenience init?(rgba value: Any) {
361
361
  guard let rgba = (value as? NSNumber)?.uint32Value else { return nil }
362
362
 
363
363
  self.init(
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nativue/core",
3
- "version": "0.15.3",
3
+ "version": "0.16.0",
4
4
  "description": "Vue rendering real native views on iOS and Android",
5
5
  "keywords": [
6
6
  "vue",
@@ -24,13 +24,6 @@ export interface AccessibilityProps {
24
24
  'aria-checked'?: BooleanAttribute
25
25
  }
26
26
  type EventHandler<Payload> = ((payload: Payload) => void) | AnimatedEvent<Payload>
27
- // [tag, attributes], e.g. ['circle', { cx: 12, cy: 12, r: 10 }]: path, circle, ellipse, rect, line,
28
- // polyline and polygon. Stroked with `color`; filled too when `fill` isn't 'none'.
29
- export type SvgElement = [tag: string, attributes: Record<string, string | number>]
30
- // An icon component that carries its drawing, so it can also be a tab bar icon (see @nativue/icons).
31
- export interface SvgIcon {
32
- svg: { viewBox: [number, number, number, number]; elements: SvgElement[] }
33
- }
34
27
  type ModelProps<Value> = { modelValue?: Value; 'onUpdate:modelValue'?: (value: Value) => void }
35
28
 
36
29
  declare module '@vue/runtime-core' {
@@ -91,13 +84,6 @@ declare module '@vue/runtime-core' {
91
84
  color?: string
92
85
  size?: 'small' | 'large'
93
86
  }>
94
- // Low level: draws SVG elements, e.g. an icon set's nodes (see @nativue/icons).
95
- Svg: NativeComponent<{
96
- viewBox?: [number, number, number, number]
97
- elements: SvgElement[]
98
- color?: string
99
- strokeWidth?: number
100
- }>
101
87
  Modal: NativeComponent<{
102
88
  visible?: boolean
103
89
  animationType?: 'none' | 'slide' | 'fade'