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