SPB Git

Repository Public

EditorInsertions.swift 7.0 KB 79 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Notes/EditorInsertions.swift3// Description: The one list of what can be inserted in a note — legacy blocks and every 3.0 block — used by the Insert menu, the toolbar, the « / » menu and the command center, so that an entry cannot exist in one place and be missing in another.4import SwiftUI5import UniformTypeIdentifiers6import SPNotesDocument7import SPNotesEditor8import SPNotesAPI910struct EditorInsertion: Identifiable {11    let id: String, title: String, symbol: String12    var subtitle: String? = nil13    var group = "Blocs"14    var keywords = ""15    /// True for the entries the editor module already lists in its own « / » menu.16    var builtin = false17    let run: (NoteTextView) -> Void18}1920@MainActor enum EditorInsertions {21    static func all(window: WindowModel, env: AppEnvironment) -> [EditorInsertion] {22        guard let session = window.session else { return [] }23        let editor = session.editor24        return [25            EditorInsertion(id: "table", title: "Tableau", symbol: "tablecells", group: "Blocs", keywords: "table", builtin: true) { v in v.insertTable(); v.activateInsertedAtom() },26            EditorInsertion(id: "divider", title: "Séparateur", symbol: "minus", group: "Blocs", builtin: true) { $0.insertRule() },27            EditorInsertion(id: "math", title: "Équation", symbol: "sum", group: "Blocs", keywords: "latex", builtin: true) { v in v.insertBlockMath(""); v.activateInsertedAtom() },28            EditorInsertion(id: "imath", title: "Équation en ligne", symbol: "x.squareroot", group: "Blocs", builtin: true) { v in v.insertInlineMath("x"); v.activateInsertedAtom() },29            EditorInsertion(id: "toggle", title: "Section repliable", symbol: "chevron.right.square", group: "Blocs", keywords: "details toggle", builtin: true) { $0.insertDetails() },30            EditorInsertion(id: "footnote", title: "Note de bas de page", symbol: "textformat.superscript", group: "Blocs", keywords: "footnote", builtin: true) { $0.insertFootnote() },31            EditorInsertion(id: "image", title: "Image…", symbol: "photo", subtitle: "Depuis un fichier", group: "Médias") { _ in editor.requestFile = (true, UUID()) },32            EditorInsertion(id: "file", title: "Fichier…", symbol: "paperclip", subtitle: "Pièce jointe", group: "Médias") { _ in editor.requestFile = (false, UUID()) },33            EditorInsertion(id: "pdf", title: "PDF annotable…", symbol: "doc.richtext", subtitle: "Première page affichée dans la note", group: "Médias", keywords: "pdf") { v in attach(types: [.pdf], session: session, env: env) { a in v.insertPDF(attachmentId: a.id, name: a.name) } },34            EditorInsertion(id: "record", title: "Note vocale (enregistrer)…", symbol: "mic", subtitle: "Micro du Mac, transcription sur demande", group: "Médias", keywords: "audio voice record micro") { _ in editor.sheet = .audioRecording },35            EditorInsertion(id: "audio", title: "Note vocale (fichier audio)…", symbol: "waveform", subtitle: "m4a, mp3, wav", group: "Médias", keywords: "audio voice") { v in attach(types: [.audio], session: session, env: env) { a in v.insertAudio(attachmentId: a.id, duration: a.duration ?? 0, title: (a.name as NSString).deletingPathExtension, recordedAt: nil) } },36            EditorInsertion(id: "drawing", title: "Dessin", symbol: "scribble.variable", subtitle: "Encre sur iPad ou sur le Web", group: "Médias", keywords: "drawing ink", builtin: true) { $0.insertDrawing() },37            EditorInsertion(id: "mermaid", title: "Diagramme Mermaid", symbol: "point.3.connected.trianglepath.dotted", group: "Blocs 3.0", keywords: "mermaid flowchart", builtin: true) { v in v.insertMermaid(); v.activateInsertedAtom() },38            EditorInsertion(id: "chart", title: "Graphique", symbol: "chart.bar.xaxis", group: "Blocs 3.0", keywords: "chart", builtin: true) { v in v.insertChart(); v.activateInsertedAtom() },39            EditorInsertion(id: "runcode", title: "Code exécutable", symbol: "play.rectangle", group: "Blocs 3.0", keywords: "run code javascript", builtin: true) { v in v.insertRunCode(); v.activateInsertedAtom() },40            EditorInsertion(id: "query", title: "Vue dynamique", symbol: "rectangle.stack.badge.play", group: "Blocs 3.0", keywords: "query view living", builtin: true) { v in v.insertQueryView(); v.activateInsertedAtom() },41            EditorInsertion(id: "blockref", title: "Référence à un bloc…", symbol: "arrow.turn.down.right", subtitle: "Affiche un bloc d'une autre note", group: "Blocs 3.0", keywords: "transclusion embed") { _ in editor.sheet = .blockRef },42            EditorInsertion(id: "citation", title: "Citation de référence…", symbol: "quote.opening", subtitle: "Auteur et année, avec localisateur", group: "Blocs 3.0", keywords: "cite reference") { _ in editor.sheet = .citation },43            EditorInsertion(id: "bibliography", title: "Bibliographie", symbol: "books.vertical", group: "Blocs 3.0", keywords: "references", builtin: true) { $0.insertBibliography() },44            EditorInsertion(id: "canvas", title: "Lien vers un canvas…", symbol: "square.on.square.dashed", group: "Blocs 3.0", keywords: "canvas whiteboard") { _ in editor.sheet = .canvasLink },45            EditorInsertion(id: "link", title: "Lien vers une note", symbol: "link", subtitle: "Tape @ puis le titre", group: "Liens") { v in v.insertText("@", replacementRange: NSRange(location: NSNotFound, length: 0)) },46        ]47    }4849    /// Chooses one file, stores it as an attachment of the note, then inserts the block that shows it.50    private static func attach(types: [UTType], session: NoteSession, env: AppEnvironment, insert: @escaping (AttachedFile) -> Void) {51        let panel = NSOpenPanel(); panel.allowsMultipleSelection = false; panel.canChooseDirectories = false; panel.allowedContentTypes = types52        panel.begin { r in53            guard r == .OK, let url = panel.url else { return }54            Task { @MainActor in55                do { let a = try await AttachmentService(env: env).importFile(url, pageId: session.id); insert(AttachedFile(id: a.id, name: a.name, duration: await AttachedFile.duration(of: url))) }56                catch { env.toasts.error(error) }57            }58        }59    }60}6162struct AttachedFile {63    let id: String, name: String, duration: Double?64    /// Duration of an audio file, read by AVFoundation (nil for anything else).65    static func duration(of url: URL) async -> Double? {66        guard UTType(filenameExtension: url.pathExtension)?.conforms(to: .audio) == true else { return nil }67        return await AudioProbe.duration(url)68    }69}7071/// « Auteur Année » of a research reference, as the web writes the cached label of a citation.72enum CitationFormat {73    static func label(_ r: ResearchReference) -> String {74        let names = (r.authors ?? []).compactMap { $0.split(separator: " ").last.map(String.init) }75        let who = names.isEmpty ? r.citeKey : names.count == 1 ? names[0] : names.count == 2 ? "\(names[0]) et \(names[1])" : "\(names[0]) et al."76        return r.year.map { "\(who) \($0)" } ?? who77    }78}79
Files main
Menu

Theme