Open History to see the last commit
1import { decodeComposerContextFragment } from "@t3tools/shared/composerContextClipboard";
2import {
3 collectComposerContextReferences,
4 formatComposerContextHref,
5 formatComposerContextReference,
6} from "@t3tools/shared/composerContextReferences";
7import {
8 markdownForNativeRendering,
9 markdownWithFileEmbeds,
10 markdownWithHtml,
11 markdownWithInlineFileLinks,
12 markdownWithTableBreaks,
13} from "../lib/markdownDocument";
14import { isValidElement, useCallback, useMemo, useState, type ReactNode } from "react";
15import { Platform, Share, StyleSheet, View } from "react-native";
16import {
17 EnrichedMarkdownText,
18 type MarkdownImageBlock,
19 type MarkdownLinkOccurrence,
20 type MarkdownStyle,
21} from "react-native-enriched-markdown";
22import type { SelectableMarkdownTextProps } from "./SelectableMarkdownText.types";
23
24import { useAppearancePreferences } from "../features/settings/appearance/AppearancePreferencesProvider";
25import { Menu } from "../components/ui/Menu";
26import { useEnrichedLinkVariants } from "./useEnrichedLinkVariants";
27import { useRetryingImageSource } from "./useRetryingImageSource";
28import { copyTextWithHaptic } from "../lib/copyTextWithHaptic";
29import {
30 ENRICHED_INLINE_FILE_LINK_REGEX,
31 enrichedSkillLinkRegex,
32 enrichedLinkVariantPattern,
33} from "../lib/enrichedLinkPresentation";
34
35function enrichedStyle(
36 style: SelectableMarkdownTextProps["textStyle"],
37 dark: boolean,
38): MarkdownStyle {
39 const monospace = Platform.OS === "ios" ? "Menlo" : "monospace";
40 // Keep the radius modest: iOS clips square table-cell borders without stroking the corner arcs.
41 const block = {
42 marginTop: 4,
43 marginBottom: 12,
44 borderRadius: 8,
45 borderWidth: StyleSheet.hairlineWidth,
46 borderColor: style.dividerColor,
47 };
48 const body = {
49 color: style.color,
50 fontFamily: style.fontFamily,
51 fontSize: style.fontSize,
52 lineHeight: style.lineHeight,
53 marginTop: 0,
54 marginBottom: 8,
55 };
56 const heading = (level: number) => {
57 const fontSize = style.headingFontSizes?.[level - 1] ?? style.fontSize * (1.6 - level * 0.1);
58 return {
59 ...body,
60 color: style.strongColor,
61 fontFamily: style.headingFontFamily,
62 fontSize,
63 lineHeight: fontSize * 1.35,
64 marginTop: 8,
65 };
66 };
67 return {
68 paragraph: body,
69 math: {
70 fontSize: style.fontSize,
71 color: style.color,
72 backgroundColor: "transparent",
73 padding: 8,
74 marginTop: 4,
75 marginBottom: 12,
76 },
77 inlineMath: { color: style.color },
78 h1: heading(1),
79 h2: heading(2),
80 h3: heading(3),
81 h4: heading(4),
82 h5: heading(5),
83 h6: heading(6),
84 strong: { color: style.strongColor, fontFamily: style.boldFontFamily, fontWeight: "normal" },
85 link: { color: style.linkColor, underline: false },
86 code: {
87 fontFamily: monospace,
88 color: style.inlineCodeColor,
89 backgroundColor: "transparent",
90 borderColor: "transparent",
91 fontSize: style.fontSize * 0.9,
92 },
93 codeBlock: {
94 ...body,
95 color: style.codeColor,
96 backgroundColor: style.codeBlockBackgroundColor,
97 fontFamily: monospace,
98 fontSize: style.fontSize * 0.9,
99 ...block,
100 padding: 12,
101 syntaxColors: dark
102 ? {
103 keyword: "#ff7b72",
104 string: "#a5d6ff",
105 number: "#79c0ff",
106 constant: "#79c0ff",
107 comment: "#8b949e",
108 function: "#d2a8ff",
109 type: "#ffa657",
110 property: "#79c0ff",
111 tag: "#7ee787",
112 attribute: "#79c0ff",
113 }
114 : {
115 keyword: "#cf222e",
116 string: "#0a3069",
117 number: "#0550ae",
118 constant: "#0550ae",
119 comment: "#6e7781",
120 function: "#8250df",
121 type: "#953800",
122 property: "#0550ae",
123 tag: "#116329",
124 attribute: "#0550ae",
125 },
126 },
127 blockquote: {
128 ...body,
129 color: style.mutedColor,
130 backgroundColor: "transparent",
131 borderColor: style.quoteMarkerColor,
132 borderWidth: 2,
133 gapWidth: 12,
134 },
135 list: { ...body, bulletColor: style.mutedColor, markerColor: style.mutedColor, gapWidth: 6 },
136 thematicBreak: { color: style.dividerColor, height: 1, marginTop: 8, marginBottom: 8 },
137 table: {
138 ...body,
139 ...block,
140 headerFontFamily: style.boldFontFamily,
141 headerTextColor: style.strongColor,
142 headerBackgroundColor: style.codeBlockBackgroundColor,
143 rowEvenBackgroundColor: "transparent",
144 rowOddBackgroundColor: "transparent",
145 cellPaddingHorizontal: 10,
146 cellPaddingVertical: 7,
147 },
148 taskList: {
149 checkedColor: style.linkColor,
150 checkedTextColor: style.color,
151 borderColor: style.mutedColor,
152 checkedStrikethrough: false,
153 },
154 };
155}
156
157export function MobileEnrichedMarkdownText(props: SelectableMarkdownTextProps) {
158 const { renderImage, resolveImageSource, fileEmbedLabel } = props;
159 const { themeAppearance, mathRenderingEnabled } = useAppearancePreferences();
160 const { markdown, fileHrefs } = useMemo(() => {
161 if (!fileEmbedLabel) {
162 return {
163 markdown: markdownForNativeRendering(props.markdown, ENRICHED_INLINE_FILE_LINK_REGEX),
164 fileHrefs: new Set<string>(),
165 };
166 }
167 const content = markdownWithInlineFileLinks(
168 markdownWithHtml(props.markdown),
169 ENRICHED_INLINE_FILE_LINK_REGEX,
170 );
171 const files = markdownWithFileEmbeds(content, fileEmbedLabel);
172 return { ...files, markdown: markdownWithTableBreaks(files.markdown) };
173 }, [props.markdown, fileEmbedLabel]);
174 const [parsedLinkUrls, setParsedLinkUrls] = useState<ReadonlyArray<string>>([]);
175 const onLinksChange = useCallback((links: MarkdownLinkOccurrence[]) => {
176 const urls = [...new Set(links.map((link) => link.url))];
177 setParsedLinkUrls((previous) =>
178 previous.length === urls.length && previous.every((url, index) => url === urls[index])
179 ? previous
180 : urls,
181 );
182 }, []);
183 const skillRegex = useMemo(() => enrichedSkillLinkRegex(props.skills), [props.skills]);
184 // Skill links come from linkRecognition, which runs as the text is drawn, so
185 // onLinksChange never reports them. Joined so a streaming tick keeps the value.
186 const skillLinkKey = useMemo(
187 () =>
188 skillRegex
189 ? [...new Set(markdown.match(new RegExp(skillRegex.source, "gu")) ?? [])].join("\n")
190 : "",
191 [markdown, skillRegex],
192 );
193 const linkUrls = useMemo(
194 () =>
195 skillLinkKey
196 ? [...new Set([...parsedLinkUrls, ...skillLinkKey.split("\n")])]
197 : parsedLinkUrls,
198 [parsedLinkUrls, skillLinkKey],
199 );
200 const { linkVariants, linkPillContent } = useEnrichedLinkVariants(linkUrls, props, fileHrefs);
201 const linkRecognition = useMemo(() => ({ text: skillRegex ?? undefined }), [skillRegex]);
202 const [activeMenu, setActiveMenu] = useState<{
203 url: string;
204 menu: NonNullable<ReturnType<NonNullable<typeof props.fileContextMenu>>>;
205 } | null>(null);
206 const { fileContextMenu, onFileContextMenuAction } = props;
207 const onLinkPress = useCallback(
208 (url: string) =>
209 (fileHrefs.has(url) ? (props.onImagePress ?? props.onLinkPress) : props.onLinkPress)?.(url),
210 [fileHrefs, props.onImagePress, props.onLinkPress],
211 );
212 const performMenuAction = useCallback(
213 (url: string, actionId: string) => {
214 if (actionId === "enriched-open-link") onLinkPress(url);
215 else if (actionId === "enriched-copy-link") copyTextWithHaptic(url);
216 else if (actionId === "enriched-share-link") void Share.share({ message: url });
217 else onFileContextMenuAction?.(url, actionId);
218 },
219 [onLinkPress, onFileContextMenuAction],
220 );
221 const linkContextMenuItems = useMemo(
222 () =>
223 Platform.OS === "ios" && (fileContextMenu || props.onLinkPress || props.onImagePress)
224 ? Object.fromEntries(
225 linkUrls.map((url) => {
226 const menu = fileContextMenu?.(url) ?? {
227 title: url,
228 actions: [
229 { id: "enriched-open-link", title: "Open link" },
230 { id: "enriched-copy-link", title: "Copy link" },
231 { id: "enriched-share-link", title: "Share link" },
232 ],
233 };
234 return [
235 enrichedLinkVariantPattern(url),
236 menu.actions.map((action) => ({
237 text: action.title,
238 disabled: "disabled" in action && action.disabled,
239 onPress: () => performMenuAction(url, action.id),
240 })),
241 ];
242 }),
243 )
244 : undefined,
245 [linkUrls, fileContextMenu, props.onLinkPress, props.onImagePress, performMenuAction],
246 );
247 const selectionClipboard = useMemo(() => {
248 const fragment = decodeComposerContextFragment(props.contextClipboardFragment);
249 if (!fragment) return undefined;
250 const references = collectComposerContextReferences(props.markdown);
251 const linkTextByUrl = Object.fromEntries(
252 references.flatMap((reference) => {
253 const record = fragment.records.find((entry) => entry.contextId === reference.contextId);
254 return record
255 ? [
256 [
257 formatComposerContextHref(reference.kind, reference.contextId),
258 formatComposerContextReference({ ...reference, label: record.label }),
259 ],
260 ]
261 : [];
262 }),
263 );
264 return {
265 linkTextByUrl,
266 htmlAttributes: {
267 "data-t3-context-fragment": encodeURIComponent(props.contextClipboardFragment!),
268 },
269 mimeTypes: { "app.t3.context-fragment": props.contextClipboardFragment! },
270 };
271 }, [props.contextClipboardFragment, props.markdown]);
272 const markdownStyle = useMemo(
273 () => ({ ...enrichedStyle(props.textStyle, themeAppearance === "dark"), linkVariants }),
274 [props.textStyle, themeAppearance, linkVariants],
275 );
276 const renderers = useMemo(
277 () =>
278 renderImage
279 ? {
280 image: (block: MarkdownImageBlock) => {
281 const element = renderImage({
282 href: block.url,
283 alt: block.altText || null,
284 title: block.title || null,
285 });
286 return isValidElement(element) ? element : undefined;
287 },
288 }
289 : undefined,
290 [renderImage],
291 );
292 const resolveNativeImageSource = useRetryingImageSource(resolveImageSource);
293 const renderMarkdown = (openAndroidMenu?: () => void) => {
294 const onLinkLongPress =
295 Platform.OS === "android" && props.fileContextMenu
296 ? ({ url }: { url: string }) => {
297 const menu = props.fileContextMenu?.(url) ?? {
298 title: url,
299 actions: [
300 { id: "enriched-open-link", title: "Open link" },
301 { id: "enriched-copy-link", title: "Copy link" },
302 ],
303 };
304 setActiveMenu({ url, menu });
305 openAndroidMenu?.();
306 }
307 : undefined;
308
309 return (
310 <View
311 style={{
312 flexShrink: 1,
313 minWidth: 0,
314 marginTop: props.marginTop,
315 marginBottom: props.marginBottom,
316 }}
317 >
318 <EnrichedMarkdownText
319 markdown={markdown}
320 markdownStyle={markdownStyle}
321 onLinksChange={onLinksChange}
322 renderers={renderers}
323 resolveImageSource={resolveNativeImageSource}
324 onImagePress={
325 props.onImagePress || props.onLinkPress
326 ? ({ url }) => (props.onImagePress ?? props.onLinkPress)?.(url)
327 : undefined
328 }
329 linkRecognition={linkRecognition}
330 containerStyle={{ flexShrink: 1, minWidth: 0 }}
331 flavor="github"
332 selectable
333 selectionClipboard={selectionClipboard}
334 selectionColor={props.textStyle.selectionColor}
335 selectionHandleColor={props.textStyle.selectionHandleColor}
336 md4cFlags={{
337 latexMath: mathRenderingEnabled,
338 hardSoftBreaks: props.preserveSoftBreaks ?? false,
339 admonitions: true,
340 }}
341 enableTaskListItemToggle={false}
342 enableCodeBlockWrapToggle
343 spoilerOverlay="solid"
344 onLinkPress={
345 props.onLinkPress || props.onImagePress ? ({ url }) => onLinkPress(url) : undefined
346 }
347 onLinkLongPress={onLinkLongPress}
348 linkContextMenuItems={linkContextMenuItems}
349 linkPillContent={linkPillContent}
350 />
351 </View>
352 );
353 };
354
355 return Platform.OS === "android" && props.fileContextMenu ? (
356 <Menu
357 shouldOpenOnLongPress
358 title={activeMenu?.menu.title}
359 actions={
360 activeMenu?.menu.actions.map((action) => ({
361 id: action.id,
362 title: action.title,
363 attributes: { disabled: action.disabled },
364 })) ?? []
365 }
366 onPressAction={({ nativeEvent }) => {
367 if (activeMenu) performMenuAction(activeMenu.url, nativeEvent.event);
368 }}
369 style={{ flexShrink: 1, minWidth: 0 }}
370 >
371 <MarkdownMenuAnchor renderMarkdown={renderMarkdown} />
372 </Menu>
373 ) : (
374 renderMarkdown()
375 );
376}
377
378function MarkdownMenuAnchor(props: {
379 readonly renderMarkdown: (openMenu?: () => void) => ReactNode;
380 readonly onLongPress?: () => void;
381}) {
382 return props.renderMarkdown(props.onLongPress);
383}