SPB Git

Repository Public

StudioPreview.swift 15.7 KB 340 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/Shared/Studio/StudioPreview.swift3// Description: Rendering of templates in the app's isolated renderer (JavaScript off, non-persistent store, every load blocked, CSP) — live preview with4// device width and forced light / dark, lazily rendered library thumbnails cached as snapshots, and a plain code editor for the HTML source.5// Remote https images of a template are fetched by the app through the backend image proxy and served by the custom scheme handler — never directly.6import SPMailCore7import SwiftUI8import UniformTypeIdentifiers9import WebKit1011#if os(macOS)12typealias PlatformImage = NSImage13extension Image { init(platform: PlatformImage) { self.init(nsImage: platform) } }14#else15typealias PlatformImage = UIImage16extension Image { init(platform: PlatformImage) { self.init(uiImage: platform) } }17#endif1819enum TemplateRendering {20    /// Template images: only the proxy scheme, only through `/api/img` with the bearer token.21    static func loader(api: APIClient) -> MailImageSchemeHandler.Loader {22        { url in23            guard url.scheme == HTMLSanitizer.proxyScheme, let remote = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems?.first(where: { $0.name == "u" })?.value,24                  remote.lowercased().hasPrefix("https://") else { return nil }25            return try? await api.proxiedImage(remote)26        }27    }28}2930/// The rendered template at a given width, in the isolated renderer. Its height follows the document (the enclosing view scrolls).31struct TemplateWebPreview: View {32    let document: String33    let width: CGFloat34    let api: APIClient35    @State private var rules: WKContentRuleList?36    @State private var failed = false37    @State private var height: CGFloat = 4803839    var body: some View {40        Group {41            if let rules {42                BodyWebView(document: document, rules: rules, loader: TemplateRendering.loader(api: api), onLink: { _ in }, height: $height)43                    .frame(width: width, height: max(200, height))44            } else if failed {45                Label("Le moteur de rendu isolé n’a pas pu démarrer.", systemImage: "exclamationmark.triangle").foregroundStyle(.secondary).frame(width: width, height: 200)46            } else { ProgressView().frame(width: width, height: 200) }47        }48        .task { rules = await BodyRenderer.contentRules(); failed = rules == nil }49        .accessibilityLabel(Text("Aperçu du modèle"))50    }51}5253// MARK: - thumbnails5455/// Library thumbnails: each template version is rendered once in an off-screen isolated web view (one at a time), snapshotted, and kept56/// in memory and in the app's cache folder under `<id>-v<version>`. Requests of cards that scrolled away are dropped before they render.57@MainActor58final class ThumbnailStore: NSObject, WKNavigationDelegate {59    static let shared = ThumbnailStore()60    static let size = CGSize(width: 600, height: 720)61    private var memory: [String: PlatformImage] = [:]62    private var order: [String] = []63    private var tail: Task<Void, Never>?64    private var web: WKWebView?65    private var handler: MailImageSchemeHandler?66    private var loading: CheckedContinuation<Void, Never>?67    private(set) var rendered = 06869    private var directory: URL { AppConfig.cacheDirectory.appendingPathComponent("thumbnails", isDirectory: true) }70    private func key(_ t: MailTemplate) -> String { "\(t.id)-v\(t.version)" }71    private func file(_ key: String) -> URL { directory.appendingPathComponent(key + ".png") }7273    func cached(_ t: MailTemplate) -> PlatformImage? { memory[key(t)] }7475    private func remember(_ key: String, _ image: PlatformImage) {76        memory[key] = image77        order.append(key)78        if order.count > 240 { memory[order.removeFirst()] = nil }79    }8081    func forget(_ id: String) {82        for k in memory.keys where k.hasPrefix(id + "-v") { memory[k] = nil }83        for f in (try? FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil)) ?? [] where f.lastPathComponent.hasPrefix(id + "-v") { try? FileManager.default.removeItem(at: f) }84    }85    func clear() { memory = [:]; order = []; try? FileManager.default.removeItem(at: directory) }8687    /// The snapshot of this template version: from memory, from disk, or rendered now (queued behind the renders already asked for).88    func image(for t: MailTemplate, api: APIClient) async -> PlatformImage? {89        let key = key(t)90        if let hit = memory[key] { return hit }91        if let data = try? Data(contentsOf: file(key)), let image = PlatformImage(data: data) { remember(key, image); return image }92        let previous = tail93        let job = Task { @MainActor [weak self] () -> PlatformImage? in94            await previous?.value95            guard let self, !Task.isCancelled else { return nil }96            if let hit = self.memory[key] { return hit }97            return await self.render(t, key: key, api: api)98        }99        tail = Task { _ = await job.value }100        return await withTaskCancellationHandler { await job.value } onCancel: { job.cancel() }101    }102103    private func render(_ t: MailTemplate, key: String, api: APIClient) async -> PlatformImage? {104        guard let rules = await BodyRenderer.contentRules(), let r = try? await api.renderTemplate(id: t.id), !Task.isCancelled else { return nil }105        if web == nil {106            let h = MailImageSchemeHandler(loader: TemplateRendering.loader(api: api))107            let v = BodyRenderer.makeWebView(rules: rules, handler: h, passthrough: false)108            v.frame = CGRect(origin: .zero, size: Self.size)109            v.navigationDelegate = self110            #if os(iOS)111            // a web view outside any window does not paint on iOS: parked far outside the visible area of the key window112            v.frame.origin = CGPoint(x: -4000, y: 0)113            v.isUserInteractionEnabled = false114            v.accessibilityElementsHidden = true115            UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first?.keyWindow?.insertSubview(v, at: 0)116            #endif117            web = v; handler = h118        }119        guard let web else { return nil }120        let finished = Task { @MainActor in await withCheckedContinuation { (c: CheckedContinuation<Void, Never>) in self.loading = c } }121        web.loadHTMLString(TemplatePreview.document(html: r.html, scheme: .light), baseURL: nil)122        let timeout = Task { @MainActor [weak self] in try? await Task.sleep(for: .seconds(5)); self?.finishLoading() }123        await finished.value124        timeout.cancel()125        try? await Task.sleep(for: .milliseconds(150)) // first paint126        let config = WKSnapshotConfiguration()127        config.rect = CGRect(origin: .zero, size: Self.size)128        config.snapshotWidth = 360129        guard let image = try? await web.takeSnapshot(configuration: config) else { return nil }130        remember(key, image)131        rendered += 1132        if let png = image.pngData {133            try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)134            try? png.write(to: file(key), options: .atomic)135        }136        return image137    }138139    private func finishLoading() { loading?.resume(); loading = nil }140    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { finishLoading() }141    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { finishLoading() }142    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { finishLoading() }143    func webView(_ webView: WKWebView, decidePolicyFor action: WKNavigationAction) async -> WKNavigationActionPolicy {144        let url = action.request.url145        return action.navigationType != .linkActivated && (url == nil || url?.absoluteString == "about:blank") ? .allow : .cancel146    }147}148149extension PlatformImage {150    #if os(macOS)151    var pngData: Data? {152        guard let tiff = tiffRepresentation, let rep = NSBitmapImageRep(data: tiff) else { return nil }153        return rep.representation(using: .png, properties: [:])154    }155    #else156    var pngData: Data? { pngData() }157    #endif158    /// Share of pixels that differ from the first one — a blank snapshot gives 0 (self-test).159    var contentRatio: Double {160        #if os(macOS)161        guard let cg = cgImage(forProposedRect: nil, context: nil, hints: nil) else { return 0 }162        #else163        guard let cg = cgImage else { return 0 }164        #endif165        let w = 60, h = 72166        var px = [UInt8](repeating: 0, count: w * h * 4)167        guard let ctx = CGContext(data: &px, width: w, height: h, bitsPerComponent: 8, bytesPerRow: w * 4, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { return 0 }168        ctx.draw(cg, in: CGRect(x: 0, y: 0, width: w, height: h))169        var different = 0170        for i in stride(from: 0, to: px.count, by: 4) where abs(Int(px[i]) - Int(px[0])) + abs(Int(px[i + 1]) - Int(px[1])) + abs(Int(px[i + 2]) - Int(px[2])) > 24 { different += 1 }171        return Double(different) / Double(w * h)172    }173}174175struct TemplateThumbnail: View {176    let template: MailTemplate177    let api: APIClient178    @State private var image: PlatformImage?179180    var body: some View {181        ZStack {182            Rectangle().fill(Color.white)183            if let image { Image(platform: image).resizable().interpolation(.medium).aspectRatio(contentMode: .fill) } else { ProgressView().controlSize(.small) }184        }185        .aspectRatio(ThumbnailStore.size.width / ThumbnailStore.size.height, contentMode: .fit)186        .clipped()187        .task(id: "\(template.id)-v\(template.version)") {188            image = ThumbnailStore.shared.cached(template)189            if image == nil { image = await ThumbnailStore.shared.image(for: template, api: api) }190        }191        .accessibilityHidden(true)192    }193}194195// MARK: - source editor196197/// A plain monospaced text view for the HTML source and the text version: no smart quotes, no dashes, no autocorrection, the system's198/// find bar (⌘F), and text storage owned by the platform view so 80 kB stays fluid.199struct CodeEditor: PlatformViewRepresentable {200    @Binding var text: String201    var findToken = 0202203    func makeCoordinator() -> Coordinator { Coordinator(self) }204205    #if os(macOS)206    func makeNSView(context: Context) -> NSScrollView {207        let scroll = NSTextView.scrollableTextView()208        guard let view = scroll.documentView as? NSTextView else { return scroll }209        view.delegate = context.coordinator210        view.font = .monospacedSystemFont(ofSize: 12, weight: .regular)211        view.isAutomaticQuoteSubstitutionEnabled = false212        view.isAutomaticDashSubstitutionEnabled = false213        view.isAutomaticTextReplacementEnabled = false214        view.isAutomaticSpellingCorrectionEnabled = false215        view.isContinuousSpellCheckingEnabled = false216        view.isGrammarCheckingEnabled = false217        view.isRichText = false218        view.allowsUndo = true219        view.usesFindBar = true220        view.isIncrementalSearchingEnabled = true221        view.textContainerInset = NSSize(width: 6, height: 8)222        view.string = text223        view.setAccessibilityLabel(String(localized: "Code source"))224        return scroll225    }226    func updateNSView(_ scroll: NSScrollView, context: Context) {227        context.coordinator.parent = self228        guard let view = scroll.documentView as? NSTextView else { return }229        if view.string != text { view.string = text }230        if context.coordinator.findToken != findToken {231            context.coordinator.findToken = findToken232            let item = NSMenuItem(); item.tag = Int(NSTextFinder.Action.showFindInterface.rawValue)233            view.window?.makeFirstResponder(view)234            view.performFindPanelAction(item)235        }236    }237    #else238    func makeUIView(context: Context) -> UITextView {239        let view = UITextView()240        view.delegate = context.coordinator241        view.font = UIFontMetrics(forTextStyle: .body).scaledFont(for: .monospacedSystemFont(ofSize: 13, weight: .regular))242        view.adjustsFontForContentSizeCategory = true243        view.smartQuotesType = .no244        view.smartDashesType = .no245        view.smartInsertDeleteType = .no246        view.autocorrectionType = .no247        view.autocapitalizationType = .none248        view.spellCheckingType = .no249        view.isFindInteractionEnabled = true250        view.backgroundColor = .clear251        view.text = text252        view.accessibilityLabel = String(localized: "Code source")253        return view254    }255    func updateUIView(_ view: UITextView, context: Context) {256        context.coordinator.parent = self257        if view.text != text { view.text = text }258        if context.coordinator.findToken != findToken {259            context.coordinator.findToken = findToken260            view.becomeFirstResponder()261            view.findInteraction?.presentFindNavigator(showingReplace: false)262        }263    }264    #endif265266    @MainActor267    final class Coordinator: NSObject {268        var parent: CodeEditor269        var findToken: Int270        init(_ parent: CodeEditor) { self.parent = parent; findToken = parent.findToken }271    }272}273274#if os(macOS)275extension CodeEditor.Coordinator: NSTextViewDelegate {276    func textDidChange(_ notification: Notification) {277        guard let view = notification.object as? NSTextView else { return }278        parent.text = view.string279    }280}281#else282extension CodeEditor.Coordinator: UITextViewDelegate {283    func textViewDidChange(_ textView: UITextView) { parent.text = textView.text }284}285#endif286287// MARK: - export288289struct HTMLDocument: FileDocument {290    static let readableContentTypes: [UTType] = [.html, .plainText]291    var data: Data292    init(_ text: String) { data = Data(text.utf8) }293    init(configuration: ReadConfiguration) throws { data = configuration.file.regularFileContents ?? Data() }294    func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper { FileWrapper(regularFileWithContents: data) }295}296297/// A template as an `.html` file for the share sheet and for dragging out of the window (written on demand in the app's private temporary folder).298struct TemplateFile: Transferable {299    let name: String300    let html: String301    static var transferRepresentation: some TransferRepresentation {302        FileRepresentation(exportedContentType: .html) { item in303            let dir = FileManager.default.temporaryDirectory.appendingPathComponent("spmail-files/\(UUID().uuidString)", isDirectory: true)304            try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)305            let url = dir.appendingPathComponent(item.name + ".html")306            try Data(item.html.utf8).write(to: url)307            return SentTransferredFile(url)308        }309    }310}311312enum Clipboard {313    static func copy(_ s: String) {314        #if os(macOS)315        NSPasteboard.general.clearContents(); NSPasteboard.general.setString(s, forType: .string)316        #else317        UIPasteboard.general.string = s318        #endif319    }320}321322extension Color {323    /// `#rrggbb` in sRGB.324    var hex: String {325        #if os(macOS)326        guard let c = NSColor(self).usingColorSpace(.sRGB) else { return "" }327        let (r, g, b) = (c.redComponent, c.greenComponent, c.blueComponent)328        #else329        var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0330        guard UIColor(self).getRed(&r, green: &g, blue: &b, alpha: &a) else { return "" }331        #endif332        func v(_ x: CGFloat) -> Int { Int((min(1, max(0, x)) * 255).rounded()) }333        return String(format: "#%02x%02x%02x", v(r), v(g), v(b))334    }335    init?(hex: String) {336        guard hex.range(of: "^#[0-9a-fA-F]{6}$", options: .regularExpression) != nil, let v = UInt32(hex.dropFirst(), radix: 16) else { return nil }337        self.init(.sRGB, red: Double((v >> 16) & 255) / 255, green: Double((v >> 8) & 255) / 255, blue: Double(v & 255) / 255)338    }339}340
Files main
Menu

Theme