UNPKG

@mornya/react-image-libs

Version:
34 lines (33 loc) 2.01 kB
var __read = (this && this.__read) || function (o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; }; import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime"; import { useState, useMemo, useCallback, useEffect } from 'react'; import classNames from 'classnames'; import { LazyBackground } from './LazyBackground'; import { usePrev } from './hooks'; export var SwapImage = function (props) { var _a = __read(useState(false), 2), isMainImageReady = _a[0], setMainImageReady = _a[1]; var isOnly = useMemo(function () { return !props.subImagePath; }, [props.subImagePath]); var prevMainImagePath = usePrev(props.mainImagePath); var onLoadedMainImage = useCallback(function () { return setTimeout(function () { return setMainImageReady(true); }, 100); }, []); useEffect(function () { if (props.mainImagePath !== prevMainImagePath) { setMainImageReady(false); } }, [props.mainImagePath, prevMainImagePath]); return props.mainImagePath ? (_jsxs("div", { className: classNames('swap-image', { only: isOnly }), children: [_jsx(LazyBackground, { url: props.mainImagePath, title: props.title, loading: props.loading, error: props.error, className: classNames('img-area', { trigger: !isMainImageReady }, props.className), style: props.style, onLoaded: !isMainImageReady ? onLoadedMainImage : undefined }, props.mainImagePath), props.subImagePath && isMainImageReady && (_jsx(LazyBackground, { url: props.subImagePath, title: props.title, error: props.error, className: classNames('img-area', props.className), style: props.style }, props.subImagePath))] })) : null; };