ActivityWebView.swift 9.1 KB

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