-
Notifications
You must be signed in to change notification settings - Fork 61
/
RCTMarkdownUtils.mm
205 lines (174 loc) · 11.1 KB
/
RCTMarkdownUtils.mm
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
#import <RNLiveMarkdown/RCTMarkdownUtils.h>
#import "react_native_assert.h"
#import <React/RCTAssert.h>
#import <React/RCTFont.h>
#include <jsi/jsi.h>
#include <hermes/hermes.h>
using namespace facebook;
@implementation RCTMarkdownUtils
- (void)applyFormatting:(nonnull NSMutableAttributedString *)attributedString withDefaultTextAttributes:(nonnull NSDictionary<NSAttributedStringKey,id> *)defaultTextAttributes
{
static std::shared_ptr<jsi::Runtime> runtime;
static std::mutex runtimeMutex;
auto lock = std::lock_guard<std::mutex>(runtimeMutex);
if (runtime == nullptr) {
NSString *path = [[NSBundle mainBundle] pathForResource:@"react-native-live-markdown-parser" ofType:@"js"];
assert(path != nil && "[react-native-live-markdown] Markdown parser bundle not found");
NSString *content = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:NULL];
assert(content != nil && "[react-native-live-markdown] Markdown parser bundle is empty");
runtime = facebook::hermes::makeHermesRuntime();
auto codeBuffer = std::make_shared<const jsi::StringBuffer>([content UTF8String]);
runtime->evaluateJavaScript(codeBuffer, "evaluateJavaScript");
}
jsi::Runtime &rt = *runtime;
auto text = jsi::String::createFromUtf8(rt, attributedString.string.UTF8String);
auto func = rt.global().getPropertyAsFunction(rt, "parseExpensiMarkToRanges");
auto output = func.call(rt, text);
// TODO: memoize parser output
const auto &ranges = output.asObject(rt).asArray(rt);
NSRange fullRange = NSMakeRange(0, attributedString.length);
[attributedString beginEditing];
[attributedString addAttributes:defaultTextAttributes range:fullRange];
_blockquoteRangesAndLevels = [NSMutableArray new];
// TODO: use custom attribute to mark blockquotes
for (size_t i = 0, n = ranges.size(rt); i < n; ++i) {
const auto &item = ranges.getValueAtIndex(rt, i).asObject(rt);
const auto &type = item.getProperty(rt, "type").asString(rt).utf8(rt);
const auto &start = static_cast<int>(item.getProperty(rt, "start").asNumber());
const auto &length = static_cast<int>(item.getProperty(rt, "length").asNumber());
const auto &depth = item.hasProperty(rt, "depth") ? static_cast<int>(item.getProperty(rt, "depth").asNumber()) : 1;
[self applyRangeToAttributedString:attributedString type:type start:start length:length depth:depth];
}
RCTApplyBaselineOffset(attributedString);
/*
Calling `[attributedString addAttributes:defaultTextAttributes range:fullRange]` breaks the font for emojis.
Before, NSFont attribute is ".SFUI-Regular" and NSOriginalFont attribute is ".AppleColorEmoji".
After the call, both are set to ".SFUI-Regular" which makes emoji invisible and zero-width.
Calling `fixAttributesInRange:` fixes this problem.
*/
[attributedString fixAttributesInRange:fullRange];
/*
When updating MarkdownTextInput's `style` property without changing `markdownStyle`,
React Native calls `[RCTTextInputComponentView _setAttributedString:]` which skips update if strings are equal.
See https://github.com/facebook/react-native/blob/287e20033207df5e59d199a347b7ae2b4cd7a59e/packages/react-native/React/Fabric/Mounting/ComponentViews/TextInput/RCTTextInputComponentView.mm#L680-L684
The attributed strings are compared using `[RCTTextInputComponentView _textOf:equals:]` which compares only raw strings
if NSOriginalFont attribute is present. So we purposefully remove this attribute to force update.
See https://github.com/facebook/react-native/blob/287e20033207df5e59d199a347b7ae2b4cd7a59e/packages/react-native/React/Fabric/Mounting/ComponentViews/TextInput/RCTTextInputComponentView.mm#L751-L784
*/
[attributedString removeAttribute:@"NSOriginalFont" range:fullRange];
[attributedString endEditing];
}
- (void)applyRangeToAttributedString:(NSMutableAttributedString *)attributedString type:(const std::string)type start:(const int)start length:(const int)length depth:(const int)depth {
if (length == 0 || start + length > attributedString.length) {
return;
}
NSRange range = NSMakeRange(start, length);
if (type == "bold" || type == "italic" || type == "code" || type == "pre" || type == "h1" || type == "emoji") {
UIFont *font = [attributedString attribute:NSFontAttributeName atIndex:start effectiveRange:NULL];
if (type == "bold") {
font = [RCTFont updateFont:font withWeight:@"bold"];
} else if (type == "italic") {
font = [RCTFont updateFont:font withStyle:@"italic"];
} else if (type == "code") {
font = [RCTFont updateFont:font withFamily:_markdownStyle.codeFontFamily
size:[NSNumber numberWithFloat:_markdownStyle.codeFontSize]
weight:nil
style:nil
variant:nil
scaleMultiplier:0];
} else if (type == "pre") {
font = [RCTFont updateFont:font withFamily:_markdownStyle.preFontFamily
size:[NSNumber numberWithFloat:_markdownStyle.preFontSize]
weight:nil
style:nil
variant:nil
scaleMultiplier:0];
} else if (type == "h1") {
font = [RCTFont updateFont:font withFamily:nil
size:[NSNumber numberWithFloat:_markdownStyle.h1FontSize]
weight:@"bold"
style:nil
variant:nil
scaleMultiplier:0];
} else if (type == "emoji") {
font = [RCTFont updateFont:font withFamily:nil
size:[NSNumber numberWithFloat:_markdownStyle.emojiFontSize]
weight:nil
style:nil
variant:nil
scaleMultiplier:0];
}
[attributedString addAttribute:NSFontAttributeName value:font range:range];
}
if (type == "syntax") {
[attributedString addAttribute:NSForegroundColorAttributeName value:_markdownStyle.syntaxColor range:range];
} else if (type == "strikethrough") {
[attributedString addAttribute:NSStrikethroughStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:range];
} else if (type == "code") {
[attributedString addAttribute:NSForegroundColorAttributeName value:_markdownStyle.codeColor range:range];
[attributedString addAttribute:NSBackgroundColorAttributeName value:_markdownStyle.codeBackgroundColor range:range];
} else if (type == "mention-here") {
[attributedString addAttribute:NSForegroundColorAttributeName value:_markdownStyle.mentionHereColor range:range];
[attributedString addAttribute:NSBackgroundColorAttributeName value:_markdownStyle.mentionHereBackgroundColor range:range];
} else if (type == "mention-user") {
// TODO: change mention color when it mentions current user
[attributedString addAttribute:NSForegroundColorAttributeName value:_markdownStyle.mentionUserColor range:range];
[attributedString addAttribute:NSBackgroundColorAttributeName value:_markdownStyle.mentionUserBackgroundColor range:range];
} else if (type == "mention-report") {
[attributedString addAttribute:NSForegroundColorAttributeName value:_markdownStyle.mentionReportColor range:range];
[attributedString addAttribute:NSBackgroundColorAttributeName value:_markdownStyle.mentionReportBackgroundColor range:range];
} else if (type == "link") {
[attributedString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:range];
[attributedString addAttribute:NSForegroundColorAttributeName value:_markdownStyle.linkColor range:range];
} else if (type == "blockquote") {
CGFloat indent = (_markdownStyle.blockquoteMarginLeft + _markdownStyle.blockquoteBorderWidth + _markdownStyle.blockquotePaddingLeft) * depth;
NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
paragraphStyle.firstLineHeadIndent = indent;
paragraphStyle.headIndent = indent;
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:range];
[_blockquoteRangesAndLevels addObject:@{
@"range": [NSValue valueWithRange:range],
@"depth": @(depth)
}];
} else if (type == "pre") {
[attributedString addAttribute:NSForegroundColorAttributeName value:_markdownStyle.preColor range:range];
NSRange rangeForBackground = [[attributedString string] characterAtIndex:range.location] == '\n' ? NSMakeRange(range.location + 1, range.length - 1) : range;
[attributedString addAttribute:NSBackgroundColorAttributeName value:_markdownStyle.preBackgroundColor range:rangeForBackground];
// TODO: pass background color and ranges to layout manager
}
}
static void RCTApplyBaselineOffset(NSMutableAttributedString *attributedText)
{
__block CGFloat maximumLineHeight = 0;
[attributedText enumerateAttribute:NSParagraphStyleAttributeName
inRange:NSMakeRange(0, attributedText.length)
options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired
usingBlock:^(NSParagraphStyle *paragraphStyle, __unused NSRange range, __unused BOOL *stop) {
if (!paragraphStyle) {
return;
}
maximumLineHeight = MAX(paragraphStyle.maximumLineHeight, maximumLineHeight);
}];
if (maximumLineHeight == 0) {
// `lineHeight` was not specified, nothing to do.
return;
}
__block CGFloat maximumFontLineHeight = 0;
[attributedText enumerateAttribute:NSFontAttributeName
inRange:NSMakeRange(0, attributedText.length)
options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired
usingBlock:^(UIFont *font, NSRange range, __unused BOOL *stop) {
if (!font) {
return;
}
maximumFontLineHeight = MAX(font.lineHeight, maximumFontLineHeight);
}];
if (maximumLineHeight < maximumFontLineHeight) {
return;
}
CGFloat baseLineOffset = (maximumLineHeight - maximumFontLineHeight) / 2.0;
[attributedText addAttribute:NSBaselineOffsetAttributeName
value:@(baseLineOffset)
range:NSMakeRange(0, attributedText.length)];
}
@end