SPB Git

Repository Public

EditorCommands.swift 23.4 KB 365 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Editor/EditorCommands.swift3// Description: Editing commands of the note editor: block types, lists, quotes, indentation, marks, links, atoms (tables, rules, equations, images, mentions), block moves, Markdown insertion.4import AppKit5import SPNotesDocument67public enum BlockKind: Equatable, Sendable {8    case paragraph, heading(Int), code, bullet, ordered(start: Int), task, quote, callout9}1011/// What the toolbar and the menus need to know about the selection.12public struct SelectionState: Equatable, Sendable {13    public var marks: Set<String> = []14    public var block: BlockKind = .paragraph15    public var inQuote = false16    public var inList = false17    public var linkHref: String?18    public var hasSelection = false19    public var onAtom = false20    public var words = 021    /// Kind of the callout around the caret (3.0: note, info, warning, danger, success, decision, question, hypothesis).22    public var calloutKind: String?23    /// The caret is in a task item (due date and priority apply).24    public var inTask = false25    public var inAIBlock = false26    /// Node type of the selected block atom (mermaid, chart, pdf, table…).27    public var atomType: String?28    public init() {}2930    /// What the toolbar morphs to (signature motion 2): the controls that make sense for the block under the caret.31    public enum Context: Hashable, Sendable { case text, heading, list, task, code, callout, ai, atom(String) }32    public var context: Context {33        if let atomType { return .atom(atomType) }34        if block == .code { return .code }35        if inTask { return .task }36        if calloutKind != nil { return .callout }37        if inAIBlock { return .ai }38        if inList { return .list }39        if case .heading = block { return .heading }40        return .text41    }42}4344public extension NoteTextView {45    // MARK: State4647    var selectionState: SelectionState {48        var s = SelectionState()49        let sel = selectedRange(); let style = paraStyle(at: sel.location)50        let marks = activeMarks()51        s.marks = Set(marks.marks.map(\.type)); s.hasSelection = sel.length > 0; s.onAtom = style.isAtom52        s.linkHref = marks.href ?? (sel.length == 0 ? link(at: sel.location)?.href ?? (sel.location > 0 ? link(at: sel.location - 1)?.href : nil) : nil)53        s.inQuote = style.path.contains { $0.type == "blockquote" }54        s.calloutKind = style.path.last { $0.type == "callout" }.map { $0.attrs["kind"]?.string ?? "note" }55        s.inTask = style.item?.item.type == "taskItem"; s.inAIBlock = style.path.contains { $0.type == "aiBlock" }56        if style.isAtom, let a = storage.attribute(.attachment, at: paragraphRange(at: sel.location).location, effectiveRange: nil) as? AtomAttachment { s.atomType = a.node.type }57        if let it = style.item { s.inList = true; s.block = it.list.type == "bulletList" ? .bullet : it.list.type == "orderedList" ? .ordered(start: it.list.attrs["start"]?.int ?? 1) : .task }58        else if let l = style.headingLevel { s.block = .heading(l) }59        else if style.isCode { s.block = .code }60        else if style.path.last?.type == "callout" { s.block = .callout }61        else if s.inQuote { s.block = .quote }62        return s63    }6465    private var selectedParagraphs: NSRange {66        let sel = selectedRange(); let ns = storage.string as NSString67        guard ns.length > 0 else { return sel }68        return ns.paragraphRange(for: NSRange(location: min(sel.location, ns.length - 1), length: min(sel.length, ns.length - min(sel.location, ns.length - 1))))69    }7071    // MARK: Blocks7273    /// Sets the block type of the selected paragraphs. With `toggle`, applying the type a paragraph already has removes it.74    func setBlock(_ kind: BlockKind, toggle: Bool = true) {75        let range = selectedParagraphs76        let current = selectionState.block77        switch kind {78        case .paragraph:79            restyleParagraphs(in: range, actionName: "Texte") { s, _ in s.isAtom ? s : s.type == "paragraph" ? s : self.newParagraphStyle(path: s.path) }80        case .heading(let level):81            let lv = min(3, max(1, level)); let off = toggle && current == .heading(lv)82            restyleParagraphs(in: range, actionName: off ? "Texte" : "Titre \(lv)") { s, _ in83                if s.isAtom || s.isCode { return s }84                var keep: [String: JSONValue] = ["level": .int(Int64(lv))]; if let id = s.attrs["id"] { keep["id"] = id }85                return off ? self.newParagraphStyle(path: s.path, attrs: s.attrs["id"].map { ["id": $0] } ?? [:]) : self.newParagraphStyle(path: s.path, type: "heading", attrs: keep)86            }87        case .code:88            if toggle, current == .code {89                // each line of the block becomes a paragraph of its own90                restyleParagraphs(in: codeBlockRange(at: range.location), actionName: "Texte", perParagraph: true) { s, _ in s.isCode ? self.newParagraphStyle(path: s.path) : s }91            } else {92                // the selected paragraphs become the lines of one block; marks do not exist in code93                let code = newParagraphStyle(path: paraStyle(at: range.location).path.filter { !Styler.listTypes.contains($0.type) && !Styler.itemTypes.contains($0.type) }, type: "codeBlock", attrs: ["language": .null])94                let copy = NSMutableAttributedString(attributedString: storage.attributedSubstring(from: range))95                let all = NSRange(location: 0, length: copy.length)96                copy.addAttributes([.spPara: code, .spMarks: MarkSet.none], range: all)97                copy.mutableString.replaceOccurrences(of: "\u{2028}", with: " ", options: [], range: all)98                replace(range, with: copy, select: selectedRange(), actionName: "Bloc de code")99            }100        case .bullet: toggleList("bulletList", attrs: [:], toggle: toggle)101        case .ordered(let start): toggleList("orderedList", attrs: ["start": .int(Int64(start))], toggle: toggle)102        case .task: toggleList("taskList", attrs: [:], toggle: toggle)103        case .quote: toggleWrapper("blockquote", attrs: [:], toggle: toggle)104        case .callout: toggleWrapper("callout", attrs: ["kind": .string("note"), "icon": .string("💡")], toggle: toggle)105        }106    }107108    private func toggleList(_ type: String, attrs: [String: JSONValue], toggle: Bool) {109        let range = selectedParagraphs110        let allSame = everyParagraph(in: range) { $0.item?.list.type == type }111        var made: [String: Container] = [:]       // one new list per run of paragraphs with the same parent path112        var replaced: [Int: Container] = [:]      // a list of another type becomes one list of the new type113        // a list of the same type right above, at the same level, is continued instead of starting a second one114        var joinable: Container?115        if range.location > 0 { let prev = paraStyle(at: range.location - 1); if let it = prev.item, it.list.type == type, it.depth == 1 || true { joinable = it.list } }116        restyleParagraphs(in: range, actionName: "Liste") { s, _ in117            if s.isCode || s.type == "detailsSummary" { return s }118            var path = s.path119            if let it = s.item {120                if it.list.type == type { if toggle && allSame { path.removeLast(2) }; return s.with(path: path) }121                let list = replaced[it.list.key] ?? self.newContainer(type, attrs: attrs); replaced[it.list.key] = list122                path[path.count - 2] = list; path[path.count - 1] = self.newItem(for: list)123                return s.with(path: path)124            }125            let parentKey = path.map { String($0.key) }.joined(separator: "/")126            let list: Container127            if let l = made[parentKey] { list = l }128            else if let j = joinable, self.parentPath(of: j, at: range.location - 1).map(\.key) == path.map(\.key) { list = j }129            else { list = self.newContainer(type, attrs: attrs) }130            made[parentKey] = list131            path.append(list); path.append(self.newItem(for: list))132            let base = s.type == "heading" ? self.newParagraphStyle(path: path) : s.with(path: path)133            return base134        }135    }136    private func parentPath(of container: Container, at location: Int) -> [Container] {137        let p = paraStyle(at: location).path138        guard let i = p.firstIndex(where: { $0.key == container.key }) else { return [] }139        return Array(p[..<i])140    }141    private func everyParagraph(in range: NSRange, _ test: (ParaStyle) -> Bool) -> Bool {142        var loc = range.location; var ok = true143        while loc < NSMaxRange(range), loc < storage.length { if !test(paraStyle(at: loc)) { ok = false; break }; loc = NSMaxRange(paragraphRange(at: loc)) }144        return ok145    }146147    internal func toggleWrapper(_ type: String, attrs: [String: JSONValue], toggle: Bool) {148        let range = selectedParagraphs149        let all = everyParagraph(in: range) { $0.path.contains { $0.type == type } }150        var wrapper: Container?151        if !all, range.location > 0, let first = paraStyle(at: range.location - 1).path.first, first.type == type { wrapper = first }152        restyleParagraphs(in: range, actionName: type == "blockquote" ? "Citation" : "Encadré") { s, _ in153            var path = s.path154            if let i = path.lastIndex(where: { $0.type == type }) { if toggle && all { path.remove(at: i) }; return s.with(path: path) }155            let w = wrapper ?? self.newContainer(type, attrs: attrs); wrapper = w156            path.insert(w, at: 0)157            return s.with(path: path)158        }159    }160161    /// Tab in a list: the item becomes a child of the item above.162    func indent() {163        let range = selectedParagraphs164        guard range.location > 0 else { return }165        var nested: [Int: Container] = [:]   // parent item key → nested list166        var prevStyle = paraStyle(at: range.location - 1)167        restyleParagraphs(in: range, actionName: "Augmenter le retrait") { s, _ in168            defer { prevStyle = s }169            guard let it = s.item else { return s }170            let depth = s.path.count - 2171            // the paragraph above must be an earlier item of the same list (possibly deeper)172            guard prevStyle.path.count >= depth + 2, prevStyle.path[depth].key == it.list.key, prevStyle.path[depth + 1].key != it.item.key else { return s }173            let parentItem = prevStyle.path[depth + 1]174            var list: Container175            if let n = nested[parentItem.key] { list = n }176            else if prevStyle.path.count > depth + 2, Styler.listTypes.contains(prevStyle.path[depth + 2].type) { list = prevStyle.path[depth + 2] }177            else { list = self.newContainer(it.list.type, attrs: it.list.type == "orderedList" ? ["start": .int(1)] : [:]) }178            nested[parentItem.key] = list179            let item = list.type == "taskList" && it.item.type != "taskItem" ? self.newItem(for: list) : list.type != "taskList" && it.item.type == "taskItem" ? self.newItem(for: list) : it.item180            let result = s.with(path: Array(s.path[..<depth]) + [it.list, parentItem, list, item])181            return result182        }183    }184185    /// ⇧Tab: one level out.186    func outdent() {187        restyleParagraphs(in: selectedParagraphs, actionName: "Diminuer le retrait") { s, _ in s.path.isEmpty ? s : self.lifted(s) }188    }189190    /// Moves the selected blocks above the previous block or below the next one.191    func moveBlock(up: Bool) {192        var range = selectedParagraphs193        if paraStyle(at: range.location).isCode { range = NSUnionRange(range, codeBlockRange(at: range.location)) }194        let sel = selectedRange()195        if up {196            guard range.location > 0 else { return }197            var prev = paragraphRange(at: range.location - 1); if paraStyle(at: prev.location).isCode { prev = codeBlockRange(at: prev.location) }198            let moved = NSMutableAttributedString(attributedString: storage.attributedSubstring(from: range)); moved.append(storage.attributedSubstring(from: prev))199            replace(NSUnionRange(prev, range), with: moved, select: NSRange(location: sel.location - prev.length, length: sel.length), actionName: "Déplacer le bloc")200        } else {201            guard NSMaxRange(range) < storage.length else { return }202            var next = paragraphRange(at: NSMaxRange(range)); if paraStyle(at: next.location).isCode { next = codeBlockRange(at: next.location) }203            let moved = NSMutableAttributedString(attributedString: storage.attributedSubstring(from: next)); moved.append(storage.attributedSubstring(from: range))204            replace(NSUnionRange(range, next), with: moved, select: NSRange(location: sel.location + next.length, length: sel.length), actionName: "Déplacer le bloc")205        }206    }207208    // MARK: Marks209210    func toggleMark(_ type: String) {211        let sel = selectedRange()212        if paraStyle(at: sel.location).isCode && sel.length == 0 { return }213        let active = activeMarks()214        if sel.length == 0 {215            let next = active.has(type) ? active.removing(type) : active.adding(PMMark(type: type))216            pendingMarks = (sel.location, next)217            refreshTypingAttributes(); noteDelegate?.noteTextViewSelectionDidChange(self)218            return219        }220        let on = !active.has(type)221        mapMarks(in: sel, actionName: Self.markName(type)) { m in on ? m.adding(PMMark(type: type)) : m.removing(type) }222    }223    private static func markName(_ t: String) -> String { ["bold": "Gras", "italic": "Italique", "underline": "Souligné", "strike": "Barré", "code": "Code", "highlight": "Surlignage", "subscript": "Indice", "superscript": "Exposant", "link": "Lien"][t] ?? "Format" }224225    private func mapMarks(in range: NSRange, actionName: String, _ f: (MarkSet) -> MarkSet) {226        let copy = NSMutableAttributedString(attributedString: storage.attributedSubstring(from: range))227        let ns = copy.string as NSString228        copy.enumerateAttributes(in: NSRange(location: 0, length: copy.length)) { attrs, r, _ in229            if (attrs[.spPara] as? ParaStyle)?.isCode == true || attrs[.attachment] != nil { return }230            if ns.substring(with: r) == "\n" { return }231            copy.addAttribute(.spMarks, value: f((attrs[.spMarks] as? MarkSet) ?? .none), range: r)232        }233        replace(range, with: copy, select: range, actionName: actionName)234    }235236    /// Removes every mark from the selection.237    func clearFormatting() { let sel = selectedRange(); guard sel.length > 0 else { return }; mapMarks(in: sel, actionName: "Effacer le format") { _ in .none } }238239    /// Sets (or removes, with nil) the link of the selection; with no selection, of the link under the caret, or inserts240    /// `text` as a new link.241    func setLink(_ href: String?, text: String? = nil) {242        var sel = selectedRange()243        if sel.length == 0, let l = link(at: sel.location) ?? (sel.location > 0 ? link(at: sel.location - 1) : nil) { sel = l.range }244        if sel.length == 0 {245            guard let href, !href.isEmpty else { return }246            let label = (text?.isEmpty == false ? text! : href)247            let style = paraStyle(at: sel.location); guard !style.isAtom, !style.isCode else { return }248            let marks = activeMarks().adding(PMMark(type: "link", attrs: ["href": .string(href)]))249            replace(sel, with: NSAttributedString(string: label, attributes: [.spPara: style, .spMarks: marks]), select: NSRange(location: sel.location + (label as NSString).length, length: 0), actionName: "Lien")250            return251        }252        mapMarks(in: sel, actionName: "Lien") { m in253            guard let href, !href.isEmpty else { return m.removing("link") }254            var attrs = m.mark("link")?.attrs ?? [:]; attrs["href"] = .string(href)255            return m.adding(PMMark(type: "link", attrs: attrs))256        }257    }258259    // MARK: Atoms260261    /// Inserts a block node (table, image, rule, equation, file) as its own paragraph after the caret's block.262    func insertBlockAtom(_ node: PMNode, actionName: String = "Insérer") {263        let sel = selectedRange(); let style = paraStyle(at: sel.location); let pr = paragraphRange(at: sel.location)264        var n = node265        if Self.idTypes.contains(n.type), n.attrs?["id"] == nil { var a = n.attrs ?? [:]; a["id"] = .string(Self.newBlockID()); n.attrs = a }266        let path = style.isCode ? style.path : style.path267        let atom = codec.attributed(Line(blockAtom: n, path: path))268        let emptyParagraph = !style.isAtom && !style.isCode && contentRange(at: sel.location).length == 0269        if emptyParagraph {270            // the empty paragraph gives its place to the block; a fresh paragraph follows when the block ends the note271            let needsTail = NSMaxRange(pr) >= storage.length272            if needsTail { atom.append(paragraph(style: newParagraphStyle(path: path))) }273            replace(pr, with: atom, select: NSRange(location: pr.location + 2, length: 0), actionName: actionName)274        } else {275            let at = style.isCode ? NSMaxRange(codeBlockRange(at: sel.location)) : NSMaxRange(pr)276            if at >= storage.length { atom.append(paragraph(style: newParagraphStyle(path: path))) }277            replace(NSRange(location: at, length: 0), with: atom, select: NSRange(location: min(at + 2, at + atom.length - 1), length: 0), actionName: actionName)278        }279    }280281    func insertInlineAtom(_ node: PMNode, actionName: String = "Insérer") {282        let sel = selectedRange(); let style = paraStyle(at: sel.location)283        guard !style.isAtom, !style.isCode else { return }284        let a = NSMutableAttributedString(attributedString: codec.attributed(.atom(node)))285        a.addAttribute(.spPara, value: style, range: NSRange(location: 0, length: a.length))286        replace(sel, with: a, select: NSRange(location: sel.location + a.length, length: 0), actionName: actionName)287    }288289    /// Replaces the node of an existing atom (edited table, equation, renamed image…).290    func replaceAtom(at range: NSRange, with node: PMNode, actionName: String = "Modifier") {291        guard range.location < storage.length, let old = storage.attribute(.attachment, at: range.location, effectiveRange: nil) as? AtomAttachment else { return }292        let attrs = storage.attributes(at: range.location, effectiveRange: nil)293        let a = NSMutableAttributedString(attachment: AtomAttachment(node: node, isBlock: old.isBlock, theme: theme, resources: resources))294        var keep: [NSAttributedString.Key: Any] = [.spMarks: attrs[.spMarks] ?? MarkSet.none]295        if let p = attrs[.spPara] as? ParaStyle { keep[.spPara] = old.isBlock ? ParaStyle(line: p.line(.blockAtom(node)), isAtom: true) : p }296        a.addAttributes(keep, range: NSRange(location: 0, length: a.length))297        if old.isBlock {298            // the paragraph terminator shares the block's style299            let pr = paragraphRange(at: range.location)300            a.append(NSAttributedString(string: "\n", attributes: keep))301            replace(pr, with: a, select: NSRange(location: pr.location, length: 1), actionName: actionName)302        } else { replace(NSRange(location: range.location, length: 1), with: a, select: NSRange(location: range.location + 1, length: 0), actionName: actionName) }303    }304305    func insertRule() { insertBlockAtom(.horizontalRule(), actionName: "Séparateur") }306    func insertTable(rows: Int = 3, columns: Int = 3) { insertBlockAtom(.table(rows: rows, cols: columns, withHeaderRow: true), actionName: "Tableau") }307    func insertBlockMath(_ latex: String) { insertBlockAtom(.blockMath(latex: latex), actionName: "Équation") }308    func insertInlineMath(_ latex: String) { insertInlineAtom(.inlineMath(latex: latex), actionName: "Équation") }309    func insertMention(id: String, label: String) { insertInlineAtom(.mention(id: id, label: label), actionName: "Lien vers une note") }310    func insertImage(src: String, alt: String?) { insertBlockAtom(.image(src: src, alt: alt), actionName: "Image") }311    func insertFile(src: String, name: String, size: Int, mime: String, attachmentId: String) {312        insertBlockAtom(.fileBlock(src: src, name: name, size: size, mime: mime, attachmentId: attachmentId), actionName: "Pièce jointe")313    }314315    // MARK: Documents and Markdown316317    /// Inserts the lines of a document at the caret (AI result, Markdown paste, import into a note). Keys are renumbered.318    func insert(_ doc: NoteDocument, replacing range: NSRange? = nil, actionName: String = "Insérer") {319        let sel = range ?? selectedRange(); let style = paraStyle(at: sel.location)320        var remap: [Int: Container] = [:]321        var lines = doc.lines322        guard !lines.isEmpty else { return }323        for i in lines.indices {324            lines[i].path = style.path.filter { _ in !style.isCode } + lines[i].path.map { c in if let k = remap[c.key] { return k }; var n = c; n.key = keys.make(); if n.attrs["id"] != nil { n.attrs["id"] = .string(Self.newBlockID()) }; remap[c.key] = n; return n }325            if lines[i].attrs["id"] != nil || Self.idTypes.contains(lines[i].type) { lines[i].attrs["id"] = .string(Self.newBlockID()) }326        }327        // one plain line of inline content: insert it in place, inside the current paragraph328        if lines.count == 1, case .inline(let runs) = lines[0].content, lines[0].type == "paragraph", doc.lines[0].path.isEmpty, !style.isAtom {329            let a = NSMutableAttributedString(); for r in runs { a.append(codec.attributed(r, code: style.isCode)) }330            a.addAttribute(.spPara, value: style, range: NSRange(location: 0, length: a.length))331            replace(sel, with: a, select: NSRange(location: sel.location + a.length, length: 0), actionName: actionName)332            return333        }334        let block = NSMutableAttributedString(); for l in lines { block.append(codec.attributed(l)) }335        undoManager?.beginUndoGrouping(); defer { undoManager?.endUndoGrouping() }336        if sel.length > 0 { replace(sel, with: NSAttributedString(), select: NSRange(location: sel.location, length: 0), actionName: actionName) }337        let caret = selectedRange().location; let pr = paragraphRange(at: caret); let here = paraStyle(at: caret)338        if !here.isAtom, !here.isCode, contentRange(at: caret).length == 0 {339            replace(pr, with: block, select: NSRange(location: pr.location + block.length - 1, length: 0), actionName: actionName)340        } else {341            let at = here.isCode ? NSMaxRange(codeBlockRange(at: caret)) : NSMaxRange(pr)342            replace(NSRange(location: at, length: 0), with: block, select: NSRange(location: at + block.length - 1, length: 0), actionName: actionName)343        }344    }345    func insertMarkdown(_ markdown: String, replacing range: NSRange? = nil, actionName: String = "Insérer") { insert(NoteDocument(markdown: markdown), replacing: range, actionName: actionName) }346347    /// Plain text of the selection (or of the whole note when nothing is selected) — what AI actions receive.348    func selectedMarkdown() -> String {349        let sel = selectedRange()350        if sel.length == 0 { return document().markdown() }351        return NoteFragment(text: storage, range: sel).document.markdown()352    }353354    // MARK: Menu actions (responder chain)355356    @objc func spToggleBold(_ sender: Any?) { toggleMark("bold") }357    @objc func spToggleItalic(_ sender: Any?) { toggleMark("italic") }358    @objc func spToggleUnderline(_ sender: Any?) { toggleMark("underline") }359    @objc func spToggleStrike(_ sender: Any?) { toggleMark("strike") }360    @objc func spToggleCode(_ sender: Any?) { toggleMark("code") }361    @objc func spToggleHighlight(_ sender: Any?) { toggleMark("highlight") }362    @objc func spMoveBlockUp(_ sender: Any?) { moveBlock(up: true) }363    @objc func spMoveBlockDown(_ sender: Any?) { moveBlock(up: false) }364}365
Files main
Menu

Theme