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.
- package/android/build.gradle +1 -1
- package/android/src/main/java/expo/modules/minimalwebview/Asks.kt +5 -11
- package/android/src/main/java/expo/modules/minimalwebview/Hooks.kt +17 -11
- package/android/src/main/java/expo/modules/minimalwebview/MinimalWebView.kt +64 -119
- package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewClients.kt +16 -31
- package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewModule.kt +4 -16
- package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewNavigation.kt +24 -38
- package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewScripts.kt +24 -36
- package/android/src/main/java/expo/modules/minimalwebview/NavigationRules.kt +19 -20
- package/android/src/main/java/expo/modules/minimalwebview/PlatformSettings.kt +25 -37
- package/android/src/main/java/expo/modules/minimalwebview/PullToRefresh.kt +14 -18
- package/android/src/main/java/expo/modules/minimalwebview/requests/Downloads.kt +12 -23
- package/android/src/main/java/expo/modules/minimalwebview/requests/FileUpload.kt +0 -1
- package/android/src/main/java/expo/modules/minimalwebview/requests/FullscreenVideo.kt +1 -4
- package/android/src/main/java/expo/modules/minimalwebview/requests/Permissions.kt +34 -24
- package/build/WebView.d.ts +8 -1
- package/build/WebView.d.ts.map +1 -1
- package/build/WebView.js +22 -68
- package/build/WebView.js.map +1 -1
- package/build/bridge/createBridge.d.ts +1 -5
- package/build/bridge/createBridge.d.ts.map +1 -1
- package/build/bridge/createBridge.js +3 -15
- package/build/bridge/createBridge.js.map +1 -1
- package/build/bridge/endpoint.d.ts +1 -2
- package/build/bridge/endpoint.d.ts.map +1 -1
- package/build/bridge/endpoint.js +5 -6
- package/build/bridge/endpoint.js.map +1 -1
- package/build/bridge/matchesOrigin.d.ts +11 -0
- package/build/bridge/matchesOrigin.d.ts.map +1 -0
- package/build/bridge/matchesOrigin.js +26 -0
- package/build/bridge/matchesOrigin.js.map +1 -0
- package/build/bridge/origins.d.ts +2 -13
- package/build/bridge/origins.d.ts.map +1 -1
- package/build/bridge/origins.js +1 -30
- package/build/bridge/origins.js.map +1 -1
- package/build/bridge/pageClient.generated.d.ts +1 -1
- package/build/bridge/pageClient.generated.d.ts.map +1 -1
- package/build/bridge/pageClient.generated.js +2 -2
- package/build/bridge/pageClient.generated.js.map +1 -1
- package/build/bridge/protocol.d.ts +3 -5
- package/build/bridge/protocol.d.ts.map +1 -1
- package/build/bridge/protocol.js +12 -14
- package/build/bridge/protocol.js.map +1 -1
- package/build/index.d.ts +1 -1
- package/build/index.js +1 -1
- package/build/navigationRules.d.ts +0 -5
- package/build/navigationRules.d.ts.map +1 -1
- package/build/navigationRules.js +3 -12
- package/build/navigationRules.js.map +1 -1
- package/build/reactNativeWebViewDefaults.d.ts +0 -4
- package/build/reactNativeWebViewDefaults.d.ts.map +1 -1
- package/build/reactNativeWebViewDefaults.js +0 -4
- package/build/reactNativeWebViewDefaults.js.map +1 -1
- package/build/reactNativeWebViewMessages.d.ts.map +1 -1
- package/build/reactNativeWebViewMessages.js +0 -1
- package/build/reactNativeWebViewMessages.js.map +1 -1
- package/build/refStore.d.ts +0 -2
- package/build/refStore.d.ts.map +1 -1
- package/build/refStore.js +0 -6
- package/build/refStore.js.map +1 -1
- package/build/types.d.ts +25 -12
- package/build/types.d.ts.map +1 -1
- package/ios/Asks.swift +6 -9
- package/ios/DelegateProxy.swift +2 -19
- package/ios/DownloadName.swift +0 -2
- package/ios/Downloads.swift +0 -2
- package/ios/Hooks.swift +4 -6
- package/ios/Loads.swift +37 -19
- package/ios/MinimalWebView+Dialogs.swift +2 -6
- package/ios/MinimalWebView+Navigation.swift +17 -50
- package/ios/MinimalWebView+Scripts.swift +4 -16
- package/ios/MinimalWebView.podspec +1 -2
- package/ios/MinimalWebView.swift +62 -132
- package/ios/MinimalWebViewModule.swift +1 -18
- package/ios/NavigationRules.swift +2 -9
- package/ios/OriginRules.swift +4 -13
- package/ios/PlatformSettings.swift +9 -30
- package/ios/ReadAccess.swift +0 -2
- package/ios/Records.swift +18 -0
- package/ios/Recovery.swift +2 -8
- package/ios/SharedCookies.swift +10 -25
- package/package.json +4 -4
- package/src/WebView.tsx +34 -77
- package/src/bridge/createBridge.ts +5 -20
- package/src/bridge/endpoint.ts +6 -9
- package/src/bridge/matchesOrigin.ts +27 -0
- package/src/bridge/origins.ts +2 -30
- package/src/bridge/pageClient.generated.ts +2 -2
- package/src/bridge/pageClient.ts +1 -7
- package/src/bridge/protocol.ts +16 -18
- package/src/index.ts +1 -1
- package/src/navigationRules.ts +6 -12
- package/src/reactNativeWebViewDefaults.ts +0 -4
- package/src/reactNativeWebViewMessages.ts +0 -1
- package/src/refStore.ts +0 -7
- package/src/types.ts +25 -12
|
@@ -2,33 +2,17 @@ import ObjectiveC
|
|
|
2
2
|
import UIKit
|
|
3
3
|
import WebKit
|
|
4
4
|
|
|
5
|
-
/// The `ios` settings prop, `{ configuration: {…}, preferences: {…}, webpagePreferences: {…}, webView: {…},
|
|
6
|
-
/// scrollView: {…} }`, applied by Objective-C property name through Key-Value Coding, so a public property this
|
|
7
|
-
/// package doesn't know (one a newer WebKit adds) needs no code here. `configuration` is read once, when the WKWebView
|
|
8
|
-
/// is created; the other roots apply live, to `webView.configuration.preferences`,
|
|
9
|
-
/// `webView.configuration.defaultWebpagePreferences`, the WKWebView and its scroll view.
|
|
10
|
-
///
|
|
11
|
-
/// A value must fit the property's type (coerce); anything else is rejected before KVC runs: a wrong value in an object-typed property can take the process down
|
|
12
|
-
/// (WebKit asserts), and an unknown key raises an Objective-C exception Swift can't catch. Underscore (private)
|
|
13
|
-
/// properties are refused, and the only private keys accepted are the two react-native-webview sets by KVC
|
|
14
|
-
/// (`privateBools`).
|
|
15
|
-
///
|
|
16
|
-
/// `get` reads a property of a root and `call` invokes a method on one by selector, through MRWInvoke (MRWInvoke.h),
|
|
17
|
-
/// which sets the arguments by the method's signature. For those two, `websiteDataStore` and `httpCookieStore` are
|
|
18
|
-
/// roots as well.
|
|
19
5
|
final class PlatformSettings {
|
|
20
|
-
/// "root.key" -> the last value applied or rejected, so an unchanged value is neither applied nor reported again.
|
|
21
6
|
private var applied: [String: NSObject] = [:]
|
|
22
|
-
/// "root.key" of a live root -> its value before the first write (NSNull for nil), set back when the key is removed.
|
|
23
7
|
private var originals: [String: Any] = [:]
|
|
24
8
|
|
|
25
9
|
/// Applies `settings`. While creating (`configuration` given, no WebView yet) only the `configuration` root applies;
|
|
26
|
-
/// live, every other root does
|
|
27
|
-
///
|
|
10
|
+
/// live, every other root does, and a key applied before and missing now goes back to its value before the first
|
|
11
|
+
/// write. Returns the rejected keys.
|
|
28
12
|
func apply(_ settings: [String: Any], webView: WKWebView?, configuration: WKWebViewConfiguration? = nil) -> [[String: String]] {
|
|
29
13
|
var rejected: [[String: String]] = []
|
|
30
14
|
let creating = configuration != nil
|
|
31
|
-
//
|
|
15
|
+
// Restoring a scroll view's inset can move its offset.
|
|
32
16
|
if !creating { rejected += restore(removedFrom: settings, webView: webView) }
|
|
33
17
|
for (rootName, entries) in settings {
|
|
34
18
|
guard let entries = entries as? [String: Any] else {
|
|
@@ -67,8 +51,6 @@ final class PlatformSettings {
|
|
|
67
51
|
guard let original = originals.removeValue(forKey: id), let dot = id.firstIndex(of: "."),
|
|
68
52
|
let object = root(String(id[..<dot]), webView: webView, configuration: nil) else { continue }
|
|
69
53
|
let key = String(id[id.index(after: dot)...])
|
|
70
|
-
// shortcut: a null_resettable property (underPageBackgroundColor) comes back as the value read, not as "follow the
|
|
71
|
-
// default"; set nil for those if one matters.
|
|
72
54
|
if let reason = __MRWCatchException({ object.setValue(original is NSNull ? nil : original, forKey: key) }) {
|
|
73
55
|
failed.append(["key": id, "reason": "removed, but restoring it failed: \(reason)"])
|
|
74
56
|
}
|
|
@@ -126,10 +108,8 @@ final class PlatformSettings {
|
|
|
126
108
|
return String(decoding: data, as: UTF8.self)
|
|
127
109
|
}
|
|
128
110
|
|
|
129
|
-
///
|
|
130
|
-
///
|
|
131
|
-
/// performSelector), object lifecycle (init, copy, new: a re-initialized live object, or a +1 result MRWInvoke would
|
|
132
|
-
/// leak) and reference counting. `mutable` covers `mutableCopy` and KVC's `mutableArrayValueForKey:` and its kin.
|
|
111
|
+
/// KVC, KVO and performSelector reach any selector; `init`, `copy`, `new` and `mutableCopy` return a +1 object
|
|
112
|
+
/// MRWInvoke would leak.
|
|
133
113
|
private static let refused = [
|
|
134
114
|
"_", "load", "go", "reload", "stop", "evaluateJavaScript", "callAsyncJavaScript", "startDownload", "resumeDownload",
|
|
135
115
|
"setInteractionState", "setNavigationDelegate", "setUIDelegate", "setDelegate", "setValue", "setValuesForKeys", "valueForKey",
|
|
@@ -152,8 +132,7 @@ final class PlatformSettings {
|
|
|
152
132
|
}
|
|
153
133
|
|
|
154
134
|
/// Sets one property, or returns why not; with `original`, first keeps the value it replaces under that id unless one
|
|
155
|
-
/// is kept already.
|
|
156
|
-
/// the value may be.
|
|
135
|
+
/// is kept already.
|
|
157
136
|
private func set(_ object: NSObject, _ key: String, _ value: Any, original id: String?) -> String? {
|
|
158
137
|
guard !key.hasPrefix("_"), !key.contains(".") else { return "private and nested keys are not allowed" }
|
|
159
138
|
guard let attributes = Self.attributes(object, key) else { return "no such property" }
|
|
@@ -174,14 +153,14 @@ final class PlatformSettings {
|
|
|
174
153
|
return String(cString: property_getAttributes(property)!).split(separator: ",")
|
|
175
154
|
}
|
|
176
155
|
|
|
177
|
-
/// KVC reaches these through WebKit's `_set…` accessors: WebKit declares no property by these names.
|
|
178
|
-
/// `file:` pages read: other `file:` URLs, and any URL.
|
|
156
|
+
/// KVC reaches these through WebKit's `_set…` accessors: WebKit declares no property by these names.
|
|
179
157
|
private static let privateBools: [String: AnyClass] = [
|
|
180
158
|
"allowFileAccessFromFileURLs": WKPreferences.self,
|
|
181
159
|
"allowUniversalAccessFromFileURLs": WKWebViewConfiguration.self,
|
|
182
160
|
]
|
|
183
161
|
|
|
184
|
-
/// `value` as KVC must get it for a property of type encoding `type`; NSNull stands for nil. Nil: doesn't fit.
|
|
162
|
+
/// `value` as KVC must get it for a property of type encoding `type`; NSNull stands for nil. Nil: doesn't fit. A value
|
|
163
|
+
/// of the wrong class in an object-typed property can take the process down (WebKit asserts).
|
|
185
164
|
private static func coerce(_ value: Any, _ type: String) -> Any? {
|
|
186
165
|
let isBool = CFGetTypeID(value as CFTypeRef) == CFBooleanGetTypeID()
|
|
187
166
|
let number = isBool ? nil : value as? NSNumber
|
package/ios/ReadAccess.swift
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import Foundation
|
|
2
2
|
|
|
3
|
-
/// The read root of a `file:` load the app starts, from `source.readAccessRoot`.
|
|
4
3
|
enum ReadAccess {
|
|
5
4
|
/// `root` when it is a `file:` URL that contains `file`, else `file`'s directory and a warning that says why `root`
|
|
6
5
|
/// didn't apply. Always a file URL: loadFileURL raises an exception (a crash) for any other.
|
|
@@ -10,7 +9,6 @@ enum ReadAccess {
|
|
|
10
9
|
guard let url = URL(string: root), url.isFileURL else {
|
|
11
10
|
return (directory, "source.readAccessRoot \(root) is not a file: URL, so the file's directory applies")
|
|
12
11
|
}
|
|
13
|
-
// Components, not a string prefix: `..` is resolved, and /a/site2 isn't inside /a/site.
|
|
14
12
|
guard file.standardizedFileURL.pathComponents.starts(with: url.standardizedFileURL.pathComponents) else {
|
|
15
13
|
return (directory, "source.readAccessRoot \(root) doesn't contain \(file.absoluteString), so the file's directory applies")
|
|
16
14
|
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import ExpoModulesCore
|
|
2
|
+
|
|
3
|
+
// A prop that fails to convert is dropped whole (ExpoFabricView's try?), so every field is optional.
|
|
4
|
+
|
|
5
|
+
struct WebViewSource: Record {
|
|
6
|
+
@Field var uri: String? = nil
|
|
7
|
+
@Field var headers: [String: String]? = nil
|
|
8
|
+
@Field var body: String? = nil
|
|
9
|
+
@Field var readAccessRoot: String? = nil
|
|
10
|
+
@Field var html: String? = nil
|
|
11
|
+
@Field var baseUrl: String? = nil
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
struct InjectedScript: Record {
|
|
15
|
+
@Field var code: String? = nil
|
|
16
|
+
@Field var allFrames: Bool? = nil
|
|
17
|
+
}
|
|
18
|
+
|
package/ios/Recovery.swift
CHANGED
|
@@ -1,10 +1,6 @@
|
|
|
1
1
|
import Foundation
|
|
2
2
|
|
|
3
|
-
/// Crash recovery's choices that need no WebView, as on Android (`showsSource` and `crashAllowsReload` in
|
|
4
|
-
/// MinimalWebView.kt). Cases: src/__tests__/vectors/recovery.json.
|
|
5
3
|
enum Recovery {
|
|
6
|
-
/// Whether the committed `url` is the page of the `source` with this `uri`: the same `Loads.canonical` form up to
|
|
7
|
-
/// trailing slashes.
|
|
8
4
|
static func showsSource(_ uri: String, _ url: String) -> Bool {
|
|
9
5
|
func page(_ url: String) -> String {
|
|
10
6
|
(URL(string: url).map(Loads.canonical) ?? url).replacingOccurrences(of: "/+$", with: "", options: .regularExpression)
|
|
@@ -12,15 +8,13 @@ enum Recovery {
|
|
|
12
8
|
return page(uri) == page(url)
|
|
13
9
|
}
|
|
14
10
|
|
|
15
|
-
/// Records a web content process death at `now` in `times`, and says
|
|
16
|
-
///
|
|
17
|
-
/// `ProcessInfo.systemUptime`, which a change of device time doesn't move.
|
|
11
|
+
/// Records a web content process death at `now`, in seconds of `ProcessInfo.systemUptime`, in `times`, and says
|
|
12
|
+
/// whether to reload after it.
|
|
18
13
|
static func crashAllowsReload(_ times: inout [TimeInterval], now: TimeInterval) -> Bool {
|
|
19
14
|
times = times.filter { now - $0 <= crashWindow } + [now]
|
|
20
15
|
return times.count <= maxCrashesPerWindow
|
|
21
16
|
}
|
|
22
17
|
}
|
|
23
18
|
|
|
24
|
-
// shortcut: a fixed crash-loop guard, make it a prop if an app needs a different policy
|
|
25
19
|
private let maxCrashesPerWindow = 3
|
|
26
20
|
private let crashWindow: TimeInterval = 60
|
package/ios/SharedCookies.swift
CHANGED
|
@@ -1,30 +1,22 @@
|
|
|
1
1
|
import WebKit
|
|
2
2
|
|
|
3
|
-
/// The `sharedCookies` prop. In the core, not a hook: the copy before the first `source` load is something nothing
|
|
4
|
-
/// outside the core can hold.
|
|
5
3
|
final class SharedCookies: NSObject, WKHTTPCookieStoreObserver {
|
|
6
|
-
private weak var
|
|
7
|
-
private var enabled = false
|
|
4
|
+
private weak var observed: WKHTTPCookieStore?
|
|
8
5
|
private var copyScheduled = false
|
|
9
|
-
/// The WebView's cookies at the last copy: one gone from it since is deleted from native too.
|
|
10
6
|
private var copied: [HTTPCookie] = []
|
|
11
7
|
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
8
|
+
func set(_ enabled: Bool, for store: WKHTTPCookieStore) {
|
|
9
|
+
let next = enabled ? store : nil
|
|
10
|
+
guard next !== observed else { return }
|
|
11
|
+
observed?.remove(self)
|
|
12
|
+
next?.add(self)
|
|
13
|
+
observed = next
|
|
15
14
|
}
|
|
16
15
|
|
|
17
|
-
|
|
18
|
-
guard enabled != self.enabled else { return }
|
|
19
|
-
self.enabled = enabled
|
|
20
|
-
if enabled { store?.add(self) } else { store?.remove(self) }
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
/// Work that must finish before a `source` load: calls `done` once the native cookies are in the WebView.
|
|
16
|
+
/// Calls `done` once the native cookies are in the WebView.
|
|
24
17
|
func prepare(done: @escaping () -> Void) {
|
|
25
|
-
guard
|
|
18
|
+
guard let store = observed else { return done() }
|
|
26
19
|
let group = DispatchGroup()
|
|
27
|
-
// shortcut: one setCookie per cookie, use iOS 26's batch setCookies once the minimum allows
|
|
28
20
|
for cookie in HTTPCookieStorage.shared.cookies ?? [] {
|
|
29
21
|
group.enter()
|
|
30
22
|
store.setCookie(cookie) { group.leave() }
|
|
@@ -32,27 +24,20 @@ final class SharedCookies: NSObject, WKHTTPCookieStoreObserver {
|
|
|
32
24
|
group.notify(queue: .main, execute: done)
|
|
33
25
|
}
|
|
34
26
|
|
|
35
|
-
/// One copy per main-queue turn: `prepare`'s setCookie calls, or a page setting many cookies, each fire this.
|
|
36
27
|
func cookiesDidChange(in cookieStore: WKHTTPCookieStore) {
|
|
37
28
|
guard !copyScheduled else { return }
|
|
38
29
|
copyScheduled = true
|
|
39
30
|
DispatchQueue.main.async { [weak self] in
|
|
40
31
|
guard let self else { return }
|
|
41
|
-
// Cleared before the read: a change after it schedules the next copy.
|
|
42
32
|
self.copyScheduled = false
|
|
43
|
-
self.
|
|
33
|
+
self.observed?.getAllCookies { [weak self] cookies in
|
|
44
34
|
guard let self else { return }
|
|
45
35
|
let key = { (cookie: HTTPCookie) in [cookie.name, cookie.domain, cookie.path] }
|
|
46
36
|
let present = Set(cookies.map(key))
|
|
47
|
-
// Deleted or expired in the WebView (a logout): native drops it too. Cookies only native set stay.
|
|
48
37
|
self.copied.filter { !present.contains(key($0)) }.forEach(HTTPCookieStorage.shared.deleteCookie)
|
|
49
38
|
cookies.forEach(HTTPCookieStorage.shared.setCookie)
|
|
50
39
|
self.copied = cookies
|
|
51
40
|
}
|
|
52
41
|
}
|
|
53
42
|
}
|
|
54
|
-
|
|
55
|
-
func detach() {
|
|
56
|
-
store?.remove(self)
|
|
57
|
-
}
|
|
58
43
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "react-native-minimal-webview",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.3.0",
|
|
4
4
|
"description": "A React Native WebView that hands you the iOS and Android WebView APIs, instead of wrapping each one in a prop",
|
|
5
5
|
"main": "build/index.js",
|
|
6
6
|
"types": "build/index.d.ts",
|
|
@@ -27,11 +27,11 @@
|
|
|
27
27
|
"scripts": {
|
|
28
28
|
"build": "tsc && tsc -p extensions",
|
|
29
29
|
"clean": "rm -rf build extensions/build",
|
|
30
|
-
"pretest": "npm run build:page-client -- --check && npm run gen:platform-types -- --check && npm run gen:defaults -- --check",
|
|
30
|
+
"pretest": "node --test '.github/scripts/*.test.mts' && npm run build:page-client -- --check && npm run gen:platform-types -- --check && npm run gen:defaults -- --check",
|
|
31
31
|
"test": "jest",
|
|
32
32
|
"lint": "eslint --max-warnings 0 src extensions example .github && prettier --check .",
|
|
33
33
|
"prepare": "npm run clean && npm run build",
|
|
34
|
-
"check": "npm test && npm run lint && knip --config .config/knip.json && tsc --noEmit -p src/__tests__/tsconfig.json && tsc --noEmit -p extensions/src/__tests__/tsconfig.json && (cd example && npx tsc --noEmit) && node .github/scripts/check-doc-samples.mts && node .github/scripts/check-expo-set.mts && npm run prepare && npm run docs:check && tsc --noEmit -p .github/scripts && tsc --noEmit -p example/maestro/scripts",
|
|
34
|
+
"check": "npm test && npm run lint && knip --config .config/knip.json && tsc --noEmit -p src/__tests__/tsconfig.json && tsc --noEmit -p extensions/src/__tests__/tsconfig.json && (cd example && npx tsc --noEmit) && node .github/scripts/check-doc-samples.mts && node .github/scripts/check-expo-set.mts && node .github/scripts/check-cache-keys.mts && npm run prepare && npm run docs:check && tsc --noEmit -p .github/scripts && tsc --noEmit -p example/maestro/scripts",
|
|
35
35
|
"mutation": "stryker run .config/stryker.config.json",
|
|
36
36
|
"build:page-client": "node .github/scripts/build-page-client.mts",
|
|
37
37
|
"gen:platform-types": "node .github/scripts/gen-platform-types.mts",
|
|
@@ -72,7 +72,7 @@
|
|
|
72
72
|
"globals": "^17.14.0",
|
|
73
73
|
"jest": "^30.0.0",
|
|
74
74
|
"jest-expo": "~58.0.15",
|
|
75
|
-
"knip": "6.
|
|
75
|
+
"knip": "6.46.1",
|
|
76
76
|
"prettier": "^3.10.1",
|
|
77
77
|
"react": "19.3.0",
|
|
78
78
|
"react-native": "0.88.1",
|
package/src/WebView.tsx
CHANGED
|
@@ -38,11 +38,9 @@ export type AskableEvent = {
|
|
|
38
38
|
askId?: number;
|
|
39
39
|
};
|
|
40
40
|
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
*/
|
|
45
|
-
const REQUESTS = [
|
|
41
|
+
export type CoreEventPayloads = { warning: { message: string }; askCancelled: { askId: number } };
|
|
42
|
+
|
|
43
|
+
const REQUEST_HANDLER_PROPS = [
|
|
46
44
|
'onNavigationRequest',
|
|
47
45
|
'onOpenExternal',
|
|
48
46
|
'onFileRequest',
|
|
@@ -52,7 +50,6 @@ const REQUESTS = [
|
|
|
52
50
|
'onNavigation',
|
|
53
51
|
] as const;
|
|
54
52
|
|
|
55
|
-
/** Every prop that is not a `ViewProps` one, so it never reaches the outermost view. */
|
|
56
53
|
const OWN = [
|
|
57
54
|
'source',
|
|
58
55
|
'ios',
|
|
@@ -69,12 +66,11 @@ const OWN = [
|
|
|
69
66
|
'onProcessGone',
|
|
70
67
|
'onLoadStart',
|
|
71
68
|
'onLoadEnd',
|
|
72
|
-
...
|
|
69
|
+
...REQUEST_HANDLER_PROPS,
|
|
73
70
|
'ref',
|
|
74
71
|
'children',
|
|
75
72
|
] as const satisfies (Exclude<keyof WebViewProps, keyof ViewProps> | 'children')[];
|
|
76
73
|
type Unlisted = Exclude<Exclude<keyof WebViewProps, keyof ViewProps>, (typeof OWN)[number]>;
|
|
77
|
-
// A prop missing from OWN fails to compile here, by name.
|
|
78
74
|
const OWN_SET: Set<string> &
|
|
79
75
|
([Unlisted] extends [never] ? unknown : Record<Unlisted, 'missing from OWN'>) = new Set(OWN);
|
|
80
76
|
|
|
@@ -82,13 +78,11 @@ type NativeSettings = Record<string, Record<string, SettingValue | undefined>>;
|
|
|
82
78
|
|
|
83
79
|
type NativeProps = ViewProps &
|
|
84
80
|
Pick<WebViewProps, 'source' | 'navigationRules' | 'pullToRefresh'> & {
|
|
85
|
-
/** With each script's `origins` in its code (`nativeScripts`). */
|
|
86
81
|
injectedScripts: Omit<InjectedScript, 'origins'>[] | undefined;
|
|
87
82
|
ref: Ref<NativeMethods>;
|
|
88
83
|
sharedCookies: boolean | undefined;
|
|
89
84
|
/**
|
|
90
|
-
*
|
|
91
|
-
* string, so that a `null` (reset this key) survives the trip; the native dictionary conversion drops it.
|
|
85
|
+
* A string, so that a `null` (reset this key) survives the trip; the native dictionary conversion drops it.
|
|
92
86
|
*/
|
|
93
87
|
settings: string;
|
|
94
88
|
bridgeScript: string | undefined;
|
|
@@ -111,7 +105,6 @@ export type NativeMethods = {
|
|
|
111
105
|
reload(): Promise<void>;
|
|
112
106
|
stopLoading(): Promise<void>;
|
|
113
107
|
bridgePost(message: string): Promise<void>;
|
|
114
|
-
/** Answers a native `ask`. `json` is JSON, as for `call`. */
|
|
115
108
|
answer(askId: number, json: string): Promise<void>;
|
|
116
109
|
/** The JSON-encoded result. */
|
|
117
110
|
evaluate(script: string): Promise<string>;
|
|
@@ -151,7 +144,6 @@ function assertLinked() {
|
|
|
151
144
|
const notRegistered = (error: unknown) =>
|
|
152
145
|
(error as { code?: string } | null)?.code === 'ERR_VIEW_NOT_FOUND';
|
|
153
146
|
|
|
154
|
-
/** A native call nothing awaits: a rejection is logged, bar one for a view not registered yet, where it does nothing. */
|
|
155
147
|
const unawaited = (call: Promise<unknown> | undefined, name: string) =>
|
|
156
148
|
void call?.catch((error: unknown) => {
|
|
157
149
|
if (!notRegistered(error))
|
|
@@ -192,12 +184,9 @@ function useBridgeChangeWarning(bridge: WebViewProps['bridge']) {
|
|
|
192
184
|
}, [bridge]);
|
|
193
185
|
}
|
|
194
186
|
|
|
195
|
-
/** One native WebView's life: a new creation key remounts it, so its state, ref attachment and bridge start over. */
|
|
196
187
|
function WebViewInstance({ ref, ...props }: WebViewProps) {
|
|
197
188
|
const native = useRef<NativeMethods>(null);
|
|
198
189
|
|
|
199
|
-
// The rejecters of native calls not settled yet. An unmount rejects them: native may never answer (a hook handler
|
|
200
|
-
// that never replies), and a late answer then settles nothing.
|
|
201
190
|
const [inFlight] = useState(() => new Set<(error: Error) => void>());
|
|
202
191
|
useEffect(
|
|
203
192
|
() => () => {
|
|
@@ -212,8 +201,8 @@ function WebViewInstance({ ref, ...props }: WebViewProps) {
|
|
|
212
201
|
const gone = (): never => {
|
|
213
202
|
throw codedError({ code: 'unavailable', message: 'the WebView is gone' });
|
|
214
203
|
};
|
|
215
|
-
const settled = (promise: Promise<
|
|
216
|
-
new Promise<
|
|
204
|
+
const settled = <T,>(promise: Promise<T>) =>
|
|
205
|
+
new Promise<T>((resolve, reject) => {
|
|
217
206
|
inFlight.add(reject);
|
|
218
207
|
promise.then(
|
|
219
208
|
(value) => {
|
|
@@ -226,11 +215,10 @@ function WebViewInstance({ ref, ...props }: WebViewProps) {
|
|
|
226
215
|
}
|
|
227
216
|
);
|
|
228
217
|
});
|
|
229
|
-
|
|
230
|
-
const mounted = async (call: () => Promise<string> | undefined) => {
|
|
218
|
+
const retriedUntilViewRegistered = async <T,>(call: () => Promise<T> | undefined) => {
|
|
231
219
|
for (let frame = 0; ; frame++) {
|
|
232
220
|
try {
|
|
233
|
-
return
|
|
221
|
+
return await settled(call() ?? gone());
|
|
234
222
|
} catch (error) {
|
|
235
223
|
if (!notRegistered(error)) throw error;
|
|
236
224
|
if (frame === 60 || AppState.currentState === 'background') gone();
|
|
@@ -238,6 +226,8 @@ function WebViewInstance({ ref, ...props }: WebViewProps) {
|
|
|
238
226
|
}
|
|
239
227
|
}
|
|
240
228
|
};
|
|
229
|
+
const jsonResultOf = async (call: () => Promise<string> | undefined) =>
|
|
230
|
+
JSON.parse(await retriedUntilViewRegistered(call)) as unknown;
|
|
241
231
|
return {
|
|
242
232
|
goBack: () => unawaited(native.current?.goBack(), 'goBack'),
|
|
243
233
|
goForward: () => unawaited(native.current?.goForward(), 'goForward'),
|
|
@@ -249,10 +239,8 @@ function WebViewInstance({ ref, ...props }: WebViewProps) {
|
|
|
249
239
|
);
|
|
250
240
|
return;
|
|
251
241
|
}
|
|
252
|
-
// mounted() parses a JSON result, and load has none. A view that went away or never came loads nothing, as
|
|
253
|
-
// a navigation method does after an unmount.
|
|
254
242
|
unawaited(
|
|
255
|
-
|
|
243
|
+
retriedUntilViewRegistered(() => native.current?.load(url)).catch((error: unknown) => {
|
|
256
244
|
const code = (error as { code?: string } | null)?.code;
|
|
257
245
|
if (code !== 'unavailable' && code !== 'navigated') throw error;
|
|
258
246
|
}),
|
|
@@ -261,12 +249,12 @@ function WebViewInstance({ ref, ...props }: WebViewProps) {
|
|
|
261
249
|
},
|
|
262
250
|
reload: () => unawaited(native.current?.reload(), 'reload'),
|
|
263
251
|
stopLoading: () => unawaited(native.current?.stopLoading(), 'stopLoading'),
|
|
264
|
-
evaluate: (script) =>
|
|
265
|
-
get: (key) =>
|
|
252
|
+
evaluate: (script) => jsonResultOf(() => native.current?.evaluate(script)),
|
|
253
|
+
get: (key) => jsonResultOf(() => native.current?.get(key)),
|
|
266
254
|
call: (method, args = []) =>
|
|
267
|
-
|
|
255
|
+
jsonResultOf(() => native.current?.call(method, JSON.stringify(args))),
|
|
268
256
|
hook: (name, method, args = []) =>
|
|
269
|
-
|
|
257
|
+
jsonResultOf(() => native.current?.hook(name, method, JSON.stringify(args))),
|
|
270
258
|
};
|
|
271
259
|
});
|
|
272
260
|
const publish = useAttach(ref, handle);
|
|
@@ -279,7 +267,6 @@ function WebViewInstance({ ref, ...props }: WebViewProps) {
|
|
|
279
267
|
if (was.loading && !state.loading) props.onLoadEnd?.(state);
|
|
280
268
|
};
|
|
281
269
|
|
|
282
|
-
// The same string while nothing in it changed, so a re-render sends native nothing.
|
|
283
270
|
const settings = JSON.stringify(platformSettings(props));
|
|
284
271
|
const injectedScripts = useMemo(
|
|
285
272
|
() => nativeScripts(props.injectedScripts),
|
|
@@ -296,7 +283,6 @@ function WebViewInstance({ ref, ...props }: WebViewProps) {
|
|
|
296
283
|
const hookOptions = useHookOptions(props.extensions);
|
|
297
284
|
const navigationRules = useNavigationRules(props.navigationRules);
|
|
298
285
|
|
|
299
|
-
// One per ask in flight, by id: aborted when native stops waiting (the core's `askCancelled`) or at unmount.
|
|
300
286
|
const [asks] = useState(() => new Map<number, AbortController>());
|
|
301
287
|
useEffect(() => () => asks.forEach((controller) => controller.abort()), [asks]);
|
|
302
288
|
|
|
@@ -304,33 +290,36 @@ function WebViewInstance({ ref, ...props }: WebViewProps) {
|
|
|
304
290
|
nativeEvent: { key, name, payload, askId },
|
|
305
291
|
}: Native<AskableEvent>) => {
|
|
306
292
|
const core = key === 'core';
|
|
307
|
-
// The core's own events: a warning for the developer, and an ask native stopped waiting for.
|
|
308
293
|
if (core && name === 'warning')
|
|
309
|
-
return console.warn(
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
294
|
+
return console.warn(
|
|
295
|
+
`[react-native-minimal-webview] ${(payload as CoreEventPayloads['warning']).message}`
|
|
296
|
+
);
|
|
297
|
+
if (core && name === 'askCancelled')
|
|
298
|
+
return asks.get((payload as CoreEventPayloads['askCancelled']).askId)?.abort();
|
|
299
|
+
const request = REQUEST_HANDLER_PROPS.find((prop) => core && prop === name);
|
|
313
300
|
const owner = props.extensions?.findLast((e): e is HookExtension => !!e && e.key === key);
|
|
314
301
|
const handler = request
|
|
315
302
|
? (props[request] as ((payload: unknown, signal?: AbortSignal) => unknown) | undefined)
|
|
316
|
-
: (_: unknown, signal?: AbortSignal) =>
|
|
317
|
-
|
|
303
|
+
: (_: unknown, signal?: AbortSignal) =>
|
|
304
|
+
signal && owner?.onAsk
|
|
305
|
+
? owner.onAsk({ name, payload }, signal)
|
|
306
|
+
: owner?.onEvent?.({ name, payload }, signal);
|
|
318
307
|
let controller: AbortController | undefined;
|
|
319
308
|
if (askId !== undefined) {
|
|
320
309
|
controller = new AbortController();
|
|
321
310
|
asks.set(askId, controller);
|
|
322
311
|
}
|
|
323
|
-
const failure = request
|
|
312
|
+
const failure = request
|
|
313
|
+
? `${request} failed`
|
|
314
|
+
: `${hookHandlerName(owner, askId)} failed for ${key}.${name}`;
|
|
324
315
|
let value: unknown = null;
|
|
325
316
|
try {
|
|
326
317
|
value = await handler?.(payload, controller?.signal);
|
|
327
318
|
} catch (error) {
|
|
328
|
-
// Native waits on this handler: one that throws still answers, with null (native's safe default).
|
|
329
319
|
console.error(`[react-native-minimal-webview] ${failure}`, error);
|
|
330
320
|
}
|
|
331
321
|
if (askId === undefined) return;
|
|
332
322
|
asks.delete(askId);
|
|
333
|
-
// Native already answered a cancelled ask with null; a late answer would find nothing.
|
|
334
323
|
if (!controller?.signal.aborted) await native.current?.answer(askId, answerJson(value));
|
|
335
324
|
};
|
|
336
325
|
|
|
@@ -358,7 +347,9 @@ function WebViewInstance({ ref, ...props }: WebViewProps) {
|
|
|
358
347
|
);
|
|
359
348
|
}
|
|
360
349
|
|
|
361
|
-
|
|
350
|
+
const hookHandlerName = (owner: HookExtension | undefined, askId: number | undefined) =>
|
|
351
|
+
askId !== undefined && owner?.onAsk ? 'onAsk' : 'onEvent';
|
|
352
|
+
|
|
362
353
|
function answerJson(value: unknown) {
|
|
363
354
|
try {
|
|
364
355
|
return JSON.stringify(value) ?? 'null';
|
|
@@ -367,10 +358,6 @@ function answerJson(value: unknown) {
|
|
|
367
358
|
}
|
|
368
359
|
}
|
|
369
360
|
|
|
370
|
-
/**
|
|
371
|
-
* The scripts as native runs them: one whose `origins` lack `*` runs inside a function, so that even its function
|
|
372
|
-
* declarations take effect only where the guard lets it run.
|
|
373
|
-
*/
|
|
374
361
|
function nativeScripts(scripts: InjectedScript[] | undefined) {
|
|
375
362
|
return scripts?.map(({ code, allFrames, origins }) => {
|
|
376
363
|
if (!Array.isArray(origins))
|
|
@@ -380,10 +367,6 @@ function nativeScripts(scripts: InjectedScript[] | undefined) {
|
|
|
380
367
|
});
|
|
381
368
|
}
|
|
382
369
|
|
|
383
|
-
/**
|
|
384
|
-
* The rules as the core gets them (`checkNavigationRules`), and a development warning for each malformed one. The same
|
|
385
|
-
* array when none is malformed.
|
|
386
|
-
*/
|
|
387
370
|
function useNavigationRules(rules: WebViewProps['navigationRules']) {
|
|
388
371
|
const { checked, warnings } = useMemo(
|
|
389
372
|
() => checkNavigationRules(rules ?? defaultNavigationRules),
|
|
@@ -393,7 +376,6 @@ function useNavigationRules(rules: WebViewProps['navigationRules']) {
|
|
|
393
376
|
return checked;
|
|
394
377
|
}
|
|
395
378
|
|
|
396
|
-
/** Logs each warning in development, again only when the list changes. */
|
|
397
379
|
function useDevWarnings(warnings: string[]) {
|
|
398
380
|
const json = JSON.stringify(warnings);
|
|
399
381
|
useEffect(() => {
|
|
@@ -403,17 +385,11 @@ function useDevWarnings(warnings: string[]) {
|
|
|
403
385
|
}, [json]);
|
|
404
386
|
}
|
|
405
387
|
|
|
406
|
-
/** The `REQUESTS` with a prop set, as a new array only when that set changes. */
|
|
407
388
|
function useRequestHandlers(props: WebViewProps) {
|
|
408
|
-
const key =
|
|
389
|
+
const key = REQUEST_HANDLER_PROPS.filter((prop) => props[prop]).join();
|
|
409
390
|
return useMemo(() => (key ? key.split(',') : []), [key]);
|
|
410
391
|
}
|
|
411
392
|
|
|
412
|
-
/**
|
|
413
|
-
* The core's `hookOptions`: each extension's `options` by its key, the later of two extensions with one key winning (a
|
|
414
|
-
* development warning). The same object while the JSON is the same, so a render with new handlers sends the core
|
|
415
|
-
* nothing.
|
|
416
|
-
*/
|
|
417
393
|
function useHookOptions(extensions: WebViewProps['extensions']) {
|
|
418
394
|
const on = (extensions ?? []).filter((extension) => !!extension);
|
|
419
395
|
const keys = on.map(({ key }) => key);
|
|
@@ -423,24 +399,14 @@ function useHookOptions(extensions: WebViewProps['extensions']) {
|
|
|
423
399
|
)
|
|
424
400
|
);
|
|
425
401
|
const json = JSON.stringify(
|
|
426
|
-
withoutOff(
|
|
427
|
-
Object.fromEntries(
|
|
428
|
-
// An unset `options` is `true` (HookExtension.options).
|
|
429
|
-
on.map(({ key, options = true }) => [key, options])
|
|
430
|
-
)
|
|
431
|
-
)
|
|
402
|
+
withoutOff(Object.fromEntries(on.map(({ key, options = true }) => [key, options])))
|
|
432
403
|
);
|
|
433
404
|
return useMemo(() => JSON.parse(json) as Record<string, unknown>, [json]);
|
|
434
405
|
}
|
|
435
406
|
|
|
436
|
-
/** Bridges by identity, for the creation key. */
|
|
437
407
|
const bridgeIds = new WeakMap<object, number>();
|
|
438
408
|
let lastBridgeId = 0;
|
|
439
409
|
|
|
440
|
-
/**
|
|
441
|
-
* What native sets up once, at creation (the bridge, `ios.configuration`). As WebViewInstance's `key`, a change
|
|
442
|
-
* remounts it.
|
|
443
|
-
*/
|
|
444
410
|
function creationKey(props: WebViewProps) {
|
|
445
411
|
const bridge = props.bridge;
|
|
446
412
|
let id = bridge && bridgeIds.get(bridge);
|
|
@@ -451,13 +417,11 @@ function creationKey(props: WebViewProps) {
|
|
|
451
417
|
);
|
|
452
418
|
}
|
|
453
419
|
|
|
454
|
-
/** A null or false value is off, and its key is left out: native treats a present key as on. */
|
|
455
420
|
const withoutOff = (options: Record<string, unknown>) =>
|
|
456
421
|
Object.fromEntries(
|
|
457
422
|
Object.entries(options).filter(([, value]) => value != null && value !== false)
|
|
458
423
|
);
|
|
459
424
|
|
|
460
|
-
/** A JSON.stringify replacer: the same options in another key order are the same key. */
|
|
461
425
|
const sortedKeys = (_: string, value: unknown) =>
|
|
462
426
|
value && typeof value === 'object' && !Array.isArray(value)
|
|
463
427
|
? Object.fromEntries(Object.entries(value).sort())
|
|
@@ -467,7 +431,6 @@ function viewPropsOf(props: WebViewProps): ViewProps {
|
|
|
467
431
|
return Object.fromEntries(Object.entries(props).filter(([key]) => !OWN_SET.has(key)));
|
|
468
432
|
}
|
|
469
433
|
|
|
470
|
-
/** Each root's keys with its `other` ones among them, as native takes them; a generated key wins. */
|
|
471
434
|
const flattened = (
|
|
472
435
|
roots: Record<string, { other?: NativeSettings[string] } | undefined> = {}
|
|
473
436
|
): NativeSettings =>
|
|
@@ -475,18 +438,12 @@ const flattened = (
|
|
|
475
438
|
Object.entries(roots).map(([name, { other, ...keys } = {}]) => [name, { ...other, ...keys }])
|
|
476
439
|
);
|
|
477
440
|
|
|
478
|
-
/** Each layer's roots over the earlier layers', key by key. */
|
|
479
441
|
const layered = (...layers: NativeSettings[]) =>
|
|
480
442
|
layers.reduce<NativeSettings>((out, layer) => {
|
|
481
443
|
for (const [root, keys] of Object.entries(layer)) out[root] = { ...out[root], ...keys };
|
|
482
444
|
return out;
|
|
483
445
|
}, {});
|
|
484
446
|
|
|
485
|
-
/**
|
|
486
|
-
* The platform's settings for native: the package's defaults, react-native-webview's over them, the app's `ios` or
|
|
487
|
-
* `android` roots over those, and `userAgent` on top. Native restores the key of a removed `userAgent`. Android's
|
|
488
|
-
* own defaults are written natively.
|
|
489
|
-
*/
|
|
490
447
|
function platformSettings(props: WebViewProps): NativeSettings {
|
|
491
448
|
const [defaults, rnw, app, userAgent] =
|
|
492
449
|
Platform.OS === 'ios'
|