craft-native 0.0.254 → 0.0.262

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.
@@ -1090,6 +1090,8 @@ private final class CraftNativeVideoView: UIView, AVPlayerViewControllerDelegate
1090
1090
  private var playingObservation: NSKeyValueObservation?
1091
1091
  private var timeObserver: Any?
1092
1092
  private var loops = false
1093
+ private var requestedTime: Double?
1094
+ private var pendingSeek: Double?
1093
1095
  private var wasPlaying: Bool?
1094
1096
  private var playIntent: Bool?
1095
1097
  private var userPaused = false
@@ -1097,7 +1099,8 @@ private final class CraftNativeVideoView: UIView, AVPlayerViewControllerDelegate
1097
1099
  /// This video holds a claim on the audio session (`CraftNativeSounds`).
1098
1100
  private var claimedSession = false
1099
1101
  /// The screen's handlers by event name (`onEnd`, `onPlay`, `onPause`,
1100
- /// `onProgress`, `onLoad`, `onError`), and how an event reaches them.
1102
+ /// `onProgress`, `onLoadStart`, `onLoad`, `onLoadEnd`, `onError`), and how
1103
+ /// an event reaches them.
1101
1104
  var handlers: [String: String] = [:]
1102
1105
  var emit: ((_ handler: String, _ nativeEvent: [String: Any]) -> Void)?
1103
1106
 
@@ -1170,8 +1173,21 @@ private final class CraftNativeVideoView: UIView, AVPlayerViewControllerDelegate
1170
1173
  CraftNativeSounds.releaseSession()
1171
1174
  }
1172
1175
 
