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

NativeMarkdownSelectableText.ios.tsx

294 lines9.7 KB

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