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

FileMarkdownPreview.tsx

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