Open History to see the last commit
1import {
2 createProjectFaviconCache as createSharedProjectFaviconCache,
3 createProjectFaviconImageLoader,
4 PROJECT_FAVICON_MAX_DATA_URL_LENGTH,
5 PROJECT_FAVICON_THUMBNAIL_SIZE,
6 type ProjectFaviconEntry,
7} from "@t3tools/client-runtime/project-favicon-cache";
8import * as Effect from "effect/Effect";
9
10import * as MobileDatabase from "../persistence/mobile-database";
11
12const CACHE_KIND = "project-favicon";
13const CACHE_SCHEMA_VERSION = 1;
14
15let database: MobileDatabase.MobileDatabase["Service"] | undefined;
16
17export function attachProjectFaviconDatabase(service: MobileDatabase.MobileDatabase["Service"]) {
18 database = service;
19}
20
21const runDatabase = <A, E>(
22 use: (database: MobileDatabase.MobileDatabase["Service"]) => Effect.Effect<A, E>,
23) =>
24 database
25 ? Effect.runPromise(use(database))
26 : Promise.reject(new Error("Project icon storage is not attached."));
27
28/**
29 * The native decoder writes the downsized frame to expo-image's disk cache,
30 * which is the only encode path it exposes; the temporary entry is removed once
31 * its bytes are read.
32 */
33export async function downscaleProjectFavicon(
34 image: { readonly url: string },
35 signal: AbortSignal,
36) {
37 const [{ Image }, { File }] = await Promise.all([
38 import("expo-image"),
39 import("expo-file-system"),
40 ]);
41 for (const size of [PROJECT_FAVICON_THUMBNAIL_SIZE, PROJECT_FAVICON_THUMBNAIL_SIZE / 2]) {
42 signal.throwIfAborted();
43 const decoded = await Image.loadAsync(image.url, { maxWidth: size, maxHeight: size });
44 const cacheKey = `t3-favicon-thumbnail:${size}:${image.url}`;
45 try {
46 signal.throwIfAborted();
47 if (decoded.width > size || decoded.height > size) {
48 throw new Error("Project icon was not resized.");
49 }
50 await Image.writeToCacheAsync(decoded, cacheKey);
51 const path = await Image.getCachePathAsync(cacheKey);
52 if (!path) throw new Error("Project icon thumbnail was not written.");
53 const file = new File(path.startsWith("file:") ? path : `file://${path}`);
54 try {
55 if (file.size > PROJECT_FAVICON_MAX_DATA_URL_LENGTH) continue;
56 const base64 = await file.base64();
57 // SDWebImage chooses JPEG for opaque images and PNG for transparency; Glide always writes PNG.
58 const mimeType = base64.startsWith("/9j/")
59 ? "image/jpeg"
60 : base64.startsWith("iVBORw0KGgo")
61 ? "image/png"
62 : null;
63 if (!mimeType) throw new Error("Unsupported project icon thumbnail encoding.");
64 const dataUrl = `data:${mimeType};base64,${base64}`;
65 if (dataUrl.length <= PROJECT_FAVICON_MAX_DATA_URL_LENGTH) return dataUrl;
66 } finally {
67 file.delete();
68 }
69 } finally {
70 decoded.release();
71 }
72 }
73 throw new Error("Project icon thumbnail exceeds the cache limit.");
74}
75
76export const projectFaviconDatabaseCache = createSharedProjectFaviconCache({
77 storage: {
78 list: () =>
79 runDatabase((database) =>
80 database.listCache(CACHE_KIND).pipe(
81 Effect.map((payloads) =>
82 payloads.flatMap((payload): Array<unknown> => {
83 try {
84 return [JSON.parse(payload)];
85 } catch {
86 return [];
87 }
88 }),
89 ),
90 ),
91 ),
92 put: (key, entry: ProjectFaviconEntry) =>
93 runDatabase((database) =>
94 database.saveCache(
95 entry.environmentId,
96 CACHE_KIND,
97 key,
98 CACHE_SCHEMA_VERSION,
99 JSON.stringify(entry),
100 ),
101 ),
102 remove: (key, entry) =>
103 runDatabase((database) => database.removeCache(entry.environmentId, CACHE_KIND, key)),
104 },
105 load: createProjectFaviconImageLoader({ downscale: downscaleProjectFavicon }),
106});