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

FileMarkdownPreview.tsx

262 lines9.5 KB

1import { settlePromise } from "@t3tools/client-runtime/state/runtime";
2import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
3import { resolveMobileMarkdownMediaSource } from "../../lib/markdownMediaSource";
4import { getBrowseDirectoryPath } from "@t3tools/client-runtime/state/projects";
5import { useState } from "react";
6import { StackActions, useNavigation } from "@react-navigation/native";
7import { RefreshControl, ScrollView, View } from "react-native";
8​
9import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
10import { FONT_FAMILIES } from "../../lib/fontFamilies";
11import { resolveNativeMarkdownTypography } from "../../lib/appearancePreferences";
12import { useUniwindTheme } from "../../lib/useUniwindTheme";
13import {
14 ThreadMarkdownImage,
15 ThreadMarkdownImageView,
16 ThreadMarkdownImageUnavailable,
17} from "../threads/ThreadMarkdownImage";
18import { ThreadMarkdownVideo } from "../threads/ThreadMarkdownVideo";
19import { markdownFileEmbedLabel, resolveMarkdownMediaPreview } from "../../lib/markdownMedia";
20import {
21 normalizeNativeMarkdownUrl,
22 resolveMarkdownLinkPresentation,
23} from "../../lib/markdownLinks";
24import { AppText as Text } from "../../components/ui/AppText";
25import { VideoPreviewModal, type VideoPreviewSource } from "../../components/VideoPreviewModal";
26import { FilePreviewModal, type FilePreviewSource } from "../../components/FilePreviewModal";
27import { useMarkdownImageSource } from "../../native/useMarkdownImageSource";
28import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
29import {
30 SelectableMarkdownText,
31 type MarkdownImageRenderer,
32 type NativeMarkdownTextStyle,
33} from "../../native/SelectableMarkdownText";
34import { fileRoutePathSegments, resolveWorkspaceFilePath } from "./filePath";
35​
36interface MarkdownPreviewStyles {
37 readonly nativeTextStyle: NativeMarkdownTextStyle;
39​
40export function useMarkdownPreviewStyles(): MarkdownPreviewStyles {
41 const { appearance } = useAppearancePreferences();
42 const nativeMarkdownTypography = resolveNativeMarkdownTypography(appearance.baseFontSize);
43 const theme = useUniwindTheme();
44 const body = theme["--color-md-body"];
45 const strong = theme["--color-md-strong"];
46 const link = theme["--color-md-link"];
47 const blockquoteBorder = theme["--color-md-blockquote-border"];
48 const codeBackground = theme["--color-md-code-bg"];
49 const codeText = theme["--color-md-code-text"];
50 const horizontalRule = theme["--color-md-hr"];
51 const regularFontFamily = FONT_FAMILIES.regular;
52 const boldFontFamily = FONT_FAMILIES.bold;
53​
54 return {
55 nativeTextStyle: {
56 color: body,
57 strongColor: strong,
58 mutedColor: body,
59 linkColor: link,
60 inlineCodeColor: codeText,
61 codeColor: codeText,
62 codeBackgroundColor: codeBackground,
63 codeBlockBackgroundColor: codeBackground,
64 fileTextColor: codeText,
65 quoteMarkerColor: blockquoteBorder,
66 dividerColor: horizontalRule,
67 fontSize: nativeMarkdownTypography.fontSize,
68 lineHeight: nativeMarkdownTypography.lineHeight,
69 headingFontSizes: nativeMarkdownTypography.headingFontSizes,
70 fontFamily: regularFontFamily,
71 headingFontFamily: boldFontFamily,
72 boldFontFamily,
73 },
74 };
76​
77export function FileMarkdownPreview(props: {
78 readonly cwd: string;
79 readonly captured?: boolean;
80 readonly environmentId: EnvironmentId;
81 readonly markdown: string;
82 readonly relativePath: string;
83 readonly threadId: ThreadId | null;
84 readonly onRefresh?: () => Promise<void> | void;
85}) {
86 const navigation = useNavigation();
87 const [isPullRefreshing, setIsPullRefreshing] = useState(false);
88 const [expandedFile, setExpandedFile] = useState<FilePreviewSource | null>(null);
89 const [expandedVideo, setExpandedVideo] = useState<VideoPreviewSource | null>(null);
90 const handlePullToRefresh = async () => {
91 if (!props.onRefresh) {
92 return;
93 }
94 setIsPullRefreshing(true);
95 // RefreshControl only needs the spinner cleared; the caller surfaces its own errors.
96 await settlePromise(async () => props.onRefresh?.());
97 setIsPullRefreshing(false);
98 };
99 const markdownDirectory = getBrowseDirectoryPath(
100 resolveWorkspaceFilePath(props.cwd, props.relativePath),
101 );
102 const renderImage: MarkdownImageRenderer = (image) => {
103 const media = resolveMobileMarkdownMediaSource(image.href, {
104 threadId: props.threadId ?? undefined,
105 workspaceRoot: markdownDirectory,
106 imageEmbed: true,
107 });
108 const preview = resolveMarkdownMediaPreview(image.href, {
109 environmentId: props.environmentId,
110 threadId: props.threadId ?? undefined,
111 workspaceRoot: markdownDirectory,
112 captured: props.captured,
113 imageEmbed: true,
114 });
115 const fileLink = resolveMarkdownLinkPresentation(image.href);
116 if (
117 (preview && preview.kind !== "image" && preview.kind !== "video") ||
118 (!props.captured && fileLink.kind === "file" && fileLink.line !== undefined)
119 ) {
120 const name =
121 preview?.source.name ?? (fileLink.kind === "file" ? fileLink.label : "Open file");
122 return (
123 <Text
124 accessibilityRole="link"
125 accessibilityLabel={`Open ${name}`}
126 onPress={() => openMedia(image.href, true)}
127 style={{ color: styles.nativeTextStyle.linkColor }}
128 >
129 {name}
130 </Text>
131 );
132 }
133 if (media?.access === "direct") {
134 if (media.kind === "video") {
135 return (
136 <ThreadMarkdownVideo
137 source={{
138 type: "media",
139 name: media.name,
140 mimeType: media.mimeType,
141 uri: normalizeNativeMarkdownUrl(media.uri),
142 actionsSource: preview?.source.actionsSource,
143 }}
144 thumbnailVisible
145 />
146 );
147 }
148 return (
149 <ThreadMarkdownImageView
150 uri={normalizeNativeMarkdownUrl(media.uri)}
151 sourceKey={media.uri}
152 unavailable={false}
153 alt={image.alt}
154 format={media.mimeType === "image/svg+xml" ? "svg" : undefined}
155 actionsSource={preview?.source.actionsSource}
156 onPressPreview={setExpandedFile}
157 />
158 );
159 }
160 if (props.captured || media === null || media.access === "unavailable") {
161 return <ThreadMarkdownImageUnavailable alt={image.alt} />;
162 }
163 if (media.kind === "video") {
164 return preview?.kind === "video" ? (
165 <ThreadMarkdownVideo source={preview.source} thumbnailVisible />
166 ) : (
167 <ThreadMarkdownImageUnavailable alt={image.alt} />
168 );
169 }
170 return (
171 <ThreadMarkdownImage
172 environmentId={props.environmentId}
173 resource={media.resource}
174 alt={image.alt}
175 srcFragment={media.srcFragment}
176 actionsSource={preview?.source.actionsSource}
177 onPressPreview={setExpandedFile}
178 />
179 );
180 };
181 const styles = useMarkdownPreviewStyles();
182 const resolveImageSource = useMarkdownImageSource({
183 environmentId: props.environmentId,
184 threadId: props.threadId,
185 workspaceRoot: markdownDirectory,
186 captured: props.captured,
187 });
188 const openMedia = (href: string, imageEmbed = false) => {
189 const media = resolveMarkdownMediaPreview(href, {
190 environmentId: props.environmentId,
191 threadId: props.threadId ?? undefined,
192 workspaceRoot: markdownDirectory,
193 captured: props.captured,
194 imageEmbed,
195 });
196 if (!media || media.kind === "file") {
197 const fileLink = resolveMarkdownLinkPresentation(href);
198 if (props.captured || fileLink.kind !== "file") return false;
199 const params = {
200 environmentId: String(props.environmentId),
201 path: fileRoutePathSegments(resolveWorkspaceFilePath(markdownDirectory, fileLink.path)),
202 ...(fileLink.line ? { line: String(fileLink.line) } : {}),
203 };
204 if (props.threadId) {
205 navigation.navigate("ThreadFile", { ...params, threadId: String(props.threadId) });
206 } else {
207 navigation.dispatch(StackActions.push("NewTaskFile", { ...params, cwd: props.cwd }));
208 }
209 return true;
210 }
211 if (media.kind === "video") setExpandedVideo(media.source);
212 else setExpandedFile(media.source);
213 return true;
214 };
215 const onImagePress = (href: string) => {
216 openMedia(href, true);
217 };
218 const onLinkPress = (href: string) => {
219 if (!openMedia(href)) void tryOpenExternalUrl(href, "markdown-link");
220 };
221​
222 return (
223 <ScrollView
224 className="flex-1 bg-sheet"
225 contentInsetAdjustmentBehavior="automatic"
226 contentContainerStyle={{ padding: 18 }}
227 refreshControl={
228 props.onRefresh ? (
229 <RefreshControl
230 refreshing={isPullRefreshing}
231 onRefresh={() => void handlePullToRefresh()}
232 />
233 ) : undefined
234 }
235 >
236 <View className="mx-auto w-full max-w-[760px]">
237 <SelectableMarkdownText
238 markdown={props.markdown}
239 fileEmbedLabel={(href) =>
240 markdownFileEmbedLabel(
241 href,
242 {
243 environmentId: props.environmentId,
244 threadId: props.threadId ?? undefined,
245 workspaceRoot: markdownDirectory,
246 captured: props.captured,
247 },
248 false,
249 )
250 }
251 onLinkPress={onLinkPress}
252 renderImage={renderImage}
253 resolveImageSource={resolveImageSource}
254 onImagePress={onImagePress}
255 textStyle={styles.nativeTextStyle}
256 />
257 <FilePreviewModal source={expandedFile} onRequestClose={() => setExpandedFile(null)} />
258 <VideoPreviewModal source={expandedVideo} onRequestClose={() => setExpandedVideo(null)} />
259 </View>
260 </ScrollView>
261 );