Open History to see the last commit
1import { createContext, useCallback, useContext } from "react";
2import {
3 findNodeHandle,
4 Image,
5 Linking,
6 Platform,
7 StyleSheet,
8 Text as RNText,
9 type TextStyle,
10 useColorScheme,
11} from "react-native";
12
13import { MarkdownTextPrimitive } from "./MarkdownTextPrimitive";
14import { markdownFileIconSource } from "./markdownFileIcons";
15import { markdownLinkIconSource } from "./markdownLinkIcons";
16import { resolveMarkdownLinkIcon } from "./markdownLinks";
17import type { NativeMarkdownTextRun } from "./nativeMarkdownText";
18import type {
19 MarkdownFileContextMenu,
20 NativeMarkdownTextStyle,
21} from "./SelectableMarkdownText.types";
22import { installMarkdownCopySanitizer } from "./T3MarkdownTextSelectionModule";
23
24export interface MarkdownFileContextMenuHandlers {
25 readonly fileContextMenu: (href: string) => MarkdownFileContextMenu | undefined;
26 readonly onFileContextMenuAction: (href: string, actionId: string) => void;
27}
28
29/** Set by SelectableMarkdownText so file chips anywhere in the block tree get the same menu. */
30export const MarkdownFileContextMenuContext = createContext<MarkdownFileContextMenuHandlers | null>(
31 null,
32);
33
34const EXTERNAL_LINK_PREFIX = "◉ ";
35const INLINE_ATTACHMENT_PREFIX = "\uFFFC\u00A0";
36const SKILL_ICON_PLACEHOLDER = "\uFFFC";
37const PARAGRAPH_STYLE_ENCODING_OFFSET = 1000;
38const MONO_FONT_FAMILY = Platform.select({
39 ios: "ui-monospace",
40 android: "monospace",
41 default: "monospace",
42});
43const styles = StyleSheet.create({
44 inlineIcon: {
45 width: 14,
46 height: 14,
47 marginHorizontal: 3,
48 transform: [{ translateY: 2 }],
49 },
50});
51
52function runKeySignature(run: NativeMarkdownTextRun): string {
53 return [
54 run.text,
55 run.bold,
56 run.italic,
57 run.strikethrough,
58 run.code,
59 run.href,
60 run.externalHost,
61 run.fileIcon,
62 run.skillName,
63 run.skillLabel,
64 run.role,
65 run.headingLevel,
66 run.depth,
67 run.spacing,
68 run.firstLineHeadIndent,
69 run.headIndent,
70 run.paragraphSpacing,
71 ].join(":");
72}
73
74const DEFAULT_BODY_FONT_SIZE = 15;
75const DEFAULT_HEADING_FONT_SIZES = [22, 19, 17, 16, 15, 15] as const;
76
77function resolveHeadingFontSize(textStyle: NativeMarkdownTextStyle, headingLevel: number): number {
78 const index = Math.max(0, Math.min(5, headingLevel - 1));
79 const configured = textStyle.headingFontSizes?.[index];
80 if (typeof configured === "number" && Number.isFinite(configured)) {
81 return configured;
82 }
83
84 const scale = textStyle.fontSize / DEFAULT_BODY_FONT_SIZE;
85 return Math.max(12, Math.round(DEFAULT_HEADING_FONT_SIZES[index] * scale));
86}
87
88function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle): TextStyle {
89 const isFile = run.fileIcon != null;
90 const isSkill = run.skillName != null;
91 const headingLevel = Math.max(1, Math.min(6, run.headingLevel ?? 1));
92 const headingFontSize = resolveHeadingFontSize(textStyle, headingLevel);
93 const isHeading = run.role === "heading";
94 const isCodeBlock = run.role === "code-block" || run.role === "code-language";
95 const hasParagraphStyle = run.headIndent !== undefined;
96 const textDecorationLine = run.strikethrough
97 ? "line-through"
98 : run.href && !isFile
99 ? "underline"
100 : "none";
101
102 return {
103 color: isFile
104 ? textStyle.fileTextColor
105 : isSkill
106 ? textStyle.skillTextColor
107 : run.href
108 ? textStyle.linkColor
109 : isHeading
110 ? textStyle.strongColor
111 : run.role === "quote-marker"
112 ? textStyle.quoteMarkerColor
113 : run.role === "divider"
114 ? textStyle.dividerColor
115 : run.role === "code-language"
116 ? textStyle.mutedColor
117 : run.role === "list-marker"
118 ? textStyle.mutedColor
119 : isCodeBlock
120 ? textStyle.codeColor
121 : run.code
122 ? textStyle.inlineCodeColor
123 : run.bold
124 ? textStyle.strongColor
125 : textStyle.color,
126 fontFamily:
127 isFile || isSkill
128 ? textStyle.boldFontFamily
129 : run.code || isCodeBlock
130 ? MONO_FONT_FAMILY
131 : isHeading
132 ? textStyle.headingFontFamily
133 : run.bold
134 ? textStyle.boldFontFamily
135 : textStyle.fontFamily,
136 fontSize:
137 run.role === "spacer"
138 ? (run.spacing ?? 10)
139 : run.role === "list-break"
140 ? textStyle.fontSize
141 : isHeading
142 ? headingFontSize
143 : run.role === "code-language"
144 ? Math.max(10, Math.round(textStyle.fontSize * 0.73))
145 : run.code || isCodeBlock
146 ? Math.max(12, textStyle.fontSize - 2)
147 : textStyle.fontSize,
148 lineHeight:
149 run.role === "spacer"
150 ? (run.spacing ?? 10)
151 : run.role === "list-break"
152 ? textStyle.lineHeight + (run.spacing ?? 0)
153 : isHeading
154 ? Math.max(headingFontSize + 6, textStyle.lineHeight + 2)
155 : isCodeBlock
156 ? Math.max(16, textStyle.lineHeight - 2)
157 : textStyle.lineHeight,
158 fontStyle: run.italic ? "italic" : "normal",
159 fontWeight: isHeading || run.bold || isFile || isSkill ? "700" : "400",
160 textDecorationLine,
161 backgroundColor: isCodeBlock ? textStyle.codeBlockBackgroundColor : undefined,
162 ...(hasParagraphStyle
163 ? {
164 shadowColor: "transparent",
165 shadowOffset: {
166 width: run.firstLineHeadIndent ?? 0,
167 height: run.headIndent,
168 },
169 shadowRadius: PARAGRAPH_STYLE_ENCODING_OFFSET + (run.paragraphSpacing ?? 0),
170 }
171 : {}),
172 };
173}
174
175export function NativeMarkdownSelectableText(props: {
176 readonly runs: ReadonlyArray<NativeMarkdownTextRun>;
177 readonly textStyle: NativeMarkdownTextStyle;
178 readonly onLinkPress?: (href: string) => void;
179}) {
180 const colorScheme = useColorScheme();
181 const menu = useContext(MarkdownFileContextMenuContext);
182 const containsInlineIcon = props.runs.some(
183 (run) =>
184 run.fileIcon != null ||
185 (run.externalHost != null && resolveMarkdownLinkIcon(run.externalHost) !== null),
186 );
187 const attachAndroidText = useCallback(
188 (textView: RNText | null) => {
189 if (Platform.OS !== "android" || !containsInlineIcon || textView === null) {
190 return;
191 }
192 const reactTag = findNodeHandle(textView);
193 if (reactTag !== null) {
194 installMarkdownCopySanitizer(reactTag);
195 }
196 },
197 [containsInlineIcon],
198 );
199 const occurrences = new Map<string, number>();
200 const prefixedExternalLinks = new Set<string>();
201 const keyedRuns = props.runs.map((run) => {
202 const signature = runKeySignature(run);
203 const occurrence = occurrences.get(signature) ?? 0;
204 occurrences.set(signature, occurrence + 1);
205
206 let text = run.text;
207 let linkIcon = null;
208 if (run.fileIcon && Platform.OS === "ios") {
209 text = `${INLINE_ATTACHMENT_PREFIX}${text}`;
210 } else if (run.skillName && run.skillLabel) {
211 text =
212 Platform.OS === "ios"
213 ? `${SKILL_ICON_PLACEHOLDER}\u00A0${run.skillLabel}`
214 : `$${run.skillName}`;
215 } else if (run.externalHost && run.href && !prefixedExternalLinks.has(run.href)) {
216 prefixedExternalLinks.add(run.href);
217 linkIcon = resolveMarkdownLinkIcon(run.externalHost);
218 if (linkIcon === null) {
219 text = `${EXTERNAL_LINK_PREFIX}${text}`;
220 } else if (Platform.OS === "ios") {
221 text = `${INLINE_ATTACHMENT_PREFIX}${text}`;
222 }
223 }
224
225 return { key: `${signature}:${occurrence}`, run, text, linkIcon };
226 });
227 // T3MarkdownText only rebuilds its attributed string during native layout. A
228 // color-only child update can otherwise leave the previous appearance cached.
229 const appearanceKey = [
230 colorScheme ?? "unspecified",
231 props.textStyle.fontSize,
232 props.textStyle.lineHeight,
233 props.textStyle.headingFontSizes?.join(","),
234 props.textStyle.color,
235 props.textStyle.strongColor,
236 props.textStyle.mutedColor,
237 props.textStyle.linkColor,
238 props.textStyle.inlineCodeColor,
239 props.textStyle.codeColor,
240 props.textStyle.codeBackgroundColor,
241 props.textStyle.codeBlockBackgroundColor,
242 props.textStyle.fileTextColor,
243 props.textStyle.skillTextColor,
244 props.textStyle.quoteMarkerColor,
245 props.textStyle.dividerColor,
246 ].join(":");
247
248 return (
249 <MarkdownTextPrimitive
250 key={appearanceKey}
251 nativeTextRef={attachAndroidText}
252 uiTextView
253 selectable
254 style={{
255 flexShrink: 1,
256 minWidth: 0,
257 color: props.textStyle.color,
258 fontFamily: props.textStyle.fontFamily,
259 fontSize: props.textStyle.fontSize,
260 lineHeight: props.textStyle.lineHeight,
261 }}
262 >
263 {keyedRuns.map(({ key, run, text, linkIcon }) => {
264 const href = run.href;
265 const contextMenu = run.fileIcon && href ? menu?.fileContextMenu(href) : undefined;
266 return (
267 <MarkdownTextPrimitive
268 key={key}
269 nativeID={
270 Platform.OS === "ios"
271 ? run.fileIcon
272 ? `t3-file:${Image.resolveAssetSource(markdownFileIconSource(run.fileIcon)).uri}`
273 : run.skillName
274 ? "t3-skill:sf:cube"
275 : linkIcon
276 ? `t3-link:${Image.resolveAssetSource(markdownLinkIconSource(linkIcon)).uri}`
277 : undefined
278 : undefined
279 }
280 contextMenuConfig={contextMenu ? JSON.stringify(contextMenu) : undefined}
281 style={runStyle(run, props.textStyle)}
282 onPress={
283 href
284 ? () => {
285 if (props.onLinkPress) {
286 props.onLinkPress(href);
287 } else {
288 void Linking.openURL(href);
289 }
290 }
291 : undefined
292 }
293 onContextMenuAction={
294 contextMenu && href && menu
295 ? (event) => menu.onFileContextMenuAction(href, event.nativeEvent.actionIdentifier)
296 : undefined
297 }
298 >
299 {Platform.OS === "android" && run.fileIcon ? (
300 <Image source={markdownFileIconSource(run.fileIcon)} style={styles.inlineIcon} />
301 ) : Platform.OS === "android" && linkIcon ? (
302 <Image
303 source={markdownLinkIconSource(linkIcon)}
304 style={styles.inlineIcon}
305 tintColor={props.textStyle.linkColor}
306 />
307 ) : null}
308 {text}
309 </MarkdownTextPrimitive>
310 );
311 })}
312 </MarkdownTextPrimitive>
313 );
314}