import React from 'react'; import classNames from 'classnames'; import { Modal, Carousel } from 'antd'; function isGood(className: string): boolean { return /\bgood\b/i.test(className); } function isBad(className: string): boolean { return /\bbad\b/i.test(className); } function isInline(className: string): boolean { return /\binline\b/i.test(className); } function isGoodBadImg(imgMeta: any): boolean { return imgMeta.isGood || imgMeta.isBad; } function isCompareImg(imgMeta: any): boolean { return isGoodBadImg(imgMeta) || imgMeta.inline; } interface PreviewImageBoxProps { coverMeta: any; cover: React.ReactNode; imgs: React.ReactNode[]; style: React.CSSProperties; previewVisible: boolean; comparable: boolean; onClick: () => void; onCancel: () => void; } const PreviewImageBox: React.FC = (props) => { const { cover, coverMeta, imgs, style, previewVisible, comparable, onClick, onCancel } = props; const onlyOneImg = comparable || imgs.length === 1; const imageWrapperClassName = classNames('preview-image-wrapper', { good: coverMeta.isGood, bad: coverMeta.isBad, }); return (
{coverMeta.alt}
{coverMeta.alt}
{comparable ? cover : imgs}
{coverMeta.alt}
); }; interface ImagePreviewProps { imgs: any[]; } interface ImagePreviewStates { previewVisible?: Record; } class ImagePreview extends React.Component { constructor(props: ImagePreviewProps) { super(props); this.state = { previewVisible: {}, }; } handleClick = (index: number) => { this.setState({ previewVisible: { [index]: true }, }); }; handleCancel = () => { this.setState({ previewVisible: {}, }); }; render() { const { imgs } = this.props; const imgsMeta = imgs.map((img) => { const { alt, description, src } = img; const imgClassName = img.class; return { className: imgClassName, alt, description, src, isGood: isGood(imgClassName), isBad: isBad(imgClassName), inline: isInline(imgClassName), }; }); const imagesList = imgsMeta.map((meta, index) => { const metaCopy = { ...meta }; delete metaCopy.description; delete metaCopy.isGood; delete metaCopy.isBad; return (
{meta.alt}
); }); const comparable = (imgs.length === 2 && imgsMeta.every(isCompareImg)) || (imgs.length >= 2 && imgsMeta.every(isGoodBadImg)); const style: React.CSSProperties = comparable ? { width: `${(100 / imgs.length).toFixed(3)}%` } : {}; const hasCarousel = imgs.length > 1 && !comparable; const previewClassName = classNames({ 'preview-image-boxes': true, clearfix: true, 'preview-image-boxes-compare': comparable, 'preview-image-boxes-with-carousel': hasCarousel, }); return (
{imagesList.map((_, index) => { if (!comparable && index !== 0) { return null; } return ( { this.handleClick(index); }} /> ); })}
); } } export default ImagePreview;