@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
@@ -1,18 +1,25 @@
1
1
  package dev.angularlynx.shell
2
2
 
3
+ import android.Manifest
3
4
  import android.content.ContentValues
4
5
  import android.content.Context
6
+ import android.content.pm.PackageManager
5
7
  import android.database.sqlite.SQLiteException
6
8
  import android.net.Uri
7
9
  import android.os.Build
8
10
  import android.os.Environment
11
+ import android.os.Handler
12
+ import android.os.Looper
9
13
  import android.provider.MediaStore
10
14
  import android.util.Base64
15
+ import androidx.annotation.RequiresApi
16
+ import androidx.core.content.ContextCompat
11
17
  import com.lynx.jsbridge.LynxMethod
12
18
  import com.lynx.jsbridge.LynxModule
13
19
  import com.lynx.react.bridge.Callback
14
20
  import com.lynx.react.bridge.JavaOnlyMap
15
21
  import com.lynx.react.bridge.ReadableMap
22
+ import java.io.File
16
23
  import java.io.IOException
17
24
  import java.util.concurrent.Executors
18
25
 
@@ -28,18 +35,48 @@ import java.util.concurrent.Executors
28
35
  * A photo goes into MediaStore's images, in `Pictures/<app name>`, and a
29
36
  * video into its videos, in `Movies/<app name>`, where the gallery and
30
37
  * Google Photos find them. From Android 10 an app may add its own media
31
- * there without any permission, so the app declares none. Before Android 10
32
- * it would need WRITE_EXTERNAL_STORAGE, asked for while it runs, which the
33
- * shell has no way to ask for yet, so `save` answers `unavailable` there
34
- * (and `permission` says `unsupported`). Each method calls back once with
35
- * `{ permission }`, `{ id, permission }` or `{ error, message, permission }`,
36
- * where `error` is one of the runtime's PhotoLibraryErrorCode values.
38
+ * there without any permission. Android 7 to 9 need WRITE_EXTERNAL_STORAGE,
39
+ * and READ_EXTERNAL_STORAGE with it (Android 8 and 9 mount shared storage
40
+ * writable only for an app holding both, so with WRITE alone a save is
41
+ * refused once the app restarts), runtime permissions the manifest declares
42
+ * only up to Android 9: the first save there asks for them through
43
+ * MainActivity's prompt (PermissionHost, the module's param), then writes
44
+ * the file into the public folder and adds it to MediaStore, as those
45
+ * versions' MediaStore has no RELATIVE_PATH or IS_PENDING. Each method calls back once with `{ permission }`,
46
+ * `{ id, permission }` or `{ error, message, permission }`, where `error` is
47
+ * one of the runtime's PhotoLibraryErrorCode values.
37
48
  */
38
49
  class PhotoLibraryModule(context: Context, param: Any?) : LynxModule(context, param) {
39
- private val resolver = context.applicationContext.contentResolver
50
+ private val appContext = context.applicationContext
51
+ private val resolver = appContext.contentResolver
40
52
  private val appName =
41
53
  context.applicationInfo.loadLabel(context.packageManager).toString()
42
54
 
55
+ /**
56
+ * MainActivity's permission prompt, for Android 7 to 9. Null for a module
57
+ * registered without it, as a project ejected before the prompt was lent
58
+ * to this module registers it: that app can't ask, so a save there
59
+ * answers `permission-denied`.
60
+ */
61
+ private val permissions = param as? PermissionHost
62
+
63
+ // The activity's prompt is shown, and answered, on the main thread, so
64
+ // the saves waiting on it are kept there too.
65
+ private val main = Handler(Looper.getMainLooper())
66
+
67
+ /**
68
+ * The saves waiting for the person to answer the storage prompt. The
69
+ * first opens it, and those that come while it's open wait for the same
70
+ * answer, since the activity shows one prompt at a time.
71
+ */
72
+ private val waitingForStorage = mutableListOf<() -> Unit>()
73
+
74
+ // Whether the app has asked for the storage permission before. Android
75
+ // can't tell an app that, and a permission never asked for looks just
76
+ // like one refused for good, so it's kept across launches to tell
77
+ // `undetermined` from `denied`.
78
+ private val preferences = appContext.getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE)
79
+
43
80
  /** `{ permission }`: whether the app may add to the library. */
