From 912b69243013b568f08512afa3b196583f3dd575 Mon Sep 17 00:00:00 2001 From: Thomas Heyenbrock Date: Thu, 19 May 2022 11:12:54 +0200 Subject: [PATCH] clean up image preview state --- .../src/editor/components/image-preview.tsx | 69 ++++++++----------- 1 file changed, 30 insertions(+), 39 deletions(-) diff --git a/packages/graphiql-react/src/editor/components/image-preview.tsx b/packages/graphiql-react/src/editor/components/image-preview.tsx index f8315bfd87b..38e3fd5c40f 100644 --- a/packages/graphiql-react/src/editor/components/image-preview.tsx +++ b/packages/graphiql-react/src/editor/components/image-preview.tsx @@ -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({ + const [dimensions, setDimensions] = useState({ width: null, height: null, - src: null, - mime: null, }); + const [mime, setMime] = useState(null); const ref = useRef(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 =
{dimensions}
; - } + const dims = + dimensions.width !== null && dimensions.height !== null ? ( +
+ {dimensions.width}x{dimensions.height} + {mime !== null ? ' ' + mime : null} +
+ ) : null; return (
{ - updateMetadata(); + setDimensions({ + width: ref.current?.naturalWidth ?? null, + height: ref.current?.naturalHeight ?? null, + }); }} ref={ref} - src={tokenToURL(props.token)?.href} + src={src} /> {dims}