craft-native 0.0.262 → 0.0.276

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.
@@ -1345,6 +1345,64 @@ private final class CraftNativeVideoView: UIView, AVPlayerViewControllerDelegate
1345
1345
  deinit { stop() }
1346
1346
  }
1347
1347
 
1348
+ /// A map pin that answers being activated as it answers a tap.
1349
+ final class CraftMarkerAnnotationView: MKAnnotationView {
1350
+ var onActivate: (() -> Void)?
1351
+
1352
+ override func accessibilityActivate() -> Bool {
1353
+ guard let onActivate else { return super.accessibilityActivate() }
1354
+ onActivate()
1355
+ return true
1356
+ }
1357
+
1358
+ override func prepareForReuse() {
1359
+ super.prepareForReuse()
1360
+ onActivate = nil
1361
+ }
1362
+ }
1363
+
1364
+ /// A tile overlay whose tiles are kept on disk.
1365
+ ///
1366
+ /// MKTileOverlay asked the network for every tile on every pan back over the
1367
+ /// same ground, and drew nothing where a tile had not come yet. These go
1368
+ /// through one session with a cache of its own (Caches/craft-map-tiles), so
1369
+ /// ground seen before draws at once and offline, and a phone on a trail
1370
+ /// does not fetch the same hillside twice.
1371
+ final class CraftCachedTileOverlay: MKTileOverlay {
1372
+ static let session: URLSession = {
1373
+ let configuration = URLSessionConfiguration.default
1374
+ let directory = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first?.appendingPathComponent("craft-map-tiles", isDirectory: true)
1375
+ configuration.urlCache = URLCache(memoryCapacity: 48 << 20, diskCapacity: 512 << 20, directory: directory)
1376
+ // Topography and imagery change on the scale of months: a tile held
1377
+ // is used without asking again.
1378
+ configuration.requestCachePolicy = .returnCacheDataElseLoad
1379
+ configuration.httpMaximumConnectionsPerHost = 8
1380
+ return URLSession(configuration: configuration)
1381
+ }()
1382
+
1383
+ override func loadTile(at path: MKTileOverlayPath, result: @escaping (Data?, Error?) -> Void) {
1384
+ let request = URLRequest(url: url(forTilePath: path), cachePolicy: .returnCacheDataElseLoad, timeoutInterval: 20)
1385
+ Self.session.dataTask(with: request) { data, response, error in
1386
+ if let status = (response as? HTTPURLResponse)?.statusCode, !(200..<300).contains(status) {
1387
+ result(nil, error ?? URLError(.badServerResponse))
1388
+ return
1389
+ }
1390
+ result(data, error)
1391
+ }.resume()
1392
+ }
1393
+ }
1394
+
1395
+ /// The basemaps a `Map` names with `basemap`, drawn the best way each
1396
+ /// platform can: Apple's vector map (with real terrain from iOS 16) for
1397
+ /// standard, imagery and hybrid, and topography with contours over a muted
1398
+ /// Apple map for outdoors.
1399
+ enum CraftBasemap: String {
1400
+ case standard, outdoors, satellite, hybrid
1401
+
1402
+ static let outdoorTiles = "https://server.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer/tile/{z}/{y}/{x}"
1403
+ static let outdoorCredit = "Topography: Esri, USGS, NOAA, OpenStreetMap contributors"
1404
+ }
1405
+
1348
1406
  private final class CraftNativeMapView: MKMapView, MKMapViewDelegate {
1349
1407
  private var annotationsByID: [String: MKPointAnnotation] = [:]
1350
1408
  private var overlaysByID: [String: MKPolyline] = [:]
@@ -1371,6 +1429,8 @@ private final class CraftNativeMapView: MKMapView, MKMapViewDelegate {
1371
1429
  private var markerPinColors: [String: UIColor] = [:]
1372
1430
  private var tileOverlay: MKTileOverlay?
1373
1431
  private var tileTemplate: String?
1432
+ private var tileReplacesMap = true
1433
+ private var appliedBasemap: CraftBasemap?
1374
1434
  private var tileAttributionBottom: NSLayoutConstraint?
1375
1435
  private lazy var tileAttribution: UILabel = {
1376
1436
  let label = UILabel()
@@ -1395,6 +1455,10 @@ private final class CraftNativeMapView: MKMapView, MKMapViewDelegate {
1395
1455
  isRotateEnabled = false
1396
1456
  let tap = UITapGestureRecognizer(target: self, action: #selector(pressedMap(_:)))
1397
1457
  tap.cancelsTouchesInView = false
1458
+ // Alongside MapKit's own recognizers, not instead of them: on its own
1459
+ // this tap won the touch, MapKit never selected the pin under it, and
1460
+ // a pin's onPress (Explore's trail card) never fired on a phone.
1461
+ tap.delegate = CraftMapTapDelegate.shared
1398
1462
  addGestureRecognizer(tap)
1399
1463
  }
1400
1464
 
@@ -1429,8 +1493,13 @@ private final class CraftNativeMapView: MKMapView, MKMapViewDelegate {
1429
1493
  isZoomEnabled = props["zoomEnabled"] as? Bool ?? true
1430
1494
  isRotateEnabled = props["rotateEnabled"] as? Bool ?? false
1431
1495
  isPitchEnabled = props["pitchEnabled"] as? Bool ?? true
1432
- mapType = Self.mapType(props["mapType"] as? String)
1433
- configureTiles(props["tileOverlay"] as? [String: Any])
1496
+ if let basemap = (props["basemap"] as? String).flatMap({ CraftBasemap(rawValue: $0.lowercased()) }) {
1497
+ applyBasemap(basemap)
1498
+ } else {
1499
+ appliedBasemap = nil
1500
+ mapType = Self.mapType(props["mapType"] as? String)
1501
+ configureTiles(props["tileOverlay"] as? [String: Any])
1502
+ }
1434
1503
  showsCompass = props["showsCompass"] as? Bool ?? false
1435
1504
  showsScale = props["showsScale"] as? Bool ?? false
1436
1505
  authoredPitch = Self.numeric(props["cameraPitch"])
@@ -1562,7 +1631,9 @@ private final class CraftNativeMapView: MKMapView, MKMapViewDelegate {
1562
1631
  overlayCoordinatesByID[id] = value.coordinates
1563
1632
  overlayColors[ObjectIdentifier(overlay)] = value.color
1564
1633
  overlayWidths[ObjectIdentifier(overlay)] = value.width
1565
- addOverlay(overlay)
1634
+ // Above labels, as a basemap's topography is: at a lower level
1635
+ // the outdoors layer covered every route drawn on it.
1636
+ addOverlay(overlay, level: .aboveLabels)
1566
1637
  }
1567
1638
  let stalePolygons = polygonsByID.keys.filter { nextPolygons[$0] == nil }
1568
1639
  for id in stalePolygons {
@@ -1595,7 +1666,7 @@ private final class CraftNativeMapView: MKMapView, MKMapViewDelegate {
1595
1666
  polygonFills[ObjectIdentifier(polygon)] = value.fill
1596
1667
  polygonStrokes[ObjectIdentifier(polygon)] = value.stroke
1597
1668
  polygonWidths[ObjectIdentifier(polygon)] = value.width
1598
- addOverlay(polygon)
1669
+ addOverlay(polygon, level: .aboveLabels)
1599
1670
  }
1600
1671
  // Keep authored casing/foreground order when an earlier line changes
1601
1672
  // or retained children move. Exchanging native overlays preserves the
@@ -1684,20 +1755,48 @@ private final class CraftNativeMapView: MKMapView, MKMapViewDelegate {
1684
1755
  tileAttribution.isHidden = true
1685
1756
  }
1686
1757
 
1687
- private func configureTiles(_ options: [String: Any]?) {
1758
+ /// A named basemap. Applied once per change: setting a map configuration
1759
+ /// again redraws the whole map.
1760
+ private func applyBasemap(_ basemap: CraftBasemap) {
1761
+ if appliedBasemap != basemap {
1762
+ appliedBasemap = basemap
1763
+ if #available(iOS 16.0, *) {
1764
+ switch basemap {
1765
+ case .satellite: preferredConfiguration = MKImageryMapConfiguration(elevationStyle: .realistic)
1766
+ case .hybrid: preferredConfiguration = MKHybridMapConfiguration(elevationStyle: .realistic)
1767
+ // Flat under the topography, so the overlay's contours sit
1768
+ // on the ground they describe.
1769
+ case .outdoors: preferredConfiguration = MKStandardMapConfiguration(elevationStyle: .flat, emphasisStyle: .muted)
1770
+ case .standard: preferredConfiguration = MKStandardMapConfiguration(elevationStyle: .realistic)
1771
+ }
1772
+ }
1773
+ else {
1774
+ mapType = basemap == .satellite ? .satellite : basemap == .hybrid ? .hybrid : basemap == .outdoors ? .mutedStandard : .standard
1775
+ }
1776
+ }
1777
+ configureTiles(basemap == .outdoors ? ["urlTemplate": CraftBasemap.outdoorTiles, "attribution": CraftBasemap.outdoorCredit] : nil, replacesMap: false)
1778
+ }
1779
+
1780
+ /// `replacesMap`: an authored `tileOverlay` replaces Apple's map, as it
1781
+ /// always has. A basemap's topography draws over it instead, above its
1782
+ /// labels, so ground whose tiles have not come yet shows the map rather
1783
+ /// than an empty grid.
1784
+ private func configureTiles(_ options: [String: Any]?, replacesMap: Bool = true) {
1688
1785
  let template = options?["urlTemplate"] as? String
1689
1786
  let credit = options?["attribution"] as? String ?? ""
1690
1787
  let valid = template.map { value in value.hasPrefix("https://") && ["{z}", "{x}", "{y}"].allSatisfy { value.contains($0) } } ?? false
1691
1788
  let next = valid && !credit.isEmpty ? template : nil
1692
- if tileTemplate != next {
1789
+ if tileTemplate != next || tileReplacesMap != replacesMap {
1693
1790
  if let overlay = tileOverlay { removeOverlay(overlay) }
1694
1791
  tileOverlay = nil
1695
1792
  tileTemplate = next
1793
+ tileReplacesMap = replacesMap
1696
1794
  if let next {
1697
- let overlay = MKTileOverlay(urlTemplate: next)
1698
- overlay.canReplaceMapContent = true
1795
+ let overlay = CraftCachedTileOverlay(urlTemplate: next)
1796
+ overlay.canReplaceMapContent = replacesMap
1797
+ overlay.maximumZ = 19
1699
1798
  tileOverlay = overlay
1700
- insertOverlay(overlay, at: 0, level: .aboveRoads)
1799
+ insertOverlay(overlay, at: 0, level: replacesMap ? .aboveRoads : .aboveLabels)
1701
1800
  }
1702
1801
  }
1703
1802
  tileAttribution.text = next == nil ? nil : credit
@@ -1756,11 +1855,27 @@ private final class CraftNativeMapView: MKMapView, MKMapViewDelegate {
1756
1855
  view.tintColor = color
1757
1856
  view.image = Self.markerImage(color: color, direction: true)
1758
1857
  view.transform = CGAffineTransform(rotationAngle: CGFloat((bearing - camera.heading) * .pi / 180))
1858
+ // Direction marks thin themselves: MapKit hides the ones that
1859
+ // would overlap at this zoom and brings them back closer in, so
1860
+ // a trail reads as a line with chevrons along it, not a column of
1861
+ // badges over the route.
1862
+ view.displayPriority = .defaultLow
1863
+ view.collisionMode = .circle
1864
+ // Decoration along the route: not a stop for VoiceOver.
1865
+ view.isAccessibilityElement = false
1759
1866
  } else {
1760
1867
  let color = (markerPinColors[id] ?? .systemRed).resolvedColor(with: traitCollection)
1761
1868
  view.tintColor = color
1762
1869
  view.image = Self.markerImage(color: color, direction: false)
1763
1870
  view.transform = .identity
1871
+ view.displayPriority = .required
1872
+ view.collisionMode = .rectangle
1873
+ // Above the user's own location: at a trailhead - where the map
1874
+ // is most often opened - the dot sat on the trail's pin and took
1875
+ // every tap meant for it.
1876
+ if #available(iOS 14.0, *) { view.zPriority = .max }
1877
+ view.isAccessibilityElement = true
1878
+ view.accessibilityTraits = .button
1764
1879
  }
1765
1880
  }
1766
1881
 
@@ -1771,9 +1886,10 @@ private final class CraftNativeMapView: MKMapView, MKMapViewDelegate {
1771
1886
  }()
1772
1887
 
1773
1888
  private static func markerImage(color: UIColor, direction: Bool) -> UIImage {
1774
- let key = "\(direction ? "direction" : "pin"):\(color.description)" as NSString
1889
+ let key = "\(direction ? "chevron" : "pin"):\(color.description)" as NSString
1775
1890
  if let cached = markerImages.object(forKey: key) { return cached }
1776
- let size = direction ? CGSize(width: 20, height: 24) : CGSize(width: 28, height: 28)
1891
+ if direction { return directionImage(color: color, key: key) }
1892
+ let size = CGSize(width: 28, height: 28)
1777
1893
  // Explicit native drawing preserves the light backing independently
1778
1894
  // of MapKit's tint and SF Symbols' multicolor rendering preferences.
1779
1895
  let image = UIGraphicsImageRenderer(size: size).image { _ in
@@ -1787,7 +1903,32 @@ private final class CraftNativeMapView: MKMapView, MKMapViewDelegate {
1787
1903
  let symbol = UIImage(systemName: direction ? "arrow.up" : "mappin",
1788
1904
  withConfiguration: UIImage.SymbolConfiguration(pointSize: 16, weight: .semibold))?
1789
1905
  .withTintColor(color, renderingMode: .alwaysOriginal)
1790
- symbol?.draw(in: direction ? CGRect(x: 5, y: 6, width: 10, height: 12) : CGRect(x: 7, y: 5, width: 14, height: 18))
1906
+ symbol?.draw(in: CGRect(x: 7, y: 5, width: 14, height: 18))
1907
+ }.withRenderingMode(.alwaysOriginal)
1908
+ markerImages.setObject(image, forKey: key)
1909
+ return image
1910
+ }
1911
+
1912
+ /// A route's direction: a 16-point chevron in the route's colour with a
1913
+ /// white edge, so it sits on the line it describes and stays legible
1914
+ /// over topography and imagery alike.
1915
+ private static func directionImage(color: UIColor, key: NSString) -> UIImage {
1916
+ let size = CGSize(width: 16, height: 16)
1917
+ let image = UIGraphicsImageRenderer(size: size).image { context in
1918
+ let chevron = UIBezierPath()
1919
+ chevron.move(to: CGPoint(x: 8, y: 2.5))
1920
+ chevron.addLine(to: CGPoint(x: 13.5, y: 12))
1921
+ chevron.addLine(to: CGPoint(x: 8, y: 9.25))
1922
+ chevron.addLine(to: CGPoint(x: 2.5, y: 12))
1923
+ chevron.close()
1924
+ chevron.lineJoinStyle = .round
1925
+ context.cgContext.setShadow(offset: .zero, blur: 1.5, color: UIColor.black.withAlphaComponent(0.25).cgColor)
1926
+ UIColor.white.setStroke()
1927
+ chevron.lineWidth = 3
1928
+ chevron.stroke()
1929
+ context.cgContext.setShadow(offset: .zero, blur: 0, color: nil)
1930
+ color.setFill()
1931
+ chevron.fill()
1791
1932
  }.withRenderingMode(.alwaysOriginal)
1792
1933
  markerImages.setObject(image, forKey: key)
1793
1934
  return image
@@ -1844,9 +1985,12 @@ private final class CraftNativeMapView: MKMapView, MKMapViewDelegate {
1844
1985
 
1845
1986
  func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
1846
1987
  guard let id = annotationsByID.first(where: { $0.value === annotation })?.key else { return nil }
1847
- let view = dequeueReusableAnnotationView(withIdentifier: "craft-native-marker")
1848
- ?? MKAnnotationView(annotation: annotation, reuseIdentifier: "craft-native-marker")
1988
+ let view = (dequeueReusableAnnotationView(withIdentifier: "craft-native-marker") as? CraftMarkerAnnotationView)
1989
+ ?? CraftMarkerAnnotationView(annotation: annotation, reuseIdentifier: "craft-native-marker")
1849
1990
  view.annotation = annotation
1991
+ // Activated (VoiceOver, Switch Control, a UI test) as a tap would:
1992
+ // the plain annotation view did nothing when activated.
1993
+ view.onActivate = { [weak self] in self?.onMarkerTap?(id) }
1850
1994
  configureMarkerView(view, id: id)
1851
1995
  view.accessibilityIdentifier = id
1852
1996
  return view
@@ -2164,6 +2308,13 @@ extension UIView {
2164
2308
  set { objc_setAssociatedObject(self, &craftNativeLayoutStyleKey, CraftNativeLayoutStyleBox(newValue), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) }
2165
2309
  }
2166
2310
 
2311
+ /// The margins this view's style asks for, for a container that places
2312
+ /// it without a flex parent (a FlatList cell).
2313
+ var craftLayoutMargins: UIEdgeInsets {
2314
+ let style = craftLayoutStyle
2315
+ return UIEdgeInsets(top: max(0, style.marginTop), left: max(0, style.marginLeft), bottom: max(0, style.marginBottom), right: max(0, style.marginRight))
2316
+ }
2317
+
2167
2318
  /// The corner radius the style asked for. The layer gets at most half the
2168
2319
  /// shortest side: Core Animation draws nothing at all for a radius larger
2169
2320
  /// than the view (`rounded-full` is 9999).
@@ -3991,6 +4142,16 @@ private final class CraftNativeModalView: UIView, UIGestureRecognizerDelegate {
3991
4142
  }
3992
4143
  }
3993
4144
 
4145
+ /// The delegate of a map's own tap (`Map`'s onPress): it watches beside
4146
+ /// MapKit's recognizers, so a tap on a pin still selects it.
4147
+ final class CraftMapTapDelegate: NSObject, UIGestureRecognizerDelegate {
4148
+ static let shared = CraftMapTapDelegate()
4149
+
4150
+ func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
4151
+ true
4152
+ }
4153
+ }
4154
+
3994
4155
  /// The delegate of a Pressable's press-in/out feedback. That recognizer is
3995
4156
  /// a long press of no duration, so it begins the moment a finger lands; on its
3996
4157
  /// own it would claim the touch, and the tap that is the Pressable's onPress
@@ -4328,9 +4489,13 @@ private final class CraftNativeScrollView: UIScrollView, UIGestureRecognizerDele
4328
4489
  /// 3 quadratic, 4 close, in viewBox units - and scaled to the view. Paint is
4329
4490
  /// inherited down the tree as SVG does; `dark:` classes arrive already
4330
4491
  /// resolved for the appearance, so a redraw is all a theme change needs.
4331
- private final class CraftNativeSvgView: UIView {
4492
+ final class CraftNativeSvgView: UIView {
4332
4493
  var drawing: [String: Any] = [:] {
4333
- didSet { setNeedsDisplay() }
4494
+ didSet {
4495
+ animates = Self.hasAnimation(drawing["children"] as? [Any] ?? [])
4496
+ setNeedsDisplay()
4497
+ updateFrames()
4498
+ }
4334
4499
  }
4335
4500
 
4336
4501
  override init(frame: CGRect) {
@@ -4338,10 +4503,123 @@ private final class CraftNativeSvgView: UIView {
4338
4503
  isOpaque = false
4339
4504
  backgroundColor = .clear
4340
4505
  contentMode = .redraw
4506
+ NotificationCenter.default.addObserver(self, selector: #selector(reduceMotionChanged), name: UIAccessibility.reduceMotionStatusDidChangeNotification, object: nil)
4341
4507
  }
4342
4508
 
4343
4509
  required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
4344
4510
 
4511
+ deinit { CraftNativeFrameClock.shared.cancel(self) }
4512
+
4513
+ // MARK: Animation
4514
+
4515
+ /// Whether a shape carries keyframes (SMIL `<animate attributeName="d">`,
4516
+ /// stx's `Animate`: an exercise's moving figure).
4517
+ private var animates = false
4518
+ /// When this drawing's repetition began: each one starts from its first
4519
+ /// pose when it comes on screen, as a page's SMIL starts when it loads.
4520
+ private var animationStart: CFTimeInterval?
4521
+
4522
+ /// Moving now: on display, and the person has not asked for less motion,
4523
+ /// when each shape keeps its own outline (the still pose).
4524
+ var isAnimating: Bool { animates && window != nil && !isHidden && !UIAccessibility.isReduceMotionEnabled }
4525
+
4526
+ override func didMoveToWindow() {
4527
+ super.didMoveToWindow()
4528
+ updateFrames()
4529
+ }
4530
+
4531
+ override var isHidden: Bool {
4532
+ didSet { if isHidden != oldValue { updateFrames() } }
4533
+ }
4534
+
4535
+ @objc private func reduceMotionChanged() {
4536
+ updateFrames()
4537
+ setNeedsDisplay()
4538
+ }
4539
+
4540
+ /// Frames from the screens' display link (CraftNativeFrameClock, up to
4541
+ /// 120Hz) while moving; none at all while still or out of sight.
4542
+ private func updateFrames() {
4543
+ if isAnimating {
4544
+ if animationStart == nil { animationStart = CACurrentMediaTime() }
4545
+ CraftNativeFrameClock.shared.request(self) { [weak self] in self?.nextFrame() }
4546
+ } else {
4547
+ animationStart = nil
4548
+ CraftNativeFrameClock.shared.cancel(self)
4549
+ }
4550
+ }
4551
+
4552
+ private func nextFrame() {
4553
+ guard isAnimating else { return updateFrames() }
4554
+ // Drawn only while some of it is on screen; a row scrolled away keeps
4555
+ // its time and is right when it comes back.
4556
+ if let window, window.bounds.intersects(convert(bounds, to: window)) { setNeedsDisplay() }
4557
+ CraftNativeFrameClock.shared.request(self) { [weak self] in self?.nextFrame() }
4558
+ }
4559
+
4560
+ private static func hasAnimation(_ children: [Any]) -> Bool {
4561
+ children.contains { child in
4562
+ guard let node = child as? [String: Any] else { return false }
4563
+ if node["type"] as? String == "Animate" { return (node["props"] as? [String: Any])?["frames"] != nil }
4564
+ return hasAnimation(node["children"] as? [Any] ?? [])
4565
+ }
4566
+ }
4567
+
4568
+ /// A shape's outline now: between the keyframes either side of `elapsed`
4569
+ /// seconds into its animation (SMIL's linear `calcMode`), or its own
4570
+ /// outline when it has none, the animation has ended, or motion is reduced.
4571
+ private func outline(of shape: [String: Any]) -> Any? {
4572
+ let geometry = (shape["props"] as? [String: Any])?["geometry"]
4573
+ guard isAnimating, let start = animationStart,
4574
+ let animate = (shape["children"] as? [Any])?.lazy.compactMap({ $0 as? [String: Any] }).first(where: { $0["type"] as? String == "Animate" }),
4575
+ let current = Self.keyframe(animate["props"] as? [String: Any] ?? [:], at: CACurrentMediaTime() - start) else { return geometry }
4576
+ return current
4577
+ }
4578
+
4579
+ /// The outline `elapsed` seconds into an `Animate`'s repetitions; nil
4580
+ /// when it does not animate path data or its repetitions are over.
4581
+ static func keyframe(_ props: [String: Any], at elapsed: CFTimeInterval) -> [Any]? {
4582
+ guard props["attributeName"] as? String == "d",
4583
+ let duration = number(props["duration"]), duration > 0, duration.isFinite,
4584
+ let frames = (props["frames"] as? [Any])?.compactMap({ ($0 as? [Any])?.compactMap(number) }),
4585
+ frames.count >= 2, elapsed >= 0 else { return nil }
4586
+ if let count = number(props["repeatCount"]), elapsed >= Double(count * duration) { return nil }
4587
+ let given = (props["frameTimes"] as? [Any])?.compactMap(number) ?? []
4588
+ let times = given.count == frames.count ? given : frames.indices.map { CGFloat($0) / CGFloat(frames.count - 1) }
4589
+ let phase = CGFloat(elapsed.truncatingRemainder(dividingBy: Double(duration))) / duration
4590
+ var index = 0
4591
+ while index < frames.count - 2, times[index + 1] <= phase { index += 1 }
4592
+ let from = frames[index]
4593
+ let to = frames[index + 1]
4594
+ let span = times[index + 1] - times[index]
4595
+ let share = span > 0 ? min(1, max(0, (phase - times[index]) / span)) : 0
4596
+ return interpolate(from, to, share).map { NSNumber(value: Double($0)) }
4597
+ }
4598
+
4599
+ /// Two outlines with the same commands, a share of the way from one to
4600
+ /// the other; the first as it is when their commands differ.
4601
+ static func interpolate(_ from: [CGFloat], _ to: [CGFloat], _ share: CGFloat) -> [CGFloat] {
4602
+ guard from.count == to.count, share > 0 else { return from }
4603
+ var out = from
4604
+ var i = 0
4605
+ while i < from.count {
4606
+ let command = Int(from[i])
4607
+ guard to[i] == from[i] else { return from }
4608
+ let count: Int
4609
+ switch command {
4610
+ case 0, 1: count = 2
4611
+ case 2: count = 6
4612
+ case 3: count = 4
4613
+ case 4: count = 0
4614
+ default: return from
4615
+ }
4616
+ guard i + count < from.count else { return from }
4617
+ if count > 0 { for k in 1...count { out[i + k] = from[i + k] + (to[i + k] - from[i + k]) * share } }
4618
+ i += count + 1
4619
+ }
4620
+ return out
4621
+ }
4622
+
4345
4623
  var viewBox: CGRect? {
4346
4624
  let props = drawing["props"] as? [String: Any] ?? [:]
4347
4625
  guard let box = props["viewBox"] as? [Any], box.count == 4 else { return nil }
@@ -4461,8 +4739,10 @@ private final class CraftNativeSvgView: UIView {
4461
4739
  draw(children: shape["children"] as? [Any] ?? [], paint: own, in: context)
4462
4740
  case "SvgText":
4463
4741
  drawText(shape, paint: own)
4742
+ case "Animate":
4743
+ continue
4464
4744
  default:
4465
- guard let path = CraftNativeSvgView.path((shape["props"] as? [String: Any])?["geometry"]) else { continue }
4745
+ guard let path = CraftNativeSvgView.path(outline(of: shape)) else { continue }
4466
4746
  context.saveGState()
4467
4747
  path.usesEvenOddFillRule = own.fillRule == "evenodd"
4468
4748
  if let fill = own.resolve(own.fill) {
@@ -4859,9 +5139,24 @@ enum CraftNativeScriptThread {
4859
5139
  static let queue = DispatchQueue(label: "craft.native.script", qos: .userInteractive)
4860
5140
 
4861
5141
  /// `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() }
5142
+ /// queued in order on the script thread. With frame pacing on
5143
+ /// (`CRAFT_FRAME_PACING=1`), work that waited or ran for 4ms or more is
5144
+ /// logged under `label`, so a slow screen can be told from a queued one.
5145
+ static func run(label: @autoclosure @escaping () -> String = "script", _ work: @escaping () -> Void) {
5146
+ let pacing = CraftFramePacing.shared
5147
+ guard pacing.enabled else {
5148
+ if isBackground { queue.async(execute: work) } else { work() }
5149
+ return
5150
+ }
5151
+ let queued = CACurrentMediaTime()
5152
+ let timed = {
5153
+ let started = CACurrentMediaTime()
5154
+ work()
5155
+ let ran = CACurrentMediaTime() - started
5156
+ let waited = started - queued
5157
+ if waited + ran >= 0.004 { pacing.scriptWork(label(), waited: waited, ran: ran) }
5158
+ }
5159
+ if isBackground { queue.async(execute: timed) } else { timed() }
4865
5160
  }
4866
5161
 
4867
5162
  /// From the script thread, `work` on the main thread, not waited for.
@@ -4954,6 +5249,17 @@ enum CraftNativeBundle {
4954
5249
  /// is not parsed again. Each screen keeps a global object of its own.
4955
5250
  static let virtualMachine = JSVirtualMachine()!
4956
5251
 
5252
+ /// JavaScriptCore's first machine and context, made on the script thread
5253
+ /// at launch instead of on the main thread by the first screen: that one-
5254
+ /// time setup was a quarter of a second of the first tab's mount, all of
5255
+ /// it in front of the first frame. Nothing is evaluated, so the main
5256
+ /// thread never waits on the machine for it.
5257
+ static func prewarm() {
5258
+ CraftNativeScriptThread.queue.async {
5259
+ _ = JSContext(virtualMachine: virtualMachine)
5260
+ }
5261
+ }
5262
+
4957
5263
  private static let sources: NSCache<NSString, NSString> = {
4958
5264
  let cache = NSCache<NSString, NSString>()
4959
5265
  // Room for the one-file bundle, or a dozen route files.
@@ -5241,7 +5547,7 @@ final class CraftNativeScreenController: UIViewController, UIScrollViewDelegate,
5241
5547
  let pacing = CraftFramePacing.shared
5242
5548
  let inputs = scriptInputs()
5243
5549
  let name = routeName ?? "screen"
5244
- CraftNativeScriptThread.run { [self] in
5550
+ CraftNativeScriptThread.run(label: "mount \(name)") { [self] in
5245
5551
  pacing.measure("mount \(name) setup") { setupJavaScript(inputs) }
5246
5552
  pacing.measure("mount \(name) bundle") { loadBundle() }
5247
5553
  }
@@ -5302,8 +5608,9 @@ final class CraftNativeScreenController: UIViewController, UIScrollViewDelegate,
5302
5608
  screenVisibilityChanged(false)
5303
5609
  stopCelebrations(in: view)
5304
5610
  // 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)
5611
+ // can disappear after the destination has already published its own;
5612
+ // released, it stays drawn until the destination says what it wants.
5613
+ CraftChrome.shared.releaseTabAccessory(ownedBy: self)
5307
5614
  // Popped (or its stack dismissed) while the bar was away: it comes
5308
5615
  // back for whatever shows next, a web page included.
5309
5616
  if tabBarHidden, isMovingFromParent || isBeingDismissed || navigationController?.isBeingDismissed == true {
@@ -5348,7 +5655,11 @@ final class CraftNativeScreenController: UIViewController, UIScrollViewDelegate,
5348
5655
  private func restoreShellChrome() {
5349
5656
  guard !isAppScript else { return }
5350
5657
  CraftChrome.shared.setHiddenByScreen(tabBarHidden)
5351
- CraftChrome.shared.updateTabAccessory(tabAccessory, owner: self)
5658
+ // A screen not yet asked about the accessory (one shown for the first
5659
+ // time, before its script has run) leaves the bar as it is; one that
5660
+ // has drawn without asking for it takes off what nobody claims.
5661
+ if tabAccessoryDeclared { CraftChrome.shared.updateTabAccessory(tabAccessory, owner: self) }
5662
+ else if hybridRendered { CraftChrome.shared.clearUnclaimedTabAccessory() }
5352
5663
  }
5353
5664
 
5354
5665
  /// `requestAnimationFrame`: the next display frame, for a screen on display
@@ -5365,7 +5676,8 @@ final class CraftNativeScreenController: UIViewController, UIScrollViewDelegate,
5365
5676
  guard frameWanted, !runtimeDisposed else { return }
5366
5677
  frameWanted = false
5367
5678
  let context = jsContext
5368
- CraftNativeScriptThread.run { context.objectForKeyedSubscript("__craftNativeFireFrame")?.call(withArguments: []) }
5679
+ let route = routeName ?? "screen"
5680
+ CraftNativeScriptThread.run(label: "frame \(route)") { context.objectForKeyedSubscript("__craftNativeFireFrame")?.call(withArguments: []) }
5369
5681
  }
5370
5682
 
5371
5683
  /// The screen came on screen or went off it: a screen pushed over it was
@@ -5400,7 +5712,8 @@ final class CraftNativeScreenController: UIViewController, UIScrollViewDelegate,
5400
5712
  routeProps = props
5401
5713
  guard isViewLoaded, !runtimeDisposed else { return }
5402
5714
  let context = jsContext
5403
- CraftNativeScriptThread.run {
5715
+ let route = routeName ?? "screen"
5716
+ CraftNativeScriptThread.run(label: "params \(route)") {
5404
5717
  context.setObject(params as NSDictionary, forKeyedSubscript: "__stxNativeParams" as NSString)
5405
5718
  context.setObject(props as NSDictionary, forKeyedSubscript: "__stxNativeProps" as NSString)
5406
5719
  }
@@ -5414,7 +5727,8 @@ final class CraftNativeScreenController: UIViewController, UIScrollViewDelegate,
5414
5727
  CraftNativeFrameClock.shared.cancel(self)
5415
5728
  disposeRenderedTree()
5416
5729
  let context = jsContext
5417
- CraftNativeScriptThread.run { context.objectForKeyedSubscript("__stxNativeUnmount")?.call(withArguments: []) }
5730
+ let route = routeName ?? "screen"
5731
+ CraftNativeScriptThread.run(label: "unmount \(route)") { context.objectForKeyedSubscript("__stxNativeUnmount")?.call(withArguments: []) }
5418
5732
  audio.close()
5419
5733
  sounds.close()
5420
5734
  streams.close()
@@ -6215,6 +6529,10 @@ final class CraftNativeScreenController: UIViewController, UIScrollViewDelegate,
6215
6529
  /// The app's tab bar away while this screen shows (`tabBarHidden`).
6216
6530
  private var tabBarHidden = false
6217
6531
  private var tabAccessory: [String: Any]?
6532
+ /// Whether the screen has said anything about the accessory yet
6533
+ /// (`tabAccessory`, null included): until it has, the bar keeps showing
6534
+ /// the one it had (CraftChrome.releaseTabAccessory).
6535
+ private var tabAccessoryDeclared = false
6218
6536
  /// Whether a back-swipe may leave this screen at all, the edge's
6219
6537
  /// included (`swipeBack: false`): a screen that steps through its own
6220
6538
  /// pages with a Back of its own (a first-run tour's questions) would
@@ -6263,6 +6581,7 @@ final class CraftNativeScreenController: UIViewController, UIScrollViewDelegate,
6263
6581
  guard !isAppScript else { return }
6264
6582
  if options.keys.contains("tabAccessory") {
6265
6583
  tabAccessory = options["tabAccessory"] as? [String: Any]
6584
+ tabAccessoryDeclared = true
6266
6585
  if navigationController?.topViewController === self, view.window != nil {
6267
6586
  CraftChrome.shared.updateTabAccessory(tabAccessory, owner: self)
6268
6587
  }
@@ -6652,7 +6971,7 @@ final class CraftNativeScreenController: UIViewController, UIScrollViewDelegate,
6652
6971
  let previous = info["previous"] as? String
6653
6972
  self.send(type: "SESSION_CHANGED", payload: ["key": key, "token": token ?? NSNull(), "previous": previous ?? NSNull()])
6654
6973
  let context = self.jsContext
6655
- CraftNativeScriptThread.run { context.objectForKeyedSubscript("__craftSessionChanged")?.call(withArguments: [token ?? NSNull(), previous ?? NSNull()]) }
6974
+ CraftNativeScriptThread.run(label: "session \(self.routeName ?? "screen")") { context.objectForKeyedSubscript("__craftSessionChanged")?.call(withArguments: [token ?? NSNull(), previous ?? NSNull()]) }
6656
6975
  })
6657
6976
  }
6658
6977
  if config.enablePushNotifications {
@@ -6937,8 +7256,15 @@ final class CraftNativeScreenController: UIViewController, UIScrollViewDelegate,
6937
7256
  }
6938
7257
  let module = payload["module"] as? String ?? ""
6939
7258
  let method = payload["method"] as? String ?? ""
7259
+ // With frame pacing on: how long the capability took to answer,
7260
+ // which a screen's script waits on (a request, the keychain).
7261
+ let pacing = CraftFramePacing.shared
7262
+ let asked = pacing.enabled ? CACurrentMediaTime() : 0
7263
+ let route = routeName ?? "screen"
7264
+ let what = module == "Network" ? "\(module).\(method) \(((args.first as? [String: Any])?["url"] as? String).flatMap { URL(string: $0)?.path } ?? "")" : "\(module).\(method)"
6940
7265
  let reply: (Result<Any, CraftNativeActionError>) -> Void = { [weak self] answer in
6941
7266
  guard let self = self, self.pendingCapabilityRequests.remove(requestToken) != nil else { return }
7267
+ if pacing.enabled { pacing.capability("\(what) \(route)", took: CACurrentMediaTime() - asked) }
6942
7268
  self.pendingCapabilityDeadlines.removeValue(forKey: requestToken)?.cancel()
6943
7269
  self.screenRequestCancellers.removeValue(forKey: requestToken)
6944
7270
  switch answer {
@@ -7167,6 +7493,8 @@ final class CraftNativeScreenController: UIViewController, UIScrollViewDelegate,
7167
7493
  hybridRendered = true
7168
7494
  // The app script's drawing is never on screen: not a first frame.
7169
7495
  if !isAppScript { hybridEvents?.nativeScreenDidRender(self) }
7496
+ // Drawn without a word about the accessory: it wants none.
7497
+ if !isAppScript, !tabAccessoryDeclared, isShownOnScreen { CraftChrome.shared.clearUnclaimedTabAccessory() }
7170
7498
  let waiting = renderWaiters
7171
7499
  renderWaiters.removeAll()
7172
7500
  waiting.forEach { $0() }
@@ -8486,8 +8814,12 @@ final class CraftNativeScreenController: UIViewController, UIScrollViewDelegate,
8486
8814
  /// Views that take their own touches whatever handlers the screen gives
8487
8815
  /// them: native controls, a scroll view, a modal, and a video's controls (with
8488
8816
  /// interaction off, its play, scrubber and full screen never answered).
8817
+ /// A map and a wheel picker too: neither is a UIControl, so a map with no
8818
+ /// long-press handler - every map - was made non-interactive, and could
8819
+ /// not be panned, zoomed, or have a pin tapped; a picker could not be spun.
8489
8820
  private func ownsTouches(_ view: UIView) -> Bool {
8490
8821
  view is UIControl || view is UIScrollView || view is CraftNativeModalView || view is CraftNativeVideoView
8822
+ || view is MKMapView || view is UIPickerView
8491
8823
  }
8492
8824
 
8493
8825
  private func updatePressHandler(_ handler: String?, for view: UIView) {
@@ -9832,7 +10164,8 @@ final class CraftNativeScreenController: UIViewController, UIScrollViewDelegate,
9832
10164
  guard let data = try? JSONSerialization.data(withJSONObject: message),
9833
10165
  let json = String(data: data, encoding: .utf8) else { return }
9834
10166
  let context = jsContext
9835
- CraftNativeScriptThread.run { context.objectForKeyedSubscript("__stxNativeCallback")?.call(withArguments: [json]) }
10167
+ let route = routeName ?? "screen"
10168
+ CraftNativeScriptThread.run(label: "\(type) \(route)") { context.objectForKeyedSubscript("__stxNativeCallback")?.call(withArguments: [json]) }
9836
10169
  }
9837
10170
 
9838
10171
  private func number(_ value: Any?) -> CGFloat? {
@@ -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
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "craft-native",
3
- "version": "0.0.262",
3
+ "version": "0.0.276",
4
4
  "type": "module",
5
5
  "description": "Build desktop apps with web languages - TypeScript SDK for Craft",
6
6
  "author": "Chris Breuer <chris@stacksjs.org>",