SPB Git

Repository Public

RunCodeBlockView.swift 5.6 KB 130 lines swift

1// SP Notes Core2// File: Sources/SPNotesFeatures/Blocks/RunCodeBlockView.swift3// Description: Detail of a `runCode` node (SPEC §2): the language, the code (editable, handed back through `onChange`)4//              and the last output written by the web sandbox. Nothing is executed here — the native apps embed no5//              script engine — and the view says so.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import Foundation10import Observation11import SPNotesDesign12import SPNotesDocument13import SwiftUI1415@Observable @MainActor16public final class RunCodeBlockModel {17    public private(set) var block: RunCodeBlock18    /// The code was edited in this view since the output was shown: the output describes an older version.19    public private(set) var editedSinceOutput = false20    public var onChange: ((RunCodeBlock) -> Void)?21    private let originalCode: String2223    public init(block: RunCodeBlock, onChange: ((RunCodeBlock) -> Void)? = nil) {24        self.block = block25        self.onChange = onChange26        originalCode = block.code27    }2829    public var code: String { block.code }30    public var language: String { block.language }31    public var output: RunCodeOutput? { block.output }3233    /// Edits the code. The stored output is kept (only a run on the web replaces it) and flagged as older.34    public func setCode(_ code: String) {35        guard code != block.code else { return }36        block.code = code37        editedSinceOutput = block.output != nil && code != originalCode38        onChange?(block)39    }4041    /// « 12 ms · 19 nov. 2026 à 13:22 » — what is known about the last run.42    public func outputCaption(timeZone: TimeZone = .current) -> String? {43        guard let output else { return nil }44        var parts: [String] = []45        if let ms = output.milliseconds { parts.append(LF("%@ ms", RunCodeBlockModel.milliseconds(ms))) }46        if let at = output.at, let date = TaskItemDetail.date(from: at) { parts.append(FeatureFormat.dayTime(date, timeZone: timeZone)) }47        return parts.isEmpty ? nil : parts.joined(separator: " · ")48    }4950    static func milliseconds(_ value: Double) -> String {51        value == value.rounded() ? String(Int(value)) : String(format: "%.1f", value).replacingOccurrences(of: ".", with: ",")52    }5354    public static func languageLabel(_ language: String) -> String {55        switch language.lowercased() {56        case "javascript", "js": return "JavaScript"57        case "typescript", "ts": return "TypeScript"58        case "python", "py": return "Python"59        case "": return L("Code")60        default: return language61        }62    }63}6465public struct RunCodeBlockView: View {66    @State private var model: RunCodeBlockModel67    @State private var draft: String6869    public init(model: RunCodeBlockModel) {70        _model = State(initialValue: model)71        _draft = State(initialValue: model.code)72    }7374    public init(block: RunCodeBlock, onChange: ((RunCodeBlock) -> Void)? = nil) {75        self.init(model: RunCodeBlockModel(block: block, onChange: onChange))76    }7778    public var body: some View {79        BlockDetailContainer(title: L("Code exécutable"), systemImage: "chevron.left.forwardslash.chevron.right", accessory: {80            NVChip(RunCodeBlockModel.languageLabel(model.language), systemImage: "curlybraces")81                .accessibilityLabel(LF("Langage : %@", RunCodeBlockModel.languageLabel(model.language)))82        }) { sizeClass in83            VStack(alignment: .leading, spacing: NVSpace.lg) {84                BlockNotice(systemImage: "globe", text: L("L'exécution se fait sur le Web, dans un bac à sable. Ici vous pouvez lire et modifier le code et consulter la dernière sortie."))85                if sizeClass.isCompact {86                    codeSection87                    outputSection88                } else {89                    HStack(alignment: .top, spacing: NVSpace.xl) {90                        codeSection.frame(maxWidth: .infinity, alignment: .topLeading)91                        outputSection.frame(maxWidth: .infinity, alignment: .topLeading)92                    }93                }94            }95        }96    }9798    private var codeSection: some View {99        VStack(alignment: .leading, spacing: NVSpace.sm) {100            BlockSectionLabel(text: L("Code"))101            BlockCodeEditor(text: $draft, label: L("Code"), minHeight: 220)102                .onChange(of: draft) { _, value in model.setCode(value) }103        }104    }105106    @ViewBuilder107    private var outputSection: some View {108        VStack(alignment: .leading, spacing: NVSpace.sm) {109            HStack(spacing: NVSpace.sm) {110                BlockSectionLabel(text: L("Dernière sortie"))111                if let output = model.output {112                    NVChip(output.isError ? L("Erreur") : L("Réussie"), systemImage: output.isError ? "xmark.octagon" : "checkmark.circle", tone: output.isError ? .danger : .neutral)113                }114                Spacer(minLength: 0)115            }116            if let output = model.output {117                BlockCodeText(text: output.text.isEmpty ? L("(sortie vide)") : output.text, tone: output.isError ? .danger : .neutral)118                if let caption = model.outputCaption() {119                    Text(caption).nvFont(.micro).foregroundStyle(NVColor.fgMuted)120                }121                if model.editedSinceOutput {122                    BlockNotice(systemImage: "clock.arrow.circlepath", text: L("Le code a changé depuis cette exécution : relancez-le sur le Web pour mettre la sortie à jour."), tone: .warning)123                }124            } else {125                Text(L("Ce bloc n'a pas encore été exécuté.")).nvFont(.body).foregroundStyle(NVColor.fgMuted)126            }127        }128    }129}130
Files main
Menu

Theme