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

NativeMarkdownBlock.ios.tsx

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