react-native-minimal-webview 1.2.1 → 1.3.0

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 (96) hide show
  1. package/android/build.gradle +1 -1
  2. package/android/src/main/java/expo/modules/minimalwebview/Asks.kt +5 -11
  3. package/android/src/main/java/expo/modules/minimalwebview/Hooks.kt +17 -11
  4. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebView.kt +64 -119
  5. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewClients.kt +16 -31
  6. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewModule.kt +4 -16
  7. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewNavigation.kt +24 -38
  8. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewScripts.kt +24 -36
  9. package/android/src/main/java/expo/modules/minimalwebview/NavigationRules.kt +19 -20
  10. package/android/src/main/java/expo/modules/minimalwebview/PlatformSettings.kt +25 -37
  11. package/android/src/main/java/expo/modules/minimalwebview/PullToRefresh.kt +14 -18
  12. package/android/src/main/java/expo/modules/minimalwebview/requests/Downloads.kt +12 -23
  13. package/android/src/main/java/expo/modules/minimalwebview/requests/FileUpload.kt +0 -1
  14. package/android/src/main/java/expo/modules/minimalwebview/requests/FullscreenVideo.kt +1 -4
  15. package/android/src/main/java/expo/modules/minimalwebview/requests/Permissions.kt +34 -24
  16. package/build/WebView.d.ts +8 -1
  17. package/build/WebView.d.ts.map +1 -1
  18. package/build/WebView.js +22 -68
  19. package/build/WebView.js.map +1 -1
  20. package/build/bridge/createBridge.d.ts +1 -5
  21. package/build/bridge/createBridge.d.ts.map +1 -1
  22. package/build/bridge/createBridge.js +3 -15
  23. package/build/bridge/createBridge.js.map +1 -1
  24. package/build/bridge/endpoint.d.ts +1 -2
  25. package/build/bridge/endpoint.d.ts.map +1 -1
  26. package/build/bridge/endpoint.js +5 -6
  27. package/build/bridge/endpoint.js.map +1 -1
  28. package/build/bridge/matchesOrigin.d.ts +11 -0
  29. package/build/bridge/matchesOrigin.d.ts.map +1 -0
  30. package/build/bridge/matchesOrigin.js +26 -0
  31. package/build/bridge/matchesOrigin.js.map +1 -0
  32. package/build/bridge/origins.d.ts +2 -13
  33. package/build/bridge/origins.d.ts.map +1 -1
  34. package/build/bridge/origins.js +1 -30
  35. package/build/bridge/origins.js.map +1 -1
  36. package/build/bridge/pageClient.generated.d.ts +1 -1
  37. package/build/bridge/pageClient.generated.d.ts.map +1 -1
  38. package/build/bridge/pageClient.generated.js +2 -2
  39. package/build/bridge/pageClient.generated.js.map +1 -1
  40. package/build/bridge/protocol.d.ts +3 -5
  41. package/build/bridge/protocol.d.ts.map +1 -1
  42. package/build/bridge/protocol.js +12 -14
  43. package/build/bridge/protocol.js.map +1 -1
  44. package/build/index.d.ts +1 -1
  45. package/build/index.js +1 -1
  46. package/build/navigationRules.d.ts +0 -5
  47. package/build/navigationRules.d.ts.map +1 -1
  48. package/build/navigationRules.js +3 -12
  49. package/build/navigationRules.js.map +1 -1
  50. package/build/reactNativeWebViewDefaults.d.ts +0 -4
  51. package/build/reactNativeWebViewDefaults.d.ts.map +1 -1
  52. package/build/reactNativeWebViewDefaults.js +0 -4
  53. package/build/reactNativeWebViewDefaults.js.map +1 -1
  54. package/build/reactNativeWebViewMessages.d.ts.map +1 -1
  55. package/build/reactNativeWebViewMessages.js +0 -1
  56. package/build/reactNativeWebViewMessages.js.map +1 -1
  57. package/build/refStore.d.ts +0 -2
  58. package/build/refStore.d.ts.map +1 -1
  59. package/build/refStore.js +0 -6
  60. package/build/refStore.js.map +1 -1
  61. package/build/types.d.ts +25 -12
  62. package/build/types.d.ts.map +1 -1
  63. package/ios/Asks.swift +6 -9
  64. package/ios/DelegateProxy.swift +2 -19
  65. package/ios/DownloadName.swift +0 -2
  66. package/ios/Downloads.swift +0 -2
  67. package/ios/Hooks.swift +4 -6
  68. package/ios/Loads.swift +37 -19
  69. package/ios/MinimalWebView+Dialogs.swift +2 -6
  70. package/ios/MinimalWebView+Navigation.swift +17 -50
  71. package/ios/MinimalWebView+Scripts.swift +4 -16
  72. package/ios/MinimalWebView.podspec +1 -2
  73. package/ios/MinimalWebView.swift +62 -132
  74. package/ios/MinimalWebViewModule.swift +1 -18
  75. package/ios/NavigationRules.swift +2 -9
  76. package/ios/OriginRules.swift +4 -13
  77. package/ios/PlatformSettings.swift +9 -30
  78. package/ios/ReadAccess.swift +0 -2
  79. package/ios/Records.swift +18 -0
  80. package/ios/Recovery.swift +2 -8
  81. package/ios/SharedCookies.swift +10 -25
  82. package/package.json +4 -4
  83. package/src/WebView.tsx +34 -77
  84. package/src/bridge/createBridge.ts +5 -20
  85. package/src/bridge/endpoint.ts +6 -9
  86. package/src/bridge/matchesOrigin.ts +27 -0
  87. package/src/bridge/origins.ts +2 -30
  88. package/src/bridge/pageClient.generated.ts +2 -2
  89. package/src/bridge/pageClient.ts +1 -7
  90. package/src/bridge/protocol.ts +16 -18
  91. package/src/index.ts +1 -1
  92. package/src/navigationRules.ts +6 -12
  93. package/src/reactNativeWebViewDefaults.ts +0 -4
  94. package/src/reactNativeWebViewMessages.ts +0 -1
  95. package/src/refStore.ts +0 -7
  96. package/src/types.ts +25 -12
