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

localAttachmentPreview.ts

133 lines4.7 KB

1import { useAtomValue } from "@effect/atom-react";
2import { videoMimeType } from "@t3tools/shared/video";
3import * as Effect from "effect/Effect";
4import * as Equal from "effect/Equal";
5import * as Hash from "effect/Hash";
6import * as Option from "effect/Option";
7import { Atom, AsyncResult } from "effect/reactivity";
8​
9import type { FileBackedComposerAttachment } from "./composerImages";
10import { resolveOwnedComposerAttachmentFileUri } from "./composerAttachmentFiles";
11import { shareLocalAttachment, type AttachmentPreviewFile } from "./attachmentDownload";
12import { retainComposerAttachmentFileForPreview } from "./composerAttachmentPreviewRetention";
13​
14export async function loadLocalAttachmentPreview(
15 attachment: FileBackedComposerAttachment,
16 signal: AbortSignal,
17): Promise<AttachmentPreviewFile | null> {
18 if (signal.aborted) return null;
19 const release = retainComposerAttachmentFileForPreview(attachment);
20 try {
21 const { File, Paths } = await import("expo-file-system");
22 if (signal.aborted) {
23 release();
24 return null;
25 }
26 const uri =
27 resolveOwnedComposerAttachmentFileUri(attachment.fileUri, Paths.document.uri) ??
28 attachment.fileUri;
29 const file = new File(uri);
30 if (!file.exists) {
31 throw new Error("The local attachment file is missing.");
32 }
33 let disposed = false;
34 return {
35 uri: file.uri,
36 dispose: () => {
37 if (disposed) return;
38 disposed = true;
39 release();
40 },
41 share: async (shareSignal, sourceIdentifier) => {
42 if (disposed || shareSignal.aborted) return;
43 const releaseShare = retainComposerAttachmentFileForPreview(attachment);
44 try {
45 await shareLocalAttachment({
46 uri: file.uri,
47 attachment: {
48 name: attachment.name,
49 mimeType:
50 attachment.type === "file"
51 ? (videoMimeType(attachment) ?? attachment.mimeType)
52 : attachment.mimeType,
53 },
54 signal: shareSignal,
55 sourceIdentifier,
56 });
57 } finally {
58 releaseShare();
59 }
60 },
61 };
62 } catch (cause) {
63 release();
64 if (signal.aborted) return null;
65 throw new Error("This attachment is no longer available. Attach the file again.", { cause });
66 }
68​
69/**
70 * Keyed by file identity only: a metadata update on the same draft must not
71 * dispose the lease of a file a viewer is still showing.
72 */
73class LocalAttachmentPreviewKey implements Equal.Equal {
74 constructor(readonly attachment: FileBackedComposerAttachment) {}
75 [Equal.symbol](that: unknown): boolean {
76 return (
77 that instanceof LocalAttachmentPreviewKey &&
78 that.attachment.id === this.attachment.id &&
79 that.attachment.fileUri === this.attachment.fileUri
80 );
81 }
82 [Hash.symbol](): number {
83 return Hash.string(`${this.attachment.id}\u0000${this.attachment.fileUri}`);
84 }
86​
87const localAttachmentPreviewFamily = Atom.family((key: LocalAttachmentPreviewKey) =>
88 Atom.make(
89 // The lease lives as long as the atom: unmounting the last reader (or a
90 // refresh) closes the scope and releases the file.
91 Effect.acquireRelease(
92 Effect.tryPromise({
93 try: (signal) => loadLocalAttachmentPreview(key.attachment, signal),
94 catch: (cause) =>
95 cause instanceof Error ? cause : new Error("The local file is unavailable."),
96 }).pipe(Effect.flatMap((file) => (file === null ? Effect.interrupt : Effect.succeed(file)))),
97 (file) => Effect.sync(file.dispose),
98 ),
99 ).pipe(Atom.withLabel(`local-attachment-preview:${key.attachment.id}`)),
100);
101​
102const noLocalAttachmentPreview = Atom.make(
103 AsyncResult.initial<AttachmentPreviewFile, Error>(),
104).pipe(Atom.withLabel("local-attachment-preview:none"));
105​
106export function localAttachmentPreviewAtom(
107 attachment: FileBackedComposerAttachment | null,
108): Atom.Atom<AsyncResult.AsyncResult<AttachmentPreviewFile, Error>> {
109 return attachment === null
110 ? noLocalAttachmentPreview
111 : localAttachmentPreviewFamily(new LocalAttachmentPreviewKey(attachment));
113​
114export interface LocalAttachmentPreviewState {
115 readonly uri: string | null;
116 readonly error: Error | null;
118​
119export function localAttachmentPreviewState(
120 result: AsyncResult.AsyncResult<AttachmentPreviewFile, Error>,
121): LocalAttachmentPreviewState {
122 return {
123 // A refresh has already released the previous lease while it reacquires.
124 uri: result._tag === "Success" && !result.waiting ? result.value.uri : null,
125 error: result._tag === "Failure" ? Option.getOrNull(AsyncResult.error(result)) : null,
126 };
128​
129export function useLocalAttachmentPreview(
130 attachment: FileBackedComposerAttachment | null,
131): LocalAttachmentPreviewState {
132 return localAttachmentPreviewState(useAtomValue(localAttachmentPreviewAtom(attachment)));