-
Notifications
You must be signed in to change notification settings - Fork 67
Expand file tree
/
Copy pathTextHtmlParser.mm
More file actions
189 lines (163 loc) · 7.08 KB
/
Copy pathTextHtmlParser.mm
File metadata and controls
189 lines (163 loc) · 7.08 KB
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
#import "TextHtmlParser.h"
#import "AlignmentEntry.h"
#import "ArrayExtension.h"
#import "EnrichedTextView.h"
#import "HtmlParser.h"
#import "LinkData.h"
#import "MentionParams.h"
#import "StyleHeaders.h"
#import "StyleUtils.h"
#import "ZeroWidthSpaceUtils.h"
#import <React/RCTLog.h>
@implementation TextHtmlParser
- (instancetype)initWithView:(EnrichedTextView *)view {
self = [super init];
_view = view;
return self;
}
- (void)replaceWholeFromHtml:(NSString *_Nonnull)html {
@try {
NSString *normalized =
[HtmlParser initiallyProcessHtml:html
useHtmlNormalizer:_view->useHtmlNormalizer];
if (normalized == nil) {
[_view->textView.textStorage
setAttributedString:[[NSAttributedString alloc]
initWithString:html
attributes:_view->
defaultTypingAttributes]];
return;
}
NSArray *result = [HtmlParser getTextAndStylesFromHtml:normalized
config:nil];
NSString *plainText = result[0];
NSArray *processedStyles = result[1];
NSArray *alignments = result[2];
NSMutableAttributedString *body = [[NSMutableAttributedString alloc]
initWithString:plainText
attributes:_view->defaultTypingAttributes];
[_view->textView.textStorage setAttributedString:body];
[self applyProcessedStyles:processedStyles];
[self applyProcessedAlignments:alignments];
} @catch (NSException *exception) {
RCTLogWarn(@"[EnrichedTextView]: Failed to parse HTML: (%@), falling back "
@"to raw input.",
exception.reason);
[_view->textView.textStorage
setAttributedString:[[NSAttributedString alloc]
initWithString:html
attributes:_view->defaultTypingAttributes]];
}
}
- (void)applyProcessedStyles:(NSArray *_Nonnull)processedStyles {
// Some paragraph styles (codeblock, blockquote, etc.) insert \u200B
// into empty lines, mutating NSTextStorage length. We need to
// shift subsequent ranges by this offset.
NSInteger zeroWidthSpaceOffset = 0;
// Inline styles collected during the first pass so their applyStyling: can
// be re-run after all paragraph styles have applied their visual attributes.
// Each entry is @[style, adjustedRange].
NSMutableArray *pendingInlineApply = [NSMutableArray array];
// Paragraph styles call applyStyling: immediately; inline styles
// defer it so that paragraph visual attributes are already in
// place when inline styles override them.
for (NSArray *arr in processedStyles) {
NSNumber *styleType = (NSNumber *)arr[0];
StylePair *stylePair = (StylePair *)arr[1];
StyleBase *style = _view->stylesDict[styleType];
if (style == nullptr)
continue;
NSRange parsedRange = [stylePair.rangeValue rangeValue];
NSUInteger textLengthBeforeStyleApplied =
_view->textView.textStorage.string.length;
// Range must be taking zeroWidthSpaceOffset into consideration
// because processed styles ranges are relative to only the new text while
// we need absolute ranges relative to the whole existing text
NSRange styleRange = NSMakeRange(
zeroWidthSpaceOffset + parsedRange.location, parsedRange.length);
if (![StyleUtils handleStyleBlocksAndConflicts:[[style class] getType]
range:styleRange
forHost:_view]) {
continue;
}
if ([styleType isEqualToNumber:@([LinkStyle getType])]) {
LinkData *linkData = (LinkData *)stylePair.styleValue;
[((LinkStyle *)style) applyLinkMetaWithData:linkData range:styleRange];
} else if ([styleType isEqualToNumber:@([MentionStyle getType])]) {
MentionParams *params = (MentionParams *)stylePair.styleValue;
[((MentionStyle *)style) applyMentionMeta:params range:styleRange];
} else if ([styleType isEqualToNumber:@([ImageStyle getType])]) {
ImageData *imgData = (ImageData *)stylePair.styleValue;
[((ImageStyle *)style) addImageAtRange:styleRange
imageData:imgData
withSelection:NO
withDirtyRange:NO];
} else if ([styleType isEqualToNumber:@([CheckboxListStyle getType])]) {
NSDictionary *checkboxStates = (NSDictionary *)stylePair.styleValue;
CheckboxListStyle *cbStyle = (CheckboxListStyle *)style;
[cbStyle addWithChecked:NO
range:styleRange
withTyping:NO
withDirtyRange:NO];
if (checkboxStates && checkboxStates.count > 0) {
for (NSNumber *key in checkboxStates) {
NSUInteger checkboxPosition =
zeroWidthSpaceOffset + [key unsignedIntegerValue];
BOOL isChecked = [checkboxStates[key] boolValue];
if (isChecked) {
[cbStyle toggleCheckedAt:checkboxPosition withDirtyRange:NO];
}
}
}
} else {
[style add:styleRange withTyping:NO withDirtyRange:NO];
}
[ZeroWidthSpaceUtils addSpacesIfNeededInHost:_view inRange:styleRange];
NSInteger delta = _view->textView.textStorage.string.length -
textLengthBeforeStyleApplied;
// Use an adjusted range so that applyStyling covers any ZWS characters that
// were just inserted by addSpacesIfNeededInHost:inRange:. Without this, a
// style applied to an empty range {0,0} would call applyStyling on {0,0}
// even after a ZWS was inserted.
NSRange adjustedStyleRange = NSMakeRange(
styleRange.location, styleRange.length + (NSUInteger)MAX(0LL, delta));
if ([style isParagraph]) {
[style applyStyling:adjustedStyleRange];
} else {
[pendingInlineApply
addObject:@[ style, [NSValue valueWithRange:adjustedStyleRange] ]];
}
// Image shifts are already handled by _precedingImageCount during tag
// finalization.
if (delta != 0 && ![styleType isEqualToNumber:@([ImageStyle getType])]) {
zeroWidthSpaceOffset += delta;
}
}
// Respect the styling priority
NSArray *sortedInlineApply =
[pendingInlineApply sortedArrayBySortKey:^NSInteger(NSArray *entry) {
return [((StyleBase *)entry[0]) stylePriority];
}];
// Apply visual styling for inline styles
for (NSArray *entry in sortedInlineApply) {
StyleBase *style = entry[0];
NSRange adjustedStyleRange = [((NSValue *)entry[1]) rangeValue];
[style applyStyling:adjustedStyleRange];
}
}
- (void)applyProcessedAlignments:(NSArray<AlignmentEntry *> *)alignments {
AlignmentStyle *alignmentStyle =
_view.stylesDict[@([AlignmentStyle getType])];
if (alignmentStyle == nil) {
return;
}
for (AlignmentEntry *entry in alignments) {
NSRange finalRange = NSMakeRange(entry.range.location, entry.range.length);
[alignmentStyle addAlignment:entry.alignment
range:finalRange
withTyping:NO
withDirtyRange:NO];
[alignmentStyle applyStyling:finalRange];
}
}
@end