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
@@ -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