craft-native 0.0.499 → 0.0.502

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
@@ -117,7 +117,7 @@ function craftBinaryNotFoundMessage(triedPath) {
117
117
  `);
118
118
  }
119
119
  // package.json
120
- var version = "0.0.499";
120
+ var version = "0.0.502";
121
121
 
122
122
  // src/sdk-version.ts
123
123
  var SDK_VERSION = version;
@@ -1520,6 +1520,33 @@ Description: ${description || opts.name}
1520
1520
  }
1521
1521
  });
1522
1522
  }
1523
+ function rpmSpec(options) {
1524
+ return [
1525
+ "%global debug_package %{nil}",
1526
+ "%global _build_id_links none",
1527
+ "%global __strip /bin/true",
1528
+ "%global __os_install_post %{nil}",
1529
+ `Name: ${options.name}`,
1530
+ `Version: ${options.version}`,
1531
+ "Release: 1",
1532
+ `Summary: ${options.summary}`,
1533
+ "License: MIT",
1534
+ `Source0: ${options.name}`,
1535
+ ...options.requires ? [`Requires: ${options.requires}`] : [],
1536
+ "",
1537
+ "%description",
1538
+ options.description,
1539
+ "",
1540
+ "%install",
1541
+ "mkdir -p %{buildroot}/usr/bin",
1542
+ `install -m 755 %{SOURCE0} %{buildroot}/usr/bin/${options.name}`,
1543
+ "",
1544
+ "%files",
1545
+ `/usr/bin/${options.name}`,
1546
+ ""
1547
+ ].join(`
1548
+ `);
1549
+ }
1523
1550
  async function createRPM(opts) {
1524
1551
  return new Promise((resolve) => {
1525
1552
  try {
@@ -1552,26 +1579,17 @@ async function createRPM(opts) {
1552
1579
  return r;
1553
1580
  }).join(", ");
1554
1581
  copyFileSync(opts.binaryPath, join3(sourcesDir, sanitizedName));
1555
- const specContent = `Name: ${sanitizedName}
1556
- Version: ${opts.version}
1557
- Release: 1%{?dist}
1558
- Summary: ${summary}
1559
- License: MIT
1560
- Requires: ${requires}
1561
-
1562
- %description
1563
- ${description}
1564
-
1565
- %install
1566
- mkdir -p %{buildroot}/usr/bin
1567
- install -m 755 %{SOURCE0} %{buildroot}/usr/bin/${sanitizedName}
1568
-
1569
- %files
1570
- /usr/bin/${sanitizedName}
1571
- `;
1582
+ const specContent = rpmSpec({ name: sanitizedName, version: opts.version, summary, description, requires });
1572
1583
  const specPath = join3(specDir, `${opts.name.toLowerCase()}.spec`);
1573
1584
  writeFileSync3(specPath, specContent);
1574
1585
  const proc = spawn("rpmbuild", ["-bb", specPath]);
1586
+ let said = "";
1587
+ proc.stdout?.on("data", (chunk) => {
1588
+ said += chunk.toString();
1589
+ });
1590
+ proc.stderr?.on("data", (chunk) => {
1591
+ said += chunk.toString();
1592
+ });
1575
1593
  proc.on("close", (code) => {
1576
1594
  if (code === 0) {
1577
1595
  const rpmName = `${opts.name.toLowerCase()}-${opts.version}-1.x86_64.rpm`;
@@ -1583,7 +1601,9 @@ install -m 755 %{SOURCE0} %{buildroot}/usr/bin/${sanitizedName}
1583
1601
  resolve({ success: false, error: "Failed to copy built RPM" });
1584
1602
  }
1585
1603
  } else {
1586
- resolve({ success: false, error: `rpmbuild exited with code ${code}` });
1604
+ resolve({ success: false, error: `rpmbuild exited with code ${code}: ${said.trim().split(`
1605
+ `).slice(-12).join(`
1606
+ `)}` });
1587
1607
  }
1588
1608
  });
1589
1609
  proc.on("error", (err) => {
@@ -2120,7 +2140,8 @@ var BridgeErrorCodes = {
2120
2140
  BRIDGE_DESTROYED: -6,
2121
2141
  BUSY: -7,
2122
2142
  PROTOCOL_MISMATCH: -8,
2123
- DISCONNECTED: -9
2143
+ DISCONNECTED: -9,
2144
+ NATIVE_ERROR: -10
2124
2145
  };
2125
2146
  var BRIDGE_PROTOCOL_VERSION = 1;
2126
2147
  function buildMessageId(prefix, counter) {
@@ -2528,6 +2549,9 @@ class NativeBridge extends EventEmitter {
2528
2549
  }
2529
2550
  try {
2530
2551
  if (typeof window !== "undefined") {
2552
+ if (message.type === "request" && this.sendThroughInjectedBridge(message)) {
2553
+ return true;
2554
+ }
2531
2555
  if (window.webkit?.messageHandlers?.craft) {
2532
2556
  window.webkit.messageHandlers.craft.postMessage(message);
2533
2557
  return true;
@@ -2555,6 +2579,31 @@ class NativeBridge extends EventEmitter {
2555
2579
  return false;
2556
2580
  }
2557
2581
  }
2582
+ sendThroughInjectedBridge(message) {
2583
+ const injected = window.craft;
2584
+ if (!injected || typeof injected.invoke !== "function" || typeof message.method !== "string")
2585
+ return false;
2586
+ let call;
2587
+ try {
2588
+ call = Promise.resolve(injected.invoke(message.method, message.params));
2589
+ } catch (e) {
2590
+ call = Promise.reject(e);
2591
+ }
2592
+ call.then((result) => this.handleResponse({ id: message.id, type: "response", result }), (error) => {
2593
+ const detail = error ?? {};
2594
+ const text = typeof detail.message === "string" && detail.message.length > 0 ? detail.message : `Native bridge refused ${message.method}`;
2595
+ this.handleResponse({
2596
+ id: message.id,
2597
+ type: "response",
2598
+ error: {
2599
+ code: BridgeErrorCodes.NATIVE_ERROR,
2600
+ message: text,
2601
+ data: { nativeCode: typeof detail.code === "string" ? detail.code : undefined, method: message.method }
2602
+ }
2603
+ });
2604
+ });
2605
+ return true;
2606
+ }
2558
2607
  failPendingForMessage(message, error) {
2559
2608
  const pending = this.pendingRequests.get(message.id);
2560
2609
  if (!pending)
@@ -4865,7 +4914,7 @@ async function getSystemInfo() {
4865
4914
  }
4866
4915
  async function exec(command, options) {
4867
4916
  if (typeof window !== "undefined" && window.craft) {
4868
- return callBridge3("process.exec", { command, ...options });
4917
+ return callBridge3("shell.exec", { command, cwd: options?.cwd });
4869
4918
  }
4870
4919
  const { exec: nodeExec } = await import("child_process");
4871
4920
  const { promisify } = await import("util");
@@ -4886,107 +4935,46 @@ async function exec(command, options) {
4886
4935
  };
4887
4936
  }
4888
4937
  }
4938
+ var nextProcessId = 0;
4939
+ function shellFacade() {
4940
+ return window.craft?.shell;
4941
+ }
4889
4942
 
4890
4943
  class ChildProcess {
4891
4944
  command;
4892
4945
  args;
4893
4946
  options;
4894
4947
  processId = null;
4895
- onStdoutHandlers = [];
4896
- onStderrHandlers = [];
4897
- onExitHandlers = [];
4898
- domListeners = [];
4899
- exited = false;
4900
4948
  constructor(command, args = [], options = {}) {
4901
4949
  this.command = command;
4902
4950
  this.args = args;
4903
4951
  this.options = options;
4904
4952
  }
4905
- addDomListener(type, handler) {
4906
- if (typeof window === "undefined")
4907
- return;
4908
- window.addEventListener(type, handler);
4909
- this.domListeners.push({ type, handler });
4910
- }
4911
- removeDomListeners() {
4912
- if (typeof window === "undefined")
4913
- return;
4914
- for (const { type, handler } of this.domListeners) {
4915
- window.removeEventListener(type, handler);
4916
- }
4917
- this.domListeners = [];
4918
- }
4919
4953
  get pid() {
4920
4954
  return this.processId;
4921
4955
  }
4922
4956
  async start() {
4923
4957
  if (typeof window !== "undefined" && window.craft) {
4924
- const result = await callBridge3("process.spawn", {
4958
+ nextProcessId += 1;
4959
+ const id = `sdk-${Date.now().toString(36)}-${nextProcessId}`;
4960
+ await callBridge3("shell.spawn", {
4961
+ id,
4925
4962
  command: this.command,
4926
4963
  args: this.args,
4927
- ...this.options
4964
+ cwd: this.options.cwd,
4965
+ shell: this.options.shell
4928
4966
  });
4929
- this.processId = result.pid;
4930
- const stdoutHandler = (event) => {
4931
- if (event.detail.pid === this.processId) {
4932
- this.onStdoutHandlers.forEach((h) => h(event.detail.data));
4933
- }
4934
- };
4935
- const stderrHandler = (event) => {
4936
- if (event.detail.pid === this.processId) {
4937
- this.onStderrHandlers.forEach((h) => h(event.detail.data));
4938
- }
4939
- };
4940
- const exitHandler = (event) => {
4941
- if (event.detail.pid === this.processId) {
4942
- this.exited = true;
4943
- this.onExitHandlers.forEach((h) => h(event.detail.code));
4944
- this.removeDomListeners();
4945
- }
4946
- };
4947
- this.addDomListener("craft:process:stdout", stdoutHandler);
4948
- this.addDomListener("craft:process:stderr", stderrHandler);
4949
- this.addDomListener("craft:process:exit", exitHandler);
4967
+ this.processId = id;
4950
4968
  return;
4951
4969
  }
4952
4970
  throw new Error("spawn() requires Craft environment");
4953
4971
  }
4954
- async write(data) {
4972
+ async kill() {
4955
4973
  if (typeof window !== "undefined" && window.craft && this.processId) {
4956
- await callBridge3("process.stdin", { pid: this.processId, data });
4974
+ await shellFacade()?.kill?.(this.processId);
4975
+ this.processId = null;
4957
4976
  }
4958
4977
  }
4959
- async kill(signal = "SIGTERM") {
4960
- if (typeof window !== "undefined" && window.craft && this.processId) {
4961
- await callBridge3("process.kill", { pid: this.processId, signal });
4962
- if (this.exited)
4963
- this.removeDomListeners();
4964
- }
4965
- }
4966
- onStdout(handler) {
4967
- this.onStdoutHandlers.push(handler);
4968
- return () => {
4969
- const idx = this.onStdoutHandlers.indexOf(handler);
4970
- if (idx >= 0)
4971
- this.onStdoutHandlers.splice(idx, 1);
4972
- };
4973
- }
4974
- onStderr(handler) {
4975
- this.onStderrHandlers.push(handler);
4976
- return () => {
4977
- const idx = this.onStderrHandlers.indexOf(handler);
4978
- if (idx >= 0)
4979
- this.onStderrHandlers.splice(idx, 1);
4980
- };
4981
- }
4982
- onExit(handler) {
4983
- this.onExitHandlers.push(handler);
4984
- return () => {
4985
- const idx = this.onExitHandlers.indexOf(handler);
4986
- if (idx >= 0)
4987
- this.onExitHandlers.splice(idx, 1);
4988
- };
4989
- }
4990
4978
  }
4991
4979
  function spawn2(command, args, options) {
4992
4980
  return new ChildProcess(command, args, options);
@@ -4999,7 +4987,7 @@ function cwd() {
4999
4987
  }
5000
4988
  async function homeDir() {
5001
4989
  if (typeof window !== "undefined" && window.craft) {
5002
- return callBridge3("process.homeDir");
4990
+ return (await callBridge3("fs.getHomeDir"))?.path || "/";
5003
4991
  }
5004
4992
  if (typeof process !== "undefined") {
5005
4993
  const os = await import("os");
@@ -5009,7 +4997,7 @@ async function homeDir() {
5009
4997
  }
5010
4998
  async function tempDir() {
5011
4999
  if (typeof window !== "undefined" && window.craft) {
5012
- return callBridge3("process.tempDir");
5000
+ return (await callBridge3("fs.getTempDir"))?.path || "/tmp";
5013
5001
  }
5014
5002
  if (typeof process !== "undefined") {
5015
5003
  const os = await import("os");
@@ -5037,7 +5025,10 @@ function argv() {
5037
5025
  }
5038
5026
  async function open(target) {
5039
5027
  if (typeof window !== "undefined" && window.craft) {
5040
- await callBridge3("process.open", { target });
5028
+ if (/^[a-z][a-z0-9+.-]*:/i.test(target) && !/^[a-z]:[\\/]/i.test(target))
5029
+ await callBridge3("shell.openUrl", { url: target });
5030
+ else
5031
+ await shellFacade()?.openPath?.(target);
5041
5032
  return;
5042
5033
  }
5043
5034
  const platform = getPlatform();
@@ -838,6 +838,23 @@ final class CraftChrome: ObservableObject {
838
838
  @Published var tabs: [Tab] = []
839
839
  @Published var tabAccessory: Tab?
840
840
  private weak var tabAccessoryOwner: AnyObject?
841
+
842
+ /// Where the compact tab actions float over the page, in window
843
+ /// coordinates, and the shell that drew them; nil when nothing floats.
844
+ /// They cover the trailing end of whatever scrolls behind them, so a
845
+ /// screen gives its scroll views that much room at the end (#523): the
846
+ /// last row can be brought clear without the app knowing this geometry.
847
+ private(set) var floatingActions: CGRect?
848
+ private(set) weak var floatingActionsHost: UIView?
849
+ static let floatingActionsDidMove = Notification.Name("CraftFloatingActionsDidMove")
850
+
851
+ func floatingActionsMoved(to frame: CGRect?, in host: UIView?) {
852
+ let next = frame.flatMap { $0.isNull || $0.isEmpty ? nil : $0.integral }
853
+ guard next != floatingActions || (next != nil && host !== floatingActionsHost) else { return }
854
+ floatingActions = next
855
+ floatingActionsHost = next == nil ? nil : host
856
+ NotificationCenter.default.post(name: Self.floatingActionsDidMove, object: self)
857
+ }
841
858
  @Published var selected: String?
842
859
  /// The visible destination may be the accessory, independently of its owning stack.
843
860
  @Published var visiblePath: String?
@@ -1665,6 +1665,8 @@ final class CraftHybridController: UITabBarController, UITabBarControllerDelegat
1665
1665
  override func viewDidLayoutSubviews() {
1666
1666
  super.viewDidLayoutSubviews()
1667
1667
  guard hybrid.controller === self else { return }
1668
+ // Once the actions are where this pass puts them.
1669
+ defer { CraftChrome.shared.floatingActionsMoved(to: floatingActionsFrame(), in: view) }
1668
1670
  #if compiler(>=6.2)
1669
1671
  if #available(iOS 26.0, *), accessoryModel?.iconOnly != true {
1670
1672
  // UIKit already supplies the native safe area. This measurement is
@@ -1701,6 +1703,20 @@ final class CraftHybridController: UITabBarController, UITabBarControllerDelegat
1701
1703
  CraftChrome.shared.layoutChanged(tabBar.isHidden ? 0 : max(0, view.bounds.maxY - tabBar.frame.minY) + accessoryInset)
1702
1704
  }
1703
1705
 
1706
+ /// The compact actions' frame in the window, or nil when none float over
1707
+ /// the page: a full-width shelf is reserved for through the safe area,
1708
+ /// and a hidden tab bar takes its actions with it. A group is its one
1709
+ /// capsule; separate actions are the row of them.
1710
+ private func floatingActionsFrame() -> CGRect? {
1711
+ guard let model = accessoryModel, model.iconOnly, view.window != nil,
1712
+ accessoryGlass.superview === view, !accessoryGlass.isHidden, !tabBar.isHidden else { return nil }
1713
+ var frame = accessoryGlass.frame
1714
+ if model.accessoryLayout == nil {
1715
+ for glass in companionGlasses where !glass.isHidden { frame = frame.union(glass.frame) }
1716
+ }
1717
+ return view.convert(frame, to: view.window)
1718
+ }
1719
+
1704
1720
  /// One capsule above the trailing end of the tab bar, companions first
1705
1721
  /// and the primary action last. Nothing divides the actions: the glass
1706
1722
  /// is one control, and each action is found by its place and its symbol.
@@ -85,6 +85,84 @@ final class CraftNotificationAttachments {
85
85
  // memory. `fetch` and the share sheet take the path; only files made here are
86
86
  // read back for a form, so a screen cannot post an arbitrary file of the app's.
87
87
 
88
+ /// A request waiting on a system picker, as the one picker slot sees it.
89
+ protocol CraftPickerRequest: AnyObject {
90
+ /// Where its picker is.
91
+ var presence: CraftPickerPresence { get }
92
+ /// It has neither been answered by its picker nor finished.
93
+ var isWaiting: Bool { get }
94
+ /// The picker went without a choice or a cancel reaching its delegate.
95
+ /// One that was on screen answers as a cancel; one that never appeared
96
+ /// answers that it could not be presented.
97
+ func pickerLeft(shown: Bool)
98
+ }
99
+
100
+ extension CraftPickerRequest {
101
+ /// Still waiting on a picker that can no longer answer.
102
+ var lostItsPicker: Bool { isWaiting && presence.lost }
103
+ }
104
+
105
+ /// Where a request's picker is: on its way to the screen, on it, or gone.
106
+ ///
107
+ /// UIKit tells a picker's delegate about a choice and about a cancel. It
108
+ /// says nothing when the picker goes because what presented it did (an app
109
+ /// closing the sheet the picker was on), or when it gives a presentation up
110
+ /// before it began: a system picker runs in another process and is presented
111
+ /// once that process answers, and by then the sheet it was to appear on may
112
+ /// have closed ("whose view is not in the window hierarchy", in the console
113
+ /// only). The request then never answered and kept the one picker slot:
114
+ /// every later pick was refused as BUSY until the app was restarted.
115
+ final class CraftPickerPresence {
116
+ weak var picker: UIViewController?
117
+ /// What the picker was handed to for presenting.
118
+ weak var presenter: UIViewController?
119
+ weak var watch: CraftPickerWatch?
120
+
121
+ /// The picker has been on screen.
122
+ var shown: Bool { watch?.shown ?? false }
123
+
124
+ /// The picker cannot answer any more.
125
+ var lost: Bool {
126
+ guard let picker else { return true }
127
+ if picker.presentingViewController != nil { return false }
128
+ // It was on screen, is not now, and nothing presents it.
129
+ if shown { return picker.viewIfLoaded?.window == nil }
130
+ // It has not appeared yet, and what was to present it has gone.
131
+ guard let presenter else { return true }
132
+ return presenter.viewIfLoaded?.window == nil
133
+ }
134
+ }
135
+
136
+ /// A view inside a system picker that says when the picker has been seen
137
+ /// and when it is gone: it leaves the window when the picker does and is
138
+ /// released when the picker is, whichever way that happens.
139
+ final class CraftPickerWatch: UIView {
140
+ private(set) var shown = false
141
+ private var left: ((_ shown: Bool) -> Void)?
142
+
143
+ static func attach(to picker: UIViewController, left: @escaping (_ shown: Bool) -> Void) -> CraftPickerWatch {
144
+ let watch = CraftPickerWatch(frame: .zero)
145
+ watch.isHidden = true
146
+ watch.isUserInteractionEnabled = false
147
+ watch.left = left
148
+ picker.view.addSubview(watch)
149
+ return watch
150
+ }
151
+
152
+ override func didMoveToWindow() {
153
+ super.didMoveToWindow()
154
+ if window != nil { shown = true } else if shown { report() }
155
+ }
156
+
157
+ deinit { report() }
158
+
159
+ private func report() {
160
+ guard let left else { return }
161
+ let shown = shown
162
+ DispatchQueue.main.async { left(shown) }
163
+ }
164
+ }
165
+
88
166
  enum CraftNativeFiles {
89
167
  /// The longest side of a picked photo unless the screen asks otherwise:
90
168
  /// sharp on any phone screen and in a share card, a few hundred kilobytes
@@ -104,6 +182,40 @@ enum CraftNativeFiles {
104
182
  /// The picker on screen, kept alive until it answers. One at a time.
105
183
  private static var activePicker: NSObject?
106
184
 
185
+ /// The slot is free when nothing holds it, or when what holds it is
186
+ /// waiting on a picker that can no longer answer.
187
+ private static func pickerSlotIsFree() -> Bool {
188
+ guard let request = activePicker as? CraftPickerRequest else { return activePicker == nil }
189
+ guard request.lostItsPicker else { return false }
190
+ activePicker = nil
191
+ request.pickerLeft(shown: request.presence.shown)
192
+ return true
193
+ }
194
+
195
+ /// Follow `picker` for the request that is waiting on it.
196
+ private static func watch(_ picker: UIViewController, for request: CraftPickerRequest) {
197
+ let presence = request.presence
198
+ presence.picker = picker
199
+ presence.presenter = CraftPresenter.topViewController()
200
+ presence.watch = CraftPickerWatch.attach(to: picker) { [weak request] shown in request?.pickerLeft(shown: shown) }
201
+ awaitAppearance(of: request, checks: 60)
202
+ }
203
+
204
+ /// Until the picker is on screen nothing of its own can say it never
205
+ /// will be, and UIKit may hold a presentation it cannot make for as long
206
+ /// as the picker's process takes to answer. Look twice a second, for half
207
+ /// a minute at most, and answer for a picker whose presenter has gone.
208
+ private static func awaitAppearance(of request: CraftPickerRequest, checks: Int) {
209
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak request] in
210
+ guard let request, request.isWaiting, !request.presence.shown else { return }
211
+ if request.presence.lost {
212
+ request.pickerLeft(shown: false)
213
+ } else if checks > 1 {
214
+ awaitAppearance(of: request, checks: checks - 1)
215
+ }
216
+ }
217
+ }
218
+
107
219
  // MARK: Files of our own
108
220
 
109
221
  /// A new file called `name`, in a folder of its own so two files can share
@@ -208,7 +320,7 @@ enum CraftNativeFiles {
208
320
  .map { $0.doubleValue }
209
321
  .flatMap { $0.isFinite ? $0 : nil } ?? defaultQuality))
210
322
  let source = options["source"] as? String ?? "library"
211
- guard activePicker == nil else {
323
+ guard pickerSlotIsFree() else {
212
324
  done(.failure(CraftNativeActionError(code: "BUSY", message: "A picker is already open")))
213
325
  return
214
326
  }
@@ -245,6 +357,7 @@ enum CraftNativeFiles {
245
357
  picker.delegate = delegate
246
358
  delegate.controller = picker
247
359
  activePicker = delegate
360
+ watch(picker, for: delegate)
248
361
  if !CraftPresenter.present(picker, from: nil) {
249
362
  delegate.finish(.failure(CraftNativeActionError(code: "PICKER_ERROR", message: "Unable to present the photo picker")))
250
363
  }
@@ -291,7 +404,7 @@ enum CraftNativeFiles {
291
404
  return "\(base).jpg"
292
405
  }
293
406
 
294
- final class LibraryDelegate: NSObject, PHPickerViewControllerDelegate {
407
+ final class LibraryDelegate: NSObject, PHPickerViewControllerDelegate, CraftPickerRequest {
295
408
  let maxPixels: Int
296
409
  let quality: Double
297
410
  let videoLimit: Int?
@@ -353,8 +466,18 @@ enum CraftNativeFiles {
353
466
  }
354
467
  }
355
468
 
469
+ let presence = CraftPickerPresence()
470
+ var isWaiting: Bool { !answered && !finished }
471
+
472
+ func pickerLeft(shown: Bool) {
473
+ guard lostItsPicker else { return }
474
+ answered = true
475
+ finish(shown ? .success(NSNull()) : .failure(CraftNativeActionError(code: "PICKER_ERROR", message: "Unable to present the \(videoLimit == nil ? "photo" : "video") picker")))
476
+ }
477
+
356
478
  func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
357
- guard !answered else { return }
479
+ // A picker whose request was already answered still closes.
480
+ guard !answered else { picker.dismiss(animated: true); return }
358
481
  picker.dismiss(animated: true)
359
482
  guard let provider = results.first?.itemProvider else {
360
483
  answered = true
@@ -403,12 +526,13 @@ enum CraftNativeFiles {
403
526
  picker.delegate = delegate
404
527
  delegate.controller = picker
405
528
  activePicker = delegate
529
+ watch(picker, for: delegate)
406
530
  if !CraftPresenter.present(picker, from: nil) {
407
531
  delegate.finish(.failure(CraftNativeActionError(code: "PICKER_ERROR", message: "Unable to present the camera")))
408
532
  }
409
533
  }
410
534
 
411
- final class CameraDelegate: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
535
+ final class CameraDelegate: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate, CraftPickerRequest {
412
536
  let maxPixels: Int
413
537
  let quality: Double
414
538
  let requestToken: String?
@@ -483,6 +607,15 @@ enum CraftNativeFiles {
483
607
  answered = true
484
608
  finish(.success(NSNull()))
485
609
  }
610
+
611
+ let presence = CraftPickerPresence()
612
+ var isWaiting: Bool { !answered && !finished }
613
+
614
+ func pickerLeft(shown: Bool) {
615
+ guard lostItsPicker else { return }
616
+ answered = true
617
+ finish(shown ? .success(NSNull()) : .failure(CraftNativeActionError(code: "PICKER_ERROR", message: "Unable to present the camera")))
618
+ }
486
619
  }
487
620
 
488
621
  #endif
@@ -493,7 +626,7 @@ enum CraftNativeFiles {
493
626
  /// the provider's URL is valid; no movie bytes cross JavaScriptCore.
494
627
  static func pickVideo(_ options: [String: Any], requestToken: String? = nil, isCancelled: @escaping () -> Bool = { false }, done: @escaping (Result<Any, CraftNativeActionError>) -> Void) {
495
628
  guard !isCancelled() else { done(.failure(importCancelled())); return }
496
- guard activePicker == nil else {
629
+ guard pickerSlotIsFree() else {
497
630
  done(.failure(CraftNativeActionError(code: "BUSY", message: "A picker is already open")))
498
631
  return
499
632
  }
@@ -512,6 +645,7 @@ enum CraftNativeFiles {
512
645
  picker.delegate = delegate
513
646
  delegate.controller = picker
514
647
  activePicker = delegate
648
+ watch(picker, for: delegate)
515
649
  if !CraftPresenter.present(picker, from: nil) {
516
650
  delegate.finish(.failure(CraftNativeActionError(code: "PICKER_ERROR", message: "Unable to present the video picker")))
517
651
  }
@@ -525,6 +659,7 @@ enum CraftNativeFiles {
525
659
  picker.delegate = delegate
526
660
  delegate.controller = picker
527
661
  activePicker = delegate
662
+ watch(picker, for: delegate)
528
663
  if !CraftPresenter.present(picker, from: nil) {
529
664
  delegate.finish(.failure(CraftNativeActionError(code: "PICKER_ERROR", message: "Unable to present the video picker")))
530
665
  }
@@ -538,7 +673,7 @@ enum CraftNativeFiles {
538
673
  /// UTIs, or filename extensions; an empty list means any document.
539
674
  static func pickFile(_ options: [String: Any], requestToken: String? = nil, isCancelled: @escaping () -> Bool = { false }, done: @escaping (Result<Any, CraftNativeActionError>) -> Void) {
540
675
  guard !isCancelled() else { done(.failure(importCancelled())); return }
541
- guard activePicker == nil else {
676
+ guard pickerSlotIsFree() else {
542
677
  done(.failure(CraftNativeActionError(code: "BUSY", message: "A picker is already open")))
543
678
  return
544
679
  }
@@ -567,6 +702,7 @@ enum CraftNativeFiles {
567
702
  picker.delegate = delegate
568
703
  delegate.controller = picker
569
704
  activePicker = delegate
705
+ watch(picker, for: delegate)
570
706
  if !CraftPresenter.present(picker, from: nil) {
571
707
  delegate.finish(.failure(CraftNativeActionError(code: "PICKER_ERROR", message: "Unable to present the file picker")))
572
708
  }
@@ -727,7 +863,7 @@ enum CraftNativeFiles {
727
863
  }
728
864
  }
729
865
 
730
- final class DocumentDelegate: NSObject, UIDocumentPickerDelegate {
866
+ final class DocumentDelegate: NSObject, UIDocumentPickerDelegate, CraftPickerRequest {
731
867
  let limit: Int
732
868
  let video: Bool
733
869
  let requestToken: String?
@@ -768,6 +904,15 @@ enum CraftNativeFiles {
768
904
  finish(.success(video ? NSNull() : []))
769
905
  }
770
906
 
907
+ let presence = CraftPickerPresence()
908
+ var isWaiting: Bool { !answered && !finished }
909
+
910
+ func pickerLeft(shown: Bool) {
911
+ guard lostItsPicker else { return }
912
+ answered = true
913
+ finish(shown ? .success(video ? NSNull() : []) : .failure(CraftNativeActionError(code: "PICKER_ERROR", message: "Unable to present the \(video ? "video" : "file") picker")))
914
+ }
915
+
771
916
  func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
772
917
  guard !answered else { return }
773
918
  answered = true