aboutsummaryrefslogtreecommitdiff
path: root/FrontEnd/src/components/BlobImage.tsx
blob: 047a13b41a973f7174bba0d86fb8e2994a852cb8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import {
  useState,
  useEffect,
  useMemo,
  Ref,
  ComponentPropsWithoutRef,
} from "react";

type BlobImageProps = Omit<ComponentPropsWithoutRef<"img">, "src"> & {
  imgRef?: Ref<HTMLImageElement>;
  src?: Blob | string | null;
  keyBySrc?: boolean;
};

export default function BlobImage(props: BlobImageProps) {
  const { imgRef, src, keyBySrc, ...otherProps } = props;

  const [url, setUrl] = useState<string | null | undefined>(undefined);

  useEffect(() => {
    if (src instanceof Blob) {
      const url = URL.createObjectURL(src);
      setUrl(url);
      return () => {
        URL.revokeObjectURL(url);
      };
    } else {
      setUrl(src);
    }
  }, [src]);

  const key = useMemo(() => {
    if (keyBySrc) {
      return url == null ? undefined : btoa(url);
    } else {
      return undefined;
    }
  }, [url, keyBySrc]);

  return <img key={key} ref={imgRef} {...otherProps} src={url ?? undefined} />;
}