Sources/OrgstarMobile/MobileEditor+Snippets.swift
141 lines · 5718 bytes
1#if os(iOS)
2import OrgCore
3import UIKit
4
5/// Snippets, as on the Mac: TAB on a hardware keyboard after a trigger where TAB means nothing
6/// else expands it, then TAB and S-TAB (or `org.snippet.next-field` and
7/// `org.snippet.previous-field`) move between its fields. Leaving the last field, Escape, or
8/// the caret or an edit leaving the snippet ends it.
9extension MobileEditor {
10 /// TAB with no binding that runs here: expands the trigger before the caret, if any.
11 func snippetTab(_ chord: KeyChord) -> Bool {
12 guard chord == KeyChord("TAB"), textView.markedTextRange == nil else { return false }
13 let expand = ExpandSnippet()
14 guard expand.applies(in: editContext()) else { return false }
15 _ = perform(expand)
16 return true
17 }
18
19 /// Keys while a snippet's fields are filled in; nil lets the key through.
20 func snippetKey(_ chord: KeyChord) -> Bool? {
21 guard snippetSession != nil else { return nil }
22 switch chord {
23 case KeyChord("TAB"):
24 nextSnippetField()
25 return true
26 case KeyChord("TAB", .shift):
27 previousSnippetField()
28 return true
29 case KeyChord("ESC"):
30 endSnippet()
31 return modal ? nil : true
32 default:
33 return nil
34 }
35 }
36
37 func nextSnippetField() {
38 guard var session = snippetSession else { return }
39 switch session.next() {
40 case .field(let range):
41 snippetSession = session
42 selectSnippet(range)
43 case .exit(let range):
44 endSnippet()
45 selectSnippet(range)
46 }
47 }
48
49 func previousSnippetField() {
50 guard var session = snippetSession else { return }
51 let range = session.previous()
52 snippetSession = session
53 selectSnippet(range)
54 }
55
56 func startSnippet(_ session: SnippetSession) {
57 snippetSession = session
58 highlightSnippet()
59 }
60
61 func endSnippet() {
62 snippetSession = nil
63 highlightSnippet()
64 }
65
66 private func selectSnippet(_ range: Range<Int>) {
67 unfold(around: range.lowerBound)
68 textView.selectedRange = NSRange(range)
69 textView.scrollRangeToVisible(textView.selectedRange)
70 highlightSnippet()
71 }
72
73 /// An edit of the buffer; one outside the snippet ends it.
74 func snippetEdited(_ edit: TextEdit) {
75 guard var session = snippetSession else { return }
76 snippetSession = session.map(edit) ? session : nil
77 }
78
79 /// After typing: mirrors take their field's new text.
80 func updateSnippetMirrors() {
81 guard let session = snippetSession, !updatingMirrors, textView.markedTextRange == nil else { return highlightSnippet() }
82 let edits = session.mirrorEdits(in: document.text)
83 if !edits.isEmpty {
84 updatingMirrors = true
85 let selected = textView.selectedRange
86 applyEdits(edits)
87 updatingMirrors = false
88 let shift = edits.filter { $0.range.upperBound <= selected.location }.reduce(0) { $0 + $1.replacement.utf16.count - $1.range.count }
89 textView.selectedRange = NSRange(location: selected.location + shift, length: selected.length)
90 }
91 highlightSnippet()
92 }
93
94 /// The caret moved: outside the snippet, it ends.
95 func snippetSelectionChanged() {
96 guard let session = snippetSession, !updatingMirrors else { return }
97 let selected = textView.selectedRange
98 if !session.contains(selected.location) || !session.contains(NSMaxRange(selected)) { endSnippet() }
99 }
100
101 /// Draws the active field with a band and the others with a fainter one.
102 func highlightSnippet() {
103 let length = (textView.textStorage.string as NSString).length
104 var covered = snippetHighlight.flatMap { $0.upperBound <= length ? $0 : $0.lowerBound < length ? $0.lowerBound..<length : nil }
105 if let extent = snippetSession?.extent, extent.upperBound <= length {
106 covered = covered.map { min($0.lowerBound, extent.lowerBound)..<max($0.upperBound, extent.upperBound) } ?? extent
107 }
108 for manager in layoutManagers {
109 func textRange(_ r: Range<Int>) -> NSTextRange? {
110 guard let content = manager.textContentManager,
111 let start = content.location(content.documentRange.location, offsetBy: r.lowerBound),
112 let end = content.location(start, offsetBy: r.count) else { return nil }
113 return NSTextRange(location: start, end: end)
114 }
115 if let covered, let range = textRange(covered) {
116 manager.removeRenderingAttribute(.backgroundColor, for: range)
117 }
118 guard let session = snippetSession else { continue }
119 for (index, field) in session.fields.enumerated() {
120 for (n, r) in field.ranges.enumerated() where !r.isEmpty && r.upperBound <= length {
121 guard let range = textRange(r) else { continue }
122 if index == session.active, n == 0 {
123 manager.addRenderingAttribute(.backgroundColor, value: UIColor.systemYellow.withAlphaComponent(0.3), for: range)
124 } else {
125 manager.addRenderingAttribute(.backgroundColor, value: UIColor.systemGray.withAlphaComponent(0.2), for: range)
126 }
127 }
128 }
129 }
130 snippetHighlight = snippetSession?.extent
131 }
132}
133
134extension MobileEditor {
135 func textViewDidChange(_ textView: UITextView) {
136 guard textView === self.textView else { return }
137 updateSnippetMirrors()
138 textTyped()
139 }
140}
141#endif