diff options
Diffstat (limited to 'FrontEnd/src/components/BlobImage.tsx')
-rw-r--r-- | FrontEnd/src/components/BlobImage.tsx | 41 |
1 files changed, 41 insertions, 0 deletions
diff --git a/FrontEnd/src/components/BlobImage.tsx b/FrontEnd/src/components/BlobImage.tsx new file mode 100644 index 00000000..047a13b4 --- /dev/null +++ b/FrontEnd/src/components/BlobImage.tsx @@ -0,0 +1,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} />; +} |