@nativue/core 0.4.2 → 0.4.4

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.
@@ -8,6 +8,7 @@ import android.graphics.Rect
8
8
  import android.os.Handler
9
9
  import android.os.Looper
10
10
  import android.util.Base64
11
+ import android.util.LruCache
11
12
  import android.view.MotionEvent
12
13
  import android.view.View
13
14
  import android.view.ViewConfiguration
@@ -20,7 +21,9 @@ import android.widget.ProgressBar
20
21
  import android.widget.ScrollView
21
22
  import android.widget.Switch
22
23
  import java.net.URL
23
- import kotlin.concurrent.thread
24
+ import java.util.concurrent.Executors
25
+ import kotlin.math.min
26
+ import kotlin.math.roundToInt
24
27
  import kotlin.math.abs
25
28
 
26
29
  /**
@@ -32,6 +35,35 @@ open class ContainerView(context: Context) : ViewGroup(context) {
32
35
  clipChildren = false
33
36
  }
34
37
 
38
+ /** Set while it reports @pan, @pinch or @rotate. */
39
+ var gestureReporter: GestureReporter? = null
40
+
41
+ /** A descendant took this touch (a scroll view scrolling, an inner gesture): its own gesture stands down. */
42
+ private var isTouchClaimedByChild = false
43
+
44
+ override fun requestDisallowInterceptTouchEvent(disallowIntercept: Boolean) {
45
+ isTouchClaimedByChild = disallowIntercept
46
+ super.requestDisallowInterceptTouchEvent(disallowIntercept)
47
+ }
48
+
49
+ /**
50
+ * Children get each touch first, then the gesture sees it too, like iOS's gesture recognizers. Once
51
+ * the gesture is recognized, onInterceptTouchEvent takes the touch: the child gets a cancel (a
52
+ * <Pressable> doesn't fire @press).
53
+ */
54
+ override fun dispatchTouchEvent(event: MotionEvent): Boolean {
55
+ val reporter = gestureReporter ?: return super.dispatchTouchEvent(event)
56
+ if (event.actionMasked == MotionEvent.ACTION_DOWN) isTouchClaimedByChild = false
57
+
58
+ super.dispatchTouchEvent(event)
59
+ if (!isTouchClaimedByChild || reporter.isRecognizing) reporter.handle(event)
60
+
61
+ return true
62
+ }
63
+
64
+ override fun onInterceptTouchEvent(event: MotionEvent): Boolean =
65
+ gestureReporter?.isRecognizing == true || super.onInterceptTouchEvent(event)
66
+
35
67
  /** Without an exact size (inside a scroll view), the size set in its layout params. */
36
68
  override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
