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