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

EnrichedMarkdownText.tsx

378 lines12.9 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 () => ({
269 ...enrichedStyle(props.textStyle, themeAppearance === "dark", fontScale),
270 linkVariants,
271 }),
272 [props.textStyle, themeAppearance, fontScale, linkVariants],
273 );
274 const renderers = renderImage
275 ? {
276 image: (block: MarkdownImageBlock) => {
277 const element = renderImage({
278 href: block.url,
279 alt: block.altText || null,
280 title: block.title || null,
281 });
282 return isValidElement(element) ? element : undefined;
283 },
284 }
285 : undefined;
286 const resolveNativeImageSource = useRetryingImageSource(resolveImageSource);
287 const renderMarkdown = (openAndroidMenu?: () => void) => {
288 const onLinkLongPress =
289 Platform.OS === "android" && props.fileContextMenu
290 ? ({ url }: { url: string }) => {
291 const menu = props.fileContextMenu?.(url) ?? {
292 title: url,
293 actions: [
294 { id: "enriched-open-link", title: "Open link" },
295 { id: "enriched-copy-link", title: "Copy link" },
296 ],
297 };
298 setActiveMenu({ url, menu });
299 openAndroidMenu?.();
300 }
301 : undefined;
302​
303 return (
304 <View
305 style={{
306 flexShrink: 1,
307 minWidth: 0,
308 marginTop: props.marginTop,
309 marginBottom: props.marginBottom,
310 }}
311 >
312 <EnrichedMarkdownText
313 markdown={markdown}
314 markdownStyle={markdownStyle}
315 onLinksChange={onLinksChange}
316 renderers={renderers}
317 resolveImageSource={resolveNativeImageSource}
318 onImagePress={
319 props.onImagePress || props.onLinkPress
320 ? ({ url }) => (props.onImagePress ?? props.onLinkPress)?.(url)
321 : undefined
322 }
323 linkRecognition={linkRecognition}
324 containerStyle={{ flexShrink: 1, minWidth: 0 }}
325 flavor="github"
326 selectable
327 selectionClipboard={selectionClipboard}
328 selectionColor={props.textStyle.selectionColor}
329 selectionHandleColor={props.textStyle.selectionHandleColor}
330 md4cFlags={{
331 latexMath: mathRenderingEnabled,
332 hardSoftBreaks: props.preserveSoftBreaks ?? false,
333 admonitions: true,
334 preserveWindowsPaths: true,
335 }}
336 enableTaskListItemToggle={false}
337 enableCodeBlockWrapToggle
338 spoilerOverlay="solid"
339 onLinkPress={
340 props.onLinkPress || props.onImagePress ? ({ url }) => onLinkPress(url) : undefined
341 }
342 onLinkLongPress={onLinkLongPress}
343 linkContextMenuItems={linkContextMenuItems}
344 linkPillContent={linkPillContent}
345 />
346 </View>
347 );
348 };
349​
350 return Platform.OS === "android" && props.fileContextMenu ? (
351 <Menu
352 shouldOpenOnLongPress
353 title={activeMenu?.menu.title}
354 actions={
355 activeMenu?.menu.actions.map((action) => ({
356 id: action.id,
357 title: action.title,
358 attributes: { disabled: action.disabled },
359 })) ?? []
360 }
361 onPressAction={({ nativeEvent }) => {
362 if (activeMenu) performMenuAction(activeMenu.url, nativeEvent.event);
363 }}
364 style={{ flexShrink: 1, minWidth: 0 }}
365 >
366 <MarkdownMenuAnchor renderMarkdown={renderMarkdown} />
367 </Menu>
368 ) : (
369 renderMarkdown()
370 );
372​
373function MarkdownMenuAnchor(props: {
374 readonly renderMarkdown: (openMenu?: () => void) => ReactNode;
375 readonly onLongPress?: () => void;
376}) {
377 return props.renderMarkdown(props.onLongPress);