@blotch/angular-lynx-native 22.3.2 → 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 (53) hide show
  1. package/README.md +8 -2
  2. package/dist/android/project.d.ts +27 -3
  3. package/dist/android/project.d.ts.map +1 -1
  4. package/dist/android/project.js +80 -9
  5. package/dist/eject.d.ts.map +1 -1
  6. package/dist/eject.js +1 -0
  7. package/dist/files.d.ts +24 -0
  8. package/dist/files.d.ts.map +1 -0
  9. package/dist/files.js +41 -0
  10. package/dist/generate.d.ts +17 -2
  11. package/dist/generate.d.ts.map +1 -1
  12. package/dist/generate.js +68 -17
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +8 -1
  15. package/dist/ios/project.d.ts +21 -2
  16. package/dist/ios/project.d.ts.map +1 -1
  17. package/dist/ios/project.js +58 -2
  18. package/dist/options.d.ts +68 -0
  19. package/dist/options.d.ts.map +1 -1
  20. package/dist/options.js +27 -0
  21. package/dist/permissions.d.ts.map +1 -1
  22. package/dist/permissions.js +18 -3
  23. package/dist/plugins.d.ts +245 -0
  24. package/dist/plugins.d.ts.map +1 -0
  25. package/dist/plugins.js +1244 -0
  26. package/package.json +1 -1
  27. package/templates/android/README.md +12 -4
  28. package/templates/android/app/build.gradle.kts +27 -9
  29. package/templates/android/app/src/main/AndroidManifest.xml +5 -0
  30. package/templates/android/app/src/main/java/dev/angularlynx/shell/AngularLynxPlugins.kt +13 -0
  31. package/templates/android/app/src/main/java/dev/angularlynx/shell/AudioRecorderModule.kt +520 -0
  32. package/templates/android/app/src/main/java/dev/angularlynx/shell/EdgeToEdgeOverlay.kt +24 -0
  33. package/templates/android/app/src/main/java/dev/angularlynx/shell/EngineThreadHint.kt +156 -0
  34. package/templates/android/app/src/main/java/dev/angularlynx/shell/GeolocationModule.kt +557 -0
  35. package/templates/android/app/src/main/java/dev/angularlynx/shell/HostElementUI.kt +331 -0
  36. package/templates/android/app/src/main/java/dev/angularlynx/shell/ImagePickerModule.kt +143 -0
  37. package/templates/android/app/src/main/java/dev/angularlynx/shell/ImagePipeline.kt +83 -0
  38. package/templates/android/app/src/main/java/dev/angularlynx/shell/MainActivity.kt +153 -9
  39. package/templates/android/app/src/main/java/dev/angularlynx/shell/NetworkStatus.kt +121 -0
  40. package/templates/android/app/src/main/java/dev/angularlynx/shell/PermissionRequests.kt +10 -0
  41. package/templates/android/app/src/main/java/dev/angularlynx/shell/PhotoLibraryModule.kt +203 -16
  42. package/templates/android/app/src/main/java/dev/angularlynx/shell/ShellApplication.kt +1 -8
  43. package/templates/android/app/src/main/java/dev/angularlynx/shell/ShellModule.kt +11 -1
  44. package/templates/android/app/src/main/res/xml/share_paths.xml +7 -2
  45. package/templates/ios/App/AngularLynxPlugins.swift +22 -0
  46. package/templates/ios/App/AnimationFrameRate.swift +66 -0
  47. package/templates/ios/App/AppDelegate.swift +3 -1
  48. package/templates/ios/App/AudioRecorderModule.swift +433 -0
  49. package/templates/ios/App/GeolocationModule.swift +455 -0
  50. package/templates/ios/App/HostElementUI.swift +270 -0
  51. package/templates/ios/App/ImagePickerModule.swift +160 -1
  52. package/templates/ios/App/LynxViewController.swift +66 -5
  53. package/templates/ios/App/NetworkStatus.swift +41 -0
