SPB Git

Repository Public

MermaidBlockView.swift 7.2 KB 162 lines swift

1// SP Notes Core2// File: Sources/SPNotesFeatures/Blocks/MermaidBlockView.swift3// Description: Detail of a `mermaid` node (SPEC §2). The natives never render Mermaid themselves: they show the 2× PNG4//              render the web editor uploaded when it was made from the current source (`previewHash` = sha256 of5//              `code`), otherwise the source with the notice « rendu à mettre à jour depuis le Web ». The source is6//              editable; an edit is handed to the editor through `onChange` and honestly invalidates the render.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import Foundation11import Observation12import SPNotesDesign13import SPNotesDocument14import SwiftUI1516@Observable @MainActor17public final class MermaidBlockModel {18    public enum Preview: Equatable, Sendable {19        /// No render exists for this diagram.20        case none21        /// A render exists but was made from another source.22        case outdated23        /// The render matches the source and is being fetched.24        case loading25        /// The render matches the source.26        case current(Data)27        /// The render matches the source but its file could not be read (offline…).28        case unavailable(FeatureFailure)29    }3031    public private(set) var block: MermaidBlock32    public private(set) var preview: Preview = .none33    public var onChange: ((MermaidBlock) -> Void)?34    private let imageLoader: BlockImageLoader?35    private var loadedFor: String?3637    public init(block: MermaidBlock, imageLoader: BlockImageLoader? = nil, onChange: ((MermaidBlock) -> Void)? = nil) {38        self.block = block39        self.imageLoader = imageLoader40        self.onChange = onChange41        preview = Self.state(of: block, data: nil)42    }4344    public var code: String { block.code }45    public var isPreviewCurrent: Bool { block.isPreviewCurrent }4647    private static func state(of block: MermaidBlock, data: Data?) -> Preview {48        guard block.preview != nil else { return .none }49        guard block.isPreviewCurrent else { return .outdated }50        return data.map(Preview.current) ?? .loading51    }5253    /// Fetches the render when (and only when) it matches the source.54    public func load() async {55        guard block.isPreviewCurrent, let id = block.preview else {56            preview = Self.state(of: block, data: nil)57            return58        }59        if case .current = preview, loadedFor == id { return }60        guard let imageLoader else {61            preview = .unavailable(FeatureFailure(kind: .other, message: L("L'image du rendu n'a pas été fournie à cette vue.")))62            return63        }64        preview = .loading65        do {66            let data = try await imageLoader(id)67            guard block.isPreviewCurrent, block.preview == id else { return }   // edited meanwhile68            if BlockImage.image(from: data, scale: 2) == nil {69                preview = .unavailable(FeatureFailure(kind: .other, message: L("Le rendu enregistré n'est pas une image lisible.")))70            } else {71                loadedFor = id72                cached = data73                preview = .current(data)74            }75        } catch {76            preview = .unavailable(FeatureFailure(error))77        }78    }7980    private var cached: Data?8182    /// Edits the source. The stored render and its hash are kept (the web replaces them): the render is simply no83    /// longer shown while it does not match; typing the original source back shows it again.84    public func setCode(_ code: String) {85        guard code != block.code else { return }86        block.code = code87        if block.isPreviewCurrent, let cached, loadedFor == block.preview { preview = .current(cached) } else { preview = Self.state(of: block, data: nil) }88        onChange?(block)89    }90}9192public struct MermaidBlockView: View {93    @State private var model: MermaidBlockModel94    @State private var draft: String9596    public init(model: MermaidBlockModel) {97        _model = State(initialValue: model)98        _draft = State(initialValue: model.code)99    }100101    public init(block: MermaidBlock, imageLoader: BlockImageLoader? = nil, onChange: ((MermaidBlock) -> Void)? = nil) {102        self.init(model: MermaidBlockModel(block: block, imageLoader: imageLoader, onChange: onChange))103    }104105    public var body: some View {106        BlockDetailContainer(title: L("Diagramme Mermaid"), systemImage: "point.3.connected.trianglepath.dotted") { sizeClass in107            if sizeClass.isCompact {108                VStack(alignment: .leading, spacing: NVSpace.lg) { previewSection; sourceSection }109            } else {110                HStack(alignment: .top, spacing: NVSpace.xl) {111                    previewSection.frame(maxWidth: .infinity, alignment: .topLeading)112                    sourceSection.frame(maxWidth: 420, alignment: .topLeading)113                }114            }115        }116        .task(id: model.isPreviewCurrent) { await model.load() }117    }118119    @ViewBuilder120    private var previewSection: some View {121        VStack(alignment: .leading, spacing: NVSpace.sm) {122            BlockSectionLabel(text: L("Rendu"))123            switch model.preview {124            case .current(let data):125                if let decoded = BlockImage.image(from: data, scale: 2) {126                    decoded.image127                        .resizable()128                        .aspectRatio(decoded.size, contentMode: .fit)129                        .frame(maxWidth: decoded.size.width)130                        .frame(maxWidth: .infinity)131                        .padding(NVSpace.lg)132                        .background(NVColor.bgElevated, in: NVRadius.shape(NVRadius.lg))133                        .overlay(NVRadius.shape(NVRadius.lg).strokeBorder(NVColor.line, lineWidth: 1))134                        .accessibilityLabel(L("Rendu du diagramme"))135                        .accessibilityValue(model.code)136                }137            case .loading:138                FeatureLoadingView(L("Chargement du rendu…")).frame(minHeight: 160)139            case .outdated:140                BlockNotice(systemImage: "arrow.triangle.2.circlepath", text: L("Rendu à mettre à jour depuis le Web : le code a changé depuis le dernier rendu."), tone: .warning)141                BlockCodeText(text: model.code)142            case .none:143                BlockNotice(systemImage: "photo", text: L("Aucun rendu pour ce diagramme. Il sera produit à la prochaine ouverture de la page sur le Web."))144                BlockCodeText(text: model.code)145            case .unavailable(let failure):146                BlockNotice(systemImage: failure.isOffline ? "wifi.slash" : "photo", text: failure.isOffline ? L("Hors ligne : le rendu n'est pas sur cet appareil.") : failure.message)147                BlockCodeText(text: model.code)148            }149        }150    }151152    private var sourceSection: some View {153        VStack(alignment: .leading, spacing: NVSpace.sm) {154            BlockSectionLabel(text: L("Code Mermaid"))155            BlockCodeEditor(text: $draft, label: L("Code Mermaid"), minHeight: 200)156                .onChange(of: draft) { _, value in model.setCode(value) }157            Text(L("Les apps natives n'exécutent pas Mermaid : le rendu vient du Web."))158                .nvFont(.micro).foregroundStyle(NVColor.fgMuted)159        }160    }161}162
Files main
Menu

Theme