SPB Git

Repository Public

HTMLView.swift 6.9 KB 163 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Immo-Ka Admin iOS9// File             : ImmoKaAdmin/Features/HTMLView.swift10// Description      : « Afficher la mise en forme » d'un courriel, dans une vue11//                    isolée. Quatre barrières, chacune suffisante pour les12//                    scripts ou pour les chargements : JavaScript désactivé ;13//                    règle de contenu qui bloque toute requête réseau ;14//                    politique de sécurité du document (`default-src 'none'`) ;15//                    toute navigation refusée (les liens sont inertes). Magasin16//                    de données non persistant.17// Module           : ImmoKaAdmin18// Repository       : https://git.spboucher.ai/immo-ka-admin-ios19// Project Website  : https://www.immo-ka.com20// Created          : 2026-11-3021// Last Modified    : 2026-11-3022//23// =============================================================================24// AUTHOR & PROFESSIONAL AFFILIATION25// =============================================================================26//27// Author           : Simon-Pierre Boucher28// Position         : Professor of Finance29// Institution      : Université du Québec en Outaouais (UQO)30// Department       : Département des sciences administratives31// Organization     : SP Boucher32//33// Website          : https://spboucher.ai34// Git              : https://git.spboucher.ai35//36// =============================================================================37// OFFICIAL CONTACT DIRECTORY38// =============================================================================39//40// General          : info@spboucher.ai41// Professional     : contact@spboucher.ai42// Direct           : simon@spboucher.ai43// Research         : research@spboucher.ai44// Development      : dev@spboucher.ai45// Support          : support@spboucher.ai46// Security/Admin   : admin@spboucher.ai47// Notifications    : notifications@spboucher.ai48//49// Preferred Contact: support@spboucher.ai50//51// =============================================================================52// COPYRIGHT & INTELLECTUAL PROPERTY53// =============================================================================54//55// Copyright (c) 202656// Simon-Pierre Boucher57//58// All rights reserved where applicable.59//60// This file is governed by the applicable project license,61// copyright notices, institutional agreements and relevant law.62//63// Unless expressly authorized by the applicable license or64// rights holder, copying, redistribution, sublicensing,65// publication and commercial exploitation are not permitted.66//67// Existing third-party rights and notices remain unaffected.68//69// =============================================================================70// CONFIDENTIALITY & SECURITY71// =============================================================================72//73// Classification   : Public74// Distribution     : Public repository; use is governed by the project license75// Security Contact : admin@spboucher.ai76//77// Access to this source does not independently grant permission78// to redistribute or disclose confidential materials.79//80// Do not embed credentials, private keys, access tokens,81// certificates or confidential personal information.82//83// =============================================================================84// LICENSE & MAINTENANCE85// =============================================================================86//87// License          : None specified (no license file in this repository)88// Maintainer       : Simon-Pierre Boucher89// Technical Contact: dev@spboucher.ai90//91// =============================================================================92// END OF SP BOUCHER SOURCE HEADER93// =============================================================================9495import SwiftUI96import WebKit9798enum IsolatedWeb {99    /// Bloque tout chargement, quelle que soit l'adresse.100    static let blockAllRule = #"[{"trigger":{"url-filter":".*"},"action":{"type":"block"}}]"#101102    @MainActor103    static func configuration() -> WKWebViewConfiguration {104        let cfg = WKWebViewConfiguration()105        cfg.websiteDataStore = .nonPersistent()106        cfg.defaultWebpagePreferences.allowsContentJavaScript = false107        cfg.preferences.javaScriptCanOpenWindowsAutomatically = false108        cfg.allowsInlineMediaPlayback = false109        cfg.mediaTypesRequiringUserActionForPlayback = .all110        cfg.dataDetectorTypes = []111        cfg.suppressesIncrementalRendering = true112        return cfg113    }114115    /// Une navigation n'est permise que pour le document remis par l'app (`about:blank`), jamais vers ailleurs.116    static func allows(_ url: URL?, type: WKNavigationType) -> Bool {117        type == .other && (url == nil || url?.absoluteString == "about:blank")118    }119}120121struct HTMLView: UIViewRepresentable {122    let html: String123124    func makeCoordinator() -> Coordinator { Coordinator() }125126    func makeUIView(context: Context) -> WKWebView {127        let view = WKWebView(frame: .zero, configuration: IsolatedWeb.configuration())128        view.navigationDelegate = context.coordinator129        view.allowsLinkPreview = false130        view.allowsBackForwardNavigationGestures = false131        view.isOpaque = false132        view.backgroundColor = .white133        context.coordinator.load(html, in: view)134        return view135    }136137    func updateUIView(_ view: WKWebView, context: Context) {138        if context.coordinator.loaded != html { context.coordinator.load(html, in: view) }139    }140141    @MainActor142    final class Coordinator: NSObject, WKNavigationDelegate {143        var loaded: String?144145        /// Le document n'est chargé qu'une fois la règle de blocage compilée et posée : sans elle, rien n'est affiché.146        func load(_ html: String, in view: WKWebView) {147            loaded = html148            WKContentRuleListStore.default().compileContentRuleList(forIdentifier: "immoka-admin-tout-bloquer", encodedContentRuleList: IsolatedWeb.blockAllRule) { [weak view] list, _ in149                Task { @MainActor in150                    guard let view, let list else { return }151                    view.configuration.userContentController.removeAllContentRuleLists()152                    view.configuration.userContentController.add(list)153                    view.loadHTMLString(MailLogic.isolatedHTMLDocument(html), baseURL: nil)154                }155            }156        }157158        func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction) async -> WKNavigationActionPolicy {159            IsolatedWeb.allows(navigationAction.request.url, type: navigationAction.navigationType) ? .allow : .cancel160        }161    }162}163
Files main
Menu

Theme