@@ -0,0 +1,270 @@
1
+ import Lynx
2
+ import UIKit
3
+
4
+ /// A native element that shows its Lynx children in a view outside the
5
+ /// LynxView, such as a system sheet's, a popover's or a dialog's, and keeps
6
+ /// them interactive there.
7
+ ///
8
+ /// Lynx hit-tests a touch from the LynxView it belongs to, against the frames
9
+ /// of the elements inside it, so a child whose view is moved out of the
10
+ /// LynxView still draws but never gets a tap, a touch or a gesture.
11
+ /// `showChildren(in:)` moves the element's own view, with every view Lynx put
12
+ /// in it, so the elements' views stay where Lynx's tree expects them relative
13
+ /// to each other, and gives it an event handler of its own rooted at the
14
+ /// element, as Lynx's `<overlay>` does for the window it shows in. Touches in
15
+ /// the container then reach the element's children as they would in the
16
+ /// LynxView: their `bindtap`, `bindtouchmove` and the rest.
17
+ ///
18
+ /// Its own background, border and box shadow go with it. Lynx draws them in
19
+ /// layers beside its view's layer rather than in it, so they're moved along
20
+ /// with the view, and kept lined up with it while it's in the container.
21
+ ///
22
+ /// A plugin's element subclasses it rather than `LynxUI<UIView>`, lays itself
23
+ /// out with CSS like any element (the width and height it has there are the
24
+ /// ones it keeps in the container), and calls `showChildren(in:)` when its
25
+ /// container appears and `returnChildren()` once it has gone.
26
+ class HostElementUI: LynxUI<UIView> {
27
+ /// Dispatches touches in the element's view while it's shown elsewhere.
28
+ /// Only then: in the LynxView, the LynxView's own handler does, and two
29
+ /// would send each event twice.
30
+ private var eventHandler: LynxEventHandler?
31
+ /// The gesture arena index `eventHandler` was given, to give it back.
32
+ private var arenaIndex = -1
33
+
34
+ /// Whether the element's view is in a container of the element's, rather
35
+ /// than in the LynxView.
36
+ var isShowingChildrenElsewhere: Bool { eventHandler != nil }
37
+
38
+ /// The element's view is one that finds the touch's target for
39
+ /// `eventHandler`, so it isn't for a subclass to change.
40
+ final override func createView() -> UIView? {
41
+ let view = HostedView()
42
+ view.host = self
43
+ return view
44
+ }
45
+
46
+ /// Has `eventHandler` find the element a touch at `point` lands on. Lynx's
47
+ /// handler hit-tests while UIKit does, from its root view's
48
+ /// `hitTest(_:with:)` (a LynxView's, or the container `<overlay>` shows in),
49
+ /// and dispatches the touch's taps and moves to the element it found.
50
+ fileprivate func findTouchTarget(at point: CGPoint, with event: UIEvent?) {
51
+ eventHandler?.hitTest(point, with: event)
52
+ }
53
+
54
+ /// Moves the element's view, with its children, its background, border
55
+ /// and box shadow, to the top left of `container`, and dispatches their
56
+ /// touches from there.
57
+ func showChildren(in container: UIView) {
58
+ let view = view()
59
+ let outer = Self.outermostView(of: self)
60
+ container.addSubview(outer)
61
+ if outer !== view {
62
+ Self.fill(outer)
63
+ }
64
+ if eventHandler == nil, let context, let emitter = context.eventEmitter {
65
+ let handler = LynxEventHandler(rootView: view, withRootUI: self)
66
+ handler.updateUiOwner(context.uiOwner, eventEmitter: emitter)
67
+ arenaIndex = Self.join(handler, toArenaOf: context.eventHandler)
68
+ eventHandler = handler
69
+ }
70
+ pinToContainer()
71
+ }
72
+
73
+ /// Puts the element's view back in the LynxView, where Lynx put it, and
74
+ /// leaves its touches to the LynxView again.
75
+ func returnChildren() {
76
+ guard let handler = eventHandler else { return }
77
+ handler.removeEventGestures()
78
+ if arenaIndex >= 0 {
79
+ handler.removeGestureArenaManager(arenaIndex)
80
+ }
81
+ eventHandler = nil
82
+ arenaIndex = -1
83
+ if let parent {
84
+ returnView(to: parent)
85
+ } else {
86
+ Self.outermostView(of: self).removeFromSuperview()
87
+ }
88
+ keepDrawnLayersWithView()
89
+ // Back to the frame Lynx's layout gives the element, and its layers with
90
+ // it.
91
+ frameDidChange()
92
+ }
93
+
94
+ /// Puts the element's view back in `parent`'s, in the order of `parent`'s
95
+ /// children, as Lynx keeps their views: below the next sibling whose view
96
+ /// is there, or else above the one before it. Not at the element's index
97
+ /// among the children, which counts siblings shown elsewhere too, and the
98
+ /// parent's views that aren't an element's, such as a scroll view's
99
+ /// indicators. Below the sibling's background and above its border, as
100
+ /// Lynx's `insertChild` orders their layers, so that neither draws over the
101
+ /// other where it didn't before.
102
+ private func returnView(to parent: LynxUI<UIView>) {
103
+ let container = parent.view()
104
+ let outer = Self.outermostView(of: self)
105
+ let siblings = parent.children.compactMap { $0 as? LynxUI<UIView> }
106
+ let index = siblings.firstIndex { $0 === self } ?? siblings.count
107
+ let attached = { (sibling: LynxUI<UIView>) in
108
+ Self.outermostView(of: sibling).superview === container
109
+ }
110
+ if let sibling = siblings[(min(index + 1, siblings.count))...].first(where: attached) {
111
+ container.insertSubview(outer, belowSubview: Self.outermostView(of: sibling))
112
+ container.layer.insertSublayer(outer.layer, below: Self.bottomLayer(of: sibling))
113
+ } else if let sibling = siblings[..<index].last(where: attached) {
114
+ container.insertSubview(outer, aboveSubview: Self.outermostView(of: sibling))
115
+ container.layer.insertSublayer(outer.layer, above: Self.topLayer(of: sibling))
116
+ } else {
117
+ container.addSubview(outer)
118
+ }
119
+ if outer !== view() {
120
+ Self.fill(outer)
121
+ }
122
+ }
123
+
124
+ /// The view that holds `ui`'s view and its layers in its parent's: the view
125
+ /// Lynx wraps them in for an opacity drawn as a group or a mask
126
+ /// (`LynxBackgroundManager`'s `opacityView`, with its background and border
127
+ /// layers inside it), or else the view itself.
128
+ private static func outermostView(of ui: LynxUI<UIView>) -> UIView {
129
+ let view = ui.view()
130
+ // `opacityView` is declared nonnull, but Lynx makes it only when it needs
131
+ // one, so it's read as optional.
132
+ guard let wrapper = ui.backgroundManager?.opacityView as UIView?,
133
+ view.superview === wrapper
134
+ else { return view }
135
+ return wrapper
136
+ }
137
+
138
+ /// `ui`'s lowest layer in its parent's: its background's, below its view's.
139
+ private static func bottomLayer(of ui: LynxUI<UIView>) -> CALayer {
140
+ let outer = outermostView(of: ui)
141
+ let bottom = ui.bottomLayer()
142
+ return bottom.superlayer === outer.layer.superlayer ? bottom : outer.layer
143
+ }
144
+
145
+ /// `ui`'s highest layer in its parent's: its border's when it draws over its
146
+ /// view's.
147
+ private static func topLayer(of ui: LynxUI<UIView>) -> CALayer {
148
+ let outer = outermostView(of: ui)
149
+ let top = ui.topLayer()
150
+ return top.superlayer === outer.layer.superlayer ? top : outer.layer
151
+ }
152
+
153
+ /// Sizes the view Lynx wraps an element in for its opacity to the one it's
154
+ /// in, as Lynx does when it makes it.
155
+ private static func fill(_ wrapper: UIView) {
156
+ guard let superview = wrapper.superview else { return }
157
+ wrapper.frame = CGRect(origin: .zero, size: superview.bounds.size)
158
+ }
159
+
160
+ /// Keeps the layers Lynx draws the element's background, border and box
161
+ /// shadow in (the shadows inside the background's, the outline inside the
162
+ /// border's) beside its view's layer, and lined up with it.
163
+ ///
164
+ /// `LynxBackgroundManager` puts them in the view's superlayer, beside the
165
+ /// view's layer rather than in it, and adds them again only when it next
166
+ /// makes one, so moving the view alone leaves them on the page. They go in
167
+ /// the order Lynx's `insertChild` gives them: the background below the
168
+ /// view, and the border above it, or, when the element's `overflow` isn't
169
+ /// hidden, below it and above the background. Lynx gives them the view's
170
+ /// frame, which in the container is the element's place on the page.
171
+ private func keepDrawnLayersWithView() {
172
+ guard let manager = backgroundManager else { return }
173
+ let layer = view().layer
174
+ CATransaction.begin()
175
+ CATransaction.setDisableActions(true)
176
+ defer { CATransaction.commit() }
177
+ if let superlayer = layer.superlayer {
178
+ let hidden = overflow == OVERFLOW_HIDDEN_VAL
179
+ let border = manager.borderLayer
180
+ if let border, border.superlayer !== superlayer {
181
+ if hidden {
182
+ superlayer.insertSublayer(border, above: layer)
183
+ } else {
184
+ superlayer.insertSublayer(border, below: layer)
185
+ }
186
+ }
187
+ if let background = manager.backgroundLayer, background.superlayer !== superlayer {
188
+ if !hidden, let border {
189
+ superlayer.insertSublayer(background, below: border)
190
+ } else {
191
+ superlayer.insertSublayer(background, below: layer)
192
+ }
193
+ }
194
+ }
195
+ let drawn: [CALayer?] = [manager.backgroundLayer, manager.borderLayer, manager.maskLayer]
196
+ for drawn in drawn.compactMap({ $0 }) {
197
+ Self.align(drawn, with: layer)
198
+ }
199
+ }
200
+
201
+ /// Moves `drawn` onto `layer`, keeping its size and transform, as Lynx gives
202
+ /// the two the same frame. Through `position`, which a transform leaves
203
+ /// alone, from each one's own anchor point.
204
+ private static func align(_ drawn: CALayer, with layer: CALayer) {
205
+ let left = layer.position.x - layer.bounds.width * layer.anchorPoint.x
206
+ let top = layer.position.y - layer.bounds.height * layer.anchorPoint.y
207
+ drawn.position = CGPoint(
208
+ x: left + drawn.bounds.width * drawn.anchorPoint.x,
209
+ y: top + drawn.bounds.height * drawn.anchorPoint.y)
210
+ }
211
+
212
+ /// The element's view moved into a window or out of one, UIKit's
213
+ /// `didMoveToWindow()`. For a subclass that presents from the view's
214
+ /// window, as a sheet does: Lynx sets an element's props while it creates
215
+ /// it, before its view is in a window to present from.
216
+ func viewDidMoveToWindow() {}
217
+
218
+ override func frameDidChange() {
219
+ super.frameDidChange()
220
+ if isShowingChildrenElsewhere {
221
+ pinToContainer()
222
+ }
223
+ }
224
+
225
+ /// Puts `handler`'s touches in the gesture arena of the page's handler,
226
+ /// where the runtime's gestures (`LynxGestureDetector`) run, and returns
227
+ /// its index there. The arena's class isn't in Lynx's public headers, so
228
+ /// Swift doesn't see the two members that take it, and they're called
229
+ /// through the Objective-C runtime.
230
+ private static func join(
231
+ _ handler: LynxEventHandler, toArenaOf page: LynxEventHandler?
232
+ ) -> Int {
233
+ let selector = NSSelectorFromString("setGestureArenaManagerAndGetIndex:")
234
+ guard let page, handler.responds(to: selector),
235
+ let arena = page.value(forKey: "gestureArenaManager") as AnyObject?
236
+ else { return -1 }
237
+ typealias Join = @convention(c) (AnyObject, Selector, AnyObject) -> Int
238
+ let join = unsafeBitCast(handler.method(for: selector), to: Join.self)
239
+ return join(handler, selector, arena)
240
+ }
241
+
242
+ /// Lynx sets the view's frame to the element's place on the page, which
243
+ /// means nothing in the container: it keeps its size and moves to the
244
+ /// container's top left, with its layers. Through `center`, which a
245
+ /// transform leaves alone.
246
+ private func pinToContainer() {
247
+ let view = view()
248
+ view.center = CGPoint(
249
+ x: view.bounds.width * view.layer.anchorPoint.x,
250
+ y: view.bounds.height * view.layer.anchorPoint.y)
251
+ keepDrawnLayersWithView()
252
+ }
253
+ }
254
+
255
+ /// A `HostElementUI`'s view, which has the element's event handler hit-test
256
+ /// with UIKit while the element shows its children elsewhere.
257
+ private final class HostedView: UIView {
258
+ weak var host: HostElementUI?
259
+
260
+ override func didMoveToWindow() {
261
+ super.didMoveToWindow()
262
+ host?.viewDidMoveToWindow()
263
+ }
264
+
265
+ override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
266
+ guard let view = super.hitTest(point, with: event) else { return nil }
267
+ host?.findTouchTarget(at: point, with: event)
268
+ return view
269
+ }
270
+ }
@@ -1,3 +1,6 @@
1
+ // angular-lynx:image-picker-camera
2
+ import AVFoundation
3
+ // /angular-lynx:image-picker-camera
1
4
  import ImageIO
