Failed to get corrections.
Could not load correction details.
`;
} finally {
setLoadingState(false);
}
};
/**
* Updates the UI with the results from the API call.
* @param {object} data - The parsed JSON object from the API.
*/
const updateUIWithResults = (data) => {
// Update corrected text
outputText.innerHTML = ''; // Clear previous content
const correctedParagraph = document.createElement('p');
correctedParagraph.textContent = data.correctedText;
outputText.appendChild(correctedParagraph);
// Update corrections breakdown
correctionsContainer.innerHTML = ''; // Clear previous content
if (data.corrections && data.corrections.length > 0) {
const list = document.createElement('div');
list.className = 'space-y-4';
data.corrections.forEach(item => {
const card = document.createElement('div');
card.className = 'p-4 border border-gray-200 rounded-lg bg-white shadow-sm';
card.innerHTML = `
`;
list.appendChild(card);
});
correctionsContainer.appendChild(list);
} else {
correctionsContainer.innerHTML = `
No Errors Found!
The provided text appears to be grammatically correct.
`;
}
// Show the PDF download button
pdfDownloadBtn.classList.remove('hidden');
};
/**
* Generates and downloads a PDF of the results.
*/
const downloadResultsAsPDF = async () => {
const { jsPDF } = window.jspdf;
const pdfOutput = document.getElementById('pdf-output');
// Temporarily add a class to hide elements we don't want in the PDF
pdfDownloadBtn.classList.add('no-print-visual');
// Use html2canvas to render the div into a canvas
const canvas = await html2canvas(pdfOutput, {
scale: 2, // Increase scale for better resolution
backgroundColor: '#ffffff',
onclone: (document) => {
// In the cloned document, actually hide the elements
document.querySelectorAll('.no-print-visual').forEach(el => el.style.display = 'none');
}
});
// Remove the temporary class after canvas is created
pdfDownloadBtn.classList.remove('no-print-visual');
const imgData = canvas.toDataURL('image/png');
const pdf = new jsPDF({
orientation: 'portrait',
unit: 'pt',
format: 'a4'
});
const pdfWidth = pdf.internal.pageSize.getWidth();
const pdfHeight = pdf.internal.pageSize.getHeight();
const canvasWidth = canvas.width;
const canvasHeight = canvas.height;
const ratio = canvasWidth / canvasHeight;
const widthInPdf = pdfWidth - 80; // A4 width in points, with margin
const heightInPdf = widthInPdf / ratio;
let finalHeight = heightInPdf;
if (heightInPdf > pdfHeight - 80) {
finalHeight = pdfHeight - 80; // Cap height to fit page with margin
}
// Add image to PDF
pdf.addImage(imgData, 'PNG', 40, 40, widthInPdf, finalHeight);
pdf.save('Grammar-Correction-Report.pdf');
};
// --- Event Listeners ---
// Attach event listener for the main action button.
checkGrammarBtn.addEventListener('click', handleGrammarCheck);
// Attach event listener for the PDF download button.
pdfDownloadBtn.addEventListener('click', downloadResultsAsPDF);
// Initialize the view
showTab(currentTab);
});