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

EnrichedMarkdownText.tsx

382 lines13.1 KB

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