Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Editor/NoteTextView.swift3// Description: The native note editor: an NSTextView on TextKit 2 whose storage carries the document structure; structured typing (Return, Tab, Backspace), undo, check boxes, links, incremental styling.4import AppKit5import SPNotesDocument67@MainActor public protocol NoteTextViewDelegate: AnyObject {8 /// The document changed (typing, command, undo). Called after every change; serialisation is the owner's business.9 func noteTextViewDidChange(_ view: NoteTextView)10 func noteTextViewSelectionDidChange(_ view: NoteTextView)11 func noteTextView(_ view: NoteTextView, open link: String)12 /// Double-click on a block or inline atom (table, equation, image, file, mention…).13 func noteTextView(_ view: NoteTextView, activate atom: AtomAttachment, at range: NSRange)14 /// Files dropped or pasted into the note: the owner stores them and inserts the resulting nodes.15 func noteTextView(_ view: NoteTextView, receive files: [URL], images: [NSImage], at location: Int)16 func noteTextView(_ view: NoteTextView, completionsFor trigger: Character, query: String) -> [CompletionItem]17 /// Click on the due / priority chips of a task item (or the command): the owner shows its editor at `anchor`.18 func noteTextView(_ view: NoteTextView, editTaskAt location: Int, anchor: CGRect)19 /// Click on a source chip of an AI block: open that page at that block.20 func noteTextView(_ view: NoteTextView, openPage pageId: String, blockId: String?)21}22public extension NoteTextViewDelegate {23 func noteTextView(_ view: NoteTextView, editTaskAt location: Int, anchor: CGRect) {}24 func noteTextView(_ view: NoteTextView, openPage pageId: String, blockId: String?) {}25}2627public struct CompletionItem: Identifiable {28 public let id: String29 public var title: String30 public var subtitle: String?31 public var symbol: String?32 public var group: String?33 /// Runs after the trigger text was removed; the caret sits where it was.34 public var action: @MainActor (NoteTextView) -> Void35 public init(id: String, title: String, subtitle: String? = nil, symbol: String? = nil, group: String? = nil, action: @escaping @MainActor (NoteTextView) -> Void) {36 self.id = id; self.title = title; self.subtitle = subtitle; self.symbol = symbol; self.group = group; self.action = action37 }38}3940public final class NoteTextView: NSTextView, NSTextStorageDelegate, NSTextLayoutManagerDelegate {41 public weak var noteDelegate: NoteTextViewDelegate?42 public weak var resources: AtomResources?43 public private(set) var theme = EditorTheme()44 public let keys = KeyAllocator()45 /// Width of the text column; the insets grow on a wide window so that lines stay readable.46 public var maxColumnWidth: CGFloat = 720 { didSet { updateInsets() } }47 var isStyling = false48 var isLoading = false49 /// Marks chosen with no selection (⌘B then type): they apply to the next typed text at this caret position.50 var pendingMarks: (location: Int, marks: MarkSet)?51 var completion: CompletionSession?52 public var styler: Styler { Styler(theme: theme) }53 public var codec: DocumentCodec { DocumentCodec(theme: theme, resources: resources) }54 public var storage: NSTextStorage { textStorage! }55 /// Each note view has its own undo history (two windows on two notes never undo each other's edits).56 private let ownUndoManager = UndoManager()57 public override var undoManager: UndoManager? { ownUndoManager }5859 // MARK: Construction6061 /// The editor inside its scroll view, on the TextKit 2 stack.62 public static func makeScrollable() -> (scroll: NSScrollView, view: NoteTextView) {63 let content = NSTextContentStorage()64 let layout = NSTextLayoutManager()65 content.addTextLayoutManager(layout)66 let container = NSTextContainer(size: CGSize(width: 600, height: CGFloat.greatestFiniteMagnitude))67 container.widthTracksTextView = true68 layout.textContainer = container69 let view = NoteTextView(frame: CGRect(x: 0, y: 0, width: 600, height: 400), textContainer: container)70 view.contentStorageRef = content71 view.configure()72 let scroll = NSScrollView()73 scroll.hasVerticalScroller = true; scroll.drawsBackground = false; scroll.borderType = .noBorder; scroll.autohidesScrollers = true74 scroll.documentView = view75 return (scroll, view)76 }77 private var contentStorageRef: NSTextContentStorage?7879 private func configure() {80 minSize = CGSize(width: 0, height: 0); maxSize = CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)81 isVerticallyResizable = true; isHorizontallyResizable = false; autoresizingMask = [.width]82 isRichText = true; importsGraphics = false; allowsUndo = true; isEditable = true; isSelectable = true83 drawsBackground = false; usesFindBar = true; isIncrementalSearchingEnabled = true84 isAutomaticQuoteSubstitutionEnabled = true; isAutomaticDashSubstitutionEnabled = false; isAutomaticLinkDetectionEnabled = false85 isContinuousSpellCheckingEnabled = true; isGrammarCheckingEnabled = false; isAutomaticSpellingCorrectionEnabled = false86 isAutomaticTextReplacementEnabled = true; smartInsertDeleteEnabled = false; usesFontPanel = false; usesRuler = false87 textContainer?.lineFragmentPadding = 488 linkTextAttributes = [:]89 insertionPointColor = EditorTheme.accent90 selectedTextAttributes = [.backgroundColor: NSColor.selectedTextBackgroundColor]91 storage.delegate = self92 textLayoutManager?.delegate = self93 registerForDraggedTypes([.fileURL, .png, .tiff, .string, NoteFragment.pasteboardType])94 setAccessibilityLabel("Contenu de la note")95 load(NoteDocument())96 }9798 public override func setFrameSize(_ newSize: NSSize) { super.setFrameSize(newSize); updateInsets() }99 private func updateInsets() {100 let w = enclosingScrollView?.contentSize.width ?? frame.width101 let side = max(EditorMetrics.minSideInset, ((w - maxColumnWidth) / 2).rounded(.down))102 if abs(textContainerInset.width - side) > 0.5 || textContainerInset.height != EditorMetrics.textInset { textContainerInset = NSSize(width: side, height: EditorMetrics.textInset) }103 }104105 // MARK: Document in / out106107 /// Replaces the whole content (opening a note). Clears the undo stack.108 public func load(_ doc: NoteDocument) {109 isLoading = true; defer { isLoading = false }110 dismissCompletion()111 // blocks without an id (a note that never went through an editor) get one now, so that it is the same at every save112 var doc = doc; doc.ensureBlockIds()113 keys.reserve(above: DocumentCodec.maxKey(doc))114 let text = codec.attributedString(from: doc)115 undoManager?.removeAllActions()116 isStyling = true117 storage.setAttributedString(text)118 isStyling = false119 setSelectedRange(NSRange(location: 0, length: 0))120 refreshTypingAttributes()121 }122123 /// The document as it is now. Blocks created in the editor already carry ids.124 public func document() -> NoteDocument {125 var d = DocumentCodec.document(from: storage)126 d.ensureBlockIds()127 return d128 }129130 /// Applies a document that came from elsewhere (synchronisation, version restore) by replacing only the lines that131 /// differ, so the caret and the scroll position stay where they are when the change is elsewhere. Not undoable.132 public func applyRemote(_ doc: NoteDocument) {133 let current = DocumentCodec.lines(from: storage, in: NSRange(location: 0, length: storage.length))134 // A document written by a 2.x editor has no id on its list items: they get one here (as at load), and an item that135 // only differs by an id it never had is the same item — its local id is kept, the line is not replaced.136 let incoming = doc.lines137 var doc = doc; doc.ensureBlockIds()138 let target = doc.lines139 func attrsMatch(_ local: Container, _ remote: Container) -> Bool {140 if local.attrs == remote.attrs { return true }141 guard Styler.itemTypes.contains(local.type), remote.attrs["id"] == nil || remote.attrs["id"] == .null else { return false }142 var l = local.attrs, r = remote.attrs; l["id"] = nil; r["id"] = nil143 return l == r144 }145 func same(_ a: Line, _ i: Int) -> Bool {146 let b = i < incoming.count ? incoming[i] : target[i]147 return a.type == b.type && a.attrs == b.attrs && a.content == b.content && a.path.count == b.path.count && a.path.map(\.type) == b.path.map(\.type) && zip(a.path, b.path).allSatisfy { attrsMatch($0, $1) }148 }149 guard incoming.count == target.count else { load(doc); return }150 var prefix = 0; while prefix < current.count, prefix < target.count, same(current[prefix], prefix) { prefix += 1 }151 var suffix = 0; while suffix < current.count - prefix, suffix < target.count - prefix, same(current[current.count - 1 - suffix], target.count - 1 - suffix) { suffix += 1 }152 if prefix == current.count, prefix == target.count { return }153 guard let ranges = paragraphRanges(lineCounts: current.map(Self.paragraphCount)) else { load(doc); return }154 let start = prefix < ranges.count ? ranges[prefix].location : storage.length155 let endIndex = current.count - suffix156 let end = endIndex > prefix ? NSMaxRange(ranges[endIndex - 1]) : start157 keys.reserve(above: DocumentCodec.maxKey(doc))158 // Container keys are local numbers. The unchanged lines on both sides tell which incoming container is which local159 // one, so a changed item stays inside its list instead of splitting it; containers never seen get fresh keys.160 var remap: [Int: Int] = [:]; var localItem: [Int: Container] = [:]161 for (i, j) in zip(Array(0..<prefix) + (0..<suffix).map { target.count - 1 - $0 }, Array(0..<prefix) + (0..<suffix).map { current.count - 1 - $0 }) {162 for (t, c) in zip(target[i].path, current[j].path) { remap[t.key] = c.key; if Styler.itemTypes.contains(c.type) { localItem[t.key] = c } }163 }164 let replacement = NSMutableAttributedString()165 for var line in target[prefix..<(target.count - suffix)] {166 line.path = line.path.map { c in if let l = localItem[c.key] { return l }; var c = c; if let k = remap[c.key] { c.key = k } else { let k = keys.make(); remap[c.key] = k; c.key = k }; return c }167 replacement.append(codec.attributed(line))168 }169 let sel = selectedRange(); let delta = replacement.length - (end - start)170 isLoading = true171 storage.beginEditing(); storage.replaceCharacters(in: NSRange(location: start, length: end - start), with: replacement); storage.endEditing()172 isLoading = false173 undoManager?.removeAllActions()174 var newSel = sel175 if sel.location >= end { newSel.location += delta } else if NSMaxRange(sel) > start { newSel = NSRange(location: min(max(start, sel.location), max(0, storage.length - 1)), length: 0) }176 setSelectedRange(clamp(newSel))177 refreshTypingAttributes()178 }179 private static func paragraphCount(_ line: Line) -> Int {180 guard line.type == "codeBlock", case .inline(let runs) = line.content else { return 1 }181 return 1 + runs.reduce(0) { n, r in if case .text(let t, _) = r { return n + t.filter { $0 == "\n" }.count }; return n }182 }183 /// Character range of each line (a code block spans several paragraphs).184 private func paragraphRanges(lineCounts: [Int]) -> [NSRange]? {185 let ns = storage.string as NSString; var out: [NSRange] = []; var loc = 0186 for count in lineCounts {187 var r = NSRange(location: loc, length: 0)188 for _ in 0..<count { guard loc < ns.length else { return nil }; let p = ns.paragraphRange(for: NSRange(location: loc, length: 0)); r = NSUnionRange(r, p); loc = NSMaxRange(p) }189 out.append(r)190 }191 return loc == ns.length ? out : nil192 }193194 public func setTheme(_ new: EditorTheme) {195 guard new != theme else { return }196 theme = new197 isStyling = true198 storage.beginEditing()199 storage.enumerateAttribute(.attachment, in: NSRange(location: 0, length: storage.length)) { v, _, _ in if let a = v as? AtomAttachment { a.theme = new; a.invalidate() } }200 styler.style(storage, in: NSRange(location: 0, length: storage.length))201 storage.endEditing()202 isStyling = false203 refreshTypingAttributes(); relayout()204 }205206 /// Images arrived on disk, or the appearance changed: attachments are drawn again.207 public func refreshAtoms() {208 storage.enumerateAttribute(.attachment, in: NSRange(location: 0, length: storage.length)) { v, r, _ in209 if let a = v as? AtomAttachment { a.invalidate(); invalidateLayout(r) }210 }211 needsDisplay = true212 }213 public override func viewDidChangeEffectiveAppearance() { super.viewDidChangeEffectiveAppearance(); refreshAtoms() }214215 func relayout() {216 guard let lm = textLayoutManager else { return }217 lm.invalidateLayout(for: lm.documentRange); needsDisplay = true218 }219 func invalidateLayout(_ range: NSRange) {220 guard let lm = textLayoutManager, let cs = contentStorageRef, let start = cs.location(cs.documentRange.location, offsetBy: range.location), let end = cs.location(start, offsetBy: range.length), let tr = NSTextRange(location: start, end: end) else { return }221 lm.invalidateLayout(for: tr)222 }223224 // MARK: Storage delegate — incremental styling225226 public nonisolated func textStorage(_ textStorage: NSTextStorage, didProcessEditing editedMask: NSTextStorageEditActions, range editedRange: NSRange, changeInLength delta: Int) {227 nonisolated(unsafe) let textStorage = textStorage228 MainActor.assumeIsolated {229 guard !isStyling, textStorage.length > 0 else { return }230 if !isLoading, !(textStorage.string as NSString).hasSuffix("\n") {231 // invariant: the last paragraph is terminated (its newline carries the paragraph attributes)232 }233 isStyling = true; defer { isStyling = false }234 let safe = NSRange(location: min(editedRange.location, textStorage.length), length: min(editedRange.length, textStorage.length - min(editedRange.location, textStorage.length)))235 // typed text must carry marks; text that arrives without (dictation, services) gets none236 if editedMask.contains(.editedCharacters), safe.length > 0 {237 textStorage.enumerateAttribute(.spMarks, in: safe) { v, r, _ in if v == nil { textStorage.addAttribute(.spMarks, value: MarkSet.none, range: r) } }238 }239 let range = styler.affectedRange(in: textStorage, for: safe)240 styler.style(textStorage, in: range)241 }242 }243244 // MARK: Layout delegate — block decorations245246 public nonisolated func textLayoutManager(_ textLayoutManager: NSTextLayoutManager, textLayoutFragmentFor location: NSTextLocation, in textElement: NSTextElement) -> NSTextLayoutFragment {247 let fragment = BlockLayoutFragment(textElement: textElement, range: textElement.elementRange)248 if let para = textElement as? NSTextParagraph, para.attributedString.length > 0 {249 fragment.decoration = para.attributedString.attribute(.spDecoration, at: 0, effectiveRange: nil) as? ParaDecoration250 }251 fragment.containerWidth = textLayoutManager.textContainer?.size.width ?? 600252 let me = self253 fragment.fontSize = MainActor.assumeIsolated { me.theme.fontSize }254 return fragment255 }256257 // MARK: Editing primitive (undoable)258259 /// Replaces `range` with `new`. Every structural command goes through here, so each one is a single undo step and260 /// the styler only sees the touched paragraphs.261 public func replace(_ range: NSRange, with new: NSAttributedString, select: NSRange? = nil, actionName: String? = nil) {262 guard range.location >= 0, NSMaxRange(range) <= storage.length else { return }263 breakUndoCoalescing()264 let old = storage.attributedSubstring(from: range)265 let oldSelection = selectedRange()266 let newRange = NSRange(location: range.location, length: new.length)267 undoManager?.registerUndo(withTarget: self) { tv in tv.replace(newRange, with: old, select: oldSelection, actionName: actionName) }268 if let actionName, undoManager?.isUndoing == false, undoManager?.isRedoing == false { undoManager?.setActionName(actionName) }269 storage.beginEditing(); storage.replaceCharacters(in: range, with: new); storage.endEditing()270 ensureTerminated()271 if let select { setSelectedRange(clamp(select)) }272 pendingMarks = nil273 refreshTypingAttributes()274 didChangeText()275 }276277 /// Rewrites the block style of every paragraph touching `range` (undoable). The closure sees paragraphs in order.278 public func restyleParagraphs(in range: NSRange, actionName: String? = nil, perParagraph: Bool = false, _ transform: (ParaStyle, Int) -> ParaStyle) {279 let ns = storage.string as NSString280 guard ns.length > 0 else { return }281 let whole = ns.paragraphRange(for: NSRange(location: min(range.location, ns.length - 1), length: min(range.length, ns.length - min(range.location, ns.length - 1))))282 let copy = NSMutableAttributedString(attributedString: storage.attributedSubstring(from: whole))283 let cns = copy.string as NSString; var loc = 0; var i = 0; var last: (old: ParaStyle, new: ParaStyle)?284 while loc < cns.length {285 let pr = cns.paragraphRange(for: NSRange(location: loc, length: 0))286 let old = (copy.attribute(.spPara, at: pr.location, effectiveRange: nil) as? ParaStyle) ?? ParaStyle()287 // lines of one code block share one instance, before and after288 let new: ParaStyle289 if !perParagraph, let l = last, l.old === old { new = l.new } else { new = transform(old, i); i += 1 }290 last = (old, new)291 copy.addAttribute(.spPara, value: new, range: pr); loc = NSMaxRange(pr)292 }293 let sel = selectedRange()294 replace(whole, with: copy, select: sel, actionName: actionName)295 }296297 private func ensureTerminated() {298 guard !(storage.string as NSString).hasSuffix("\n") else { return }299 let style = storage.length > 0 ? (storage.attribute(.spPara, at: storage.length - 1, effectiveRange: nil) as? ParaStyle)?.sibling() ?? ParaStyle() : newParagraphStyle(path: [])300 storage.append(NSAttributedString(string: "\n", attributes: [.spPara: style, .spMarks: MarkSet.none]))301 }302 public override func didChangeText() {303 ensureTerminated()304 super.didChangeText()305 if !isLoading { noteDelegate?.noteTextViewDidChange(self) }306 updateCompletion()307 }308309 // MARK: Selection310311 /// The caret never goes past the terminating newline of the last paragraph.312 func clamp(_ r: NSRange) -> NSRange {313 let maxLoc = max(0, storage.length - 1)314 let loc = min(max(0, r.location), maxLoc)315 return NSRange(location: loc, length: min(r.length, maxLoc - loc))316 }317 public override func setSelectedRanges(_ ranges: [NSValue], affinity: NSSelectionAffinity, stillSelecting: Bool) {318 let clamped = ranges.map { NSValue(range: clamp($0.rangeValue)) }319 super.setSelectedRanges(clamped, affinity: affinity, stillSelecting: stillSelecting)320 if !stillSelecting, !isLoading {321 if let p = pendingMarks, p.location != selectedRange().location || selectedRange().length > 0 { pendingMarks = nil }322 refreshTypingAttributes()323 noteDelegate?.noteTextViewSelectionDidChange(self)324 if completion != nil { updateCompletion() }325 }326 }327328 public func paraStyle(at location: Int) -> ParaStyle {329 guard storage.length > 0 else { return ParaStyle() }330 return (storage.attribute(.spPara, at: min(max(0, location), storage.length - 1), effectiveRange: nil) as? ParaStyle) ?? ParaStyle()331 }332 public func paragraphRange(at location: Int) -> NSRange { (storage.string as NSString).paragraphRange(for: NSRange(location: min(max(0, location), max(0, storage.length - 1)), length: 0)) }333 /// Paragraph range without its terminating newline.334 public func contentRange(at location: Int) -> NSRange { var r = paragraphRange(at: location); if r.length > 0 { r.length -= 1 }; return r }335336 /// Marks that typed text would get at the caret (or the marks common to the selection).337 public func activeMarks() -> MarkSet {338 let sel = selectedRange()339 if sel.length == 0 {340 if let p = pendingMarks, p.location == sel.location { return p.marks }341 let content = contentRange(at: sel.location)342 guard sel.location > content.location, storage.attribute(.attachment, at: sel.location - 1, effectiveRange: nil) == nil else { return .none }343 // a link does not extend to text typed after it344 return ((storage.attribute(.spMarks, at: sel.location - 1, effectiveRange: nil) as? MarkSet) ?? .none).removing("link")345 }346 var common: [PMMark]?347 storage.enumerateAttribute(.spMarks, in: sel) { v, r, _ in348 if (storage.string as NSString).substring(with: r).allSatisfy({ $0 == "\n" }) { return }349 let m = (v as? MarkSet)?.marks ?? []350 common = common.map { c in c.filter { x in m.contains { $0.type == x.type } } } ?? m351 }352 return MarkSet(common ?? [])353 }354355 func refreshTypingAttributes() {356 guard storage.length > 0 else { return }357 let loc = selectedRange().location358 let style = paraStyle(at: loc)359 var attrs = styler.typingAttributes(style: style.isAtom ? ParaStyle(path: style.path) : style, marks: activeMarks())360 attrs[.attachment] = nil; attrs[.spInlineNode] = nil361 typingAttributes = attrs362 }363364 // MARK: Block ids and new blocks365366 static let idAlphabet = Array("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-")367 public static func newBlockID() -> String { String((0..<10).map { _ in idAlphabet[Int.random(in: 0..<64)] }) }368 /// Same list as the server's `ID_TYPES` and Core's `Schema.idTypes` (internal there): 3.0 adds list items and the new block atoms.369 static let idTypes: Set<String> = NodeType.blockIdTypes370371 /// Style of a block born in the editor: every attribute the web schema defines (defaults included) and a fresh id,372 /// exactly as the web editor would serialise it. `attrs` overrides the defaults.373 public func newParagraphStyle(path: [Container], type: String = "paragraph", attrs: [String: JSONValue] = [:]) -> ParaStyle {374 var line: Line375 switch type {376 case "paragraph": line = .paragraph(path: path)377 case "heading": line = .heading(level: attrs["level"]?.int ?? 1, path: path)378 case "codeBlock": line = .codeBlock(language: attrs["language"]?.string, path: path)379 default: line = Line(path: path, type: type, attrs: [:], content: .inline([]))380 }381 for (k, v) in attrs { line.attrs[k] = v }382 if Self.idTypes.contains(type), line.attrs["id"] == nil { line.attrs["id"] = .string(Self.newBlockID()) }383 return ParaStyle(line: line, isAtom: false)384 }385 public func newContainer(_ type: String, attrs: [String: JSONValue] = [:]) -> Container {386 var scratch = NoteDocument(lines: [])387 var c = scratch.makeContainer(type, attrs: attrs)388 c.key = keys.make()389 if Self.idTypes.contains(type), c.attrs["id"] == nil { c.attrs["id"] = .string(Self.newBlockID()) }390 return c391 }392 func newItem(for list: Container) -> Container { newContainer(list.type == "taskList" ? "taskItem" : "listItem", attrs: list.type == "taskList" ? ["checked": .bool(false)] : [:]) }393394 func paragraph(_ text: String = "", style: ParaStyle, marks: MarkSet = .none) -> NSMutableAttributedString {395 NSMutableAttributedString(string: text + "\n", attributes: [.spPara: style, .spMarks: marks])396 }397398 // MARK: Typing399400 public override func insertText(_ string: Any, replacementRange: NSRange) {401 let text = (string as? String) ?? (string as? NSAttributedString)?.string ?? ""402 let sel = replacementRange.location == NSNotFound ? selectedRange() : replacementRange403 // typing next to a table / image / rule opens a paragraph beside it instead of mixing text into the block404 if sel.length == 0, paraStyle(at: sel.location).isAtom, !text.isEmpty {405 let pr = paragraphRange(at: sel.location); let style = paraStyle(at: sel.location)406 let after = sel.location > pr.location407 let at = after ? NSMaxRange(pr) : pr.location408 replace(NSRange(location: at, length: 0), with: paragraph(style: newParagraphStyle(path: style.path)), select: NSRange(location: at, length: 0))409 super.insertText(string, replacementRange: NSRange(location: NSNotFound, length: 0))410 return411 }412 if text == " ", sel.length == 0, applyMarkdownShortcut(at: sel.location) { return }413 if let p = pendingMarks, p.location == sel.location, sel.length == 0 { var a = typingAttributes; a[.spMarks] = p.marks; typingAttributes = styler.typingAttributes(style: paraStyle(at: sel.location), marks: p.marks).merging(a) { cur, _ in cur } }414 super.insertText(string, replacementRange: replacementRange)415 if text == "/" || text == "@" { beginCompletion(trigger: Character(text)) }416 }417418 /// `# `, `- `, `1. `, `[] `, `> ` at the start of a plain paragraph turn it into the matching block.419 private func applyMarkdownShortcut(at caret: Int) -> Bool {420 let style = paraStyle(at: caret); let content = contentRange(at: caret)421 guard style.type == "paragraph", !style.isAtom, caret - content.location <= 6, caret > content.location else { return false }422 let prefix = (storage.string as NSString).substring(with: NSRange(location: content.location, length: caret - content.location))423 let kind: BlockKind424 switch prefix {425 case "#": kind = .heading(1); case "##": kind = .heading(2); case "###": kind = .heading(3)426 case "-", "*", "+": kind = .bullet427 case "[]", "[ ]": kind = .task428 case ">": kind = .quote429 case "```": kind = .code430 default:431 guard prefix.hasSuffix("."), let n = Int(prefix.dropLast()), n >= 0, n < 10_000 else { return false }432 kind = .ordered(start: n)433 }434 if case .bullet = kind, style.item != nil { return false }435 undoManager?.beginUndoGrouping()436 replace(NSRange(location: content.location, length: caret - content.location), with: NSAttributedString(), select: NSRange(location: content.location, length: 0))437 setBlock(kind, toggle: false)438 undoManager?.endUndoGrouping()439 return true440 }441442 public override func insertNewline(_ sender: Any?) {443 if completion != nil, commitCompletion() { return }444 var sel = selectedRange()445 // Return on a selected block (table, diagram, chart, PDF…) opens its native editor, like a double-click446 if sel.length == 1, let a = storage.attribute(.attachment, at: sel.location, effectiveRange: nil) as? AtomAttachment, a.isBlock { noteDelegate?.noteTextView(self, activate: a, at: sel); return }447 if sel.length > 0 { replace(sel, with: NSAttributedString(), select: NSRange(location: sel.location, length: 0)); sel = selectedRange() }448 let caret = sel.location; let style = paraStyle(at: caret); let pr = paragraphRange(at: caret); let content = contentRange(at: caret)449 let text = (storage.string as NSString).substring(with: content)450 let empty = content.length == 0451452 if style.isAtom {453 let at = caret > pr.location ? NSMaxRange(pr) : pr.location454 replace(NSRange(location: at, length: 0), with: paragraph(style: newParagraphStyle(path: style.path)), select: NSRange(location: at, length: 0), actionName: "Nouveau paragraphe")455 return456 }457 if style.isCode {458 // an empty last line leaves the block459 let isLast = NSMaxRange(pr) >= storage.length || paraStyle(at: NSMaxRange(pr)) !== style460 if empty, isLast, pr.location > 0, paraStyle(at: pr.location - 1) === style {461 replace(pr, with: paragraph(style: newParagraphStyle(path: style.path)), select: NSRange(location: pr.location, length: 0), actionName: "Quitter le bloc de code")462 return463 }464 let indent = String(text.prefix { $0 == " " || $0 == "\t" })465 replace(NSRange(location: caret, length: 0), with: NSAttributedString(string: "\n" + indent, attributes: [.spPara: style, .spMarks: MarkSet.none]), select: NSRange(location: caret + 1 + (indent as NSString).length, length: 0), actionName: "Saisie")466 return467 }468 if style.type == "paragraph", text == "---" || text == "***" {469 let rule = codec.attributed(Line(path: style.path, type: "horizontalRule", attrs: [:], content: .blockAtom(.horizontalRule())))470 rule.append(paragraph(style: newParagraphStyle(path: style.path)))471 replace(pr, with: rule, select: NSRange(location: pr.location + 2, length: 0), actionName: "Séparateur")472 return473 }474 if style.type == "paragraph", text.hasPrefix("```"), caret == NSMaxRange(content) {475 let lang = String(text.dropFirst(3)).trimmingCharacters(in: .whitespaces)476 replace(pr, with: paragraph(style: newParagraphStyle(path: style.path, type: "codeBlock", attrs: ["language": lang.isEmpty ? .null : .string(lang)])), select: NSRange(location: pr.location, length: 0), actionName: "Bloc de code")477 return478 }479 if empty, !style.path.isEmpty {480 // Return on an empty item / quoted paragraph climbs out one level481 lift(at: caret); return482 }483 if empty, style.type != "paragraph" {484 replace(pr, with: paragraph(style: newParagraphStyle(path: style.path)), select: NSRange(location: pr.location, length: 0), actionName: "Paragraphe")485 return486 }487 // split: the new block follows the current one488 var nextPath = style.path489 if let it = style.item { nextPath[nextPath.count - 1] = newItem(for: it.list) }490 if caret == content.location, !empty {491 // caret at the very start: an empty block opens above, the text keeps its identity492 let above = newParagraphStyle(path: style.item != nil ? nextPath : style.path, type: style.item != nil ? style.type : "paragraph")493 replace(NSRange(location: caret, length: 0), with: paragraph(style: above), select: NSRange(location: caret + 1, length: 0), actionName: "Saisie")494 return495 }496 let keepType = caret < NSMaxRange(content) && style.type != "heading" ? style.type : (style.type == "detailsSummary" || style.type == "footnote" || style.type == "heading" ? "paragraph" : style.type)497 let next = newParagraphStyle(path: nextPath, type: keepType, attrs: keepType == style.type ? style.sibling().attrs : [:])498 let tail = NSMutableAttributedString(attributedString: storage.attributedSubstring(from: NSRange(location: caret, length: NSMaxRange(pr) - caret)))499 tail.addAttribute(.spPara, value: next, range: NSRange(location: 0, length: tail.length))500 let insert = NSMutableAttributedString(string: "\n", attributes: [.spPara: style, .spMarks: MarkSet.none])501 insert.append(tail)502 replace(NSRange(location: caret, length: NSMaxRange(pr) - caret), with: insert, select: NSRange(location: caret + 1, length: 0), actionName: "Saisie")503 }504505 /// ⇧Return: a line break inside the block.506 public override func insertLineBreak(_ sender: Any?) {507 let sel = selectedRange(); let style = paraStyle(at: sel.location)508 if style.isAtom { return }509 if style.isCode { insertNewline(sender); return }510 replace(sel, with: codec.attributed(.atom(.hardBreak())).with(.spPara, style), select: NSRange(location: sel.location + 1, length: 0), actionName: "Saut de ligne")511 }512513 public override func insertTab(_ sender: Any?) {514 if completion != nil, commitCompletion() { return }515 let sel = selectedRange(); let style = paraStyle(at: sel.location)516 if style.isCode { replace(sel, with: NSAttributedString(string: " ", attributes: [.spPara: style, .spMarks: MarkSet.none]), select: NSRange(location: sel.location + 4, length: 0)); return }517 if style.item != nil { indent(); return }518 super.insertTab(sender)519 }520 public override func insertBacktab(_ sender: Any?) { if paraStyle(at: selectedRange().location).item != nil { outdent() } }521522 public override func deleteBackward(_ sender: Any?) {523 let sel = selectedRange()524 if sel.length == 0 {525 let pr = paragraphRange(at: sel.location); let style = paraStyle(at: sel.location)526 if sel.location == pr.location {527 let firstOfCode = style.isCode && (pr.location == 0 || paraStyle(at: pr.location - 1) !== style)528 if !style.path.isEmpty, !style.isCode || firstOfCode { lift(at: sel.location); return }529 if (style.type != "paragraph" && !style.isAtom && !style.isCode) || firstOfCode {530 restyleParagraphs(in: firstOfCode ? codeBlockRange(at: sel.location) : pr, actionName: "Paragraphe") { s, _ in self.newParagraphStyle(path: s.path) }531 return532 }533 if pr.location > 0 {534 let prev = paraStyle(at: pr.location - 1)535 // Backspace under a table / image selects it; a second press deletes it536 if prev.isAtom, !style.isAtom { let ar = paragraphRange(at: pr.location - 1); setSelectedRange(NSRange(location: ar.location, length: 1)); return }537 if style.isAtom { setSelectedRange(NSRange(location: pr.location, length: 1)); return }538 } else { return }539 } else if style.isAtom {540 // caret after the atom: remove the whole block541 replace(pr, with: pr.location == 0 && NSMaxRange(pr) >= storage.length ? paragraph(style: newParagraphStyle(path: [])) : NSAttributedString(), select: NSRange(location: max(0, pr.location - (pr.location > 0 ? 1 : 0)), length: 0), actionName: "Supprimer le bloc")542 return543 }544 } else if let whole = wholeAtomSelection(sel) {545 replace(whole, with: whole.location == 0 && NSMaxRange(whole) >= storage.length ? paragraph(style: newParagraphStyle(path: [])) : NSAttributedString(), select: NSRange(location: max(0, whole.location - (whole.location > 0 ? 1 : 0)), length: 0), actionName: "Supprimer le bloc")546 return547 }548 super.deleteBackward(sender)549 }550 public override func deleteForward(_ sender: Any?) {551 let sel = selectedRange()552 if sel.length == 0, sel.location >= storage.length - 1 { return }553 if sel.length > 0, let whole = wholeAtomSelection(sel) { replace(whole, with: NSAttributedString(), select: NSRange(location: whole.location, length: 0), actionName: "Supprimer le bloc"); return }554 super.deleteForward(sender)555 }556 /// A selection that is exactly the attachment of an atom paragraph stands for the whole block (with its newline).557 private func wholeAtomSelection(_ sel: NSRange) -> NSRange? {558 let pr = paragraphRange(at: sel.location)559 guard paraStyle(at: sel.location).isAtom, sel.location == pr.location, sel.length == 1 else { return nil }560 return pr561 }562 func codeBlockRange(at location: Int) -> NSRange {563 let style = paraStyle(at: location); var r = paragraphRange(at: location)564 guard style.isCode else { return r }565 while r.location > 0, paraStyle(at: r.location - 1) === style { r = NSUnionRange(r, paragraphRange(at: r.location - 1)) }566 while NSMaxRange(r) < storage.length, paraStyle(at: NSMaxRange(r)) === style { r = NSUnionRange(r, paragraphRange(at: NSMaxRange(r))) }567 return r568 }569570 /// Takes the paragraph one level out of its innermost structure (nested list → parent list, list → body, quote → body).571 func lift(at location: Int) {572 restyleParagraphs(in: NSRange(location: location, length: 0), actionName: "Diminuer le retrait") { s, _ in self.lifted(s) }573 }574 func lifted(_ s: ParaStyle) -> ParaStyle {575 var path = s.path576 guard let last = path.last else { return s }577 if Styler.itemTypes.contains(last.type), path.count >= 2 {578 path.removeLast(2)579 // inside a parent item: become its next sibling580 if let parentItem = path.last, Styler.itemTypes.contains(parentItem.type), path.count >= 2 { path[path.count - 1] = newItem(for: path[path.count - 2]) }581 } else { path.removeLast(); if path.last?.type == "details" { path.removeLast() } }582 return s.with(path: path)583 }584585 // MARK: Mouse586587 public override func mouseDown(with event: NSEvent) {588 dismissCompletion()589 let point = convert(event.locationInWindow, from: nil)590 if let hit = checkboxHit(at: point) { toggleCheckbox(at: hit); return }591 if let (f, local) = fragment(at: point), let loc = location(of: f) {592 if let i = f.taskChipRects.firstIndex(where: { $0.insetBy(dx: -2, dy: -3).contains(local) }) {593 let r = f.taskChipRects[i].offsetBy(dx: f.layoutFragmentFrame.minX + textContainerOrigin.x, dy: f.layoutFragmentFrame.minY + textContainerOrigin.y)594 noteDelegate?.noteTextView(self, editTaskAt: loc, anchor: r); return595 }596 if let i = f.aiSourceRects.firstIndex(where: { $0.insetBy(dx: -1, dy: -3).contains(local) }), let chips = f.decoration?.aiSources, chips.indices.contains(i), let page = chips[i].pageId {597 noteDelegate?.noteTextView(self, openPage: page, blockId: chips[i].blockId); return598 }599 }600 let index = characterIndexForInsertion(at: point)601 if index < storage.length {602 if event.clickCount == 2, let (atom, range) = atom(near: index, point: point) { setSelectedRange(range); noteDelegate?.noteTextView(self, activate: atom, at: range); return }603 if event.modifierFlags.contains(.command) || !isEditable, let href = linkTarget(at: point) { noteDelegate?.noteTextView(self, open: href); return }604 if event.clickCount == 1, let (atom, range) = atom(near: index, point: point), !atom.isBlock, atom.node.type == "mention", event.modifierFlags.contains(.command) { noteDelegate?.noteTextView(self, activate: atom, at: range); return }605 }606 super.mouseDown(with: event)607 }608609 private func fragment(at point: CGPoint) -> (BlockLayoutFragment, CGPoint)? {610 guard let lm = textLayoutManager else { return nil }611 let p = CGPoint(x: point.x - textContainerOrigin.x, y: point.y - textContainerOrigin.y)612 guard let f = lm.textLayoutFragment(for: p) as? BlockLayoutFragment else { return nil }613 return (f, CGPoint(x: p.x - f.layoutFragmentFrame.minX, y: p.y - f.layoutFragmentFrame.minY))614 }615 private func location(of fragment: NSTextLayoutFragment) -> Int? {616 guard let cs = contentStorageRef else { return nil }617 return cs.offset(from: cs.documentRange.location, to: fragment.rangeInElement.location)618 }619 private func checkboxHit(at point: CGPoint) -> Int? {620 guard let (f, local) = fragment(at: point), let rect = f.checkboxRect, rect.insetBy(dx: -4, dy: -4).contains(local) else { return nil }621 return location(of: f)622 }623 private func atom(near index: Int, point: CGPoint) -> (AtomAttachment, NSRange)? {624 for i in [index, index - 1] where i >= 0 && i < storage.length {625 if let a = storage.attribute(.attachment, at: i, effectiveRange: nil) as? AtomAttachment { return (a, NSRange(location: i, length: 1)) }626 }627 return nil628 }629 private func linkTarget(at point: CGPoint) -> String? {630 let i = characterIndexForInsertion(at: point)631 for j in [i, i - 1] where j >= 0 && j < storage.length { if let href = (storage.attribute(.spMarks, at: j, effectiveRange: nil) as? MarkSet)?.href { return href } }632 return nil633 }634 /// Range and target of the link around a character.635 public func link(at location: Int) -> (range: NSRange, href: String)? {636 guard location < storage.length, let href = (storage.attribute(.spMarks, at: location, effectiveRange: nil) as? MarkSet)?.href else { return nil }637 var r = NSRange(location: location, length: 1); let content = contentRange(at: location)638 while r.location > content.location, (storage.attribute(.spMarks, at: r.location - 1, effectiveRange: nil) as? MarkSet)?.href == href { r.location -= 1; r.length += 1 }639 while NSMaxRange(r) < NSMaxRange(content), (storage.attribute(.spMarks, at: NSMaxRange(r), effectiveRange: nil) as? MarkSet)?.href == href { r.length += 1 }640 return (r, href)641 }642643 public func toggleCheckbox(at location: Int) {644 guard let it = paraStyle(at: location).item, it.item.type == "taskItem" else { return }645 let on = !(it.item.attrs["checked"]?.bool ?? false)646 // every paragraph of the item carries the container: rewrite them all647 var range = paragraphRange(at: location)648 while range.location > 0, paraStyle(at: range.location - 1).path.contains(where: { $0.key == it.item.key }) { range = NSUnionRange(range, paragraphRange(at: range.location - 1)) }649 while NSMaxRange(range) < storage.length, paraStyle(at: NSMaxRange(range)).path.contains(where: { $0.key == it.item.key }) { range = NSUnionRange(range, paragraphRange(at: NSMaxRange(range))) }650 restyleParagraphs(in: range, actionName: on ? "Cocher" : "Décocher") { s, _ in651 s.with(path: s.path.map { c in guard c.key == it.item.key else { return c }; var c = c; c.attrs["checked"] = .bool(on); return c })652 }653 }654655 // MARK: Keyboard routing while the completion list is open656657 public override func keyDown(with event: NSEvent) {658 if let c = completion {659 switch event.keyCode {660 case 125: c.panel.move(1); return // ↓661 case 126: c.panel.move(-1); return // ↑662 case 53: dismissCompletion(); return // esc663 default: break664 }665 }666 super.keyDown(with: event)667 }668 public override func cancelOperation(_ sender: Any?) { if completion != nil { dismissCompletion() } else { super.cancelOperation(sender) } }669 public override func resignFirstResponder() -> Bool { dismissCompletion(); return super.resignFirstResponder() }670}671672extension NSAttributedString {673 func with(_ key: NSAttributedString.Key, _ value: Any) -> NSAttributedString {674 let m = NSMutableAttributedString(attributedString: self); m.addAttribute(key, value: value, range: NSRange(location: 0, length: m.length)); return m675 }676}677