@@ -4,7 +4,7 @@ plugins {
4
4
  }
5
5
 
6
6
  group = 'expo.modules.minimalwebview'
7
- version = '0.1.0' // expo-autolinking requires it
7
+ version = '0.1.0' // expo-module-gradle-plugin requires it
8
8
 
9
9
  android {
10
10
  namespace "expo.modules.minimalwebview"
@@ -1,22 +1,16 @@
1
1
  package expo.modules.minimalwebview
2
2
 
3
-
4
- /**
5
- * Every `ask` (a page request, a navigation request or a hook's) waits here, by id, until JS answers it through [answer]
6
- * or native gives up (null, and the core's `askCancelled` to JS): a Document end, a timeout or the platform. [send] puts an
7
- * event on the view's `onHookEvent`, which reaches the app's extensions' `onEvent`. Main thread only.
8
- */
3
+ /** Main thread only. */
9
4
  internal class Asks(private val send: (Map<String, Any?>) -> Unit) {
10
5
  private val pending = mutableMapOf<Int, (Any?) -> Unit>()
11
6
  private var nextId = 0
12
- /** The view closed: JS is unmounted, and a hook may still hold its context. */
13
7
  private var closed = false
14
8
 
15
- /** Sends the ask to JS and returns its id, for [cancel]. Once the view closed it answers null at once. */
16
- fun ask(key: String, name: String, payload: Map<String, Any?>, onAnswer: (Any?) -> Unit): Int {
9
+ /** Sends the ask to JS and returns its id, for [cancel]. Once the view closed it answers null at once and returns null. */
10
+ fun ask(key: String, name: String, payload: Map<String, Any?>, onAnswer: (Any?) -> Unit): Int? {
17
11
  if (closed) {
18
12
  onAnswer(null)
19
- return 0 // no ask: cancel(0) finds nothing
13
+ return null
20
14
  }
21
15
  val id = ++nextId
22
16
  pending[id] = onAnswer
@@ -36,7 +30,7 @@ internal class Asks(private val send: (Map<String, Any?>) -> Unit) {
36
30
  onAnswer(null)
37
31
  }
38
32
 
39
- /** Cancels every pending ask. At closing JS isn't told: it aborts its own handlers at unmount. */
33
+ /** Cancels every pending ask. At closing JS isn't told. */
40
34
  fun documentEnded(reason: DocumentEnd) {
41
35
  if (reason == DocumentEnd.CLOSING) closed = true
42
36
  pending.keys.toList().forEach { cancel(it, tell = reason != DocumentEnd.CLOSING) }
@@ -33,8 +33,16 @@ object MinimalWebViewHooks {
33
33
  val key: String,
34
34
  val webViewFactory: ((Context) -> WebView)?,
35
35
  val configure: ((WebView, WebViewContext) -> Unit)?,
36
+ val newWebViewsOnly: Boolean,
36
37
  val attach: (WebView, WebViewContext) -> Unit
37
- )
38
+ ) {
39
+ val whyNotLate get() = when {
40
+ configure != null -> "configure"
41
+ webViewFactory != null -> "a webViewFactory"
42
+ newWebViewsOnly -> "newWebViewsOnly"
43
+ else -> null
44
+ }
45
+ }
38
46
 
39
47
  internal val hooks = mutableListOf<Hook>()
40
48
 
@@ -64,6 +72,8 @@ object MinimalWebViewHooks {
64
72
  * @param configure runs on the main thread as soon as each WebView this hook is attached to, on or off, is made,
65
73
  * before the package sets it up ([WebViewCompat.setProfile][androidx.webkit.WebViewCompat.setProfile] goes here).
66
74
  * It gets the same context that [attach] gets next for that WebView, so state it makes can be keyed by the context.
75
+ * @param newWebViewsOnly true attaches the hook only when a WebView is created, never to one whose key turns on
76
+ * later, as a hook with [configure] or [webViewFactory] does.
67
77
  * @param attach runs on the main thread once the WebView has its settings and is in the view hierarchy, so what it
68
78
  * sets wins over those settings. Register what to run when that WebView goes away with
69
79
  * [WebViewContext.onDestroyed]. Document-start scripts you add here run before the package's, so
@@ -73,13 +83,14 @@ object MinimalWebViewHooks {
73
83
  key: String,
74
84
  webViewFactory: ((Context) -> WebView)? = null,
75
85
  configure: ((WebView, WebViewContext) -> Unit)? = null,
86
+ newWebViewsOnly: Boolean = false,
76
87
  attach: (WebView, WebViewContext) -> Unit
77
88
  ) {
78
89
  if (key == "core") {
79
90
  Log.e(TAG, "the hook key `core` is reserved: the hook is not registered")
80
91
  return
81
92
  }
82
- if (putHook(hooks, Hook(key, webViewFactory, configure, attach))) {
93
+ if (putHook(hooks, Hook(key, webViewFactory, configure, newWebViewsOnly, attach))) {
83
94
  Log.w(
84
95
  TAG,
85
96
  "a hook under `$key` replaces the one registered before: a JS reload registers every hook again; " +
@@ -228,8 +239,8 @@ interface WebViewContext {
228
239
  fun emit(name: String, payload: Map<String, Any?>)
229
240
 
230
241
  /**
231
- * Sends the event as [emit] does, and calls [onAnswer] with JS's answer: the extension's `onEvent` return value, a
232
- * promise awaited, in JSON types as [handle]'s arguments are.
242
+ * Sends the event as [emit] does, but to the extension's `onAsk` when it has one, and calls [onAnswer] with JS's
243
+ * answer: that handler's return value, a promise awaited, in JSON types as [handle]'s arguments are.
233
244
  *
234
245
  * It answers null when the handler throws or there is none, or when the Document ends first; there is no timeout. It
235
246
  * answers null at once while the hook is off, and after the context's attach ended. An ask made before the WebView's
@@ -310,9 +321,8 @@ class HookReply internal constructor(
310
321
  }
311
322
 
312
323
  /**
313
- * [HookContext]'s base: the hook's `hookOptions` value (null while its key is absent), its lists, and whether the core
314
- * routes them. Chromium's IO thread reads [routed] and [clients] (shouldInterceptRequest), so [options] and the detach
315
- * are volatile; the rest is main thread only.
324
+ * Chromium's IO thread reads [routed] and [clients] (shouldInterceptRequest), so [options] and the detach are volatile;
325
+ * the rest is main thread only.
316
326
  */
317
327
  internal open class Attachment(value: Any?) {
318
328
  @Volatile var options: Any? = value
@@ -325,7 +335,6 @@ internal open class Attachment(value: Any?) {
325
335
  // own changes write them.
326
336
  val clients: MutableList<WebViewClient> = CopyOnWriteArrayList()
327
337
  val chromeClients = mutableListOf<WebChromeClient>()
328
- // Copy-on-write too: the core iterates them live, and a listener may remove itself while it runs.
329
338
  val touchListeners: MutableList<View.OnTouchListener> = CopyOnWriteArrayList()
330
339
  val scrollListeners: MutableList<View.OnScrollChangeListener> = CopyOnWriteArrayList()
331
340
 
@@ -374,10 +383,8 @@ internal open class Attachment(value: Any?) {
374
383
  internal fun <T> routed(attachments: List<Attachment>, pick: (Attachment) -> List<T>) =
375
384
  attachments.filter { it.routed }.flatMap(pick)
376
385
 
377
- /** The core's [WebViewContext] for one hook's attach: the hook's key goes on its events and asks. */
378
386
  internal class HookContext(val hook: MinimalWebViewHooks.Hook, view: MinimalWebView) :
379
387
  Attachment(view.hookOptions[hook.key]), WebViewContext {
380
- /** Null once the attach ended. Main thread only. */
381
388
  private var view: MinimalWebView? = view
382
389
  val key get() = hook.key
383
390
  override val url get() = view?.url.orEmpty()
@@ -385,7 +392,6 @@ internal class HookContext(val hook: MinimalWebViewHooks.Hook, view: MinimalWebV
385
392
  private val destroyedHandlers = mutableListOf<(DocumentEnd) -> Unit>()
386
393
  val handlers = mutableMapOf<String, (List<Any?>, HookReply) -> Unit>()
387
394
 
388
- /** The attach ended: also drops the view and what the hook gave it, bar the [onDestroyed] handlers [destroyed] runs next. */
389
395
  override fun detach() {
390
396
  super.detach()
391
397
  view = null
@@ -42,17 +42,14 @@ internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoVi
42
42
  private val navigation = MinimalWebViewNavigation(this) { onNavigation(it) }
43
43
  internal val scripts = MinimalWebViewScripts(this) { onBridge(it) }
44
44
 
45
- /** Set by the first prop batch and replaced after a renderer crash; see [recovering]. */
46
45
  internal lateinit var webView: WebView
47
46
  private set
48
47
  private val hasWebView get() = ::webView.isInitialized
49
48
 
50
- // Props, applied together in applyProps()
51
49
  internal var source: WebViewSource? = null
52
50
  internal var navigationRules: List<Map<String, Any?>>? = null
53
51
  internal var bridgeScript: String? = null
54
52
  internal var bridgeOrigins: List<String>? = null
55
- /** The `hookOptions` prop, made from the `extensions` prop's options: each hook's value by key. A change reaches the attached hooks (onOptions). */
56
53
  internal var hookOptions: Map<String, Any?> = emptyMap()
57
54
  set(value) {
58
55
  val old = field
@@ -60,7 +57,6 @@ internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoVi
60
57
  if (hasWebView) optionsChanged(old)
61
58
  }
62
59
  internal var injectedScripts: List<InjectedScript>? = null
63
- /** The `android` prop: WebSettings and WebView setters by name, applied by [PlatformSettings]. */
64
60
  internal var settings: Map<String, Any?>? = null
65
61
  internal val platformSettings = PlatformSettings({ hasNavigationListener }) { PlatformSettings.targets(webView, it) }
66
62
  private val refresher = PullToRefresh(this)
@@ -69,63 +65,47 @@ internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoVi
69
65
  field = value
70
66
  refresher.layout.isEnabled = value
71
67
  }
72
- /**
73
- * The page requests JS has a prop for, by prop name (`onFileRequest`, `onDownload`, ...), and `onNavigation`, read when a
74
- * request comes or a decision is reported.
75
- */
68
+ /** The page requests JS has a prop for, by prop name (`onFileRequest`, `onDownload`, ...), and `onNavigation`. */
76
69
  internal var requestHandlers: Set<String> = emptySet()
77
70
  private var loadedSource: WebViewSource? = null
78
71
 
79
- // The hooks' lists: each context owns its own, and the core routes those of the hooks that are on, in attach order.
80
72
  val clients: List<WebViewClient> get() = routed(hookContexts) { it.clients }
81
73
  val chromeClients: List<WebChromeClient> get() = routed(hookContexts) { it.chromeClients }
82
74
  internal val fileUpload = FileUpload(this)
83
75
  internal val fullscreen = FullscreenVideo(this)
84
76
  internal val permissions = Permissions(this)
85
77
  private val downloads = Downloads(this)
86
- /** Keys of the extensions that are on in `hookOptions` when the first WebView is made, plus those attached later. They pick the hooks again for the WebView built after a crash. */
87
- private var hookKeys: Set<String> = emptySet()
88
- /** The hooks' contexts for the current WebView, in attach order. Chromium's IO thread reads it (shouldInterceptRequest). */
78
+ private var keysToAttach: Set<String> = emptySet()
79
+ /** Chromium's IO thread reads it (shouldInterceptRequest). */
89
80
  @Volatile private var hookContexts: List<HookContext> = emptyList()
90
81
 
91
82
  internal val asks = Asks { onHookEvent(it) }
92
83
  internal val deciders = Deciders { message -> mainHandler.post { warn(message) } }
93
84
 
94
- // Navigation state: native owns it and tells JS. The clients (MinimalWebViewClients.kt) write it.
95
85
  internal var url = ""
96
86
  internal var pendingUrl: String? = null
97
87
  internal var title = ""
98
88
  internal var loading = false
99
89
  internal var progress = 0.0
100
- /** How the current load ends so far, "finished", "failed" or "cancelled"; JS sees it only once `loading` is false. */
101
- internal var outcome: String? = null
90
+ private var outcome: LoadOutcome? = null
102
91
  private var lastEmitted: Map<String, Any?>? = null
103
92
  private var emitScheduled = false
104
93
 
105
- /**
106
- * From a renderer death until [recover] builds the new WebView: whether it loads, the dead one's history, and whether
107
- * that history can come back on its own (the page on screen isn't the source).
108
- */
109
94
  private var pendingRecovery: Recovery? = null
110
95
  private class Recovery(val reload: Boolean, val history: Bundle?, val restorable: Boolean)
111
- /** The ref's `load` while a recovery waits: [recover] loads it instead of the dead WebView's page. */
112
96
  private var pendingLoad: String? = null
113
97
  private var destroyed = false
114
98
 
115
99
  init {
116
- // The WebView goes into the layout in setUp(); the prop only turns the pull on and off.
117
100
  addView(refresher.layout, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
118
101
  }
119
102
 
120
- private fun createWebView(): WebView {
121
- // recover() calls this while the dead WebView is still set: the keys and the one-time warnings carry over.
122
- val first = !hasWebView
123
- if (first) hookKeys = hookOptions.keys
124
- val (attaching, unregistered) = selectHooks(MinimalWebViewHooks.hooks, hookKeys)
103
+ private fun createWebView(first: Boolean): WebView {
104
+ if (first) keysToAttach = hookOptions.keys
105
+ val (attaching, unregistered) = selectHooks(MinimalWebViewHooks.hooks, keysToAttach)
125
106
  val (maker, unused) = pickFactory(attaching)
126
107
  val view = maker?.webViewFactory?.invoke(context) ?: WebView(context)
127
108
  hookContexts = attaching.map { HookContext(it, this) }
128
- // A typo, or a hook's module not linked or not rebuilt. Once: the WebView after a crash has the same keys.
129
109
  if (first) unregistered.forEach { warn("extension $it: no hook is registered under this key") }
130
110
  if (first) unused.forEach { warn("extension $it: its webViewFactory is not used, ${maker?.key}'s is") }
131
111
  // Before the package touches the WebView: some calls (WebViewCompat.setProfile) must come first.
@@ -143,14 +123,12 @@ internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoVi
143
123
  }
144
124
  if (!taken && !downloads.onDownloadStart(download)) navigation.openDownload(url)
145
125
  }
146
- // View's slots hold one listener each: the hooks share them through their lists.
147
126
  view.setOnTouchListener(::touched)
148
127
  view.setOnScrollChangeListener(::scrolled)
149
128
  if (hasNavigationListener) WebViewCompat.addNavigationListener(view, context.mainExecutor, Listener(this))
150
129
  return view
151
130
  }
152
131
 
153
- // The on hooks' own lists, not copies: this runs for every touch event and scroll change.
154
132
  private fun touched(view: View, event: MotionEvent) =
155
133
  hookContexts.any { c -> c.routed && c.touchListeners.any { it.onTouch(view, event) } }
156
134
 
@@ -163,38 +141,30 @@ internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoVi
163
141
  @SuppressLint("SetJavaScriptEnabled") // because a browser-tab WebView needs JS; no addJavascriptInterface is used
164
142
  private fun configure(settings: WebSettings) {
165
143
  settings.javaScriptEnabled = true
166
- // A tap's window.open and target=_blank reach onCreateWindow; the navigation rules decide (newWindow: true).
167
- // Without a gesture only when the app opts in (javaScriptCanOpenWindowsAutomatically, in applySettings).
168
144
  settings.setSupportMultipleWindows(true)
169
145
  settings.domStorageEnabled = true
170
146
  settings.allowFileAccess = false
171
147
  settings.allowContentAccess = false
172
148
  settings.mixedContentMode = WebSettings.MIXED_CONTENT_NEVER_ALLOW
173
- // Pinch-zoom (an accessibility basic; pages opt out with a viewport meta), without the legacy +/- buttons.
174
149
  settings.builtInZoomControls = true
175
150
  settings.displayZoomControls = false
176
- // Back and forward restore the page instead of reloading it, as WebKit does. `android.settings` applies after this.
177
151
  // Not without NavigationListener: WebView 133 sends onPageStarted for a restored page but no onPageFinished.
178
152
  if (hasNavigationListener && WebViewFeature.isFeatureSupported(WebViewFeature.BACK_FORWARD_CACHE)) {
179
153
  WebSettingsCompat.setBackForwardCacheEnabled(settings, true)
180
154
  }
181
- // No favicon requests: nothing shows them.
182
155
  if (WebViewFeature.isFeatureSupported(WebViewFeature.DOWNLOAD_FAVICONS_ENABLED)) {
183
156
  WebSettingsCompat.setDownloadFaviconsEnabled(settings, false)
184
157
  }
185
158
  }
186
159
 
187
- /** Called once per prop batch. `source` loads last so everything else is ready first. */
188
160
  internal fun applyProps() {
189
- // The dead WebView after a crash takes nothing: recover() applies the props to the new one.
190
161
  if (recovering) return
191
- // The first prop batch sets up the first WebView: the hooks get their options with it.
192
162
  if (hasWebView) {
193
163
  applySettings()
194
164
  scripts.update()
195
165
  } else {
196
166
  webView = try {
197
- createWebView()
167
+ createWebView(first = true)
198
168
  } catch (e: AndroidRuntimeException) { // no WebView provider: missing, disabled or updating
199
169
  return reportError("network", source?.uri.orEmpty(), WebViewClient.ERROR_UNKNOWN, "Android System WebView is unavailable: ${e.message}")
200
170
  }
@@ -203,16 +173,13 @@ internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoVi
203
173
  loadNewSource()
204
174
  }
205
175
 
206
- /** Loads `source` if it isn't the one loaded yet; returns whether it did. */
207
- private fun loadNewSource(): Boolean {
208
- val next = source ?: return false
209
- if (next == loadedSource) return false
176
+ private fun loadNewSource() {
177
+ val next = source ?: return
178
+ if (next == loadedSource) return
210
179
  loadedSource = next
211
180
  load(next)
212
- return true
213
181
  }
214
182
 
215
- /** Readies a new WebView, the first or the one after a crash, in one order: settings, layout, hooks, scripts. */
216
183
  private fun setUp() {
217
184
  applySettings(force = true)
218
185
  // addView(view) alone would give the view WRAP_CONTENT, and Chromium then resolves CSS vh to 0.
@@ -227,7 +194,7 @@ internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoVi
227
194
  if (source.uri == null) {
228
195
  webView.loadDataWithBaseURL(source.baseUrl, source.html ?: "", "text/html", "utf-8", null)
229
196
  } else if (source.body != null) {
230
- webView.postUrl(source.uri, source.body.toByteArray()) // form-urlencoded; postUrl takes no headers
197
+ webView.postUrl(source.uri, source.body.toByteArray())
231
198
  } else {
232
199
  webView.loadUrl(source.uri, source.headers.orEmpty())
233
200
  }
@@ -239,15 +206,11 @@ internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoVi
239
206
  if (recovering) pendingLoad = url else webView.loadUrl(url)
240
207
  }
241
208
 
242
- /** Loads the page on screen again: the `source` when that is the page (its headers, html or POST), else its URL. */
243
209
  private fun loadAgain() {
244
210
  if (showsSource(source, url)) source?.let(::load) else if (url.isNotEmpty()) webView.loadUrl(url)
245
211
  }
246
212
 
247
- /**
248
- * The ref's reload: the app's retry starts the crash-loop guard over. Only this and [load] clear it: the guard counts
249
- * the process's renderer deaths, so another view's new source or pull-to-refresh mustn't end a crash loop's count.
250
- */
213
+ /** The ref's reload: the app's retry starts the crash-loop guard over. */
251
214
  internal fun retry() {
252
215
  crashTimes.clear()
253
216
  reload()
@@ -255,12 +218,9 @@ internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoVi
255
218
 
256
219
  internal fun reload() {
257
220
  when {
258
- // The renderer died and the new WebView isn't built yet: build it now, and load.
259
- recovering -> recover(reload = true)
260
- // The first WebView couldn't be made (onError said so): try again.
221
+ recovering -> recover(forceLoad = true)
261
222
  !hasWebView -> applyProps()
262
- // Nothing loaded: the crash-loop guard gave up (processGone), and this is the app's retry. Or a POST source:
263
- // WebView's reload declines its form resubmission.
223
+ // A POST source: WebView's reload declines its form resubmission.
264
224
  webView.url == null || showingPost -> loadAgain()
265
225
  else -> webView.reload()
266
226
  }
@@ -268,18 +228,12 @@ internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoVi
268
228
 
269
229
  private val showingPost get() = source?.body != null && showsSource(source, url)
270
230
 
271
- /**
272
- * The `android` settings, applied from each prop batch (only the keys that changed) and all again to a new WebView
273
- * after a crash. A key that can't be applied is reported to JS, which warns.
274
- */
275
231
  private fun applySettings(force: Boolean = false) {
276
232
  platformSettings.apply(settings, force).forEach { warn("android.${it["key"]}: ${it["reason"]}") }
277
233
  }
278
234
 
279
- /** A warning for the app's developer, which JS logs with console.warn. */
280
235
  internal fun warn(message: String) = emit("core", "warning", mapOf("message" to message))
281
236
 
282
- /** Tells each attached hook whose value changed, and attaches a hook without `configure` or `webViewFactory` whose key turns on. */
283
237
  private fun optionsChanged(old: Map<String, Any?>) {
284
238
  for (key in inRegistrationOrder(old.keys + hookOptions.keys, MinimalWebViewHooks.hooks.map { it.key })) {
285
239
  val value = hookOptions[key]
@@ -287,7 +241,7 @@ internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoVi
287
241
  val context = hookContexts.find { it.key == key }
288
242
  if (context != null) {
289
243
  context.optionsChanged(value)
290
- } else if (key !in hookKeys && old[key] == null) {
244
+ } else if (key !in keysToAttach && old[key] == null) {
291
245
  attachLate(key)
292
246
  }
293
247
  }
@@ -296,13 +250,8 @@ internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoVi
296
250
  private fun attachLate(key: String) {
297
251
  val hook = MinimalWebViewHooks.hooks.find { it.key == key }
298
252
  ?: return warn("extension $key: no hook is registered under this key")
299
- // configure runs before the package sets the WebView up, and a factory makes it: too late for one that exists.
300
- if (hook.configure != null || hook.webViewFactory != null) {
301
- val why = if (hook.configure != null) "configure" else "a webViewFactory"
302
- return warn("extension $key: its hook has $why, so it attaches only when the WebView is created")
303
- }
304
- hookKeys = hookKeys + key
305
- // The WebView the recovery builds attaches it with the others.
253
+ hook.whyNotLate?.let { return warn("extension $key: its hook has $it, so it attaches only when the WebView is created") }
254
+ keysToAttach = keysToAttach + key
306
255
  if (recovering) return
307
256
  val context = HookContext(hook, this)
308
257
  hookContexts = hookContexts + context
@@ -315,21 +264,18 @@ internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoVi
315
264
  fun emit(key: String, name: String, payload: Map<String, Any?>) =
316
265
  onHookEvent(mapOf("key" to key, "name" to name, "payload" to payload))
317
266
 
318
- private var documentOpen = false
319
-
320
- internal fun endDocument(reason: DocumentEnd) {
321
- // The first commit after mount or a crash opens a Document and ends none: the asks and hooks don't hear it.
322
- val opening = reason == DocumentEnd.COMMITTED && !documentOpen
323
- documentOpen = reason == DocumentEnd.COMMITTED
324
- fileUpload.cancel()
325
- navigation.documentEnded()
326
- scripts.documentEnded(reason)
327
- fullscreen.documentEnded(reason)
328
- if (opening) return
329
- // The asks and hooks last, so a throw in hook or Chromium code can't skip the core's resets.
330
- asks.documentEnded(reason)
331
- hookContexts.forEach { it.documentEnded(reason) }
332
- }
267
+ internal val documents = Documents(
268
+ core = { reason ->
269
+ fileUpload.cancel()
270
+ navigation.documentEnded()
271
+ scripts.documentEnded(reason)
272
+ fullscreen.documentEnded(reason)
273
+ },
274
+ asksAndHooks = { reason ->
275
+ asks.documentEnded(reason)
276
+ hookContexts.forEach { it.documentEnded(reason) }
277
+ }
278
+ )
333
279
 
334
280
  internal fun loadStarted() {
335
281
  loading = true
@@ -337,7 +283,10 @@ internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoVi
337
283
  stateChanged()
338
284
  }
339
285
 
340
- /** A load ended (callers set outcome first): loading stops, and the spinner with it. */
286
+ internal fun settleOutcome(value: LoadOutcome) {
287
+ outcome = outcome ?: value
288
+ }
289
+
341
290
  internal fun loadEnded() {
342
291
  loading = false
343
292
  refresher.pageFinished()
@@ -347,10 +296,6 @@ internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoVi
347
296
  internal fun evaluate(script: String, onResult: (Result<String>) -> Unit) =
348
297
  if (recovering) onResult(Result.failure(EvaluateError("unavailable", RECOVERING))) else scripts.evaluate(script, onResult)
349
298
 
350
- /**
351
- * The renderer died. The WebView can't be reused: it goes now, after saving its history. The new one is built
352
- * at once if the view can be seen, else once it can (Android's guidance: not in the background).
353
- */
354
299
  internal fun processGone(cause: String, at: Long) {
355
300
  if (destroyed) return
356
301
  val reload = crashAllowsReload(crashTimes, at) && !showingPost
@@ -359,19 +304,17 @@ internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoVi
359
304
  val history = Bundle().takeIf { reload && webView.saveState(it) != null }
360
305
  tearDown(DocumentEnd.CRASHED)
361
306
  pendingRecovery = Recovery(reload, history, restorable)
362
- // Nothing will end the load the crash cut off. `url` stays: loadAgain() loads it.
363
- if (loading) outcome = "failed"
307
+ if (loading) outcome = LoadOutcome.FAILED
364
308
  loading = false
365
309
  pendingUrl = null
366
310
  progress = 0.0
367
311
  refresher.pageFinished()
368
312
  onProcessGone(mapOf("cause" to cause, "recovered" to reload))
369
- // A detached view's window reports GONE: onWindowVisibilityChanged recovers once it is shown.
313
+ // A detached view's window reports GONE.
370
314
  if (windowVisibility == View.VISIBLE) recover()
371
- stateChanged() // after onProcessGone: the cut-off load ends as failed
315
+ stateChanged()
372
316
  }
373
317
 
374
- /** The renderer died and the new WebView isn't built yet: the one in [webView] is destroyed. */
375
318
  internal val recovering get() = pendingRecovery != null
376
319
 
377
320
  // Also on attach: dispatchAttachedToWindow calls this unless the window is GONE.
@@ -380,23 +323,18 @@ internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoVi
380
323
  if (visibility == View.VISIBLE) recover()
381
324
  }
382
325
 
383
- /**
384
- * Builds the WebView that replaces the dead one and brings its history back, or else loads its page again. With
385
- * [reload] (the app's retry) it loads also when the crash-loop guard or a POST source held the reload back.
386
- */
387
- private fun recover(reload: Boolean = false) {
326
+ private fun recover(forceLoad: Boolean = false) {
388
327
  val recovery = pendingRecovery ?: return
389
328
  pendingRecovery = null
390
- webView = createWebView()
329
+ webView = createWebView(first = false)
391
330
  setUp()
392
- // The history first: a source the app set or a `load` it asked for while this waited loads on top of it, as on iOS.
393
331
  val replaced = pendingLoad != null || source != null && source != loadedSource
394
332
  val restored = (replaced || recovery.restorable) && recovery.history?.let { webView.restoreState(it) } != null
395
333
  if (replaced) {
396
334
  loadNewSource()
397
335
  pendingLoad?.let(webView::loadUrl)
398
336
  pendingLoad = null
399
- } else if (!restored && (recovery.reload || reload)) {
337
+ } else if (!restored && (recovery.reload || forceLoad)) {
400
338
  loadAgain()
401
339
  }
402
340
  stateChanged()
@@ -405,18 +343,16 @@ internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoVi
405
343
  internal fun destroy() {
406
344
  destroyed = true
407
345
  downloads.detach()
408
- // A crash tore the WebView down already, and detached the hooks; with none, there is nothing to tear down.
409
346
  if (!hasWebView || recovering) {
410
347
  pendingRecovery = null
411
- return endDocument(DocumentEnd.CLOSING)
348
+ return documents.end(DocumentEnd.CLOSING)
412
349
  }
413
350
  webView.stopLoading()
414
351
  tearDown(DocumentEnd.CLOSING)
415
352
  }
416
353
 
417
- /** Ends the Document with [reason] and destroys the WebView. The detached hooks' onDestroyed handlers run after it is destroyed. */
418
354
  private fun tearDown(reason: DocumentEnd) {
419
- endDocument(reason)
355
+ documents.end(reason)
420
356
  val detached = hookContexts
421
357
  detached.forEach { it.detach() }
422
358
  hookContexts = emptyList()
@@ -426,18 +362,15 @@ internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoVi
426
362
  }
427
363
 
428
364
  internal fun reportError(kind: String, url: String, code: Int, description: String) {
429
- // A network or SSL error fails the load in progress; one with no load JS saw start (an SSL error before 146) doesn't.
430
- if (loading) outcome = "failed"
365
+ if (loading) outcome = LoadOutcome.FAILED
431
366
  onError(mapOf("kind" to kind, "url" to url, "code" to code, "description" to description))
432
367
  }
433
368
 
434
369
  internal fun reportHttpError(url: String, statusCode: Int) =
435
370
  onError(mapOf("kind" to "http", "url" to url, "statusCode" to statusCode))
436
371
 
437
- // Changes within one frame are combined into one event, except `loading` flips: a load that starts and fails
438
- // within one frame must still reach JS as loading true -> false (onLoadStart / onLoadEnd).
439
372
  internal fun stateChanged() {
440
- if (loading != lastEmitted?.get("loading")) return emitState()
373
+ if (loadingFlipped) return emitState()
441
374
  if (emitScheduled) return
442
375
  emitScheduled = true
443
376
  mainHandler.postDelayed({
@@ -446,9 +379,10 @@ internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoVi
446
379
  }, FRAME_MS)
447
380
  }
448
381
 
382
+ private val loadingFlipped get() = loading != lastEmitted?.get("loading")
383
+
449
384
  private fun emitState() {
450
385
  if (destroyed) return
451
- // While a recovery waits, `webView` is the destroyed one: the history stays as JS saw it last.
452
386
  val (back, forward) = if (recovering) {
453
387
  (lastEmitted?.get("canGoBack") ?: false) to (lastEmitted?.get("canGoForward") ?: false)
454
388
  } else {
@@ -462,7 +396,7 @@ internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoVi
462
396
  "progress" to progress,
463
397
  "canGoBack" to back,
464
398
  "canGoForward" to forward,
465
- "outcome" to if (loading) null else outcome
399
+ "outcome" to if (loading) null else outcome?.jsName
466
400
  )
467
401
  if (state == lastEmitted) return
468
402
  lastEmitted = state
@@ -477,14 +411,15 @@ internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoVi
477
411
 
478
412
  internal const val TAG = "MinimalWebView"
479
413
 
414
+ internal enum class LoadOutcome(val jsName: String) { FINISHED("finished"), FAILED("failed"), CANCELLED("cancelled") }
415
+
480
416
  /**
481
- * The core's deferred work. Not View.post: a detached view (unmounted, or a covered screen) holds that until it is
482
- * attached again. Lazy: the JVM tests load this file, and Handler's constructor throws there.
417
+ * Not View.post: a detached view (unmounted, or a covered screen) holds that until it is attached again. Lazy: the JVM
418
+ * tests load this file, and Handler's constructor throws there.
483
419
  */
484
420
  internal val mainHandler by lazy { Handler(Looper.getMainLooper()) }
485
421
  internal const val RECOVERING = "the WebView is being rebuilt after its renderer died"
486
422
 
487
- /** Whether this process has made a WebView. */
488
423
  @Volatile internal var webViewCreated = false
489
424
 
490
425
  /** What `setWebContentsDebuggingEnabled` set; null until it is called. */
@@ -525,12 +460,23 @@ private fun canonicalUrl(url: String): String {
525
460
  return "$lower://$userinfo${host.lowercase()}$portPart${if (rest.startsWith('/')) rest else "/$rest"}"
526
461
  }
527
462
 
528
- // scheme "://" [userinfo "@"] host [":" port] rest
529
463
  private val urlAuthority = Regex("^([a-zA-Z][a-zA-Z0-9+.-]*)://([^/?#@]*@)?(\\[[^\\]/?#]*]|[^/?#:]*)(?::(\\d*))?(.*)$")
530
464
 
531
- /** The special schemes' default ports (the WHATWG URL Standard's), as on iOS (Loads.swift). */
465
+ /** The special schemes' default ports (the WHATWG URL Standard's). */
532
466
  internal val defaultPorts = mapOf("http" to 80, "https" to 443, "ws" to 80, "wss" to 443, "ftp" to 21)
533
467
 
468
+ /** The first commit after mount or a crash opens a Document and ends none: only [core] hears it. */
469
+ internal class Documents(private val core: (DocumentEnd) -> Unit, private val asksAndHooks: (DocumentEnd) -> Unit) {
470
+ private var open = false
471
+
472
+ fun end(reason: DocumentEnd) {
473
+ val opening = reason == DocumentEnd.COMMITTED && !open
474
+ open = reason == DocumentEnd.COMMITTED
475
+ core(reason)
476
+ if (!opening) asksAndHooks(reason)
477
+ }
478
+ }
479
+
534
480
  /**
535
481
  * Records a renderer death at [now] in [times] and says whether to reload after it: not after more than
536
482
  * [MAX_CRASHES_PER_WINDOW] in [CRASH_WINDOW_MS]. Every WebView on the renderer hears of its death, so one within
@@ -542,7 +488,6 @@ internal fun crashAllowsReload(times: ArrayDeque<Long>, now: Long): Boolean {
542
488
  return times.size <= MAX_CRASHES_PER_WINDOW
543
489
  }
544
490
 
545
- // shortcut: a fixed crash-loop guard, make it a prop if an app needs a different policy
546
491
  private const val MAX_CRASHES_PER_WINDOW = 3
547
492
  private const val CRASH_WINDOW_MS = 60_000L
548
493
  private const val SAME_CRASH_MS = 100L