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