@blotch/angular-lynx-native 22.2.24 → 22.2.26

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 +6 -4
  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 +83 -2
  5. package/dist/generate.d.ts +1 -1
  6. package/dist/generate.js +8 -2
  7. package/dist/index.d.ts +3 -1
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js +9 -0
  10. package/dist/ios/project.d.ts +20 -3
  11. package/dist/ios/project.d.ts.map +1 -1
  12. package/dist/ios/project.js +99 -2
  13. package/dist/options.d.ts +119 -0
  14. package/dist/options.d.ts.map +1 -1
  15. package/dist/options.js +143 -0
  16. package/dist/png.d.ts +5 -0
  17. package/dist/png.d.ts.map +1 -1
  18. package/dist/png.js +19 -5
  19. package/dist/splash.d.ts +70 -0
  20. package/dist/splash.d.ts.map +1 -0
  21. package/dist/splash.js +239 -0
  22. package/package.json +1 -1
  23. package/templates/android/README.md +19 -1
  24. package/templates/android/app/build.gradle.kts +4 -0
  25. package/templates/android/app/src/debug/java/dev/angularlynx/shell/DevServer.kt +6 -0
  26. package/templates/android/app/src/main/AndroidManifest.xml +27 -1
  27. package/templates/android/app/src/main/java/dev/angularlynx/shell/AssetsModule.kt +2 -1
  28. package/templates/android/app/src/main/java/dev/angularlynx/shell/CanvasUI.kt +16 -3
  29. package/templates/android/app/src/main/java/dev/angularlynx/shell/MainActivity.kt +81 -4
  30. package/templates/android/app/src/main/java/dev/angularlynx/shell/ShellModule.kt +10 -0
  31. package/templates/android/app/src/main/java/dev/angularlynx/shell/ShortcutActivity.kt +33 -0
  32. package/templates/android/app/src/main/java/dev/angularlynx/shell/ShortcutsModule.kt +72 -0
  33. package/templates/android/app/src/main/java/dev/angularlynx/shell/WebGLContext.kt +15 -4
  34. package/templates/android/app/src/main/java/dev/angularlynx/shell/WebGLModule.kt +10 -1
  35. package/templates/android/app/src/main/res/values/colors.xml +3 -2
  36. package/templates/android/app/src/main/res/values/splash.xml +9 -0
  37. package/templates/android/app/src/main/res/values/themes.xml +14 -0
  38. package/templates/android/app/src/main/res/xml/shortcuts.xml +7 -0
  39. package/templates/android/app/src/release/java/dev/angularlynx/shell/DevServer.kt +2 -0
  40. package/templates/ios/App/AngularLynxWebGL.h +34 -6
  41. package/templates/ios/App/AngularLynxWebGL.m +58 -23
  42. package/templates/ios/App/AngularLynxWebGLContext.m +25 -21
  43. package/templates/ios/App/AnimationFrameRate.swift +214 -0
  44. package/templates/ios/App/AppDelegate.swift +2 -0
  45. package/templates/ios/App/AssetsModule.swift +3 -1
  46. package/templates/ios/App/DevServer.swift +3 -0
  47. package/templates/ios/App/Info.plist +12 -5
  48. package/templates/ios/App/LynxViewController.swift +24 -1
  49. package/templates/ios/App/ShellModule.swift +14 -1
  50. package/templates/ios/App/ShortcutsModule.swift +82 -0
  51. package/templates/ios/App/SplashScreen.swift +71 -0
  52. package/templates/ios/App/WebViewLoader.swift +95 -0
  53. package/templates/ios/App/XElementRegistry.swift +5 -1
