import SwiftUI import UIKit import WebKit /// Sandboxed HTML file preview. Mirrors the web file page's inline preview: /// scripts are disabled and the page runs in a non-persistent data store, so /// project HTML cannot read the app's cookies/storage or call the hub API. /// Tapped links leave the preview for Safari instead of navigating the /// top-level web view. struct HTMLPreviewView: UIViewRepresentable { let html: String func makeCoordinator() -> Coordinator { Coordinator() } func makeUIView(context: Context) -> WKWebView { let configuration = WKWebViewConfiguration() configuration.websiteDataStore = .nonPersistent() configuration.defaultWebpagePreferences.allowsContentJavaScript = false let webView = WKWebView(frame: .zero, configuration: configuration) webView.navigationDelegate = context.coordinator webView.allowsBackForwardNavigationGestures = false webView.scrollView.contentInsetAdjustmentBehavior = .never webView.isOpaque = false webView.backgroundColor = .white context.coordinator.loadedHTML = html webView.loadHTMLString(html, baseURL: nil) return webView } func updateUIView(_ webView: WKWebView, context: Context) { guard context.coordinator.loadedHTML != html else { return } context.coordinator.loadedHTML = html webView.loadHTMLString(html, baseURL: nil) } final class Coordinator: NSObject, WKNavigationDelegate { var loadedHTML: String? func webView( _ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void ) { if navigationAction.navigationType == .linkActivated, let url = navigationAction.request.url { UIApplication.shared.open(url) decisionHandler(.cancel) return } decisionHandler(.allow) } } }