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

EnrichedMarkdownText.tsx

447 lines15.5 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 ReactElement, type ReactNode } from "react";
15import { Platform, Share, StyleSheet, useWindowDimensions, View } from "react-native";
16import {
17 EnrichedMarkdownText,
18 type MarkdownCodeBlock,
19 type MarkdownImageBlock,
20 type MarkdownLinkOccurrence,
21 type MarkdownStyle,
22} from "react-native-enriched-markdown";
23import { MermaidCodeBlock } from "./MermaidCodeBlock";
24import type { SelectableMarkdownTextProps } from "./SelectableMarkdownText.types";
25​
26import { useAppearancePreferences } from "../features/settings/appearance/AppearancePreferencesProvider";
27import { Menu } from "../components/ui/Menu";
28import { useEnrichedLinkVariants } from "./useEnrichedLinkVariants";
29import { useRetryingImageSource } from "./useRetryingImageSource";
30import * as Dialog from "../components/ui/Dialog";
31import { copyTextWithHaptic } from "../lib/copyTextWithHaptic";
32import {
33 ENRICHED_INLINE_FILE_LINK_REGEX,
34 enrichedTextLinkRegex,
35 enrichedModelDetails,
36 enrichedModelReference,
37 enrichedLinkVariantPattern,
38} from "../lib/enrichedLinkPresentation";
39​
40function enrichedStyle(
41 style: SelectableMarkdownTextProps["textStyle"],
42 dark: boolean,
43 fontScale: number,
44): MarkdownStyle {
45 const monospace = Platform.OS === "ios" ? "Menlo" : "monospace";
46 // Keep the radius modest: iOS clips square table-cell borders without stroking the corner arcs.
47 const block = {
48 marginTop: 4,
49 marginBottom: 12,
50 borderRadius: 8,
51 borderWidth: StyleSheet.hairlineWidth,
52 borderColor: style.dividerColor,
53 };
54 const body = {
55 color: style.color,
56 fontFamily: style.fontFamily,
57 fontSize: style.fontSize,
58 lineHeight: style.lineHeight,
59 marginTop: 0,
60 marginBottom: 8,
61 };
62 const heading = (level: number) => {
63 const fontSize = style.headingFontSizes?.[level - 1] ?? style.fontSize * (1.6 - level * 0.1);
64 return {
65 ...body,
66 color: style.strongColor,
67 fontFamily: style.headingFontFamily,
68 fontSize,
69 lineHeight: fontSize * 1.35,
70 marginTop: 8,
71 };
72 };
73 return {
74 paragraph: body,
75 math: {
76 fontSize: style.fontSize,
77 color: style.color,
78 backgroundColor: "transparent",
79 padding: 8,
80 marginTop: 4,
81 marginBottom: 12,
82 },
83 inlineMath: { color: style.color },
84 h1: heading(1),
85 h2: heading(2),
86 h3: heading(3),
87 h4: heading(4),
88 h5: heading(5),
89 h6: heading(6),
90 strong: { color: style.strongColor, fontFamily: style.boldFontFamily, fontWeight: "normal" },
91 link: { color: style.linkColor, underline: false },
92 code: {
93 fontFamily: monospace,
94 color: style.inlineCodeColor,
95 backgroundColor: "transparent",
96 borderColor: "transparent",
97 fontSize: style.fontSize * 0.9,
98 },
99 codeBlock: {
100 ...body,
101 color: style.codeColor,
102 backgroundColor: style.codeBlockBackgroundColor,
103 fontFamily: monospace,
104 fontSize: style.fontSize * 0.9,
105 ...block,
106 padding: 12,
107 syntaxColors: dark
108 ? {
109 keyword: "#ff7b72",
110 string: "#a5d6ff",
111 number: "#79c0ff",
112 constant: "#79c0ff",
113 comment: "#8b949e",
114 function: "#d2a8ff",
115 type: "#ffa657",
116 property: "#79c0ff",
117 tag: "#7ee787",
118 attribute: "#79c0ff",
119 }
120 : {
121 keyword: "#cf222e",
122 string: "#0a3069",
123 number: "#0550ae",
124 constant: "#0550ae",
125 comment: "#6e7781",
126 function: "#8250df",
127 type: "#953800",
128 property: "#0550ae",
129 tag: "#116329",
130 attribute: "#0550ae",
131 },
132 },
133 blockquote: {
134 ...body,
135 color: style.mutedColor,
136 backgroundColor: "transparent",
137 borderColor: style.quoteMarkerColor,
138 borderWidth: 2,
139 gapWidth: 12,
140 },
141 list: {
142 ...body,
143 bulletColor: style.mutedColor,
144 markerColor: style.mutedColor,
145 // The bullet is centred on the gap's edge and scales with the system text size; the gap must too.
146 gapWidth: 12 * fontScale,
147 },
148 thematicBreak: { color: style.dividerColor, height: 1, marginTop: 8, marginBottom: 8 },
149 table: {
150 ...body,
151 ...block,
152 headerFontFamily: style.boldFontFamily,
153 headerTextColor: style.strongColor,
154 headerBackgroundColor: style.codeBlockBackgroundColor,
155 rowEvenBackgroundColor: "transparent",
156 rowOddBackgroundColor: "transparent",
157 cellPaddingHorizontal: 10,
158 cellPaddingVertical: 7,
159 },
160 taskList: {
161 checkedColor: style.linkColor,
162 checkedTextColor: style.color,
163 borderColor: style.mutedColor,
164 checkedStrikethrough: false,
165 },
166 };
168​
169/** Diagram and math fences, as web draws them. A fence streams as native code until it closes. */
170function codeBlockElement(
171 block: MarkdownCodeBlock,
172 textStyle: SelectableMarkdownTextProps["textStyle"],
173 markdownStyle: MarkdownStyle,
174 mathRenderingEnabled: boolean,
175): ReactElement | undefined {
176 if (!block.isComplete) return undefined;
177 if (block.language === "mermaid") {
178 return <MermaidCodeBlock code={block.code} textStyle={textStyle} />;
179 }
180 if (block.language === "math" && mathRenderingEnabled) {
181 return (
182 <EnrichedMarkdownText
183 // A blank line would end the paragraph, and so the math, early.
184 markdown={`$$\n${block.code.replace(/\n\s*\n/g, "\n").trim()}\n$$`}
185 markdownStyle={markdownStyle}
186 md4cFlags={{ latexMath: true }}
187 containerStyle={{ flexShrink: 1, minWidth: 0 }}
188 flavor="github"
189 selectable
190 selectionColor={textStyle.selectionColor}
191 selectionHandleColor={textStyle.selectionHandleColor}
192 />
193 );
194 }
195 return undefined;
197​
198export function MobileEnrichedMarkdownText(props: SelectableMarkdownTextProps) {
199 const { renderImage, resolveImageSource, fileEmbedLabel } = props;
200 const { themeAppearance, mathRenderingEnabled } = useAppearancePreferences();
201 const { markdown, fileHrefs } = useMemo(() => {
202 if (!fileEmbedLabel) {
203 return {
204 markdown: markdownForNativeRendering(props.markdown, ENRICHED_INLINE_FILE_LINK_REGEX),
205 fileHrefs: new Set<string>(),
206 };
207 }
208 const content = markdownWithInlineFileLinks(
209 markdownForNativeParsing(props.markdown),
210 ENRICHED_INLINE_FILE_LINK_REGEX,
211 );
212 const files = markdownWithFileEmbeds(content, fileEmbedLabel);
213 return { ...files, markdown: markdownWithTableBreaks(files.markdown) };
214 }, [props.markdown, fileEmbedLabel]);
215 const [parsedLinkUrls, setParsedLinkUrls] = useState<ReadonlyArray<string>>([]);
216 const onLinksChange = (links: MarkdownLinkOccurrence[]) => {
217 const urls = [...new Set(links.map((link) => link.url))];
218 setParsedLinkUrls((previous) =>
219 previous.length === urls.length && previous.every((url, index) => url === urls[index])
220 ? previous
221 : urls,
222 );
223 };
224 const textLinkRegex = useMemo(
225 () => enrichedTextLinkRegex(props.skills, props.models),
226 [props.skills, props.models],
227 );
228 // Recognized text links are added as the text is drawn, so
229 // onLinksChange never reports them. Joined so a streaming tick keeps the value.
230 const textLinkKey = useMemo(
231 () =>
232 textLinkRegex
233 ? [...new Set(markdown.match(new RegExp(textLinkRegex.source, "gu")) ?? [])].join("\n")
234 : "",
235 [markdown, textLinkRegex],
236 );
237 const linkUrls = textLinkKey
238 ? [...new Set([...parsedLinkUrls, ...textLinkKey.split("\n")])]
239 : parsedLinkUrls;
240 const { linkVariants, linkPillContent } = useEnrichedLinkVariants(linkUrls, props, fileHrefs);
241 const linkRecognition = useMemo(() => ({ text: textLinkRegex ?? undefined }), [textLinkRegex]);
242 const [activeMenu, setActiveMenu] = useState<{
243 url: string;
244 menu: NonNullable<ReturnType<NonNullable<typeof props.fileContextMenu>>>;
245 } | null>(null);
246 const { fileContextMenu, onFileContextMenuAction } = props;
247 const onLinkPress = (url: string) => {
248 const model = enrichedModelReference(url, props.models);
249 if (model) {
250 Dialog.alert(model.label, enrichedModelDetails(model));
251 return;
252 }
253 (fileHrefs.has(url) ? (props.onImagePress ?? props.onLinkPress) : props.onLinkPress)?.(url);
254 };
255 const modelContextMenu = (url: string) => {
256 const model = enrichedModelReference(url, props.models);
257 return model
258 ? {
259 title: model.label,
260 actions: [
261 { id: "enriched-copy-link", title: "Copy model reference" },
262 { id: "enriched-share-link", title: "Share model reference" },
263 ],
264 }
265 : undefined;
266 };
267 const performMenuAction = (url: string, actionId: string) => {
268 if (actionId === "enriched-open-link") onLinkPress(url);
269 else if (actionId === "enriched-copy-link") copyTextWithHaptic(url);
270 else if (actionId === "enriched-share-link") void Share.share({ message: url });
271 else onFileContextMenuAction?.(url, actionId);
272 };
273 const linkContextMenuItems =
274 Platform.OS === "ios" && (fileContextMenu || props.onLinkPress || props.onImagePress)
275 ? Object.fromEntries(
276 linkUrls.map((url) => {
277 const menu = modelContextMenu(url) ??
278 fileContextMenu?.(url) ?? {
279 title: url,
280 actions: [
281 { id: "enriched-open-link", title: "Open link" },
282 { id: "enriched-copy-link", title: "Copy link" },
283 { id: "enriched-share-link", title: "Share link" },
284 ],
285 };
286 return [
287 enrichedLinkVariantPattern(url),
288 menu.actions.map((action) => ({
289 text: action.title,
290 disabled: "disabled" in action && action.disabled,
291 onPress: () => performMenuAction(url, action.id),
292 })),
293 ];
294 }),
295 )
296 : undefined;
297 const selectionClipboard = useMemo(() => {
298 const fragment = decodeComposerContextFragment(props.contextClipboardFragment);
299 if (!fragment) return undefined;
300 const references = collectComposerContextReferences(props.markdown);
301 const linkTextByUrl = Object.fromEntries(
302 references.flatMap((reference) => {
303 const record = fragment.records.find((entry) => entry.contextId === reference.contextId);
304 return record
305 ? [
306 [
307 formatComposerContextHref(reference.kind, reference.contextId),
308 formatComposerContextReference({ ...reference, label: record.label }),
309 ],
310 ]
311 : [];
312 }),
313 );
314 return {
315 linkTextByUrl,
316 htmlAttributes: {
317 "data-t3-context-fragment": encodeURIComponent(props.contextClipboardFragment!),
318 },
319 mimeTypes: { "app.t3.context-fragment": props.contextClipboardFragment! },
320 };
321 }, [props.contextClipboardFragment, props.markdown]);
322 const { fontScale } = useWindowDimensions();
323 const baseMarkdownStyle = useMemo(() => {
324 const style = enrichedStyle(props.textStyle, themeAppearance === "dark", fontScale);
325 return {
326 ...style,
327 paragraph: props.textAlign
328 ? { ...style.paragraph, textAlign: props.textAlign }
329 : style.paragraph,
330 };
331 }, [props.textStyle, props.textAlign, themeAppearance, fontScale]);
332 // Link variants change as a message streams. The code renderer reads only the base style, so
333 // it stays the same function and the library keeps its rendered blocks.
334 const markdownStyle = useMemo(
335 () => ({ ...baseMarkdownStyle, linkVariants }),
336 [baseMarkdownStyle, linkVariants],
337 );
338 const renderers = {
339 image: renderImage
340 ? (block: MarkdownImageBlock) => {
341 const element = renderImage({
342 href: block.url,
343 alt: block.altText || null,
344 title: block.title || null,
345 });
346 return isValidElement(element) ? element : undefined;
347 }
348 : undefined,
349 code: (block: MarkdownCodeBlock) =>
350 codeBlockElement(block, props.textStyle, baseMarkdownStyle, mathRenderingEnabled),
351 };
352 const resolveNativeImageSource = useRetryingImageSource(resolveImageSource);
353 const renderMarkdown = (openAndroidMenu?: () => void) => {
354 const onLinkLongPress =
355 Platform.OS === "android" && props.fileContextMenu
356 ? ({ url }: { url: string }) => {
357 const menu = modelContextMenu(url) ??
358 props.fileContextMenu?.(url) ?? {
359 title: url,
360 actions: [
361 { id: "enriched-open-link", title: "Open link" },
362 { id: "enriched-copy-link", title: "Copy link" },
363 ],
364 };
365 setActiveMenu({ url, menu });
366 openAndroidMenu?.();
367 }
368 : undefined;
369​
370 return (
371 <View
372 style={{
373 flexShrink: 1,
374 minWidth: 0,
375 marginTop: props.marginTop,
376 marginBottom: props.marginBottom,
377 }}
378 >
379 <EnrichedMarkdownText
380 markdown={markdown}
381 markdownStyle={markdownStyle}
382 writingDirection={props.writingDirection}
383 onLinksChange={onLinksChange}
384 renderers={renderers}
385 resolveImageSource={resolveNativeImageSource}
386 onImagePress={
387 props.onImagePress || props.onLinkPress
388 ? ({ url }) => (props.onImagePress ?? props.onLinkPress)?.(url)
389 : undefined
390 }
391 linkRecognition={linkRecognition}
392 containerStyle={{ flexShrink: 1, minWidth: 0 }}
393 flavor="github"
394 selectable
395 selectionClipboard={selectionClipboard}
396 selectionColor={props.textStyle.selectionColor}
397 selectionHandleColor={props.textStyle.selectionHandleColor}
398 md4cFlags={{
399 latexMath: mathRenderingEnabled,
400 hardSoftBreaks: props.preserveSoftBreaks ?? false,
401 admonitions: true,
402 preserveWindowsPaths: true,
403 }}
404 enableTaskListItemToggle={props.onTaskListItemPress !== undefined}
405 onTaskListItemPress={props.onTaskListItemPress}
406 enableCodeBlockWrapToggle
407 spoilerOverlay="solid"
408 onLinkPress={
409 props.onLinkPress || props.onImagePress ? ({ url }) => onLinkPress(url) : undefined
410 }
411 onLinkLongPress={onLinkLongPress}
412 linkContextMenuItems={linkContextMenuItems}
413 linkPillContent={linkPillContent}
414 />
415 </View>
416 );
417 };
418​
419 return Platform.OS === "android" && props.fileContextMenu ? (
420 <Menu
421 shouldOpenOnLongPress
422 title={activeMenu?.menu.title}
423 actions={
424 activeMenu?.menu.actions.map((action) => ({
425 id: action.id,
426 title: action.title,
427 attributes: { disabled: action.disabled },
428 })) ?? []
429 }
430 onPressAction={({ nativeEvent }) => {
431 if (activeMenu) performMenuAction(activeMenu.url, nativeEvent.event);
432 }}
433 style={{ flexShrink: 1, minWidth: 0 }}
434 >
435 <MarkdownMenuAnchor renderMarkdown={renderMarkdown} />
436 </Menu>
437 ) : (
438 renderMarkdown()
439 );
441​
442function MarkdownMenuAnchor(props: {
443 readonly renderMarkdown: (openMenu?: () => void) => ReactNode;
444 readonly onLongPress?: () => void;
445}) {
446 return props.renderMarkdown(props.onLongPress);