Repository Public
1// SP Notes iOS2// File: Editor/StructureCommands.swift3// Description: Structural commands (lists, indentation, quotes, callouts) computed on the shared document model, which guarantees a4// result valid for the web schema, then applied to the text storage as new paragraph identities — the text is not touched.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import UIKit9import SPNotesCore1011@MainActor12enum StructureCommands {13 /// Runs `body` on the document read from the storage; returns the new style of every paragraph, or nil when nothing changed or14 /// the command altered the number of lines (not a pure restructuring).15 static func run(in controller: EditorController, _ body: (inout NoteDocument) -> Bool) -> [LineStyle]? {16 var document = AttributedCodec.document(from: controller.storage)17 let count = document.lines.count18 guard count == controller.paragraphRanges().count else { return nil }19 guard body(&document), document.lines.count == count else { return nil }20 document.normalizeContainerKeys()21 document.ensureBlockIds()22 return document.lines.map { line in23 if case .blockAtom(let node) = line.content { return AttributedCodec.style(forBlockAtom: node, path: line.path) }24 return LineStyle(line)25 }26 }2728 static func toggleList(_ kind: ListKind, lines: ClosedRange<Int>, in controller: EditorController) -> [LineStyle]? {29 run(in: controller) { $0.toggleList(kind, at: lines.lowerBound..<(lines.upperBound + 1)) }30 }31 static func indent(lines: ClosedRange<Int>, in controller: EditorController) -> [LineStyle]? {32 run(in: controller) { $0.indentListItems(at: lines.lowerBound..<(lines.upperBound + 1)) }33 }34 static func outdent(lines: ClosedRange<Int>, in controller: EditorController) -> [LineStyle]? {35 run(in: controller) { $0.outdentListItems(at: lines.lowerBound..<(lines.upperBound + 1)) }36 }37 static func toggleBlockquote(lines: ClosedRange<Int>, in controller: EditorController) -> [LineStyle]? {38 run(in: controller) { $0.toggleBlockquote(at: lines.lowerBound..<(lines.upperBound + 1)) }39 }40 static func toggleCallout(kind: String, icon: String, lines: ClosedRange<Int>, in controller: EditorController) -> [LineStyle]? {41 run(in: controller) { $0.toggleCallout(kind: kind, icon: icon, at: lines.lowerBound..<(lines.upperBound + 1)) }42 }4344 /// One step out of the innermost container of the line.45 static func lift(lineAt index: Int, in controller: EditorController) -> [LineStyle]? {46 run(in: controller) { document in47 guard index < document.lines.count, let innermost = document.lines[index].path.last else { return false }48 let range = index..<(index + 1)49 switch innermost.type {50 case "listItem", "taskItem":51 if document.outdentListItems(at: range) { return true }52 guard let kind = document.listKind(at: index) else { return false }53 return document.toggleList(kind, at: range)54 case "blockquote":55 return document.toggleBlockquote(at: range)56 case "callout":57 var kind = "note", icon = "💡"58 if case .string(let k)? = innermost.attrs["kind"] { kind = k }59 if case .string(let i)? = innermost.attrs["icon"] { icon = i }60 return document.toggleCallout(kind: kind, icon: icon, at: range)61 default:62 return false63 }64 }65 }66}6768extension EditorController {69 private var selectedLines: ClosedRange<Int> {70 let range = textView.selectedRange71 let first = lineIndex(at: range.location)72 let last = lineIndex(at: range.length == 0 ? range.location : NSMaxRange(range) - 1)73 return first...max(first, last)74 }7576 func toggleList(_ kind: ListKind) {77 if let styles = StructureCommands.toggleList(kind, lines: selectedLines, in: self) { applyStyles(styles, actionName: String(localized: "Liste")) }78 }79 func toggleBlockquote() {80 if let styles = StructureCommands.toggleBlockquote(lines: selectedLines, in: self) { applyStyles(styles, actionName: String(localized: "Citation")) }81 }82 /// Wraps the selection in a callout (kind `note`, as the web does), or lifts it out of the callout it is in whatever its kind.83 func toggleCallout() {84 if calloutKind() != nil { removeCallout() } else { setCallout(.note) }85 }86 func indent() { _ = handleTab(shift: false) }87 func outdent() { _ = handleTab(shift: true) }8889 /// What the toolbar highlights for the paragraph of the caret.90 struct Context {91 var marks: Set<String> = []92 var blockType = "paragraph"93 var headingLevel: Int?94 var listType: String?95 var inQuote = false96 var inCallout = false97 var isCode = false98 var hasSelection = false99 var link: String?100 var canUndo = false101 var canRedo = false102 // 2.0: what the formatting bar morphs for103 var mode: BlockMode = .text104 var taskDue: String?105 var taskPriority: ItemPriority?106 var calloutKind: CalloutKind?107 var codeLanguage: String?108 /// Type of the block atom the caret is on.109 var atomType: String?110 }111112 /// The block atom of the caret's paragraph, with the range of its character.113 func selectedBlockAtom() -> (node: PMNode, range: NSRange)? {114 guard storage.length > 0 else { return nil }115 let paragraph = paragraphRange(at: textView.selectedRange.location)116 var found: (PMNode, NSRange)?117 storage.enumerateAttribute(.attachment, in: paragraph, options: []) { value, range, stop in118 if let atom = value as? AtomAttachment, atom.isBlock { found = (atom.node, NSRange(location: range.location, length: 1)); stop.pointee = true }119 }120 return found121 }122123 func context() -> Context {124 let s = style(at: paragraphRange(at: textView.selectedRange.location).location)125 var c = Context()126 c.marks = Set(activeMarks().map(\.type))127 c.blockType = s.type128 c.headingLevel = s.headingLevel129 c.listType = s.innermostList?.type130 c.inQuote = s.quoteDepth > 0131 c.inCallout = s.callout != nil132 c.isCode = s.isCode133 c.hasSelection = textView.selectedRange.length > 0134 c.link = linkAtSelection()?.href135 c.canUndo = textView.undoManager?.canUndo ?? false136 c.canRedo = textView.undoManager?.canRedo ?? false137 c.taskDue = s.taskDue138 c.taskPriority = s.taskPriority139 c.calloutKind = s.path.last(where: { $0.type == "callout" }).map { CalloutKind(rawValue: $0.attrs["kind"]?.stringValue ?? "note") }140 c.codeLanguage = s.isCode ? (s.attrs["language"]?.stringValue ?? "plaintext") : nil141 c.atomType = AttributedCodec.isTextual(s) ? nil : s.type142 c.mode = BlockMode(style: s)143 return c144 }145146 /// Plain text of the selection (or of the whole note when nothing is selected), for the assistant.147 func selectedPlainText() -> String {148 let range = textView.selectedRange149 guard range.length > 0 else { return document().plainText() }150 return (storage.string as NSString).substring(with: range)151 .replacingOccurrences(of: EditorCharacter.softBreak, with: "\n").replacingOccurrences(of: EditorCharacter.attachment, with: "")152 }153}154155/// 2.0 — what the caret is in, as far as the formatting bar is concerned (signature motion #2: the bar morphs with it).156enum BlockMode: String, Hashable, CaseIterable {157 case text, list, task, code, callout, atom158159 init(style: LineStyle) {160 if !AttributedCodec.isTextual(style) { self = .atom }161 else if style.isCode { self = .code }162 else if let item = style.innermostItem {163 // the innermost of a list item and a callout decides164 let itemIndex = style.innermostItemIndex ?? 0165 let calloutIndex = style.path.lastIndex(where: { $0.type == "callout" }) ?? -1166 self = calloutIndex > itemIndex ? .callout : (item.type == "taskItem" ? .task : .list)167 }168 else if style.path.contains(where: { $0.type == "callout" }) { self = .callout }169 else { self = .text }170 }171}172