react-native-minimal-webview 1.2.1 → 1.3.1

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 +67 -120
  5. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewClients.kt +23 -32
  6. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewModule.kt +8 -18
  7. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewNavigation.kt +30 -49
  8. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewScripts.kt +48 -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 +30 -40
  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 +30 -80
  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 +33 -16
  62. package/build/types.d.ts.map +1 -1
  63. package/ios/Asks.swift +6 -9
  64. package/ios/DelegateProxy.swift +6 -20
  65. package/ios/DownloadName.swift +0 -2
  66. package/ios/Downloads.swift +0 -2
  67. package/ios/Hooks.swift +6 -7
  68. package/ios/Loads.swift +37 -19
  69. package/ios/MinimalWebView+Dialogs.swift +2 -6
  70. package/ios/MinimalWebView+Navigation.swift +25 -57
  71. package/ios/MinimalWebView+Scripts.swift +4 -16
  72. package/ios/MinimalWebView.podspec +1 -2
  73. package/ios/MinimalWebView.swift +58 -144
  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 +19 -38
  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 +45 -95
  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 +33 -16
@@ -1,6 +1,5 @@
1
1
  package expo.modules.minimalwebview
2
2
 
3
- /** The structured navigation rules. Semantics and cases: src/__tests__/vectors/navigation-rules.json (shared with Swift). */
4
3
  internal object NavigationRules {
5
4
  data class Request(
6
5
  val url: String,
@@ -10,19 +9,20 @@ internal object NavigationRules {
10
9
  val isRedirect: Boolean = false
11
10
  )
12
11
 
13
- /** [action] is allow, block, external or ask; [rule] is the matching rule's index, null when a default decided. */
14
- data class Decision(val action: String, val rule: Int?)
12
+ enum class Action(val jsName: String) { ALLOW("allow"), BLOCK("block"), EXTERNAL("external"), ASK("ask") }
15
13
 
16
- /** Load in place without the rules. */
17
- private val internalSchemes = setOf("about", "data", "javascript")
14
+ /** [rule] is the index of the rule that decided, null when a default did. */
15
+ data class Decision(val action: Action, val rule: Int?)
16
+
17
+ private val schemesAllowedWithoutRules = setOf("about", "data", "javascript")
18
18
 
19
19
  /**
20
20
  * Never open as a new window, whatever the rules say: the core loads an allowed new window in the main frame itself,
21
21
  * past the engine's limits on what a page may navigate the top frame to.
22
22
  */
23
- private val noNewWindowSchemes = internalSchemes + setOf("blob", "file")
24
- private val actions = setOf("allow", "block", "external", "ask")
25
- private val answers = setOf("allow", "block", "external")
23
+ private val noNewWindowSchemes = schemesAllowedWithoutRules + setOf("blob", "file")
24
+
25
+ private fun actionOf(value: Any?) = Action.entries.find { it.jsName == value }
26
26
 
27
27
  /**
28
28
  * The rules' decision, gated for `ask`: blocked when nothing can answer it ([canAsk] false), allowed when its URL is
@@ -31,30 +31,29 @@ internal object NavigationRules {
31
31
  fun decide(rules: List<Map<String, Any?>>?, request: Request, asked: Set<String>, canAsk: Boolean): Decision {
32
32
  val decision = match(rules, request)
33
33
  return when {
34
- decision.action != "ask" -> decision
35
- !canAsk -> Decision("block", decision.rule)
36
- request.url in asked -> Decision("allow", decision.rule)
34
+ decision.action != Action.ASK -> decision
35
+ !canAsk -> Decision(Action.BLOCK, decision.rule)
36
+ request.url in asked -> Decision(Action.ALLOW, decision.rule)
37
37
  else -> decision
38
38
  }
39
39
  }
40
40
 
41
41
  /** An `ask` answer: allow, block or external; anything else (null on a timeout) blocks. */
42
- fun answer(value: Any?): String = (value as? String)?.takeIf { it in answers } ?: "block"
42
+ fun answer(value: Any?): Action = actionOf(value)?.takeIf { it != Action.ASK } ?: Action.BLOCK
43
43
 
44
44
  private fun match(rules: List<Map<String, Any?>>?, request: Request): Decision {
45
45
  val scheme = request.url.substringBefore(':', "").lowercase()
46
- if (request.newWindow && scheme in noNewWindowSchemes) return Decision("block", null)
47
- if (scheme in internalSchemes) return Decision("allow", null)
48
- // JS sends defaultNavigationRules when the prop is unset; no rules, null or empty, match nothing.
49
- if (rules.isNullOrEmpty()) return Decision("block", null)
46
+ if (request.newWindow && scheme in noNewWindowSchemes) return Decision(Action.BLOCK, null)
47
+ if (scheme in schemesAllowedWithoutRules) return Decision(Action.ALLOW, null)
48
+ if (rules.isNullOrEmpty()) return Decision(Action.BLOCK, null)
50
49
  val parts = (if (scheme == "blob") blobOrigin(request.url) else parts(scheme, request.url))
51
- ?: return Decision("block", null)
50
+ ?: return Decision(Action.BLOCK, null)
52
51
  val index = rules.indexOfFirst { matches(it, parts, request) }
53
- return if (index < 0) Decision("block", null) else Decision((rules[index]["action"] as? String)?.takeIf { it in actions } ?: "block", index)
52
+ return if (index < 0) Decision(Action.BLOCK, null) else Decision(actionOf(rules[index]["action"]) ?: Action.BLOCK, index)
54
53
  }
55
54
 
56
- // scheme ":" ["//" authority] path ["?" query]. java.net.URI rejects URLs Chromium accepts (a raw `|` in the query,
57
- // `_` in a host), so the parts are split with a regex.
55
+ // java.net.URI rejects URLs Chromium accepts (a raw `|` in the query, `_` in a host), so the parts are split with a
56
+ // regex.
58
57
  private val urlParts = Regex("^([a-zA-Z][a-zA-Z0-9+.-]*):(?://([^/?#]*))?([^?#]*)(?:\\?([^#]*))?")
59
58
 
60
59
  private data class Parts(val scheme: String, val host: String?, val path: String, val params: List<String>)
@@ -14,85 +14,79 @@ import java.lang.reflect.Method
14
14
  import java.lang.reflect.Modifier
15
15
  import kotlin.math.truncate
16
16
 
17
- /**
18
- * The `android` settings prop, `get` and `call`, by name through reflection over public SDK methods only
19
- * (`getMethods()`), so a setter a newer SDK or androidx.webkit adds needs no code here. The roots and their order:
20
- * [Companion.targets].
21
- */
22
17
  internal class PlatformSettings(
23
18
  private val hasNavigationListener: () -> Boolean = { true },
24
19
  private val targets: (root: String) -> List<Target>?
25
20
  ) {
26
- /** `root.key` -> the last value applied or rejected, so an unchanged value is neither applied nor reported again. */
27
- private val applied = mutableMapOf<String, Any?>()
21
+ private val applied = mutableMapOf<SettingId, Any?>()
28
22
 
29
- /** `root.key` -> its getter's value before the first write ([NONE]: no getter), set back when the key is removed. */
30
- private val originals = mutableMapOf<String, Any?>()
23
+ private val originals = mutableMapOf<SettingId, Any?>()
31
24
 
32
- /** A receiver (null for statics) and, for compat and CookieManager methods, the root object passed first. */
33
- internal class Target(val cls: Class<*>, val receiver: Any?, val leading: Any?)
25
+ private data class SettingId(val root: String, val key: String) {
26
+ override fun toString() = "$root.$key"
27
+ }
28
+
29
+ data class Rejected(val key: String, val reason: String)
30
+
31
+ internal class Target(val cls: Class<*>, val receiver: Any?, val firstArgument: Any?)
34
32
 
35
33
  /**
36
34
  * Applies [settings], and sets a key applied before and missing now back to its value before the first write;
37
35
  * returns the rejected keys with their reasons. [force] re-applies everything (a new WebView).
38
36
  */
39
- fun apply(settings: Map<String, Any?>?, force: Boolean = false): List<Map<String, String>> {
37
+ fun apply(settings: Map<String, Any?>?, force: Boolean = false): List<Rejected> {
40
38
  if (force) {
41
39
  applied.clear()
42
40
  originals.clear()
43
41
  }
44
- // Before the new values, so restoring one can't undo another that depends on it.
45
42
  val rejected = restore(removedFrom = settings.orEmpty()).toMutableList()
46
43
  for ((rootName, entries) in settings.orEmpty()) {
47
44
  val targets = settingsTargets(rootName)
48
45
  if (targets == null || entries !is Map<*, *>) {
49
- rejected += mapOf("key" to rootName, "reason" to "unknown root: use settings or webView")
46
+ rejected += Rejected(rootName, "unknown root: use settings or webView")
50
47
  continue
51
48
  }
52
49
  for ((k, value) in entries) {
53
50
  val key = k as? String ?: continue
54
- val id = "$rootName.$key"
51
+ val id = SettingId(rootName, key)
55
52
  if (applied.containsKey(id) && applied[id] == value) continue
56
53
  applied[id] = value
57
- val problem = write(targets, id, key, value) ?: continue
58
- rejected += mapOf("key" to id, "reason" to problem)
54
+ val problem = write(targets, id, value) ?: continue
55
+ rejected += Rejected(id.toString(), problem)
59
56
  }
60
57
  }
61
58
  return rejected
62
59
  }
63
60
 
64
- /** The targets of a root the prop has, `settings` or `webView`; null for another. */
65
61
  private fun settingsTargets(rootName: String) =
66
62
  // Not targets() first: the other roots are the WebView profile's, which `webView.profile` may not have set yet.
67
63
  if (rootName in listOf("settings", "webView")) targets(rootName) else null
68
64
 
69
65
  /** [set], keeping the value it replaces the first time under [id]; returns the problem, or null when it was set. */
70
- private fun write(targets: List<Target>, id: String, key: String, value: Any?): String? {
71
- refusal(setterOf(key), listOf(value))?.let { return it }
72
- if (id in originals) return set(targets, key, value)
73
- return set(targets, key, value) {
74
- originals[id] = runCatching { read(targets, key) }.getOrDefault(NONE)
66
+ private fun write(targets: List<Target>, id: SettingId, value: Any?): String? {
67
+ refusal(setterOf(id.key), listOf(value))?.let { return it }
68
+ if (id in originals) return set(targets, id.key, value)
69
+ return set(targets, id.key, value) {
70
+ originals[id] = runCatching { read(targets, id.key) }.getOrDefault(NONE)
75
71
  }?.also { originals.remove(id) }
76
72
  }
77
73
 
78
74
  /** Forgets each applied key [removedFrom] no longer has and sets its original value back; returns what failed. */
79
- private fun restore(removedFrom: Map<String, Any?>): List<Map<String, String>> {
75
+ private fun restore(removedFrom: Map<String, Any?>): List<Rejected> {
80
76
  val present = removedFrom.flatMap { (rootName, entries) ->
81
- (entries as? Map<*, *>)?.keys.orEmpty().map { "$rootName.$it" }
77
+ (entries as? Map<*, *>)?.keys.orEmpty().map { SettingId(rootName, it.toString()) }
82
78
  }.toSet()
83
79
  return (applied.keys - present).mapNotNull { id ->
84
80
  applied.remove(id)
85
81
  if (id !in originals) return@mapNotNull null
86
82
  val original = originals.remove(id)
87
- val (rootName, key) = id.split('.', limit = 2)
88
- // shortcut: a setter with no getter (geolocationEnabled, initialScale, backgroundColor) can't be restored; add
89
- // the platform's defaults for those if one matters.
83
+ val (rootName, key) = id
90
84
  val problem = if (original === NONE) {
91
85
  "removed, but it has no getter to restore it from: it keeps its value until the WebView is recreated"
92
86
  } else {
93
87
  set(targets(rootName).orEmpty(), key, original)?.let { "removed, but restoring it failed: $it" }
94
88
  }
95
- problem?.let { mapOf("key" to id, "reason" to it) }
89
+ problem?.let { Rejected(id.toString(), it) }
96
90
  }
97
91
  }
98
92
 
@@ -119,7 +113,6 @@ internal class PlatformSettings(
119
113
  val result = direct()
120
114
  return reply { toJson(result) }
121
115
  }
122
- // The callback runs later, outside the caller's try: the receiver converts, so it can reject instead of crashing.
123
116
  val callback = ValueCallback<Any?> { value -> reply { toJson(value) } }
124
117
  val awaiting = find(targets, args + callback) {
125
118
  it.name == name && it.parameterTypes.lastOrNull() == ValueCallback::class.java
@@ -136,7 +129,6 @@ internal class PlatformSettings(
136
129
 
137
130
  /** Why [method] can't take [args] on this WebView, or null. */
138
131
  private fun refusal(method: String, args: List<Any?>) =
139
- // Without NavigationListener the clients end a load at onPageFinished, which WebView 133 skips for a restored page.
140
132
  if (method == "setBackForwardCacheEnabled" && args == listOf(true) && !hasNavigationListener()) {
141
133
  "not supported by this WebView: below Android System WebView 146 a page restored from the cache reports no load end"
142
134
  } else {
@@ -165,10 +157,6 @@ internal class PlatformSettings(
165
157
  else -> null
166
158
  }
167
159
 
168
- /**
169
- * Methods the core owns: its clients, listeners, scripts, loads and navigations, the WebView's lifetime and timers,
170
- * and the process-wide debugging switch; the page's JS goes through `evaluate` and the bridge.
171
- */
172
160
  val OWNED = setOf(
173
161
  "setWebViewClient", "setWebChromeClient", "setDownloadListener", "addJavascriptInterface",
174
162
  "removeJavascriptInterface", "addWebMessageListener", "removeWebMessageListener", "addDocumentStartJavaScript",
@@ -212,7 +200,9 @@ internal class PlatformSettings(
212
200
  before()
213
201
  apply()
214
202
  null
215
- } catch (e: IllegalArgumentException) { // a PlatformException from invoke is one, so its reason is the message
203
+ } catch (e: PlatformException) {
204
+ e.message
205
+ } catch (e: IllegalArgumentException) {
216
206
  e.message
217
207
  }
218
208
  }
@@ -226,13 +216,13 @@ internal class PlatformSettings(
226
216
  return getter()
227
217
  }
228
218
 
229
- /** The method's arguments for [values], with the target's leading object first, or null when they don't fit. */
219
+ /** The method's arguments for [values], after the target's [Target.firstArgument], or null when they don't fit. */
230
220
  private fun arguments(method: Method, target: Target, values: List<Any?>): Array<Any?>? {
231
221
  if (target.receiver == null && !Modifier.isStatic(method.modifiers)) return null
232
222
  val types = method.parameterTypes
233
- val leading = if (target.leading != null) listOf(target.leading) else emptyList()
223
+ val leading = if (target.firstArgument != null) listOf(target.firstArgument) else emptyList()
234
224
  if (types.size != leading.size + values.size) return null
235
- if (leading.isNotEmpty() && !types[0].isInstance(target.leading)) return null
225
+ if (leading.isNotEmpty() && !types[0].isInstance(target.firstArgument)) return null
236
226
  val args = arrayOfNulls<Any?>(types.size)
237
227
  leading.forEachIndexed { i, value -> args[i] = value }
238
228
  values.forEachIndexed { i, value ->
@@ -304,4 +294,4 @@ internal class PlatformSettings(
304
294
  }
305
295
 
306
296
  /** Why [PlatformSettings.get] or [PlatformSettings.call] failed; [code] is the JS error code (`not_found`, `native_error` or `unavailable`). */
307
- internal class PlatformException(val code: String, message: String) : IllegalArgumentException(message)
297
+ internal class PlatformException(val code: String, message: String) : RuntimeException(message)
@@ -7,56 +7,50 @@ import android.widget.FrameLayout
7
7
  import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
8
8
 
9
9
  /**
10
- * The `pullToRefresh` prop. WebView sends no nested-scroll events, so it asks the WebView whether the document can
11
- * scroll up, and on touch-down asks the page whether the element under the finger is inside an inner scroller
12
- * (overflow: auto or scroll) that is already scrolled.
10
+ * WebView sends no nested-scroll events, so it asks the WebView whether the document can scroll up, and on touch-down
11
+ * asks the page whether the element under the finger is inside an inner scroller (overflow: auto or scroll) that is
12
+ * already scrolled.
13
13
  */
14
14
  internal class PullToRefresh(private val owner: MinimalWebView) {
15
- // The page's answer for the current touch; null while it is pending, which holds the pull off. The down event itself
16
- // must see false: SwipeRefreshLayout only tracks a gesture whose down event it accepted.
17
- private var innerScrolled: Boolean? = false
15
+ // The down event itself must see UNSCROLLED: SwipeRefreshLayout only tracks a gesture whose down event it accepted.
16
+ private var innerScroller = InnerScroller.UNSCROLLED
18
17
  private var touches = 0
19
18
 
20
- /** Holds the WebView. SwipeRefreshLayout keeps its first child as its target for good, so a crash swaps the WebView here. */
19
+ /** SwipeRefreshLayout keeps its first child as its target for good, so a crash swaps the WebView here. */
21
20
  val content = FrameLayout(owner.context)
22
21
 
23
- /** Always around [content]; off until the prop sets `isEnabled`. */
24
22
  val layout: SwipeRefreshLayout = Layout(owner.context).apply {
25
23
  isEnabled = false
26
24
  addView(content, ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
27
25
  setOnRefreshListener { owner.reload() }
28
- setOnChildScrollUpCallback { _, _ -> owner.webView.canScrollVertically(-1) || innerScrolled != false }
26
+ setOnChildScrollUpCallback { _, _ -> owner.webView.canScrollVertically(-1) || innerScroller != InnerScroller.UNSCROLLED }
29
27
  }
30
28
 
31
29
  private fun checkInnerScroller(x: Float, y: Float) {
32
30
  val touch = ++touches
33
31
  val density = owner.webView.resources.displayMetrics.density
34
32
  owner.webView.evaluateJavascript("($INNER_SCROLLED)(${x / density}, ${y / density})") { result ->
35
- if (touch == touches) innerScrolled = result == "true"
33
+ if (touch == touches) innerScroller = if (result == "true") InnerScroller.SCROLLED else InnerScroller.UNSCROLLED
36
34
  }
37
- // A busy page answers late: don't hold the pull off for longer than this.
38
- mainHandler.postDelayed({ if (touch == touches && innerScrolled == null) innerScrolled = false }, ANSWER_TIMEOUT_MS)
35
+ mainHandler.postDelayed({ if (touch == touches && innerScroller == InnerScroller.ASKING) innerScroller = InnerScroller.UNSCROLLED }, ANSWER_TIMEOUT_MS)
39
36
  }
40
37
 
41
38
  /** A load ended: the spinner stops, or it would ignore the next pull. */
42
39
  fun pageFinished() {
43
40
  layout.isRefreshing = false
44
- innerScrolled = false
41
+ innerScroller = InnerScroller.UNSCROLLED
45
42
  }
46
43
 
47
44
  private inner class Layout(context: Context) : SwipeRefreshLayout(context) {
48
45
  override fun onInterceptTouchEvent(event: MotionEvent): Boolean {
49
- // Off: no pull, and no question to the page on every touch.
50
46
  if (!isEnabled) return false
51
47
  if (event.actionMasked != MotionEvent.ACTION_DOWN) return super.onInterceptTouchEvent(event)
52
- innerScrolled = false
48
+ innerScroller = InnerScroller.UNSCROLLED
53
49
  val intercepted = super.onInterceptTouchEvent(event)
54
50
  if (owner.webView.canScrollVertically(-1)) {
55
- // A scrolled document already ruled this gesture out, whatever the page says: don't ask it. Dropping the
56
- // count makes a late answer or timeout from an earlier touch a no-op.
57
51
  touches++
58
52
  } else {
59
- innerScrolled = null
53
+ innerScroller = InnerScroller.ASKING
60
54
  checkInnerScroller(event.x, event.y)
61
55
  }
62
56
  return intercepted
@@ -64,6 +58,8 @@ internal class PullToRefresh(private val owner: MinimalWebView) {
64
58
  }
65
59
  }
66
60
 
61
+ private enum class InnerScroller { UNSCROLLED, SCROLLED, ASKING }
62
+
67
63
  private const val ANSWER_TIMEOUT_MS = 150L
68
64
 
69
65
  /** True when the element at (x, y) has a scrolled ancestor that can scroll vertically (CSS pixels). */
@@ -22,13 +22,10 @@ import java.util.concurrent.ArrayBlockingQueue
22
22
  import java.util.concurrent.Executors
23
23
  import java.util.concurrent.TimeUnit
24
24
 
25
- /** The server answered [code], not 2xx. */
26
25
  internal class HttpStatus(val code: Int) : IOException("HTTP $code")
27
26
 
28
- /** The file is above [Downloads.MAX_BYTES]. */
29
27
  internal class TooLarge : IOException(Downloads.TOO_LARGE)
30
28
 
31
- /** What WebView's DownloadListener reports. */
32
29
  internal data class DownloadInfo(
33
30
  val url: String,
34
31
  val userAgent: String,
@@ -37,9 +34,8 @@ internal data class DownloadInfo(
37
34
  )
38
35
 
39
36
  /**
40
- * The `onDownload` prop. WebView hands over only the URL, so http(s) is fetched again, through `HttpURLConnection` and
41
- * the WebView profile's `CookieManager` rather than React Native's OkHttp, so the package builds without
42
- * `react-android`. Nothing here may crash the app: the page controls the URL.
37
+ * WebView hands over only the URL, so http(s) is fetched again, through `HttpURLConnection` and the WebView profile's
38
+ * `CookieManager` rather than React Native's OkHttp, so the package builds without `react-android`.
43
39
  */
44
40
  internal class Downloads(private val owner: MinimalWebView) {
45
41
  private val io = Executors.newSingleThreadExecutor()
@@ -66,11 +62,7 @@ internal class Downloads(private val owner: MinimalWebView) {
66
62
  return data.second
67
63
  }
68
64
 
69
- /**
70
- * Runs [write] off the main thread (a download can be megabytes); it fills the file and returns its MIME type. One
71
- * directory per download, so the same guessed name never overwrites a file already handed to the app. The event goes
72
- * back on the main thread. [url] is the download's own URL, for the event.
73
- */
65
+ /** Runs [write] off the main thread; it fills the file and returns its MIME type. */
74
66
  private fun save(name: String, url: String, write: (File) -> String) {
75
67
  val file = File(owner.webView.context.cacheDir, "downloads/${System.nanoTime()}/$name")
76
68
  io.execute {
@@ -78,10 +70,9 @@ internal class Downloads(private val owner: MinimalWebView) {
78
70
  file.parentFile?.mkdirs()
79
71
  write(file)
80
72
  } catch (e: Exception) {
81
- // a malformed data: URL or forged JSON from the page: no failure may reach the io thread
82
73
  e
83
74
  }
84
- if (result is Exception) file.parentFile?.deleteRecursively() // no partial file stays in the cache
75
+ if (result is Exception) file.parentFile?.deleteRecursively()
85
76
  mainHandler.post {
86
77
  when (result) {
87
78
  is String -> owner.emit(
@@ -106,7 +97,7 @@ internal class Downloads(private val owner: MinimalWebView) {
106
97
  val (size, data) = readChunk(url, offset)
107
98
  type = append(file, decodeChunk(data))
108
99
  offset += CHUNK_BYTES
109
- if (offset > MAX_BYTES) throw TooLarge() // the page's own size check can be forged
100
+ if (offset > MAX_BYTES) throw TooLarge()
110
101
  } while (offset < size)
111
102
  type
112
103
  }
@@ -124,8 +115,7 @@ internal class Downloads(private val owner: MinimalWebView) {
124
115
  mainHandler.post { owner.evaluate(script) { reply.offer(it) } }
125
116
  val result = reply.poll(TIMEOUT_MS.toLong(), TimeUnit.MILLISECONDS) ?: throw IOException("the page did not read the blob in time")
126
117
  val json = result.getOrElse { throw IOException("could not read the blob: ${it.message}") }
127
- // A reply far longer than a chunk's data: URL is forged: refuse it before it is copied twice more.
128
- if (json.length > CHUNK_BYTES / 3 * 4 + 1024) throw TooLarge()
118
+ if (json.length > MAX_CHUNK_REPLY_CHARS) throw TooLarge()
129
119
  val chunk = JSONTokener(json).nextValue() as? JSONArray ?: throw IOException("could not read the blob")
130
120
  return chunk.getLong(0) to chunk.getString(1)
131
121
  }
@@ -148,11 +138,12 @@ internal class Downloads(private val owner: MinimalWebView) {
148
138
  }
149
139
 
150
140
  internal companion object {
151
- // The page picks the file, and an http(s) one fills the cache: above this a download fails instead.
152
- const val MAX_BYTES = 100L * 1024 * 1024
153
- const val TOO_LARGE = "larger than 100 MB"
141
+ private const val MAX_MIB = 100L
142
+ const val MAX_BYTES = MAX_MIB * 1024 * 1024
143
+ const val TOO_LARGE = "larger than $MAX_MIB MiB"
154
144
  const val CHUNK_BYTES = 4L * 1024 * 1024
155
- const val MAX_REDIRECTS = 20 // OkHttp's, which React Native's fetch uses
145
+ private const val MAX_CHUNK_REPLY_CHARS = CHUNK_BYTES / 3 * 4 + 1024
146
+ const val MAX_REDIRECTS = 20 // OkHttp's limit, which React Native's fetch uses
156
147
  const val TIMEOUT_MS = 30_000
157
148
  private val PERCENT_ESCAPE = Regex("%[0-9A-Fa-f]{2}")
158
149
 
@@ -161,7 +152,6 @@ internal class Downloads(private val owner: MinimalWebView) {
161
152
  * except [TooLarge]; `data` for everything else.
162
153
  */
163
154
  fun kind(error: Exception, fetched: Boolean) =
164
- // shortcut: a disk error while an http(s) body streams reads as network; tell them apart if apps need to.
165
155
  if (fetched && error is IOException && error !is TooLarge) "network" else "data"
166
156
 
167
157
  /**
@@ -189,8 +179,7 @@ internal class Downloads(private val owner: MinimalWebView) {
189
179
 
190
180
  /** [text]'s UTF-8 bytes with each `%XX` replaced by the byte XX. The result is not decoded as UTF-8 again. */
191
181
  private fun percentDecode(text: String): ByteArray {
192
- if ('%' !in text) return text.toByteArray() // a blob's chunks: spares two copies of megabytes
193
- // Latin-1 maps each byte to one char and back, so the escapes are replaced in a string.
182
+ if ('%' !in text) return text.toByteArray()
194
183
  val latin1 = String(text.toByteArray(), Charsets.ISO_8859_1)
195
184
  return PERCENT_ESCAPE.replace(latin1) { it.value.substring(1).toInt(16).toChar().toString() }.toByteArray(Charsets.ISO_8859_1)
196
185
  }
@@ -6,7 +6,6 @@ import android.webkit.WebChromeClient.FileChooserParams
6
6
  import expo.modules.minimalwebview.MinimalWebView
7
7
  import expo.modules.minimalwebview.MinimalWebViewModule
8
8
 
9
- /** `<input type="file">`, and the `onFileRequest` prop. */
10
9
  internal class FileUpload(private val owner: MinimalWebView) {
11
10
  // The page's open file chooser (WebView allows one at a time). Chromium releases it only while its document is alive,
12
11
  // so a navigation away cancels it when it starts, not at commit; a later answer is dropped.
@@ -14,12 +14,10 @@ import androidx.core.view.WindowInsetsControllerCompat
14
14
  import expo.modules.minimalwebview.DocumentEnd
15
15
  import expo.modules.minimalwebview.MinimalWebView
16
16
 
17
- /** HTML5 fullscreen video, and the `onFullscreenChange` prop. */
18
17
  internal class FullscreenVideo(private val owner: MinimalWebView) {
19
18
  private var shownCallback: CustomViewCallback? = null
20
19
  private var backdrop: FrameLayout? = null
21
20
  private var backCallback: OnBackPressedCallback? = null
22
- // The app's bars before fullscreen, restored on exit: an immersive app keeps its bars hidden.
23
21
  private var barsShownBefore = 0
24
22
  private var barsBehaviorBefore: Int? = null
25
23
 
@@ -58,7 +56,6 @@ internal class FullscreenVideo(private val owner: MinimalWebView) {
58
56
  callback.onCustomViewHidden()
59
57
  }
60
58
 
61
- /** Removes the fullscreen view, which WebView hid or we are leaving. */
62
59
  fun onHideCustomView() {
63
60
  if (shownCallback == null) return
64
61
  shownCallback = null
@@ -80,7 +77,7 @@ internal class FullscreenVideo(private val owner: MinimalWebView) {
80
77
 
81
78
  private fun controller() = owner.appContext.currentActivity?.window?.let { WindowCompat.getInsetsController(it, it.decorView) }
82
79
 
83
- /** The Document ended: removes its fullscreen view. Only CLOSING (unmount) also tells WebView via `onCustomViewHidden`; after a crash no renderer is left to tell. */
80
+ /** Only CLOSING (unmount) also tells WebView via `onCustomViewHidden`; after a crash no renderer is left to tell. */
84
81
  fun documentEnded(reason: DocumentEnd) {
85
82
  if (reason == DocumentEnd.CLOSING) exit() else onHideCustomView()
86
83
  }
@@ -6,51 +6,61 @@ import android.webkit.PermissionRequest
6
6
  import expo.modules.minimalwebview.MinimalWebView
7
7
  import expo.modules.minimalwebview.defaultPorts
8
8
 
9
- /** The `onPermissionRequest` prop. */
10
9
  internal class Permissions(private val owner: MinimalWebView) {
11
- // Asks still waiting for JS's answer, keyed by their PermissionRequest or GeolocationPermissions.Callback so a platform cancel finds them.
12
- private val waiting = mutableMapOf<Any, Int>()
10
+ private val requests = Waiting<PermissionRequest>()
11
+ private val prompts = Waiting<GeolocationPermissions.Callback>()
13
12
 
14
13
  /** Returns true when the app's prop takes the request; it is then granted or denied once. */
15
14
  fun onPermissionRequest(request: PermissionRequest): Boolean {
16
15
  val known = request.resources.filter { it in RESOURCES }
17
- return decide(request, request.origin.toString(), known.map { RESOURCES.getValue(it) }, deny = request::deny) {
16
+ return requests.decide(request, request.origin.toString(), known.map { RESOURCES.getValue(it) }, deny = request::deny) {
18
17
  request.grant(known.toTypedArray())
19
18
  }
20
19
  }
21
20
 
22
21
  fun onGeolocationPrompt(origin: String, callback: GeolocationPermissions.Callback) =
23
- decide(callback, origin, listOf("geolocation"), deny = { callback.invoke(origin, false, false) }) {
22
+ prompts.decide(callback, origin, listOf("geolocation"), deny = { callback.invoke(origin, false, false) }) {
24
23
  callback.invoke(origin, true, false)
25
24
  }
26
25
 
27
26
  // Chromium gave up on the request: cancel its ask, removed first so that nothing answers the request. Answering one
28
27
  // Chromium already destroyed aborts the app on WebView 133 (an invalid JNI weak reference).
29
- fun onPermissionRequestCanceled(request: PermissionRequest) {
30
- waiting.remove(request)?.let { owner.asks.cancel(it) }
31
- }
28
+ fun onPermissionRequestCanceled(request: PermissionRequest) = requests.cancel(request)
32
29
 
33
30
  // Not told which prompt: every geolocation ask goes, unanswered like a cancelled request.
34
- fun onGeolocationPromptHidden() =
35
- waiting.keys.filterIsInstance<GeolocationPermissions.Callback>().forEach { key -> waiting.remove(key)?.let { owner.asks.cancel(it) } }
31
+ fun onGeolocationPromptHidden() = prompts.cancelAll()
32
+
33
+ private inner class Waiting<K> {
34
+ private val ids = mutableMapOf<K, Int>()
36
35
 
37
- /**
38
- * Asks the app, then runs [grant] or [deny]. Returns false (the caller denies) without the prop. Android reports the
39
- * requesting frame's origin but not the frame, so an origin other than the top-level page's is denied.
40
- */
41
- private fun decide(key: Any, origin: String, resources: List<String>, deny: () -> Unit, grant: () -> Unit): Boolean {
42
- if ("onPermissionRequest" !in owner.requestHandlers) return false
43
- val value = originOf(origin)
44
- if (resources.isEmpty() || value != originOf(owner.url)) {
45
- deny()
36
+ /**
37
+ * Asks the app, then runs [grant] or [deny]. Returns false (the caller denies) without the prop. Android reports the
38
+ * requesting frame's origin but not the frame, so an origin other than the top-level page's is denied.
39
+ */
40
+ fun decide(key: K, origin: String, resources: List<String>, deny: () -> Unit, grant: () -> Unit): Boolean {
41
+ if ("onPermissionRequest" !in owner.requestHandlers) return false
42
+ val value = originOf(origin)
43
+ if (resources.isEmpty() || value != originOf(owner.url)) {
44
+ deny()
45
+ return true
46
+ }
47
+ val id = owner.asks.ask("core", "onPermissionRequest", mapOf("origin" to value, "resources" to resources)) { answer ->
48
+ if (ids.remove(key) == null) return@ask
49
+ if (answer == true) grant() else deny()
50
+ }
51
+ if (id != null) ids[key] = id
46
52
  return true
47
53
  }
48
- waiting[key] = owner.asks.ask("core", "onPermissionRequest", mapOf("origin" to value, "resources" to resources)) { answer ->
49
- // Not there: Chromium cancelled the request, and it takes no answer.
50
- if (waiting.remove(key) == null) return@ask
51
- if (answer == true) grant() else deny()
54
+
55
+ fun cancel(key: K) {
56
+ ids.remove(key)?.let { owner.asks.cancel(it) }
57
+ }
58
+
59
+ fun cancelAll() {
60
+ val cancelled = ids.values.toList()
61
+ ids.clear()
62
+ cancelled.forEach { owner.asks.cancel(it) }
52
63
  }
53
- return true
54
64
  }
55
65
 
56
66
  internal companion object {
@@ -9,6 +9,14 @@ export type AskableEvent = {
9
9
  payload: Record<string, unknown>;
10
10
  askId?: number;
11
11
  };
12
+ export type CoreEventPayloads = {
13
+ warning: {
14
+ message: string;
15
+ };
16
+ askCancelled: {
17
+ askId: number;
18
+ };
19
+ };
12
20
  export type NativeMethods = {
13
21
  goBack(): Promise<void>;
14
22
  goForward(): Promise<void>;
@@ -16,7 +24,6 @@ export type NativeMethods = {
16
24
  reload(): Promise<void>;
17
25
  stopLoading(): Promise<void>;
18
26
  bridgePost(message: string): Promise<void>;
19
- /** Answers a native `ask`. `json` is JSON, as for `call`. */
20
27
  answer(askId: number, json: string): Promise<void>;
21
28
  /** The JSON-encoded result. */
22
29
  evaluate(script: string): Promise<string>;
@@ -1 +1 @@
1
- {"version":3,"file":"WebView.d.ts","sourceRoot":"","sources":["../src/WebView.tsx"],"names":[],"mappings":"AAUA,OAAO,KAAK,EAQV,YAAY,EAEb,MAAM,SAAS,CAAC;AASjB;;;GAGG;AACH,MAAM,MAAM,YAAY,GAAG;IACzB,GAAG,EAAE,MAAM,CAAC;IACZ,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACjC,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB,CAAC;AAoEF,MAAM,MAAM,aAAa,GAAG;IAC1B,MAAM,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IACxB,SAAS,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IAC3B,IAAI,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACjC,MAAM,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IACxB,WAAW,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IAC7B,UAAU,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC3C,6DAA6D;IAC7D,MAAM,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO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