react-native-minimal-webview 0.0.0-stage → 1.0.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 (118) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +130 -2
  3. package/android/build.gradle +26 -0
  4. package/android/consumer-rules.pro +4 -0
  5. package/android/src/main/AndroidManifest.xml +2 -0
  6. package/android/src/main/java/expo/modules/minimalwebview/Asks.kt +44 -0
  7. package/android/src/main/java/expo/modules/minimalwebview/DocumentEnd.kt +31 -0
  8. package/android/src/main/java/expo/modules/minimalwebview/Hooks.kt +496 -0
  9. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebView.kt +510 -0
  10. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewClients.kt +359 -0
  11. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewModule.kt +245 -0
  12. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewNavigation.kt +199 -0
  13. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewScripts.kt +191 -0
  14. package/android/src/main/java/expo/modules/minimalwebview/NavigationRules.kt +113 -0
  15. package/android/src/main/java/expo/modules/minimalwebview/PlatformSettings.kt +306 -0
  16. package/android/src/main/java/expo/modules/minimalwebview/PullToRefresh.kt +76 -0
  17. package/android/src/main/java/expo/modules/minimalwebview/requests/Downloads.kt +258 -0
  18. package/android/src/main/java/expo/modules/minimalwebview/requests/FileUpload.kt +44 -0
  19. package/android/src/main/java/expo/modules/minimalwebview/requests/FullscreenVideo.kt +87 -0
  20. package/android/src/main/java/expo/modules/minimalwebview/requests/Permissions.kt +77 -0
  21. package/build/WebView.d.ts +99 -0
  22. package/build/WebView.d.ts.map +1 -0
  23. package/build/WebView.js +448 -0
  24. package/build/WebView.js.map +1 -0
  25. package/build/bridge/createBridge.d.ts +32 -0
  26. package/build/bridge/createBridge.d.ts.map +1 -0
  27. package/build/bridge/createBridge.js +135 -0
  28. package/build/bridge/createBridge.js.map +1 -0
  29. package/build/bridge/endpoint.d.ts +35 -0
  30. package/build/bridge/endpoint.d.ts.map +1 -0
  31. package/build/bridge/endpoint.js +100 -0
  32. package/build/bridge/endpoint.js.map +1 -0
  33. package/build/bridge/origins.d.ts +25 -0
  34. package/build/bridge/origins.d.ts.map +1 -0
  35. package/build/bridge/origins.js +60 -0
  36. package/build/bridge/origins.js.map +1 -0
  37. package/build/bridge/pageClient.generated.d.ts +3 -0
  38. package/build/bridge/pageClient.generated.d.ts.map +1 -0
  39. package/build/bridge/pageClient.generated.js +4 -0
  40. package/build/bridge/pageClient.generated.js.map +1 -0
  41. package/build/bridge/protocol.d.ts +50 -0
  42. package/build/bridge/protocol.d.ts.map +1 -0
  43. package/build/bridge/protocol.js +52 -0
  44. package/build/bridge/protocol.js.map +1 -0
  45. package/build/defaultNavigationRules.d.ts +16 -0
  46. package/build/defaultNavigationRules.d.ts.map +1 -0
  47. package/build/defaultNavigationRules.js +23 -0
  48. package/build/defaultNavigationRules.js.map +1 -0
  49. package/build/index.d.ts +31 -0
  50. package/build/index.d.ts.map +1 -0
  51. package/build/index.js +30 -0
  52. package/build/index.js.map +1 -0
  53. package/build/platform.generated.d.ts +702 -0
  54. package/build/platform.generated.d.ts.map +1 -0
  55. package/build/platform.generated.js +199 -0
  56. package/build/platform.generated.js.map +1 -0
  57. package/build/reactNativeWebViewDefaults.d.ts +21 -0
  58. package/build/reactNativeWebViewDefaults.d.ts.map +1 -0
  59. package/build/reactNativeWebViewDefaults.js +12 -0
  60. package/build/reactNativeWebViewDefaults.js.map +1 -0
  61. package/build/reactNativeWebViewMessages.d.ts +22 -0
  62. package/build/reactNativeWebViewMessages.d.ts.map +1 -0
  63. package/build/reactNativeWebViewMessages.js +30 -0
  64. package/build/reactNativeWebViewMessages.js.map +1 -0
  65. package/build/refStore.d.ts +31 -0
  66. package/build/refStore.d.ts.map +1 -0
  67. package/build/refStore.js +113 -0
  68. package/build/refStore.js.map +1 -0
  69. package/build/types.d.ts +1127 -0
  70. package/build/types.d.ts.map +1 -0
  71. package/build/types.defaults.d.ts +8 -0
  72. package/build/types.defaults.d.ts.map +1 -0
  73. package/build/types.defaults.js +17 -0
  74. package/build/types.defaults.js.map +1 -0
  75. package/build/types.js +2 -0
  76. package/build/types.js.map +1 -0
  77. package/expo-module.config.json +9 -0
  78. package/ios/Asks.swift +45 -0
  79. package/ios/DelegateProxy.swift +162 -0
  80. package/ios/DocumentEnd.swift +23 -0
  81. package/ios/DownloadName.swift +12 -0
  82. package/ios/Downloads.swift +51 -0
  83. package/ios/Hooks.swift +308 -0
  84. package/ios/Loads.swift +44 -0
  85. package/ios/MRWExceptions.h +9 -0
  86. package/ios/MRWExceptions.m +10 -0
  87. package/ios/MRWInvoke.h +23 -0
  88. package/ios/MRWInvoke.m +187 -0
  89. package/ios/MinimalWebView+Dialogs.swift +99 -0
  90. package/ios/MinimalWebView+Navigation.swift +244 -0
  91. package/ios/MinimalWebView+Scripts.swift +92 -0
  92. package/ios/MinimalWebView.docc/MinimalWebView.md +13 -0
  93. package/ios/MinimalWebView.podspec +32 -0
  94. package/ios/MinimalWebView.swift +512 -0
  95. package/ios/MinimalWebViewModule.swift +110 -0
  96. package/ios/NavigationRules.swift +123 -0
  97. package/ios/OriginRules.swift +35 -0
  98. package/ios/PlatformCompletions.generated.swift +39 -0
  99. package/ios/PlatformSettings.swift +247 -0
  100. package/ios/ReadAccess.swift +19 -0
  101. package/ios/Recovery.swift +25 -0
  102. package/ios/SharedCookies.swift +59 -0
  103. package/package.json +94 -4
  104. package/src/WebView.tsx +623 -0
  105. package/src/bridge/createBridge.ts +176 -0
  106. package/src/bridge/endpoint.ts +119 -0
  107. package/src/bridge/origins.ts +62 -0
  108. package/src/bridge/pageClient.generated.ts +5 -0
  109. package/src/bridge/pageClient.ts +68 -0
  110. package/src/bridge/protocol.ts +78 -0
  111. package/src/defaultNavigationRules.ts +25 -0
  112. package/src/index.ts +37 -0
  113. package/src/platform.generated.ts +694 -0
  114. package/src/reactNativeWebViewDefaults.ts +13 -0
  115. package/src/reactNativeWebViewMessages.ts +32 -0
  116. package/src/refStore.ts +164 -0
  117. package/src/types.defaults.ts +24 -0
  118. package/src/types.ts +1194 -0
