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

filePreview.ts

211 lines7.2 KB

1import { videoMimeType } from "./video.ts";
2​
3const ICON_EXTENSION_BY_MIME_TYPE: Readonly<Record<string, string>> = {
4 "image/png": "png",
5 "image/jpeg": "jpg",
6 "image/gif": "gif",
7 "image/webp": "webp",
8 "application/pdf": "pdf",
9 "application/zip": "zip",
10 "application/vnd.sqlite3": "sqlite",
11 "text/x-python": "py",
12 "text/javascript": "js",
13 "text/x-ruby": "rb",
14 "text/x-shellscript": "sh",
15};
16​
17export function fileIconPathForMimeType(path: string, mimeType?: string): string {
18 const extension = ICON_EXTENSION_BY_MIME_TYPE[mimeType ?? ""];
19 return extension ? `file.${extension}` : path;
21​
22export type FilePreviewKind =
23 | "image"
24 | "video"
25 | "audio"
26 | "pdf"
27 | "html"
28 | "markdown"
29 | "text"
30 | "unsupported";
31​
32export function filePreviewKind(file: {
33 readonly name: string;
34 readonly mimeType?: string;
35}): FilePreviewKind {
36 const mime = file.mimeType?.split(";", 1)[0]?.trim().toLowerCase() ?? "";
37 const name = file.name.toLowerCase();
38 const extension = name.slice(name.lastIndexOf("."));
39 const generic = !mime || mime === "application/octet-stream" || mime === "text/plain";
40 if (mime === "application/pdf") return "pdf";
41 if (mime === "text/html") return "html";
42 if (mime === "text/markdown" || mime === "text/x-markdown") return "markdown";
43 if (mime.startsWith("image/")) return "image";
44 if (mime.startsWith("video/")) return "video";
45 if (mime.startsWith("audio/")) return "audio";
46 if (generic) {
47 if (extension === ".pdf") return "pdf";
48 if (/^\.html?$/.test(extension)) return "html";
49 if (/^\.(md|markdown|mdown|mkd|mdx)$/.test(extension)) return "markdown";
50 const media = mediaMimeTypeFromExtension(extension);
51 if (media?.startsWith("image/")) return "image";
52 if (media?.startsWith("video/")) return "video";
53 if (audioMimeTypeFromExtension(extension) !== null) return "audio";
54 if (
55 /^\.(txt|log|json|jsonc|jsonl|ndjson|yaml|yml|toml|ini|conf|config|env|csv|tsv|xml|css|scss|sass|less|js|jsx|mjs|cjs|ts|tsx|mts|cts|py|pyi|rb|go|rs|swift|kt|kts|java|c|h|cc|cpp|hpp|cs|php|sh|bash|zsh|fish|sql|graphql|gql|vue|svelte|r|lua|ex|exs|erl|hs|clj|dart|diff|patch|lock|properties|gradle)$/.test(
56 extension,
57 ) ||
58 /^(dockerfile|makefile|gemfile|rakefile|license|readme|\.gitignore|\.gitattributes|\.editorconfig|\.env)(\.|$)/i.test(
59 name.split(/[\\/]/).at(-1) ?? "",
60 )
61 )
62 return "text";
63 }
64 if (
65 mime.startsWith("text/") ||
66 /^(application\/(json|.*\+json|xml|.*\+xml|javascript|x-javascript|yaml|x-yaml|toml|sql))$/.test(
67 mime,
68 )
69 )
70 return "text";
71 return "unsupported";
73​
74export const FILE_TEXT_PREVIEW_MAX_BYTES = 1024 * 1024;
75​
76export function decodeFilePreviewText(bytes: Uint8Array, truncated = false) {
77 const bounded = bytes.subarray(0, FILE_TEXT_PREVIEW_MAX_BYTES);
78 if (bounded.some((byte) => byte === 0))
79 throw new Error("This file contains binary data and cannot be shown as text.");
80 const decoder = new TextDecoder("utf-8", { fatal: true });
81 try {
82 return {
83 text: decoder.decode(bounded, { stream: truncated || bytes.length > bounded.length }),
84 truncated: truncated || bytes.length > bounded.length,
85 };
86 } catch {
87 throw new Error("This file is not UTF-8 text. Open it in another app to view its contents.");
88 }
90​
91export const WORKSPACE_BROWSER_PREVIEW_EXTENSIONS = [".htm", ".html", ".pdf"] as const;
92​
93export const WORKSPACE_IMAGE_PREVIEW_EXTENSIONS = [
94 ".avif",
95 ".gif",
96 ".ico",
97 ".jpeg",
98 ".jpg",
99 ".png",
100 ".svg",
101 ".webp",
102] as const;
103​
104const IMAGE_MIME_TYPE_BY_EXTENSION = new Map([
105 [".avif", "image/avif"],
106 [".gif", "image/gif"],
107 [".ico", "image/x-icon"],
108 [".jpeg", "image/jpeg"],
109 [".jpg", "image/jpeg"],
110 [".png", "image/png"],
111 [".svg", "image/svg+xml"],
112 [".webp", "image/webp"],
113]);
114​
115const BROWSER_MIME_TYPE_BY_EXTENSION = new Map([
116 [".htm", "text/html"],
117 [".html", "text/html"],
118 [".pdf", "application/pdf"],
119]);
120​
121const AUDIO_MIME_TYPE_BY_EXTENSION = new Map([
122 [".mp3", "audio/mpeg"],
123 [".wav", "audio/wav"],
124 [".ogg", "audio/ogg"],
125 [".oga", "audio/ogg"],
126 [".flac", "audio/flac"],
127 [".aac", "audio/aac"],
128 [".m4a", "audio/mp4"],
129 [".opus", "audio/ogg"],
130 [".aiff", "audio/aiff"],
131]);
132​
133export function audioMimeTypeFromExtension(extension: string): string | null {
134 if (!/^\.[a-z0-9]+$/i.test(extension)) return null;
135 return AUDIO_MIME_TYPE_BY_EXTENSION.get(extension.toLowerCase()) ?? null;
137​
138/** Classifies a literal filesystem extension, without URL decoding or suffix removal. */
139export function mediaMimeTypeFromExtension(extension: string): string | null {
140 if (!/^\.[a-z0-9]+$/i.test(extension)) return null;
141 return (
142 IMAGE_MIME_TYPE_BY_EXTENSION.get(extension.toLowerCase()) ??
143 videoMimeType({ name: `media${extension}`, mimeType: "" })
144 );
146​
147export function hostPreviewMimeTypeFromExtension(extension: string): string | null {
148 if (!/^\.[a-z0-9]+$/i.test(extension)) return null;
149 return (
150 mediaMimeTypeFromExtension(extension) ??
151 audioMimeTypeFromExtension(extension) ??
152 BROWSER_MIME_TYPE_BY_EXTENSION.get(extension.toLowerCase()) ??
153 null
154 );
156​
157/** Classifies an authored media path or URL. Filesystem validation uses the literal extension. */
158export function mediaMimeType(path: string): string | null {
159 const trimmed = path.trim();
160 const source = trimmed.startsWith("<") && trimmed.endsWith(">") ? trimmed.slice(1, -1) : trimmed;
161 const dataMimeType = /^data:((?:image|video)\/[\w.+-]+)[;,]/i.exec(source)?.[1];
162 if (dataMimeType) return dataMimeType.toLowerCase();
163​
164 let sourcePath = source.split(/[?#]/, 1)[0] ?? "";
165 if (/^(?:https?:|file:|\/\/)/i.test(source)) {
166 try {
167 sourcePath = new URL(source, "https://media.invalid").pathname;
168 } catch {
169 return null;
170 }
171 }
172 try {
173 sourcePath = decodeURIComponent(sourcePath);
174 } catch {}
175 const basename = sourcePath.split(/[\\/]/).at(-1) ?? "";
176 const extensionIndex = basename.lastIndexOf(".");
177 return extensionIndex < 0 ? null : mediaMimeTypeFromExtension(basename.slice(extensionIndex));
179​
180export function mediaKindFromPath(path: string): "image" | "video" | null {
181 const mimeType = mediaMimeType(path);
182 if (mimeType === null) return null;
183 return mimeType.startsWith("video/") ? "video" : "image";
185​
186function hasPreviewExtension(path: string, extensions: ReadonlyArray<string>): boolean {
187 const literalPath = path.toLowerCase();
188 return extensions.some((extension) => literalPath.endsWith(extension));
190​
191export function isWorkspaceBrowserPreviewPath(path: string): boolean {
192 return hasPreviewExtension(path, WORKSPACE_BROWSER_PREVIEW_EXTENSIONS);
194​
195export function isWorkspaceImagePreviewPath(path: string): boolean {
196 return hasPreviewExtension(path, WORKSPACE_IMAGE_PREVIEW_EXTENSIONS);
198​
199/** File viewers receive literal filesystem paths, not Markdown URLs. */
200export function isWorkspaceVideoPreviewPath(path: string): boolean {
201 return videoMimeType({ name: path, mimeType: "" }) !== null;
203​
204export function isWorkspaceAudioPreviewPath(path: string): boolean {
205 const extensionIndex = path.lastIndexOf(".");
206 return extensionIndex >= 0 && audioMimeTypeFromExtension(path.slice(extensionIndex)) !== null;
208​
209export function isWorkspacePreviewEntryPath(path: string): boolean {
210 return isWorkspaceBrowserPreviewPath(path) || isWorkspaceImagePreviewPath(path);