@craft-native/ios 0.0.272 → 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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@craft-native/ios",
3
- "version": "0.0.272",
3
+ "version": "0.0.276",
4
4
  "homepage": "https://github.com/craft-native/craft/tree/main/packages/ios#readme",
5
5
  "repository": {
6
6
  "type": "git",
@@ -357,6 +357,7 @@ final class CraftHybrid: NSObject {
357
357
  isConfigured = true
358
358
  self.config = config
359
359
  CraftNativeScriptThread.isBackground = config.nativeScriptThread == "background"
360
+ if CraftNativeScriptThread.isBackground { CraftNativeBundle.prewarm() }
360
361
  hasWeb = config.renderer != "native"
361
362
  siteURL = config.devServerURL.flatMap(URL.init(string:)).flatMap { url in
362
363
  ["http", "https"].contains((url.scheme ?? "").lowercased()) ? url : nil
@@ -2295,13 +2296,15 @@ final class CraftFramePacing: NSObject {
2295
2296
  }
2296
2297
  }
2297
2298
 
2298
- /// One main-thread block, timed: a screen mount, a bundle evaluation.
2299
+ /// One block, timed: a screen mount, a bundle evaluation. Labelled by the
2300
+ /// thread it ran on, since a screen's script now runs off the main thread
2301
+ /// and a bundle's time there costs no frames.
2299
2302
  @discardableResult
2300
2303
  func measure<T>(_ name: String, _ work: () -> T) -> T {
2301
2304
  guard enabled else { return work() }
2302
2305
  let started = CACurrentMediaTime()
2303
2306
  let result = work()
2304
- write(String(format: "%@ main=%.1fms", name, (CACurrentMediaTime() - started) * 1000))
2307
+ write(String(format: "%@ %@=%.1fms", name, Thread.isMainThread ? "main" : "script", (CACurrentMediaTime() - started) * 1000))
2305
2308
  return result
2306
2309
  }
2307
2310
 
@@ -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
@@ -3998,6 +4142,16 @@ private final class CraftNativeModalView: UIView, UIGestureRecognizerDelegate {
3998
4142
  }
3999
4143
  }
4000
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
+
4001
4155
  /// The delegate of a Pressable's press-in/out feedback. That recognizer is
4002
4156
  /// a long press of no duration, so it begins the moment a finger lands; on its
4003
4157
  /// own it would claim the touch, and the tap that is the Pressable's onPress
@@ -5095,6 +5249,17 @@ enum CraftNativeBundle {
5095
5249
  /// is not parsed again. Each screen keeps a global object of its own.
5096
5250
  static let virtualMachine = JSVirtualMachine()!
5097
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
+
5098
5263
  private static let sources: NSCache<NSString, NSString> = {
5099
5264
  let cache = NSCache<NSString, NSString>()
5100
5265
  // Room for the one-file bundle, or a dozen route files.
@@ -8649,8 +8814,12 @@ final class CraftNativeScreenController: UIViewController, UIScrollViewDelegate,
8649
8814
  /// Views that take their own touches whatever handlers the screen gives
8650
8815
  /// them: native controls, a scroll view, a modal, and a video's controls (with
8651
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.
8652
8820
  private func ownsTouches(_ view: UIView) -> Bool {
8653
8821
  view is UIControl || view is UIScrollView || view is CraftNativeModalView || view is CraftNativeVideoView
8822
+ || view is MKMapView || view is UIPickerView
8654
8823
  }
8655
8824
 
8656
8825
  private func updatePressHandler(_ handler: String?, for view: UIView) {