2
5
  import Lynx
3
6
  import PhotosUI
@@ -17,13 +20,25 @@ import UniformTypeIdentifiers
17
20
  /// runtime's relay to the main thread carry only what JSON can. Scaling it
18
21
  /// down here first, with `maxDimension`, keeps that small: a 12-megapixel
19
22
  /// photo is several megabytes, a 1024-pixel one a few hundred kilobytes.
23
+ ///
24
+ /// `takePhoto`, the camera, is only in an app whose angular.json sets
25
+ /// `permissions.camera`: App Store Connect flags an app whose code uses the
26
+ /// camera without NSCameraUsageDescription (ITMS-90683), which only that
27
+ /// permission writes. So the generator takes out the lines between the
28
+ /// `angular-lynx:image-picker-camera` markers in every other app, and
29
+ /// `takePhoto` isn't in `methodLookup`, which the runtime answers with
30
+ /// `unavailable`.
20
31
  final class ImagePickerModule: NSObject, LynxModule, PHPickerViewControllerDelegate,
21
32
  UIAdaptivePresentationControllerDelegate
22
33
  {
23
34
  static var name: String { "AngularLynxImagePicker" }
24
35
 
25
36
  static var methodLookup: [String: String] {
26
- ["pick": NSStringFromSelector(#selector(pick(_:callback:)))]
37
+ var methods = ["pick": NSStringFromSelector(#selector(pick(_:callback:)))]
38
+ // angular-lynx:image-picker-camera
39
+ methods["takePhoto"] = NSStringFromSelector(#selector(takePhoto(_:callback:)))
40
+ // /angular-lynx:image-picker-camera
41
+ return methods
27
42
  }
28
43
 
29
44
  /// What a re-encoded image gets when the app doesn't choose a quality.
@@ -225,3 +240,147 @@ request.callback(
225
240
  return top
226
241
  }
227
242
  }
243
+
244
+ // angular-lynx:image-picker-camera
245
+ /// The camera, for `LynxImagePicker.pick({ source: 'camera' })`.
246
+ /// PHPickerViewController has none, so it's UIImagePickerController's, which
247
+ /// asks for the camera with NSCameraUsageDescription (angular.json's
248
+ /// `permissions.camera`).
249
+ extension ImagePickerModule: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
250
+ /// Opens the camera and calls back once with `{ base64, name, type }`, a
251
+ /// JPEG of the photo taken, `{ canceled: true }` when the person closes it,
252
+ /// or `{ error, message }`: `unavailable` on a device without a camera,
253
+ /// such as the Simulator, `denied` when the person doesn't let the app use
254
+ /// it, or `failed`.
255
+ @objc func takePhoto(_ options: [String: Any], callback: @escaping LynxCallbackBlock) {
256
+ // Lynx calls modules off the main thread, and the camera is UI.
257
+ DispatchQueue.main.async {
258
+ self.openCamera(options, callback)
259
+ }
260
+ }
261
+
262
+ private func openCamera(_ options: [String: Any], _ callback: @escaping LynxCallbackBlock) {
263
+ guard open == nil else {
264
+ callback(["error": "failed", "message": "A picker is already open."])
265
+ return
266
+ }
267
+ guard UIImagePickerController.isSourceTypeAvailable(.camera) else {
268
+ callback(["error": "unavailable", "message": "This device has no camera."])
269
+ return
270
+ }
271
+ // UIImagePickerController would open on a black screen for a person who
272
+ // declined the camera, so that's told to the app instead. Asking first
273
+ // also shows iOS's prompt before the camera, rather than over it.
274
+ switch AVCaptureDevice.authorizationStatus(for: .video) {
275
+ case .authorized:
276
+ presentCamera(options, callback)
277
+ case .notDetermined:
278
+ AVCaptureDevice.requestAccess(for: .video) { granted in
279
+ DispatchQueue.main.async {
280
+ if granted {
281
+ self.presentCamera(options, callback)
282
+ } else {
283
+ callback(Self.cameraDenied)
284
+ }
285
+ }
286
+ }
287
+ default:
288
+ callback(Self.cameraDenied)
289
+ }
290
+ }
291
+
292
+ private static let cameraDenied: [String: Any] = [
293
+ "error": "denied", "message": "The app isn't allowed to use the camera.",
294
+ ]
295
+
296
+ private func presentCamera(_ options: [String: Any], _ callback: @escaping LynxCallbackBlock) {
297
+ // Asked again: a second takePhoto can arrive while the prompt is open.
298
+ guard open == nil else {
299
+ callback(["error": "failed", "message": "A picker is already open."])
300
+ return
301
+ }
302
+ guard let presenter = topViewController() else {
303
+ callback(["error": "failed", "message": "There's no screen to open the camera over."])
304
+ return
305
+ }
306
+ let camera = UIImagePickerController()
307
+ camera.sourceType = .camera
308
+ camera.mediaTypes = [UTType.image.identifier]
309
+ camera.delegate = self
310
+ open = Request(
311
+ maxDimension: (options["maxDimension"] as? NSNumber)?.intValue,
312
+ quality: (options["quality"] as? NSNumber)?.doubleValue,
313
+ callback: callback)
314
+ presenter.present(camera, animated: true)
315
+ }
316
+
317
+ func imagePickerController(
318
+ _ picker: UIImagePickerController,
319
+ didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]
320
+ ) {
321
+ picker.dismiss(animated: true)
322
+ guard let request = open else { return }
323
+ open = nil
324
+ guard let image = info[.originalImage] as? UIImage else {
325
+ request.callback(["error": "failed", "message": "The camera gave no photo."])
326
+ return
327
+ }
328
+ let name = Self.photoName()
329
+ // Encoding a 12-megapixel photo takes a moment: off the main thread.
330
+ DispatchQueue.global(qos: .userInitiated).async {
331
+ guard
332
+ let jpeg = Self.jpeg(
333
+ image, maxDimension: request.maxDimension,
334
+ quality: request.quality ?? Self.defaultQuality)
335
+ else {
336
+ request.callback(["error": "failed", "message": "The photo couldn't be encoded."])
337
+ return
338
+ }
339
+ request.callback([
340
+ "base64": jpeg.base64EncodedString(), "name": name, "type": "image/jpeg",
341
+ ])
342
+ }
343
+ }
344
+
345
+ func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
346
+ picker.dismiss(animated: true)
347
+ guard let request = open else { return }
348
+ open = nil
349
+ request.callback(["canceled": true])
350
+ }
351
+
352
+ /// The photo as a JPEG: upright, as drawing a UIImage applies its
353
+ /// orientation, no larger than `maxDimension` on its longest side, and
354
+ /// without the camera's metadata, such as where it was taken, as a picked
355
+ /// photo that's re-encoded comes back.
356
+ private static func jpeg(_ image: UIImage, maxDimension: Int?, quality: Double) -> Data? {
357
+ // The size in pixels, the way the photo is turned.
358
+ let width = image.size.width * image.scale
359
+ let height = image.size.height * image.scale
360
+ let longest = max(width, height)
361
+ guard longest > 0 else { return nil }
362
+ // Never larger than the photo.
363
+ let scale = min(CGFloat(maxDimension ?? Int(longest)), longest) / longest
364
+ let size = CGSize(
365
+ width: max(1, (width * scale).rounded()), height: max(1, (height * scale).rounded()))
366
+ let format = UIGraphicsImageRendererFormat()
367
+ format.scale = 1
368
+ // A JPEG has no transparency, and the camera's photo has none.
369
+ format.opaque = true
370
+ return UIGraphicsImageRenderer(size: size, format: format).jpegData(
371
+ withCompressionQuality: quality
372
+ ) { _ in
373
+ image.draw(in: CGRect(origin: .zero, size: size))
374
+ }
375
+ }
376
+
377
+ /// `IMG_20261129_142305.jpg`, from when the photo was taken: the camera
378
+ /// gives the photo no name.
379
+ private static func photoName() -> String {
380
+ let formatter = DateFormatter()
381
+ formatter.locale = Locale(identifier: "en_US_POSIX")
382
+ formatter.dateFormat = "yyyyMMdd_HHmmss"
383
+ return "IMG_\(formatter.string(from: Date())).jpg"
384
+ }
385
+ }
386
+ // /angular-lynx:image-picker-camera
@@ -9,6 +9,9 @@ final class LynxViewController: UIViewController, LynxViewLifecycle {
9
9
  /// it sets up (see lynxView(_:didLoadFinishedWithUrl:)).
10
10
  private var builtFontScale: CGFloat = 1
11
11
  private var lastViewport: CGRect = .zero
12
+ /// The window's size, as Lynx last heard it: the screen's, which the
13
+ /// LynxView is built with, until layoutLynxView finds the view in its window.
14
+ private var lastScreen: CGSize = .zero
12
15
 
13
16
  /// Where the app is, for LynxAppState: "active", "inactive" or
14
17
  /// "background". Sent in the global props, and again as the scene's
@@ -22,6 +25,11 @@ final class LynxViewController: UIViewController, LynxViewLifecycle {
22
25
  /// build a new controller, so deinit removes them.
23
26
  private var appStateObservers: [NSObjectProtocol] = []
24
27
 
28
+ /// Whether the phone is online, for LynxNetwork: sent in the global props,
29
+ /// and again each time it changes. Released with the controller, which
30
+ /// stops its monitor.
31
+ private var networkStatus: NetworkStatus?
32
+
25
33
  deinit {
26
34
  for observer in appStateObservers {
27
35
  NotificationCenter.default.removeObserver(observer)
@@ -51,7 +59,7 @@ final class LynxViewController: UIViewController, LynxViewLifecycle {
51
59
  view.backgroundColor = UIColor(named: "LaunchBackground") ?? .systemBackground
52
60
 
53
61
  let fetcher = BundleResourceFetcher.shared
54
- let screenSize = UIScreen.main.bounds.size
62
+ lastScreen = UIScreen.main.bounds.size
55
63
  // The shell's native modules, which the runtime's services call.
56
64
  let config = LynxConfig(provider: LynxEnv.sharedInstance().config.templateProvider)
57
65
  config.register(WebAuthModule.self)
@@ -146,6 +154,16 @@ final class LynxViewController: UIViewController, LynxViewLifecycle {
146
154
  if let tracking = NSClassFromString("AngularLynxTrackingModule") as? LynxModule.Type {
147
155
  config.register(tracking)
148
156
  }
157
+ // The microphone's recorder behind LynxAudioRecorder
158
+ // (AudioRecorderModule), by name too: the generator leaves its source out
159
+ // of an app whose angular.json doesn't set permissions.microphone, since
160
+ // App Store Connect flags an app whose code uses the microphone without
161
+ // a microphone usage description.
162
+ if let audioRecorder = NSClassFromString("AngularLynxAudioRecorderModule")
163
+ as? LynxModule.Type
164
+ {
165
+ config.register(audioRecorder)
166
+ }
149
167
  // Core NFC's reader behind LynxNfc (NfcModule), by name too: the
150
168
  // generator leaves its source out of an app whose angular.json doesn't
151
169
  // set permissions.nfc, with the usage description and entitlement it
@@ -159,6 +177,13 @@ final class LynxViewController: UIViewController, LynxViewLifecycle {
159
177
  if let wifi = NSClassFromString("AngularLynxWifiModule") as? LynxModule.Type {
160
178
  config.register(wifi)
161
179
  }
180
+ // Core Location behind LynxGeolocation (GeolocationModule), by name
181
+ // too: the generator leaves its source out of an app whose angular.json
182
+ // doesn't set permissions.location, since App Store Connect flags Core
183
+ // Location code without NSLocationWhenInUseUsageDescription.
184
+ if let geolocation = NSClassFromString("AngularLynxGeolocationModule") as? LynxModule.Type {
185
+ config.register(geolocation)
186
+ }
162
187
  // Bundled files for the main thread's fetch and Image (AssetsModule).
163
188
  config.register(AssetsModule.self)
164
189
  // The full collections the runtime asks for after screens go
@@ -169,6 +194,11 @@ final class LynxViewController: UIViewController, LynxViewLifecycle {
169
194
  config.register(ShortcutsModule.self)
170
195
  // `ng serve --platform ios`'s live reload, in the development build.
171
196
  DevServer.shared.register(in: config)
197
+ // The app's native plugins' modules and elements (angular.json's
198
+ // `nativePlugins`), after the shell's own and the dev server's, as on
199
+ // Android. A module gets this controller, held weakly, in its param, to
200
+ // present a screen from.
201
+ AngularLynxPlugins.register(in: config, host: self)
172
202
  builtFontScale = textScale()
173
203
  let lynxView = LynxView { builder in
174
204
  builder.config = config
@@ -186,7 +216,7 @@ final class LynxViewController: UIViewController, LynxViewLifecycle {
186
216
  // with lynx.module(name): WebGL needs answers synchronously. Lynx calls
187
217
  // them on its engine thread, not the UI thread (see AngularLynxWebGL.h).
188
218
  builder.enableMTSModule = true
189
- builder.screenSize = screenSize
219
+ builder.screenSize = self.lastScreen
190
220
  // The user's text size (see textScale()). The build tells Lynx to
191
221
  // scale only `sp` lengths by it, which the page's root font size is
192
222
  // written in, so every rem grows with it and a px size doesn't.
@@ -245,6 +275,12 @@ final class LynxViewController: UIViewController, LynxViewLifecycle {
245
275
 
246
276
  // Send the app's state again each time the scene's activation changes.
247
277
  observeAppState()
278
+
279
+ // Send whether the phone is online again each time it changes.
280
+ networkStatus = NetworkStatus { [weak self] _ in
281
+ guard let self else { return }
282
+ self.lynxView?.updateGlobalProps(with: self.globalProps())
283
+ }
248
284
  }
249
285
 
250
286
  @objc private func accessibilitySettingsDidChange() {
@@ -356,10 +392,25 @@ final class LynxViewController: UIViewController, LynxViewLifecycle {
356
392
  /// env(safe-area-inset-*) the safeArea* global props below instead, as CSS
357
393
  /// variables on the page that restyle what reads them when they change, and
358
394
  /// 0 when the LynxView is inside the safe area (see `edgeToEdge` there).
395
+ ///
396
+ /// It runs again whenever the window changes size: a rotation, and on an
397
+ /// iPad, split view and Stage Manager. Lynx 4 lays the page out again at
398
+ /// the new size by itself, once it's told, in its foldable guide's order:
399
+ /// the window's size, which rpx lengths are a 750th of, then the
400
+ /// LynxView's, which %, vw, vh and @media measure against, then the global
401
+ /// props LynxViewport reads, all in points. A new window size alone
402
+ /// doesn't lay the page out again, which the viewport and triggerLayout do.
359
403
  private func layoutLynxView() {
360
404
  guard let lynxView else { return }
361
405
  let frame = edgeToEdge ? view.bounds : view.bounds.inset(by: view.safeAreaInsets)
362
- guard frame != lastViewport else { return }
406
+ // The window's bounds, once the view is in it; before, the screen's,
407
+ // which the LynxView was built with.
408
+ let screen = view.window?.bounds.size ?? lastScreen
409
+ guard frame != lastViewport || screen != lastScreen else { return }
410
+ if screen != lastScreen {
411
+ lastScreen = screen
412
+ lynxView.updateScreenMetrics(withWidth: screen.width, height: screen.height)
413
+ }
363
414
  lastViewport = frame
364
415
  lynxView.frame = frame
365
416
  lynxView.preferredLayoutWidth = frame.width
@@ -374,8 +425,9 @@ final class LynxViewController: UIViewController, LynxViewLifecycle {
374
425
  /// (LynxSafeArea), `appLocale` (LynxLocale), `appTimeZone` (the `intl`
375
426
  /// build option's Intl.DateTimeFormat), the accessibility settings
376
427
  /// and text scale (LynxAccessibilitySettings), `appState` (LynxAppState),
377
- /// `osVersion` (LynxSystemInfo) and `initialURL` (LynxLinking and the
378
- /// router), plus the safe-area insets and `edgeToEdge`, which
428
+ /// `online` (LynxNetwork), `osVersion` (LynxSystemInfo), `initialURL` (LynxLinking and the
429
+ /// router) and the window's and the LynxView's sizes (LynxViewport), plus
430
+ /// the safe-area insets and `edgeToEdge`, which
379
431
  /// env(safe-area-inset-*) reads. The Android shell sends the same keys, and
380
432
  /// Lynx Explorer sends theme and isNotchScreen too.
381
433
  private func globalProps() -> LynxTemplateData {
@@ -405,10 +457,19 @@ final class LynxViewController: UIViewController, LynxViewLifecycle {
405
457
  "textScale": textScale(),
406
458
  // Whether the app is in the foreground, taking touches.
407
459
  "appState": appState,
460
+ // Whether the phone has a connection to the internet. Online until the
461
+ // monitor first answers, which comes after the first props go out.
462
+ "online": networkStatus?.online ?? true,
408
463
  // Lynx builds the main thread's SystemInfo, where Angular runs, without
409
464
  // the OS version, so LynxSystemInfo reads it from here. The glass
410
465
  // components need it: blur-view draws Liquid Glass only from iOS 26.
411
466
  "osVersion": UIDevice.current.systemVersion,
467
+ // The sizes Lynx's foldable guide names, in points: the window's, and
468
+ // the LynxView's, which is smaller with "edgeToEdge": false.
469
+ "screenWidth": lastScreen.width,
470
+ "screenHeight": lastScreen.height,
471
+ "viewportWidth": lastViewport.width,
472
+ "viewportHeight": lastViewport.height,
412
473
  ]
413
474
  // The user's first language as a BCP 47 tag, such as "fr-FR". iOS
414
475
  // restarts the app when the language changes, so there's no update to send.
@@ -0,0 +1,41 @@
1
+ import Foundation
2
+ import Network
3
+
4
+ /// Whether the phone has a connection to the internet, for LynxNetwork, which
5
+ /// LynxViewController sends in the `online` global prop. Lynx tells the app's
6
+ /// code nothing about the connection, and has no `navigator.onLine`, so the
7
+ /// shell watches it itself.
8
+ ///
9
+ /// Online while NWPathMonitor's path is `satisfied`: there's a route out,
10
+ /// over Wi-Fi, cellular or a wired link. It needs no permission and shows the
11
+ /// user nothing.
12
+ final class NetworkStatus {
13
+ private let monitor = NWPathMonitor()
14
+
15
+ /// Online until the monitor's first path arrives, which comes just after
16
+ /// it starts: the first global props go out before that, and an app
17
+ /// shouldn't flash an offline screen at every launch.
18
+ private(set) var online = true
19
+
20
+ /// - Parameter onChange: called on the main queue each time `online`
21
+ /// changes, and only then: a new path with the same answer (another
22
+ /// Wi-Fi, or a switch to cellular) would only make the app run its
23
+ /// change detection for nothing.
24
+ init(onChange: @escaping (Bool) -> Void) {
25
+ monitor.pathUpdateHandler = { [weak self] path in
26
+ let online = path.status == .satisfied
27
+ guard let self, self.online != online else { return }
28
+ self.online = online
29
+ onChange(online)
30
+ }
31
+ // The main queue, where the controller's LynxView takes its updates and
32
+ // `online` is read: no hop between threads, and nothing to lock.
33
+ monitor.start(queue: .main)
34
+ }
35
+
36
+ /// The monitor runs until it's canceled, so it stops with its controller,
37
+ /// which iOS can drop with its scene and build again.
38
+ deinit {
39
+ monitor.cancel()
40
+ }
41
+ }