Merge pull request #318 from ets-cfuhrman-pfe/philippe/quiz-to-pdf
Some checks failed
CI/CD Pipeline for Backend / build_and_push_backend (push) Failing after 0s
CI/CD Pipeline for Nginx Router / build_and_push_nginx (push) Failing after 0s
CI/CD Pipeline for Frontend / build_and_push_frontend (push) Failing after 0s
Tests / lint-and-tests (client) (push) Failing after 0s
Tests / lint-and-tests (server) (push) Failing after 0s

Download quiz en PDF
This commit is contained in:
Christopher (Cris) Fuhrman 2025-04-10 21:34:15 -04:00 committed by GitHub
commit b8f13897ec
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 618 additions and 189 deletions

View file

@ -1,2 +1,3 @@
VITE_BACKEND_URL=http://localhost:4400 VITE_BACKEND_URL=http://localhost:4400
VITE_BACKEND_SOCKET_URL=http://localhost:4400 VITE_BACKEND_SOCKET_URL=http://localhost:4400
VITE_AZURE_BACKEND_URL=http://localhost:4400

496
client/package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -18,17 +18,18 @@
"@fortawesome/fontawesome-svg-core": "^6.7.2", "@fortawesome/fontawesome-svg-core": "^6.7.2",
"@fortawesome/free-solid-svg-icons": "^6.7.2", "@fortawesome/free-solid-svg-icons": "^6.7.2",
"@fortawesome/react-fontawesome": "^0.2.0", "@fortawesome/react-fontawesome": "^0.2.0",
"@mui/icons-material": "^7.0.1", "@mui/icons-material": "^7.0.2",
"@mui/lab": "^5.0.0-alpha.153", "@mui/lab": "^5.0.0-alpha.153",
"@mui/material": "^7.0.1", "@mui/material": "^7.0.2",
"@types/uuid": "^9.0.7", "@types/uuid": "^9.0.7",
"axios": "^1.8.1", "axios": "^1.8.1",
"dompurify": "^3.2.5", "dompurify": "^3.2.5",
"esbuild": "^0.25.2", "esbuild": "^0.25.2",
"gift-pegjs": "^2.0.0-beta.1", "gift-pegjs": "^2.0.0-beta.1",
"jest-environment-jsdom": "^29.7.0", "jest-environment-jsdom": "^29.7.0",
"jspdf": "^3.0.1",
"jwt-decode": "^4.0.0", "jwt-decode": "^4.0.0",
"katex": "^0.16.11", "katex": "^0.16.22",
"marked": "^15.0.8", "marked": "^15.0.8",
"nanoid": "^5.1.5", "nanoid": "^5.1.5",
"qrcode.react": "^4.2.0", "qrcode.react": "^4.2.0",
@ -73,7 +74,7 @@
"ts-jest": "^29.3.1", "ts-jest": "^29.3.1",
"typescript": "^5.8.3", "typescript": "^5.8.3",
"typescript-eslint": "^8.29.1", "typescript-eslint": "^8.29.1",
"vite": "^6.2.0", "vite": "^6.2.6",
"vite-plugin-environment": "^1.1.3" "vite-plugin-environment": "^1.1.3"
} }
} }

View file

@ -0,0 +1,72 @@
import React from 'react';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import '@testing-library/jest-dom';
import DownloadQuizModal from '../../../components/DownloadQuizModal/DownloadQuizModal';
import ApiService from '../../../services/ApiService';
import { QuizType } from '../../../Types/QuizType';
jest.mock('../../../services/ApiService');
jest.mock('jspdf', () => {
return jest.fn().mockImplementation(() => ({
addImage: jest.fn(),
save: jest.fn(),
addPage: jest.fn(),
}));
});
jest.mock('html2canvas', () => jest.fn(() => Promise.resolve(document.createElement('canvas'))));
jest.mock('dompurify', () => ({
sanitize: jest.fn((input) => input),
}));
const mockQuiz: QuizType = {
_id: '123',
title: 'Sample Quiz',
content: ['::Question 1:: What is 2+2? {=4 ~3 ~5}'],
folderId: 'folderId',
folderName: 'folderName',
userId: 'userId',
created_at: new Date(),
updated_at: new Date(),
};
describe('DownloadQuizModal', () => {
beforeEach(() => {
jest.clearAllMocks();
(ApiService.getQuiz as jest.Mock).mockResolvedValue(mockQuiz);
jest.spyOn(console, 'error').mockImplementation(() => {});
});
it('renders without crashing', () => {
render(<DownloadQuizModal quiz={mockQuiz} />);
expect(screen.getByRole('button', { name: /télécharger quiz/i })).toBeInTheDocument();
});
it('opens modal when download button is clicked', () => {
render(<DownloadQuizModal quiz={mockQuiz} />);
fireEvent.click(screen.getByRole('button', { name: /télécharger quiz/i }));
expect(screen.getByText(/choisissez un format de téléchargement/i)).toBeInTheDocument();
});
it('closes modal when a format button is clicked', async () => {
render(<DownloadQuizModal quiz={mockQuiz} />);
fireEvent.click(screen.getByRole('button', { name: /télécharger quiz/i }));
fireEvent.click(screen.getByRole('button', { name: /gift/i }));
await waitFor(() =>
expect(screen.queryByText(/choisissez un format de téléchargement/i)).not.toBeInTheDocument()
);
});
it('handles error when quiz API fails', async () => {
(ApiService.getQuiz as jest.Mock).mockRejectedValue(new Error('Quiz not found'));
render(<DownloadQuizModal quiz={mockQuiz} />);
fireEvent.click(screen.getByRole('button', { name: /télécharger quiz/i }));
fireEvent.click(screen.getByRole('button', { name: /gift/i }));
await waitFor(() => {
expect(console.error).toHaveBeenCalledWith(
expect.any(String),
expect.objectContaining({ message: expect.stringContaining("Quiz not found") })
);
});
});
});