1173
- func configure(source: Any?, autoplay: Bool, paused: Bool, loop: Bool, muted: Bool, controls: Bool, resizeMode: String?, pictureInPicture: Bool = false) {
1176
+ private func applyPendingSeek() {
1177
+ guard let target = pendingSeek, let player, let item = player.currentItem, item.status == .readyToPlay else { return }
1178
+ let current = seconds(player.currentTime())
1179
+ pendingSeek = nil
1180
+ guard abs(current - target) > 0.25 else { return }
1181
+ player.seek(to: CMTime(seconds: target, preferredTimescale: 600))
1182
+ }
1183
+
1184
+ func configure(source: Any?, autoplay: Bool, paused: Bool, loop: Bool, muted: Bool, currentTime: Any?, controls: Bool, resizeMode: String?, pictureInPicture: Bool = false) {
1174
1185
  let uri = (source as? String) ?? (source as? [String: Any])?["uri"] as? String ?? ""
1186
+ let nextTime = number(currentTime).map(Double.init).map { max(0, $0) }
1187
+ if nextTime != requestedTime {
1188
+ requestedTime = nextTime
1189
+ pendingSeek = nextTime
1190
+ }
1175
1191
  let nextShouldPlay = autoplay && !paused
1176
1192
  if playIntent != nextShouldPlay {
1177
1193
  userPaused = false
@@ -1184,6 +1200,7 @@ private final class CraftNativeVideoView: UIView, AVPlayerViewControllerDelegate
1184
1200
  userPaused = false
1185
1201
  ended = false
1186
1202
  loops = false
1203
+ pendingSeek = requestedTime
1187
1204
  // The copy `craft.media.keep` put on the phone plays in place of
1188
1205
  // the address, so a kept video plays with no signal.
1189
1206
  let kept = CraftNativeMedia.local(uri)
@@ -1200,11 +1217,13 @@ private final class CraftNativeVideoView: UIView, AVPlayerViewControllerDelegate
1200
1217
  return
1201
1218
  }
1202
1219
  let next = AVPlayer(url: url)
1220
+ fire("onLoadStart")
1203
1221
  player = next
1204
1222
  playerController.player = next
1205
1223
  observe(next)
1206
1224
  }
1207
1225
  guard let player else { return }
1226
+ applyPendingSeek()
1208
1227
  player.isMuted = muted
1209
1228
  // A muted video makes no sound, so it leaves the session as it is.
1210
1229
  if muted { releaseSession() } else { claimSession() }
@@ -1258,7 +1277,10 @@ private final class CraftNativeVideoView: UIView, AVPlayerViewControllerDelegate
1258
1277
  DispatchQueue.main.async {
1259
1278
  guard let self, self.player?.currentItem === item else { return }
1260
1279
  switch item.status {
1261
- case .readyToPlay: self.fire("onLoad", ["duration": self.seconds(item.duration)])
1280
+ case .readyToPlay:
1281
+ self.applyPendingSeek()
1282
+ self.fire("onLoad", ["duration": self.seconds(item.duration)])
1283
+ self.fire("onLoadEnd")
1262
1284
  case .failed: self.fire("onError", ["message": item.error?.localizedDescription ?? "The video could not be played"])
1263
1285
  default: break
1264
1286
  }
@@ -1306,6 +1328,8 @@ private final class CraftNativeVideoView: UIView, AVPlayerViewControllerDelegate
1306
1328
  playerController.player = nil
1307
1329
  playerController.delegate = nil
1308
1330
  sourceURI = ""
1331
+ requestedTime = nil
1332
+ pendingSeek = nil
1309
1333
  playIntent = nil
1310
1334
  userPaused = false
1311
1335
  ended = false
@@ -2022,6 +2046,8 @@ private struct CraftNativeLayoutStyle {
2022
2046
  let bottom: CGFloat?
2023
2047
  let left: CGFloat?
2024
2048
  let alignSelf: String?
2049
+ /// CSS/Yoga order; equal values retain source order.
2050
+ let order: Int
2025
2051
  let flexGrow: CGFloat
2026
2052
  /// Nil when the style does not say: the parent picks the default for the
2027
2053
  /// kind of view (text shrinks along a row, a box does not).
@@ -2059,6 +2085,7 @@ private struct CraftNativeLayoutStyle {
2059
2085
  left = number(raw["left"])
2060
2086
  let align = raw["alignSelf"] as? String
2061
2087
  alignSelf = align == "auto" ? nil : align
2088
+ order = number(raw["order"]).map { Int($0.rounded(.towardZero)) } ?? 0
2062
2089
  // `flex: n` is the web's and React Native's shorthand: a positive
2063
2090
  // number grows by n, shrinks, and starts from nothing, so `flex-1`
2064
2091
  // siblings share a row equally whatever their content.
@@ -2516,6 +2543,7 @@ final class CraftNativeCelebration {
2516
2543
  group.duration = 2.2 + Double(spread) * 0.45
2517
2544
  group.beginTime = now + Double(index % 7) * 0.018
2518
2545
  group.fillMode = .backwards
2546
+ group.atDisplayRate()
2519
2547
  piece.add(group, forKey: "craft.celebration.particle")
2520
2548
  }
2521
2549
 
@@ -2529,6 +2557,7 @@ final class CraftNativeCelebration {
2529
2557
  entrance.stiffness = 160
2530
2558
  entrance.mass = 1
2531
2559
  entrance.duration = 0.95
2560
+ entrance.atDisplayRate()
2532
2561
  view.layer.add(entrance, forKey: "craft.celebration.entrance")
2533
2562
 
2534
2563
  let sheen = CAGradientLayer()
@@ -2554,6 +2583,7 @@ final class CraftNativeCelebration {
2554
2583
  shine.animations = [sweep, light]
2555
2584
  shine.duration = 1.15
2556
2585
  shine.beginTime = now + 0.55
2586
+ shine.atDisplayRate()
2557
2587
  sheen.add(shine, forKey: "craft.celebration.sweep")
2558
2588
  let cleanup = DispatchWorkItem { [weak self] in self?.stop() }
2559
2589
  self.cleanup = cleanup
@@ -2886,7 +2916,15 @@ private class CraftNativeFlowView: UIStackView {
2886
2916
 
2887
2917
  /// Children that take part in the flow: shown, not a modal overlay.
2888
2918
  private var visibleChildren: [UIView] {
2889
- flowChildren.filter { $0.superview === self && !$0.isHidden && !($0 is CraftNativeModalView) }
2919
+ flowChildren.enumerated()
2920
+ .filter { $0.element.superview === self && !$0.element.isHidden && !($0.element is CraftNativeModalView) }
2921
+ .sorted {
2922
+ if $0.element.craftLayoutStyle.order != $1.element.craftLayoutStyle.order {
2923
+ return $0.element.craftLayoutStyle.order < $1.element.craftLayoutStyle.order
2924
+ }
2925
+ return $0.offset < $1.offset
2926
+ }
2927
+ .map(\.element)
2890
2928
  }
2891
2929
 
2892
2930
  /// Builds the eligible portion of this container for the host-neutral
@@ -3088,7 +3126,8 @@ private class CraftNativeFlowView: UIStackView {
3088
3126
  frames: &frames
3089
3127
  )
3090
3128
  }
3091
- if place, flow.count == children.count, let sharedTree = sharedTreeFrames(flow, width: width, height: height), (sharedTree.nodes.count > flow.count + 1 || grid) {
3129
+ if place, flow.count == children.count, let sharedTree = sharedTreeFrames(flow, width: width, height: height),
3130
+ (sharedTree.nodes.count > flow.count + 1 || grid || reverse || wrapReverse || gridAutoRows != nil || gridRows != nil) {
3092
3131
  frames = []
3093
3132
  for index in 1..<sharedTree.nodes.count {
3094
3133
  guard let view = sharedTree.nodes[index].view else { continue }
@@ -3795,6 +3834,17 @@ private final class CraftNativeModalView: UIView, UIGestureRecognizerDelegate {
3795
3834
  didSet { blocker.backgroundColor = transparent ? .clear : UIColor.black.withAlphaComponent(0.32) }
3796
3835
  }
3797
3836
 
3837
+ /// Existing Modal nodes block by default. A non-modal popup keeps the
3838
+ /// screen-level overlay but lets hit testing fall through outside its
3839
+ /// interactive content.
3840
+ var blocksBackground = true {
3841
+ didSet { blocker.isUserInteractionEnabled = blocksBackground }
3842
+ }
3843
+ /// An opt-in non-modal dismissal policy. The default popup remains
3844
+ /// pass-through; when enabled, an outside tap is consumed and routed to
3845
+ /// onRequestClose instead of reaching the view below.
3846
+ var dismissOnOutsideTap = false
3847
+
3798
3848
  override init(frame: CGRect) {
3799
3849
  super.init(frame: frame)
3800
3850
  isUserInteractionEnabled = true
@@ -3876,10 +3926,13 @@ private final class CraftNativeModalView: UIView, UIGestureRecognizerDelegate {
3876
3926
  transform = .identity
3877
3927
  alpha = 0
3878
3928
  isUserInteractionEnabled = true
3929
+ blocksBackground = true
3930
+ dismissOnOutsideTap = false
3879
3931
  onRequestClose = nil
3880
3932
  }
3881
3933
 
3882
3934
  func requestClose(reason: String = "backdrop") {
3935
+ guard blocksBackground || dismissOnOutsideTap else { return }
3883
3936
  guard let onRequestClose else { return }
3884
3937
  isUserInteractionEnabled = false
3885
3938
  onRequestClose(reason)
@@ -3912,6 +3965,14 @@ private final class CraftNativeModalView: UIView, UIGestureRecognizerDelegate {
3912
3965
  candidate = view.superview
3913
3966
  }
3914
3967
  }
3968
+ if !blocksBackground {
3969
+ // A dismissible popup consumes its outside hit so the close event
3970
+ // cannot also activate the screen below. Otherwise it owns the
3971
+ // hit only when a blocking modal is underneath it; with no modal
3972
+ // below, the screen remains pass-through.
3973
+ if dismissOnOutsideTap { return self }
3974
+ return craftScreenController?.hasBlockingModalBelow(self) == true ? self : nil
3975
+ }
3915
3976
  return blocker.hitTest(blocker.convert(point, from: self), with: event)
3916
3977
  }
3917
3978
 
@@ -4824,6 +4885,62 @@ enum CraftNativeScriptThread {
4824
4885
  }
4825
4886
  }
4826
4887
 
4888
+ extension CAAnimation {
4889
+ /// Asks for the display's full rate, up to 120Hz on ProMotion. Core
4890
+ /// Animation otherwise picks a rate for the motion and often stays at 60;
4891
+ /// a transition or a spring the eye follows reads smoother at 120.
4892
+ func atDisplayRate() {
4893
+ if #available(iOS 15.0, *) { preferredFrameRateRange = CAFrameRateRange(minimum: 80, maximum: 120, preferred: 120) }
4894
+ }
4895
+ }
4896
+
4897
+ /// `requestAnimationFrame` for native screens: one display link, at the
4898
+ /// display's own rate (up to 120Hz on a ProMotion iPhone, which the app
4899
+ /// allows with `CADisableMinimumFrameDurationOnPhone`), running only while a
4900
+ /// screen on display is waiting for a frame. Each frame hands every waiting
4901
+ /// screen one `__craftNativeFireFrame`, where its script runs; a screen asks
4902
+ /// again for the frame after, as a browser's page does. A screen out of sight
4903
+ /// waits until it is shown, as a browser pauses a hidden tab's frames, and as
4904
+ /// Craft's Android host does (Choreographer). Main thread only.
4905
+ final class CraftNativeFrameClock: NSObject {
4906
+ static let shared = CraftNativeFrameClock()
4907
+
4908
+ private var waiting: [ObjectIdentifier: () -> Void] = [:]
4909
+ private var link: CADisplayLink?
4910
+
4911
+ /// How many screens wait for the next frame.
4912
+ var waitingCount: Int { waiting.count }
4913
+ /// Whether the display link is counting frames now.
4914
+ var isRunning: Bool { link.map { !$0.isPaused } ?? false }
4915
+
4916
+ /// `deliver` on the next frame, once. Asking again before it comes keeps one.
4917
+ func request(_ owner: AnyObject, _ deliver: @escaping () -> Void) {
4918
+ waiting[ObjectIdentifier(owner)] = deliver
4919
+ if link == nil {
4920
+ let link = CADisplayLink(target: self, selector: #selector(frame(_:)))
4921
+ if #available(iOS 15.0, *) {
4922
+ link.preferredFrameRateRange = CAFrameRateRange(minimum: 30, maximum: 120, preferred: 120)
4923
+ }
4924
+ link.add(to: .main, forMode: .common)
4925
+ self.link = link
4926
+ }
4927
+ link?.isPaused = false
4928
+ }
4929
+
4930
+ /// `owner` no longer waits: it went out of sight or away.
4931
+ func cancel(_ owner: AnyObject) {
4932
+ waiting.removeValue(forKey: ObjectIdentifier(owner))
4933
+ if waiting.isEmpty { link?.isPaused = true }
4934
+ }
4935
+
4936
+ @objc private func frame(_ link: CADisplayLink) {
4937
+ let due = waiting
4938
+ waiting.removeAll()
4939
+ if waiting.isEmpty { link.isPaused = true }
4940
+ due.values.forEach { $0() }
4941
+ }
4942
+ }
4943
+
4827
4944
  /// The native screens' JavaScript. A screen is a JavaScriptCore context of
4828
4945
  /// its own and evaluates the whole file it is given, so each route has a file
4829
4946
  /// of its own when stx wrote one (`dist/native-screens/<route>.js`, stx's
@@ -4900,6 +5017,25 @@ enum CraftNativeBundle {
4900
5017
  }
4901
5018
  }
4902
5019
 
5020
+ private final class CraftNativeScreenRootView: UIView {
5021
+ weak var controller: CraftNativeScreenController?
5022
+
5023
+ override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
5024
+ // A popup's host frame is only its authored card, so UIKit would not
5025
+ // ask it about an outside point. Shield that point at the screen root
5026
+ // only when a blocking modal is underneath; ordinary non-modal
5027
+ // overlays remain pass-through.
5028
+ if let controller {
5029
+ for modal in controller.view.subviews.compactMap({ $0 as? CraftNativeModalView }).reversed()
5030
+ where !modal.blocksBackground && !modal.isHidden && modal.alpha > 0.01 {
5031
+ let local = modal.convert(point, from: self)
5032
+ if !modal.bounds.contains(local) && (modal.dismissOnOutsideTap || controller.hasBlockingModalBelow(modal)) { return modal }
5033
+ }
5034
+ }
5035
+ return super.hitTest(point, with: event)
5036
+ }
5037
+ }
5038
+
4903
5039
  final class CraftNativeScreenController: UIViewController, UIScrollViewDelegate, UITextFieldDelegate, UITextViewDelegate, UIPickerViewDataSource, UIPickerViewDelegate {
4904
5040
  private final class RenderedNode {
4905
5041
  /// A recycled list row's root takes the identity of the row it shows next.
@@ -4952,6 +5088,10 @@ final class CraftNativeScreenController: UIViewController, UIScrollViewDelegate,
4952
5088
  private var scrollMomentumEndHandlers: [ObjectIdentifier: String] = [:]
4953
5089
  private var sliderCompleteHandlers: [ObjectIdentifier: String] = [:]
4954
5090
  private var sliderSteps: [ObjectIdentifier: Float] = [:]
5091
+ /// A controlled switch can be reconciled while UIKit is still animating
5092
+ /// the user's tap. Remember that native value briefly so the echo does not
5093
+ /// interrupt the animation and leave the thumb painted at its old edge.
5094
+ private var switchUserValues: [ObjectIdentifier: Bool] = [:]
4955
5095
  private var pickerOptions: [ObjectIdentifier: [(value: String, label: String)]] = [:]
4956
5096
  private var modalVisibility: [ObjectIdentifier: Bool] = [:]
4957
5097
  private var modalFocusRestore: [ObjectIdentifier: UIView] = [:]
@@ -5026,6 +5166,9 @@ final class CraftNativeScreenController: UIViewController, UIScrollViewDelegate,
5026
5166
  var pending: [Int: DispatchWorkItem] = [:]
5027
5167
  }
5028
5168
  private let timers = Timers()
5169
+ /// The script asked for an animation frame it has not had yet
5170
+ /// (`requestAnimationFrame`, CraftNativeFrameClock). Main thread only.
5171
+ private var frameWanted = false
5029
5172
  private var lifecycleObservers: [NSObjectProtocol] = []
5030
5173
  private var deepLinkListener: UUID?
5031
5174
  private var keyboardSafeAreaInset: CGFloat = 0
@@ -5056,6 +5199,12 @@ final class CraftNativeScreenController: UIViewController, UIScrollViewDelegate,
5056
5199
  fatalError("init(coder:) has not been implemented")
5057
5200
  }
5058
5201
 
5202
+ override func loadView() {
5203
+ let root = CraftNativeScreenRootView()
5204
+ root.controller = self
5205
+ view = root
5206
+ }
5207
+
5059
5208
  deinit {
5060
5209
  disposeRuntime()
5061
5210
  imageTasks.values.forEach { $0.cancel() }
@@ -5202,6 +5351,23 @@ final class CraftNativeScreenController: UIViewController, UIScrollViewDelegate,
5202
5351
  CraftChrome.shared.updateTabAccessory(tabAccessory, owner: self)
5203
5352
  }
5204
5353
 
5354
+ /// `requestAnimationFrame`: the next display frame, for a screen on display
5355
+ /// (or the app script, which is never shown). One out of sight keeps the
5356
+ /// request until it is shown again (screenVisibilityChanged).
5357
+ private func requestFrame() {
5358
+ guard !runtimeDisposed, !frameWanted else { return }
5359
+ frameWanted = true
5360
+ guard isAppScript || reportedVisible != false else { return }
5361
+ CraftNativeFrameClock.shared.request(self) { [weak self] in self?.fireFrame() }
5362
+ }
5363
+
5364
+ private func fireFrame() {
5365
+ guard frameWanted, !runtimeDisposed else { return }
5366
+ frameWanted = false
5367
+ let context = jsContext
5368
+ CraftNativeScriptThread.run { context.objectForKeyedSubscript("__craftNativeFireFrame")?.call(withArguments: []) }
5369
+ }
5370
+
5205
5371
  /// The screen came on screen or went off it: a screen pushed over it was
5206
5372
  /// popped, or the hybrid shell switched to or away from its tab (which
5207
5373
  /// hides a stack rather than moving it, so UIKit says nothing). The first
@@ -5216,6 +5382,8 @@ final class CraftNativeScreenController: UIViewController, UIScrollViewDelegate,
5216
5382
  // preview also restores a screen that never lost focus, so restore its
5217
5383
  // chrome even when no new SCREEN_FOCUS event is needed.
5218
5384
  if visible { restoreShellChrome() }
5385
+ if visible, frameWanted { CraftNativeFrameClock.shared.request(self) { [weak self] in self?.fireFrame() } }
5386
+ if !visible { CraftNativeFrameClock.shared.cancel(self) }
5219
5387
  guard visible != reportedVisible else { return }
5220
5388
  let first = reportedVisible == nil
5221
5389
  reportedVisible = visible
@@ -5242,6 +5410,8 @@ final class CraftNativeScreenController: UIViewController, UIScrollViewDelegate,
5242
5410
  private func disposeRuntime() {
5243
5411
  guard !runtimeDisposed else { return }
5244
5412
  runtimeDisposed = true
5413
+ frameWanted = false
5414
+ CraftNativeFrameClock.shared.cancel(self)
5245
5415
  disposeRenderedTree()
5246
5416
  let context = jsContext
5247
5417
  CraftNativeScriptThread.run { context.objectForKeyedSubscript("__stxNativeUnmount")?.call(withArguments: []) }
@@ -5312,9 +5482,58 @@ final class CraftNativeScreenController: UIViewController, UIScrollViewDelegate,
5312
5482
  if bar.intersects(view.bounds) { insets.top = max(insets.top, bar.maxY) }
5313
5483
  }
5314
5484
  for modal in modals {
5315
- if modal.frame != view.bounds { modal.frame = view.bounds }
5316
- modal.contentInsets = insets
5485
+ guard !modal.blocksBackground else {
5486
+ if modal.frame != view.bounds { modal.frame = view.bounds }
5487
+ modal.contentInsets = insets
5488
+ continue
5489
+ }
5490
+
5491
+ // Non-modal overlays are viewport children, not full-screen
5492
+ // scrims. Their absolute style uses the same full screenViewport
5493
+ // origin that View.measure returns. Safe-area-aware placement is
5494
+ // owned by the caller (for example, STX's anchor/clamp logic), so
5495
+ // an authored left/top is never shifted by an implicit inset.
5496
+ let viewport = view.bounds
5497
+ let style = modal.craftLayoutStyle
5498
+ let width = style.left != nil && style.right != nil
5499
+ ? max(0, viewport.width - (style.left ?? 0) - (style.right ?? 0))
5500
+ : style.width?.resolve(viewport.width)
5501
+ ?? min(viewport.width, modal.contentStack.sizeThatFits(viewport.size).width)
5502
+ let height = style.top != nil && style.bottom != nil
5503
+ ? max(0, viewport.height - (style.top ?? 0) - (style.bottom ?? 0))
5504
+ : style.height?.resolve(viewport.height)
5505
+ ?? min(viewport.height, modal.contentStack.sizeThatFits(viewport.size).height)
5506
+ let x = viewport.minX + (style.left ?? (style.right.map { viewport.width - $0 - width } ?? 0))
5507
+ let y = viewport.minY + (style.top ?? (style.bottom.map { viewport.height - $0 - height } ?? 0))
5508
+ let frame = CGRect(x: x, y: y, width: width, height: height)
5509
+ if modal.frame != frame { modal.frame = frame }
5510
+ // The frame already excludes the safe area; inset the content no
5511
+ // further or authored top/left coordinates would be shifted twice.
5512
+ modal.contentInsets = .zero
5513
+ }
5514
+ }
5515
+
5516
+ /// A non-modal popup above a blocking modal must not leak its outside tap
5517
+ /// to the modal's scrim and dismiss the wrong layer.
5518
+ fileprivate func hasBlockingModalBelow(_ modal: CraftNativeModalView) -> Bool {
5519
+ guard let index = view.subviews.firstIndex(where: { $0 === modal }) else { return false }
5520
+ return view.subviews[..<index].contains { candidate in
5521
+ guard let other = candidate as? CraftNativeModalView else { return false }
5522
+ return other.blocksBackground && !other.isHidden && other.alpha > 0.01
5523
+ }
5524
+ }
5525
+
5526
+ /// The native route's Back button dismisses the top presented modal before
5527
+ /// it pops the route, matching Android's activity back callback.
5528
+ @discardableResult
5529
+ func handleBackForModal() -> Bool {
5530
+ let modal = view.subviews.reversed().compactMap { $0 as? CraftNativeModalView }.first {
5531
+ !$0.isHidden && $0.alpha > 0.01 && ($0.blocksBackground || $0.dismissOnOutsideTap)
5317
5532
  }
5533
+ guard let modal else { return false }
5534
+ let hasHandler = modal.onRequestClose != nil
5535
+ modal.requestClose(reason: "back")
5536
+ return hasHandler
5318
5537
  }
5319
5538
 
5320
5539
  private static func safeJavaScriptString(_ value: JSValue?) -> String? {
@@ -5415,6 +5634,12 @@ final class CraftNativeScreenController: UIViewController, UIScrollViewDelegate,
5415
5634
  }
5416
5635
  jsContext.setObject(scheduleTimer, forKeyedSubscript: "craftNativeScheduleTimer" as NSString)
5417
5636
  jsContext.setObject(cancelTimer, forKeyedSubscript: "craftNativeCancelTimer" as NSString)
5637
+ // The next display frame, from the script's thread; the frame itself
5638
+ // comes back there as `__craftNativeFireFrame`.
5639
+ let requestFrame: @convention(block) () -> Void = { [weak self] in
5640
+ CraftNativeScriptThread.toMain { self?.requestFrame() }
5641
+ }
5642
+ jsContext.setObject(requestFrame, forKeyedSubscript: "craftNativeRequestFrame" as NSString)
5418
5643
  let capabilityJSON = inputs.capabilityJSON
5419
5644
  // The app's site and build, as JSON strings: the site an all-native
5420
5645
  // app's paths and links belong to (`devServerURL`), and the version a
@@ -5450,6 +5675,41 @@ final class CraftNativeScreenController: UIViewController, UIScrollViewDelegate,
5450
5675
  jsContext.evaluateScript(Self.nativeWebAPICompatibilityPrelude)
5451
5676
  installHostAPIs()
5452
5677
  jsContext.evaluateScript("""
5678
+ // requestAnimationFrame on the display's frames (CraftNativeFrameClock),
5679
+ // at its own rate, 120 a second on ProMotion: a timer guessing at 60
5680
+ // would cap every animation a screen draws itself. One request covers
5681
+ // every callback for the frame; a callback that throws does not stop
5682
+ // the others, and is reported after them.
5683
+ if (typeof globalThis.requestAnimationFrame !== 'function') {
5684
+ (function() {
5685
+ var frames = [];
5686
+ var cancelled = new Set();
5687
+ var nextFrame = 0;
5688
+ globalThis.requestAnimationFrame = function(callback) {
5689
+ if (typeof callback !== 'function') return 0;
5690
+ var id = ++nextFrame;
5691
+ frames.push({ id: id, callback: callback });
5692
+ if (frames.length === 1) craftNativeRequestFrame();
5693
+ return id;
5694
+ };
5695
+ globalThis.cancelAnimationFrame = function(id) {
5696
+ if (frames.some(function(frame) { return frame.id === id; })) cancelled.add(id);
5697
+ };
5698
+ globalThis.__craftNativeFireFrame = function() {
5699
+ var due = frames;
5700
+ var skip = cancelled;
5701
+ frames = [];
5702
+ cancelled = new Set();
5703
+ var now = globalThis.performance && typeof globalThis.performance.now === 'function' ? globalThis.performance.now() : Date.now();
5704
+ var failures = [];
5705
+ for (var i = 0; i < due.length; i++) {
5706
+ if (skip.has(due[i].id)) continue;
5707
+ try { due[i].callback(now); } catch (error) { failures.push(error); }
5708
+ }
5709
+ failures.forEach(function(error) { globalThis.setTimeout(function() { throw error; }, 0); });
5710
+ };
5711
+ })();
5712
+ }
5453
5713
  if (typeof globalThis.setTimeout !== 'function') {
5454
5714
  (function() {
5455
5715
  var timers = new Map();
@@ -7328,6 +7588,8 @@ final class CraftNativeScreenController: UIViewController, UIScrollViewDelegate,
7328
7588
  let modal = result as! CraftNativeModalView
7329
7589
  let focusBeforeContent = firstResponder(in: rootStack) ?? lastFocusedInput
7330
7590
  modal.transparent = props["transparent"] as? Bool == true
7591
+ modal.blocksBackground = props["nonModal"] as? Bool != true
7592
+ modal.dismissOnOutsideTap = props["dismissOnOutsideTap"] as? Bool == true
7331
7593
  let visible: Bool
7332
7594
  if let propVisible = props["visible"] as? Bool {
7333
7595
  // An explicit visible prop owns modal visibility. The
@@ -7385,7 +7647,13 @@ final class CraftNativeScreenController: UIViewController, UIScrollViewDelegate,
7385
7647
  // UIKit has already changed the value before emitting the
7386
7648
  // event. Echoing it through the script must not restart its
7387
7649
  // native animation.
7388
- if toggle.isOn != value { toggle.isOn = value }
7650
+ let id = ObjectIdentifier(toggle)
7651
+ if switchUserValues[id] != value, toggle.isOn != value {
7652
+ // Programmatic changes should settle immediately. A
7653
+ // native tap is handled above without touching UIKit
7654
+ // while its own thumb animation is in flight.
7655
+ toggle.setOn(value, animated: false)
7656
+ }
7389
7657
  }
7390
7658
  toggle.isEnabled = props["disabled"] as? Bool != true
7391
7659
  if let track = props["trackColor"] as? [String: Any] {
@@ -7512,6 +7780,7 @@ final class CraftNativeScreenController: UIViewController, UIScrollViewDelegate,
7512
7780
  paused: (props["paused"] as? Bool) == true,
7513
7781
  loop: (props["loop"] as? Bool) == true,
7514
7782
  muted: (props["muted"] as? Bool) == true,
7783
+ currentTime: props["currentTime"],
7515
7784
  controls: (props["controls"] as? Bool) == true,
7516
7785
  resizeMode: style["resizeMode"] as? String ?? props["resizeMode"] as? String,
7517
7786
  pictureInPicture: (props["pictureInPicture"] as? Bool) == true
@@ -8104,6 +8373,7 @@ final class CraftNativeScreenController: UIViewController, UIScrollViewDelegate,
8104
8373
  imageLoadEndHandlers.removeValue(forKey: id)
8105
8374
  imageErrorHandlers.removeValue(forKey: id)
8106
8375
  checkboxIndeterminate.removeValue(forKey: id)
8376
+ switchUserValues.removeValue(forKey: id)
8107
8377
  if let video = node.view as? CraftNativeVideoView { video.stop() }
8108
8378
  if let map = node.view as? CraftNativeMapView { map.destroy() }
8109
8379
  for child in node.children { forgetHandlers(child, preservingInputDrafts: preservingInputDrafts) }
@@ -9086,7 +9356,8 @@ final class CraftNativeScreenController: UIViewController, UIScrollViewDelegate,
9086
9356
  let hasLinkTarget = ["href", "to"].contains { !(props[$0] as? String ?? "").isEmpty }
9087
9357
  let linkedControl = ["Link", "TouchableOpacity", "TouchableHighlight", "Pressable"].contains(type) && hasLinkTarget
9088
9358
  let touchable = ["TouchableOpacity", "TouchableHighlight", "Pressable"].contains(type)
9089
- let role = (props["accessibilityRole"] as? String) ?? (linkedControl ? "link" : touchable ? "button" : nil)
9359
+ let role = (props["accessibilityRole"] as? String)
9360
+ ?? (linkedControl ? "link" : touchable ? "button" : ["FlatList", "SectionList"].contains(type) ? "list" : nil)
9090
9361
  // A scroll view, a list or a group of controls holds what VoiceOver
9091
9362
  // reads: its label names the group, as a tab strip or a pager's
9092
9363
  // name, and never stands in for its content. As an element of its
@@ -9281,7 +9552,13 @@ final class CraftNativeScreenController: UIViewController, UIScrollViewDelegate,
9281
9552
  }
9282
9553
 
9283
9554
  @objc private func switchChanged(_ sender: UISwitch) {
9284
- guard let handler = handlers[ObjectIdentifier(sender)] else { return }
9555
+ let id = ObjectIdentifier(sender)
9556
+ switchUserValues[id] = sender.isOn
9557
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.35) { [weak self, weak sender] in
9558
+ guard let self, let sender, self.switchUserValues[id] == sender.isOn else { return }
9559
+ self.switchUserValues.removeValue(forKey: id)
9560
+ }
9561
+ guard let handler = handlers[id] else { return }
9285
9562
  send(type: "EVENT", payload: ["handlerName": handler, "nativeEvent": ["value": sender.isOn]])
9286
9563
  }
9287
9564
 
@@ -9962,6 +10239,7 @@ extension CraftNativeScreenController {
9962
10239
  }
9963
10240
  animation.fromValue = from
9964
10241
  let key = "\(CraftNativeRunningAnimation.key).\(keyPath)"
10242
+ animation.atDisplayRate()
9965
10243
  layer.add(animation, forKey: key)
9966
10244
  running.layers.append((layer, key))
9967
10245
  }
package/dist/mobile.js CHANGED
@@ -1725,7 +1725,7 @@ var health = {
1725
1725
  return () => {};
1726
1726
  const listener = (event) => {
1727
1727
  const detail = event.detail;
1728
- if (detail && typeof detail.id === "string" && (detail.event === "state" || detail.event === "error"))
1728
+ if (detail && typeof detail.id === "string" && (detail.event === "state" || detail.event === "metrics" || detail.event === "error"))
1729
1729
  callback(detail);
1730
1730
  };
1731
1731
  window.addEventListener("craftHealthWorkout", listener);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "craft-native",
3
- "version": "0.0.254",
3
+ "version": "0.0.262",
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>",