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