react-native-minimal-webview 1.1.0 → 1.2.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 (70) hide show
  1. package/android/src/main/java/expo/modules/minimalwebview/Hooks.kt +1 -6
  2. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebView.kt +34 -22
  3. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewClients.kt +3 -2
  4. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewModule.kt +2 -1
  5. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewNavigation.kt +3 -3
  6. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewScripts.kt +5 -7
  7. package/android/src/main/java/expo/modules/minimalwebview/PlatformSettings.kt +29 -34
  8. package/android/src/main/java/expo/modules/minimalwebview/PullToRefresh.kt +2 -2
  9. package/android/src/main/java/expo/modules/minimalwebview/requests/Downloads.kt +7 -8
  10. package/android/src/main/java/expo/modules/minimalwebview/requests/FullscreenVideo.kt +2 -2
  11. package/android/src/main/java/expo/modules/minimalwebview/requests/Permissions.kt +4 -5
  12. package/build/WebView.d.ts +1 -9
  13. package/build/WebView.d.ts.map +1 -1
  14. package/build/WebView.js +37 -100
  15. package/build/WebView.js.map +1 -1
  16. package/build/bridge/createBridge.d.ts +17 -11
  17. package/build/bridge/createBridge.d.ts.map +1 -1
  18. package/build/bridge/createBridge.js +32 -44
  19. package/build/bridge/createBridge.js.map +1 -1
  20. package/build/bridge/endpoint.d.ts +1 -3
  21. package/build/bridge/endpoint.d.ts.map +1 -1
  22. package/build/bridge/endpoint.js +2 -2
  23. package/build/bridge/endpoint.js.map +1 -1
  24. package/build/bridge/origins.d.ts +5 -2
  25. package/build/bridge/origins.d.ts.map +1 -1
  26. package/build/bridge/origins.js +15 -4
  27. package/build/bridge/origins.js.map +1 -1
  28. package/build/bridge/pageClient.generated.d.ts +1 -1
  29. package/build/bridge/pageClient.generated.d.ts.map +1 -1
  30. package/build/bridge/pageClient.generated.js +1 -1
  31. package/build/bridge/pageClient.generated.js.map +1 -1
  32. package/build/index.d.ts +1 -1
  33. package/build/index.d.ts.map +1 -1
  34. package/build/index.js +1 -1
  35. package/build/index.js.map +1 -1
  36. package/build/{defaultNavigationRules.d.ts → navigationRules.d.ts} +10 -1
  37. package/build/navigationRules.d.ts.map +1 -0
  38. package/build/navigationRules.js +93 -0
  39. package/build/navigationRules.js.map +1 -0
  40. package/build/refStore.d.ts.map +1 -1
  41. package/build/refStore.js +13 -17
  42. package/build/refStore.js.map +1 -1
  43. package/build/types.d.ts +39 -16
  44. package/build/types.d.ts.map +1 -1
  45. package/ios/DelegateProxy.swift +32 -30
  46. package/ios/Loads.swift +4 -4
  47. package/ios/MRWInvoke.h +8 -0
  48. package/ios/MRWInvoke.m +39 -24
  49. package/ios/MinimalWebView+Navigation.swift +17 -14
  50. package/ios/MinimalWebView.swift +72 -28
  51. package/ios/MinimalWebViewModule.swift +1 -0
  52. package/ios/NavigationRules.swift +15 -15
  53. package/ios/PlatformSettings.swift +2 -13
  54. package/ios/SharedCookies.swift +1 -2
  55. package/package.json +1 -1
  56. package/src/WebView.tsx +50 -114
  57. package/src/bridge/createBridge.ts +45 -53
  58. package/src/bridge/endpoint.ts +3 -5
  59. package/src/bridge/origins.ts +18 -6
  60. package/src/bridge/pageClient.generated.ts +1 -1
  61. package/src/index.ts +1 -1
  62. package/src/navigationRules.ts +111 -0
  63. package/src/refStore.ts +15 -19
  64. package/src/types.ts +39 -16
  65. package/build/defaultNavigationRules.d.ts.map +0 -1
  66. package/build/defaultNavigationRules.js +0 -22
  67. package/build/defaultNavigationRules.js.map +0 -1
  68. package/ios/MRWExceptions.h +0 -9
  69. package/ios/MRWExceptions.m +0 -10
  70. package/src/defaultNavigationRules.ts +0 -24
package/ios/MRWInvoke.h CHANGED
@@ -2,6 +2,10 @@
2
2
 
3
3
  NS_ASSUME_NONNULL_BEGIN
4
4
 
