Compare commits

..

No commits in common. "e24df3d5bfed294cca47d77061693bf06caf9c03" and "e795fb6dd3c59f6080611a45880c029581f2eb31" have entirely different histories.

7 changed files with 145 additions and 567 deletions

View file

@ -6,7 +6,7 @@
# EvalueTonSavoir # EvalueTonSavoir
EvalueTonSavoir ("Check What You Know") is an open-source and self-hosted platform that continues the development of the code from https://github.com/ETS-PFE004-Plateforme-sondage-minitest. This minimalist platform is designed as a learning and teaching tool, offering a simple and effective solution for creating quizzes using the GIFT format, similar to Moodle. EvalueTonSavoir is an open-source and self-hosted platform that continues the development of the code from https://github.com/ETS-PFE004-Plateforme-sondage-minitest. This minimalist platform is designed as a learning and teaching tool, offering a simple and effective solution for creating quizzes using the GIFT format, similar to Moodle.
## Key Features ## Key Features

View file

@ -1,3 +1,2 @@
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

403
client/package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -28,9 +28,8 @@
"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.22", "katex": "^0.16.11",
"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",
@ -75,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.6", "vite": "^6.2.0",
"vite-plugin-environment": "^1.1.3" "vite-plugin-environment": "^1.1.3"
} }
} }

View file

@ -1,72 +0,0 @@
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

@ -1,173 +0,0 @@
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,6 +263,46 @@ 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');
@ -641,10 +681,16 @@ const Dashboard: React.FC = () => {
</Tooltip> </Tooltip>
</div> </div>
<div className='actions'> <div className="actions">
<div className="dashboard"> <Tooltip title="Télécharger" placement="top">
<DownloadQuizModal quiz={quiz} /> <IconButton
</div> color="primary"
onClick={() => downloadTxtFile(quiz)}
>
{' '}
<FileDownload />{' '}
</IconButton>
</Tooltip>
<Tooltip title="Modifier" placement="top"> <Tooltip title="Modifier" placement="top">
<IconButton <IconButton