-
Notifications
You must be signed in to change notification settings - Fork 58
/
RCTAztecView.swift
543 lines (432 loc) · 16.9 KB
/
RCTAztecView.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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
import Aztec
import CoreServices
import Foundation
import UIKit
class RCTAztecView: Aztec.TextView {
@objc var onBackspace: RCTBubblingEventBlock? = nil
@objc var onChange: RCTBubblingEventBlock? = nil
@objc var onEnter: RCTBubblingEventBlock? = nil
@objc var onFocus: RCTBubblingEventBlock? = nil
@objc var onBlur: RCTBubblingEventBlock? = nil
@objc var onPaste: RCTBubblingEventBlock? = nil
@objc var onContentSizeChange: RCTBubblingEventBlock? = nil
@objc var onSelectionChange: RCTBubblingEventBlock? = nil
@objc var blockType: NSDictionary? = nil {
didSet {
guard let block = blockType, let tag = block["tag"] as? String else {
return
}
blockModel = BlockModel(tag: tag)
}
}
@objc var activeFormats: NSSet? = nil {
didSet {
let currentTypingAttributes = formattingIdentifiersForTypingAttributes()
for (key, value) in formatStringMap where currentTypingAttributes.contains(key) != activeFormats?.contains(value) {
toggleFormat(format: value)
}
}
}
@objc var disableEditingMenu: Bool = false {
didSet {
allowsEditingTextAttributes = !disableEditingMenu
}
}
var blockModel = BlockModel(tag: "") {
didSet {
forceTypingAttributesIfNeeded()
}
}
private var previousContentSize: CGSize = .zero
var leftTextInset: CGFloat {
return contentInset.left + textContainerInset.left + textContainer.lineFragmentPadding
}
var leftTextInsetInRTLLayout: CGFloat {
return bounds.width - leftTextInset
}
var hasRTLLayout: Bool {
return reactLayoutDirection == .rightToLeft
}
private(set) lazy var placeholderLabel: UILabel = {
let label = UILabel(frame: .zero)
label.translatesAutoresizingMaskIntoConstraints = false
label.textAlignment = .natural
label.font = font
return label
}()
// RCTScrollViews are flipped horizontally on RTL. This messes up competelly horizontal layout contraints
// on views inserted after the transformation.
var placeholderPreferedHorizontalAnchor: NSLayoutXAxisAnchor {
return hasRTLLayout ? placeholderLabel.rightAnchor : placeholderLabel.leftAnchor
}
// This constraint is created from the prefered horizontal anchor (analog to "leading")
// but appending it always to left of its super view (Aztec).
// This partially fixes the position issue originated from fliping the scroll view.
// fixLabelPositionForRTLLayout() fixes the rest.
private lazy var placeholderHorizontalConstraint: NSLayoutConstraint = {
return placeholderPreferedHorizontalAnchor.constraint(
equalTo: leftAnchor,
constant: leftTextInset
)
}()
/// If a dictation start with an empty UITextView,
/// the dictation engine refreshes the TextView with an empty string when the dictation finishes.
/// This helps to avoid propagating that unwanted empty string to RN. (Solving #606)
/// on `textViewDidChange` and `textViewDidChangeSelection`
private var isInsertingDictationResult = false
// MARK: - Font
/// Font family for all contents Once this is set, it will always override the font family for all of its
/// contents, regardless of what HTML is provided to Aztec.
private var fontFamily: String? = nil
/// Font size for all contents. Once this is set, it will always override the font size for all of its
/// contents, regardless of what HTML is provided to Aztec.
private var fontSize: CGFloat? = nil
/// Font weight for all contents. Once this is set, it will always override the font weight for all of its
/// contents, regardless of what HTML is provided to Aztec.
private var fontWeight: String? = nil
// MARK: - Formats
private let formatStringMap: [FormattingIdentifier: String] = [
.bold: "bold",
.italic: "italic",
.strikethrough: "strikethrough",
.link: "link",
]
override init(defaultFont: UIFont, defaultParagraphStyle: ParagraphStyle, defaultMissingImage: UIImage) {
super.init(defaultFont: defaultFont, defaultParagraphStyle: defaultParagraphStyle, defaultMissingImage: defaultMissingImage)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
func commonInit() {
delegate = self
textContainerInset = .zero
contentInset = .zero
textContainer.lineFragmentPadding = 0
addPlaceholder()
}
func addPlaceholder() {
addSubview(placeholderLabel)
NSLayoutConstraint.activate([
placeholderHorizontalConstraint,
placeholderLabel.topAnchor.constraint(equalTo: topAnchor, constant: contentInset.top + textContainerInset.top)
])
}
// MARK - View Height: Match to content height
override func layoutSubviews() {
super.layoutSubviews()
fixLabelPositionForRTLLayout()
updateContentSizeInRN()
}
private func fixLabelPositionForRTLLayout() {
if hasRTLLayout {
// RCTScrollViews are flipped horizontally on RTL layout.
// This fixes the position of the label after "fixing" (partially) the constraints.
placeholderHorizontalConstraint.constant = leftTextInsetInRTLLayout
}
}
func updateContentSizeInRN() {
let newSize = sizeThatFits(frame.size)
guard previousContentSize != newSize,
let onContentSizeChange = onContentSizeChange else {
return
}
previousContentSize = newSize
let body = packForRN(newSize, withName: "contentSize")
onContentSizeChange(body)
}
// MARK: - Paste handling
private func html(from pasteboard: UIPasteboard) -> String? {
guard let data = pasteboard.data(forPasteboardType: kUTTypeHTML as String) else {
return nil
}
return String(data: data, encoding: .utf8)
}
private func text(from pasteboard: UIPasteboard) -> String? {
guard let data = pasteboard.data(forPasteboardType: kUTTypePlainText as String) else {
return nil
}
return String(data: data, encoding: .utf8)
}
private func cleanHTML() -> String {
let html = getHTML(prettify: false).replacingOccurrences(of: "\n", with: "")
return html
}
func saveToDisk(image: UIImage) -> URL? {
let fileName = "\(ProcessInfo.processInfo.globallyUniqueString)_file.jpg"
guard let data = image.jpegData(compressionQuality: 0.9) else {
return nil
}
let fileURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(fileName)
guard (try? data.write(to: fileURL, options: [.atomic])) != nil else {
return nil
}
return fileURL
}
private func images(from pasteboard: UIPasteboard) -> [String] {
guard let images = pasteboard.images else {
return []
}
let imagesURLs = images.compactMap({ saveToDisk(image: $0)?.absoluteString })
return imagesURLs
}
override func paste(_ sender: Any?) {
let start = selectedRange.location
let end = selectedRange.location + selectedRange.length
let pasteboard = UIPasteboard.general
let text = self.text(from: pasteboard) ?? ""
let html = self.html(from: pasteboard) ?? ""
let imagesURLs = self.images(from: pasteboard)
onPaste?([
"currentContent": cleanHTML(),
"selectionStart": start,
"selectionEnd": end,
"pastedText": text,
"pastedHtml": html,
"files": imagesURLs] )
}
// MARK: - Edits
open override func insertText(_ text: String) {
guard !interceptEnter(text) else {
return
}
super.insertText(text)
updatePlaceholderVisibility()
}
open override func deleteBackward() {
guard !interceptBackspace() else {
return
}
super.deleteBackward()
updatePlaceholderVisibility()
}
// MARK: - Dictation
override func dictationRecordingDidEnd() {
isInsertingDictationResult = true
}
public override func insertDictationResult(_ dictationResult: [UIDictationPhrase]) {
let text = dictationResult.reduce("") { $0 + $1.text }
insertText(text)
isInsertingDictationResult = false
}
// MARK: - Custom Edit Intercepts
private func interceptEnter(_ text: String) -> Bool {
if text == "\t" {
return true
}
guard text == "\n",
let onEnter = onEnter else {
return false
}
let caretData = packCaretDataForRN()
onEnter(caretData)
return true
}
private func interceptBackspace() -> Bool {
guard selectedRange.location == 0 && selectedRange.length == 0,
let onBackspace = onBackspace else {
return false
}
let caretData = packCaretDataForRN()
onBackspace(caretData)
return true
}
override var keyCommands: [UIKeyCommand]? {
// Remove defautls Tab and Shift+Tab commands, leaving just Shift+Enter command.
return [carriageReturnKeyCommand]
}
// MARK: - Native-to-RN Value Packing Logic
func packForRN(_ text: String, withName name: String) -> [AnyHashable: Any] {
return [name: text,
"eventCount": 1]
}
func packForRN(_ size: CGSize, withName name: String) -> [AnyHashable: Any] {
let size = ["width": size.width,
"height": size.height]
return [name: size]
}
func packCaretDataForRN() -> [AnyHashable: Any] {
var start = selectedRange.location
var end = selectedRange.location + selectedRange.length
if selectionAffinity == .backward {
(start, end) = (end, start)
}
var result: [AnyHashable : Any] = packForRN(getHTML(prettify: false), withName: "text")
result["selectionStart"] = start
result["selectionEnd"] = end
if let selectedTextRange = selectedTextRange {
let caretEndRect = caretRect(for: selectedTextRange.end)
// Sergio Estevao: Sometimes the carectRect can be invalid so we need to check before sending this to JS.
if !(caretEndRect.isInfinite || caretEndRect.isNull) {
result["selectionEndCaretX"] = caretEndRect.origin.x
result["selectionEndCaretY"] = caretEndRect.origin.y
}
}
return result
}
// MARK: - RN Properties
@objc
func setContents(_ contents: NSDictionary) {
guard contents["eventCount"] == nil else {
return
}
let html = contents["text"] as? String ?? ""
setHTML(html)
updatePlaceholderVisibility()
refreshFont()
if let selection = contents["selection"] as? NSDictionary,
let start = selection["start"] as? NSNumber,
let end = selection["end"] as? NSNumber {
setSelection(start: start, end: end)
}
}
// MARK: - Placeholder
@objc var placeholder: String {
set {
placeholderLabel.text = newValue
}
get {
return placeholderLabel.text ?? ""
}
}
@objc var placeholderTextColor: UIColor {
set {
placeholderLabel.textColor = newValue
}
get {
return placeholderLabel.textColor
}
}
func setSelection(start: NSNumber, end: NSNumber) {
if let startPosition = position(from: beginningOfDocument, offset: start.intValue),
let endPosition = position(from: beginningOfDocument, offset: end.intValue) {
selectedTextRange = textRange(from: startPosition, to: endPosition)
}
}
func updatePlaceholderVisibility() {
placeholderLabel.isHidden = !self.text.isEmpty
}
// MARK: - Font Setters
@objc func setFontFamily(_ family: String) {
fontFamily = family
refreshFont()
}
@objc func setFontSize(_ size: CGFloat) {
fontSize = size
refreshFont()
}
@objc func setFontWeight(_ weight: String) {
fontWeight = weight
refreshFont()
}
// MARK: - Font Refreshing
/// Applies the family, size and weight constraints to the provided font.
///
private func applyFontConstraints(to baseFont: UIFont) -> UIFont {
let oldDescriptor = baseFont.fontDescriptor
let newFontSize: CGFloat
if let fontSize = fontSize {
newFontSize = fontSize
} else {
newFontSize = baseFont.pointSize
}
var newTraits = oldDescriptor.symbolicTraits
if let fontWeight = fontWeight {
if (fontWeight == "bold") {
newTraits.update(with: .traitBold)
}
}
var newDescriptor: UIFontDescriptor
if let fontFamily = fontFamily {
newDescriptor = UIFontDescriptor(name: fontFamily, size: newFontSize)
newDescriptor = newDescriptor.withSymbolicTraits(newTraits) ?? newDescriptor
} else {
newDescriptor = oldDescriptor
}
return UIFont(descriptor: newDescriptor, size: newFontSize)
}
/// Returns the font from the specified attributes, or the default font if no specific one is set.
///
private func font(from attributes: [NSAttributedString.Key: Any]) -> UIFont {
return attributes[.font] as? UIFont ?? defaultFont
}
/// This method refreshes the font for the whole view if the font-family, the font-size or the font-weight
/// were ever set.
///
private func refreshFont() {
guard fontFamily != nil || fontSize != nil || fontWeight != nil else {
return
}
let fullRange = NSRange(location: 0, length: textStorage.length)
textStorage.enumerateAttributes(in: fullRange, options: []) { (attributes, subrange, stop) in
let oldFont = font(from: attributes)
let newFont = applyFontConstraints(to: oldFont)
textStorage.addAttribute(.font, value: newFont, range: subrange)
}
refreshTypingAttributesAndPlaceholderFont()
}
/// This method refreshes the font for the palceholder field and typing attributes.
/// This method should not be called directly. Call `refreshFont()` instead.
///
private func refreshTypingAttributesAndPlaceholderFont() {
let oldFont = font(from: typingAttributes)
let newFont = applyFontConstraints(to: oldFont)
typingAttributes[.font] = newFont
placeholderLabel.font = newFont
}
// MARK: - Formatting interface
@objc func toggleFormat(format: String) {
let emptyRange = NSRange(location: selectedRange.location, length: 0)
switch format {
case "bold": toggleBold(range: emptyRange)
case "italic": toggleItalic(range: emptyRange)
case "strikethrough": toggleStrikethrough(range: emptyRange)
default: print("Format not recognized")
}
}
func forceTypingAttributesIfNeeded() {
if let formatHandler = HeadingBlockFormatHandler(block: blockModel) {
formatHandler.forceTypingFormat(on: self)
}
}
// MARK: - Event Propagation
func propagateContentChanges() {
if let onChange = onChange {
let text = packForRN(cleanHTML(), withName: "text")
onChange(text)
}
}
func propagateSelectionChanges() {
guard let onSelectionChange = onSelectionChange else {
return
}
let caretData = packCaretDataForRN()
onSelectionChange(caretData)
}
}
// MARK: UITextView Delegate Methods
extension RCTAztecView: UITextViewDelegate {
func textViewDidChangeSelection(_ textView: UITextView) {
guard isInsertingDictationResult == false else {
return
}
propagateSelectionChanges()
}
func textViewDidChange(_ textView: UITextView) {
guard isInsertingDictationResult == false else {
return
}
forceTypingAttributesIfNeeded()
propagateContentChanges()
updatePlaceholderVisibility()
//Necessary to send height information to JS after pasting text.
textView.setNeedsLayout()
}
func textViewDidBeginEditing(_ textView: UITextView) {
onFocus?([:])
}
func textViewDidEndEditing(_ textView: UITextView) {
onBlur?([:])
}
}