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