-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy pathHtmlParser.mm
More file actions
1480 lines (1346 loc) · 61.4 KB
/
Copy pathHtmlParser.mm
File metadata and controls
1480 lines (1346 loc) · 61.4 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
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
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#import "HtmlParser.h"
#import "AlignmentEntry.h"
#import "AlignmentUtils.h"
#import "ImageData.h"
#import "LinkData.h"
#import "MentionParams.h"
#import "StringExtension.h"
#import "StyleHeaders.h"
#import "StylePair.h"
#include "GumboParser.hpp"
@implementation HtmlParser
+ (BOOL)isBlockTag:(NSString *)tagName {
return [tagName isEqualToString:@"ul"] || [tagName isEqualToString:@"ol"] ||
[tagName isEqualToString:@"blockquote"] ||
[tagName isEqualToString:@"codeblock"];
}
/**
* Prepares HTML for the parser by stripping extraneous whitespace and newlines
* from structural tags, while preserving them within text content.
*
* APPROACH:
* This function treats the HTML as having two distinct states:
* 1. Structure Mode (Depth == 0): We are inside or between container tags (like
* blockquote, ul, codeblock). In this mode whitespace and newlines are
* considered layout artifacts and are REMOVED to prevent the parser from
* creating unwanted spaces.
* 2. Content Mode (Depth > 0): We are inside a text-containing tag (like p,
* b, li). In this mode, all whitespace is PRESERVED exactly as is, ensuring
* that sentences and inline formatting remain readable.
*
* The function iterates character-by-character, using a depth counter to track
* nesting levels of the specific tags defined in `textTags`.
*
* IMPORTANT:
* The `textTags` set acts as a whitelist for "Content Mode". If you add support
* for a new HTML tag that contains visible text (e.g., h4, h5, h6),
* you MUST add it to the `textTags` set below.
*/
+ (NSString *)stripExtraWhiteSpacesAndNewlines:(NSString *)html {
NSSet *textTags = [NSSet setWithObjects:@"p", @"h1", @"h2", @"h3", @"h4",
@"h5", @"h6", @"li", @"b", @"a", @"s",
@"mention", @"code", @"u", @"i", nil];
NSMutableString *output = [NSMutableString stringWithCapacity:html.length];
NSMutableString *currentTagBuffer = [NSMutableString string];
NSCharacterSet *whitespaceAndNewlineSet =
[NSCharacterSet whitespaceAndNewlineCharacterSet];
BOOL isReadingTag = NO;
NSInteger textDepth = 0;
for (NSUInteger i = 0; i < html.length; i++) {
unichar c = [html characterAtIndex:i];
if (c == '<') {
isReadingTag = YES;
[currentTagBuffer setString:@""];
[output appendString:@"<"];
} else if (c == '>') {
isReadingTag = NO;
[output appendString:@">"];
NSString *fullTag = [currentTagBuffer lowercaseString];
NSString *cleanName = [fullTag
stringByTrimmingCharactersInSet:
[NSCharacterSet characterSetWithCharactersInString:@"/"]];
NSArray *parts =
[cleanName componentsSeparatedByCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSString *tagName = parts.firstObject;
if (![textTags containsObject:tagName]) {
continue;
}
if ([fullTag hasPrefix:@"/"]) {
textDepth--;
if (textDepth < 0)
textDepth = 0;
} else {
// Opening tag (e.g. <h1>) -> Enter Text Mode
// (Ignore self-closing tags like <img/> if they happen to be in the
// list)
if (![fullTag hasSuffix:@"/"]) {
textDepth++;
}
}
} else {
if (isReadingTag) {
[currentTagBuffer appendFormat:@"%C", c];
[output appendFormat:@"%C", c];
continue;
}
if (textDepth > 0) {
[output appendFormat:@"%C", c];
} else {
if (![whitespaceAndNewlineSet characterIsMember:c]) {
[output appendFormat:@"%C", c];
}
}
}
}
return output;
}
+ (NSString *)stringByAddingNewlinesToTag:(NSString *)tag
inString:(NSString *)html
leading:(BOOL)leading
trailing:(BOOL)trailing {
NSString *str = [html copy];
if (leading) {
NSString *formattedTag = [NSString stringWithFormat:@">%@", tag];
NSString *formattedNewTag = [NSString stringWithFormat:@">\n%@", tag];
str = [str stringByReplacingOccurrencesOfString:formattedTag
withString:formattedNewTag];
}
if (trailing) {
NSString *formattedTag = [NSString stringWithFormat:@"%@<", tag];
NSString *formattedNewTag = [NSString stringWithFormat:@"%@\n<", tag];
str = [str stringByReplacingOccurrencesOfString:formattedTag
withString:formattedNewTag];
}
return str;
}
#pragma mark - External HTML normalization
/**
* Normalizes external HTML (from Google Docs, Word, web pages, etc.) into our
* canonical tag subset using the Gumbo-based C++ normalizer.
*
* Converts: strong → b, em → i, span style="font-weight:bold" → b,
* strips unknown tags while preserving text
*/
+ (NSString *_Nullable)normalizeExternalHtml:(NSString *_Nonnull)html {
std::string result =
GumboParser::normalizeHtml(std::string([html UTF8String]));
if (result.empty())
return nil;
return [NSString stringWithUTF8String:result.c_str()];
}
+ (void)finalizeTagEntry:(NSMutableString *)tagName
ongoingTags:(NSMutableDictionary *)ongoingTags
initiallyProcessedTags:(NSMutableArray *)processedTags
plainText:(NSMutableString *)plainText
precedingImageCount:(NSInteger *)precedingImageCount {
NSMutableArray *tagEntry = [[NSMutableArray alloc] init];
NSArray *tagData = ongoingTags[tagName];
if (tagData == nil) {
return;
}
NSInteger tagLocation = [((NSNumber *)tagData[0]) intValue];
NSInteger openImageCount = [((NSNumber *)tagData[1]) intValue];
NSInteger currentImageCount = *precedingImageCount;
// 'plainText' doesn't contain image placeholders yet, but the final
// NSTextStorage will, so each image adds one character that ranges here
// must account for. 'openImageCount' (captured when the tag opened) shifts
// the start past images finalized BEFORE this tag, while the diff against
// 'currentImageCount' extends the length to cover images finalized INSIDE
// it.
NSRange tagRange = NSMakeRange(tagLocation + openImageCount,
(plainText.length - tagLocation) +
(currentImageCount - openImageCount));
[tagEntry addObject:[tagName copy]];
[tagEntry addObject:[NSValue valueWithRange:tagRange]];
if (tagData.count > 2) {
[tagEntry addObject:[(NSString *)tagData[2] copy]];
}
[processedTags addObject:tagEntry];
[ongoingTags removeObjectForKey:tagName];
if ([tagName isEqualToString:@"img"]) {
(*precedingImageCount)++;
}
}
+ (BOOL)isUlCheckboxList:(NSString *)params {
return ([params containsString:@"data-type=\"checkbox\""] ||
[params containsString:@"data-type='checkbox'"]);
}
+ (NSDictionary *)prepareCheckboxListStyleValue:(NSValue *)rangeValue
checkboxStates:(NSDictionary *)checkboxStates {
NSRange range = [rangeValue rangeValue];
NSMutableDictionary *statesInRange = [[NSMutableDictionary alloc] init];
for (NSNumber *key in checkboxStates) {
NSUInteger pos = [key unsignedIntegerValue];
if (pos >= range.location && pos < range.location + range.length) {
[statesInRange setObject:checkboxStates[key] forKey:key];
}
}
return statesInRange;
}
+ (NSString *_Nullable)initiallyProcessHtml:(NSString *_Nonnull)html
useHtmlNormalizer:(BOOL)useHtmlNormalizer {
NSString *htmlWithoutSpaces = [self stripExtraWhiteSpacesAndNewlines:html];
NSString *fixedHtml = nullptr;
if (htmlWithoutSpaces.length >= 13) {
NSString *firstSix =
[htmlWithoutSpaces substringWithRange:NSMakeRange(0, 6)];
NSString *lastSeven = [htmlWithoutSpaces
substringWithRange:NSMakeRange(htmlWithoutSpaces.length - 7, 7)];
if ([firstSix isEqualToString:@"<html>"] &&
[lastSeven isEqualToString:@"</html>"]) {
// remove html tags, might be with newlines or without them
fixedHtml = [htmlWithoutSpaces copy];
// firstly remove newlined html tags if any:
fixedHtml = [fixedHtml stringByReplacingOccurrencesOfString:@"<html>\n"
withString:@""];
fixedHtml = [fixedHtml stringByReplacingOccurrencesOfString:@"\n</html>"
withString:@""];
// fallback; remove html tags without their newlines
fixedHtml = [fixedHtml stringByReplacingOccurrencesOfString:@"<html>"
withString:@""];
fixedHtml = [fixedHtml stringByReplacingOccurrencesOfString:@"</html>"
withString:@""];
} else if (useHtmlNormalizer) {
// External HTML (from Google Docs, Word, web pages, etc.)
// Run through the Gumbo-based normalizer to convert arbitrary HTML
// into our canonical tag subset.
NSString *normalized = [self normalizeExternalHtml:html];
if (normalized != nil) {
fixedHtml = normalized;
}
}
// Additionally, try getting the content from between body tags if there are
// some:
// Firstly make sure there are no newlines between them.
fixedHtml = [fixedHtml stringByReplacingOccurrencesOfString:@"<body>\n"
withString:@"<body>"];
fixedHtml = [fixedHtml stringByReplacingOccurrencesOfString:@"\n</body>"
withString:@"</body>"];
// Then, if there actually are body tags, use the content between them.
NSRange openingBodyRange = [htmlWithoutSpaces rangeOfString:@"<body>"];
NSRange closingBodyRange = [htmlWithoutSpaces rangeOfString:@"</body>"];
if (openingBodyRange.length != 0 && closingBodyRange.length != 0) {
NSInteger newStart = openingBodyRange.location + 6;
NSInteger newEnd = closingBodyRange.location - 1;
fixedHtml = [htmlWithoutSpaces
substringWithRange:NSMakeRange(newStart, newEnd - newStart + 1)];
}
}
// second processing - try fixing htmls with wrong newlines' setup
if (fixedHtml != nullptr) {
// add <br> tag wherever needed
fixedHtml = [fixedHtml stringByReplacingOccurrencesOfString:@"<p></p>"
withString:@"<br>"];
// remove <p> tags inside of <li>
fixedHtml = [fixedHtml stringByReplacingOccurrencesOfString:@"<li><p>"
withString:@"<li>"];
fixedHtml = [fixedHtml stringByReplacingOccurrencesOfString:@"</p></li>"
withString:@"</li>"];
// change <br/> to <br>
fixedHtml = [fixedHtml stringByReplacingOccurrencesOfString:@"<br/>"
withString:@"<br>"];
// remove <p> tags around <br>
fixedHtml = [fixedHtml stringByReplacingOccurrencesOfString:@"<p><br>"
withString:@"<br>"];
fixedHtml = [fixedHtml stringByReplacingOccurrencesOfString:@"<br></p>"
withString:@"<br>"];
// add <br> tags inside empty blockquote and codeblock tags
fixedHtml = [fixedHtml
stringByReplacingOccurrencesOfString:@"<blockquote></blockquote>"
withString:@"<blockquote><br></"
@"blockquote>"];
fixedHtml = [fixedHtml
stringByReplacingOccurrencesOfString:@"<codeblock></codeblock>"
withString:@"<codeblock><br></codeblock>"];
// remove empty ul and ol tags
fixedHtml = [fixedHtml stringByReplacingOccurrencesOfString:@"<ul></ul>"
withString:@""];
fixedHtml = [fixedHtml
stringByReplacingOccurrencesOfString:@"<ul data-type=\"checkbox\"></ul>"
withString:@""];
fixedHtml = [fixedHtml stringByReplacingOccurrencesOfString:@"<ol></ol>"
withString:@""];
// tags that have to be in separate lines
fixedHtml = [self stringByAddingNewlinesToTag:@"<br>"
inString:fixedHtml
leading:YES
trailing:YES];
fixedHtml = [self stringByAddingNewlinesToTag:@"<ul>"
inString:fixedHtml
leading:YES
trailing:YES];
fixedHtml = [self stringByAddingNewlinesToTag:@"</ul>"
inString:fixedHtml
leading:YES
trailing:YES];
fixedHtml = [self stringByAddingNewlinesToTag:@"<ol>"
inString:fixedHtml
leading:YES
trailing:YES];
fixedHtml = [self stringByAddingNewlinesToTag:@"</ol>"
inString:fixedHtml
leading:YES
trailing:YES];
fixedHtml = [self stringByAddingNewlinesToTag:@"<blockquote>"
inString:fixedHtml
leading:YES
trailing:YES];
fixedHtml = [self stringByAddingNewlinesToTag:@"</blockquote>"
inString:fixedHtml
leading:YES
trailing:YES];
fixedHtml = [self stringByAddingNewlinesToTag:@"<codeblock>"
inString:fixedHtml
leading:YES
trailing:YES];
fixedHtml = [self stringByAddingNewlinesToTag:@"</codeblock>"
inString:fixedHtml
leading:YES
trailing:YES];
// line opening tags
fixedHtml = [self stringByAddingNewlinesToTag:@"<p>"
inString:fixedHtml
leading:YES
trailing:NO];
fixedHtml = [self stringByAddingNewlinesToTag:@"<li>"
inString:fixedHtml
leading:YES
trailing:NO];
fixedHtml = [self stringByAddingNewlinesToTag:@"<li checked>"
inString:fixedHtml
leading:YES
trailing:NO];
fixedHtml = [self stringByAddingNewlinesToTag:@"<h1>"
inString:fixedHtml
leading:YES
trailing:NO];
fixedHtml = [self stringByAddingNewlinesToTag:@"<h2>"
inString:fixedHtml
leading:YES
trailing:NO];
fixedHtml = [self stringByAddingNewlinesToTag:@"<h3>"
inString:fixedHtml
leading:YES
trailing:NO];
fixedHtml = [self stringByAddingNewlinesToTag:@"<h4>"
inString:fixedHtml
leading:YES
trailing:NO];
fixedHtml = [self stringByAddingNewlinesToTag:@"<h5>"
inString:fixedHtml
leading:YES
trailing:NO];
fixedHtml = [self stringByAddingNewlinesToTag:@"<h6>"
inString:fixedHtml
leading:YES
trailing:NO];
// line closing tags
fixedHtml = [self stringByAddingNewlinesToTag:@"</p>"
inString:fixedHtml
leading:NO
trailing:YES];
fixedHtml = [self stringByAddingNewlinesToTag:@"</li>"
inString:fixedHtml
leading:NO
trailing:YES];
fixedHtml = [self stringByAddingNewlinesToTag:@"</h1>"
inString:fixedHtml
leading:NO
trailing:YES];
fixedHtml = [self stringByAddingNewlinesToTag:@"</h2>"
inString:fixedHtml
leading:NO
trailing:YES];
fixedHtml = [self stringByAddingNewlinesToTag:@"</h3>"
inString:fixedHtml
leading:NO
trailing:YES];
fixedHtml = [self stringByAddingNewlinesToTag:@"</h4>"
inString:fixedHtml
leading:NO
trailing:YES];
fixedHtml = [self stringByAddingNewlinesToTag:@"</h5>"
inString:fixedHtml
leading:NO
trailing:YES];
fixedHtml = [self stringByAddingNewlinesToTag:@"</h6>"
inString:fixedHtml
leading:NO
trailing:YES];
}
return fixedHtml;
}
+ (NSArray *_Nonnull)getTextAndStylesFromHtml:(NSString *_Nonnull)fixedHtml {
NSMutableString *plainText = [[NSMutableString alloc] initWithString:@""];
NSMutableDictionary *ongoingTags = [[NSMutableDictionary alloc] init];
NSMutableArray *initiallyProcessedTags = [[NSMutableArray alloc] init];
NSMutableDictionary *checkboxStates = [[NSMutableDictionary alloc] init];
NSMutableArray<AlignmentEntry *> *foundAlignments =
[[NSMutableArray alloc] init];
BOOL insideCheckboxList = NO;
NSInteger precedingImageCount = 0;
BOOL insideTag = NO;
BOOL gettingTagName = NO;
BOOL gettingTagParams = NO;
BOOL closingTag = NO;
BOOL lastTagWasBr = NO;
NSMutableString *currentTagName =
[[NSMutableString alloc] initWithString:@""];
NSMutableString *currentTagParams =
[[NSMutableString alloc] initWithString:@""];
NSDictionary *htmlEntitiesDict =
[NSString getEscapedCharactersInfoFrom:fixedHtml];
// firstly, extract text and initially processed tags
for (int i = 0; i < fixedHtml.length; i++) {
NSString *currentCharacterStr =
[fixedHtml substringWithRange:NSMakeRange(i, 1)];
unichar currentCharacterChar = [fixedHtml characterAtIndex:i];
if (currentCharacterChar == '<') {
// opening the tag, mark that we are inside and getting its name
insideTag = YES;
gettingTagName = YES;
} else if (currentCharacterChar == '>') {
// finishing some tag, no longer marked as inside or getting its
// name/params
insideTag = NO;
gettingTagName = NO;
gettingTagParams = NO;
BOOL isSelfClosing = NO;
// Check if params ended with '/' (e.g. <img src="" />)
if ([currentTagParams hasSuffix:@"/"]) {
[currentTagParams
deleteCharactersInRange:NSMakeRange(currentTagParams.length - 1,
1)];
isSelfClosing = YES;
}
if ([currentTagName isEqualToString:@"br"]) {
lastTagWasBr = YES;
// do nothing, we don't include these tags in styles
} else if ([currentTagName isEqualToString:@"li"]) {
if (!closingTag) {
// Opening tag <li>
// Track checkbox state if we're inside a checkbox list
if (insideCheckboxList) {
BOOL isChecked = [currentTagParams containsString:@"checked"];
checkboxStates[@(plainText.length)] = @(isChecked);
}
// Record the start location so we can check if it's empty when
// closing
ongoingTags[@"li"] = @[ @(plainText.length) ];
} else {
// Closing tag </li>
NSArray *tagData = ongoingTags[@"li"];
if (tagData != nil) {
NSInteger tagLocation = [((NSNumber *)tagData[0]) intValue];
NSString *innerContent = [plainText substringFromIndex:tagLocation];
// If the li is completely empty (or just contains layout newlines),
// inject ZWS
if ([innerContent
stringByTrimmingCharactersInSet:[NSCharacterSet
newlineCharacterSet]]
.length == 0) {
[plainText appendString:@"\u200B"];
}
[ongoingTags removeObjectForKey:@"li"];
}
}
} else if (!closingTag) {
BOOL isPlainParagraph = [currentTagName isEqualToString:@"p"] &&
currentTagParams.length == 0;
if (!isPlainParagraph) {
// we finish opening tag - get its location, the current
// precedingImageCount and optionally params and put them under tag
// name key in ongoingTags. Storing the open-time image count lets
// finalizeTagEntry: correctly shift the start and extend the length
// so the range covers any images finalized between open and close.
NSMutableArray *tagArr = [[NSMutableArray alloc] init];
[tagArr addObject:[NSNumber numberWithInteger:plainText.length]];
[tagArr addObject:[NSNumber numberWithInteger:precedingImageCount]];
if (currentTagParams.length > 0) {
[tagArr addObject:[currentTagParams copy]];
}
ongoingTags[currentTagName] = tagArr;
// Check if this is a checkbox list
if ([currentTagName isEqualToString:@"ul"] &&
[self isUlCheckboxList:currentTagParams]) {
insideCheckboxList = YES;
}
// skip one newline if it was added after opening tags that are in
// separate lines
if ([self isBlockTag:currentTagName] && i + 1 < fixedHtml.length &&
[[NSCharacterSet newlineCharacterSet]
characterIsMember:[fixedHtml characterAtIndex:i + 1]]) {
i += 1;
}
if ([currentTagName isEqualToString:@"img"]) {
// Images have no inner text, so we manually break the <br> streak
// here.
lastTagWasBr = NO;
}
if (isSelfClosing) {
[self finalizeTagEntry:currentTagName
ongoingTags:ongoingTags
initiallyProcessedTags:initiallyProcessedTags
plainText:plainText
precedingImageCount:&precedingImageCount];
}
}
} else {
// we finish closing tags - pack tag name, tag range and optionally tag
// params into an entry that goes inside initiallyProcessedTags
// Check if we're closing a checkbox list by looking at the params
if ([currentTagName isEqualToString:@"ul"] &&
[self isUlCheckboxList:currentTagParams]) {
insideCheckboxList = NO;
}
BOOL isBlockTag = [self isBlockTag:currentTagName];
// ZWS logic for blockquote and codeblock
BOOL needsZWS = [currentTagName isEqualToString:@"blockquote"] ||
[currentTagName isEqualToString:@"codeblock"];
BOOL isEmptyBlock = NO;
if (needsZWS) {
NSArray *tagData = ongoingTags[currentTagName];
if (tagData != nil) {
NSInteger tagLoc = [tagData[0] intValue];
NSString *inner = [plainText substringFromIndex:tagLoc];
if ([inner stringByTrimmingCharactersInSet:[NSCharacterSet
newlineCharacterSet]]
.length == 0) {
isEmptyBlock = YES;
}
}
}
// skip one newline if it was added before some closing tags that are
// in separate lines
if (isBlockTag && plainText.length > 0 &&
[[NSCharacterSet newlineCharacterSet]
characterIsMember:[plainText
characterAtIndex:plainText.length - 1]]) {
// If the last thing processed was a <br>, or the block is totally
// empty, inject a \u200B before trimming the trailing newline to save
// the empty line.
if (lastTagWasBr || isEmptyBlock) {
[plainText insertString:@"\u200B" atIndex:plainText.length - 1];
}
plainText = [[plainText
substringWithRange:NSMakeRange(0, plainText.length - 1)]
mutableCopy];
}
[self checkForAlignments:ongoingTags[currentTagName]
plainText:plainText
foundAlignments:foundAlignments
precedingImageCount:precedingImageCount];
[self finalizeTagEntry:currentTagName
ongoingTags:ongoingTags
initiallyProcessedTags:initiallyProcessedTags
plainText:plainText
precedingImageCount:&precedingImageCount];
}
// post-tag cleanup
closingTag = NO;
currentTagName = [[NSMutableString alloc] initWithString:@""];
currentTagParams = [[NSMutableString alloc] initWithString:@""];
} else {
if (!insideTag) {
// no tags logic - just append the right text
// html entity on the index; use unescaped character and forward
// iterator accordingly
NSArray *entityInfo = htmlEntitiesDict[@(i)];
if (entityInfo != nullptr) {
NSString *escaped = entityInfo[0];
NSString *unescaped = entityInfo[1];
[plainText appendString:unescaped];
// the iterator will forward by 1 itself
i += escaped.length - 1;
} else {
[plainText appendString:currentCharacterStr];
// Any typed character that isn't a newline breaks the <br> streak
if (![[NSCharacterSet newlineCharacterSet]
characterIsMember:currentCharacterChar]) {
lastTagWasBr = NO;
}
}
} else {
if (gettingTagName) {
if (currentCharacterChar == ' ') {
// no longer getting tag name - switch to params
gettingTagName = NO;
gettingTagParams = YES;
} else if (currentCharacterChar == '/') {
// mark that the tag is closing
closingTag = YES;
} else {
// append next tag char
[currentTagName appendString:currentCharacterStr];
}
} else if (gettingTagParams) {
// append next tag params char
[currentTagParams appendString:currentCharacterStr];
}
}
}
}
// process tags into proper StyleType + StylePair values
NSMutableArray *processedStyles = [[NSMutableArray alloc] init];
// Tracks the number of processed images to remove their pre-generated
// placeholder offsets from tag ranges when reading from plainText
// (which does not contain those placeholders).
NSInteger secondPassImageCount = 0;
for (NSArray *arr in initiallyProcessedTags) {
NSString *tagName = (NSString *)arr[0];
NSValue *tagRangeValue = (NSValue *)arr[1];
NSMutableString *params = [[NSMutableString alloc] initWithString:@""];
if (arr.count > 2) {
[params appendString:(NSString *)arr[2]];
}
NSMutableArray *styleArr = [[NSMutableArray alloc] init];
StylePair *stylePair = [[StylePair alloc] init];
if ([tagName isEqualToString:@"b"]) {
[styleArr addObject:@([BoldStyle getType])];
} else if ([tagName isEqualToString:@"i"]) {
[styleArr addObject:@([ItalicStyle getType])];
} else if ([tagName isEqualToString:@"img"]) {
NSRegularExpression *srcRegex =
[NSRegularExpression regularExpressionWithPattern:@"src=\"([^\"]+)\""
options:0
error:nullptr];
NSTextCheckingResult *match =
[srcRegex firstMatchInString:params
options:0
range:NSMakeRange(0, params.length)];
if (match == nullptr) {
continue;
}
NSRange srcRange = match.range;
[styleArr addObject:@([ImageStyle getType])];
// cut only the uri from the src="..." string
NSString *uri =
[params substringWithRange:NSMakeRange(srcRange.location + 5,
srcRange.length - 6)];
ImageData *imageData = [[ImageData alloc] init];
imageData.uri = uri;
NSRegularExpression *widthRegex = [NSRegularExpression
regularExpressionWithPattern:@"width=\"([0-9.]+)\""
options:0
error:nil];
NSTextCheckingResult *widthMatch =
[widthRegex firstMatchInString:params
options:0
range:NSMakeRange(0, params.length)];
if (widthMatch) {
NSString *widthString =
[params substringWithRange:[widthMatch rangeAtIndex:1]];
imageData.width = [widthString floatValue];
}
NSRegularExpression *heightRegex = [NSRegularExpression
regularExpressionWithPattern:@"height=\"([0-9.]+)\""
options:0
error:nil];
NSTextCheckingResult *heightMatch =
[heightRegex firstMatchInString:params
options:0
range:NSMakeRange(0, params.length)];
if (heightMatch) {
NSString *heightString =
[params substringWithRange:[heightMatch rangeAtIndex:1]];
imageData.height = [heightString floatValue];
}
stylePair.styleValue = imageData;
secondPassImageCount++;
} else if ([tagName isEqualToString:@"u"]) {
[styleArr addObject:@([UnderlineStyle getType])];
} else if ([tagName isEqualToString:@"s"]) {
[styleArr addObject:@([StrikethroughStyle getType])];
} else if ([tagName isEqualToString:@"code"]) {
[styleArr addObject:@([InlineCodeStyle getType])];
} else if ([tagName isEqualToString:@"a"]) {
NSRegularExpression *hrefRegex =
[NSRegularExpression regularExpressionWithPattern:@"href=\".+\""
options:0
error:nullptr];
NSTextCheckingResult *match =
[hrefRegex firstMatchInString:params
options:0
range:NSMakeRange(0, params.length)];
if (match == nullptr) {
// same as on Android, no href (or empty href) equals no link style
continue;
}
NSRange hrefRange = match.range;
[styleArr addObject:@([LinkStyle getType])];
// cut only the url from the href="..." string
NSString *url =
[params substringWithRange:NSMakeRange(hrefRange.location + 6,
hrefRange.length - 7)];
// tagRange location includes one extra offset per preceding image
// placeholder, which don't exist in plainText. Subtract them to map
// back to the correct plainText index.
NSRange adjustedRange = tagRangeValue.rangeValue;
NSRange plainTextRange = NSMakeRange(
adjustedRange.location - secondPassImageCount, adjustedRange.length);
NSString *text = [plainText substringWithRange:plainTextRange];
LinkData *linkData = [[LinkData alloc] init];
linkData.url = url;
linkData.text = text;
linkData.isManual = ![text isEqualToString:url];
stylePair.styleValue = linkData;
} else if ([tagName isEqualToString:@"mention"]) {
[styleArr addObject:@([MentionStyle getType])];
// extract html expression into dict using some regex
NSMutableDictionary *paramsDict = [[NSMutableDictionary alloc] init];
NSString *pattern = @"(\\w+)=(['\"])(.*?)\\2";
NSRegularExpression *regex =
[NSRegularExpression regularExpressionWithPattern:pattern
options:0
error:nil];
[regex enumerateMatchesInString:params
options:0
range:NSMakeRange(0, params.length)
usingBlock:^(NSTextCheckingResult *_Nullable result,
NSMatchingFlags flags,
BOOL *_Nonnull stop) {
if (result.numberOfRanges == 4) {
NSString *key = [params
substringWithRange:[result rangeAtIndex:1]];
NSString *value = [params
substringWithRange:[result rangeAtIndex:3]];
paramsDict[key] = value;
}
}];
MentionParams *mentionParams = [[MentionParams alloc] init];
mentionParams.text = paramsDict[@"text"];
mentionParams.indicator = paramsDict[@"indicator"];
[paramsDict removeObjectsForKeys:@[ @"text", @"indicator" ]];
NSError *error;
NSData *attrsData = [NSJSONSerialization dataWithJSONObject:paramsDict
options:0
error:&error];
NSString *formattedAttrsString =
[[NSString alloc] initWithData:attrsData
encoding:NSUTF8StringEncoding];
mentionParams.attributes = formattedAttrsString;
stylePair.styleValue = mentionParams;
} else if ([tagName isEqualToString:@"h1"]) {
[styleArr addObject:@([H1Style getType])];
} else if ([tagName isEqualToString:@"h2"]) {
[styleArr addObject:@([H2Style getType])];
} else if ([tagName isEqualToString:@"h3"]) {
[styleArr addObject:@([H3Style getType])];
} else if ([tagName isEqualToString:@"h4"]) {
[styleArr addObject:@([H4Style getType])];
} else if ([tagName isEqualToString:@"h5"]) {
[styleArr addObject:@([H5Style getType])];
} else if ([tagName isEqualToString:@"h6"]) {
[styleArr addObject:@([H6Style getType])];
} else if ([tagName isEqualToString:@"ul"]) {
if ([self isUlCheckboxList:params]) {
[styleArr addObject:@([CheckboxListStyle getType])];
stylePair.styleValue =
[self prepareCheckboxListStyleValue:tagRangeValue
checkboxStates:checkboxStates];
} else {
[styleArr addObject:@([UnorderedListStyle getType])];
}
} else if ([tagName isEqualToString:@"ol"]) {
[styleArr addObject:@([OrderedListStyle getType])];
} else if ([tagName isEqualToString:@"blockquote"]) {
[styleArr addObject:@([BlockQuoteStyle getType])];
} else if ([tagName isEqualToString:@"codeblock"]) {
[styleArr addObject:@([CodeBlockStyle getType])];
} else {
// some other external tags like span just don't get put into the
// processed styles
continue;
}
stylePair.rangeValue = tagRangeValue;
[styleArr addObject:stylePair];
[processedStyles addObject:styleArr];
}
return @[ plainText, processedStyles, foundAlignments ];
}
+ (NSString *)parseToHtmlFromRange:(NSRange)range
host:(id<EnrichedViewHost>)host {
NSInteger offset = range.location;
NSString *text = [host.textView.textStorage.string substringWithRange:range];
if (text.length == 0) {
return @"<html>\n<p></p>\n</html>";
}
NSMutableString *result = [[NSMutableString alloc] initWithString:@"<html>"];
NSSet<NSNumber *> *previousActiveStyles = [[NSSet<NSNumber *> alloc] init];
BOOL newLine = YES;
BOOL inUnorderedList = NO;
BOOL inOrderedList = NO;
BOOL inBlockQuote = NO;
BOOL inCodeBlock = NO;
BOOL inCheckboxList = NO;
unichar lastCharacter = 0;
for (int i = 0; i < text.length; i++) {
NSRange currentRange = NSMakeRange(offset + i, 1);
NSMutableSet<NSNumber *> *currentActiveStyles =
[[NSMutableSet<NSNumber *> alloc] init];
NSMutableDictionary *currentActiveStylesBeginning =
[[NSMutableDictionary alloc] init];
// check each existing style existence
for (NSNumber *type in host.stylesDict) {
StyleBase *style = host.stylesDict[type];
// we do not want to add <></> tags for alignment
if ([style isKindOfClass:[AlignmentStyle class]]) {
continue;
}
if ([style detect:currentRange]) {
[currentActiveStyles addObject:type];
if (![previousActiveStyles member:type]) {
currentActiveStylesBeginning[type] = [NSNumber numberWithInt:i];
}
} else if ([previousActiveStyles member:type]) {
[currentActiveStylesBeginning removeObjectForKey:type];
}
}
NSString *currentCharacterStr =
[host.textView.textStorage.string substringWithRange:currentRange];
unichar currentCharacterChar = [host.textView.textStorage.string
characterAtIndex:currentRange.location];
if ([[NSCharacterSet newlineCharacterSet]
characterIsMember:currentCharacterChar]) {
if (newLine) {
// we can either have an empty list item OR need to close the list and
// put a BR in such a situation the existence of the list must be
// checked on 0 length range, not on the newline character
if (inOrderedList) {
OrderedListStyle *oStyle = host.stylesDict[@(OrderedList)];
BOOL detected = [oStyle detect:NSMakeRange(currentRange.location, 0)];
if (detected) {
[result appendString:@"\n<li></li>"];
} else {
[result appendString:@"\n</ol>\n<br>"];
inOrderedList = NO;
}
} else if (inUnorderedList) {
UnorderedListStyle *uStyle = host.stylesDict[@(UnorderedList)];
BOOL detected = [uStyle detect:NSMakeRange(currentRange.location, 0)];
if (detected) {
[result appendString:@"\n<li></li>"];
} else {
[result appendString:@"\n</ul>\n<br>"];
inUnorderedList = NO;
}
} else if (inBlockQuote) {
BlockQuoteStyle *bqStyle = host.stylesDict[@(BlockQuote)];
BOOL detected =
[bqStyle detect:NSMakeRange(currentRange.location, 0)];
if (detected) {
[result appendString:@"\n<br>"];
} else {
[result appendString:@"\n</blockquote>\n<br>"];
inBlockQuote = NO;
}
} else if (inCodeBlock) {
CodeBlockStyle *cbStyle = host.stylesDict[@(CodeBlock)];
BOOL detected =
[cbStyle detect:NSMakeRange(currentRange.location, 0)];
if (detected) {
[result appendString:@"\n<br>"];
} else {
[result appendString:@"\n</codeblock>\n<br>"];
inCodeBlock = NO;
}
} else if (inCheckboxList) {
CheckboxListStyle *cbLStyle = host.stylesDict[@(CheckboxList)];
BOOL detected =
[cbLStyle detect:NSMakeRange(currentRange.location, 0)];
if (detected) {
BOOL checked = [cbLStyle getCheckboxStateAt:currentRange.location];
if (checked) {
[result appendString:@"\n<li checked></li>"];
} else {
[result appendString:@"\n<li></li>"];
}
} else {
[result appendString:@"\n</ul>\n<br>"];
inCheckboxList = NO;
}
} else {
[result appendString:@"\n<br>"];
}
} else {
// newline finishes a paragraph and all style tags need to be closed
// we use previous styles
NSArray<NSNumber *> *sortedEndedStyles = [previousActiveStyles
sortedArrayUsingDescriptors:@[ [NSSortDescriptor
sortDescriptorWithKey:@"intValue"
ascending:NO] ]];
// append closing tags
for (NSNumber *style in sortedEndedStyles) {
if ([style isEqualToNumber:@([ImageStyle getType])]) {
continue;
}
NSString *tagContent = [self tagContentForStyle:style
openingTag:NO
location:currentRange.location
host:host];
[result
appendString:[NSString stringWithFormat:@"</%@>", tagContent]];
}
// append closing paragraph tag
if ([previousActiveStyles
containsObject:@([UnorderedListStyle getType])] ||
[previousActiveStyles
containsObject:@([OrderedListStyle getType])] ||
[previousActiveStyles containsObject:@([H1Style getType])] ||
[previousActiveStyles containsObject:@([H2Style getType])] ||
[previousActiveStyles containsObject:@([H3Style getType])] ||
[previousActiveStyles containsObject:@([H4Style getType])] ||
[previousActiveStyles containsObject:@([H5Style getType])] ||
[previousActiveStyles containsObject:@([H6Style getType])] ||
[previousActiveStyles
containsObject:@([BlockQuoteStyle getType])] ||
[previousActiveStyles containsObject:@([CodeBlockStyle getType])] ||
[previousActiveStyles
containsObject:@([CheckboxListStyle getType])]) {
// do nothing, proper closing paragraph tags have been already
// appended
} else {
[result appendString:@"</p>"];
}
}