| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183 |
- 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 = {}
- var receivedClose: ((SurveySubmission?) -> Void)? = nil
- 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, privacyURL: notice.privacyURL, state: webState, tracking: tracking, didLoad: didLoad, close: { submission in
- if let receivedClose { receivedClose(submission) } else { close() }
- }).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 && (notice.isSurvey || 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(.trailing, 10)
- .padding(.top, 76)
- }
- }
- }
- .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
- let privacyURL: URL?
- @ObservedObject var state: ActivityWebState
- let tracking: FacebookTracking
- let didLoad: () -> Void
- let close: (SurveySubmission?) -> Void
- func makeCoordinator() -> Coordinator {
- Coordinator(state: state, didLoad: didLoad, bridge: ActivityBridge(pageURL: url, tracking: tracking, close: close) { 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(privacyURL: privacyURL),
- 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
- }
- }
- }
|