fix(clients): persist project icons across reloads and reconnects (#10138)
This commit is contained in:
1 parent
050690d1bc
commit
eee05575eb
20 files changed
+1207
-62
No files matched your search
@@ -5,9 +5,13 @@ import { View } from "react-native";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import {
|
||||
getProjectFaviconCacheKey,
|
||||
getProjectFaviconResourceKey,
|
||||
isProjectFaviconFallbackUrl,
|
||||
} from "@t3tools/shared/projectFavicon";
|
||||
import { useAssetUrl } from "../state/assets";
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
import { projectFaviconUrlAtom } from "../state/assets";
|
||||
|
||||
import {
|
||||
beginProjectFaviconRequest,
|
||||
createProjectFaviconRequest,
|
||||
@@ -16,6 +20,8 @@ import {
|
||||
markProjectFaviconLoaded,
|
||||
} from "./projectFaviconCache";
|
||||
|
||||
const EMPTY_FAVICON_URL = Atom.make<string | null>(null);
|
||||
|
||||
/* ─── Component ──────────────────────────────────────────────────────── */
|
||||
export function ProjectFavicon(props: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
@@ -26,20 +32,23 @@ export function ProjectFavicon(props: {
|
||||
readonly faviconPath?: string | null;
|
||||
}) {
|
||||
const size = props.size ?? 42;
|
||||
const faviconUrl = useAssetUrl(
|
||||
props.environmentId,
|
||||
props.workspaceRoot === null || props.workspaceRoot === undefined
|
||||
? null
|
||||
: {
|
||||
_tag: "project-favicon",
|
||||
const faviconUrl = useAtomValue(
|
||||
props.workspaceRoot == null
|
||||
? EMPTY_FAVICON_URL
|
||||
: projectFaviconUrlAtom({
|
||||
environmentId: props.environmentId,
|
||||
cwd: props.workspaceRoot,
|
||||
...(props.faviconPath ? { path: props.faviconPath } : {}),
|
||||
},
|
||||
faviconPath: props.faviconPath,
|
||||
}),
|
||||
);
|
||||
const renderableFaviconUrl = isProjectFaviconFallbackUrl(faviconUrl) ? null : faviconUrl;
|
||||
// Inline images are self-contained; remote URLs key on their revision so signed-token
|
||||
// rotation reuses the disk cache while a changed icon starts from the loading state.
|
||||
const cacheKey =
|
||||
renderableFaviconUrl && props.workspaceRoot
|
||||
? getProjectFaviconCacheKey(props.environmentId, props.workspaceRoot, renderableFaviconUrl)
|
||||
? renderableFaviconUrl.startsWith("data:")
|
||||
? getProjectFaviconResourceKey(props.environmentId, props.workspaceRoot, props.faviconPath)
|
||||
: getProjectFaviconCacheKey(props.environmentId, props.workspaceRoot, renderableFaviconUrl)
|
||||
: null;
|
||||
|
||||
return (
|
||||
@@ -75,7 +84,9 @@ function ProjectFaviconImage(props: {
|
||||
}, [faviconRequest]);
|
||||
|
||||
const [status, setStatus] = useState<"loading" | "loaded" | "error">(() =>
|
||||
hasLoadedProjectFavicon(props.cacheKey) ? "loaded" : "loading",
|
||||
props.faviconUrl?.startsWith("data:") || hasLoadedProjectFavicon(props.cacheKey)
|
||||
? "loaded"
|
||||
: "loading",
|
||||
);
|
||||
|
||||
const requestIsActive = faviconRequest !== null && activeFaviconRequest === faviconRequest;
|
||||
@@ -104,11 +115,12 @@ function ProjectFaviconImage(props: {
|
||||
{requestIsActive ? (
|
||||
<Image
|
||||
key={faviconRequest.faviconUrl}
|
||||
source={{
|
||||
uri: faviconRequest.faviconUrl,
|
||||
cacheKey: faviconRequest.cacheKey,
|
||||
}}
|
||||
cachePolicy="memory-disk"
|
||||
source={
|
||||
faviconRequest.faviconUrl.startsWith("data:")
|
||||
? { uri: faviconRequest.faviconUrl }
|
||||
: { uri: faviconRequest.faviconUrl, cacheKey: faviconRequest.cacheKey }
|
||||
}
|
||||
cachePolicy={faviconRequest.faviconUrl.startsWith("data:") ? "memory" : "memory-disk"}
|
||||
recyclingKey={faviconRequest.cacheKey}
|
||||
accessibilityLabel={`${props.projectTitle} favicon`}
|
||||
style={{
|
||||
|
||||
@@ -32,6 +32,12 @@ function makeDatabase() {
|
||||
const database = MobileDatabase.of({
|
||||
loadCache: (environmentId, kind, cacheKey) =>
|
||||
Effect.succeed(Option.fromUndefinedOr(values.get(cacheId(environmentId, kind, cacheKey)))),
|
||||
listCache: (kind) =>
|
||||
Effect.sync(() =>
|
||||
[...values.entries()]
|
||||
.filter(([key]) => key.split(":")[1] === kind)
|
||||
.map(([, payload]) => payload),
|
||||
),
|
||||
saveCache: (environmentId, kind, cacheKey, _schemaVersion, payload) =>
|
||||
Effect.sync(() => {
|
||||
values.set(cacheId(environmentId, kind, cacheKey), payload);
|
||||
|
||||
@@ -15,6 +15,7 @@ import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as MobileDatabase from "../persistence/mobile-database";
|
||||
import { attachProjectFaviconDatabase, projectFaviconCache } from "../lib/projectFaviconCache";
|
||||
|
||||
const SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION = 1;
|
||||
// v3 adds windowed (paginated) snapshots carrying `page` metadata; the bump
|
||||
@@ -115,6 +116,7 @@ function loadDecodedCache<A, B>(input: {
|
||||
|
||||
export const make = Effect.fn("MobileEnvironmentCacheStore.make")(function* () {
|
||||
const database = yield* MobileDatabase.MobileDatabase;
|
||||
attachProjectFaviconDatabase(database);
|
||||
return EnvironmentCacheStore.of({
|
||||
loadShell: Effect.fn("MobileEnvironmentCache.loadShell")((environmentId) =>
|
||||
loadDecodedCache({
|
||||
@@ -126,7 +128,7 @@ export const make = Effect.fn("MobileEnvironmentCacheStore.make")(function* () {
|
||||
decode: decodeStoredShellSnapshot,
|
||||
select: (stored) =>
|
||||
stored.environmentId === environmentId ? Option.some(stored.snapshot) : Option.none(),
|
||||
}),
|
||||
}).pipe(Effect.tap(() => Effect.promise(() => projectFaviconCache.hydrate()))),
|
||||
),
|
||||
saveShell: Effect.fn("MobileEnvironmentCache.saveShell")(function* (environmentId, snapshot) {
|
||||
const payload = yield* encodeStoredShellSnapshot({
|
||||
@@ -237,9 +239,10 @@ export const make = Effect.fn("MobileEnvironmentCacheStore.make")(function* () {
|
||||
.pipe(Effect.mapError(mapDatabaseError("clear-vcs-refs"))),
|
||||
),
|
||||
clear: Effect.fn("MobileEnvironmentCache.clear")((environmentId) =>
|
||||
database
|
||||
.clearEnvironmentCache(environmentId)
|
||||
.pipe(Effect.mapError(mapDatabaseError("clear-environment"))),
|
||||
Effect.promise(() => projectFaviconCache.clearEnvironment(environmentId)).pipe(
|
||||
Effect.andThen(database.clearEnvironmentCache(environmentId)),
|
||||
Effect.mapError(mapDatabaseError("clear-environment")),
|
||||
),
|
||||
),
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
import { PROJECT_FAVICON_MAX_DATA_URL_LENGTH } from "@t3tools/client-runtime/project-favicon-cache";
|
||||
|
||||
const native = vi.hoisted(() => ({
|
||||
load: vi.fn(async (_url: string, options: { maxWidth: number; maxHeight: number }) => ({
|
||||
width: options.maxWidth,
|
||||
height: options.maxHeight,
|
||||
release: vi.fn(),
|
||||
})),
|
||||
write: vi.fn(async () => {}),
|
||||
path: vi.fn(async () => "/cache/thumbnail"),
|
||||
read: vi.fn(),
|
||||
remove: vi.fn(),
|
||||
}));
|
||||
vi.mock("expo-image", () => ({
|
||||
Image: {
|
||||
loadAsync: native.load,
|
||||
writeToCacheAsync: native.write,
|
||||
getCachePathAsync: native.path,
|
||||
},
|
||||
}));
|
||||
vi.mock("expo-file-system", () => ({
|
||||
File: class {
|
||||
size = 24_000;
|
||||
base64 = native.read;
|
||||
delete = native.remove;
|
||||
},
|
||||
}));
|
||||
|
||||
import { downscaleProjectFavicon } from "./projectFaviconCache";
|
||||
|
||||
const png = "iVBORw0KGgoAAAAA";
|
||||
const image = { url: "https://remote/icon.png" };
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
native.read.mockReset().mockResolvedValue(png);
|
||||
native.load.mockReset().mockImplementation(async (_url, { maxWidth }) => ({
|
||||
width: maxWidth,
|
||||
height: maxWidth,
|
||||
release: vi.fn(),
|
||||
}));
|
||||
});
|
||||
|
||||
describe("mobile project icon thumbnails", () => {
|
||||
it("reduces an oversized encoding and deletes temporary thumbnail files", async () => {
|
||||
native.read.mockResolvedValueOnce(
|
||||
`iVBORw0KGgo${"a".repeat(PROJECT_FAVICON_MAX_DATA_URL_LENGTH)}`,
|
||||
);
|
||||
const thumbnail = await downscaleProjectFavicon(image, new AbortController().signal);
|
||||
expect(thumbnail).toBe(`data:image/png;base64,${png}`);
|
||||
expect(native.load.mock.calls.map(([, options]) => options.maxWidth)).toEqual([96, 48]);
|
||||
expect(native.remove).toHaveBeenCalledTimes(2);
|
||||
for (const call of native.load.mock.results)
|
||||
expect((await call.value).release).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("releases a decoded image when its request was canceled", async () => {
|
||||
const controller = new AbortController();
|
||||
const release = vi.fn();
|
||||
native.load.mockImplementationOnce(async () => {
|
||||
controller.abort();
|
||||
return { width: 96, height: 96, release };
|
||||
});
|
||||
await expect(downscaleProjectFavicon(image, controller.signal)).rejects.toThrow();
|
||||
expect(release).toHaveBeenCalledOnce();
|
||||
expect(native.write).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects an image the native decoder did not downsize", async () => {
|
||||
const release = vi.fn();
|
||||
native.load.mockResolvedValueOnce({ width: 4000, height: 3000, release });
|
||||
await expect(downscaleProjectFavicon(image, new AbortController().signal)).rejects.toThrow(
|
||||
"not resized",
|
||||
);
|
||||
expect(native.write).not.toHaveBeenCalled();
|
||||
expect(release).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,112 @@
|
||||
import {
|
||||
createProjectFaviconCache,
|
||||
createProjectFaviconImageLoader,
|
||||
PROJECT_FAVICON_MAX_DATA_URL_LENGTH,
|
||||
PROJECT_FAVICON_THUMBNAIL_SIZE,
|
||||
type ProjectFaviconEntry,
|
||||
} from "@t3tools/client-runtime/project-favicon-cache";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
import * as MobileDatabase from "../persistence/mobile-database";
|
||||
|
||||
const CACHE_KIND = "project-favicon";
|
||||
const CACHE_SCHEMA_VERSION = 1;
|
||||
|
||||
let database: MobileDatabase.MobileDatabase["Service"] | undefined;
|
||||
|
||||
/**
|
||||
* The cache is a module singleton because the favicon atom family holds it outside
|
||||
* any Effect runtime. Its rows live in `client_cache`, so the environment cache store
|
||||
* hands over the database it already owns instead of the cache re-entering the runtime.
|
||||
*/
|
||||
export function attachProjectFaviconDatabase(service: MobileDatabase.MobileDatabase["Service"]) {
|
||||
database = service;
|
||||
}
|
||||
|
||||
const runDatabase = <A, E>(
|
||||
use: (database: MobileDatabase.MobileDatabase["Service"]) => Effect.Effect<A, E>,
|
||||
) =>
|
||||
database
|
||||
? Effect.runPromise(use(database))
|
||||
: Promise.reject(new Error("Project icon storage is not attached."));
|
||||
|
||||
/**
|
||||
* Rasterizes a bitmap that is too large to inline. The native decoder writes the
|
||||
* downsized frame to expo-image's disk cache, which is the only encode path it
|
||||
* exposes; the temporary entry is removed once its bytes are read.
|
||||
*/
|
||||
export async function downscaleProjectFavicon(
|
||||
image: { readonly url: string },
|
||||
signal: AbortSignal,
|
||||
) {
|
||||
const [{ Image }, { File }] = await Promise.all([
|
||||
import("expo-image"),
|
||||
import("expo-file-system"),
|
||||
]);
|
||||
for (const size of [PROJECT_FAVICON_THUMBNAIL_SIZE, PROJECT_FAVICON_THUMBNAIL_SIZE / 2]) {
|
||||
signal.throwIfAborted();
|
||||
const decoded = await Image.loadAsync(image.url, { maxWidth: size, maxHeight: size });
|
||||
const cacheKey = `t3-favicon-thumbnail:${size}:${image.url}`;
|
||||
try {
|
||||
signal.throwIfAborted();
|
||||
if (decoded.width > size || decoded.height > size) {
|
||||
throw new Error("Project icon was not resized.");
|
||||
}
|
||||
await Image.writeToCacheAsync(decoded, cacheKey);
|
||||
const path = await Image.getCachePathAsync(cacheKey);
|
||||
if (!path) throw new Error("Project icon thumbnail was not written.");
|
||||
const file = new File(path.startsWith("file:") ? path : `file://${path}`);
|
||||
try {
|
||||
if (file.size > PROJECT_FAVICON_MAX_DATA_URL_LENGTH) continue;
|
||||
const base64 = await file.base64();
|
||||
// SDWebImage chooses JPEG for opaque images and PNG for transparency; Glide always writes PNG.
|
||||
const mimeType = base64.startsWith("/9j/")
|
||||
? "image/jpeg"
|
||||
: base64.startsWith("iVBORw0KGgo")
|
||||
? "image/png"
|
||||
: null;
|
||||
if (!mimeType) throw new Error("Unsupported project icon thumbnail encoding.");
|
||||
const dataUrl = `data:${mimeType};base64,${base64}`;
|
||||
if (dataUrl.length <= PROJECT_FAVICON_MAX_DATA_URL_LENGTH) return dataUrl;
|
||||
} finally {
|
||||
file.delete();
|
||||
}
|
||||
} finally {
|
||||
decoded.release();
|
||||
}
|
||||
}
|
||||
throw new Error("Project icon thumbnail exceeds the cache limit.");
|
||||
}
|
||||
|
||||
/** Rows live in `client_cache` so Settings → Client storage counts and clears them. */
|
||||
export const projectFaviconCache = createProjectFaviconCache({
|
||||
storage: {
|
||||
list: () =>
|
||||
runDatabase((database) =>
|
||||
database.listCache(CACHE_KIND).pipe(
|
||||
Effect.map((payloads) =>
|
||||
payloads.flatMap((payload): Array<unknown> => {
|
||||
try {
|
||||
return [JSON.parse(payload)];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
put: (key, entry: ProjectFaviconEntry) =>
|
||||
runDatabase((database) =>
|
||||
database.saveCache(
|
||||
entry.environmentId,
|
||||
CACHE_KIND,
|
||||
key,
|
||||
CACHE_SCHEMA_VERSION,
|
||||
JSON.stringify(entry),
|
||||
),
|
||||
),
|
||||
remove: (key, entry) =>
|
||||
runDatabase((database) => database.removeCache(entry.environmentId, CACHE_KIND, key)),
|
||||
},
|
||||
load: createProjectFaviconImageLoader({ downscale: downscaleProjectFavicon }),
|
||||
});
|
||||
@@ -16,7 +16,13 @@ const LEGACY_CACHE_DIRECTORIES = [
|
||||
"connection-vcs-refs",
|
||||
] as const;
|
||||
|
||||
export const ClientCacheKind = Schema.Literals(["shell", "thread", "server-config", "vcs-refs"]);
|
||||
export const ClientCacheKind = Schema.Literals([
|
||||
"shell",
|
||||
"thread",
|
||||
"server-config",
|
||||
"vcs-refs",
|
||||
"project-favicon",
|
||||
]);
|
||||
export type ClientCacheKind = typeof ClientCacheKind.Type;
|
||||
|
||||
export interface ClientCacheSummaryRow {
|
||||
@@ -44,6 +50,7 @@ const MobileDatabaseOperation = Schema.Literals([
|
||||
"open",
|
||||
"migrate",
|
||||
"load-cache",
|
||||
"list-cache",
|
||||
"save-cache",
|
||||
"remove-cache",
|
||||
"clear-cache-kind",
|
||||
@@ -192,6 +199,9 @@ export class MobileDatabase extends Context.Service<
|
||||
kind: ClientCacheKind,
|
||||
cacheKey: string,
|
||||
) => Effect.Effect<Option.Option<string>, MobileDatabaseError>;
|
||||
readonly listCache: (
|
||||
kind: ClientCacheKind,
|
||||
) => Effect.Effect<ReadonlyArray<string>, MobileDatabaseError>;
|
||||
readonly saveCache: (
|
||||
environmentId: EnvironmentId,
|
||||
kind: ClientCacheKind,
|
||||
@@ -292,6 +302,16 @@ const makeAvailable = Effect.gen(function* () {
|
||||
catch: databaseError("load-cache"),
|
||||
}).pipe(Effect.map((row) => Option.fromNullishOr(row?.payload))),
|
||||
),
|
||||
listCache: Effect.fn("MobileDatabase.listCache")((kind) =>
|
||||
Effect.tryPromise({
|
||||
try: () =>
|
||||
database.getAllAsync<{ readonly payload: string }>(
|
||||
"SELECT payload FROM client_cache WHERE kind = ? ORDER BY updated_at",
|
||||
kind,
|
||||
),
|
||||
catch: databaseError("list-cache"),
|
||||
}).pipe(Effect.map((rows) => rows.map((row) => row.payload))),
|
||||
),
|
||||
saveCache: Effect.fn("MobileDatabase.saveCache")(
|
||||
(environmentId, kind, cacheKey, schemaVersion, payload) =>
|
||||
Effect.tryPromise({
|
||||
@@ -405,6 +425,7 @@ function makeUnavailable(error: MobileDatabaseError): MobileDatabase["Service"]
|
||||
const fail = Effect.fail(error);
|
||||
return MobileDatabase.of({
|
||||
loadCache: () => fail,
|
||||
listCache: () => fail,
|
||||
saveCache: () => fail,
|
||||
removeCache: () => fail,
|
||||
clearCacheKind: () => fail,
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
import {
|
||||
assetUrlStateFromResult,
|
||||
createAssetEnvironmentAtoms,
|
||||
createProjectFaviconUrlAtomFamily,
|
||||
EMPTY_ASSET_URL_ATOM,
|
||||
} from "@t3tools/client-runtime/state/assets";
|
||||
import type { AssetResource, EnvironmentId } from "@t3tools/contracts";
|
||||
@@ -15,14 +16,21 @@ import { useCallback } from "react";
|
||||
|
||||
import { environmentCatalog } from "../connection/catalog";
|
||||
import { connectionAtomRuntime } from "../connection/runtime";
|
||||
import { projectFaviconCache } from "../lib/projectFaviconCache";
|
||||
import { type AssetUrlState, deriveAssetUrlState } from "./asset-url-state";
|
||||
import { usePreparedConnection } from "./session";
|
||||
import { environmentSession, usePreparedConnection } from "./session";
|
||||
import { useAtomQueryRunner } from "./use-atom-query-runner";
|
||||
|
||||
export type { AssetUrlFailureReason, AssetUrlState } from "./asset-url-state";
|
||||
|
||||
export const assetEnvironment = createAssetEnvironmentAtoms(connectionAtomRuntime);
|
||||
|
||||
export const projectFaviconUrlAtom = createProjectFaviconUrlAtomFamily({
|
||||
imageCache: projectFaviconCache,
|
||||
createUrl: assetEnvironment.createUrl,
|
||||
preparedConnection: environmentSession.preparedConnectionValueAtom,
|
||||
});
|
||||
|
||||
const EMPTY_CONNECTION_STATE_ATOM = Atom.make(AsyncResult.initial<never, never>(false)).pipe(
|
||||
Atom.withLabel("mobile-asset-connection-state:empty"),
|
||||
);
|
||||
|
||||
@@ -3,6 +3,7 @@ import * as Effect from "effect/Effect";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
import { type ClientCacheKind, MobileDatabase } from "../persistence/mobile-database";
|
||||
import { projectFaviconCache } from "../lib/projectFaviconCache";
|
||||
import * as Runtime from "../lib/runtime";
|
||||
|
||||
export interface EnvironmentClientCacheSummary {
|
||||
@@ -71,7 +72,12 @@ export const clientCacheSummaryAtom = clientCacheRuntime
|
||||
|
||||
export const clearClientCacheAtom = clientCacheRuntime
|
||||
.fn((scope: ClientCacheClearScope, get) =>
|
||||
MobileDatabase.pipe(
|
||||
Effect.promise(() =>
|
||||
scope.type === "all"
|
||||
? projectFaviconCache.clearAll()
|
||||
: projectFaviconCache.clearEnvironment(scope.environmentId),
|
||||
).pipe(
|
||||
Effect.andThen(MobileDatabase),
|
||||
Effect.flatMap((database) =>
|
||||
scope.type === "all"
|
||||
? database.clearAllCaches
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
import {
|
||||
createProjectFaviconCache,
|
||||
createProjectFaviconImageLoader,
|
||||
PROJECT_FAVICON_MAX_DATA_URL_LENGTH,
|
||||
PROJECT_FAVICON_THUMBNAIL_SIZE,
|
||||
} from "@t3tools/client-runtime/project-favicon-cache";
|
||||
|
||||
const DATABASE_NAME = "t3code:project-favicons";
|
||||
const DATABASE_VERSION = 2;
|
||||
const STORE_NAME = "images";
|
||||
let database: Promise<IDBDatabase> | undefined;
|
||||
|
||||
function openDatabase() {
|
||||
return (database ??= new Promise<IDBDatabase>((resolve, reject) => {
|
||||
const request = indexedDB.open(DATABASE_NAME, DATABASE_VERSION);
|
||||
request.addEventListener("upgradeneeded", () => {
|
||||
for (const name of request.result.objectStoreNames) {
|
||||
if (name !== STORE_NAME) request.result.deleteObjectStore(name);
|
||||
}
|
||||
if (!request.result.objectStoreNames.contains(STORE_NAME)) {
|
||||
request.result.createObjectStore(STORE_NAME);
|
||||
}
|
||||
});
|
||||
request.addEventListener("success", () => resolve(request.result));
|
||||
request.addEventListener("error", () => reject(request.error));
|
||||
request.addEventListener("blocked", () => reject(new Error("Project icon cache is blocked.")));
|
||||
}));
|
||||
}
|
||||
|
||||
function completed(transaction: IDBTransaction) {
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
transaction.addEventListener("complete", () => resolve());
|
||||
transaction.addEventListener("abort", () => reject(transaction.error));
|
||||
transaction.addEventListener("error", () => reject(transaction.error));
|
||||
});
|
||||
}
|
||||
|
||||
async function withStore<A>(
|
||||
mode: IDBTransactionMode,
|
||||
use: (store: IDBObjectStore) => IDBRequest<A> | void,
|
||||
) {
|
||||
const transaction = (await openDatabase()).transaction(STORE_NAME, mode);
|
||||
const request = use(transaction.objectStore(STORE_NAME));
|
||||
await completed(transaction);
|
||||
return request?.result;
|
||||
}
|
||||
|
||||
/** Rasterizes a bitmap that is too large to inline, retrying at half size. */
|
||||
export async function downscaleProjectFavicon(
|
||||
image: { readonly mimeType: string; readonly bytes: Uint8Array<ArrayBuffer> },
|
||||
signal: AbortSignal,
|
||||
) {
|
||||
const bitmap = await createImageBitmap(new Blob([image.bytes], { type: image.mimeType }));
|
||||
try {
|
||||
signal.throwIfAborted();
|
||||
const canvas = document.createElement("canvas");
|
||||
for (const size of [PROJECT_FAVICON_THUMBNAIL_SIZE, PROJECT_FAVICON_THUMBNAIL_SIZE / 2]) {
|
||||
const scale = Math.min(1, size / bitmap.width, size / bitmap.height);
|
||||
canvas.width = Math.max(1, Math.round(bitmap.width * scale));
|
||||
canvas.height = Math.max(1, Math.round(bitmap.height * scale));
|
||||
const context = canvas.getContext("2d");
|
||||
if (!context) throw new Error("Canvas is unavailable.");
|
||||
context.clearRect(0, 0, canvas.width, canvas.height);
|
||||
context.drawImage(bitmap, 0, 0, canvas.width, canvas.height);
|
||||
const dataUrl = canvas.toDataURL("image/webp", 0.85);
|
||||
if (dataUrl.length <= PROJECT_FAVICON_MAX_DATA_URL_LENGTH) return dataUrl;
|
||||
}
|
||||
throw new Error("Project icon thumbnail exceeds the cache limit.");
|
||||
} finally {
|
||||
bitmap.close();
|
||||
}
|
||||
}
|
||||
|
||||
export const projectFaviconCache = createProjectFaviconCache({
|
||||
storage: {
|
||||
list: async () => (await withStore("readonly", (store) => store.getAll())) ?? [],
|
||||
put: async (key, entry) => {
|
||||
await withStore("readwrite", (store) => store.put(entry, key));
|
||||
},
|
||||
remove: async (key) => {
|
||||
await withStore("readwrite", (store) => store.delete(key));
|
||||
},
|
||||
},
|
||||
load: createProjectFaviconImageLoader({ downscale: downscaleProjectFavicon }),
|
||||
});
|
||||
@@ -5,7 +5,7 @@ import { PROJECT_FAVICON_FALLBACK_MARKER } from "@t3tools/shared/projectFavicon"
|
||||
|
||||
const testState = vi.hoisted(() => ({
|
||||
faviconUrl: "https://environment.test/api/assets/token-a/v1-20-favicon.svg",
|
||||
lastResource: null as unknown,
|
||||
lastTarget: null as unknown,
|
||||
}));
|
||||
|
||||
const hooks = vi.hoisted(() => {
|
||||
@@ -57,10 +57,12 @@ vi.mock("lucide-react/dynamic", () => ({
|
||||
DynamicIcon: "dynamic-icon",
|
||||
iconNames: ["alarm-clock", "folder-code"],
|
||||
}));
|
||||
vi.mock("../assets/assetUrls", () => ({
|
||||
useAssetUrlState: (_environmentId: unknown, resource: unknown) => {
|
||||
testState.lastResource = resource;
|
||||
return { _tag: "Success", url: testState.faviconUrl };
|
||||
vi.mock("@effect/atom-react", () => ({
|
||||
useAtomValue: () => testState.faviconUrl,
|
||||
}));
|
||||
vi.mock("../state/assets", () => ({
|
||||
projectFaviconUrlAtom: (input: unknown) => {
|
||||
testState.lastTarget = input;
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -212,10 +214,10 @@ describe("ProjectFavicon", () => {
|
||||
faviconPath: "brand/icon.svg",
|
||||
});
|
||||
|
||||
expect(testState.lastResource).toEqual({
|
||||
_tag: "project-favicon",
|
||||
expect(testState.lastTarget).toMatchObject({
|
||||
environmentId: "environment-test",
|
||||
cwd: "/workspace-test",
|
||||
path: "brand/icon.svg",
|
||||
faviconPath: "brand/icon.svg",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { EnvironmentId, ProjectIconColor, ProjectIconOverride } from "@t3tools/contracts";
|
||||
import {
|
||||
getProjectFaviconCacheKey,
|
||||
getProjectFaviconResourceKey,
|
||||
isProjectFaviconFallbackUrl,
|
||||
} from "@t3tools/shared/projectFavicon";
|
||||
import {
|
||||
@@ -30,12 +30,12 @@ import {
|
||||
import type { IconName } from "lucide-react/dynamic";
|
||||
import type { ComponentType } from "react";
|
||||
import { lazy, Suspense, useState } from "react";
|
||||
import { useAssetUrlState } from "../assets/assetUrls";
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { projectFaviconUrlAtom } from "../state/assets";
|
||||
import { selectProjectIcon, type ProjectIconName } from "../projectIconModel";
|
||||
import { projectIconColorClassName } from "../projectIconColors";
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
const loadedProjectFaviconSrcs = new Map<string, string>();
|
||||
const DynamicIcon = lazy(() =>
|
||||
import("lucide-react/dynamic").then((module) => ({ default: module.DynamicIcon })),
|
||||
);
|
||||
@@ -103,8 +103,7 @@ export function ProjectFavicon(input: {
|
||||
className?: string | undefined;
|
||||
fallbackIcon?: ComponentType<{ className?: string }>;
|
||||
}) {
|
||||
const state = useProjectFaviconAsset(input);
|
||||
const src = state._tag === "Success" ? state.url : null;
|
||||
const src = useAtomValue(projectFaviconUrlAtom(input));
|
||||
if (input.projectIcon?.kind === "emoji") {
|
||||
return <ProjectFaviconFallback className={input.className} emoji={input.projectIcon.emoji} />;
|
||||
}
|
||||
@@ -150,12 +149,11 @@ export function ProjectFavicon(input: {
|
||||
);
|
||||
}
|
||||
|
||||
const cacheKey = getProjectFaviconCacheKey(input.environmentId, input.cwd, src);
|
||||
const cacheKey = getProjectFaviconResourceKey(input.environmentId, input.cwd, input.faviconPath);
|
||||
|
||||
return (
|
||||
<ProjectFaviconImage
|
||||
key={cacheKey}
|
||||
cacheKey={cacheKey}
|
||||
src={src}
|
||||
className={input.className}
|
||||
fallbackIcon={FallbackIcon}
|
||||
@@ -165,18 +163,6 @@ export function ProjectFavicon(input: {
|
||||
);
|
||||
}
|
||||
|
||||
export function useProjectFaviconAsset(input: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly cwd: string;
|
||||
readonly faviconPath?: string | null | undefined;
|
||||
}) {
|
||||
return useAssetUrlState(input.environmentId, {
|
||||
_tag: "project-favicon",
|
||||
cwd: input.cwd,
|
||||
...(input.faviconPath ? { path: input.faviconPath } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
function ProjectFaviconFallback({
|
||||
className,
|
||||
colorClassName,
|
||||
@@ -207,28 +193,23 @@ function ProjectFaviconFallback({
|
||||
}
|
||||
|
||||
function ProjectFaviconImage({
|
||||
cacheKey,
|
||||
src,
|
||||
className,
|
||||
fallbackIcon: FallbackIcon,
|
||||
fallbackEmoji,
|
||||
fallbackColorClassName,
|
||||
}: {
|
||||
readonly cacheKey: string;
|
||||
readonly src: string;
|
||||
readonly className?: string | undefined;
|
||||
readonly fallbackIcon?: ComponentType<{ className?: string }> | undefined;
|
||||
readonly fallbackEmoji?: string | undefined;
|
||||
readonly fallbackColorClassName?: string | undefined;
|
||||
}) {
|
||||
const [displayedSrc, setDisplayedSrc] = useState<string | null>(
|
||||
() => loadedProjectFaviconSrcs.get(cacheKey) ?? null,
|
||||
const [displayedSrc, setDisplayedSrc] = useState<string | null>(() =>
|
||||
src.startsWith("data:image/") ? src : null,
|
||||
);
|
||||
const isLoading = displayedSrc !== src;
|
||||
const handleLoadError = (failedSrc: string) => {
|
||||
if (loadedProjectFaviconSrcs.get(cacheKey) === failedSrc) {
|
||||
loadedProjectFaviconSrcs.delete(cacheKey);
|
||||
}
|
||||
setDisplayedSrc((currentSrc) => (currentSrc === failedSrc ? null : currentSrc));
|
||||
};
|
||||
|
||||
@@ -256,7 +237,6 @@ function ProjectFaviconImage({
|
||||
alt=""
|
||||
className="hidden"
|
||||
onLoad={() => {
|
||||
loadedProjectFaviconSrcs.set(cacheKey, src);
|
||||
setDisplayedSrc(src);
|
||||
}}
|
||||
onError={() => handleLoadError(src)}
|
||||
|
||||
@@ -56,7 +56,8 @@ vi.mock("~/browserHistoryStore", () => ({
|
||||
useThreadRecentHistory: () => EMPTY_HISTORY,
|
||||
}));
|
||||
|
||||
vi.mock("~/state/session", () => ({
|
||||
vi.mock("~/state/session", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("~/state/session")>()),
|
||||
readPreparedConnection: mocks.readPreparedConnection,
|
||||
}));
|
||||
|
||||
|
||||
@@ -33,6 +33,7 @@ import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import { projectFaviconCache } from "../assets/projectFaviconCache";
|
||||
|
||||
const DATABASE_NAME = "t3code:connection-runtime";
|
||||
const DATABASE_VERSION = 4;
|
||||
@@ -461,6 +462,7 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
const cacheStore = EnvironmentCacheStore.of({
|
||||
loadShell: (environmentId) =>
|
||||
readDatabaseValue(database, SHELL_STORE_NAME, environmentId).pipe(
|
||||
Effect.tap(() => Effect.promise(() => projectFaviconCache.hydrate())),
|
||||
Effect.flatMap((raw) => {
|
||||
if (typeof raw !== "string") {
|
||||
return Effect.succeed(Option.none());
|
||||
@@ -638,6 +640,7 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
clear: (environmentId) =>
|
||||
Effect.all(
|
||||
[
|
||||
Effect.promise(() => projectFaviconCache.clearEnvironment(environmentId)),
|
||||
removeDatabaseValue(database, SHELL_STORE_NAME, environmentId),
|
||||
removeDatabaseValuesInRange(
|
||||
database,
|
||||
|
||||
@@ -1,5 +1,16 @@
|
||||
import { createAssetEnvironmentAtoms } from "@t3tools/client-runtime/state/assets";
|
||||
import {
|
||||
createAssetEnvironmentAtoms,
|
||||
createProjectFaviconUrlAtomFamily,
|
||||
} from "@t3tools/client-runtime/state/assets";
|
||||
|
||||
import { connectionAtomRuntime } from "../connection/runtime";
|
||||
import { projectFaviconCache } from "../assets/projectFaviconCache";
|
||||
import { environmentSession } from "./session";
|
||||
|
||||
export const assetEnvironment = createAssetEnvironmentAtoms(connectionAtomRuntime);
|
||||
|
||||
export const projectFaviconUrlAtom = createProjectFaviconUrlAtomFamily({
|
||||
imageCache: projectFaviconCache,
|
||||
createUrl: assetEnvironment.createUrl,
|
||||
preparedConnection: environmentSession.preparedConnectionValueAtom,
|
||||
});
|
||||
Reference in new issue
Block a user