Open History to see the last commit
1import { createContext, memo, useContext, useMemo } from "react";
2import { Image, Platform, ScrollView, Text, useColorScheme, View } from "react-native";
3import type { MarkdownNode } from "react-native-nitro-markdown/headless";
4
5import { CopyTextButton } from "./CopyTextButton";
6import { MarkdownTextPrimitive } from "./MarkdownTextPrimitive";
7import {
8 nativeMarkdownDocumentRuns,
9 nativeMarkdownListItemBlocks,
10 nativeMarkdownNodePosition,
11} from "./nativeMarkdownText";
12import { NativeMarkdownSelectableText } from "./NativeMarkdownSelectableText";
13import type {
14 MarkdownCodeHighlighter,
15 MarkdownHighlightedToken,
16 MarkdownImageRenderer,
17 NativeMarkdownTextStyle,
18 SelectableMarkdownSkill,
19} from "./SelectableMarkdownText.types";
20import { useHighlightedCode, type HighlightedCode } from "./useHighlightedCode";
21
22/** Set by SelectableMarkdownText so images anywhere in the block tree can use it. */
23export const MarkdownImageRendererContext = createContext<MarkdownImageRenderer | null>(null);
24
25const MONO_FONT_FAMILY = Platform.select({
26 ios: "ui-monospace",
27 android: "monospace",
28 default: "monospace",
29});
30
31function nodeKey(node: MarkdownNode, index: number): string {
32 return `${node.type}:${nativeMarkdownNodePosition(node, index)}`;
33}
34
35/** Code inside markdown scales with the base text size (12pt at the default 15pt body). */
36function codeBlockFontSize(textStyle: NativeMarkdownTextStyle): number {
37 return Math.max(10, Math.round(textStyle.fontSize * 0.8));
38}
39
40function codeBlockLineHeight(textStyle: NativeMarkdownTextStyle): number {
41 return codeBlockFontSize(textStyle) + 6;
42}
43
44function nodeText(node: MarkdownNode): string {
45 if (node.content !== undefined) {
46 return node.content;
47 }
48 return (node.children ?? []).map(nodeText).join("");
49}
50
51function documentFor(node: MarkdownNode): MarkdownNode {
52 return node.type === "document" ? node : { type: "document", children: [node] };
53}
54
55function SelectableNode(props: {
56 readonly node: MarkdownNode;
57 readonly skills: ReadonlyArray<SelectableMarkdownSkill>;
58 readonly textStyle: NativeMarkdownTextStyle;
59 readonly onLinkPress?: (href: string) => void;
60}) {
61 return (
62 <NativeMarkdownSelectableText
63 runs={nativeMarkdownDocumentRuns(documentFor(props.node), props.skills)}
64 textStyle={props.textStyle}
65 onLinkPress={props.onLinkPress}
66 />
67 );
68}
69
70const HighlightedCodeLine = memo(function HighlightedCodeLine(props: {
71 readonly tokens: ReadonlyArray<MarkdownHighlightedToken>;
72 readonly color: string;
73 readonly newline: boolean;
74}) {
75 let offset = 0;
76 const children = [];
77 for (const token of props.tokens) {
78 if (!token.content) continue;
79 children.push(
80 <MarkdownTextPrimitive
81 key={offset}
82 style={{
83 color: token.color ?? props.color,
84 fontFamily: MONO_FONT_FAMILY,
85 fontStyle: token.fontStyle !== null && (token.fontStyle & 1) === 1 ? "italic" : "normal",
86 fontWeight: token.fontStyle !== null && (token.fontStyle & 2) === 2 ? "700" : "400",
87 }}
88 >
89 {token.content}
90 </MarkdownTextPrimitive>,
91 );
92 offset += token.content.length;
93 }
94 return (
95 <MarkdownTextPrimitive>
96 {children}
97 {props.newline ? "\n" : ""}
98 </MarkdownTextPrimitive>
99 );
100});
101
102function HighlightedCodeText(props: {
103 readonly content: string;
104 readonly highlighted: HighlightedCode | null;
105 readonly textStyle: NativeMarkdownTextStyle;
106}) {
107 // The text root provides inherited styles through context. A new style object
108 // would rerender every token even when its completed line is unchanged.
109 const fontSize = codeBlockFontSize(props.textStyle);
110 const lineHeight = codeBlockLineHeight(props.textStyle);
111 const style = useMemo(
112 () => ({
113 color: props.textStyle.codeColor,
114 fontFamily: MONO_FONT_FAMILY,
115 fontSize,
116 lineHeight,
117 }),
118 [props.textStyle.codeColor, fontSize, lineHeight],
119 );
120 let offset = 0;
121 const lines = [];
122 if (props.highlighted) {
123 for (const tokens of props.highlighted) {
124 lines.push(
125 <HighlightedCodeLine
126 key={offset}
127 tokens={tokens}
128 color={props.textStyle.codeColor}
129 newline={lines.length + 1 < props.highlighted.length}
130 />,
131 );
132 offset += tokens.reduce((length, token) => length + token.content.length, 0) + 1;
133 }
134 }
135 return (
136 <MarkdownTextPrimitive uiTextView selectable style={style}>
137 {props.highlighted ? lines : props.content}
138 </MarkdownTextPrimitive>
139 );
140}
141
142function NativeCodeBlock(props: {
143 readonly node: MarkdownNode;
144 readonly textStyle: NativeMarkdownTextStyle;
145 readonly highlightCode: MarkdownCodeHighlighter;
146 readonly compact?: boolean;
147}) {
148 const content = nodeText(props.node).replace(/\n$/, "");
149 const colorScheme = useColorScheme();
150 const theme = colorScheme === "dark" ? "dark" : "light";
151 const highlighted = useHighlightedCode(content, props.node.language, theme, props.highlightCode);
152 const languageLabel = props.node.language?.toUpperCase() ?? "CODE";
153 return (
154 <View
155 style={{
156 backgroundColor: props.textStyle.codeBlockBackgroundColor,
157 borderColor: props.textStyle.dividerColor,
158 borderCurve: "continuous",
159 borderRadius: 10,
160 borderWidth: 1,
161 marginVertical: props.compact ? 7 : 0,
162 overflow: "hidden",
163 }}
164 >
165 <View
166 style={{
167 minHeight: 42,
168 borderBottomColor: props.textStyle.dividerColor,
169 borderBottomWidth: 1,
170 paddingLeft: 14,
171 paddingRight: 6,
172 flexDirection: "row",
173 alignItems: "center",
174 justifyContent: "space-between",
175 }}
176 >
177 <Text
178 selectable
179 style={{
180 flex: 1,
181 color: props.textStyle.mutedColor,
182 fontFamily: MONO_FONT_FAMILY,
183 fontSize: codeBlockFontSize(props.textStyle),
184 }}
185 >
186 {languageLabel}
187 </Text>
188 <CopyTextButton
189 accessibilityLabel={`Copy ${languageLabel.toLowerCase()} code`}
190 text={content}
191 tintColor={props.textStyle.mutedColor}
192 copiedTintColor={props.textStyle.linkColor}
193 backgroundColor={props.textStyle.codeBackgroundColor}
194 borderColor={props.textStyle.dividerColor}
195 buttonSize={34}
196 iconSize={14}
197 />
198 </View>
199 <ScrollView
200 horizontal
201 bounces={false}
202 nestedScrollEnabled={Platform.OS === "android"}
203 showsHorizontalScrollIndicator={false}
204 contentContainerStyle={{ paddingHorizontal: 14, paddingVertical: 12 }}
205 >
206 <HighlightedCodeText
207 content={content}
208 highlighted={highlighted}
209 textStyle={props.textStyle}
210 />
211 </ScrollView>
212 </View>
213 );
214}
215
216function collectTableRows(node: MarkdownNode): MarkdownNode[] {
217 const rows: MarkdownNode[] = [];
218 const visit = (child: MarkdownNode) => {
219 if (child.type === "table_row") {
220 rows.push(child);
221 return;
222 }
223 for (const nested of child.children ?? []) {
224 visit(nested);
225 }
226 };
227 visit(node);
228 return rows;
229}
230
231function NativeTable(props: {
232 readonly node: MarkdownNode;
233 readonly skills: ReadonlyArray<SelectableMarkdownSkill>;
234 readonly textStyle: NativeMarkdownTextStyle;
235 readonly onLinkPress?: (href: string) => void;
236}) {
237 const rows = collectTableRows(props.node);
238 return (
239 <ScrollView
240 horizontal
241 bounces={false}
242 nestedScrollEnabled={Platform.OS === "android"}
243 showsHorizontalScrollIndicator={false}
244 >
245 <View
246 style={{
247 borderColor: props.textStyle.dividerColor,
248 borderCurve: "continuous",
249 borderRadius: 8,
250 borderWidth: 1,
251 overflow: "hidden",
252 }}
253 >
254 {rows.map((row, rowIndex) => (
255 <View
256 key={nodeKey(row, rowIndex)}
257 style={{
258 flexDirection: "row",
259 backgroundColor: rowIndex === 0 ? props.textStyle.codeBackgroundColor : "transparent",
260 borderTopColor: props.textStyle.dividerColor,
261 borderTopWidth: rowIndex === 0 ? 0 : 1,
262 }}
263 >
264 {(row.children ?? []).map((cell, cellIndex) => (
265 <View
266 key={nodeKey(cell, cellIndex)}
267 style={{
268 width: 160,
269 borderLeftColor: props.textStyle.dividerColor,
270 borderLeftWidth: cellIndex === 0 ? 0 : 1,
271 paddingHorizontal: 10,
272 paddingVertical: 8,
273 }}
274 >
275 <NativeMarkdownSelectableText
276 runs={nativeMarkdownDocumentRuns(documentFor(cell), props.skills).map((run) =>
277 rowIndex === 0 || cell.isHeader ? { ...run, bold: true } : run,
278 )}
279 textStyle={props.textStyle}
280 onLinkPress={props.onLinkPress}
281 />
282 </View>
283 ))}
284 </View>
285 ))}
286 </View>
287 </ScrollView>
288 );
289}
290
291function NativeMarkdownImage(props: {
292 readonly node: MarkdownNode;
293 readonly skills: ReadonlyArray<SelectableMarkdownSkill>;
294 readonly textStyle: NativeMarkdownTextStyle;
295 readonly onLinkPress?: (href: string) => void;
296}) {
297 const renderImage = useContext(MarkdownImageRendererContext);
298 const href = props.node.href;
299 if (!href) {
300 return (
301 <SelectableNode
302 node={props.node}
303 skills={props.skills}
304 textStyle={props.textStyle}
305 onLinkPress={props.onLinkPress}
306 />
307 );
308 }
309
310 if (renderImage) {
311 const rendered = renderImage({
312 href,
313 alt: props.node.alt ?? null,
314 title: props.node.title ?? null,
315 });
316 if (rendered != null) {
317 return <>{rendered}</>;
318 }
319 }
320
321 return (
322 <View style={{ gap: 6 }}>
323 <Image
324 source={{ uri: href }}
325 resizeMode="contain"
326 accessibilityLabel={props.node.alt ?? props.node.title}
327 style={{
328 width: "100%",
329 aspectRatio: 16 / 9,
330 backgroundColor: props.textStyle.codeBackgroundColor,
331 borderRadius: 10,
332 }}
333 />
334 {props.node.alt ? (
335 <Text
336 selectable
337 style={{
338 color: props.textStyle.mutedColor,
339 fontFamily: props.textStyle.fontFamily,
340 fontSize: 12,
341 lineHeight: 16,
342 }}
343 >
344 {props.node.alt}
345 </Text>
346 ) : null}
347 </View>
348 );
349}
350
351function inlineGroups(nodes: ReadonlyArray<MarkdownNode>): MarkdownNode[] {
352 const groups: MarkdownNode[] = [];
353 let inline: MarkdownNode[] = [];
354 const flush = () => {
355 if (inline.length === 0) {
356 return;
357 }
358 groups.push({ type: "paragraph", children: inline });
359 inline = [];
360 };
361
362 for (const node of nodes) {
363 if (node.type === "image") {
364 flush();
365 groups.push(node);
366 } else {
367 inline.push(node);
368 }
369 }
370 flush();
371 return groups;
372}
373
374function NativeMixedParagraph(props: {
375 readonly node: MarkdownNode;
376 readonly skills: ReadonlyArray<SelectableMarkdownSkill>;
377 readonly textStyle: NativeMarkdownTextStyle;
378 readonly onLinkPress?: (href: string) => void;
379}) {
380 return (
381 <View style={{ gap: 8 }}>
382 {inlineGroups(props.node.children ?? []).map((child, index) =>
383 child.type === "image" ? (
384 <NativeMarkdownImage
385 key={nodeKey(child, index)}
386 node={child}
387 skills={props.skills}
388 textStyle={props.textStyle}
389 onLinkPress={props.onLinkPress}
390 />
391 ) : (
392 <SelectableNode
393 key={nodeKey(child, index)}
394 node={child}
395 skills={props.skills}
396 textStyle={props.textStyle}
397 onLinkPress={props.onLinkPress}
398 />
399 ),
400 )}
401 </View>
402 );
403}
404
405function NativeList(props: {
406 readonly node: MarkdownNode;
407 readonly skills: ReadonlyArray<SelectableMarkdownSkill>;
408 readonly textStyle: NativeMarkdownTextStyle;
409 readonly highlightCode: MarkdownCodeHighlighter;
410 readonly onLinkPress?: (href: string) => void;
411 readonly depth: number;
412}) {
413 const ordered = props.node.ordered ?? false;
414 const start = props.node.start ?? 1;
415 const nested = props.depth > 0;
416 return (
417 <View
418 style={{
419 gap: nested ? 3 : 5,
420 }}
421 >
422 {(props.node.children ?? []).map((item, index) => {
423 const taskMarker = item.type === "task_list_item";
424 const marker = taskMarker
425 ? item.checked
426 ? "☑︎"
427 : "☐︎"
428 : ordered
429 ? `${start + index}.`
430 : props.depth % 3 === 1
431 ? "◦"
432 : props.depth % 3 === 2
433 ? "▪︎"
434 : "•";
435 const markerWidth = ordered ? 28 : taskMarker ? 20 : 18;
436 const markerOffset = taskMarker ? 3 : ordered ? 0 : 2;
437 return (
438 <View
439 key={nodeKey(item, index)}
440 style={{ alignItems: "flex-start", flexDirection: "row" }}
441 >
442 <View
443 style={{
444 width: markerWidth,
445 height: props.textStyle.lineHeight,
446 marginRight: 6,
447 alignItems: ordered ? "flex-end" : "center",
448 justifyContent: "flex-start",
449 }}
450 >
451 <Text
452 style={{
453 color: props.textStyle.color,
454 fontFamily: props.textStyle.fontFamily,
455 fontSize: taskMarker ? 14 : props.textStyle.fontSize,
456 lineHeight: props.textStyle.lineHeight,
457 fontVariant: ordered ? ["tabular-nums"] : undefined,
458 transform: [{ translateY: markerOffset }],
459 }}
460 >
461 {marker}
462 </Text>
463 </View>
464 <View style={{ flex: 1, minWidth: 0, gap: 2 }}>
465 {nativeMarkdownListItemBlocks(item).map((child, childIndex) => (
466 <NativeMarkdownBlock
467 key={nodeKey(child, childIndex)}
468 node={child}
469 skills={props.skills}
470 textStyle={props.textStyle}
471 highlightCode={props.highlightCode}
472 onLinkPress={props.onLinkPress}
473 depth={props.depth + 1}
474 compact
475 />
476 ))}
477 </View>
478 </View>
479 );
480 })}
481 </View>
482 );
483}
484
485export function NativeMarkdownBlock(props: {
486 readonly node: MarkdownNode;
487 readonly skills: ReadonlyArray<SelectableMarkdownSkill>;
488 readonly textStyle: NativeMarkdownTextStyle;
489 readonly highlightCode: MarkdownCodeHighlighter;
490 readonly onLinkPress?: (href: string) => void;
491 readonly depth?: number;
492 readonly compact?: boolean;
493}) {
494 const depth = props.depth ?? 0;
495 switch (props.node.type) {
496 case "document":
497 return (
498 <View style={{ gap: 8 }}>
499 {(props.node.children ?? []).map((child, index) => (
500 <NativeMarkdownBlock
501 key={nodeKey(child, index)}
502 node={child}
503 skills={props.skills}
504 textStyle={props.textStyle}
505 highlightCode={props.highlightCode}
506 onLinkPress={props.onLinkPress}
507 depth={depth}
508 />
509 ))}
510 </View>
511 );
512 case "code_block":
513 return (
514 <NativeCodeBlock
515 node={props.node}
516 textStyle={props.textStyle}
517 highlightCode={props.highlightCode}
518 compact={props.compact}
519 />
520 );
521 case "table":
522 return (
523 <NativeTable
524 node={props.node}
525 skills={props.skills}
526 textStyle={props.textStyle}
527 onLinkPress={props.onLinkPress}
528 />
529 );
530 case "image":
531 return (
532 <NativeMarkdownImage
533 node={props.node}
534 skills={props.skills}
535 textStyle={props.textStyle}
536 onLinkPress={props.onLinkPress}
537 />
538 );
539 case "horizontal_rule":
540 return (
541 <View
542 style={{
543 height: 1,
544 backgroundColor: props.textStyle.dividerColor,
545 }}
546 />
547 );
548 case "blockquote":
549 return (
550 <View
551 style={{
552 borderLeftColor: props.textStyle.quoteMarkerColor,
553 borderLeftWidth: 2,
554 marginVertical: props.compact ? 4 : 0,
555 paddingLeft: 11,
556 paddingVertical: 2,
557 gap: 6,
558 }}
559 >
560 {(props.node.children ?? []).map((child, index) => (
561 <NativeMarkdownBlock
562 key={nodeKey(child, index)}
563 node={child}
564 skills={props.skills}
565 textStyle={props.textStyle}
566 highlightCode={props.highlightCode}
567 onLinkPress={props.onLinkPress}
568 depth={depth}
569 compact
570 />
571 ))}
572 </View>
573 );
574 case "list":
575 return (
576 <NativeList
577 node={props.node}
578 skills={props.skills}
579 textStyle={props.textStyle}
580 highlightCode={props.highlightCode}
581 onLinkPress={props.onLinkPress}
582 depth={depth}
583 />
584 );
585 case "paragraph":
586 return (props.node.children ?? []).some((child) => child.type === "image") ? (
587 <NativeMixedParagraph
588 node={props.node}
589 skills={props.skills}
590 textStyle={props.textStyle}
591 onLinkPress={props.onLinkPress}
592 />
593 ) : (
594 <SelectableNode
595 node={props.node}
596 skills={props.skills}
597 textStyle={props.textStyle}
598 onLinkPress={props.onLinkPress}
599 />
600 );
601 case "html_block":
602 case "math_block":
603 return (
604 <View
605 style={{
606 marginVertical: props.compact ? 2 : 0,
607 paddingHorizontal: props.node.type === "math_block" ? 10 : 0,
608 paddingVertical: props.node.type === "math_block" ? 8 : 0,
609 backgroundColor:
610 props.node.type === "math_block"
611 ? props.textStyle.codeBackgroundColor
612 : "transparent",
613 }}
614 >
615 <SelectableNode
616 node={props.node}
617 skills={props.skills}
618 textStyle={props.textStyle}
619 onLinkPress={props.onLinkPress}
620 />
621 </View>
622 );
623 case "table_head":
624 case "table_body":
625 case "table_row":
626 case "table_cell":
627 case "list_item":
628 case "task_list_item":
629 return (
630 <View style={{ gap: 4 }}>
631 {(props.node.children ?? []).map((child, index) => (
632 <NativeMarkdownBlock
633 key={nodeKey(child, index)}
634 node={child}
635 skills={props.skills}
636 textStyle={props.textStyle}
637 highlightCode={props.highlightCode}
638 onLinkPress={props.onLinkPress}
639 depth={depth}
640 compact
641 />
642 ))}
643 </View>
644 );
645 default:
646 return (
647 <SelectableNode
648 node={props.node}
649 skills={props.skills}
650 textStyle={props.textStyle}
651 onLinkPress={props.onLinkPress}
652 />
653 );
654 }
655}