Open History to see the last commit
1import { useMemo } from "react";
2import { View } from "react-native";
3import { parseMarkdownWithOptions } from "react-native-nitro-markdown/headless";
4
5import {
6 nativeMarkdownChunkSpacing,
7 nativeMarkdownDocumentChunks,
8 nativeMarkdownDocumentRuns,
9 nativeMarkdownWithPreservedSoftBreaks,
10} from "./nativeMarkdownText";
11import { MarkdownImageRendererContext, NativeMarkdownBlock } from "./NativeMarkdownBlock.ios";
12import { NativeMarkdownSelectableText } from "./NativeMarkdownSelectableText.ios";
13import type {
14 SelectableMarkdownSkill,
15 SelectableMarkdownTextProps,
16} from "./SelectableMarkdownText.types";
17
18const EMPTY_SKILLS: ReadonlyArray<SelectableMarkdownSkill> = [];
19
20export type {
21 MarkdownCodeHighlighter,
22 MarkdownHighlightedToken,
23 MarkdownImageRenderer,
24 MarkdownImageRequest,
25 NativeMarkdownTextStyle,
26 SelectableMarkdownSkill,
27 SelectableMarkdownTextProps,
28} from "./SelectableMarkdownText.types";
29
30export function hasNativeSelectableMarkdownText(): boolean {
31 return true;
32}
33
34export function SelectableMarkdownText({
35 markdown,
36 skills = EMPTY_SKILLS,
37 textStyle,
38 highlightCode,
39 preserveSoftBreaks = false,
40 onLinkPress,
41 renderImage,
42 marginTop = 0,
43 marginBottom = 0,
44}: SelectableMarkdownTextProps) {
45 const chunks = useMemo(() => {
46 const parsedDocument = parseMarkdownWithOptions(markdown, {
47 gfm: true,
48 html: true,
49 math: false,
50 });
51 const document = preserveSoftBreaks
52 ? nativeMarkdownWithPreservedSoftBreaks(parsedDocument)
53 : parsedDocument;
54 return nativeMarkdownDocumentChunks(document).map((chunk) =>
55 chunk.kind === "selectable"
56 ? {
57 ...chunk,
58 runs: nativeMarkdownDocumentRuns(chunk.node, skills),
59 }
60 : chunk,
61 );
62 }, [markdown, preserveSoftBreaks, skills]);
63
64 return (
65 <MarkdownImageRendererContext.Provider value={renderImage ?? null}>
66 {/* A percentage width here creates a cyclic intrinsic measurement inside
67 shrink-to-fit containers such as user-message bubbles. Yoga then gives
68 the native text node an unbounded second pass and the parent only clips
69 the resulting single-line width instead of reflowing it. */}
70 <View style={{ flexShrink: 1, minWidth: 0, marginTop, marginBottom }}>
71 {chunks.map((chunk, index) => {
72 const content =
73 chunk.kind === "rich" ? (
74 <NativeMarkdownBlock
75 node={chunk.node}
76 skills={skills}
77 textStyle={textStyle}
78 highlightCode={highlightCode}
79 onLinkPress={onLinkPress}
80 />
81 ) : (
82 <NativeMarkdownSelectableText
83 runs={chunk.runs}
84 textStyle={textStyle}
85 onLinkPress={onLinkPress}
86 />
87 );
88
89 return (
90 <View
91 key={chunk.key}
92 style={{ paddingTop: nativeMarkdownChunkSpacing(chunks[index - 1], chunk) }}
93 >
94 {content}
95 </View>
96 );
97 })}
98 </View>
99 </MarkdownImageRendererContext.Provider>
100 );
101}