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

EnrichedMarkdownText.tsx

365 lines12.2 KB

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