@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 03:37 UTC

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