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

browserFaviconStore.ts

355 lines12.3 KB

1import {
2 parseScopedProjectKey,
3 scopedProjectKey,
4 scopedThreadKey,
5 scopeProjectRef,
6} from "@t3tools/client-runtime/environment";
7import type { DesktopPreviewFavicon, ScopedProjectRef, ScopedThreadRef } from "@t3tools/contracts";
8import * as Option from "effect/Option";
9import { create } from "zustand";
10import { createJSONStorage, persist } from "zustand/middleware";
11​
12import { normalizeHostname } from "~/browser/browserTargetResolver";
13import { readThreadShell, useQuietThreadShell } from "~/state/entities";
14import { readPreparedConnection, usePreparedConnection } from "~/state/session";
15​
16import {
17 BROWSER_FAVICON_MAX_ALIASES_PER_ENTRY,
18 type BrowserFaviconEntry,
19 canCanonicalizeFaviconWithoutEnvironment,
20 evictExcessFavicons,
21 faviconKey,
22 faviconStorageLocation,
23 isStorableFaviconDataUrl,
24 isValidFaviconCapturedAt,
25 migratePersistedBrowserFaviconState,
26 readPersistedBrowserFaviconState,
27} from "./browserFaviconLogic";
28import { useComposerDraftStore } from "./composerDraftStore";
29import { createMemoryStorage, type StateStorage } from "./lib/storage";
30​
31const BROWSER_FAVICON_STORAGE_KEY = "t3code:browser-favicons:v1";
32const MAX_PENDING_ORIGINS_PER_THREAD = 10;
33const MAX_PENDING_THREADS = 20;
34​
35type PendingFavicon = DesktopPreviewFavicon;
36type PendingFaviconsByOrigin = Record<string, PendingFavicon>;
37​
38export interface BrowserFaviconStoreState {
39 byKey: Record<string, BrowserFaviconEntry>;
40 pendingByThreadKey: Record<string, PendingFaviconsByOrigin>;
41 recordFavicon: (
42 key: string,
43 dataUrl: string,
44 capturedAt: number,
45 aliases?: ReadonlyArray<string>,
46 ) => void;
48​
49function pendingOriginKey(pageUrl: string): string | null {
50 return faviconKey("pending", pageUrl, null)?.slice("pending ".length) ?? null;
52​
53function addPendingFavicon(
54 pendingByThreadKey: Record<string, PendingFaviconsByOrigin>,
55 threadKey: string,
56 favicon: PendingFavicon,
57): Record<string, PendingFaviconsByOrigin> {
58 const originKey = pendingOriginKey(favicon.pageUrl);
59 if (!originKey) return pendingByThreadKey;
60 const current = pendingByThreadKey[threadKey] ?? {};
61 const existing = current[originKey];
62 if (existing && existing.capturedAt >= favicon.capturedAt) return pendingByThreadKey;
63 const nextForThread = {
64 ...current,
65 [originKey]: favicon,
66 };
67 const boundedForThread = Object.fromEntries(
68 Object.entries(nextForThread)
69 .toSorted(([, left], [, right]) => right.capturedAt - left.capturedAt)
70 .slice(0, MAX_PENDING_ORIGINS_PER_THREAD),
71 );
72​
73 const withoutThread = { ...pendingByThreadKey };
74 delete withoutThread[threadKey];
75 return Object.fromEntries(
76 [...Object.entries(withoutThread), [threadKey, boundedForThread]].slice(-MAX_PENDING_THREADS),
77 );
79​
80export function resolveBrowserFaviconStorage(): StateStorage {
81 const fallback = createMemoryStorage();
82 const shadowedNames = new Set<string>();
83 let primary: Storage;
84 try {
85 if (typeof window === "undefined") return fallback;
86 primary = window.localStorage;
87 } catch {
88 return fallback;
89 }
90 return {
91 getItem: (name) => {
92 if (shadowedNames.has(name)) return fallback.getItem(name);
93 try {
94 return primary.getItem(name);
95 } catch {
96 return fallback.getItem(name);
97 }
98 },
99 setItem: (name, value) => {
100 fallback.setItem(name, value);
101 try {
102 primary.setItem(name, value);
103 shadowedNames.delete(name);
104 } catch {
105 shadowedNames.add(name);
106 }
107 },
108 removeItem: (name) => {
109 fallback.removeItem(name);
110 try {
111 primary.removeItem(name);
112 shadowedNames.delete(name);
113 } catch {
114 shadowedNames.add(name);
115 }
116 },
117 };
119​
120export const useBrowserFaviconStore = create<BrowserFaviconStoreState>()(
121 persist(
122 (set) => ({
123 byKey: {},
124 pendingByThreadKey: {},
125 recordFavicon: (key, dataUrl, capturedAt, aliases = []) =>
126 set((state) => {
127 if (!isStorableFaviconDataUrl(dataUrl)) return state;
128 if (!isValidFaviconCapturedAt(capturedAt)) return state;
129 const existing = state.byKey[key];
130 const aliasCandidates =
131 capturedAt > (existing?.capturedAt ?? -1)
132 ? [...aliases, ...(existing?.aliases ?? [])]
133 : [...(existing?.aliases ?? []), ...aliases];
134 const nextAliases = [...new Set(aliasCandidates)].slice(
135 0,
136 BROWSER_FAVICON_MAX_ALIASES_PER_ENTRY,
137 );
138 const aliasesUnchanged =
139 nextAliases.length === (existing?.aliases?.length ?? 0) &&
140 nextAliases.every((alias, index) => alias === existing?.aliases?.[index]);
141 if (existing && capturedAt <= existing.capturedAt && aliasesUnchanged) return state;
142 return {
143 byKey: evictExcessFavicons({
144 ...state.byKey,
145 [key]: {
146 dataUrl: capturedAt > (existing?.capturedAt ?? -1) ? dataUrl : existing!.dataUrl,
147 capturedAt: Math.max(capturedAt, existing?.capturedAt ?? -1),
148 ...(nextAliases.length > 0 ? { aliases: nextAliases } : {}),
149 },
150 }),
151 };
152 }),
153 }),
154 {
155 name: BROWSER_FAVICON_STORAGE_KEY,
156 version: 1,
157 storage: createJSONStorage(resolveBrowserFaviconStorage),
158 partialize: (state) => ({ byKey: state.byKey }),
159 migrate: migratePersistedBrowserFaviconState,
160 merge: mergeBrowserFaviconState,
161 },
162 ),
163);
164​
165function mergeBrowserFaviconState(
166 persistedState: unknown,
167 currentState: BrowserFaviconStoreState,
168): BrowserFaviconStoreState {
169 return {
170 ...currentState,
171 ...readPersistedBrowserFaviconState(persistedState),
172 };
174​
175/** Server threads name their project in the shell; drafts in the composer draft store. */
176function useFaviconProjectRefForThread(threadRef: ScopedThreadRef): ScopedProjectRef | null {
177 const shell = useQuietThreadShell(threadRef);
178 const draftProjectRef = useComposerDraftStore((state) => {
179 const draft = state.getDraftSessionByRef(threadRef);
180 return draft ? scopedProjectKey(scopeProjectRef(draft.environmentId, draft.projectId)) : null;
181 });
182 if (shell?.projectId) return scopeProjectRef(threadRef.environmentId, shell.projectId);
183 return draftProjectRef === null ? null : parseScopedProjectKey(draftProjectRef);
185​
186function readThreadProjectRef(threadRef: ScopedThreadRef): ScopedProjectRef | null {
187 const projectId = readThreadShell(threadRef)?.projectId;
188 if (projectId) return scopeProjectRef(threadRef.environmentId, projectId);
189 const draft = useComposerDraftStore.getState().getDraftSessionByRef(threadRef);
190 return draft ? scopeProjectRef(draft.environmentId, draft.projectId) : null;
192​
193export function recordFaviconForProject(
194 projectRef: ScopedProjectRef,
195 favicon: DesktopPreviewFavicon,
196 environmentHostname: string | null,
197): boolean {
198 if (!isStorableFaviconDataUrl(favicon.dataUrl) || !isValidFaviconCapturedAt(favicon.capturedAt)) {
199 return false;
200 }
201 const location = faviconStorageLocation(
202 scopedProjectKey(projectRef),
203 favicon.pageUrl,
204 environmentHostname,
205 );
206 if (!location) return false;
207 const state = useBrowserFaviconStore.getState();
208 const existing = state.byKey[location.key];
209 if (
210 existing &&
211 existing.capturedAt >= favicon.capturedAt &&
212 location.aliases.every((alias) => existing.aliases?.includes(alias))
213 )
214 return true;
215 state.recordFavicon(location.key, favicon.dataUrl, favicon.capturedAt, location.aliases);
216 return true;
218​
219/**
220 * The thread's project and environment host may not be known yet when a capture
221 * arrives; such captures wait per thread and land with the next capture that can
222 * resolve them.
223 */
224export function recordFaviconForThread(
225 threadRef: ScopedThreadRef,
226 favicon: DesktopPreviewFavicon,
227): boolean {
228 if (
229 !isStorableFaviconDataUrl(favicon.dataUrl) ||
230 !isValidFaviconCapturedAt(favicon.capturedAt) ||
231 !pendingOriginKey(favicon.pageUrl)
232 )
233 return false;
234 const projectRef = readThreadProjectRef(threadRef);
235 const connection = readPreparedConnection(threadRef.environmentId);
236 const environmentHostname = connection ? new URL(connection.httpBaseUrl).hostname : undefined;
237 if (projectRef) flushPendingFaviconsForThread(threadRef, projectRef, environmentHostname);
238 const hostname =
239 environmentHostname !== undefined
240 ? environmentHostname
241 : canCanonicalizeFaviconWithoutEnvironment(favicon.pageUrl)
242 ? null
243 : undefined;
244 if (
245 projectRef &&
246 hostname !== undefined &&
247 recordFaviconForProject(projectRef, favicon, hostname)
248 ) {
249 return true;
250 }
251 const threadKey = scopedThreadKey(threadRef);
252 const state = useBrowserFaviconStore.getState();
253 const pendingByThreadKey = addPendingFavicon(state.pendingByThreadKey, threadKey, favicon);
254 if (pendingByThreadKey !== state.pendingByThreadKey) {
255 useBrowserFaviconStore.setState({ pendingByThreadKey });
256 }
257 return false;
259​
260function flushPendingFaviconsForThread(
261 threadRef: ScopedThreadRef,
262 projectRef: ScopedProjectRef,
263 environmentHostname: string | undefined,
264): boolean {
265 const threadKey = scopedThreadKey(threadRef);
266 const pending = useBrowserFaviconStore.getState().pendingByThreadKey[threadKey];
267 if (!pending) return true;
268 const remaining = Object.fromEntries(
269 Object.entries(pending).filter(([, favicon]) => {
270 const hostname =
271 environmentHostname !== undefined
272 ? environmentHostname
273 : canCanonicalizeFaviconWithoutEnvironment(favicon.pageUrl)
274 ? null
275 : undefined;
276 return hostname === undefined || !recordFaviconForProject(projectRef, favicon, hostname);
277 }),
278 );
279 useBrowserFaviconStore.setState((state) => {
280 const pendingByThreadKey = { ...state.pendingByThreadKey };
281 if (Object.keys(remaining).length === 0) delete pendingByThreadKey[threadKey];
282 else pendingByThreadKey[threadKey] = remaining;
283 return { pendingByThreadKey };
284 });
285 return Object.keys(remaining).length === 0;
287​
288export function useFaviconForThreadUrl(threadRef: ScopedThreadRef, url: string): string | null {
289 const projectRef = useFaviconProjectRefForThread(threadRef);
290 const preparedConnection = usePreparedConnection(threadRef.environmentId);
291 const environmentHostname = Option.isSome(preparedConnection)
292 ? new URL(preparedConnection.value.httpBaseUrl).hostname
293 : null;
294 const threadKey = scopedThreadKey(threadRef);
295 return useBrowserFaviconStore((state) =>
296 lookupFaviconForThread(state, threadKey, projectRef, url, environmentHostname),
297 );
299​
300/**
301 * A capture waiting for its thread's project still shows on that thread, and wins
302 * over an older stored capture for the same origin.
303 */
304export function lookupFaviconForThread(
305 state: Pick<BrowserFaviconStoreState, "byKey" | "pendingByThreadKey">,
306 threadKey: string,
307 projectRef: ScopedProjectRef | null,
308 url: string,
309 environmentHostname: string | null,
310): string | null {
311 const stored = lookupFaviconEntry(state.byKey, projectRef, url, environmentHostname);
312 const originKey = pendingOriginKey(url);
313 const pending = originKey ? state.pendingByThreadKey[threadKey]?.[originKey] : undefined;
314 if (pending && (!stored || pending.capturedAt > stored.capturedAt)) return pending.dataUrl;
315 return stored?.dataUrl ?? null;
317​
318export function lookupFavicon(
319 byKey: Record<string, BrowserFaviconEntry>,
320 projectRef: ScopedProjectRef | null,
321 url: string,
322 environmentHostname: string | null,
323): string | null {
324 return lookupFaviconEntry(byKey, projectRef, url, environmentHostname)?.dataUrl ?? null;
326​
327function lookupFaviconEntry(
328 byKey: Record<string, BrowserFaviconEntry>,
329 projectRef: ScopedProjectRef | null,
330 url: string,
331 environmentHostname: string | null,
332): BrowserFaviconEntry | null {
333 const key = projectRef
334 ? faviconKey(scopedProjectKey(projectRef), url, environmentHostname)
335 : null;
336 if (!key) return null;
337 const direct = byKey[key];
338 if (direct) return direct;
339 try {
340 const requestedHost = normalizeHostname(new URL(url).hostname);
341 const localKey = faviconKey(scopedProjectKey(projectRef!), url, requestedHost);
342 const localEntry = localKey ? byKey[localKey] : null;
343 return localEntry?.aliases?.includes(requestedHost) ? localEntry : null;
344 } catch {
345 return null;
346 }
348​
349export function resetBrowserFaviconsForTests(): void {
350 useBrowserFaviconStore.setState({
351 byKey: {},
352 pendingByThreadKey: {},
353 });
354 useBrowserFaviconStore.persist.clearStorage();