@blotch/angular-lynx-native 22.3.1 → 22.3.3

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.
Files changed (123) hide show
  1. package/README.md +47 -15
  2. package/dist/android/project.d.ts +114 -1
  3. package/dist/android/project.d.ts.map +1 -1
  4. package/dist/android/project.js +440 -5
  5. package/dist/eject.d.ts +15 -1
  6. package/dist/eject.d.ts.map +1 -1
  7. package/dist/eject.js +14 -2
  8. package/dist/features.d.ts +70 -0
  9. package/dist/features.d.ts.map +1 -0
  10. package/dist/features.js +115 -0
  11. package/dist/files.d.ts +24 -0
  12. package/dist/files.d.ts.map +1 -0
  13. package/dist/files.js +41 -0
  14. package/dist/generate.d.ts +34 -3
  15. package/dist/generate.d.ts.map +1 -1
  16. package/dist/generate.js +78 -19
  17. package/dist/index.d.ts +1 -0
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +16 -2
  20. package/dist/ios/build.d.ts.map +1 -1
  21. package/dist/ios/build.js +8 -2
  22. package/dist/ios/frameworks.d.ts +6 -5
  23. package/dist/ios/frameworks.d.ts.map +1 -1
  24. package/dist/ios/frameworks.js +46 -15
  25. package/dist/ios/project.d.ts +192 -11
  26. package/dist/ios/project.d.ts.map +1 -1
  27. package/dist/ios/project.js +823 -33
  28. package/dist/options.d.ts +208 -1
  29. package/dist/options.d.ts.map +1 -1
  30. package/dist/options.js +154 -0
  31. package/dist/permissions.d.ts +18 -1
  32. package/dist/permissions.d.ts.map +1 -1
  33. package/dist/permissions.js +79 -4
  34. package/dist/plugins.d.ts +245 -0
  35. package/dist/plugins.d.ts.map +1 -0
  36. package/dist/plugins.js +1244 -0
  37. package/package.json +1 -1
  38. package/templates/android/README.md +46 -5
  39. package/templates/android/angular-lynx.properties +2 -0
  40. package/templates/android/app/build.gradle.kts +78 -11
  41. package/templates/android/app/src/main/AndroidManifest.xml +19 -3
  42. package/templates/android/app/src/main/java/dev/angularlynx/shell/AngularLynxPlugins.kt +13 -0
  43. package/templates/android/app/src/main/java/dev/angularlynx/shell/AudioRecorderModule.kt +520 -0
  44. package/templates/android/app/src/main/java/dev/angularlynx/shell/BarcodeScannerModule.kt +144 -0
  45. package/templates/android/app/src/main/java/dev/angularlynx/shell/BiometricsModule.kt +433 -0
  46. package/templates/android/app/src/main/java/dev/angularlynx/shell/BitmapPresenter.kt +98 -0
  47. package/templates/android/app/src/main/java/dev/angularlynx/shell/BitmapRendererContext.kt +175 -0
  48. package/templates/android/app/src/main/java/dev/angularlynx/shell/BluetoothModule.kt +1288 -0
  49. package/templates/android/app/src/main/java/dev/angularlynx/shell/CalendarModule.kt +127 -0
  50. package/templates/android/app/src/main/java/dev/angularlynx/shell/Canvas2DContext.kt +1557 -0
  51. package/templates/android/app/src/main/java/dev/angularlynx/shell/Canvas2DOps.kt +63 -0
  52. package/templates/android/app/src/main/java/dev/angularlynx/shell/CanvasFilter.kt +357 -0
  53. package/templates/android/app/src/main/java/dev/angularlynx/shell/CanvasUI.kt +4 -3
  54. package/templates/android/app/src/main/java/dev/angularlynx/shell/EdgeToEdgeOverlay.kt +24 -0
  55. package/templates/android/app/src/main/java/dev/angularlynx/shell/EngineThreadHint.kt +156 -0
  56. package/templates/android/app/src/main/java/dev/angularlynx/shell/FilePickerModule.kt +263 -0
  57. package/templates/android/app/src/main/java/dev/angularlynx/shell/GeolocationModule.kt +557 -0
  58. package/templates/android/app/src/main/java/dev/angularlynx/shell/HapticsModule.kt +82 -0
  59. package/templates/android/app/src/main/java/dev/angularlynx/shell/HostElementUI.kt +331 -0
  60. package/templates/android/app/src/main/java/dev/angularlynx/shell/ImagePickerModule.kt +143 -0
  61. package/templates/android/app/src/main/java/dev/angularlynx/shell/ImagePipeline.kt +83 -0
  62. package/templates/android/app/src/main/java/dev/angularlynx/shell/MainActivity.kt +523 -9
  63. package/templates/android/app/src/main/java/dev/angularlynx/shell/ModuleBytes.kt +58 -0
  64. package/templates/android/app/src/main/java/dev/angularlynx/shell/MotionModule.kt +332 -0
  65. package/templates/android/app/src/main/java/dev/angularlynx/shell/NetworkStatus.kt +121 -0
  66. package/templates/android/app/src/main/java/dev/angularlynx/shell/NfcModule.kt +274 -0
  67. package/templates/android/app/src/main/java/dev/angularlynx/shell/PermissionRequests.kt +35 -0
  68. package/templates/android/app/src/main/java/dev/angularlynx/shell/PhotoLibraryModule.kt +355 -0
  69. package/templates/android/app/src/main/java/dev/angularlynx/shell/ShareTargetModule.kt +234 -0
  70. package/templates/android/app/src/main/java/dev/angularlynx/shell/ShellApplication.kt +7 -8
  71. package/templates/android/app/src/main/java/dev/angularlynx/shell/ShellModule.kt +58 -4
  72. package/templates/android/app/src/main/java/dev/angularlynx/shell/StoreReviewModule.kt +66 -0
  73. package/templates/android/app/src/main/java/dev/angularlynx/shell/SystemFontFamilies.kt +68 -0
  74. package/templates/android/app/src/main/java/dev/angularlynx/shell/TrackingModule.kt +74 -0
  75. package/templates/android/app/src/main/java/dev/angularlynx/shell/VideoFrameTarget.kt +429 -0
  76. package/templates/android/app/src/main/java/dev/angularlynx/shell/VideoUI.kt +676 -0
  77. package/templates/android/app/src/main/java/dev/angularlynx/shell/WebGLContext.kt +128 -13
  78. package/templates/android/app/src/main/java/dev/angularlynx/shell/WebGLModule.kt +493 -65
  79. package/templates/android/app/src/main/java/dev/angularlynx/shell/WifiModule.kt +429 -0
  80. package/templates/android/app/src/main/res/values/biometrics.xml +9 -0
  81. package/templates/android/app/src/main/res/values/share_target.xml +11 -0
  82. package/templates/android/app/src/main/res/xml/backup_rules.xml +5 -3
  83. package/templates/android/app/src/main/res/xml/data_extraction_rules.xml +6 -3
  84. package/templates/android/app/src/main/res/xml/share_paths.xml +7 -2
  85. package/templates/android/build.gradle.kts +1 -1
  86. package/templates/android/gradle/wrapper/gradle-wrapper.properties +2 -2
  87. package/templates/ios/App/AngularLynxBitmapRendererContext.m +188 -0
  88. package/templates/ios/App/AngularLynxCanvas2DContext.m +2467 -0
  89. package/templates/ios/App/AngularLynxCanvas2DOps.h +61 -0
  90. package/templates/ios/App/AngularLynxPlugins.swift +22 -0
  91. package/templates/ios/App/AngularLynxVideo.h +37 -0
  92. package/templates/ios/App/AngularLynxVideo.m +435 -0
  93. package/templates/ios/App/AngularLynxWebGL.h +69 -7
  94. package/templates/ios/App/AngularLynxWebGL.m +538 -29
  95. package/templates/ios/App/AngularLynxWebGLContext.m +148 -46
  96. package/templates/ios/App/AnimationFrameRate.swift +66 -0
  97. package/templates/ios/App/AppDelegate.swift +37 -3
  98. package/templates/ios/App/AppleSignInButton.swift +106 -0
  99. package/templates/ios/App/AppleSignInModule.swift +222 -0
  100. package/templates/ios/App/AudioRecorderModule.swift +433 -0
  101. package/templates/ios/App/BarcodeScannerModule.swift +284 -0
  102. package/templates/ios/App/BiometricsModule.swift +256 -0
  103. package/templates/ios/App/BluetoothModule.swift +1086 -0
  104. package/templates/ios/App/CalendarModule.swift +158 -0
  105. package/templates/ios/App/FilePickerModule.swift +240 -0
  106. package/templates/ios/App/GeolocationModule.swift +455 -0
  107. package/templates/ios/App/HapticsModule.swift +90 -0
  108. package/templates/ios/App/HostElementUI.swift +270 -0
  109. package/templates/ios/App/ImagePickerModule.swift +160 -1
  110. package/templates/ios/App/Info.plist +2 -0
  111. package/templates/ios/App/LynxViewController.swift +274 -9
  112. package/templates/ios/App/MotionModule.swift +430 -0
  113. package/templates/ios/App/NetworkStatus.swift +41 -0
  114. package/templates/ios/App/NfcModule.swift +346 -0
  115. package/templates/ios/App/PhotoLibraryModule.swift +169 -0
  116. package/templates/ios/App/ShareTargetModule.swift +150 -0
  117. package/templates/ios/App/ShellModule.swift +17 -0
  118. package/templates/ios/App/StoreReviewModule.swift +61 -0
  119. package/templates/ios/App/TrackingModule.swift +121 -0
  120. package/templates/ios/App/WifiModule.swift +237 -0
  121. package/templates/ios/App/XElementRegistry.swift +13 -3
  122. package/templates/ios/ShareExtension/Info.plist +42 -0
  123. package/templates/ios/ShareExtension/ShareViewController.swift +387 -0
