import SwiftUI import WebKit import Combine private struct RemoteActivityVisibilityKey: EnvironmentKey { static let defaultValue = false } extension EnvironmentValues { var isRemoteActivityVisible: Bool { get { self[RemoteActivityVisibilityKey.self] } set { self[RemoteActivityVisibilityKey.self] = newValue } } } @MainActor private final class ActivityWebState: ObservableObject { @Published var isLoading = true @Published var failed = false @Published var reloadID = 0 @Published var loaded = false } struct ActivityNoticeView: View { @EnvironmentObject private var language: LanguageStore @EnvironmentObject private var tracking: FacebookTracking let notice: ActivityNotice var showsControls = false var didLoad: () -> Void = {} let close: () -> Void @StateObject private var webState = ActivityWebState() @StateObject private var closeCountdown = ActivityCloseCountdown() private var closePolicy: ActivityClosePolicy { ActivityClosePolicy(url: notice.url) } var body: some View { VStack(spacing: 0) { if showsControls { banner Divider() } ZStack { ActivityWebContent(url: notice.url, state: webState, tracking: tracking, didLoad: didLoad).id(notice.id) if webState.isLoading { ProgressView().tint(Palette.blue).padding(15).background(.regularMaterial, in: RoundedRectangle(cornerRadius: 13)) } if webState.failed { VStack(spacing: 20) { Image(systemName: "wifi.exclamationmark").font(.system(size: 38)).foregroundStyle(Palette.muted) Text(language.text("Unable to load this activity. Please try again.")).multilineTextAlignment(.center).foregroundStyle(Palette.muted) if showsControls { Button(language.text("Retry")) { webState.reloadID += 1 }.tint(Palette.blue) } }.padding(28).frame(maxWidth: .infinity, maxHeight: .infinity).background(Palette.background) } } .overlay(alignment: .topTrailing) { if !showsControls && (webState.failed || closeCountdown.isAvailable) { Button(action: close) { Image(systemName: "xmark").font(.system(size: 16, weight: .semibold)) .foregroundStyle(.white).frame(width: 44, height: 44) .background(.black.opacity(0.72), in: Circle()) } .accessibilityLabel(language.text("Close")) .accessibilityIdentifier("activity.close") .padding(10) } } } .background { Color.black.ignoresSafeArea() }.accessibilityAddTraits(.isModal) .task(id: [webState.loaded, webState.failed]) { await closeCountdown.update(policy: closePolicy, loaded: webState.loaded, failed: webState.failed) } } private var banner: some View { HStack(spacing: 14) { VStack(alignment: .leading, spacing: 3) { Text(language.text("Activity Notice")).font(.system(size: 18, weight: .semibold)) Text(notice.url.host ?? "").font(.system(size: 11)).foregroundStyle(Palette.muted).lineLimit(1) } Spacer() Button { webState.reloadID += 1 } label: { Image(systemName: "arrow.clockwise").frame(width: 35, height: 40) }.accessibilityLabel(language.text("Reload Activity")) Button(language.text("Close"), action: close).font(.system(size: 16, weight: .semibold)).frame(minHeight: 44) .accessibilityIdentifier("activity.close") }.foregroundStyle(Palette.ink).padding(.horizontal, 18).background(.white, ignoresSafeAreaEdges: []) } } private struct ActivityWebContent: UIViewRepresentable { let url: URL @ObservedObject var state: ActivityWebState let tracking: FacebookTracking let didLoad: () -> Void func makeCoordinator() -> Coordinator { Coordinator(state: state, didLoad: didLoad, bridge: ActivityBridge(pageURL: url, tracking: tracking) { url in UIApplication.shared.open(url, options: [:], completionHandler: nil) }) } func makeUIView(context: Context) -> WKWebView { let configuration = WKWebViewConfiguration() configuration.websiteDataStore = .default() configuration.userContentController.add(context.coordinator, name: ActivityBridgeScript.handlerName) configuration.userContentController.addUserScript(WKUserScript(source: ActivityBridgeScript.source, injectionTime: .atDocumentStart, forMainFrameOnly: true)) let view = WKWebView(frame: .zero, configuration: configuration) #if DEBUG if #available(iOS 16.4, *) { view.isInspectable = true } #endif view.overrideUserInterfaceStyle = .light view.isOpaque = false view.backgroundColor = .black view.scrollView.backgroundColor = .black view.navigationDelegate = context.coordinator view.uiDelegate = context.coordinator view.allowsBackForwardNavigationGestures = true return view } func updateUIView(_ view: WKWebView, context: Context) { guard context.coordinator.sourceURL != url || context.coordinator.reloadID != state.reloadID else { return } context.coordinator.sourceURL = url context.coordinator.reloadID = state.reloadID view.load(URLRequest(url: url, cachePolicy: .useProtocolCachePolicy)) } static func dismantleUIView(_ view: WKWebView, coordinator: Coordinator) { view.configuration.userContentController.removeScriptMessageHandler(forName: ActivityBridgeScript.handlerName) view.configuration.userContentController.removeAllUserScripts() view.stopLoading(); view.navigationDelegate = nil; view.uiDelegate = nil } @MainActor final class Coordinator: NSObject, WKNavigationDelegate, WKUIDelegate, WKScriptMessageHandler { let state: ActivityWebState let bridge: ActivityBridge let didLoad: () -> Void var sourceURL: URL? var reloadID = -1 init(state: ActivityWebState, didLoad: @escaping () -> Void, bridge: ActivityBridge) { self.state = state; self.didLoad = didLoad; self.bridge = bridge } func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { guard message.name == ActivityBridgeScript.handlerName else { return } bridge.receive(message.body, from: message.frameInfo.request.url, isMainFrame: message.frameInfo.isMainFrame) } func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) { state.isLoading = true; state.failed = false; state.loaded = false } func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) { state.isLoading = false } func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { let succeeded = !state.failed && webView.url.flatMap { ActivityURL.parse($0.absoluteString) } != nil state.isLoading = false; state.failed = false state.loaded = succeeded if succeeded { didLoad() } } func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { fail(error) } func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { fail(error) } private func fail(_ error: Error) { guard (error as NSError).code != NSURLErrorCancelled else { return } state.isLoading = false; state.failed = true; state.loaded = false } func webViewWebContentProcessDidTerminate(_ webView: WKWebView) { state.isLoading = false; state.failed = true; state.loaded = false } func webView(_ webView: WKWebView, decidePolicyFor action: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { let allowed = action.request.url.flatMap { ActivityURL.parse($0.absoluteString) } != nil decisionHandler(allowed ? .allow : .cancel) } func webView(_ webView: WKWebView, decidePolicyFor response: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) { if response.isForMainFrame, let http = response.response as? HTTPURLResponse, http.statusCode >= 400 { state.isLoading = false; state.failed = true; state.loaded = false decisionHandler(.cancel) } else { decisionHandler(.allow) } } func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for action: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? { if action.targetFrame == nil, let url = action.request.url, ActivityURL.parse(url.absoluteString) != nil { webView.load(action.request) } return nil } } }