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
137 uiTextView
138 selectable
139 selectionColor={props.textStyle.selectionColor}
140 selectionHandleColor={props.textStyle.selectionHandleColor}
141 style={style}
142 >
143 {props.highlighted ? lines : props.content}
144 </MarkdownTextPrimitive>
145 );
146}
147
148function NativeCodeBlock(props: {
149 readonly node: MarkdownNode;
150 readonly textStyle: NativeMarkdownTextStyle;
151 readonly highlightCode: MarkdownCodeHighlighter;
152 readonly compact?: boolean;
153}) {
154 const content = nodeText(props.node).replace(/\n$/, "");
155 const colorScheme = useColorScheme();
156 const theme = colorScheme === "dark" ? "dark" : "light";
157 const highlighted = useHighlightedCode(content, props.node.language, theme, props.highlightCode);
158 const languageLabel = props.node.language?.toUpperCase() ?? "CODE";
159 return (
160 <View
161 style={{
162 backgroundColor: props.textStyle.codeBlockBackgroundColor,
163 borderColor: props.textStyle.dividerColor,
164 borderCurve: "continuous",
165 borderRadius: 10,
166 borderWidth: 1,
167 marginVertical: props.compact ? 7 : 0,
168 overflow: "hidden",
169 }}
170 >
171 <View
172 style={{
173 minHeight: 42,
174 borderBottomColor: props.textStyle.dividerColor,
175 borderBottomWidth: 1,
176 paddingLeft: 14,
177 paddingRight: 6,
178 flexDirection: "row",
179 alignItems: "center",
180 justifyContent: "space-between",
181 }}
182 >
183 <MarkdownTextPrimitive
184 selectable
185 selectionColor={props.textStyle.selectionColor}
186 selectionHandleColor={props.textStyle.selectionHandleColor}
187 style={{
188 flex: 1,
189 color: props.textStyle.mutedColor,
190 fontFamily: MONO_FONT_FAMILY,
191 fontSize: codeBlockFontSize(props.textStyle),
192 }}
193 >
194 {languageLabel}
195 </MarkdownTextPrimitive>
196 <CopyTextButton
197 accessibilityLabel={`Copy ${languageLabel.toLowerCase()} code`}
198 text={content}
199 tintColor={props.textStyle.mutedColor}
200 copiedTintColor={props.textStyle.linkColor}
201 backgroundColor={props.textStyle.codeBackgroundColor}
202 borderColor={props.textStyle.dividerColor}
203 buttonSize={34}
204 iconSize={14}
205 />
206 </View>
207 <ScrollView
208 horizontal
209 bounces={false}
210 nestedScrollEnabled={Platform.OS === "android"}
211 showsHorizontalScrollIndicator={false}
212 contentContainerStyle={{ paddingHorizontal: 14, paddingVertical: 12 }}
213 >
214 <HighlightedCodeText
215 content={content}
216 highlighted={highlighted}
217 textStyle={props.textStyle}
218 />
219 </ScrollView>
220 </View>
221 );
222}
223
224function collectTableRows(node: MarkdownNode): MarkdownNode[] {
225 const rows: MarkdownNode[] = [];
226 const visit = (child: MarkdownNode) => {
227 if (child.type === "table_row") {
228 rows.push(child);
229 return;
230 }
231 for (const nested of child.children ?? []) {
232 visit(nested);
233 }
234 };
235 visit(node);
236 return rows;
237}
238
239function NativeTable(props: {
240 readonly node: MarkdownNode;
241 readonly skills: ReadonlyArray<SelectableMarkdownSkill>;
242 readonly textStyle: NativeMarkdownTextStyle;
243 readonly onLinkPress?: (href: string) => void;
244}) {
245 const rows = collectTableRows(props.node);
246 return (
247 <ScrollView
248 horizontal
249 bounces={false}
250 nestedScrollEnabled={Platform.OS === "android"}
251 showsHorizontalScrollIndicator={false}
252 >
253 <View
254 style={{
255 borderColor: props.textStyle.dividerColor,
256 borderCurve: "continuous",
257 borderRadius: 8,
258 borderWidth: 1,
259 overflow: "hidden",
260 }}
261 >
262 {rows.map((row, rowIndex) => (
263 <View
264 key={nodeKey(row, rowIndex)}
265 style={{
266 flexDirection: "row",
267 backgroundColor: rowIndex === 0 ? props.textStyle.codeBackgroundColor : "transparent",
268 borderTopColor: props.textStyle.dividerColor,
269 borderTopWidth: rowIndex === 0 ? 0 : 1,
270 }}
271 >
272 {(row.children ?? []).map((cell, cellIndex) => (
273 <View
274 key={nodeKey(cell, cellIndex)}
275 style={{
276 width: 160,
277 borderLeftColor: props.textStyle.dividerColor,
278 borderLeftWidth: cellIndex === 0 ? 0 : 1,
279 paddingHorizontal: 10,
280 paddingVertical: 8,
281 }}
282 >
283 <NativeMarkdownSelectableText
284 runs={nativeMarkdownDocumentRuns(documentFor(cell), props.skills).map((run) =>
285 rowIndex === 0 || cell.isHeader ? { ...run, bold: true } : run,
286 )}
287 textStyle={props.textStyle}
288 onLinkPress={props.onLinkPress}
289 />
290 </View>
291 ))}
292 </View>
293 ))}
294 </View>
295 </ScrollView>
296 );
297}
298
299function NativeMarkdownImage(props: {
300 readonly node: MarkdownNode;
301 readonly skills: ReadonlyArray<SelectableMarkdownSkill>;
302 readonly textStyle: NativeMarkdownTextStyle;
303 readonly onLinkPress?: (href: string) => void;
304}) {
305 const renderImage = useContext(MarkdownImageRendererContext);
306 const href = props.node.href;
307 if (!href) {
308 return (
309 <SelectableNode
310 node={props.node}
311 skills={props.skills}
312 textStyle={props.textStyle}
313 onLinkPress={props.onLinkPress}
314 />
315 );
316 }
317
318 if (renderImage) {
319 const rendered = renderImage({
320 href,
321 alt: props.node.alt ?? null,
322 title: props.node.title ?? null,
323 });
324 if (rendered != null) {
325 return <>{rendered}</>;
326 }
327 }
328
329 return (
330 <View style={{ gap: 6 }}>
331 <Image
332 source={{ uri: href }}
333 resizeMode="contain"
334 accessibilityLabel={props.node.alt ?? props.node.title}
335 style={{
336 width: "100%",
337 aspectRatio: 16 / 9,
338 backgroundColor: props.textStyle.codeBackgroundColor,
339 borderRadius: 10,
340 }}
341 />
342 {props.node.alt ? (
343 <MarkdownTextPrimitive
344 selectable
345 selectionColor={props.textStyle.selectionColor}
346 selectionHandleColor={props.textStyle.selectionHandleColor}
347 style={{
348 color: props.textStyle.mutedColor,
349 fontFamily: props.textStyle.fontFamily,
350 fontSize: 12,
351 lineHeight: 16,
352 }}
353 >
354 {props.node.alt}
355 </MarkdownTextPrimitive>
356 ) : null}
357 </View>
358 );
359}
360
361function inlineGroups(nodes: ReadonlyArray<MarkdownNode>): MarkdownNode[] {
362 const groups: MarkdownNode[] = [];
363 let inline: MarkdownNode[] = [];
364 const flush = () => {
365 if (inline.length === 0) {
366 return;
367 }
368 groups.push({ type: "paragraph", children: inline });
369 inline = [];
370 };
371
372 for (const node of nodes) {
373 if (node.type === "image") {
374 flush();
375 groups.push(node);
376 } else {
377 inline.push(node);
378 }
379 }
380 flush();
381 return groups;
382}
383
384function NativeMixedParagraph(props: {
385 readonly node: MarkdownNode;
386 readonly skills: ReadonlyArray<SelectableMarkdownSkill>;
387 readonly textStyle: NativeMarkdownTextStyle;
388 readonly onLinkPress?: (href: string) => void;
389}) {
390 return (
391 <View style={{ gap: 8 }}>
392 {inlineGroups(props.node.children ?? []).map((child, index) =>
393 child.type === "image" ? (
394 <NativeMarkdownImage
395 key={nodeKey(child, index)}
396 node={child}
397 skills={props.skills}
398 textStyle={props.textStyle}
399 onLinkPress={props.onLinkPress}
400 />
401 ) : (
402 <SelectableNode
403 key={nodeKey(child, index)}
404 node={child}
405 skills={props.skills}
406 textStyle={props.textStyle}
407 onLinkPress={props.onLinkPress}
408 />
409 ),
410 )}
411 </View>
412 );
413}
414
415function NativeList(props: {
416 readonly node: MarkdownNode;
417 readonly skills: ReadonlyArray<SelectableMarkdownSkill>;
418 readonly textStyle: NativeMarkdownTextStyle;
419 readonly highlightCode: MarkdownCodeHighlighter;
420 readonly onLinkPress?: (href: string) => void;
421 readonly depth: number;
422}) {
423 const ordered = props.node.ordered ?? false;
424 const start = props.node.start ?? 1;
425 const nested = props.depth > 0;
426 return (
427 <View
428 style={{
429 gap: nested ? 3 : 5,
430 }}
431 >
432 {(props.node.children ?? []).map((item, index) => {
433 const taskMarker = item.type === "task_list_item";
434 const marker = taskMarker
435 ? item.checked
436 ? "☑︎"
437 : "☐︎"
438 : ordered
439 ? `${start + index}.`
440 : props.depth % 3 === 1
441 ? "◦"
442 : props.depth % 3 === 2
443 ? "▪︎"
444 : "•";
445 const markerWidth = ordered ? 28 : taskMarker ? 20 : 18;
446 const markerOffset = taskMarker ? 3 : ordered ? 0 : 2;
447 return (
448 <View
449 key={nodeKey(item, index)}
450 style={{ alignItems: "flex-start", flexDirection: "row" }}
451 >
452 <View
453 style={{
454 width: markerWidth,
455 height: props.textStyle.lineHeight,
456 marginRight: 6,
457 alignItems: ordered ? "flex-end" : "center",
458 justifyContent: "flex-start",
459 }}
460 >
461 <Text
462 style={{
463 color: props.textStyle.color,
464 fontFamily: props.textStyle.fontFamily,
465 fontSize: taskMarker ? 14 : props.textStyle.fontSize,
466 lineHeight: props.textStyle.lineHeight,
467 fontVariant: ordered ? ["tabular-nums"] : undefined,
468 transform: [{ translateY: markerOffset }],
469 }}
470 >
471 {marker}
472 </Text>
473 </View>
474 <View style={{ flex: 1, minWidth: 0, gap: 2 }}>
475 {nativeMarkdownListItemBlocks(item).map((child, childIndex) => (
476 <NativeMarkdownBlock
477 key={nodeKey(child, childIndex)}
478 node={child}
479 skills={props.skills}
480 textStyle={props.textStyle}
481 highlightCode={props.highlightCode}
482 onLinkPress={props.onLinkPress}
483 depth={props.depth + 1}
484 compact
485 />
486 ))}
487 </View>
488 </View>
489 );
490 })}
491 </View>
492 );
493}
494
495export function NativeMarkdownBlock(props: {
496 readonly node: MarkdownNode;
497 readonly skills: ReadonlyArray<SelectableMarkdownSkill>;
498 readonly textStyle: NativeMarkdownTextStyle;
499 readonly highlightCode: MarkdownCodeHighlighter;
500 readonly onLinkPress?: (href: string) => void;
501 readonly depth?: number;
502 readonly compact?: boolean;
503}) {
504 const depth = props.depth ?? 0;
505 switch (props.node.type) {
506 case "document":
507 return (
508 <View style={{ gap: 8 }}>
509 {(props.node.children ?? []).map((child, index) => (
510 <NativeMarkdownBlock
511 key={nodeKey(child, index)}
512 node={child}
513 skills={props.skills}
514 textStyle={props.textStyle}
515 highlightCode={props.highlightCode}
516 onLinkPress={props.onLinkPress}
517 depth={depth}
518 />
519 ))}
520 </View>
521 );
522 case "code_block":
523 return (
524 <NativeCodeBlock
525 node={props.node}
526 textStyle={props.textStyle}
527 highlightCode={props.highlightCode}
528 compact={props.compact}
529 />
530 );
531 case "table":
532 return (
533 <NativeTable
534 node={props.node}
535 skills={props.skills}
536 textStyle={props.textStyle}
537 onLinkPress={props.onLinkPress}
538 />
539 );
540 case "image":
541 return (
542 <NativeMarkdownImage
543 node={props.node}
544 skills={props.skills}
545 textStyle={props.textStyle}
546 onLinkPress={props.onLinkPress}
547 />
548 );
549 case "horizontal_rule":
550 return (
551 <View
552 style={{
553 height: 1,
554 backgroundColor: props.textStyle.dividerColor,
555 }}
556 />
557 );
558 case "blockquote":
559 return (
560 <View
561 style={{
562 borderLeftColor: props.textStyle.quoteMarkerColor,
563 borderLeftWidth: 2,
564 marginVertical: props.compact ? 4 : 0,
565 paddingLeft: 11,
566 paddingVertical: 2,
567 gap: 6,
568 }}
569 >
570 {(props.node.children ?? []).map((child, index) => (
571 <NativeMarkdownBlock
572 key={nodeKey(child, index)}
573 node={child}
574 skills={props.skills}
575 textStyle={props.textStyle}
576 highlightCode={props.highlightCode}
577 onLinkPress={props.onLinkPress}
578 depth={depth}
579 compact
580 />
581 ))}
582 </View>
583 );
584 case "list":
585 return (
586 <NativeList
587 node={props.node}
588 skills={props.skills}
589 textStyle={props.textStyle}
590 highlightCode={props.highlightCode}
591 onLinkPress={props.onLinkPress}
592 depth={depth}
593 />
594 );
595 case "paragraph":
596 return (props.node.children ?? []).some((child) => child.type === "image") ? (
597 <NativeMixedParagraph
598 node={props.node}
599 skills={props.skills}
600 textStyle={props.textStyle}
601 onLinkPress={props.onLinkPress}
602 />
603 ) : (
604 <SelectableNode
605 node={props.node}
606 skills={props.skills}
607 textStyle={props.textStyle}
608 onLinkPress={props.onLinkPress}
609 />
610 );
611 case "html_block":
612 case "math_block":
613 return (
614 <View
615 style={{
616 marginVertical: props.compact ? 2 : 0,
617 paddingHorizontal: props.node.type === "math_block" ? 10 : 0,
618 paddingVertical: props.node.type === "math_block" ? 8 : 0,
619 backgroundColor:
620 props.node.type === "math_block"
621 ? props.textStyle.codeBackgroundColor
622 : "transparent",
623 }}
624 >
625 <SelectableNode
626 node={props.node}
627 skills={props.skills}
628 textStyle={props.textStyle}
629 onLinkPress={props.onLinkPress}
630 />
631 </View>
632 );
633 case "table_head":
634 case "table_body":
635 case "table_row":
636 case "table_cell":
637 case "list_item":
638 case "task_list_item":
639 return (
640 <View style={{ gap: 4 }}>
641 {(props.node.children ?? []).map((child, index) => (
642 <NativeMarkdownBlock
643 key={nodeKey(child, index)}
644 node={child}
645 skills={props.skills}
646 textStyle={props.textStyle}
647 highlightCode={props.highlightCode}
648 onLinkPress={props.onLinkPress}
649 depth={depth}
650 compact
651 />
652 ))}
653 </View>
654 );
655 default:
656 return (
657 <SelectableNode
658 node={props.node}
659 skills={props.skills}
660 textStyle={props.textStyle}
661 onLinkPress={props.onLinkPress}
662 />
663 );
664 }
665}