import { useEffect, useState } from '@wordpress/element'; import PropTypes from 'prop-types'; import type { Product } from '../catalog/products/Product'; import type { Image } from '../shared/Image'; import { Modal } from 'bootstrap'; declare const wp: any; export const ProductImages = (props) => { const [product, setProduct] = useState(); const imageName = (image: { name?: string; orig_url: string }) => { if (image.name) { return image.name; } const url = new URL(image.orig_url); return url.pathname.split('/').pop(); }; const handleAdd = (image: Image) => { const updatedProduct = { ...product }; if (updatedProduct.images) { updatedProduct.images.push({ thumbnail: image.thumbnail.url, orig_url: image.full.url, orig_w: image.full.width, orig_h: image.full.height, }); } setProduct(updatedProduct); props.handleChange('images', updatedProduct.images); }; const handleConfirm = (index: number) => { const modalEl = document.getElementById(`confirmationModal-${index}`); const modal = Modal.getInstance(modalEl); modal.hide(); modalEl.addEventListener('hidden.bs.modal', (e) => { handleRemove(index); }); }; const handleRemove = (index: number) => { const updatedProduct = { ...product }; if (updatedProduct.images) { if (updatedProduct?.images[index].wpImg) { delete updatedProduct.images[index]; } else { updatedProduct.images[index].deleted = true; } } setProduct(updatedProduct); props.handleChange('images', updatedProduct.images); }; const handleUpload = () => { const fileFrame = wp.media({ title: 'Select or upload image', library: { type: 'image', }, button: { text: 'Select', }, multiple: false, }); fileFrame.on('select', () => { const image = fileFrame .state() .get('selection') .first() .toJSON().sizes; handleAdd(image); }); fileFrame.open(); // Hide edit and delete attachment links. fileFrame.on('selection:toggle', () => { const editLink = document.querySelector('.edit-attachment'); const deleteLink = document.querySelector('.delete-attachment'); if (editLink) { editLink.style.display = 'none'; } if (deleteLink) { deleteLink.style.display = 'none'; } }); }; useEffect(() => { setProduct(JSON.parse(props.product)); }, [props]); return ( <>
{product?.images?.map((image, index) => ( <> {!image.deleted && (
{imageName(image)}
{`${image.orig_w.toLocaleString()} by ${image.orig_h.toLocaleString()} px`}
)} ))}
); }; ProductImages.propTypes = { product: PropTypes.string, images: PropTypes.string, // Stringified array handleChange: PropTypes.func, };