Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Editor/NextCommands.swift3// Description: Editing commands of the 3.0 document format: insertion of the new block atoms and of citations, callout kinds, due date and priority of task items, toggles (details) and footnotes, and navigation to a block by its id (scroll and flash).4import AppKit5import SPNotesDocument6import SPNotesDesign78public extension NoteTextView {9 // MARK: New block atoms (typed builders of SPNotesDocument: schema defaults and a fresh block id)1011 func insertMermaid(_ code: String = "flowchart TD\n A[Idée] --> B{Décision}\n B -->|oui| C[Action]\n B -->|non| D[Abandon]") { insertBlockAtom(MermaidBlock(code: code).node(), actionName: "Diagramme") }12 func insertChart(kind: ChartKind = .bar) { insertBlockAtom(ChartBlock(kind: kind, columns: ["Catégorie", "Valeur"]).node(), actionName: "Graphique") }13 func insertRunCode(language: String = "javascript", code: String = "") { insertBlockAtom(RunCodeBlock(language: language, code: code).node(), actionName: "Code exécutable") }14 func insertQueryView(source: QuerySource = .tasks, title: String = "") { insertBlockAtom(QueryViewBlock(source: source, title: title).node(), actionName: "Vue dynamique") }15 func insertBibliography() { insertBlockAtom(BibliographyBlock().node(), actionName: "Bibliographie") }16 func insertPDF(attachmentId: String, name: String) { insertBlockAtom(PDFBlock(attachmentId: attachmentId, name: name).node(), actionName: "PDF") }17 func insertAudio(attachmentId: String, duration: Double, title: String, recordedAt: Date? = nil) { insertBlockAtom(AudioBlock(attachmentId: attachmentId, duration: duration, title: title, recordedAt: recordedAt).node(), actionName: "Note vocale") }18 func insertDrawing(width: Double = 800, height: Double = 500) { insertBlockAtom(DrawingBlock(width: width, height: height).node(), actionName: "Dessin") }19 func insertBlockRef(pageId: String, blockId: String?, mode: BlockRefMode = .embed) { insertBlockAtom(BlockRefBlock(pageId: pageId, blockId: blockId, mode: mode).node(), actionName: "Référence à un bloc") }20 func insertCanvasLink(pageId: String) { insertBlockAtom(CanvasLinkBlock(pageId: pageId).node(), actionName: "Lien vers un canvas") }21 func insertCitation(refId: String, label: String, locator: String = "") { insertInlineAtom(CitationInline(refId: refId, label: label, locator: locator).node(), actionName: "Citation") }2223 // MARK: Callout kinds2425 /// The callout around the caret, when there is one.26 var currentCallout: (container: Container, kind: CalloutKind)? {27 guard let c = paraStyle(at: selectedRange().location).path.last(where: { $0.type == "callout" }) else { return nil }28 return (c, CalloutKind(rawValue: c.attrs["kind"]?.string ?? "note"))29 }3031 /// Turns the selected paragraphs into a callout of `kind`, or changes the kind of the callout around the caret. The icon32 /// follows the kind unless the owner had chosen another one.33 func setCallout(_ kind: CalloutKind) {34 guard let current = currentCallout else {35 toggleWrapper("callout", attrs: ["kind": .string(kind.rawValue), "icon": .string(kind.defaultIcon)], toggle: false); return36 }37 guard current.kind != kind else { return }38 let key = current.container.key39 var range = paragraphRange(at: selectedRange().location)40 while range.location > 0, paraStyle(at: range.location - 1).path.contains(where: { $0.key == key }) { range = NSUnionRange(range, paragraphRange(at: range.location - 1)) }41 while NSMaxRange(range) < storage.length, paraStyle(at: NSMaxRange(range)).path.contains(where: { $0.key == key }) { range = NSUnionRange(range, paragraphRange(at: NSMaxRange(range))) }42 let icon = current.container.attrs["icon"]?.string43 let keepIcon = icon != nil && icon != current.kind.defaultIcon44 restyleParagraphs(in: range, actionName: "Type d'encadré", perParagraph: true) { s, _ in45 s.with(path: s.path.map { c in guard c.key == key else { return c }; var c = c; c.attrs["kind"] = .string(kind.rawValue); if !keepIcon { c.attrs["icon"] = .string(kind.defaultIcon) }; return c })46 }47 }4849 // MARK: Task items (3.0: due date, priority)5051 struct TaskItemState: Equatable, Sendable { public var due: String?; public var priority: TaskPriority?; public var checked: Bool; public var taskId: String? }5253 /// The task item that holds the paragraph at `location`.54 func taskItem(at location: Int) -> TaskItemState? {55 guard let it = paraStyle(at: location).item, it.item.type == "taskItem" else { return nil }56 let a = it.item.attrs57 return TaskItemState(due: a["due"]?.string.flatMap { $0.isEmpty ? nil : $0 }, priority: a["priority"]?.string.flatMap(TaskPriority.init(rawValue:)), checked: a["checked"]?.bool ?? false, taskId: a["taskId"]?.string)58 }5960 /// Sets the due date (`YYYY-MM-DD`, nil clears it) and the priority of the task item at `location`. One undo step.61 func setTaskAttributes(at location: Int, due: String?, priority: TaskPriority?) {62 guard let it = paraStyle(at: location).item, it.item.type == "taskItem" else { return }63 let key = it.item.key64 var range = paragraphRange(at: location)65 while range.location > 0, paraStyle(at: range.location - 1).path.contains(where: { $0.key == key }) { range = NSUnionRange(range, paragraphRange(at: range.location - 1)) }66 while NSMaxRange(range) < storage.length, paraStyle(at: NSMaxRange(range)).path.contains(where: { $0.key == key }) { range = NSUnionRange(range, paragraphRange(at: NSMaxRange(range))) }67 restyleParagraphs(in: range, actionName: "Échéance et priorité", perParagraph: true) { s, _ in68 s.with(path: s.path.map { c in guard c.key == key else { return c }; var c = c; c.attrs["due"] = due.map(JSONValue.string) ?? .null; c.attrs["priority"] = priority.map { .string($0.rawValue) } ?? .null; return c })69 }70 }7172 /// Asks the owner (popover) for the due date and priority of the task item at the caret.73 func requestTaskDetails() {74 let loc = selectedRange().location75 guard taskItem(at: loc) != nil else { return }76 noteDelegate?.noteTextView(self, editTaskAt: loc, anchor: blockFrame(for: paragraphRange(at: loc)) ?? .zero)77 }7879 // MARK: Toggles and footnotes8081 /// Wraps the paragraph at the caret in a collapsible section: its text becomes the summary, an empty paragraph opens inside.82 func insertDetails() {83 let caret = selectedRange().location; let style = paraStyle(at: caret); let pr = paragraphRange(at: caret)84 guard !style.isAtom, !style.isCode, style.type != "detailsSummary", !style.path.contains(where: { $0.type == "details" }) else { return }85 let details = newContainer("details", attrs: ["open": .bool(true)])86 let content = newContainer("detailsContent")87 let summaryStyle = ParaStyle(path: style.path + [details], type: "detailsSummary", attrs: [:])88 let text = NSMutableAttributedString(attributedString: storage.attributedSubstring(from: pr))89 if contentRange(at: caret).length == 0 { text.insert(NSAttributedString(string: "Détails", attributes: [.spMarks: MarkSet.none]), at: 0) }90 // a summary holds text only: inline atoms of the paragraph stay in the body91 let body = NSMutableAttributedString()92 text.enumerateAttribute(.attachment, in: NSRange(location: 0, length: text.length), options: .reverse) { v, r, _ in if v != nil { text.deleteCharacters(in: r) } }93 text.addAttribute(.spPara, value: summaryStyle, range: NSRange(location: 0, length: text.length))94 body.append(text); body.append(paragraph(style: newParagraphStyle(path: style.path + [details, content])))95 replace(pr, with: body, select: NSRange(location: pr.location + body.length - 1, length: 0), actionName: "Section repliable")96 }9798 /// Inserts a numbered footnote reference at the caret and its footnote at the end of the note (the web editor's rule:99 /// the number is one more than the footnotes that exist).100 func insertFootnote() {101 let sel = selectedRange(); let style = paraStyle(at: sel.location)102 guard !style.isAtom, !style.isCode, style.type != "detailsSummary" else { return }103 let existing = DocumentCodec.document(from: storage).lines.filter { $0.type == "footnote" && $0.path.isEmpty }.count104 let n = String(existing + 1)105 undoManager?.beginUndoGrouping(); defer { undoManager?.endUndoGrouping() }106 insertInlineAtom(PMNode(type: "footnoteRef", attrs: ["id": .string(n)]), actionName: "Note de bas de page")107 let caret = selectedRange()108 let note = NSMutableAttributedString(string: "Note \(n)\n", attributes: [.spPara: ParaStyle(path: [], type: "footnote", attrs: ["id": .string(n)]), .spMarks: MarkSet.none])109 let end = storage.length110 replace(NSRange(location: end, length: 0), with: note, select: caret, actionName: "Note de bas de page")111 }112113 // MARK: Blocks by id (routes carry a page and a block)114115 /// Character range of the block whose id is `id`: a text block, a block atom, or the first paragraph of a container116 /// (list, list item, quote, callout, AI block) that carries it.117 func rangeOfBlock(id: String) -> NSRange? {118 guard !id.isEmpty else { return nil }119 let ns = storage.string as NSString; var loc = 0120 while loc < ns.length {121 let pr = ns.paragraphRange(for: NSRange(location: loc, length: 0)); let style = paraStyle(at: pr.location)122 if style.blockID == id || style.path.contains(where: { $0.attrs["id"]?.string == id }) { return style.isCode ? codeBlockRange(at: pr.location) : pr }123 loc = NSMaxRange(pr)124 }125 return nil126 }127128 /// Frame, in the view's coordinates, of the layout fragments of a character range.129 func blockFrame(for range: NSRange) -> CGRect? {130 guard let lm = textLayoutManager, let cm = lm.textContentManager, let start = cm.location(cm.documentRange.location, offsetBy: range.location),131 let end = cm.location(start, offsetBy: max(1, range.length)), let tr = NSTextRange(location: start, end: end) else { return nil }132 lm.ensureLayout(for: tr)133 var frame = CGRect.null134 lm.enumerateTextLayoutFragments(from: start, options: [.ensuresLayout]) { f in135 guard let fr = f.textElement?.elementRange, fr.location.compare(tr.endLocation) == .orderedAscending else { return false }136 frame = frame.union(f.layoutFragmentFrame); return true137 }138 guard !frame.isNull else { return nil }139 return CGRect(x: textContainerOrigin.x, y: frame.minY + textContainerOrigin.y, width: (textContainer?.size.width ?? bounds.width), height: frame.height)140 }141142 /// Scrolls to a block and flashes it. False when the block is not in this document (the caller says so, it never fails silently).143 @discardableResult func scrollToBlock(id: String, flash: Bool = true, reduceMotion: Bool = NSWorkspace.shared.accessibilityDisplayShouldReduceMotion) -> Bool {144 guard let range = rangeOfBlock(id: id) else { return false }145 setSelectedRange(NSRange(location: range.location, length: 0))146 guard let frame = blockFrame(for: range) else { scrollRangeToVisible(range); return true }147 if let clip = enclosingScrollView?.contentView {148 // the block is placed a third down the window, not glued to its top edge149 let y = max(0, min(frame.minY - clip.bounds.height / 3, max(0, bounds.height - clip.bounds.height)))150 if reduceMotion { clip.setBoundsOrigin(CGPoint(x: clip.bounds.origin.x, y: y)) }151 else { NSAnimationContext.runAnimationGroup { ctx in ctx.duration = NVMotion.Token.base.duration; ctx.allowsImplicitAnimation = true; clip.animator().setBoundsOrigin(CGPoint(x: clip.bounds.origin.x, y: y)) } }152 enclosingScrollView?.reflectScrolledClipView(clip)153 } else { scrollRangeToVisible(range) }154 if flash { flashBlock(frame, reduceMotion: reduceMotion) }155 return true156 }157158 /// A soft accent wash over a block that fades out: where the link, the citation or the search result landed.159 internal func flashBlock(_ frame: CGRect, reduceMotion: Bool) {160 wantsLayer = true161 guard let host = layer else { return }162 host.sublayers?.filter { $0.name == "sp.flash" }.forEach { $0.removeFromSuperlayer() }163 let l = CALayer(); l.name = "sp.flash"164 l.frame = frame.insetBy(dx: -NVSpace.sm, dy: -NVSpace.xxs); l.cornerRadius = NVRadius.sm165 effectiveAppearance.performAsCurrentDrawingAppearance { l.backgroundColor = EditorTheme.flash.cgColor }166 l.zPosition = -1167 host.addSublayer(l)168 let fade = CABasicAnimation(keyPath: "opacity"); fade.fromValue = 1; fade.toValue = 0169 fade.beginTime = CACurrentMediaTime() + 0.9; fade.duration = reduceMotion ? NVMotion.reducedMaxDuration : NVMotion.Token.slow.duration170 fade.fillMode = .both; fade.isRemovedOnCompletion = false171 l.add(fade, forKey: "fade")172 Task { @MainActor [weak l] in try? await Task.sleep(for: .milliseconds(1500)); l?.removeFromSuperlayer() }173 }174175 // MARK: Living Pages (signature motion 1)176177 /// What the opening animation of a note does: the first blocks rise 6 pt and fade in one after the other (18 ms apart,178 /// 24 blocks at most); under Reduce Motion, one cross-fade of 120 ms at most, nothing moves.179 struct RevealPlan: Equatable, Sendable { public var blocks: Int; public var staggered: Bool; public var rise: CGFloat; public var duration: Double; public var lastDelay: Double }180181 static func revealPlan(blockCount: Int, reduceMotion: Bool) -> RevealPlan {182 let n = min(max(0, blockCount), NVMotion.staggerCap)183 if reduceMotion { return RevealPlan(blocks: n, staggered: false, rise: 0, duration: NVMotion.duration(.base, reduceMotion: true), lastDelay: 0) }184 return RevealPlan(blocks: n, staggered: n > 1, rise: NVMotion.revealRise, duration: NVMotion.Token.base.duration, lastDelay: NVMotion.staggerDelay(index: max(0, n - 1), reduceMotion: false))185 }186187 /// Plays the opening animation over the blocks that are on screen. Each block is uncovered by its own layer, so the188 /// text itself is never moved or re-laid out, and typing can start at once.189 @discardableResult func playReveal(reduceMotion: Bool = NSWorkspace.shared.accessibilityDisplayShouldReduceMotion) -> RevealPlan {190 guard let lm = textLayoutManager else { return Self.revealPlan(blockCount: 0, reduceMotion: reduceMotion) }191 var frames: [CGRect] = []192 let visible = enclosingScrollView?.documentVisibleRect ?? bounds193 lm.enumerateTextLayoutFragments(from: lm.documentRange.location, options: [.ensuresLayout]) { f in194 let r = f.layoutFragmentFrame.offsetBy(dx: 0, dy: self.textContainerOrigin.y)195 if r.minY > visible.maxY { return false }196 frames.append(CGRect(x: 0, y: r.minY, width: self.bounds.width, height: r.height))197 return frames.count < NVMotion.staggerCap198 }199 let plan = Self.revealPlan(blockCount: frames.count, reduceMotion: reduceMotion)200 guard plan.blocks > 0 else { return plan }201 wantsLayer = true202 guard let host = layer else { return plan }203 host.sublayers?.filter { $0.name == "sp.reveal" }.forEach { $0.removeFromSuperlayer() }204 var cover = CGColor(gray: 1, alpha: 1)205 effectiveAppearance.performAsCurrentDrawingAppearance { cover = EditorTheme.background.cgColor }206 let now = CACurrentMediaTime()207 let timing = CAMediaTimingFunction(controlPoints: Float(NVMotion.Curve.standard.x1), Float(NVMotion.Curve.standard.y1), Float(NVMotion.Curve.standard.x2), Float(NVMotion.Curve.standard.y2))208 for (i, frame) in frames.enumerated() {209 let l = CALayer(); l.name = "sp.reveal"; l.frame = frame; l.backgroundColor = cover; l.zPosition = 10210 host.addSublayer(l)211 let delay = plan.staggered ? NVMotion.staggerDelay(index: i, reduceMotion: false) : 0212 let fade = CABasicAnimation(keyPath: "opacity"); fade.fromValue = 1; fade.toValue = 0213 fade.beginTime = now + delay; fade.duration = plan.duration; fade.timingFunction = reduceMotion ? CAMediaTimingFunction(name: .linear) : timing214 fade.fillMode = .both; fade.isRemovedOnCompletion = false215 l.add(fade, forKey: "fade")216 }217 if plan.rise > 0 {218 let rise = CABasicAnimation(keyPath: "sublayerTransform.translation.y"); rise.fromValue = isFlipped ? plan.rise : -plan.rise; rise.toValue = 0219 rise.duration = plan.duration + plan.lastDelay; rise.timingFunction = timing220 host.add(rise, forKey: "sp.rise")221 }222 let total = plan.duration + plan.lastDelay + 0.05223 Task { @MainActor [weak host] in try? await Task.sleep(for: .milliseconds(Int(total * 1000))); host?.sublayers?.filter { $0.name == "sp.reveal" }.forEach { $0.removeFromSuperlayer() } }224 return plan225 }226}227