@@ -0,0 +1,214 @@
1
+ import Foundation
2
+ import ObjectiveC
3
+ import QuartzCore
4
+
5
+ /// Asks iOS to run the app's Core Animation transitions at up to 120 fps on a
6
+ /// ProMotion iPhone.
7
+ ///
8
+ /// An element with `enable-new-animator="false"` hands its CSS transitions and
9
+ /// `@keyframes` to Core Animation, as `<lynx-stack-outlet>`'s pages and
10
+ /// `ui-bottom-sheet` do. Lynx makes those animations without a
11
+ /// `preferredFrameRateRange`, and iOS runs an animation that asks for no rate at
12
+ /// 60 fps: `CADisableMinimumFrameDurationOnPhone` in Info.plist only lets the
13
+ /// app ask for more. On an iPhone 14 Pro a stack push ran at a steady 60 fps
14
+ /// while the Home Screen's own animations ran at 120.
15
+ ///
16
+ /// Lynx adds its animations in many places (a transition, a keyframe
17
+ /// animation, and their copies on the element's background and border layers),
18
+ /// and they all go through `CALayer.add(_:forKey:)`, so the shell asks there,
19
+ /// for every animation added in the app: UIKit's in the shell's own views too.
20
+ /// With it, the push ran at 120 fps while it moved fast, then slower as it
21
+ /// eased to a stop, as the Home Screen's animations do.
22
+ ///
23
+ /// It leaves alone an animation that asks for a rate of its own, and a loop
24
+ /// that never ends, such as a spinner or a pulse: nobody follows those with
25
+ /// their eye, so they keep the system's rate, and the battery that saves.
26
+ enum AnimationFrameRate {
27
+ /// The range Apple's ProMotion guidance gives fast motion: 120 fps, and no
28
+ /// lower than 80.
29
+ static let fastMotion = CAFrameRateRange(minimum: 80, maximum: 120, preferred: 120)
30
+
31
+ /// The most repeats a finite animation has. Lynx writes CSS's `infinite` as
32
+ /// 10⁹ iterations (half that with `alternate`), and UIKit's loops repeat
33
+ /// forever (`.infinity`), so anything above this is a loop.
34
+ static let loopRepeatCount: Float = 1_000
35
+
36
+ /// Whether the shell asks for `fastMotion` on this animation.
37
+ static func asksForFastMotion(_ animation: CAAnimation) -> Bool {
38
+ // The default range, {0, 0, 0}, is an animation that asks for nothing.
39
+ animation.preferredFrameRateRange.maximum == 0
40
+ && animation.repeatCount <= loopRepeatCount
41
+ && animation.repeatDuration.isFinite
42
+ }
43
+
44
+ /// Swaps in `CALayer`'s replacement `add(_:forKey:)`, and has Lynx's own
45
+ /// animator's rate asked for from the main thread (see `LynxAnimatorFrameRate`).
46
+ /// Call it once, before the first LynxView exists.
47
+ static func install() {
48
+ _ = swapped
49
+ LynxAnimatorFrameRate.install()
50
+ }
51
+
52
+ /// A static's initializer runs once, however often `install()` is called:
53
+ /// swapping twice would put CALayer's own method back.
54
+ private static let swapped: Void = {
55
+ guard
56
+ let original = class_getInstanceMethod(
57
+ CALayer.self, #selector(CALayer.add(_:forKey:))),
58
+ let replacement = class_getInstanceMethod(
59
+ CALayer.self, #selector(CALayer.angularLynx_add(_:forKey:)))
60
+ else { return }
61
+ method_exchangeImplementations(original, replacement)
62
+ }()
63
+ }
64
+
65
+ /// Asks iOS, from the main thread, for the rate Lynx's own animator asks for,
66
+ /// while that animator runs.
67
+ ///
68
+ /// Lynx works out each frame of an element's CSS transitions and `animate()`
69
+ /// itself (every element without `enable-new-animator="false"`), from a
70
+ /// `CADisplayLink` in its `LynxVSyncPulse`. The build's `preferredFps: 'high'`
71
+ /// has Lynx ask that link for up to 120 fps. But the link is made on the thread
72
+ /// that first asks it for a frame, and the shell runs Lynx's engine off the
73
+ /// main thread (`MostOnTASM`), so it lives on the engine thread, and iOS doesn't
74
+ /// raise the display's rate for a display link there. On an iPhone 14 Pro a
75
+ /// transition on Lynx's animator drew a frame every 16.7 ms while the same one
76
+ /// in Core Animation drew one every 8.3 ms. With a display link on the main
77
+ /// thread asking for the same range, it drew one every 8.3 ms too: the engine
78
+ /// already ticked that fast, and only the display held it back.
79
+ ///
80
+ /// So the shell swaps in its own `requestPulse`, which Lynx calls on the engine
81
+ /// thread for each frame it wants, and while those frames come from a link that
82
+ /// asks for more than 60 fps, a display link on the main thread asks for the
83
+ /// same range. It pauses once Lynx has asked for no frame for a few frames, so
84
+ /// a screen with nothing moving keeps the system's rate. A `preferredFps` of
85
+ /// `'auto'` or `'low'` leaves Lynx's link asking for nothing, so nothing is
86
+ /// asked for here either.
87
+ final class LynxAnimatorFrameRate: NSObject {
88
+ static let shared = LynxAnimatorFrameRate()
89
+
90
+ /// How long the main thread keeps asking after Lynx's last frame request: a
91
+ /// few frames, so a frame Angular's work delays doesn't drop the rate between
92
+ /// two of an animation's frames.
93
+ static let linger: CFTimeInterval = 0.1
94
+
95
+ /// The highest rate a display link asks for before the main thread asks too:
96
+ /// what an app gets without asking.
97
+ static let defaultMaximum: Float = 60
98
+
99
+ /// Guards what both threads read: the engine thread writes the request, the
100
+ /// main thread reads it on its own frames.
101
+ private let lock = NSLock()
102
+ private var lastRequest: CFTimeInterval = 0
103
+ private var range = CAFrameRateRange.default
104
+ /// Whether the main thread's link runs, or is about to.
105
+ private var asking = false
106
+ /// The main thread's link. Only the main thread touches it.
107
+ private var link: CADisplayLink?
108
+
109
+ /// Swaps `LynxVSyncPulse`'s `requestPulse` for one that also asks from the
110
+ /// main thread. Does nothing if Lynx no longer has that class or method.
111
+ static func install() {
112
+ _ = swapped
113
+ }
114
+
115
+ private static let swapped: Void = {
116
+ let selector = NSSelectorFromString("requestPulse")
117
+ let replacementSelector = #selector(NSObject.angularLynx_requestPulse)
118
+ guard
119
+ let pulse = NSClassFromString("LynxVSyncPulse"),
120
+ let original = class_getInstanceMethod(pulse, selector),
121
+ let replacement = class_getInstanceMethod(NSObject.self, replacementSelector),
122
+ // Added to LynxVSyncPulse itself, so the swap changes only its methods,
123
+ // not NSObject's.
124
+ class_addMethod(
125
+ pulse, replacementSelector, method_getImplementation(replacement),
126
+ method_getTypeEncoding(replacement)),
127
+ let added = class_getInstanceMethod(pulse, replacementSelector)
128
+ else { return }
129
+ method_exchangeImplementations(original, added)
130
+ }()
131
+
132
+ /// Whether a link's range asks for more than an app gets by default.
133
+ static func asksForHighRate(_ range: CAFrameRateRange) -> Bool {
134
+ max(range.maximum, range.preferred ?? 0) > defaultMaximum
135
+ }
136
+
137
+ /// Called on the engine thread for each frame Lynx asks its link for.
138
+ func lynxRequestedFrame(_ range: CAFrameRateRange) {
139
+ lock.lock()
140
+ lastRequest = CACurrentMediaTime()
141
+ self.range = range
142
+ let start = !asking
143
+ asking = true
144
+ lock.unlock()
145
+ if start {
146
+ DispatchQueue.main.async { self.resume() }
147
+ }
148
+ }
149
+
150
+ private func resume() {
151
+ let link: CADisplayLink
152
+ if let existing = self.link {
153
+ link = existing
154
+ } else {
155
+ link = CADisplayLink(target: self, selector: #selector(tick(_:)))
156
+ link.add(to: .main, forMode: .common)
157
+ self.link = link
158
+ }
159
+ lock.lock()
160
+ let range = self.range
161
+ lock.unlock()
162
+ link.preferredFrameRateRange = range
163
+ link.isPaused = false
164
+ }
165
+
166
+ @objc private func tick(_ link: CADisplayLink) {
167
+ lock.lock()
168
+ let idle = link.timestamp - lastRequest > Self.linger
169
+ if idle {
170
+ // A request after this unlock finds `asking` false and resumes the link
171
+ // on a later turn of the main thread, after this pause.
172
+ asking = false
173
+ }
174
+ lock.unlock()
175
+ if idle {
176
+ link.isPaused = true
177
+ }
178
+ }
179
+ }
180
+
181
+ extension NSObject {
182
+ /// Takes the place of `LynxVSyncPulse`'s `requestPulse` once
183
+ /// `LynxAnimatorFrameRate.install()` has run, so `self` is a `LynxVSyncPulse`.
184
+ @objc fileprivate func angularLynx_requestPulse() {
185
+ // The implementations are swapped, so this runs Lynx's own requestPulse.
186
+ angularLynx_requestPulse()
187
+ let getter = NSSelectorFromString("displayLink")
188
+ guard responds(to: getter),
189
+ let link = perform(getter)?.takeUnretainedValue() as? CADisplayLink,
190
+ LynxAnimatorFrameRate.asksForHighRate(link.preferredFrameRateRange)
191
+ else { return }
192
+ LynxAnimatorFrameRate.shared.lynxRequestedFrame(link.preferredFrameRateRange)
193
+ }
194
+ }
195
+
196
+ extension CALayer {
197
+ /// Takes the place of `add(_:forKey:)` once `AnimationFrameRate.install()`
198
+ /// has run.
199
+ @objc fileprivate func angularLynx_add(_ animation: CAAnimation, forKey key: String?) {
200
+ // The implementations are swapped, so each `angularLynx_add` call below
201
+ // runs CALayer's own `add(_:forKey:)`.
202
+ guard AnimationFrameRate.asksForFastMotion(animation),
203
+ // Core Animation adds a copy of the animation anyway. The one passed in
204
+ // may be one a layer handed back from `animation(forKey:)`, which mustn't
205
+ // be changed, so the rate goes on a copy of our own.
206
+ let fast = animation.copy() as? CAAnimation
207
+ else {
208
+ angularLynx_add(animation, forKey: key)
209
+ return
210
+ }
211
+ fast.preferredFrameRateRange = AnimationFrameRate.fastMotion
212
+ angularLynx_add(fast, forKey: key)
213
+ }
214
+ }
@@ -14,6 +14,8 @@ final class AppDelegate: UIResponder, UIApplicationDelegate {
14
14
  didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
15
15
  ) -> Bool {
16
16
  XElementRegistry.register()
17
+ // Before any LynxView, so its first transition already asks for 120 fps.
18
+ AnimationFrameRate.install()
17
19
  let config = LynxConfig(provider: BundleResourceFetcher.shared)
18
20
  LynxEnv.sharedInstance().prepareConfig(config)
19
21
  // LynxService's image service decodes through SDWebImage, which only
@@ -9,7 +9,9 @@ import Lynx
9
9
  /// Lynx's own `<image>`.
10
10
  ///
11
11
  /// Called from the main thread, synchronously (`lynx.module(name)`), like
12
- /// the WebGL module: the runtime turns the answer into a Response.
12
+ /// the WebGL module: the runtime turns the answer into a Response. Lynx calls
13
+ /// it on its engine thread, which LynxViewController runs off the UI thread,
14
+ /// so a dev server download that waits blocks Angular, not UIKit.
13
15
  final class AssetsModule: NSObject, LynxModule {
14
16
  static var name: String { "AngularLynxAssets" }
15
17
 
@@ -185,6 +185,9 @@ final class DevServer {
185
185
  status.text = message
186
186
  statusScreen.isHidden = false
187
187
  statusScreen.superview?.bringSubviewToFront(statusScreen)
188
+ // The launch screen's copy makes way for the message, rather than
189
+ // hide it until it times out (SplashScreen.swift).
190
+ SplashScreen.shared.hide()
188
191
  }
189
192
  #endif
190
193
  }
@@ -2,6 +2,13 @@
2
2
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3
3
  <plist version="1.0">
4
4
  <dict>
5
+ <!-- Lets the app draw at up to 120 fps on a ProMotion iPhone. Without it
6
+ iOS holds an app's CADisplayLink and Core Animation to 60 fps there,
7
+ while the system's own UI runs at 120, and Lynx animates through a
8
+ CADisplayLink: every transition and drag ran at half the phone's
9
+ rate. Lynx asks for 120 itself (the build's `preferredFps`). -->
10
+ <key>CADisableMinimumFrameDurationOnPhone</key>
11
+ <true/>
5
12
  <key>CFBundleDevelopmentRegion</key>
6
13
  <string>$(DEVELOPMENT_LANGUAGE)</string>
7
14
  <key>CFBundleDisplayName</key>
@@ -29,16 +36,16 @@
29
36
  <key>UIApplicationSupportsMultipleScenes</key>
30
37
  <false/>
31
38
  </dict>
32
- <key>UILaunchScreen</key>
33
- <dict>
34
- <key>UIColorName</key>
35
- <string>LaunchBackground</string>
36
- </dict>
37
39
  <key>UIRequiredDeviceCapabilities</key>
38
40
  <array>
39
41
  <string>arm64</string>
40
42
  </array>
41
43
  <!-- angular-lynx:info -->
44
+ <key>UILaunchScreen</key>
45
+ <dict>
46
+ <key>UIColorName</key>
47
+ <string>LaunchBackground</string>
48
+ </dict>
42
49
  <key>UISupportedInterfaceOrientations</key>
43
50
  <array>
44
51
  <string>UIInterfaceOrientationPortrait</string>
@@ -16,6 +16,8 @@ final class LynxViewController: UIViewController {
16
16
 
17
17
  override func viewDidLoad() {
18
18
  super.viewDidLoad()
19
+ // The launch screen's color (angular.json's splash.backgroundColor),
20
+ // behind the LynxView, so no other color shows between the two.
19
21
  view.backgroundColor = UIColor(named: "LaunchBackground") ?? .systemBackground
20
22
 
21
23
  let fetcher = BundleResourceFetcher.shared
@@ -43,12 +45,26 @@ final class LynxViewController: UIViewController {
43
45
  // The full collections the runtime asks for after screens go
44
46
  // (ShellModule).
45
47
  config.register(ShellModule.self)
48
+ // The shortcuts the person runs from Siri, Spotlight or the Shortcuts
49
+ // app, which LynxShortcuts takes (ShortcutsModule).
50
+ config.register(ShortcutsModule.self)
46
51
  // `ng serve --platform ios`'s live reload, in the development build.
47
52
  DevServer.shared.register(in: config)
48
53
  let lynxView = LynxView { builder in
49
54
  builder.config = config
55
+ // Lynx's engine thread, which runs the main thread's JavaScript (the
56
+ // whole Angular app), layout and Lynx's animator, gets a thread of its
57
+ // own. Lynx's default, AllOnUI, runs it on the UI thread, where change
58
+ // detection, a screen being built or a long event handler took frames
59
+ // from what UIKit runs itself: a scroll view's momentum, typing, a web
60
+ // view. Off it, the element tree reaches the screen a step later, once
61
+ // the flush crosses to the UI thread: the build plugin turns on Lynx's
62
+ // pending invokes so UI methods follow it, and the runtime sets
63
+ // enable-async-list on every <list>, which this strategy requires.
64
+ builder.setThreadStrategyForRender(.mostOnTASM)
50
65
  // Lets main-thread code, where Angular runs, call the config's modules
51
- // with lynx.module(name): WebGL needs answers synchronously.
66
+ // with lynx.module(name): WebGL needs answers synchronously. Lynx calls
67
+ // them on its engine thread, not the UI thread (see AngularLynxWebGL.h).
52
68
  builder.enableMTSModule = true
53
69
  builder.screenSize = screenSize
54
70
  builder.fontScale = 1.0
@@ -61,6 +77,8 @@ final class LynxViewController: UIViewController {
61
77
  lynxView.layoutHeightMode = .exact
62
78
  view.addSubview(lynxView)
63
79
  self.lynxView = lynxView
80
+ // Who hears that a shortcut ran while the app is open.
81
+ ShortcutCenter.shared.lynxView = lynxView
64
82
 
65
83
  layoutLynxView()
66
84
  lynxView.updateGlobalProps(with: globalProps())
@@ -68,6 +86,11 @@ final class LynxViewController: UIViewController {
68
86
  // server's, which it loads again on every edit.
69
87
  let templateURL = DevServer.shared.templateURL
70
88
  lynxView.loadTemplate(fromURL: templateURL, initData: nil)
89
+ // The launch screen, over the LynxView until the app's first screen is
90
+ // drawn: iOS takes its own down at the first frame, which is the empty
91
+ // LynxView (SplashScreen.swift). The development build's messages go
92
+ // over it.
93
+ SplashScreen.shared.show(over: view)
71
94
  DevServer.shared.attach(to: view) { [weak self] in
72
95
  self?.lynxView?.loadTemplate(fromURL: templateURL, initData: nil)
73
96
  }
@@ -14,11 +14,18 @@ import UIKit
14
14
  /// memory pressure, so this reports a moderate one. The runtime asks once it
15
15
  /// has released about a screen's worth of elements and the app has settled
16
16
  /// (`collect-garbage.ts` in `packages/runtime`).
17
+ ///
18
+ /// `hideSplashScreen` fades out the copy of the launch screen the shell keeps
19
+ /// over the app until its first screen is ready (SplashScreen.swift). The
20
+ /// runtime's LynxSplashScreen calls it.
17
21
  final class ShellModule: NSObject, LynxModule {
18
22
  static var name: String { "AngularLynxShell" }
19
23
 
20
24
  static var methodLookup: [String: String] {
21
- ["collectGarbage": NSStringFromSelector(#selector(collectGarbage))]
25
+ [
26
+ "collectGarbage": NSStringFromSelector(#selector(collectGarbage)),
27
+ "hideSplashScreen": NSStringFromSelector(#selector(hideSplashScreen)),
28
+ ]
22
29
  }
23
30
 
24
31
  override init() {
@@ -39,4 +46,10 @@ final class ShellModule: NSObject, LynxModule {
39
46
  LynxEnv.sharedInstance().trimMemory(.moderate)
40
47
  }
41
48
  }
49
+
50
+ @objc func hideSplashScreen() {
51
+ DispatchQueue.main.async {
52
+ SplashScreen.shared.hide()
53
+ }
54
+ }
42
55
  }
@@ -0,0 +1,82 @@
1
+ import Lynx
2
+ import UIKit
3
+
4
+ /// The shortcuts the person has run and the app hasn't taken yet.
5
+ ///
6
+ /// angular.json's `shortcuts` become App Intents (AppShortcuts.swift, which
7
+ /// the generator writes), and iOS runs one from Siri, Spotlight or the
8
+ /// Shortcuts app. It may run before the app has started, which iOS then
9
+ /// launches for it, so an intent can't call into the app: it leaves the
10
+ /// shortcut here, and the runtime's `LynxShortcuts` takes it when it's ready,
11
+ /// at startup and again each time it hears the `angularLynxShortcut` global
12
+ /// event. A shortcut waits here for as long as that takes, so the one that
13
+ /// launched the app is never lost, and none is handled twice.
14
+ final class ShortcutCenter {
15
+ static let shared = ShortcutCenter()
16
+
17
+ /// The global event that says a shortcut is waiting. It carries nothing:
18
+ /// the listener answers by taking them.
19
+ static let event = "angularLynxShortcut"
20
+
21
+ /// App Intents run off the main thread, and Lynx calls modules off it too.
22
+ private let lock = NSLock()
23
+ private var waiting: [[String: String]] = []
24
+
25
+ /// The app's LynxView, which LynxViewController sets once it has one.
26
+ weak var lynxView: LynxView?
27
+
28
+ /// Called by each shortcut's App Intent, with angular.json's `id` and
29
+ /// `route`.
30
+ func run(id: String, route: String? = nil) {
31
+ var shortcut = ["id": id]
32
+ if let route {
33
+ shortcut["route"] = route
34
+ }
35
+ lock.lock()
36
+ waiting.append(shortcut)
37
+ lock.unlock()
38
+ DispatchQueue.main.async {
39
+ // Before the LynxView exists there's nobody to tell, and the runtime
40
+ // asks when it starts anyway.
41
+ self.lynxView?.sendGlobalEvent(Self.event, withParams: [])
42
+ }
43
+ }
44
+
45
+ /// The waiting shortcuts, oldest first, which stop waiting.
46
+ func take() -> [[String: String]] {
47
+ lock.lock()
48
+ defer { lock.unlock() }
49
+ let taken = waiting
50
+ waiting = []
51
+ return taken
52
+ }
53
+ }
54
+
55
+ /// The native module behind the runtime's `LynxShortcuts`, which calls it as
56
+ /// `NativeModules.AngularLynxShortcuts` (from the background thread, where
57
+ /// NativeModules lives). Android's shell has one of the same name.
58
+ ///
59
+ /// `take` calls back with `{ shortcuts }`: each shortcut the person ran since
60
+ /// the last call, as `{ id, route? }`.
61
+ final class ShortcutsModule: NSObject, LynxModule {
62
+ static var name: String { "AngularLynxShortcuts" }
63
+
64
+ static var methodLookup: [String: String] {
65
+ ["take": NSStringFromSelector(#selector(take(_:)))]
66
+ }
67
+
68
+ override init() {
69
+ super.init()
70
+ }
71
+
72
+ // Swift can't import an optional initializer as optional, so Lynx's
73
+ // initWithParam: is required here. Registered without a param, the module
74
+ // ignores it.
75
+ init(param: Any) {
76
+ super.init()
77
+ }
78
+
79
+ @objc func take(_ callback: @escaping LynxCallbackBlock) {
80
+ callback(["shortcuts": ShortcutCenter.shared.take()])
81
+ }
82
+ }
@@ -0,0 +1,71 @@
1
+ import UIKit
2
+
3
+ /// Keeps the launch screen up until the app's first screen is ready.
4
+ ///
5
+ /// iOS takes the launch screen down as soon as the app draws its first
6
+ /// frame, which is the empty LynxView: the bundle hasn't run yet, and the
7
+ /// app's first screen may have work to finish first, such as a lazy route or
8
+ /// a guard. So the shell puts a copy of the launch screen over the LynxView
9
+ /// (UILaunchScreen's color and image, from the asset catalog, laid out as iOS
10
+ /// lays them out), and fades it out when the runtime says the screen under
11
+ /// it is drawn: `ShellModule.hideSplashScreen`, which the runtime's
12
+ /// LynxSplashScreen calls after the first frame Angular commits, or when the
13
+ /// app's `provideSplashScreen()` says.
14
+ ///
15
+ /// A host the runtime can't reach never asks, so the copy also goes after
16
+ /// `timeout`, rather than leave the app behind its logo.
17
+ final class SplashScreen {
18
+ static let shared = SplashScreen()
19
+
20
+ /// The longest the copy stays up: enough for a slow first screen, short
21
+ /// enough that one that never settles doesn't look like a hung app.
22
+ static let timeout: TimeInterval = 5
23
+ /// The fade, as long as UIKit's own transitions.
24
+ private static let fadeDuration: TimeInterval = 0.25
25
+
26
+ private weak var overlay: UIView?
27
+
28
+ private init() {}
29
+
30
+ /// Puts the copy over everything in `view`, now and until it's hidden.
31
+ func show(over view: UIView) {
32
+ let overlay = UIView(frame: view.bounds)
33
+ overlay.autoresizingMask = [.flexibleWidth, .flexibleHeight]
34
+ // The same names Info.plist's UILaunchScreen reads, so the two match.
35
+ // Both follow dark mode, as the launch screen does.
36
+ overlay.backgroundColor = UIColor(named: "LaunchBackground") ?? .systemBackground
37
+ // An app without angular.json's splash.image has none: the color alone.
38
+ if let image = UIImage(named: "LaunchImage") {
39
+ let imageView = UIImageView(image: image)
40
+ // At its natural size, centered on the whole screen, as the launch
41
+ // screen draws it (UIImageRespectsSafeAreaInsets is false).
42
+ imageView.center = CGPoint(x: overlay.bounds.midX, y: overlay.bounds.midY)
43
+ imageView.autoresizingMask = [
44
+ .flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin, .flexibleBottomMargin,
45
+ ]
46
+ overlay.addSubview(imageView)
47
+ }
48
+ // VoiceOver has nothing to read until the app is there.
49
+ overlay.isAccessibilityElement = false
50
+ view.addSubview(overlay)
51
+ self.overlay = overlay
52
+
53
+ DispatchQueue.main.asyncAfter(deadline: .now() + Self.timeout) { [weak self] in
54
+ self?.hide()
55
+ }
56
+ }
57
+
58
+ /// Fades the copy out. Main thread only. Once it's gone, does nothing: the
59
+ /// development build loads the app again on every edit, and each load
60
+ /// asks.
61
+ func hide() {
62
+ guard let overlay else { return }
63
+ self.overlay = nil
64
+ // Reduce Motion keeps the fade, as UIKit's cross-dissolves do: it moves
65
+ // nothing.
66
+ UIView.animate(
67
+ withDuration: Self.fadeDuration, delay: 0, options: [.curveEaseOut],
68
+ animations: { overlay.alpha = 0 },
69
+ completion: { _ in overlay.removeFromSuperview() })
70
+ }
71
+ }
@@ -0,0 +1,95 @@
1
+ import Lynx
2
+ import WebKit
3
+ import XElement
4
+
5
+ /// The loader behind every `<webview>`: XElement's own, which lets its web
6
+ /// view go when the element goes.
7
+ ///
8
+ /// XElement's `LynxWebViewDefaultLoader` never does (issue #397). It makes
9
+ /// itself its web view's script message handler, and `WKUserContentController`
10
+ /// keeps its handlers until they're taken off, which nothing does. So the
11
+ /// loader keeps the web view, the web view's content controller keeps the
12
+ /// loader, and when the element lets the loader go, the two keep each other.
13
+ /// With them stays the WebContent process WebKit started for the web view:
14
+ /// every `<webview>` an app had shown stayed for as long as it ran, 21 of them
15
+ /// holding 0.9 to 2.4 GB after three visits to a screen with seven. Android's
16
+ /// WebViews have no such cycle and go with their elements.
17
+ ///
18
+ /// This wraps XElement's loader and takes the handler off when the element
19
+ /// lets it go, which ends the cycle; the two then go with the element.
20
+ /// Everything else is XElement's: the web view's settings, the navigation
21
+ /// callbacks, and the messages a page posts (`bindmessage`). The element
22
+ /// keeps its loader on the main thread, where this goes too.
23
+ final class ShellWebViewLoader: NSObject, LynxWebViewLoader {
24
+ private let loader: LynxWebViewLoader
25
+ /// The name the handler is under. Taken now: by the time this goes, the
26
+ /// element that names it (the delegate, held weakly) has gone.
27
+ private let handlerName: String
28
+ private var webView: WKWebView?
29
+
30
+ init(delegate: LynxWebViewLoaderDelegate) {
31
+ loader = LynxWebViewDefaultLoader(delegate: delegate)
32
+ handlerName = delegate.nameOfScriptMessageHandler()
33
+ super.init()
34
+ }
35
+
36
+ deinit {
37
+ webView?.configuration.userContentController
38
+ .removeScriptMessageHandler(forName: handlerName)
39
+ }
40
+
41
+ // XElement's container is its web view. Going through getWebView() here
42
+ // means the web view is known to deinit however the element first asks.
43
+ func getContainerView() -> UIView {
44
+ getWebView()
45
+ }
46
+
47
+ func getWebView() -> WKWebView {
48
+ let webView = loader.getWebView()
49
+ self.webView = webView
50
+ return webView
51
+ }
52
+
53
+ func setParams(_ params: [AnyHashable: Any]) {
54
+ loader.setParams(params)
55
+ }
56
+
57
+ func load(_ urlStr: String) {
58
+ loader.load(urlStr)
59
+ }
60
+
61
+ func loadHtmlString(_ htmlString: String) {
62
+ loader.loadHtmlString(htmlString)
63
+ }
64
+
65
+ func reload() {
66
+ loader.reload()
67
+ }
68
+
69
+ func evaluateJavaScript(
70
+ _ javaScriptString: String,
71
+ completionHandler: ((Any?, Error?) -> Void)?
72
+ ) {
73
+ loader.evaluateJavaScript(javaScriptString, completionHandler: completionHandler)
74
+ }
75
+ }
76
+
77
+ /// Makes `ShellWebViewLoader` the `"default"` loader, the one a `<webview>`
78
+ /// uses unless its `webview-type` names another.
79
+ final class ShellWebViewLoaderProvider: NSObject, LynxWebViewLoaderProvider {
80
+ static func register() {
81
+ // XElement registers its own provider as "default" in a task Lynx runs
82
+ // the first time it starts (LYNX_LOAD_LAZY), which would replace one
83
+ // registered before that. The tasks run once, so starting them here puts
84
+ // this one after XElement's.
85
+ LynxLazyRegister.loadLynxInitTask()
86
+ LynxWebViewService.sharedInstance().providers?["default"] =
87
+ ShellWebViewLoaderProvider()
88
+ }
89
+
90
+ func createLynxWebViewLoader(with delegate: LynxWebViewLoaderDelegate)
91
+ -> LynxWebViewLoader?
92
+ {
93
+ ShellWebViewLoader(delegate: delegate)
94
+ }
95
+ }
@@ -13,7 +13,8 @@ import XElement
13
13
  /// classes under the same names here, before the first LynxConfig or LynxView
14
14
  /// exists. `<blur-view>` is XElement's with UIKit's blur materials and glass
15
15
  /// transitions added (BlurView). `<canvas>` is the shell's own, for WebGL
16
- /// (AngularLynxWebGL.h).
16
+ /// (AngularLynxWebGL.h). `<webview>`'s loader is XElement's, wrapped so its web
17
+ /// view doesn't outlive the element (ShellWebViewLoader).
17
18
  enum XElementRegistry {
18
19
  static func register() {
19
20
  let elements: [(String, AnyClass)] = [
@@ -53,5 +54,8 @@ enum XElementRegistry {
53
54
  for (name, node) in shadowNodes {
54
55
  LynxComponentRegistry.registerShadowNode(node, withName: name)
55
56
  }
57
+ // <webview> loads through XElement's loader, wrapped so the web view and
58
+ // its WebContent process go with the element (WebViewLoader.swift).
59
+ ShellWebViewLoaderProvider.register()
56
60
  }
57
61
  }