Open History to see the last commit
1#include "T3MarkdownTextShadowNode.h"
2#include "T3MarkdownTextRunShadowNode.h"
3#import "T3ContextChip.h"
4#include <react/renderer/components/view/ViewShadowNode.h>
5#import <react/renderer/textlayoutmanager/RCTAttributedTextUtils.h>
6
7#include <algorithm>
8#include <cmath>
9
10namespace facebook::react {
11
12static constexpr Float ParagraphStyleEncodingOffset = 1000;
13static constexpr auto FileAttachmentNativeIdPrefix = "t3-file:";
14static constexpr auto SkillAttachmentNativeIdPrefix = "t3-skill:";
15static constexpr auto LinkAttachmentNativeIdPrefix = "t3-link:";
16
17static void applyParagraphStyles(
18 NSMutableAttributedString *attributedString,
19 const std::vector<T3MarkdownTextParagraphStyleRange> &styleRanges)
20{
21 for (const auto &styleRange : styleRanges) {
22 if (styleRange.length == 0 || styleRange.location >= attributedString.length) {
23 continue;
24 }
25
26 const NSRange markerRange = NSMakeRange(
27 styleRange.location,
28 MIN(styleRange.length, attributedString.length - styleRange.location));
29 const NSRange paragraphRange = [attributedString.string paragraphRangeForRange:markerRange];
30 const NSParagraphStyle *existingStyle =
31 [attributedString attribute:NSParagraphStyleAttributeName
32 atIndex:paragraphRange.location
33 effectiveRange:nil];
34 NSMutableParagraphStyle *paragraphStyle =
35 existingStyle ? [existingStyle mutableCopy] : [NSMutableParagraphStyle new];
36 paragraphStyle.firstLineHeadIndent = styleRange.firstLineHeadIndent;
37 paragraphStyle.headIndent = styleRange.headIndent;
38 paragraphStyle.paragraphSpacing = styleRange.paragraphSpacing;
39 paragraphStyle.tabStops = @[
40 [[NSTextTab alloc] initWithTextAlignment:NSTextAlignmentLeft
41 location:styleRange.headIndent
42 options:@{}]
43 ];
44 paragraphStyle.defaultTabInterval = styleRange.headIndent;
45 [attributedString addAttribute:NSParagraphStyleAttributeName
46 value:paragraphStyle
47 range:paragraphRange];
48 }
49}
50
51static void applyAttachments(
52 NSMutableAttributedString *attributedString,
53 const std::vector<T3MarkdownTextAttachmentRange> &attachmentRanges)
54{
55 for (const auto &attachmentRange : attachmentRanges) {
56 if (attachmentRange.length == 0 || attachmentRange.location >= attributedString.length) {
57 continue;
58 }
59
60 NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
61 attachment.image = [[UIImage alloc] init];
62 const CGFloat attachmentSize = T3MarkdownTextAttachmentSize(attachmentRange);
63 attachment.bounds = CGRectMake(
64 0,
65 T3MarkdownTextAttachmentBaselineOffset(attachmentRange),
66 attachmentSize,
67 attachmentSize);
68 NSDictionary *runAttributes =
69 [attributedString attributesAtIndex:attachmentRange.location effectiveRange:nil];
70 if (attachmentRange.chipWidth > 0) {
71 attachment.bounds = T3ContextChipBounds(
72 runAttributes[NSFontAttributeName],
73 CGSizeMake(attachmentRange.chipWidth, attachmentRange.chipHeight));
74 }
75 const NSRange range = NSMakeRange(
76 attachmentRange.location,
77 MIN(attachmentRange.length, attributedString.length - attachmentRange.location));
78 [attributedString replaceCharactersInRange:range
79 withAttributedString:T3MarkdownTextAttachmentString(attachment, runAttributes)];
80 }
81}
82
83T3MarkdownTextShadowNode::T3MarkdownTextShadowNode(
84 const ShadowNode& sourceShadowNode,
85 const ShadowNodeFragment& fragment
86) : ConcreteViewShadowNode(sourceShadowNode, fragment) {
87};
88
89Size T3MarkdownTextShadowNode::measureContent(
90 const LayoutContext& layoutContext,
91 const LayoutConstraints& layoutConstraints) const {
92 const auto &baseProps = getConcreteProps();
93
94 auto baseTextAttributes = TextAttributes::defaultTextAttributes();
95 baseTextAttributes.backgroundColor = baseProps.backgroundColor;
96 baseTextAttributes.allowFontScaling = baseProps.allowFontScaling;
97
98 Float fontSizeMultiplier = 1.0;
99 if (baseTextAttributes.allowFontScaling) {
100 fontSizeMultiplier = layoutContext.fontSizeMultiplier;
101 }
102
103 auto baseAttributedString = AttributedString{};
104 auto paragraphStyleRanges = std::vector<T3MarkdownTextParagraphStyleRange>{};
105 auto attachmentRanges = std::vector<T3MarkdownTextAttachmentRange>{};
106 size_t utf16Offset = 0;
107 const auto &children = getChildren();
108 for (size_t i = 0; i < children.size(); i++) {
109 const auto child = children[i].get();
110 if (auto textViewChild = dynamic_cast<const T3MarkdownTextRunShadowNode *>(child)) {
111 auto &props = textViewChild->getConcreteProps();
112 auto fragment = AttributedString::Fragment{};
113 auto textAttributes = TextAttributes::defaultTextAttributes();
114
115 textAttributes.allowFontScaling = baseProps.allowFontScaling;
116 textAttributes.backgroundColor = props.backgroundColor;
117 textAttributes.fontSize = props.fontSize * fontSizeMultiplier;
118 textAttributes.lineHeight = props.lineHeight * fontSizeMultiplier;
119 textAttributes.foregroundColor = props.color;
120 const bool hasParagraphStyle = props.shadowRadius >= ParagraphStyleEncodingOffset;
121 if (!hasParagraphStyle) {
122 textAttributes.textShadowColor = props.shadowColor;
123 textAttributes.textShadowOffset = props.shadowOffset;
124 textAttributes.textShadowRadius = props.shadowRadius;
125 }
126 textAttributes.letterSpacing = props.letterSpacing;
127 textAttributes.textDecorationColor = props.textDecorationColor;
128 textAttributes.fontFamily = props.fontFamily;
129
130 if (props.fontStyle == T3MarkdownTextRunFontStyle::Italic) {
131 textAttributes.fontStyle = FontStyle::Italic;
132 } else {
133 textAttributes.fontStyle = FontStyle::Normal;
134 }
135
136 if (props.fontWeight == T3MarkdownTextRunFontWeight::Bold) {
137 textAttributes.fontWeight = FontWeight::Bold;
138 } else if (props.fontWeight == T3MarkdownTextRunFontWeight::UltraLight) {
139 textAttributes.fontWeight = FontWeight::UltraLight;
140 } else if (props.fontWeight == T3MarkdownTextRunFontWeight::Light) {
141 textAttributes.fontWeight = FontWeight::Light;
142 } else if (props.fontWeight == T3MarkdownTextRunFontWeight::Medium) {
143 textAttributes.fontWeight = FontWeight::Medium;
144 } else if (props.fontWeight == T3MarkdownTextRunFontWeight::Semibold) {
145 textAttributes.fontWeight = FontWeight::Semibold;
146 } else if (props.fontWeight == T3MarkdownTextRunFontWeight::Heavy) {
147 textAttributes.fontWeight = FontWeight::Heavy;
148 } else {
149 textAttributes.fontWeight = FontWeight::Regular;
150 }
151
152 if (props.textDecorationLine == T3MarkdownTextRunTextDecorationLine::LineThrough) {
153 textAttributes.textDecorationLineType = TextDecorationLineType::Strikethrough;
154 } else if (props.textDecorationLine == T3MarkdownTextRunTextDecorationLine::Underline) {
155 textAttributes.textDecorationLineType = TextDecorationLineType::Underline;
156 } else {
157 textAttributes.textDecorationLineType = TextDecorationLineType::None;
158 }
159
160 if (props.textDecorationStyle == T3MarkdownTextRunTextDecorationStyle::Solid) {
161 textAttributes.textDecorationStyle = TextDecorationStyle::Solid;
162 } else if (props.textDecorationStyle == T3MarkdownTextRunTextDecorationStyle::Dotted) {
163 textAttributes.textDecorationStyle = TextDecorationStyle::Dotted;
164 } else if (props.textDecorationStyle == T3MarkdownTextRunTextDecorationStyle::Dashed) {
165 textAttributes.textDecorationStyle = TextDecorationStyle::Dashed;
166 } else if (props.textDecorationStyle == T3MarkdownTextRunTextDecorationStyle::Double) {
167 textAttributes.textDecorationStyle = TextDecorationStyle::Double;
168 }
169
170 if (props.textAlign == T3MarkdownTextRunTextAlign::Left) {
171 textAttributes.alignment = TextAlignment::Left;
172 } else if (props.textAlign == T3MarkdownTextRunTextAlign::Right) {
173 textAttributes.alignment = TextAlignment::Right;
174 } else if (props.textAlign == T3MarkdownTextRunTextAlign::Center) {
175 textAttributes.alignment = TextAlignment::Center;
176 } else if (props.textAlign == T3MarkdownTextRunTextAlign::Justify) {
177 textAttributes.alignment = TextAlignment::Justified;
178 } else if (props.textAlign == T3MarkdownTextRunTextAlign::Auto) {
179 textAttributes.alignment = TextAlignment::Natural;
180 }
181
182 textAttributes.backgroundColor = props.backgroundColor;
183
184 fragment.string = props.text;
185 fragment.textAttributes = textAttributes;
186
187 NSString *fragmentText = [NSString stringWithUTF8String:props.text.c_str()];
188 const size_t fragmentLength = fragmentText.length;
189 if (hasParagraphStyle) {
190 paragraphStyleRanges.push_back(T3MarkdownTextParagraphStyleRange{
191 utf16Offset,
192 fragmentLength,
193 props.shadowOffset.width,
194 props.shadowOffset.height,
195 props.shadowRadius - ParagraphStyleEncodingOffset,
196 });
197 }
198 if (props.nativeId.rfind("t3-chip:", 0) == 0 && fragmentLength > 0) {
199 const std::string uri = props.nativeId.substr(3);
200 NSMutableDictionary *payload =
201 [T3ContextChipPayload([NSString stringWithUTF8String:uri.c_str()]) mutableCopy];
202 // Chips must scale with the paragraph or smaller Dynamic Type sizes clip them.
203 // Store the scaled payload so measurement and the rendered bitmap use the same font.
204 payload[@"fontSizeMultiplier"] = @(fontSizeMultiplier);
205 NSData *data = [NSJSONSerialization dataWithJSONObject:payload options:0 error:nil];
206 NSString *scaledUri = [@"chip:" stringByAppendingString:
207 [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]];
208 const CGFloat maxWidth = std::isfinite(layoutConstraints.maximumSize.width)
209 ? layoutConstraints.maximumSize.width : 320;
210 const CGSize size = T3ContextChipSize(payload, maxWidth);
211 attachmentRanges.push_back(T3MarkdownTextAttachmentRange{
212 utf16Offset, 1, std::string(scaledUri.UTF8String), false,
213 static_cast<Float>(size.width), static_cast<Float>(size.height),
214 });
215 } else if (props.nativeId.rfind(FileAttachmentNativeIdPrefix, 0) == 0 && fragmentLength > 0) {
216 attachmentRanges.push_back(T3MarkdownTextAttachmentRange{
217 utf16Offset,
218 1,
219 props.nativeId.substr(std::char_traits<char>::length(FileAttachmentNativeIdPrefix)),
220 false,
221 });
222 } else if (
223 props.nativeId.rfind(SkillAttachmentNativeIdPrefix, 0) == 0 && fragmentLength > 0) {
224 attachmentRanges.push_back(T3MarkdownTextAttachmentRange{
225 utf16Offset,
226 1,
227 props.nativeId.substr(
228 std::char_traits<char>::length(SkillAttachmentNativeIdPrefix)),
229 false,
230 });
231 } else if (
232 props.nativeId.rfind(LinkAttachmentNativeIdPrefix, 0) == 0 && fragmentLength > 0) {
233 attachmentRanges.push_back(T3MarkdownTextAttachmentRange{
234 utf16Offset,
235 1,
236 props.nativeId.substr(std::char_traits<char>::length(LinkAttachmentNativeIdPrefix)),
237 true,
238 });
239 }
240 utf16Offset += fragmentLength;
241 baseAttributedString.appendFragment(std::move(fragment));
242 }
243 }
244
245 _attributedString = baseAttributedString;
246 _paragraphStyleRanges = paragraphStyleRanges;
247 _attachmentRanges = attachmentRanges;
248
249 NSMutableAttributedString *convertedAttributedString =
250 [RCTNSAttributedStringFromAttributedString(baseAttributedString) mutableCopy];
251 applyParagraphStyles(convertedAttributedString, paragraphStyleRanges);
252 applyAttachments(convertedAttributedString, attachmentRanges);
253 // TextKit stacks a paragraph's extra line height above the glyphs. React Native's own
254 // layout manager centres them with a baseline offset; do the same, after attachments
255 // so chips shift with the words.
256 RCTApplyBaselineOffset(convertedAttributedString);
257
258 const CGFloat maximumWidth = std::isfinite(layoutConstraints.maximumSize.width)
259 ? layoutConstraints.maximumSize.width
260 : CGFLOAT_MAX;
261 NSTextStorage *textStorage =
262 [[NSTextStorage alloc] initWithAttributedString:convertedAttributedString];
263 NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
264 layoutManager.usesFontLeading = NO;
265 NSTextContainer *textContainer =
266 [[NSTextContainer alloc] initWithSize:CGSizeMake(maximumWidth, CGFLOAT_MAX)];
267 textContainer.lineFragmentPadding = 0;
268 textContainer.maximumNumberOfLines = baseProps.numberOfLines;
269 if (baseProps.ellipsizeMode == T3MarkdownTextEllipsizeMode::Head) {
270 textContainer.lineBreakMode = NSLineBreakByTruncatingHead;
271 } else if (baseProps.ellipsizeMode == T3MarkdownTextEllipsizeMode::Middle) {
272 textContainer.lineBreakMode = NSLineBreakByTruncatingMiddle;
273 } else if (baseProps.ellipsizeMode == T3MarkdownTextEllipsizeMode::Tail) {
274 textContainer.lineBreakMode = NSLineBreakByTruncatingTail;
275 } else {
276 textContainer.lineBreakMode = NSLineBreakByClipping;
277 }
278 [layoutManager addTextContainer:textContainer];
279 [textStorage addLayoutManager:layoutManager];
280 [layoutManager ensureLayoutForTextContainer:textContainer];
281 const CGRect usedRect = [layoutManager usedRectForTextContainer:textContainer];
282
283 return {
284 std::clamp(
285 static_cast<Float>(std::ceil(usedRect.size.width)),
286 layoutConstraints.minimumSize.width,
287 layoutConstraints.maximumSize.width),
288 std::clamp(
289 static_cast<Float>(std::ceil(usedRect.size.height)),
290 layoutConstraints.minimumSize.height,
291 layoutConstraints.maximumSize.height),
292 };
293}
294
295void T3MarkdownTextShadowNode::layout(LayoutContext layoutContext) {
296 ensureUnsealed();
297 setStateData(T3MarkdownTextStateReal{
298 _attributedString,
299 _paragraphStyleRanges,
300 _attachmentRanges,
301 });
302}
303}