View file

@ -0,0 +1,173 @@
import React, { useState } from 'react';
import { Dialog, DialogTitle, DialogActions, Button, Tooltip, IconButton } from '@mui/material';
import { FileDownload } from '@mui/icons-material';
import { QuizType } from '../../Types/QuizType';
import ApiService from '../../services/ApiService';
import jsPDF from 'jspdf';
import html2canvas from 'html2canvas';
import { parse } from 'gift-pegjs';
import DOMPurify from 'dompurify';
import Template, { ErrorTemplate } from '../GiftTemplate/templates';
interface DownloadQuizModalProps {
quiz: QuizType;
}
const DownloadQuizModal: React.FC<DownloadQuizModalProps> = ({ quiz }) => {
const [open, setOpen] = useState(false);
const handleOpenModal = () => setOpen(true);
const handleCloseModal = () => setOpen(false);
const handleDownload = async (format: 'txt' | 'pdf-with-answers' | 'pdf-without-answers') => {
switch (format) {
case 'txt':
await downloadTxtFile(quiz);
break;
case 'pdf-with-answers':
await downloadPdfFile(quiz, true);
break;
case 'pdf-without-answers':
await downloadPdfFile(quiz, false);
break;
}
handleCloseModal();
};
const downloadTxtFile = async (quiz: QuizType) => {
try {
const selectedQuiz = await ApiService.getQuiz(quiz._id) as QuizType;
if (!selectedQuiz) throw new Error('Quiz not found');
let quizContent = "";
selectedQuiz.content.forEach((question) => {
const formattedQuestion = question.trim();
if (formattedQuestion !== '') quizContent += formattedQuestion + '\n\n';
});
const blob = new Blob([quizContent], { type: 'text/plain' });
const a = document.createElement('a');
a.download = `${selectedQuiz.title}.gift`;
a.href = window.URL.createObjectURL(blob);
a.click();
} catch (error) {
console.error('Error exporting quiz:', error);
}
};
const downloadPdfFile = async (quiz: QuizType, withAnswers: boolean) => {
try {
const selectedQuiz = await ApiService.getQuiz(quiz._id) as QuizType;
if (!selectedQuiz) throw new Error('Quiz not found');
let previewHTML = '<h2>' + selectedQuiz.title + '</h2>';
selectedQuiz.content.forEach((giftQuestion) => {
try {
const question = parse(giftQuestion);
previewHTML += Template(question[0], {
preview: true,
theme: 'light',
});
} catch (error) {
if (error instanceof Error) {
previewHTML += ErrorTemplate(giftQuestion, error.message );
} else {
previewHTML += ErrorTemplate(giftQuestion, 'Erreur inconnue');
}
}
});
if (!withAnswers) {
const svgRegex = /<svg[^>]*>([\s\S]*?)<\/svg>/gi;
previewHTML = previewHTML.replace(svgRegex, '');
const placeholderRegex = /(placeholder=")[^"]*(")/gi;
previewHTML = previewHTML.replace(placeholderRegex, '$1$2');
const feedbackContainerRegex = /<(div|span)[^>]*class="feedback-container"[^>]*>[\s\S]*?<\/div>/gi;
previewHTML = previewHTML.replace(feedbackContainerRegex, '');
const answerClassRegex = /<(div|span)[^>]*class="[^"]*answer[^"]*"[^>]*>[\s\S]*?<\/\1>/gi;
previewHTML = previewHTML.replace(answerClassRegex, '');
const bonneReponseRegex = /<p[^>]*>[^<]*bonne réponse[^<]*<\/p>/gi;
previewHTML = previewHTML.replace(bonneReponseRegex, '');
const AllAnswersFieldRegex = /<(p|span)[^>]*>\s*Réponse:\s*<\/\1>\s*<input[^>]*>/gi
previewHTML = previewHTML.replace(AllAnswersFieldRegex, '');
}
const sanitizedHTML = DOMPurify.sanitize(previewHTML);
console.log('previewHTML:', sanitizedHTML);
const tempDiv = document.createElement('div');
tempDiv.innerHTML = sanitizedHTML;
document.body.appendChild(tempDiv);
// allowTaint and useCORS are set to true to allow cross-origin images to be used in the canvas
const canvas = await html2canvas(tempDiv, { scale: 2, useCORS: true, allowTaint: true });
document.body.removeChild(tempDiv);
const pdf = new jsPDF('p', 'mm', 'letter');
const pageWidth = pdf.internal.pageSize.width;
const pageHeight = pdf.internal.pageSize.height;
const margin = 10;
const imgWidth = pageWidth - 2 * margin;
let yOffset = 0;
while (yOffset < canvas.height) {
const pageCanvas = document.createElement('canvas');
pageCanvas.width = canvas.width;
pageCanvas.height = Math.min(canvas.height - yOffset, (pageHeight - 2 * margin) * (canvas.width / imgWidth));
const pageCtx = pageCanvas.getContext('2d');
if (pageCtx) {
pageCtx.drawImage(canvas, 0, yOffset, canvas.width, pageCanvas.height, 0, 0, pageCanvas.width, pageCanvas.height);
}
const pageImgData = pageCanvas.toDataURL('image/png');
if (yOffset > 0) pdf.addPage();
pdf.addImage(pageImgData, 'PNG', margin, margin, imgWidth, (pageCanvas.height * imgWidth) / pageCanvas.width);
yOffset += pageCanvas.height;
}
const filename = withAnswers
? `${selectedQuiz.title}_avec_reponses.pdf`
: `${selectedQuiz.title}_sans_reponses.pdf`;
pdf.save(filename);
} catch (error) {
console.error('Error exporting quiz as PDF:', error);
}
};
return (
<>
<Tooltip title="Télécharger quiz" placement="top">
<IconButton color="primary" onClick={handleOpenModal}>
<FileDownload />
</IconButton>
</Tooltip>
<Dialog open={open} onClose={handleCloseModal} fullWidth maxWidth="xs">
<DialogTitle sx={{ textAlign: "center" }}>Choisissez un format de téléchargement</DialogTitle>
<DialogActions sx={{ display: "flex", justifyContent: "center", gap: 2 }}>
<Button onClick={() => handleDownload('txt')}>GIFT</Button>
<Button onClick={() => handleDownload('pdf-with-answers')}> PDF avec réponses</Button>
<Button onClick={() => handleDownload('pdf-without-answers')}>PDF sans réponses</Button>
</DialogActions>
</Dialog>
</>
);
};
export default DownloadQuizModal;

View file

@ -33,13 +33,13 @@ import {
import { import {
Search, Search,
DeleteOutline, DeleteOutline,
FileDownload,
Add, Add,
Upload, Upload,
FolderCopy, FolderCopy,
ContentCopy, ContentCopy,
Edit Edit
} from '@mui/icons-material'; } from '@mui/icons-material';
import DownloadQuizModal from 'src/components/DownloadQuizModal/DownloadQuizModal';
import ShareQuizModal from 'src/components/ShareQuizModal/ShareQuizModal'; import ShareQuizModal from 'src/components/ShareQuizModal/ShareQuizModal';
// Create a custom-styled Card component // Create a custom-styled Card component
@ -263,46 +263,6 @@ const Dashboard: React.FC = () => {
return true; return true;
}; };
const downloadTxtFile = async (quiz: QuizType) => {
try {
const selectedQuiz = (await ApiService.getQuiz(quiz._id)) as QuizType;
//quizzes.find((quiz) => quiz._id === quiz._id);
if (!selectedQuiz) {
throw new Error('Selected quiz not found');
}
//const { title, content } = selectedQuiz;
let quizContent = '';
const title = selectedQuiz.title;
console.log(selectedQuiz.content);
selectedQuiz.content.forEach((question, qIndex) => {
const formattedQuestion = question.trim();
// console.log(formattedQuestion);
if (formattedQuestion !== '') {
quizContent += formattedQuestion + '\n';
if (qIndex !== selectedQuiz.content.length - 1) {
quizContent += '\n';
}
}
});
if (!validateQuiz(selectedQuiz.content)) {
window.alert(
'Attention! Ce quiz contient des questions invalides selon le format GIFT.'
);
}
const blob = new Blob([quizContent], { type: 'text/plain' });
const a = document.createElement('a');
const filename = title;
a.download = `${filename}.gift`;
a.href = window.URL.createObjectURL(blob);
a.click();
} catch (error) {
console.error('Error exporting selected quiz:', error);
}
};
const handleCreateFolder = async () => { const handleCreateFolder = async () => {
try { try {
const folderTitle = prompt('Titre du dossier'); const folderTitle = prompt('Titre du dossier');
@ -681,16 +641,10 @@ const Dashboard: React.FC = () => {
</Tooltip> </Tooltip>
</div> </div>
<div className="actions"> <div className='actions'>
<Tooltip title="Télécharger" placement="top"> <div className="dashboard">
<IconButton <DownloadQuizModal quiz={quiz} />
color="primary" </div>
onClick={() => downloadTxtFile(quiz)}
>
{' '}
<FileDownload />{' '}
</IconButton>
</Tooltip>
<Tooltip title="Modifier" placement="top"> <Tooltip title="Modifier" placement="top">
<IconButton <IconButton