Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

NativeMarkdownBlock.ios.tsx

711 lines20.2 KB

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