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

workspace-file-image-cache.ts

48 lines1.6 KB

1import * as Data from "effect/Data";
2import * as Effect from "effect/Effect";
3import { Atom } from "effect/unstable/reactivity";
4​
5const WORKSPACE_IMAGE_IDLE_TTL_MS = 30 * 60_000;
6​
7type ImagePrefetch = (uri: string) => Promise<boolean>;
8​
9class WorkspaceImageCacheKey extends Data.Class<{ readonly uri: string }> {}
10​
11export class WorkspaceImagePrefetchError extends Data.TaggedError("WorkspaceImagePrefetchError")<{
12 readonly cause?: unknown;
13 readonly uri: string;
14}> {}
15​
16async function prefetchWithNativeImage(uri: string): Promise<boolean> {
17 const { Image } = await import("react-native");
18 return Image.prefetch(uri);
20​
21export function createWorkspaceFileImageAtomFamily(options?: {
22 readonly idleTtlMs?: number;
23 readonly prefetch?: ImagePrefetch;
24}) {
25 const idleTtlMs = options?.idleTtlMs ?? WORKSPACE_IMAGE_IDLE_TTL_MS;
26 const prefetch = options?.prefetch ?? prefetchWithNativeImage;
27 const family = Atom.family((key: WorkspaceImageCacheKey) =>
28 Atom.make(
29 Effect.tryPromise({
30 try: async () => {
31 const cached = await prefetch(key.uri);
32 if (!cached) {
33 throw new WorkspaceImagePrefetchError({ uri: key.uri });
34 }
35 return key.uri;
36 },
37 catch: (cause) =>
38 cause instanceof WorkspaceImagePrefetchError
39 ? cause
40 : new WorkspaceImagePrefetchError({ uri: key.uri, cause }),
41 }),
42 ).pipe(Atom.setIdleTTL(idleTtlMs), Atom.withLabel(`mobile:workspace-image:${key.uri}`)),
43 );
44​
45 return (uri: string) => family(new WorkspaceImageCacheKey({ uri }));
47​
48export const workspaceFileImageAtom = createWorkspaceFileImageAtomFamily();