Open History to see the last commit
1import type { EnvironmentId } from "@t3tools/contracts";
2import { safeDecodeURIComponent } from "@t3tools/shared/markdownLinks";
3import type { FilePreviewItem, FilePreviewSource } from "../components/ui/FilePreviewModal.types";
4
5export function remoteAttachmentImageSource(
6 environmentId: EnvironmentId,
7 attachmentId: string,
8 { name, mimeType }: { readonly name: string; readonly mimeType: string },
9) {
10 const resource = {
11 _tag: "attachment" as const,
12 attachmentId,
13 fileName: name,
14 mimeType,
15 };
16 return {
17 kind: "image",
18 name,
19 environmentId,
20 resource,
21 actionsSource: { name, mimeType, environmentId, resource },
22 } satisfies FilePreviewItem;
23}
24
25export function filePreviewKey(source: FilePreviewItem): string {
26 if ("resource" in source)
27 return JSON.stringify([
28 source.environmentId,
29 Object.entries(source.resource)
30 .filter(([key]) => key !== "mimeType" && key !== "fileName")
31 .sort(([a], [b]) => a.localeCompare(b)),
32 ]);
33 if ("attachment" in source) return `attachment:${source.attachment.id}`;
34 return source.uri;
35}
36
37/** The thumbnail a gallery page opens from and closes into, including pages that were not tapped. */
38export function filePreviewSourceIdentifier(source: FilePreviewItem): string {
39 return source.sourceIdentifier ?? `preview:${filePreviewKey(source)}`;
40}
41
42export function filePreviewGallery(source: FilePreviewSource, group: readonly FilePreviewItem[]) {
43 if (source.kind !== "image") return [source];
44 const selectedKey = filePreviewKey(source);
45 const seen = new Set<string>();
46 const items: FilePreviewItem[] = [];
47 for (const item of source.gallery ?? group) {
48 if (item.kind !== "image") continue;
49 const key = filePreviewKey(item);
50 if (seen.has(key)) continue;
51 seen.add(key);
52 items.push(key === selectedKey ? source : item);
53 }
54 if (!seen.has(selectedKey)) items.unshift(source);
55 return items;
56}
57
58export function filePreviewName(source: FilePreviewItem): string {
59 const uriName =
60 "uri" in source
61 ? safeDecodeURIComponent(source.uri.split(/[?#]/)[0]?.split("/").pop() ?? "")
62 : undefined;
63 const name =
64 source.name ?? ("attachment" in source ? source.attachment.name : uriName) ?? "Preview";
65 const extension =
66 /\.(png|jpe?g|gif|webp|heic|heif|avif|bmp|ico|tiff?|svg|pdf|docx?|xlsx?|pptx?|txt|rtf)$/i;
67 const filename =
68 source.kind !== "image" || extension.test(name)
69 ? name
70 : uriName && extension.test(uriName)
71 ? uriName
72 : name.replace(/\./g, "_");
73 return Array.from(filename, (character) =>
74 character.charCodeAt(0) < 32 || "/:\\".includes(character) ? "_" : character,
75 ).join("");
76}