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

filePreview.ts

241 lines8.4 KB

1import {
2 audioMimeTypeFromExtension,
3 isWorkspaceImagePreviewPath,
4 mediaMimeTypeFromExtension,
5} from "./mediaPreview.ts";
6export {
7 isWorkspaceAudioPreviewPath,
8 isWorkspaceImagePreviewPath,
9 mediaKindFromPath,
10 mediaMimeTypeFromExtension,
11} from "./mediaPreview.ts";
12import { videoMimeType } from "./video.ts";
13​
14export type FilePreviewKind =
15 | "image"
16 | "video"
17 | "audio"
18 | "pdf"
19 | "html"
20 | "markdown"
21 | "mermaid"
22 | "font"
23 | "archive"
24 | "sqlite"
25 | "docx"
26 | "xlsx"
27 | "pptx"
28 | "odt"
29 | "ods"
30 | "odp"
31 | "rtf"
32 | "epub"
33 | "ipynb"
34 | "text"
35 | "unsupported";
36​
37export function filePreviewKind(
38 file: { readonly name: string; readonly mimeType?: string },
39 options?: { readonly richDocuments?: boolean },
40): FilePreviewKind {
41 const mime = file.mimeType?.split(";", 1)[0]?.trim().toLowerCase() ?? "";
42 const name = file.name.toLowerCase();
43 const extension = name.slice(name.lastIndexOf("."));
44 const generic = !mime || mime === "application/octet-stream" || mime === "text/plain";
45 const richDocuments = options?.richDocuments !== false;
46 const office = richDocuments ? officePreviewKind(file) : null;
47 if (office) return office;
48 const binary = binaryPreviewKind(file);
49 if (binary) return binary;
50 if (mime === "application/pdf") return "pdf";
51 if (mime === "text/html") return "html";
52 if (mime === "text/markdown" || mime === "text/x-markdown") return "markdown";
53 if (richDocuments && mime === "text/vnd.mermaid") return "mermaid";
54 if (richDocuments && mime.startsWith("font/")) return "font";
55 // Linux's MIME database also assigns .otf to OpenDocument formula templates.
56 // FontFace validates the actual bytes before a specimen is shown.
57 if (
58 richDocuments &&
59 extension === ".otf" &&
60 mime === "application/vnd.oasis.opendocument.formula-template"
61 )
62 return "font";
63 if (mime.startsWith("image/")) return "image";
64 if (mime.startsWith("video/")) return "video";
65 if (mime.startsWith("audio/")) return "audio";
66 if (generic) {
67 if (extension === ".pdf") return "pdf";
68 if (/^\.html?$/.test(extension)) return "html";
69 if (/^\.(md|markdown|mdown|mkd|mdx)$/.test(extension)) return "markdown";
70 if (richDocuments && /^\.(mmd|mermaid)$/.test(extension)) return "mermaid";
71 if (richDocuments && isWorkspaceFontPreviewPath(name)) return "font";
72 if (richDocuments && extension === ".rtf") return "text";
73 const media = mediaMimeTypeFromExtension(extension);
74 if (media?.startsWith("image/")) return "image";
75 if (media?.startsWith("video/")) return "video";
76 if (audioMimeTypeFromExtension(extension) !== null) return "audio";
77 if (
78 /^\.(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(
79 extension,
80 ) ||
81 /^(dockerfile|makefile|gemfile|rakefile|license|readme|\.gitignore|\.gitattributes|\.editorconfig|\.env)(\.|$)/i.test(
82 name.split(/[\\/]/).at(-1) ?? "",
83 )
84 )
85 return "text";
86 }
87 if (
88 mime.startsWith("text/") ||
89 /^(application\/(json|.*\+json|xml|.*\+xml|javascript|x-javascript|yaml|x-yaml|toml|sql))$/.test(
90 mime,
91 )
92 )
93 return "text";
94 return "unsupported";
96​
97const BINARY_MIME_TYPES = new Map([
98 [".zip", "application/zip"],
99 [".jar", "application/java-archive"],
100 [".tar", "application/x-tar"],
101 [".gz", "application/gzip"],
102 [".tgz", "application/gzip"],
103 [".sqlite", "application/vnd.sqlite3"],
104 [".sqlite3", "application/vnd.sqlite3"],
105 [".db", "application/vnd.sqlite3"],
106]);
107​
108export function binaryPreviewKind(file: {
109 readonly name: string;
110 readonly mimeType?: string;
111}): "archive" | "sqlite" | null {
112 const mime = file.mimeType?.split(";", 1)[0]?.trim().toLowerCase() ?? "";
113 if (["application/vnd.sqlite3", "application/x-sqlite3", "application/x-sqlite"].includes(mime))
114 return "sqlite";
115 if (
116 [
117 "application/zip",
118 "application/x-zip-compressed",
119 "application/java-archive",
120 "application/x-java-archive",
121 "application/x-tar",
122 "application/gzip",
123 "application/x-gzip",
124 "application/x-compressed-tar",
125 ].includes(mime)
126 )
127 return "archive";
128 if (mime && mime !== "application/octet-stream" && mime !== "text/plain") return null;
129 const extension = file.name.slice(file.name.lastIndexOf(".")).toLowerCase();
130 const inferred = BINARY_MIME_TYPES.get(extension);
131 return inferred === "application/vnd.sqlite3" ? "sqlite" : inferred ? "archive" : null;
133​
134export const FILE_TEXT_PREVIEW_MAX_BYTES = 1024 * 1024;
135​
136const OFFICE_MIME_TYPES = {
137 docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
138 xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
139 pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
140 odt: "application/vnd.oasis.opendocument.text",
141 ods: "application/vnd.oasis.opendocument.spreadsheet",
142 odp: "application/vnd.oasis.opendocument.presentation",
143 rtf: "application/rtf",
144 epub: "application/epub+zip",
145 ipynb: "application/x-ipynb+json",
146} as const;
147​
148export type OfficePreviewKind = keyof typeof OFFICE_MIME_TYPES;
149​
150export function officePreviewKind(file: {
151 readonly name: string;
152 readonly mimeType?: string;
153}): OfficePreviewKind | null {
154 const mime = file.mimeType?.split(";", 1)[0]?.trim().toLowerCase() ?? "";
155 if (mime === "text/rtf") return "rtf";
156 for (const kind of Object.keys(OFFICE_MIME_TYPES) as OfficePreviewKind[]) {
157 if (mime === OFFICE_MIME_TYPES[kind]) return kind;
158 if (
159 (!mime ||
160 mime === "application/octet-stream" ||
161 mime === "text/plain" ||
162 (kind === "ipynb" && mime === "application/json")) &&
163 file.name.toLowerCase().endsWith(`.${kind}`)
164 )
165 return kind;
166 }
167 return null;
169​
170export function decodeFilePreviewText(bytes: Uint8Array, truncated = false) {
171 const bounded = bytes.subarray(0, FILE_TEXT_PREVIEW_MAX_BYTES);
172 if (bounded.some((byte) => byte === 0))
173 throw new Error("This file contains binary data and cannot be shown as text.");
174 const decoder = new TextDecoder("utf-8", { fatal: true });
175 try {
176 return {
177 text: decoder.decode(bounded, { stream: truncated || bytes.length > bounded.length }),
178 truncated: truncated || bytes.length > bounded.length,
179 };
180 } catch {
181 throw new Error("This file is not UTF-8 text. Open it in another app to view its contents.");
182 }
184​
185export const WORKSPACE_BROWSER_PREVIEW_EXTENSIONS = [".htm", ".html", ".pdf"] as const;
186​
187const BROWSER_MIME_TYPE_BY_EXTENSION = new Map([
188 [".htm", "text/html"],
189 [".html", "text/html"],
190 [".pdf", "application/pdf"],
191]);
192​
193const FONT_MIME_TYPE_BY_EXTENSION = new Map([
194 [".ttf", "font/ttf"],
195 [".otf", "font/otf"],
196 [".woff", "font/woff"],
197 [".woff2", "font/woff2"],
198]);
199​
200export function isWorkspaceFontPreviewPath(path: string): boolean {
201 return /\.(ttf|otf|woff2?)$/i.test(path);
203​
204export function hostPreviewMimeTypeFromExtension(extension: string): string | null {
205 if (!/^\.[a-z0-9-]+$/i.test(extension)) return null;
206 return (
207 mediaMimeTypeFromExtension(extension) ??
208 audioMimeTypeFromExtension(extension) ??
209 BROWSER_MIME_TYPE_BY_EXTENSION.get(extension.toLowerCase()) ??
210 FONT_MIME_TYPE_BY_EXTENSION.get(extension.toLowerCase()) ??
211 BINARY_MIME_TYPES.get(extension.toLowerCase()) ??
212 (Object.hasOwn(OFFICE_MIME_TYPES, extension.toLowerCase().slice(1))
213 ? OFFICE_MIME_TYPES[extension.toLowerCase().slice(1) as OfficePreviewKind]
214 : null) ??
215 null
216 );
218​
219function hasPreviewExtension(path: string, extensions: ReadonlyArray<string>): boolean {
220 const literalPath = path.toLowerCase();
221 return extensions.some((extension) => literalPath.endsWith(extension));
223​
224export function isWorkspaceBrowserPreviewPath(path: string): boolean {
225 return hasPreviewExtension(path, WORKSPACE_BROWSER_PREVIEW_EXTENSIONS);
227​
228/** File viewers receive literal filesystem paths, not Markdown URLs. */
229export function isWorkspaceVideoPreviewPath(path: string): boolean {
230 return videoMimeType({ name: path, mimeType: "" }) !== null;
232​
233export function isWorkspacePreviewEntryPath(path: string): boolean {
234 return (
235 isWorkspaceBrowserPreviewPath(path) ||
236 isWorkspaceImagePreviewPath(path) ||
237 isWorkspaceFontPreviewPath(path) ||
238 officePreviewKind({ name: path }) !== null ||
239 binaryPreviewKind({ name: path }) !== null
240 );