The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 22, 23:15 UTC
feat(web): preview images in the project icon picker (#20372)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Julius Marminge <julius0216@outlook.com>
Sergey Novikov committed
Oct 20, 2026 at 07:06 UTC
55b72ff2b19b1d1c00df1af6896bfef1bc2ba3f3
3 files changed
+244
-13
apps/web/src/components/settings/ProjectFaviconPickerDialog.browser.test.tsx
+181
-12
@@ -1,13 +1,44 @@
1
-import { EnvironmentId } from "@t3tools/contracts";
1
+import { RegistryContext } from "@effect/atom-react";
2
+import { EnvironmentId, type AssetCreateUrlResult, type ProjectEntry } from "@t3tools/contracts";
3
+import { AsyncResult, Atom } from "effect/reactivity";
4
import { act } from "react";
5
import { createRoot, type Root } from "react-dom/client";
6
import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
7
8
+import "~/index.css";
9
+
10
+type AssetResult = AsyncResult.AsyncResult<AssetCreateUrlResult, Error>;
11
+const state = vi.hoisted(() => ({
12
+ entries: [] as ProjectEntry[],
13
+ assets: new Map<string, Atom.Writable<AssetResult>>(),
14
+ canReadFiles: true,
15
+ createUrl: vi.fn(),
16
+}));
17
const toast = vi.hoisted(() => vi.fn());
18
+vi.mock(import("~/state/assets"), async (original) => ({
19
+ ...(await original()),
20
+ assetEnvironment: { createUrl: state.createUrl, createUrls: vi.fn() },
21
+}));
22
+vi.mock(import("~/state/session"), async (original) => ({
23
+ ...(await original()),
24
+ usePreparedConnection: () =>
25
+ ({
26
+ _tag: "Some" as const,
27
+ value: { httpBaseUrl: location.origin },
28
+ }) as ReturnType<typeof import("~/state/session").usePreparedConnection>,
29
+}));
30
+vi.mock(import("~/state/filesystem"), async (original) => ({
31
+ ...(await original()),
32
+ useFilesystemReadAccess: () => ({
33
+ canReadFiles: state.canReadFiles,
34
+ isPending: false,
35
+ error: null,
36
+ }),
37
+}));
38
vi.mock(import("../files/projectFilesQueryState"), async (original) => ({
39
...(await original()),
40
useProjectFilePickerQuery: () => ({
10
- entries: [],
41
+ entries: state.entries,
42
error: null,
43
isPending: false,
44
matchedQuery: "",
@@ -18,6 +49,8 @@ vi.mock(import("../ui/toast"), async (original) => {
49
return { ...actual, toastManager: { ...actual.toastManager, add: toast } };
50
});
51
52
+import { appAtomRegistry } from "~/rpc/atomRegistry";
53
+
54
import {
55
canPickExternalProjectFavicon,
56
ProjectFaviconPickerDialog,
@@ -30,6 +63,12 @@ beforeEach(() => {
63
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
64
Object.defineProperty(navigator, "platform", { configurable: true, get: () => "MacIntel" });
65
toast.mockClear();
66
+ state.entries = [];
67
+ state.assets.clear();
68
+ state.canReadFiles = true;
69
+ state.createUrl
70
+ .mockReset()
71
+ .mockImplementation(({ input }) => state.assets.get(input.resource.path)!);
72
container = document.createElement("div");
73
document.body.append(container);
74
root = createRoot(container);
@@ -41,20 +80,22 @@ afterEach(async () => {
80
vi.unstubAllGlobals();
81
});
82
44
-async function renderPicker(onPickExternal: () => Promise<string | null>) {
83
+async function renderPicker(onPickExternal?: () => Promise<string | null>) {
84
const onOpenChange = vi.fn();
85
const onSelect = vi.fn();
86
await act(async () =>
87
root.render(
49
- <ProjectFaviconPickerDialog
50
- cwd="/Users/me/project"
51
- environmentId={EnvironmentId.make("local")}
52
- onOpenChange={onOpenChange}
53
- onPickExternal={onPickExternal}
54
- onSelect={onSelect}
55
- open
56
- projectName="Project"
57
- />,
88
+ <RegistryContext.Provider value={appAtomRegistry}>
89
+ <ProjectFaviconPickerDialog
90
+ cwd="/Users/me/project"
91
+ environmentId={EnvironmentId.make("local")}
92
+ onOpenChange={onOpenChange}
93
+ {...(onPickExternal ? { onPickExternal } : {})}
94
+ onSelect={onSelect}
95
+ open
96
+ projectName="Project"
97
+ />
98
+ </RegistryContext.Provider>,
99
),
100
);
101
return { onOpenChange, onSelect };
@@ -98,3 +139,131 @@ it("keeps the dialog open when the native picker fails", async () => {
139
description: "picker failed",
140
});
141
});
142
+
143
+const imageUrl = `data:image/svg+xml,${encodeURIComponent(
144
+ '<svg xmlns="http://www.w3.org/2000/svg" width="8" height="8"><rect width="8" height="8" fill="red"/></svg>',
145
+)}`;
146
+
147
+function addFiles(paths: string[]) {
148
+ state.entries = paths.map((path) => ({ path, kind: "file" }));
149
+ for (const path of paths) state.assets.set(path, Atom.make<AssetResult>(AsyncResult.initial()));
150
+}
151
+
152
+function fileRow(path: string) {
153
+ const row = [...document.querySelectorAll<HTMLElement>('[role="option"]')].find((element) =>
154
+ element.textContent?.includes(path),
155
+ );
156
+ expect(row, path).toBeDefined();
157
+ return row!;
158
+}
159
+
160
+async function publishUrl(path: string, url: string) {
161
+ await act(async () => {
162
+ appAtomRegistry.set(
163
+ state.assets.get(path)!,
164
+ AsyncResult.success({ relativeUrl: url, expiresAt: Date.now() + 60_000 }),
165
+ );
166
+ });
167
+}
168
+
169
+async function expectPreview(row: HTMLElement) {
170
+ await expect.poll(() => row.querySelector("img")?.naturalWidth).toBe(8);
171
+ expect(row.querySelector("svg")).toBeNull();
172
+}
173
+
174
+it("loads previews asynchronously and only acquires offscreen images after scrolling", async () => {
175
+ const paths = Array.from({ length: 40 }, (_, index) => `icons/icon-${index}.svg`);
176
+ addFiles(paths);
177
+ const { onSelect } = await renderPicker();
178
+ const first = fileRow("icons/icon-0.svg");
179
+ const last = fileRow("icons/icon-39.svg");
180
+
181
+ await expect.poll(() => state.createUrl.mock.calls.length).toBeGreaterThan(0);
182
+ expect(first.querySelector("img")).toBeNull();
183
+ expect(first.querySelector("svg")).not.toBeNull();
184
+ expect(last.getBoundingClientRect().top).toBeGreaterThan(window.innerHeight);
185
+ expect(
186
+ state.createUrl.mock.calls.some(
187
+ ([target]) => target.input.resource.path === "icons/icon-39.svg",
188
+ ),
189
+ ).toBe(false);
190
+
191
+ await publishUrl("icons/icon-0.svg", imageUrl);
192
+ await expectPreview(first);
193
+
194
+ await act(async () => last.scrollIntoView({ block: "center" }));
195
+ await expect
196
+ .poll(() =>
197
+ state.createUrl.mock.calls.some(
198
+ ([target]) => target.input.resource.path === "icons/icon-39.svg",
199
+ ),
200
+ )
201
+ .toBe(true);
202
+ await publishUrl("icons/icon-39.svg", imageUrl);
203
+ await expectPreview(last);
204
+ await act(async () => last.click());
205
+ expect(onSelect).toHaveBeenCalledWith("icons/icon-39.svg");
206
+});
207
+
208
+it("loads without IntersectionObserver and recovers a failed image when its URL changes", async () => {
209
+ vi.stubGlobal("IntersectionObserver", undefined);
210
+ addFiles(["icons/logo.svg"]);
211
+ await renderPicker();
212
+ const row = fileRow("icons/logo.svg");
213
+
214
+ expect(state.createUrl).toHaveBeenCalledWith({
215
+ environmentId: EnvironmentId.make("local"),
216
+ input: {
217
+ resource: { _tag: "draft-workspace-file", cwd: "/Users/me/project", path: "icons/logo.svg" },
218
+ },
219
+ });
220
+ expect(row.querySelector("svg")).not.toBeNull();
221
+ await publishUrl("icons/logo.svg", imageUrl);
222
+ await expectPreview(row);
223
+
224
+ // Let Chromium reject the image bytes rather than dispatching a synthetic error.
225
+ await publishUrl("icons/logo.svg", "data:image/png;base64,broken");
226
+ await expect.poll(() => row.querySelector("img")).toBeNull();
227
+ expect(row.querySelector("svg")).not.toBeNull();
228
+
229
+ await publishUrl("icons/logo.svg", `${imageUrl}#renewed`);
230
+ await expectPreview(row);
231
+});
232
+
233
+it("keeps denied previews selectable with their file icon", async () => {
234
+ vi.stubGlobal("IntersectionObserver", undefined);
235
+ state.canReadFiles = false;
236
+ addFiles(["icons/private.svg"]);
237
+ const { onSelect } = await renderPicker();
238
+ const row = fileRow("icons/private.svg");
239
+
240
+ await act(async () => row.click());
241
+ expect(row.querySelector("img")).toBeNull();
242
+ expect(row.querySelector("svg")).not.toBeNull();
243
+ expect(state.createUrl).not.toHaveBeenCalled();
244
+ expect(onSelect).toHaveBeenCalledWith("icons/private.svg");
245
+});
246
+
247
+it("keeps the file icon until the image load is acknowledged", async () => {
248
+ vi.stubGlobal("IntersectionObserver", undefined);
249
+ addFiles(["icons/loading.svg"]);
250
+ await renderPicker();
251
+ const row = fileRow("icons/loading.svg");
252
+ // Hold the load notification so a fast data URL has the same UI state as a slow request.
253
+ const holdLoad = (event: Event) => {
254
+ if (event.target instanceof HTMLImageElement && row.contains(event.target)) {
255
+ event.stopImmediatePropagation();
256
+ }
257
+ };
258
+ document.addEventListener("load", holdLoad, true);
259
+ try {
260
+ await publishUrl("icons/loading.svg", imageUrl);
261
+ await expect.poll(() => row.querySelector("img")?.naturalWidth).toBe(8);
262
+ expect(row.querySelector("svg")).not.toBeNull();
263
+ document.removeEventListener("load", holdLoad, true);
264
+ await publishUrl("icons/loading.svg", `${imageUrl}#loaded`);
265
+ await expectPreview(row);
266
+ } finally {
267
+ document.removeEventListener("load", holdLoad, true);
268
+ }
269
+});
apps/web/src/components/settings/ProjectFaviconPickerDialog.tsx
+9
-1
@@ -17,6 +17,7 @@ import {
17
import { useProjectFilePickerQuery } from "../files/projectFilesQueryState";
18
import { CommandDialog, CommandDialogPopup, CommandFooterAction } from "../ui/command";
19
import { toastManager } from "../ui/toast";
20
+import { ProjectFaviconThumbnail } from "./ProjectFaviconThumbnail";
21
22
function emptyMessage(query: string, error: string | null, isPending: boolean): string {
23
if (error) return error;
@@ -61,7 +62,14 @@ export function ProjectFaviconPickerDialog(props: {
62
searchTerms: [match.name, match.path],
63
title: match.name,
64
description: match.path,
64
- icon: <PierreEntryIcon pathValue={match.path} kind="file" theme={resolvedTheme} />,
65
+ icon: (
66
+ <ProjectFaviconThumbnail
67
+ cwd={props.cwd}
68
+ environmentId={props.environmentId}
69
+ fallback={<PierreEntryIcon pathValue={match.path} kind="file" theme={resolvedTheme} />}
70
+ path={match.path}
71
+ />
72
+ ),
73
run: async () => onSelect(match.path),
74
}));
75
apps/web/src/components/settings/ProjectFaviconThumbnail.tsx
new
+54
@@ -0,0 +1,54 @@
1
+import type { EnvironmentId } from "@t3tools/contracts";
2
+import { type ReactNode, useEffect, useRef, useState } from "react";
3
+
4
+import { useAssetUrlState } from "~/assets/assetUrls";
5
+
6
+export function ProjectFaviconThumbnail(props: {
7
+ readonly cwd: string;
8
+ readonly environmentId: EnvironmentId;
9
+ readonly fallback: ReactNode;
10
+ readonly path: string;
11
+}) {
12
+ const ref = useRef<HTMLSpanElement>(null);
13
+ const [inView, setInView] = useState(() => typeof IntersectionObserver === "undefined");
14
+ const [loadedUrl, setLoadedUrl] = useState<string | null>(null);
15
+ const [failedUrl, setFailedUrl] = useState<string | null>(null);
16
+
17
+ // Asset URLs require a server request, so defer acquisition until the row is visible.
18
+ useEffect(() => {
19
+ const element = ref.current;
20
+ if (inView || !element) return;
21
+ const observer = new IntersectionObserver((entries) => {
22
+ if (entries.some((entry) => entry.isIntersecting)) setInView(true);
23
+ });
24
+ observer.observe(element);
25
+ return () => observer.disconnect();
26
+ }, [inView]);
27
+
28
+ const state = useAssetUrlState(
29
+ props.environmentId,
30
+ inView ? { _tag: "draft-workspace-file", cwd: props.cwd, path: props.path } : null,
31
+ );
32
+ const url = state._tag === "Success" ? state.url : null;
33
+
34
+ const showImage = url !== null && failedUrl !== url;
35
+ const imageLoaded = showImage && loadedUrl === url;
36
+
37
+ return (
38
+ <span ref={ref} className="relative flex size-8 shrink-0 items-center justify-center">
39
+ {!imageLoaded ? props.fallback : null}
40
+ {showImage ? (
41
+ <img
42
+ key={url}
43
+ alt=""
44
+ className={`absolute max-h-8 max-w-8 rounded-sm object-contain${imageLoaded ? "" : " invisible"}`}
45
+ decoding="async"
46
+ loading="lazy"
47
+ onError={() => setFailedUrl(url)}
48
+ onLoad={() => setLoadedUrl(url)}
49
+ src={url}
50
+ />
51
+ ) : null}
52
+ </span>
53
+ );
54
+}