aboutsummaryrefslogtreecommitdiff
path: root/FrontEnd/src/components/BlobImage.tsx
blob: cccf2f744f691482fbda5d851fd8a1354e16618d (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
import { ComponentPropsWithoutRef, useState, useEffect, useMemo } from "react";

type BlobImageProps = Omit<ComponentPropsWithoutRef<"img">, "src"> & {
  imgRef?: React.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} />;
}