mirror of
https://github.com/ets-cfuhrman-pfe/EvalueTonSavoir.git
synced 2025-08-11 21:23:54 -04:00
Merge remote-tracking branch 'mgr/philippe/quiz-to-pdf' into dev-h25-merge-cus
This commit is contained in:
commit
1d9c30eb62
7 changed files with 515 additions and 182 deletions
|
|
@ -1,2 +1,3 @@
|
|||
VITE_BACKEND_URL=http://localhost:4400
|
||||
VITE_BACKEND_SOCKET_URL=http://localhost:4400
|
||||
VITE_AZURE_BACKEND_URL=http://localhost:4400
|
||||
|
|
|
|||
383
client/package-lock.json
generated
383
client/package-lock.json
generated
File diff suppressed because it is too large
Load diff
|
|
@ -27,6 +27,7 @@
|
|||
"esbuild": "^0.23.1",
|
||||
"gift-pegjs": "^2.0.0-beta.1",
|
||||
"jest-environment-jsdom": "^29.7.0",
|
||||
"jspdf": "^2.5.2",
|
||||
"katex": "^0.16.11",
|
||||
"marked": "^14.1.2",
|
||||
"nanoid": "^5.0.2",
|
||||
|
|
|
|||
|
|
@ -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") })
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
});
|
||||
172
client/src/components/DownloadQuizModal/DownloadQuizModal.tsx
Normal file
172
client/src/components/DownloadQuizModal/DownloadQuizModal.tsx
Normal file
|
|
@ -0,0 +1,172 @@
|
|||
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 = '';
|
||||
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 + '\n' + error.message);
|
||||
} else {
|
||||
previewHTML += ErrorTemplate(giftQuestion + '\n' + '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);
|
||||
|
||||
const canvas = await html2canvas(tempDiv, { scale: 2 });
|
||||
|
||||
document.body.removeChild(tempDiv);
|
||||
|
||||
const pdf = new jsPDF('p', 'mm', 'a4');
|
||||
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;
|
||||
|
|
@ -27,7 +27,6 @@ import {
|
|||
import {
|
||||
Search,
|
||||
DeleteOutline,
|
||||
FileDownload,
|
||||
Add,
|
||||
Upload,
|
||||
FolderCopy,
|
||||
|
|
@ -36,6 +35,7 @@ import {
|
|||
Share,
|
||||
// DriveFileMove
|
||||
} from '@mui/icons-material';
|
||||
import DownloadQuizModal from 'src/components/DownloadQuizModal/DownloadQuizModal';
|
||||
|
||||
// Create a custom-styled Card component
|
||||
const CustomCard = styled(Card)({
|
||||
|
|
@ -196,7 +196,7 @@ const Dashboard: React.FC = () => {
|
|||
// questions[i] = QuestionService.ignoreImgTags(questions[i]);
|
||||
const parsedItem = parse(questions[i]);
|
||||
Template(parsedItem[0]);
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
} catch (error) {
|
||||
return false;
|
||||
}
|
||||
|
|
@ -205,47 +205,6 @@ const Dashboard: React.FC = () => {
|
|||
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 () => {
|
||||
try {
|
||||
const folderTitle = prompt('Titre du dossier');
|
||||
|
|
@ -299,7 +258,7 @@ const Dashboard: React.FC = () => {
|
|||
const renamedFolderId = selectedFolderId;
|
||||
const result = await ApiService.renameFolder(selectedFolderId, newTitle);
|
||||
|
||||
if (result !== true ) {
|
||||
if (result !== true) {
|
||||
window.alert(`Une erreur est survenue: ${result}`);
|
||||
return;
|
||||
}
|
||||
|
|
@ -481,12 +440,9 @@ const Dashboard: React.FC = () => {
|
|||
</div>
|
||||
|
||||
<div className='actions'>
|
||||
<Tooltip title="Télécharger quiz" placement="top">
|
||||
<IconButton
|
||||
color="primary"
|
||||
onClick={() => downloadTxtFile(quiz)}
|
||||
> <FileDownload /> </IconButton>
|
||||
</Tooltip>
|
||||
<div className="dashboard">
|
||||
<DownloadQuizModal quiz={quiz} />
|
||||
</div>
|
||||
|
||||
<Tooltip title="Modifier quiz" placement="top">
|
||||
<IconButton
|
||||
|
|
|
|||
6
package-lock.json
generated
Normal file
6
package-lock.json
generated
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
{
|
||||
"name": "EvalueTonSavoir",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {}
|
||||
}
|
||||
Loading…
Reference in a new issue