react-native-minimal-webview 0.0.0-stage → 1.0.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 (118) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +150 -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 +487 -0
  9. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebView.kt +507 -0
  10. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewClients.kt +358 -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 +197 -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 +303 -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 +259 -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 +96 -0
  22. package/build/WebView.d.ts.map +1 -0
  23. package/build/WebView.js +453 -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 +137 -0
  28. package/build/bridge/createBridge.js.map +1 -0
  29. package/build/bridge/endpoint.d.ts +33 -0
  30. package/build/bridge/endpoint.d.ts.map +1 -0
  31. package/build/bridge/endpoint.js +105 -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 +59 -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 +15 -0
  46. package/build/defaultNavigationRules.d.ts.map +1 -0
  47. package/build/defaultNavigationRules.js +22 -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 +701 -0
  54. package/build/platform.generated.d.ts.map +1 -0
  55. package/build/platform.generated.js +201 -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 +16 -0
  62. package/build/reactNativeWebViewMessages.d.ts.map +1 -0
  63. package/build/reactNativeWebViewMessages.js +24 -0
  64. package/build/reactNativeWebViewMessages.js.map +1 -0
  65. package/build/refStore.d.ts +32 -0
  66. package/build/refStore.d.ts.map +1 -0
  67. package/build/refStore.js +115 -0
  68. package/build/refStore.js.map +1 -0
  69. package/build/types.d.ts +1173 -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 +158 -0
  80. package/ios/DocumentEnd.swift +22 -0
  81. package/ios/DownloadName.swift +10 -0
  82. package/ios/Downloads.swift +51 -0
  83. package/ios/Hooks.swift +310 -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 +38 -0
  88. package/ios/MRWInvoke.m +187 -0
  89. package/ios/MinimalWebView+Dialogs.swift +96 -0
  90. package/ios/MinimalWebView+Navigation.swift +243 -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 +513 -0
  95. package/ios/MinimalWebViewModule.swift +110 -0
  96. package/ios/NavigationRules.swift +123 -0
  97. package/ios/OriginRules.swift +36 -0
  98. package/ios/PlatformCompletions.generated.swift +39 -0
  99. package/ios/PlatformSettings.swift +252 -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 +99 -4
  104. package/src/WebView.tsx +626 -0
  105. package/src/bridge/createBridge.ts +178 -0
  106. package/src/bridge/endpoint.ts +123 -0
  107. package/src/bridge/origins.ts +61 -0
  108. package/src/bridge/pageClient.generated.ts +5 -0
  109. package/src/bridge/pageClient.ts +67 -0
  110. package/src/bridge/protocol.ts +78 -0
  111. package/src/defaultNavigationRules.ts +24 -0
  112. package/src/index.ts +37 -0
  113. package/src/platform.generated.ts +693 -0
  114. package/src/reactNativeWebViewDefaults.ts +13 -0
  115. package/src/reactNativeWebViewMessages.ts +26 -0
  116. package/src/refStore.ts +165 -0
  117. package/src/types.defaults.ts +24 -0
  118. package/src/types.ts +1240 -0
