import React, {useMemo} from 'react'; import classNames from 'classnames'; import {useImgSrc} from '@moda/imgsrc'; import './retina_image.scss'; export interface Props extends React.HTMLAttributes { src: null | string; maxWidth: number; maxHeight: number; alt: string; quality?: number; forwardedRef?: React.Ref; onError?(): void; onLoad?(): void; } enum Mode { 'Pending', 'Ready', 'Error' } type Action = | {type: 'ERROR'} | {type: 'LOAD'} | { type: 'UPDATE_SRC'; payload: {src: string}; }; interface State { mode: Mode; src: string; } const reducer = (state: State, action: Action): State => { switch (action.type) { case 'LOAD': return { ...state, mode: Mode.Ready }; case 'ERROR': return { ...state, mode: Mode.Error }; case 'UPDATE_SRC': { return { ...state, mode: Mode.Pending, src: action.payload.src }; } } }; const PENDING_SRC = '//:0'; const RetinaImageBase: React.FC = ({ src, maxWidth, maxHeight, alt, quality = 90, onError, onLoad, forwardedRef, className, ...rest }) => { const isPending = src === null || src === undefined; const {resize} = useImgSrc(); const [state, dispatch] = React.useReducer(reducer, { mode: Mode.Pending, src: isPending ? PENDING_SRC : src }); React.useEffect(() => { if (isPending) return; dispatch({type: 'UPDATE_SRC', payload: {src}}); }, [src, isPending]); const handleError = React.useCallback(() => { if (!isPending) { onError && onError(); dispatch({type: 'ERROR'}); } }, [isPending, onError]); const handleLoad = React.useCallback(() => { onLoad && onLoad(); dispatch({type: 'LOAD'}); }, [onLoad]); const src1x = useMemo( () => src ? resize({ src, quality, height: maxHeight, width: maxWidth, dpr: 1.0 }) : null, [maxHeight, maxWidth, quality, resize, src] ); const src2x = useMemo( () => src ? resize({ src, quality, height: maxHeight, width: maxWidth, dpr: 2.0 }) : null, [maxHeight, maxWidth, quality, resize, src] ); if (state.mode === Mode.Error) { return ; } return ( {alt} ); }; export const RetinaImage = React.forwardRef( (props: Props, ref: React.Ref) => ( ) ); RetinaImage.displayName = 'RetinaImage';