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

FileMarkdownPreview.tsx

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