SPB Git

Repository Public

EditorController.swift 51.3 KB 888 lines swift

1// SP Notes iOS2// File: Editor/EditorController.swift3// Description: The native editing engine around one UITextView (TextKit 2): keeps the model attributes of the text storage consistent4//              after every edit (paragraph identity, block ids, list items), restyles only what changed, and implements Enter,5//              Backspace, marks, links, atoms and undo. The storage is the working document; `document()` reads it back.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import UIKit10import SPNotesCore1112@MainActor13protocol EditorControllerDelegate: AnyObject {14    /// The content changed because of the user (typing, command, undo). Not called when a document is loaded.15    func editorDidChange(_ controller: EditorController)16    func editorDidChangeSelection(_ controller: EditorController)17    func editor(_ controller: EditorController, didTapAtom node: PMNode, at range: NSRange)18    func editor(_ controller: EditorController, didTapLink href: String)19}2021@MainActor22final class EditorController: NSObject {23    let textView: NoteTextView24    let atoms: AtomRenderer25    let styler: EditorStyler26    weak var delegate: EditorControllerDelegate?2728    private var nextKey = 129    var isLoading = false30    /// The references cited by a document while it is being loaded (its atoms are drawn before it is in the storage).31    private var citedWhileLoading: [String]?32    /// Marks chosen from the toolbar with an empty selection; they apply to the next typed characters.33    private var pendingMarks: [PMMark]?34    var structureChanged = false35    private var lastLength = 03637    // 2.0 input ergonomics and block commands (Editor/EditorController+Input.swift, +Blocks.swift, SlashMenu.swift)38    /// Runs a command chosen in the slash menu (the owner dispatches it like a toolbar action).39    var onCommand: ((EditorAction) -> Void)?40    /// The due date / priority badge of the task item at this location was tapped.41    var onTapTaskBadge: ((Int) -> Void)?42    let slash = SlashMenuController()43    var markdownShortcutsEnabled = true44    var codeColourWork: DispatchWorkItem?4546    var storage: NSTextStorage { textView.textStorage }4748    override init() {49        atoms = AtomRenderer()50        styler = EditorStyler(atoms: atoms)51        textView = NoteTextView(frame: .zero, textContainer: nil)52        super.init()53        textView.controller = self54        textView.delegate = self55        textView.textStorage.delegate = self56        textView.textLayoutManager?.delegate = self57        // 2.0: the content of a closed toggle (`details` with open = false) is not laid out58        textView.textLayoutManager?.textContentManager?.delegate = self59        textView.configure()60        slash.editor = self61        styler.defersLargeCode = true62        atoms.cards.citedReferences = { [weak self] in self?.citedWhileLoading ?? self?.citedReferenceIds() ?? [] }63        load(NoteDocument(lines: []))64    }6566    // MARK: document in / out6768    /// Replaces the whole content (opening a note, applying a remote version). Clears the undo stack.69    func load(_ document: NoteDocument) {70        var document = document71        if document.lines.isEmpty { document.lines = [Line(path: [], type: "paragraph", attrs: LineStyle.paragraphAttrs, content: .inline([]))] }72        document.ensureBlockIds()73        slash.cancel()74        nextKey = (document.lines.flatMap { $0.path.map(\.key) }.max() ?? 0) + 175        let attributed = AttributedCodec.attributedString(from: document)76        styler.contentWidth = contentWidth77        atoms.traits = textView.traitCollection78        citedWhileLoading = document.citedReferences()79        styler.restyleAll(attributed)80        citedWhileLoading = nil81        isLoading = true82        let selection = textView.selectedRange83        storage.setAttributedString(attributed)84        isLoading = false85        lastLength = storage.length86        textView.undoManager?.removeAllActions()87        textView.selectedRange = NSRange(location: min(selection.location, max(0, storage.length - 1)), length: 0)88        refreshTypingAttributes()89    }9091    /// The current content as a document (block ids already present: they are assigned when paragraphs are created).92    func document() -> NoteDocument {93        var document = AttributedCodec.document(from: storage)94        document.ensureBlockIds()95        return document96    }9798    var contentWidth: CGFloat {99        let inset = textView.textContainerInset100        return max(200, textView.bounds.width - inset.left - inset.right - 2 * textView.textContainer.lineFragmentPadding)101    }102103    /// Called by the text view when its width or its appearance changed: block atoms are drawn for a given width and colour scheme.104    func relayout(force: Bool = false) {105        let width = contentWidth106        guard force || abs(width - styler.contentWidth) > 0.5 else { return }107        styler.contentWidth = width108        atoms.traits = textView.traitCollection109        guard storage.length > 0 else { return }110        isLoading = true111        storage.beginEditing()112        if force { storage.enumerateAttribute(.attachment, in: NSRange(location: 0, length: storage.length)) { value, _, _ in (value as? AtomAttachment)?.image = nil } }113        styler.restyle(storage, range: NSRange(location: 0, length: storage.length))114        storage.endEditing()115        isLoading = false116    }117118    /// A picture finished downloading: redraw the atoms that show it.119    func invalidateImages(src: String) {120        var ranges: [NSRange] = []121        storage.enumerateAttribute(.attachment, in: NSRange(location: 0, length: storage.length)) { value, range, _ in122            if let atom = value as? AtomAttachment, atom.node.type == "image", atom.node.stringAttr("src") == src { atom.image = nil; ranges.append(range) }123        }124        guard !ranges.isEmpty else { return }125        isLoading = true126        storage.beginEditing()127        for range in ranges { styler.restyle(storage, range: range); storage.edited(.editedAttributes, range: range, changeInLength: 0) }128        storage.endEditing()129        isLoading = false130    }131132    // MARK: ids and keys133134    func newKey() -> Int { defer { nextKey += 1 }; return nextKey }135136    static func newBlockID() -> String {137        let alphabet = Array("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-")138        var generator = SystemRandomNumberGenerator()139        return String((0..<10).map { _ in alphabet[Int(generator.next() & 63)] })140    }141142    func freshParagraph(at style: LineStyle) -> LineStyle {143        var s = style.paragraphHere()144        s.attrs["id"] = .string(Self.newBlockID())145        return s146    }147148    /// The style of the paragraph created by a line break inside a paragraph of style `style`.149    private func continuation(of style: LineStyle) -> LineStyle {150        var s = freshParagraph(at: style)151        if let index = style.innermostItemIndex {152            // a new sibling item, which starts with a plain paragraph153            let item = style.path[index]154            s.path = Array(style.path[...index])155            // a new item never shares the id of the one it was split from; a new task is unchecked, without due date, priority or156            // linked task (same rule as the Core's `splitLine`)157            var attrs = item.attrs158            attrs["id"] = .string(Self.newBlockID())159            if item.type == "taskItem" {160                attrs["checked"] = .bool(false)161                for key in ["due", "priority", "taskId"] where attrs[key] != nil { attrs[key] = .null }162            }163            s.path[index] = Container(key: newKey(), type: item.type, attrs: attrs)164        }165        return s166    }167168    // MARK: paragraph helpers169170    func paragraphRange(at location: Int) -> NSRange {171        let string = storage.string as NSString172        guard string.length > 0 else { return NSRange(location: 0, length: 0) }173        return string.paragraphRange(for: NSRange(location: min(max(0, location), string.length - 1), length: 0))174    }175176    func lineBox(at location: Int) -> LineBox? {177        guard storage.length > 0 else { return nil }178        return storage.attribute(.spnLine, at: min(max(0, location), storage.length - 1), effectiveRange: nil) as? LineBox179    }180181    func style(at location: Int) -> LineStyle { lineBox(at: location)?.style ?? LineStyle(attrs: LineStyle.paragraphAttrs) }182183    /// Index of the model line (paragraph) that contains `location`.184    func lineIndex(at location: Int) -> Int {185        let string = storage.string as NSString186        var count = 0187        var searchRange = NSRange(location: 0, length: min(max(0, location), string.length))188        while searchRange.length > 0 {189            let found = string.range(of: "\n", options: [], range: searchRange)190            if found.location == NSNotFound { break }191            count += 1192            searchRange = NSRange(location: NSMaxRange(found), length: NSMaxRange(searchRange) - NSMaxRange(found))193        }194        return count195    }196197    /// Paragraph ranges of the model lines `lines`.198    func paragraphRanges() -> [NSRange] {199        let string = storage.string as NSString200        var out: [NSRange] = []201        var location = 0202        while location < string.length {203            let range = string.paragraphRange(for: NSRange(location: location, length: 0))204            out.append(range)205            location = NSMaxRange(range)206        }207        return out208    }209210    func blockAtom(in paragraph: NSRange) -> AtomAttachment? {211        var found: AtomAttachment?212        storage.enumerateAttribute(.attachment, in: paragraph, options: []) { value, _, stop in213            if let atom = value as? AtomAttachment, atom.isBlock { found = atom; stop.pointee = true }214        }215        return found216    }217218    // MARK: typing attributes219220    func marksBeforeCaret() -> [PMMark] {221        let selection = textView.selectedRange222        let paragraph = paragraphRange(at: selection.location)223        let index = selection.length > 0 ? selection.location : selection.location - 1224        guard index >= paragraph.location, index < storage.length else { return [] }225        if storage.attribute(.attachment, at: index, effectiveRange: nil) != nil { return [] }226        return (storage.attribute(.spnMarks, at: index, effectiveRange: nil) as? MarksBox)?.marks ?? []227    }228229    /// Marks that apply at the caret (or over the whole selection), for the toolbar state.230    func activeMarks() -> [PMMark] {231        if textView.selectedRange.length == 0 { return pendingMarks ?? marksBeforeCaret() }232        var common: [PMMark]?233        storage.enumerateAttributes(in: textView.selectedRange, options: []) { attributes, range, _ in234            if attributes[.attachment] != nil { return }235            if (storage.string as NSString).substring(with: range).trimmingCharacters(in: .newlines).isEmpty { return }236            let marks = (attributes[.spnMarks] as? MarksBox)?.marks ?? []237            common = common.map { existing in existing.filter { m in marks.contains { $0.type == m.type } } } ?? marks238        }239        return common ?? []240    }241242    func refreshTypingAttributes() {243        guard storage.length > 0 else { return }244        let location = min(textView.selectedRange.location, storage.length - 1)245        let box = lineBox(at: paragraphRange(at: location).location) ?? LineBox(LineStyle(attrs: LineStyle.paragraphAttrs))246        var marks = pendingMarks ?? marksBeforeCaret()247        // A link does not extend to what is typed after it.248        if pendingMarks == nil { marks.removeAll { $0.type == "link" } }249        var attributes = styler.typingAttributes(style: box.style, marks: marks)250        attributes[.spnLine] = box // the paragraph's own box instance: lets the engine recognise a split paragraph251        textView.typingAttributes = attributes252    }253254    // MARK: programmatic edits (with undo)255256    /// Replaces `range` by `replacement` as one undoable step. All commands that change characters go through here.257    func replace(_ range: NSRange, with replacement: NSAttributedString, selectAfter: NSRange? = nil, actionName: String? = nil) {258        let old = storage.attributedSubstring(from: range)259        let oldSelection = textView.selectedRange260        storage.beginEditing()261        storage.replaceCharacters(in: range, with: replacement)262        storage.endEditing()263        let newRange = NSRange(location: range.location, length: replacement.length)264        if let selectAfter { textView.selectedRange = clampSelection(selectAfter) }265        textView.undoManager?.registerUndo(withTarget: self) { target in266            MainActor.assumeIsolated { target.replace(newRange, with: old, selectAfter: oldSelection, actionName: actionName) }267        }268        if let actionName { textView.undoManager?.setActionName(actionName) }269        didEdit()270    }271272    /// Changes attributes over `range` (marks, paragraph identity) as one undoable step; `body` must not change characters.273    func mutateAttributes(in range: NSRange, actionName: String? = nil, structural: Bool = false, _ body: (NSTextStorage) -> Void) {274        guard range.length > 0 else { return }275        let old = storage.attributedSubstring(from: range)276        let selection = textView.selectedRange277        if structural { structureChanged = true }278        storage.beginEditing()279        body(storage)280        storage.edited(.editedAttributes, range: range, changeInLength: 0)281        styler.restyle(storage, range: range)282        if structural { styler.renumber(storage) }283        storage.endEditing()284        textView.undoManager?.registerUndo(withTarget: self) { target in285            MainActor.assumeIsolated {286                target.mutateAttributes(in: range, actionName: actionName, structural: structural) { storage in287                    // restore the model attributes exactly; presentation is recomputed288                    old.enumerateAttributes(in: NSRange(location: 0, length: old.length), options: []) { attributes, sub, _ in289                        let target = NSRange(location: range.location + sub.location, length: sub.length)290                        for key in [NSAttributedString.Key.spnLine, .spnMarks] {291                            if let value = attributes[key] { storage.addAttribute(key, value: value, range: target) } else { storage.removeAttribute(key, range: target) }292                        }293                    }294                }295                target.textView.selectedRange = target.clampSelection(selection)296            }297        }298        if let actionName { textView.undoManager?.setActionName(actionName) }299        didEdit()300    }301302    func didEdit() {303        refreshTypingAttributes()304        delegate?.editorDidChange(self)305        delegate?.editorDidChangeSelection(self)306    }307308    /// The caret never goes past the final paragraph terminator (every paragraph, the last one included, ends with a newline that309    /// carries its attributes).310    func clampSelection(_ range: NSRange) -> NSRange {311        let limit = max(0, storage.length - 1)312        let location = min(max(0, range.location), limit)313        let end = min(max(location, NSMaxRange(range)), limit)314        return NSRange(location: location, length: end - location)315    }316317    // MARK: marks and links318319    func toggleMark(_ type: String) {320        let selection = textView.selectedRange321        let current = activeMarks()322        let isOn = current.contains { $0.type == type }323        if selection.length == 0 {324            guard !style(at: selection.location).isCode else { return }325            pendingMarks = Self.toggled(current, type: type, on: !isOn)326            refreshTypingAttributes()327            delegate?.editorDidChangeSelection(self)328            return329        }330        mutateAttributes(in: selection, actionName: String(localized: "Mise en forme")) { storage in331            storage.enumerateAttributes(in: selection, options: []) { attributes, range, _ in332                if attributes[.attachment] != nil { return }333                if (attributes[.spnLine] as? LineBox)?.style.isCode == true { return }334                let marks = Self.toggled((attributes[.spnMarks] as? MarksBox)?.marks ?? [], type: type, on: !isOn)335                if marks.isEmpty { storage.removeAttribute(.spnMarks, range: range) } else { storage.addAttribute(.spnMarks, value: MarksBox(marks), range: range) }336            }337        }338    }339340    /// Mark order follows the web schema; `code` excludes every other mark.341    static let markOrder = ["link", "bold", "code", "italic", "strike", "underline", "highlight", "subscript", "superscript"]342    static func toggled(_ marks: [PMMark], type: String, on: Bool, attrs: [String: JSONValue]? = nil) -> [PMMark] {343        var out = marks.filter { $0.type != type }344        if on {345            if type == "code" { out = [] } else { out.removeAll { $0.type == "code" } }346            if type == "subscript" { out.removeAll { $0.type == "superscript" } }347            if type == "superscript" { out.removeAll { $0.type == "subscript" } }348            out.append(PMMark(type: type, attrs: attrs))349        }350        return out.sorted { (markOrder.firstIndex(of: $0.type) ?? 99) < (markOrder.firstIndex(of: $1.type) ?? 99) }351    }352353    /// The range of the link around the caret / selection, with its address.354    func linkAtSelection() -> (range: NSRange, href: String)? {355        let selection = textView.selectedRange356        let index = selection.length > 0 ? selection.location : max(0, selection.location - (selection.location > 0 && linkHref(at: selection.location) == nil ? 1 : 0))357        guard let href = linkHref(at: index) else { return nil }358        var start = index, end = index + 1359        while start > 0, linkHref(at: start - 1) == href { start -= 1 }360        while end < storage.length, linkHref(at: end) == href { end += 1 }361        return (NSRange(location: start, length: end - start), href)362    }363364    private func linkHref(at index: Int) -> String? {365        guard index >= 0, index < storage.length else { return nil }366        return (storage.attribute(.spnMarks, at: index, effectiveRange: nil) as? MarksBox)?.link367    }368369    static func linkAttrs(_ href: String) -> [String: JSONValue] {370        ["href": .string(href), "target": .string("_blank"), "rel": .string("noopener noreferrer nofollow"), "class": .null, "title": .null]371    }372373    /// Normalises what the user typed into a safe address (https by default; script and data URLs refused, like the server does).374    static func normalizedLink(_ raw: String) -> String? {375        var href = raw.trimmingCharacters(in: .whitespacesAndNewlines)376        guard !href.isEmpty else { return nil }377        if href.range(of: "^[a-zA-Z][a-zA-Z0-9+.-]*:", options: .regularExpression) == nil, !href.hasPrefix("/") { href = "https://" + href }378        if href.range(of: "^\\s*(javascript|vbscript|data):", options: [.regularExpression, .caseInsensitive]) != nil { return nil }379        return href380    }381382    /// Sets (or removes, with nil) the link on the selection or on the link around the caret; with an empty selection outside a link,383    /// inserts the address itself as linked text.384    func setLink(_ href: String?) {385        let selection = textView.selectedRange386        if let existing = linkAtSelection(), selection.length == 0 || NSIntersectionRange(existing.range, selection).length > 0 {387            let range = selection.length > 0 ? NSUnionRange(existing.range, selection) : existing.range388            applyLink(href, to: range)389        } else if selection.length > 0 {390            applyLink(href, to: selection)391        } else if let href {392            var attributes = styler.typingAttributes(style: style(at: selection.location), marks: Self.toggled(marksBeforeCaret().filter { $0.type != "link" }, type: "link", on: true, attrs: Self.linkAttrs(href)))393            attributes[.spnLine] = lineBox(at: selection.location)394            replace(selection, with: NSAttributedString(string: href, attributes: attributes), selectAfter: NSRange(location: selection.location + (href as NSString).length, length: 0), actionName: String(localized: "Lien"))395        }396    }397398    private func applyLink(_ href: String?, to range: NSRange) {399        mutateAttributes(in: range, actionName: String(localized: "Lien")) { storage in400            storage.enumerateAttributes(in: range, options: []) { attributes, sub, _ in401                if attributes[.attachment] != nil { return }402                if (attributes[.spnLine] as? LineBox)?.style.isCode == true { return }403                let marks = Self.toggled((attributes[.spnMarks] as? MarksBox)?.marks ?? [], type: "link", on: href != nil, attrs: href.map(Self.linkAttrs))404                if marks.isEmpty { storage.removeAttribute(.spnMarks, range: sub) } else { storage.addAttribute(.spnMarks, value: MarksBox(marks), range: sub) }405            }406        }407    }408409    // MARK: atoms410411    /// Inserts a block atom as its own paragraph after the paragraph of the caret (or in place of it when it is empty).412    @discardableResult413    func insertBlockAtom(_ node: PMNode) -> NSRange {414        let selection = textView.selectedRange415        let paragraph = paragraphRange(at: selection.location)416        let current = style(at: paragraph.location)417        // Atoms sit beside text blocks, not inside a heading or a code block: keep the container path only.418        let atomStyle = AttributedCodec.style(forBlockAtom: node, path: current.path)419        let atomParagraph = NSMutableAttributedString(attachment: AtomAttachment(node: node, isBlock: true))420        atomParagraph.append(NSAttributedString(string: "\n"))421        atomParagraph.addAttribute(.spnLine, value: LineBox(atomStyle), range: NSRange(location: 0, length: atomParagraph.length))422        let isEmptyParagraph = paragraph.length <= 1 && AttributedCodec.isTextual(current)423        if isEmptyParagraph {424            // keep an empty paragraph after the atom so typing can continue425            let after = NSAttributedString(string: "\n", attributes: [.spnLine: LineBox(freshParagraph(at: current))])426            atomParagraph.append(after)427            replace(paragraph, with: atomParagraph, selectAfter: NSRange(location: paragraph.location + 2, length: 0), actionName: String(localized: "Insertion"))428            return NSRange(location: paragraph.location, length: 1)429        } else {430            let insertion = NSRange(location: NSMaxRange(paragraph), length: 0)431            let isLast = NSMaxRange(paragraph) >= storage.length432            if isLast { atomParagraph.append(NSAttributedString(string: "\n", attributes: [.spnLine: LineBox(freshParagraph(at: current))])) }433            replace(insertion, with: atomParagraph, selectAfter: NSRange(location: insertion.location + 2, length: 0), actionName: String(localized: "Insertion"))434            return NSRange(location: insertion.location, length: 1)435        }436    }437438    func insertInlineAtom(_ node: PMNode) {439        let selection = textView.selectedRange440        guard !style(at: selection.location).isCode else { return }441        let attributed = NSMutableAttributedString(attachment: AtomAttachment(node: node, isBlock: false))442        if let box = lineBox(at: selection.location) { attributed.addAttribute(.spnLine, value: box, range: NSRange(location: 0, length: 1)) }443        replace(selection, with: attributed, selectAfter: NSRange(location: selection.location + 1, length: 0), actionName: String(localized: "Insertion"))444        if node.type == NodeType.citation { invalidateAtoms { $0.type == NodeType.bibliography } }445    }446447    /// Replaces the node of the atom at `range` (edited table, equation, drawing…).448    func updateAtom(at range: NSRange, node: PMNode) {449        guard range.length == 1, range.location < storage.length, let atom = storage.attribute(.attachment, at: range.location, effectiveRange: nil) as? AtomAttachment else { return }450        let replacement = NSMutableAttributedString(attachment: AtomAttachment(node: node, isBlock: atom.isBlock))451        let path = style(at: range.location).path452        let box = atom.isBlock ? LineBox(AttributedCodec.style(forBlockAtom: node, path: path)) : (lineBox(at: range.location) ?? LineBox(LineStyle()))453        replacement.addAttribute(.spnLine, value: box, range: NSRange(location: 0, length: 1))454        if atom.isBlock {455            // the paragraph terminator carries the same identity456            let paragraph = paragraphRange(at: range.location)457            let whole = NSMutableAttributedString(attributedString: replacement)458            whole.append(NSAttributedString(string: "\n", attributes: [.spnLine: box]))459            replace(paragraph, with: whole, selectAfter: textView.selectedRange, actionName: String(localized: "Modification"))460        } else {461            replace(range, with: replacement, selectAfter: textView.selectedRange, actionName: String(localized: "Modification"))462        }463        if node.type == NodeType.citation { invalidateAtoms { $0.type == NodeType.bibliography } }464    }465466    func deleteAtom(at range: NSRange) {467        guard range.location < storage.length, let atom = storage.attribute(.attachment, at: range.location, effectiveRange: nil) as? AtomAttachment else { return }468        if atom.isBlock {469            let paragraph = paragraphRange(at: range.location)470            if paragraph.location == 0 && NSMaxRange(paragraph) >= storage.length {471                // the only paragraph: leave an empty one472                replace(paragraph, with: NSAttributedString(string: "\n", attributes: [.spnLine: LineBox(freshParagraph(at: style(at: 0)))]), selectAfter: NSRange(location: 0, length: 0), actionName: String(localized: "Suppression"))473            } else {474                replace(paragraph, with: NSAttributedString(), selectAfter: NSRange(location: max(0, paragraph.location - 1), length: 0), actionName: String(localized: "Suppression"))475            }476        } else {477            replace(range, with: NSAttributedString(), selectAfter: NSRange(location: range.location, length: 0), actionName: String(localized: "Suppression"))478            if atom.node.type == NodeType.citation { invalidateAtoms { $0.type == NodeType.bibliography } }479        }480    }481482    /// Inserts plain text at the selection with the current typing attributes (AI results, dictation helpers, snippets).483    func insertText(_ text: String) {484        let selection = textView.selectedRange485        let isCode = style(at: selection.location).isCode486        let shown = isCode ? text.replacingOccurrences(of: "\n", with: EditorCharacter.softBreak) : text487        replace(selection, with: NSAttributedString(string: shown, attributes: textView.typingAttributes), selectAfter: NSRange(location: selection.location + (shown as NSString).length, length: 0), actionName: String(localized: "Insertion"))488    }489490    /// Inserts document lines (parsed Markdown, an AI result) after the paragraph of the caret, or in place of `range` when given491    /// whole paragraphs. The inserted lines join the container of the caret's paragraph when they are top-level.492    func insertLines(_ lines: [Line], replacing range: NSRange? = nil) {493        guard !lines.isEmpty else { return }494        var fragmentDocument = NoteDocument(lines: lines)495        fragmentDocument.ensureBlockIds()496        // container keys of the fragment must not collide with the document's497        var mapping: [Int: Int] = [:]498        let remapped = fragmentDocument.lines.map { line -> Line in499            var line = line500            line.path = line.path.map { c in Container(key: mapping[c.key] ?? { let k = newKey(); mapping[c.key] = k; return k }(), type: c.type, attrs: c.attrs) }501            return line502        }503        let attributed = AttributedCodec.attributedString(from: NoteDocument(lines: remapped))504        styler.restyle(attributed, range: NSRange(location: 0, length: attributed.length))505        let target: NSRange506        if let range {507            let start = paragraphRange(at: range.location).location508            let end = range.length == 0 ? NSMaxRange(paragraphRange(at: range.location)) : NSMaxRange(paragraphRange(at: max(range.location, NSMaxRange(range) - 1)))509            target = NSRange(location: start, length: end - start)510        } else {511            target = NSRange(location: NSMaxRange(paragraphRange(at: textView.selectedRange.location)), length: 0)512        }513        var insertion = attributed514        if NSMaxRange(target) >= storage.length && target.length == 0 {515            // inserting after the last paragraph: nothing more to do, every inserted line carries its terminator516            insertion = attributed517        }518        structureChanged = true519        replace(target, with: insertion, selectAfter: NSRange(location: target.location + max(0, insertion.length - 1), length: 0), actionName: String(localized: "Insertion"))520    }521522    // MARK: paragraph styles and structure523524    /// Rewrites the identity (LineStyle) of the paragraphs intersecting `range` with `transform`; one undoable step.525    func transformParagraphs(in range: NSRange, actionName: String, _ transform: (LineStyle, NSRange) -> LineStyle?) {526        let start = paragraphRange(at: range.location).location527        let end = NSMaxRange(paragraphRange(at: range.length == 0 ? range.location : NSMaxRange(range) - 1))528        let whole = NSRange(location: start, length: end - start)529        mutateAttributes(in: whole, actionName: actionName, structural: true) { storage in530            let string = storage.string as NSString531            var location = whole.location532            while location < NSMaxRange(whole) {533                let paragraph = string.paragraphRange(for: NSRange(location: location, length: 0))534                let current = (storage.attribute(.spnLine, at: paragraph.location, effectiveRange: nil) as? LineBox)?.style ?? LineStyle()535                if let next = transform(current, paragraph), next != current {536                    storage.addAttribute(.spnLine, value: LineBox(next), range: paragraph)537                    if next.isCode { storage.removeAttribute(.spnMarks, range: paragraph) }538                }539                location = NSMaxRange(paragraph)540            }541        }542    }543544    /// Replaces the identity of every paragraph by `styles` (same count as the paragraphs); used by the structural commands computed545    /// on the document model (lists, indentation, quotes, callouts).546    func applyStyles(_ styles: [LineStyle], actionName: String) {547        let ranges = paragraphRanges()548        guard styles.count == ranges.count, !ranges.isEmpty else { return }549        var firstChanged: Int?, lastChanged: Int?550        for (index, range) in ranges.enumerated() where style(at: range.location) != styles[index] {551            if firstChanged == nil { firstChanged = index }552            lastChanged = index553        }554        guard let first = firstChanged, let last = lastChanged else { return }555        let whole = NSRange(location: ranges[first].location, length: NSMaxRange(ranges[last]) - ranges[first].location)556        nextKey = max(nextKey, (styles.flatMap { $0.path.map(\.key) }.max() ?? 0) + 1)557        mutateAttributes(in: whole, actionName: actionName, structural: true) { storage in558            for index in first...last {559                storage.addAttribute(.spnLine, value: LineBox(styles[index]), range: ranges[index])560                if styles[index].isCode { storage.removeAttribute(.spnMarks, range: ranges[index]) }561            }562        }563    }564565    func setBlockType(_ type: String, level: Int? = nil) {566        transformParagraphs(in: textView.selectedRange, actionName: String(localized: "Style de paragraphe")) { style, paragraph in567            guard AttributedCodec.isTextual(style), style.type == "paragraph" || style.type == "heading" || style.type == "codeBlock" else { return nil }568            var next = style569            let id = style.attrs["id"] ?? .string(Self.newBlockID())570            switch type {571            case "heading":572                let target = level ?? 2573                if style.headingLevel == target { next.type = "paragraph"; next.attrs = ["textAlign": style.attrs["textAlign"] ?? .null, "id": id] }574                else { next.type = "heading"; next.attrs = ["textAlign": style.attrs["textAlign"] ?? .null, "level": .int(Int64(target)), "id": id] }575            case "codeBlock":576                if style.isCode { next.type = "paragraph"; next.attrs = ["textAlign": .null, "id": id] }577                else { next.type = "codeBlock"; next.attrs = ["language": .string("plaintext"), "id": id] }578            default:579                next.type = "paragraph"; next.attrs = ["textAlign": style.attrs["textAlign"] ?? .null, "id": id]580            }581            return next582        }583    }584585    /// Toggles the checkbox of the task item that contains `location`.586    func toggleTask(at location: Int) {587        guard let item = style(at: location).innermostItem, item.type == "taskItem" else { return }588        let checked = !(style(at: location).isTaskChecked)589        // every paragraph of the item (and of nested content) carries the item frame590        let ranges = paragraphRanges().filter { range in style(at: range.location).path.contains { $0.key == item.key } }591        guard let first = ranges.first, let last = ranges.last else { return }592        let whole = NSRange(location: first.location, length: NSMaxRange(last) - first.location)593        mutateAttributes(in: whole, actionName: String(localized: "Case à cocher")) { storage in594            for range in ranges {595                var s = self.style(at: range.location)596                // only `checked` changes: the id, the due date, the priority and the linked task of the item are kept597                s.path = s.path.map { frame in598                    guard frame.key == item.key else { return frame }599                    var attrs = frame.attrs600                    attrs["checked"] = .bool(checked)601                    return Container(key: frame.key, type: frame.type, attrs: attrs)602                }603                storage.addAttribute(.spnLine, value: LineBox(s), range: range)604            }605        }606        UIImpactFeedbackGenerator(style: .light).impactOccurred()607    }608609    /// One step out of the innermost container (list item, quote, callout) for the paragraph at `location`. Returns false when the610    /// paragraph is at the top level. Used by Enter on an empty item and Backspace at the start of a paragraph.611    @discardableResult612    func lift(at location: Int) -> Bool {613        let paragraph = paragraphRange(at: location)614        let current = style(at: paragraph.location)615        guard !current.path.isEmpty else { return false }616        if let lifted = StructureCommands.lift(lineAt: lineIndex(at: paragraph.location), in: self) {617            applyStyles(lifted, actionName: String(localized: "Retrait"))618            return true619        }620        return false621    }622623    // MARK: keyboard events routed by the text view624625    /// Returns true when the event was handled (the default insertion must not happen).626    func handleReturn() -> Bool {627        let selection = textView.selectedRange628        let paragraph = paragraphRange(at: selection.location)629        let current = style(at: paragraph.location)630        if current.isCode {631            // Enter on an empty last line of a code block leaves the block; otherwise it is a line break inside the block.632            let content = NSRange(location: paragraph.location, length: max(0, paragraph.length - 1))633            let text = (storage.string as NSString).substring(with: content)634            if selection.length == 0, selection.location == NSMaxRange(content), text.hasSuffix(EditorCharacter.softBreak) {635                let after = NSMutableAttributedString(string: "\n", attributes: [.spnLine: lineBox(at: paragraph.location) ?? LineBox(current)])636                after.append(NSAttributedString(string: "\n", attributes: [.spnLine: LineBox(freshParagraph(at: current))]))637                replace(NSRange(location: selection.location - 1, length: 2), with: after, selectAfter: NSRange(location: selection.location, length: 0), actionName: String(localized: "Saisie"))638                structureChanged = true639                return true640            }641            replace(selection, with: NSAttributedString(string: EditorCharacter.softBreak, attributes: textView.typingAttributes), selectAfter: NSRange(location: selection.location + 1, length: 0), actionName: String(localized: "Saisie"))642            return true643        }644        if current.type == "detailsSummary" {645            // a summary is one line: Return goes to the content of the toggle (opening it when it is closed)646            if current.details?.attrs["open"]?.boolValue != true { toggleDetails(at: paragraph.location) }647            let next = NSMaxRange(paragraphRange(at: selection.location))648            if next < storage.length, style(at: next).details?.key == current.details?.key { textView.selectedRange = clampSelection(NSRange(location: max(next, NSMaxRange(paragraphRange(at: next)) - 1), length: 0)) }649            return true650        }651        if selection.length == 0, exitDetails(at: paragraph) { return true }652        // Enter in an empty paragraph inside a list, a quote or a callout steps out of it.653        if selection.length == 0, paragraph.length <= 1, AttributedCodec.isTextual(current), !current.path.isEmpty, lift(at: paragraph.location) { return true }654        return false655    }656657    /// Backspace with an empty selection. Returns true when handled.658    func handleDeleteBackward() -> Bool {659        let selection = textView.selectedRange660        guard selection.length == 0 else { return false }661        let paragraph = paragraphRange(at: selection.location)662        guard selection.location == paragraph.location else { return false }663        let current = style(at: paragraph.location)664        if AttributedCodec.isTextual(current), current.type == "heading" || current.type == "codeBlock" {665            setBlockType("paragraph")666            return true667        }668        if AttributedCodec.isTextual(current), !current.path.isEmpty, lift(at: paragraph.location) { return true }669        // 2.0: the previous paragraph is hidden in a closed toggle: Backspace opens the toggle instead of merging text into what is not shown670        if paragraph.location > 0 {671            let hidden = style(at: paragraphRange(at: paragraph.location - 1).location)672            if hidden.isHiddenInClosedDetails, let closed = hidden.path.first(where: { $0.type == "details" && $0.attrs["open"]?.boolValue != true }),673               let summary = paragraphRanges().first(where: { range in style(at: range.location).path.contains { $0.key == closed.key } }) {674                toggleDetails(at: summary.location)675                return true676            }677        }678        if paragraph.location > 0 {679            // The previous paragraph is a block atom: Backspace removes the atom, it never merges text into it.680            let previous = paragraphRange(at: paragraph.location - 1)681            if blockAtom(in: previous) != nil {682                replace(previous, with: NSAttributedString(), selectAfter: NSRange(location: previous.location, length: 0), actionName: String(localized: "Suppression"))683                return true684            }685        } else {686            return true // start of the document: nothing to delete687        }688        return false689    }690691    func handleTab(shift: Bool) -> Bool {692        let location = textView.selectedRange.location693        let current = style(at: location)694        if current.isCode && !shift { insertText("    "); return true }695        guard current.innermostItem != nil else { return false }696        let range = textView.selectedRange697        let first = lineIndex(at: range.location), last = lineIndex(at: range.length == 0 ? range.location : NSMaxRange(range) - 1)698        if let styles = shift ? StructureCommands.outdent(lines: first...last, in: self) : StructureCommands.indent(lines: first...last, in: self) {699            applyStyles(styles, actionName: shift ? String(localized: "Diminuer le retrait") : String(localized: "Augmenter le retrait"))700        }701        return true702    }703}704705// MARK: - UITextViewDelegate706707extension EditorController: UITextViewDelegate {708    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {709        // The final paragraph terminator is not editable.710        if NSMaxRange(range) > storage.length - 1 && range.length > 0 {711            let clamped = clampSelection(range)712            if clamped.length == 0 && text.isEmpty { return false }713            if clamped != range { replace(clamped, with: NSAttributedString(string: text, attributes: textView.typingAttributes), selectAfter: NSRange(location: clamped.location + (text as NSString).length, length: 0)); return false }714        }715        if handleInputAssist(range: range, text: text) { return false }716        if text == "\n" { return !handleReturn() }717        let paragraph = paragraphRange(at: range.location)718        let current = style(at: paragraph.location)719        // Line breaks pasted or dictated into a code block stay inside the block; a summary line stays one line.720        if text.contains("\n"), current.isCode || current.type == "detailsSummary" {721            let flattened = text.replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\n", with: current.isCode ? EditorCharacter.softBreak : " ")722            replace(range, with: NSAttributedString(string: flattened, attributes: textView.typingAttributes), selectAfter: NSRange(location: range.location + (flattened as NSString).length, length: 0))723            return false724        }725        // Typing beside a block atom opens a new paragraph instead of putting text in the atom's paragraph.726        if !text.isEmpty, range.length == 0, let _ = blockAtom(in: paragraph) {727            let fresh = LineBox(freshParagraph(at: current))728            var attributes = styler.typingAttributes(style: fresh.style, marks: [])729            attributes[.spnLine] = fresh730            if range.location == paragraph.location {731                let inserted = NSMutableAttributedString(string: text + "\n", attributes: attributes)732                replace(NSRange(location: paragraph.location, length: 0), with: inserted, selectAfter: NSRange(location: paragraph.location + (text as NSString).length, length: 0))733            } else {734                let inserted = NSMutableAttributedString(string: text + "\n", attributes: attributes)735                replace(NSRange(location: NSMaxRange(paragraph), length: 0), with: inserted, selectAfter: NSRange(location: NSMaxRange(paragraph) + (text as NSString).length, length: 0))736            }737            return false738        }739        return true740    }741742    func textViewDidChange(_ textView: UITextView) {743        pendingMarks = nil744        // The storage always ends with the last paragraph's terminator; restore it if a system edit (select all + cut, dictation) removed it.745        if storage.length == 0 || (storage.string as NSString).character(at: storage.length - 1) != EditorCharacter.newlineScalar {746            let box = storage.length > 0 ? (lineBox(at: storage.length - 1) ?? LineBox(freshParagraph(at: LineStyle()))) : LineBox(freshParagraph(at: LineStyle()))747            isLoading = true748            storage.beginEditing()749            storage.append(NSAttributedString(string: "\n", attributes: styler.typingAttributes(style: box.style, marks: []).merging([.spnLine: box]) { _, new in new }))750            storage.endEditing()751            isLoading = false752        }753        lastLength = storage.length754        refreshTypingAttributes()755        slash.refresh()756        scheduleDeferredCodeColouring()757        delegate?.editorDidChange(self)758    }759760    func textViewDidChangeSelection(_ textView: UITextView) {761        let clamped = clampSelection(textView.selectedRange)762        if clamped != textView.selectedRange { textView.selectedRange = clamped; return }763        if storage.length == lastLength { pendingMarks = nil } // a caret move (not typing) forgets marks chosen for the next characters764        if slash.isActive { slash.refresh() }765        if leaveHiddenContent() { return }766        refreshTypingAttributes()767        delegate?.editorDidChangeSelection(self)768    }769}770771// MARK: - NSTextStorageDelegate: keep the model attributes consistent after every character edit772773extension EditorController: NSTextStorageDelegate {774    nonisolated func textStorage(_ textStorage: NSTextStorage, willProcessEditing editedMask: NSTextStorage.EditActions, range editedRange: NSRange, changeInLength delta: Int) {775        // Text storage edits happen on the main thread (the text view's); the delegate protocol is just not annotated.776        nonisolated(unsafe) let storage = textStorage777        MainActor.assumeIsolated {778            guard !isLoading, editedMask.contains(.editedCharacters), storage.length > 0 else { return }779            fixParagraphs(in: storage, editedRange: editedRange)780        }781    }782783    private func fixParagraphs(in storage: NSTextStorage, editedRange: NSRange) {784        let string = storage.string as NSString785        let length = string.length786        let startParagraph = string.paragraphRange(for: NSRange(location: min(editedRange.location, length - 1), length: 0))787        // one paragraph past the edit: a newline typed at the end of a paragraph turns the old terminator into the new paragraph788        let endLocation = min(NSMaxRange(editedRange), length - 1)789        let endParagraph = string.paragraphRange(for: NSRange(location: endLocation, length: 0))790        var previousBox: LineBox? = startParagraph.location > 0 ? storage.attribute(.spnLine, at: startParagraph.location - 1, effectiveRange: nil) as? LineBox : nil791        var location = startParagraph.location792        var changed = false793        while location < NSMaxRange(endParagraph) && location < length {794            let paragraph = string.paragraphRange(for: NSRange(location: location, length: 0))795            var box = storage.attribute(.spnLine, at: paragraph.location, effectiveRange: nil) as? LineBox796            if box == nil {797                storage.enumerateAttribute(.spnLine, in: paragraph, options: []) { value, _, stop in if let b = value as? LineBox { box = b; stop.pointee = true } }798            }799            var replacement: LineBox?800            let atom = blockAtom(in: paragraph)801            if let atom {802                let wanted = AttributedCodec.style(forBlockAtom: atom.node, path: box?.style.path ?? previousBox?.style.path ?? [])803                if box?.style != wanted { replacement = LineBox(wanted) }804            } else if let existing = box {805                if !AttributedCodec.isTextual(existing.style) {806                    replacement = LineBox(freshParagraph(at: existing.style))807                } else if let previousBox, existing === previousBox || (existing.style.attrs["id"] != nil && existing.style == previousBox.style) {808                    // same identity as the paragraph above: this one was created by a line break809                    replacement = LineBox(continuation(of: existing.style))810                }811            } else {812                replacement = LineBox(previousBox.map { continuation(of: $0.style) } ?? freshParagraph(at: LineStyle()))813            }814            let final = replacement ?? box!815            if replacement != nil { changed = true }816            var effective = NSRange()817            let currentValue = storage.attribute(.spnLine, at: paragraph.location, longestEffectiveRange: &effective, in: paragraph) as? LineBox818            if replacement != nil || currentValue !== final || effective != paragraph { storage.addAttribute(.spnLine, value: final, range: paragraph) }819            previousBox = final820            location = NSMaxRange(paragraph)821        }822        let processed = NSRange(location: startParagraph.location, length: NSMaxRange(endParagraph) - startParagraph.location)823        styler.restyle(storage, range: processed)824        // list numbering and item heads depend on the paragraphs around: recompute when paragraphs were added, removed or re-identified825        let newlineTouched = changed || structureChanged || storage.length != lastLength && lineCountMayHaveChanged(string: string, editedRange: editedRange)826        if newlineTouched { styler.renumber(storage); structureChanged = false }827    }828829    private func lineCountMayHaveChanged(string: NSString, editedRange: NSRange) -> Bool {830        // A deletion can only be seen by its effect on the length; an insertion is checked for a newline.831        if storage.length < lastLength { return true }832        guard editedRange.length > 0 else { return false }833        return string.range(of: "\n", options: [], range: editedRange).location != NSNotFound834    }835}836837// MARK: - NSTextLayoutManagerDelegate: custom fragments draw markers and boxes838839extension EditorController: NSTextLayoutManagerDelegate {840    nonisolated func textLayoutManager(_ textLayoutManager: NSTextLayoutManager, textLayoutFragmentFor location: any NSTextLocation, in textElement: NSTextElement) -> NSTextLayoutFragment {841        let fragment = EditorLayoutFragment(textElement: textElement, range: textElement.elementRange)842        guard let paragraph = textElement as? NSTextParagraph, paragraph.attributedString.length > 0,843              let style = (paragraph.attributedString.attribute(.spnLine, at: 0, effectiveRange: nil) as? LineBox)?.style else { return fragment }844        // Boxes (callout, code) join across neighbouring paragraphs of the same box.845        guard let boxKey = Self.boxKey(style), let content = textLayoutManager.textContentManager as? NSTextContentStorage, let storage = content.textStorage,846              let range = textElement.elementRange else { return fragment }847        let start = content.offset(from: content.documentRange.location, to: range.location)848        let end = content.offset(from: content.documentRange.location, to: range.endLocation)849        if start > 0, let previous = (storage.attribute(.spnLine, at: start - 1, effectiveRange: nil) as? LineBox)?.style { fragment.joinsPrevious = Self.boxKey(previous) == boxKey }850        if end < storage.length, let next = (storage.attribute(.spnLine, at: end, effectiveRange: nil) as? LineBox)?.style { fragment.joinsNext = Self.boxKey(next) == boxKey }851        return fragment852    }853854    /// Identity of the box a paragraph is drawn in: the callout container, or the code block itself.855    nonisolated static func boxKey(_ style: LineStyle) -> String? {856        if let container = style.path.first(where: { $0.type == "callout" || $0.type == "aiBlock" || $0.type == "details" }) { return "c\(container.key)" }857        if style.isCode { if case .string(let id)? = style.attrs["id"] { return "k\(id)" } else { return "k" } }858        return nil859    }860}861862// MARK: - NSTextContentStorageDelegate: the content of a closed toggle is skipped by the layout (2.0)863864extension EditorController: NSTextContentStorageDelegate {865    nonisolated func textContentManager(_ textContentManager: NSTextContentManager, shouldEnumerate textElement: NSTextElement, options: NSTextContentManager.EnumerationOptions = []) -> Bool {866        guard let paragraph = textElement as? NSTextParagraph, paragraph.attributedString.length > 0,867              let style = (paragraph.attributedString.attribute(.spnLine, at: 0, effectiveRange: nil) as? LineBox)?.style else { return true }868        return !style.isHiddenInClosedDetails869    }870871    /// A caret that lands in the hidden content of a closed toggle (arrow keys, a programmatic selection) goes to the end of872    /// the toggle's summary instead. Returns true when it moved the selection.873    func leaveHiddenContent() -> Bool {874        let selection = textView.selectedRange875        guard selection.length == 0, storage.length > 0, style(at: selection.location).isHiddenInClosedDetails else { return false }876        var location = paragraphRange(at: selection.location).location877        while location > 0 {878            let previous = paragraphRange(at: location - 1)879            if !style(at: previous.location).isHiddenInClosedDetails {880                textView.selectedRange = NSRange(location: max(previous.location, NSMaxRange(previous) - 1), length: 0)881                return true882            }883            location = previous.location884        }885        return false886    }887}888
Files main
Menu

Theme