import { loaderHandler, setDisabledButton, returnCheckedDocumentsIds, showErrorAlert } from './helpers'; /** * Attaches event listeners to checkboxes to enable/disable the delete button. */ export const checkboxesHandler = () => { const checkboxes = document.querySelectorAll('.js-accessible-docs-checkbox'); if (checkboxes.length > 0) { checkboxes.forEach((checkbox) => { checkbox.addEventListener('change', () => { const checkedValues = returnCheckedDocumentsIds(); const disabled = checkedValues ? false : true; setDisabledButton('.js-remove-selected-button', disabled); }); }); } }; /** * Sends a request to delete selected documents. * @returns A promise resolving to the response data. * @throws Will throw an error if the request fails. */ const handleDeleteSelectedDocuments = async (): Promise => { try { const selectedIds = returnCheckedDocumentsIds(); if (!selectedIds) { showErrorAlert(`No documents selected`); } const formData = new FormData(); formData.append('action', 'accessible_docs_delete_selected'); // @ts-ignore formData.append('nonce', accessible_docs_object.nonce); formData.append('selectedIds', selectedIds.toString()); // @ts-ignore const response = await fetch(accessible_docs_object.ajax_url, { method: 'POST', body: formData, }); if (!response.ok) { showErrorAlert(`Request failed with status: ${response.status}`); throw new Error(`Request failed with status: ${response.status}`); } const result = await response.json(); return result.data; // Default to 'success' if status is missing } catch (error: any) { throw new Error(`Error: ${error}`); } } /** * Handles the click event on the delete button and triggers document deletion. */ const deleteSelectedDocumentsHandler = () => { const deleteButton = document.querySelector('.js-remove-selected-button') as HTMLElement | null; if (deleteButton) { deleteButton.addEventListener('click', async () => { const selectedIds = returnCheckedDocumentsIds(); if (selectedIds && window.confirm(deleteButton.dataset.text)) { loaderHandler('add'); const request = await handleDeleteSelectedDocuments(); if (request.status === 'success') { window.location.href = `${window.location.origin}${window.location.pathname}?page=accessible-docs-admin-documents-list`; } else { loaderHandler('remove'); alert(request.error); } } }); } }; /** * Initializes the event handlers for checkboxes and delete button. */ const initDeleteSelectedDocementsHandler = () => { checkboxesHandler(); deleteSelectedDocumentsHandler(); }; export default initDeleteSelectedDocementsHandler;