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

EnrichedMarkdownText.tsx

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