@@ -0,0 +1,512 @@
1
+ import ExpoModulesCore
2
+ import WebKit
3
+
4
+ // swiftlint:disable file_length - because the view is the aggregate root: it holds what has one owner (the Expo surface, the platform WebView's life, crash recovery, the Document scope, the navigation state, the hook plumbing), and a feature with state of its own gets its own class
5
+ // swiftlint:disable:next type_body_length - because the view is the aggregate root: it holds what has one owner (the Expo surface, the platform WebView's life, crash recovery, the Document scope, the navigation state, the hook plumbing), and a feature with state of its own gets its own class
6
+ class MinimalWebView: ExpoView, WKNavigationDelegate {
7
+ let onNavigationState = EventDispatcher()
8
+ let onBridge = EventDispatcher()
9
+ let onHookEvent = EventDispatcher()
10
+ let onError = EventDispatcher()
11
+ let onProcessGone = EventDispatcher()
12
+ let onNavigation = EventDispatcher()
13
+
14
+ // Props, applied together in applyProps(). The bridge, the hooks with a configure step and the `configuration`
15
+ // settings are fixed at mount: they are read once, when the WKWebView is created.
16
+ var source: WebViewSource?
17
+ var bridgeScript: String?
18
+ var bridgeOrigins: [String] = []
19
+ /// The `hookOptions` prop, made from the `extensions` prop's options: each hook's value by key. A change reaches the attached hooks (onOptions).
20
+ var hookOptions: [String: Any] = [:] {
21
+ didSet { if webView != nil { optionsChanged(from: oldValue) } }
22
+ }
23
+ /// The `ios` prop: WebKit properties by name, applied by PlatformSettings.
24
+ var settings: [String: Any] = [:]
25
+ let platformSettings = PlatformSettings()
26
+ var pullToRefresh = false
27
+ private(set) lazy var refreshControl: UIRefreshControl = {
28
+ let control = UIRefreshControl()
29
+ control.addAction(UIAction { [weak self] _ in self?.reload() }, for: .valueChanged)
30
+ return control
31
+ }()
32
+ var sharedCookies = false
33
+ private let cookies = SharedCookies()
34
+ var navigationRules: [[String: Any]]?
35
+ var injectedScripts: [InjectedScript] = [] {
36
+ didSet { if let webView { installScripts(webView.configuration.userContentController) } }
37
+ }
38
+ /// The user scripts installScripts added: the others in the content controller are a hook's.
39
+ var ownScripts: [WKUserScript] = []
40
+ /// The page requests JS has a prop for, by prop name (`onDownload`, `onNavigationRequest`, ...), and `onNavigation`, read when a
41
+ /// request comes or a decision is reported.
42
+ var requestHandlers: Set<String> = []
43
+ private var loadedSource: NSDictionary?
44
+
45
+ // Created once, from the first props: WebKit reads some WKWebViewConfiguration settings only at creation.
46
+ private(set) var webView: WKWebView?
47
+ private var observations: [NSKeyValueObservation] = []
48
+ private(set) lazy var downloads = Downloads(view: self)
49
+ private lazy var proxy = DelegateProxy(core: self)
50
+ /// When the user last tapped the WKWebView: a link activation counts as user-initiated only right after a tap.
51
+ let taps = Taps(target: nil, action: nil)
52
+ /// The decision warnings sent, shared and taken (DelegateProxy): one each per view.
53
+ private var warnedDecisions: Set<String> = []
54
+
55
+ // Navigation state, derived from WebKit in refreshUrls(). Native owns the committed URL; JS is told.
56
+ private(set) var url = ""
57
+ /// `url` as the hooks see it (`WebViewContext.url`): it follows `url` while no load is in flight and WebKit's own URL
58
+ /// agrees, and takes the new page at each commit, after `onDocumentEnd`. WebKit moves the back-forward list to the
59
+ /// next page before didCommit, and `url` can follow it early.
60
+ private(set) var hookUrl = ""
61
+ private var pendingUrl: String?
62
+ /// An html source never reaches the back-forward list (WebKit hides substitute-data loads from session history):
63
+ /// while the item that was current at its commit stays current, the html page is what is on screen.
64
+ private var htmlNavigation: WKNavigation?
65
+ private var htmlCommit: (url: String, item: WKBackForwardListItem?)?
66
+ /// The URL this view loads itself (source, reload after an error, an allowed new window): it skips the rules.
67
+ var programmaticUrl: URL?
68
+ private(set) lazy var asks = Asks { [weak self] in self?.onHookEvent($0) }
69
+ /// The attached hooks' contexts in attach order, for the life of the WKWebView: a hook may keep its own.
70
+ var hookContexts: [HookContext] = []
71
+ /// URLs an `ask` allowed in this Document, keyed by mainFrame: a subframe's answer doesn't decide the main frame's.
72
+ var askedAndAllowed: [Bool: Set<String>] = [:]
73
+ /// A `source` load is being prepared (shared cookies): loads wait until it is done.
74
+ private var preparing = false
75
+ /// After a failed main-frame load `url` is the failed URL (as on Android, which commits an error page);
76
+ /// WKWebView itself keeps the previous page, so `url` and reload() use this.
77
+ private(set) var failedUrl: String?
78
+ /// How the last load ended, "finished", "failed" or "cancelled"; JS sees it only while nothing loads.
79
+ private var outcome: String?
80
+ private var lastEmitted: NSDictionary?
81
+ private var updateScheduled = false
82
+ private var crashTimes: [TimeInterval] = []
83
+ /// `evaluate` calls waiting for their result, by id, until a new document or a dead web process rejects them.
84
+ var evaluations: [Int: Promise] = [:]
85
+ var nextEvaluation = 0
86
+
87
+ // The origin of the document whose page client last posted, as `location.origin` writes it (`*` when every origin is
88
+ // allowed). RN's messages are delivered only while the page still has it.
89
+ var bridgeOrigin: String?
90
+ // The JS dialog on screen, and how to complete it if it has to go away. WebKit requires exactly one completion.
91
+ // While one is up the page is blocked, and an accessibility query into it (XCTest's) hangs: hide it.
92
+ var dialog: (controller: UIAlertController, cancel: () -> Void)? {
93
+ didSet { webView?.accessibilityElementsHidden = dialog != nil }
94
+ }
95
+
96
+ required init(appContext: AppContext? = nil) {
97
+ super.init(appContext: appContext)
98
+ clipsToBounds = true
99
+ // Made here, not lazily in the deinit fallback's endDocument(.closing), where its closure can't form a weak self.
100
+ _ = asks
101
+ }
102
+
103
+ private var documentOpen = false
104
+
105
+ private func endDocument(_ reason: DocumentEnd) {
106
+ // The first commit after mount or a crash opens a Document and ends none: the asks and hooks don't hear it.
107
+ let opening = reason == .committed && !documentOpen
108
+ documentOpen = reason == .committed
109
+ if !opening { asks.documentEnded(reason) }
110
+ failEvaluations()
111
+ bridgeOrigin = nil
112
+ // JS queues bridge messages until the next page is ready; at unmount it rejects what is in flight itself.
113
+ if reason != .closing, bridgeScript != nil { onBridge(["navigated": true]) }
114
+ askedAndAllowed.removeAll()
115
+ dismissDialog()
116
+ // The spinner belongs to a load, and a crash ends the load without a delegate callback.
117
+ if reason == .crashed { refreshControl.endRefreshing() }
118
+ if !opening { hookContexts.forEach { $0.documentEnded(reason) } }
119
+ }
120
+
121
+ /// Called once per prop batch. `source` loads last so everything else is ready first.
122
+ func applyProps() {
123
+ if webView == nil { createWebView() }
124
+ guard let webView, !preparing else { return }
125
+ report(platformSettings.apply(settings, webView: webView))
126
+ let refresh = pullToRefresh ? refreshControl : nil
127
+ if webView.scrollView.refreshControl !== refresh { webView.scrollView.refreshControl = refresh }
128
+ cookies.set(sharedCookies)
129
+ // Records aren't Equatable: compare their dictionaries.
130
+ guard let next = source, loadedSource != next.toDictionary() as NSDictionary else { return }
131
+ loadedSource = next.toDictionary() as NSDictionary
132
+ // New content from the app: the crash-loop guard starts over (recovery reloads don't come through here).
133
+ crashTimes = []
134
+ preparing = true
135
+ cookies.prepare { [weak self, weak webView] in
136
+ guard let self, let webView, webView === self.webView else { return }
137
+ preparing = false
138
+ load(next)
139
+ // Props that changed while preparing (a newer source) apply now.
140
+ applyProps()
141
+ }
142
+ }
143
+
144
+ private func load(_ source: WebViewSource) {
145
+ if let uri = source.uri, let target = URL(string: uri) {
146
+ var request = URLRequest(url: target)
147
+ source.headers?.forEach { request.setValue($0.value, forHTTPHeaderField: $0.key) }
148
+ if let body = source.body {
149
+ request.httpMethod = "POST"
150
+ request.httpBody = Data(body.utf8)
151
+ if request.value(forHTTPHeaderField: "Content-Type") == nil {
152
+ request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
153
+ }
154
+ }
155
+ loadProgrammatic(request)
156
+ } else {
157
+ htmlNavigation = webView?.loadHTMLString(source.html ?? "", baseURL: source.baseUrl.flatMap(URL.init))
158
+ }
159
+ }
160
+
161
+ /// The page on screen (`url`) is the `source`: its URL, or an html source whose commit no other commit or failed load
162
+ /// has followed.
163
+ private var onSource: Bool {
164
+ guard let source else { return false }
165
+ guard let uri = source.uri.flatMap(URL.init) else { return htmlCommit != nil && failedUrl == nil }
166
+ return Recovery.showsSource(uri.absoluteString, url)
167
+ }
168
+
169
+ /// The page on screen is the POST `source`: it can't be fetched again by URL, so reload loads the source instead.
170
+ private var onPostSource: Bool { source?.body != nil && onSource }
171
+
172
+ /// Settings keys that could not be applied, as warnings: JS logs them with console.warn.
173
+ private func report(_ rejected: [[String: String]]) {
174
+ for entry in rejected {
175
+ warn("ios.\(entry["key"] ?? ""): \(entry["reason"] ?? "")")
176
+ }
177
+ }
178
+
179
+ /// Loads a request the app started, not the page: it skips the navigation rules. A file URL goes through loadFileURL
180
+ /// with the source's read root, so the page's own assets load (load(_:) can't read local files).
181
+ func loadProgrammatic(_ request: URLRequest) {
182
+ programmaticUrl = request.url
183
+ if let url = request.url, url.isFileURL {
184
+ let access = ReadAccess.root(for: url, source?.readAccessRoot)
185
+ if let warning = access.warning { warn(warning) }
186
+ webView?.loadFileURL(url, allowingReadAccessTo: access.root)
187
+ } else {
188
+ webView?.load(request)
189
+ }
190
+ }
191
+
192
+ /// The ref's reload: an explicit retry starts the crash-loop guard over, like a new source. Pull-to-refresh uses
193
+ /// reload().
194
+ func retry() {
195
+ crashTimes = []
196
+ reload()
197
+ }
198
+
199
+ func reload() {
200
+ // WebKit's reload redoes no failed load or POST, and loads nothing while `url` is nil (no commit, a dead process).
201
+ if let webView, webView.url != nil, failedUrl == nil, !onPostSource { webView.reload() } else { loadAgain() }
202
+ }
203
+
204
+ /// The page on screen loaded again, as crash recovery does: the `source` when that is the page or nothing has
205
+ /// committed (with its headers, its POST body or its html, which isn't in the history), else the failed URL, else
206
+ /// the back-forward list's item (a dead web process relaunches with it, so history stays). A `source` being prepared
207
+ /// loads once it is ready instead.
208
+ private func loadAgain() {
209
+ guard let webView, !preparing else { return }
210
+ if let source, onSource || failedUrl == nil && webView.backForwardList.currentItem == nil {
211
+ load(source)
212
+ } else if let failedUrl, let target = URL(string: failedUrl) {
213
+ loadProgrammatic(URLRequest(url: target))
214
+ } else {
215
+ webView.reload()
216
+ }
217
+ }
218
+
219
+ /// The WKWebView, from the first props. `source` loads from applyProps once the load is prepared.
220
+ private func createWebView() {
221
+ let configuration = WKWebViewConfiguration()
222
+ // The creation-time settings (`ios.configuration`) and the configure hooks go first and the bridge after them,
223
+ // so nothing they set displaces the content controller the bridge is installed in.
224
+ report(platformSettings.apply(settings, webView: nil, configuration: configuration))
225
+ hookContexts = MinimalWebViewHooks.hooks.filter { hookOptions[$0.key] != nil }.map { HookContext($0, self) }
226
+ for context in hookContexts { context.hook.configure?(configuration, context) }
227
+ // A typo, or a hook's module not linked or not rebuilt.
228
+ for key in hookOptions.keys where !hookContexts.contains(where: { $0.key == key }) {
229
+ warn("extension \(key): no hook is registered under this key")
230
+ }
231
+ if bridgeScript != nil {
232
+ configuration.userContentController.add(WeakBridgeHandler(self), contentWorld: .page, name: "nativeBridge")
233
+ }
234
+ installScripts(configuration.userContentController)
235
+ let classes = hookContexts.compactMap { context in context.hook.webViewClass.map { (context.key, $0) } }
236
+ let webViewClass = classes.first?.1 ?? WKWebView.self
237
+ for (key, other) in classes where other != webViewClass {
238
+ warn("extension \(key): its webViewClass is not used, \(classes[0].0)'s is")
239
+ }
240
+ let webView = webViewClass.init(frame: bounds, configuration: configuration)
241
+ webView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
242
+ webView.navigationDelegate = proxy
243
+ webView.uiDelegate = proxy
244
+ webView.addGestureRecognizer(taps)
245
+ addSubview(webView)
246
+ let update = { [weak self] in self?.scheduleUpdate() }
247
+ observations = [
248
+ webView.observe(\.url) { _, _ in update() },
249
+ webView.observe(\.isLoading) { _, _ in update() },
250
+ webView.observe(\.title) { _, _ in update() },
251
+ webView.observe(\.estimatedProgress) { _, _ in update() }
252
+ ] + [\WKWebView.canGoBack, \.canGoForward].map { webView.observe($0) { _, _ in update() } }
253
+ self.webView = webView
254
+ cookies.didCreate(webView)
255
+ // The live settings before the hooks, as on Android: what a hook sets wins over the package's defaults.
256
+ report(platformSettings.apply(settings, webView: webView))
257
+ hookContexts.forEach { $0.hook.attach(webView, $0) }
258
+ }
259
+
260
+ /// React Native calls `invalidate` on this view (the Fabric component view; Expo's are never recycled) at every
261
+ /// unmount. Expo's Swift-visible header doesn't declare it, so Swift can't `override` it: declared here, it wins at
262
+ /// runtime, and it calls the inherited one as `super` would.
263
+ @objc func invalidate() {
264
+ tearDown()
265
+ // Expo's (React Native 0.82+) resets its size-update guard; React Native's UIView default does nothing.
266
+ let selector = #selector(invalidate)
267
+ typealias Invalidate = @convention(c) (AnyObject, Selector) -> Void
268
+ guard class_respondsToSelector(ExpoView.self, selector),
269
+ let inherited = class_getMethodImplementation(ExpoView.self, selector) else { return }
270
+ unsafeBitCast(inherited, to: Invalidate.self)(self, selector)
271
+ }
272
+
273
+ /// Once: from invalidate, or from deinit if that never ran.
274
+ private func tearDown() {
275
+ guard let webView else { return }
276
+ endDocument(.closing)
277
+ cookies.detach()
278
+ let closed = hookContexts
279
+ closed.forEach { $0.detach() }
280
+ hookContexts = []
281
+ proxy.navigationDelegates = []
282
+ proxy.uiDelegates = []
283
+ observations.removeAll()
284
+ webView.configuration.userContentController.removeAllScriptMessageHandlers()
285
+ webView.stopLoading()
286
+ // Audio and video otherwise keep playing after unmount (react-native-webview #2449, PR #3234).
287
+ webView.pauseAllMediaPlayback()
288
+ webView.removeFromSuperview()
289
+ closed.forEach { $0.destroyed() }
290
+ self.webView = nil
291
+ htmlCommit = nil
292
+ }
293
+
294
+ deinit {
295
+ // deinit is nonisolated; the view is released on the main thread, as UIKit views are.
296
+ MainActor.assumeIsolated { tearDown() }
297
+ }
298
+
299
+ /// The page on screen: the back-forward list's current item, which a commit creates or moves to a moment before
300
+ /// didCommit (a history step may move it earlier), and pushState/replaceState/hash update.
301
+ private func refreshUrls() {
302
+ guard let webView else { return }
303
+ let item = webView.backForwardList.currentItem
304
+ // Empty before the first commit: the URL being loaded is pendingUrl.
305
+ let committed = htmlCommit.flatMap { $0.item === item ? $0.url : nil } ?? item?.url.absoluteString ?? ""
306
+ url = failedUrl ?? committed
307
+ // WebKit's `url` is the active URL: a pending or provisional load shows here first.
308
+ let active = webView.url?.absoluteString
309
+ pendingUrl = webView.isLoading && active != committed ? active : nil
310
+ if !webView.isLoading, failedUrl != nil || active == committed { hookUrl = url }
311
+ }
312
+
313
+ /// WebKit's KVO fires before the delegate callbacks: the state is read and emitted one main-queue turn later, once
314
+ /// per turn, so changes within one pass are combined into one event. The start of a load goes out at once as well: a
315
+ /// load that starts and fails within one pass must still reach JS as loading true -> false. The end of a load waits
316
+ /// for the pass, because WebKit clears isLoading before it reports the failure (the error and outcome go first).
317
+ private func scheduleUpdate() {
318
+ if let webView, webView.isLoading, lastEmitted?["loading"] as? Bool != true { emitState() }
319
+ guard !updateScheduled else { return }
320
+ updateScheduled = true
321
+ DispatchQueue.main.async { [weak self] in
322
+ guard let self else { return }
323
+ updateScheduled = false
324
+ refreshUrls()
325
+ emitState()
326
+ }
327
+ }
328
+
329
+ private func emitState() {
330
+ guard let webView else { return }
331
+ let state: NSDictionary = [
332
+ "url": url,
333
+ "pendingUrl": pendingUrl as Any? ?? NSNull(),
334
+ "title": webView.title ?? "",
335
+ "loading": webView.isLoading,
336
+ "progress": webView.estimatedProgress,
337
+ "canGoBack": webView.canGoBack,
338
+ "canGoForward": webView.canGoForward,
339
+ "outcome": webView.isLoading ? NSNull() : outcome as Any? ?? NSNull()
340
+ ]
341
+ guard state != lastEmitted else { return }
342
+ lastEmitted = state
343
+ onNavigationState(state as? [String: Any] ?? [:])
344
+ }
345
+
346
+ /// An observation callback the core implements: every hook delegate that implements it gets it after the core.
347
+ private func forward(_ callback: (WKNavigationDelegate) -> Void) {
348
+ proxy.navigationDelegates.forEach(callback)
349
+ }
350
+
351
+ /// A main-frame load WebKit ended with `error`: reports it to onError when it failed (`Loads.ended`), and returns its
352
+ /// outcome.
353
+ private func ended(with error: Error) -> String {
354
+ let nsError = error as NSError
355
+ let end = Loads.ended(by: nsError)
356
+ guard let kind = end.kind else { return end.outcome }
357
+ let failing = (nsError.userInfo[NSURLErrorFailingURLErrorKey] as? URL)?.absoluteString
358
+ ?? nsError.userInfo[NSURLErrorFailingURLStringErrorKey] as? String ?? pendingUrl ?? url
359
+ failedUrl = failing
360
+ onError(["kind": kind, "url": failing, "code": nsError.code, "description": nsError.localizedDescription])
361
+ return end.outcome
362
+ }
363
+
364
+ // MARK: WKNavigationDelegate
365
+
366
+ func webView(
367
+ _ webView: WKWebView,
368
+ decidePolicyFor navigationAction: WKNavigationAction,
369
+ decisionHandler: @escaping @MainActor (WKNavigationActionPolicy) -> Void
370
+ ) {
371
+ decideNavigation(navigationAction, decide: decisionHandler)
372
+ }
373
+
374
+ func webView(
375
+ _ webView: WKWebView,
376
+ decidePolicyFor navigationResponse: WKNavigationResponse,
377
+ decisionHandler: @escaping @MainActor (WKNavigationResponsePolicy) -> Void
378
+ ) {
379
+ if Downloads.isDownload(navigationResponse) {
380
+ if requestHandlers.contains("onDownload") { return decisionHandler(.download) }
381
+ // A file no hook takes (no onDownload).
382
+ if let url = navigationResponse.response.url {
383
+ openDownload(url)
384
+ return decisionHandler(.cancel)
385
+ }
386
+ }
387
+ if navigationResponse.isForMainFrame, let response = navigationResponse.response as? HTTPURLResponse, response.statusCode >= 400 {
388
+ onError(["kind": "http", "url": response.url?.absoluteString ?? "", "statusCode": response.statusCode])
389
+ }
390
+ decisionHandler(.allow)
391
+ }
392
+
393
+ func webView(_ webView: WKWebView, navigationAction: WKNavigationAction, didBecome download: WKDownload) {
394
+ became(download) { $0.webView?(webView, navigationAction: navigationAction, didBecome: download) }
395
+ }
396
+
397
+ func webView(_ webView: WKWebView, navigationResponse: WKNavigationResponse, didBecome download: WKDownload) {
398
+ became(download) { $0.webView?(webView, navigationResponse: navigationResponse, didBecome: download) }
399
+ }
400
+
401
+ private func became(_ download: WKDownload, _ callback: (WKNavigationDelegate) -> Void) {
402
+ if requestHandlers.contains("onDownload") { download.delegate = downloads }
403
+ forward(callback)
404
+ }
405
+
406
+ func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
407
+ endDocument(.committed)
408
+ programmaticUrl = nil
409
+ failedUrl = nil
410
+ htmlCommit = navigation === htmlNavigation
411
+ ? (webView.url?.absoluteString ?? "about:blank", webView.backForwardList.currentItem) : nil
412
+ refreshUrls()
413
+ hookUrl = url
414
+ scheduleUpdate()
415
+ forward { $0.webView?(webView, didCommit: navigation) }
416
+ }
417
+
418
+ func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
419
+ loadEnded { $0.webView?(webView, didFinish: navigation) }
420
+ }
421
+
422
+ func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
423
+ loadEnded(error) { $0.webView?(webView, didFail: navigation, withError: error) }
424
+ }
425
+
426
+ func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
427
+ loadEnded(error) { $0.webView?(webView, didFailProvisionalNavigation: navigation, withError: error) }
428
+ }
429
+
430
+ private func loadEnded(_ error: Error? = nil, _ callback: (WKNavigationDelegate) -> Void) {
431
+ outcome = error.map { ended(with: $0) } ?? "finished"
432
+ // The spinner stops, or it would ignore the next pull.
433
+ refreshControl.endRefreshing()
434
+ scheduleUpdate()
435
+ forward(callback)
436
+ }
437
+
438
+ /// The web content process died. The WKWebView survives it, so reload, unless it keeps crashing.
439
+ /// WebKit does not say whether it crashed or was killed for memory, so its `cause` is `unknown` on iOS.
440
+ func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {
441
+ let recovered = Recovery.crashAllowsReload(&crashTimes, now: ProcessInfo.processInfo.systemUptime) && !onPostSource
442
+ endDocument(.crashed)
443
+ if lastEmitted?["loading"] as? Bool == true { outcome = "failed" } // the load the crash cut off
444
+ if recovered { loadAgain() }
445
+ onProcessGone(["cause": "unknown", "recovered": recovered])
446
+ forward { $0.webViewWebContentProcessDidTerminate?(webView) }
447
+ }
448
+ }
449
+
450
+ /// What the hooks see of this view, through a HookContext per attached hook. The proxy gets the delegates of the
451
+ /// contexts that are on; WebKit reads what a delegate responds to when it is assigned, so each change re-assigns it.
452
+ extension MinimalWebView {
453
+ /// Tells each attached hook whose value changed, and attaches a hook without `configure` or `webViewClass` whose key turns on.
454
+ private func optionsChanged(from old: [String: Any]) {
455
+ for key in inRegistrationOrder(Set(old.keys).union(hookOptions.keys), MinimalWebViewHooks.hooks.map(\.key)) {
456
+ let (was, value) = (old[key], hookOptions[key])
457
+ if staysOn(was, value) { continue }
458
+ if let context = hookContexts.first(where: { $0.key == key }) {
459
+ context.optionsChanged(value)
460
+ } else if was == nil {
461
+ attachLate(key)
462
+ }
463
+ }
464
+ }
465
+
466
+ private func attachLate(_ key: String) {
467
+ guard let webView, let hook = MinimalWebViewHooks.hooks.first(where: { $0.key == key }) else {
468
+ return warn("extension \(key): no hook is registered under this key")
469
+ }
470
+ // configure edits the configuration the WKWebView was created from, and webViewClass makes it: too late for this one.
471
+ guard hook.configure == nil, hook.webViewClass == nil else {
472
+ let why = hook.configure != nil ? "configure" : "a webViewClass"
473
+ return warn("extension \(key): its hook has \(why), so it attaches only when the WebView is created")
474
+ }
475
+ let context = HookContext(hook, self)
476
+ hookContexts.append(context)
477
+ hook.attach(webView, context)
478
+ }
479
+
480
+ func hookHandler(_ key: String, _ method: String) -> (([Any], HookReply) -> Void)? {
481
+ hookContexts.first { $0.key == key && $0.isOn }?.handlers[method]
482
+ }
483
+
484
+ /// Gives the proxy the delegates of the hooks that are on, in attach order, then each hook's own order.
485
+ func routeDelegates() {
486
+ let on = hookContexts.filter(\.isOn)
487
+ proxy.navigationDelegates = on.flatMap(\.navigationDelegates)
488
+ proxy.uiDelegates = on.flatMap(\.uiDelegates)
489
+ webView?.navigationDelegate = nil
490
+ webView?.navigationDelegate = proxy
491
+ webView?.uiDelegate = nil
492
+ webView?.uiDelegate = proxy
493
+ warnDecisions()
494
+ }
495
+
496
+ private func warnDecisions() {
497
+ for name in proxy.sharedDecisions where warnedDecisions.insert(name).inserted {
498
+ warn("\(name): more than one hook delegate implements it; only the first one gets it")
499
+ }
500
+ for (name, lost) in proxy.takenDecisions where warnedDecisions.insert("\(name) taken").inserted {
501
+ warn("\(name): a hook delegate takes it, so \(lost)")
502
+ }
503
+ }
504
+
505
+ func emit(_ key: String, _ name: String, _ payload: [String: Any]) {
506
+ onHookEvent(["key": key, "name": name, "payload": payload])
507
+ }
508
+
509
+ func warn(_ message: String) {
510
+ emit("core", "warning", ["message": message])
511
+ }
512
+ }
@@ -0,0 +1,110 @@
1
+ import ExpoModulesCore
2
+ import WebKit
3
+
4
+ /// The Expo module behind the `MinimalWebView` view; autolinking loads it, and apps don't call it.
5
+ @_documentation(visibility: internal)
6
+ public class MinimalWebViewModule: Module {
7
+ public func definition() -> ModuleDefinition {
8
+ Name("MinimalWebView")
9
+
10
+ // View functions run on the main queue.
11
+ View(MinimalWebView.self) {
12
+ Events("onNavigationState", "onBridge", "onHookEvent", "onError", "onProcessGone", "onNavigation")
13
+
14
+ Prop("source") { (view: MinimalWebView, source: WebViewSource?) in view.source = source }
15
+ Prop("bridgeScript") { (view: MinimalWebView, script: String?) in view.bridgeScript = script }
16
+ Prop("bridgeOrigins") { (view: MinimalWebView, origins: [String]?) in view.bridgeOrigins = origins ?? [] }
17
+ Prop("hookOptions") { (view: MinimalWebView, options: [String: Any]?) in view.hookOptions = options ?? [:] }
18
+ Prop("settings") { (view: MinimalWebView, json: String?) in
19
+ let data = json?.data(using: .utf8) ?? Data()
20
+ view.settings = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] ?? [:]
21
+ }
22
+ Prop("pullToRefresh") { (view: MinimalWebView, value: Bool?) in view.pullToRefresh = value ?? false }
23
+ Prop("sharedCookies") { (view: MinimalWebView, value: Bool?) in view.sharedCookies = value ?? false }
24
+ Prop("navigationRules") { (view: MinimalWebView, rules: [[String: Any]]?) in view.navigationRules = rules }
25
+ Prop("injectedScripts") { (view: MinimalWebView, value: [InjectedScript]?) in view.injectedScripts = value ?? [] }
26
+ Prop("requestHandlers") { (view: MinimalWebView, value: [String]?) in view.requestHandlers = Set(value ?? []) }
27
+
28
+ OnViewDidUpdateProps { (view: MinimalWebView) in view.applyProps() }
29
+
30
+ AsyncFunction("goBack") { (view: MinimalWebView) in view.webView?.goBack() }
31
+ AsyncFunction("goForward") { (view: MinimalWebView) in view.webView?.goForward() }
32
+ AsyncFunction("reload") { (view: MinimalWebView) in view.retry() }
33
+ AsyncFunction("stopLoading") { (view: MinimalWebView) in view.webView?.stopLoading() }
34
+ AsyncFunction("get") { (view: MinimalWebView, path: String, promise: Promise) in
35
+ native(view, promise) { webView in promise.resolve(try view.platformSettings.get(path, webView: webView)) }
36
+ }
37
+ AsyncFunction("call") { (view: MinimalWebView, path: String, argsJson: String, promise: Promise) in
38
+ call(view, path, argsJson, promise)
39
+ }
40
+ AsyncFunction("bridgePost") { (view: MinimalWebView, message: String) in view.bridgePost(message) }
41
+ AsyncFunction("answer") { (view: MinimalWebView, askId: Int, json: String) in
42
+ let value = try? JSONSerialization.jsonObject(with: Data(json.utf8), options: .fragmentsAllowed)
43
+ view.asks.answer(askId, value is NSNull ? nil : value)
44
+ }
45
+ AsyncFunction("hook") { (view: MinimalWebView, name: String, method: String, args: String, promise: Promise) in
46
+ hook(view, name, method, args, promise)
47
+ }
48
+ AsyncFunction("evaluate") { (view: MinimalWebView, script: String, promise: Promise) in
49
+ view.evaluate(script, promise)
50
+ }
51
+ }
52
+ }
53
+ }
54
+
55
+ private func call(_ view: MinimalWebView, _ path: String, _ argsJson: String, _ promise: Promise) {
56
+ let args = (try? JSONSerialization.jsonObject(with: Data(argsJson.utf8))) as? [Any] ?? []
57
+ native(view, promise) { webView in
58
+ try view.platformSettings.call(path, args: args, webView: webView) { json, error in
59
+ if let error { promise.reject("native_error", error) } else { promise.resolve(json) }
60
+ }
61
+ }
62
+ }
63
+
64
+ private func hook(_ view: MinimalWebView, _ name: String, _ method: String, _ args: String, _ promise: Promise) {
65
+ guard let handler = view.hookHandler(name, method) else {
66
+ return promise.reject("not_found", "no attached hook `\(name)` handles `\(method)`")
67
+ }
68
+ let reply = HookReply(
69
+ resolve: { value in
70
+ do {
71
+ promise.resolve(try PlatformSettings.json { __MRWJsonable(value) })
72
+ } catch {
73
+ reject(promise, error)
74
+ }
75
+ },
76
+ reject: { promise.reject("handler_error", $0) }
77
+ )
78
+ handler((try? JSONSerialization.jsonObject(with: Data(args.utf8))) as? [Any] ?? [], reply)
79
+ }
80
+
81
+ private func native(_ view: MinimalWebView, _ promise: Promise, _ body: (WKWebView) throws -> Void) {
82
+ guard let webView = view.webView else { return promise.reject("unavailable", "No WebView") }
83
+ do {
84
+ try body(webView)
85
+ } catch {
86
+ reject(promise, error)
87
+ }
88
+ }
89
+
90
+ private func reject(_ promise: Promise, _ error: Error) {
91
+ let platform = error as? PlatformError
92
+ promise.reject(platform?.code ?? "native_error", platform?.message ?? error.localizedDescription)
93
+ }
94
+
95
+ // A prop that fails to convert is dropped whole (ExpoFabricView's try?), so every field is optional.
96
+
97
+ struct WebViewSource: Record {
98
+ @Field var uri: String? = nil
99
+ @Field var headers: [String: String]? = nil
100
+ @Field var body: String? = nil
101
+ @Field var readAccessRoot: String? = nil
102
+ @Field var html: String? = nil
103
+ @Field var baseUrl: String? = nil
104
+ }
105
+
106
+ struct InjectedScript: Record {
107
+ @Field var code: String? = nil
108
+ @Field var allFrames: Bool? = nil
109
+ }
110
+