@craft-native/ios 0.0.262 → 0.0.272

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@craft-native/ios",
3
- "version": "0.0.262",
3
+ "version": "0.0.272",
4
4
  "homepage": "https://github.com/craft-native/craft/tree/main/packages/ios#readme",
5
5
  "repository": {
6
6
  "type": "git",
@@ -797,10 +797,21 @@ final class CraftChrome: ObservableObject {
797
797
  tabAccessory = next
798
798
  }
799
799
 
800
- /// A retained or prepared screen cannot clear another screen's chrome.
801
- func clearTabAccessory(ownedBy owner: AnyObject) {
800
+ /// A screen going away gives its accessory up without taking it off the
801
+ /// bar (a retained or prepared screen cannot clear another's): the screen coming in shows it until it says what it wants. Taken
802
+ /// off at once, the pill stretched across the bar and back while the
803
+ /// next screen (Messages, opened from the accessory; a tab opened for the
804
+ /// first time) started up and set the same accessory again.
805
+ func releaseTabAccessory(ownedBy owner: AnyObject) {
802
806
  guard tabAccessoryOwner === owner else { return }
803
- updateTabAccessory(nil)
807
+ tabAccessoryOwner = nil
808
+ }
809
+
810
+ /// Takes off an accessory nobody claims any more: the screen now showing
811
+ /// drew without asking for one, or is a page that never does.
812
+ func clearUnclaimedTabAccessory() {
813
+ guard tabAccessoryOwner == nil, tabAccessory != nil else { return }
814
+ tabAccessory = nil
804
815
  }
805
816
 
806
817
  func setHiddenByScreen(_ hidden: Bool) {
@@ -6347,6 +6358,7 @@ struct CraftWebView: UIViewRepresentable {
6347
6358
 
6348
6359
  SecItemDelete(query as CFDictionary)
6349
6360
  let status = SecItemAdd(query as CFDictionary, nil)
6361
+ CraftKeychain.forget(account: key)
6350
6362
  return status == errSecSuccess
6351
6363
  }
6352
6364
 
@@ -6373,12 +6385,14 @@ struct CraftWebView: UIViewRepresentable {
6373
6385
  kSecAttrAccount as String: key
6374
6386
  ]
6375
6387
  let status = SecItemDelete(query as CFDictionary)
6388
+ CraftKeychain.forget(account: key)
6376
6389
  return status == errSecSuccess || status == errSecItemNotFound
6377
6390
  }
6378
6391
 
6379
6392
  private func secureClear() -> Bool {
6380
6393
  let query: [String: Any] = [kSecClass as String: kSecClassGenericPassword]
6381
6394
  let status = SecItemDelete(query as CFDictionary)
6395
+ CraftKeychain.forget(account: nil)
6382
6396
  return status == errSecSuccess || status == errSecItemNotFound
6383
6397
  }
6384
6398
 
@@ -8259,6 +8273,7 @@ struct CraftWebView: UIViewRepresentable {
8259
8273
  SecItemDelete(query as CFDictionary)
8260
8274
 
8261
8275
  let status = SecItemAdd(query as CFDictionary, nil)
8276
+ CraftKeychain.forget(account: key)
8262
8277
  if status == errSecSuccess {
8263
8278
  resolveCallback(callbackId, result: ["success": true, "key": key])
8264
8279
  } else {
@@ -8301,6 +8316,7 @@ struct CraftWebView: UIViewRepresentable {
8301
8316
  }
8302
8317
 
8303
8318
  let status = SecItemDelete(query as CFDictionary)
8319
+ CraftKeychain.forget(account: key)
8304
8320
  if status == errSecSuccess || status == errSecItemNotFound {
8305
8321
  resolveCallback(callbackId, result: ["success": true, "key": key])
8306
8322
  } else {
@@ -240,8 +240,10 @@ enum CraftHybridKeychain {
240
240
  static let nativeService = "dev.craft.native.secure"
241
241
 
242
242
  static func set(_ key: String, value: String?) {
243
+ defer { CraftKeychain.forget(account: key) }
243
244
  // Every item for the account, whatever its service.
244
245
  SecItemDelete([kSecClass as String: kSecClassGenericPassword, kSecAttrAccount as String: key] as CFDictionary)
246
+ CraftKeychain.forget(account: key)
245
247
  guard let value else { return }
246
248
  for service in [nil, nativeService] {
247
249
  var add: [String: Any] = [
@@ -2034,6 +2036,8 @@ final class CraftHybridController: UIViewController, UINavigationControllerDeleg
2034
2036
  func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
2035
2037
  lastNavigation = CACurrentMediaTime()
2036
2038
  CraftFramePacing.shared.end("navigation")
2039
+ // A page shows no native accessory; one a screen gave up is taken off.
2040
+ if viewController is CraftHybridWebSlot { CraftChrome.shared.clearUnclaimedTabAccessory() }
2037
2041
  let key = ObjectIdentifier(navigationController)
2038
2042
  let before = shownStacks[key] ?? []
2039
2043
  let now = navigationController.viewControllers
@@ -2301,6 +2305,22 @@ final class CraftFramePacing: NSObject {
2301
2305
  return result
2302
2306
  }
2303
2307
 
2308
+ /// One piece of the screens' JavaScript (CraftNativeScriptThread): how
2309
+ /// long it waited behind other screens' work, and how long it ran. The
2310
+ /// screens share one serial script thread, so a screen in front can sit
2311
+ /// behind hidden tabs reloading; `waited` is where that shows.
2312
+ func scriptWork(_ name: String, waited: CFTimeInterval, ran: CFTimeInterval) {
2313
+ guard enabled else { return }
2314
+ write(String(format: "script %@ waited=%.1fms ran=%.1fms", name, waited * 1000, ran * 1000))
2315
+ }
2316
+
2317
+ /// A capability a screen asked for (a request, the keychain), from the
2318
+ /// ask to the answer. Logged from 4ms, as script work is.
2319
+ func capability(_ name: String, took: CFTimeInterval) {
2320
+ guard enabled, took >= 0.004 else { return }
2321
+ write(String(format: "capability %@ took=%.1fms", name, took * 1000))
2322
+ }
2323
+
2304
2324
  /// Each line to the log and to `Library/Caches/craft-frame-pacing.log`
2305
2325
  /// in the app's container, which a test run reads back whole (a
2306
2326
  /// simulator's unified log can drop an app's lines under load). Written
@@ -219,11 +219,13 @@ enum CraftNativeActions {
219
219
  }
220
220
  // A write that moves the sign-in token is the account's change:
221
221
  // every screen hears it (CraftSession). Reads skip the check.
222
- if ["set", "remove", "delete", "clear"].contains(method) {
223
- sync = CraftSession.observe(key: method == "clear" ? nil : args.first as? String, config: config, write)
224
- } else {
225
- sync = write()
222
+ // Off the main thread, in order (CraftKeychain.queue).
223
+ let isWrite = ["set", "remove", "delete", "clear"].contains(method)
224
+ CraftKeychain.queue.async {
225
+ let result = isWrite ? CraftSession.observe(key: method == "clear" ? nil : args.first as? String, config: config, write) : write()
226
+ complete(requestToken, result, completion)
226
227
  }
228
+ return
227
229
  case ("Biometrics", "isAvailable"):
228
230
  sync = config.enableBiometric ? .success(biometricContext().canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil)) : failure("CAPABILITY_DISABLED", "Biometric authentication is disabled")
229
231
  case ("Biometrics", "getBiometricType"):
@@ -957,6 +959,7 @@ enum CraftNativeActions {
957
959
  if method == "clear" {
958
960
  let query: [String: Any] = [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service]
959
961
  let status = SecItemDelete(query as CFDictionary)
962
+ CraftKeychain.forget(account: nil)
960
963
  guard status == errSecSuccess || status == errSecItemNotFound else {
961
964
  return failure("SECURE_STORAGE_ERROR", "Secure storage could not be cleared")
962
965
  }
@@ -977,24 +980,38 @@ enum CraftNativeActions {
977
980
  query[kSecValueData as String] = Data(value.utf8)
978
981
  query[kSecAttrAccessible as String] = kSecAttrAccessibleWhenUnlockedThisDeviceOnly
979
982
  let removed = SecItemDelete(base as CFDictionary)
983
+ CraftKeychain.forget(account: key)
980
984
  guard removed == errSecSuccess || removed == errSecItemNotFound else {
981
985
  return failure("SECURE_STORAGE_ERROR", "Secure storage could not be replaced (\(removed))")
982
986
  }
983
987
  let status = SecItemAdd(query as CFDictionary, nil)
988
+ CraftKeychain.forget(account: key)
984
989
  return status == errSecSuccess ? .success(true) : failure("SECURE_STORAGE_ERROR", "Secure storage could not be written (\(status))")
985
990
  case "get":
986
- var query = base
987
- query[kSecReturnData as String] = true
988
- query[kSecMatchLimit as String] = kSecMatchLimitOne
989
- var result: AnyObject?
990
- let status = SecItemCopyMatching(query as CFDictionary, &result)
991
- if status == errSecItemNotFound { return .success(NSNull()) }
992
- guard status == errSecSuccess, let data = result as? Data else {
991
+ // A failed read is not remembered: it is answered as a failure,
992
+ // and the next read asks the Keychain again.
993
+ var failed = false
994
+ let value = CraftKeychain.value(account: key, service: service) { () -> String? in
995
+ var query = base
996
+ query[kSecReturnData as String] = true
997
+ query[kSecMatchLimit as String] = kSecMatchLimitOne
998
+ var result: AnyObject?
999
+ let status = SecItemCopyMatching(query as CFDictionary, &result)
1000
+ if status == errSecItemNotFound { return nil }
1001
+ guard status == errSecSuccess, let data = result as? Data else {
1002
+ failed = true
1003
+ return nil
1004
+ }
1005
+ return String(decoding: data, as: UTF8.self)
1006
+ }
1007
+ if failed {
1008
+ CraftKeychain.forget(account: key)
993
1009
  return failure("SECURE_STORAGE_ERROR", "Secure storage could not be read")
994
1010
  }
995
- return .success(String(decoding: data, as: UTF8.self))
1011
+ return .success(value.map { $0 as Any } ?? NSNull())
996
1012
  case "remove":
997
1013
  let status = SecItemDelete(base as CFDictionary)
1014
+ CraftKeychain.forget(account: key)
998
1015
  return status == errSecSuccess || status == errSecItemNotFound ? .success(true) : failure("SECURE_STORAGE_ERROR", "Secure storage could not be removed")
999
1016
  default:
1000
1017
  return failure("UNKNOWN_ACTION", "Unsupported SecureStorage method")
@@ -1500,15 +1517,85 @@ extension CraftNativeActions {
1500
1517
  /// `secureStore` writes it. Nil when there is none.
1501
1518
  static func webSecureValue(forKey key: String) -> String? {
1502
1519
  guard let key = validKey(key) else { return nil }
1503
- let query: [String: Any] = [
1504
- kSecClass as String: kSecClassGenericPassword,
1505
- kSecAttrAccount as String: key,
1506
- kSecReturnData as String: true,
1507
- kSecMatchLimit as String: kSecMatchLimitOne,
1508
- ]
1509
- var result: AnyObject?
1510
- guard SecItemCopyMatching(query as CFDictionary, &result) == errSecSuccess, let data = result as? Data else { return nil }
1511
- return String(data: data, encoding: .utf8)
1520
+ return CraftKeychain.value(account: key, service: nil) {
1521
+ let query: [String: Any] = [
1522
+ kSecClass as String: kSecClassGenericPassword,
1523
+ kSecAttrAccount as String: key,
1524
+ kSecReturnData as String: true,
1525
+ kSecMatchLimit as String: kSecMatchLimitOne,
1526
+ ]
1527
+ var result: AnyObject?
1528
+ guard SecItemCopyMatching(query as CFDictionary, &result) == errSecSuccess, let data = result as? Data else { return nil }
1529
+ return String(data: data, encoding: .utf8)
1530
+ }
1531
+ }
1532
+ }
1533
+
1534
+ /// The app's own Keychain items, read once and then remembered.
1535
+ ///
1536
+ /// A Keychain read is `SecItemCopyMatching`, which took 100-900ms a read on a
1537
+ /// simulator and is not free on a phone, and every screen reads the sign-in
1538
+ /// token and the account beside it when it opens. They ran on the main
1539
+ /// thread, one after another, so a sign-in that made each open screen check
1540
+ /// the account again held the interface for seconds.
1541
+ ///
1542
+ /// This process is the only writer of these items, through `secureStorage`,
1543
+ /// `CraftHybridKeychain` and the web bridge's secure storage, and each of
1544
+ /// them forgets what it changed. An item another process could write (a
1545
+ /// shared access group, an extension) is not remembered, and coming back to
1546
+ /// the foreground forgets everything, so a value written while the app was
1547
+ /// away is read fresh.
1548
+ enum CraftKeychain {
1549
+ /// Where native screens' secure storage runs: off the main thread, one
1550
+ /// call at a time, so a write is always seen by the read after it.
1551
+ static let queue = DispatchQueue(label: "craft.keychain", qos: .userInitiated)
1552
+ private static let lock = NSLock()
1553
+ private static var values: [String: String?] = [:]
1554
+ /// Moves on every forget, so a read that raced a write is not kept.
1555
+ private static var generation = 0
1556
+ private static var observing: NSObjectProtocol?
1557
+
1558
+ private static func cacheKey(_ account: String, _ service: String?) -> String {
1559
+ "\(service ?? "*")\u{1F}\(account)"
1560
+ }
1561
+
1562
+ /// `account`'s value under `service` (nil: whichever service holds it),
1563
+ /// from memory when it was read before, else from `read`.
1564
+ static func value(account: String, service: String?, read: () -> String?) -> String? {
1565
+ let key = cacheKey(account, service)
1566
+ lock.lock()
1567
+ if observing == nil { observeForeground() }
1568
+ if let known = values[key] {
1569
+ lock.unlock()
1570
+ return known
1571
+ }
1572
+ let started = generation
1573
+ lock.unlock()
1574
+ let value = read()
1575
+ lock.lock()
1576
+ if generation == started { values[key] = .some(value) }
1577
+ lock.unlock()
1578
+ return value
1579
+ }
1580
+
1581
+ /// Drop what is remembered for `account`, under every service; nil drops all.
1582
+ static func forget(account: String?) {
1583
+ lock.lock()
1584
+ generation += 1
1585
+ if let account {
1586
+ let suffix = "\u{1F}\(account)"
1587
+ values = values.filter { !$0.key.hasSuffix(suffix) }
1588
+ } else {
1589
+ values.removeAll()
1590
+ }
1591
+ lock.unlock()
1592
+ }
1593
+
1594
+ /// Called with `lock` held.
1595
+ private static func observeForeground() {
1596
+ observing = NotificationCenter.default.addObserver(forName: UIApplication.willEnterForegroundNotification, object: nil, queue: nil) { _ in
1597
+ forget(account: nil)
1598
+ }
1512
1599
  }
1513
1600
  }
1514
1601
 
@@ -49,6 +49,8 @@ final class CraftNativeFlatList: UICollectionView, UICollectionViewDelegateFlowL
49
49
 
50
50
  private(set) var representedIdentity: String?
51
51
  private(set) var hostedView: UIView?
52
+ /// Top, bottom, leading and trailing: the row's own margins inset it.
53
+ private var hostedConstraints: [NSLayoutConstraint] = []
52
54
  var onRecycle: ((String) -> Void)?
53
55
  override func prepareForReuse() {
54
56
  super.prepareForReuse()
@@ -74,7 +76,7 @@ final class CraftNativeFlatList: UICollectionView, UICollectionViewDelegateFlowL
74
76
  representedIdentity = identity
75
77
  // The same view, already here. A view that left for another cell
76
78
  // and is asked for again is put back below.
77
- guard hostedView !== view || view.superview !== contentView else { return }
79
+ guard hostedView !== view || view.superview !== contentView else { return applyHostedMargins() }
78
80
  // Only a view still in this cell is taken out of it: one that has
79
81
  // since moved to another cell is that cell's now, and pulling it
80
82
  // from there blanked a row on screen.
@@ -82,12 +84,27 @@ final class CraftNativeFlatList: UICollectionView, UICollectionViewDelegateFlowL
82
84
  hostedView = view
83
85
  view.translatesAutoresizingMaskIntoConstraints = false
84
86
  contentView.addSubview(view)
85
- NSLayoutConstraint.activate([
87
+ hostedConstraints = [
86
88
  view.topAnchor.constraint(equalTo: contentView.topAnchor),
87
- view.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
89
+ contentView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
88
90
  view.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
89
- view.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
90
- ])
91
+ contentView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
92
+ ]
93
+ applyHostedMargins()
94
+ NSLayoutConstraint.activate(hostedConstraints)
95
+ }
96
+
97
+ /// A row's margins (`mx-4` on a grouped row) inset it in its cell, as
98
+ /// a column inset it: pinned edge to edge, HQ's Discover results ran
99
+ /// to the screen's sides. Read again on every pass, since a style
100
+ /// update changes the row in place.
101
+ private func applyHostedMargins() {
102
+ guard let view = hostedView, view.superview === contentView, hostedConstraints.count == 4 else { return }
103
+ let margins = view.craftLayoutMargins
104
+ let constants = [margins.top, margins.bottom, margins.left, margins.right]
105
+ for (constraint, constant) in zip(hostedConstraints, constants) where constraint.constant != constant {
106
+ constraint.constant = constant
107
+ }
91
108
  }
92
109
 
93
110
  func releaseHostedView() {
@@ -106,6 +123,8 @@ final class CraftNativeFlatList: UICollectionView, UICollectionViewDelegateFlowL
106
123
  _ layoutAttributes: UICollectionViewLayoutAttributes
107
124
  ) -> UICollectionViewLayoutAttributes {
108
125
  guard let hostedView = hostedView else { return layoutAttributes }
126
+ applyHostedMargins()
127
+ let margins = hostedView.craftLayoutMargins
109
128
  let attributes = layoutAttributes.copy() as! UICollectionViewLayoutAttributes
110
129
  // A cell has no collectionView property; the list is its nearest
111
130
  // collection view ancestor.
@@ -121,24 +140,26 @@ final class CraftNativeFlatList: UICollectionView, UICollectionViewDelegateFlowL
121
140
  let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout,
122
141
  flowLayout.scrollDirection == .horizontal {
123
142
  let height = fittingExtent ?? layoutAttributes.size.height
143
+ let inner = max(0, height - margins.top - margins.bottom)
124
144
  let measured = CraftNativeFlexLayout.measure(
125
145
  hostedView,
126
146
  width: nil,
127
- height: height,
147
+ height: inner,
128
148
  maxWidth: CraftNativeFlexLayout.unbounded,
129
- maxHeight: height
149
+ maxHeight: inner
130
150
  )
131
- attributes.size = CGSize(width: max(1, ceil(measured.width)), height: max(1, height))
151
+ attributes.size = CGSize(width: max(1, ceil(measured.width + margins.left + margins.right)), height: max(1, height))
132
152
  } else {
133
153
  let width = fittingExtent ?? layoutAttributes.size.width
154
+ let inner = max(0, width - margins.left - margins.right)
134
155
  let measured = CraftNativeFlexLayout.measure(
135
156
  hostedView,
136
- width: width,
157
+ width: inner,
137
158
  height: nil,
138
- maxWidth: width,
159
+ maxWidth: inner,
139
160
  maxHeight: CraftNativeFlexLayout.unbounded
140
161
  )
141
- attributes.size = CGSize(width: max(1, width), height: max(1, ceil(measured.height)))
162
+ attributes.size = CGSize(width: max(1, width), height: max(1, ceil(measured.height + margins.top + margins.bottom)))
142
163
  }
143
164
  return attributes
144
165
  }
@@ -184,6 +205,14 @@ final class CraftNativeFlatList: UICollectionView, UICollectionViewDelegateFlowL
184
205
  private var keyboardShouldPersistTaps = "never"
185
206
  private var scrollTargetKey: String?
186
207
  private var pendingScrollTarget: (id: String, animated: Bool, attempts: Int)?
208
+ /// A target that ends at the list's end, held to the true bottom while
209
+ /// the rows near it measure themselves. Rows self-size from a 44pt
210
+ /// estimate, so an offset worked out before they are measured stops short
211
+ /// of tall rows (multi-paragraph replies, cards). Cleared by a drag.
212
+ private var endSettlePasses: Int?
213
+ private var endSettleGeneration = 0
214
+ private var isAnimatingToEnd = false
215
+ private var isMeasuringEnd = false
187
216
 
188
217
  init() {
189
218
  let layout = CraftNativeFlatListLayout()
@@ -339,6 +368,7 @@ final class CraftNativeFlatList: UICollectionView, UICollectionViewDelegateFlowL
339
368
  guard key != scrollTargetKey else { return }
340
369
  scrollTargetKey = key
341
370
  pendingScrollTarget = (id, animated, 0)
371
+ cancelEndSettle()
342
372
  scrollToPendingTarget()
343
373
  }
344
374
 
@@ -538,6 +568,7 @@ final class CraftNativeFlatList: UICollectionView, UICollectionViewDelegateFlowL
538
568
  pendingThemeRefresh = false
539
569
  scrollTargetKey = nil
540
570
  pendingScrollTarget = nil
571
+ cancelEndSettle()
541
572
  }
542
573
 
543
574
  /// Releases callbacks and UIKit ownership that belong to a permanently
@@ -569,15 +600,28 @@ final class CraftNativeFlatList: UICollectionView, UICollectionViewDelegateFlowL
569
600
  }
570
601
 
571
602
  func scrollViewDidScroll(_ scrollView: UIScrollView) {
603
+ // The end is measured by jumping there and back in one pass, before
604
+ // anything draws: the screen hears only where the scroll goes.
605
+ guard !isMeasuringEnd else { return }
572
606
  onScrollEvent?(scrollView)
573
607
  onLayoutChanged?()
574
608
  evaluateEndReached()
575
609
  }
576
610
 
577
611
  func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
612
+ // The finger has the list now: stop holding it to its end.
613
+ cancelEndSettle()
578
614
  onScrollBeginDrag?(scrollView)
579
615
  }
580
616
 
617
+ func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
618
+ guard isAnimatingToEnd else { return }
619
+ isAnimatingToEnd = false
620
+ // Rows passed on the way measured themselves and moved the end.
621
+ settleAtEnd()
622
+ scheduleEndSettle()
623
+ }
624
+
581
625
  func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
582
626
  onScrollEndDrag?(scrollView)
583
627
  }
@@ -636,12 +680,16 @@ final class CraftNativeFlatList: UICollectionView, UICollectionViewDelegateFlowL
636
680
 
637
681
  private func scrollToPendingTarget() {
638
682
  guard let target = pendingScrollTarget else { return }
683
+ // A snapshot that is landing, or queued behind the one landing, can
684
+ // add rows before the target or move it: an index read now is stale
685
+ // (it scrolled to the old end). finishApplyingSnapshot() aims again
686
+ // once the rows are in, and so does a list not laid out yet.
687
+ guard !isApplyingSnapshot, pendingApply == nil, bounds.width > 0, bounds.height > 0 else { return }
639
688
  guard let index = targetIndex(for: target.id), index < numberOfItems(inSection: 0) else {
689
+ // No row has this id once the list is idle: try a few more
690
+ // passes, then let it go.
640
691
  if target.attempts >= 4 {
641
- // A diffable snapshot may still be applying. Keep the target
642
- // for finishApplyingSnapshot(), but discard an invalid target
643
- // once the list is otherwise idle.
644
- if !isApplyingSnapshot { pendingScrollTarget = nil }
692
+ pendingScrollTarget = nil
645
693
  return
646
694
  }
647
695
  pendingScrollTarget = (target.id, target.animated, target.attempts + 1)
@@ -649,8 +697,100 @@ final class CraftNativeFlatList: UICollectionView, UICollectionViewDelegateFlowL
649
697
  return
650
698
  }
651
699
  pendingScrollTarget = nil
700
+ let indexPath = IndexPath(item: index, section: 0)
701
+ let identity = diffableDataSource.itemIdentifier(for: indexPath) ?? items[index].identity
702
+ if index == numberOfItems(inSection: 0) - 1 {
703
+ scrollToEnd(animated: target.animated)
704
+ return
705
+ }
652
706
  let position: UICollectionView.ScrollPosition = flowLayout.scrollDirection == .horizontal ? .left : .top
653
- scrollToItem(at: IndexPath(item: index, section: 0), at: position, animated: target.animated)
707
+ scrollToItem(at: indexPath, at: position, animated: target.animated)
708
+ guard !target.animated else { return }
709
+ // A row near the end cannot come to the top: the list stops at its
710
+ // end, which is only true once the rows there are measured.
711
+ layoutIfNeeded()
712
+ if rowReachesPastEnd(identity) { scrollToEnd(animated: false) }
713
+ }
714
+
715
+ /// The offset that shows the end of the content, along the scroll axis.
716
+ private var endOffset: CGPoint {
717
+ if flowLayout.scrollDirection == .horizontal {
718
+ return CGPoint(
719
+ x: max(-adjustedContentInset.left, contentSize.width + adjustedContentInset.right - bounds.width),
720
+ y: contentOffset.y
721
+ )
722
+ }
723
+ return CGPoint(
724
+ x: contentOffset.x,
725
+ y: max(-adjustedContentInset.top, contentSize.height + adjustedContentInset.bottom - bounds.height)
726
+ )
727
+ }
728
+
729
+ /// Whether the row's leading edge lies past where the list can scroll to.
730
+ private func rowReachesPastEnd(_ identity: String) -> Bool {
731
+ guard let indexPath = diffableDataSource.indexPath(for: identity),
732
+ let frame = layoutAttributesForItem(at: indexPath)?.frame else { return false }
733
+ if flowLayout.scrollDirection == .horizontal {
734
+ return frame.minX - adjustedContentInset.left >= endOffset.x - 0.5
735
+ }
736
+ return frame.minY - adjustedContentInset.top >= endOffset.y - 0.5
737
+ }
738
+
739
+ private func scrollToEnd(animated: Bool) {
740
+ endSettlePasses = 2
741
+ endSettleGeneration += 1
742
+ if animated {
743
+ // Measure the rows at the end where they will be, then animate
744
+ // there from where the list was, so the animation lands on the
745
+ // true end rather than on an estimate.
746
+ let start = contentOffset
747
+ isMeasuringEnd = true
748
+ settleAtEnd()
749
+ let end = contentOffset
750
+ setContentOffset(start, animated: false)
751
+ isMeasuringEnd = false
752
+ if abs(end.x - start.x) > 0.5 || abs(end.y - start.y) > 0.5 {
753
+ isAnimatingToEnd = true
754
+ setContentOffset(end, animated: true)
755
+ }
756
+ } else {
757
+ settleAtEnd()
758
+ }
759
+ scheduleEndSettle()
760
+ }
761
+
762
+ /// Moves to the end until it stops moving: each move shows rows that
763
+ /// measure themselves and change the content size.
764
+ private func settleAtEnd() {
765
+ guard endSettlePasses != nil, !isDragging, !isTracking else { return cancelEndSettle() }
766
+ for _ in 0..<6 {
767
+ layoutIfNeeded()
768
+ let end = endOffset
769
+ guard abs(end.x - contentOffset.x) > 0.5 || abs(end.y - contentOffset.y) > 0.5 else { break }
770
+ setContentOffset(end, animated: false)
771
+ }
772
+ }
773
+
774
+ /// Checks the end again on the next runloop passes, while late rows and
775
+ /// the content size settle.
776
+ private func scheduleEndSettle() {
777
+ let generation = endSettleGeneration
778
+ DispatchQueue.main.async { [weak self] in
779
+ guard let self, self.endSettleGeneration == generation, let passes = self.endSettlePasses,
780
+ // An animation on its way there settles, and checks
781
+ // again, when it ends.
782
+ !self.isAnimatingToEnd else { return }
783
+ if passes <= 0 { return self.cancelEndSettle() }
784
+ self.endSettlePasses = passes - 1
785
+ if !self.isApplyingSnapshot, self.pendingApply == nil { self.settleAtEnd() }
786
+ self.scheduleEndSettle()
787
+ }
788
+ }
789
+
790
+ private func cancelEndSettle() {
791
+ endSettlePasses = nil
792
+ endSettleGeneration += 1
793
+ isAnimatingToEnd = false
654
794
  }
655
795
 
656
796
  private func clamped(_ offset: CGPoint) -> CGPoint {
@@ -339,11 +339,13 @@ final class CraftNativeMutationDocument {
339
339
  /// `Svg`). Only View, SafeAreaView and ScrollView used to be here, so a
340
340
  /// drawing revealed after the first paint (an `:if` around an `<svg>`)
341
341
  /// had its shapes refused as INVALID_PARENT, and the whole screen was
342
- /// drawn again; Android's host already took the same list.
342
+ /// drawn again; Android's host already took the same list. A shape holds
343
+ /// its `Animate` (SMIL keyframes: HQ's moving exercise figures).
343
344
  static let containerTypes: Set<String> = [
344
345
  "View", "SafeAreaView", "ScrollView", "KeyboardAvoidingView", "Modal", "Pressable",
345
346
  "TouchableOpacity", "TouchableHighlight", "ImageBackground", "FlatList", "SectionList",
346
347
  "Fragment", "Svg", "G", "Map",
348
+ "Path", "Line", "Rect", "Circle", "Ellipse", "Polyline", "Polygon",
347
349
  ]
348
350
  private static let containerTypeKeys = Set(containerTypes.map { $0.lowercased() })
349
351
 
@@ -2164,6 +2164,13 @@ extension UIView {
2164
2164
  set { objc_setAssociatedObject(self, &craftNativeLayoutStyleKey, CraftNativeLayoutStyleBox(newValue), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) }
2165
2165
  }
2166
2166
 
2167
+ /// The margins this view's style asks for, for a container that places
2168
+ /// it without a flex parent (a FlatList cell).
2169
+ var craftLayoutMargins: UIEdgeInsets {
2170
+ let style = craftLayoutStyle
2171
+ return UIEdgeInsets(top: max(0, style.marginTop), left: max(0, style.marginLeft), bottom: max(0, style.marginBottom), right: max(0, style.marginRight))
2172
+ }
2173
+
2167
2174
  /// The corner radius the style asked for. The layer gets at most half the
2168
2175
  /// shortest side: Core Animation draws nothing at all for a radius larger
2169
2176
  /// than the view (`rounded-full` is 9999).
@@ -4328,9 +4335,13 @@ private final class CraftNativeScrollView: UIScrollView, UIGestureRecognizerDele
4328
4335
  /// 3 quadratic, 4 close, in viewBox units - and scaled to the view. Paint is
4329
4336
  /// inherited down the tree as SVG does; `dark:` classes arrive already
4330
4337
  /// resolved for the appearance, so a redraw is all a theme change needs.
4331
- private final class CraftNativeSvgView: UIView {
4338
+ final class CraftNativeSvgView: UIView {
4332
4339
  var drawing: [String: Any] = [:] {
4333
- didSet { setNeedsDisplay() }
4340
+ didSet {
4341
+ animates = Self.hasAnimation(drawing["children"] as? [Any] ?? [])
4342
+ setNeedsDisplay()
4343
+ updateFrames()
4344
+ }
4334
4345
  }
4335
4346
 
4336
4347
  override init(frame: CGRect) {
@@ -4338,10 +4349,123 @@ private final class CraftNativeSvgView: UIView {
4338
4349
  isOpaque = false
4339
4350
  backgroundColor = .clear
4340
4351
  contentMode = .redraw
4352
+ NotificationCenter.default.addObserver(self, selector: #selector(reduceMotionChanged), name: UIAccessibility.reduceMotionStatusDidChangeNotification, object: nil)
4341
4353
  }
4342
4354
 
4343
4355
  required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
4344
4356
 
4357
+ deinit { CraftNativeFrameClock.shared.cancel(self) }
4358
+
4359
+ // MARK: Animation
4360
+
4361
+ /// Whether a shape carries keyframes (SMIL `<animate attributeName="d">`,
4362
+ /// stx's `Animate`: an exercise's moving figure).
4363
+ private var animates = false
4364
+ /// When this drawing's repetition began: each one starts from its first
4365
+ /// pose when it comes on screen, as a page's SMIL starts when it loads.
4366
+ private var animationStart: CFTimeInterval?
4367
+
4368
+ /// Moving now: on display, and the person has not asked for less motion,
4369
+ /// when each shape keeps its own outline (the still pose).
4370
+ var isAnimating: Bool { animates && window != nil && !isHidden && !UIAccessibility.isReduceMotionEnabled }
4371
+
4372
+ override func didMoveToWindow() {
4373
+ super.didMoveToWindow()
4374
+ updateFrames()
4375
+ }
4376
+
4377
+ override var isHidden: Bool {
4378
+ didSet { if isHidden != oldValue { updateFrames() } }
4379
+ }
4380
+
4381
+ @objc private func reduceMotionChanged() {
4382
+ updateFrames()
4383
+ setNeedsDisplay()
4384
+ }
4385
+
4386
+ /// Frames from the screens' display link (CraftNativeFrameClock, up to
4387
+ /// 120Hz) while moving; none at all while still or out of sight.
4388
+ private func updateFrames() {
4389
+ if isAnimating {
4390
+ if animationStart == nil { animationStart = CACurrentMediaTime() }
4391
+ CraftNativeFrameClock.shared.request(self) { [weak self] in self?.nextFrame() }
4392
+ } else {
4393
+ animationStart = nil
4394
+ CraftNativeFrameClock.shared.cancel(self)
4395
+ }
4396
+ }
4397
+
4398
+ private func nextFrame() {
4399
+ guard isAnimating else { return updateFrames() }
4400
+ // Drawn only while some of it is on screen; a row scrolled away keeps
4401
+ // its time and is right when it comes back.
4402
+ if let window, window.bounds.intersects(convert(bounds, to: window)) { setNeedsDisplay() }
4403
+ CraftNativeFrameClock.shared.request(self) { [weak self] in self?.nextFrame() }
4404
+ }
4405
+
4406
+ private static func hasAnimation(_ children: [Any]) -> Bool {
4407
+ children.contains { child in
4408
+ guard let node = child as? [String: Any] else { return false }
4409
+ if node["type"] as? String == "Animate" { return (node["props"] as? [String: Any])?["frames"] != nil }
4410
+ return hasAnimation(node["children"] as? [Any] ?? [])
4411
+ }
4412
+ }
4413
+
4414
+ /// A shape's outline now: between the keyframes either side of `elapsed`
4415
+ /// seconds into its animation (SMIL's linear `calcMode`), or its own
4416
+ /// outline when it has none, the animation has ended, or motion is reduced.
4417
+ private func outline(of shape: [String: Any]) -> Any? {
4418
+ let geometry = (shape["props"] as? [String: Any])?["geometry"]
4419
+ guard isAnimating, let start = animationStart,
4420
+ let animate = (shape["children"] as? [Any])?.lazy.compactMap({ $0 as? [String: Any] }).first(where: { $0["type"] as? String == "Animate" }),
4421
+ let current = Self.keyframe(animate["props"] as? [String: Any] ?? [:], at: CACurrentMediaTime() - start) else { return geometry }
4422
+ return current
4423
+ }
4424
+
4425
+ /// The outline `elapsed` seconds into an `Animate`'s repetitions; nil
4426
+ /// when it does not animate path data or its repetitions are over.
4427
+ static func keyframe(_ props: [String: Any], at elapsed: CFTimeInterval) -> [Any]? {
4428
+ guard props["attributeName"] as? String == "d",
4429
+ let duration = number(props["duration"]), duration > 0, duration.isFinite,
4430
+ let frames = (props["frames"] as? [Any])?.compactMap({ ($0 as? [Any])?.compactMap(number) }),
4431
+ frames.count >= 2, elapsed >= 0 else { return nil }
4432
+ if let count = number(props["repeatCount"]), elapsed >= Double(count * duration) { return nil }
4433
+ let given = (props["frameTimes"] as? [Any])?.compactMap(number) ?? []
4434
+ let times = given.count == frames.count ? given : frames.indices.map { CGFloat($0) / CGFloat(frames.count - 1) }
4435
+ let phase = CGFloat(elapsed.truncatingRemainder(dividingBy: Double(duration))) / duration
4436
+ var index = 0
4437
+ while index < frames.count - 2, times[index + 1] <= phase { index += 1 }
4438
+ let from = frames[index]
4439
+ let to = frames[index + 1]
4440
+ let span = times[index + 1] - times[index]
4441
+ let share = span > 0 ? min(1, max(0, (phase - times[index]) / span)) : 0
4442
+ return interpolate(from, to, share).map { NSNumber(value: Double($0)) }
4443
+ }
4444
+
4445
+ /// Two outlines with the same commands, a share of the way from one to
4446
+ /// the other; the first as it is when their commands differ.
4447
+ static func interpolate(_ from: [CGFloat], _ to: [CGFloat], _ share: CGFloat) -> [CGFloat] {
4448
+ guard from.count == to.count, share > 0 else { return from }
4449
+ var out = from
4450
+ var i = 0
4451
+ while i < from.count {
4452
+ let command = Int(from[i])
4453
+ guard to[i] == from[i] else { return from }
4454
+ let count: Int
4455
+ switch command {
4456
+ case 0, 1: count = 2
4457
+ case 2: count = 6
4458
+ case 3: count = 4
4459
+ case 4: count = 0
4460
+ default: return from
4461
+ }
4462
+ guard i + count < from.count else { return from }
4463
+ if count > 0 { for k in 1...count { out[i + k] = from[i + k] + (to[i + k] - from[i + k]) * share } }
4464
+ i += count + 1
4465
+ }
4466
+ return out
4467
+ }
4468
+
4345
4469
  var viewBox: CGRect? {
4346
4470
  let props = drawing["props"] as? [String: Any] ?? [:]
4347
4471
  guard let box = props["viewBox"] as? [Any], box.count == 4 else { return nil }
@@ -4461,8 +4585,10 @@ private final class CraftNativeSvgView: UIView {
4461
4585
  draw(children: shape["children"] as? [Any] ?? [], paint: own, in: context)
4462
4586
  case "SvgText":
4463
4587
  drawText(shape, paint: own)
4588
+ case "Animate":
4589
+ continue
4464
4590
  default:
4465
- guard let path = CraftNativeSvgView.path((shape["props"] as? [String: Any])?["geometry"]) else { continue }
4591
+ guard let path = CraftNativeSvgView.path(outline(of: shape)) else { continue }
4466
4592
  context.saveGState()
4467
4593
  path.usesEvenOddFillRule = own.fillRule == "evenodd"
4468
4594
  if let fill = own.resolve(own.fill) {
@@ -4859,9 +4985,24 @@ enum CraftNativeScriptThread {
4859
4985
  static let queue = DispatchQueue(label: "craft.native.script", qos: .userInteractive)
4860
4986
 
4861
4987
  /// `work` where the screens' JavaScript runs: now on the main thread, or
4862
- /// queued in order on the script thread.
4863
- static func run(_ work: @escaping () -> Void) {
4864
- if isBackground { queue.async(execute: work) } else { work() }
4988
+ /// queued in order on the script thread. With frame pacing on
4989
+ /// (`CRAFT_FRAME_PACING=1`), work that waited or ran for 4ms or more is
4990
+ /// logged under `label`, so a slow screen can be told from a queued one.
4991
+ static func run(label: @autoclosure @escaping () -> String = "script", _ work: @escaping () -> Void) {
4992
+ let pacing = CraftFramePacing.shared
4993
+ guard pacing.enabled else {
4994
+ if isBackground { queue.async(execute: work) } else { work() }
4995
+ return
4996
+ }
4997
+ let queued = CACurrentMediaTime()
4998
+ let timed = {
4999
+ let started = CACurrentMediaTime()
5000
+ work()
5001
+ let ran = CACurrentMediaTime() - started
5002
+ let waited = started - queued
5003
+ if waited + ran >= 0.004 { pacing.scriptWork(label(), waited: waited, ran: ran) }
5004
+ }
5005
+ if isBackground { queue.async(execute: timed) } else { timed() }
4865
5006
  }
4866
5007
 
4867
5008
  /// From the script thread, `work` on the main thread, not waited for.
@@ -5241,7 +5382,7 @@ final class CraftNativeScreenController: UIViewController, UIScrollViewDelegate,
5241
5382
  let pacing = CraftFramePacing.shared
5242
5383
  let inputs = scriptInputs()
5243
5384
  let name = routeName ?? "screen"
5244
- CraftNativeScriptThread.run { [self] in
5385
+ CraftNativeScriptThread.run(label: "mount \(name)") { [self] in
5245
5386
  pacing.measure("mount \(name) setup") { setupJavaScript(inputs) }
5246
5387
  pacing.measure("mount \(name) bundle") { loadBundle() }
5247
5388
  }
@@ -5302,8 +5443,9 @@ final class CraftNativeScreenController: UIViewController, UIScrollViewDelegate,
5302
5443
  screenVisibilityChanged(false)
5303
5444
  stopCelebrations(in: view)
5304
5445
  // Release only this screen's accessory. A retained or prepared screen
5305
- // can disappear after the destination has already published its own.
5306
- CraftChrome.shared.clearTabAccessory(ownedBy: self)
5446
+ // can disappear after the destination has already published its own;
5447
+ // released, it stays drawn until the destination says what it wants.
5448
+ CraftChrome.shared.releaseTabAccessory(ownedBy: self)
5307
5449
  // Popped (or its stack dismissed) while the bar was away: it comes
5308
5450
  // back for whatever shows next, a web page included.
5309
5451
  if tabBarHidden, isMovingFromParent || isBeingDismissed || navigationController?.isBeingDismissed == true {
@@ -5348,7 +5490,11 @@ final class CraftNativeScreenController: UIViewController, UIScrollViewDelegate,
5348
5490
  private func restoreShellChrome() {
5349
5491
  guard !isAppScript else { return }
5350
5492
  CraftChrome.shared.setHiddenByScreen(tabBarHidden)
5351
- CraftChrome.shared.updateTabAccessory(tabAccessory, owner: self)
5493
+ // A screen not yet asked about the accessory (one shown for the first
5494
+ // time, before its script has run) leaves the bar as it is; one that
5495
+ // has drawn without asking for it takes off what nobody claims.
5496
+ if tabAccessoryDeclared { CraftChrome.shared.updateTabAccessory(tabAccessory, owner: self) }
5497
+ else if hybridRendered { CraftChrome.shared.clearUnclaimedTabAccessory() }
5352
5498
  }
5353
5499
 
5354
5500
  /// `requestAnimationFrame`: the next display frame, for a screen on display
@@ -5365,7 +5511,8 @@ final class CraftNativeScreenController: UIViewController, UIScrollViewDelegate,
5365
5511
  guard frameWanted, !runtimeDisposed else { return }
5366
5512
  frameWanted = false
5367
5513
  let context = jsContext
5368
- CraftNativeScriptThread.run { context.objectForKeyedSubscript("__craftNativeFireFrame")?.call(withArguments: []) }
5514
+ let route = routeName ?? "screen"
5515
+ CraftNativeScriptThread.run(label: "frame \(route)") { context.objectForKeyedSubscript("__craftNativeFireFrame")?.call(withArguments: []) }
5369
5516
  }
5370
5517
 
5371
5518
  /// The screen came on screen or went off it: a screen pushed over it was
@@ -5400,7 +5547,8 @@ final class CraftNativeScreenController: UIViewController, UIScrollViewDelegate,
5400
5547
  routeProps = props
5401
5548
  guard isViewLoaded, !runtimeDisposed else { return }
5402
5549
  let context = jsContext
5403
- CraftNativeScriptThread.run {
5550
+ let route = routeName ?? "screen"
5551
+ CraftNativeScriptThread.run(label: "params \(route)") {
5404
5552
  context.setObject(params as NSDictionary, forKeyedSubscript: "__stxNativeParams" as NSString)
5405
5553
  context.setObject(props as NSDictionary, forKeyedSubscript: "__stxNativeProps" as NSString)
5406
5554
  }
@@ -5414,7 +5562,8 @@ final class CraftNativeScreenController: UIViewController, UIScrollViewDelegate,
5414
5562
  CraftNativeFrameClock.shared.cancel(self)
5415
5563
  disposeRenderedTree()
5416
5564
  let context = jsContext
5417
- CraftNativeScriptThread.run { context.objectForKeyedSubscript("__stxNativeUnmount")?.call(withArguments: []) }
5565
+ let route = routeName ?? "screen"
5566
+ CraftNativeScriptThread.run(label: "unmount \(route)") { context.objectForKeyedSubscript("__stxNativeUnmount")?.call(withArguments: []) }
5418
5567
  audio.close()
5419
5568
  sounds.close()
5420
5569
  streams.close()
@@ -6215,6 +6364,10 @@ final class CraftNativeScreenController: UIViewController, UIScrollViewDelegate,
6215
6364
  /// The app's tab bar away while this screen shows (`tabBarHidden`).
6216
6365
  private var tabBarHidden = false
6217
6366
  private var tabAccessory: [String: Any]?
6367
+ /// Whether the screen has said anything about the accessory yet
6368
+ /// (`tabAccessory`, null included): until it has, the bar keeps showing
6369
+ /// the one it had (CraftChrome.releaseTabAccessory).
6370
+ private var tabAccessoryDeclared = false
6218
6371
  /// Whether a back-swipe may leave this screen at all, the edge's
6219
6372
  /// included (`swipeBack: false`): a screen that steps through its own
6220
6373
  /// pages with a Back of its own (a first-run tour's questions) would
@@ -6263,6 +6416,7 @@ final class CraftNativeScreenController: UIViewController, UIScrollViewDelegate,
6263
6416
  guard !isAppScript else { return }
6264
6417
  if options.keys.contains("tabAccessory") {
6265
6418
  tabAccessory = options["tabAccessory"] as? [String: Any]
6419
+ tabAccessoryDeclared = true
6266
6420
  if navigationController?.topViewController === self, view.window != nil {
6267
6421
  CraftChrome.shared.updateTabAccessory(tabAccessory, owner: self)
6268
6422
  }
@@ -6652,7 +6806,7 @@ final class CraftNativeScreenController: UIViewController, UIScrollViewDelegate,
6652
6806
  let previous = info["previous"] as? String
6653
6807
  self.send(type: "SESSION_CHANGED", payload: ["key": key, "token": token ?? NSNull(), "previous": previous ?? NSNull()])
6654
6808
  let context = self.jsContext
6655
- CraftNativeScriptThread.run { context.objectForKeyedSubscript("__craftSessionChanged")?.call(withArguments: [token ?? NSNull(), previous ?? NSNull()]) }
6809
+ CraftNativeScriptThread.run(label: "session \(self.routeName ?? "screen")") { context.objectForKeyedSubscript("__craftSessionChanged")?.call(withArguments: [token ?? NSNull(), previous ?? NSNull()]) }
6656
6810
  })
6657
6811
  }
6658
6812
  if config.enablePushNotifications {
@@ -6937,8 +7091,15 @@ final class CraftNativeScreenController: UIViewController, UIScrollViewDelegate,
6937
7091
  }
6938
7092
  let module = payload["module"] as? String ?? ""
6939
7093
  let method = payload["method"] as? String ?? ""
7094
+ // With frame pacing on: how long the capability took to answer,
7095
+ // which a screen's script waits on (a request, the keychain).
7096
+ let pacing = CraftFramePacing.shared
7097
+ let asked = pacing.enabled ? CACurrentMediaTime() : 0
7098
+ let route = routeName ?? "screen"
7099
+ let what = module == "Network" ? "\(module).\(method) \(((args.first as? [String: Any])?["url"] as? String).flatMap { URL(string: $0)?.path } ?? "")" : "\(module).\(method)"
6940
7100
  let reply: (Result<Any, CraftNativeActionError>) -> Void = { [weak self] answer in
6941
7101
  guard let self = self, self.pendingCapabilityRequests.remove(requestToken) != nil else { return }
7102
+ if pacing.enabled { pacing.capability("\(what) \(route)", took: CACurrentMediaTime() - asked) }
6942
7103
  self.pendingCapabilityDeadlines.removeValue(forKey: requestToken)?.cancel()
6943
7104
  self.screenRequestCancellers.removeValue(forKey: requestToken)
6944
7105
  switch answer {
@@ -7167,6 +7328,8 @@ final class CraftNativeScreenController: UIViewController, UIScrollViewDelegate,
7167
7328
  hybridRendered = true
7168
7329
  // The app script's drawing is never on screen: not a first frame.
7169
7330
  if !isAppScript { hybridEvents?.nativeScreenDidRender(self) }
7331
+ // Drawn without a word about the accessory: it wants none.
7332
+ if !isAppScript, !tabAccessoryDeclared, isShownOnScreen { CraftChrome.shared.clearUnclaimedTabAccessory() }
7170
7333
  let waiting = renderWaiters
7171
7334
  renderWaiters.removeAll()
7172
7335
  waiting.forEach { $0() }
@@ -9832,7 +9995,8 @@ final class CraftNativeScreenController: UIViewController, UIScrollViewDelegate,
9832
9995
  guard let data = try? JSONSerialization.data(withJSONObject: message),
9833
9996
  let json = String(data: data, encoding: .utf8) else { return }
9834
9997
  let context = jsContext
9835
- CraftNativeScriptThread.run { context.objectForKeyedSubscript("__stxNativeCallback")?.call(withArguments: [json]) }
9998
+ let route = routeName ?? "screen"
9999
+ CraftNativeScriptThread.run(label: "\(type) \(route)") { context.objectForKeyedSubscript("__stxNativeCallback")?.call(withArguments: [json]) }
9836
10000
  }
9837
10001
 
9838
10002
  private func number(_ value: Any?) -> CGFloat? {