ActivityWebView.swift 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. import SwiftUI
  2. import WebKit
  3. import Combine
  4. private struct RemoteActivityVisibilityKey: EnvironmentKey { static let defaultValue = false }
  5. extension EnvironmentValues {
  6. var isRemoteActivityVisible: Bool {
  7. get { self[RemoteActivityVisibilityKey.self] }
  8. set { self[RemoteActivityVisibilityKey.self] = newValue }
  9. }
  10. }
  11. @MainActor private final class ActivityWebState: ObservableObject {
  12. @Published var isLoading = true
  13. @Published var failed = false
  14. @Published var reloadID = 0
  15. @Published var loaded = false
  16. }
  17. struct ActivityNoticeView: View {
  18. @EnvironmentObject private var language: LanguageStore
  19. @EnvironmentObject private var tracking: FacebookTracking
  20. let notice: ActivityNotice
  21. var showsControls = false
  22. var didLoad: () -> Void = {}
  23. var receivedClose: ((SurveySubmission?) -> Void)? = nil
  24. let close: () -> Void
  25. @StateObject private var webState = ActivityWebState()
  26. @StateObject private var closeCountdown = ActivityCloseCountdown()
  27. private var closePolicy: ActivityClosePolicy { ActivityClosePolicy(url: notice.url) }
  28. var body: some View {
  29. VStack(spacing: 0) {
  30. if showsControls {
  31. banner
  32. Divider()
  33. }
  34. ZStack {
  35. ActivityWebContent(url: notice.url, privacyURL: notice.privacyURL, state: webState, tracking: tracking, didLoad: didLoad, close: { submission in
  36. if let receivedClose { receivedClose(submission) } else { close() }
  37. }).id(notice.id)
  38. if webState.isLoading { ProgressView().tint(Palette.blue).padding(15).background(.regularMaterial, in: RoundedRectangle(cornerRadius: 13)) }
  39. if webState.failed {
  40. VStack(spacing: 20) {
  41. Image(systemName: "wifi.exclamationmark").font(.system(size: 38)).foregroundStyle(Palette.muted)
  42. Text(language.text("Unable to load this activity. Please try again.")).multilineTextAlignment(.center).foregroundStyle(Palette.muted)
  43. if showsControls {
  44. Button(language.text("Retry")) { webState.reloadID += 1 }.tint(Palette.blue)
  45. }
  46. }.padding(28).frame(maxWidth: .infinity, maxHeight: .infinity).background(Palette.background)
  47. }
  48. }
  49. .overlay(alignment: .topTrailing) {
  50. if !showsControls && (notice.isSurvey || webState.failed || closeCountdown.isAvailable) {
  51. Button(action: close) {
  52. Image(systemName: "xmark").font(.system(size: 16, weight: .semibold))
  53. .foregroundStyle(.white).frame(width: 44, height: 44)
  54. .background(.black.opacity(0.72), in: Circle())
  55. }
  56. .accessibilityLabel(language.text("Close"))
  57. .accessibilityIdentifier("activity.close")
  58. .padding(.trailing, 10)
  59. .padding(.top, 76)
  60. }
  61. }
  62. }
  63. .background { Color.black.ignoresSafeArea() }.accessibilityAddTraits(.isModal)
  64. .task(id: [webState.loaded, webState.failed]) {
  65. await closeCountdown.update(policy: closePolicy, loaded: webState.loaded, failed: webState.failed)
  66. }
  67. }
  68. private var banner: some View {
  69. HStack(spacing: 14) {
  70. VStack(alignment: .leading, spacing: 3) {
  71. Text(language.text("Activity Notice")).font(.system(size: 18, weight: .semibold))
  72. Text(notice.url.host ?? "").font(.system(size: 11)).foregroundStyle(Palette.muted).lineLimit(1)
  73. }
  74. Spacer()
  75. Button { webState.reloadID += 1 } label: {
  76. Image(systemName: "arrow.clockwise").frame(width: 35, height: 40)
  77. }.accessibilityLabel(language.text("Reload Activity"))
  78. Button(language.text("Close"), action: close).font(.system(size: 16, weight: .semibold)).frame(minHeight: 44)
  79. .accessibilityIdentifier("activity.close")
  80. }.foregroundStyle(Palette.ink).padding(.horizontal, 18).background(.white, ignoresSafeAreaEdges: [])
  81. }
  82. }
  83. private struct ActivityWebContent: UIViewRepresentable {
  84. let url: URL
  85. let privacyURL: URL?
  86. @ObservedObject var state: ActivityWebState
  87. let tracking: FacebookTracking
  88. let didLoad: () -> Void
  89. let close: (SurveySubmission?) -> Void
  90. func makeCoordinator() -> Coordinator {
  91. Coordinator(state: state, didLoad: didLoad, bridge: ActivityBridge(pageURL: url, tracking: tracking, close: close) { url in
  92. UIApplication.shared.open(url, options: [:], completionHandler: nil)
  93. })
  94. }
  95. func makeUIView(context: Context) -> WKWebView {
  96. let configuration = WKWebViewConfiguration()
  97. configuration.websiteDataStore = .default()
  98. configuration.userContentController.add(context.coordinator, name: ActivityBridgeScript.handlerName)
  99. configuration.userContentController.addUserScript(WKUserScript(source: ActivityBridgeScript.source(privacyURL: privacyURL),
  100. injectionTime: .atDocumentStart, forMainFrameOnly: true))
  101. let view = WKWebView(frame: .zero, configuration: configuration)
  102. #if DEBUG
  103. if #available(iOS 16.4, *) { view.isInspectable = true }
  104. #endif
  105. view.overrideUserInterfaceStyle = .light
  106. view.isOpaque = false
  107. view.backgroundColor = .black
  108. view.scrollView.backgroundColor = .black
  109. view.navigationDelegate = context.coordinator
  110. view.uiDelegate = context.coordinator
  111. view.allowsBackForwardNavigationGestures = true
  112. return view
  113. }
  114. func updateUIView(_ view: WKWebView, context: Context) {
  115. guard context.coordinator.sourceURL != url || context.coordinator.reloadID != state.reloadID else { return }
  116. context.coordinator.sourceURL = url
  117. context.coordinator.reloadID = state.reloadID
  118. view.load(URLRequest(url: url, cachePolicy: .useProtocolCachePolicy))
  119. }
  120. static func dismantleUIView(_ view: WKWebView, coordinator: Coordinator) {
  121. view.configuration.userContentController.removeScriptMessageHandler(forName: ActivityBridgeScript.handlerName)
  122. view.configuration.userContentController.removeAllUserScripts()
  123. view.stopLoading(); view.navigationDelegate = nil; view.uiDelegate = nil
  124. }
  125. @MainActor final class Coordinator: NSObject, WKNavigationDelegate, WKUIDelegate, WKScriptMessageHandler {
  126. let state: ActivityWebState
  127. let bridge: ActivityBridge
  128. let didLoad: () -> Void
  129. var sourceURL: URL?
  130. var reloadID = -1
  131. init(state: ActivityWebState, didLoad: @escaping () -> Void, bridge: ActivityBridge) {
  132. self.state = state; self.didLoad = didLoad; self.bridge = bridge
  133. }
  134. func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
  135. guard message.name == ActivityBridgeScript.handlerName else { return }
  136. bridge.receive(message.body, from: message.frameInfo.request.url, isMainFrame: message.frameInfo.isMainFrame)
  137. }
  138. func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
  139. state.isLoading = true; state.failed = false; state.loaded = false
  140. }
  141. func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
  142. state.isLoading = false
  143. }
  144. func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
  145. let succeeded = !state.failed && webView.url.flatMap { ActivityURL.parse($0.absoluteString) } != nil
  146. state.isLoading = false; state.failed = false
  147. state.loaded = succeeded
  148. if succeeded { didLoad() }
  149. }
  150. func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { fail(error) }
  151. func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { fail(error) }
  152. private func fail(_ error: Error) {
  153. guard (error as NSError).code != NSURLErrorCancelled else { return }
  154. state.isLoading = false; state.failed = true; state.loaded = false
  155. }
  156. func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {
  157. state.isLoading = false; state.failed = true; state.loaded = false
  158. }
  159. func webView(_ webView: WKWebView, decidePolicyFor action: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
  160. let allowed = action.request.url.flatMap { ActivityURL.parse($0.absoluteString) } != nil
  161. decisionHandler(allowed ? .allow : .cancel)
  162. }
  163. func webView(_ webView: WKWebView, decidePolicyFor response: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
  164. if response.isForMainFrame, let http = response.response as? HTTPURLResponse, http.statusCode >= 400 {
  165. state.isLoading = false; state.failed = true; state.loaded = false
  166. decisionHandler(.cancel)
  167. } else { decisionHandler(.allow) }
  168. }
  169. func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for action: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
  170. if action.targetFrame == nil, let url = action.request.url, ActivityURL.parse(url.absoluteString) != nil { webView.load(action.request) }
  171. return nil
  172. }
  173. }
  174. }