-
Notifications
You must be signed in to change notification settings - Fork 83
/
RichTextEditorContext.swift
264 lines (213 loc) · 10.9 KB
/
RichTextEditorContext.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
//
// RichTextViewContext.swift
// Proton
//
// Created by Rajdeep Kwatra on 7/1/20.
// Copyright © 2020 Rajdeep Kwatra. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import UIKit
import CoreServices
class RichTextEditorContext: RichTextViewContext {
static let `default` = RichTextEditorContext()
func textViewDidBeginEditing(_ textView: UITextView) {
guard textView.delegate === self else { return }
selectedTextView = textView.asRichTextView
activeTextView = textView.asRichTextView
guard let richTextView = activeTextView else { return }
let range = richTextView.selectedRange
richTextView.richTextViewDelegate?.richTextView(richTextView, didReceiveFocusAt: range)
var attributes = [NSAttributedString.Key:Any]()
if richTextView.selectedRange.endLocation < richTextView.contentLength {
attributes = richTextView.attributedText.attributes(at: range.endLocation, effectiveRange: nil)
} else {
attributes = richTextView.defaultTypingAttributes
}
let contentType = attributes[.blockContentType] as? EditorContent.Name ?? .unknown
attributes[.blockContentType] = nil
richTextView.richTextViewDelegate?.richTextView(richTextView, didChangeSelection: range, attributes: attributes, contentType: contentType)
}
func textViewDidEndEditing(_ textView: UITextView) {
guard textView.delegate === self else { return }
defer {
activeTextView = nil
selectedTextView = nil
}
guard let richTextView = activeTextView else { return }
richTextView.richTextViewDelegate?.richTextView(richTextView, didLoseFocusFrom: textView.selectedRange)
}
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
guard textView.delegate === self,
let richTextView = activeTextView
else { return true }
if shouldChangeText(richTextView, range: range, replacementText: text) == false {
return false
}
// if backspace
var handled = false
if text.isEmpty {
richTextView.richTextViewDelegate?.richTextView(richTextView, shouldHandle: .backspace, modifierFlags: [], at: range, handled: &handled)
guard handled == false else {
return false
}
// User tapped backspace with nothing selected, selected or remove Attachment
let attributedText: NSAttributedString = textView.attributedText // single allocation
if
range.length == 1, // Hit backspace with nothing selected
range.location <= attributedText.length, // ... within bounds
let attachment = attributedText.attribute(.attachment, at: range.location, effectiveRange: nil) as? Attachment,
let delegate = richTextView.richTextViewDelegate,
(delegate.richTextView(richTextView, shouldSelectAttachmentOnBackspace: attachment) == true ||
attachment.selectBeforeDelete), // ...should be selected
!attachment.isSelected // ... but isn't.
{
attachment.isSelected = true // Select it
textView.selectedRange = range
return false // don't delete anything
}
// Else, handle backspace normally
return true
}
if text == "\n" {
richTextView.richTextViewDelegate?.richTextView(richTextView, shouldHandle: .enter, modifierFlags: [], at: range, handled: &handled)
guard handled == false else {
return false
}
richTextView.richTextViewDelegate?.richTextView(richTextView, didReceive: .enter, modifierFlags: [], at: range)
}
if text == "\t" {
richTextView.richTextViewDelegate?.richTextView(richTextView, shouldHandle: .tab, modifierFlags: [], at: range, handled: &handled)
guard handled == false else {
return false
}
}
applyFontFixForEmojiIfRequired(in: richTextView, at: range)
return true
}
private func shouldChangeText(_ richTextView: RichTextView, range: NSRange, replacementText: String) -> Bool {
guard let editor = richTextView.superview as? EditorView else { return true }
updateTypingAttributes(editor: editor, editedRange: range)
for processor in richTextView.textProcessor?.sortedProcessors ?? [] {
let shouldProcess = processor.shouldProcess(editor, shouldProcessTextIn: range, replacementText: replacementText)
if shouldProcess == false {
return false
}
}
return true
}
private func updateTypingAttributes(editor: EditorView, editedRange: NSRange) {
guard editedRange.location > 0,
editedRange.location <= editor.contentLength
else { return }
// custom attributes to carry over
let customAttributesToApply: [NSAttributedString.Key] = [.backgroundStyle]
let attributes = editor.attributedText.attributes(at: editedRange.location - 1, effectiveRange: nil)
let filteredAttributes = attributes.filter { customAttributesToApply.contains($0.key) }
for attribute in filteredAttributes {
editor.typingAttributes[attribute.key] = attribute.value
}
// Drop locked attributes
if let lockedAttributes = attributes.first(where: { $0.key == .lockedAttributes })?.value as? [NSAttributedString.Key] {
for attribute in lockedAttributes {
editor.typingAttributes[attribute] = nil
}
}
}
func textViewDidChange(_ textView: UITextView) {
guard textView.delegate === self else { return }
selectedTextView = textView.asRichTextView
guard let richTextView = activeTextView else { return }
applyFontFixForEmojiIfRequired(in: richTextView, at: textView.selectedRange)
invokeDidProcessIfRequired(richTextView)
richTextView.richTextViewDelegate?.richTextView(richTextView, didChangeTextAtRange: richTextView.selectedRange)
}
private func invokeDidProcessIfRequired(_ richTextView: RichTextView) {
guard let editor = richTextView.superview as? EditorView else { return }
for processor in richTextView.textProcessor?.sortedProcessors ?? [] {
processor.didProcess(editor: editor)
}
}
// This func is required to handle a bug in NSTextStorage/UITextView where after inserting an emoji character, the
// typing attributes are set to default Menlo font. This causes the editor to lose the applied font that exists before the emoji
// character. The code looks for existing font information before emoji char and resets that in the typing attributes.
private func applyFontFixForEmojiIfRequired(in textView: RichTextView, at range: NSRange) {
guard let font = textView.typingAttributes[.font] as? UIFont,
font.isAppleEmoji
else { return }
textView.typingAttributes[.font] = getDefaultFont(textView: textView, before: range)
}
private func getDefaultFont(textView: RichTextView, before range: NSRange) -> UIFont {
var fontToApply: UIFont?
let traversalRange = NSRange(location: 0, length: range.location)
textView.enumerateAttribute(.font, in: traversalRange, options: [.longestEffectiveRangeNotRequired, .reverse]) { font, fontRange, stop in
if let font = font as? UIFont,
font.isAppleEmoji == false {
fontToApply = font
stop.pointee = true
}
}
return fontToApply ?? textView.defaultFont
}
}
extension UIScrollView {
var scrollViewDelegate: UIScrollViewDelegate? {
(self as? RichTextView)?.richTextScrollViewDelegate
}
}
// ScrollView Delegate functions
extension RichTextEditorContext {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
scrollView.scrollViewDelegate?.scrollViewDidScroll?(scrollView)
}
func scrollViewDidZoom(_ scrollView: UIScrollView) {
scrollView.scrollViewDelegate?.scrollViewDidZoom?(scrollView)
}
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
scrollView.scrollViewDelegate?.scrollViewWillBeginDragging?(scrollView)
}
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
scrollView.scrollViewDelegate?.scrollViewWillEndDragging?(scrollView, withVelocity: velocity, targetContentOffset: targetContentOffset)
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
scrollView.scrollViewDelegate?.scrollViewDidEndDragging?(scrollView, willDecelerate: decelerate)
}
func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) {
scrollView.scrollViewDelegate?.scrollViewWillBeginDecelerating?(scrollView)
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
scrollView.scrollViewDelegate?.scrollViewDidEndDecelerating?(scrollView)
}
func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
scrollView.scrollViewDelegate?.scrollViewDidEndScrollingAnimation?(scrollView)
}
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
scrollView.scrollViewDelegate?.viewForZooming?(in: scrollView)
}
func scrollViewWillBeginZooming(_ scrollView: UIScrollView, with view: UIView?) {
scrollView.scrollViewDelegate?.scrollViewWillBeginZooming?(scrollView, with: view)
}
func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) {
scrollView.scrollViewDelegate?.scrollViewDidEndZooming?(scrollView, with: view, atScale: scale)
}
func scrollViewShouldScrollToTop(_ scrollView: UIScrollView) -> Bool {
scrollView.scrollViewDelegate?.scrollViewShouldScrollToTop?(scrollView) ?? false
}
func scrollViewDidScrollToTop(_ scrollView: UIScrollView) {
scrollView.scrollViewDelegate?.scrollViewDidScrollToTop?(scrollView)
}
func scrollViewDidChangeAdjustedContentInset(_ scrollView: UIScrollView) {
scrollView.scrollViewDelegate?.scrollViewDidChangeAdjustedContentInset?(scrollView)
}
}