11import "katex/dist/katex.min.css" ;
2- import React , { cloneElement , isValidElement , useEffect , useMemo , useRef , useState } from "react" ;
2+ import React , { cloneElement , isValidElement , useEffect , useMemo , useRef } from "react" ;
33import ReactMarkdown from "react-markdown" ;
44import { Prism as SyntaxHighlighter } from "react-syntax-highlighter" ;
55import {
@@ -20,6 +20,7 @@ import "yet-another-react-lightbox/styles.css";
2020import { drawBlurhashToCanvas } from "../utils/blurhash" ;
2121import { useColorMode } from "../utils/darkModeUtils" ;
2222import { parseImageUrlMetadata } from "../utils/image-upload" ;
23+ import { useImageLoadState } from "../utils/use-image-load-state" ;
2324
2425
2526const countNewlinesBeforeNode = ( text : string , offset : number ) => {
@@ -64,17 +65,11 @@ function MarkdownImage({
6465 className ?: string ;
6566} ) {
6667 const canvasRef = useRef < HTMLCanvasElement > ( null ) ;
67- const [ loaded , setLoaded ] = useState ( false ) ;
68- const [ failed , setFailed ] = useState ( false ) ;
6968 const { src : cleanSrc , blurhash, width, height } = parseImageUrlMetadata ( src ) ;
69+ const { failed, imageRef, loaded, onError, onLoad } = useImageLoadState ( cleanSrc ) ;
7070 const roundedClass = rounded ? "rounded-xl" : "" ;
7171 const aspectRatio = width && height ? `${ width } / ${ height } ` : undefined ;
7272
73- useEffect ( ( ) => {
74- setLoaded ( false ) ;
75- setFailed ( false ) ;
76- } , [ src ] ) ;
77-
7873 useEffect ( ( ) => {
7974 if ( ! blurhash || ! canvasRef . current ) {
8075 return ;
@@ -99,21 +94,16 @@ function MarkdownImage({
9994 />
10095 ) : null }
10196 < img
97+ ref = { imageRef }
10298 src = { cleanSrc }
10399 alt = { alt }
104100 width = { width }
105101 height = { height }
106102 onClick = { ( ) => {
107103 show ( cleanSrc ) ;
108104 } }
109- onLoad = { ( ) => {
110- setLoaded ( true ) ;
111- setFailed ( false ) ;
112- } }
113- onError = { ( ) => {
114- setLoaded ( false ) ;
115- setFailed ( true ) ;
116- } }
105+ onLoad = { onLoad }
106+ onError = { onError }
117107 className = { `mx-auto max-w-full cursor-zoom-in transition-opacity ${ roundedClass } ${ className || "" } ${
118108 blurhash && ( ! loaded || failed ) ? "opacity-0" : "opacity-100"
119109 } `}
0 commit comments