Skip to content

Commit

Permalink
clean up image preview state
Browse files Browse the repository at this point in the history
  • Loading branch information
thomasheyenbrock committed May 19, 2022
1 parent 917ef62 commit 912b692
Showing 1 changed file with 30 additions and 39 deletions.
69 changes: 30 additions & 39 deletions packages/graphiql-react/src/editor/components/image-preview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,69 +3,60 @@ import { useEffect, useRef, useState } from 'react';

type ImagePreviewProps = { token: Token };

type ImagePreviewState = {
type Dimensions = {
width: number | null;
height: number | null;
src: string | null;
mime: string | null;
};

export function ImagePreview(props: ImagePreviewProps) {
const [state, setState] = useState<ImagePreviewState>({
const [dimensions, setDimensions] = useState<Dimensions>({
width: null,
height: null,
src: null,
mime: null,
});
const [mime, setMime] = useState<string | null>(null);

const ref = useRef<HTMLImageElement>(null);

function updateMetadata() {
const src = tokenToURL(props.token)?.href;

useEffect(() => {
if (!ref.current) {
return;
}

const width = ref.current.naturalWidth;
const height = ref.current.naturalHeight;
const src = ref.current.src;

if (src !== state.src) {
setState(current => ({ ...current, src }));
fetch(src, { method: 'HEAD' }).then(response => {
setState(current => ({
...current,
mime: response.headers.get('Content-Type'),
}));
});
if (!src) {
setDimensions({ width: null, height: null });
setMime(null);
return;
}

if (width !== state.width || height !== state.height) {
setState(current => ({ ...current, height, width }));
}
}

useEffect(() => {
updateMetadata();
});

let dims = null;
if (state.width !== null && state.height !== null) {
let dimensions = state.width + 'x' + state.height;
if (state.mime !== null) {
dimensions += ' ' + state.mime;
}
fetch(src, { method: 'HEAD' })
.then(response => {
setMime(response.headers.get('Content-Type'));
})
.catch(() => {
setMime(null);
});
}, [src]);

dims = <div>{dimensions}</div>;
}
const dims =
dimensions.width !== null && dimensions.height !== null ? (
<div>
{dimensions.width}x{dimensions.height}
{mime !== null ? ' ' + mime : null}
</div>
) : null;

return (
<div>
<img
onLoad={() => {
updateMetadata();
setDimensions({
width: ref.current?.naturalWidth ?? null,
height: ref.current?.naturalHeight ?? null,
});
}}
ref={ref}
src={tokenToURL(props.token)?.href}
src={src}
/>
{dims}
</div>
Expand Down

0 comments on commit 912b692

Please sign in to comment.