SPB Git

Repository Public

AtomEditors.swift 14.2 KB 227 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Notes/AtomEditors.swift3// Description: Native editors of the blocks handled as a unit: table grid, LaTeX equation with live preview, image and file details, link sheet.4import SwiftUI5import SPNotesDocument6import SPNotesEditor7import SPNotesAPI8import SPNotesDesign910struct AtomEditorSheet: View {11    @Environment(AppEnvironment.self) private var env12    @Environment(WindowModel.self) private var window13    @Environment(\.dismiss) private var dismiss14    let session: NoteSession15    let atom: EditorController.ActiveAtom1617    var body: some View { content.frame(minWidth: 420) }1819    @ViewBuilder private var content: some View {20        let editable = session.isEditable21        let applyNode: (PMNode) -> Void = { apply($0) }22        let removeAtom: () -> Void = { remove() }23        let removeIfEditable: (() -> Void)? = editable ? removeAtom : nil24        // the 3.0 blocks: detail views from the provider (this app's today, SPNotesFeatures' tomorrow)25        if let detail = env.blockDetails.detail(for: atom.node, context: BlockDetailContext(env: env, session: session, editable: editable, router: window, apply: applyNode, remove: removeAtom, dismiss: { dismiss(); session.editor.focus() })) { detail }26        else {27            switch atom.node.type {28            case "table": TableEditor(node: atom.node, editable: editable, onDone: applyNode)29            case "blockMath", "inlineMath", "math": MathEditor(node: atom.node, editable: editable, onDone: applyNode)30            case "image": ImageDetails(node: atom.node, editable: editable, apply: applyNode, remove: removeAtom)31            case "fileBlock": FileDetails(node: atom.node, remove: removeIfEditable)32            default: UnknownBlock(node: atom.node)33            }34        }35    }36    private func apply(_ node: PMNode) { if node != atom.node { session.editor.textView.replaceAtom(at: atom.range, with: node) }; session.editor.refreshCitedCount(); dismiss(); session.editor.focus() }37    private func remove() {38        let v = session.editor.textView39        if atom.isBlock { v.setSelectedRange(atom.range); v.deleteBackward(nil) } else { v.replace(atom.range, with: NSAttributedString(), select: NSRange(location: atom.range.location, length: 0), actionName: "Supprimer") }40        dismiss(); session.editor.focus()41    }42}4344/// Spreadsheet-like grid over the table node. Cells are edited as plain text; a cell that is not touched keeps its45/// formatted content (the shared document module only rewrites cells whose text changed).46struct TableEditor: View {47    @Environment(\.dismiss) private var dismiss48    @State private var node: PMNode49    @State private var texts: [[String]]50    @FocusState private var focus: Cell?51    let editable: Bool52    let onDone: (PMNode) -> Void53    struct Cell: Hashable { let r: Int, c: Int }5455    init(node: PMNode, editable: Bool, onDone: @escaping (PMNode) -> Void) {56        _node = State(initialValue: node); _texts = State(initialValue: node.tableGrid.map { $0.map(\.text) }); self.editable = editable; self.onDone = onDone57    }58    private var rows: Int { texts.count }59    private var cols: Int { texts.map(\.count).max() ?? 0 }60    private var hasHeader: Bool { node.tableGrid.first?.contains { $0.isHeader } ?? false }6162    var body: some View {63        VStack(alignment: .leading, spacing: 12) {64            HStack {65                Text("Tableau").font(.headline); Text("\(rows) × \(cols)").foregroundStyle(.secondary)66                Spacer()67                Toggle("Ligne d'en-tête", isOn: Binding(get: { hasHeader }, set: { _ in commitTexts(); _ = node.toggleTableHeaderRow() })).toggleStyle(.checkbox).disabled(!editable)68            }69            ScrollView([.horizontal, .vertical]) {70                Grid(horizontalSpacing: 4, verticalSpacing: 4) {71                    ForEach(0..<rows, id: \.self) { r in72                        GridRow {73                            ForEach(0..<texts[r].count, id: \.self) { c in74                                TextField("", text: Binding(get: { texts[r][c] }, set: { texts[r][c] = $0 }), axis: .vertical)75                                    .textFieldStyle(.plain).lineLimit(1...6).font(hasHeader && r == 0 ? .body.weight(.semibold) : .body)76                                    .padding(6).frame(minWidth: 110, maxWidth: 220, alignment: .leading)77                                    .background(hasHeader && r == 0 ? NVColor.bgHover : Color.clear).overlay(Rectangle().strokeBorder(Color.primary.opacity(focus == Cell(r: r, c: c) ? 0.5 : 0.15)))78                                    .focused($focus, equals: Cell(r: r, c: c)).disabled(!editable)79                                    .accessibilityLabel("Ligne \(r + 1), colonne \(c + 1)")80                            }81                        }82                    }83                }.padding(2)84            }.frame(maxHeight: 360)85            HStack {86                Menu("Lignes") {87                    Button("Ajouter au-dessus") { structural { $0.insertTableRow(at: focus?.r ?? 0) } }88                    Button("Ajouter en dessous") { structural { $0.insertTableRow(at: (focus?.r ?? rows - 1) + 1) } }89                    Button("Supprimer la ligne", role: .destructive) { structural { $0.deleteTableRow(at: focus?.r ?? rows - 1) } }.disabled(rows <= 1)90                }.fixedSize()91                Menu("Colonnes") {92                    Button("Ajouter à gauche") { structural { $0.insertTableColumn(at: focus?.c ?? 0) } }93                    Button("Ajouter à droite") { structural { $0.insertTableColumn(at: (focus?.c ?? cols - 1) + 1) } }94                    Button("Supprimer la colonne", role: .destructive) { structural { $0.deleteTableColumn(at: focus?.c ?? cols - 1) } }.disabled(cols <= 1)95                }.fixedSize()96                Spacer()97                Button("Annuler", role: .cancel) { dismiss() }.keyboardShortcut(.cancelAction)98                Button("Terminé") { commitTexts(); onDone(node) }.keyboardShortcut(.defaultAction).disabled(!editable)99            }.disabled(!editable && false)100        }101        .padding(18).frame(minWidth: 520)102        .onAppear { focus = Cell(r: 0, c: 0) }103    }104    private func commitTexts() { for r in 0..<texts.count { for c in 0..<texts[r].count { _ = node.setTableCellText(texts[r][c], row: r, column: c) } } }105    private func structural(_ change: (inout PMNode) -> Bool) { commitTexts(); _ = change(&node); texts = node.tableGrid.map { $0.map(\.text) } }106}107108struct MathEditor: View {109    @Environment(\.dismiss) private var dismiss110    @State private var latex: String111    let node: PMNode, editable: Bool112    let onDone: (PMNode) -> Void113    init(node: PMNode, editable: Bool, onDone: @escaping (PMNode) -> Void) {114        self.node = node; self.editable = editable; self.onDone = onDone115        var l = ""; if case .string(let s)? = node.attrs?["latex"] { l = s }116        _latex = State(initialValue: l)117    }118    private var display: Bool { node.type == "blockMath" }119    var body: some View {120        VStack(alignment: .leading, spacing: 12) {121            Text(display ? "Équation" : "Équation en ligne").font(.headline)122            TextEditor(text: $latex).font(.system(.body, design: .monospaced)).frame(minHeight: 70, maxHeight: 160).scrollContentBackground(.hidden).padding(6)123                .background(NVColor.bgHover, in: RoundedRectangle(cornerRadius: 7)).disabled(!editable).accessibilityLabel("Source LaTeX")124            GroupBox {125                Group {126                    if latex.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { Text("Saisis du LaTeX, par exemple \\frac{a}{b}").foregroundStyle(.tertiary) }127                    else if let img = EditorImages.math(latex, fontSize: 20, display: display) { Image(nsImage: img).renderingMode(.template).foregroundStyle(.primary) }128                    else { Label("Formule non reconnue — elle sera conservée telle quelle", systemImage: "exclamationmark.triangle").foregroundStyle(NVColor.warningText).font(.callout) }129                }.frame(maxWidth: .infinity, minHeight: 60).padding(6)130            }131            HStack { Spacer(); Button("Annuler", role: .cancel) { dismiss() }.keyboardShortcut(.cancelAction)132                Button("Terminé") { var n = node; var a = n.attrs ?? [:]; a["latex"] = .string(latex); n.attrs = a; onDone(n) }.keyboardShortcut(.defaultAction).disabled(!editable) }133        }.padding(18).frame(width: 460)134    }135}136137struct ImageDetails: View {138    @Environment(AppEnvironment.self) private var env139    @Environment(\.dismiss) private var dismiss140    let node: PMNode, editable: Bool141    let apply: (PMNode) -> Void142    let remove: () -> Void143    @State private var alt = ""144    private var src: String { if case .string(let s)? = node.attrs?["src"] { return s }; return "" }145    var body: some View {146        VStack(alignment: .leading, spacing: 12) {147            Text("Image").font(.headline)148            if let img = env.localImage(for: src) { Image(nsImage: img).resizable().scaledToFit().frame(maxHeight: 280).clipShape(RoundedRectangle(cornerRadius: 6)) }149            else { Label(src.hasPrefix("/api/files/") ? "L'image n'est pas encore sur ce Mac." : src, systemImage: "photo").foregroundStyle(.secondary) }150            TextField("Description (texte alternatif)", text: $alt).disabled(!editable)151            HStack {152                if let id = NotesAPI.fileID(fromSource: src) {153                    Button("Coup d'œil") { Task { await AttachmentService(env: env).preview(attachmentId: id, name: alt.isEmpty ? nil : alt) } }154                    Button("Enregistrer sous…") { Task { await AttachmentService(env: env).saveCopy(attachmentId: id, name: alt.isEmpty ? "image.png" : alt) } }155                }156                if editable { Button("Retirer de la note", role: .destructive, action: remove) }157                Spacer()158                Button("Annuler", role: .cancel) { dismiss() }.keyboardShortcut(.cancelAction)159                Button("Terminé") { var n = node; var a = n.attrs ?? [:]; a["alt"] = alt.isEmpty ? .null : .string(alt); n.attrs = a; apply(n) }.keyboardShortcut(.defaultAction)160            }161        }162        .padding(18).frame(width: 480)163        .onAppear { if case .string(let s)? = node.attrs?["alt"] { alt = s } }164    }165}166167struct FileDetails: View {168    @Environment(AppEnvironment.self) private var env169    @Environment(\.dismiss) private var dismiss170    let node: PMNode171    let remove: (() -> Void)?172    private func attr(_ k: String) -> String { if case .string(let s)? = node.attrs?[k] { return s }; return "" }173    private var size: Int64 { if case .int(let n)? = node.attrs?["size"] { return n }; return 0 }174    var body: some View {175        VStack(alignment: .leading, spacing: 12) {176            Label(attr("name").isEmpty ? "Fichier" : attr("name"), systemImage: "paperclip").font(.headline)177            Text([size > 0 ? Format.bytes(size) : nil, attr("mime").isEmpty ? nil : attr("mime")].compactMap { $0 }.joined(separator: " · ")).foregroundStyle(.secondary).font(.callout)178            HStack {179                if let id = NotesAPI.fileID(fromSource: attr("src")) ?? (attr("attachmentId").isEmpty ? nil : attr("attachmentId")) {180                    Button("Coup d'œil") { Task { await AttachmentService(env: env).preview(attachmentId: id, name: attr("name")) } }.keyboardShortcut(.defaultAction)181                    Button("Enregistrer sous…") { Task { await AttachmentService(env: env).saveCopy(attachmentId: id, name: attr("name")) } }182                    Toggle("Conserver hors ligne", isOn: Binding(get: { keep }, set: { v in keep = v; Task { try? await env.store.setAttachmentKeepOffline(id: id, v); if v { _ = try? await env.syncMonitor.download(attachmentId: id) } } })).toggleStyle(.checkbox)183                }184                if let remove { Button("Retirer", role: .destructive, action: remove) }185                Spacer(); Button("Fermer") { dismiss() }.keyboardShortcut(.cancelAction)186            }187        }188        .padding(18).frame(width: 520)189        .task { if let id = NotesAPI.fileID(fromSource: attr("src")), let rec = try? await env.store.attachment(id: id) { keep = rec.keepOffline } }190    }191    @State private var keep = false192}193194struct UnknownBlock: View {195    @Environment(\.dismiss) private var dismiss196    let node: PMNode197    var body: some View {198        VStack(alignment: .leading, spacing: 12) {199            Label("Bloc non pris en charge", systemImage: "square.dashed").font(.headline)200            Text("Le type « \(node.type) » vient d'une version plus récente et n'a pas d'éditeur dans cette version de SP Notes. Il est conservé tel quel, sans aucune modification, et reste modifiable sur note.spboucher.ai.").fixedSize(horizontal: false, vertical: true).foregroundStyle(.secondary)201            HStack { Spacer(); Button("Fermer") { dismiss() }.keyboardShortcut(.defaultAction) }202        }.padding(18).frame(width: 420)203    }204}205206struct LinkEditorSheet: View {207    @Environment(\.dismiss) private var dismiss208    @State var draft: NoteEditorPane.LinkDraft209    let apply: (String, String) -> Void210    var body: some View {211        VStack(alignment: .leading, spacing: 12) {212            Text(draft.existing ? "Modifier le lien" : "Insérer un lien").font(.headline)213            TextField("https://…", text: $draft.href).accessibilityIdentifier("link-url")214            if !draft.hasSelection { TextField("Texte affiché (facultatif)", text: $draft.text) }215            if !valid, !draft.href.isEmpty { Text("Adresse acceptée : http, https ou mailto.").font(.caption).foregroundStyle(NVColor.warningText) }216            HStack {217                if draft.existing { Button("Retirer le lien", role: .destructive) { apply("", ""); dismiss() } }218                Spacer()219                Button("Annuler", role: .cancel) { dismiss() }.keyboardShortcut(.cancelAction)220                Button("OK") { apply(normalized, draft.text); dismiss() }.keyboardShortcut(.defaultAction).disabled(!valid)221            }222        }.padding(18).frame(width: 420)223    }224    private var normalized: String { let h = draft.href.trimmingCharacters(in: .whitespaces); return h.contains(":") || h.hasPrefix("/") ? h : "https://" + h }225    private var valid: Bool { guard let u = URL(string: normalized), let s = u.scheme?.lowercased() else { return false }; return ["http", "https", "mailto"].contains(s) && !draft.href.trimmingCharacters(in: .whitespaces).isEmpty }226}227
Files main
Menu

Theme