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

composerImagePreview.ts

60 lines2.3 KB

1import * as Effect from "effect/Effect";
2import * as Equal from "effect/Equal";
3import * as Hash from "effect/Hash";
4import { Atom } from "effect/reactivity";
5​
6import type { DraftComposerImageAttachment } from "./composerImages";
7​
8const PREVIEW_CACHE_DIRECTORY = "t3-composer-previews";
9​
10async function materializeDataUrlPreview(id: string, dataUrl: string): Promise<string | null> {
11 const comma = dataUrl.indexOf(",");
12 if (comma < 0) return null;
13 const { Directory, File, Paths } = await import("expo-file-system");
14 const mimeType = /^data:([^;,]+)/.exec(dataUrl)?.[1] ?? "image/jpeg";
15 const extension = (mimeType.split("/")[1] ?? "jpg").replace("jpeg", "jpg");
16 const directory = new Directory(Paths.cache, PREVIEW_CACHE_DIRECTORY);
17 directory.create({ idempotent: true, intermediates: true });
18 const file = new File(directory, `${id}.${extension}`);
19 if (file.exists) return file.uri;
20 // Write beside the cache entry and move it in, so a failed or interrupted write is never reused.
21 const partial = new File(directory, `${id}.${extension}.partial`);
22 if (partial.exists) partial.delete();
23 partial.create();
24 try {
25 await partial.write(dataUrl.slice(comma + 1), { encoding: "base64" });
26 } catch (error) {
27 partial.delete();
28 throw error;
29 }
30 await partial.move(file);
31 return file.uri;
33​
34/**
35 * Keyed by attachment id only: the cached file is named by id, and an upload
36 * reference landing on the same draft must not restart materialization and
37 * blank the preview. Hashing the id also avoids rehashing a multi-megabyte data URL.
38 */
39export class MaterializedPreviewKey implements Equal.Equal {
40 constructor(readonly attachment: DraftComposerImageAttachment) {}
41 [Equal.symbol](that: unknown): boolean {
42 return that instanceof MaterializedPreviewKey && that.attachment.id === this.attachment.id;
43 }
44 [Hash.symbol](): number {
45 return Hash.string(this.attachment.id);
46 }
48​
49export const materializedPreviewAtom = Atom.family(({ attachment }: MaterializedPreviewKey) =>
50 Atom.make(
51 Effect.tryPromise(() => materializeDataUrlPreview(attachment.id, attachment.previewUri)).pipe(
52 Effect.catch((error) =>
53 Effect.sync(() => {
54 console.warn("[composer-attachments] could not cache an image preview", error);
55 return null;
56 }),
57 ),
58 ),
59 ).pipe(Atom.withLabel(`composer-image-preview:${attachment.id}`)),
60);