mirror of
https://github.com/ets-cfuhrman-pfe/EvalueTonSavoir.git
synced 2025-08-11 21:23:54 -04:00
Compare commits
87 commits
e0897ff536
...
95a0abecff
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
95a0abecff | ||
|
|
e19048f5dd | ||
|
|
09ec127a76 | ||
|
|
911d051089 | ||
|
|
ddf955a7a2 | ||
|
|
51cebdaba1 | ||
|
|
57c5321c09 | ||
|
|
62df610d62 | ||
|
|
f13b58d89b | ||
|
|
a66631c60b | ||
|
|
5a5897d25c | ||
|
|
20bfb8774f | ||
|
|
36b5c58b94 | ||
|
|
40aee9aa89 | ||
|
|
c13e73208e | ||
|
|
f28bd90c6e | ||
|
|
7a8ab7e5f5 | ||
|
|
42c0bee527 | ||
|
|
1de68418e0 | ||
|
|
8f6cf8cffa | ||
|
|
9205c0c6bf | ||
|
|
8e999dc10f | ||
|
|
d0328f9ec8 | ||
|
|
61bf9b9d86 | ||
|
|
a26ffa2880 | ||
|
|
95f914ce3e | ||
|
|
46c17ba127 | ||
|
|
74764ee695 | ||
|
|
6600da990b | ||
|
|
7c7fe031f8 | ||
|
|
aa739233dd | ||
|
|
0d7b6ee5eb | ||
|
|
d5733fa728 | ||
|
|
78e398ecd8 | ||
|
|
755d14a5b7 | ||
|
|
1a7dc7fec2 | ||
|
|
ee7a7a0544 | ||
|
|
8c57a8759f | ||
|
|
22a2754e31 | ||
|
|
3d9015febd | ||
|
|
fc15d2c3bd | ||
|
|
13136b9e91 | ||
|
|
b92f81cc0e | ||
|
|
42e3041830 | ||
|
|
81bedf0672 | ||
|
|
c50cd3e6e7 | ||
|
|
a3e0ba70f9 | ||
|
|
a4d36389c7 | ||
|
|
dc7fb82d97 | ||
|
|
4e0d5d778d | ||
|
|
d9480e2d14 | ||
|
|
ab9636c8db | ||
|
|
e2376dd8c3 | ||
|
|
92699f9a83 | ||
|
|
1c16e06319 | ||
|
|
b7a7962435 | ||
|
|
b7ec35c0c9 | ||
|
|
fb41980f29 | ||
|
|
0243270fdb | ||
|
|
241854159b | ||
|
|
312ccd0b52 | ||
|
|
ef192eb784 | ||
|
|
01deaee487 | ||
|
|
f4bcfd27b9 | ||
|
|
6b654c769c | ||
|
|
f0b3d74c31 | ||
|
|
2ca21a7d6b | ||
|
|
66ce4937d9 | ||
|
|
9ff2882761 | ||
|
|
de5f8fad6c | ||
|
|
1512f320c8 | ||
|
|
78f6993547 | ||
|
|
f6afb1f7ed | ||
|
|
1b321c74f9 | ||
|
|
add7d9954b | ||
|
|
71f57fd2cf | ||
|
|
f055a47305 | ||
|
|
f8357883e6 | ||
|
|
0f87bab5ff | ||
|
|
c9d65c0082 | ||
|
|
460b4f1648 | ||
|
|
5ba89072e2 | ||
|
|
9e5613a011 | ||
|
|
16d594c61d | ||
|
|
e7c3c84b80 | ||
|
|
ee5e096984 | ||
|
|
c6c830ef74 |
60 changed files with 3687 additions and 1592 deletions
1
.gitignore
vendored
1
.gitignore
vendored
|
|
@ -41,6 +41,7 @@ build/Release
|
||||||
# Dependency directories
|
# Dependency directories
|
||||||
node_modules/
|
node_modules/
|
||||||
jspm_packages/
|
jspm_packages/
|
||||||
|
mongo-backup/
|
||||||
|
|
||||||
# Snowpack dependency directory (https://snowpack.dev/)
|
# Snowpack dependency directory (https://snowpack.dev/)
|
||||||
web_modules/
|
web_modules/
|
||||||
|
|
|
||||||
30
README.fr-ca.md
Normal file
30
README.fr-ca.md
Normal file
|
|
@ -0,0 +1,30 @@
|
||||||
|
[](https://github.com/ets-cfuhrman-pfe/EvalueTonSavoir/actions/workflows/frontend-deploy.yml)
|
||||||
|
[](https://github.com/ets-cfuhrman-pfe/EvalueTonSavoir/actions/workflows/backend-deploy.yml)
|
||||||
|
[](https://github.com/ets-cfuhrman-pfe/EvalueTonSavoir/actions/workflows/deploy.yml)
|
||||||
|
|
||||||
|
|
||||||
|
[](https://github.com/ets-cfuhrman-pfe/EvalueTonSavoir/blob/master/README.md)
|
||||||
|
|
||||||
|
# EvalueTonSavoir
|
||||||
|
|
||||||
|
EvalueTonSavoir est une plateforme open source et auto-hébergée qui poursuit le développement du code provenant de https://github.com/ETS-PFE004-Plateforme-sondage-minitest. Cette plateforme minimaliste est conçue comme un outil d'apprentissage et d'enseignement, offrant une solution simple et efficace pour la création de quiz utilisant le format GIFT, similaire à Moodle.
|
||||||
|
|
||||||
|
## Fonctionnalités clés
|
||||||
|
|
||||||
|
* Open Source et Auto-hébergé : Possédez et contrôlez vos données en déployant la plateforme sur votre propre infrastructure.
|
||||||
|
* Compatibilité GIFT : Créez des quiz facilement en utilisant le format GIFT, permettant une intégration transparente avec d'autres systèmes d'apprentissage.
|
||||||
|
* Minimaliste et Efficace : Une approche bare bones pour garantir la simplicité et la facilité d'utilisation, mettant l'accent sur l'essentiel de l'apprentissage.
|
||||||
|
|
||||||
|
## Contribution
|
||||||
|
|
||||||
|
Actuellement, il n'y a pas de modèle établi pour les contributions. Si vous constatez quelque chose de manquant ou si vous pensez qu'une amélioration est possible, n'hésitez pas à ouvrir un issue et/ou une PR)
|
||||||
|
|
||||||
|
## Liens utiles
|
||||||
|
|
||||||
|
* [Dépôt d'origine Frontend](https://github.com/ETS-PFE004-Plateforme-sondage-minitest/ETS-PFE004-EvalueTonSavoir-Frontend)
|
||||||
|
* [Dépôt d'origine Backend](https://github.com/ETS-PFE004-Plateforme-sondage-minitest/ETS-PFE004-EvalueTonSavoir-Backend)
|
||||||
|
* [Documentation (Wiki)](https://github.com/ets-cfuhrman-pfe/EvalueTonSavoir/wiki)
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
EvalueTonSavoir is open-sourced and licensed under the [MIT License](/LICENSE).
|
||||||
22
README.md
22
README.md
|
|
@ -2,24 +2,26 @@
|
||||||
[](https://github.com/ets-cfuhrman-pfe/EvalueTonSavoir/actions/workflows/backend-deploy.yml)
|
[](https://github.com/ets-cfuhrman-pfe/EvalueTonSavoir/actions/workflows/backend-deploy.yml)
|
||||||
[](https://github.com/ets-cfuhrman-pfe/EvalueTonSavoir/actions/workflows/deploy.yml)
|
[](https://github.com/ets-cfuhrman-pfe/EvalueTonSavoir/actions/workflows/deploy.yml)
|
||||||
|
|
||||||
# EvalueTonSavoir
|
[](https://github.com/ets-cfuhrman-pfe/EvalueTonSavoir/blob/main/README.fr-ca.md)
|
||||||
|
|
||||||
EvalueTonSavoir est une plateforme open source et auto-hébergée qui poursuit le développement du code provenant de https://github.com/ETS-PFE004-Plateforme-sondage-minitest. Cette plateforme minimaliste est conçue comme un outil d'apprentissage et d'enseignement, offrant une solution simple et efficace pour la création de quiz utilisant le format GIFT, similaire à Moodle.
|
# EvalueTonSavoir
|
||||||
|
|
||||||
## Fonctionnalités clés
|
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.
|
||||||
|
|
||||||
* Open Source et Auto-hébergé : Possédez et contrôlez vos données en déployant la plateforme sur votre propre infrastructure.
|
## Key Features
|
||||||
* Compatibilité GIFT : Créez des quiz facilement en utilisant le format GIFT, permettant une intégration transparente avec d'autres systèmes d'apprentissage.
|
|
||||||
* Minimaliste et Efficace : Une approche bare bones pour garantir la simplicité et la facilité d'utilisation, mettant l'accent sur l'essentiel de l'apprentissage.
|
* **Open Source and Self-Hosted**: Own and control your data by deploying the platform on your own infrastructure.
|
||||||
|
* **GIFT Compatibility**: Easily create quizzes using the GIFT format, enabling seamless integration with other learning systems.
|
||||||
|
* **Minimalist and Efficient**: A bare-bones approach to ensure simplicity and ease of use, focusing on the essentials of learning.
|
||||||
|
|
||||||
## Contribution
|
## Contribution
|
||||||
|
|
||||||
Actuellement, il n'y a pas de modèle établi pour les contributions. Si vous constatez quelque chose de manquant ou si vous pensez qu'une amélioration est possible, n'hésitez pas à ouvrir un issue et/ou une PR)
|
Currently, there is no established model for contributions. If you notice something missing or think an improvement is possible, feel free to open an issue and/or a PR.
|
||||||
|
|
||||||
## Liens utiles
|
## Useful Links
|
||||||
|
|
||||||
* [Dépôt d'origine Frontend](https://github.com/ETS-PFE004-Plateforme-sondage-minitest/ETS-PFE004-EvalueTonSavoir-Frontend)
|
* [Original Frontend Repository](https://github.com/ETS-PFE004-Plateforme-sondage-minitest/ETS-PFE004-EvalueTonSavoir-Frontend)
|
||||||
* [Dépôt d'origine Backend](https://github.com/ETS-PFE004-Plateforme-sondage-minitest/ETS-PFE004-EvalueTonSavoir-Backend)
|
* [Original Backend Repository](https://github.com/ETS-PFE004-Plateforme-sondage-minitest/ETS-PFE004-EvalueTonSavoir-Backend)
|
||||||
* [Documentation (Wiki)](https://github.com/ets-cfuhrman-pfe/EvalueTonSavoir/wiki)
|
* [Documentation (Wiki)](https://github.com/ets-cfuhrman-pfe/EvalueTonSavoir/wiki)
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
|
||||||
|
|
@ -1,2 +1,2 @@
|
||||||
VITE_BACKEND_URL=http://localhost:4400
|
VITE_BACKEND_URL=http://localhost:4400
|
||||||
VITE_AZURE_BACKEND_URL=http://localhost:4400
|
VITE_AZURE_BACKEND_URL=http://localhost:4400
|
||||||
|
|
|
||||||
954
client/package-lock.json
generated
954
client/package-lock.json
generated
File diff suppressed because it is too large
Load diff
|
|
@ -8,7 +8,7 @@
|
||||||
"build": "tsc && vite build",
|
"build": "tsc && vite build",
|
||||||
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
|
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
|
||||||
"preview": "vite preview",
|
"preview": "vite preview",
|
||||||
"test": "jest --colors",
|
"test": "jest --colors --silent",
|
||||||
"test:watch": "jest --watch"
|
"test:watch": "jest --watch"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
|
@ -18,19 +18,20 @@
|
||||||
"@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": "^6.4.6",
|
"@mui/icons-material": "^7.0.1",
|
||||||
"@mui/lab": "^5.0.0-alpha.153",
|
"@mui/lab": "^5.0.0-alpha.153",
|
||||||
"@mui/material": "^6.4.7",
|
"@mui/material": "^7.0.1",
|
||||||
"@types/uuid": "^9.0.7",
|
"@types/uuid": "^9.0.7",
|
||||||
"axios": "^1.8.1",
|
"axios": "^1.8.1",
|
||||||
"dompurify": "^3.2.3",
|
"dompurify": "^3.2.5",
|
||||||
"esbuild": "^0.25.0",
|
"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",
|
||||||
"jwt-decode": "^4.0.0",
|
"jwt-decode": "^4.0.0",
|
||||||
"katex": "^0.16.11",
|
"katex": "^0.16.11",
|
||||||
"marked": "^14.1.2",
|
"marked": "^15.0.8",
|
||||||
"nanoid": "^5.1.2",
|
"nanoid": "^5.1.5",
|
||||||
|
"qrcode.react": "^4.2.0",
|
||||||
"react": "^18.3.1",
|
"react": "^18.3.1",
|
||||||
"react-dom": "^18.3.1",
|
"react-dom": "^18.3.1",
|
||||||
"react-modal": "^3.16.3",
|
"react-modal": "^3.16.3",
|
||||||
|
|
@ -38,39 +39,40 @@
|
||||||
"remark-math": "^6.0.0",
|
"remark-math": "^6.0.0",
|
||||||
"socket.io-client": "^4.7.2",
|
"socket.io-client": "^4.7.2",
|
||||||
"ts-node": "^10.9.1",
|
"ts-node": "^10.9.1",
|
||||||
"uuid": "^9.0.1",
|
"uuid": "^11.1.0",
|
||||||
"vite-plugin-checker": "^0.9.0"
|
"vite-plugin-checker": "^0.9.1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@babel/preset-env": "^7.26.9",
|
"@babel/preset-env": "^7.26.9",
|
||||||
"@babel/preset-react": "^7.26.3",
|
"@babel/preset-react": "^7.26.3",
|
||||||
"@babel/preset-typescript": "^7.23.3",
|
"@babel/preset-typescript": "^7.27.0",
|
||||||
"@eslint/js": "^9.21.0",
|
"@eslint/js": "^9.24.0",
|
||||||
"@testing-library/dom": "^10.4.0",
|
"@testing-library/dom": "^10.4.0",
|
||||||
"@testing-library/jest-dom": "^6.6.3",
|
"@testing-library/jest-dom": "^6.6.3",
|
||||||
"@testing-library/react": "^16.2.0",
|
"@testing-library/react": "^16.3.0",
|
||||||
|
"@testing-library/user-event": "^14.6.1",
|
||||||
"@types/jest": "^29.5.13",
|
"@types/jest": "^29.5.13",
|
||||||
"@types/node": "^22.13.5",
|
"@types/node": "^22.14.0",
|
||||||
"@types/react": "^18.2.15",
|
"@types/react": "^18.2.15",
|
||||||
"@types/react-dom": "^18.2.7",
|
"@types/react-dom": "^18.2.7",
|
||||||
"@types/react-latex": "^2.0.3",
|
"@types/react-latex": "^2.0.3",
|
||||||
"@typescript-eslint/eslint-plugin": "^8.25.0",
|
"@typescript-eslint/eslint-plugin": "^8.29.1",
|
||||||
"@typescript-eslint/parser": "^8.25.0",
|
"@typescript-eslint/parser": "^8.29.1",
|
||||||
"@vitejs/plugin-react-swc": "^3.8.0",
|
"@vitejs/plugin-react-swc": "^3.8.1",
|
||||||
"cross-env": "^7.0.3",
|
"cross-env": "^7.0.3",
|
||||||
"eslint": "^9.21.0",
|
"eslint": "^9.24.0",
|
||||||
"eslint-plugin-eslint-comments": "^3.2.0",
|
"eslint-plugin-eslint-comments": "^3.2.0",
|
||||||
"eslint-plugin-jest": "^28.11.0",
|
"eslint-plugin-jest": "^28.11.0",
|
||||||
"eslint-plugin-react": "^7.37.3",
|
"eslint-plugin-react": "^7.37.5",
|
||||||
"eslint-plugin-react-hooks": "^5.1.0-rc-206df66e-20240912",
|
"eslint-plugin-react-hooks": "^5.1.0-rc-206df66e-20240912",
|
||||||
"eslint-plugin-react-refresh": "^0.4.19",
|
"eslint-plugin-react-refresh": "^0.4.19",
|
||||||
"eslint-plugin-unused-imports": "^4.1.4",
|
"eslint-plugin-unused-imports": "^4.1.4",
|
||||||
"globals": "^15.14.0",
|
"globals": "^15.14.0",
|
||||||
"identity-obj-proxy": "^3.0.0",
|
"identity-obj-proxy": "^3.0.0",
|
||||||
"jest": "^29.7.0",
|
"jest": "^29.7.0",
|
||||||
"ts-jest": "^29.2.6",
|
"ts-jest": "^29.3.1",
|
||||||
"typescript": "^5.7.3",
|
"typescript": "^5.8.3",
|
||||||
"typescript-eslint": "^8.25.0",
|
"typescript-eslint": "^8.29.1",
|
||||||
"vite": "^6.2.0",
|
"vite": "^6.2.0",
|
||||||
"vite-plugin-environment": "^1.1.3"
|
"vite-plugin-environment": "^1.1.3"
|
||||||
}
|
}
|
||||||
|
|
|
||||||
17
client/src/Types/Images.tsx
Normal file
17
client/src/Types/Images.tsx
Normal file
|
|
@ -0,0 +1,17 @@
|
||||||
|
export interface Images {
|
||||||
|
id: string;
|
||||||
|
file_content: string;
|
||||||
|
file_name: string;
|
||||||
|
mime_type: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ImagesResponse {
|
||||||
|
images: Images[];
|
||||||
|
total: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ImagesParams {
|
||||||
|
page: number;
|
||||||
|
limit: number;
|
||||||
|
uid?: string;
|
||||||
|
}
|
||||||
|
|
@ -19,8 +19,8 @@ const mockQuestions: QuestionType[] = mockGiftQuestions.map((question, index) =>
|
||||||
});
|
});
|
||||||
|
|
||||||
const mockStudents: StudentType[] = [
|
const mockStudents: StudentType[] = [
|
||||||
{ id: "1", name: 'Student 1', answers: [{ idQuestion: 1, answer: 'Answer 1', isCorrect: true }] },
|
{ id: "1", name: 'Student 1', answers: [{ idQuestion: 1, answer: ['Answer 1'], isCorrect: true }] },
|
||||||
{ id: "2", name: 'Student 2', answers: [{ idQuestion: 2, answer: 'Answer 2', isCorrect: false }] },
|
{ id: "2", name: 'Student 2', answers: [{ idQuestion: 2, answer: ['Answer 2'], isCorrect: false }] },
|
||||||
];
|
];
|
||||||
|
|
||||||
const mockShowSelectedQuestion = jest.fn();
|
const mockShowSelectedQuestion = jest.fn();
|
||||||
|
|
@ -92,4 +92,4 @@ describe('LiveResults', () => {
|
||||||
|
|
||||||
expect(mockShowSelectedQuestion).toHaveBeenCalled();
|
expect(mockShowSelectedQuestion).toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -20,8 +20,8 @@ const mockQuestions: QuestionType[] = mockGiftQuestions.map((question, index) =>
|
||||||
|
|
||||||
|
|
||||||
const mockStudents: StudentType[] = [
|
const mockStudents: StudentType[] = [
|
||||||
{ id: "1", name: 'Student 1', answers: [{ idQuestion: 1, answer: 'Answer 1', isCorrect: true }] },
|
{ id: "1", name: 'Student 1', answers: [{ idQuestion: 1, answer: ['Answer 1'], isCorrect: true }] },
|
||||||
{ id: "2", name: 'Student 2', answers: [{ idQuestion: 2, answer: 'Answer 2', isCorrect: false }] },
|
{ id: "2", name: 'Student 2', answers: [{ idQuestion: 2, answer: ['Answer 2'], isCorrect: false }] },
|
||||||
];
|
];
|
||||||
|
|
||||||
const mockShowSelectedQuestion = jest.fn();
|
const mockShowSelectedQuestion = jest.fn();
|
||||||
|
|
|
||||||
|
|
@ -20,8 +20,8 @@ const mockQuestions: QuestionType[] = mockGiftQuestions.map((question, index) =>
|
||||||
});
|
});
|
||||||
|
|
||||||
const mockStudents: StudentType[] = [
|
const mockStudents: StudentType[] = [
|
||||||
{ id: "1", name: 'Student 1', answers: [{ idQuestion: 1, answer: 'Answer 1', isCorrect: true }] },
|
{ id: "1", name: 'Student 1', answers: [{ idQuestion: 1, answer: ['Answer 1'], isCorrect: true }] },
|
||||||
{ id: "2", name: 'Student 2', answers: [{ idQuestion: 2, answer: 'Answer 2', isCorrect: false }] },
|
{ id: "2", name: 'Student 2', answers: [{ idQuestion: 2, answer: ['Answer 2'], isCorrect: false }] },
|
||||||
];
|
];
|
||||||
|
|
||||||
const mockGetStudentGrade = jest.fn((student: StudentType) => {
|
const mockGetStudentGrade = jest.fn((student: StudentType) => {
|
||||||
|
|
|
||||||
|
|
@ -6,8 +6,8 @@ import LiveResultsTableFooter from 'src/components/LiveResults/LiveResultsTable/
|
||||||
|
|
||||||
|
|
||||||
const mockStudents: StudentType[] = [
|
const mockStudents: StudentType[] = [
|
||||||
{ id: "1", name: 'Student 1', answers: [{ idQuestion: 1, answer: 'Answer 1', isCorrect: true }] },
|
{ id: "1", name: 'Student 1', answers: [{ idQuestion: 1, answer: ['Answer 1'], isCorrect: true }] },
|
||||||
{ id: "2", name: 'Student 2', answers: [{ idQuestion: 2, answer: 'Answer 2', isCorrect: false }] },
|
{ id: "2", name: 'Student 2', answers: [{ idQuestion: 2, answer: ['Answer 2'], isCorrect: false }] },
|
||||||
];
|
];
|
||||||
|
|
||||||
const mockGetStudentGrade = jest.fn((student: StudentType) => {
|
const mockGetStudentGrade = jest.fn((student: StudentType) => {
|
||||||
|
|
@ -52,4 +52,4 @@ describe('LiveResultsTableFooter', () => {
|
||||||
|
|
||||||
expect(screen.getByText('50 %')).toBeInTheDocument();
|
expect(screen.getByText('50 %')).toBeInTheDocument();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -29,7 +29,7 @@ const katekMock: TemplateOptions & MultipleChoiceQuestion = {
|
||||||
formattedStem: { format: 'plain' , text: '$$\\frac{zzz}{yyy}$$'},
|
formattedStem: { format: 'plain' , text: '$$\\frac{zzz}{yyy}$$'},
|
||||||
choices: [
|
choices: [
|
||||||
{ formattedText: { format: 'plain' , text: 'Choice 1'}, isCorrect: true, formattedFeedback: { format: 'plain' , text: 'Correct!'}, weight: 1 },
|
{ formattedText: { format: 'plain' , text: 'Choice 1'}, isCorrect: true, formattedFeedback: { format: 'plain' , text: 'Correct!'}, weight: 1 },
|
||||||
{ formattedText: { format: 'plain', text: 'Choice 2' }, isCorrect: true, formattedFeedback: { format: 'plain' , text: 'Correct!'}, weight: 1 }
|
{ formattedText: { format: 'plain', text: 'Choice 2' }, isCorrect: false, formattedFeedback: { format: 'plain' , text: 'Correct!'}, weight: 0 }
|
||||||
],
|
],
|
||||||
formattedGlobalFeedback: { format: 'plain', text: 'Sample Global Feedback' }
|
formattedGlobalFeedback: { format: 'plain', text: 'Sample Global Feedback' }
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -733,7 +733,7 @@ exports[`MultipleChoice snapshot test with katex 1`] = `
|
||||||
|
|
||||||
<div class='multiple-choice-answers-container'>
|
<div class='multiple-choice-answers-container'>
|
||||||
<input class="gift-input" type="radio" id="idmocked-id" name="idmocked-id">
|
<input class="gift-input" type="radio" id="idmocked-id" name="idmocked-id">
|
||||||
<span class="answer-weight-container answer-positive-weight">1%</span>
|
|
||||||
<label style="
|
<label style="
|
||||||
display: inline-block;
|
display: inline-block;
|
||||||
padding: 0.2em 0 0.2em 0;
|
padding: 0.2em 0 0.2em 0;
|
||||||
|
|
@ -742,15 +742,15 @@ exports[`MultipleChoice snapshot test with katex 1`] = `
|
||||||
" for="idmocked-id">
|
" for="idmocked-id">
|
||||||
Choice 2
|
Choice 2
|
||||||
</label>
|
</label>
|
||||||
<svg data-testid="correct-icon" style="
|
<svg data-testid="incorrect-icon" style="
|
||||||
vertical-align: text-bottom;
|
vertical-align: text-bottom;
|
||||||
display: inline-block;
|
display: inline-block;
|
||||||
margin-left: 0.1rem;
|
margin-left: 0.1rem;
|
||||||
margin-right: 0.2rem;
|
margin-right: 0.2rem;
|
||||||
|
|
||||||
width: 1em;
|
width: 0.75em;
|
||||||
color: hsl(120, 39%, 54%);
|
color: hsl(2, 64%, 58%);
|
||||||
" role="img" aria-hidden="true" focusable="false" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path fill="currentColor" d="M173.898 439.404l-166.4-166.4c-9.997-9.997-9.997-26.206 0-36.204l36.203-36.204c9.997-9.998 26.207-9.998 36.204 0L192 312.69 432.095 72.596c9.997-9.997 26.207-9.997 36.204 0l36.203 36.204c9.997 9.997 9.997 26.206 0 36.204l-294.4 294.401c-9.998 9.997-26.207 9.997-36.204-.001z"></path></svg>
|
" role="img" aria-hidden="true" focusable="false" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 352 512"><path fill="currentColor" d="M242.72 256l100.07-100.07c12.28-12.28 12.28-32.19 0-44.48l-22.24-22.24c-12.28-12.28-32.19-12.28-44.48 0L176 189.28 75.93 89.21c-12.28-12.28-32.19-12.28-44.48 0L9.21 111.45c-12.28 12.28-12.28 32.19 0 44.48L109.28 256 9.21 356.07c-12.28 12.28-12.28 32.19 0 44.48l22.24 22.24c12.28 12.28 32.2 12.28 44.48 0L176 322.72l100.07 100.07c12.28 12.28 32.2 12.28 44.48 0l22.24-22.24c12.28-12.28 12.28-32.19 0-44.48L242.72 256z"></path></svg>
|
||||||
<span class="feedback-container">Correct!</span>
|
<span class="feedback-container">Correct!</span>
|
||||||
</input>
|
</input>
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,147 @@
|
||||||
|
import React, { act } from "react";
|
||||||
|
import "@testing-library/jest-dom";
|
||||||
|
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
|
||||||
|
import ImageGallery from "../../../components/ImageGallery/ImageGallery";
|
||||||
|
import ApiService from "../../../services/ApiService";
|
||||||
|
import { Images } from "../../../Types/Images";
|
||||||
|
import userEvent from "@testing-library/user-event";
|
||||||
|
|
||||||
|
jest.mock("../../../services/ApiService");
|
||||||
|
|
||||||
|
const mockImages: Images[] = [
|
||||||
|
{ id: "1", file_name: "image1.jpg", mime_type: "image/jpeg", file_content: "mockBase64Content1" },
|
||||||
|
{ id: "2", file_name: "image2.jpg", mime_type: "image/jpeg", file_content: "mockBase64Content2" },
|
||||||
|
{ id: "3", file_name: "image3.jpg", mime_type: "image/jpeg", file_content: "mockBase64Content3" },
|
||||||
|
];
|
||||||
|
|
||||||
|
beforeAll(() => {
|
||||||
|
global.URL.createObjectURL = jest.fn(() => 'mockedObjectUrl');
|
||||||
|
Object.assign(navigator, {
|
||||||
|
clipboard: {
|
||||||
|
writeText: jest.fn(),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("ImageGallery", () => {
|
||||||
|
let mockHandleDelete: jest.Mock;
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
(ApiService.getUserImages as jest.Mock).mockResolvedValue({ images: mockImages, total: 3 });
|
||||||
|
(ApiService.deleteImage as jest.Mock).mockResolvedValue(true);
|
||||||
|
(ApiService.uploadImage as jest.Mock).mockResolvedValue('mockImageUrl');
|
||||||
|
await act(async () => {
|
||||||
|
render(<ImageGallery />);
|
||||||
|
});
|
||||||
|
mockHandleDelete = jest.fn();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should render images correctly", async () => {
|
||||||
|
await act(async () => {
|
||||||
|
await screen.findByText("Galerie");
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(screen.getByAltText("Image image1.jpg")).toBeInTheDocument();
|
||||||
|
expect(screen.getByAltText("Image image2.jpg")).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should handle copy action", async () => {
|
||||||
|
const handleCopyMock = jest.fn();
|
||||||
|
await act(async () => {
|
||||||
|
render(<ImageGallery handleCopy={handleCopyMock} />);
|
||||||
|
});
|
||||||
|
|
||||||
|
const copyButtons = await waitFor(() => screen.findAllByTestId(/gallery-tab-copy-/));
|
||||||
|
await act(async () => {
|
||||||
|
fireEvent.click(copyButtons[0]);
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(navigator.clipboard.writeText).toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should delete an image and update the gallery", async () => {
|
||||||
|
const fetchImagesMock = jest.fn().mockResolvedValue({ images: mockImages.filter((image) => image.id !== "1"), total: 2 });
|
||||||
|
|
||||||
|
(ApiService.getUserImages as jest.Mock).mockImplementation(fetchImagesMock);
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
render(<ImageGallery handleDelete={mockHandleDelete} />);
|
||||||
|
});
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
await screen.findByAltText("Image image1.jpg");
|
||||||
|
});
|
||||||
|
|
||||||
|
const deleteButtons = await waitFor(() => screen.findAllByTestId(/gallery-tab-delete-/));
|
||||||
|
fireEvent.click(deleteButtons[0]);
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(screen.getByText("Voulez-vous supprimer cette image?")).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
const confirmDeleteButton = screen.getByText("Delete");
|
||||||
|
await act(async () => {
|
||||||
|
fireEvent.click(confirmDeleteButton);
|
||||||
|
});
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(ApiService.deleteImage).toHaveBeenCalledWith("1");
|
||||||
|
});
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(screen.queryByAltText("Image image1.jpg")).toBeNull();
|
||||||
|
expect(screen.getByText("Image supprimée avec succès!")).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should upload an image and display success message", async () => {
|
||||||
|
const importTab = screen.getByRole("tab", { name: /import/i });
|
||||||
|
fireEvent.click(importTab);
|
||||||
|
|
||||||
|
const fileInputs = await screen.findAllByTestId("file-input");
|
||||||
|
const fileInput = fileInputs[1];
|
||||||
|
|
||||||
|
expect(fileInput).toBeInTheDocument();
|
||||||
|
|
||||||
|
const file = new File(["image"], "image.jpg", { type: "image/jpeg" });
|
||||||
|
await userEvent.upload(fileInput, file);
|
||||||
|
|
||||||
|
|
||||||
|
await waitFor(() => screen.getByAltText("Preview"));
|
||||||
|
const previewImage = screen.getByAltText("Preview");
|
||||||
|
|
||||||
|
expect(previewImage).toBeInTheDocument();
|
||||||
|
|
||||||
|
const uploadButton = screen.getByRole('button', { name: /téléverser/i });
|
||||||
|
fireEvent.click(uploadButton);
|
||||||
|
const successMessage = await screen.findByText(/téléversée avec succès/i);
|
||||||
|
expect(successMessage).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should close the image preview dialog when close button is clicked", async () => {
|
||||||
|
const imageCard = screen.getByAltText("Image image1.jpg");
|
||||||
|
fireEvent.click(imageCard);
|
||||||
|
|
||||||
|
const dialogImage = await screen.findByAltText("Enlarged view");
|
||||||
|
expect(dialogImage).toBeInTheDocument();
|
||||||
|
|
||||||
|
const closeButton = screen.getByTestId("close-button");
|
||||||
|
fireEvent.click(closeButton);
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(screen.queryByAltText("Enlarged view")).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should show an error message when no file is selected", async () => {
|
||||||
|
const importTab = screen.getByRole("tab", { name: /import/i });
|
||||||
|
fireEvent.click(importTab);
|
||||||
|
const uploadButton = screen.getByRole('button', { name: /téléverser/i });
|
||||||
|
fireEvent.click(uploadButton);
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(screen.getByText("Veuillez choisir une image à téléverser.")).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
});
|
||||||
|
|
@ -0,0 +1,44 @@
|
||||||
|
import React from "react";
|
||||||
|
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
|
||||||
|
import ImageGalleryModal from "../../../components/ImageGallery/ImageGalleryModal/ImageGalleryModal";
|
||||||
|
import "@testing-library/jest-dom";
|
||||||
|
|
||||||
|
jest.mock("../../../components/ImageGallery/ImageGallery", () => ({
|
||||||
|
__esModule: true,
|
||||||
|
default: jest.fn(() => <div data-testid="image-gallery" />),
|
||||||
|
}));
|
||||||
|
|
||||||
|
describe("ImageGalleryModal", () => {
|
||||||
|
|
||||||
|
it("renders button correctly", () => {
|
||||||
|
render(<ImageGalleryModal />);
|
||||||
|
|
||||||
|
const button = screen.getByLabelText(/images-open/i);
|
||||||
|
expect(button).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("opens the modal when button is clicked", () => {
|
||||||
|
render(<ImageGalleryModal />);
|
||||||
|
|
||||||
|
const button = screen.getByRole("button", { name: /images/i });
|
||||||
|
fireEvent.click(button);
|
||||||
|
|
||||||
|
const dialog = screen.getByRole("dialog");
|
||||||
|
expect(dialog).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
it("closes the modal when close button is clicked", async () => {
|
||||||
|
render(<ImageGalleryModal />);
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: /images/i }));
|
||||||
|
|
||||||
|
const closeButton = screen.getByRole("button", { name: /close/i });
|
||||||
|
fireEvent.click(closeButton);
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
});
|
||||||
|
|
@ -5,7 +5,7 @@ import LiveResults from 'src/components/LiveResults/LiveResults';
|
||||||
import { QuestionType } from 'src/Types/QuestionType';
|
import { QuestionType } from 'src/Types/QuestionType';
|
||||||
import { StudentType } from 'src/Types/StudentType';
|
import { StudentType } from 'src/Types/StudentType';
|
||||||
import { Socket } from 'socket.io-client';
|
import { Socket } from 'socket.io-client';
|
||||||
import { BaseQuestion,parse } from 'gift-pegjs';
|
import { BaseQuestion, parse } from 'gift-pegjs';
|
||||||
|
|
||||||
const mockSocket: Socket = {
|
const mockSocket: Socket = {
|
||||||
on: jest.fn(),
|
on: jest.fn(),
|
||||||
|
|
@ -19,19 +19,28 @@ const mockGiftQuestions = parse(
|
||||||
`::Sample Question 1:: Question stem
|
`::Sample Question 1:: Question stem
|
||||||
{
|
{
|
||||||
=Choice 1
|
=Choice 1
|
||||||
~Choice 2
|
=Choice 2
|
||||||
}`);
|
~Choice 3
|
||||||
|
~Choice 4
|
||||||
|
}
|
||||||
|
|
||||||
|
::Sample Question 2:: Question stem {TRUE}
|
||||||
|
`);
|
||||||
|
|
||||||
const mockQuestions: QuestionType[] = mockGiftQuestions.map((question, index) => {
|
const mockQuestions: QuestionType[] = mockGiftQuestions.map((question, index) => {
|
||||||
if (question.type !== "Category")
|
if (question.type !== "Category")
|
||||||
question.id = (index + 1).toString();
|
question.id = (index + 1).toString();
|
||||||
const newMockQuestion = question;
|
const newMockQuestion = question;
|
||||||
return {question : newMockQuestion as BaseQuestion};
|
return { question: newMockQuestion as BaseQuestion };
|
||||||
});
|
});
|
||||||
|
|
||||||
|
console.log(`mockQuestions: ${JSON.stringify(mockQuestions)}`);
|
||||||
|
|
||||||
|
// each student should have a different score for the tests to pass
|
||||||
const mockStudents: StudentType[] = [
|
const mockStudents: StudentType[] = [
|
||||||
{ id: '1', name: 'Student 1', answers: [{ idQuestion: 1, answer: 'Choice 1', isCorrect: true }] },
|
{ id: '1', name: 'Student 1', answers: [] },
|
||||||
{ id: '2', name: 'Student 2', answers: [{ idQuestion: 1, answer: 'Choice 2', isCorrect: false }] },
|
{ id: '2', name: 'Student 2', answers: [{ idQuestion: 1, answer: ['Choice 3'], isCorrect: false }, { idQuestion: 2, answer: [true], isCorrect: true}] },
|
||||||
|
{ id: '3', name: 'Student 3', answers: [{ idQuestion: 1, answer: ['Choice 1', 'Choice 2'], isCorrect: true }, { idQuestion: 2, answer: [true], isCorrect: true}] },
|
||||||
];
|
];
|
||||||
|
|
||||||
describe('LiveResults', () => {
|
describe('LiveResults', () => {
|
||||||
|
|
@ -52,7 +61,7 @@ describe('LiveResults', () => {
|
||||||
|
|
||||||
// Toggle the display of usernames back
|
// Toggle the display of usernames back
|
||||||
fireEvent.click(toggleUsernamesSwitch);
|
fireEvent.click(toggleUsernamesSwitch);
|
||||||
|
|
||||||
// Check if the component renders the students
|
// Check if the component renders the students
|
||||||
mockStudents.forEach((student) => {
|
mockStudents.forEach((student) => {
|
||||||
expect(screen.getByText(student.name)).toBeInTheDocument();
|
expect(screen.getByText(student.name)).toBeInTheDocument();
|
||||||
|
|
@ -82,82 +91,88 @@ describe('LiveResults', () => {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
});
|
test('calculates and displays the correct student grades', () => {
|
||||||
test('calculates and displays the correct student grades', () => {
|
render(
|
||||||
render(
|
<LiveResults
|
||||||
<LiveResults
|
socket={mockSocket}
|
||||||
socket={mockSocket}
|
questions={mockQuestions}
|
||||||
questions={mockQuestions}
|
showSelectedQuestion={jest.fn()}
|
||||||
showSelectedQuestion={jest.fn()}
|
quizMode="teacher"
|
||||||
quizMode="teacher"
|
students={mockStudents}
|
||||||
students={mockStudents}
|
/>
|
||||||
/>
|
);
|
||||||
);
|
|
||||||
|
|
||||||
|
|
||||||
// Toggle the display of usernames
|
// Toggle the display of usernames
|
||||||
const toggleUsernamesSwitch = screen.getByLabelText('Afficher les noms');
|
const toggleUsernamesSwitch = screen.getByLabelText('Afficher les noms');
|
||||||
|
|
||||||
// Toggle the display of usernames back
|
// Toggle the display of usernames back
|
||||||
fireEvent.click(toggleUsernamesSwitch);
|
fireEvent.click(toggleUsernamesSwitch);
|
||||||
|
|
||||||
// Check if the student grades are calculated and displayed correctly
|
// Check if the student grades are calculated and displayed correctly
|
||||||
mockStudents.forEach((student) => {
|
const getByTextInTableCellBody = (text: string) => {
|
||||||
const grade = student.answers.filter(answer => answer.isCorrect).length / mockQuestions.length * 100;
|
const elements = screen.getAllByText(text); // Get all elements with the specified text
|
||||||
expect(screen.getByText(`${grade.toFixed()} %`)).toBeInTheDocument();
|
return elements.find((element) => element.closest('.MuiTableCell-body')); // don't get the footer element(s)
|
||||||
|
};
|
||||||
|
mockStudents.forEach((student) => {
|
||||||
|
const grade = student.answers.filter(answer => answer.isCorrect).length / mockQuestions.length * 100;
|
||||||
|
const element = getByTextInTableCellBody(`${grade.toFixed()} %`);
|
||||||
|
expect(element).toBeInTheDocument();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
});
|
|
||||||
|
|
||||||
test('calculates and displays the class average', () => {
|
test('calculates and displays the class average', () => {
|
||||||
render(
|
render(
|
||||||
<LiveResults
|
<LiveResults
|
||||||
socket={mockSocket}
|
socket={mockSocket}
|
||||||
questions={mockQuestions}
|
questions={mockQuestions}
|
||||||
showSelectedQuestion={jest.fn()}
|
showSelectedQuestion={jest.fn()}
|
||||||
quizMode="teacher"
|
quizMode="teacher"
|
||||||
students={mockStudents}
|
students={mockStudents}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
|
|
||||||
// Toggle the display of usernames
|
// Toggle the display of usernames
|
||||||
const toggleUsernamesSwitch = screen.getByLabelText('Afficher les noms');
|
const toggleUsernamesSwitch = screen.getByLabelText('Afficher les noms');
|
||||||
|
|
||||||
// Toggle the display of usernames back
|
// Toggle the display of usernames back
|
||||||
fireEvent.click(toggleUsernamesSwitch);
|
fireEvent.click(toggleUsernamesSwitch);
|
||||||
|
|
||||||
// Calculate the class average
|
|
||||||
const totalGrades = mockStudents.reduce((total, student) => {
|
|
||||||
return total + (student.answers.filter(answer => answer.isCorrect).length / mockQuestions.length * 100);
|
|
||||||
}, 0);
|
|
||||||
const classAverage = totalGrades / mockStudents.length;
|
|
||||||
|
|
||||||
// Check if the class average is displayed correctly
|
// Calculate the class average
|
||||||
const classAverageElements = screen.getAllByText(`${classAverage.toFixed()} %`);
|
const totalGrades = mockStudents.reduce((total, student) => {
|
||||||
const classAverageElement = classAverageElements.find((element) => {
|
return total + (student.answers.filter(answer => answer.isCorrect).length / mockQuestions.length * 100);
|
||||||
return element.closest('td')?.classList.contains('MuiTableCell-footer');
|
}, 0);
|
||||||
});
|
const classAverage = totalGrades / mockStudents.length;
|
||||||
expect(classAverageElement).toBeInTheDocument();
|
|
||||||
});
|
|
||||||
|
|
||||||
test('displays the correct answers per question', () => {
|
// Check if the class average is displayed correctly
|
||||||
render(
|
const classAverageElements = screen.getAllByText(`${classAverage.toFixed()} %`);
|
||||||
<LiveResults
|
const classAverageElement = classAverageElements.find((element) => {
|
||||||
socket={mockSocket}
|
return element.closest('td')?.classList.contains('MuiTableCell-footer');
|
||||||
questions={mockQuestions}
|
|
||||||
showSelectedQuestion={jest.fn()}
|
|
||||||
quizMode="teacher"
|
|
||||||
students={mockStudents}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
|
|
||||||
// Check if the correct answers per question are displayed correctly
|
|
||||||
mockQuestions.forEach((_, index) => {
|
|
||||||
const correctAnswers = mockStudents.filter(student => student.answers.some(answer => answer.idQuestion === index + 1 && answer.isCorrect)).length;
|
|
||||||
const correctAnswersPercentage = (correctAnswers / mockStudents.length) * 100;
|
|
||||||
const correctAnswersElements = screen.getAllByText(`${correctAnswersPercentage.toFixed()} %`);
|
|
||||||
const correctAnswersElement = correctAnswersElements.find((element) => {
|
|
||||||
return element.closest('td')?.classList.contains('MuiTableCell-root');
|
|
||||||
});
|
});
|
||||||
expect(correctAnswersElement).toBeInTheDocument();
|
expect(classAverageElement).toBeInTheDocument();
|
||||||
});
|
});
|
||||||
});
|
|
||||||
|
test('displays the correct answers per question', () => {
|
||||||
|
render(
|
||||||
|
<LiveResults
|
||||||
|
socket={mockSocket}
|
||||||
|
questions={mockQuestions}
|
||||||
|
showSelectedQuestion={jest.fn()}
|
||||||
|
quizMode="teacher"
|
||||||
|
students={mockStudents}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
|
||||||
|
// Check if the correct answers per question are displayed correctly
|
||||||
|
mockQuestions.forEach((_, index) => {
|
||||||
|
const correctAnswers = mockStudents.filter(student => student.answers.some(answer => answer.idQuestion === index + 1 && answer.isCorrect)).length;
|
||||||
|
const correctAnswersPercentage = (correctAnswers / mockStudents.length) * 100;
|
||||||
|
const correctAnswersElements = screen.getAllByText(`${correctAnswersPercentage.toFixed()} %`);
|
||||||
|
const correctAnswersElement = correctAnswersElements.find((element) => {
|
||||||
|
return element.closest('td')?.classList.contains('MuiTableCell-root');
|
||||||
|
});
|
||||||
|
expect(correctAnswersElement).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
});
|
||||||
|
|
|
||||||
|
|
@ -12,14 +12,23 @@ const questions = parse(
|
||||||
{
|
{
|
||||||
=Choice 1
|
=Choice 1
|
||||||
~Choice 2
|
~Choice 2
|
||||||
}`) as MultipleChoiceQuestion[];
|
}
|
||||||
|
|
||||||
|
::Sample Question 2:: Question stem
|
||||||
|
{
|
||||||
|
=Choice 1
|
||||||
|
=Choice 2
|
||||||
|
~Choice 3
|
||||||
|
}
|
||||||
|
`) as MultipleChoiceQuestion[];
|
||||||
|
|
||||||
const question = questions[0];
|
const questionWithOneCorrectChoice = questions[0];
|
||||||
|
const questionWithMultipleCorrectChoices = questions[1];
|
||||||
|
|
||||||
describe('MultipleChoiceQuestionDisplay', () => {
|
describe('MultipleChoiceQuestionDisplay', () => {
|
||||||
const mockHandleOnSubmitAnswer = jest.fn();
|
const mockHandleOnSubmitAnswer = jest.fn();
|
||||||
|
|
||||||
const TestWrapper = ({ showAnswer }: { showAnswer: boolean }) => {
|
const TestWrapper = ({ showAnswer, question }: { showAnswer: boolean; question: MultipleChoiceQuestion }) => {
|
||||||
const [showAnswerState, setShowAnswerState] = useState(showAnswer);
|
const [showAnswerState, setShowAnswerState] = useState(showAnswer);
|
||||||
|
|
||||||
const handleOnSubmitAnswer = (answer: AnswerType) => {
|
const handleOnSubmitAnswer = (answer: AnswerType) => {
|
||||||
|
|
@ -38,28 +47,51 @@ describe('MultipleChoiceQuestionDisplay', () => {
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
const choices = question.choices;
|
const twoChoices = questionWithOneCorrectChoice.choices;
|
||||||
|
const threeChoices = questionWithMultipleCorrectChoices.choices;
|
||||||
|
|
||||||
beforeEach(() => {
|
test('renders a question (that has only one correct choice) and its choices', () => {
|
||||||
render(<TestWrapper showAnswer={false} />);
|
render(<TestWrapper showAnswer={false} question={questionWithOneCorrectChoice} />);
|
||||||
});
|
|
||||||
|
|
||||||
test('renders the question and choices', () => {
|
expect(screen.getByText(questionWithOneCorrectChoice.formattedStem.text)).toBeInTheDocument();
|
||||||
expect(screen.getByText(question.formattedStem.text)).toBeInTheDocument();
|
twoChoices.forEach((choice) => {
|
||||||
choices.forEach((choice) => {
|
|
||||||
expect(screen.getByText(choice.formattedText.text)).toBeInTheDocument();
|
expect(screen.getByText(choice.formattedText.text)).toBeInTheDocument();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('only allows one choice to be selected when question only has one correct answer', () => {
|
||||||
|
render(<TestWrapper showAnswer={false} question={questionWithOneCorrectChoice} />);
|
||||||
|
|
||||||
|
const choiceButton1 = screen.getByText('Choice 1').closest('button');
|
||||||
|
const choiceButton2 = screen.getByText('Choice 2').closest('button');
|
||||||
|
|
||||||
|
if (!choiceButton1 || !choiceButton2) throw new Error('Choice buttons not found');
|
||||||
|
|
||||||
|
// Simulate selecting multiple answers
|
||||||
|
act(() => {
|
||||||
|
fireEvent.click(choiceButton1);
|
||||||
|
});
|
||||||
|
act(() => {
|
||||||
|
fireEvent.click(choiceButton2);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Verify that only the last answer is selected
|
||||||
|
expect(choiceButton1.querySelector('.answer-text.selected')).not.toBeInTheDocument();
|
||||||
|
expect(choiceButton2.querySelector('.answer-text.selected')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
test('does not submit when no answer is selected', () => {
|
test('does not submit when no answer is selected', () => {
|
||||||
|
render(<TestWrapper showAnswer={false} question={questionWithOneCorrectChoice} />);
|
||||||
const submitButton = screen.getByText('Répondre');
|
const submitButton = screen.getByText('Répondre');
|
||||||
act(() => {
|
act(() => {
|
||||||
fireEvent.click(submitButton);
|
fireEvent.click(submitButton);
|
||||||
});
|
});
|
||||||
expect(mockHandleOnSubmitAnswer).not.toHaveBeenCalled();
|
expect(mockHandleOnSubmitAnswer).not.toHaveBeenCalled();
|
||||||
|
mockHandleOnSubmitAnswer.mockClear();
|
||||||
});
|
});
|
||||||
|
|
||||||
test('submits the selected answer', () => {
|
test('submits the selected answer', () => {
|
||||||
|
render(<TestWrapper showAnswer={false} question={questionWithOneCorrectChoice} />);
|
||||||
const choiceButton = screen.getByText('Choice 1').closest('button');
|
const choiceButton = screen.getByText('Choice 1').closest('button');
|
||||||
if (!choiceButton) throw new Error('Choice button not found');
|
if (!choiceButton) throw new Error('Choice button not found');
|
||||||
act(() => {
|
act(() => {
|
||||||
|
|
@ -70,10 +102,68 @@ describe('MultipleChoiceQuestionDisplay', () => {
|
||||||
fireEvent.click(submitButton);
|
fireEvent.click(submitButton);
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(mockHandleOnSubmitAnswer).toHaveBeenCalledWith('Choice 1');
|
expect(mockHandleOnSubmitAnswer).toHaveBeenCalledWith(['Choice 1']);
|
||||||
|
mockHandleOnSubmitAnswer.mockClear();
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
test('renders a question (that has multiple correct choices) and its choices', () => {
|
||||||
|
render(<TestWrapper showAnswer={false} question={questionWithMultipleCorrectChoices} />);
|
||||||
|
expect(screen.getByText(questionWithMultipleCorrectChoices.formattedStem.text)).toBeInTheDocument();
|
||||||
|
threeChoices.forEach((choice) => {
|
||||||
|
expect(screen.getByText(choice.formattedText.text)).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('allows multiple choices to be selected when question has multiple correct answers', () => {
|
||||||
|
render(<TestWrapper showAnswer={false} question={questionWithMultipleCorrectChoices} />);
|
||||||
|
const choiceButton1 = screen.getByText('Choice 1').closest('button');
|
||||||
|
const choiceButton2 = screen.getByText('Choice 2').closest('button');
|
||||||
|
const choiceButton3 = screen.getByText('Choice 3').closest('button');
|
||||||
|
|
||||||
|
if (!choiceButton1 || !choiceButton2 || !choiceButton3) throw new Error('Choice buttons not found');
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
fireEvent.click(choiceButton1);
|
||||||
|
});
|
||||||
|
act(() => {
|
||||||
|
fireEvent.click(choiceButton2);
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(choiceButton1.querySelector('.answer-text.selected')).toBeInTheDocument();
|
||||||
|
expect(choiceButton2.querySelector('.answer-text.selected')).toBeInTheDocument();
|
||||||
|
expect(choiceButton3.querySelector('.answer-text.selected')).not.toBeInTheDocument(); // didn't click
|
||||||
|
|
||||||
|
});
|
||||||
|
|
||||||
|
test('submits multiple selected answers', () => {
|
||||||
|
render(<TestWrapper showAnswer={false} question={questionWithMultipleCorrectChoices} />);
|
||||||
|
const choiceButton1 = screen.getByText('Choice 1').closest('button');
|
||||||
|
const choiceButton2 = screen.getByText('Choice 2').closest('button');
|
||||||
|
|
||||||
|
if (!choiceButton1 || !choiceButton2) throw new Error('Choice buttons not found');
|
||||||
|
|
||||||
|
// Simulate selecting multiple answers
|
||||||
|
act(() => {
|
||||||
|
fireEvent.click(choiceButton1);
|
||||||
|
});
|
||||||
|
act(() => {
|
||||||
|
fireEvent.click(choiceButton2);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Simulate submitting the answers
|
||||||
|
const submitButton = screen.getByText('Répondre');
|
||||||
|
act(() => {
|
||||||
|
fireEvent.click(submitButton);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Verify that the mockHandleOnSubmitAnswer function is called with both answers
|
||||||
|
expect(mockHandleOnSubmitAnswer).toHaveBeenCalledWith(['Choice 1', 'Choice 2']);
|
||||||
|
mockHandleOnSubmitAnswer.mockClear();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should show ✅ next to the correct answer and ❌ next to the wrong answers when showAnswer is true', async () => {
|
it('should show ✅ next to the correct answer and ❌ next to the wrong answers when showAnswer is true', async () => {
|
||||||
|
render(<TestWrapper showAnswer={false} question={questionWithOneCorrectChoice} />);
|
||||||
const choiceButton = screen.getByText('Choice 1').closest('button');
|
const choiceButton = screen.getByText('Choice 1').closest('button');
|
||||||
if (!choiceButton) throw new Error('Choice button not found');
|
if (!choiceButton) throw new Error('Choice button not found');
|
||||||
|
|
||||||
|
|
@ -89,16 +179,17 @@ describe('MultipleChoiceQuestionDisplay', () => {
|
||||||
});
|
});
|
||||||
|
|
||||||
// Wait for the DOM to update
|
// Wait for the DOM to update
|
||||||
const correctAnswer = screen.getByText("Choice 1").closest('button');
|
const correctAnswer = screen.getByText("Choice 1").closest('button');
|
||||||
expect(correctAnswer).toBeInTheDocument();
|
expect(correctAnswer).toBeInTheDocument();
|
||||||
expect(correctAnswer?.textContent).toContain('✅');
|
expect(correctAnswer?.textContent).toContain('✅');
|
||||||
|
|
||||||
const wrongAnswer1 = screen.getByText("Choice 2").closest('button');
|
const wrongAnswer1 = screen.getByText("Choice 2").closest('button');
|
||||||
expect(wrongAnswer1).toBeInTheDocument();
|
expect(wrongAnswer1).toBeInTheDocument();
|
||||||
expect(wrongAnswer1?.textContent).toContain('❌');
|
expect(wrongAnswer1?.textContent).toContain('❌');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should not show ✅ or ❌ when repondre button is not clicked', async () => {
|
it('should not show ✅ or ❌ when Répondre button is not clicked', async () => {
|
||||||
|
render(<TestWrapper showAnswer={false} question={questionWithOneCorrectChoice} />);
|
||||||
const choiceButton = screen.getByText('Choice 1').closest('button');
|
const choiceButton = screen.getByText('Choice 1').closest('button');
|
||||||
if (!choiceButton) throw new Error('Choice button not found');
|
if (!choiceButton) throw new Error('Choice button not found');
|
||||||
|
|
||||||
|
|
@ -118,5 +209,5 @@ describe('MultipleChoiceQuestionDisplay', () => {
|
||||||
expect(wrongAnswer1?.textContent).not.toContain('❌');
|
expect(wrongAnswer1?.textContent).not.toContain('❌');
|
||||||
});
|
});
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -67,6 +67,7 @@ describe('NumericalQuestion Component', () => {
|
||||||
fireEvent.click(submitButton);
|
fireEvent.click(submitButton);
|
||||||
|
|
||||||
expect(mockHandleOnSubmitAnswer).not.toHaveBeenCalled();
|
expect(mockHandleOnSubmitAnswer).not.toHaveBeenCalled();
|
||||||
|
mockHandleOnSubmitAnswer.mockClear();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('submits answer correctly', () => {
|
it('submits answer correctly', () => {
|
||||||
|
|
@ -77,6 +78,7 @@ describe('NumericalQuestion Component', () => {
|
||||||
|
|
||||||
fireEvent.click(submitButton);
|
fireEvent.click(submitButton);
|
||||||
|
|
||||||
expect(mockHandleOnSubmitAnswer).toHaveBeenCalledWith(7);
|
expect(mockHandleOnSubmitAnswer).toHaveBeenCalledWith([7]);
|
||||||
|
mockHandleOnSubmitAnswer.mockClear();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -29,23 +29,24 @@ describe('Questions Component', () => {
|
||||||
render(<QuestionDisplay question={question} {...sampleProps} />);
|
render(<QuestionDisplay question={question} {...sampleProps} />);
|
||||||
};
|
};
|
||||||
|
|
||||||
describe('question type parsing', () => {
|
// describe('question type parsing', () => {
|
||||||
it('parses true/false question type correctly', () => {
|
// it('parses true/false question type correctly', () => {
|
||||||
expect(sampleTrueFalseQuestion.type).toBe('TF');
|
// expect(sampleTrueFalseQuestion.type).toBe('TF');
|
||||||
});
|
// });
|
||||||
|
|
||||||
it('parses multiple choice question type correctly', () => {
|
// it('parses multiple choice question type correctly', () => {
|
||||||
expect(sampleMultipleChoiceQuestion.type).toBe('MC');
|
// expect(sampleMultipleChoiceQuestion.type).toBe('MC');
|
||||||
});
|
// });
|
||||||
|
|
||||||
it('parses numerical question type correctly', () => {
|
// it('parses numerical question type correctly', () => {
|
||||||
expect(sampleNumericalQuestion.type).toBe('Numerical');
|
// expect(sampleNumericalQuestion.type).toBe('Numerical');
|
||||||
});
|
// });
|
||||||
|
|
||||||
|
// it('parses short answer question type correctly', () => {
|
||||||
|
// expect(sampleShortAnswerQuestion.type).toBe('Short');
|
||||||
|
// });
|
||||||
|
// });
|
||||||
|
|
||||||
it('parses short answer question type correctly', () => {
|
|
||||||
expect(sampleShortAnswerQuestion.type).toBe('Short');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
it('renders correctly for True/False question', () => {
|
it('renders correctly for True/False question', () => {
|
||||||
renderComponent(sampleTrueFalseQuestion);
|
renderComponent(sampleTrueFalseQuestion);
|
||||||
|
|
||||||
|
|
@ -73,7 +74,8 @@ describe('Questions Component', () => {
|
||||||
const submitButton = screen.getByText('Répondre');
|
const submitButton = screen.getByText('Répondre');
|
||||||
fireEvent.click(submitButton);
|
fireEvent.click(submitButton);
|
||||||
|
|
||||||
expect(mockHandleSubmitAnswer).toHaveBeenCalledWith('Choice 1');
|
expect(mockHandleSubmitAnswer).toHaveBeenCalledWith(['Choice 1']);
|
||||||
|
mockHandleSubmitAnswer.mockClear();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('renders correctly for Numerical question', () => {
|
it('renders correctly for Numerical question', () => {
|
||||||
|
|
@ -93,7 +95,8 @@ describe('Questions Component', () => {
|
||||||
const submitButton = screen.getByText('Répondre');
|
const submitButton = screen.getByText('Répondre');
|
||||||
fireEvent.click(submitButton);
|
fireEvent.click(submitButton);
|
||||||
|
|
||||||
expect(mockHandleSubmitAnswer).toHaveBeenCalledWith(7);
|
expect(mockHandleSubmitAnswer).toHaveBeenCalledWith([7]);
|
||||||
|
mockHandleSubmitAnswer.mockClear();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('renders correctly for Short Answer question', () => {
|
it('renders correctly for Short Answer question', () => {
|
||||||
|
|
@ -117,7 +120,7 @@ describe('Questions Component', () => {
|
||||||
const submitButton = screen.getByText('Répondre');
|
const submitButton = screen.getByText('Répondre');
|
||||||
fireEvent.click(submitButton);
|
fireEvent.click(submitButton);
|
||||||
|
|
||||||
expect(mockHandleSubmitAnswer).toHaveBeenCalledWith('User Input');
|
expect(mockHandleSubmitAnswer).toHaveBeenCalledWith(['User Input']);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -47,6 +47,7 @@ describe('ShortAnswerQuestion Component', () => {
|
||||||
fireEvent.click(submitButton);
|
fireEvent.click(submitButton);
|
||||||
|
|
||||||
expect(mockHandleSubmitAnswer).not.toHaveBeenCalled();
|
expect(mockHandleSubmitAnswer).not.toHaveBeenCalled();
|
||||||
|
mockHandleSubmitAnswer.mockClear();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('submits answer correctly', () => {
|
it('submits answer correctly', () => {
|
||||||
|
|
@ -60,6 +61,7 @@ describe('ShortAnswerQuestion Component', () => {
|
||||||
|
|
||||||
fireEvent.click(submitButton);
|
fireEvent.click(submitButton);
|
||||||
|
|
||||||
expect(mockHandleSubmitAnswer).toHaveBeenCalledWith('User Input');
|
expect(mockHandleSubmitAnswer).toHaveBeenCalledWith(['User Input']);
|
||||||
|
mockHandleSubmitAnswer.mockClear();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -56,6 +56,7 @@ describe('TrueFalseQuestion Component', () => {
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(mockHandleSubmitAnswer).not.toHaveBeenCalled();
|
expect(mockHandleSubmitAnswer).not.toHaveBeenCalled();
|
||||||
|
mockHandleSubmitAnswer.mockClear();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('submits answer correctly for True', () => {
|
it('submits answer correctly for True', () => {
|
||||||
|
|
@ -70,7 +71,8 @@ describe('TrueFalseQuestion Component', () => {
|
||||||
fireEvent.click(submitButton);
|
fireEvent.click(submitButton);
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(mockHandleSubmitAnswer).toHaveBeenCalledWith(true);
|
expect(mockHandleSubmitAnswer).toHaveBeenCalledWith([true]);
|
||||||
|
mockHandleSubmitAnswer.mockClear();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('submits answer correctly for False', () => {
|
it('submits answer correctly for False', () => {
|
||||||
|
|
@ -83,7 +85,8 @@ describe('TrueFalseQuestion Component', () => {
|
||||||
fireEvent.click(submitButton);
|
fireEvent.click(submitButton);
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(mockHandleSubmitAnswer).toHaveBeenCalledWith(false);
|
expect(mockHandleSubmitAnswer).toHaveBeenCalledWith([false]);
|
||||||
|
mockHandleSubmitAnswer.mockClear();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -112,7 +115,7 @@ describe('TrueFalseQuestion Component', () => {
|
||||||
expect(wrongAnswer1?.textContent).toContain('❌');
|
expect(wrongAnswer1?.textContent).toContain('❌');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should not show ✅ or ❌ when repondre button is not clicked', async () => {
|
it('should not show ✅ or ❌ when Répondre button is not clicked', async () => {
|
||||||
const choiceButton = screen.getByText('Vrai').closest('button');
|
const choiceButton = screen.getByText('Vrai').closest('button');
|
||||||
if (!choiceButton) throw new Error('Choice button not found');
|
if (!choiceButton) throw new Error('Choice button not found');
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,81 @@
|
||||||
|
import React from 'react';
|
||||||
|
import { render, screen, fireEvent, act } from '@testing-library/react';
|
||||||
|
import ShareQuizModal from '../../../components/ShareQuizModal/ShareQuizModal.tsx';
|
||||||
|
import { QuizType } from '../../../Types/QuizType';
|
||||||
|
import '@testing-library/jest-dom';
|
||||||
|
|
||||||
|
describe('ShareQuizModal', () => {
|
||||||
|
const mockQuiz: QuizType = {
|
||||||
|
_id: '123',
|
||||||
|
folderId: 'folder-123',
|
||||||
|
folderName: 'Test Folder',
|
||||||
|
userId: 'user-123',
|
||||||
|
title: 'Test Quiz',
|
||||||
|
content: ['Question 1', 'Question 2'],
|
||||||
|
created_at: new Date(),
|
||||||
|
updated_at: new Date(),
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeAll(() => {
|
||||||
|
// Properly mock the clipboard API
|
||||||
|
Object.defineProperty(navigator, 'clipboard', {
|
||||||
|
value: {
|
||||||
|
writeText: jest.fn().mockImplementation(() => Promise.resolve()),
|
||||||
|
},
|
||||||
|
writable: true,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
jest.clearAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('renders the share button', () => {
|
||||||
|
render(<ShareQuizModal quiz={mockQuiz} />);
|
||||||
|
expect(screen.getByLabelText('partager quiz')).toBeInTheDocument();
|
||||||
|
expect(screen.getByTestId('ShareIcon')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('copies the quiz URL to clipboard when share button is clicked', async () => {
|
||||||
|
render(<ShareQuizModal quiz={mockQuiz} />);
|
||||||
|
const shareButton = screen.getByLabelText('partager quiz');
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
fireEvent.click(shareButton);
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(navigator.clipboard.writeText).toHaveBeenCalledWith(
|
||||||
|
`${window.location.origin}/teacher/share/${mockQuiz._id}`
|
||||||
|
);
|
||||||
|
|
||||||
|
// Check for feedback dialog content
|
||||||
|
expect(screen.getByText(/L'URL de partage pour le quiz/i)).toBeInTheDocument();
|
||||||
|
expect(screen.getByText(mockQuiz.title)).toBeInTheDocument();
|
||||||
|
expect(screen.getByText(/a été copiée\./i)).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows error message when clipboard write fails', async () => {
|
||||||
|
// Override the mock to reject
|
||||||
|
(navigator.clipboard.writeText as jest.Mock).mockRejectedValueOnce(new Error('Clipboard write failed'));
|
||||||
|
|
||||||
|
render(<ShareQuizModal quiz={mockQuiz} />);
|
||||||
|
const shareButton = screen.getByLabelText('partager quiz');
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
fireEvent.click(shareButton);
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(screen.getByText(/Une erreur est survenue lors de la copie de l'URL\./i)).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('displays the quiz title in the success message', async () => {
|
||||||
|
render(<ShareQuizModal quiz={mockQuiz} />);
|
||||||
|
const shareButton = screen.getByLabelText('partager quiz');
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
fireEvent.click(shareButton);
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(screen.getByText(mockQuiz.title)).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
359
client/src/__tests__/pages/ManageRoom/IsCorrect.test.tsx
Normal file
359
client/src/__tests__/pages/ManageRoom/IsCorrect.test.tsx
Normal file
|
|
@ -0,0 +1,359 @@
|
||||||
|
import { checkIfIsCorrect } from 'src/pages/Teacher/ManageRoom/useRooms';
|
||||||
|
import { HighLowNumericalAnswer, MultipleChoiceQuestion, MultipleNumericalAnswer, NumericalQuestion, RangeNumericalAnswer, ShortAnswerQuestion, SimpleNumericalAnswer, TrueFalseQuestion } from 'gift-pegjs';
|
||||||
|
import { AnswerType } from 'src/pages/Student/JoinRoom/JoinRoom';
|
||||||
|
import { QuestionType } from 'src/Types/QuestionType';
|
||||||
|
|
||||||
|
describe('checkIfIsCorrect', () => {
|
||||||
|
const mockQuestions: QuestionType[] = [
|
||||||
|
{
|
||||||
|
question: {
|
||||||
|
id: '1',
|
||||||
|
type: 'MC',
|
||||||
|
choices: [
|
||||||
|
{ isCorrect: true, formattedText: { text: 'Answer1' } },
|
||||||
|
{ isCorrect: true, formattedText: { text: 'Answer2' } },
|
||||||
|
{ isCorrect: false, formattedText: { text: 'Answer3' } },
|
||||||
|
],
|
||||||
|
} as MultipleChoiceQuestion,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
test('returns true when all selected answers are correct', () => {
|
||||||
|
const answer: AnswerType = ['Answer1', 'Answer2'];
|
||||||
|
const result = checkIfIsCorrect(answer, 1, mockQuestions);
|
||||||
|
expect(result).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('returns false when some selected answers are incorrect', () => {
|
||||||
|
const answer: AnswerType = ['Answer1', 'Answer3'];
|
||||||
|
const result = checkIfIsCorrect(answer, 1, mockQuestions);
|
||||||
|
expect(result).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('returns false when all correct answers are selected, but one incorrect is also selected', () => {
|
||||||
|
const answer: AnswerType = ['Answer1', 'Answer2', 'Answer3'];
|
||||||
|
const result = checkIfIsCorrect(answer, 1, mockQuestions);
|
||||||
|
expect(result).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('returns false when no answers are selected', () => {
|
||||||
|
const answer: AnswerType = [];
|
||||||
|
const result = checkIfIsCorrect(answer, 1, mockQuestions);
|
||||||
|
expect(result).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('returns false when no correct answers are provided in the question', () => {
|
||||||
|
const mockQuestionsWithNoCorrectAnswers: QuestionType[] = [
|
||||||
|
{
|
||||||
|
question: {
|
||||||
|
id: '1',
|
||||||
|
type: 'MC',
|
||||||
|
choices: [
|
||||||
|
{ isCorrect: false, formattedText: { text: 'Answer1' } },
|
||||||
|
{ isCorrect: false, formattedText: { text: 'Answer2' } },
|
||||||
|
],
|
||||||
|
} as MultipleChoiceQuestion,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
const answer: AnswerType = ['Answer1'];
|
||||||
|
const result = checkIfIsCorrect(answer, 1, mockQuestionsWithNoCorrectAnswers);
|
||||||
|
expect(result).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('returns true for a correct true/false answer', () => {
|
||||||
|
const mockQuestionsTF: QuestionType[] = [
|
||||||
|
{
|
||||||
|
question: {
|
||||||
|
id: '2',
|
||||||
|
type: 'TF',
|
||||||
|
isTrue: true,
|
||||||
|
} as TrueFalseQuestion,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
const answer: AnswerType = [true];
|
||||||
|
const result = checkIfIsCorrect(answer, 2, mockQuestionsTF);
|
||||||
|
expect(result).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('returns false for an incorrect true/false answer', () => {
|
||||||
|
const mockQuestionsTF: QuestionType[] = [
|
||||||
|
{
|
||||||
|
question: {
|
||||||
|
id: '2',
|
||||||
|
type: 'TF',
|
||||||
|
isTrue: true,
|
||||||
|
} as TrueFalseQuestion,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
const answer: AnswerType = [false];
|
||||||
|
const result = checkIfIsCorrect(answer, 2, mockQuestionsTF);
|
||||||
|
expect(result).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('returns false for a true/false question with no answer', () => {
|
||||||
|
const mockQuestionsTF: QuestionType[] = [
|
||||||
|
{
|
||||||
|
question: {
|
||||||
|
id: '2',
|
||||||
|
type: 'TF',
|
||||||
|
isTrue: true,
|
||||||
|
} as TrueFalseQuestion,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
const answer: AnswerType = [];
|
||||||
|
const result = checkIfIsCorrect(answer, 2, mockQuestionsTF);
|
||||||
|
expect(result).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('returns true for a correct true/false answer when isTrue is false', () => {
|
||||||
|
const mockQuestionsTF: QuestionType[] = [
|
||||||
|
{
|
||||||
|
question: {
|
||||||
|
id: '3',
|
||||||
|
type: 'TF',
|
||||||
|
isTrue: false, // Correct answer is false
|
||||||
|
} as TrueFalseQuestion,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
const answer: AnswerType = [false];
|
||||||
|
const result = checkIfIsCorrect(answer, 3, mockQuestionsTF);
|
||||||
|
expect(result).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('returns false for an incorrect true/false answer when isTrue is false', () => {
|
||||||
|
const mockQuestionsTF: QuestionType[] = [
|
||||||
|
{
|
||||||
|
question: {
|
||||||
|
id: '3',
|
||||||
|
type: 'TF',
|
||||||
|
isTrue: false, // Correct answer is false
|
||||||
|
} as TrueFalseQuestion,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
const answer: AnswerType = [true];
|
||||||
|
const result = checkIfIsCorrect(answer, 3, mockQuestionsTF);
|
||||||
|
expect(result).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('returns true for a correct short answer', () => {
|
||||||
|
const mockQuestionsShort: QuestionType[] = [
|
||||||
|
{
|
||||||
|
question: {
|
||||||
|
id: '4',
|
||||||
|
type: 'Short',
|
||||||
|
choices: [
|
||||||
|
{ text: 'CorrectAnswer1' },
|
||||||
|
{ text: 'CorrectAnswer2' },
|
||||||
|
],
|
||||||
|
} as ShortAnswerQuestion,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
const answer: AnswerType = ['CorrectAnswer1'];
|
||||||
|
const result = checkIfIsCorrect(answer, 4, mockQuestionsShort);
|
||||||
|
expect(result).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('returns false for an incorrect short answer', () => {
|
||||||
|
const mockQuestionsShort: QuestionType[] = [
|
||||||
|
{
|
||||||
|
question: {
|
||||||
|
id: '4',
|
||||||
|
type: 'Short',
|
||||||
|
choices: [
|
||||||
|
{ text: 'CorrectAnswer1' },
|
||||||
|
{ text: 'CorrectAnswer2' },
|
||||||
|
],
|
||||||
|
} as ShortAnswerQuestion,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
const answer: AnswerType = ['WrongAnswer'];
|
||||||
|
const result = checkIfIsCorrect(answer, 4, mockQuestionsShort);
|
||||||
|
expect(result).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('returns true for a correct short answer with case insensitivity', () => {
|
||||||
|
const mockQuestionsShort: QuestionType[] = [
|
||||||
|
{
|
||||||
|
question: {
|
||||||
|
id: '4',
|
||||||
|
type: 'Short',
|
||||||
|
choices: [
|
||||||
|
{ text: 'CorrectAnswer1' },
|
||||||
|
{ text: 'CorrectAnswer2' },
|
||||||
|
],
|
||||||
|
} as ShortAnswerQuestion,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
const answer: AnswerType = ['correctanswer1']; // Lowercase version of the correct answer
|
||||||
|
const result = checkIfIsCorrect(answer, 4, mockQuestionsShort);
|
||||||
|
expect(result).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('returns false for a short answer question with no answer', () => {
|
||||||
|
const mockQuestionsShort: QuestionType[] = [
|
||||||
|
{
|
||||||
|
question: {
|
||||||
|
id: '4',
|
||||||
|
type: 'Short',
|
||||||
|
choices: [
|
||||||
|
{ text: 'CorrectAnswer1' },
|
||||||
|
{ text: 'CorrectAnswer2' },
|
||||||
|
],
|
||||||
|
} as ShortAnswerQuestion,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
const answer: AnswerType = [];
|
||||||
|
const result = checkIfIsCorrect(answer, 4, mockQuestionsShort);
|
||||||
|
expect(result).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
test('returns true for a correct simple numerical answer', () => {
|
||||||
|
const mockQuestionsNumerical: QuestionType[] = [
|
||||||
|
{
|
||||||
|
question: {
|
||||||
|
id: '5',
|
||||||
|
type: 'Numerical',
|
||||||
|
choices: [
|
||||||
|
{ type: 'simple', number: 42 } as SimpleNumericalAnswer,
|
||||||
|
],
|
||||||
|
} as NumericalQuestion,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
const answer: AnswerType = [42]; // User's answer
|
||||||
|
const result = checkIfIsCorrect(answer, 5, mockQuestionsNumerical);
|
||||||
|
expect(result).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('returns false for an incorrect simple numerical answer', () => {
|
||||||
|
const mockQuestionsNumerical: QuestionType[] = [
|
||||||
|
{
|
||||||
|
question: {
|
||||||
|
id: '5',
|
||||||
|
type: 'Numerical',
|
||||||
|
choices: [
|
||||||
|
{ type: 'simple', number: 42 } as SimpleNumericalAnswer,
|
||||||
|
],
|
||||||
|
} as NumericalQuestion,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
const answer: AnswerType = [43]; // User's answer
|
||||||
|
const result = checkIfIsCorrect(answer, 5, mockQuestionsNumerical);
|
||||||
|
expect(result).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('returns true for a correct range numerical answer', () => {
|
||||||
|
const mockQuestionsNumerical: QuestionType[] = [
|
||||||
|
{
|
||||||
|
question: {
|
||||||
|
id: '6',
|
||||||
|
type: 'Numerical',
|
||||||
|
choices: [
|
||||||
|
{ type: 'range', number: 50, range: 5 } as RangeNumericalAnswer,
|
||||||
|
],
|
||||||
|
} as NumericalQuestion,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
const answer: AnswerType = [52]; // User's answer within the range (50 ± 5)
|
||||||
|
const result = checkIfIsCorrect(answer, 6, mockQuestionsNumerical);
|
||||||
|
expect(result).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('returns false for an out-of-range numerical answer', () => {
|
||||||
|
const mockQuestionsNumerical: QuestionType[] = [
|
||||||
|
{
|
||||||
|
question: {
|
||||||
|
id: '6',
|
||||||
|
type: 'Numerical',
|
||||||
|
choices: [
|
||||||
|
{ type: 'range', number: 50, range: 5 } as RangeNumericalAnswer,
|
||||||
|
],
|
||||||
|
} as NumericalQuestion,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
const answer: AnswerType = [56]; // User's answer outside the range (50 ± 5)
|
||||||
|
const result = checkIfIsCorrect(answer, 6, mockQuestionsNumerical);
|
||||||
|
expect(result).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('returns true for a correct high-low numerical answer', () => {
|
||||||
|
const mockQuestionsNumerical: QuestionType[] = [
|
||||||
|
{
|
||||||
|
question: {
|
||||||
|
id: '7',
|
||||||
|
type: 'Numerical',
|
||||||
|
choices: [
|
||||||
|
{ type: 'high-low', numberHigh: 100, numberLow: 90 } as HighLowNumericalAnswer,
|
||||||
|
],
|
||||||
|
} as NumericalQuestion,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
const answer: AnswerType = [95]; // User's answer within the range (90 to 100)
|
||||||
|
const result = checkIfIsCorrect(answer, 7, mockQuestionsNumerical);
|
||||||
|
expect(result).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('returns false for an out-of-range high-low numerical answer', () => {
|
||||||
|
const mockQuestionsNumerical: QuestionType[] = [
|
||||||
|
{
|
||||||
|
question: {
|
||||||
|
id: '7',
|
||||||
|
type: 'Numerical',
|
||||||
|
choices: [
|
||||||
|
{ type: 'high-low', numberHigh: 100, numberLow: 90 } as HighLowNumericalAnswer,
|
||||||
|
],
|
||||||
|
} as NumericalQuestion,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
const answer: AnswerType = [105]; // User's answer outside the range (90 to 100)
|
||||||
|
const result = checkIfIsCorrect(answer, 7, mockQuestionsNumerical);
|
||||||
|
expect(result).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('returns true for a correct multiple numerical answer', () => {
|
||||||
|
const mockQuestionsNumerical: QuestionType[] = [
|
||||||
|
{
|
||||||
|
question: {
|
||||||
|
id: '8',
|
||||||
|
type: 'Numerical',
|
||||||
|
choices: [
|
||||||
|
{
|
||||||
|
isCorrect: true,
|
||||||
|
answer: { type: 'simple', number: 42 } as SimpleNumericalAnswer,
|
||||||
|
} as MultipleNumericalAnswer,
|
||||||
|
{
|
||||||
|
isCorrect: false,
|
||||||
|
answer: { type: 'high-low', numberHigh: 100, numberLow: 90 } as HighLowNumericalAnswer,
|
||||||
|
formattedFeedback: { text: 'You guessed way too high' },
|
||||||
|
}
|
||||||
|
],
|
||||||
|
} as NumericalQuestion,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
const answer: AnswerType = [42]; // User's answer matches the correct multiple numerical answer
|
||||||
|
const result = checkIfIsCorrect(answer, 8, mockQuestionsNumerical);
|
||||||
|
expect(result).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('returns false for an incorrect multiple numerical answer', () => {
|
||||||
|
const mockQuestionsNumerical: QuestionType[] = [
|
||||||
|
{
|
||||||
|
question: {
|
||||||
|
id: '8',
|
||||||
|
type: 'Numerical',
|
||||||
|
choices: [
|
||||||
|
{
|
||||||
|
type: 'multiple',
|
||||||
|
isCorrect: true,
|
||||||
|
answer: { type: 'simple', number: 42 } as SimpleNumericalAnswer,
|
||||||
|
} as MultipleNumericalAnswer,
|
||||||
|
],
|
||||||
|
} as NumericalQuestion,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
const answer: AnswerType = [43]; // User's answer does not match the correct multiple numerical answer
|
||||||
|
const result = checkIfIsCorrect(answer, 8, mockQuestionsNumerical);
|
||||||
|
expect(result).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
});
|
||||||
|
|
@ -19,6 +19,11 @@ jest.mock('react-router-dom', () => ({
|
||||||
}));
|
}));
|
||||||
jest.mock('src/pages/Teacher/ManageRoom/RoomContext');
|
jest.mock('src/pages/Teacher/ManageRoom/RoomContext');
|
||||||
|
|
||||||
|
jest.mock('qrcode.react', () => ({
|
||||||
|
__esModule: true,
|
||||||
|
QRCodeCanvas: ({ value }: { value: string }) => <div data-testid="qr-code">{value}</div>,
|
||||||
|
}));
|
||||||
|
|
||||||
const mockSocket = {
|
const mockSocket = {
|
||||||
on: jest.fn(),
|
on: jest.fn(),
|
||||||
off: jest.fn(),
|
off: jest.fn(),
|
||||||
|
|
@ -44,7 +49,7 @@ const mockStudents: StudentType[] = [
|
||||||
];
|
];
|
||||||
|
|
||||||
const mockAnswerData: AnswerReceptionFromBackendType = {
|
const mockAnswerData: AnswerReceptionFromBackendType = {
|
||||||
answer: 'Answer1',
|
answer: ['Answer1'],
|
||||||
idQuestion: 1,
|
idQuestion: 1,
|
||||||
idUser: '1',
|
idUser: '1',
|
||||||
username: 'Student 1',
|
username: 'Student 1',
|
||||||
|
|
@ -233,7 +238,7 @@ describe('ManageRoom', () => {
|
||||||
|
|
||||||
await act(async () => {
|
await act(async () => {
|
||||||
const createSuccessCallback = (mockSocket.on as jest.Mock).mock.calls.find(call => call[0] === 'create-success')[1];
|
const createSuccessCallback = (mockSocket.on as jest.Mock).mock.calls.find(call => call[0] === 'create-success')[1];
|
||||||
createSuccessCallback('test-room-name');
|
createSuccessCallback('Test Room');
|
||||||
});
|
});
|
||||||
|
|
||||||
const launchButton = screen.getByText('Lancer');
|
const launchButton = screen.getByText('Lancer');
|
||||||
|
|
@ -256,6 +261,7 @@ describe('ManageRoom', () => {
|
||||||
});
|
});
|
||||||
|
|
||||||
await waitFor(() => {
|
await waitFor(() => {
|
||||||
|
// console.info(consoleSpy.mock.calls);
|
||||||
expect(consoleSpy).toHaveBeenCalledWith(
|
expect(consoleSpy).toHaveBeenCalledWith(
|
||||||
'Received answer from Student 1 for question 1: Answer1'
|
'Received answer from Student 1 for question 1: Answer1'
|
||||||
);
|
);
|
||||||
|
|
@ -293,4 +299,84 @@ describe('ManageRoom', () => {
|
||||||
expect(screen.queryByText('Student 1')).not.toBeInTheDocument();
|
expect(screen.queryByText('Student 1')).not.toBeInTheDocument();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('terminates the quiz and navigates to teacher dashboard when the "Terminer le quiz" button is clicked', async () => {
|
||||||
|
await act(async () => {
|
||||||
|
render(
|
||||||
|
<MemoryRouter>
|
||||||
|
<ManageRoom />
|
||||||
|
</MemoryRouter>
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
const createSuccessCallback = (mockSocket.on as jest.Mock).mock.calls.find(call => call[0] === 'create-success')[1];
|
||||||
|
createSuccessCallback('Test Room');
|
||||||
|
});
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByText('Lancer'));
|
||||||
|
fireEvent.click(screen.getByText('Rythme du professeur'));
|
||||||
|
fireEvent.click(screen.getAllByText('Lancer')[1]);
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(screen.getByText('Test Quiz')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
const finishQuizButton = screen.getByText('Terminer le quiz');
|
||||||
|
fireEvent.click(finishQuizButton);
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(navigate).toHaveBeenCalledWith('/teacher/dashboard');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test("Affiche la modale QR Code lorsqu’on clique sur le bouton", async () => {
|
||||||
|
render(<MemoryRouter><ManageRoom /></MemoryRouter>);
|
||||||
|
|
||||||
|
const button = screen.getByRole('button', { name: /lien de participation/i });
|
||||||
|
fireEvent.click(button);
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(screen.getByRole('dialog')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(screen.getByRole('heading', { name: /Rejoindre la salle/i })).toBeInTheDocument();
|
||||||
|
expect(screen.getByText(/Scannez ce QR code ou partagez le lien ci-dessous/i)).toBeInTheDocument();
|
||||||
|
expect(screen.getByTestId('qr-code')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("Ferme la modale QR Code lorsqu’on clique sur le bouton Fermer", async () => {
|
||||||
|
render(<MemoryRouter><ManageRoom /></MemoryRouter>);
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: /lien de participation/i }));
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(screen.getByRole('dialog')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: /fermer/i }));
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Affiche le bon lien de participation', () => {
|
||||||
|
render(<MemoryRouter><ManageRoom /></MemoryRouter>);
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: /lien de participation/i }));
|
||||||
|
|
||||||
|
const roomUrl = `${window.location.origin}/student/join-room?roomName=Test Room`;
|
||||||
|
expect(screen.getByTestId('qr-code')).toHaveTextContent(roomUrl);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Vérifie que le QR code contient la bonne URL', () => {
|
||||||
|
render(<MemoryRouter><ManageRoom /></MemoryRouter>);
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: /lien de participation/i }));
|
||||||
|
|
||||||
|
const roomUrl = `${window.location.origin}/student/join-room?roomName=Test Room`;
|
||||||
|
expect(screen.getByTestId('qr-code')).toHaveTextContent(roomUrl);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -8,7 +8,7 @@ import { QuestionType } from 'src/Types/QuestionType';
|
||||||
import { AnswerSubmissionToBackendType } from 'src/services/WebsocketService';
|
import { AnswerSubmissionToBackendType } from 'src/services/WebsocketService';
|
||||||
|
|
||||||
const mockGiftQuestions = parse(
|
const mockGiftQuestions = parse(
|
||||||
`::Sample Question 1:: Sample Question 1 {=Option A ~Option B}
|
`::Sample Question 1:: Sample Question 1 {=Option A =Option B ~Option C}
|
||||||
|
|
||||||
::Sample Question 2:: Sample Question 2 {T}`);
|
::Sample Question 2:: Sample Question 2 {T}`);
|
||||||
|
|
||||||
|
|
@ -23,9 +23,6 @@ const mockSubmitAnswer = jest.fn();
|
||||||
const mockDisconnectWebSocket = jest.fn();
|
const mockDisconnectWebSocket = jest.fn();
|
||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
// Clear local storage before each test
|
|
||||||
// localStorage.clear();
|
|
||||||
|
|
||||||
render(
|
render(
|
||||||
<MemoryRouter>
|
<MemoryRouter>
|
||||||
<StudentModeQuiz
|
<StudentModeQuiz
|
||||||
|
|
@ -54,7 +51,7 @@ describe('StudentModeQuiz', () => {
|
||||||
fireEvent.click(screen.getByText('Répondre'));
|
fireEvent.click(screen.getByText('Répondre'));
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(mockSubmitAnswer).toHaveBeenCalledWith('Option A', 1);
|
expect(mockSubmitAnswer).toHaveBeenCalledWith(['Option A'], 1);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('handles shows feedback for an already answered question', async () => {
|
test('handles shows feedback for an already answered question', async () => {
|
||||||
|
|
@ -65,13 +62,13 @@ describe('StudentModeQuiz', () => {
|
||||||
act(() => {
|
act(() => {
|
||||||
fireEvent.click(screen.getByText('Répondre'));
|
fireEvent.click(screen.getByText('Répondre'));
|
||||||
});
|
});
|
||||||
expect(mockSubmitAnswer).toHaveBeenCalledWith('Option A', 1);
|
expect(mockSubmitAnswer).toHaveBeenCalledWith(['Option A'], 1);
|
||||||
|
|
||||||
const firstButtonA = screen.getByRole("button", {name: '✅ A Option A'});
|
const firstButtonA = screen.getByRole("button", {name: '✅ A Option A'});
|
||||||
expect(firstButtonA).toBeInTheDocument();
|
expect(firstButtonA).toBeInTheDocument();
|
||||||
expect(firstButtonA.querySelector('.selected')).toBeInTheDocument();
|
expect(firstButtonA.querySelector('.selected')).toBeInTheDocument();
|
||||||
|
|
||||||
expect(screen.getByRole("button", {name: '❌ B Option B'})).toBeInTheDocument();
|
expect(screen.getByRole("button", {name: '✅ B Option B'})).toBeInTheDocument();
|
||||||
expect(screen.queryByText('Répondre')).not.toBeInTheDocument();
|
expect(screen.queryByText('Répondre')).not.toBeInTheDocument();
|
||||||
|
|
||||||
// Navigate to the next question
|
// Navigate to the next question
|
||||||
|
|
@ -87,12 +84,12 @@ describe('StudentModeQuiz', () => {
|
||||||
});
|
});
|
||||||
expect(await screen.findByText('Sample Question 1')).toBeInTheDocument();
|
expect(await screen.findByText('Sample Question 1')).toBeInTheDocument();
|
||||||
|
|
||||||
// Since answers are mocked, the it doesn't recognize the question as already answered
|
// Since answers are mocked, it doesn't recognize the question as already answered
|
||||||
// TODO these tests are partially faked, need to be fixed if we can mock the answers
|
// TODO these tests are partially faked, need to be fixed if we can mock the answers
|
||||||
// const buttonA = screen.getByRole("button", {name: '✅ A Option A'});
|
// const buttonA = screen.getByRole("button", {name: '✅ A Option A'});
|
||||||
const buttonA = screen.getByRole("button", {name: 'A Option A'});
|
const buttonA = screen.getByRole("button", {name: 'A Option A'});
|
||||||
expect(buttonA).toBeInTheDocument();
|
expect(buttonA).toBeInTheDocument();
|
||||||
// const buttonB = screen.getByRole("button", {name: '❌ B Option B'});
|
// const buttonB = screen.getByRole("button", {name: '✅ B Option B'});
|
||||||
const buttonB = screen.getByRole("button", {name: 'B Option B'});
|
const buttonB = screen.getByRole("button", {name: 'B Option B'});
|
||||||
expect(buttonB).toBeInTheDocument();
|
expect(buttonB).toBeInTheDocument();
|
||||||
// // "Option A" div inside the name of button should have selected class
|
// // "Option A" div inside the name of button should have selected class
|
||||||
|
|
@ -122,4 +119,30 @@ describe('StudentModeQuiz', () => {
|
||||||
expect(screen.getByText('Sample Question 2')).toBeInTheDocument();
|
expect(screen.getByText('Sample Question 2')).toBeInTheDocument();
|
||||||
expect(screen.getByText('Répondre')).toBeInTheDocument();
|
expect(screen.getByText('Répondre')).toBeInTheDocument();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// le test suivant est fait dans MultipleChoiceQuestionDisplay.test.tsx
|
||||||
|
// test('allows multiple answers to be selected for a question', async () => {
|
||||||
|
// // Simulate selecting multiple answers
|
||||||
|
// act(() => {
|
||||||
|
// fireEvent.click(screen.getByText('Option A'));
|
||||||
|
// });
|
||||||
|
// act(() => {
|
||||||
|
// fireEvent.click(screen.getByText('Option B'));
|
||||||
|
// });
|
||||||
|
|
||||||
|
// // Simulate submitting the answers
|
||||||
|
// act(() => {
|
||||||
|
// fireEvent.click(screen.getByText('Répondre'));
|
||||||
|
// });
|
||||||
|
|
||||||
|
// // Verify that the mockSubmitAnswer function is called with both answers
|
||||||
|
// expect(mockSubmitAnswer).toHaveBeenCalledWith(['Option A', 'Option B'], 1);
|
||||||
|
|
||||||
|
// // Verify that the selected answers are displayed as selected
|
||||||
|
// const buttonA = screen.getByRole('button', { name: '✅ A Option A' });
|
||||||
|
// const buttonB = screen.getByRole('button', { name: '✅ B Option B' });
|
||||||
|
// expect(buttonA).toBeInTheDocument();
|
||||||
|
// expect(buttonB).toBeInTheDocument();
|
||||||
|
// });
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -63,7 +63,8 @@ describe('TeacherModeQuiz', () => {
|
||||||
act(() => {
|
act(() => {
|
||||||
fireEvent.click(screen.getByText('Répondre'));
|
fireEvent.click(screen.getByText('Répondre'));
|
||||||
});
|
});
|
||||||
expect(mockSubmitAnswer).toHaveBeenCalledWith('Option A', 1);
|
expect(mockSubmitAnswer).toHaveBeenCalledWith(['Option A'], 1);
|
||||||
|
mockSubmitAnswer.mockClear();
|
||||||
});
|
});
|
||||||
|
|
||||||
test('handles shows feedback for an already answered question', () => {
|
test('handles shows feedback for an already answered question', () => {
|
||||||
|
|
@ -74,7 +75,8 @@ describe('TeacherModeQuiz', () => {
|
||||||
act(() => {
|
act(() => {
|
||||||
fireEvent.click(screen.getByText('Répondre'));
|
fireEvent.click(screen.getByText('Répondre'));
|
||||||
});
|
});
|
||||||
expect(mockSubmitAnswer).toHaveBeenCalledWith('Option A', 1);
|
expect(mockSubmitAnswer).toHaveBeenCalledWith(['Option A'], 1);
|
||||||
|
mockSubmitAnswer.mockClear();
|
||||||
mockQuestion = mockQuestions[1].question as MultipleChoiceQuestion;
|
mockQuestion = mockQuestions[1].question as MultipleChoiceQuestion;
|
||||||
// Navigate to the next question by re-rendering with new props
|
// Navigate to the next question by re-rendering with new props
|
||||||
act(() => {
|
act(() => {
|
||||||
|
|
|
||||||
95
client/src/__tests__/pages/Teacher/Share/Share.test.tsx
Normal file
95
client/src/__tests__/pages/Teacher/Share/Share.test.tsx
Normal file
|
|
@ -0,0 +1,95 @@
|
||||||
|
import React from 'react';
|
||||||
|
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
|
||||||
|
import { MemoryRouter, Route, Routes, useParams } from 'react-router-dom';
|
||||||
|
import Share from '../../../../pages/Teacher/Share/Share.tsx';
|
||||||
|
import ApiService from '../../../../services/ApiService';
|
||||||
|
import '@testing-library/jest-dom';
|
||||||
|
|
||||||
|
// Mock the ApiService and react-router-dom
|
||||||
|
jest.mock('../../../../services/ApiService');
|
||||||
|
jest.mock('react-router-dom', () => ({
|
||||||
|
...jest.requireActual('react-router-dom'),
|
||||||
|
useParams: jest.fn(),
|
||||||
|
useNavigate: jest.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
describe('Share Component', () => {
|
||||||
|
const mockNavigate = jest.fn();
|
||||||
|
const mockUseParams = useParams as jest.Mock;
|
||||||
|
const mockApiService = ApiService as jest.Mocked<typeof ApiService>;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
jest.clearAllMocks();
|
||||||
|
mockUseParams.mockReturnValue({ id: 'quiz123' });
|
||||||
|
require('react-router-dom').useNavigate.mockReturnValue(mockNavigate);
|
||||||
|
});
|
||||||
|
|
||||||
|
const renderComponent = (initialEntries = ['/share/quiz123']) => {
|
||||||
|
return render(
|
||||||
|
<MemoryRouter initialEntries={initialEntries}>
|
||||||
|
<Routes>
|
||||||
|
<Route path="/share/:id" element={<Share />} />
|
||||||
|
<Route path="/teacher/dashboard" element={<div>Dashboard</div>} />
|
||||||
|
<Route path="/login" element={<div>Login</div>} />
|
||||||
|
</Routes>
|
||||||
|
</MemoryRouter>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
it('should show loading state initially', () => {
|
||||||
|
mockApiService.getAllQuizIds.mockResolvedValue([]);
|
||||||
|
mockApiService.getUserFolders.mockResolvedValue([]);
|
||||||
|
mockApiService.getSharedQuiz.mockResolvedValue('Test Quiz');
|
||||||
|
|
||||||
|
renderComponent();
|
||||||
|
expect(screen.getByText('Chargement...')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should redirect to login if not authenticated', async () => {
|
||||||
|
mockApiService.isLoggedIn.mockReturnValue(false);
|
||||||
|
|
||||||
|
renderComponent();
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(mockNavigate).toHaveBeenCalledWith('/login');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should show "quiz already exists" message when quiz exists', async () => {
|
||||||
|
mockApiService.isLoggedIn.mockReturnValue(true);
|
||||||
|
mockApiService.getAllQuizIds.mockResolvedValue(['quiz123']);
|
||||||
|
|
||||||
|
renderComponent();
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(screen.getByText('Quiz déjà existant')).toBeInTheDocument();
|
||||||
|
expect(screen.getByText(/Le quiz que vous essayez d'importer existe déjà sur votre compte/i)).toBeInTheDocument();
|
||||||
|
expect(screen.getByText('Retour au tableau de bord')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should navigate to dashboard when clicking return button in "quiz exists" view', async () => {
|
||||||
|
mockApiService.isLoggedIn.mockReturnValue(true);
|
||||||
|
mockApiService.getAllQuizIds.mockResolvedValue(['quiz123']);
|
||||||
|
|
||||||
|
renderComponent();
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
fireEvent.click(screen.getByText('Retour au tableau de bord'));
|
||||||
|
expect(mockNavigate).toHaveBeenCalledWith('/teacher/dashboard');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should show error when no folders exist', async () => {
|
||||||
|
mockApiService.isLoggedIn.mockReturnValue(true);
|
||||||
|
mockApiService.getAllQuizIds.mockResolvedValue([]);
|
||||||
|
mockApiService.getUserFolders.mockResolvedValue([]);
|
||||||
|
|
||||||
|
renderComponent();
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(mockNavigate).toHaveBeenCalledWith('/teacher/dashboard');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
});
|
||||||
42
client/src/__tests__/services/ShareQuizService.test.tsx
Normal file
42
client/src/__tests__/services/ShareQuizService.test.tsx
Normal file
|
|
@ -0,0 +1,42 @@
|
||||||
|
import axios from 'axios';
|
||||||
|
import ApiService from '../../services/ApiService';
|
||||||
|
import { ENV_VARIABLES } from '../../constants';
|
||||||
|
|
||||||
|
jest.mock('axios');
|
||||||
|
const mockedAxios = axios as jest.Mocked<typeof axios>;
|
||||||
|
|
||||||
|
describe('getSharedQuiz', () => {
|
||||||
|
it('should call the API to get a shared quiz and return the quiz data on success', async () => {
|
||||||
|
const quizId = '123';
|
||||||
|
const quizData = 'Quiz data';
|
||||||
|
const response = { status: 200, data: { data: quizData } };
|
||||||
|
mockedAxios.get.mockResolvedValue(response);
|
||||||
|
|
||||||
|
const result = await ApiService.getSharedQuiz(quizId);
|
||||||
|
|
||||||
|
expect(mockedAxios.get).toHaveBeenCalledWith(
|
||||||
|
`${ENV_VARIABLES.VITE_BACKEND_URL}/api/quiz/getShare/${quizId}`,
|
||||||
|
{ headers: expect.any(Object) }
|
||||||
|
);
|
||||||
|
expect(result).toBe(quizData);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return an error message if the API call fails', async () => {
|
||||||
|
const quizId = '123';
|
||||||
|
const errorMessage = 'An unexpected error occurred.';
|
||||||
|
mockedAxios.get.mockRejectedValue({ response: { data: { error: errorMessage } } });
|
||||||
|
|
||||||
|
const result = await ApiService.getSharedQuiz(quizId);
|
||||||
|
|
||||||
|
expect(result).toBe(errorMessage);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return a generic error message if an unexpected error occurs', async () => {
|
||||||
|
const quizId = '123';
|
||||||
|
mockedAxios.get.mockRejectedValue(new Error('Unexpected error'));
|
||||||
|
|
||||||
|
const result = await ApiService.getSharedQuiz(quizId);
|
||||||
|
|
||||||
|
expect(result).toBe('An unexpected error occurred.');
|
||||||
|
});
|
||||||
|
});
|
||||||
42
client/src/__tests__/services/getAllQuizIdsService.test.tsx
Normal file
42
client/src/__tests__/services/getAllQuizIdsService.test.tsx
Normal file
|
|
@ -0,0 +1,42 @@
|
||||||
|
import axios from 'axios';
|
||||||
|
import ApiService from '../../services/ApiService';
|
||||||
|
import { FolderType } from '../../Types/FolderType';
|
||||||
|
import { QuizType } from '../../Types/QuizType';
|
||||||
|
|
||||||
|
jest.mock('axios');
|
||||||
|
const mockedAxios = axios as jest.Mocked<typeof axios>;
|
||||||
|
|
||||||
|
describe('ApiService', () => {
|
||||||
|
describe('getAllQuizIds', () => {
|
||||||
|
it('should return all quiz IDs from all folders', async () => {
|
||||||
|
const folders: FolderType[] = [
|
||||||
|
{ _id: 'folder1', title: 'Folder 1', userId: 'user1', created_at: new Date().toISOString() },
|
||||||
|
{ _id: 'folder2', title: 'Folder 2', userId: 'user2', created_at: new Date().toISOString() }
|
||||||
|
];
|
||||||
|
const quizzesFolder1: QuizType[] = [
|
||||||
|
{ _id: 'quiz1', title: 'Quiz 1', content: [], folderId: 'folder1', folderName: 'Folder 1', userId: 'user1', created_at: new Date(), updated_at: new Date() },
|
||||||
|
{ _id: 'quiz2', title: 'Quiz 2', content: [], folderId: 'folder1', folderName: 'Folder 1', userId: 'user1', created_at: new Date(), updated_at: new Date() }
|
||||||
|
];
|
||||||
|
const quizzesFolder2: QuizType[] = [
|
||||||
|
{ _id: 'quiz3', title: 'Quiz 3', content: [], folderId: 'folder2', folderName: 'Folder 2', userId: 'user2', created_at: new Date(), updated_at: new Date() }
|
||||||
|
];
|
||||||
|
|
||||||
|
mockedAxios.get
|
||||||
|
.mockResolvedValueOnce({ status: 200, data: { data: folders } })
|
||||||
|
.mockResolvedValueOnce({ status: 200, data: { data: quizzesFolder1 } })
|
||||||
|
.mockResolvedValueOnce({ status: 200, data: { data: quizzesFolder2 } });
|
||||||
|
|
||||||
|
const result = await ApiService.getAllQuizIds();
|
||||||
|
|
||||||
|
expect(result).toEqual(['quiz1', 'quiz2', 'quiz3']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return an empty array if no folders are found', async () => {
|
||||||
|
mockedAxios.get.mockResolvedValueOnce({ status: 200, data: { data: [] } });
|
||||||
|
|
||||||
|
const result = await ApiService.getAllQuizIds();
|
||||||
|
|
||||||
|
expect(result).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -13,14 +13,14 @@ type AnswerFeedbackOptions = TemplateOptions & Pick<TextChoice, 'formattedFeedba
|
||||||
interface AnswerWeightOptions extends TemplateOptions {
|
interface AnswerWeightOptions extends TemplateOptions {
|
||||||
weight: TextChoice['weight'];
|
weight: TextChoice['weight'];
|
||||||
}
|
}
|
||||||
|
// careful -- this template is re-used by True/False questions!
|
||||||
export default function MultipleChoiceAnswersTemplate({ choices }: MultipleChoiceAnswerOptions) {
|
export default function MultipleChoiceAnswersTemplate({ choices }: MultipleChoiceAnswerOptions) {
|
||||||
const id = `id${nanoid(8)}`;
|
const id = `id${nanoid(8)}`;
|
||||||
|
|
||||||
const isMultipleAnswer = choices.filter(({ isCorrect }) => isCorrect === true).length === 0;
|
const hasManyCorrectChoices = choices.filter(({ isCorrect }) => isCorrect === true).length > 1;
|
||||||
|
|
||||||
const prompt = `<span style="${ParagraphStyle(state.theme)}">Choisir une réponse${
|
const prompt = `<span style="${ParagraphStyle(state.theme)}">Choisir une réponse${
|
||||||
isMultipleAnswer ? ` ou plusieurs` : ``
|
hasManyCorrectChoices ? ` ou plusieurs` : ``
|
||||||
}:</span>`;
|
}:</span>`;
|
||||||
const result = choices
|
const result = choices
|
||||||
.map(({ weight, isCorrect, formattedText, formattedFeedback }) => {
|
.map(({ weight, isCorrect, formattedText, formattedFeedback }) => {
|
||||||
|
|
@ -32,12 +32,12 @@ export default function MultipleChoiceAnswersTemplate({ choices }: MultipleChoic
|
||||||
const inputId = `id${nanoid(6)}`;
|
const inputId = `id${nanoid(6)}`;
|
||||||
|
|
||||||
const isPositiveWeight = (weight != undefined) && (weight > 0);
|
const isPositiveWeight = (weight != undefined) && (weight > 0);
|
||||||
const isCorrectOption = isMultipleAnswer ? isPositiveWeight : isCorrect;
|
const isCorrectOption = hasManyCorrectChoices ? isPositiveWeight || isCorrect : isCorrect;
|
||||||
|
|
||||||
return `
|
return `
|
||||||
<div class='multiple-choice-answers-container'>
|
<div class='multiple-choice-answers-container'>
|
||||||
<input class="gift-input" type="${
|
<input class="gift-input" type="${
|
||||||
isMultipleAnswer ? 'checkbox' : 'radio'
|
hasManyCorrectChoices ? 'checkbox' : 'radio'
|
||||||
}" id="${inputId}" name="${id}">
|
}" id="${inputId}" name="${id}">
|
||||||
${AnswerWeight({ weight: weight })}
|
${AnswerWeight({ weight: weight })}
|
||||||
<label style="${CustomLabel} ${ParagraphStyle(state.theme)}" for="${inputId}">
|
<label style="${CustomLabel} ${ParagraphStyle(state.theme)}" for="${inputId}">
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,7 @@ import * as React from 'react';
|
||||||
import './header.css';
|
import './header.css';
|
||||||
import { Button } from '@mui/material';
|
import { Button } from '@mui/material';
|
||||||
import AdminDrawer from '../AdminDrawer/AdminDrawer';
|
import AdminDrawer from '../AdminDrawer/AdminDrawer';
|
||||||
|
import ExitToAppIcon from '@mui/icons-material/ExitToApp';
|
||||||
|
|
||||||
interface HeaderProps {
|
interface HeaderProps {
|
||||||
isLoggedIn: boolean;
|
isLoggedIn: boolean;
|
||||||
|
|
@ -27,16 +28,18 @@ const Header: React.FC<HeaderProps> = ({ isLoggedIn, isAdmin, handleLogout }) =>
|
||||||
|
|
||||||
{ isAdmin && <AdminDrawer /> }
|
{ isAdmin && <AdminDrawer /> }
|
||||||
|
|
||||||
<Button
|
<Button
|
||||||
variant="outlined"
|
variant="outlined"
|
||||||
color="primary"
|
color="primary"
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
handleLogout();
|
handleLogout();
|
||||||
navigate('/');
|
navigate('/');
|
||||||
}}
|
}}
|
||||||
>
|
startIcon={<ExitToAppIcon />}
|
||||||
Logout
|
>
|
||||||
</Button>
|
Déconnexion
|
||||||
|
</Button>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -22,8 +22,8 @@ import CloseIcon from "@mui/icons-material/Close";
|
||||||
import { ImageType } from "../../Types/ImageType";
|
import { ImageType } from "../../Types/ImageType";
|
||||||
import ApiService from "../../services/ApiService";
|
import ApiService from "../../services/ApiService";
|
||||||
import { Upload } from "@mui/icons-material";
|
import { Upload } from "@mui/icons-material";
|
||||||
import { ENV_VARIABLES } from '../../constants';
|
|
||||||
import { escapeForGIFT } from "src/utils/giftUtils";
|
import { escapeForGIFT } from "src/utils/giftUtils";
|
||||||
|
import { ENV_VARIABLES } from "src/constants";
|
||||||
|
|
||||||
interface ImagesProps {
|
interface ImagesProps {
|
||||||
handleCopy?: (id: string) => void;
|
handleCopy?: (id: string) => void;
|
||||||
|
|
@ -83,9 +83,9 @@ const ImageGallery: React.FC<ImagesProps> = ({ handleCopy, handleDelete }) => {
|
||||||
|
|
||||||
const defaultHandleCopy = (id: string) => {
|
const defaultHandleCopy = (id: string) => {
|
||||||
if (navigator.clipboard) {
|
if (navigator.clipboard) {
|
||||||
const link = `${ENV_VARIABLES.IMG_URL}/api/image/get/${id}`;
|
const link = `${ENV_VARIABLES.BACKEND_URL}/api/image/get/${id}`;
|
||||||
const imgTag = `[markdown]} "texte de l'infobulle")`;
|
const imgTag = `[markdown] } "texte de l'infobulle (ne fonctionne pas sur écran tactile généralement)") `;
|
||||||
setSnackbarMessage("Le lien Markdown de l’image a été copié dans le presse-papiers");
|
setSnackbarMessage("Le lien Markdown de l'image a été copié dans le presse-papiers");
|
||||||
setSnackbarSeverity("success");
|
setSnackbarSeverity("success");
|
||||||
setSnackbarOpen(true);
|
setSnackbarOpen(true);
|
||||||
navigator.clipboard.writeText(imgTag);
|
navigator.clipboard.writeText(imgTag);
|
||||||
|
|
@ -147,7 +147,7 @@ const ImageGallery: React.FC<ImagesProps> = ({ handleCopy, handleDelete }) => {
|
||||||
return (
|
return (
|
||||||
<Box p={3}>
|
<Box p={3}>
|
||||||
<Tabs value={tabValue} onChange={(_, newValue) => setTabValue(newValue)}>
|
<Tabs value={tabValue} onChange={(_, newValue) => setTabValue(newValue)}>
|
||||||
<Tab label="Gallery" />
|
<Tab label="Galerie" />
|
||||||
<Tab label="Import" />
|
<Tab label="Import" />
|
||||||
</Tabs>
|
</Tabs>
|
||||||
{tabValue === 0 && (
|
{tabValue === 0 && (
|
||||||
|
|
|
||||||
|
|
@ -51,7 +51,7 @@ const LiveResultsTableFooter: React.FC<LiveResultsFooterProps> = ({
|
||||||
borderWidth: 1,
|
borderWidth: 1,
|
||||||
borderColor: 'rgba(224, 224, 224, 1)',
|
borderColor: 'rgba(224, 224, 224, 1)',
|
||||||
fontWeight: 'bold',
|
fontWeight: 'bold',
|
||||||
color: 'rgba(0, 0, 0)'
|
color: 'rgba(0, 0, 0)',
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{students.length > 0
|
{students.length > 0
|
||||||
|
|
@ -67,7 +67,7 @@ const LiveResultsTableFooter: React.FC<LiveResultsFooterProps> = ({
|
||||||
borderColor: 'rgba(224, 224, 224, 1)',
|
borderColor: 'rgba(224, 224, 224, 1)',
|
||||||
fontWeight: 'bold',
|
fontWeight: 'bold',
|
||||||
fontSize: '1rem',
|
fontSize: '1rem',
|
||||||
color: 'rgba(0, 0, 0)'
|
color: 'rgba(0, 0, 0)',
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{students.length > 0 ? `${classAverage.toFixed()} %` : '-'}
|
{students.length > 0 ? `${classAverage.toFixed()} %` : '-'}
|
||||||
|
|
@ -76,4 +76,4 @@ const LiveResultsTableFooter: React.FC<LiveResultsFooterProps> = ({
|
||||||
</TableFooter>
|
</TableFooter>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
export default LiveResultsTableFooter;
|
export default LiveResultsTableFooter;
|
||||||
|
|
|
||||||
|
|
@ -15,76 +15,115 @@ interface Props {
|
||||||
|
|
||||||
const MultipleChoiceQuestionDisplay: React.FC<Props> = (props) => {
|
const MultipleChoiceQuestionDisplay: React.FC<Props> = (props) => {
|
||||||
const { question, showAnswer, handleOnSubmitAnswer, passedAnswer } = props;
|
const { question, showAnswer, handleOnSubmitAnswer, passedAnswer } = props;
|
||||||
const [answer, setAnswer] = useState<AnswerType>(passedAnswer || '');
|
console.log('MultipleChoiceQuestionDisplay: passedAnswer', JSON.stringify(passedAnswer));
|
||||||
|
|
||||||
|
const [answer, setAnswer] = useState<AnswerType>(() => {
|
||||||
|
if (passedAnswer && passedAnswer.length > 0) {
|
||||||
|
return passedAnswer;
|
||||||
|
}
|
||||||
|
return [];
|
||||||
|
});
|
||||||
|
|
||||||
let disableButton = false;
|
let disableButton = false;
|
||||||
if(handleOnSubmitAnswer === undefined){
|
if (handleOnSubmitAnswer === undefined) {
|
||||||
disableButton = true;
|
disableButton = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (passedAnswer !== undefined) {
|
console.log('MultipleChoiceQuestionDisplay: passedAnswer', JSON.stringify(passedAnswer));
|
||||||
setAnswer(passedAnswer);
|
if (passedAnswer !== undefined) {
|
||||||
}
|
setAnswer(passedAnswer);
|
||||||
}, [passedAnswer]);
|
} else {
|
||||||
|
setAnswer([]);
|
||||||
|
}
|
||||||
|
}, [passedAnswer, question.id]);
|
||||||
|
|
||||||
const handleOnClickAnswer = (choice: string) => {
|
const handleOnClickAnswer = (choice: string) => {
|
||||||
setAnswer(choice);
|
setAnswer((prevAnswer) => {
|
||||||
|
console.log(`handleOnClickAnswer -- setAnswer(): prevAnswer: ${prevAnswer}, choice: ${choice}`);
|
||||||
|
const correctAnswersCount = question.choices.filter((c) => c.isCorrect).length;
|
||||||
|
|
||||||
|
if (correctAnswersCount === 1) {
|
||||||
|
// If only one correct answer, replace the current selection
|
||||||
|
return prevAnswer.includes(choice) ? [] : [choice];
|
||||||
|
} else {
|
||||||
|
// Allow multiple selections if there are multiple correct answers
|
||||||
|
if (prevAnswer.includes(choice)) {
|
||||||
|
// Remove the choice if it's already selected
|
||||||
|
return prevAnswer.filter((selected) => selected !== choice);
|
||||||
|
} else {
|
||||||
|
// Add the choice if it's not already selected
|
||||||
|
return [...prevAnswer, choice];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const alpha = Array.from(Array(26)).map((_e, i) => i + 65);
|
const alpha = Array.from(Array(26)).map((_e, i) => i + 65);
|
||||||
const alphabet = alpha.map((x) => String.fromCharCode(x));
|
const alphabet = alpha.map((x) => String.fromCharCode(x));
|
||||||
return (
|
|
||||||
|
|
||||||
|
return (
|
||||||
<div className="question-container">
|
<div className="question-container">
|
||||||
<div className="question content">
|
<div className="question content">
|
||||||
<div dangerouslySetInnerHTML={{ __html: FormattedTextTemplate(question.formattedStem) }} />
|
<div dangerouslySetInnerHTML={{ __html: FormattedTextTemplate(question.formattedStem) }} />
|
||||||
</div>
|
</div>
|
||||||
<div className="choices-wrapper mb-1">
|
<div className="choices-wrapper mb-1">
|
||||||
|
|
||||||
{question.choices.map((choice, i) => {
|
{question.choices.map((choice, i) => {
|
||||||
const selected = answer === choice.formattedText.text ? 'selected' : '';
|
console.log(`answer: ${answer}, choice: ${choice.formattedText.text}`);
|
||||||
|
const selected = answer.includes(choice.formattedText.text) ? 'selected' : '';
|
||||||
return (
|
return (
|
||||||
<div key={choice.formattedText.text + i} className="choice-container">
|
<div key={choice.formattedText.text + i} className="choice-container">
|
||||||
<Button
|
<Button
|
||||||
variant="text"
|
variant="text"
|
||||||
className="button-wrapper"
|
className="button-wrapper"
|
||||||
disabled={disableButton}
|
disabled={disableButton}
|
||||||
onClick={() => !showAnswer && handleOnClickAnswer(choice.formattedText.text)}>
|
onClick={() => !showAnswer && handleOnClickAnswer(choice.formattedText.text)}
|
||||||
{showAnswer? (<div> {(choice.isCorrect ? '✅' : '❌')}</div>)
|
>
|
||||||
:``}
|
{showAnswer ? (
|
||||||
|
<div>{choice.isCorrect ? '✅' : '❌'}</div>
|
||||||
|
) : (
|
||||||
|
''
|
||||||
|
)}
|
||||||
<div className={`circle ${selected}`}>{alphabet[i]}</div>
|
<div className={`circle ${selected}`}>{alphabet[i]}</div>
|
||||||
<div className={`answer-text ${selected}`}>
|
<div className={`answer-text ${selected}`}>
|
||||||
<div dangerouslySetInnerHTML={{ __html: FormattedTextTemplate(choice.formattedText) }} />
|
<div
|
||||||
|
dangerouslySetInnerHTML={{
|
||||||
|
__html: FormattedTextTemplate(choice.formattedText),
|
||||||
|
}}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
{choice.formattedFeedback && showAnswer && (
|
{choice.formattedFeedback && showAnswer && (
|
||||||
<div className="feedback-container mb-1 mt-1/2">
|
<div className="feedback-container mb-1 mt-1/2">
|
||||||
<div dangerouslySetInnerHTML={{ __html: FormattedTextTemplate(choice.formattedFeedback) }} />
|
<div
|
||||||
</div>
|
dangerouslySetInnerHTML={{
|
||||||
)}
|
__html: FormattedTextTemplate(choice.formattedFeedback),
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</Button>
|
</Button>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
</div>
|
</div>
|
||||||
{question.formattedGlobalFeedback && showAnswer && (
|
{question.formattedGlobalFeedback && showAnswer && (
|
||||||
<div className="global-feedback mb-2">
|
<div className="global-feedback mb-2">
|
||||||
<div dangerouslySetInnerHTML={{ __html: FormattedTextTemplate(question.formattedGlobalFeedback) }} />
|
<div
|
||||||
</div>
|
dangerouslySetInnerHTML={{
|
||||||
|
__html: FormattedTextTemplate(question.formattedGlobalFeedback),
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{!showAnswer && handleOnSubmitAnswer && (
|
{!showAnswer && handleOnSubmitAnswer && (
|
||||||
|
|
||||||
<Button
|
<Button
|
||||||
variant="contained"
|
variant="contained"
|
||||||
onClick={() =>
|
onClick={() =>
|
||||||
answer !== "" && handleOnSubmitAnswer && handleOnSubmitAnswer(answer)
|
answer.length > 0 && handleOnSubmitAnswer && handleOnSubmitAnswer(answer)
|
||||||
}
|
}
|
||||||
disabled={answer === '' || answer === null}
|
disabled={answer.length === 0}
|
||||||
>
|
>
|
||||||
Répondre
|
Répondre
|
||||||
|
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
|
|
@ -17,7 +17,7 @@ interface Props {
|
||||||
const NumericalQuestionDisplay: React.FC<Props> = (props) => {
|
const NumericalQuestionDisplay: React.FC<Props> = (props) => {
|
||||||
const { question, showAnswer, handleOnSubmitAnswer, passedAnswer } =
|
const { question, showAnswer, handleOnSubmitAnswer, passedAnswer } =
|
||||||
props;
|
props;
|
||||||
const [answer, setAnswer] = useState<AnswerType>(passedAnswer || '');
|
const [answer, setAnswer] = useState<AnswerType>(passedAnswer || []);
|
||||||
const correctAnswers = question.choices;
|
const correctAnswers = question.choices;
|
||||||
let correctAnswer = '';
|
let correctAnswer = '';
|
||||||
|
|
||||||
|
|
@ -69,7 +69,7 @@ const NumericalQuestionDisplay: React.FC<Props> = (props) => {
|
||||||
id={question.formattedStem.text}
|
id={question.formattedStem.text}
|
||||||
name={question.formattedStem.text}
|
name={question.formattedStem.text}
|
||||||
onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
|
onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
setAnswer(e.target.valueAsNumber);
|
setAnswer([e.target.valueAsNumber]);
|
||||||
}}
|
}}
|
||||||
inputProps={{ 'data-testid': 'number-input' }}
|
inputProps={{ 'data-testid': 'number-input' }}
|
||||||
/>
|
/>
|
||||||
|
|
@ -87,7 +87,7 @@ const NumericalQuestionDisplay: React.FC<Props> = (props) => {
|
||||||
handleOnSubmitAnswer &&
|
handleOnSubmitAnswer &&
|
||||||
handleOnSubmitAnswer(answer)
|
handleOnSubmitAnswer(answer)
|
||||||
}
|
}
|
||||||
disabled={answer === "" || isNaN(answer as number)}
|
disabled={answer === undefined || answer === null || isNaN(answer[0] as number)}
|
||||||
>
|
>
|
||||||
Répondre
|
Répondre
|
||||||
</Button>
|
</Button>
|
||||||
|
|
|
||||||
|
|
@ -16,7 +16,7 @@ interface Props {
|
||||||
const ShortAnswerQuestionDisplay: React.FC<Props> = (props) => {
|
const ShortAnswerQuestionDisplay: React.FC<Props> = (props) => {
|
||||||
|
|
||||||
const { question, showAnswer, handleOnSubmitAnswer, passedAnswer } = props;
|
const { question, showAnswer, handleOnSubmitAnswer, passedAnswer } = props;
|
||||||
const [answer, setAnswer] = useState<AnswerType>(passedAnswer || '');
|
const [answer, setAnswer] = useState<AnswerType>(passedAnswer || []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (passedAnswer !== undefined) {
|
if (passedAnswer !== undefined) {
|
||||||
|
|
@ -58,7 +58,7 @@ const ShortAnswerQuestionDisplay: React.FC<Props> = (props) => {
|
||||||
id={question.formattedStem.text}
|
id={question.formattedStem.text}
|
||||||
name={question.formattedStem.text}
|
name={question.formattedStem.text}
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
setAnswer(e.target.value);
|
setAnswer([e.target.value]);
|
||||||
}}
|
}}
|
||||||
disabled={showAnswer}
|
disabled={showAnswer}
|
||||||
aria-label="short-answer-input"
|
aria-label="short-answer-input"
|
||||||
|
|
@ -72,7 +72,7 @@ const ShortAnswerQuestionDisplay: React.FC<Props> = (props) => {
|
||||||
handleOnSubmitAnswer &&
|
handleOnSubmitAnswer &&
|
||||||
handleOnSubmitAnswer(answer)
|
handleOnSubmitAnswer(answer)
|
||||||
}
|
}
|
||||||
disabled={answer === null || answer === ''}
|
disabled={answer === null || answer === undefined || answer.length === 0}
|
||||||
>
|
>
|
||||||
Répondre
|
Répondre
|
||||||
</Button>
|
</Button>
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
// TrueFalseQuestion.tsx
|
// TrueFalseQuestion.tsx
|
||||||
import React, { useState,useEffect } from 'react';
|
import React, { useState, useEffect } from 'react';
|
||||||
import '../questionStyle.css';
|
import '../questionStyle.css';
|
||||||
import { Button } from '@mui/material';
|
import { Button } from '@mui/material';
|
||||||
import { TrueFalseQuestion } from 'gift-pegjs';
|
import { TrueFalseQuestion } from 'gift-pegjs';
|
||||||
|
|
@ -8,37 +8,37 @@ import { AnswerType } from 'src/pages/Student/JoinRoom/JoinRoom';
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
question: TrueFalseQuestion;
|
question: TrueFalseQuestion;
|
||||||
handleOnSubmitAnswer?: (answer: AnswerType) => void;
|
handleOnSubmitAnswer?: (answer: AnswerType) => void;
|
||||||
showAnswer?: boolean;
|
showAnswer?: boolean;
|
||||||
passedAnswer?: AnswerType;
|
passedAnswer?: AnswerType;
|
||||||
}
|
}
|
||||||
|
|
||||||
const TrueFalseQuestionDisplay: React.FC<Props> = (props) => {
|
const TrueFalseQuestionDisplay: React.FC<Props> = (props) => {
|
||||||
const { question, showAnswer, handleOnSubmitAnswer, passedAnswer} =
|
const { question, showAnswer, handleOnSubmitAnswer, passedAnswer } =
|
||||||
props;
|
props;
|
||||||
|
|
||||||
|
const [answer, setAnswer] = useState<boolean | undefined>(() => {
|
||||||
|
|
||||||
|
if (passedAnswer && (passedAnswer[0] === true || passedAnswer[0] === false)) {
|
||||||
|
return passedAnswer[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
return undefined;
|
||||||
|
});
|
||||||
|
|
||||||
let disableButton = false;
|
let disableButton = false;
|
||||||
if(handleOnSubmitAnswer === undefined){
|
if (handleOnSubmitAnswer === undefined) {
|
||||||
disableButton = true;
|
disableButton = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
console.log("passedAnswer", answer);
|
console.log("passedAnswer", passedAnswer);
|
||||||
if (passedAnswer === true || passedAnswer === false) {
|
if (passedAnswer && (passedAnswer[0] === true || passedAnswer[0] === false)) {
|
||||||
setAnswer(passedAnswer);
|
setAnswer(passedAnswer[0]);
|
||||||
} else {
|
} else {
|
||||||
setAnswer(undefined);
|
setAnswer(undefined);
|
||||||
}
|
|
||||||
}, [passedAnswer, question.id]);
|
|
||||||
|
|
||||||
const [answer, setAnswer] = useState<boolean | undefined>(() => {
|
|
||||||
|
|
||||||
if (passedAnswer === true || passedAnswer === false) {
|
|
||||||
return passedAnswer;
|
|
||||||
}
|
}
|
||||||
|
}, [passedAnswer, question.id]);
|
||||||
return undefined;
|
|
||||||
});
|
|
||||||
|
|
||||||
const handleOnClickAnswer = (choice: boolean) => {
|
const handleOnClickAnswer = (choice: boolean) => {
|
||||||
setAnswer(choice);
|
setAnswer(choice);
|
||||||
|
|
@ -49,7 +49,7 @@ const TrueFalseQuestionDisplay: React.FC<Props> = (props) => {
|
||||||
return (
|
return (
|
||||||
<div className="question-container">
|
<div className="question-container">
|
||||||
<div className="question content">
|
<div className="question content">
|
||||||
<div dangerouslySetInnerHTML={{ __html: FormattedTextTemplate(question.formattedStem) }} />
|
<div dangerouslySetInnerHTML={{ __html: FormattedTextTemplate(question.formattedStem) }} />
|
||||||
</div>
|
</div>
|
||||||
<div className="choices-wrapper mb-1">
|
<div className="choices-wrapper mb-1">
|
||||||
<Button
|
<Button
|
||||||
|
|
@ -58,15 +58,14 @@ const TrueFalseQuestionDisplay: React.FC<Props> = (props) => {
|
||||||
fullWidth
|
fullWidth
|
||||||
disabled={disableButton}
|
disabled={disableButton}
|
||||||
>
|
>
|
||||||
{showAnswer? (<div> {(question.isTrue ? '✅' : '❌')}</div>):``}
|
{showAnswer ? (<div> {(question.isTrue ? '✅' : '❌')}</div>) : ``}
|
||||||
<div className={`circle ${selectedTrue}`}>V</div>
|
|
||||||
<div className={`answer-text ${selectedTrue}`}>Vrai</div>
|
<div className={`answer-text ${selectedTrue}`}>Vrai</div>
|
||||||
|
|
||||||
{showAnswer && answer && question.trueFormattedFeedback && (
|
{showAnswer && answer && question.trueFormattedFeedback && (
|
||||||
<div className="true-feedback mb-2">
|
<div className="true-feedback mb-2">
|
||||||
<div dangerouslySetInnerHTML={{ __html: FormattedTextTemplate(question.trueFormattedFeedback) }} />
|
<div dangerouslySetInnerHTML={{ __html: FormattedTextTemplate(question.trueFormattedFeedback) }} />
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
className="button-wrapper"
|
className="button-wrapper"
|
||||||
|
|
@ -75,15 +74,14 @@ const TrueFalseQuestionDisplay: React.FC<Props> = (props) => {
|
||||||
disabled={disableButton}
|
disabled={disableButton}
|
||||||
|
|
||||||
>
|
>
|
||||||
{showAnswer? (<div> {(!question.isTrue ? '✅' : '❌')}</div>):``}
|
{showAnswer ? (<div> {(!question.isTrue ? '✅' : '❌')}</div>) : ``}
|
||||||
<div className={`circle ${selectedFalse}`}>F</div>
|
|
||||||
<div className={`answer-text ${selectedFalse}`}>Faux</div>
|
<div className={`answer-text ${selectedFalse}`}>Faux</div>
|
||||||
|
|
||||||
{showAnswer && !answer && question.falseFormattedFeedback && (
|
{showAnswer && !answer && question.falseFormattedFeedback && (
|
||||||
<div className="false-feedback mb-2">
|
<div className="false-feedback mb-2">
|
||||||
<div dangerouslySetInnerHTML={{ __html: FormattedTextTemplate(question.falseFormattedFeedback) }} />
|
<div dangerouslySetInnerHTML={{ __html: FormattedTextTemplate(question.falseFormattedFeedback) }} />
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
{question.formattedGlobalFeedback && showAnswer && (
|
{question.formattedGlobalFeedback && showAnswer && (
|
||||||
|
|
@ -95,8 +93,7 @@ const TrueFalseQuestionDisplay: React.FC<Props> = (props) => {
|
||||||
<Button
|
<Button
|
||||||
variant="contained"
|
variant="contained"
|
||||||
onClick={() =>
|
onClick={() =>
|
||||||
answer !== undefined && handleOnSubmitAnswer && handleOnSubmitAnswer(answer)
|
answer !== undefined && handleOnSubmitAnswer && handleOnSubmitAnswer([answer])
|
||||||
|
|
||||||
}
|
}
|
||||||
disabled={answer === undefined}
|
disabled={answer === undefined}
|
||||||
>
|
>
|
||||||
|
|
|
||||||
94
client/src/components/ShareQuizModal/ShareQuizModal.tsx
Normal file
94
client/src/components/ShareQuizModal/ShareQuizModal.tsx
Normal file
|
|
@ -0,0 +1,94 @@
|
||||||
|
import React, { useState } from 'react';
|
||||||
|
import { Dialog, DialogTitle, DialogActions, Button, Tooltip, IconButton, Typography, Box } from '@mui/material';
|
||||||
|
import { Share } from '@mui/icons-material';
|
||||||
|
import { QuizType } from '../../Types/QuizType';
|
||||||
|
|
||||||
|
interface ShareQuizModalProps {
|
||||||
|
quiz: QuizType;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ShareQuizModal: React.FC<ShareQuizModalProps> = ({ quiz }) => {
|
||||||
|
const [_open, setOpen] = useState(false);
|
||||||
|
const [feedback, setFeedback] = useState({
|
||||||
|
open: false,
|
||||||
|
title: '',
|
||||||
|
isError: false
|
||||||
|
});
|
||||||
|
|
||||||
|
const handleCloseModal = () => setOpen(false);
|
||||||
|
|
||||||
|
const handleShareByUrl = () => {
|
||||||
|
const quizUrl = `${window.location.origin}/teacher/share/${quiz._id}`;
|
||||||
|
navigator.clipboard.writeText(quizUrl)
|
||||||
|
.then(() => {
|
||||||
|
setFeedback({
|
||||||
|
open: true,
|
||||||
|
title: 'L\'URL de partage pour le quiz',
|
||||||
|
isError: false
|
||||||
|
});
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
setFeedback({
|
||||||
|
open: true,
|
||||||
|
title: 'Une erreur est survenue lors de la copie de l\'URL.',
|
||||||
|
isError: true
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
handleCloseModal();
|
||||||
|
};
|
||||||
|
|
||||||
|
const closeFeedback = () => {
|
||||||
|
setFeedback(prev => ({ ...prev, open: false }));
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Tooltip title="Partager" placement="top">
|
||||||
|
<IconButton color="primary" onClick={handleShareByUrl} aria-label="partager quiz">
|
||||||
|
<Share />
|
||||||
|
</IconButton>
|
||||||
|
</Tooltip>
|
||||||
|
|
||||||
|
{/* Feedback Dialog */}
|
||||||
|
<Dialog
|
||||||
|
open={feedback.open}
|
||||||
|
onClose={closeFeedback}
|
||||||
|
fullWidth
|
||||||
|
maxWidth="xs"
|
||||||
|
>
|
||||||
|
<DialogTitle sx={{ textAlign: "center" }}>
|
||||||
|
<Box>
|
||||||
|
{feedback.isError ? (
|
||||||
|
<Typography color="error.main">
|
||||||
|
{feedback.title}
|
||||||
|
</Typography>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<Typography component="span">
|
||||||
|
L'URL de partage pour le quiz{' '}
|
||||||
|
</Typography>
|
||||||
|
<Typography component="span" fontWeight="bold">
|
||||||
|
{quiz.title}
|
||||||
|
</Typography>
|
||||||
|
<Typography component="span">
|
||||||
|
{' '}a été copiée.
|
||||||
|
</Typography>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
</DialogTitle>
|
||||||
|
<DialogActions sx={{ display: "flex", justifyContent: "center" }}>
|
||||||
|
<Button
|
||||||
|
onClick={closeFeedback}
|
||||||
|
variant="contained"
|
||||||
|
>
|
||||||
|
OK
|
||||||
|
</Button>
|
||||||
|
</DialogActions>
|
||||||
|
</Dialog>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default ShareQuizModal;
|
||||||
|
|
@ -26,8 +26,7 @@ const StudentWaitPage: React.FC<Props> = ({ students, launchQuiz, setQuizMode })
|
||||||
variant="contained"
|
variant="contained"
|
||||||
onClick={handleLaunchClick}
|
onClick={handleLaunchClick}
|
||||||
startIcon={<PlayArrow />}
|
startIcon={<PlayArrow />}
|
||||||
fullWidth
|
sx={{ fontWeight: 600, fontSize: 20, width: 'auto' }}
|
||||||
sx={{ fontWeight: 600, fontSize: 20 }}
|
|
||||||
>
|
>
|
||||||
Lancer
|
Lancer
|
||||||
</Button>
|
</Button>
|
||||||
|
|
|
||||||
|
|
@ -116,7 +116,7 @@ const TeacherModeQuiz: React.FC<TeacherModeQuizProps> = ({
|
||||||
</DialogContent>
|
</DialogContent>
|
||||||
<DialogActions>
|
<DialogActions>
|
||||||
<Button onClick={handleFeedbackDialogClose} color="primary">
|
<Button onClick={handleFeedbackDialogClose} color="primary">
|
||||||
OK
|
Fermer
|
||||||
</Button>
|
</Button>
|
||||||
</DialogActions>
|
</DialogActions>
|
||||||
</Dialog>
|
</Dialog>
|
||||||
|
|
|
||||||
|
|
@ -2,9 +2,8 @@
|
||||||
const ENV_VARIABLES = {
|
const ENV_VARIABLES = {
|
||||||
MODE: process.env.MODE || "production",
|
MODE: process.env.MODE || "production",
|
||||||
VITE_BACKEND_URL: process.env.VITE_BACKEND_URL || "",
|
VITE_BACKEND_URL: process.env.VITE_BACKEND_URL || "",
|
||||||
IMG_URL: process.env.MODE == "development" ? process.env.VITE_BACKEND_URL : process.env.VITE_IMG_URL,
|
BACKEND_URL: process.env.SITE_URL != undefined ? `${process.env.SITE_URL}${process.env.USE_PORTS ? `:${process.env.BACKEND_PORT}` : ''}` : process.env.VITE_BACKEND_URL || '',
|
||||||
BACKEND_URL: process.env.SITE_URL != undefined ? `${process.env.SITE_URL}${process.env.USE_PORTS ? `:${process.env.BACKEND_PORT}`:''}` : process.env.VITE_BACKEND_URL || '',
|
FRONTEND_URL: process.env.SITE_URL != undefined ? `${process.env.SITE_URL}${process.env.USE_PORTS ? `:${process.env.PORT}` : ''}` : ''
|
||||||
FRONTEND_URL: process.env.SITE_URL != undefined ? `${process.env.SITE_URL}${process.env.USE_PORTS ? `:${process.env.PORT}`:''}` : ''
|
|
||||||
};
|
};
|
||||||
|
|
||||||
console.log(`ENV_VARIABLES.VITE_BACKEND_URL=${ENV_VARIABLES.VITE_BACKEND_URL}`);
|
console.log(`ENV_VARIABLES.VITE_BACKEND_URL=${ENV_VARIABLES.VITE_BACKEND_URL}`);
|
||||||
|
|
|
||||||
|
|
@ -44,7 +44,6 @@ const SimpleLogin: React.FC = () => {
|
||||||
variant="outlined"
|
variant="outlined"
|
||||||
value={email}
|
value={email}
|
||||||
onChange={(e) => setEmail(e.target.value)}
|
onChange={(e) => setEmail(e.target.value)}
|
||||||
placeholder="Nom d'utilisateur"
|
|
||||||
sx={{ marginBottom: '1rem' }}
|
sx={{ marginBottom: '1rem' }}
|
||||||
fullWidth
|
fullWidth
|
||||||
/>
|
/>
|
||||||
|
|
@ -55,7 +54,6 @@ const SimpleLogin: React.FC = () => {
|
||||||
type="password"
|
type="password"
|
||||||
value={password}
|
value={password}
|
||||||
onChange={(e) => setPassword(e.target.value)}
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
placeholder="Nom de la salle"
|
|
||||||
sx={{ marginBottom: '1rem' }}
|
sx={{ marginBottom: '1rem' }}
|
||||||
fullWidth
|
fullWidth
|
||||||
/>
|
/>
|
||||||
|
|
|
||||||
|
|
@ -5,7 +5,7 @@ import { ENV_VARIABLES } from 'src/constants';
|
||||||
|
|
||||||
import StudentModeQuiz from 'src/components/StudentModeQuiz/StudentModeQuiz';
|
import StudentModeQuiz from 'src/components/StudentModeQuiz/StudentModeQuiz';
|
||||||
import TeacherModeQuiz from 'src/components/TeacherModeQuiz/TeacherModeQuiz';
|
import TeacherModeQuiz from 'src/components/TeacherModeQuiz/TeacherModeQuiz';
|
||||||
import webSocketService, { AnswerSubmissionToBackendType } from '../../../services/WebsocketService';
|
import webSocketService, {AnswerSubmissionToBackendType} from '../../../services/WebsocketService';
|
||||||
import DisconnectButton from 'src/components/DisconnectButton/DisconnectButton';
|
import DisconnectButton from 'src/components/DisconnectButton/DisconnectButton';
|
||||||
|
|
||||||
import './joinRoom.css';
|
import './joinRoom.css';
|
||||||
|
|
@ -13,11 +13,12 @@ import { QuestionType } from '../../../Types/QuestionType';
|
||||||
import { TextField } from '@mui/material';
|
import { TextField } from '@mui/material';
|
||||||
import LoadingButton from '@mui/lab/LoadingButton';
|
import LoadingButton from '@mui/lab/LoadingButton';
|
||||||
|
|
||||||
import LoginContainer from 'src/components/LoginContainer/LoginContainer'
|
import LoginContainer from 'src/components/LoginContainer/LoginContainer';
|
||||||
|
|
||||||
import ApiService from '../../../services/ApiService'
|
import ApiService from '../../../services/ApiService';
|
||||||
|
import { useSearchParams } from 'react-router-dom';
|
||||||
|
|
||||||
export type AnswerType = string | number | boolean;
|
export type AnswerType = Array<string | number | boolean>;
|
||||||
|
|
||||||
const JoinRoom: React.FC = () => {
|
const JoinRoom: React.FC = () => {
|
||||||
const [roomName, setRoomName] = useState('');
|
const [roomName, setRoomName] = useState('');
|
||||||
|
|
@ -30,6 +31,17 @@ const JoinRoom: React.FC = () => {
|
||||||
const [answers, setAnswers] = useState<AnswerSubmissionToBackendType[]>([]);
|
const [answers, setAnswers] = useState<AnswerSubmissionToBackendType[]>([]);
|
||||||
const [connectionError, setConnectionError] = useState<string>('');
|
const [connectionError, setConnectionError] = useState<string>('');
|
||||||
const [isConnecting, setIsConnecting] = useState<boolean>(false);
|
const [isConnecting, setIsConnecting] = useState<boolean>(false);
|
||||||
|
const [isQRCodeJoin, setIsQRCodeJoin] = useState(false);
|
||||||
|
const [searchParams] = useSearchParams();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const roomFromUrl = searchParams.get('roomName');
|
||||||
|
if (roomFromUrl) {
|
||||||
|
setRoomName(roomFromUrl);
|
||||||
|
setIsQRCodeJoin(true);
|
||||||
|
console.log('Mode QR Code détecté, salle:', roomFromUrl);
|
||||||
|
}
|
||||||
|
}, [searchParams]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
handleCreateSocket();
|
handleCreateSocket();
|
||||||
|
|
@ -42,7 +54,7 @@ const JoinRoom: React.FC = () => {
|
||||||
console.log(`JoinRoom: useEffect: questions: ${JSON.stringify(questions)}`);
|
console.log(`JoinRoom: useEffect: questions: ${JSON.stringify(questions)}`);
|
||||||
setAnswers(questions ? Array(questions.length).fill({} as AnswerSubmissionToBackendType) : []);
|
setAnswers(questions ? Array(questions.length).fill({} as AnswerSubmissionToBackendType) : []);
|
||||||
}, [questions]);
|
}, [questions]);
|
||||||
|
|
||||||
|
|
||||||
const handleCreateSocket = () => {
|
const handleCreateSocket = () => {
|
||||||
console.log(`JoinRoom: handleCreateSocket: ${ENV_VARIABLES.VITE_BACKEND_URL}`);
|
console.log(`JoinRoom: handleCreateSocket: ${ENV_VARIABLES.VITE_BACKEND_URL}`);
|
||||||
|
|
@ -101,7 +113,7 @@ const JoinRoom: React.FC = () => {
|
||||||
};
|
};
|
||||||
|
|
||||||
const disconnect = () => {
|
const disconnect = () => {
|
||||||
// localStorage.clear();
|
// localStorage.clear();
|
||||||
webSocketService.disconnect();
|
webSocketService.disconnect();
|
||||||
setSocket(null);
|
setSocket(null);
|
||||||
setQuestion(undefined);
|
setQuestion(undefined);
|
||||||
|
|
@ -198,21 +210,25 @@ const JoinRoom: React.FC = () => {
|
||||||
default:
|
default:
|
||||||
return (
|
return (
|
||||||
<LoginContainer
|
<LoginContainer
|
||||||
title='Rejoindre une salle'
|
title={isQRCodeJoin ? `Rejoindre la salle ${roomName}` : 'Rejoindre une salle'}
|
||||||
error={connectionError}>
|
error={connectionError}
|
||||||
|
>
|
||||||
<TextField
|
{/* Afficher champ salle SEULEMENT si pas de QR code */}
|
||||||
type="text"
|
{!isQRCodeJoin && (
|
||||||
label="Nom de la salle"
|
<TextField
|
||||||
variant="outlined"
|
type="text"
|
||||||
value={roomName}
|
label="Nom de la salle"
|
||||||
onChange={(e) => setRoomName(e.target.value.toUpperCase())}
|
variant="outlined"
|
||||||
placeholder="Nom de la salle"
|
value={roomName}
|
||||||
sx={{ marginBottom: '1rem' }}
|
onChange={(e) => setRoomName(e.target.value.toUpperCase())}
|
||||||
fullWidth={true}
|
placeholder="Nom de la salle"
|
||||||
onKeyDown={handleReturnKey}
|
sx={{ marginBottom: '1rem' }}
|
||||||
/>
|
fullWidth={true}
|
||||||
|
onKeyDown={handleReturnKey}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Champ username toujours visible */}
|
||||||
<TextField
|
<TextField
|
||||||
label="Nom d'utilisateur"
|
label="Nom d'utilisateur"
|
||||||
variant="outlined"
|
variant="outlined"
|
||||||
|
|
@ -229,9 +245,10 @@ const JoinRoom: React.FC = () => {
|
||||||
onClick={handleSocket}
|
onClick={handleSocket}
|
||||||
variant="contained"
|
variant="contained"
|
||||||
sx={{ marginBottom: `${connectionError && '2rem'}` }}
|
sx={{ marginBottom: `${connectionError && '2rem'}` }}
|
||||||
disabled={!username || !roomName}
|
disabled={!username || (isQRCodeJoin && !roomName)}
|
||||||
>Rejoindre</LoadingButton>
|
>
|
||||||
|
{isQRCodeJoin ? 'Rejoindre avec QR Code' : 'Rejoindre'}
|
||||||
|
</LoadingButton>
|
||||||
</LoginContainer>
|
</LoginContainer>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -38,10 +38,9 @@ import {
|
||||||
Upload,
|
Upload,
|
||||||
FolderCopy,
|
FolderCopy,
|
||||||
ContentCopy,
|
ContentCopy,
|
||||||
Edit,
|
Edit
|
||||||
Share
|
|
||||||
// DriveFileMove
|
|
||||||
} from '@mui/icons-material';
|
} from '@mui/icons-material';
|
||||||
|
import ShareQuizModal from 'src/components/ShareQuizModal/ShareQuizModal';
|
||||||
|
|
||||||
// Create a custom-styled Card component
|
// Create a custom-styled Card component
|
||||||
const CustomCard = styled(Card)({
|
const CustomCard = styled(Card)({
|
||||||
|
|
@ -66,6 +65,7 @@ const Dashboard: React.FC = () => {
|
||||||
const [selectedRoom, selectRoom] = useState<RoomType>(); // menu
|
const [selectedRoom, selectRoom] = useState<RoomType>(); // menu
|
||||||
const [errorMessage, setErrorMessage] = useState('');
|
const [errorMessage, setErrorMessage] = useState('');
|
||||||
const [showErrorDialog, setShowErrorDialog] = useState(false);
|
const [showErrorDialog, setShowErrorDialog] = useState(false);
|
||||||
|
const [isSearchVisible, setIsSearchVisible] = useState(false);
|
||||||
|
|
||||||
// Filter quizzes based on search term
|
// Filter quizzes based on search term
|
||||||
// const filteredQuizzes = quizzes.filter(quiz =>
|
// const filteredQuizzes = quizzes.filter(quiz =>
|
||||||
|
|
@ -105,7 +105,7 @@ const Dashboard: React.FC = () => {
|
||||||
|
|
||||||
fetchData();
|
fetchData();
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (rooms.length > 0 && !selectedRoom) {
|
if (rooms.length > 0 && !selectedRoom) {
|
||||||
selectRoom(rooms[rooms.length - 1]);
|
selectRoom(rooms[rooms.length - 1]);
|
||||||
|
|
@ -121,41 +121,44 @@ const Dashboard: React.FC = () => {
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Créer une salle
|
const toggleSearchVisibility = () => {
|
||||||
const createRoom = async (title: string) => {
|
setIsSearchVisible(!isSearchVisible);
|
||||||
// Créer la salle et récupérer l'objet complet
|
};
|
||||||
const newRoom = await ApiService.createRoom(title);
|
|
||||||
|
|
||||||
// Mettre à jour la liste des salles
|
|
||||||
const updatedRooms = await ApiService.getUserRooms();
|
|
||||||
setRooms(updatedRooms as RoomType[]);
|
|
||||||
|
|
||||||
// Sélectionner la nouvelle salle avec son ID
|
|
||||||
selectRoomByName(newRoom); // Utiliser l'ID de l'objet retourné
|
|
||||||
};
|
|
||||||
|
|
||||||
|
// Créer une salle
|
||||||
|
const createRoom = async (title: string) => {
|
||||||
|
// Créer la salle et récupérer l'objet complet
|
||||||
|
const newRoom = await ApiService.createRoom(title);
|
||||||
|
|
||||||
// Sélectionner une salle
|
// Mettre à jour la liste des salles
|
||||||
const selectRoomByName = (roomId: string) => {
|
const updatedRooms = await ApiService.getUserRooms();
|
||||||
const room = rooms.find(r => r._id === roomId);
|
setRooms(updatedRooms as RoomType[]);
|
||||||
selectRoom(room);
|
|
||||||
localStorage.setItem('selectedRoomId', roomId);
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleCreateRoom = async () => {
|
// Sélectionner la nouvelle salle avec son ID
|
||||||
if (newRoomTitle.trim()) {
|
selectRoomByName(newRoom); // Utiliser l'ID de l'objet retourné
|
||||||
try {
|
};
|
||||||
|
|
||||||
|
// Sélectionner une salle
|
||||||
|
const selectRoomByName = (roomId: string) => {
|
||||||
|
const room = rooms.find((r) => r._id === roomId);
|
||||||
|
selectRoom(room);
|
||||||
|
localStorage.setItem('selectedRoomId', roomId);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleCreateRoom = async () => {
|
||||||
|
if (newRoomTitle.trim()) {
|
||||||
|
try {
|
||||||
await createRoom(newRoomTitle);
|
await createRoom(newRoomTitle);
|
||||||
const userRooms = await ApiService.getUserRooms();
|
const userRooms = await ApiService.getUserRooms();
|
||||||
setRooms(userRooms as RoomType[]);
|
setRooms(userRooms as RoomType[]);
|
||||||
setOpenAddRoomDialog(false);
|
setOpenAddRoomDialog(false);
|
||||||
setNewRoomTitle('');
|
setNewRoomTitle('');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
setErrorMessage(error instanceof Error ? error.message : "Erreur inconnue");
|
setErrorMessage(error instanceof Error ? error.message : 'Erreur inconnue');
|
||||||
setShowErrorDialog(true);
|
setShowErrorDialog(true);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleSelectFolder = (event: React.ChangeEvent<HTMLSelectElement>) => {
|
const handleSelectFolder = (event: React.ChangeEvent<HTMLSelectElement>) => {
|
||||||
setSelectedFolderId(event.target.value);
|
setSelectedFolderId(event.target.value);
|
||||||
|
|
@ -398,57 +401,68 @@ const Dashboard: React.FC = () => {
|
||||||
} else {
|
} else {
|
||||||
const randomSixDigit = Math.floor(100000 + Math.random() * 900000);
|
const randomSixDigit = Math.floor(100000 + Math.random() * 900000);
|
||||||
navigate(`/teacher/manage-room/${quiz._id}/${randomSixDigit}`);
|
navigate(`/teacher/manage-room/${quiz._id}/${randomSixDigit}`);
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleShareQuiz = async (quiz: QuizType) => {
|
|
||||||
try {
|
|
||||||
const email = prompt(
|
|
||||||
`Veuillez saisir l'email de la personne avec qui vous souhaitez partager ce quiz`,
|
|
||||||
''
|
|
||||||
);
|
|
||||||
|
|
||||||
if (email) {
|
|
||||||
const result = await ApiService.ShareQuiz(quiz._id, email);
|
|
||||||
|
|
||||||
if (!result) {
|
|
||||||
window.alert(`Une erreur est survenue.\n Veuillez réessayer plus tard`);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
window.alert(`Quiz partagé avec succès!`);
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Erreur lors du partage du quiz:', error);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="dashboard">
|
<div className="dashboard">
|
||||||
<div className="title">Tableau de bord</div>
|
{/* Conteneur pour le titre et le sélecteur de salle */}
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
display: 'flex',
|
||||||
|
justifyContent: 'space-between',
|
||||||
|
alignItems: 'center',
|
||||||
|
marginBottom: '20px'
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{/* Titre tableau de bord */}
|
||||||
|
<div className="title" style={{ fontSize: '30px', fontWeight: 'bold' }}>
|
||||||
|
Tableau de bord
|
||||||
|
</div>
|
||||||
|
|
||||||
<div className="roomSelection">
|
{/* Sélecteur de salle */}
|
||||||
<label htmlFor="select-room">Sélectionner une salle: </label>
|
<div
|
||||||
<select value={selectedRoom?._id || ''} onChange={(e) => handleSelectRoom(e)}>
|
className="roomSelection"
|
||||||
<option value="" disabled>
|
style={{ display: 'flex', justifyContent: 'flex-end', gap: '15px' }}
|
||||||
-- Sélectionner une salle --
|
>
|
||||||
</option>
|
<select
|
||||||
{rooms.map((room) => (
|
value={selectedRoom?._id || ''}
|
||||||
<option key={room._id} value={room._id}>
|
onChange={(e) => handleSelectRoom(e)}
|
||||||
{room.title}
|
id="room-select"
|
||||||
|
style={{
|
||||||
|
padding: '8px 12px',
|
||||||
|
fontSize: '14px',
|
||||||
|
borderRadius: '8px',
|
||||||
|
border: '1px solid #ccc',
|
||||||
|
backgroundColor: '#fff',
|
||||||
|
maxWidth: '200px',
|
||||||
|
cursor: 'pointer',
|
||||||
|
fontWeight: '500'
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<option value="" disabled>
|
||||||
|
Sélectionner une salle
|
||||||
</option>
|
</option>
|
||||||
))}
|
{rooms.map((room) => (
|
||||||
<option value="add-room">Ajouter salle</option>
|
<option key={room._id} value={room._id}>
|
||||||
</select>
|
{room.title}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
<option
|
||||||
|
value="add-room"
|
||||||
|
style={{
|
||||||
|
color: 'black',
|
||||||
|
backgroundColor: '#f0f0f0',
|
||||||
|
fontWeight: 'bold'
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Ajouter une salle
|
||||||
|
</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{selectedRoom && (
|
{/* Dialog pour créer une salle */}
|
||||||
<div className="roomTitle">
|
|
||||||
<h2>Salle sélectionnée: {selectedRoom.title}</h2>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<Dialog open={openAddRoomDialog} onClose={() => setOpenAddRoomDialog(false)}>
|
<Dialog open={openAddRoomDialog} onClose={() => setOpenAddRoomDialog(false)}>
|
||||||
<DialogTitle>Créer une nouvelle salle</DialogTitle>
|
<DialogTitle>Créer une nouvelle salle</DialogTitle>
|
||||||
<DialogContent>
|
<DialogContent>
|
||||||
|
|
@ -473,24 +487,17 @@ const Dashboard: React.FC = () => {
|
||||||
</DialogActions>
|
</DialogActions>
|
||||||
</Dialog>
|
</Dialog>
|
||||||
|
|
||||||
<div className="search-bar">
|
<div
|
||||||
<TextField
|
style={{
|
||||||
onChange={handleSearch}
|
display: 'flex',
|
||||||
value={searchTerm}
|
justifyContent: 'flex-end',
|
||||||
placeholder="Rechercher un quiz par son titre"
|
alignItems: 'center',
|
||||||
fullWidth
|
width: '100%',
|
||||||
InputProps={{
|
gap: '20px'
|
||||||
endAdornment: (
|
}}
|
||||||
<InputAdornment position="end">
|
></div>
|
||||||
<IconButton>
|
|
||||||
<Search />
|
|
||||||
</IconButton>
|
|
||||||
</InputAdornment>
|
|
||||||
)
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
|
{/* Conteneur principal avec les actions et la liste des quiz */}
|
||||||
<div className="folder">
|
<div className="folder">
|
||||||
<div className="select">
|
<div className="select">
|
||||||
<NativeSelect
|
<NativeSelect
|
||||||
|
|
@ -498,13 +505,18 @@ const Dashboard: React.FC = () => {
|
||||||
color="primary"
|
color="primary"
|
||||||
value={selectedFolderId}
|
value={selectedFolderId}
|
||||||
onChange={handleSelectFolder}
|
onChange={handleSelectFolder}
|
||||||
|
sx={{
|
||||||
|
padding: '6px 12px',
|
||||||
|
maxWidth: '180px',
|
||||||
|
borderRadius: '8px',
|
||||||
|
borderColor: '#e0e0e0',
|
||||||
|
'&:hover': { borderColor: '#5271FF' }
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
<option value=""> Tous les dossiers... </option>
|
<option value="">Tous les dossiers...</option>
|
||||||
|
{folders.map((folder) => (
|
||||||
{folders.map((folder: FolderType) => (
|
|
||||||
<option value={folder._id} key={folder._id}>
|
<option value={folder._id} key={folder._id}>
|
||||||
{' '}
|
{folder.title}
|
||||||
{folder.title}{' '}
|
|
||||||
</option>
|
</option>
|
||||||
))}
|
))}
|
||||||
</NativeSelect>
|
</NativeSelect>
|
||||||
|
|
@ -520,65 +532,130 @@ const Dashboard: React.FC = () => {
|
||||||
|
|
||||||
<Tooltip title="Renommer dossier" placement="top">
|
<Tooltip title="Renommer dossier" placement="top">
|
||||||
<div>
|
<div>
|
||||||
<IconButton
|
<IconButton
|
||||||
color="primary"
|
color="primary"
|
||||||
onClick={handleRenameFolder}
|
onClick={handleRenameFolder}
|
||||||
disabled={selectedFolderId == ''} // cannot action on all
|
disabled={selectedFolderId == ''} // cannot action on all
|
||||||
>
|
>
|
||||||
{' '}
|
{' '}
|
||||||
<Edit />{' '}
|
<Edit />{' '}
|
||||||
</IconButton>
|
</IconButton>
|
||||||
</div>
|
</div>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
|
|
||||||
<Tooltip title="Dupliquer dossier" placement="top">
|
<Tooltip title="Dupliquer dossier" placement="top">
|
||||||
<div>
|
<div>
|
||||||
<IconButton
|
<IconButton
|
||||||
color="primary"
|
color="primary"
|
||||||
onClick={handleDuplicateFolder}
|
onClick={handleDuplicateFolder}
|
||||||
disabled={selectedFolderId == ''} // cannot action on all
|
disabled={selectedFolderId == ''} // cannot action on all
|
||||||
>
|
>
|
||||||
{' '}
|
{' '}
|
||||||
<FolderCopy />{' '}
|
<FolderCopy />{' '}
|
||||||
</IconButton>
|
</IconButton>
|
||||||
</div>
|
</div>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
|
|
||||||
<Tooltip title="Supprimer dossier" placement="top">
|
<Tooltip title="Supprimer dossier" placement="top">
|
||||||
<div>
|
<div>
|
||||||
<IconButton
|
<IconButton
|
||||||
aria-label="delete"
|
aria-label="delete"
|
||||||
color="primary"
|
color="primary"
|
||||||
onClick={handleDeleteFolder}
|
onClick={handleDeleteFolder}
|
||||||
disabled={selectedFolderId == ''} // cannot action on all
|
disabled={selectedFolderId == ''} // cannot action on all
|
||||||
>
|
>
|
||||||
{' '}
|
{' '}
|
||||||
<DeleteOutline />{' '}
|
<DeleteOutline />{' '}
|
||||||
</IconButton>
|
</IconButton>
|
||||||
</div>
|
</div>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="ajouter">
|
<div
|
||||||
<Button
|
className="search-bar"
|
||||||
variant="outlined"
|
style={{
|
||||||
color="primary"
|
display: 'flex',
|
||||||
startIcon={<Add />}
|
justifyContent: 'space-between',
|
||||||
onClick={handleCreateQuiz}
|
alignItems: 'center',
|
||||||
>
|
gap: '20px',
|
||||||
Ajouter un nouveau quiz
|
width: '100%'
|
||||||
</Button>
|
}}
|
||||||
|
>
|
||||||
|
<div style={{ flex: 1 }}>
|
||||||
|
{!isSearchVisible ? (
|
||||||
|
<IconButton
|
||||||
|
onClick={toggleSearchVisibility}
|
||||||
|
sx={{
|
||||||
|
borderRadius: '8px',
|
||||||
|
border: '1px solid #ccc',
|
||||||
|
padding: '8px 12px',
|
||||||
|
backgroundColor: '#fff',
|
||||||
|
color: '#5271FF'
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Search />
|
||||||
|
</IconButton>
|
||||||
|
) : (
|
||||||
|
<TextField
|
||||||
|
onChange={handleSearch}
|
||||||
|
value={searchTerm}
|
||||||
|
placeholder="Rechercher un quiz"
|
||||||
|
fullWidth
|
||||||
|
autoFocus
|
||||||
|
sx={{
|
||||||
|
borderRadius: '8px',
|
||||||
|
border: '1px solid #ccc',
|
||||||
|
padding: '8px 12px',
|
||||||
|
backgroundColor: '#fff',
|
||||||
|
fontWeight: 500,
|
||||||
|
width: '100%',
|
||||||
|
maxWidth: '1000px'
|
||||||
|
}}
|
||||||
|
InputProps={{
|
||||||
|
endAdornment: (
|
||||||
|
<InputAdornment position="end">
|
||||||
|
<IconButton
|
||||||
|
onClick={toggleSearchVisibility}
|
||||||
|
sx={{
|
||||||
|
borderRadius: '8px',
|
||||||
|
border: '1px solid #ccc',
|
||||||
|
backgroundColor: '#fff',
|
||||||
|
color: '#5271FF'
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Search />
|
||||||
|
</IconButton>
|
||||||
|
</InputAdornment>
|
||||||
|
)
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
<Button
|
{/* À droite : les boutons */}
|
||||||
variant="outlined"
|
<div style={{ display: 'flex', gap: '12px' }}>
|
||||||
color="primary"
|
<Button
|
||||||
startIcon={<Upload />}
|
variant="outlined"
|
||||||
onClick={handleOnImport}
|
color="primary"
|
||||||
>
|
startIcon={<Add />}
|
||||||
Import
|
onClick={handleCreateQuiz}
|
||||||
</Button>
|
sx={{ borderRadius: '8px', minWidth: 'auto', padding: '4px 12px' }}
|
||||||
|
>
|
||||||
|
Nouveau quiz
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
variant="outlined"
|
||||||
|
color="primary"
|
||||||
|
startIcon={<Upload />}
|
||||||
|
onClick={handleOnImport}
|
||||||
|
>
|
||||||
|
Importer
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="list">
|
<div className="list">
|
||||||
{Object.keys(quizzesByFolder).map((folderName) => (
|
{Object.keys(quizzesByFolder).map((folderName) => (
|
||||||
<CustomCard key={folderName} className="folder-card">
|
<CustomCard key={folderName} className="folder-card">
|
||||||
|
|
@ -587,14 +664,16 @@ const Dashboard: React.FC = () => {
|
||||||
{quizzesByFolder[folderName].map((quiz: QuizType) => (
|
{quizzesByFolder[folderName].map((quiz: QuizType) => (
|
||||||
<div className="quiz" key={quiz._id}>
|
<div className="quiz" key={quiz._id}>
|
||||||
<div className="title">
|
<div className="title">
|
||||||
<Tooltip title="Lancer quiz" placement="top">
|
<Tooltip title="Démarrer" placement="top">
|
||||||
<div>
|
<div>
|
||||||
<Button
|
<Button
|
||||||
variant="outlined"
|
variant="outlined"
|
||||||
onClick={() => handleLancerQuiz(quiz)}
|
onClick={() => handleLancerQuiz(quiz)}
|
||||||
disabled={!validateQuiz(quiz.content)}
|
disabled={!validateQuiz(quiz.content)}
|
||||||
>
|
>
|
||||||
{`${quiz.title} (${quiz.content.length} question${
|
{`${quiz.title} (${
|
||||||
|
quiz.content.length
|
||||||
|
} question${
|
||||||
quiz.content.length > 1 ? 's' : ''
|
quiz.content.length > 1 ? 's' : ''
|
||||||
})`}
|
})`}
|
||||||
</Button>
|
</Button>
|
||||||
|
|
@ -603,7 +682,7 @@ const Dashboard: React.FC = () => {
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="actions">
|
<div className="actions">
|
||||||
<Tooltip title="Télécharger quiz" placement="top">
|
<Tooltip title="Télécharger" placement="top">
|
||||||
<IconButton
|
<IconButton
|
||||||
color="primary"
|
color="primary"
|
||||||
onClick={() => downloadTxtFile(quiz)}
|
onClick={() => downloadTxtFile(quiz)}
|
||||||
|
|
@ -613,7 +692,7 @@ const Dashboard: React.FC = () => {
|
||||||
</IconButton>
|
</IconButton>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
|
|
||||||
<Tooltip title="Modifier quiz" placement="top">
|
<Tooltip title="Modifier" placement="top">
|
||||||
<IconButton
|
<IconButton
|
||||||
color="primary"
|
color="primary"
|
||||||
onClick={() => handleEditQuiz(quiz)}
|
onClick={() => handleEditQuiz(quiz)}
|
||||||
|
|
@ -623,7 +702,7 @@ const Dashboard: React.FC = () => {
|
||||||
</IconButton>
|
</IconButton>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
|
|
||||||
<Tooltip title="Dupliquer quiz" placement="top">
|
<Tooltip title="Dupliquer" placement="top">
|
||||||
<IconButton
|
<IconButton
|
||||||
color="primary"
|
color="primary"
|
||||||
onClick={() => handleDuplicateQuiz(quiz)}
|
onClick={() => handleDuplicateQuiz(quiz)}
|
||||||
|
|
@ -632,27 +711,20 @@ const Dashboard: React.FC = () => {
|
||||||
<ContentCopy />{' '}
|
<ContentCopy />{' '}
|
||||||
</IconButton>
|
</IconButton>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
|
<div className="quiz-share">
|
||||||
|
<ShareQuizModal quiz={quiz} />
|
||||||
|
</div>
|
||||||
|
|
||||||
<Tooltip title="Supprimer quiz" placement="top">
|
<Tooltip title="Supprimer" placement="top">
|
||||||
<IconButton
|
<IconButton
|
||||||
aria-label="delete"
|
aria-label="delete"
|
||||||
color="primary"
|
color="error"
|
||||||
onClick={() => handleRemoveQuiz(quiz)}
|
onClick={() => handleRemoveQuiz(quiz)}
|
||||||
>
|
>
|
||||||
{' '}
|
{' '}
|
||||||
<DeleteOutline />{' '}
|
<DeleteOutline />{' '}
|
||||||
</IconButton>
|
</IconButton>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
|
|
||||||
<Tooltip title="Partager quiz" placement="top">
|
|
||||||
<IconButton
|
|
||||||
color="primary"
|
|
||||||
onClick={() => handleShareQuiz(quiz)}
|
|
||||||
>
|
|
||||||
{' '}
|
|
||||||
<Share />{' '}
|
|
||||||
</IconButton>
|
|
||||||
</Tooltip>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
// EditorQuiz.tsx
|
// EditorQuiz.tsx
|
||||||
import React, { useState, useEffect, useRef, CSSProperties } from 'react';
|
import React, { useState, useEffect, CSSProperties } from 'react';
|
||||||
import { useParams, useNavigate } from 'react-router-dom';
|
import { useParams, useNavigate } from 'react-router-dom';
|
||||||
|
|
||||||
import { FolderType } from '../../../Types/FolderType';
|
import { FolderType } from '../../../Types/FolderType';
|
||||||
|
|
@ -9,14 +9,15 @@ import GiftCheatSheet from 'src/components/GIFTCheatSheet/GiftCheatSheet';
|
||||||
import GIFTTemplatePreview from 'src/components/GiftTemplate/GIFTTemplatePreview';
|
import GIFTTemplatePreview from 'src/components/GiftTemplate/GIFTTemplatePreview';
|
||||||
|
|
||||||
import { QuizType } from '../../../Types/QuizType';
|
import { QuizType } from '../../../Types/QuizType';
|
||||||
|
import SaveIcon from '@mui/icons-material/Save';
|
||||||
import './editorQuiz.css';
|
import './editorQuiz.css';
|
||||||
import { Button, TextField, NativeSelect, Divider, Dialog, DialogTitle, DialogActions, DialogContent } from '@mui/material';
|
import { Button, TextField, NativeSelect, Divider } from '@mui/material';
|
||||||
import ReturnButton from 'src/components/ReturnButton/ReturnButton';
|
import ReturnButton from 'src/components/ReturnButton/ReturnButton';
|
||||||
|
import ImageGalleryModal from 'src/components/ImageGallery/ImageGalleryModal/ImageGalleryModal';
|
||||||
|
|
||||||
import ApiService from '../../../services/ApiService';
|
import ApiService from '../../../services/ApiService';
|
||||||
import { escapeForGIFT } from '../../../utils/giftUtils';
|
import { escapeForGIFT } from '../../../utils/giftUtils';
|
||||||
import { Upload } from '@mui/icons-material';
|
import { ENV_VARIABLES } from 'src/constants';
|
||||||
|
|
||||||
interface EditQuizParams {
|
interface EditQuizParams {
|
||||||
id: string;
|
id: string;
|
||||||
|
|
@ -38,8 +39,6 @@ const QuizForm: React.FC = () => {
|
||||||
const handleSelectFolder = (event: React.ChangeEvent<HTMLSelectElement>) => {
|
const handleSelectFolder = (event: React.ChangeEvent<HTMLSelectElement>) => {
|
||||||
setSelectedFolder(event.target.value);
|
setSelectedFolder(event.target.value);
|
||||||
};
|
};
|
||||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
|
||||||
const [dialogOpen, setDialogOpen] = useState(false);
|
|
||||||
const [showScrollButton, setShowScrollButton] = useState(false);
|
const [showScrollButton, setShowScrollButton] = useState(false);
|
||||||
|
|
||||||
const scrollToTop = () => {
|
const scrollToTop = () => {
|
||||||
|
|
@ -166,86 +165,75 @@ const QuizForm: React.FC = () => {
|
||||||
return <div>Chargement...</div>;
|
return <div>Chargement...</div>;
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleSaveImage = async () => {
|
|
||||||
try {
|
|
||||||
const inputElement = document.getElementById('file-input') as HTMLInputElement;
|
|
||||||
|
|
||||||
if (!inputElement?.files || inputElement.files.length === 0) {
|
|
||||||
setDialogOpen(true);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!inputElement.files || inputElement.files.length === 0) {
|
|
||||||
window.alert("Veuillez d'abord choisir une image à téléverser.")
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const imageUrl = await ApiService.uploadImage(inputElement.files[0]);
|
|
||||||
|
|
||||||
// Check for errors
|
|
||||||
if(imageUrl.indexOf("ERROR") >= 0) {
|
|
||||||
window.alert(`Une erreur est survenue.\n Veuillez réessayer plus tard`)
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
setImageLinks(prevLinks => [...prevLinks, imageUrl]);
|
|
||||||
|
|
||||||
// Reset the file input element
|
|
||||||
if (fileInputRef.current) {
|
|
||||||
fileInputRef.current.value = '';
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
window.alert(`Une erreur est survenue.\n${error}\nVeuillez réessayer plus tard.`)
|
|
||||||
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleCopyToClipboard = async (link: string) => {
|
const handleCopyToClipboard = async (link: string) => {
|
||||||
navigator.clipboard.writeText(link);
|
navigator.clipboard.writeText(link);
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
const handleCopyImage = (id: string) => {
|
||||||
<div className='quizEditor'>
|
const escLink = `${ENV_VARIABLES.BACKEND_URL}/api/image/get/${id}`;
|
||||||
|
setImageLinks(prevLinks => [...prevLinks, escLink]);
|
||||||
|
}
|
||||||
|
|
||||||
<div className='editHeader'>
|
return (
|
||||||
|
<div className="quizEditor">
|
||||||
|
<div
|
||||||
|
className="editHeader"
|
||||||
|
style={{
|
||||||
|
display: 'flex',
|
||||||
|
justifyContent: 'space-between',
|
||||||
|
alignItems: 'center',
|
||||||
|
marginBottom: '32px'
|
||||||
|
}}
|
||||||
|
>
|
||||||
<ReturnButton
|
<ReturnButton
|
||||||
askConfirm
|
askConfirm
|
||||||
message={`Êtes-vous sûr de vouloir quitter l'éditeur sans sauvegarder le questionnaire?`}
|
message={`Êtes-vous sûr de vouloir quitter l'éditeur sans sauvegarder le questionnaire?`}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<div className='title'>Éditeur de quiz</div>
|
<Button
|
||||||
|
variant="contained"
|
||||||
|
onClick={handleQuizSave}
|
||||||
|
sx={{ display: 'flex', alignItems: 'center' }}
|
||||||
|
>
|
||||||
|
<SaveIcon sx={{ fontSize: 20 }} />
|
||||||
|
Enregistrer
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div className='dumb'></div>
|
<div style={{ textAlign: 'center', marginTop: '30px' }}>
|
||||||
|
<div className="title">Éditeur de quiz</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* <h2 className="subtitle">Éditeur</h2> */}
|
{/* <h2 className="subtitle">Éditeur</h2> */}
|
||||||
|
|
||||||
<TextField
|
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
|
||||||
onChange={handleQuizTitleChange}
|
<TextField
|
||||||
value={quizTitle}
|
onChange={handleQuizTitleChange}
|
||||||
placeholder="Titre du quiz"
|
value={quizTitle}
|
||||||
label="Titre du quiz"
|
color="primary"
|
||||||
fullWidth
|
placeholder="Titre du quiz"
|
||||||
/>
|
label="Titre du quiz"
|
||||||
<label>Choisir un dossier:
|
sx={{ width: '200px', marginTop: '50px' }}
|
||||||
<NativeSelect
|
/>
|
||||||
id="select-folder"
|
<NativeSelect
|
||||||
color="primary"
|
id="select-folder"
|
||||||
value={selectedFolder}
|
color="primary"
|
||||||
onChange={handleSelectFolder}
|
value={selectedFolder}
|
||||||
disabled={!isNewQuiz}
|
onChange={handleSelectFolder}
|
||||||
style={{ marginBottom: '16px' }} // Ajout de marge en bas
|
disabled={!isNewQuiz}
|
||||||
|
style={{ marginBottom: '16px', width: '200px', marginTop: '10px' }}
|
||||||
>
|
>
|
||||||
<option disabled value=""> Choisir un dossier... </option>
|
<option disabled value="">
|
||||||
|
Choisir un dossier...
|
||||||
|
</option>
|
||||||
|
{folders.map((folder: FolderType) => (
|
||||||
|
<option value={folder._id} key={folder._id}>
|
||||||
|
{folder.title}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</NativeSelect>
|
||||||
|
</div>
|
||||||
|
|
||||||
{folders.map((folder: FolderType) => (
|
|
||||||
<option value={folder._id} key={folder._id}> {folder.title} </option>
|
|
||||||
))}
|
|
||||||
</NativeSelect></label>
|
|
||||||
|
|
||||||
<Button variant="contained" onClick={handleQuizSave}>
|
|
||||||
Enregistrer
|
|
||||||
</Button>
|
|
||||||
|
|
||||||
<Divider style={{ margin: '16px 0' }} />
|
<Divider style={{ margin: '16px 0' }} />
|
||||||
|
|
||||||
|
|
@ -258,37 +246,11 @@ const QuizForm: React.FC = () => {
|
||||||
onEditorChange={handleUpdatePreview} />
|
onEditorChange={handleUpdatePreview} />
|
||||||
|
|
||||||
<div className='images'>
|
<div className='images'>
|
||||||
<div className='upload'>
|
<div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
|
||||||
<label className="dropArea">
|
<h4>Mes images :</h4>
|
||||||
<input type="file" id="file-input" className="file-input"
|
<ImageGalleryModal handleCopy={handleCopyImage} />
|
||||||
accept="image/jpeg, image/png"
|
|
||||||
multiple
|
|
||||||
ref={fileInputRef} />
|
|
||||||
|
|
||||||
<Button
|
|
||||||
variant="outlined"
|
|
||||||
aria-label='Téléverser'
|
|
||||||
onClick={handleSaveImage}>
|
|
||||||
Téléverser <Upload />
|
|
||||||
</Button>
|
|
||||||
|
|
||||||
</label>
|
|
||||||
<Dialog
|
|
||||||
open={dialogOpen}
|
|
||||||
onClose={() => setDialogOpen(false)} >
|
|
||||||
<DialogTitle>Erreur</DialogTitle>
|
|
||||||
<DialogContent>
|
|
||||||
Veuillez d'abord choisir une image à téléverser.
|
|
||||||
</DialogContent>
|
|
||||||
<DialogActions>
|
|
||||||
<Button onClick={() => setDialogOpen(false)} color="primary">
|
|
||||||
OK
|
|
||||||
</Button>
|
|
||||||
</DialogActions>
|
|
||||||
</Dialog>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<h4>Mes images :</h4>
|
|
||||||
<div>
|
<div>
|
||||||
<div>
|
<div>
|
||||||
<div style={{ display: "inline" }}>(Voir section </div>
|
<div style={{ display: "inline" }}>(Voir section </div>
|
||||||
|
|
@ -302,7 +264,7 @@ const QuizForm: React.FC = () => {
|
||||||
</div>
|
</div>
|
||||||
<ul>
|
<ul>
|
||||||
{imageLinks.map((link, index) => {
|
{imageLinks.map((link, index) => {
|
||||||
const imgTag = `} "texte de l'infobulle")`;
|
const imgTag = `[markdown]} "texte de l'infobulle") {T}`;
|
||||||
return (
|
return (
|
||||||
<li key={index}>
|
<li key={index}>
|
||||||
<code
|
<code
|
||||||
|
|
|
||||||
|
|
@ -1,12 +1,7 @@
|
||||||
import React, { useEffect, useState } from 'react';
|
import React, { useEffect, useState } from 'react';
|
||||||
import { useNavigate, useParams } from 'react-router-dom';
|
import { useNavigate, useParams } from 'react-router-dom';
|
||||||
import { Socket } from 'socket.io-client';
|
import { Socket } from 'socket.io-client';
|
||||||
import { ParsedGIFTQuestion, BaseQuestion, parse, Question } from 'gift-pegjs';
|
import { BaseQuestion, parse, Question } from 'gift-pegjs';
|
||||||
import {
|
|
||||||
isSimpleNumericalAnswer,
|
|
||||||
isRangeNumericalAnswer,
|
|
||||||
isHighLowNumericalAnswer
|
|
||||||
} from 'gift-pegjs/typeGuards';
|
|
||||||
import LiveResultsComponent from 'src/components/LiveResults/LiveResults';
|
import LiveResultsComponent from 'src/components/LiveResults/LiveResults';
|
||||||
import webSocketService, {
|
import webSocketService, {
|
||||||
AnswerReceptionFromBackendType
|
AnswerReceptionFromBackendType
|
||||||
|
|
@ -14,6 +9,7 @@ import webSocketService, {
|
||||||
import { QuizType } from '../../../Types/QuizType';
|
import { QuizType } from '../../../Types/QuizType';
|
||||||
import GroupIcon from '@mui/icons-material/Group';
|
import GroupIcon from '@mui/icons-material/Group';
|
||||||
import './manageRoom.css';
|
import './manageRoom.css';
|
||||||
|
import QRCodeIcon from '@mui/icons-material/QrCode';
|
||||||
import { ENV_VARIABLES } from 'src/constants';
|
import { ENV_VARIABLES } from 'src/constants';
|
||||||
import { StudentType, Answer } from '../../../Types/StudentType';
|
import { StudentType, Answer } from '../../../Types/StudentType';
|
||||||
import LoadingCircle from 'src/components/LoadingCircle/LoadingCircle';
|
import LoadingCircle from 'src/components/LoadingCircle/LoadingCircle';
|
||||||
|
|
@ -23,36 +19,55 @@ import DisconnectButton from 'src/components/DisconnectButton/DisconnectButton';
|
||||||
import QuestionDisplay from 'src/components/QuestionsDisplay/QuestionDisplay';
|
import QuestionDisplay from 'src/components/QuestionsDisplay/QuestionDisplay';
|
||||||
import ApiService from '../../../services/ApiService';
|
import ApiService from '../../../services/ApiService';
|
||||||
import { QuestionType } from 'src/Types/QuestionType';
|
import { QuestionType } from 'src/Types/QuestionType';
|
||||||
import { Button } from '@mui/material';
|
import {
|
||||||
import { AnswerType } from 'src/pages/Student/JoinRoom/JoinRoom';
|
Button,
|
||||||
|
Dialog,
|
||||||
|
DialogTitle,
|
||||||
|
DialogContent,
|
||||||
|
DialogContentText,
|
||||||
|
DialogActions
|
||||||
|
} from '@mui/material';
|
||||||
|
import { checkIfIsCorrect } from './useRooms';
|
||||||
|
import { QRCodeCanvas } from 'qrcode.react';
|
||||||
|
import ContentCopyIcon from '@mui/icons-material/ContentCopy';
|
||||||
|
|
||||||
const ManageRoom: React.FC = () => {
|
const ManageRoom: React.FC = () => {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const [socket, setSocket] = useState<Socket | null>(null);
|
const [socket, setSocket] = useState<Socket | null>(null);
|
||||||
const [students, setStudents] = useState<StudentType[]>([]);
|
const [students, setStudents] = useState<StudentType[]>([]);
|
||||||
const { quizId = '', roomName = '' } = useParams<{ quizId: string, roomName: string }>();
|
const { quizId = '', roomName = '' } = useParams<{ quizId: string; roomName: string }>();
|
||||||
const [quizQuestions, setQuizQuestions] = useState<QuestionType[] | undefined>();
|
const [quizQuestions, setQuizQuestions] = useState<QuestionType[] | undefined>();
|
||||||
const [quiz, setQuiz] = useState<QuizType | null>(null);
|
const [quiz, setQuiz] = useState<QuizType | null>(null);
|
||||||
const [quizMode, setQuizMode] = useState<'teacher' | 'student'>('teacher');
|
const [quizMode, setQuizMode] = useState<'teacher' | 'student'>('teacher');
|
||||||
const [connectingError, setConnectingError] = useState<string>('');
|
const [connectingError, setConnectingError] = useState<string>('');
|
||||||
const [currentQuestion, setCurrentQuestion] = useState<QuestionType | undefined>(undefined);
|
const [currentQuestion, setCurrentQuestion] = useState<QuestionType | undefined>(undefined);
|
||||||
const [quizStarted, setQuizStarted] = useState<boolean>(false);
|
const [quizStarted, setQuizStarted] = useState<boolean>(false);
|
||||||
const [formattedRoomName, setFormattedRoomName] = useState("");
|
const [formattedRoomName, setFormattedRoomName] = useState('');
|
||||||
const [newlyConnectedUser, setNewlyConnectedUser] = useState<StudentType | null>(null);
|
const [newlyConnectedUser, setNewlyConnectedUser] = useState<StudentType | null>(null);
|
||||||
|
const roomUrl = `${window.location.origin}/student/join-room?roomName=${roomName}`;
|
||||||
|
const [showQrModal, setShowQrModal] = useState(false);
|
||||||
|
const [copied, setCopied] = useState(false);
|
||||||
|
|
||||||
// Handle the newly connected user in useEffect, because it needs state info
|
const handleCopy = () => {
|
||||||
|
navigator.clipboard.writeText(roomUrl).then(() => {
|
||||||
|
setCopied(true);
|
||||||
|
setTimeout(() => setCopied(false), 2000);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
// Handle the newly connected user in useEffect, because it needs state info
|
||||||
// not available in the socket.on() callback
|
// not available in the socket.on() callback
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (newlyConnectedUser) {
|
if (newlyConnectedUser) {
|
||||||
console.log(`Handling newly connected user: ${newlyConnectedUser.name}`);
|
console.log(`Handling newly connected user: ${newlyConnectedUser.name}`);
|
||||||
setStudents((prevStudents) => [...prevStudents, newlyConnectedUser]);
|
setStudents((prevStudents) => [...prevStudents, newlyConnectedUser]);
|
||||||
|
|
||||||
// only send nextQuestion if the quiz has started
|
// only send nextQuestion if the quiz has started
|
||||||
if (!quizStarted) {
|
if (!quizStarted) {
|
||||||
console.log(`!quizStarted: returning.... `);
|
console.log(`!quizStarted: returning.... `);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (quizMode === 'teacher') {
|
if (quizMode === 'teacher') {
|
||||||
webSocketService.nextQuestion({
|
webSocketService.nextQuestion({
|
||||||
roomName: formattedRoomName,
|
roomName: formattedRoomName,
|
||||||
|
|
@ -65,7 +80,7 @@ const ManageRoom: React.FC = () => {
|
||||||
} else {
|
} else {
|
||||||
console.error('Invalid quiz mode:', quizMode);
|
console.error('Invalid quiz mode:', quizMode);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Reset the newly connected user state
|
// Reset the newly connected user state
|
||||||
setNewlyConnectedUser(null);
|
setNewlyConnectedUser(null);
|
||||||
}
|
}
|
||||||
|
|
@ -82,6 +97,15 @@ const ManageRoom: React.FC = () => {
|
||||||
verifyLogin();
|
verifyLogin();
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!roomName) {
|
||||||
|
console.error('Room name is missing!');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`Joining room: ${roomName}`);
|
||||||
|
}, [roomName]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!roomName || !quizId) {
|
if (!roomName || !quizId) {
|
||||||
window.alert(
|
window.alert(
|
||||||
|
|
@ -96,7 +120,7 @@ const ManageRoom: React.FC = () => {
|
||||||
return () => {
|
return () => {
|
||||||
disconnectWebSocket();
|
disconnectWebSocket();
|
||||||
};
|
};
|
||||||
}, [roomName, navigate]);
|
}, [roomName, navigate]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (quizId) {
|
if (quizId) {
|
||||||
|
|
@ -143,8 +167,8 @@ const ManageRoom: React.FC = () => {
|
||||||
setFormattedRoomName(roomNameUpper);
|
setFormattedRoomName(roomNameUpper);
|
||||||
console.log(`Creating WebSocket room named ${roomNameUpper}`);
|
console.log(`Creating WebSocket room named ${roomNameUpper}`);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* ATTENTION: Lire les variables d'état dans
|
* ATTENTION: Lire les variables d'état dans
|
||||||
* les .on() n'est pas une bonne pratique.
|
* les .on() n'est pas une bonne pratique.
|
||||||
* Les valeurs sont celles au moment de la création
|
* Les valeurs sont celles au moment de la création
|
||||||
* de la fonction et non au moment de l'exécution.
|
* de la fonction et non au moment de l'exécution.
|
||||||
|
|
@ -184,7 +208,6 @@ const ManageRoom: React.FC = () => {
|
||||||
};
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
|
||||||
if (socket) {
|
if (socket) {
|
||||||
console.log(`Listening for submit-answer-room in room ${formattedRoomName}`);
|
console.log(`Listening for submit-answer-room in room ${formattedRoomName}`);
|
||||||
socket.on('submit-answer-room', (answerData: AnswerReceptionFromBackendType) => {
|
socket.on('submit-answer-room', (answerData: AnswerReceptionFromBackendType) => {
|
||||||
|
|
@ -258,10 +281,12 @@ const ManageRoom: React.FC = () => {
|
||||||
if (nextQuestionIndex === undefined || nextQuestionIndex > quizQuestions.length - 1) return;
|
if (nextQuestionIndex === undefined || nextQuestionIndex > quizQuestions.length - 1) return;
|
||||||
|
|
||||||
setCurrentQuestion(quizQuestions[nextQuestionIndex]);
|
setCurrentQuestion(quizQuestions[nextQuestionIndex]);
|
||||||
webSocketService.nextQuestion({roomName: formattedRoomName,
|
webSocketService.nextQuestion({
|
||||||
questions: quizQuestions,
|
roomName: formattedRoomName,
|
||||||
questionIndex: nextQuestionIndex,
|
questions: quizQuestions,
|
||||||
isLaunch: false});
|
questionIndex: nextQuestionIndex,
|
||||||
|
isLaunch: false
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const previousQuestion = () => {
|
const previousQuestion = () => {
|
||||||
|
|
@ -271,7 +296,12 @@ const ManageRoom: React.FC = () => {
|
||||||
|
|
||||||
if (prevQuestionIndex === undefined || prevQuestionIndex < 0) return;
|
if (prevQuestionIndex === undefined || prevQuestionIndex < 0) return;
|
||||||
setCurrentQuestion(quizQuestions[prevQuestionIndex]);
|
setCurrentQuestion(quizQuestions[prevQuestionIndex]);
|
||||||
webSocketService.nextQuestion({roomName: formattedRoomName, questions: quizQuestions, questionIndex: prevQuestionIndex, isLaunch: false});
|
webSocketService.nextQuestion({
|
||||||
|
roomName: formattedRoomName,
|
||||||
|
questions: quizQuestions,
|
||||||
|
questionIndex: prevQuestionIndex,
|
||||||
|
isLaunch: false
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const initializeQuizQuestion = () => {
|
const initializeQuizQuestion = () => {
|
||||||
|
|
@ -299,7 +329,12 @@ const ManageRoom: React.FC = () => {
|
||||||
}
|
}
|
||||||
|
|
||||||
setCurrentQuestion(quizQuestions[0]);
|
setCurrentQuestion(quizQuestions[0]);
|
||||||
webSocketService.nextQuestion({roomName: formattedRoomName, questions: quizQuestions, questionIndex: 0, isLaunch: true});
|
webSocketService.nextQuestion({
|
||||||
|
roomName: formattedRoomName,
|
||||||
|
questions: quizQuestions,
|
||||||
|
questionIndex: 0,
|
||||||
|
isLaunch: true
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const launchStudentMode = () => {
|
const launchStudentMode = () => {
|
||||||
|
|
@ -336,73 +371,26 @@ const ManageRoom: React.FC = () => {
|
||||||
if (quiz?.content && quizQuestions) {
|
if (quiz?.content && quizQuestions) {
|
||||||
setCurrentQuestion(quizQuestions[questionIndex]);
|
setCurrentQuestion(quizQuestions[questionIndex]);
|
||||||
if (quizMode === 'teacher') {
|
if (quizMode === 'teacher') {
|
||||||
webSocketService.nextQuestion({roomName: formattedRoomName, questions: quizQuestions, questionIndex, isLaunch: false});
|
webSocketService.nextQuestion({
|
||||||
|
roomName: formattedRoomName,
|
||||||
|
questions: quizQuestions,
|
||||||
|
questionIndex,
|
||||||
|
isLaunch: false
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const finishQuiz = () => {
|
||||||
|
disconnectWebSocket();
|
||||||
|
navigate('/teacher/dashboard');
|
||||||
|
};
|
||||||
|
|
||||||
const handleReturn = () => {
|
const handleReturn = () => {
|
||||||
disconnectWebSocket();
|
disconnectWebSocket();
|
||||||
navigate('/teacher/dashboard');
|
navigate('/teacher/dashboard');
|
||||||
};
|
};
|
||||||
|
|
||||||
function checkIfIsCorrect(
|
|
||||||
answer: AnswerType,
|
|
||||||
idQuestion: number,
|
|
||||||
questions: QuestionType[]
|
|
||||||
): boolean {
|
|
||||||
const questionInfo = questions.find((q) =>
|
|
||||||
q.question.id ? q.question.id === idQuestion.toString() : false
|
|
||||||
) as QuestionType | undefined;
|
|
||||||
|
|
||||||
const answerText = answer.toString();
|
|
||||||
if (questionInfo) {
|
|
||||||
const question = questionInfo.question as ParsedGIFTQuestion;
|
|
||||||
if (question.type === 'TF') {
|
|
||||||
return (
|
|
||||||
(question.isTrue && answerText == 'true') ||
|
|
||||||
(!question.isTrue && answerText == 'false')
|
|
||||||
);
|
|
||||||
} else if (question.type === 'MC') {
|
|
||||||
return question.choices.some(
|
|
||||||
(choice) => choice.isCorrect && choice.formattedText.text === answerText
|
|
||||||
);
|
|
||||||
} else if (question.type === 'Numerical') {
|
|
||||||
if (isHighLowNumericalAnswer(question.choices[0])) {
|
|
||||||
const choice = question.choices[0];
|
|
||||||
const answerNumber = parseFloat(answerText);
|
|
||||||
if (!isNaN(answerNumber)) {
|
|
||||||
return (
|
|
||||||
answerNumber <= choice.numberHigh && answerNumber >= choice.numberLow
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (isRangeNumericalAnswer(question.choices[0])) {
|
|
||||||
const answerNumber = parseFloat(answerText);
|
|
||||||
const range = question.choices[0].range;
|
|
||||||
const correctAnswer = question.choices[0].number;
|
|
||||||
if (!isNaN(answerNumber)) {
|
|
||||||
return (
|
|
||||||
answerNumber <= correctAnswer + range &&
|
|
||||||
answerNumber >= correctAnswer - range
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (isSimpleNumericalAnswer(question.choices[0])) {
|
|
||||||
const answerNumber = parseFloat(answerText);
|
|
||||||
if (!isNaN(answerNumber)) {
|
|
||||||
return answerNumber === question.choices[0].number;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else if (question.type === 'Short') {
|
|
||||||
return question.choices.some(
|
|
||||||
(choice) => choice.text.toUpperCase() === answerText.toUpperCase()
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!formattedRoomName) {
|
if (!formattedRoomName) {
|
||||||
return (
|
return (
|
||||||
<div className="center">
|
<div className="center">
|
||||||
|
|
@ -427,32 +415,95 @@ const ManageRoom: React.FC = () => {
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="room">
|
<div className="room">
|
||||||
<h1>Salle : {formattedRoomName}</h1>
|
{/* En-tête avec bouton Disconnect à gauche et QR code à droite */}
|
||||||
<div className="roomHeader">
|
<div
|
||||||
|
style={{
|
||||||
|
display: 'flex',
|
||||||
|
justifyContent: 'space-between',
|
||||||
|
alignItems: 'center',
|
||||||
|
marginBottom: '20px'
|
||||||
|
}}
|
||||||
|
>
|
||||||
<DisconnectButton
|
<DisconnectButton
|
||||||
onReturn={handleReturn}
|
onReturn={handleReturn}
|
||||||
askConfirm
|
askConfirm
|
||||||
message={`Êtes-vous sûr de vouloir quitter?`}
|
message={`Êtes-vous sûr de vouloir quitter?`}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
variant="contained"
|
||||||
|
color="primary"
|
||||||
|
onClick={() => setShowQrModal(true)}
|
||||||
|
startIcon={<QRCodeIcon />}
|
||||||
|
>
|
||||||
|
Lien de participation
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Dialog
|
||||||
|
open={showQrModal}
|
||||||
|
onClose={() => setShowQrModal(false)}
|
||||||
|
aria-labelledby="qr-modal-title"
|
||||||
|
>
|
||||||
|
<DialogTitle id="qr-modal-title">
|
||||||
|
Rejoindre la salle: {formattedRoomName}
|
||||||
|
</DialogTitle>
|
||||||
|
<DialogContent>
|
||||||
|
<DialogContentText>
|
||||||
|
Scannez ce QR code ou partagez le lien ci-dessous pour rejoindre la salle :
|
||||||
|
</DialogContentText>
|
||||||
|
|
||||||
|
<div style={{ textAlign: 'center', margin: '20px 0' }}>
|
||||||
|
<QRCodeCanvas value={roomUrl} size={256} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style={{ wordBreak: 'break-all', textAlign: 'center' }}>
|
||||||
|
<h3>URL de participation :</h3>
|
||||||
|
<p>{roomUrl}</p>
|
||||||
|
<Button
|
||||||
|
variant="contained"
|
||||||
|
startIcon={<ContentCopyIcon />}
|
||||||
|
onClick={handleCopy}
|
||||||
|
style={{ marginTop: '10px' }}
|
||||||
|
>
|
||||||
|
{copied ? 'Copié !' : 'Copier le lien'}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</DialogContent>
|
||||||
|
<DialogActions>
|
||||||
|
<Button onClick={() => setShowQrModal(false)} color="primary">
|
||||||
|
Fermer
|
||||||
|
</Button>
|
||||||
|
</DialogActions>
|
||||||
|
</Dialog>
|
||||||
|
|
||||||
|
<div className="roomHeader">
|
||||||
<div
|
<div
|
||||||
className="headerContent"
|
|
||||||
style={{
|
style={{
|
||||||
display: 'flex',
|
display: 'flex',
|
||||||
justifyContent: 'space-between',
|
justifyContent: 'center',
|
||||||
alignItems: 'center',
|
alignItems: 'center',
|
||||||
width: '100%'
|
width: '100%',
|
||||||
|
marginBottom: '10px'
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{(
|
<h1 style={{ margin: 0, display: 'flex', alignItems: 'center' }}>
|
||||||
|
Salle : {formattedRoomName}
|
||||||
<div
|
<div
|
||||||
className="userCount subtitle smallText"
|
className="userCount subtitle"
|
||||||
style={{ display: "flex", justifyContent: "flex-end" }}
|
style={{
|
||||||
|
display: 'inline-flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
fontSize: '1.5rem',
|
||||||
|
fontWeight: 'bold',
|
||||||
|
marginLeft: '20px',
|
||||||
|
marginBottom: '0px'
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
<GroupIcon style={{ marginRight: '5px' }} />
|
<GroupIcon style={{ marginRight: '5px', verticalAlign: 'middle' }} />{' '}
|
||||||
{students.length}/60
|
{students.length}/60
|
||||||
</div>
|
</div>
|
||||||
)}
|
</h1>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="dumb"></div>
|
<div className="dumb"></div>
|
||||||
|
|
@ -487,7 +538,6 @@ const ManageRoom: React.FC = () => {
|
||||||
<QuestionDisplay
|
<QuestionDisplay
|
||||||
showAnswer={false}
|
showAnswer={false}
|
||||||
question={currentQuestion?.question as Question}
|
question={currentQuestion?.question as Question}
|
||||||
|
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
|
@ -529,6 +579,11 @@ const ManageRoom: React.FC = () => {
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
<div className="finishQuizButton">
|
||||||
|
<Button onClick={finishQuiz} variant="contained">
|
||||||
|
Terminer le quiz
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<StudentWaitPage
|
<StudentWaitPage
|
||||||
|
|
|
||||||
|
|
@ -2,25 +2,31 @@
|
||||||
.room .roomHeader {
|
.room .roomHeader {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: row;
|
flex-direction: column;
|
||||||
justify-content: space-between;
|
align-items: flex-start;
|
||||||
align-content: stretch
|
position: relative;
|
||||||
}
|
}
|
||||||
.room .roomHeader .returnButton {
|
.room .roomHeader .returnButton {
|
||||||
flex-basis: 10%;
|
position: absolute;
|
||||||
|
top: 10px;
|
||||||
display: flex;
|
left: 0;
|
||||||
justify-content: center;
|
z-index: 10;
|
||||||
}
|
}
|
||||||
|
|
||||||
.room .roomHeader .centerTitle {
|
.room .roomHeader .centerTitle {
|
||||||
flex-basis: auto;
|
flex-basis: auto;
|
||||||
|
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
justify-content: flex-start;
|
||||||
justify-content: flex-end;
|
align-items: flex-start;
|
||||||
align-items: flex-end;
|
margin-top: 40px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.room .roomHeader .headerContent {
|
||||||
|
width: 100%;
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
margin-top: 60px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.room .roomHeader .dumb {
|
.room .roomHeader .dumb {
|
||||||
|
|
@ -34,152 +40,16 @@
|
||||||
|
|
||||||
overflow: auto;
|
overflow: auto;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
/* align-items: center; */
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.room .finishQuizButton {
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/* .create-room-container {
|
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
|
||||||
align-items: center;
|
|
||||||
justify-content: center;
|
|
||||||
height: 100%;
|
|
||||||
}
|
|
||||||
|
|
||||||
.manage-room-container {
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
align-items: center;
|
|
||||||
height: 100%;
|
|
||||||
width: 100%;
|
|
||||||
}
|
|
||||||
|
|
||||||
.quiz-setup-container {
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
width: 100%;
|
|
||||||
margin-top: 2rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.quiz-mode-selection {
|
|
||||||
display: flex;
|
|
||||||
flex-grow: 0;
|
|
||||||
flex-direction: column;
|
|
||||||
justify-content: center;
|
|
||||||
align-items: center;
|
|
||||||
margin-top: 10px;
|
|
||||||
height: 15vh;
|
|
||||||
}
|
|
||||||
|
|
||||||
.users-container {
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
align-items: center;
|
|
||||||
flex-grow: 1;
|
|
||||||
gap: 2vh;
|
|
||||||
}
|
|
||||||
|
|
||||||
.launch-quiz-btn {
|
|
||||||
width: 20vw;
|
|
||||||
height: 11vh;
|
|
||||||
margin-top: 2vh;
|
|
||||||
box-shadow: 2px 2px 4px rgba(0, 0, 0, 0.2);
|
|
||||||
}
|
|
||||||
|
|
||||||
.mode-choice {
|
|
||||||
display: flex;
|
|
||||||
flex-direction: row;
|
|
||||||
justify-content: center;
|
|
||||||
align-items: center;
|
|
||||||
width: 20vw;
|
|
||||||
margin-top: 2vh;
|
|
||||||
}
|
|
||||||
|
|
||||||
.user {
|
|
||||||
background-color: #e7dad1;
|
|
||||||
padding: 10px 20px;
|
|
||||||
border: 1px solid black;
|
|
||||||
border-radius: 10px;
|
|
||||||
box-shadow: 2px 2px 4px rgba(0, 0, 0, 0.2);
|
|
||||||
}
|
|
||||||
|
|
||||||
.bottom-btn {
|
|
||||||
display: flex;
|
|
||||||
width: 100%;
|
|
||||||
justify-content: flex-end;
|
justify-content: flex-end;
|
||||||
margin-top: 2vh;
|
margin-left: auto;
|
||||||
}
|
|
||||||
|
|
||||||
.room-container {
|
|
||||||
position: relative;
|
|
||||||
width: 100%;
|
|
||||||
max-width: 60vw;
|
|
||||||
}
|
|
||||||
|
|
||||||
@media only screen and (max-device-width: 768px) {
|
|
||||||
.room-container {
|
|
||||||
max-width: 100%;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.room-wrapper {
|
|
||||||
display: flex;
|
|
||||||
width: 100%;
|
|
||||||
height: 100%;
|
|
||||||
justify-content: center;
|
|
||||||
}
|
|
||||||
|
|
||||||
.room-name-wrapper {
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
align-items: end;
|
|
||||||
}
|
|
||||||
.user-item {
|
|
||||||
width: 100%;
|
width: 100%;
|
||||||
}
|
}
|
||||||
|
|
||||||
.flex-column-wrapper {
|
.room h1 {
|
||||||
display: flex;
|
text-align: center;
|
||||||
flex-direction: column;
|
margin-top: 50px;
|
||||||
height: 85vh;
|
}
|
||||||
overflow: auto;
|
|
||||||
}
|
|
||||||
|
|
||||||
.preview-and-result-container {
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
gap: 2rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.nextQuestionButton {
|
|
||||||
align-self: flex-end;
|
|
||||||
margin-bottom: 5rem !important;
|
|
||||||
}
|
|
||||||
|
|
||||||
.top-container {
|
|
||||||
display: flex;
|
|
||||||
justify-content: space-between;
|
|
||||||
align-items: center;
|
|
||||||
}
|
|
||||||
|
|
||||||
@media only screen and (max-device-height: 4000px) {
|
|
||||||
.flex-column-wrapper {
|
|
||||||
height: 60vh;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@media only screen and (max-device-height: 1079px) {
|
|
||||||
.flex-column-wrapper {
|
|
||||||
height: 50vh;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@media only screen and (max-device-height: 741px) {
|
|
||||||
.flex-column-wrapper {
|
|
||||||
height: 40vh;
|
|
||||||
}
|
|
||||||
} */
|
|
||||||
|
|
@ -1,8 +1,15 @@
|
||||||
import { useContext } from 'react';
|
import { useContext } from 'react';
|
||||||
import { RoomType } from 'src/Types/RoomType';
|
import { RoomType } from 'src/Types/RoomType';
|
||||||
import { createContext } from 'react';
|
import { createContext } from 'react';
|
||||||
|
import { MultipleNumericalAnswer, NumericalAnswer, ParsedGIFTQuestion } from 'gift-pegjs';
|
||||||
//import { RoomContext } from './RoomContext';
|
import { QuestionType } from 'src/Types/QuestionType';
|
||||||
|
import { AnswerType } from 'src/pages/Student/JoinRoom/JoinRoom';
|
||||||
|
import {
|
||||||
|
isSimpleNumericalAnswer,
|
||||||
|
isRangeNumericalAnswer,
|
||||||
|
isHighLowNumericalAnswer,
|
||||||
|
isMultipleNumericalAnswer
|
||||||
|
} from 'gift-pegjs/typeGuards';
|
||||||
|
|
||||||
type RoomContextType = {
|
type RoomContextType = {
|
||||||
rooms: RoomType[];
|
rooms: RoomType[];
|
||||||
|
|
@ -18,3 +25,137 @@ export const useRooms = () => {
|
||||||
if (!context) throw new Error('useRooms must be used within a RoomProvider');
|
if (!context) throw new Error('useRooms must be used within a RoomProvider');
|
||||||
return context;
|
return context;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Checks if the answer is correct - logic varies by type of question!
|
||||||
|
* True/False: answer must match the isTrue property
|
||||||
|
* Multiple Choice: answer must match the correct choice(s)
|
||||||
|
* Numerical: answer must be within the range or equal to the number (for each type of correct answer)
|
||||||
|
* Short Answer: answer must match the correct choice(s) (case-insensitive)
|
||||||
|
* @param answer
|
||||||
|
* @param idQuestion
|
||||||
|
* @param questions
|
||||||
|
* @returns
|
||||||
|
*/
|
||||||
|
export function checkIfIsCorrect(
|
||||||
|
answer: AnswerType,
|
||||||
|
idQuestion: number,
|
||||||
|
questions: QuestionType[]
|
||||||
|
): boolean {
|
||||||
|
const questionInfo = questions.find((q) =>
|
||||||
|
q.question.id ? q.question.id === idQuestion.toString() : false
|
||||||
|
) as QuestionType | undefined;
|
||||||
|
|
||||||
|
const simpleAnswerText = answer.toString();
|
||||||
|
if (questionInfo) {
|
||||||
|
const question = questionInfo.question as ParsedGIFTQuestion;
|
||||||
|
if (question.type === 'TF') {
|
||||||
|
return (
|
||||||
|
(question.isTrue && simpleAnswerText == 'true') ||
|
||||||
|
(!question.isTrue && simpleAnswerText == 'false')
|
||||||
|
);
|
||||||
|
} else if (question.type === 'MC') {
|
||||||
|
const correctChoices = question.choices.filter((choice) => choice.isCorrect
|
||||||
|
/* || (choice.weight && choice.weight > 0)*/ // handle weighted answers
|
||||||
|
);
|
||||||
|
const multipleAnswers = Array.isArray(answer) ? answer : [answer as string];
|
||||||
|
if (correctChoices.length === 0) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
// check if all (and only) correct choices are in the multipleAnswers array
|
||||||
|
return correctChoices.length === multipleAnswers.length && correctChoices.every(
|
||||||
|
(choice) => multipleAnswers.includes(choice.formattedText.text)
|
||||||
|
);
|
||||||
|
} else if (question.type === 'Numerical') {
|
||||||
|
if (isMultipleNumericalAnswer(question.choices[0])) { // Multiple numerical answers
|
||||||
|
// check to see if answer[0] is a match for any of the choices that isCorrect
|
||||||
|
const correctChoices = question.choices.filter((choice) => isMultipleNumericalAnswer(choice) && choice.isCorrect);
|
||||||
|
if (correctChoices.length === 0) { // weird case where there are multiple numerical answers but none are correct
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return correctChoices.some((choice) => {
|
||||||
|
// narrow choice to MultipleNumericalAnswer type
|
||||||
|
const multipleNumericalChoice = choice as MultipleNumericalAnswer;
|
||||||
|
return isCorrectNumericalAnswer(multipleNumericalChoice.answer, simpleAnswerText);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (isHighLowNumericalAnswer(question.choices[0])) {
|
||||||
|
// const choice = question.choices[0];
|
||||||
|
// const answerNumber = parseFloat(simpleAnswerText);
|
||||||
|
// if (!isNaN(answerNumber)) {
|
||||||
|
// return (
|
||||||
|
// answerNumber <= choice.numberHigh && answerNumber >= choice.numberLow
|
||||||
|
// );
|
||||||
|
// }
|
||||||
|
return isCorrectNumericalAnswer(question.choices[0], simpleAnswerText);
|
||||||
|
}
|
||||||
|
if (isRangeNumericalAnswer(question.choices[0])) {
|
||||||
|
// const answerNumber = parseFloat(simpleAnswerText);
|
||||||
|
// const range = question.choices[0].range;
|
||||||
|
// const correctAnswer = question.choices[0].number;
|
||||||
|
// if (!isNaN(answerNumber)) {
|
||||||
|
// return (
|
||||||
|
// answerNumber <= correctAnswer + range &&
|
||||||
|
// answerNumber >= correctAnswer - range
|
||||||
|
// );
|
||||||
|
// }
|
||||||
|
return isCorrectNumericalAnswer(question.choices[0], simpleAnswerText);
|
||||||
|
}
|
||||||
|
if (isSimpleNumericalAnswer(question.choices[0])) {
|
||||||
|
// const answerNumber = parseFloat(simpleAnswerText);
|
||||||
|
// if (!isNaN(answerNumber)) {
|
||||||
|
// return answerNumber === question.choices[0].number;
|
||||||
|
// }
|
||||||
|
return isCorrectNumericalAnswer(question.choices[0], simpleAnswerText);
|
||||||
|
}
|
||||||
|
} else if (question.type === 'Short') {
|
||||||
|
return question.choices.some(
|
||||||
|
(choice) => choice.text.toUpperCase() === simpleAnswerText.toUpperCase()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Determines if a numerical answer is correct based on the type of numerical answer.
|
||||||
|
* @param correctAnswer The correct answer (of type NumericalAnswer).
|
||||||
|
* @param userAnswer The user's answer (as a string or number).
|
||||||
|
* @returns True if the user's answer is correct, false otherwise.
|
||||||
|
*/
|
||||||
|
export function isCorrectNumericalAnswer(
|
||||||
|
correctAnswer: NumericalAnswer,
|
||||||
|
userAnswer: string | number
|
||||||
|
): boolean {
|
||||||
|
const answerNumber = typeof userAnswer === 'string' ? parseFloat(userAnswer) : userAnswer;
|
||||||
|
|
||||||
|
if (isNaN(answerNumber)) {
|
||||||
|
return false; // User's answer is not a valid number
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isSimpleNumericalAnswer(correctAnswer)) {
|
||||||
|
// Exact match for simple numerical answers
|
||||||
|
return answerNumber === correctAnswer.number;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isRangeNumericalAnswer(correctAnswer)) {
|
||||||
|
// Check if the user's answer is within the range
|
||||||
|
const { number, range } = correctAnswer;
|
||||||
|
return answerNumber >= number - range && answerNumber <= number + range;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isHighLowNumericalAnswer(correctAnswer)) {
|
||||||
|
// Check if the user's answer is within the high-low range
|
||||||
|
const { numberLow, numberHigh } = correctAnswer;
|
||||||
|
return answerNumber >= numberLow && answerNumber <= numberHigh;
|
||||||
|
}
|
||||||
|
|
||||||
|
// if (isMultipleNumericalAnswer(correctAnswer)) {
|
||||||
|
// // Check if the user's answer matches any of the multiple numerical answers
|
||||||
|
// return correctAnswer.answer.some((choice) =>
|
||||||
|
// isCorrectNumericalAnswer(choice, answerNumber)
|
||||||
|
// );
|
||||||
|
// }
|
||||||
|
|
||||||
|
return false; // Default to false if the answer type is not recognized
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,66 +1,72 @@
|
||||||
// EditorQuiz.tsx
|
|
||||||
import React, { useState, useEffect } from 'react';
|
import React, { useState, useEffect } from 'react';
|
||||||
import { useParams, useNavigate } from 'react-router-dom';
|
import { useParams, useNavigate } from 'react-router-dom';
|
||||||
|
|
||||||
import { FolderType } from '../../../Types/FolderType';
|
import { FolderType } from '../../../Types/FolderType';
|
||||||
|
|
||||||
|
|
||||||
import './share.css';
|
import './share.css';
|
||||||
import { Button, NativeSelect } from '@mui/material';
|
import { Button, NativeSelect, Typography, Box } from '@mui/material';
|
||||||
import ReturnButton from 'src/components/ReturnButton/ReturnButton';
|
import ReturnButton from 'src/components/ReturnButton/ReturnButton';
|
||||||
|
|
||||||
import ApiService from '../../../services/ApiService';
|
import ApiService from '../../../services/ApiService';
|
||||||
|
import SaveIcon from '@mui/icons-material/Save';
|
||||||
|
|
||||||
const Share: React.FC = () => {
|
const Share: React.FC = () => {
|
||||||
console.log('Component rendered');
|
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const { id } = useParams<string>();
|
const { id } = useParams<string>();
|
||||||
|
|
||||||
const [quizTitle, setQuizTitle] = useState('');
|
const [quizTitle, setQuizTitle] = useState('');
|
||||||
const [selectedFolder, setSelectedFolder] = useState<string>('');
|
const [selectedFolder, setSelectedFolder] = useState<string>('');
|
||||||
|
|
||||||
const [folders, setFolders] = useState<FolderType[]>([]);
|
const [folders, setFolders] = useState<FolderType[]>([]);
|
||||||
|
const [quizExists, setQuizExists] = useState(false);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const fetchData = async () => {
|
const fetchData = async () => {
|
||||||
console.log("QUIZID : " + id)
|
try {
|
||||||
if (!id) {
|
if (!id) {
|
||||||
window.alert(`Une erreur est survenue.\n Le quiz n'a pas été trouvé\nVeuillez réessayer plus tard`)
|
console.error('Quiz not found for id:', id);
|
||||||
console.error('Quiz not found for id:', id);
|
navigate('/teacher/dashboard');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!ApiService.isLoggedIn()) {
|
||||||
|
navigate("/login");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const quizIds = await ApiService.getAllQuizIds();
|
||||||
|
|
||||||
|
if (quizIds.includes(id)) {
|
||||||
|
setQuizExists(true);
|
||||||
|
setLoading(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const userFolders = await ApiService.getUserFolders();
|
||||||
|
|
||||||
|
if (userFolders.length == 0) {
|
||||||
|
navigate('/teacher/dashboard');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setFolders(userFolders as FolderType[]);
|
||||||
|
|
||||||
|
const title = await ApiService.getSharedQuiz(id);
|
||||||
|
|
||||||
|
if (!title) {
|
||||||
|
console.error('Quiz not found for id:', id);
|
||||||
|
navigate('/teacher/dashboard');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setQuizTitle(title);
|
||||||
|
setLoading(false);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching data:', error);
|
||||||
|
setLoading(false);
|
||||||
navigate('/teacher/dashboard');
|
navigate('/teacher/dashboard');
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!ApiService.isLoggedIn()) {
|
|
||||||
window.alert(`Vous n'êtes pas connecté.\nVeuillez vous connecter et revenir à ce lien`);
|
|
||||||
navigate("/login");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const userFolders = await ApiService.getUserFolders();
|
|
||||||
|
|
||||||
if (userFolders.length == 0) {
|
|
||||||
window.alert(`Vous n'avez aucun dossier.\nVeuillez en créer un et revenir à ce lien`)
|
|
||||||
navigate('/teacher/dashboard');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
setFolders(userFolders as FolderType[]);
|
|
||||||
|
|
||||||
const title = await ApiService.getSharedQuiz(id);
|
|
||||||
|
|
||||||
if (!title) {
|
|
||||||
window.alert(`Une erreur est survenue.\n Veuillez réessayer plus tard`)
|
|
||||||
console.error('Quiz not found for id:', id);
|
|
||||||
navigate('/teacher/dashboard');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
setQuizTitle(title);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
fetchData();
|
fetchData();
|
||||||
}, []);
|
}, [id, navigate]);
|
||||||
|
|
||||||
const handleSelectFolder = (event: React.ChangeEvent<HTMLSelectElement>) => {
|
const handleSelectFolder = (event: React.ChangeEvent<HTMLSelectElement>) => {
|
||||||
setSelectedFolder(event.target.value);
|
setSelectedFolder(event.target.value);
|
||||||
|
|
@ -68,14 +74,12 @@ const Share: React.FC = () => {
|
||||||
|
|
||||||
const handleQuizSave = async () => {
|
const handleQuizSave = async () => {
|
||||||
try {
|
try {
|
||||||
|
|
||||||
if (selectedFolder == '') {
|
if (selectedFolder == '') {
|
||||||
alert("Veuillez choisir un dossier");
|
alert("Veuillez choisir un dossier");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!id) {
|
if (!id) {
|
||||||
window.alert(`Une erreur est survenue.\n Le quiz n'a pas été trouvé\nVeuillez réessayer plus tard`)
|
|
||||||
console.error('Quiz not found for id:', id);
|
console.error('Quiz not found for id:', id);
|
||||||
navigate('/teacher/dashboard');
|
navigate('/teacher/dashboard');
|
||||||
return;
|
return;
|
||||||
|
|
@ -85,49 +89,92 @@ const Share: React.FC = () => {
|
||||||
navigate('/teacher/dashboard');
|
navigate('/teacher/dashboard');
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
window.alert(`Une erreur est survenue.\n Veuillez réessayer plus tard`)
|
|
||||||
console.log(error)
|
console.log(error)
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return <div className='quizImport'>Chargement...</div>;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (quizExists) {
|
||||||
|
return (
|
||||||
|
<div className='quizImport'>
|
||||||
|
<div className='importHeader'>
|
||||||
|
<ReturnButton />
|
||||||
|
<div className='titleContainer'>
|
||||||
|
<div className='mainTitle'>Quiz déjà existant</div>
|
||||||
|
</div>
|
||||||
|
<div className='dumb'></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className='editSection'>
|
||||||
|
<Box sx={{
|
||||||
|
textAlign: 'center',
|
||||||
|
padding: 3,
|
||||||
|
maxWidth: 600,
|
||||||
|
margin: '0 auto'
|
||||||
|
}}>
|
||||||
|
<Typography variant="h6" gutterBottom>
|
||||||
|
Le quiz que vous essayez d'importer existe déjà sur votre compte.
|
||||||
|
</Typography>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
variant="contained"
|
||||||
|
onClick={() => navigate('/teacher/dashboard')}
|
||||||
|
sx={{ mt: 3, mb: 1 }}
|
||||||
|
fullWidth
|
||||||
|
>
|
||||||
|
Retour au tableau de bord
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<Typography variant="body2" color="text.secondary">
|
||||||
|
Si vous souhaitiez créer une copie de ce quiz,
|
||||||
|
vous pouvez utiliser la fonction "Dupliquer" disponible
|
||||||
|
dans votre tableau de bord.
|
||||||
|
</Typography>
|
||||||
|
</Box>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className='quizImport'>
|
<div className='quizImport'>
|
||||||
|
|
||||||
<div className='importHeader'>
|
<div className='importHeader'>
|
||||||
<ReturnButton />
|
<ReturnButton />
|
||||||
|
<div className='titleContainer'>
|
||||||
<div className='title'>Importer quiz: {quizTitle}</div>
|
<div className='mainTitle'>Importation du Quiz: {quizTitle}</div>
|
||||||
|
<div className='subTitle'>
|
||||||
|
Vous êtes sur le point d'importer le quiz <strong>{quizTitle}</strong>, choisissez un dossier dans lequel enregistrer ce nouveau quiz.
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
<div className='dumb'></div>
|
<div className='dumb'></div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className='editSection'>
|
<div className='editSection'>
|
||||||
|
<div className='formContainer'>
|
||||||
<div>
|
|
||||||
|
|
||||||
<NativeSelect
|
<NativeSelect
|
||||||
id="select-folder"
|
id="select-folder"
|
||||||
color="primary"
|
color="primary"
|
||||||
value={selectedFolder}
|
value={selectedFolder}
|
||||||
onChange={handleSelectFolder}
|
onChange={handleSelectFolder}
|
||||||
|
className="folderSelect"
|
||||||
>
|
>
|
||||||
<option disabled value=""> Choisir un dossier... </option>
|
<option disabled value=""> Choisir un dossier... </option>
|
||||||
|
|
||||||
{folders.map((folder: FolderType) => (
|
{folders.map((folder: FolderType) => (
|
||||||
<option value={folder._id} key={folder._id}> {folder.title} </option>
|
<option value={folder._id} key={folder._id}> {folder.title} </option>
|
||||||
))}
|
))}
|
||||||
</NativeSelect>
|
</NativeSelect>
|
||||||
|
|
||||||
<Button variant="contained" onClick={handleQuizSave}>
|
<Button variant="contained" onClick={handleQuizSave} className="saveButton">
|
||||||
|
{<SaveIcon sx={{ fontSize: 20, marginRight: '8px' }} />}
|
||||||
Enregistrer
|
Enregistrer
|
||||||
</Button>
|
</Button>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export default Share;
|
export default Share;
|
||||||
|
|
@ -3,19 +3,58 @@
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: row;
|
flex-direction: row;
|
||||||
justify-content: space-between;
|
justify-content: space-between;
|
||||||
align-content: stretch
|
align-content: stretch;
|
||||||
}
|
}
|
||||||
|
|
||||||
.quizImport .importHeader .returnButton {
|
.quizImport .importHeader .returnButton {
|
||||||
flex-basis: 10%;
|
flex-basis: 10%;
|
||||||
|
|
||||||
display: flex;
|
display: flex;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
}
|
}
|
||||||
|
|
||||||
.quizImport .importHeader .title {
|
.quizImport .importHeader .titleContainer {
|
||||||
flex-basis: auto;
|
flex-basis: auto;
|
||||||
|
text-align: center; /* Center the title and subtitle */
|
||||||
|
}
|
||||||
|
|
||||||
|
.quizImport .importHeader .mainTitle {
|
||||||
|
font-size: 44px; /* Larger font size for the main title */
|
||||||
|
font-weight: bold; /* Remove bold */
|
||||||
|
color: #333; /* Slightly paler color */
|
||||||
|
}
|
||||||
|
|
||||||
|
.quizImport .importHeader .subTitle {
|
||||||
|
font-size: 14px; /* Smaller font size for the subtitle */
|
||||||
|
color: #666; /* Pale gray color */
|
||||||
|
margin-top: 8px; /* Add some space between the title and subtitle */
|
||||||
}
|
}
|
||||||
|
|
||||||
.quizImport .importHeader .dumb {
|
.quizImport .importHeader .dumb {
|
||||||
flex-basis: 10%;
|
flex-basis: 10%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.quizImport .editSection {
|
||||||
|
display: flex;
|
||||||
|
justify-content: center;
|
||||||
|
align-items: center;
|
||||||
|
margin-top: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.quizImport .editSection .formContainer {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
gap: 20px; /* Adds space between the select and button */
|
||||||
|
width: 100%;
|
||||||
|
max-width: 400px; /* Limits the width of the form container */
|
||||||
|
}
|
||||||
|
|
||||||
|
.quizImport .editSection .folderSelect {
|
||||||
|
width: 100%; /* Ensures the select element takes the full width of its container */
|
||||||
|
}
|
||||||
|
|
||||||
|
.quizImport .editSection .saveButton {
|
||||||
|
width: 100%; /* Makes the button take the full width of its container */
|
||||||
|
padding: 10px 20px; /* Increases the button's padding for a larger appearance */
|
||||||
|
font-size: 16px; /* Increases the font size for better visibility */
|
||||||
}
|
}
|
||||||
|
|
@ -76,8 +76,6 @@ class ApiService {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log("ApiService: isLoggedIn: Token:", token);
|
|
||||||
|
|
||||||
// Update token expiry
|
// Update token expiry
|
||||||
this.saveToken(token);
|
this.saveToken(token);
|
||||||
|
|
||||||
|
|
@ -93,7 +91,6 @@ class ApiService {
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
console.log("ApiService: isLoggedInTeacher: Token:", token);
|
|
||||||
const decodedToken = jwtDecode(token) as { roles: string[] };
|
const decodedToken = jwtDecode(token) as { roles: string[] };
|
||||||
|
|
||||||
/////// REMOVE BELOW
|
/////// REMOVE BELOW
|
||||||
|
|
@ -105,7 +102,6 @@ class ApiService {
|
||||||
const userRoles = decodedToken.roles;
|
const userRoles = decodedToken.roles;
|
||||||
const requiredRole = 'teacher';
|
const requiredRole = 'teacher';
|
||||||
|
|
||||||
console.log("ApiService: isLoggedInTeacher: UserRoles:", userRoles);
|
|
||||||
if (!userRoles || !userRoles.includes(requiredRole)) {
|
if (!userRoles || !userRoles.includes(requiredRole)) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
@ -165,6 +161,22 @@ class ApiService {
|
||||||
return object.username;
|
return object.username;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public getUserID(): string {
|
||||||
|
const token = localStorage.getItem("jwt");
|
||||||
|
|
||||||
|
if (!token) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
const jsonObj = jwtDecode(token) as { userId: string };
|
||||||
|
|
||||||
|
if (!jsonObj.userId) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
return jsonObj.userId;
|
||||||
|
}
|
||||||
|
|
||||||
// Route to know if rooms need authentication to join
|
// Route to know if rooms need authentication to join
|
||||||
public async getRoomsRequireAuth(): Promise<any> {
|
public async getRoomsRequireAuth(): Promise<any> {
|
||||||
const url: string = this.constructRequestUrl(`/auth/getRoomsRequireAuth`);
|
const url: string = this.constructRequestUrl(`/auth/getRoomsRequireAuth`);
|
||||||
|
|
@ -201,7 +213,6 @@ class ApiService {
|
||||||
|
|
||||||
const result: AxiosResponse = await axios.post(url, body, { headers: headers });
|
const result: AxiosResponse = await axios.post(url, body, { headers: headers });
|
||||||
|
|
||||||
console.log(result);
|
|
||||||
if (result.status == 200) {
|
if (result.status == 200) {
|
||||||
//window.location.href = result.request.responseURL;
|
//window.location.href = result.request.responseURL;
|
||||||
window.location.href = '/login';
|
window.location.href = '/login';
|
||||||
|
|
@ -213,7 +224,6 @@ class ApiService {
|
||||||
return true;
|
return true;
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log("Error details: ", error);
|
|
||||||
|
|
||||||
if (axios.isAxiosError(error)) {
|
if (axios.isAxiosError(error)) {
|
||||||
const err = error as AxiosError;
|
const err = error as AxiosError;
|
||||||
|
|
@ -576,7 +586,6 @@ public async login(email: string, password: string): Promise<any> {
|
||||||
const headers = this.constructRequestHeaders();
|
const headers = this.constructRequestHeaders();
|
||||||
const body = { folderId };
|
const body = { folderId };
|
||||||
|
|
||||||
console.log(headers);
|
|
||||||
const result: AxiosResponse = await axios.post(url, body, { headers: headers });
|
const result: AxiosResponse = await axios.post(url, body, { headers: headers });
|
||||||
|
|
||||||
if (result.status !== 200) {
|
if (result.status !== 200) {
|
||||||
|
|
@ -866,36 +875,6 @@ public async login(email: string, password: string): Promise<any> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async ShareQuiz(quizId: string, email: string): Promise<ApiResponse> {
|
|
||||||
try {
|
|
||||||
if (!quizId || !email) {
|
|
||||||
throw new Error(`quizId and email are required.`);
|
|
||||||
}
|
|
||||||
|
|
||||||
const url: string = this.constructRequestUrl(`/quiz/Share`);
|
|
||||||
const headers = this.constructRequestHeaders();
|
|
||||||
const body = { quizId, email };
|
|
||||||
|
|
||||||
const result: AxiosResponse = await axios.put(url, body, { headers: headers });
|
|
||||||
|
|
||||||
if (result.status !== 200) {
|
|
||||||
throw new Error(`Update and share quiz failed. Status: ${result.status}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
return true;
|
|
||||||
} catch (error) {
|
|
||||||
console.log("Error details: ", error);
|
|
||||||
|
|
||||||
if (axios.isAxiosError(error)) {
|
|
||||||
const err = error as AxiosError;
|
|
||||||
const data = err.response?.data as { error: string } | undefined;
|
|
||||||
return data?.error || 'Unknown server error during request.';
|
|
||||||
}
|
|
||||||
|
|
||||||
return `An unexpected error occurred.`;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async getSharedQuiz(quizId: string): Promise<string> {
|
async getSharedQuiz(quizId: string): Promise<string> {
|
||||||
try {
|
try {
|
||||||
if (!quizId) {
|
if (!quizId) {
|
||||||
|
|
@ -1192,33 +1171,11 @@ public async login(email: string, password: string): Promise<any> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public async getUsers(): Promise<AdminTableType[]> {
|
public async getImages(page: number, limit: number): Promise<ImagesResponse> {
|
||||||
try {
|
return this.isAdmin() ? this.getAllImages(page, limit) : this.getUserImages(page, limit);
|
||||||
|
|
||||||
const url: string = this.constructRequestUrl(`/admin/getUsers`);
|
|
||||||
const headers = this.constructRequestHeaders();
|
|
||||||
const result: AxiosResponse = await axios.get(url, { headers });
|
|
||||||
|
|
||||||
if (result.status !== 200) {
|
|
||||||
throw new Error(`L'obtention des titres des salles a échoué. Status: ${result.status}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
return result.data.users;
|
|
||||||
} catch (error) {
|
|
||||||
console.log("Error details: ", error);
|
|
||||||
|
|
||||||
if (axios.isAxiosError(error)) {
|
|
||||||
const err = error as AxiosError;
|
|
||||||
const data = err.response?.data as { error: string } | undefined;
|
|
||||||
const msg = data?.error || 'Erreur serveur inconnue lors de la requête.';
|
|
||||||
throw new Error(`L'enregistrement a échoué. Status: ${msg}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
throw new Error(`ERROR : Une erreur inattendue s'est produite.`);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public async getImages(page: number, limit: number): Promise<ImagesResponse> {
|
public async getAllImages(page: number, limit: number): Promise<ImagesResponse> {
|
||||||
try {
|
try {
|
||||||
const url: string = this.constructRequestUrl(`/admin/getImages`);
|
const url: string = this.constructRequestUrl(`/admin/getImages`);
|
||||||
const headers = this.constructRequestHeaders();
|
const headers = this.constructRequestHeaders();
|
||||||
|
|
@ -1247,7 +1204,126 @@ public async login(email: string, password: string): Promise<any> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async getUserImages(page: number, limit: number): Promise<ImagesResponse> {
|
||||||
|
try {
|
||||||
|
const url: string = this.constructRequestUrl(`/image/getUserImages`);
|
||||||
|
const headers = this.constructRequestHeaders();
|
||||||
|
let params : ImagesParams = { page: page, limit: limit };
|
||||||
|
|
||||||
|
const uid = this.getUserID();
|
||||||
|
if(uid !== ''){
|
||||||
|
params.uid = uid;
|
||||||
|
}
|
||||||
|
|
||||||
|
const result: AxiosResponse = await axios.get(url, { params: params, headers: headers });
|
||||||
|
|
||||||
|
if (result.status !== 200) {
|
||||||
|
throw new Error(`L'affichage des images de l'utilisateur a échoué. Status: ${result.status}`);
|
||||||
|
}
|
||||||
|
const images = result.data;
|
||||||
|
|
||||||
|
return images;
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.log("Error details: ", error);
|
||||||
|
|
||||||
|
if (axios.isAxiosError(error)) {
|
||||||
|
const err = error as AxiosError;
|
||||||
|
const data = err.response?.data as { error: string } | undefined;
|
||||||
|
const msg = data?.error || 'Erreur serveur inconnue lors de la requête.';
|
||||||
|
throw new Error(`L'enregistrement a échoué. Status: ${msg}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error(`ERROR : Une erreur inattendue s'est produite.`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public async deleteImage(imgId: string): Promise<ApiResponse> {
|
public async deleteImage(imgId: string): Promise<ApiResponse> {
|
||||||
|
return this.isAdmin() ? this.deleteAnyImage(imgId) : this.deleteUserImage(imgId);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async deleteUserImage(imgId: string): Promise<ApiResponse> {
|
||||||
|
try {
|
||||||
|
const url: string = this.constructRequestUrl(`/image/delete`);
|
||||||
|
const headers = this.constructRequestHeaders();
|
||||||
|
const uid = this.getUserID();
|
||||||
|
let params = { uid: uid, imgId: imgId };
|
||||||
|
|
||||||
|
const result: AxiosResponse = await axios.delete(url, { params: params, headers: headers });
|
||||||
|
|
||||||
|
if (result.status !== 200) {
|
||||||
|
throw new Error(`La suppression de l'image a échoué. Status: ${result.status}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const deleted = result.data.deleted;
|
||||||
|
return deleted;
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.log("Error details: ", error);
|
||||||
|
|
||||||
|
if (axios.isAxiosError(error)) {
|
||||||
|
const err = error as AxiosError;
|
||||||
|
const data = err.response?.data as { error: string } | undefined;
|
||||||
|
const msg = data?.error || 'Erreur serveur inconnue lors de la requête.';
|
||||||
|
throw new Error(`L'enregistrement a échoué. Status: ${msg}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error(`ERROR : Une erreur inattendue s'est produite.`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async getAllQuizIds(): Promise<string[]> {
|
||||||
|
try {
|
||||||
|
const folders = await this.getUserFolders();
|
||||||
|
|
||||||
|
const allQuizIds: string[] = [];
|
||||||
|
|
||||||
|
if (Array.isArray(folders)) {
|
||||||
|
for (const folder of folders) {
|
||||||
|
const folderQuizzes = await this.getFolderContent(folder._id);
|
||||||
|
|
||||||
|
if (Array.isArray(folderQuizzes)) {
|
||||||
|
allQuizIds.push(...folderQuizzes.map(quiz => quiz._id));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
console.error('Failed to get user folders:', folders);
|
||||||
|
}
|
||||||
|
|
||||||
|
return allQuizIds;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to get all quiz ids:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async getUsers(): Promise<AdminTableType[]> {
|
||||||
|
try {
|
||||||
|
|
||||||
|
const url: string = this.constructRequestUrl(`/admin/getUsers`);
|
||||||
|
const headers = this.constructRequestHeaders();
|
||||||
|
const result: AxiosResponse = await axios.get(url, { headers });
|
||||||
|
|
||||||
|
if (result.status !== 200) {
|
||||||
|
throw new Error(`L'obtention des titres des salles a échoué. Status: ${result.status}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return result.data.users;
|
||||||
|
} catch (error) {
|
||||||
|
console.log("Error details: ", error);
|
||||||
|
|
||||||
|
if (axios.isAxiosError(error)) {
|
||||||
|
const err = error as AxiosError;
|
||||||
|
const data = err.response?.data as { error: string } | undefined;
|
||||||
|
const msg = data?.error || 'Erreur serveur inconnue lors de la requête.';
|
||||||
|
throw new Error(`L'enregistrement a échoué. Status: ${msg}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error(`ERROR : Une erreur inattendue s'est produite.`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async deleteAnyImage(imgId: string): Promise<ApiResponse> {
|
||||||
try {
|
try {
|
||||||
const url: string = this.constructRequestUrl(`/admin/deleteImage`);
|
const url: string = this.constructRequestUrl(`/admin/deleteImage`);
|
||||||
const headers = this.constructRequestHeaders();
|
const headers = this.constructRequestHeaders();
|
||||||
|
|
|
||||||
|
|
@ -55,7 +55,7 @@ services:
|
||||||
image: mongo
|
image: mongo
|
||||||
container_name: mongo
|
container_name: mongo
|
||||||
ports:
|
ports:
|
||||||
- "27017:27017"
|
- "27019:27017"
|
||||||
tty: true
|
tty: true
|
||||||
volumes:
|
volumes:
|
||||||
- mongodb_data:/data/db
|
- mongodb_data:/data/db
|
||||||
|
|
|
||||||
329
package-lock.json
generated
Normal file
329
package-lock.json
generated
Normal file
|
|
@ -0,0 +1,329 @@
|
||||||
|
{
|
||||||
|
"name": "EvalueTonSavoir",
|
||||||
|
"lockfileVersion": 3,
|
||||||
|
"requires": true,
|
||||||
|
"packages": {
|
||||||
|
"": {
|
||||||
|
"dependencies": {
|
||||||
|
"axios-mock-adapter": "^2.1.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/asynckit": {
|
||||||
|
"version": "0.4.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
|
||||||
|
"integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==",
|
||||||
|
"peer": true
|
||||||
|
},
|
||||||
|
"node_modules/axios": {
|
||||||
|
"version": "1.8.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/axios/-/axios-1.8.2.tgz",
|
||||||
|
"integrity": "sha512-ls4GYBm5aig9vWx8AWDSGLpnpDQRtWAfrjU+EuytuODrFBkqesN2RkOQCBzrA1RQNHw1SmRMSDDDSwzNAYQ6Rg==",
|
||||||
|
"peer": true,
|
||||||
|
"dependencies": {
|
||||||
|
"follow-redirects": "^1.15.6",
|
||||||
|
"form-data": "^4.0.0",
|
||||||
|
"proxy-from-env": "^1.1.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/axios-mock-adapter": {
|
||||||
|
"version": "2.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/axios-mock-adapter/-/axios-mock-adapter-2.1.0.tgz",
|
||||||
|
"integrity": "sha512-AZUe4OjECGCNNssH8SOdtneiQELsqTsat3SQQCWLPjN436/H+L9AjWfV7bF+Zg/YL9cgbhrz5671hoh+Tbn98w==",
|
||||||
|
"dependencies": {
|
||||||
|
"fast-deep-equal": "^3.1.3",
|
||||||
|
"is-buffer": "^2.0.5"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"axios": ">= 0.17.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/call-bind-apply-helpers": {
|
||||||
|
"version": "1.0.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
|
||||||
|
"integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",
|
||||||
|
"peer": true,
|
||||||
|
"dependencies": {
|
||||||
|
"es-errors": "^1.3.0",
|
||||||
|
"function-bind": "^1.1.2"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 0.4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/combined-stream": {
|
||||||
|
"version": "1.0.8",
|
||||||
|
"resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
|
||||||
|
"integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",
|
||||||
|
"peer": true,
|
||||||
|
"dependencies": {
|
||||||
|
"delayed-stream": "~1.0.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 0.8"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/delayed-stream": {
|
||||||
|
"version": "1.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
|
||||||
|
"integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==",
|
||||||
|
"peer": true,
|
||||||
|
"engines": {
|
||||||
|
"node": ">=0.4.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/dunder-proto": {
|
||||||
|
"version": "1.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
|
||||||
|
"integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",
|
||||||
|
"peer": true,
|
||||||
|
"dependencies": {
|
||||||
|
"call-bind-apply-helpers": "^1.0.1",
|
||||||
|
"es-errors": "^1.3.0",
|
||||||
|
"gopd": "^1.2.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 0.4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/es-define-property": {
|
||||||
|
"version": "1.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
|
||||||
|
"integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
|
||||||
|
"peer": true,
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 0.4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/es-errors": {
|
||||||
|
"version": "1.3.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",
|
||||||
|
"integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
|
||||||
|
"peer": true,
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 0.4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/es-object-atoms": {
|
||||||
|
"version": "1.1.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz",
|
||||||
|
"integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==",
|
||||||
|
"peer": true,
|
||||||
|
"dependencies": {
|
||||||
|
"es-errors": "^1.3.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 0.4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/es-set-tostringtag": {
|
||||||
|
"version": "2.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz",
|
||||||
|
"integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==",
|
||||||
|
"peer": true,
|
||||||
|
"dependencies": {
|
||||||
|
"es-errors": "^1.3.0",
|
||||||
|
"get-intrinsic": "^1.2.6",
|
||||||
|
"has-tostringtag": "^1.0.2",
|
||||||
|
"hasown": "^2.0.2"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 0.4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/fast-deep-equal": {
|
||||||
|
"version": "3.1.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
|
||||||
|
"integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="
|
||||||
|
},
|
||||||
|
"node_modules/follow-redirects": {
|
||||||
|
"version": "1.15.9",
|
||||||
|
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.9.tgz",
|
||||||
|
"integrity": "sha512-gew4GsXizNgdoRyqmyfMHyAmXsZDk6mHkSxZFCzW9gwlbtOW44CDtYavM+y+72qD/Vq2l550kMF52DT8fOLJqQ==",
|
||||||
|
"funding": [
|
||||||
|
{
|
||||||
|
"type": "individual",
|
||||||
|
"url": "https://github.com/sponsors/RubenVerborgh"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"peer": true,
|
||||||
|
"engines": {
|
||||||
|
"node": ">=4.0"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"debug": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/form-data": {
|
||||||
|
"version": "4.0.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.2.tgz",
|
||||||
|
"integrity": "sha512-hGfm/slu0ZabnNt4oaRZ6uREyfCj6P4fT/n6A1rGV+Z0VdGXjfOhVUpkn6qVQONHGIFwmveGXyDs75+nr6FM8w==",
|
||||||
|
"peer": true,
|
||||||
|
"dependencies": {
|
||||||
|
"asynckit": "^0.4.0",
|
||||||
|
"combined-stream": "^1.0.8",
|
||||||
|
"es-set-tostringtag": "^2.1.0",
|
||||||
|
"mime-types": "^2.1.12"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 6"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/function-bind": {
|
||||||
|
"version": "1.1.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
|
||||||
|
"integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
|
||||||
|
"peer": true,
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/sponsors/ljharb"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/get-intrinsic": {
|
||||||
|
"version": "1.3.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
|
||||||
|
"integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",
|
||||||
|
"peer": true,
|
||||||
|
"dependencies": {
|
||||||
|
"call-bind-apply-helpers": "^1.0.2",
|
||||||
|
"es-define-property": "^1.0.1",
|
||||||
|
"es-errors": "^1.3.0",
|
||||||
|
"es-object-atoms": "^1.1.1",
|
||||||
|
"function-bind": "^1.1.2",
|
||||||
|
"get-proto": "^1.0.1",
|
||||||
|
"gopd": "^1.2.0",
|
||||||
|
"has-symbols": "^1.1.0",
|
||||||
|
"hasown": "^2.0.2",
|
||||||
|
"math-intrinsics": "^1.1.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 0.4"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/sponsors/ljharb"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/get-proto": {
|
||||||
|
"version": "1.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",
|
||||||
|
"integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",
|
||||||
|
"peer": true,
|
||||||
|
"dependencies": {
|
||||||
|
"dunder-proto": "^1.0.1",
|
||||||
|
"es-object-atoms": "^1.0.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 0.4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/gopd": {
|
||||||
|
"version": "1.2.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
|
||||||
|
"integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",
|
||||||
|
"peer": true,
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 0.4"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/sponsors/ljharb"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/has-symbols": {
|
||||||
|
"version": "1.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",
|
||||||
|
"integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",
|
||||||
|
"peer": true,
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 0.4"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/sponsors/ljharb"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/has-tostringtag": {
|
||||||
|
"version": "1.0.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz",
|
||||||
|
"integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==",
|
||||||
|
"peer": true,
|
||||||
|
"dependencies": {
|
||||||
|
"has-symbols": "^1.0.3"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 0.4"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/sponsors/ljharb"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/hasown": {
|
||||||
|
"version": "2.0.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz",
|
||||||
|
"integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==",
|
||||||
|
"peer": true,
|
||||||
|
"dependencies": {
|
||||||
|
"function-bind": "^1.1.2"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 0.4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/is-buffer": {
|
||||||
|
"version": "2.0.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-2.0.5.tgz",
|
||||||
|
"integrity": "sha512-i2R6zNFDwgEHJyQUtJEk0XFi1i0dPFn/oqjK3/vPCcDeJvW5NQ83V8QbicfF1SupOaB0h8ntgBC2YiE7dfyctQ==",
|
||||||
|
"funding": [
|
||||||
|
{
|
||||||
|
"type": "github",
|
||||||
|
"url": "https://github.com/sponsors/feross"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "patreon",
|
||||||
|
"url": "https://www.patreon.com/feross"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "consulting",
|
||||||
|
"url": "https://feross.org/support"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/math-intrinsics": {
|
||||||
|
"version": "1.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
|
||||||
|
"integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",
|
||||||
|
"peer": true,
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 0.4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/mime-db": {
|
||||||
|
"version": "1.52.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
|
||||||
|
"integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
|
||||||
|
"peer": true,
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 0.6"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/mime-types": {
|
||||||
|
"version": "2.1.35",
|
||||||
|
"resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",
|
||||||
|
"integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
|
||||||
|
"peer": true,
|
||||||
|
"dependencies": {
|
||||||
|
"mime-db": "1.52.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 0.6"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/proxy-from-env": {
|
||||||
|
"version": "1.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz",
|
||||||
|
"integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==",
|
||||||
|
"peer": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
5
package.json
Normal file
5
package.json
Normal file
|
|
@ -0,0 +1,5 @@
|
||||||
|
{
|
||||||
|
"dependencies": {
|
||||||
|
"axios-mock-adapter": "^2.1.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -7,6 +7,9 @@
|
||||||
|
|
||||||
// const BASE_URL = '/image'
|
// const BASE_URL = '/image'
|
||||||
|
|
||||||
|
const Images = require('../models/images');
|
||||||
|
const ObjectId = require('mongodb').ObjectId;
|
||||||
|
|
||||||
describe.skip("POST /upload", () => {
|
describe.skip("POST /upload", () => {
|
||||||
|
|
||||||
describe("when the jwt is not sent", () => {
|
describe("when the jwt is not sent", () => {
|
||||||
|
|
@ -64,3 +67,289 @@ describe.skip("GET /get", () => {
|
||||||
})
|
})
|
||||||
|
|
||||||
})
|
})
|
||||||
|
|
||||||
|
jest.mock('mongodb', () => {
|
||||||
|
const originalModule = jest.requireActual('mongodb');
|
||||||
|
return {
|
||||||
|
...originalModule,
|
||||||
|
ObjectId: {
|
||||||
|
...originalModule.ObjectId,
|
||||||
|
createFromHexString: jest.fn().mockReturnValue('507f191e810c19729de860ea'), // Return a valid 24-character ObjectId string
|
||||||
|
},
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Images', () => {
|
||||||
|
let db;
|
||||||
|
let images;
|
||||||
|
let dbConn;
|
||||||
|
let mockImagesCollection;
|
||||||
|
let mockFindCursor;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
|
||||||
|
const mockImagesCursor = {
|
||||||
|
sort: jest.fn().mockReturnThis(),
|
||||||
|
skip: jest.fn().mockReturnThis(),
|
||||||
|
limit: jest.fn().mockReturnThis(),
|
||||||
|
toArray: jest.fn()
|
||||||
|
};
|
||||||
|
|
||||||
|
const mockFilesCursor = {
|
||||||
|
sort: jest.fn().mockReturnThis(),
|
||||||
|
skip: jest.fn().mockReturnThis(),
|
||||||
|
limit: jest.fn().mockReturnThis(),
|
||||||
|
toArray: jest.fn()
|
||||||
|
};
|
||||||
|
|
||||||
|
mockImagesCollection = {
|
||||||
|
insertOne: jest.fn().mockResolvedValue({ insertedId: 'image123' }),
|
||||||
|
findOne: jest.fn(),
|
||||||
|
find: jest.fn().mockReturnValue(mockImagesCursor),
|
||||||
|
countDocuments: jest.fn(),
|
||||||
|
deleteOne: jest.fn()
|
||||||
|
};
|
||||||
|
|
||||||
|
mockFilesCollection = {
|
||||||
|
find: jest.fn().mockReturnValue(mockFilesCursor)
|
||||||
|
};
|
||||||
|
|
||||||
|
dbConn = {
|
||||||
|
collection: jest.fn((name) => {
|
||||||
|
if (name === 'images') {
|
||||||
|
return mockImagesCollection;
|
||||||
|
} else if (name === 'files') {
|
||||||
|
return mockFilesCollection;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
};
|
||||||
|
|
||||||
|
db = {
|
||||||
|
connect: jest.fn().mockResolvedValue(),
|
||||||
|
getConnection: jest.fn().mockReturnValue(dbConn)
|
||||||
|
};
|
||||||
|
|
||||||
|
images = new Images(db);
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('upload', () => {
|
||||||
|
it('should upload an image and return the inserted ID', async () => {
|
||||||
|
const testFile = { originalname: 'test.png', buffer: Buffer.from('dummydata'), mimetype: 'image/png' };
|
||||||
|
const userId = 'user123';
|
||||||
|
|
||||||
|
const result = await images.upload(testFile, userId);
|
||||||
|
|
||||||
|
expect(db.connect).toHaveBeenCalled();
|
||||||
|
expect(db.getConnection).toHaveBeenCalled();
|
||||||
|
expect(dbConn.collection).toHaveBeenCalledWith('images');
|
||||||
|
expect(mockImagesCollection.insertOne).toHaveBeenCalledWith({
|
||||||
|
userId: userId,
|
||||||
|
file_name: 'test.png',
|
||||||
|
file_content: testFile.buffer.toString('base64'),
|
||||||
|
mime_type: 'image/png',
|
||||||
|
created_at: expect.any(Date)
|
||||||
|
});
|
||||||
|
expect(result).toBe('image123');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('get', () => {
|
||||||
|
it('should retrieve the image if found', async () => {
|
||||||
|
const imageId = '65d9a8f9b5e8d1a5e6a8c9f0';
|
||||||
|
const testImage = {
|
||||||
|
file_name: 'test.png',
|
||||||
|
file_content: Buffer.from('dummydata').toString('base64'),
|
||||||
|
mime_type: 'image/png'
|
||||||
|
};
|
||||||
|
mockImagesCollection.findOne.mockResolvedValue(testImage);
|
||||||
|
|
||||||
|
const result = await images.get(imageId);
|
||||||
|
|
||||||
|
expect(db.connect).toHaveBeenCalled();
|
||||||
|
expect(db.getConnection).toHaveBeenCalled();
|
||||||
|
expect(dbConn.collection).toHaveBeenCalledWith('images');
|
||||||
|
expect(mockImagesCollection.findOne).toHaveBeenCalledWith({ _id: ObjectId.createFromHexString(imageId) });
|
||||||
|
expect(result).toEqual({
|
||||||
|
file_name: 'test.png',
|
||||||
|
file_content: Buffer.from('dummydata'),
|
||||||
|
mime_type: 'image/png'
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return null if image is not found', async () => {
|
||||||
|
const imageId = '65d9a8f9b5e8d1a5e6a8c9f0';
|
||||||
|
mockImagesCollection.findOne.mockResolvedValue(null);
|
||||||
|
|
||||||
|
const result = await images.get(imageId);
|
||||||
|
|
||||||
|
expect(result).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('getImages', () => {
|
||||||
|
it('should retrieve a paginated list of images', async () => {
|
||||||
|
const mockImages = [
|
||||||
|
{ _id: '1', userId: 'user1', file_name: 'image1.png', file_content: Buffer.from('data1'), mime_type: 'image/png' },
|
||||||
|
{ _id: '2', userId: 'user2', file_name: 'image2.png', file_content: Buffer.from('data2'), mime_type: 'image/png' }
|
||||||
|
];
|
||||||
|
|
||||||
|
mockImagesCollection.countDocuments.mockResolvedValue(2);
|
||||||
|
// Create a mock cursor for images collection
|
||||||
|
const mockFindCursor = {
|
||||||
|
sort: jest.fn().mockReturnThis(),
|
||||||
|
skip: jest.fn().mockReturnThis(),
|
||||||
|
limit: jest.fn().mockReturnThis(),
|
||||||
|
toArray: jest.fn().mockResolvedValue(mockImages), // Return mock images when toArray is called
|
||||||
|
};
|
||||||
|
|
||||||
|
// Mock the find method to return the mock cursor
|
||||||
|
mockImagesCollection.find.mockReturnValue(mockFindCursor);
|
||||||
|
const result = await images.getImages(1, 10);
|
||||||
|
|
||||||
|
expect(db.connect).toHaveBeenCalled();
|
||||||
|
expect(db.getConnection).toHaveBeenCalled();
|
||||||
|
expect(dbConn.collection).toHaveBeenCalledWith('images');
|
||||||
|
expect(mockImagesCollection.find).toHaveBeenCalledWith({});
|
||||||
|
expect(mockFindCursor.sort).toHaveBeenCalledWith({ created_at: 1 });
|
||||||
|
expect(mockFindCursor.skip).toHaveBeenCalledWith(0);
|
||||||
|
expect(mockFindCursor.limit).toHaveBeenCalledWith(10);
|
||||||
|
expect(result).toEqual({
|
||||||
|
images: [
|
||||||
|
{ id: '1', user: 'user1', file_name: 'image1.png', file_content: 'ZGF0YTE=', mime_type: 'image/png' },
|
||||||
|
{ id: '2', user: 'user2', file_name: 'image2.png', file_content: 'ZGF0YTI=', mime_type: 'image/png' }
|
||||||
|
],
|
||||||
|
total: 2,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return an empty array if no images are found', async () => {
|
||||||
|
mockImagesCollection.countDocuments.mockResolvedValue(0);
|
||||||
|
|
||||||
|
const result = await images.getImages(1, 10);
|
||||||
|
|
||||||
|
expect(result).toEqual({ images: [], total: 0 });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('getUserImages', () => {
|
||||||
|
it('should return empty images array when no images exist', async () => {
|
||||||
|
mockImagesCollection.countDocuments.mockResolvedValue(0);
|
||||||
|
|
||||||
|
const result = await images.getUserImages(1, 10, 'user123');
|
||||||
|
|
||||||
|
expect(result).toEqual({ images: [], total: 0 });
|
||||||
|
expect(db.connect).toHaveBeenCalled();
|
||||||
|
expect(mockImagesCollection.countDocuments).toHaveBeenCalledWith({ userId: 'user123' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return images when they exist', async () => {
|
||||||
|
const mockImages = [
|
||||||
|
{
|
||||||
|
_id: 'img1',
|
||||||
|
userId: 'user123',
|
||||||
|
file_name: 'image1.png',
|
||||||
|
file_content: Buffer.from('testdata'),
|
||||||
|
mime_type: 'image/png'
|
||||||
|
}
|
||||||
|
];
|
||||||
|
|
||||||
|
mockImagesCollection.countDocuments.mockResolvedValue(1);
|
||||||
|
mockImagesCollection.find.mockReturnValue({
|
||||||
|
sort: jest.fn().mockReturnThis(),
|
||||||
|
skip: jest.fn().mockReturnThis(),
|
||||||
|
limit: jest.fn().mockReturnThis(),
|
||||||
|
toArray: jest.fn().mockResolvedValue(mockImages)
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await images.getUserImages(1, 10, 'user123');
|
||||||
|
|
||||||
|
expect(result).toEqual({
|
||||||
|
images: [
|
||||||
|
{
|
||||||
|
id: 'img1',
|
||||||
|
user: 'user123',
|
||||||
|
file_name: 'image1.png',
|
||||||
|
file_content: Buffer.from('testdata').toString('base64'),
|
||||||
|
mime_type: 'image/png'
|
||||||
|
}
|
||||||
|
],
|
||||||
|
total: 1
|
||||||
|
});
|
||||||
|
expect(db.connect).toHaveBeenCalled();
|
||||||
|
expect(mockImagesCollection.countDocuments).toHaveBeenCalledWith({ userId: 'user123' });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
describe('delete', () => {
|
||||||
|
it('should not delete the image when it exists in the files collection', async () => {
|
||||||
|
const uid = 'user123';
|
||||||
|
const imgId = '507f191e810c19729de860ea'; // A valid 24-character ObjectId string
|
||||||
|
|
||||||
|
// Mock the files collection cursor to simulate an image found
|
||||||
|
const mockFilesCursor = {
|
||||||
|
toArray: jest.fn().mockResolvedValue([{ _id: imgId }]) // Image found
|
||||||
|
};
|
||||||
|
|
||||||
|
mockFilesCollection.find.mockReturnValue(mockFilesCursor);
|
||||||
|
mockImagesCollection.deleteOne.mockResolvedValue({ deletedCount: 0 });
|
||||||
|
|
||||||
|
const result = await images.delete(uid, imgId);
|
||||||
|
|
||||||
|
// Ensure the files collection is queried
|
||||||
|
expect(dbConn.collection).toHaveBeenCalledWith('files');
|
||||||
|
expect(mockFilesCollection.find).toHaveBeenCalledWith({
|
||||||
|
userId: uid,
|
||||||
|
content: { $regex: new RegExp(`/api/image/get/${imgId}`) },
|
||||||
|
});
|
||||||
|
|
||||||
|
// Ensure the images collection is queried for deletion
|
||||||
|
expect(dbConn.collection).toHaveBeenCalledWith('files');
|
||||||
|
expect(mockImagesCollection.deleteOne).not.toHaveBeenCalledWith({
|
||||||
|
_id: ObjectId.createFromHexString(imgId), // Ensure the ObjectId is created correctly
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result).toEqual({ deleted: false });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should delete the image if not found in the files collection', async () => {
|
||||||
|
const uid = 'user123';
|
||||||
|
const imgId = '507f191e810c19729de860ea';
|
||||||
|
|
||||||
|
// Mock the files collection cursor to simulate the image not being found
|
||||||
|
const mockFindCursor = {
|
||||||
|
toArray: jest.fn().mockResolvedValue([]) // Empty array means image not found
|
||||||
|
};
|
||||||
|
|
||||||
|
mockFilesCollection.find.mockReturnValue(mockFindCursor);
|
||||||
|
mockImagesCollection.deleteOne.mockResolvedValue({ deletedCount: 1 });
|
||||||
|
|
||||||
|
const result = await images.delete(uid, imgId);
|
||||||
|
|
||||||
|
// Ensure the deleteOne is not called if the image is not found
|
||||||
|
expect(mockImagesCollection.deleteOne).toHaveBeenCalled();
|
||||||
|
expect(result).toEqual({ deleted: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return false if the delete operation fails in the images collection', async () => {
|
||||||
|
const uid = 'user123';
|
||||||
|
const imgId = '507f191e810c19729de860ea';
|
||||||
|
|
||||||
|
// Mock the files collection cursor to simulate the image being found
|
||||||
|
const mockFindCursor = {
|
||||||
|
toArray: jest.fn().mockResolvedValue([{ _id: imgId }]) // Image found
|
||||||
|
};
|
||||||
|
|
||||||
|
mockFilesCollection.find.mockReturnValue(mockFindCursor);
|
||||||
|
mockImagesCollection.deleteOne.mockResolvedValue({ deletedCount: 0 }); // Simulate failure
|
||||||
|
|
||||||
|
const result = await images.delete(uid, imgId);
|
||||||
|
|
||||||
|
// Ensure the images collection deletion is called
|
||||||
|
expect(mockImagesCollection.deleteOne).not.toHaveBeenCalledWith({
|
||||||
|
_id: ObjectId.createFromHexString(imgId), // Ensure the ObjectId is created correctly
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result).toEqual({ deleted: false });
|
||||||
|
});
|
||||||
|
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -50,6 +50,58 @@ class ImagesController {
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
getImages = async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const page = parseInt(req.query.page) || 1;
|
||||||
|
const limit = parseInt(req.query.limit) || 5;
|
||||||
|
const images = await this.images.getImages(page, limit);
|
||||||
|
|
||||||
|
if (!images || images.length === 0) {
|
||||||
|
throw new AppError(IMAGE_NOT_FOUND);
|
||||||
|
}
|
||||||
|
|
||||||
|
res.setHeader('Content-Type', 'application/json');
|
||||||
|
return res.status(200).json(images);
|
||||||
|
} catch (error) {
|
||||||
|
return next(error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
getUserImages = async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const page = parseInt(req.query.page) || 1;
|
||||||
|
const limit = parseInt(req.query.limit) || 5;
|
||||||
|
const uid = req.query.uid;
|
||||||
|
const images = await this.images.getUserImages(page, limit, uid);
|
||||||
|
|
||||||
|
if (!images || images.length === 0) {
|
||||||
|
throw new AppError(IMAGE_NOT_FOUND);
|
||||||
|
}
|
||||||
|
|
||||||
|
res.setHeader('Content-Type', 'application/json');
|
||||||
|
return res.status(200).json(images);
|
||||||
|
} catch (error) {
|
||||||
|
return next(error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
delete = async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const uid = req.query.uid;
|
||||||
|
const imgId = req.query.imgId;
|
||||||
|
|
||||||
|
if (!uid || !imgId) {
|
||||||
|
throw new AppError(MISSING_REQUIRED_PARAMETER);
|
||||||
|
}
|
||||||
|
const images = await this.images.delete(uid, imgId);
|
||||||
|
|
||||||
|
res.setHeader('Content-Type', 'application/json');
|
||||||
|
return res.status(200).json(images);
|
||||||
|
} catch (error) {
|
||||||
|
return next(error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = ImagesController;
|
module.exports = ImagesController;
|
||||||
|
|
|
||||||
|
|
@ -42,6 +42,84 @@ class Images {
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async getImages(page, limit) {
|
||||||
|
await this.db.connect()
|
||||||
|
const conn = this.db.getConnection();
|
||||||
|
|
||||||
|
const imagesCollection = conn.collection('images');
|
||||||
|
|
||||||
|
|
||||||
|
const total = await imagesCollection.countDocuments();
|
||||||
|
if (!total || total === 0) return { images: [], total };
|
||||||
|
|
||||||
|
const result = await imagesCollection.find({})
|
||||||
|
.sort({ created_at: 1 })
|
||||||
|
.skip((page - 1) * limit)
|
||||||
|
.limit(limit)
|
||||||
|
.toArray();
|
||||||
|
|
||||||
|
const objImages = result.map(image => ({
|
||||||
|
id: image._id,
|
||||||
|
user: image.userId,
|
||||||
|
file_name: image.file_name,
|
||||||
|
file_content: image.file_content.toString('base64'),
|
||||||
|
mime_type: image.mime_type
|
||||||
|
}));
|
||||||
|
|
||||||
|
let respObj = {
|
||||||
|
images: objImages,
|
||||||
|
total: total
|
||||||
|
}
|
||||||
|
|
||||||
|
return respObj;
|
||||||
|
}
|
||||||
|
|
||||||
|
async getUserImages(page, limit, uid) {
|
||||||
|
await this.db.connect()
|
||||||
|
const conn = this.db.getConnection();
|
||||||
|
const imagesCollection = conn.collection('images');
|
||||||
|
const total = await imagesCollection.countDocuments({ userId: uid });
|
||||||
|
if (!total || total === 0) return { images: [], total };
|
||||||
|
|
||||||
|
const result = await imagesCollection.find({ userId: uid })
|
||||||
|
.sort({ created_at: -1 })
|
||||||
|
.skip((page - 1) * limit)
|
||||||
|
.limit(limit)
|
||||||
|
.toArray();
|
||||||
|
|
||||||
|
const objImages = result.map(image => ({
|
||||||
|
id: image._id,
|
||||||
|
user: image.userId,
|
||||||
|
file_name: image.file_name,
|
||||||
|
file_content: image.file_content.toString('base64'),
|
||||||
|
mime_type: image.mime_type
|
||||||
|
}));
|
||||||
|
|
||||||
|
let respObj = {
|
||||||
|
images: objImages,
|
||||||
|
total: total
|
||||||
|
}
|
||||||
|
|
||||||
|
return respObj;
|
||||||
|
}
|
||||||
|
|
||||||
|
async delete(uid, imgId) {
|
||||||
|
let resp = false;
|
||||||
|
await this.db.connect()
|
||||||
|
const conn = this.db.getConnection();
|
||||||
|
const quizColl = conn.collection('files');
|
||||||
|
const rgxImg = new RegExp(`/api/image/get/${imgId}`);
|
||||||
|
|
||||||
|
const result = await quizColl.find({ userId: uid, content: { $regex: rgxImg }}).toArray();
|
||||||
|
if(!result || result.length < 1){
|
||||||
|
const imgsColl = conn.collection('images');
|
||||||
|
const isDeleted = await imgsColl.deleteOne({ _id: ObjectId.createFromHexString(imgId) });
|
||||||
|
if(isDeleted){
|
||||||
|
resp = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { deleted: resp };
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = Images;
|
module.exports = Images;
|
||||||
|
|
|
||||||
221
server/package-lock.json
generated
221
server/package-lock.json
generated
|
|
@ -24,6 +24,7 @@
|
||||||
"passport-oauth2": "^1.8.0",
|
"passport-oauth2": "^1.8.0",
|
||||||
"passport-openidconnect": "^0.1.2",
|
"passport-openidconnect": "^0.1.2",
|
||||||
"patch-package": "^8.0.0",
|
"patch-package": "^8.0.0",
|
||||||
|
"qrcode.react": "^4.2.0",
|
||||||
"socket.io": "^4.7.2",
|
"socket.io": "^4.7.2",
|
||||||
"socket.io-client": "^4.7.2"
|
"socket.io-client": "^4.7.2"
|
||||||
},
|
},
|
||||||
|
|
@ -38,7 +39,7 @@
|
||||||
"supertest": "^6.3.4"
|
"supertest": "^6.3.4"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": "20.x"
|
"node": "22.x"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@ampproject/remapping": {
|
"node_modules/@ampproject/remapping": {
|
||||||
|
|
@ -55,68 +56,20 @@
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@babel/code-frame": {
|
"node_modules/@babel/code-frame": {
|
||||||
"version": "7.22.13",
|
"version": "7.26.2",
|
||||||
"resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.22.13.tgz",
|
"resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.26.2.tgz",
|
||||||
"integrity": "sha512-XktuhWlJ5g+3TJXc5upd9Ks1HutSArik6jf2eAjYFyIOf4ej3RN+184cZbzDvbPnuTJIUhPKKJE3cIsYTiAT3w==",
|
"integrity": "sha512-RJlIHRueQgwWitWgF8OdFYGZX328Ax5BCemNGlqHfplnRT9ESi8JkFlvaVYbS+UubVY6dpv87Fs2u5M29iNFVQ==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@babel/highlight": "^7.22.13",
|
"@babel/helper-validator-identifier": "^7.25.9",
|
||||||
"chalk": "^2.4.2"
|
"js-tokens": "^4.0.0",
|
||||||
|
"picocolors": "^1.0.0"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=6.9.0"
|
"node": ">=6.9.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@babel/code-frame/node_modules/ansi-styles": {
|
|
||||||
"version": "3.2.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz",
|
|
||||||
"integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==",
|
|
||||||
"dev": true,
|
|
||||||
"dependencies": {
|
|
||||||
"color-convert": "^1.9.0"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">=4"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@babel/code-frame/node_modules/chalk": {
|
|
||||||
"version": "2.4.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz",
|
|
||||||
"integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==",
|
|
||||||
"dev": true,
|
|
||||||
"dependencies": {
|
|
||||||
"ansi-styles": "^3.2.1",
|
|
||||||
"escape-string-regexp": "^1.0.5",
|
|
||||||
"supports-color": "^5.3.0"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">=4"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@babel/code-frame/node_modules/color-convert": {
|
|
||||||
"version": "1.9.3",
|
|
||||||
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz",
|
|
||||||
"integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==",
|
|
||||||
"dev": true,
|
|
||||||
"dependencies": {
|
|
||||||
"color-name": "1.1.3"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@babel/code-frame/node_modules/color-name": {
|
|
||||||
"version": "1.1.3",
|
|
||||||
"resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz",
|
|
||||||
"integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==",
|
|
||||||
"dev": true
|
|
||||||
},
|
|
||||||
"node_modules/@babel/code-frame/node_modules/escape-string-regexp": {
|
|
||||||
"version": "1.0.5",
|
|
||||||
"resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz",
|
|
||||||
"integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==",
|
|
||||||
"dev": true,
|
|
||||||
"engines": {
|
|
||||||
"node": ">=0.8.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@babel/compat-data": {
|
"node_modules/@babel/compat-data": {
|
||||||
"version": "7.23.3",
|
"version": "7.23.3",
|
||||||
"resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.23.3.tgz",
|
"resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.23.3.tgz",
|
||||||
|
|
@ -342,19 +295,21 @@
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@babel/helper-string-parser": {
|
"node_modules/@babel/helper-string-parser": {
|
||||||
"version": "7.22.5",
|
"version": "7.25.9",
|
||||||
"resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.22.5.tgz",
|
"resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.25.9.tgz",
|
||||||
"integrity": "sha512-mM4COjgZox8U+JcXQwPijIZLElkgEpO5rsERVDJTc2qfCDfERyob6k5WegS14SX18IIjv+XD+GrqNumY5JRCDw==",
|
"integrity": "sha512-4A/SCr/2KLd5jrtOMFzaKjVtAei3+2r/NChoBNoZ3EyP/+GlhoaEGoWOZUmFmoITP7zOJyHIMm+DYRd8o3PvHA==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=6.9.0"
|
"node": ">=6.9.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@babel/helper-validator-identifier": {
|
"node_modules/@babel/helper-validator-identifier": {
|
||||||
"version": "7.22.20",
|
"version": "7.25.9",
|
||||||
"resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.22.20.tgz",
|
"resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.25.9.tgz",
|
||||||
"integrity": "sha512-Y4OZ+ytlatR8AI+8KZfKuL5urKp7qey08ha31L8b3BwewJAoJamTzyvxPR/5D+KkdJCGPq/+8TukHBlY10FX9A==",
|
"integrity": "sha512-Ed61U6XJc3CVRfkERJWDz4dJwKe7iLmmJsbOGu9wSloNSFttHV0I8g6UAgb7qnK5ly5bGLPd4oXZlxCdANBOWQ==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=6.9.0"
|
"node": ">=6.9.0"
|
||||||
}
|
}
|
||||||
|
|
@ -369,88 +324,28 @@
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@babel/helpers": {
|
"node_modules/@babel/helpers": {
|
||||||
"version": "7.23.2",
|
"version": "7.26.10",
|
||||||
"resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.23.2.tgz",
|
"resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.26.10.tgz",
|
||||||
"integrity": "sha512-lzchcp8SjTSVe/fPmLwtWVBFC7+Tbn8LGHDVfDp9JGxpAY5opSaEFgt8UQvrnECWOTdji2mOWMz1rOhkHscmGQ==",
|
"integrity": "sha512-UPYc3SauzZ3JGgj87GgZ89JVdC5dj0AoetR5Bw6wj4niittNyFh6+eOGonYvJ1ao6B8lEa3Q3klS7ADZ53bc5g==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@babel/template": "^7.22.15",
|
"@babel/template": "^7.26.9",
|
||||||
"@babel/traverse": "^7.23.2",
|
"@babel/types": "^7.26.10"
|
||||||
"@babel/types": "^7.23.0"
|
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=6.9.0"
|
"node": ">=6.9.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@babel/highlight": {
|
|
||||||
"version": "7.22.20",
|
|
||||||
"resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.22.20.tgz",
|
|
||||||
"integrity": "sha512-dkdMCN3py0+ksCgYmGG8jKeGA/8Tk+gJwSYYlFGxG5lmhfKNoAy004YpLxpS1W2J8m/EK2Ew+yOs9pVRwO89mg==",
|
|
||||||
"dev": true,
|
|
||||||
"dependencies": {
|
|
||||||
"@babel/helper-validator-identifier": "^7.22.20",
|
|
||||||
"chalk": "^2.4.2",
|
|
||||||
"js-tokens": "^4.0.0"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">=6.9.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@babel/highlight/node_modules/ansi-styles": {
|
|
||||||
"version": "3.2.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz",
|
|
||||||
"integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==",
|
|
||||||
"dev": true,
|
|
||||||
"dependencies": {
|
|
||||||
"color-convert": "^1.9.0"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">=4"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@babel/highlight/node_modules/chalk": {
|
|
||||||
"version": "2.4.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz",
|
|
||||||
"integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==",
|
|
||||||
"dev": true,
|
|
||||||
"dependencies": {
|
|
||||||
"ansi-styles": "^3.2.1",
|
|
||||||
"escape-string-regexp": "^1.0.5",
|
|
||||||
"supports-color": "^5.3.0"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">=4"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@babel/highlight/node_modules/color-convert": {
|
|
||||||
"version": "1.9.3",
|
|
||||||
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz",
|
|
||||||
"integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==",
|
|
||||||
"dev": true,
|
|
||||||
"dependencies": {
|
|
||||||
"color-name": "1.1.3"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@babel/highlight/node_modules/color-name": {
|
|
||||||
"version": "1.1.3",
|
|
||||||
"resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz",
|
|
||||||
"integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==",
|
|
||||||
"dev": true
|
|
||||||
},
|
|
||||||
"node_modules/@babel/highlight/node_modules/escape-string-regexp": {
|
|
||||||
"version": "1.0.5",
|
|
||||||
"resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz",
|
|
||||||
"integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==",
|
|
||||||
"dev": true,
|
|
||||||
"engines": {
|
|
||||||
"node": ">=0.8.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@babel/parser": {
|
"node_modules/@babel/parser": {
|
||||||
"version": "7.23.3",
|
"version": "7.26.10",
|
||||||
"resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.23.3.tgz",
|
"resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.26.10.tgz",
|
||||||
"integrity": "sha512-uVsWNvlVsIninV2prNz/3lHCb+5CJ+e+IUBfbjToAHODtfGYLfCFuY4AU7TskI+dAKk+njsPiBjq1gKTvZOBaw==",
|
"integrity": "sha512-6aQR2zGE/QFi8JpDLjUZEPYOs7+mhKXm86VaKFiLP35JQwQb6bwUE+XbvkH0EptsYhbNBSUGaUBLKqxH1xSgsA==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@babel/types": "^7.26.10"
|
||||||
|
},
|
||||||
"bin": {
|
"bin": {
|
||||||
"parser": "bin/babel-parser.js"
|
"parser": "bin/babel-parser.js"
|
||||||
},
|
},
|
||||||
|
|
@ -636,14 +531,15 @@
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@babel/template": {
|
"node_modules/@babel/template": {
|
||||||
"version": "7.22.15",
|
"version": "7.26.9",
|
||||||
"resolved": "https://registry.npmjs.org/@babel/template/-/template-7.22.15.tgz",
|
"resolved": "https://registry.npmjs.org/@babel/template/-/template-7.26.9.tgz",
|
||||||
"integrity": "sha512-QPErUVm4uyJa60rkI73qneDacvdvzxshT3kksGqlGWYdOTIUOwJ7RDUL8sGqslY1uXWSL6xMFKEXDS3ox2uF0w==",
|
"integrity": "sha512-qyRplbeIpNZhmzOysF/wFMuP9sctmh2cFzRAZOn1YapxBsE1i9bJIY586R/WBLfLcmcBlM8ROBiQURnnNy+zfA==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@babel/code-frame": "^7.22.13",
|
"@babel/code-frame": "^7.26.2",
|
||||||
"@babel/parser": "^7.22.15",
|
"@babel/parser": "^7.26.9",
|
||||||
"@babel/types": "^7.22.15"
|
"@babel/types": "^7.26.9"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=6.9.0"
|
"node": ">=6.9.0"
|
||||||
|
|
@ -704,14 +600,14 @@
|
||||||
"dev": true
|
"dev": true
|
||||||
},
|
},
|
||||||
"node_modules/@babel/types": {
|
"node_modules/@babel/types": {
|
||||||
"version": "7.23.3",
|
"version": "7.26.10",
|
||||||
"resolved": "https://registry.npmjs.org/@babel/types/-/types-7.23.3.tgz",
|
"resolved": "https://registry.npmjs.org/@babel/types/-/types-7.26.10.tgz",
|
||||||
"integrity": "sha512-OZnvoH2l8PK5eUvEcUyCt/sXgr/h+UWpVuBbOljwcrAgUl6lpchoQ++PHGyQy1AtYnVA6CEq3y5xeEI10brpXw==",
|
"integrity": "sha512-emqcG3vHrpxUKTrxcblR36dcrcoRDvKmnL/dCL6ZsHaShW80qxCAcNhzQZrpeM765VzEos+xOi4s+r4IXzTwdQ==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@babel/helper-string-parser": "^7.22.5",
|
"@babel/helper-string-parser": "^7.25.9",
|
||||||
"@babel/helper-validator-identifier": "^7.22.20",
|
"@babel/helper-validator-identifier": "^7.25.9"
|
||||||
"to-fast-properties": "^2.0.0"
|
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=6.9.0"
|
"node": ">=6.9.0"
|
||||||
|
|
@ -4772,7 +4668,8 @@
|
||||||
"version": "4.0.0",
|
"version": "4.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
|
||||||
"integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==",
|
"integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==",
|
||||||
"dev": true
|
"dev": true,
|
||||||
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/js-yaml": {
|
"node_modules/js-yaml": {
|
||||||
"version": "3.14.1",
|
"version": "3.14.1",
|
||||||
|
|
@ -5954,6 +5851,15 @@
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
|
"node_modules/qrcode.react": {
|
||||||
|
"version": "4.2.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/qrcode.react/-/qrcode.react-4.2.0.tgz",
|
||||||
|
"integrity": "sha512-QpgqWi8rD9DsS9EP3z7BT+5lY5SFhsqGjpgW5DY/i3mK4M9DTBNz3ErMi8BWYEfI3L0d8GIbGmcdFAS1uIRGjA==",
|
||||||
|
"license": "ISC",
|
||||||
|
"peerDependencies": {
|
||||||
|
"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/qs": {
|
"node_modules/qs": {
|
||||||
"version": "6.13.0",
|
"version": "6.13.0",
|
||||||
"resolved": "https://registry.npmjs.org/qs/-/qs-6.13.0.tgz",
|
"resolved": "https://registry.npmjs.org/qs/-/qs-6.13.0.tgz",
|
||||||
|
|
@ -5998,6 +5904,16 @@
|
||||||
"node": ">= 0.8"
|
"node": ">= 0.8"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/react": {
|
||||||
|
"version": "19.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/react/-/react-19.0.0.tgz",
|
||||||
|
"integrity": "sha512-V8AVnmPIICiWpGfm6GLzCR/W5FXLchHop40W4nXBmdlEceh16rCN8O8LNWm5bh5XUX91fh7KpA+W0TgMKmgTpQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"peer": true,
|
||||||
|
"engines": {
|
||||||
|
"node": ">=0.10.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/react-is": {
|
"node_modules/react-is": {
|
||||||
"version": "18.2.0",
|
"version": "18.2.0",
|
||||||
"resolved": "https://registry.npmjs.org/react-is/-/react-is-18.2.0.tgz",
|
"resolved": "https://registry.npmjs.org/react-is/-/react-is-18.2.0.tgz",
|
||||||
|
|
@ -6683,15 +6599,6 @@
|
||||||
"integrity": "sha512-3f0uOEAQwIqGuWW2MVzYg8fV/QNnc/IpuJNG837rLuczAaLVHslWHZQj4IGiEl5Hs3kkbhwL9Ab7Hrsmuj+Smw==",
|
"integrity": "sha512-3f0uOEAQwIqGuWW2MVzYg8fV/QNnc/IpuJNG837rLuczAaLVHslWHZQj4IGiEl5Hs3kkbhwL9Ab7Hrsmuj+Smw==",
|
||||||
"dev": true
|
"dev": true
|
||||||
},
|
},
|
||||||
"node_modules/to-fast-properties": {
|
|
||||||
"version": "2.0.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-2.0.0.tgz",
|
|
||||||
"integrity": "sha512-/OaKK0xYrs3DmxRYqL/yDc+FxFUVYhDlXMhRmv3z915w2HF1tnN1omB354j8VUGO/hbRzyD6Y3sA7v7GS/ceog==",
|
|
||||||
"dev": true,
|
|
||||||
"engines": {
|
|
||||||
"node": ">=4"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/to-regex-range": {
|
"node_modules/to-regex-range": {
|
||||||
"version": "5.0.1",
|
"version": "5.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz",
|
"resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz",
|
||||||
|
|
|
||||||
|
|
@ -28,6 +28,7 @@
|
||||||
"passport-oauth2": "^1.8.0",
|
"passport-oauth2": "^1.8.0",
|
||||||
"passport-openidconnect": "^0.1.2",
|
"passport-openidconnect": "^0.1.2",
|
||||||
"patch-package": "^8.0.0",
|
"patch-package": "^8.0.0",
|
||||||
|
"qrcode.react": "^4.2.0",
|
||||||
"socket.io": "^4.7.2",
|
"socket.io": "^4.7.2",
|
||||||
"socket.io-client": "^4.7.2"
|
"socket.io-client": "^4.7.2"
|
||||||
},
|
},
|
||||||
|
|
@ -42,7 +43,7 @@
|
||||||
"supertest": "^6.3.4"
|
"supertest": "^6.3.4"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": "20.x"
|
"node": "22.x"
|
||||||
},
|
},
|
||||||
"jest": {
|
"jest": {
|
||||||
"testEnvironment": "node",
|
"testEnvironment": "node",
|
||||||
|
|
|
||||||
|
|
@ -12,5 +12,8 @@ const upload = multer({ storage: storage });
|
||||||
|
|
||||||
router.post("/upload", jwt.authenticate, upload.single('image'), asyncHandler(images.upload));
|
router.post("/upload", jwt.authenticate, upload.single('image'), asyncHandler(images.upload));
|
||||||
router.get("/get/:id", asyncHandler(images.get));
|
router.get("/get/:id", asyncHandler(images.get));
|
||||||
|
router.get("/getImages", asyncHandler(images.getImages));
|
||||||
|
router.get("/getUserImages", jwt.authenticate, asyncHandler(images.getUserImages));
|
||||||
|
router.delete("/delete", jwt.authenticate, asyncHandler(images.delete));
|
||||||
|
|
||||||
module.exports = router;
|
module.exports = router;
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue