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

FileMarkdownPreview.tsx

307 lines11.1 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 { useGT } from "gt-react-native";
7import { useState } from "react";
8import { StackActions, useNavigation } from "@react-navigation/native";
9import { View } from "react-native";
10import { LegendList } from "@legendapp/list/react-native";
11import {
12 LARGE_MARKDOWN_CHUNK_MAX_CHARS,
13 splitMarkdown,
14 withMarkdownDefinitions,
15} from "@t3tools/shared/markdownChunks";
16import { NativeScrollView } from "../../native/NativeScrollViewMarker";
17import { RefreshControl } from "../../components/ui/RefreshControl";
18​
19import { tryOpenWebLink } from "../../lib/openExternalUrl";
20import { FONT_FAMILIES } from "../../lib/fontFamilies";
21import { resolveNativeMarkdownTypography } from "../../lib/appearancePreferences";
22import { useUniwindTheme } from "../../lib/useUniwindTheme";
23import {
24 ThreadMarkdownImage,
25 ThreadMarkdownImageView,
26 ThreadMarkdownImageUnavailable,
27} from "../threads/ThreadMarkdownImage";
28import { ThreadMarkdownVideo } from "../threads/ThreadMarkdownVideo";
29import { markdownFileEmbedLabel, resolveMarkdownMediaPreview } from "../../lib/markdownMedia";
30import {
31 normalizeNativeMarkdownUrl,
32 resolveMarkdownLinkPresentation,
33} from "../../lib/markdownLinks";
34import { AppText as Text } from "../../components/ui/AppText";
35import { VideoPreviewModal, type VideoPreviewSource } from "../../components/ui/VideoPreviewModal";
36import { FilePreviewModal, type FilePreviewSource } from "../../components/ui/FilePreviewModal";
37import { useMarkdownImageSource } from "../../native/useMarkdownImageSource";
38import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
39import {
40 SelectableMarkdownText,
41 type MarkdownImageRenderer,
42 type NativeMarkdownTextStyle,
43} from "../../native/SelectableMarkdownText";
44import { fileRoutePathSegments, resolveWorkspaceFilePath } from "./filePath";
45import { SourceFileSurface } from "./SourceFileSurface";
46​
47interface MarkdownPreviewStyles {
48 readonly nativeTextStyle: NativeMarkdownTextStyle;
50​
51export function useMarkdownPreviewStyles(): MarkdownPreviewStyles {
52 const { appearance } = useAppearancePreferences();
53 const nativeMarkdownTypography = resolveNativeMarkdownTypography(appearance.baseFontSize);
54 const theme = useUniwindTheme();
55 const body = theme["--color-md-body"];
56 const strong = theme["--color-md-strong"];
57 const link = theme["--color-md-link"];
58 const blockquoteBorder = theme["--color-md-blockquote-border"];
59 const codeBackground = theme["--color-md-code-bg"];
60 const codeText = theme["--color-md-code-text"];
61 const horizontalRule = theme["--color-md-hr"];
62 const regularFontFamily = FONT_FAMILIES.regular;
63 const boldFontFamily = FONT_FAMILIES.bold;
64​
65 return {
66 nativeTextStyle: {
67 color: body,
68 strongColor: strong,
69 mutedColor: body,
70 linkColor: link,
71 inlineCodeColor: codeText,
72 codeColor: codeText,
73 codeBackgroundColor: codeBackground,
74 codeBlockBackgroundColor: codeBackground,
75 fileTextColor: codeText,
76 quoteMarkerColor: blockquoteBorder,
77 dividerColor: horizontalRule,
78 fontSize: nativeMarkdownTypography.fontSize,
79 lineHeight: nativeMarkdownTypography.lineHeight,
80 headingFontSizes: nativeMarkdownTypography.headingFontSizes,
81 fontFamily: regularFontFamily,
82 headingFontFamily: boldFontFamily,
83 boldFontFamily,
84 },
85 };
87​
88export function FileMarkdownPreview(props: {
89 readonly cwd: string;
90 readonly captured?: boolean;
91 readonly environmentId: EnvironmentId;
92 readonly markdown: string;
93 readonly relativePath: string;
94 readonly threadId: ThreadId | null;
95 readonly onRefresh?: () => Promise<void> | void;
96}) {
97 const navigation = useNavigation();
98 const gt = useGT();
99 const [isPullRefreshing, setIsPullRefreshing] = useState(false);
100 const [expandedFile, setExpandedFile] = useState<FilePreviewSource | null>(null);
101 const [expandedVideo, setExpandedVideo] = useState<VideoPreviewSource | null>(null);
102 const handlePullToRefresh = async () => {
103 if (!props.onRefresh) {
104 return;
105 }
106 setIsPullRefreshing(true);
107 // RefreshControl only needs the spinner cleared; the caller surfaces its own errors.
108 await settlePromise(async () => props.onRefresh?.());
109 setIsPullRefreshing(false);
110 };
111 const markdownDirectory = getBrowseDirectoryPath(
112 resolveWorkspaceFilePath(props.cwd, props.relativePath),
113 );
114 const renderImage: MarkdownImageRenderer = (image) => {
115 const media = resolveMobileMarkdownMediaSource(image.href, {
116 threadId: props.threadId ?? undefined,
117 workspaceRoot: markdownDirectory,
118 imageEmbed: true,
119 });
120 const preview = resolveMarkdownMediaPreview(image.href, {
121 environmentId: props.environmentId,
122 threadId: props.threadId ?? undefined,
123 workspaceRoot: markdownDirectory,
124 captured: props.captured,
125 imageEmbed: true,
126 });
127 const fileLink = resolveMarkdownLinkPresentation(image.href);
128 if (
129 (preview && preview.kind !== "image" && preview.kind !== "video") ||
130 (!props.captured && fileLink.kind === "file" && fileLink.line !== undefined)
131 ) {
132 const name =
133 preview?.source.name ?? (fileLink.kind === "file" ? fileLink.label : gt("Open file"));
134 return (
135 <Text
136 accessibilityRole="link"
137 accessibilityLabel={gt("Open {name}", { name })}
138 onPress={() => openMedia(image.href, true)}
139 style={{ color: styles.nativeTextStyle.linkColor }}
140 >
141 {name}
142 </Text>
143 );
144 }
145 if (media?.access === "direct") {
146 if (media.kind === "video") {
147 return (
148 <ThreadMarkdownVideo
149 source={{
150 type: "media",
151 name: media.name,
152 mimeType: media.mimeType,
153 uri: normalizeNativeMarkdownUrl(media.uri),
154 actionsSource: preview?.source.actionsSource,
155 }}
156 thumbnailVisible
157 />
158 );
159 }
160 return (
161 <ThreadMarkdownImageView
162 uri={normalizeNativeMarkdownUrl(media.uri)}
163 sourceKey={media.uri}
164 unavailable={false}
165 alt={image.alt}
166 format={media.mimeType === "image/svg+xml" ? "svg" : undefined}
167 actionsSource={preview?.source.actionsSource}
168 onPressPreview={setExpandedFile}
169 />
170 );
171 }
172 if (props.captured || media === null || media.access === "unavailable") {
173 return <ThreadMarkdownImageUnavailable alt={image.alt} />;
174 }
175 if (media.kind === "video") {
176 return preview?.kind === "video" ? (
177 <ThreadMarkdownVideo source={preview.source} thumbnailVisible />
178 ) : (
179 <ThreadMarkdownImageUnavailable alt={image.alt} />
180 );
181 }
182 return (
183 <ThreadMarkdownImage
184 environmentId={props.environmentId}
185 resource={media.resource}
186 alt={image.alt}
187 srcFragment={media.srcFragment}
188 actionsSource={preview?.source.actionsSource}
189 onPressPreview={setExpandedFile}
190 />
191 );
192 };
193 const styles = useMarkdownPreviewStyles();
194 const resolveImageSource = useMarkdownImageSource({
195 environmentId: props.environmentId,
196 threadId: props.threadId,
197 workspaceRoot: markdownDirectory,
198 captured: props.captured,
199 });
200 const openMedia = (href: string, imageEmbed = false) => {
201 const media = resolveMarkdownMediaPreview(href, {
202 environmentId: props.environmentId,
203 threadId: props.threadId ?? undefined,
204 workspaceRoot: markdownDirectory,
205 captured: props.captured,
206 imageEmbed,
207 });
208 if (!media || media.kind === "file") {
209 const fileLink = resolveMarkdownLinkPresentation(href);
210 if (props.captured || fileLink.kind !== "file") return false;
211 const params = {
212 environmentId: String(props.environmentId),
213 path: fileRoutePathSegments(resolveWorkspaceFilePath(markdownDirectory, fileLink.path)),
214 ...(fileLink.line ? { line: String(fileLink.line) } : {}),
215 };
216 if (props.threadId) {
217 navigation.navigate("ThreadFile", { ...params, threadId: String(props.threadId) });
218 } else {
219 navigation.dispatch(StackActions.push("NewTaskFile", { ...params, cwd: props.cwd }));
220 }
221 return true;
222 }
223 if (media.kind === "video") setExpandedVideo(media.source);
224 else setExpandedFile(media.source);
225 return true;
226 };
227 const onImagePress = (href: string) => {
228 openMedia(href, true);
229 };
230 const onLinkPress = (href: string) => {
231 if (!openMedia(href)) void tryOpenWebLink(href, "markdown-link");
232 };
233​
234 const refreshControl = props.onRefresh ? (
235 <RefreshControl refreshing={isPullRefreshing} onRefresh={() => void handlePullToRefresh()} />
236 ) : undefined;
237 const renderMarkdown = (markdown: string) => (
238 <SelectableMarkdownText
239 markdown={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 );
259 const modals = (
260 <>
261 <FilePreviewModal source={expandedFile} onRequestClose={() => setExpandedFile(null)} />
262 <VideoPreviewModal source={expandedVideo} onRequestClose={() => setExpandedVideo(null)} />
263 </>
264 );
265 const markdown = maskMarkdownFrontmatter(props.markdown);
266​
267 // Only chunks near the viewport mount, so only they pay for the JS rewrites and native parse.
268 const { chunks, definitions } = splitMarkdown(markdown);
269 if (chunks.some((chunk) => chunk.text.length > LARGE_MARKDOWN_CHUNK_MAX_CHARS)) {
270 return (
271 <SourceFileSurface
272 contents={props.markdown}
273 path={props.relativePath}
274 onRefresh={props.onRefresh}
275 />
276 );
277 }
278 return (
279 <View className="flex-1 bg-sheet">
280 <LegendList
281 renderScrollComponent={NativeScrollView}
282 contentInsetAdjustmentBehavior="automatic"
283 refreshControl={refreshControl}
284 data={chunks}
285 keyExtractor={(_chunk, index) => String(index)}
286 estimatedItemSize={
287 (styles.nativeTextStyle.lineHeight *
288 chunks.reduce((lines, chunk) => lines + chunk.lines, 0)) /
289 chunks.length
290 }
291 recycleItems={false}
292 contentContainerStyle={{ paddingHorizontal: 18, paddingVertical: 18 }}
293 ItemSeparatorComponent={ChunkSeparator}
294 renderItem={({ item }) => (
295 <View className="mx-auto w-full max-w-[760px]">
296 {renderMarkdown(withMarkdownDefinitions(item.text, definitions))}
297 </View>
298 )}
299 />
300 {modals}
301 </View>
302 );
304​
305function ChunkSeparator() {
306 return <View className="h-5" />;