-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
RCTAztecView.swift
817 lines (675 loc) · 28.2 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
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
import Aztec
import CoreServices
import Foundation
import UIKit
class RCTAztecView: Aztec.TextView {
@objc var onBackspace: RCTBubblingEventBlock? = nil
@objc var onChange: RCTBubblingEventBlock? = nil
@objc var onKeyDown: 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 minWidth: CGFloat = 0
@objc var maxWidth: CGFloat = 0
@objc var triggerKeyCodes: NSArray?
@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
}
}
@objc var disableAutocorrection: Bool = false {
didSet {
autocorrectionType = disableAutocorrection ? .no : .default
}
}
override var textAlignment: NSTextAlignment {
set {
super.textAlignment = newValue
defaultParagraphStyle.alignment = newValue
placeholderLabel.textAlignment = newValue
}
get {
return super.textAlignment
}
}
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
)
}()
private lazy var placeholderWidthConstraint: NSLayoutConstraint = {
// width needs to be shrunk on both the left and the right by the textInset in order for
// the placeholder to be appropriately positioned with right alignment.
let placeholderWidthInset = 2 * leftTextInset
return placeholderLabel.widthAnchor.constraint(equalTo: widthAnchor, constant: -placeholderWidthInset)
}()
// MARK: - Font
/// Flag to enable using the defaultFont in Aztec for specific blocks
/// Like the Preformatted and Heading blocks.
private var blockUseDefaultFont: Bool = false
/// 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
/// Line height 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 lineHeight: CGFloat? = nil
// MARK: - Formats
private let formatStringMap: [FormattingIdentifier: String] = [
.bold: "bold",
.italic: "italic",
.strikethrough: "strikethrough",
.link: "link",
.mark: "mark"
]
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() {
Configuration.headersWithBoldTrait = true
delegate = self
textContainerInset = .zero
contentInset = .zero
textContainer.lineFragmentPadding = 0
frame.size = .zero
addPlaceholder()
textDragInteraction?.isEnabled = false
storage.htmlConverter.characterToReplaceLastEmptyLine = Character(.zeroWidthSpace)
storage.htmlConverter.shouldCollapseSpaces = false
shouldNotifyOfNonUserChanges = false
// Typing attributes are controlled by RichText component so we have to prevent Aztec to recalculate them when deleting backward.
shouldRecalculateTypingAttributesOnDeleteBackward = false
disableLinkTapRecognizer()
preBackgroundColor = .clear
}
func addPlaceholder() {
addSubview(placeholderLabel)
let topConstant = contentInset.top + textContainerInset.top
NSLayoutConstraint.activate([
placeholderHorizontalConstraint,
placeholderWidthConstraint,
placeholderLabel.topAnchor.constraint(equalTo: topAnchor, constant: topConstant)
])
}
/**
This handles a bug introduced by iOS 13.0 (tested up to 13.2) where link interactions don't respect what the documentation says.
The documenatation for textView(_:shouldInteractWith:in:interaction:) says:
> Links in text views are interactive only if the text view is selectable but noneditable.
Our Aztec Text views are selectable and editable, and yet iOS was opening links on Safari when tapped.
*/
func disableLinkTapRecognizer() {
guard let recognizer = gestureRecognizers?.first(where: { $0.name == "UITextInteractionNameLinkTap" }) else {
return
}
recognizer.isEnabled = false
}
// MARK: - View height and width: Match to the content
override func layoutSubviews() {
super.layoutSubviews()
adjustWidth()
fixLabelPositionForRTLLayout()
updateContentSizeInRN()
}
private func adjustWidth() {
if (maxWidth > 0 && minWidth > 0) {
let maxSize = CGSize(width: maxWidth, height: CGFloat.greatestFiniteMagnitude)
let newWidth = sizeThatFits(maxSize).width
if (newWidth != frame.size.width) {
frame.size.width = max(newWidth, minWidth)
}
}
}
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
}
}
override func sizeThatFits(_ size: CGSize) -> CGSize {
// Set the Placeholder height as the minimum TextView height.
let minimumHeight = placeholderLabel.frame.height
let fittingSize = super.sizeThatFits(size)
let height = max(fittingSize.height, minimumHeight)
return CGSize(width: fittingSize.width, height: height)
}
func updateContentSizeInRN() {
let newSize = sizeThatFits(frame.size)
guard previousContentSize != newSize,
let onContentSizeChange = onContentSizeChange else {
return
}
previousContentSize = newSize
let body = packForRN(newSize, withName: "contentSize")
let caretData = packCaretDataForRN()
var result = body
result.merge(caretData) { (_, new) in new }
onContentSizeChange(result)
}
// MARK: - Paste handling
private func read(from pasteboard: UIPasteboard, uti: CFString, documentType: DocumentType) -> String? {
guard let data = pasteboard.data(forPasteboardType: uti as String),
let attributedString = try? NSAttributedString(data: data, options: [.documentType: documentType], documentAttributes: nil),
let storage = self.textStorage as? TextStorage else {
return nil
}
return storage.getHTML(from: attributedString)
}
private func readHTML(from pasteboard: UIPasteboard) -> String? {
if let data = pasteboard.data(forPasteboardType: kUTTypeHTML as String), let html = String(data: data, encoding: .utf8) {
// Make sure we are not getting a full HTML DOC. We only want inner content
if !html.hasPrefix("<!DOCTYPE html") {
return html
}
}
if let flatRTFDString = read(from: pasteboard, uti: kUTTypeFlatRTFD, documentType: DocumentType.rtfd) {
return flatRTFDString
}
if let rtfString = read(from: pasteboard, uti: kUTTypeRTF, documentType: DocumentType.rtf) {
return rtfString
}
if let rtfdString = read(from: pasteboard, uti: kUTTypeRTFD, documentType: DocumentType.rtfd) {
return rtfdString
}
return nil
}
private func readText(from pasteboard: UIPasteboard) -> String? {
var text = pasteboard.string
// Text that comes from Aztec will have paragraphSeparator instead of line feed AKA as \n. The paste methods in GB are expecting \n so this line will fix that.
text = text?.replacingOccurrences(of: String(.paragraphSeparator), with: String(.lineFeed))
return text
}
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 readImages(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 pasteboard = UIPasteboard.general
let text = readText(from: pasteboard) ?? ""
let html = readHTML(from: pasteboard) ?? ""
let imagesURLs = readImages(from: pasteboard)
sendPasteCallback(text: text, html: html, imagesURLs: imagesURLs);
}
override func pasteWithoutFormatting(_ sender: Any?) {
let pasteboard = UIPasteboard.general
let text = readText(from: pasteboard) ?? ""
let imagesURLs = readImages(from: pasteboard)
sendPasteCallback(text: text, html: "", imagesURLs: imagesURLs);
}
private func sendPasteCallback(text: String, html: String, imagesURLs: [String]) {
let start = selectedRange.location
let end = selectedRange.location + selectedRange.length
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
}
interceptTriggersKeyCodes(text)
super.insertText(text)
updatePlaceholderVisibility()
}
open override func deleteBackward() {
guard !interceptBackspace() else {
return
}
super.deleteBackward()
updatePlaceholderVisibility()
}
// MARK: - Dictation
func removeUnicodeAndRestoreCursor(from textView: UITextView) {
// Capture current cursor position
let originalPosition = textView.offset(from: textView.beginningOfDocument, to: textView.selectedTextRange?.start ?? textView.beginningOfDocument)
// Replace occurrences of the obj symbol ("\u{FFFC}")
textView.text = textView.text?.replacingOccurrences(of: "\u{FFFC}", with: "")
// Detect if cursor is off-by-one and correct, if so
let newPositionOffset = originalPosition > 0 ? originalPosition - 1 : originalPosition
if let newPosition = textView.position(from: textView.beginningOfDocument, offset: newPositionOffset) {
// Move the cursor to the correct, new position following dictation
textView.selectedTextRange = textView.textRange(from: newPosition, to: newPosition)
}
}
// MARK: - Custom Edit Intercepts
private func interceptEnter(_ text: String) -> Bool {
if text == "\t" {
return true
}
guard text == "\n",
let onKeyDown = onKeyDown else {
return false
}
var eventData = packCaretDataForRN()
eventData = add(keyTrigger: "\r", to: eventData)
onKeyDown(eventData)
return true
}
private func interceptBackspace() -> Bool {
guard (isNewLineBeforeSelectionAndNotEndOfContent() && selectedRange.length == 0)
|| (selectedRange.location == 0 && selectedRange.length == 0)
|| text.count == 1 // send backspace event when cleaning all characters
|| selectedRange == NSRange(location: 0, length: textStorage.length), // send backspace event when deleting all the text
let onKeyDown = onKeyDown else {
return false
}
var range = selectedRange
if text.count == 1 {
range = NSRange(location: 0, length: textStorage.length)
}
var caretData = packCaretDataForRN(overrideRange: range)
onSelectionChange?(caretData)
let backSpaceKeyCode:UInt8 = 8
caretData = add(keyCode: backSpaceKeyCode, to: caretData)
onKeyDown(caretData)
return true
}
private func interceptTriggersKeyCodes(_ text: String) {
guard let keyCodes = triggerKeyCodes,
keyCodes.count > 0,
let onKeyDown = onKeyDown,
text.count == 1
else {
return
}
for value in keyCodes {
guard let keyString = value as? String,
let keyCode = keyString.first?.asciiValue,
text.contains(keyString)
else {
continue
}
var eventData = [AnyHashable:Any]()
eventData = add(keyCode: keyCode, to: eventData)
onKeyDown(eventData)
return
}
}
private func isNewLineBeforeSelectionAndNotEndOfContent() -> Bool {
guard let currentLocation = text.indexFromLocation(selectedRange.location) else {
return false
}
return text.isStartOfParagraph(at: currentLocation) && !(text.endIndex == currentLocation)
}
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
private func cleanHTML() -> String {
let html = getHTML(prettify: false).replacingOccurrences(of: String(.paragraphSeparator), with: String(.lineFeed)).replacingOccurrences(of: String(.zeroWidthSpace), with: "")
return html
}
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(overrideRange: NSRange? = nil) -> [AnyHashable: Any] {
var range = selectedRange
if let overrideRange = overrideRange {
range = overrideRange
}
var start = range.location
var end = range.location + range.length
if selectionAffinity == .backward {
(start, end) = (end, start)
}
var result: [AnyHashable : Any] = packForRN(cleanHTML(), withName: "text")
result["selectionStart"] = start
result["selectionEnd"] = end
if let range = selectedTextRange {
let caretEndRect = caretRect(for: range.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
result["selectionEndCaretHeight"] = caretEndRect.size.height
}
}
return result
}
func add(keyTrigger: String, to pack:[AnyHashable: Any]) -> [AnyHashable: Any] {
guard let keyCode = keyTrigger.first?.asciiValue else {
return pack
}
return add(keyCode: keyCode, to: pack)
}
func add(keyCode: UInt8, to pack:[AnyHashable: Any]) -> [AnyHashable: Any] {
var result = pack
result["keyCode"] = keyCode
return result
}
// MARK: - RN Properties
@objc func setBlockUseDefaultFont(_ useDefaultFont: Bool) {
guard blockUseDefaultFont != useDefaultFont else {
return
}
if useDefaultFont {
// Enable using the defaultFont in Aztec
// For the PreFormatter and HeadingFormatter
Configuration.useDefaultFont = true
}
blockUseDefaultFont = useDefaultFont
refreshFont()
}
@objc
func setContents(_ contents: NSDictionary) {
if let hexString = contents["linkTextColor"] as? String, let linkColor = UIColor(hexString: hexString), linkTextColor != linkColor {
linkTextColor = linkColor
}
guard contents["eventCount"] == nil else {
return
}
let html = contents["text"] as? String ?? ""
let tag = contents["tag"] as? String ?? ""
checkDefaultFontFamily(tag: tag)
setHTML(html)
updatePlaceholderVisibility()
refreshTypingAttributesAndPlaceholderFont()
if let selection = contents["selection"] as? NSDictionary,
let start = selection["start"] as? NSNumber,
let end = selection["end"] as? NSNumber {
setSelection(start: start, end: end)
}
// This signals the RN/JS system that the component needs to relayout
setNeedsLayout()
}
override var textColor: UIColor? {
didSet {
typingAttributes[NSAttributedString.Key.foregroundColor] = self.textColor
self.defaultTextColor = self.textColor
}
}
override var typingAttributes: [NSAttributedString.Key : Any] {
didSet {
// Keep placeholder attributes in sync with typing attributes.
placeholderLabel.attributedText = NSAttributedString(string: placeholderLabel.text ?? "", attributes: placeholderAttributes)
}
}
// MARK: - Placeholder
@objc var placeholder: String {
set {
placeholderLabel.attributedText = NSAttributedString(string: newValue, attributes: placeholderAttributes)
}
get {
return placeholderLabel.text ?? ""
}
}
/// Attributes to use on the placeholder.
var placeholderAttributes: [NSAttributedString.Key: Any] {
var placeholderAttributes = typingAttributes
placeholderAttributes[.foregroundColor] = placeholderTextColor
return placeholderAttributes
}
@objc var placeholderTextColor: UIColor {
set {
placeholderLabel.textColor = newValue
}
get {
return placeholderLabel.textColor
}
}
var linkTextColor: UIColor {
set {
let shadow = NSShadow()
shadow.shadowColor = newValue
linkTextAttributes = [.foregroundColor: newValue, .underlineStyle: NSNumber(value: NSUnderlineStyle.single.rawValue), .shadow: shadow]
}
get {
return linkTextAttributes[.foregroundColor] as? UIColor ?? UIColor.blue
}
}
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.replacingOccurrences(of: String(.zeroWidthSpace), with: "").isEmpty
}
// MARK: - Font Setters
@objc func setFontFamily(_ family: String) {
guard fontFamily != family else {
return
}
fontFamily = family
refreshFont()
}
@objc func setFontSize(_ size: CGFloat) {
guard fontSize != size else {
return
}
fontSize = size
refreshFont()
refreshLineHeight()
}
@objc func setFontWeight(_ weight: String) {
guard fontWeight != weight else {
return
}
fontWeight = weight
refreshFont()
}
@objc func setLineHeight(_ newLineHeight: CGFloat) {
guard lineHeight != newLineHeight else {
return
}
lineHeight = newLineHeight
refreshLineHeight()
}
// 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
let fontMetrics = UIFontMetrics(forTextStyle: .body)
if let fontSize = fontSize {
newFontSize = fontMetrics.scaledValue(for: fontSize)
} else {
newFontSize = fontMetrics.scaledValue(for: 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() {
let newFont = applyFontConstraints(to: defaultFont)
font = newFont
placeholderLabel.font = newFont
defaultFont = newFont
if textStorage.length > 0 {
typingAttributes[NSAttributedString.Key.font] = newFont
}
}
/// 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 currentFont = font(from: typingAttributes)
placeholderLabel.font = currentFont
}
/// This method refreshes the line height.
private func refreshLineHeight() {
if let lineHeight = lineHeight {
let attributeString = NSMutableAttributedString(string: self.text)
let style = NSMutableParagraphStyle()
let currentFontSize = fontSize ?? defaultFont.pointSize
let lineSpacing = ((currentFontSize * lineHeight) / UIScreen.main.scale) - (currentFontSize / lineHeight) / 2
style.lineSpacing = lineSpacing
defaultParagraphStyle.regularLineSpacing = lineSpacing
textStorage.addAttribute(NSAttributedString.Key.paragraphStyle, value: style, range: NSMakeRange(0, textStorage.length))
}
}
/// This method sets the desired font family
/// for specific tags.
private func checkDefaultFontFamily(tag: String) {
// Since we are using the defaultFont to customize
// the font size, we need to set the monospace font.
if (blockUseDefaultFont && tag == "pre") {
setFontFamily(FontProvider.shared.monospaceFont.fontName)
}
}
// 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)
case "mark": toggleMark(range: emptyRange)
default: print("Format not recognized")
}
}
// 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: - Selection
private func correctSelectionAfterLastEmptyLine() {
guard selectedTextRange?.start == endOfDocument,
let characterToReplaceLastEmptyLine = storage.htmlConverter.characterToReplaceLastEmptyLine,
text == String(characterToReplaceLastEmptyLine) else {
return
}
selectedTextRange = self.textRange(from: beginningOfDocument, to: beginningOfDocument)
}
}
// MARK: UITextView Delegate Methods
extension RCTAztecView: UITextViewDelegate {
func textViewDidChangeSelection(_ textView: UITextView) {
guard isFirstResponder else {
return
}
correctSelectionAfterLastEmptyLine()
propagateSelectionChanges()
}
func textViewDidBeginEditing(_ textView: UITextView) {
correctSelectionAfterLastEmptyLine()
}
func textViewDidChange(_ textView: UITextView) {
// Workaround for RN dictation bug that adds obj symbol.
// Ref: https://github.com/facebook/react-native/issues/36521
// TODO: Remove workaround when RN issue is fixed
if textView.text?.contains("\u{FFFC}") == true {
removeUnicodeAndRestoreCursor(from: textView)
}
propagateContentChanges()
updatePlaceholderVisibility()
//Necessary to send height information to JS after pasting text.
textView.setNeedsLayout()
}
override func becomeFirstResponder() -> Bool {
if !isFirstResponder && canBecomeFirstResponder {
let caretData = packCaretDataForRN()
onFocus?(caretData)
}
return super.becomeFirstResponder()
}
func textViewDidEndEditing(_ textView: UITextView) {
let text = packForRN(cleanHTML(), withName: "text")
onBlur?(text)
}
}