44
81
  @LynxMethod
45
82
  fun permission(callback: Callback) {
@@ -52,15 +89,56 @@ class PhotoLibraryModule(context: Context, param: Any?) : LynxModule(context, pa
52
89
  */
53
90
  @LynxMethod
54
91
  fun save(request: ReadableMap, callback: Callback) {
55
- if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
56
- callback.invoke(
57
- failure(
58
- "unavailable",
59
- "Saving to the photo library needs Android 10 or later.",
60
- ),
61
- )
92
+ if (needsStorage() && !storageGranted()) {
93
+ main.post { askForStorage { if (storageGranted()) write(request, callback) else refused(callback) } }
62
94
  return
63
95
  }
96
+ write(request, callback)
97
+ }
98
+
99
+ /**
100
+ * Asks for the storage permissions, then calls [answered] on the main
101
+ * thread once the person has chosen, or at once when the app can't ask.
102
+ */
103
+ private fun askForStorage(answered: () -> Unit) {
104
+ waitingForStorage += answered
105
+ if (waitingForStorage.size > 1) return
106
+ val host = permissions
107
+ val asked = try {
108
+ host?.requestPermissions(STORAGE) { results ->
109
+ // An empty answer is a prompt closed without a choice (the
110
+ // activity going away mid-request), which refused nothing:
111
+ // counting it as asked would read as denied for good.
112
+ if (results.isNotEmpty()) preferences.edit().putBoolean(ASKED, true).apply()
113
+ answerWaiting()
114
+ } ?: false
115
+ } catch (_: IllegalStateException) {
116
+ // The activity's launcher throws once the activity is going.
117
+ false
118
+ }
119
+ if (!asked) answerWaiting()
120
+ }
121
+
122
+ private fun answerWaiting() {
123
+ val waiting = waitingForStorage.toList()
124
+ waitingForStorage.clear()
125
+ waiting.forEach { it() }
126
+ }
127
+
128
+ private fun refused(callback: Callback) {
129
+ callback.invoke(
130
+ failure(
131
+ "permission-denied",
132
+ if (permissions == null) {
133
+ "This app can't ask for the storage permission Android ${Build.VERSION.RELEASE} needs to save photos."
134
+ } else {
135
+ "The app isn't allowed to add to the photo library."
136
+ },
137
+ ),
138
+ )
139
+ }
140
+
141
+ private fun write(request: ReadableMap, callback: Callback) {
64
142
  // Decoding and writing a video takes a moment: off the JavaScript
65
143
  // thread, one at a time.
66
144
  worker.execute {
@@ -93,6 +171,13 @@ class PhotoLibraryModule(context: Context, param: Any?) : LynxModule(context, pa
93
171
  }
94
172
 
95
173
  private fun insert(request: ReadableMap): Uri {
174
+ val media = decode(request)
175
+ // Spelled out rather than needsStorage(), so lint sees the check.
176
+ return if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) insertFile(media) else insertPending(media)
177
+ }
178
+
179
+ /** What [request] asks to save: its bytes, name and type, checked. */
180
+ private fun decode(request: ReadableMap): Media {
96
181
  val base64 = if (request.hasKey("base64")) request.getString("base64") else null
97
182
  val bytes = Base64.decode(base64 ?: throw IllegalArgumentException(), Base64.DEFAULT)
98
183
  val type = if (request.hasKey("type")) request.getString("type") ?: "" else ""
@@ -104,6 +189,16 @@ class PhotoLibraryModule(context: Context, param: Any?) : LynxModule(context, pa
104
189
  ?.replace('/', '_')
105
190
  ?.takeIf { it.isNotBlank() }
106
191
  ?: if (isVideo) "Video.mp4" else "Photo.jpg"
192
+ return Media(bytes, name, type, isVideo)
193
+ }
194
+
195
+ /**
196
+ * Android 10 and later: a MediaStore entry in the app's folder, hidden
197
+ * until its bytes are all written.
198
+ */
199
+ @RequiresApi(Build.VERSION_CODES.Q)
200
+ private fun insertPending(media: Media): Uri {
201
+ val (bytes, name, type, isVideo) = media
107
202
  val collection =
108
203
  if (isVideo) {
109
204
  MediaStore.Video.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
@@ -147,21 +242,113 @@ class PhotoLibraryModule(context: Context, param: Any?) : LynxModule(context, pa
147
242
  return uri
148
243
  }
149
244
 
245
+ /**
246
+ * Android 7 to 9: the file written into the public Pictures or Movies
247
+ * folder, in the app's own folder, then added to MediaStore by its path,
248
+ * which those versions' MediaStore takes in place of RELATIVE_PATH.
249
+ * Inserting gives the `content://` URI at once, where a media scan would
250
+ * answer later.
251
+ */
252
+ @Suppress("DEPRECATION")
253
+ private fun insertFile(media: Media): Uri {
254
+ val (bytes, name, type, isVideo) = media
255
+ if (Environment.getExternalStorageState() != Environment.MEDIA_MOUNTED) {
256
+ throw IOException("The phone's shared storage isn't available.")
257
+ }
258
+ val folder = File(
259
+ Environment.getExternalStoragePublicDirectory(
260
+ if (isVideo) Environment.DIRECTORY_MOVIES else Environment.DIRECTORY_PICTURES,
261
+ ),
262
+ folderName(),
263
+ )
264
+ if (!folder.isDirectory && !folder.mkdirs()) {
265
+ throw IOException("The folder ${folder.path} couldn't be made.")
266
+ }
267
+ val file = unusedFile(folder, name)
268
+ try {
269
+ file.writeBytes(bytes)
270
+ val values = ContentValues().apply {
271
+ put(MediaStore.MediaColumns.DATA, file.absolutePath)
272
+ put(MediaStore.MediaColumns.DISPLAY_NAME, file.name)
273
+ put(MediaStore.MediaColumns.MIME_TYPE, type)
274
+ put(MediaStore.MediaColumns.SIZE, bytes.size.toLong())
275
+ val now = System.currentTimeMillis()
276
+ put(MediaStore.MediaColumns.DATE_ADDED, now / 1000)
277
+ put(MediaStore.MediaColumns.DATE_MODIFIED, now / 1000)
278
+ if (!isVideo) put(MediaStore.Images.ImageColumns.DATE_TAKEN, now)
279
+ }
280
+ val collection =
281
+ if (isVideo) MediaStore.Video.Media.EXTERNAL_CONTENT_URI else MediaStore.Images.Media.EXTERNAL_CONTENT_URI
282
+ return try {
283
+ resolver.insert(collection, values)
284
+ } catch (error: IllegalArgumentException) {
285
+ throw UnsupportedType("The photo library doesn't take $type files.")
286
+ } ?: throw IOException("MediaStore didn't make an entry for it.")
287
+ } catch (error: Exception) {
288
+ // Nothing half-saved stays behind in the folder.
289
+ file.delete()
290
+ throw error
291
+ }
292
+ }
293
+
294
+ /**
295
+ * [name] in [folder], or `name (2).jpg` and on while that's taken: a file
296
+ * written over would change a photo already in the gallery. Android 10's
297
+ * MediaStore picks a free name itself.
298
+ */
299
+ private fun unusedFile(folder: File, name: String): File {
300
+ val dot = name.lastIndexOf('.').takeIf { it > 0 } ?: name.length
301
+ val stem = name.substring(0, dot)
302
+ val extension = name.substring(dot)
303
+ var file = File(folder, name)
304
+ var count = 2
305
+ while (file.exists()) file = File(folder, "$stem ($count)$extension").also { count++ }
306
+ return file
307
+ }
308
+
150
309
  /** The app's name as a folder, without what a path can't hold. */
151
310
  private fun folderName(): String =
152
311
  appName.replace(Regex("[\\\\/:*?\"<>|]"), "_").trim().ifEmpty { "Pictures" }
153
312
 
154
- private fun permissionName(): String =
155
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) "granted" else "unsupported"
313
+ /** Whether this Android version needs the storage permissions to add media. */
314
+ private fun needsStorage() = Build.VERSION.SDK_INT < Build.VERSION_CODES.Q
315
+
316
+ private fun storageGranted() = STORAGE.all {
317
+ ContextCompat.checkSelfPermission(appContext, it) == PackageManager.PERMISSION_GRANTED
318
+ }
319
+
320
+ /**
321
+ * `granted` from Android 10, or with the storage permission. Without it,
322
+ * `undetermined` while asking would still show Android's prompt (never
323
+ * asked, or refused without "Don't ask again"), and `denied` once only
324
+ * Settings can give it.
325
+ */
326
+ private fun permissionName(): String = when {
327
+ !needsStorage() || storageGranted() -> "granted"
328
+ preferences.getBoolean(ASKED, false) && STORAGE.none { permissions?.canAskAgain(it) == true } -> "denied"
329
+ else -> "undetermined"
330
+ }
156
331
 
157
332
  private fun failure(code: String, message: String) =
158
333
  JavaOnlyMap.from(mapOf("error" to code, "message" to message, "permission" to permissionName()))
159
334
 
160
335
  private class UnsupportedType(message: String) : Exception(message)
161
336
 
337
+ /** A file to save, as [decode] read it from the request. */
338
+ private data class Media(val bytes: ByteArray, val name: String, val type: String, val isVideo: Boolean)
339
+
162
340
  companion object {
163
341
  const val NAME = "AngularLynxPhotoLibrary"
164
342
 
343
+ // Capped at Android 9 in the manifest (permissions.ts).
344
+ @Suppress("DEPRECATION")
345
+ private val STORAGE = arrayOf(
346
+ Manifest.permission.READ_EXTERNAL_STORAGE,
347
+ Manifest.permission.WRITE_EXTERNAL_STORAGE,
348
+ )
349
+ private const val PREFERENCES = "dev.angularlynx.shell.PhotoLibrary"
350
+ private const val ASKED = "askedForStorage"
351
+
165
352
  // One thread, so saves happen in the order the app made them.
166
353
  private val worker = Executors.newSingleThreadExecutor()
167
354
  }
@@ -4,9 +4,6 @@ import android.app.Application
4
4
  import android.content.ComponentCallbacks2
5
5
  import android.content.pm.ApplicationInfo
6
6
  import com.facebook.drawee.backends.pipeline.Fresco
7
- import com.facebook.imagepipeline.core.ImagePipelineConfig
8
- import com.facebook.imagepipeline.memory.PoolConfig
9
- import com.facebook.imagepipeline.memory.PoolFactory
10
7
  import com.lynx.service.http.LynxHttpService
11
8
  import com.lynx.service.image.LynxImageService
12
9
  import com.lynx.service.log.LynxLogService
@@ -27,11 +24,7 @@ class ShellApplication : Application() {
27
24
  // LynxImageService draws <image> through Fresco, which must be
28
25
  // initialized first. Fresco also understands asset:/// URIs natively,
29
26
  // which is how bundled images are loaded (see AssetMediaResourceFetcher).
30
- val pools = PoolFactory(PoolConfig.newBuilder().build())
31
- Fresco.initialize(
32
- this,
33
- ImagePipelineConfig.newBuilder(this).setPoolFactory(pools).build(),
34
- )
27
+ Fresco.initialize(this, imagePipelineConfig(this))
35
28
  LynxServiceCenter.inst().registerService(LynxImageService.getInstance())
36
29
  LynxServiceCenter.inst().registerService(LynxLogService)
37
30
  LynxServiceCenter.inst().registerService(LynxHttpService)
@@ -6,6 +6,7 @@ import android.os.Looper
6
6
  import android.os.SystemClock
7
7
  import android.os.Trace
8
8
  import android.util.Log
9
+ import androidx.core.os.HandlerCompat
9
10
  import com.lynx.jsbridge.LynxMethod
10
11
  import com.lynx.jsbridge.LynxModule
11
12
  import com.lynx.tasm.LynxEnv
@@ -71,6 +72,15 @@ class ShellModule(context: Context, param: Any?) : LynxModule(context, param) {
71
72
  private val host = param as Host
72
73
  private val main = Handler(Looper.getMainLooper())
73
74
 
75
+ // The UI thread's queue for hideSplashScreen, whose messages don't wait
76
+ // behind a frame's sync barrier. While the splash screen is up, its
77
+ // pre-draw check cancels each frame and schedules the next, and each
78
+ // schedule puts a sync barrier in the UI thread's queue that holds back
79
+ // every ordinary message until that frame runs. So a hide posted to
80
+ // `main` ran only after the next frame had been canceled once more, and
81
+ // the screen came a frame later than it could: 8 ms at 120 Hz.
82
+ private val beforeNextFrame = HandlerCompat.createAsync(Looper.getMainLooper())
83
+
74
84
  interface Host {
75
85
  fun setBackHandlerEnabled(enabled: Boolean)
76
86
  fun hideSplashScreen()
@@ -84,7 +94,7 @@ class ShellModule(context: Context, param: Any?) : LynxModule(context, param) {
84
94
 
85
95
  @LynxMethod
86
96
  fun hideSplashScreen() {
87
- main.post { host.hideSplashScreen() }
97
+ beforeNextFrame.post { host.hideSplashScreen() }
88
98
  }
89
99
 
90
100
  @LynxMethod
@@ -1,8 +1,13 @@
1
1
  <?xml version="1.0" encoding="utf-8"?>
2
2
  <!--
3
- The folder FileProvider shares LynxShare's files from (ShareModule.kt
4
- writes them there), and nothing else of the app's.
3
+ The folders FileProvider shares from, and nothing else of the app's:
4
+ LynxShare's files (ShareModule.kt writes them there), and the folder the
5
+ camera app writes LynxImagePicker's photo to (ImagePickerModule.kt), which
6
+ only an app with angular.json's permissions.camera keeps.
5
7
  -->
6
8
  <paths>
7
9
  <cache-path name="shared" path="angular-lynx-share/" />
10
+ <!-- angular-lynx:image-picker-camera -->
11
+ <cache-path name="camera" path="angular-lynx-camera/" />
12
+ <!-- /angular-lynx:image-picker-camera -->
8
13
  </paths>
@@ -0,0 +1,22 @@
1
+ // Written by @blotch/angular-lynx-native from the plugins angular.json's
2
+ // `nativePlugins` lists: a generated project gets a new copy on every
3
+ // build, so change the plugins rather than this file. In an ejected
4
+ // project it is yours, and `nativePlugins` no longer applies.
5
+ import Lynx
6
+ import UIKit
7
+
8
+ /// The app's native plugins' modules and elements.
9
+ enum AngularLynxPlugins {
10
+ static func register(in config: LynxConfig, host: UIViewController) {}
11
+ }
12
+
13
+ /// A plugin module's param: the view controller showing the app, for a
14
+ /// module that presents a screen of its own. Weak, as Lynx keeps the
15
+ /// param as long as the config, which the controller keeps.
16
+ final class AngularLynxPluginHost: NSObject {
17
+ weak var viewController: UIViewController?
18
+
19
+ init(_ viewController: UIViewController) {
20
+ self.viewController = viewController
21
+ }
22
+ }
@@ -1,6 +1,7 @@
1
1
  import Foundation
2
2
  import ObjectiveC
3
3
  import QuartzCore
4
+ import UIKit
4
5
 
5
6
  /// Asks iOS to run the app's Core Animation transitions at up to 120 fps on a
6
7
  /// ProMotion iPhone.
@@ -178,6 +179,71 @@ final class LynxAnimatorFrameRate: NSObject {
178
179
  }
179
180
  }
180
181
 
182
+ /// Asks iOS for fast motion's rate while a finger moves in the app's window.
183
+ ///
184
+ /// A page that follows the finger isn't animated: `<lynx-stack-outlet>`'s
185
+ /// swipe back and `ui-sheet`'s drag set a transform from each `touchmove`,
186
+ /// as an app's own drag does. So nothing above asks for a rate, and iOS draws
187
+ /// the drag at 60 fps, where UIKit's interactive pop and sheet drag draw at
188
+ /// 120. On an iPhone 17 Pro the stack's swipe back drew a frame every 16.7 ms
189
+ /// until the finger lifted, and the settle animation then drew one every
190
+ /// 8.3 ms.
191
+ ///
192
+ /// The window hands it every touch event it sends (`ShellWindow`), so a touch
193
+ /// in a system sheet or a popover that shows Lynx content counts too. It
194
+ /// reads the events after the window has sent them and takes part in nothing:
195
+ /// a gesture recognizer on the window would, and Lynx's touch handler waits
196
+ /// for every recognizer outside the LynxView to fail before it recognizes,
197
+ /// which one that only watches never does, so the stack's swipe back stopped
198
+ /// working. It asks only while a finger moves, and for a few frames after: a
199
+ /// finger resting on the screen moves nothing.
200
+ final class TouchFrameRate: NSObject {
201
+ static let shared = TouchFrameRate()
202
+
203
+ /// How long the rate is asked for after a finger last moved: a few frames,
204
+ /// so a frame Angular's work delays doesn't drop it mid-drag, and the
205
+ /// animation a release starts asks for its own.
206
+ static let linger: CFTimeInterval = 0.1
207
+
208
+ private var lastMove: CFTimeInterval = 0
209
+ /// Runs, asking for `AnimationFrameRate.fastMotion`, while a finger moves.
210
+ /// Only the main thread, where the window sends events, touches it.
211
+ private var link: CADisplayLink?
212
+
213
+ /// Called with each event the window has sent.
214
+ func windowSent(_ event: UIEvent) {
215
+ guard event.type == .touches,
216
+ event.allTouches?.contains(where: { $0.phase == .moved }) == true
217
+ else { return }
218
+ lastMove = CACurrentMediaTime()
219
+ let link: CADisplayLink
220
+ if let existing = self.link {
221
+ link = existing
222
+ } else {
223
+ link = CADisplayLink(target: self, selector: #selector(tick(_:)))
224
+ link.preferredFrameRateRange = AnimationFrameRate.fastMotion
225
+ // `.common`, so it keeps running while a scroll view tracks the touch.
226
+ link.add(to: .main, forMode: .common)
227
+ self.link = link
228
+ }
229
+ link.isPaused = false
230
+ }
231
+
232
+ @objc private func tick(_ link: CADisplayLink) {
233
+ if link.timestamp - lastMove > Self.linger {
234
+ link.isPaused = true
235
+ }
236
+ }
237
+ }
238
+
239
+ /// The app's window, which shows `TouchFrameRate` the touch events it sends.
240
+ final class ShellWindow: UIWindow {
241
+ override func sendEvent(_ event: UIEvent) {
242
+ super.sendEvent(event)
243
+ TouchFrameRate.shared.windowSent(event)
244
+ }
245
+ }
246
+
181
247
  extension NSObject {
182
248
  /// Takes the place of `LynxVSyncPulse`'s `requestPulse` once
183
249
  /// `LynxAnimatorFrameRate.install()` has run, so `self` is a `LynxVSyncPulse`.
@@ -77,7 +77,9 @@ final class SceneDelegate: UIResponder, UIWindowSceneDelegate {
77
77
  (connectionOptions.urlContexts.lazy.map(\.url).first { !Self.isShareLink($0) }
78
78
  ?? connectionOptions.userActivities.lazy.compactMap(Self.universalLink).first)?
79
79
  .absoluteString
80
- let window = UIWindow(windowScene: windowScene)
80
+ // A ShellWindow, so a drag that moves the app's content asks for 120
81
+ // fps, as an animation does (TouchFrameRate in AnimationFrameRate.swift).
82
+ let window = ShellWindow(windowScene: windowScene)
81
83
  window.rootViewController = LynxViewController()
82
84
  window.makeKeyAndVisible()
83
85
  self.window = window