@@ -0,0 +1,158 @@
1
+ import EventKit
2
+ import EventKitUI
3
+ import Lynx
4
+ import UIKit
5
+
6
+ /// The native module behind the runtime's `LynxCalendar`, which calls it as
7
+ /// `NativeModules.AngularLynxCalendar` (from the background thread, where
8
+ /// NativeModules lives).
9
+ ///
10
+ /// `addEvent` opens the system's event editor, EventKitUI's
11
+ /// `EKEventEditViewController`, filled in with the app's event, and calls
12
+ /// back once with `{ result: "saved" }` or `{ result: "canceled" }` when the
13
+ /// person closes it, or `{ error, message }`. From iOS 17 the editor runs
14
+ /// outside the app and writes the event itself, so the app needs no calendar
15
+ /// permission and no usage description for it: it never sees the person's
16
+ /// calendars. Before iOS 17 the editor needs full calendar access, which
17
+ /// this module doesn't ask for, so it answers `unavailable` there.
18
+ ///
19
+ /// The generator leaves this file out of an app whose angular.json doesn't
20
+ /// set `calendar`, and LynxViewController registers the module by its
21
+ /// Objective-C name only when it's there, hence the `@objc` name.
22
+ @objc(AngularLynxCalendarModule)
23
+ final class CalendarModule: NSObject, LynxModule, EKEventEditViewDelegate,
24
+ UIAdaptivePresentationControllerDelegate
25
+ {
26
+ static var name: String { "AngularLynxCalendar" }
27
+
28
+ static var methodLookup: [String: String] {
29
+ ["addEvent": NSStringFromSelector(#selector(addEvent(_:callback:)))]
30
+ }
31
+
32
+ /// Who to tell how the open editor closed. The editor keeps its delegate
33
+ /// weakly, and Lynx keeps the module, so the module is the delegate.
34
+ private var open: LynxCallbackBlock?
35
+
36
+ override init() {
37
+ super.init()
38
+ }
39
+
40
+ // Swift can't import an optional initializer as optional, so Lynx's
41
+ // initWithParam: is required here. Registered without a param, the module
42
+ // ignores it.
43
+ init(param: Any) {
44
+ super.init()
45
+ }
46
+
47
+ /// Opens the editor with `event`: `{ title, start, end, allDay, location?,
48
+ /// notes? }`, with the times in milliseconds since 1970.
49
+ @objc func addEvent(_ event: [String: Any], callback: @escaping LynxCallbackBlock) {
50
+ // Lynx calls modules off the main thread, and the editor is UI.
51
+ DispatchQueue.main.async {
52
+ self.present(event, callback)
53
+ }
54
+ }
55
+
56
+ private func present(_ event: [String: Any], _ callback: @escaping LynxCallbackBlock) {
57
+ guard #available(iOS 17.0, *) else {
58
+ callback([
59
+ "error": "unavailable",
60
+ "message":
61
+ "Adding an event without calendar access needs iOS 17 or later.",
62
+ ])
63
+ return
64
+ }
65
+ guard open == nil else {
66
+ callback(["error": "failed", "message": "The event editor is already open."])
67
+ return
68
+ }
69
+ guard
70
+ let title = event["title"] as? String,
71
+ let start = (event["start"] as? NSNumber)?.doubleValue,
72
+ let end = (event["end"] as? NSNumber)?.doubleValue
73
+ else {
74
+ callback(["error": "failed", "message": "The event needs a title, a start and an end."])
75
+ return
76
+ }
77
+ guard let presenter = topViewController() else {
78
+ callback(["error": "failed", "message": "There's no screen to open the editor over."])
79
+ return
80
+ }
81
+ // UIKit refuses to present over a controller that's still coming or
82
+ // going, and then never calls the editor's delegate, which would leave
83
+ // this request unanswered and every later one "already open".
84
+ guard !presenter.isBeingPresented, !presenter.isBeingDismissed else {
85
+ callback(["error": "failed", "message": "Another screen is still opening or closing."])
86
+ return
87
+ }
88
+ // A store with no access is all the editor needs from iOS 17: it saves
89
+ // the event in its own process.
90
+ let store = EKEventStore()
91
+ let draft = EKEvent(eventStore: store)
92
+ draft.title = title
93
+ let allDay = (event["allDay"] as? NSNumber)?.boolValue ?? false
94
+ let startDate = Date(timeIntervalSince1970: start / 1000)
95
+ let endDate = Date(timeIntervalSince1970: end / 1000)
96
+ if allDay {
97
+ // Only an all-day event's days count, and the runtime accepts one that
98
+ // ends earlier in its last day than it starts in its first. EventKit
99
+ // won't save an end before the start, so both become their day's
100
+ // start, which is how it keeps an all-day event's days.
101
+ draft.startDate = Calendar.current.startOfDay(for: startDate)
102
+ draft.endDate = Calendar.current.startOfDay(for: endDate)
103
+ } else {
104
+ draft.startDate = startDate
105
+ draft.endDate = endDate
106
+ }
107
+ draft.isAllDay = allDay
108
+ draft.location = event["location"] as? String
109
+ draft.notes = event["notes"] as? String
110
+
111
+ let editor = EKEventEditViewController()
112
+ editor.eventStore = store
113
+ editor.event = draft
114
+ editor.editViewDelegate = self
115
+ open = callback
116
+ presenter.present(editor, animated: true)
117
+ // Swiping the sheet down closes it without the delegate's answer.
118
+ editor.presentationController?.delegate = self
119
+ }
120
+
121
+ func eventEditViewController(
122
+ _ controller: EKEventEditViewController, didCompleteWith action: EKEventEditViewAction
123
+ ) {
124
+ // .deleted can't happen to an event that was never saved; it's a cancel
125
+ // to the app.
126
+ let result = action == .saved ? "saved" : "canceled"
127
+ // Answered once the editor has gone, so `open` keeps a second addEvent()
128
+ // out until UIKit can present again.
129
+ controller.dismiss(animated: true) {
130
+ self.finish(result)
131
+ }
132
+ }
133
+
134
+ // Called once a swipe down has finished closing the sheet.
135
+ func presentationControllerDidDismiss(_ presentationController: UIPresentationController) {
136
+ finish("canceled")
137
+ }
138
+
139
+ /// Calls back once, however the editor closed.
140
+ private func finish(_ result: String) {
141
+ guard let callback = open else { return }
142
+ open = nil
143
+ callback(["result": result])
144
+ }
145
+
146
+ /// The view controller on top, which the editor opens over.
147
+ private func topViewController() -> UIViewController? {
148
+ let window = UIApplication.shared.connectedScenes
149
+ .compactMap { $0 as? UIWindowScene }
150
+ .flatMap(\.windows)
151
+ .first(where: \.isKeyWindow)
152
+ var top = window?.rootViewController
153
+ while let presented = top?.presentedViewController {
154
+ top = presented
155
+ }
156
+ return top
157
+ }
158
+ }
@@ -0,0 +1,240 @@
1
+ import Lynx
2
+ import UIKit
3
+ import UniformTypeIdentifiers
4
+
5
+ /// The native module behind the runtime's `LynxFilePicker`, which calls it as
6
+ /// `NativeModules.AngularLynxFilePicker` (from the background thread, where
7
+ /// NativeModules lives).
8
+ ///
9
+ /// Lynx has no `<input type="file">` and no downloads.
10
+ /// UIDocumentPickerViewController stands in for both: it shows the Files
11
+ /// app's places (iCloud Drive, On My iPhone, other apps' file providers),
12
+ /// runs outside the app and hands over only what the person chose, so the
13
+ /// app needs no permission.
14
+ ///
15
+ /// `pick` opens it for the content types asked for, as copies the app owns
16
+ /// (`asCopy`), so nothing needs a security-scoped bookmark, and reads them
17
+ /// back as base64, since the module's callback and the runtime's relay to
18
+ /// the main thread carry only what JSON can. `save` writes the file to a
19
+ /// temporary file of its name and exports a copy of it wherever the person
20
+ /// chooses.
21
+ ///
22
+ /// The generator leaves this file out of an app whose angular.json doesn't
23
+ /// set `filePicker`, and LynxViewController registers the module by its
24
+ /// Objective-C name only when it's there, hence the `@objc` name.
25
+ @objc(AngularLynxFilePickerModule)
26
+ final class FilePickerModule: NSObject, LynxModule, UIDocumentPickerDelegate,
27
+ UIAdaptivePresentationControllerDelegate
28
+ {
29
+ static var name: String { "AngularLynxFilePicker" }
30
+
31
+ static var methodLookup: [String: String] {
32
+ [
33
+ "pick": NSStringFromSelector(#selector(pick(_:callback:))),
34
+ "save": NSStringFromSelector(#selector(save(_:callback:))),
35
+ ]
36
+ }
37
+
38
+ /// The open picker, until it closes: what it's for and who to tell.
39
+ private enum Request {
40
+ case pick(maxBytes: Int, callback: LynxCallbackBlock)
41
+ /// `folder` holds the temporary copy that's exported, deleted after.
42
+ case save(folder: URL, callback: LynxCallbackBlock)
43
+ }
44
+ private var open: Request?
45
+
46
+ override init() {
47
+ super.init()
48
+ }
49
+
50
+ // Swift can't import an optional initializer as optional, so Lynx's
51
+ // initWithParam: is required here. Registered without a param, the module
52
+ // ignores it.
53
+ init(param: Any) {
54
+ super.init()
55
+ }
56
+
57
+ /// Opens the picker and calls back once with `{ files: [{ base64, name,
58
+ /// type }] }`, `{ canceled: true }` when the person closes it, or
59
+ /// `{ error: "too-large" | "failed", message }`.
60
+ @objc func pick(_ options: [String: Any], callback: @escaping LynxCallbackBlock) {
61
+ let types = Self.contentTypes(options["types"] as? [String] ?? [])
62
+ let multiple = (options["multiple"] as? NSNumber)?.boolValue ?? false
63
+ let maxBytes = (options["maxBytes"] as? NSNumber)?.intValue ?? Int.max
64
+ // Lynx calls modules off the main thread, and the picker is UI.
65
+ DispatchQueue.main.async {
66
+ let picker = UIDocumentPickerViewController(forOpeningContentTypes: types, asCopy: true)
67
+ picker.allowsMultipleSelection = multiple
68
+ self.present(picker, .pick(maxBytes: maxBytes, callback: callback))
69
+ }
70
+ }
71
+
72
+ /// Writes `{ base64, name }` to a temporary file and lets the person
73
+ /// choose where to export it. Calls back once with `{ saved: true }`,
74
+ /// `{ saved: false }` when they close the picker, or
75
+ /// `{ error: "failed", message }`.
76
+ @objc func save(_ file: [String: Any], callback: @escaping LynxCallbackBlock) {
77
+ guard let base64 = file["base64"] as? String, let data = Data(base64Encoded: base64) else {
78
+ callback(["error": "failed", "message": "The file to save had no bytes."])
79
+ return
80
+ }
81
+ // A folder of its own, so the exported file keeps exactly its name, and
82
+ // two saves of the same name can't overwrite each other.
83
+ let folder = FileManager.default.temporaryDirectory
84
+ .appendingPathComponent("angular-lynx-save", isDirectory: true)
85
+ .appendingPathComponent(UUID().uuidString, isDirectory: true)
86
+ let url = folder.appendingPathComponent(Self.fileName(file["name"] as? String))
87
+ do {
88
+ try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
89
+ try data.write(to: url)
90
+ } catch {
91
+ callback(["error": "failed", "message": error.localizedDescription])
92
+ return
93
+ }
94
+ DispatchQueue.main.async {
95
+ let picker = UIDocumentPickerViewController(forExporting: [url], asCopy: true)
96
+ self.present(picker, .save(folder: folder, callback: callback))
97
+ }
98
+ }
99
+
100
+ private func present(_ picker: UIDocumentPickerViewController, _ request: Request) {
101
+ guard open == nil else {
102
+ finish(request, ["error": "failed", "message": "A picker is already open."])
103
+ return
104
+ }
105
+ guard let presenter = topViewController() else {
106
+ finish(request, ["error": "failed", "message": "There's no screen to open the picker over."])
107
+ return
108
+ }
109
+ picker.delegate = self
110
+ open = request
111
+ presenter.present(picker, animated: true)
112
+ // Swiping the sheet down closes it without the delegate's cancel call.
113
+ picker.presentationController?.delegate = self
114
+ }
115
+
116
+ func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
117
+ guard let request = take() else { return }
118
+ switch request {
119
+ case .save:
120
+ finish(request, ["saved": true])
121
+ case .pick(let maxBytes, let callback):
122
+ // Reading a large file takes a moment: off the main thread.
123
+ DispatchQueue.global(qos: .userInitiated).async {
124
+ callback(Self.read(urls, maxBytes: maxBytes))
125
+ // The copies are the app's, in its temporary folder: once their
126
+ // bytes are on their way, nothing reads them again.
127
+ for url in urls {
128
+ try? FileManager.default.removeItem(at: url)
129
+ }
130
+ }
131
+ }
132
+ }
133
+
134
+ // UIKit's British spelling, which the delegate method must match.
135
+ // cspell:disable-next-line
136
+ func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
137
+ closed()
138
+ }
139
+
140
+ func presentationControllerDidDismiss(_ presentationController: UIPresentationController) {
141
+ closed()
142
+ }
143
+
144
+ /// The person closed the picker without choosing.
145
+ private func closed() {
146
+ guard let request = take() else { return }
147
+ switch request {
148
+ case .pick: finish(request, ["canceled": true])
149
+ case .save: finish(request, ["saved": false])
150
+ }
151
+ }
152
+
153
+ private func take() -> Request? {
154
+ let request = open
155
+ open = nil
156
+ return request
157
+ }
158
+
159
+ /// Calls back, and deletes a save's temporary copy, which the picker has
160
+ /// exported by then.
161
+ private func finish(_ request: Request, _ result: [String: Any]) {
162
+ switch request {
163
+ case .pick(_, let callback):
164
+ callback(result)
165
+ case .save(let folder, let callback):
166
+ try? FileManager.default.removeItem(at: folder)
167
+ callback(result)
168
+ }
169
+ }
170
+
171
+ /// The callback's answer for the picked files: their bytes, names and
172
+ /// types, or too-large when they hold more than the runtime can carry,
173
+ /// checked from their sizes before anything is read.
174
+ private static func read(_ urls: [URL], maxBytes: Int) -> [String: Any] {
175
+ let total = urls.reduce(0) { sum, url in
176
+ sum + ((try? url.resourceValues(forKeys: [.fileSizeKey]).fileSize) ?? 0)
177
+ }
178
+ if total > maxBytes {
179
+ return ["error": "too-large", "message": "The files picked are too large."]
180
+ }
181
+ var files: [[String: Any]] = []
182
+ for url in urls {
183
+ guard let data = try? Data(contentsOf: url) else {
184
+ return ["error": "failed", "message": "\(url.lastPathComponent) couldn't be read."]
185
+ }
186
+ files.append([
187
+ "base64": data.base64EncodedString(),
188
+ "name": url.lastPathComponent,
189
+ "type": UTType(filenameExtension: url.pathExtension)?.preferredMIMEType
190
+ ?? "application/octet-stream",
191
+ ])
192
+ }
193
+ return ["files": files]
194
+ }
195
+
196
+ /// The content types for `LynxFilePicker`'s `types`, which are given as
197
+ /// an `<input type="file">`'s `accept`: MIME types, a family such as
198
+ /// `image/*`, or extensions such as `.docx`. Any file when none is given,
199
+ /// or none is one iOS knows.
200
+ private static func contentTypes(_ types: [String]) -> [UTType] {
201
+ let families: [String: UTType] = [
202
+ "*/*": .data,
203
+ "image/*": .image,
204
+ "audio/*": .audio,
205
+ "video/*": .movie,
206
+ "text/*": .text,
207
+ "application/*": .data,
208
+ ]
209
+ let resolved = types.compactMap { type -> UTType? in
210
+ if type.hasPrefix(".") {
211
+ return UTType(filenameExtension: String(type.dropFirst()))
212
+ }
213
+ if let family = families[type.lowercased()] { return family }
214
+ return UTType(mimeType: type)
215
+ }
216
+ // .data, not .item: an item can be a folder, which has no bytes to read
217
+ // and would fail the whole pick. Regular files are all data.
218
+ return resolved.isEmpty ? [.data] : resolved
219
+ }
220
+
221
+ /// A name a file can have: a slash would make it a path.
222
+ private static func fileName(_ name: String?) -> String {
223
+ let cleaned = (name ?? "").replacingOccurrences(of: "/", with: "_")
224
+ .replacingOccurrences(of: ":", with: "_")
225
+ return cleaned.isEmpty ? "file" : cleaned
226
+ }
227
+
228
+ /// The view controller on top, which the picker opens over.
229
+ private func topViewController() -> UIViewController? {
230
+ let window = UIApplication.shared.connectedScenes
231
+ .compactMap { $0 as? UIWindowScene }
232
+ .flatMap(\.windows)
233
+ .first(where: \.isKeyWindow)
234
+ var top = window?.rootViewController
235
+ while let presented = top?.presentedViewController {
236
+ top = presented
237
+ }
238
+ return top
239
+ }
240
+ }