@@ -0,0 +1,513 @@
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, see the file_length reason above
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 (see `webView`).
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). JS'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 (see `programmaticUrl`). A file URL goes through loadFileURL with the source's read
180
+ /// 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
+ /// Loads the page on screen again, as crash recovery does. In order:
205
+ /// - the `source`, when it is the page or nothing has committed (so its headers, POST body or html are used);
206
+ /// - else the failed URL;
207
+ /// - else the back-forward list's item (a dead web process relaunches with it, so history stays).
208
+ /// A `source` being prepared loads once it is ready instead.
209
+ private func loadAgain() {
210
+ guard let webView, !preparing else { return }
211
+ if let source, onSource || failedUrl == nil && webView.backForwardList.currentItem == nil {
212
+ load(source)
213
+ } else if let failedUrl, let target = URL(string: failedUrl) {
214
+ loadProgrammatic(URLRequest(url: target))
215
+ } else {
216
+ webView.reload()
217
+ }
218
+ }
219
+
220
+ /// `source` loads from applyProps once the load is prepared.
221
+ private func createWebView() {
222
+ let configuration = WKWebViewConfiguration()
223
+ // The creation-time settings (`ios.configuration`) and the configure hooks go first and the bridge after them,
224
+ // so nothing they set displaces the content controller the bridge is installed in.
225
+ report(platformSettings.apply(settings, webView: nil, configuration: configuration))
226
+ hookContexts = MinimalWebViewHooks.hooks.filter { hookOptions[$0.key] != nil }.map { HookContext($0, self) }
227
+ for context in hookContexts { context.hook.configure?(configuration, context) }
228
+ // A typo, or a hook's module not linked or not rebuilt.
229
+ for key in hookOptions.keys where !hookContexts.contains(where: { $0.key == key }) {
230
+ warn("extension \(key): no hook is registered under this key")
231
+ }
232
+ if bridgeScript != nil {
233
+ configuration.userContentController.add(WeakBridgeHandler(self), contentWorld: .page, name: "nativeBridge")
234
+ }
235
+ installScripts(configuration.userContentController)
236
+ let classes = hookContexts.compactMap { context in context.hook.webViewClass.map { (context.key, $0) } }
237
+ let webViewClass = classes.first?.1 ?? WKWebView.self
238
+ for (key, other) in classes where other != webViewClass {
239
+ warn("extension \(key): its webViewClass is not used, \(classes[0].0)'s is")
240
+ }
241
+ let webView = webViewClass.init(frame: bounds, configuration: configuration)
242
+ webView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
243
+ webView.navigationDelegate = proxy
244
+ webView.uiDelegate = proxy
245
+ webView.addGestureRecognizer(taps)
246
+ addSubview(webView)
247
+ let update = { [weak self] in self?.scheduleUpdate() }
248
+ observations = [
249
+ webView.observe(\.url) { _, _ in update() },
250
+ webView.observe(\.isLoading) { _, _ in update() },
251
+ webView.observe(\.title) { _, _ in update() },
252
+ webView.observe(\.estimatedProgress) { _, _ in update() }
253
+ ] + [\WKWebView.canGoBack, \.canGoForward].map { webView.observe($0) { _, _ in update() } }
254
+ self.webView = webView
255
+ cookies.didCreate(webView)
256
+ // The live settings before the hooks, as on Android: what a hook sets wins over the package's defaults.
257
+ report(platformSettings.apply(settings, webView: webView))
258
+ hookContexts.forEach { $0.hook.attach(webView, $0) }
259
+ }
260
+
261
+ /// React Native calls `invalidate` on this view (the Fabric component view; Expo's are never recycled) at every
262
+ /// unmount. Expo's Swift-visible header doesn't declare it, so Swift can't `override` it: declared here, it wins at
263
+ /// runtime, and it calls the inherited one as `super` would.
264
+ @objc func invalidate() {
265
+ tearDown()
266
+ // Expo's (React Native 0.82+) resets its size-update guard; React Native's UIView default does nothing.
267
+ let selector = #selector(invalidate)
268
+ typealias Invalidate = @convention(c) (AnyObject, Selector) -> Void
269
+ guard class_respondsToSelector(ExpoView.self, selector),
270
+ let inherited = class_getMethodImplementation(ExpoView.self, selector) else { return }
271
+ unsafeBitCast(inherited, to: Invalidate.self)(self, selector)
272
+ }
273
+
274
+ /// Once: from invalidate, or from deinit if that never ran.
275
+ private func tearDown() {
276
+ guard let webView else { return }
277
+ endDocument(.closing)
278
+ cookies.detach()
279
+ let closed = hookContexts
280
+ closed.forEach { $0.detach() }
281
+ hookContexts = []
282
+ proxy.navigationDelegates = []
283
+ proxy.uiDelegates = []
284
+ observations.removeAll()
285
+ webView.configuration.userContentController.removeAllScriptMessageHandlers()
286
+ webView.stopLoading()
287
+ // Audio and video otherwise keep playing after unmount (react-native-webview #2449, PR #3234).
288
+ webView.pauseAllMediaPlayback()
289
+ webView.removeFromSuperview()
290
+ closed.forEach { $0.destroyed() }
291
+ self.webView = nil
292
+ htmlCommit = nil
293
+ }
294
+
295
+ deinit {
296
+ // deinit is nonisolated; the view is released on the main thread, as UIKit views are.
297
+ MainActor.assumeIsolated { tearDown() }
298
+ }
299
+
300
+ /// The page on screen: the back-forward list's current item, which a commit creates or moves to a moment before
301
+ /// didCommit (a history step may move it earlier), and pushState/replaceState/hash update.
302
+ private func refreshUrls() {
303
+ guard let webView else { return }
304
+ let item = webView.backForwardList.currentItem
305
+ // Empty before the first commit: the URL being loaded is pendingUrl.
306
+ let committed = htmlCommit.flatMap { $0.item === item ? $0.url : nil } ?? item?.url.absoluteString ?? ""
307
+ url = failedUrl ?? committed
308
+ // WebKit's `url` is the active URL: a pending or provisional load shows here first.
309
+ let active = webView.url?.absoluteString
310
+ pendingUrl = webView.isLoading && active != committed ? active : nil
311
+ if !webView.isLoading, failedUrl != nil || active == committed { hookUrl = url }
312
+ }
313
+
314
+ /// WebKit's KVO fires before the delegate callbacks: the state is read and emitted one main-queue turn later, once
315
+ /// per turn, so changes within one pass are combined into one event. The start of a load goes out at once as well: a
316
+ /// load that starts and fails within one pass must still reach JS as loading true -> false. The end of a load waits
317
+ /// for the pass, because WebKit clears isLoading before it reports the failure (the error and outcome go first).
318
+ private func scheduleUpdate() {
319
+ if let webView, webView.isLoading, lastEmitted?["loading"] as? Bool != true { emitState() }
320
+ guard !updateScheduled else { return }
321
+ updateScheduled = true
322
+ DispatchQueue.main.async { [weak self] in
323
+ guard let self else { return }
324
+ updateScheduled = false
325
+ refreshUrls()
326
+ emitState()
327
+ }
328
+ }
329
+
330
+ private func emitState() {
331
+ guard let webView else { return }
332
+ let state: NSDictionary = [
333
+ "url": url,
334
+ "pendingUrl": pendingUrl as Any? ?? NSNull(),
335
+ "title": webView.title ?? "",
336
+ "loading": webView.isLoading,
337
+ "progress": webView.estimatedProgress,
338
+ "canGoBack": webView.canGoBack,
339
+ "canGoForward": webView.canGoForward,
340
+ "outcome": webView.isLoading ? NSNull() : outcome as Any? ?? NSNull()
341
+ ]
342
+ guard state != lastEmitted else { return }
343
+ lastEmitted = state
344
+ onNavigationState(state as? [String: Any] ?? [:])
345
+ }
346
+
347
+ /// An observation callback the core implements: every hook delegate that implements it gets it after the core.
348
+ private func forward(_ callback: (WKNavigationDelegate) -> Void) {
349
+ proxy.navigationDelegates.forEach(callback)
350
+ }
351
+
352
+ /// A main-frame load WebKit ended with `error`: reports it to onError when it failed (`Loads.ended`), and returns its
353
+ /// outcome.
354
+ private func ended(with error: Error) -> String {
355
+ let nsError = error as NSError
356
+ let end = Loads.ended(by: nsError)
357
+ guard let kind = end.kind else { return end.outcome }
358
+ let failing = (nsError.userInfo[NSURLErrorFailingURLErrorKey] as? URL)?.absoluteString
359
+ ?? nsError.userInfo[NSURLErrorFailingURLStringErrorKey] as? String ?? pendingUrl ?? url
360
+ failedUrl = failing
361
+ onError(["kind": kind, "url": failing, "code": nsError.code, "description": nsError.localizedDescription])
362
+ return end.outcome
363
+ }
364
+
365
+ // MARK: WKNavigationDelegate
366
+
367
+ func webView(
368
+ _ webView: WKWebView,
369
+ decidePolicyFor navigationAction: WKNavigationAction,
370
+ decisionHandler: @escaping @MainActor (WKNavigationActionPolicy) -> Void
371
+ ) {
372
+ decideNavigation(navigationAction, decide: decisionHandler)
373
+ }
374
+
375
+ func webView(
376
+ _ webView: WKWebView,
377
+ decidePolicyFor navigationResponse: WKNavigationResponse,
378
+ decisionHandler: @escaping @MainActor (WKNavigationResponsePolicy) -> Void
379
+ ) {
380
+ if Downloads.isDownload(navigationResponse) {
381
+ if requestHandlers.contains("onDownload") { return decisionHandler(.download) }
382
+ // A file no hook takes (no onDownload).
383
+ if let url = navigationResponse.response.url {
384
+ openDownload(url)
385
+ return decisionHandler(.cancel)
386
+ }
387
+ }
388
+ if navigationResponse.isForMainFrame, let response = navigationResponse.response as? HTTPURLResponse, response.statusCode >= 400 {
389
+ onError(["kind": "http", "url": response.url?.absoluteString ?? "", "statusCode": response.statusCode])
390
+ }
391
+ decisionHandler(.allow)
392
+ }
393
+
394
+ func webView(_ webView: WKWebView, navigationAction: WKNavigationAction, didBecome download: WKDownload) {
395
+ became(download) { $0.webView?(webView, navigationAction: navigationAction, didBecome: download) }
396
+ }
397
+
398
+ func webView(_ webView: WKWebView, navigationResponse: WKNavigationResponse, didBecome download: WKDownload) {
399
+ became(download) { $0.webView?(webView, navigationResponse: navigationResponse, didBecome: download) }
400
+ }
401
+
402
+ private func became(_ download: WKDownload, _ callback: (WKNavigationDelegate) -> Void) {
403
+ if requestHandlers.contains("onDownload") { download.delegate = downloads }
404
+ forward(callback)
405
+ }
406
+
407
+ func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
408
+ endDocument(.committed)
409
+ programmaticUrl = nil
410
+ failedUrl = nil
411
+ htmlCommit = navigation === htmlNavigation
412
+ ? (webView.url?.absoluteString ?? "about:blank", webView.backForwardList.currentItem) : nil
413
+ refreshUrls()
414
+ hookUrl = url
415
+ scheduleUpdate()
416
+ forward { $0.webView?(webView, didCommit: navigation) }
417
+ }
418
+
419
+ func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
420
+ loadEnded { $0.webView?(webView, didFinish: navigation) }
421
+ }
422
+
423
+ func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
424
+ loadEnded(error) { $0.webView?(webView, didFail: navigation, withError: error) }
425
+ }
426
+
427
+ func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
428
+ loadEnded(error) { $0.webView?(webView, didFailProvisionalNavigation: navigation, withError: error) }
429
+ }
430
+
431
+ private func loadEnded(_ error: Error? = nil, _ callback: (WKNavigationDelegate) -> Void) {
432
+ outcome = error.map { ended(with: $0) } ?? "finished"
433
+ // The spinner stops, or it would ignore the next pull.
434
+ refreshControl.endRefreshing()
435
+ scheduleUpdate()
436
+ forward(callback)
437
+ }
438
+
439
+ /// The web content process died. The WKWebView survives it, so reload, unless it keeps crashing.
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
+ // WebKit doesn't say whether it crashed or was killed for memory
446
+ onProcessGone(["cause": "unknown", "recovered": recovered])
447
+ forward { $0.webViewWebContentProcessDidTerminate?(webView) }
448
+ }
449
+ }
450
+
451
+ /// What the hooks see of this view, through a HookContext per attached hook. The proxy gets the delegates of the
452
+ /// contexts that are on; WebKit reads what a delegate responds to when it is assigned, so each change re-assigns it.
453
+ extension MinimalWebView {
454
+ /// Tells each attached hook whose value changed, and attaches a hook without `configure` or `webViewClass` whose key turns on.
455
+ private func optionsChanged(from old: [String: Any]) {
456
+ for key in inRegistrationOrder(Set(old.keys).union(hookOptions.keys), MinimalWebViewHooks.hooks.map(\.key)) {
457
+ let (was, value) = (old[key], hookOptions[key])
458
+ if staysOn(was, value) { continue }
459
+ if let context = hookContexts.first(where: { $0.key == key }) {
460
+ context.optionsChanged(value)
461
+ } else if was == nil {
462
+ attachLate(key)
463
+ }
464
+ }
465
+ }
466
+
467
+ private func attachLate(_ key: String) {
468
+ guard let webView, let hook = MinimalWebViewHooks.hooks.first(where: { $0.key == key }) else {
469
+ return warn("extension \(key): no hook is registered under this key")
470
+ }
471
+ // configure edits the configuration the WKWebView was created from, and webViewClass makes it: too late for this one.
472
+ guard hook.configure == nil, hook.webViewClass == nil else {
473
+ let why = hook.configure != nil ? "configure" : "a webViewClass"
474
+ return warn("extension \(key): its hook has \(why), so it attaches only when the WebView is created")
475
+ }
476
+ let context = HookContext(hook, self)
477
+ hookContexts.append(context)
478
+ hook.attach(webView, context)
479
+ }
480
+
481
+ func hookHandler(_ key: String, _ method: String) -> (([Any], HookReply) -> Void)? {
482
+ hookContexts.first { $0.key == key && $0.isOn }?.handlers[method]
483
+ }
484
+
485
+ /// Gives the proxy the delegates of the hooks that are on, in attach order, then each hook's own order.
486
+ func routeDelegates() {
487
+ let on = hookContexts.filter(\.isOn)
488
+ proxy.navigationDelegates = on.flatMap(\.navigationDelegates)
489
+ proxy.uiDelegates = on.flatMap(\.uiDelegates)
490
+ webView?.navigationDelegate = nil
491
+ webView?.navigationDelegate = proxy
492
+ webView?.uiDelegate = nil
493
+ webView?.uiDelegate = proxy
494
+ warnDecisions()
495
+ }
496
+
497
+ private func warnDecisions() {
498
+ for name in proxy.sharedDecisions where warnedDecisions.insert(name).inserted {
499
+ warn("\(name): more than one hook delegate implements it; only the first one gets it")
500
+ }
501
+ for (name, lost) in proxy.takenDecisions where warnedDecisions.insert("\(name) taken").inserted {
502
+ warn("\(name): a hook delegate takes it, so \(lost)")
503
+ }
504
+ }
505
+
506
+ func emit(_ key: String, _ name: String, _ payload: [String: Any]) {
507
+ onHookEvent(["key": key, "name": name, "payload": payload])
508
+ }
509
+
510
+ func warn(_ message: String) {
511
+ emit("core", "warning", ["message": message])
512
+ }
513
+ }
@@ -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
+