Repository Public
1// SP Notes iOS2// File: Editor/EditorController+Blocks.swift3// Description: 2.0 commands of the editing engine: redrawing block cards when their outside data arrives, cited references,4// scrolling to a block and flashing it, due date and priority of task items, callout kinds, creation of toggles5// (`details`) and footnotes, code-block language, and the block the formatting bar morphs for.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import SPNotesCore10import SPNotesDesign11import UIKit1213extension EditorController {14 // MARK: cards1516 /// Redraws the atoms matching `predicate` (their outside data arrived or changed). Characters and model attributes are untouched.17 func invalidateAtoms(where predicate: (PMNode) -> Bool) {18 guard storage.length > 0 else { return }19 var ranges: [NSRange] = []20 storage.enumerateAttribute(.attachment, in: NSRange(location: 0, length: storage.length)) { value, range, _ in21 if let atom = value as? AtomAttachment, predicate(atom.node) { atom.image = nil; ranges.append(range) }22 }23 guard !ranges.isEmpty else { return }24 isLoading = true25 storage.beginEditing()26 for range in ranges { styler.restyle(storage, range: range); storage.edited(.editedAttributes, range: range, changeInLength: 0) }27 storage.endEditing()28 isLoading = false29 }3031 /// Ids of the references cited in the text, in order, without repetition (what a `bibliography` block lists).32 func citedReferenceIds() -> [String] {33 var out: [String] = []34 guard storage.length > 0 else { return out }35 storage.enumerateAttribute(.attachment, in: NSRange(location: 0, length: storage.length)) { value, _, _ in36 guard let atom = value as? AtomAttachment, !atom.isBlock, let id = CitationInline(node: atom.node)?.refId, !out.contains(id) else { return }37 out.append(id)38 }39 return out40 }4142 /// The first atom of the given type with its range (tests, sheets).43 func firstAtom(ofType type: String) -> (node: PMNode, range: NSRange)? {44 var found: (PMNode, NSRange)?45 storage.enumerateAttribute(.attachment, in: NSRange(location: 0, length: storage.length)) { value, range, stop in46 if let atom = value as? AtomAttachment, atom.node.type == type { found = (atom.node, NSRange(location: range.location, length: 1)); stop.pointee = true }47 }48 return found49 }5051 // MARK: reveal5253 /// The characters of the block whose `id` attribute is `id`: a text block, a block atom, or every paragraph of a container54 /// (list, list item, quote, callout…).55 func rangeOfBlock(id: String) -> NSRange? {56 let wanted = JSONValue.string(id)57 var result: NSRange?58 var containerKey: Int?59 for range in paragraphRanges() {60 let style = style(at: range.location)61 if let key = containerKey {62 if style.path.contains(where: { $0.key == key }), let current = result { result = NSUnionRange(current, range); continue }63 break64 }65 if let frame = style.path.first(where: { $0.attrs["id"] == wanted }) {66 result = range67 containerKey = frame.key68 continue69 }70 if style.attrs["id"] == wanted { return range }71 }72 return result73 }7475 static let flashIdentifier = "block-flash"7677 /// Durations of the flash (seconds): appear, stay, fade. Under Reduce Motion nothing moves or scales: it is there, then a78 /// plain fade of at most 120 ms.79 static func flashTimings(reduceMotion: Bool) -> (appear: Double, hold: Double, fade: Double) {80 reduceMotion ? (0, 0.9, NVMotion.duration(.slow, reduceMotion: true)) : (NVMotion.duration(.fast, reduceMotion: false), 0.7, NVMotion.duration(.ambient, reduceMotion: false))81 }8283 /// Scrolls to the block with this id and flashes it. False when the document has no such block.84 @discardableResult85 func revealBlock(id: String, animated: Bool = true) -> Bool {86 guard let range = rangeOfBlock(id: id) else { return false }87 // TextKit 2 estimates what it has not laid out yet: lay the document out so the block's rectangle is its real one88 if let layout = textView.textLayoutManager { layout.ensureLayout(for: layout.documentRange) }89 textView.layoutIfNeeded()90 let visible = NSRange(location: range.location, length: max(1, range.length - 1))91 guard let start = textView.position(from: textView.beginningOfDocument, offset: visible.location),92 let end = textView.position(from: start, offset: visible.length), let textRange = textView.textRange(from: start, to: end) else { return true }93 var rect = CGRect.null94 for selection in textView.selectionRects(for: textRange) where !selection.rect.isNull && !selection.rect.isInfinite { rect = rect.union(selection.rect) }95 if rect.isNull || rect.isEmpty { rect = textView.firstRect(for: textRange) }96 guard !rect.isNull, !rect.isInfinite else { return true }97 // the whole width of the text column, so a short line is as visible as a card98 let inset = textView.textContainerInset99 rect = CGRect(x: inset.left - 8, y: rect.minY - 4, width: textView.bounds.width - inset.left - inset.right + 16, height: rect.height + 8)100 if textView.isScrollEnabled {101 let target = rect.insetBy(dx: 0, dy: -min(80, max(0, (textView.bounds.height - rect.height) / 3)))102 textView.scrollRectToVisible(target, animated: animated && !UIAccessibility.isReduceMotionEnabled)103 }104 flash(rect)105 return true106 }107108 private func flash(_ rect: CGRect) {109 textView.subviews.filter { $0.accessibilityIdentifier == Self.flashIdentifier }.forEach { $0.removeFromSuperview() }110 let view = UIView(frame: rect)111 view.accessibilityIdentifier = Self.flashIdentifier112 view.isUserInteractionEnabled = false113 view.backgroundColor = NVUIColor.accentSoft114 view.layer.cornerRadius = NVRadius.md115 view.layer.cornerCurve = .continuous116 view.layer.borderWidth = 1117 view.layer.borderColor = NVUIColor.accent.withAlphaComponent(0.35).resolvedColor(with: textView.traitCollection).cgColor118 textView.insertSubview(view, at: 0)119 let reduce = UIAccessibility.isReduceMotionEnabled120 let timings = Self.flashTimings(reduceMotion: reduce)121 if !reduce {122 view.alpha = 0123 view.transform = CGAffineTransform(scaleX: 0.985, y: 0.94)124 UIView.animate(withDuration: timings.appear, delay: 0, options: [.curveEaseOut, .allowUserInteraction]) { view.alpha = 1; view.transform = .identity }125 }126 UIView.animate(withDuration: timings.fade, delay: timings.appear + timings.hold, options: [reduce ? .curveLinear : .curveEaseIn, .allowUserInteraction]) {127 view.alpha = 0128 } completion: { _ in view.removeFromSuperview() }129 }130131 // MARK: task items132133 private var caretLine: Int { lineIndex(at: paragraphRange(at: textView.selectedRange.location).location) }134135 /// Due date (ISO day or date-time; nil clears it) of the task item of the caret.136 func setTaskDue(_ due: String?) {137 let line = caretLine138 if let styles = StructureCommands.run(in: self, { $0.setTaskDue(due, at: line) }) { applyStyles(styles, actionName: String(localized: "Échéance")) }139 }140141 func setTaskPriority(_ priority: ItemPriority?) {142 let line = caretLine143 if let styles = StructureCommands.run(in: self, { $0.setTaskPriority(priority, at: line) }) { applyStyles(styles, actionName: String(localized: "Priorité")) }144 }145146 // MARK: callouts147148 /// The kind of the innermost callout of the caret's paragraph.149 func calloutKind() -> CalloutKind? {150 guard let frame = style(at: paragraphRange(at: textView.selectedRange.location).location).path.last(where: { $0.type == NodeType.callout }) else { return nil }151 return CalloutKind(rawValue: frame.attrs["kind"]?.stringValue ?? "note")152 }153154 private var selectedLineRange: Range<Int> {155 let range = textView.selectedRange156 let first = lineIndex(at: range.location)157 let last = lineIndex(at: range.length == 0 ? range.location : NSMaxRange(range) - 1)158 return first..<(max(first, last) + 1)159 }160161 /// Wraps the selected blocks in a callout of this kind, or re-types the callout they are in (same kind: nothing changes).162 func setCallout(_ kind: CalloutKind) {163 guard calloutKind() != kind else { return }164 let lines = selectedLineRange165 if let styles = StructureCommands.run(in: self, { $0.toggleCallout(kind, at: lines) }) { applyStyles(styles, actionName: String(localized: "Encadré")) }166 }167168 /// Lifts the selected blocks out of their callout.169 func removeCallout() {170 guard let kind = calloutKind() else { return }171 let lines = selectedLineRange172 let icon = style(at: paragraphRange(at: textView.selectedRange.location).location).path.last(where: { $0.type == NodeType.callout })?.attrs["icon"]?.stringValue ?? kind.defaultIcon173 if let styles = StructureCommands.run(in: self, { $0.toggleCallout(kind: kind.rawValue, icon: icon, at: lines) }) { applyStyles(styles, actionName: String(localized: "Encadré")) }174 }175176 // MARK: code177178 /// Language of the code block of the caret.179 func setCodeLanguage(_ language: String) {180 transformParagraphs(in: NSRange(location: textView.selectedRange.location, length: 0), actionName: String(localized: "Langage")) { style, _ in181 guard style.isCode else { return nil }182 var next = style183 next.attrs["language"] = .string(language)184 return next185 }186 }187188 // MARK: toggles (details) and footnotes189190 /// Whether a toggle can be created from the caret's paragraph: a plain paragraph that is not the head of a list item.191 var canInsertDetails: Bool {192 let style = style(at: paragraphRange(at: textView.selectedRange.location).location)193 return AttributedCodec.isTextual(style) && style.type == NodeType.paragraph && style.innermostItem == nil && !style.isInDetails194 }195196 /// Turns the caret's paragraph into the summary of a new open toggle (`details`) with an empty paragraph as content.197 /// The containers come from the Core (`makeContainer`: schema defaults, fresh id); nothing else is needed from the schema.198 @discardableResult199 func insertDetails() -> Bool {200 guard canInsertDetails else { return false }201 let paragraph = paragraphRange(at: textView.selectedRange.location)202 let index = lineIndex(at: paragraph.location)203 var document = AttributedCodec.document(from: storage)204 guard document.lines.indices.contains(index), case .inline(let runs) = document.lines[index].content else { return false }205 let path = document.lines[index].path206 let details = document.makeContainer(NodeType.details, attrs: ["open": .bool(true)])207 let content = document.makeContainer(NodeType.detailsContent)208 let summary = Line(path: path + [details], type: NodeType.detailsSummary, attrs: [:], content: .inline(runs))209 let body = Line.paragraph([], path: path + [details, content])210 // a toggle that would end the document is followed by an empty paragraph, so there is always a way to write after it211 let endsDocument = NSMaxRange(paragraph) >= storage.length212 insertLines([summary, body] + (endsDocument ? [Line.paragraph([], path: path)] : []), replacing: NSRange(location: paragraph.location, length: 0))213 // caret: in the summary when it is empty (to name the toggle), otherwise in the content214 let summaryRange = paragraphRange(at: paragraph.location)215 textView.selectedRange = clampSelection(NSRange(location: runs.isEmpty ? summaryRange.location : NSMaxRange(summaryRange), length: 0))216 refreshTypingAttributes()217 return true218 }219220 /// Return on an empty paragraph that ends the content of a toggle (and is not its only block) moves it out, after the toggle.221 func exitDetails(at paragraph: NSRange) -> Bool {222 let current = style(at: paragraph.location)223 guard current.type == NodeType.paragraph, paragraph.length <= 1, let content = current.path.last, content.type == NodeType.detailsContent,224 let detailsIndex = current.path.lastIndex(where: { $0.type == NodeType.details }), paragraph.location > 0 else { return false }225 let previous = style(at: paragraphRange(at: paragraph.location - 1).location)226 guard previous.path.contains(where: { $0.key == content.key }) else { return false } // not the only block of the content227 let next = NSMaxRange(paragraph)228 if next < storage.length, style(at: next).path.contains(where: { $0.key == current.path[detailsIndex].key }) { return false } // not the last one229 transformParagraphs(in: NSRange(location: paragraph.location, length: 0), actionName: String(localized: "Bloc dépliable")) { style, _ in230 var out = style231 out.path = Array(style.path[..<detailsIndex])232 return out233 }234 return true235 }236237 /// The label the next footnote takes: one more than the highest numeric label in the document.238 func nextFootnoteLabel() -> String {239 var highest = 0240 storage.enumerateAttribute(.attachment, in: NSRange(location: 0, length: storage.length)) { value, _, _ in241 if let atom = value as? AtomAttachment, atom.node.type == NodeType.footnoteRef, let n = Int(atom.node.stringAttr("id") ?? "") { highest = max(highest, n) }242 }243 for range in paragraphRanges() {244 let style = style(at: range.location)245 if style.type == NodeType.footnote, let n = Int(style.attrs["id"]?.stringValue ?? "") { highest = max(highest, n) }246 }247 return String(highest + 1)248 }249250 /// Inserts a footnote reference at the caret and its (empty) footnote at the end of the document, where the caret goes.251 @discardableResult252 func insertFootnote() -> Bool {253 let selection = textView.selectedRange254 let current = style(at: paragraphRange(at: selection.location).location)255 guard AttributedCodec.isTextual(current), !current.isCode, current.type != NodeType.footnote else { return false }256 let label = nextFootnoteLabel()257 insertInlineAtom(PMNode(type: NodeType.footnoteRef, attrs: ["id": .string(label)]))258 let footnote = Line(path: [], type: NodeType.footnote, attrs: ["id": .string(label)], content: .inline([]))259 textView.selectedRange = NSRange(location: max(0, storage.length - 1), length: 0)260 insertLines([footnote])261 textView.selectedRange = clampSelection(NSRange(location: max(0, storage.length - 1), length: 0))262 refreshTypingAttributes()263 return true264 }265266 /// Opens or closes the toggle whose summary is at `location` (the `open` attribute of the `details` node).267 func toggleDetails(at location: Int) {268 guard let frame = style(at: location).path.last(where: { $0.type == NodeType.details }) else { return }269 let open = !(frame.attrs["open"]?.boolValue ?? false)270 let ranges = paragraphRanges().filter { range in style(at: range.location).path.contains { $0.key == frame.key } }271 guard let first = ranges.first, let last = ranges.last else { return }272 let whole = NSRange(location: first.location, length: NSMaxRange(last) - first.location)273 mutateAttributes(in: whole, actionName: String(localized: "Bloc dépliable"), structural: true) { storage in274 for range in ranges {275 var s = self.style(at: range.location)276 s.path = s.path.map { f in277 guard f.key == frame.key else { return f }278 var attrs = f.attrs279 attrs["open"] = .bool(open)280 return Container(key: f.key, type: f.type, attrs: attrs)281 }282 storage.addAttribute(.spnLine, value: LineBox(s), range: range)283 }284 }285 // the caret never stays inside hidden content286 if !open, let summary = ranges.first, textView.selectedRange.location >= NSMaxRange(summary), textView.selectedRange.location < NSMaxRange(whole) {287 textView.selectedRange = NSRange(location: max(summary.location, NSMaxRange(summary) - 1), length: 0)288 }289 Haptics.selection()290 }291}292293extension LineStyle {294 /// The innermost `details` container and whether it is open.295 var details: Container? { path.last(where: { $0.type == NodeType.details }) }296 /// True for a paragraph inside the content of a closed toggle: it is not laid out.297 var isHiddenInClosedDetails: Bool {298 guard type != NodeType.detailsSummary || path.filter({ $0.type == NodeType.details }).count > 1 else { return false }299 // every enclosing toggle but the one this line is the summary of must be open300 let frames = path.enumerated().filter { $0.element.type == NodeType.details }301 for (offset, frame) in frames {302 let isOwnSummary = type == NodeType.detailsSummary && offset == frames.last?.offset303 if !isOwnSummary, frame.attrs["open"]?.boolValue != true { return true }304 }305 return false306 }307 var taskItem: Container? { innermostItem?.type == NodeType.taskItem ? innermostItem : nil }308 var taskDue: String? {309 guard let value = taskItem?.attrs["due"]?.stringValue, !value.isEmpty else { return nil }310 return value311 }312 var taskPriority: ItemPriority? { taskItem?.attrs["priority"]?.stringValue.flatMap(ItemPriority.init(rawValue:)) }313}314