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

EnrichedMarkdownText.tsx

531 lines18.3 KB

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