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