Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/Shared/MessageBodyView.swift3// Description: The ONLY web view of the app — an isolated renderer for sanitised HTML message bodies. JavaScript off, non-persistent store,4// every network load blocked by a content rule list; inline (cid:) and opted-in remote images are served by the app through a custom scheme5// (gateway download / backend image proxy with the bearer token), never fetched from the sender's server.6import SPMailCore7import SwiftUI8import WebKit910/// Serves `spmail-cid://part/<cid>` (inline parts via the gateway) and `spmail-img://proxy/?u=<url>` (remote images via `/api/img`).11final class MailImageSchemeHandler: NSObject, WKURLSchemeHandler {12 typealias Loader = @Sendable (URL) async -> (Data, String)?13 private let loader: Loader14 private var active: [ObjectIdentifier: Task<Void, Never>] = [:]15 init(loader: @escaping Loader) { self.loader = loader }1617 func webView(_ webView: WKWebView, start task: any WKURLSchemeTask) {18 guard let url = task.request.url else { task.didFailWithError(URLError(.badURL)); return }19 let key = ObjectIdentifier(task)20 let loader = loader21 active[key] = Task { @MainActor [weak self] in22 let result = await loader(url)23 guard let self, self.active[key] != nil, !Task.isCancelled else { return } // stopped meanwhile: the task object must not be touched24 self.active[key] = nil25 if let (data, type) = result {26 task.didReceive(URLResponse(url: url, mimeType: type, expectedContentLength: data.count, textEncodingName: nil))27 task.didReceive(data)28 task.didFinish()29 } else { task.didFailWithError(URLError(.resourceUnavailable)) }30 }31 }32 func webView(_ webView: WKWebView, stop task: any WKURLSchemeTask) {33 active.removeValue(forKey: ObjectIdentifier(task))?.cancel()34 }35}3637@MainActor38enum BodyRenderer {39 private static var rules: WKContentRuleList?40 static let heightMessage = "spmHeight"41 /// The app's own observer, in the app's isolated content world: JavaScript of the MESSAGE stays disabled (`allowsContentJavaScript = false`42 /// only governs scripts of the page). It reports the height of the document on every layout change — late images, a new width,43 /// a font change — instead of measuring at fixed delays.44 static let heightScript = """45 (function () {46 var last = -1;47 function report() {48 var h = Math.ceil(Math.max(document.body ? document.body.getBoundingClientRect().bottom + window.scrollY : 0, document.documentElement.offsetHeight));49 if (h !== last) { last = h; window.webkit.messageHandlers.\(heightMessage).postMessage(h); }50 }51 new ResizeObserver(report).observe(document.documentElement);52 if (document.body) { new ResizeObserver(report).observe(document.body); }53 window.addEventListener('load', report);54 report();55 })();56 """57 /// Blocks every load except the app's two image schemes. Compiled once; rendering waits for it (fail closed).58 static func contentRules() async -> WKContentRuleList? {59 if let rules { return rules }60 let json = """61 [{"trigger":{"url-filter":".*"},"action":{"type":"block"}},62 {"trigger":{"url-filter":"^\(HTMLSanitizer.cidScheme):"},"action":{"type":"ignore-previous-rules"}},63 {"trigger":{"url-filter":"^\(HTMLSanitizer.proxyScheme):"},"action":{"type":"ignore-previous-rules"}},64 {"trigger":{"url-filter":"^about:"},"action":{"type":"ignore-previous-rules"}}]65 """66 rules = try? await WKContentRuleListStore.default().compileContentRuleList(forIdentifier: "spmail-block-all-v1", encodedContentRuleList: json)67 return rules68 }6970 /// `passthrough` (message bodies, template previews laid out at their measured height): wheel events go to the enclosing scroll view.71 /// `heightObserver` (message bodies): receives the document height whenever the layout changes — see `heightScript`.72 static func makeWebView(rules: WKContentRuleList, handler: MailImageSchemeHandler, passthrough: Bool = true, heightObserver: WKScriptMessageHandler? = nil) -> WKWebView {73 let config = WKWebViewConfiguration()74 config.websiteDataStore = .nonPersistent()75 config.defaultWebpagePreferences.allowsContentJavaScript = false76 config.userContentController.add(rules)77 if let heightObserver {78 config.userContentController.add(heightObserver, contentWorld: .defaultClient, name: heightMessage)79 config.userContentController.addUserScript(WKUserScript(source: heightScript, injectionTime: .atDocumentEnd, forMainFrameOnly: true, in: .defaultClient))80 }81 config.setURLSchemeHandler(handler, forURLScheme: HTMLSanitizer.cidScheme)82 config.setURLSchemeHandler(handler, forURLScheme: HTMLSanitizer.proxyScheme)83 config.suppressesIncrementalRendering = false84 #if os(iOS)85 config.allowsInlineMediaPlayback = false86 config.dataDetectorTypes = []87 #endif88 config.mediaTypesRequiringUserActionForPlayback = .all89 let view = passthrough ? PassthroughWebView(frame: .zero, configuration: config) : WKWebView(frame: .zero, configuration: config)90 view.allowsLinkPreview = false91 view.allowsBackForwardNavigationGestures = false92 #if os(macOS)93 view.setValue(false, forKey: "drawsBackground")94 view.allowsMagnification = false95 #else96 view.isOpaque = false97 view.backgroundColor = .clear98 view.scrollView.backgroundColor = .clear99 view.scrollView.isScrollEnabled = false100 view.scrollView.bounces = false101 #endif102 return view103 }104}105106/// On macOS the web view sits inside the conversation's scroll view: wheel events go to the parent instead of being swallowed.107final class PassthroughWebView: WKWebView {108 #if os(macOS)109 override func scrollWheel(with event: NSEvent) { nextResponder?.scrollWheel(with: event) }110 #endif111}112113struct MessageBodyView: View {114 let html: String115 let emailId: String116 let allowRemoteImages: Bool117 /// Already scaled for Dynamic Type by the caller.118 let fontSize: Int119 /// Dark rendering (« Lecture sombre »); otherwise the message is laid out for a white sheet.120 let dark: Bool121 /// CSS family of the reading font preference.122 var fontFamily = ReadingFont.system.cssFamily123 let loader: MailImageSchemeHandler.Loader124 let onLink: (URL) -> Void125 @State private var rules: WKContentRuleList?126 @State private var height: CGFloat = 120127 @State private var failed = false128129 private var document: String {130 // the reading font is a default the message's own styles can still override131 HTMLSanitizer.document(body: "<style>body{font-family:\(fontFamily)}</style>" + html, dark: dark, fontSize: fontSize)132 }133134 var body: some View {135 Group {136 if let rules {137 BodyWebView(document: document, rules: rules, loader: loader, onLink: onLink, height: $height)138 .frame(height: max(40, height))139 .accessibilityLabel(Text("Contenu du message"))140 } else if failed {141 Text(HTMLText.plainText(fromHTML: html)).textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading)142 } else {143 BodySkeleton()144 }145 }146 .task {147 rules = await BodyRenderer.contentRules()148 failed = rules == nil149 }150 }151}152153#if os(macOS)154typealias PlatformViewRepresentable = NSViewRepresentable155#else156typealias PlatformViewRepresentable = UIViewRepresentable157#endif158159struct BodyWebView: PlatformViewRepresentable {160 let document: String161 let rules: WKContentRuleList162 let loader: MailImageSchemeHandler.Loader163 let onLink: (URL) -> Void164 @Binding var height: CGFloat165166 func makeCoordinator() -> Coordinator { Coordinator(self) }167168 private func make(_ context: Context) -> WKWebView {169 let view = BodyRenderer.makeWebView(rules: rules, handler: context.coordinator.handler, heightObserver: HeightRelay(context.coordinator))170 view.navigationDelegate = context.coordinator171 context.coordinator.load(document, in: view)172 return view173 }174 private func update(_ view: WKWebView, _ context: Context) {175 context.coordinator.parent = self176 context.coordinator.load(document, in: view)177 }178 #if os(macOS)179 func makeNSView(context: Context) -> WKWebView { make(context) }180 func updateNSView(_ view: WKWebView, context: Context) { update(view, context) }181 static func dismantleNSView(_ view: WKWebView, coordinator: Coordinator) { view.configuration.userContentController.removeScriptMessageHandler(forName: BodyRenderer.heightMessage, contentWorld: .defaultClient) }182 #else183 func makeUIView(context: Context) -> WKWebView { make(context) }184 func updateUIView(_ view: WKWebView, context: Context) { update(view, context) }185 static func dismantleUIView(_ view: WKWebView, coordinator: Coordinator) { view.configuration.userContentController.removeScriptMessageHandler(forName: BodyRenderer.heightMessage, contentWorld: .defaultClient) }186 #endif187188 /// The user content controller retains its message handlers: the relay holds the coordinator weakly so nothing leaks.189 final class HeightRelay: NSObject, WKScriptMessageHandler {190 weak var coordinator: Coordinator?191 init(_ coordinator: Coordinator) { self.coordinator = coordinator }192 func userContentController(_ controller: WKUserContentController, didReceive message: WKScriptMessage) {193 guard message.name == BodyRenderer.heightMessage, let h = (message.body as? NSNumber)?.doubleValue else { return }194 coordinator?.report(height: h)195 }196 }197198 @MainActor199 final class Coordinator: NSObject, WKNavigationDelegate {200 var parent: BodyWebView201 let handler: MailImageSchemeHandler202 private var loaded: String?203 init(_ parent: BodyWebView) { self.parent = parent; handler = MailImageSchemeHandler(loader: parent.loader) }204205 func load(_ document: String, in view: WKWebView) {206 guard document != loaded else { return }207 loaded = document208 view.loadHTMLString(document, baseURL: nil) // about:blank origin: nothing to be relative to209 }210211 func webView(_ webView: WKWebView, decidePolicyFor action: WKNavigationAction) async -> WKNavigationActionPolicy {212 let url = action.request.url213 if action.navigationType == .linkActivated {214 if let url, ["http", "https", "mailto"].contains(url.scheme?.lowercased() ?? "") { parent.onLink(url) }215 return .cancel216 }217 // the only navigation ever allowed is our own document218 return (url == nil || url?.absoluteString == "about:blank") && action.targetFrame?.isMainFrame != false ? .allow : .cancel219 }220221 /// Height reported by the layout observer (see `BodyRenderer.heightScript`). The binding is written outside the view update.222 func report(height h: Double) {223 guard h > 0 else { return }224 // no margin added: a document sized on its viewport (height:100%) must settle, not grow at every report225 let v = min(CGFloat(h), 60_000)226 guard abs(v - parent.height) > 1 else { return }227 Task { @MainActor [weak self] in self?.parent.height = v }228 }229 }230}231