37
69
  setMeasuredDimension(
@@ -81,6 +113,22 @@ class PressableView(context: Context) : ContainerView(context) {
81
113
  private val longPressHandler = Handler(Looper.getMainLooper())
82
114
  private var didLongPress = false
83
115
 
116
+ init {
117
+ isClickable = true // so TalkBack can activate it
118
+ }
119
+
120
+ /** TalkBack's double tap. Touches don't come through here: onTouchEvent reports them. */
121
+ override fun performClick(): Boolean {
122
+ super.performClick()
123
+ if (!isEnabled) return false
124
+
125
+ onEvent("pressin")
126
+ onEvent("pressout")
127
+ onEvent("press")
128
+
129
+ return true
130
+ }
131
+
84
132
  @SuppressLint("ClickableViewAccessibility")
85
133
  override fun onTouchEvent(event: MotionEvent): Boolean {
86
134
  // Consumed but ignored, as disabled Android buttons do: the touch doesn't reach a parent.
@@ -171,6 +219,7 @@ class ScrollContainerView(context: Context) : ContainerView(context) {
171
219
  private var isPullingToRefresh = false
172
220
 
173
221
  init {
222
+ clipChildren = true // like a UIScrollView: scrolled content stays inside the list
174
223
  addView(scroller)
175
224
  addView(refreshIndicator)
176
225
  }
@@ -439,9 +488,18 @@ private fun pageOffset(offset: Int, pageSize: Int, velocity: Int): Int {
439
488
  return targetPage.toInt() * pageSize
440
489
  }
441
490
 
442
- /** Loads `data:` URIs (bundled images) and http(s) URLs off the main thread. */
491
+ /**
492
+ * Loads `data:` URIs (bundled images) and http(s) URLs off the main thread. Decoded images are kept in
493
+ * memory, so one that comes back on screen (a list row) shows at once.
494
+ */
495
+ // Limitation: No HTTP disk cache, unlike iOS's URLCache: after a relaunch images download again. Give image
496
+ // requests their own cache if that matters (a global HttpResponseCache would also cache the dev bundle).
443
497
  class RemoteImageView(context: Context) : ImageView(context) {
498
+ /** The image changed, and with it the size the view measures. */
499
+ var onImageChange: () -> Unit = {}
500
+
444
501
  private var source: String? = null
502
+ private var bitmap: Bitmap? = null
445
503
 
446
504
  init {
447
505
  scaleType = ScaleType.CENTER_CROP
@@ -451,15 +509,54 @@ class RemoteImageView(context: Context) : ImageView(context) {
451
509
  if (source == this.source) return
452
510
 
453
511
  this.source = source
454
- setImageDrawable(null)
455
- if (source == null) return
512
+ show(source?.let(decodedImages::get))
513
+ if (source == null || bitmap != null) return
456
514
 
457
- thread {
458
- val bitmap = runCatching { decode(source) }.getOrNull()
459
- post { if (source == this.source) setImageBitmap(bitmap) }
515
+ loader.execute {
516
+ val bitmap = runCatching { decode(source) }.getOrNull() ?: return@execute
517
+ decodedImages.put(source, bitmap)
518
+ post { if (source == this.source) show(bitmap) }
460
519
  }
461
520
  }
462
521
 
522
+ private fun show(nextBitmap: Bitmap?) {
523
+ if (nextBitmap === bitmap) return
524
+
525
+ bitmap = nextBitmap
526
+ setImageBitmap(nextBitmap)
527
+ onImageChange()
528
+ }
529
+
530
+ /**
531
+ * Without a width or height, the image takes its own size, a pixel per dp; given one of them, the other
532
+ * follows its aspect ratio, as on the web.
533
+ */
534
+ override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
535
+ val density = resources.displayMetrics.density
536
+ val naturalWidth = (bitmap?.width ?: 0) * density
537
+ val naturalHeight = (bitmap?.height ?: 0) * density
538
+ val widthMode = MeasureSpec.getMode(widthMeasureSpec)
539
+ val heightMode = MeasureSpec.getMode(heightMeasureSpec)
540
+ val width = MeasureSpec.getSize(widthMeasureSpec).toFloat()
541
+ val height = MeasureSpec.getSize(heightMeasureSpec).toFloat()
542
+ val maxWidth = if (widthMode == MeasureSpec.UNSPECIFIED) Float.POSITIVE_INFINITY else width
543
+ val maxHeight = if (heightMode == MeasureSpec.UNSPECIFIED) Float.POSITIVE_INFINITY else height
544
+ val aspectRatio = naturalWidth / naturalHeight
545
+
546
+ val (measuredWidth, measuredHeight) = when {
547
+ widthMode == MeasureSpec.EXACTLY && heightMode == MeasureSpec.EXACTLY -> width to height
548
+ naturalWidth == 0f || naturalHeight == 0f ->
549
+ (if (widthMode == MeasureSpec.EXACTLY) width else 0f) to (if (heightMode == MeasureSpec.EXACTLY) height else 0f)
550
+ widthMode == MeasureSpec.EXACTLY -> width to min(width / aspectRatio, maxHeight)
551
+ heightMode == MeasureSpec.EXACTLY -> min(height * aspectRatio, maxWidth) to height
552
+ else -> {
553
+ val scale = minOf(1f, maxWidth / naturalWidth, maxHeight / naturalHeight)
554
+ naturalWidth * scale to naturalHeight * scale
555
+ }
556
+ }
557
+ setMeasuredDimension(measuredWidth.roundToInt(), measuredHeight.roundToInt())
558
+ }
559
+
463
560
  private fun decode(source: String): Bitmap? {
464
561
  if (source.startsWith("data:")) {
465
562
  val bytes = Base64.decode(source.substringAfter(","), Base64.DEFAULT)
@@ -470,6 +567,13 @@ class RemoteImageView(context: Context) : ImageView(context) {
470
567
  }
471
568
 
472
569
  companion object {
570
+ private val loader = Executors.newFixedThreadPool(4)
571
+
572
+ /** Decoded images, an eighth of the app's memory at most: one that comes back on screen shows at once. */
573
+ private val decodedImages = object : LruCache<String, Bitmap>((Runtime.getRuntime().maxMemory() / 8).toInt()) {
574
+ override fun sizeOf(key: String, value: Bitmap) = value.byteCount
575
+ }
576
+
473
577
  val scaleTypes = mapOf(
474
578
  "cover" to ScaleType.CENTER_CROP,
475
579
  "contain" to ScaleType.FIT_CENTER,
@@ -0,0 +1,68 @@
1
+ import UIKit
2
+
3
+ extension NativeNode {
4
+ private static let traitsByRole: [String: UIAccessibilityTraits] = [
5
+ "button": .button,
6
+ "link": .link,
7
+ "heading": .header,
8
+ "img": .image,
9
+ "text": .staticText,
10
+ "switch": .toggleButton,
11
+ "checkbox": .toggleButton,
12
+ ]
13
+
14
+ /// role, alt and aria-*, from the renderer: all of them, whenever one changes.
15
+ func applyAccessibility(_ attributes: [String: Any]) {
16
+ let role = attributes["role"] as? String
17
+ let label = attributes["label"] as? String
18
+ let isHidden = attributes["hidden"] != nil
19
+ let isElement = !isHidden && role != "none" && (role != nil || label != nil || defaultAccessibility.isElement)
20
+
21
+ view.accessibilityElementsHidden = isHidden
22
+ view.isAccessibilityElement = isElement
23
+ view.accessibilityLabel = label
24
+ view.accessibilityHint = attributes["hint"] as? String
25
+ view.accessibilityTraits = traits(role: role, attributes: attributes)
26
+ // A container read as one element says the text inside it, as a <button> does on the web.
27
+ view.accessibilityLabelBlock = isElement && label == nil && !defaultAccessibility.isElement
28
+ ? { [weak view] in view.map { Self.labels(inside: $0).joined(separator: ", ") } }
29
+ : nil
30
+
31
+ if role == "switch" || role == "checkbox" {
32
+ view.accessibilityValue = attributes["checked"] != nil ? "1" : "0"
33
+ }
34
+ }
35
+
36
+ private func traits(role: String?, attributes: [String: Any]) -> UIAccessibilityTraits {
37
+ var traits = defaultAccessibility.traits
38
+ if let role, let roleTraits = Self.traitsByRole[role] { traits.formUnion(roleTraits) }
39
+ if attributes["disabled"] != nil { traits.insert(.notEnabled) }
40
+ if attributes["selected"] != nil { traits.insert(.selected) }
41
+
42
+ return traits
43
+ }
44
+
45
+ private static func labels(inside view: UIView) -> [String] {
46
+ view.subviews.flatMap { subview -> [String] in
47
+ if subview.isHidden || subview.accessibilityElementsHidden { return [] }
48
+ if subview.isAccessibilityElement, let label = subview.accessibilityLabel, !label.isEmpty { return [label] }
49
+
50
+ return labels(inside: subview)
51
+ }
52
+ }
53
+ }
54
+
55
+ /// What a screen reader needs to know about the system, for AccessibilityInfo. Read on the main thread.
56
+ struct AccessibilityStatus {
57
+ var screenReaderEnabled = UIAccessibility.isVoiceOverRunning
58
+ var reduceMotionEnabled = UIAccessibility.isReduceMotionEnabled
59
+
60
+ static let changeNotifications = [
61
+ UIAccessibility.voiceOverStatusDidChangeNotification,
62
+ UIAccessibility.reduceMotionStatusDidChangeNotification,
63
+ ]
64
+
65
+ var dictionary: [String: Bool] {
66
+ ["screenReaderEnabled": screenReaderEnabled, "reduceMotionEnabled": reduceMotionEnabled]
67
+ }
68
+ }
package/ios/Bridge.swift CHANGED
@@ -34,19 +34,19 @@ final class Bridge {
34
34
  private var nextLayoutAnimation: LayoutAnimation?
35
35
  /// Appearance.getColorScheme(): read on the main thread at start, then kept up to date.
36
36
  private var colorScheme = "light"
37
+ /// Kept on the JS queue, for AccessibilityInfo.
38
+ private var accessibilityStatus = AccessibilityStatus()
37
39
 
38
40
  // Only touched on the main thread.
39
41
  var rootView: RootView!
40
42
  private var gestureReportersByNodeId: [Int: GestureReporter] = [:]
41
43
  private let animatedGraph = AnimatedGraph()
42
- // Limitation: Children of a removed node stay in the dictionary; clean up recursively if memory leaks.
43
44
  var nodesById: [Int: NativeNode] = [:]
45
+ /// Views with @layout, and the box they last reported.
46
+ private var reportedLayoutsByNodeId: [Int: CGRect] = [:]
44
47
  /// Modals and screens: their content is laid out as a separate Yoga root.
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).
48
48
  private var contentRootsByNodeId: [Int: ContentRoot] = [:]
49
- /// Read on the main thread at start, for Dimensions.get('window').
49
+ /// For Dimensions.get('window'): the screen's at start, then the root view's, kept on the JS queue.
50
50
  private var windowSize: CGSize = .zero
51
51
  /// The bundle running now, for the error overlay's Reload.
52
52
  private var bundle = Data()
@@ -60,6 +60,7 @@ final class Bridge {
60
60
  func start(rootView: RootView) {
61
61
  self.rootView = rootView
62
62
  rootView.onLayoutSubviews = { [unowned self] in layout() }
63
+ NativeNode.onLayoutCalculated = { [unowned self] in reportLayoutChanges() }
63
64
  let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene
64
65
  windowSize = windowScene?.screen.bounds.size ?? .zero
65
66
  colorScheme = Self.colorScheme(of: windowScene?.traitCollection ?? rootView.traitCollection)
@@ -69,6 +70,18 @@ final class Bridge {
69
70
  [unowned self] (rootView: RootView, _: UITraitCollection) in
70
71
  colorSchemeDidChange(to: Self.colorScheme(of: rootView.traitCollection))
71
72
  }
73
+ _ = rootView.registerForTraitChanges([UITraitPreferredContentSizeCategory.self]) {
74
+ [unowned self] (rootView: RootView, _: UITraitCollection) in
75
+ nodesById.values.forEach { $0.updateFont() }
76
+ rootView.setNeedsLayout()
77
+ }
78
+ }
79
+
80
+ for name in AccessibilityStatus.changeNotifications {
81
+ NotificationCenter.default.addObserver(forName: name, object: nil, queue: .main) { [unowned self] _ in
82
+ let nextStatus = AccessibilityStatus()
83
+ evaluate { [unowned self] in accessibilityStatus = nextStatus }
84
+ }
72
85
  }
73
86
 
74
87
  NotificationCenter.default.addObserver(forName: Self.openURLNotification, object: nil, queue: .main) {
@@ -131,6 +144,7 @@ final class Bridge {
131
144
 
132
145
  func layout() {
133
146
  nodesById[0]?.calculateLayout(width: rootView.bounds.width, height: rootView.bounds.height)
147
+ windowSizeDidChange(to: rootView.bounds.size)
134
148
 
135
149
  for contentRoot in contentRootsByNodeId.values {
136
150
  (contentRoot as? ModalController)?.dismissIfDetached()
@@ -161,6 +175,18 @@ final class Bridge {
161
175
  }
162
176
  }
163
177
 
178
+ /// Rotation and split view resize the root view.
179
+ private func windowSizeDidChange(to nextWindowSize: CGSize) {
180
+ guard nextWindowSize != .zero else { return }
181
+
182
+ evaluate { [unowned self] in
183
+ guard nextWindowSize != windowSize else { return }
184
+
185
+ windowSize = nextWindowSize
186
+ runtime?.call("__windowSizeChanged", arguments: [["width": windowSize.width, "height": windowSize.height]])
187
+ }
188
+ }
189
+
164
190
  /// Queued on the JS queue, so a URL that opens the app arrives after the bundle has run.
165
191
  private func openURL(_ url: URL) {
166
192
  evaluate { [unowned self] in
@@ -224,13 +250,19 @@ final class Bridge {
224
250
  reportError(message: string(arguments[0]), details: string(arguments[1]))
225
251
  }
226
252
 
227
- // Limitation: The size at launch; report rotation and split view changes if the app supports them.
228
253
  defineGetter("windowSize") { [unowned self] _ in
229
254
  ["width": windowSize.width, "height": windowSize.height]
230
255
  }
231
256
 
232
257
  defineGetter("platform") { _ in "ios" }
233
258
 
259
+ defineGetter("accessibilityInfo") { [unowned self] _ in accessibilityStatus.dictionary }
260
+
261
+ define("announce") { arguments in
262
+ let message = string(arguments[0])
263
+ DispatchQueue.main.async { UIAccessibility.post(notification: .announcement, argument: message) }
264
+ }
265
+
234
266
  // Prefixed, so a plugin can't replace nativue's own functions.
235
267
  for (name, function) in pluginRegistry.functions {
236
268
  defineGetter("plugin:\(name)", function)
@@ -267,7 +299,8 @@ final class Bridge {
267
299
 
268
300
  define("remove") { [unowned self] arguments in
269
301
  let id = int(arguments[0])
270
- enqueue { [unowned self] in removeNode(id: id) }
302
+ let subtreeIds = (arguments[1] as? [Any] ?? []).map(int)
303
+ enqueue { [unowned self] in removeNode(id: id, subtreeIds: subtreeIds) }
271
304
  }
272
305
 
273
306
  define("setText") { [unowned self] arguments in
@@ -351,6 +384,7 @@ final class Bridge {
351
384
  contentRootsByNodeId.values.forEach { ($0 as? ModalController)?.setVisible(false) }
352
385
  contentRootsByNodeId = [:]
353
386
  gestureReportersByNodeId = [:] // node ids start over
387
+ reportedLayoutsByNodeId = [:]
354
388
  animatedGraph.reset()
355
389
  animatedGraph.onAnimationEnd = { [unowned self] animationId, finished in
356
390
  evaluate { [unowned self] in
@@ -377,16 +411,49 @@ final class Bridge {
377
411
  }
378
412
 
379
413
  /// A screen leaves through its stack, so the navigation controller animates it out.
380
- private func removeNode(id: Int) {
381
- guard let node = nodesById.removeValue(forKey: id) else { return }
414
+ private func removeNode(id: Int, subtreeIds: [Int]) {
415
+ guard let node = nodesById[id] else { return }
382
416
 
383
- guard let screen = screenController(id) else {
417
+ if let screen = screenController(id) {
418
+ screen.container?.removeScreen(screen)
419
+ } else {
384
420
  node.removeFromParent()
385
- return
386
421
  }
422
+ subtreeIds.forEach(forgetNode)
423
+ }
387
424
 
425
+ /// Its view left the tree: what refers to it by id goes too, and a modal or sheet inside closes.
426
+ private func forgetNode(id: Int) {
427
+ let node = nodesById.removeValue(forKey: id)
428
+ (node?.view as? ScreenStackView)?.dismissPresentedScreens()
429
+ modalController(id)?.dismissIfDetached()
388
430
  contentRootsByNodeId[id] = nil
389
- screen.container?.removeScreen(screen)
431
+ gestureReportersByNodeId[id] = nil
432
+ reportedLayoutsByNodeId[id] = nil
433
+ }
434
+
435
+ /// @layout fires for the views whose box changed: { x, y, width, height }, in points, in its parent.
436
+ /// All of a layout pass's changes go in one call, so JS re-renders once for them, not once per view.
437
+ private func reportLayoutChanges() {
438
+ var changedLayouts: [[String: Any]] = []
439
+
440
+ for (id, reportedLayout) in reportedLayoutsByNodeId {
441
+ guard let yogaNode = nodesById[id]?.yogaNode else { continue }
442
+
443
+ let layout = CGRect(
444
+ x: CGFloat(YGNodeLayoutGetLeft(yogaNode)),
445
+ y: CGFloat(YGNodeLayoutGetTop(yogaNode)),
446
+ width: CGFloat(YGNodeLayoutGetWidth(yogaNode)),
447
+ height: CGFloat(YGNodeLayoutGetHeight(yogaNode))
448
+ )
449
+ guard !layout.width.isNaN, layout != reportedLayout else { continue }
450
+
451
+ reportedLayoutsByNodeId[id] = layout
452
+ changedLayouts.append(["id": id, "x": layout.minX, "y": layout.minY, "width": layout.width, "height": layout.height])
453
+ }
454
+ guard !changedLayouts.isEmpty else { return }
455
+
456
+ evaluate { [unowned self] in runtime?.call("__layoutsChanged", arguments: [changedLayouts]) }
390
457
  }
391
458
 
392
459
  private func modalController(_ id: Int) -> ModalController? {
@@ -397,7 +464,19 @@ final class Bridge {
397
464
  contentRootsByNodeId[id] as? ScreenController
398
465
  }
399
466
 
467
+ /// Text views start at the platform's size, scaled to the system's text size like styled ones.
400
468
  private func makeNode(type: String, id: Int) -> NativeNode {
469
+ let node = makeUnstyledNode(type: type, id: id)
470
+ if let button = node.view as? UIButton, let systemFont = button.titleLabel?.font {
471
+ node.defaultFontSize = systemFont.pointSize
472
+ node.fontSize = systemFont.pointSize
473
+ }
474
+ node.updateFont()
475
+
476
+ return node
477
+ }
478
+
479
+ private func makeUnstyledNode(type: String, id: Int) -> NativeNode {
401
480
  switch type {
402
481
  case "Text":
403
482
  let label = UILabel()
@@ -413,7 +492,13 @@ final class Bridge {
413
492
  return NativeNode(view: VueScrollView(), measuresContent: false)
414
493
 
415
494
  case "Image":
416
- return NativeNode(view: ImageView(frame: .zero), measuresContent: false)
495
+ let imageView = ImageView(frame: .zero)
496
+ let node = NativeNode(view: imageView, measuresContent: true)
497
+ imageView.onImageChange = { [unowned self, weak node] in
498
+ node?.markContentChanged()
499
+ rootView.setNeedsLayout()
500
+ }
501
+ return node
417
502
 
418
503
  case "SwipeableView":
419
504
  return NativeNode(view: SwipeableView(frame: .zero), measuresContent: false)
@@ -756,6 +841,9 @@ final class Bridge {
756
841
  case "disabled":
757
842
  (node.view as? UIControl)?.isEnabled = !isTruthyAttribute(value)
758
843
 
844
+ case "accessibility":
845
+ node.applyAccessibility(value as? [String: Any] ?? [:])
846
+
759
847
  case "animating":
760
848
  guard let indicator = node.view as? UIActivityIndicatorView else { break }
761
849
  if isTruthyAttribute(value) { indicator.startAnimating() } else { indicator.stopAnimating() }
@@ -814,6 +902,11 @@ final class Bridge {
814
902
  case "resizeMode":
815
903
  node.view.contentMode = ImageView.resizeModes[value as? String ?? ""] ?? .scaleAspectFill
816
904
 
905
+ case "onLayout":
906
+ // A new handler on every render re-registers: only a first one waits for a report.
907
+ if !isTruthyAttribute(value) { reportedLayoutsByNodeId[id] = nil }
908
+ else if reportedLayoutsByNodeId[id] == nil { reportedLayoutsByNodeId[id] = .null }
909
+
817
910
  case "onScroll":
818
911
  (node.view as? VueScrollView)?.onScroll = isTruthyAttribute(value) ? reportScroll(toNodeId: id) : nil
819
912
 
@@ -1,9 +1,9 @@
1
1
  import UIKit
2
+ import yoga
2
3
 
3
4
  /// Image view behind <Image>. Loads `source` (an http(s) or data: url) through URLSession, which also
4
- /// gives HTTP caching through URLCache.
5
- // Limitation: No decoded-image cache and no intrinsic size; add an NSCache / measure function if lists of
6
- // images stutter or sizing by hand gets annoying.
5
+ /// gives HTTP caching through URLCache; decoded images are kept in memory, so one that comes back on
6
+ /// screen (a list row) shows at once.
7
7
  final class ImageView: UIImageView {
8
8
  static let resizeModes: [String: UIView.ContentMode] = [
9
9
  "cover": .scaleAspectFill,
@@ -12,6 +12,17 @@ final class ImageView: UIImageView {
12
12
  "center": .center,
13
13
  ]
14
14
 
15
+ /// NSCache also empties itself when memory runs low.
16
+ private static let decodedImages: NSCache<NSString, UIImage> = {
17
+ let cache = NSCache<NSString, UIImage>()
18
+ cache.totalCostLimit = 64 * 1024 * 1024
19
+
20
+ return cache
21
+ }()
22
+
23
+ /// The image changed, and with it the size the view measures.
24
+ var onImageChange: (() -> Void)?
25
+
15
26
  private var loadingTask: Task<Void, Never>?
16
27
 
17
28
  override init(frame: CGRect) {
@@ -25,19 +36,57 @@ final class ImageView: UIImageView {
25
36
  fatalError("init(coder:) is not supported")
26
37
  }
27
38
 
28
- func load(_ urlString: String?) {
39
+ func load(_ source: String?) {
29
40
  loadingTask?.cancel()
30
- image = nil
31
41
 
32
- guard let urlString, let url = URL(string: urlString) else { return }
42
+ guard let source, let url = URL(string: source) else { return show(nil) }
43
+ if let cachedImage = Self.decodedImages.object(forKey: source as NSString) { return show(cachedImage) }
33
44
 
45
+ show(nil)
34
46
  loadingTask = Task { [weak self] in
35
47
  guard
36
48
  let (data, _) = try? await URLSession.shared.data(from: url),
49
+ let image = await UIImage(data: data)?.byPreparingForDisplay(), // decoded off the main thread
37
50
  !Task.isCancelled
38
51
  else { return }
39
52
 
40
- self?.image = UIImage(data: data)
53
+ Self.decodedImages.setObject(image, forKey: source as NSString, cost: Self.byteCount(of: image))
54
+ self?.show(image)
55
+ }
56
+ }
57
+
58
+ /// Without a width or height, the image takes its own size, a pixel per point; given one of them, the
59
+ /// other follows its aspect ratio, as on the web.
60
+ func measuredSize(width: Float, widthMode: YGMeasureMode, height: Float, heightMode: YGMeasureMode) -> YGSize {
61
+ let naturalWidth = Float(image?.size.width ?? 0)
62
+ let naturalHeight = Float(image?.size.height ?? 0)
63
+ let maxWidth = widthMode == .undefined ? .infinity : width
64
+ let maxHeight = heightMode == .undefined ? .infinity : height
65
+
66
+ if widthMode == .exactly && heightMode == .exactly { return YGSize(width: width, height: height) }
67
+ if naturalWidth == 0 || naturalHeight == 0 {
68
+ return YGSize(width: widthMode == .exactly ? width : 0, height: heightMode == .exactly ? height : 0)
41
69
  }
70
+
71
+ let aspectRatio = naturalWidth / naturalHeight
72
+ if widthMode == .exactly { return YGSize(width: width, height: min(width / aspectRatio, maxHeight)) }
73
+ if heightMode == .exactly { return YGSize(width: min(height * aspectRatio, maxWidth), height: height) }
74
+
75
+ let scale = min(1, maxWidth / naturalWidth, maxHeight / naturalHeight)
76
+
77
+ return YGSize(width: naturalWidth * scale, height: naturalHeight * scale)
78
+ }
79
+
80
+ private func show(_ nextImage: UIImage?) {
81
+ guard nextImage !== image else { return }
82
+
83
+ image = nextImage
84
+ onImageChange?()
85
+ }
86
+
87
+ private static func byteCount(of image: UIImage) -> Int {
88
+ guard let cgImage = image.cgImage else { return 0 }
89
+
90
+ return cgImage.bytesPerRow * cgImage.height
42
91
  }
43
92
  }
@@ -17,6 +17,11 @@ final class NativeNode {
17
17
  /// Where children go when it isn't this node (a <Modal>'s children live in the presented controller).
18
18
  var contentNode: NativeNode?
19
19
 
20
+ /// The view's own, before role and aria-* change them: read the first time they're applied.
21
+ lazy var defaultAccessibility = (isElement: view.isAccessibilityElement, traits: view.accessibilityTraits)
22
+
23
+ /// The view's own size, which a removed fontSize goes back to.
24
+ var defaultFontSize: CGFloat = UIFont.labelFontSize
20
25
  var fontSize: CGFloat = UIFont.labelFontSize
21
26
  var fontWeight: UIFont.Weight = .regular
22
27
 
@@ -75,9 +80,13 @@ final class NativeNode {
75
80
  }
76
81
 
77
82
  /// Computes the layout for this subtree and applies the resulting frames to the views.
83
+ /// After every layout pass, of the root or of a screen's or modal's content: for @layout.
84
+ static var onLayoutCalculated: (() -> Void)?
85
+
78
86
  func calculateLayout(width: CGFloat, height: CGFloat) {
79
87
  YGNodeCalculateLayout(yogaNode, Float(width), Float(height), .LTR)
80
88
  Self.applyFrames(of: yogaNode)
89
+ Self.onLayoutCalculated?()
81
90
  }
82
91
 
83
92
  /// A view inserted during a layout animation would grow from the corner: it fades in where it lands.
@@ -177,6 +186,10 @@ private func measureView(
177
186
  let maxHeight = heightMode == .undefined ? CGFloat.greatestFiniteMagnitude : CGFloat(height)
178
187
 
179
188
  let view = NativeNode.view(of: yogaNode!)
189
+ if let imageView = view as? ImageView {
190
+ return imageView.measuredSize(width: width, widthMode: widthMode, height: height, heightMode: heightMode)
191
+ }
192
+
180
193
  let singleLineLabelSize = (view as? UILabel).flatMap { singleLineSize(of: $0, maxWidth: maxWidth) }
181
194
  let fittingSize = singleLineLabelSize ?? view.sizeThatFits(CGSize(width: maxWidth, height: maxHeight))
182
195
 
@@ -54,6 +54,17 @@ final class PressableView: UIControl {
54
54
  .contains { $0 is UIControl || $0 is UIScrollView || !($0.gestureRecognizers ?? []).isEmpty }
55
55
  }
56
56
 
57
+ /// VoiceOver's double tap: a press, even when something interactive sits under the activation point.
58
+ override func accessibilityActivate() -> Bool {
59
+ guard isEnabled else { return false }
60
+
61
+ onEvent?("pressin")
62
+ onEvent?("pressout")
63
+ onEvent?("press")
64
+
65
+ return true
66
+ }
67
+
57
68
  @objc private func handleLongPress(_ recognizer: UILongPressGestureRecognizer) {
58
69
  guard recognizer.state == .began, isEnabled else { return }
59
70
 
@@ -170,6 +170,13 @@ final class ScreenStackView: UIView, ScreenContainer, UINavigationControllerDele
170
170
  }
171
171
  }
172
172
 
173
+ /// The stack left the tree: the screens it presented close with it.
174
+ func dismissPresentedScreens() {
175
+ guard !modalNavigationControllers.isEmpty else { return }
176
+
177
+ dismissModals(from: 0)
178
+ }
179
+
173
180
  private func dismissModals(from index: Int) {
174
181
  let presenter = modalNavigationControllers[index].presentingViewController
175
182
  modalNavigationControllers.removeSubrange(index...)