Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Editor/Completion.swift3// Description: The « / » block menu and the « @ » note-link menu: a floating native list anchored at the caret, filtered as the user types, driven from the text view's keyboard.4import AppKit5import SPNotesDocument67@MainActor final class CompletionSession {8 let trigger: Character9 /// Location of the trigger character in the storage.10 let start: Int11 let panel: CompletionPanel12 init(trigger: Character, start: Int, panel: CompletionPanel) { self.trigger = trigger; self.start = start; self.panel = panel }13}1415extension NoteTextView {16 /// Built-in block menu; the application appends its own entries (image, file, assistant) through the delegate.17 public static func builtinSlashItems() -> [CompletionItem] {18 func item(_ id: String, _ title: String, _ subtitle: String?, _ symbol: String, _ group: String, _ action: @escaping @MainActor (NoteTextView) -> Void) -> CompletionItem { CompletionItem(id: id, title: title, subtitle: subtitle, symbol: symbol, group: group, action: action) }19 return [20 item("text", "Texte", "Paragraphe simple", "textformat", "Base") { $0.setBlock(.paragraph) },21 item("h1", "Titre 1", "Grand titre de section", "1.square", "Base") { $0.setBlock(.heading(1), toggle: false) },22 item("h2", "Titre 2", nil, "2.square", "Base") { $0.setBlock(.heading(2), toggle: false) },23 item("h3", "Titre 3", nil, "3.square", "Base") { $0.setBlock(.heading(3), toggle: false) },24 item("bullet", "Liste à puces", nil, "list.bullet", "Base") { $0.setBlock(.bullet, toggle: false) },25 item("ordered", "Liste numérotée", nil, "list.number", "Base") { $0.setBlock(.ordered(start: 1), toggle: false) },26 item("todo", "Liste de tâches", "Cases à cocher", "checklist", "Base") { $0.setBlock(.task, toggle: false) },27 item("quote", "Citation", nil, "text.quote", "Base") { $0.setBlock(.quote, toggle: false) },28 item("callout", "Encadré", "Note mise en évidence", "lightbulb", "Base") { $0.setBlock(.callout, toggle: false) },29 item("divider", "Séparateur", nil, "minus", "Base") { $0.insertRule() },30 item("code", "Bloc de code", "Coloration syntaxique", "chevron.left.forwardslash.chevron.right", "Avancé") { $0.setBlock(.code, toggle: false) },31 item("table", "Tableau", "3 × 3 avec en-tête", "tablecells", "Avancé") { $0.insertTable() },32 item("math", "Équation", "Bloc LaTeX", "sum", "Avancé") { v in v.insertBlockMath("E = mc^2"); v.activateAtomBeforeCaret() },33 item("imath", "Équation en ligne", nil, "x.squareroot", "Avancé") { v in v.insertInlineMath("x^2"); v.activateAtomBeforeCaret() },34 item("toggle", "Section repliable", "Titre et contenu repliable", "chevron.right.square", "Avancé") { $0.insertDetails() },35 item("footnote", "Note de bas de page", "Appel numéroté et note en fin de page", "textformat.superscript", "Avancé") { $0.insertFootnote() },36 item("decision", "Décision", "Encadré ⚖️ — journalisée dans la chronologie", "checkmark.seal", "Encadrés") { $0.setCallout(.decision) },37 item("question", "Question ouverte", "Encadré ❓", "questionmark.circle", "Encadrés") { $0.setCallout(.question) },38 item("hypothesis", "Hypothèse", "Encadré 🧪", "flask", "Encadrés") { $0.setCallout(.hypothesis) },39 item("warning", "Avertissement", "Encadré ⚠️", "exclamationmark.triangle", "Encadrés") { $0.setCallout(.warning) },40 item("mermaid", "Diagramme Mermaid", "Organigramme, séquence, Gantt…", "point.3.connected.trianglepath.dotted", "Blocs 3.0") { v in v.insertMermaid(); v.activateAtomBeforeCaret() },41 item("chart", "Graphique", "Barres, courbes, aires, secteurs, nuage", "chart.bar.xaxis", "Blocs 3.0") { v in v.insertChart(); v.activateAtomBeforeCaret() },42 item("runcode", "Code exécutable", "Code et dernière sortie (exécution sur le Web)", "play.rectangle", "Blocs 3.0") { v in v.insertRunCode(); v.activateAtomBeforeCaret() },43 item("query", "Vue dynamique", "Tâches, notes ou base, toujours à jour", "rectangle.stack.badge.play", "Blocs 3.0") { v in v.insertQueryView(); v.activateAtomBeforeCaret() },44 item("bibliography", "Bibliographie", "Références citées dans la note", "books.vertical", "Blocs 3.0") { $0.insertBibliography() },45 item("drawing", "Dessin", "Zone de dessin (encre sur iPad ou sur le Web)", "scribble.variable", "Blocs 3.0") { $0.insertDrawing() },46 ]47 }4849 /// Opens the editor of the atom that was just inserted (equation, table).50 func activateAtomBeforeCaret() {51 let loc = selectedRange().location52 for i in [loc - 1, loc - 2, loc] where i >= 0 && i < storage.length {53 if let a = storage.attribute(.attachment, at: i, effectiveRange: nil) as? AtomAttachment { noteDelegate?.noteTextView(self, activate: a, at: NSRange(location: i, length: 1)); return }54 }55 }5657 func beginCompletion(trigger: Character) {58 let caret = selectedRange().location59 guard caret > 0, !paraStyle(at: caret).isCode, !paraStyle(at: caret).isAtom else { return }60 let start = caret - 1; let content = contentRange(at: caret)61 // only at the start of a block or after a space: « a/b » and e-mail addresses stay plain text62 if start > content.location { let before = (storage.string as NSString).character(at: start - 1); guard before == 0x20 || before == 0xA0 || before == 0x2028 else { return } }63 let panel = CompletionPanel()64 panel.onPick = { [weak self] item in self?.commitCompletion(item) }65 completion = CompletionSession(trigger: trigger, start: start, panel: panel)66 updateCompletion()67 }6869 private func completionQuery() -> String? {70 guard let c = completion else { return nil }71 let caret = selectedRange().location72 guard selectedRange().length == 0, caret > c.start, c.start < storage.length, (storage.string as NSString).substring(with: NSRange(location: c.start, length: 1)) == String(c.trigger) else { return nil }73 let q = (storage.string as NSString).substring(with: NSRange(location: c.start + 1, length: caret - c.start - 1))74 if q.contains("\n") || q.count > 40 || (c.trigger == "/" && q.contains(" ")) { return nil }75 return q76 }7778 func updateCompletion() {79 guard let c = completion else { return }80 guard let q = completionQuery() else { dismissCompletion(); return }81 var items: [CompletionItem] = []82 if c.trigger == "/" { items = Self.builtinSlashItems() }83 items += noteDelegate?.noteTextView(self, completionsFor: c.trigger, query: q) ?? []84 if c.trigger == "/" {85 let needle = q.folding(options: [.diacriticInsensitive, .caseInsensitive], locale: nil)86 if !needle.isEmpty { items = items.filter { ($0.title + " " + $0.id + " " + ($0.subtitle ?? "")).folding(options: [.diacriticInsensitive, .caseInsensitive], locale: nil).contains(needle) } }87 }88 if items.isEmpty { if q.count > 12 || c.trigger == "/" && q.count > 0 { dismissCompletion() } else { c.panel.orderOut(nil) }; return }89 c.panel.show(items: Array(items.prefix(40)), at: caretScreenRect(at: c.start), parent: window)90 }9192 private func caretScreenRect(at location: Int) -> CGRect {93 var actual = NSRange()94 let r = firstRect(forCharacterRange: NSRange(location: location, length: 1), actualRange: &actual)95 return r96 }9798 /// Applies the highlighted entry. False when there is nothing to apply (the key then keeps its normal meaning).99 @discardableResult func commitCompletion(_ picked: CompletionItem? = nil) -> Bool {100 guard let c = completion, c.panel.isVisible || picked != nil, let item = picked ?? c.panel.selected else { dismissCompletion(); return false }101 let caret = selectedRange().location102 dismissCompletion()103 undoManager?.beginUndoGrouping()104 if caret >= c.start { replace(NSRange(location: c.start, length: caret - c.start), with: NSAttributedString(), select: NSRange(location: c.start, length: 0), actionName: item.title) }105 item.action(self)106 undoManager?.endUndoGrouping()107 return true108 }109110 func dismissCompletion() { completion?.panel.close(); completion = nil }111}112113/// Borderless floating list. Never becomes key: the text view keeps the keyboard.114@MainActor final class CompletionPanel: NSPanel {115 private let stack = NSStackView()116 private let scroll = NSScrollView()117 private var items: [CompletionItem] = []118 private var rows: [CompletionRow] = []119 private var index = 0120 var onPick: ((CompletionItem) -> Void)?121 var selected: CompletionItem? { items.indices.contains(index) ? items[index] : nil }122123 init() {124 super.init(contentRect: CGRect(x: 0, y: 0, width: 300, height: 200), styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: true)125 isOpaque = false; backgroundColor = .clear; hasShadow = true; level = .popUpMenu; isReleasedWhenClosed = false; hidesOnDeactivate = true126 let effect = NSVisualEffectView(); effect.material = .menu; effect.state = .active; effect.blendingMode = .behindWindow127 effect.wantsLayer = true; effect.layer?.cornerRadius = 9; effect.layer?.masksToBounds = true128 stack.orientation = .vertical; stack.alignment = .leading; stack.spacing = 0; stack.edgeInsets = NSEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)129 stack.translatesAutoresizingMaskIntoConstraints = false130 let doc = FlippedView(); doc.translatesAutoresizingMaskIntoConstraints = false; doc.addSubview(stack)131 scroll.documentView = doc; scroll.drawsBackground = false; scroll.hasVerticalScroller = true; scroll.autohidesScrollers = true; scroll.translatesAutoresizingMaskIntoConstraints = false132 effect.addSubview(scroll)133 NSLayoutConstraint.activate([134 scroll.leadingAnchor.constraint(equalTo: effect.leadingAnchor), scroll.trailingAnchor.constraint(equalTo: effect.trailingAnchor), scroll.topAnchor.constraint(equalTo: effect.topAnchor), scroll.bottomAnchor.constraint(equalTo: effect.bottomAnchor),135 stack.leadingAnchor.constraint(equalTo: doc.leadingAnchor), stack.trailingAnchor.constraint(equalTo: doc.trailingAnchor), stack.topAnchor.constraint(equalTo: doc.topAnchor), stack.bottomAnchor.constraint(equalTo: doc.bottomAnchor),136 doc.widthAnchor.constraint(equalTo: scroll.widthAnchor),137 ])138 contentView = effect139 setAccessibilityRole(.list)140 }141 override var canBecomeKey: Bool { false }142 override var canBecomeMain: Bool { false }143144 func show(items new: [CompletionItem], at anchor: CGRect, parent: NSWindow?) {145 let keep = selected?.id146 items = new147 rows.forEach { $0.removeFromSuperview() }; stack.arrangedSubviews.forEach { $0.removeFromSuperview() }; rows = []148 var lastGroup: String?149 for (i, item) in items.enumerated() {150 if let g = item.group, g != lastGroup {151 let label = NSTextField(labelWithString: g.uppercased()); label.font = .systemFont(ofSize: 10, weight: .semibold); label.textColor = .tertiaryLabelColor152 let box = NSView(); box.translatesAutoresizingMaskIntoConstraints = false; label.translatesAutoresizingMaskIntoConstraints = false; box.addSubview(label)153 NSLayoutConstraint.activate([label.leadingAnchor.constraint(equalTo: box.leadingAnchor, constant: 8), label.topAnchor.constraint(equalTo: box.topAnchor, constant: i == 0 ? 3 : 8), label.bottomAnchor.constraint(equalTo: box.bottomAnchor, constant: -3), box.widthAnchor.constraint(equalToConstant: 290)])154 stack.addArrangedSubview(box); lastGroup = g155 }156 let row = CompletionRow(item: item) { [weak self] in self?.onPick?(item) }157 stack.addArrangedSubview(row); rows.append(row)158 }159 index = keep.flatMap { k in items.firstIndex { $0.id == k } } ?? 0160 highlight()161 stack.layoutSubtreeIfNeeded()162 let height = min(340, stack.fittingSize.height)163 var origin = CGPoint(x: anchor.minX - 8, y: anchor.minY - height - 6)164 if let screen = parent?.screen ?? NSScreen.main {165 if origin.y < screen.visibleFrame.minY + 8 { origin.y = anchor.maxY + 6 }166 origin.x = min(max(screen.visibleFrame.minX + 8, origin.x), screen.visibleFrame.maxX - 308)167 }168 setFrame(CGRect(x: origin.x, y: origin.y, width: 300, height: height), display: true)169 if !isVisible { parent?.addChildWindow(self, ordered: .above) }170 orderFront(nil)171 }172173 func move(_ delta: Int) {174 guard !items.isEmpty else { return }175 index = (index + delta + items.count) % items.count176 highlight()177 if rows.indices.contains(index) { rows[index].scrollToVisible(rows[index].bounds) }178 }179 private func highlight() { for (i, r) in rows.enumerated() { r.isHighlighted = i == index } }180 override func close() { parent?.removeChildWindow(self); super.close() }181}182183private final class FlippedView: NSView { override var isFlipped: Bool { true } }184185@MainActor private final class CompletionRow: NSView {186 private let pick: () -> Void187 var isHighlighted = false { didSet { needsDisplay = true; title.textColor = isHighlighted ? .white : .labelColor; subtitle.textColor = isHighlighted ? NSColor.white.withAlphaComponent(0.8) : .secondaryLabelColor; icon.contentTintColor = isHighlighted ? .white : .secondaryLabelColor } }188 private let title = NSTextField(labelWithString: "")189 private let subtitle = NSTextField(labelWithString: "")190 private let icon = NSImageView()191192 init(item: CompletionItem, pick: @escaping () -> Void) {193 self.pick = pick194 super.init(frame: .zero)195 translatesAutoresizingMaskIntoConstraints = false196 title.stringValue = item.title; title.font = .systemFont(ofSize: 13); title.lineBreakMode = .byTruncatingTail197 subtitle.stringValue = item.subtitle ?? ""; subtitle.font = .systemFont(ofSize: 11); subtitle.textColor = .secondaryLabelColor; subtitle.lineBreakMode = .byTruncatingTail198 icon.image = item.symbol.flatMap { NSImage(systemSymbolName: $0, accessibilityDescription: nil) }; icon.contentTintColor = .secondaryLabelColor; icon.symbolConfiguration = .init(pointSize: 13, weight: .regular)199 for v in [title, subtitle, icon] as [NSView] { v.translatesAutoresizingMaskIntoConstraints = false; addSubview(v) }200 let hasSub = !(item.subtitle ?? "").isEmpty201 NSLayoutConstraint.activate([202 widthAnchor.constraint(equalToConstant: 290), heightAnchor.constraint(equalToConstant: hasSub ? 40 : 28),203 icon.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 9), icon.centerYAnchor.constraint(equalTo: centerYAnchor), icon.widthAnchor.constraint(equalToConstant: 20),204 title.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 36), title.trailingAnchor.constraint(lessThanOrEqualTo: trailingAnchor, constant: -8),205 hasSub ? title.topAnchor.constraint(equalTo: topAnchor, constant: 4) : title.centerYAnchor.constraint(equalTo: centerYAnchor),206 subtitle.leadingAnchor.constraint(equalTo: title.leadingAnchor), subtitle.trailingAnchor.constraint(lessThanOrEqualTo: trailingAnchor, constant: -8), subtitle.topAnchor.constraint(equalTo: title.bottomAnchor, constant: 0),207 ])208 subtitle.isHidden = !hasSub209 setAccessibilityRole(.menuItem); setAccessibilityLabel(item.title)210 }211 required init?(coder: NSCoder) { fatalError() }212 override func draw(_ dirtyRect: NSRect) {213 if isHighlighted { NSColor.controlAccentColor.setFill(); NSBezierPath(roundedRect: bounds, xRadius: 5, yRadius: 5).fill() }214 }215 override func mouseDown(with event: NSEvent) { pick() }216 override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true }217}218219public extension NoteTextView {220 /// The application's completion results changed (asynchronous note search): rebuild the open list.221 func refreshCompletion() { updateCompletion() }222}223224/// Typeset formulas for the application's equation editor (same renderer as the document).225@MainActor public enum EditorImages {226 public static func math(_ latex: String, fontSize: CGFloat, display: Bool) -> NSImage? { MathRenderer.render(latex, fontSize: fontSize, display: display)?.image }227}228