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