5
+ /// Runs `block` and returns the Objective-C exception it raised as `name: reason`, or nil. Swift can't catch those;
6
+ /// Key-Value Coding raises one for an unknown key or a value a setter rejects.
7
+ FOUNDATION_EXPORT NSString *_Nullable MRWCatchException(void (NS_NOESCAPE ^block)(void)) NS_REFINED_FOR_SWIFT;
8
+
5
9
  /// Calls `selector` on `target` with the JSON `args` and resolves with the result as `MRWJsonable` makes it, or with
6
10
  /// why it couldn't.
7
11
  ///
@@ -28,4 +32,8 @@ FOUNDATION_EXPORT void MRWInvoke(id target, SEL selector, NSArray *args, NSStrin
28
32
  /// `value` as JSON, in the forms WebViewRef.call's @returns lists; anything else, and nil, is null.
29
33
  FOUNDATION_EXPORT id MRWJsonable(id _Nullable value) NS_REFINED_FOR_SWIFT;
30
34
 
35
+ /// `json` as the struct the type encoding `type` names, in the forms WebViewRef.call's @param lists; nil for another
36
+ /// type or a value that doesn't fit.
37
+ FOUNDATION_EXPORT NSValue *_Nullable MRWStructValue(const char *type, id json) NS_REFINED_FOR_SWIFT;
38
+
31
39
  NS_ASSUME_NONNULL_END
package/ios/MRWInvoke.m CHANGED
@@ -1,22 +1,35 @@
1
1
  #import "MRWInvoke.h"
2
- #import "MRWExceptions.h"
3
2
  #import <UIKit/UIKit.h>
4
3
 
5
- static NSDictionary *MRWStruct(NSValue *value) {
6
- const char *type = value.objCType;
7
- if (strcmp(type, @encode(UIEdgeInsets)) == 0) {
8
- UIEdgeInsets i = value.UIEdgeInsetsValue;
9
- return @{@"top": @(i.top), @"left": @(i.left), @"bottom": @(i.bottom), @"right": @(i.right)};
10
- }
11
- if (strcmp(type, @encode(CGPoint)) == 0) return @{@"x": @(value.CGPointValue.x), @"y": @(value.CGPointValue.y)};
12
- if (strcmp(type, @encode(CGSize)) == 0) return @{@"width": @(value.CGSizeValue.width), @"height": @(value.CGSizeValue.height)};
13
- if (strcmp(type, @encode(CGRect)) == 0) {
14
- CGRect r = value.CGRectValue;
15
- return @{@"x": @(r.origin.x), @"y": @(r.origin.y), @"width": @(r.size.width), @"height": @(r.size.height)};
4
+ NSString *MRWCatchException(void (NS_NOESCAPE ^block)(void)) {
5
+ @try {
6
+ block();
7
+ return nil;
8
+ } @catch (NSException *exception) {
9
+ return [NSString stringWithFormat:@"%@: %@", exception.name, exception.reason ?: @""];
16
10
  }
11
+ }
12
+
13
+ /// The JSON keys of a struct `call` and the settings carry, in field order, by its type encoding; nil for any other.
14
+ /// Each one's fields are doubles (CGFloat), so its bytes are the values in that order.
15
+ static NSArray<NSString *> *MRWStructKeys(const char *type) {
16
+ if (strcmp(type, @encode(UIEdgeInsets)) == 0) return @[@"top", @"left", @"bottom", @"right"];
17
+ if (strcmp(type, @encode(CGPoint)) == 0) return @[@"x", @"y"];
18
+ if (strcmp(type, @encode(CGSize)) == 0) return @[@"width", @"height"];
19
+ if (strcmp(type, @encode(CGRect)) == 0) return @[@"x", @"y", @"width", @"height"];
17
20
  return nil;
18
21
  }
19
22
 
23
+ static NSDictionary *MRWStruct(NSValue *value) {
24
+ NSArray<NSString *> *keys = MRWStructKeys(value.objCType);
25
+ if (!keys) return nil;
26
+ double n[4];
27
+ [value getValue:n size:keys.count * sizeof(double)];
28
+ NSMutableDictionary *json = [NSMutableDictionary new];
29
+ for (NSUInteger i = 0; i < keys.count; i++) json[keys[i]] = @(n[i]);
30
+ return json;
31
+ }
32
+
20
33
  id MRWJsonable(id value) {
21
34
  if ([value isKindOfClass:NSNumber.class] || [value isKindOfClass:NSString.class]) return value;
22
35
  if ([value isKindOfClass:NSURL.class]) return [value absoluteString];
@@ -56,9 +69,9 @@ static id MRWObject(id json) {
56
69
  return json;
57
70
  }
58
71
 
59
- /// Reads `keys` of `object` as numbers into `out`; NO when one is missing or not a number.
72
+ /// Reads `keys` of `object` as numbers into `out`; NO when `keys` is nil or one is missing or not a number.
60
73
  static BOOL MRWNumbers(id object, NSArray<NSString *> *keys, double *out) {
61
- if (![object isKindOfClass:NSDictionary.class]) return NO;
74
+ if (!keys || ![object isKindOfClass:NSDictionary.class]) return NO;
62
75
  for (NSUInteger i = 0; i < keys.count; i++) {
63
76
  id number = object[keys[i]];
64
77
  if (![number isKindOfClass:NSNumber.class]) return NO;
@@ -67,6 +80,11 @@ static BOOL MRWNumbers(id object, NSArray<NSString *> *keys, double *out) {
67
80
  return YES;
68
81
  }
69
82
 
83
+ NSValue *MRWStructValue(const char *type, id json) {
84
+ double n[4];
85
+ return MRWNumbers(json, MRWStructKeys(type), n) ? [NSValue valueWithBytes:n objCType:type] : nil;
86
+ }
87
+
70
88
  #define MRW_SET(ctype, expr) { ctype v = (expr); [invocation setArgument:&v atIndex:index]; return YES; }
71
89
 
72
90
  /// Sets argument `index` from the JSON `value` as the type encoding `type` wants it, or returns NO when it doesn't fit.
@@ -96,10 +114,7 @@ static BOOL MRWSetArgument(NSInvocation *invocation, NSUInteger index, const cha
96
114
  MRW_SET(id, object)
97
115
  }
98
116
  case '{':
99
- if (strcmp(type, @encode(UIEdgeInsets)) == 0 && MRWNumbers(value, @[@"top", @"left", @"bottom", @"right"], n)) MRW_SET(UIEdgeInsets, UIEdgeInsetsMake(n[0], n[1], n[2], n[3]))
100
- if (strcmp(type, @encode(CGPoint)) == 0 && MRWNumbers(value, @[@"x", @"y"], n)) MRW_SET(CGPoint, CGPointMake(n[0], n[1]))
101
- if (strcmp(type, @encode(CGSize)) == 0 && MRWNumbers(value, @[@"width", @"height"], n)) MRW_SET(CGSize, CGSizeMake(n[0], n[1]))
102
- if (strcmp(type, @encode(CGRect)) == 0 && MRWNumbers(value, @[@"x", @"y", @"width", @"height"], n)) MRW_SET(CGRect, CGRectMake(n[0], n[1], n[2], n[3]))
117
+ if (MRWNumbers(value, MRWStructKeys(type), n)) { [invocation setArgument:n atIndex:index]; return YES; }
103
118
  break;
104
119
  default: break;
105
120
  }
@@ -125,12 +140,12 @@ static id MRWReturnValue(NSInvocation *invocation) {
125
140
  case 'f': MRW_GET(float, @(v))
126
141
  case 'd': MRW_GET(double, @(v))
127
142
  case '@': { __unsafe_unretained id v = nil; [invocation getReturnValue:&v]; return v; }
128
- case '{':
129
- if (strcmp(type, @encode(UIEdgeInsets)) == 0) MRW_GET(UIEdgeInsets, [NSValue valueWithUIEdgeInsets:v])
130
- if (strcmp(type, @encode(CGPoint)) == 0) MRW_GET(CGPoint, [NSValue valueWithCGPoint:v])
131
- if (strcmp(type, @encode(CGSize)) == 0) MRW_GET(CGSize, [NSValue valueWithCGSize:v])
132
- if (strcmp(type, @encode(CGRect)) == 0) MRW_GET(CGRect, [NSValue valueWithCGRect:v])
133
- return NSNull.null;
143
+ case '{': {
144
+ if (!MRWStructKeys(type)) return NSNull.null;
145
+ double n[4];
146
+ [invocation getReturnValue:n];
147
+ return [NSValue valueWithBytes:n objCType:type];
148
+ }
134
149
  default: return NSNull.null;
135
150
  }
136
151
  }
@@ -11,10 +11,11 @@ extension MinimalWebView {
11
11
  // rules, as on Android (shouldOverrideUrlLoading is not called for them).
12
12
  guard let targetFrame = action.targetFrame else { return decide(allowInPlace) }
13
13
  let mainFrame = targetFrame.isMainFrame
14
- let own = mainFrame && programmaticUrl.map { Loads.sameURL($0, target) } == true
15
- if own || action.navigationType == .backForward || action.navigationType == .reload
14
+ if mainFrame { mainFrameChecks += 1 }
15
+ let own = mainFrame ? ownLoads.firstIndex { Loads.sameURL($0.url, target) } : nil
16
+ if own != nil || action.navigationType == .backForward || action.navigationType == .reload
16
17
  || action.request.httpMethod == "POST" {
17
- if own { programmaticUrl = nil }
18
+ if let own { ownLoads.remove(at: own) }
18
19
  return decide(allowInPlace)
19
20
  }
20
21
  let request = NavigationRules.Request(
@@ -47,7 +48,7 @@ extension MinimalWebView {
47
48
  func openDownload(_ url: URL) {
48
49
  guard ["http", "https"].contains(url.scheme?.lowercased()) else { return }
49
50
  let request = NavigationRules.Request(url: url.absoluteString, mainFrame: true, newWindow: false, userInitiated: false)
50
- finish(request, "external", nil) { _ in }
51
+ finish(request, .external, nil) { _ in }
51
52
  }
52
53
 
53
54
  /// window.open and target=_blank. Never a second WKWebView: a popup model (presenting and closing a child,
@@ -88,7 +89,7 @@ extension MinimalWebView {
88
89
  navigationRules, request, asked: askedAndAllowed[request.mainFrame] ?? [],
89
90
  canAsk: requestHandlers.contains("onNavigationRequest")
90
91
  )
91
- guard decision.action == "ask" else {
92
+ guard decision.action == .ask else {
92
93
  finish(request, decision.action, decision.rule, completion)
93
94
  return
94
95
  }
@@ -96,7 +97,7 @@ extension MinimalWebView {
96
97
  // The view can be gone: the decision handler must still be called.
97
98
  guard let self else { return completion(false) }
98
99
  let action = NavigationRules.answer(answer)
99
- if action == "allow" { self.askedAndAllowed[request.mainFrame, default: []].insert(request.url) }
100
+ if action == .allow { self.askedAndAllowed[request.mainFrame, default: []].insert(request.url) }
100
101
  self.finish(request, action, decision.rule, completion)
101
102
  }
102
103
  // Unanswered after the timeout: block.
@@ -105,25 +106,27 @@ extension MinimalWebView {
105
106
  }
106
107
  }
107
108
 
108
- private func finish(_ request: NavigationRules.Request, _ action: String, _ rule: Int?, _ completion: (Bool) -> Void) {
109
- completion(action == "allow")
110
- guard action == "external" else { return report(request, action, rule) }
109
+ private func finish(
110
+ _ request: NavigationRules.Request, _ action: NavigationRules.Action, _ rule: Int?, _ completion: (Bool) -> Void
111
+ ) {
112
+ completion(action == .allow)
113
+ guard action == .external else { return report(request, action, rule) }
111
114
  guard requestHandlers.contains("onOpenExternal") else { return open(request, rule) }
112
115
  // A page that moved on first answers nil, which counts as opened. No timeout: nothing waits for the answer.
113
116
  asks.ask("core", "onOpenExternal", request.payload) { [weak self] answer in
114
- if answer as? Bool == false { self?.open(request, rule) } else { self?.report(request, "external", rule) }
117
+ if answer as? Bool == false { self?.open(request, rule) } else { self?.report(request, .external, rule) }
115
118
  }
116
119
  }
117
120
 
118
121
  /// Opens an `external` URL outside the WebView. As on Android, one that nothing opens is reported as blocked.
119
122
  private func open(_ request: NavigationRules.Request, _ rule: Int?) {
120
- guard let url = URL(string: request.url) else { return report(request, "block", rule) }
121
- UIApplication.shared.open(url) { [weak self] opened in self?.report(request, opened ? "external" : "block", rule) }
123
+ guard let url = URL(string: request.url) else { return report(request, .block, rule) }
124
+ UIApplication.shared.open(url) { [weak self] opened in self?.report(request, opened ? .external : .block, rule) }
122
125
  }
123
126
 
124
- private func report(_ request: NavigationRules.Request, _ action: String, _ rule: Int?) {
127
+ private func report(_ request: NavigationRules.Request, _ action: NavigationRules.Action, _ rule: Int?) {
125
128
  guard requestHandlers.contains("onNavigation") else { return }
126
- onNavigation(request.payload.merging(["action": action, "rule": rule as Any? ?? NSNull()]) { $1 })
129
+ onNavigation(request.payload.merging(["action": action.rawValue, "rule": rule as Any? ?? NSNull()]) { $1 })
127
130
  }
128
131
  }
129
132
 
@@ -45,12 +45,10 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
45
45
  // Created once, from the first props: WebKit reads some WKWebViewConfiguration settings only at creation.
46
46
  private(set) var webView: WKWebView?
47
47
  private var observations: [NSKeyValueObservation] = []
48
- private(set) lazy var downloads = Downloads(view: self)
48
+ private lazy var downloads = Downloads(view: self)
49
49
  private lazy var proxy = DelegateProxy(core: self)
50
50
  /// When the user last tapped the WKWebView: a link activation counts as user-initiated only right after a tap.
51
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
52
 
55
53
  // Navigation state, derived from WebKit in refreshUrls(). Native owns the committed URL; JS is told.
56
54
  private(set) var url = ""
@@ -63,15 +61,21 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
63
61
  /// while the item that was current at its commit stays current, the html page is what is on screen.
64
62
  private var htmlNavigation: WKNavigation?
65
63
  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?
64
+ /// The loads this view starts itself (source, `load`, reload after an error, an allowed new window), each until its
65
+ /// main-frame policy check, which skips the rules, with `mainFrameChecks` at its start. A list: a load can start
66
+ /// before the previous one's check, and the page being left can commit after it. A commit drops the loads a later
67
+ /// check passed (cut off before their own), so a page can't later skip the rules by navigating to one.
68
+ var ownLoads: [(url: URL, checks: Int)] = []
69
+ var mainFrameChecks = 0
68
70
  private(set) lazy var asks = Asks { [weak self] in self?.onHookEvent($0) }
69
71
  /// The attached hooks' contexts in attach order, for the life of the WKWebView: a hook may keep its own.
70
72
  var hookContexts: [HookContext] = []
71
73
  /// URLs an `ask` allowed in this Document, keyed by mainFrame: a subframe's answer doesn't decide the main frame's.
72
74
  var askedAndAllowed: [Bool: Set<String>] = [:]
73
- /// A `source` load is being prepared (shared cookies): loads wait until it is done.
75
+ /// A `source` or `load` load is being prepared (shared cookies): loads wait until it is done.
74
76
  private var preparing = false
77
+ /// The ref's `load` while it is prepared: it loads instead of the `source` being prepared, if any.
78
+ private var queuedUrl: URL?
75
79
  /// After a failed main-frame load `url` is the failed URL (as on Android, which commits an error page);
76
80
  /// WKWebView itself keeps the previous page, so `url` and reload() use this.
77
81
  private(set) var failedUrl: String?
@@ -80,6 +84,8 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
80
84
  private var lastEmitted: NSDictionary?
81
85
  private var updateScheduled = false
82
86
  private var crashTimes: [TimeInterval] = []
87
+ /// A web-process death whose reload waits until the view can be seen; a `load`, reload or new `source` replaces it.
88
+ private var recoveryPending = false
83
89
  /// `evaluate` calls waiting for their result, by id, until a new document or a dead web process rejects them.
84
90
  var evaluations: [Int: Promise] = [:]
85
91
  var nextEvaluation = 0
@@ -98,6 +104,21 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
98
104
  clipsToBounds = true
99
105
  // Made here, not lazily in the deinit fallback's endDocument(.closing), where its closure can't form a weak self.
100
106
  _ = asks
107
+ NotificationCenter.default.addObserver(
108
+ self, selector: #selector(recoverIfVisible), name: UIApplication.didBecomeActiveNotification, object: nil)
109
+ }
110
+
111
+ override func didMoveToWindow() {
112
+ super.didMoveToWindow()
113
+ recoverIfVisible()
114
+ }
115
+
116
+ /// Crash recovery reloads only in a window of an app not in the background, as on Android: there the reload
117
+ /// could die the same way, unseen.
118
+ @objc private func recoverIfVisible() {
119
+ guard recoveryPending, window != nil, UIApplication.shared.applicationState != .background else { return }
120
+ recoveryPending = false
121
+ loadAgain()
101
122
  }
102
123
 
103
124
  private var documentOpen = false
@@ -109,7 +130,8 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
109
130
  failEvaluations()
110
131
  bridgeOrigin = nil
111
132
  // JS queues bridge messages until the next page is ready; at unmount it rejects what is in flight itself.
112
- if reason != .closing, bridgeScript != nil { onBridge(["navigated": true]) }
133
+ if reason == .committed, bridgeScript != nil { onBridge(["navigated": true]) }
134
+ if reason == .crashed, bridgeScript != nil { onBridge(["crashed": true]) }
113
135
  askedAndAllowed.removeAll()
114
136
  dismissDialog()
115
137
  // The spinner belongs to a load, and a crash ends the load without a delegate callback.
@@ -130,11 +152,33 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
130
152
  loadedSource = next.toDictionary() as NSDictionary
131
153
  // New content from the app: the crash-loop guard starts over (recovery reloads don't come through here).
132
154
  crashTimes = []
155
+ recoveryPending = false
156
+ prepare(next)
157
+ }
158
+
159
+ /// The ref's `load`. It is prepared as a `source` load is, and a later call replaces one still waiting.
160
+ func load(url: String) {
161
+ guard let target = URL(string: url) else { return warn("load: \(url) is not a URL") }
162
+ guard webView != nil else { return }
163
+ crashTimes = []
164
+ recoveryPending = false
165
+ queuedUrl = target
166
+ if !preparing { prepare(nil) }
167
+ }
168
+
169
+ private func prepare(_ source: WebViewSource?) {
133
170
  preparing = true
134
171
  cookies.prepare { [weak self, weak webView] in
135
172
  guard let self, let webView, webView === self.webView else { return }
136
173
  preparing = false
137
- load(next)
174
+ // A load asked for while the source was prepared replaces it: started first, the source's request (a POST
175
+ // included) would be sent only to be cut off.
176
+ if let queuedUrl {
177
+ self.queuedUrl = nil
178
+ loadProgrammatic(URLRequest(url: queuedUrl), inSourceRoot: false)
179
+ } else if let source {
180
+ load(source)
181
+ }
138
182
  // Props that changed while preparing (a newer source) apply now.
139
183
  applyProps()
140
184
  }
@@ -153,7 +197,10 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
153
197
  }
154
198
  loadProgrammatic(request)
155
199
  } else {
156
- htmlNavigation = webView?.loadHTMLString(source.html ?? "", baseURL: source.baseUrl.flatMap(URL.init))
200
+ let baseURL = source.baseUrl.flatMap(URL.init)
201
+ // WebKit puts the html load through decidePolicyFor at its base URL, about:blank without one.
202
+ if let own = baseURL ?? URL(string: "about:blank") { ownLoads.append((own, mainFrameChecks)) }
203
+ htmlNavigation = webView?.loadHTMLString(source.html ?? "", baseURL: baseURL)
157
204
  }
158
205
  }
159
206
 
@@ -175,12 +222,12 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
175
222
  }
176
223
  }
177
224
 
178
- /// Loads a request the app started (see `programmaticUrl`). A file URL goes through loadFileURL with the source's read
179
- /// root, so the page's own assets load (load(_:) can't read local files).
180
- func loadProgrammatic(_ request: URLRequest) {
181
- programmaticUrl = request.url
225
+ /// Loads a request the app started (see `ownLoads`). A file URL goes through loadFileURL, so the page's own assets
226
+ /// load (load(_:) can't read local files), with the source's read root or, outside it, the file's directory.
227
+ func loadProgrammatic(_ request: URLRequest, inSourceRoot: Bool = true) {
228
+ if let url = request.url { ownLoads.append((url, mainFrameChecks)) }
182
229
  if let url = request.url, url.isFileURL {
183
- let access = ReadAccess.root(for: url, source?.readAccessRoot)
230
+ let access = ReadAccess.root(for: url, inSourceRoot ? source?.readAccessRoot : nil)
184
231
  if let warning = access.warning { warn(warning) }
185
232
  webView?.loadFileURL(url, allowingReadAccessTo: access.root)
186
233
  } else {
@@ -196,8 +243,11 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
196
243
  }
197
244
 
198
245
  func reload() {
199
- // WebKit's reload redoes no failed load or POST, and loads nothing while `url` is nil (no commit, a dead process).
200
- if let webView, webView.url != nil, failedUrl == nil, !onPostSource { webView.reload() } else { loadAgain() }
246
+ recoveryPending = false
247
+ // WebKit's reload redoes no failed load, POST or html source (it fetches the base URL), and loads nothing while `url`
248
+ // is nil (no commit, a dead process).
249
+ let onHtmlSource = onSource && source?.uri == nil
250
+ if let webView, webView.url != nil, failedUrl == nil, !onPostSource, !onHtmlSource { webView.reload() } else { loadAgain() }
201
251
  }
202
252
 
203
253
  /// Loads the page on screen again, as crash recovery does. In order:
@@ -405,7 +455,7 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
405
455
 
406
456
  func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
407
457
  endDocument(.committed)
408
- programmaticUrl = nil
458
+ ownLoads.removeAll { $0.checks < mainFrameChecks }
409
459
  failedUrl = nil
410
460
  htmlCommit = navigation === htmlNavigation
411
461
  ? (webView.url?.absoluteString ?? "about:blank", webView.backForwardList.currentItem) : nil
@@ -440,7 +490,10 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
440
490
  let recovered = Recovery.crashAllowsReload(&crashTimes, now: ProcessInfo.processInfo.systemUptime) && !onPostSource
441
491
  endDocument(.crashed)
442
492
  if lastEmitted?["loading"] as? Bool == true { outcome = "failed" } // the load the crash cut off
443
- if recovered { loadAgain() }
493
+ if recovered {
494
+ recoveryPending = true
495
+ recoverIfVisible()
496
+ }
444
497
  onProcessGone(["cause": "unknown", "recovered": recovered])
445
498
  forward { $0.webViewWebContentProcessDidTerminate?(webView) }
446
499
  }
@@ -489,16 +542,7 @@ extension MinimalWebView {
489
542
  webView?.navigationDelegate = proxy
490
543
  webView?.uiDelegate = nil
491
544
  webView?.uiDelegate = proxy
492
- warnDecisions()
493
- }
494
-
495
- private func warnDecisions() {
496
- for name in proxy.sharedDecisions where warnedDecisions.insert(name).inserted {
497
- warn("\(name): more than one hook delegate implements it; only the first one gets it")
498
- }
499
- for (name, lost) in proxy.takenDecisions where warnedDecisions.insert("\(name) taken").inserted {
500
- warn("\(name): a hook delegate takes it, so \(lost)")
501
- }
545
+ proxy.newWarnings().forEach(warn)
502
546
  }
503
547
 
504
548
  func emit(_ key: String, _ name: String, _ payload: [String: Any]) {
@@ -29,6 +29,7 @@ public class MinimalWebViewModule: Module {
29
29
 
30
30
  AsyncFunction("goBack") { (view: MinimalWebView) in view.webView?.goBack() }
31
31
  AsyncFunction("goForward") { (view: MinimalWebView) in view.webView?.goForward() }
32
+ AsyncFunction("load") { (view: MinimalWebView, url: String) in view.load(url: url) }
32
33
  AsyncFunction("reload") { (view: MinimalWebView) in view.retry() }
33
34
  AsyncFunction("stopLoading") { (view: MinimalWebView) in view.webView?.stopLoading() }
34
35
  AsyncFunction("get") { (view: MinimalWebView, path: String, promise: Promise) in
@@ -14,9 +14,11 @@ enum NavigationRules {
14
14
  }
15
15
  }
16
16
 
17
- /// `action` is allow, block, external or ask; `rule` is the matching rule's index, nil when a default decided.
17
+ enum Action: String { case allow, block, external, ask }
18
+
19
+ /// `rule` is the matching rule's index, nil when a default decided.
18
20
  struct Decision: Equatable {
19
- let action: String
21
+ let action: Action
20
22
  let rule: Int?
21
23
  }
22
24
 
@@ -33,36 +35,34 @@ enum NavigationRules {
33
35
  /// Never open as a new window, whatever the rules say: the core loads an allowed new window in the main frame itself,
34
36
  /// past the engine's limits on what a page may navigate the top frame to.
35
37
  private static let noNewWindowSchemes = internalSchemes.union(["blob", "file"])
36
- private static let actions: Set<String> = ["allow", "block", "external", "ask"]
37
- private static let answers: Set<String> = ["allow", "block", "external"]
38
38
 
39
39
  /// The rules' decision, gated for `ask`: blocked when nothing can answer it (`canAsk` false), allowed when its URL is
40
40
  /// in `asked` (URLs an `ask` already allowed). An unknown rule action blocks.
41
41
  static func decide(_ rules: [[String: Any]]?, _ request: Request, asked: Set<String>, canAsk: Bool) -> Decision {
42
42
  let decision = match(rules, request)
43
- guard decision.action == "ask" else { return decision }
44
- if !canAsk { return Decision(action: "block", rule: decision.rule) }
45
- return asked.contains(request.url) ? Decision(action: "allow", rule: decision.rule) : decision
43
+ guard decision.action == .ask else { return decision }
44
+ if !canAsk { return Decision(action: .block, rule: decision.rule) }
45
+ return asked.contains(request.url) ? Decision(action: .allow, rule: decision.rule) : decision
46
46
  }
47
47
 
48
48
  /// An `ask` answer: allow, block or external; anything else (nil on a timeout) blocks.
49
- static func answer(_ value: Any?) -> String {
50
- (value as? String).flatMap { answers.contains($0) ? $0 : nil } ?? "block"
49
+ static func answer(_ value: Any?) -> Action {
50
+ guard let action = (value as? String).flatMap(Action.init), action != .ask else { return .block }
51
+ return action
51
52
  }
52
53
 
53
54
  private static func match(_ rules: [[String: Any]]?, _ request: Request) -> Decision {
54
55
  let scheme = request.url.firstIndex(of: ":").map { request.url[..<$0].lowercased() } ?? ""
55
- if request.newWindow, noNewWindowSchemes.contains(scheme) { return Decision(action: "block", rule: nil) }
56
- if internalSchemes.contains(scheme) { return Decision(action: "allow", rule: nil) }
56
+ if request.newWindow, noNewWindowSchemes.contains(scheme) { return Decision(action: .block, rule: nil) }
57
+ if internalSchemes.contains(scheme) { return Decision(action: .allow, rule: nil) }
57
58
  // JS sends defaultNavigationRules when the prop is unset; no rules, nil or empty, match nothing.
58
59
  guard let rules, !rules.isEmpty,
59
60
  let parts = scheme == "blob" ? blobOrigin(request.url) : urlParts(scheme, request.url)
60
- else { return Decision(action: "block", rule: nil) }
61
+ else { return Decision(action: .block, rule: nil) }
61
62
  guard let index = rules.firstIndex(where: { matches($0, parts, request) }) else {
62
- return Decision(action: "block", rule: nil)
63
+ return Decision(action: .block, rule: nil)
63
64
  }
64
- let action = rules[index]["action"] as? String
65
- return Decision(action: action.flatMap { actions.contains($0) ? $0 : nil } ?? "block", rule: index)
65
+ return Decision(action: (rules[index]["action"] as? String).flatMap(Action.init) ?? .block, rule: index)
66
66
  }
67
67
 
68
68
  private static func urlParts(_ scheme: String, _ url: String) -> Parts {
@@ -186,7 +186,6 @@ final class PlatformSettings {
186
186
  let isBool = CFGetTypeID(value as CFTypeRef) == CFBooleanGetTypeID()
187
187
  let number = isBool ? nil : value as? NSNumber
188
188
  let string = value as? String
189
- let object = value as? [String: Any]
190
189
  let isNull = value is NSNull
191
190
  switch type {
192
191
  case "B", "c":
@@ -207,18 +206,8 @@ final class PlatformSettings {
207
206
  case "nonPersistent": return WKWebsiteDataStore.nonPersistent()
208
207
  default: return nil
209
208
  }
210
- case "{UIEdgeInsets=dddd}":
211
- guard let o = object, let t = o["top"] as? Double, let l = o["left"] as? Double, let b = o["bottom"] as? Double, let r = o["right"] as? Double else { return nil }
212
- return NSValue(uiEdgeInsets: UIEdgeInsets(top: t, left: l, bottom: b, right: r))
213
- case "{CGPoint=dd}":
214
- guard let o = object, let x = o["x"] as? Double, let y = o["y"] as? Double else { return nil }
215
- return NSValue(cgPoint: CGPoint(x: x, y: y))
216
- case "{CGSize=dd}":
217
- guard let o = object, let w = o["width"] as? Double, let h = o["height"] as? Double else { return nil }
218
- return NSValue(cgSize: CGSize(width: w, height: h))
219
- case "{CGRect={CGPoint=dd}{CGSize=dd}}":
220
- guard let o = object, let x = o["x"] as? Double, let y = o["y"] as? Double, let w = o["width"] as? Double, let h = o["height"] as? Double else { return nil }
221
- return NSValue(cgRect: CGRect(x: x, y: y, width: w, height: h))
209
+ case _ where type.hasPrefix("{"):
210
+ return __MRWStructValue(type, value)
222
211
  default:
223
212
  return nil
224
213
  }
@@ -9,10 +9,9 @@ final class SharedCookies: NSObject, WKHTTPCookieStoreObserver {
9
9
  /// The WebView's cookies at the last copy: one gone from it since is deleted from native too.
10
10
  private var copied: [HTTPCookie] = []
11
11
 
12
- /// Once: the view's one WKWebView, which a crash keeps.
12
+ /// Once, before the first `set`: the view's one WKWebView, which a crash keeps.
13
13
  func didCreate(_ webView: WKWebView) {
14
14
  store = webView.configuration.websiteDataStore.httpCookieStore
15
- if enabled { store?.add(self) }
16
15
  }
17
16
 
18
17
  func set(_ enabled: Bool) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-native-minimal-webview",
3
- "version": "1.1.0",
3
+ "version": "1.2.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",