import React, { useCallback, useMemo, useState, } from 'react'; import type { IUser } from '@growi/core'; import { UserPicture, LoadingSpinner } from '@growi/ui/dist/components'; import { useTranslation } from 'next-i18next'; import { Button, Modal, ModalHeader, ModalBody, ModalFooter, } from 'reactstrap'; import { toastSuccess, toastError } from '~/client/util/toastr'; import { useDeleteAttachmentModal } from '~/stores/modal'; import loggerFactory from '~/utils/logger'; import { Username } from '../User/Username'; import styles from './DeleteAttachmentModal.module.scss'; const logger = loggerFactory('growi:attachmentDelete'); const iconByFormat = (format: string): string => { return format.match(/image\/.+/i) ? 'image' : 'description'; }; export const DeleteAttachmentModal: React.FC = () => { const [deleting, setDeleting] = useState(false); const [deleteError, setDeleteError] = useState(''); const { t } = useTranslation(); const { data: deleteAttachmentModal, close: closeDeleteAttachmentModal } = useDeleteAttachmentModal(); const isOpen = deleteAttachmentModal?.isOpened; const attachment = deleteAttachmentModal?.attachment; const remove = deleteAttachmentModal?.remove; const toggleHandler = useCallback(() => { closeDeleteAttachmentModal(); setDeleting(false); setDeleteError(''); }, [closeDeleteAttachmentModal]); const onClickDeleteButtonHandler = useCallback(async() => { if (remove == null || attachment == null) { return; } setDeleting(true); try { await remove({ attachment_id: attachment._id }); setDeleting(false); closeDeleteAttachmentModal(); toastSuccess(`Delete ${attachment.originalName}`); } catch (err) { setDeleting(false); setDeleteError('Attachment could not be deleted.'); toastError(err); logger.error(err); } }, [attachment, closeDeleteAttachmentModal, remove]); const attachmentFileFormat = useMemo(() => { if (attachment == null) { return; } const content = (attachment.fileFormat.match(/image\/.+/i)) // eslint-disable-next-line @next/next/no-img-element ? deleting image : ''; return (

{iconByFormat(attachment.fileFormat)} {attachment.originalName}

uploaded by

{content}
); }, [attachment]); const deletingIndicator = useMemo(() => { if (deleting) { return ; } if (deleteError) { return {deleteError}; } return <>; }, [deleting, deleteError]); return ( {t('delete_attachment_modal.confirm_delete_attachment')} {attachmentFileFormat}
{deletingIndicator}
); };