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

ProjectFaviconThumbnail.tsx

54 lines1.8 KB

1import type { EnvironmentId } from "@t3tools/contracts";
2import { type ReactNode, useEffect, useRef, useState } from "react";
3​
4import { useAssetUrlState } from "~/assets/assetUrls";
5​
6export 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 );