import { showErrorAlert, loaderHandler } from './helpers'; /** * Handles the asynchronous request to clear the accessible documents table. * Sends a POST request to the WordPress AJAX endpoint with a nonce for security. * * @returns {Promise} - Returns the result of the AJAX call as a JSON object. * @throws {Error} - Throws an error if the request fails or an unexpected error occurs. */ const handleClearAccessibleDocsTable = async (): Promise => { try { const formData = new FormData(); formData.append('action', 'accessible_docs_clear_table'); // @ts-ignore formData.append('nonce', accessible_docs_object.nonce); // @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) { showErrorAlert(error); throw new Error(`Error: ${error}`); } }; /** * Initializes the event handlers for clear table button. */ const initClearDocumentsTable = () => { const clearButton = document.querySelector('.js-clear-table-button') as HTMLElement | null; if (clearButton) { clearButton.addEventListener('click', async () => { if (window.confirm(clearButton.dataset.text)) { loaderHandler('add'); const request = await handleClearAccessibleDocsTable(); 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); } } }); } }; export default initClearDocumentsTable;