@craft-native/ios 0.0.238 → 0.0.241

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/dist/index.js CHANGED
@@ -228,10 +228,18 @@ function serializeSimulatorSteps(steps) {
228
228
  if (!Number.isInteger(number(step.index)))
229
229
  throw new Error("field index must be an integer");
230
230
  arg = `${step.index} ${step.text}`;
231
+ } else if ("position" in step) {
232
+ if (number(step.position) > 1)
233
+ throw new Error("Slider position must be between 0 and 1");
234
+ arg = `${token(step.id)} ${step.position}`;
231
235
  } else if ("id" in step)
232
236
  arg = `${token(step.id)} ${step.text}`;
233
237
  else if ("text" in step) {
234
238
  arg = step.text;
239
+ if (step.command === "longpressid")
240
+ token(arg);
241
+ if (step.command === "expectapp" && !/^[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+$/.test(arg))
242
+ throw new Error("Expected an application bundle identifier");
235
243
  if ("seconds" in step && step.seconds !== undefined) {
236
244
  if (arg.includes("|"))
237
245
  throw new Error("A timed expectation cannot contain |");
package/dist/testing.d.ts CHANGED
@@ -66,15 +66,27 @@ export type SimulatorStep = {
66
66
  index: number;
67
67
  text: string;
68
68
  } | {
69
- command: 'typeid' | 'labelid';
69
+ command: 'typeid' | 'labelid' | 'valueid';
70
70
  id: string;
71
71
  text: string;
72
+ }
73
+ /** Adjust an actual native UISlider by identifier, using its normalized range. */
74
+ | {
75
+ command: 'sliderid';
76
+ id: string;
77
+ position: number;
78
+ }
79
+ /** Assert a handoff reached the foreground application without launching it. */
80
+ | {
81
+ command: 'expectapp';
82
+ text: string;
83
+ seconds?: number;
72
84
  } | {
73
85
  command: 'expect' | 'expectexact' | 'expectid' | 'systemexpect';
74
86
  text: string;
75
87
  seconds?: number;
76
88
  } | {
77
- command: 'tap' | 'tapif' | 'tapid' | 'tapexact' | 'type' | 'absent' | 'absentid' | 'selected' | 'tab' | 'scrollto' | 'dismiss' | 'log' | 'systemtap' | 'systemabsent';
89
+ command: 'tap' | 'tapif' | 'tapid' | 'longpressid' | 'tapexact' | 'type' | 'absent' | 'absentid' | 'selected' | 'tab' | 'scrollto' | 'dismiss' | 'log' | 'systemtap' | 'systemabsent';
78
90
  text: string;
79
91
  } | {
80
92
  command: 'shot' | 'tree' | 'audit' | 'exec' | 'systemtree';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@craft-native/ios",
3
- "version": "0.0.238",
3
+ "version": "0.0.241",
4
4
  "homepage": "https://github.com/craft-native/craft/tree/main/packages/ios#readme",
5
5
  "repository": {
6
6
  "type": "git",
@@ -1991,6 +1991,9 @@ struct CraftWebView: UIViewRepresentable {
1991
1991
  private var locationManager: CLLocationManager?
1992
1992
  private var singleLocationCallbackId: String?
1993
1993
  private var singleLocationTimeoutWorkItem: DispatchWorkItem?
1994
+ private var singleLocationTimeoutMilliseconds: Double = 30_000
1995
+ private var singleLocationAcquisitionStarted = false
1996
+ private var singleLocationAuthorizationRequested = false
1994
1997
  private var locationPermissionCallbackId: String?
1995
1998
  private var locationPermissionRequiresAlways = false
1996
1999
  private var isWatchingLocation = false
@@ -2065,7 +2068,7 @@ struct CraftWebView: UIViewRepresentable {
2065
2068
  // SQLite database
2066
2069
  private var db: OpaquePointer?
2067
2070
 
2068
- init(config: CraftConfig, recordingDirectory: URL? = nil) {
2071
+ init(config: CraftConfig, locationManager suppliedLocationManager: CLLocationManager? = nil, recordingDirectory: URL? = nil) {
2069
2072
  self.recordingDirectory = recordingDirectory
2070
2073
  self.config = config
2071
2074
  super.init()
@@ -2073,7 +2076,7 @@ struct CraftWebView: UIViewRepresentable {
2073
2076
  speechRecognizer = SFSpeechRecognizer(locale: Locale(identifier: "en-US"))
2074
2077
  }
2075
2078
  if config.enableGeolocation {
2076
- locationManager = CLLocationManager()
2079
+ locationManager = suppliedLocationManager ?? CLLocationManager()
2077
2080
  locationManager?.desiredAccuracy = kCLLocationAccuracyBest
2078
2081
  locationManager?.activityType = .fitness
2079
2082
  locationManager?.pausesLocationUpdatesAutomatically = false
@@ -6400,7 +6403,7 @@ struct CraftWebView: UIViewRepresentable {
6400
6403
  }
6401
6404
  singleLocationCallbackId = callbackId
6402
6405
  let maximumAge = max(0, (body["maximumAge"] as? NSNumber)?.doubleValue ?? 0)
6403
- if maximumAge > 0,
6406
+ if (manager.authorizationStatus == .authorizedAlways || manager.authorizationStatus == .authorizedWhenInUse), maximumAge > 0,
6404
6407
  let cachedLocation = manager.location,
6405
6408
  max(0, Date().timeIntervalSince(cachedLocation.timestamp) * 1000) <= maximumAge {
6406
6409
  finishSingleLocationRequest()
@@ -6408,7 +6411,35 @@ struct CraftWebView: UIViewRepresentable {
6408
6411
  return
6409
6412
  }
6410
6413
 
6411
- let timeoutMs = max(0, (body["timeout"] as? NSNumber)?.doubleValue ?? 30_000)
6414
+ singleLocationTimeoutMilliseconds = max(0, (body["timeout"] as? NSNumber)?.doubleValue ?? 30_000)
6415
+ continueSingleLocationRequest(manager)
6416
+ }
6417
+
6418
+ private func continueSingleLocationRequest(_ manager: CLLocationManager) {
6419
+ guard let callbackId = singleLocationCallbackId else { return }
6420
+ switch manager.authorizationStatus {
6421
+ case .notDetermined:
6422
+ if !singleLocationAuthorizationRequested {
6423
+ singleLocationAuthorizationRequested = true
6424
+ manager.requestWhenInUseAuthorization()
6425
+ }
6426
+ return
6427
+ case .denied, .restricted:
6428
+ finishSingleLocationRequest()
6429
+ rejectCallback(callbackId, error: "Location permission was denied.", code: "PERMISSION_DENIED")
6430
+ return
6431
+ case .authorizedAlways, .authorizedWhenInUse:
6432
+ break
6433
+ @unknown default:
6434
+ finishSingleLocationRequest()
6435
+ rejectCallback(callbackId, error: "Location authorization is unavailable.", code: "PERMISSION_DENIED")
6436
+ return
6437
+ }
6438
+ guard !singleLocationAcquisitionStarted else { return }
6439
+ singleLocationAcquisitionStarted = true
6440
+ // The acquisition timeout starts after the person decides. A
6441
+ // permission sheet is not a failed or timed-out GPS fix.
6442
+ let timeoutMs = singleLocationTimeoutMilliseconds
6412
6443
  let timeoutWorkItem = DispatchWorkItem { [weak self] in
6413
6444
  guard let self, self.singleLocationCallbackId == callbackId else { return }
6414
6445
  self.finishSingleLocationRequest()
@@ -6416,7 +6447,6 @@ struct CraftWebView: UIViewRepresentable {
6416
6447
  }
6417
6448
  singleLocationTimeoutWorkItem = timeoutWorkItem
6418
6449
  DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(Int(min(timeoutMs + 100, Double(Int.max)))), execute: timeoutWorkItem)
6419
- requestLocationAuthorization()
6420
6450
  manager.requestLocation()
6421
6451
  }
6422
6452
 
@@ -6424,6 +6454,8 @@ struct CraftWebView: UIViewRepresentable {
6424
6454
  singleLocationTimeoutWorkItem?.cancel()
6425
6455
  singleLocationTimeoutWorkItem = nil
6426
6456
  singleLocationCallbackId = nil
6457
+ singleLocationAcquisitionStarted = false
6458
+ singleLocationAuthorizationRequested = false
6427
6459
  locationManager?.desiredAccuracy = kCLLocationAccuracyBest
6428
6460
  }
6429
6461
 
@@ -6753,6 +6785,10 @@ struct CraftWebView: UIViewRepresentable {
6753
6785
 
6754
6786
  func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
6755
6787
  let nativeError = error as NSError
6788
+ if nativeError.domain == kCLErrorDomain, nativeError.code == CLError.Code.denied.rawValue,
6789
+ manager.authorizationStatus == .notDetermined, singleLocationCallbackId != nil, !singleLocationAcquisitionStarted {
6790
+ return
6791
+ }
6756
6792
  // kCLErrorLocationUnknown is Core Location saying it has no fix
6757
6793
  // *yet*, not that it failed. requestLocation gives up on it, so a
6758
6794
  // one-shot asks again shortly instead of failing a caller whose
@@ -6761,7 +6797,7 @@ struct CraftWebView: UIViewRepresentable {
6761
6797
  if nativeError.domain == kCLErrorDomain && nativeError.code == CLError.Code.locationUnknown.rawValue {
6762
6798
  if let waiting = singleLocationCallbackId {
6763
6799
  DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1)) { [weak self] in
6764
- guard let self, self.singleLocationCallbackId == waiting else { return }
6800
+ guard let self, self.singleLocationCallbackId == waiting, self.singleLocationAcquisitionStarted else { return }
6765
6801
  self.locationManager?.requestLocation()
6766
6802
  }
6767
6803
  }
@@ -6777,6 +6813,7 @@ struct CraftWebView: UIViewRepresentable {
6777
6813
  }
6778
6814
 
6779
6815
  func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
6816
+ if singleLocationCallbackId != nil { continueSingleLocationRequest(manager) }
6780
6817
  guard let callbackId = locationPermissionCallbackId else { return }
6781
6818
  let status = manager.authorizationStatus
6782
6819
  if status == .notDetermined { return }
@@ -139,7 +139,7 @@ private enum CraftNativeTreeLayoutBridge {
139
139
  var alignItems: UInt32 = 3
140
140
  var alignSelf: UInt32 = 0
141
141
  var flexWrap: UInt32 = 0
142
- var alignContent: UInt32 = 6
142
+ var alignContent: UInt32 = 5
143
143
  var marginTop: Float = 0
144
144
  var marginRight: Float = 0
145
145
  var marginBottom: Float = 0
@@ -180,7 +180,7 @@ private enum CraftNativeTreeLayoutBridge {
180
180
  var alignItems: UInt32 = 3
181
181
  var alignSelf: UInt32 = 0
182
182
  var flexWrap: UInt32 = 0
183
- var alignContent: UInt32 = 6
183
+ var alignContent: UInt32 = 5
184
184
  var marginTop: Float = 0
185
185
  var marginRight: Float = 0
186
186
  var marginBottom: Float = 0
@@ -222,7 +222,7 @@ private enum CraftNativeTreeLayoutBridge {
222
222
  var alignItems: UInt32 = 3
223
223
  var alignSelf: UInt32 = 0
224
224
  var flexWrap: UInt32 = 0
225
- var alignContent: UInt32 = 6
225
+ var alignContent: UInt32 = 5
226
226
  var marginTop: Float = 0
227
227
  var marginRight: Float = 0
228
228
  var marginBottom: Float = 0
@@ -1171,8 +1171,10 @@ private final class CraftNativeMapView: MKMapView, MKMapViewDelegate {
1171
1171
  private var authoredHeading: Double?
1172
1172
  private var edgePadding = UIEdgeInsets(top: 24, left: 24, bottom: 24, right: 24)
1173
1173
  private var markerBearings: [String: Double] = [:]
1174
+ private var markerPinColors: [String: UIColor] = [:]
1174
1175
  private var tileOverlay: MKTileOverlay?
1175
1176
  private var tileTemplate: String?
1177
+ private var tileAttributionBottom: NSLayoutConstraint?
1176
1178
  private lazy var tileAttribution: UILabel = {
1177
1179
  let label = UILabel()
1178
1180
  label.font = .systemFont(ofSize: 9)
@@ -1181,7 +1183,9 @@ private final class CraftNativeMapView: MKMapView, MKMapViewDelegate {
1181
1183
  label.translatesAutoresizingMaskIntoConstraints = false
1182
1184
  label.numberOfLines = 2
1183
1185
  addSubview(label)
1184
- NSLayoutConstraint.activate([label.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -8), label.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -8), label.leadingAnchor.constraint(greaterThanOrEqualTo: leadingAnchor, constant: 48)])
1186
+ let bottom = label.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -8)
1187
+ tileAttributionBottom = bottom
1188
+ NSLayoutConstraint.activate([label.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -8), bottom, label.leadingAnchor.constraint(greaterThanOrEqualTo: leadingAnchor, constant: 48)])
1185
1189
  return label
1186
1190
  }()
1187
1191
 
@@ -1206,6 +1210,7 @@ private final class CraftNativeMapView: MKMapView, MKMapViewDelegate {
1206
1210
  isScrollEnabled = props["scrollEnabled"] as? Bool ?? true
1207
1211
  isZoomEnabled = props["zoomEnabled"] as? Bool ?? true
1208
1212
  isRotateEnabled = props["rotateEnabled"] as? Bool ?? false
1213
+ isPitchEnabled = props["pitchEnabled"] as? Bool ?? true
1209
1214
  mapType = Self.mapType(props["mapType"] as? String)
1210
1215
  configureTiles(props["tileOverlay"] as? [String: Any])
1211
1216
  showsCompass = props["showsCompass"] as? Bool ?? false
@@ -1219,6 +1224,7 @@ private final class CraftNativeMapView: MKMapView, MKMapViewDelegate {
1219
1224
  }
1220
1225
  edgePadding = UIEdgeInsets(top: inset("top"), left: inset("left"), bottom: inset("bottom"), right: inset("right"))
1221
1226
  var nextBearings: [String: Double] = [:]
1227
+ var nextPinColors: [String: UIColor] = [:]
1222
1228
  // Showing the user dot must not trigger a permission prompt from a
1223
1229
  // renderer pass. The app's existing location capability owns that
1224
1230
  // prompt; a map only opts in after authorization is already granted.
@@ -1227,6 +1233,7 @@ private final class CraftNativeMapView: MKMapView, MKMapViewDelegate {
1227
1233
  var nextMarkers: [String: (coordinate: CLLocationCoordinate2D, title: String?)] = [:]
1228
1234
  var nextHandlers: [String: String] = [:]
1229
1235
  var nextPolylines: [String: (coordinates: [CLLocationCoordinate2D], color: UIColor, width: CGFloat)] = [:]
1236
+ var nextPolylineIDs: [String] = []
1230
1237
  for (index, child) in children.enumerated() {
1231
1238
  guard let node = child as? [String: Any], let rawType = node["type"] as? String else { continue }
1232
1239
  let type = rawType.lowercased()
@@ -1239,6 +1246,7 @@ private final class CraftNativeMapView: MKMapView, MKMapViewDelegate {
1239
1246
  if type == "mapmarker" || type == "marker" {
1240
1247
  guard let point = points.first else { continue }
1241
1248
  nextMarkers[id] = (point, childProps["title"] as? String)
1249
+ if let color = childProps["pinColor"] as? String { nextPinColors[id] = Self.color(color) }
1242
1250
  if let bearing = Self.numeric(childProps["bearing"]), bearing.isFinite {
1243
1251
  nextBearings[id] = bearing.truncatingRemainder(dividingBy: 360)
1244
1252
  }
@@ -1251,11 +1259,13 @@ private final class CraftNativeMapView: MKMapView, MKMapViewDelegate {
1251
1259
  let authoredWidth = Self.numeric(childProps["strokeWidth"]) ?? 3
1252
1260
  let width = CGFloat(authoredWidth)
1253
1261
  guard authoredWidth.isFinite, width.isFinite, width > 0 else { continue }
1262
+ if nextPolylines[id] == nil { nextPolylineIDs.append(id) }
1254
1263
  nextPolylines[id] = (points, Self.color(childProps["strokeColor"] as? String), width)
1255
1264
  }
1256
1265
  }
1257
1266
 
1258
1267
  markerBearings = nextBearings
1268
+ markerPinColors = nextPinColors
1259
1269
  let staleMarkers = annotationsByID.keys.filter { nextMarkers[$0] == nil }
1260
1270
  removeAnnotations(staleMarkers.compactMap { annotationsByID.removeValue(forKey: $0) })
1261
1271
  for (id, value) in nextMarkers {
@@ -1282,7 +1292,8 @@ private final class CraftNativeMapView: MKMapView, MKMapViewDelegate {
1282
1292
  }
1283
1293
  overlayCoordinatesByID.removeValue(forKey: id)
1284
1294
  }
1285
- for (id, value) in nextPolylines {
1295
+ for id in nextPolylineIDs {
1296
+ guard let value = nextPolylines[id] else { continue }
1286
1297
  if let overlay = overlaysByID[id],
1287
1298
  let coordinates = overlayCoordinatesByID[id],
1288
1299
  Self.coordinatesEqual(coordinates, value.coordinates),
@@ -1302,6 +1313,19 @@ private final class CraftNativeMapView: MKMapView, MKMapViewDelegate {
1302
1313
  overlayWidths[ObjectIdentifier(overlay)] = value.width
1303
1314
  addOverlay(overlay)
1304
1315
  }
1316
+ // Keep authored casing/foreground order when an earlier line changes
1317
+ // or retained children move. Exchanging native overlays preserves the
1318
+ // unchanged objects, tile levels and current camera.
1319
+ let ownedOverlayIDs = Set(overlaysByID.values.map { ObjectIdentifier($0) })
1320
+ var orderedOverlays = overlays.compactMap { $0 as? MKPolyline }
1321
+ .filter { ownedOverlayIDs.contains(ObjectIdentifier($0)) }
1322
+ for (index, id) in nextPolylineIDs.enumerated() {
1323
+ guard let overlay = overlaysByID[id], index < orderedOverlays.count,
1324
+ orderedOverlays[index] !== overlay,
1325
+ let previousIndex = orderedOverlays.firstIndex(where: { $0 === overlay }) else { continue }
1326
+ exchangeOverlay(orderedOverlays[index], with: orderedOverlays[previousIndex])
1327
+ orderedOverlays.swapAt(index, previousIndex)
1328
+ }
1305
1329
 
1306
1330
  if let region = Self.region(props["region"]) {
1307
1331
  // `region` is controlled: an authored change is allowed to move
@@ -1411,20 +1435,27 @@ private final class CraftNativeMapView: MKMapView, MKMapViewDelegate {
1411
1435
 
1412
1436
  private func configureMarkerView(_ view: MKAnnotationView, id: String) {
1413
1437
  if let bearing = markerBearings[id] {
1414
- let configuration = UIImage.SymbolConfiguration(pointSize: 24, weight: .semibold)
1438
+ let configuration = UIImage.SymbolConfiguration(pointSize: 16, weight: .semibold)
1415
1439
  .applying(UIImage.SymbolConfiguration(paletteColors: [.white, .systemGreen]))
1416
- view.image = UIImage(systemName: "arrow.up.circle.fill", withConfiguration: configuration)
1440
+ // MapKit otherwise tints this as a monochrome template and loses
1441
+ // the contrasting route arrow when displayed over map content.
1442
+ view.image = UIImage(systemName: "arrow.up.circle.fill", withConfiguration: configuration)?
1443
+ .withRenderingMode(.alwaysOriginal)
1417
1444
  view.transform = CGAffineTransform(rotationAngle: CGFloat((bearing - camera.heading) * .pi / 180))
1418
1445
  } else {
1446
+ view.tintColor = markerPinColors[id] ?? .systemRed
1419
1447
  view.image = UIImage(systemName: "mappin.circle.fill", withConfiguration: UIImage.SymbolConfiguration(pointSize: 28))?
1420
- .withTintColor(.systemRed, renderingMode: .alwaysOriginal)
1448
+ .withTintColor(view.tintColor, renderingMode: .alwaysOriginal)
1421
1449
  view.transform = .identity
1422
1450
  }
1423
1451
  }
1424
1452
 
1425
1453
  override func layoutSubviews() {
1426
1454
  super.layoutSubviews()
1427
- if tileTemplate != nil { bringSubviewToFront(tileAttribution) }
1455
+ if tileTemplate != nil {
1456
+ tileAttributionBottom?.constant = -min(edgePadding.bottom, max(0, bounds.height - 40)) - 8
1457
+ bringSubviewToFront(tileAttribution)
1458
+ }
1428
1459
  if let region = pendingRegion, bounds.width > 0, bounds.height > 0 {
1429
1460
  pendingRegion = nil
1430
1461
  setRegion(region, animated: false)
@@ -2681,11 +2712,24 @@ private class CraftNativeFlowView: UIStackView {
2681
2712
  var fixedHeight = style.top != nil && style.bottom != nil
2682
2713
  ? max(0, content.height - (style.top ?? 0) - (style.bottom ?? 0))
2683
2714
  : style.height?.resolve(content.height)
2715
+ let authoredWidth = fixedWidth != nil
2716
+ let authoredHeight = fixedHeight != nil
2684
2717
  (fixedWidth, fixedHeight) = aspectDimensions(style, width: fixedWidth, height: fixedHeight)
2685
- let measured = CraftNativeFlexLayout.measure(child, width: fixedWidth, height: fixedHeight, maxWidth: content.width, maxHeight: content.height)
2686
- let x = style.left ?? (style.right.map { content.width - $0 - measured.width } ?? 0)
2687
- let y = style.top ?? (style.bottom.map { content.height - $0 - measured.height } ?? 0)
2688
- frames.append((child, CGRect(x: content.minX + x, y: content.minY + y, width: measured.width, height: measured.height)))
2718
+ var measured = CraftNativeFlexLayout.measure(child, width: fixedWidth, height: fixedHeight, maxWidth: content.width, maxHeight: content.height)
2719
+ var boundedWidth = clamp(measured.width, style.minWidth?.resolve(content.width), style.maxWidth?.resolve(content.width))
2720
+ let proposedHeight = !authoredHeight && style.aspectRatio != nil ? boundedWidth / style.aspectRatio! : fixedHeight
2721
+ if abs(boundedWidth - measured.width) > 0.0001 || proposedHeight != fixedHeight {
2722
+ // A narrower label or container must wrap before its
2723
+ // height and bottom anchor are resolved.
2724
+ measured = CraftNativeFlexLayout.measure(child, width: boundedWidth, height: proposedHeight, maxWidth: content.width, maxHeight: content.height)
2725
+ }
2726
+ let boundedHeight = clamp(measured.height, style.minHeight?.resolve(content.height), style.maxHeight?.resolve(content.height))
2727
+ if !authoredWidth, authoredHeight, let ratio = style.aspectRatio {
2728
+ boundedWidth = clamp(boundedHeight * ratio, style.minWidth?.resolve(content.width), style.maxWidth?.resolve(content.width))
2729
+ }
2730
+ let x = style.left ?? (style.right.map { content.width - $0 - boundedWidth } ?? 0)
2731
+ let y = style.top ?? (style.bottom.map { content.height - $0 - boundedHeight } ?? 0)
2732
+ frames.append((child, CGRect(x: content.minX + x, y: content.minY + y, width: boundedWidth, height: boundedHeight)))
2689
2733
  }
2690
2734
  }
2691
2735
  return (size, frames)
@@ -3370,6 +3414,8 @@ private final class CraftNativeModalView: UIView {
3370
3414
  let generation = animationGeneration
3371
3415
  layer.removeAllAnimations()
3372
3416
  guard visible else {
3417
+ craftScreenController?.forgetFocusedInput(in: self)
3418
+ endEditing(true)
3373
3419
  if animationType == "slide" && wasVisible {
3374
3420
  let distance = max(bounds.height, superview?.bounds.height ?? UIScreen.main.bounds.height)
3375
3421
  UIView.animate(withDuration: 0.24, animations: {
@@ -3409,6 +3455,8 @@ private final class CraftNativeModalView: UIView {
3409
3455
  }
3410
3456
 
3411
3457
  func resetForTeardown() {
3458
+ craftScreenController?.forgetFocusedInput(in: self)
3459
+ endEditing(true)
3412
3460
  animationGeneration += 1
3413
3461
  layer.removeAllAnimations()
3414
3462
  isHidden = true
@@ -4326,6 +4374,11 @@ final class CraftNativeScreenController: UIViewController, UIScrollViewDelegate,
4326
4374
  func forgetFocusedInput(_ input: UIView? = nil) {
4327
4375
  if input == nil || lastFocusedInput === input { lastFocusedInput = nil }
4328
4376
  }
4377
+ func forgetFocusedInput(in container: UIView) {
4378
+ if let input = lastFocusedInput, input === container || input.isDescendant(of: container) {
4379
+ lastFocusedInput = nil
4380
+ }
4381
+ }
4329
4382
  private var flatListRows: [ObjectIdentifier: [String: RenderedNode]] = [:]
4330
4383
  private var flatListOwners: [String: String] = [:]
4331
4384
  /// A drawing's shapes are not views: a change to one redraws its `Svg`.
@@ -6054,6 +6107,11 @@ final class CraftNativeScreenController: UIViewController, UIScrollViewDelegate,
6054
6107
  private func restoreFocus(_ focused: UIView?) {
6055
6108
  guard let focused, focused.window != nil, !focused.isFirstResponder,
6056
6109
  lastFocusedInput === focused, firstResponder(in: rootStack) == nil else { return }
6110
+ var ancestor: UIView? = focused
6111
+ while let view = ancestor {
6112
+ if view.isHidden { return }
6113
+ ancestor = view.superview
6114
+ }
6057
6115
  // A delayed acknowledgement belongs to the input that scheduled it.
6058
6116
  // A newer field or an explicit dismissal owns focus now.
6059
6117
  _ = focused.becomeFirstResponder()
@@ -21,6 +21,7 @@ import Darwin
21
21
  /// tap <text> first hittable element whose label contains text
22
22
  /// tapif <text> tap it when it is on screen, else carry on (the big timer's "Show the controls")
23
23
  /// tapid <identifier>
24
+ /// longpressid <identifier> holds a hittable native element to open its edit menu
24
25
  /// touches <JSON> timed normalized touch paths in one native dispatch
25
26
  /// tapxy <x> <y> normalised 0…1 of the screen
26
27
  /// tapexact <label> a button whose label is exactly this
@@ -29,11 +30,14 @@ import Darwin
29
30
  /// return the keyboard's return key (Go on a sign-in form)
30
31
  /// field <n> <text> tap the n-th text field (0-based, secure fields after plain) and type
31
32
  /// typeid <identifier> <text> tap the element with this identifier and type
33
+ /// sliderid <identifier> <0…1> adjusts a hittable native slider
34
+ /// expectapp <bundle-id> [| secs] asserts a native app handoff reached the foreground
32
35
  /// expect <text> [| secs] waits for an element containing text; logs PASS/FAIL
33
36
  /// expectexact <label> [| secs] a button or text whose label is exactly this
34
37
  /// absent <text> logs PASS when no element contains text
35
38
  /// expectid <id> [| secs] / absentid <id> the same by accessibility identifier (testID)
36
39
  /// labelid <id> <text> that element's label is exactly text (a count, a status)
40
+ /// valueid <id> <text> that element's actual string value is exactly text
37
41
  /// tabbar shown|hidden the native tab bar (Today, Calendar, …) can be tapped, or not
38
42
  /// selected <tab> the tab bar's selected button is this one
39
43
  /// tab <name> tap a tab bar button
@@ -297,6 +301,14 @@ final class DriverTests: XCTestCase {
297
301
  let target = identified(arg)
298
302
  if target.waitForExistence(timeout: 10) { press(target); note("tapid \(arg): ok") }
299
303
  else { XCTFail("Element not found"); note("FAIL tapid \(arg): NOT FOUND") }
304
+ case "longpressid":
305
+ let target = identified(arg)
306
+ guard target.waitForExistence(timeout: 10), target.isHittable else {
307
+ check(false, "longpressid \(arg) is hittable")
308
+ return
309
+ }
310
+ target.press(forDuration: 1.2)
311
+ note("longpressid \(arg): ok")
300
312
  case "touches":
301
313
  do {
302
314
  guard let data = arg.data(using: .utf8),
@@ -367,6 +379,23 @@ final class DriverTests: XCTestCase {
367
379
  app.typeText(idParts.count > 1 ? idParts[1] : "")
368
380
  note("typeid \(idParts[0]): ok")
369
381
  } else { XCTFail("Element not found"); note("FAIL typeid \(idParts[0]): NOT FOUND") }
382
+ case "sliderid":
383
+ let parts = arg.split(separator: " ", maxSplits: 1).map(String.init)
384
+ guard parts.count == 2, let position = Double(parts[1]), position.isFinite, (0...1).contains(position) else {
385
+ check(false, "sliderid requires an identifier and normalized position")
386
+ return
387
+ }
388
+ let slider = app.sliders.matching(NSPredicate(format: "identifier == %@", parts[0])).firstMatch
389
+ guard slider.waitForExistence(timeout: 10), slider.isHittable else {
390
+ check(false, "sliderid \(parts[0]) is hittable")
391
+ return
392
+ }
393
+ slider.adjust(toNormalizedSliderPosition: CGFloat(position))
394
+ note("sliderid \(parts[0]): \(position)")
395
+ case "expectapp":
396
+ let (bundle, seconds) = split(arg)
397
+ let target = XCUIApplication(bundleIdentifier: bundle)
398
+ check(target.wait(for: .runningForeground, timeout: seconds), "expectapp \(bundle)")
370
399
  case "field":
371
400
  let fieldParts = arg.split(separator: " ", maxSplits: 1).map(String.init)
372
401
  let index = Int(fieldParts[0]) ?? 0
@@ -392,6 +421,14 @@ final class DriverTests: XCTestCase {
392
421
  let want = idParts.count > 1 ? idParts[1] : ""
393
422
  let seen = target.waitForExistence(timeout: 5) ? target.label : "(missing)"
394
423
  check(seen == want, "labelid \(idParts[0]) \(want) (saw \(seen))")
424
+ case "valueid":
425
+ let idParts = arg.split(separator: " ", maxSplits: 1).map(String.init)
426
+ let target = identified(idParts[0])
427
+ let want = idParts.count > 1 ? idParts[1] : ""
428
+ let matched = poll(5) {
429
+ target.exists && (target.value as? String) == want ? target : nil
430
+ }
431
+ check(matched != nil, "valueid \(idParts[0]) \(want)")
395
432
  case "absentid":
396
433
  check(!identified(arg).exists, "absentid \(arg)")
397
434
  case "absent":