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

SelectableMarkdownText.ios.tsx

96 lines2.8 KB

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 { 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 NativeMarkdownTextStyle,
24 SelectableMarkdownSkill,
25 SelectableMarkdownTextProps,
26} from "./SelectableMarkdownText.types";
27​
28export function hasNativeSelectableMarkdownText(): boolean {
29 return true;
31​
32export function SelectableMarkdownText({
33 markdown,
34 skills = EMPTY_SKILLS,
35 textStyle,
36 highlightCode,
37 preserveSoftBreaks = false,
38 onLinkPress,
39 marginTop = 0,
40 marginBottom = 0,
41}: SelectableMarkdownTextProps) {
42 const chunks = useMemo(() => {
43 const parsedDocument = parseMarkdownWithOptions(markdown, {
44 gfm: true,
45 html: true,
46 math: false,
47 });
48 const document = preserveSoftBreaks
49 ? nativeMarkdownWithPreservedSoftBreaks(parsedDocument)
50 : parsedDocument;
51 return nativeMarkdownDocumentChunks(document).map((chunk) =>
52 chunk.kind === "selectable"
53 ? {
54 ...chunk,
55 runs: nativeMarkdownDocumentRuns(chunk.node, skills),
56 }
57 : chunk,
58 );
59 }, [markdown, preserveSoftBreaks, skills]);
60​
61 return (
62 // A percentage width here creates a cyclic intrinsic measurement inside
63 // shrink-to-fit containers such as user-message bubbles. Yoga then gives
64 // the native text node an unbounded second pass and the parent only clips
65 // the resulting single-line width instead of reflowing it.
66 <View style={{ flexShrink: 1, minWidth: 0, marginTop, marginBottom }}>
67 {chunks.map((chunk, index) => {
68 const content =
69 chunk.kind === "rich" ? (
70 <NativeMarkdownBlock
71 node={chunk.node}
72 skills={skills}
73 textStyle={textStyle}
74 highlightCode={highlightCode}
75 onLinkPress={onLinkPress}
76 />
77 ) : (
78 <NativeMarkdownSelectableText
79 runs={chunk.runs}
80 textStyle={textStyle}
81 onLinkPress={onLinkPress}
82 />
83 );
84​
85 return (
86 <View
87 key={chunk.key}
88 style={{ paddingTop: nativeMarkdownChunkSpacing(chunks[index - 1], chunk) }}
89 >
90 {content}
91 </View>
92 );
93 })}
94 </View>
95 );