mirror of
https://github.com/ets-cfuhrman-pfe/EvalueTonSavoir.git
synced 2025-08-11 21:23:54 -04:00
Compare commits
89 commits
4f46957cc2
...
65bcda2134
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
65bcda2134 | ||
|
|
dd49f0adfd | ||
|
|
62df610d62 | ||
|
|
f13b58d89b | ||
|
|
a66631c60b | ||
|
|
5a5897d25c | ||
|
|
20bfb8774f | ||
|
|
40aee9aa89 | ||
|
|
c13e73208e | ||
|
|
f28bd90c6e | ||
|
|
7a8ab7e5f5 | ||
|
|
1de68418e0 | ||
|
|
814a022bc2 | ||
|
|
d218134316 | ||
|
|
33bc038d32 | ||
|
|
def3e9f929 | ||
|
|
11b719e2ca | ||
|
|
5ff5b2018f | ||
|
|
8f6cf8cffa | ||
|
|
9205c0c6bf | ||
|
|
8e999dc10f | ||
|
|
d0328f9ec8 | ||
|
|
58da59c632 | ||
|
|
b0cbb7af39 | ||
|
|
5cdf4abd92 | ||
|
|
032325be66 | ||
|
|
1b000a8798 | ||
|
|
1ae9125c5b | ||
|
|
355f9f40ec | ||
|
|
c35db46387 | ||
|
|
cf2083ff85 | ||
|
|
2695716e18 | ||
|
|
6e91ab311d | ||
|
|
61bf9b9d86 | ||
|
|
a26ffa2880 | ||
|
|
95f914ce3e | ||
|
|
46c17ba127 | ||
|
|
7c7fe031f8 | ||
|
|
aa739233dd | ||
|
|
0d7b6ee5eb | ||
|
|
d5733fa728 | ||
|
|
78e398ecd8 | ||
|
|
755d14a5b7 | ||
|
|
1a7dc7fec2 | ||
|
|
81bedf0672 | ||
|
|
c50cd3e6e7 | ||
|
|
a3e0ba70f9 | ||
|
|
a4d36389c7 | ||
|
|
dc7fb82d97 | ||
|
|
c18b1a8759 | ||
|
|
4e0d5d778d | ||
|
|
d9480e2d14 | ||
|
|
ab9636c8db | ||
|
|
e2376dd8c3 | ||
|
|
92699f9a83 | ||
|
|
1c16e06319 | ||
|
|
b7a7962435 | ||
|
|
b7ec35c0c9 | ||
|
|
fb41980f29 | ||
|
|
0243270fdb | ||
|
|
241854159b | ||
|
|
312ccd0b52 | ||
|
|
ef192eb784 | ||
|
|
01deaee487 | ||
|
|
aa74227981 | ||
|
|
f4bcfd27b9 | ||
|
|
6b654c769c | ||
|
|
f0b3d74c31 | ||
|
|
2ca21a7d6b | ||
|
|
66ce4937d9 | ||
|
|
9ff2882761 | ||
|
|
de5f8fad6c | ||
|
|
1512f320c8 | ||
|
|
78f6993547 | ||
|
|
f6afb1f7ed | ||
|
|
1b321c74f9 | ||
|
|
add7d9954b | ||
|
|
71f57fd2cf | ||
|
|
f055a47305 | ||
|
|
f8357883e6 | ||
|
|
0f87bab5ff | ||
|
|
c9d65c0082 | ||
|
|
460b4f1648 | ||
|
|
5ba89072e2 | ||
|
|
9e5613a011 | ||
|
|
16d594c61d | ||
|
|
e7c3c84b80 | ||
|
|
ee5e096984 | ||
|
|
c6c830ef74 |
40 changed files with 3543 additions and 1138 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/
|
||||||
|
|
|
||||||
1067
client/package-lock.json
generated
1067
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,59 +18,63 @@
|
||||||
"@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.6",
|
"@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-beautiful-dnd": "^13.1.1",
|
||||||
"react-dom": "^18.3.1",
|
"react-dom": "^18.3.1",
|
||||||
"react-modal": "^3.16.3",
|
"react-modal": "^3.16.3",
|
||||||
"react-router-dom": "^6.26.2",
|
"react-router-dom": "^6.26.2",
|
||||||
"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-beautiful-dnd": "^13.1.8",
|
||||||
"@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/ImageType.tsx
Normal file
17
client/src/Types/ImageType.tsx
Normal file
|
|
@ -0,0 +1,17 @@
|
||||||
|
export interface ImageType {
|
||||||
|
id: string;
|
||||||
|
file_content: string;
|
||||||
|
file_name: string;
|
||||||
|
mime_type: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ImagesResponse {
|
||||||
|
images: ImageType[];
|
||||||
|
total: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ImagesParams {
|
||||||
|
page: number;
|
||||||
|
limit: number;
|
||||||
|
uid?: string;
|
||||||
|
}
|
||||||
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;
|
||||||
|
}
|
||||||
|
|
@ -1,80 +1,78 @@
|
||||||
// Editor.test.tsx
|
|
||||||
import React from 'react';
|
import React from 'react';
|
||||||
import { render, fireEvent, screen } from '@testing-library/react';
|
import { render, screen, fireEvent } from '@testing-library/react';
|
||||||
import '@testing-library/jest-dom';
|
import '@testing-library/jest-dom';
|
||||||
import Editor from 'src/components/Editor/Editor';
|
import Editor from '../../../components/Editor/Editor';
|
||||||
|
|
||||||
describe('Editor Component', () => {
|
describe('Editor Component', () => {
|
||||||
const mockOnEditorChange = jest.fn();
|
const mockOnValuesChange = jest.fn();
|
||||||
|
const mockOnFocusQuestion = jest.fn();
|
||||||
|
|
||||||
const sampleProps = {
|
const sampleProps = {
|
||||||
label: 'Sample Label',
|
label: 'Sample Label',
|
||||||
initialValue: 'Sample Initial Value',
|
values: ['Question 1', 'Question 2'],
|
||||||
onEditorChange: mockOnEditorChange
|
onValuesChange: mockOnValuesChange,
|
||||||
|
onFocusQuestion: mockOnFocusQuestion,
|
||||||
};
|
};
|
||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
|
mockOnValuesChange.mockClear();
|
||||||
|
mockOnFocusQuestion.mockClear();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('renders the label correctly', () => {
|
||||||
render(<Editor {...sampleProps} />);
|
render(<Editor {...sampleProps} />);
|
||||||
|
const label = screen.getByText('Sample Label');
|
||||||
|
expect(label).toBeInTheDocument();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('renders correctly with initial value', () => {
|
test('renders the correct number of questions', () => {
|
||||||
const editorTextarea = screen.getByRole('textbox') as HTMLTextAreaElement;
|
render(<Editor {...sampleProps} />);
|
||||||
expect(editorTextarea).toBeInTheDocument();
|
const questions = screen.getAllByRole('textbox');
|
||||||
expect(editorTextarea.value).toBe('Sample Initial Value');
|
expect(questions.length).toBe(2);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('calls onEditorChange callback when editor value changes', () => {
|
test('calls onValuesChange with updated values when a question is changed', () => {
|
||||||
const editorTextarea = screen.getByRole('textbox') as HTMLTextAreaElement;
|
render(<Editor {...sampleProps} />);
|
||||||
fireEvent.change(editorTextarea, { target: { value: 'Updated Value' } });
|
const questionInput = screen.getAllByRole('textbox')[0];
|
||||||
expect(mockOnEditorChange).toHaveBeenCalledWith('Updated Value');
|
fireEvent.change(questionInput, { target: { value: 'Updated Question 1' } });
|
||||||
|
expect(mockOnValuesChange).toHaveBeenCalledWith(['Updated Question 1', 'Question 2']);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('updates editor value when initialValue prop changes', () => {
|
test('calls onValuesChange with updated values when an empty question is deleted', () => {
|
||||||
const updatedProps = {
|
const sampleProps = {
|
||||||
label: 'Updated Label',
|
label: 'Test Editor',
|
||||||
initialValue: 'Updated Initial Value',
|
values: [''],
|
||||||
onEditorChange: mockOnEditorChange
|
onValuesChange: mockOnValuesChange,
|
||||||
};
|
};
|
||||||
|
render(<Editor {...sampleProps} />);
|
||||||
render(<Editor {...updatedProps} />);
|
const deleteButton = screen.getAllByLabelText('delete')[0];
|
||||||
|
fireEvent.click(deleteButton);
|
||||||
const editorTextareas = screen.getAllByRole('textbox') as HTMLTextAreaElement[];
|
expect(mockOnValuesChange).toHaveBeenCalledWith([]);
|
||||||
const editorTextarea = editorTextareas[1];
|
|
||||||
|
|
||||||
expect(editorTextarea.value).toBe('Updated Initial Value');
|
|
||||||
});
|
});
|
||||||
|
|
||||||
test('should call change text with the correct value on textarea change', () => {
|
test('renders delete buttons for each question', () => {
|
||||||
const updatedProps = {
|
render(<Editor {...sampleProps} />);
|
||||||
label: 'Updated Label',
|
const deleteButtons = screen.getAllByLabelText('delete');
|
||||||
initialValue: 'Updated Initial Value',
|
expect(deleteButtons.length).toBe(2);
|
||||||
onEditorChange: mockOnEditorChange
|
|
||||||
};
|
|
||||||
|
|
||||||
render(<Editor {...updatedProps} />);
|
|
||||||
|
|
||||||
const editorTextareas = screen.getAllByRole('textbox') as HTMLTextAreaElement[];
|
|
||||||
const editorTextarea = editorTextareas[1];
|
|
||||||
fireEvent.change(editorTextarea, { target: { value: 'New value' } });
|
|
||||||
|
|
||||||
expect(editorTextarea.value).toBe('New value');
|
|
||||||
});
|
});
|
||||||
|
|
||||||
test('should call onEditorChange with an empty string if textarea value is falsy', () => {
|
test('calls onFocusQuestion with correct index when focus button is clicked', () => {
|
||||||
const updatedProps = {
|
render(<Editor {...sampleProps} />);
|
||||||
label: 'Updated Label',
|
const focusButton = screen.getAllByLabelText('focus question')[1];
|
||||||
initialValue: 'Updated Initial Value',
|
fireEvent.click(focusButton);
|
||||||
onEditorChange: mockOnEditorChange
|
expect(mockOnFocusQuestion).toHaveBeenCalledWith(1);
|
||||||
};
|
|
||||||
|
|
||||||
render(<Editor {...updatedProps} />);
|
|
||||||
|
|
||||||
const editorTextareas = screen.getAllByRole('textbox') as HTMLTextAreaElement[];
|
|
||||||
const editorTextarea = editorTextareas[1];
|
|
||||||
fireEvent.change(editorTextarea, { target: { value: '' } });
|
|
||||||
|
|
||||||
expect(editorTextarea.value).toBe('');
|
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('renders focus buttons for each question', () => {
|
||||||
|
render(<Editor {...sampleProps} />);
|
||||||
|
const focusButtons = screen.getAllByLabelText('focus question');
|
||||||
|
expect(focusButtons.length).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('does not throw error when onFocusQuestion is not provided', () => {
|
||||||
|
const { onFocusQuestion, ...propsWithoutFocus } = sampleProps;
|
||||||
|
render(<Editor {...propsWithoutFocus} />);
|
||||||
|
const focusButton = screen.getAllByLabelText('focus question')[0];
|
||||||
|
expect(() => fireEvent.click(focusButton)).not.toThrow();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
@ -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();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
});
|
||||||
|
|
@ -1,46 +1,148 @@
|
||||||
import React from 'react';
|
import React from 'react';
|
||||||
import { render, screen, fireEvent } from '@testing-library/react';
|
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
|
||||||
import '@testing-library/jest-dom';
|
import '@testing-library/jest-dom';
|
||||||
import ReturnButton from 'src/components/ReturnButton/ReturnButton';
|
|
||||||
import { useNavigate } from 'react-router-dom';
|
import { useNavigate } from 'react-router-dom';
|
||||||
|
import ReturnButton from '../../../components/ReturnButton/ReturnButton.tsx'; // Adjust path as needed
|
||||||
|
import ApiService from '../../../services/ApiService';
|
||||||
|
|
||||||
|
// Mock react-router-dom's useNavigate
|
||||||
jest.mock('react-router-dom', () => ({
|
jest.mock('react-router-dom', () => ({
|
||||||
...jest.requireActual('react-router-dom'),
|
...jest.requireActual('react-router-dom'),
|
||||||
useNavigate: jest.fn()
|
useNavigate: jest.fn(),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
describe('ReturnButton', () => {
|
// Mock ApiService
|
||||||
test('navigates back when askConfirm is false', () => {
|
jest.mock('../../../services/ApiService', () => ({
|
||||||
const navigateMock = jest.fn();
|
createQuiz: jest.fn(),
|
||||||
(useNavigate as jest.Mock).mockReturnValue(navigateMock);
|
updateQuiz: jest.fn(),
|
||||||
render(<ReturnButton askConfirm={false} />);
|
}));
|
||||||
fireEvent.click(screen.getByText('Retour'));
|
|
||||||
expect(navigateMock).toHaveBeenCalledWith(-1);
|
describe('ReturnButton Component', () => {
|
||||||
|
const mockNavigate = jest.fn();
|
||||||
|
const mockOnReturn = jest.fn();
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
// Reset mocks before each test
|
||||||
|
jest.clearAllMocks();
|
||||||
|
(useNavigate as jest.Mock).mockReturnValue(mockNavigate);
|
||||||
|
(ApiService.createQuiz as jest.Mock).mockResolvedValue({});
|
||||||
|
(ApiService.updateQuiz as jest.Mock).mockResolvedValue({});
|
||||||
});
|
});
|
||||||
|
|
||||||
test('shows confirmation modal when askConfirm is true', () => {
|
test('renders the button with "Retour" text when not saving', () => {
|
||||||
render(<ReturnButton askConfirm={true} />);
|
render(<ReturnButton />);
|
||||||
fireEvent.click(screen.getByText('Retour'));
|
expect(screen.getByText('Retour')).toBeInTheDocument();
|
||||||
const confirmButton = screen.getByTestId('modal-confirm-button');
|
|
||||||
expect(confirmButton).toBeInTheDocument();
|
|
||||||
});
|
});
|
||||||
|
|
||||||
/*test('navigates back after confirming in the modal', () => {
|
test('renders "Enregistrement..." text when saving', async () => {
|
||||||
const navigateMock = jest.fn();
|
render(<ReturnButton quizTitle="Test Quiz" quizFolder="folder1" isNewQuiz />);
|
||||||
(useNavigate as jest.Mock).mockReturnValue(navigateMock);
|
|
||||||
render(<ReturnButton askConfirm={true} />);
|
|
||||||
fireEvent.click(screen.getByText('Retour'));
|
fireEvent.click(screen.getByText('Retour'));
|
||||||
const confirmButton = screen.getByTestId('modal-confirm-button');
|
expect(screen.getByText('Enregistrement...')).toBeInTheDocument();
|
||||||
fireEvent.click(confirmButton);
|
await waitFor(() => expect(screen.queryByText('Enregistrement...')).not.toBeInTheDocument());
|
||||||
expect(navigateMock).toHaveBeenCalledWith(-1);
|
});
|
||||||
});*/
|
|
||||||
|
|
||||||
test('cancels navigation when canceling in the modal', () => {
|
test('navigates to /teacher/dashboard by default when clicked', async () => {
|
||||||
const navigateMock = jest.fn();
|
render(<ReturnButton />);
|
||||||
(useNavigate as jest.Mock).mockReturnValue(navigateMock);
|
|
||||||
render(<ReturnButton askConfirm={true} />);
|
|
||||||
fireEvent.click(screen.getByText('Retour'));
|
fireEvent.click(screen.getByText('Retour'));
|
||||||
fireEvent.click(screen.getByText('Annuler'));
|
await waitFor(() => expect(mockNavigate).toHaveBeenCalledWith('/teacher/dashboard'));
|
||||||
expect(navigateMock).not.toHaveBeenCalled();
|
});
|
||||||
|
|
||||||
|
test('calls onReturn prop instead of navigating when provided', async () => {
|
||||||
|
render(<ReturnButton onReturn={mockOnReturn} />);
|
||||||
|
fireEvent.click(screen.getByText('Retour'));
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(mockOnReturn).toHaveBeenCalled();
|
||||||
|
expect(mockNavigate).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('disables button while saving', async () => {
|
||||||
|
render(<ReturnButton quizTitle="Test Quiz" quizFolder="folder1" isNewQuiz />);
|
||||||
|
const button = screen.getByText('Retour');
|
||||||
|
fireEvent.click(button);
|
||||||
|
expect(button).toBeDisabled();
|
||||||
|
await waitFor(() => expect(button).not.toBeDisabled());
|
||||||
|
});
|
||||||
|
|
||||||
|
test('calls ApiService.createQuiz for new quiz with valid data', async () => {
|
||||||
|
const props = {
|
||||||
|
quizTitle: 'New Quiz',
|
||||||
|
quizContent: ['Q1', 'Q2'],
|
||||||
|
quizFolder: 'folder1',
|
||||||
|
isNewQuiz: true,
|
||||||
|
};
|
||||||
|
render(<ReturnButton {...props} />);
|
||||||
|
fireEvent.click(screen.getByText('Retour'));
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(ApiService.createQuiz).toHaveBeenCalledWith('New Quiz', ['Q1', 'Q2'], 'folder1');
|
||||||
|
expect(ApiService.updateQuiz).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('calls ApiService.updateQuiz for existing quiz with valid data', async () => {
|
||||||
|
const props = {
|
||||||
|
quizId: 'quiz123',
|
||||||
|
quizTitle: 'Updated Quiz',
|
||||||
|
quizContent: ['Q1', 'Q2'],
|
||||||
|
isNewQuiz: false,
|
||||||
|
};
|
||||||
|
render(<ReturnButton {...props} />);
|
||||||
|
fireEvent.click(screen.getByText('Retour'));
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(ApiService.updateQuiz).toHaveBeenCalledWith('quiz123', 'Updated Quiz', ['Q1', 'Q2']);
|
||||||
|
expect(ApiService.createQuiz).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('does not call ApiService if quizTitle is missing for new quiz', async () => {
|
||||||
|
render(<ReturnButton quizFolder="folder1" isNewQuiz />);
|
||||||
|
fireEvent.click(screen.getByText('Retour'));
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(ApiService.createQuiz).not.toHaveBeenCalled();
|
||||||
|
expect(ApiService.updateQuiz).not.toHaveBeenCalled();
|
||||||
|
expect(mockNavigate).toHaveBeenCalledWith('/teacher/dashboard');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('does not call ApiService if quizId and quizTitle are missing for update', async () => {
|
||||||
|
render(<ReturnButton />);
|
||||||
|
fireEvent.click(screen.getByText('Retour'));
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(ApiService.createQuiz).not.toHaveBeenCalled();
|
||||||
|
expect(ApiService.updateQuiz).not.toHaveBeenCalled();
|
||||||
|
expect(mockNavigate).toHaveBeenCalledWith('/teacher/dashboard');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('navigates even if ApiService.createQuiz fails', async () => {
|
||||||
|
(ApiService.createQuiz as jest.Mock).mockRejectedValue(new Error('Save failed'));
|
||||||
|
const props = {
|
||||||
|
quizTitle: 'New Quiz',
|
||||||
|
quizContent: ['Q1'],
|
||||||
|
quizFolder: 'folder1',
|
||||||
|
isNewQuiz: true,
|
||||||
|
};
|
||||||
|
render(<ReturnButton {...props} />);
|
||||||
|
fireEvent.click(screen.getByText('Retour'));
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(ApiService.createQuiz).toHaveBeenCalled();
|
||||||
|
expect(mockNavigate).toHaveBeenCalledWith('/teacher/dashboard');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('navigates even if ApiService.updateQuiz fails', async () => {
|
||||||
|
(ApiService.updateQuiz as jest.Mock).mockRejectedValue(new Error('Update failed'));
|
||||||
|
const props = {
|
||||||
|
quizId: 'quiz123',
|
||||||
|
quizTitle: 'Updated Quiz',
|
||||||
|
quizContent: ['Q1'],
|
||||||
|
isNewQuiz: false,
|
||||||
|
};
|
||||||
|
render(<ReturnButton {...props} />);
|
||||||
|
fireEvent.click(screen.getByText('Retour'));
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(ApiService.updateQuiz).toHaveBeenCalled();
|
||||||
|
expect(mockNavigate).toHaveBeenCalledWith('/teacher/dashboard');
|
||||||
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -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();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -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(),
|
||||||
|
|
@ -325,5 +330,53 @@ describe('ManageRoom', () => {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
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);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,62 +1,55 @@
|
||||||
import React from 'react';
|
import React from 'react';
|
||||||
import { render, screen, fireEvent } from '@testing-library/react';
|
import { render, screen, waitFor } from '@testing-library/react';
|
||||||
import '@testing-library/jest-dom';
|
import '@testing-library/jest-dom';
|
||||||
import { MemoryRouter } from 'react-router-dom';
|
import { MemoryRouter } from 'react-router-dom';
|
||||||
import QuizForm from '../../../../pages/Teacher/EditorQuiz/EditorQuiz';
|
import QuizForm from '../../../../pages/Teacher/EditorQuiz/EditorQuiz';
|
||||||
import { waitFor } from '@testing-library/react';
|
|
||||||
|
|
||||||
|
// Mock localStorage with proper TypeScript types
|
||||||
const localStorageMock = (() => {
|
const localStorageMock = (() => {
|
||||||
let store: Record<string, string> = {};
|
let store: Record<string, string> = {};
|
||||||
return {
|
return {
|
||||||
getItem: (key: string) => store[key] || null,
|
getItem: (key: string): string | null => store[key] || null,
|
||||||
setItem: (key: string, value: string) => (store[key] = value.toString()),
|
setItem: (key: string, value: string): void => {
|
||||||
clear: () => (store = {}),
|
store[key] = value.toString();
|
||||||
|
},
|
||||||
|
clear: (): void => {
|
||||||
|
store = {};
|
||||||
|
},
|
||||||
};
|
};
|
||||||
})();
|
})();
|
||||||
Object.defineProperty(window, 'localStorage', { value: localStorageMock });
|
Object.defineProperty(window, 'localStorage', { value: localStorageMock });
|
||||||
|
|
||||||
|
// Mock react-router-dom
|
||||||
|
const mockNavigate = jest.fn();
|
||||||
jest.mock('react-router-dom', () => ({
|
jest.mock('react-router-dom', () => ({
|
||||||
...jest.requireActual('react-router-dom'),
|
...jest.requireActual('react-router-dom'),
|
||||||
useNavigate: jest.fn(),
|
useNavigate: () => mockNavigate,
|
||||||
|
useParams: () => ({ id: 'new' }), // Simulate the "new" route
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Mock ApiService
|
||||||
|
jest.mock('../../../../services/ApiService', () => ({
|
||||||
|
getUserFolders: jest.fn(() => Promise.resolve([])), // Mock empty folder list
|
||||||
|
getQuiz: jest.fn(),
|
||||||
|
createQuiz: jest.fn(),
|
||||||
|
updateQuiz: jest.fn(),
|
||||||
|
uploadImage: jest.fn(),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
describe('QuizForm Component', () => {
|
describe('QuizForm Component', () => {
|
||||||
test('renders QuizForm with default state for a new quiz', () => {
|
test('renders QuizForm with default state for a new quiz', async () => {
|
||||||
render(
|
render(
|
||||||
<MemoryRouter initialEntries={['/teacher/editor-quiz/new']}>
|
<MemoryRouter initialEntries={['/teacher/editor-quiz/new']}>
|
||||||
<QuizForm />
|
<QuizForm />
|
||||||
</MemoryRouter>
|
</MemoryRouter>
|
||||||
);
|
);
|
||||||
|
|
||||||
expect(screen.queryByText('Éditeur de quiz')).toBeInTheDocument();
|
// Wait for the component to render the title
|
||||||
// expect(screen.queryByText('Éditeur')).toBeInTheDocument();
|
|
||||||
expect(screen.queryByText('Prévisualisation')).toBeInTheDocument();
|
|
||||||
});
|
|
||||||
|
|
||||||
test.skip('renders QuizForm for a new quiz', async () => {
|
|
||||||
const { container } = render(
|
|
||||||
<MemoryRouter initialEntries={['/teacher/editor-quiz']}>
|
|
||||||
<QuizForm />
|
|
||||||
</MemoryRouter>
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(screen.getByText(/Éditeur de quiz/i)).toBeInTheDocument();
|
|
||||||
|
|
||||||
// find the 'editor' text area
|
|
||||||
const editorTextArea = container.querySelector('textarea.editor');
|
|
||||||
fireEvent.change(editorTextArea!, { target: { value: 'Sample question?' } });
|
|
||||||
|
|
||||||
await waitFor(() => {
|
await waitFor(() => {
|
||||||
const sampleQuestionElements = screen.queryAllByText(/Sample question\?/i);
|
expect(screen.getByText('Éditeur de Quiz')).toBeInTheDocument();
|
||||||
expect(sampleQuestionElements.length).toBeGreaterThan(0);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const saveButton = screen.getByText(/Enregistrer/i);
|
// Check for other expected elements
|
||||||
fireEvent.click(saveButton);
|
expect(screen.getByText('Prévisualisation')).toBeInTheDocument();
|
||||||
|
|
||||||
await waitFor(() => {
|
|
||||||
expect(screen.getByText(/Sauvegarder le questionnaire/i)).toBeInTheDocument();
|
|
||||||
});
|
});
|
||||||
});
|
|
||||||
|
|
||||||
});
|
});
|
||||||
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([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -1,36 +1,202 @@
|
||||||
// Editor.tsx
|
import React, { useState } from 'react';
|
||||||
import React, { useState, useRef } from 'react';
|
import { TextField, Typography, IconButton, Box, Collapse, Dialog, DialogActions, DialogContent, DialogContentText, DialogTitle, Button } from '@mui/material';
|
||||||
import './editor.css';
|
import DeleteIcon from '@mui/icons-material/Delete';
|
||||||
import { TextareaAutosize } from '@mui/material';
|
import VisibilityIcon from '@mui/icons-material/Visibility';
|
||||||
|
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
|
||||||
|
import ExpandLessIcon from '@mui/icons-material/ExpandLess';
|
||||||
|
import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd';
|
||||||
|
|
||||||
interface EditorProps {
|
interface EditorProps {
|
||||||
label: string;
|
label: string;
|
||||||
initialValue: string;
|
values: string[];
|
||||||
onEditorChange: (value: string) => void;
|
onValuesChange: (values: string[]) => void;
|
||||||
|
onFocusQuestion?: (index: number) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
const Editor: React.FC<EditorProps> = ({ initialValue, onEditorChange, label }) => {
|
const Editor: React.FC<EditorProps> = ({ label, values, onValuesChange, onFocusQuestion }) => {
|
||||||
const [value, setValue] = useState(initialValue);
|
const [collapsed, setCollapsed] = useState<boolean[]>(Array(values.length).fill(false));
|
||||||
const editorRef = useRef<HTMLTextAreaElement | null>(null);
|
const [dialogOpen, setDialogOpen] = useState(false);
|
||||||
|
const [deleteIndex, setDeleteIndex] = useState<number | null>(null);
|
||||||
|
|
||||||
function handleEditorChange(event: React.ChangeEvent<HTMLTextAreaElement>) {
|
const handleChange = (index: number) => (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
const text = event.target.value;
|
const newValues = [...values];
|
||||||
setValue(text);
|
newValues[index] = event.target.value;
|
||||||
onEditorChange(text || '');
|
onValuesChange(newValues);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleDeleteQuestion = (index: number) => () => {
|
||||||
|
if (values[index].trim() === '') {
|
||||||
|
const newValues = values.filter((_, i) => i !== index);
|
||||||
|
onValuesChange(newValues);
|
||||||
|
setCollapsed((prev) => prev.filter((_, i) => i !== index));
|
||||||
|
} else {
|
||||||
|
setDeleteIndex(index);
|
||||||
|
setDialogOpen(true);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleConfirmDelete = () => {
|
||||||
|
if (deleteIndex !== null) {
|
||||||
|
const newValues = values.filter((_, i) => i !== deleteIndex);
|
||||||
|
onValuesChange(newValues);
|
||||||
|
setCollapsed((prev) => prev.filter((_, i) => i !== deleteIndex));
|
||||||
|
}
|
||||||
|
setDialogOpen(false);
|
||||||
|
setDeleteIndex(null);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleCancelDelete = () => {
|
||||||
|
setDialogOpen(false);
|
||||||
|
setDeleteIndex(null);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleFocusQuestion = (index: number) => () => {
|
||||||
|
if (onFocusQuestion) {
|
||||||
|
onFocusQuestion(index);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleToggleCollapse = (index: number) => () => {
|
||||||
|
setCollapsed((prev) => {
|
||||||
|
const newCollapsed = [...prev];
|
||||||
|
newCollapsed[index] = !newCollapsed[index];
|
||||||
|
return newCollapsed;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const onDragEnd = (result: any) => {
|
||||||
|
if (!result.destination) return;
|
||||||
|
|
||||||
|
const newValues = [...values];
|
||||||
|
const [reorderedItem] = newValues.splice(result.source.index, 1);
|
||||||
|
newValues.splice(result.destination.index, 0, reorderedItem);
|
||||||
|
onValuesChange(newValues);
|
||||||
|
|
||||||
|
const newCollapsed = [...collapsed];
|
||||||
|
const [reorderedCollapsed] = newCollapsed.splice(result.source.index, 1);
|
||||||
|
newCollapsed.splice(result.destination.index, 0, reorderedCollapsed);
|
||||||
|
setCollapsed(newCollapsed);
|
||||||
|
};
|
||||||
|
|
||||||
|
if (collapsed.length !== values.length) {
|
||||||
|
setCollapsed((prev) => {
|
||||||
|
const newCollapsed = [...prev];
|
||||||
|
while (newCollapsed.length < values.length) newCollapsed.push(false);
|
||||||
|
while (newCollapsed.length > values.length) newCollapsed.pop();
|
||||||
|
return newCollapsed;
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<label>
|
<div>
|
||||||
<h4>{label}</h4>
|
<Typography variant="h6" fontWeight="bold" style={{ marginBottom: '24px' }}>
|
||||||
<TextareaAutosize
|
{label}
|
||||||
id="editor-textarea"
|
</Typography>
|
||||||
ref={editorRef}
|
|
||||||
onChange={handleEditorChange}
|
<DragDropContext onDragEnd={onDragEnd}>
|
||||||
|
<Droppable droppableId="questions">
|
||||||
|
{(provided) => (
|
||||||
|
<div {...provided.droppableProps} ref={provided.innerRef}>
|
||||||
|
{values.map((value, index) => (
|
||||||
|
<Draggable key={index} draggableId={`question-${index}`} index={index}>
|
||||||
|
{(provided) => (
|
||||||
|
<Box
|
||||||
|
ref={provided.innerRef}
|
||||||
|
{...provided.draggableProps}
|
||||||
|
{...provided.dragHandleProps}
|
||||||
|
sx={{
|
||||||
|
marginBottom: '8px',
|
||||||
|
boxShadow: '0px 2px 4px rgba(0, 0, 0, 0.1)',
|
||||||
|
border: '1px solid rgba(0, 0, 0, 0.1)',
|
||||||
|
padding: '16px',
|
||||||
|
borderRadius: '4px',
|
||||||
|
...provided.draggableProps.style,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Box display="flex" alignItems="center" justifyContent="space-between">
|
||||||
|
<Typography variant="subtitle1" fontWeight="bold" style={{ marginBottom: '8px' }}>
|
||||||
|
Question {index + 1}
|
||||||
|
</Typography>
|
||||||
|
<Box>
|
||||||
|
<IconButton
|
||||||
|
onClick={handleToggleCollapse(index)}
|
||||||
|
aria-label="toggle collapse"
|
||||||
|
sx={{
|
||||||
|
color: 'gray',
|
||||||
|
'&:hover': { color: 'blue' },
|
||||||
|
mr: 1,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{collapsed[index] ? <ExpandMoreIcon /> : <ExpandLessIcon />}
|
||||||
|
</IconButton>
|
||||||
|
<IconButton
|
||||||
|
onClick={handleFocusQuestion(index)}
|
||||||
|
aria-label="focus question"
|
||||||
|
sx={{
|
||||||
|
color: 'gray',
|
||||||
|
'&:hover': { color: 'blue' },
|
||||||
|
mr: 1,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<VisibilityIcon />
|
||||||
|
</IconButton>
|
||||||
|
<IconButton
|
||||||
|
onClick={handleDeleteQuestion(index)}
|
||||||
|
aria-label="delete"
|
||||||
|
sx={{
|
||||||
|
color: 'light-gray',
|
||||||
|
'&:hover': { color: 'red' },
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<DeleteIcon />
|
||||||
|
</IconButton>
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
<Collapse in={!collapsed[index]}>
|
||||||
|
<TextField
|
||||||
value={value}
|
value={value}
|
||||||
className="editor"
|
onChange={handleChange(index)}
|
||||||
minRows={5}
|
fullWidth
|
||||||
|
multiline
|
||||||
|
minRows={4}
|
||||||
|
maxRows={Infinity}
|
||||||
|
variant="outlined"
|
||||||
|
style={{ overflow: 'auto' }}
|
||||||
/>
|
/>
|
||||||
</label>
|
</Collapse>
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
</Draggable>
|
||||||
|
))}
|
||||||
|
{provided.placeholder}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</Droppable>
|
||||||
|
</DragDropContext>
|
||||||
|
|
||||||
|
{/* Confirmation Dialog */}
|
||||||
|
<Dialog
|
||||||
|
open={dialogOpen}
|
||||||
|
onClose={handleCancelDelete}
|
||||||
|
aria-labelledby="delete-confirmation-title"
|
||||||
|
aria-describedby="delete-confirmation-description"
|
||||||
|
>
|
||||||
|
<DialogTitle id="delete-confirmation-title" sx={{ textAlign: 'center'}}>Suppression</DialogTitle>
|
||||||
|
<DialogContent>
|
||||||
|
<DialogContentText id="delete-confirmation-description">
|
||||||
|
Confirmez vous la suppression de Question {deleteIndex !== null ? deleteIndex + 1 : ''} ?
|
||||||
|
</DialogContentText>
|
||||||
|
</DialogContent>
|
||||||
|
<DialogActions sx={{ justifyContent: 'center', pb: 2 }}>
|
||||||
|
<Button onClick={handleCancelDelete} color="primary" sx={{ mx: 1 }}>
|
||||||
|
Annuler
|
||||||
|
</Button>
|
||||||
|
<Button onClick={handleConfirmDelete} color="error" sx={{ mx: 1 }} autoFocus>
|
||||||
|
Supprimer
|
||||||
|
</Button>
|
||||||
|
</DialogActions>
|
||||||
|
</Dialog>
|
||||||
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -12,22 +12,23 @@ interface GIFTTemplatePreviewProps {
|
||||||
|
|
||||||
const GIFTTemplatePreview: React.FC<GIFTTemplatePreviewProps> = ({
|
const GIFTTemplatePreview: React.FC<GIFTTemplatePreviewProps> = ({
|
||||||
questions,
|
questions,
|
||||||
hideAnswers = false
|
hideAnswers = false,
|
||||||
}) => {
|
}) => {
|
||||||
const [error, setError] = useState('');
|
const [error, setError] = useState('');
|
||||||
const [isPreviewReady, setIsPreviewReady] = useState(false);
|
const [isPreviewReady, setIsPreviewReady] = useState(false);
|
||||||
const [items, setItems] = useState('');
|
const [questionItems, setQuestionItems] = useState<string[]>([]); // Array of HTML strings for each question
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
try {
|
try {
|
||||||
let previewHTML = '';
|
const previewItems: string[] = [];
|
||||||
questions.forEach((giftQuestion) => {
|
questions.forEach((giftQuestion) => {
|
||||||
try {
|
try {
|
||||||
const question = parse(giftQuestion);
|
const question = parse(giftQuestion);
|
||||||
previewHTML += Template(question[0], {
|
const html = Template(question[0], {
|
||||||
preview: true,
|
preview: true,
|
||||||
theme: 'light'
|
theme: 'light',
|
||||||
});
|
});
|
||||||
|
previewItems.push(html);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
let errorMsg: string;
|
let errorMsg: string;
|
||||||
if (error instanceof UnsupportedQuestionTypeError) {
|
if (error instanceof UnsupportedQuestionTypeError) {
|
||||||
|
|
@ -37,18 +38,21 @@ const GIFTTemplatePreview: React.FC<GIFTTemplatePreviewProps> = ({
|
||||||
} else {
|
} else {
|
||||||
errorMsg = ErrorTemplate(giftQuestion, 'Erreur inconnue');
|
errorMsg = ErrorTemplate(giftQuestion, 'Erreur inconnue');
|
||||||
}
|
}
|
||||||
previewHTML += `<div label="error-message">${errorMsg}</div>`;
|
previewItems.push(`<div label="error-message">${errorMsg}</div>`);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
if (hideAnswers) {
|
if (hideAnswers) {
|
||||||
|
previewItems.forEach((item, index) => {
|
||||||
const svgRegex = /<svg[^>]*>([\s\S]*?)<\/svg>/gi;
|
const svgRegex = /<svg[^>]*>([\s\S]*?)<\/svg>/gi;
|
||||||
previewHTML = previewHTML.replace(svgRegex, '');
|
|
||||||
const placeholderRegex = /(placeholder=")[^"]*(")/gi;
|
const placeholderRegex = /(placeholder=")[^"]*(")/gi;
|
||||||
previewHTML = previewHTML.replace(placeholderRegex, '$1$2');
|
previewItems[index] = item
|
||||||
|
.replace(svgRegex, '')
|
||||||
|
.replace(placeholderRegex, '$1$2');
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
setItems(previewHTML);
|
setQuestionItems(previewItems);
|
||||||
setIsPreviewReady(true);
|
setIsPreviewReady(true);
|
||||||
} catch (error: unknown) {
|
} catch (error: unknown) {
|
||||||
if (error instanceof Error) {
|
if (error instanceof Error) {
|
||||||
|
|
@ -57,7 +61,7 @@ const GIFTTemplatePreview: React.FC<GIFTTemplatePreviewProps> = ({
|
||||||
setError('Une erreur est survenue durant le chargement de la prévisualisation.');
|
setError('Une erreur est survenue durant le chargement de la prévisualisation.');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}, [questions]);
|
}, [questions, hideAnswers]);
|
||||||
|
|
||||||
const PreviewComponent = () => (
|
const PreviewComponent = () => (
|
||||||
<React.Fragment>
|
<React.Fragment>
|
||||||
|
|
@ -65,8 +69,13 @@ const GIFTTemplatePreview: React.FC<GIFTTemplatePreviewProps> = ({
|
||||||
<div className="error">{error}</div>
|
<div className="error">{error}</div>
|
||||||
) : isPreviewReady ? (
|
) : isPreviewReady ? (
|
||||||
<div data-testid="preview-container">
|
<div data-testid="preview-container">
|
||||||
|
{questionItems.map((item, index) => (
|
||||||
<div dangerouslySetInnerHTML={{ __html: FormattedTextTemplate({ format: 'html', text: items }) }}></div>
|
<div
|
||||||
|
key={index}
|
||||||
|
className="question-item"
|
||||||
|
dangerouslySetInnerHTML={{ __html: FormattedTextTemplate({ format: 'html', text: item }) }}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="loading">Chargement de la prévisualisation...</div>
|
<div className="loading">Chargement de la prévisualisation...</div>
|
||||||
|
|
|
||||||
309
client/src/components/ImageGallery/ImageGallery.tsx
Normal file
309
client/src/components/ImageGallery/ImageGallery.tsx
Normal file
|
|
@ -0,0 +1,309 @@
|
||||||
|
import React, { useState, useEffect } from "react";
|
||||||
|
import {
|
||||||
|
Box,
|
||||||
|
CircularProgress,
|
||||||
|
Button,
|
||||||
|
IconButton,
|
||||||
|
Card,
|
||||||
|
CardContent,
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogActions,
|
||||||
|
DialogTitle,
|
||||||
|
DialogContentText,
|
||||||
|
Tabs,
|
||||||
|
Tab,
|
||||||
|
TextField, Snackbar,
|
||||||
|
Alert
|
||||||
|
} from "@mui/material";
|
||||||
|
import DeleteIcon from "@mui/icons-material/Delete";
|
||||||
|
import ContentCopyIcon from "@mui/icons-material/ContentCopy";
|
||||||
|
import CloseIcon from "@mui/icons-material/Close";
|
||||||
|
import { ImageType } from "../../Types/ImageType";
|
||||||
|
import ApiService from "../../services/ApiService";
|
||||||
|
import { Upload } from "@mui/icons-material";
|
||||||
|
import { escapeForGIFT } from "src/utils/giftUtils";
|
||||||
|
import { ENV_VARIABLES } from "src/constants";
|
||||||
|
|
||||||
|
interface ImagesProps {
|
||||||
|
handleCopy?: (id: string) => void;
|
||||||
|
handleDelete?: (id: string) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ImageGallery: React.FC<ImagesProps> = ({ handleCopy, handleDelete }) => {
|
||||||
|
const [images, setImages] = useState<ImageType[]>([]);
|
||||||
|
const [totalImg, setTotalImg] = useState(0);
|
||||||
|
const [imgPage, setImgPage] = useState(1);
|
||||||
|
const [imgLimit] = useState(6);
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [selectedImage, setSelectedImage] = useState<ImageType | null>(null);
|
||||||
|
const [openDeleteDialog, setOpenDeleteDialog] = useState(false);
|
||||||
|
const [imageToDelete, setImageToDelete] = useState<ImageType | null>(null);
|
||||||
|
const [tabValue, setTabValue] = useState(0);
|
||||||
|
const [importedImage, setImportedImage] = useState<File | null>(null);
|
||||||
|
const [preview, setPreview] = useState<string | null>(null);
|
||||||
|
const [snackbarOpen, setSnackbarOpen] = useState(false);
|
||||||
|
const [snackbarMessage, setSnackbarMessage] = useState("");
|
||||||
|
const [snackbarSeverity, setSnackbarSeverity] = useState<"success" | "error">("success");
|
||||||
|
|
||||||
|
const fetchImages = async () => {
|
||||||
|
setLoading(true);
|
||||||
|
const data = await ApiService.getUserImages(imgPage, imgLimit);
|
||||||
|
setImages(data.images);
|
||||||
|
setTotalImg(data.total);
|
||||||
|
setLoading(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
fetchImages();
|
||||||
|
}, [imgPage]);
|
||||||
|
|
||||||
|
const defaultHandleDelete = async (id: string) => {
|
||||||
|
if (imageToDelete) {
|
||||||
|
setLoading(true);
|
||||||
|
const isDeleted = await ApiService.deleteImage(id);
|
||||||
|
setLoading(false);
|
||||||
|
|
||||||
|
if (isDeleted) {
|
||||||
|
setImgPage(1);
|
||||||
|
fetchImages();
|
||||||
|
setSnackbarMessage("Image supprimée avec succès!");
|
||||||
|
setSnackbarSeverity("success");
|
||||||
|
} else {
|
||||||
|
setSnackbarMessage("Erreur lors de la suppression de l'image. Veuillez réessayer.");
|
||||||
|
setSnackbarSeverity("error");
|
||||||
|
}
|
||||||
|
|
||||||
|
setSnackbarOpen(true);
|
||||||
|
setSelectedImage(null);
|
||||||
|
setImageToDelete(null);
|
||||||
|
setOpenDeleteDialog(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const defaultHandleCopy = (id: string) => {
|
||||||
|
if (navigator.clipboard) {
|
||||||
|
const link = `${ENV_VARIABLES.BACKEND_URL}/api/image/get/${id}`;
|
||||||
|
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");
|
||||||
|
setSnackbarSeverity("success");
|
||||||
|
setSnackbarOpen(true);
|
||||||
|
navigator.clipboard.writeText(imgTag);
|
||||||
|
}
|
||||||
|
if(handleCopy) {
|
||||||
|
handleCopy(id);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleDeleteFunction = handleDelete || defaultHandleDelete;
|
||||||
|
|
||||||
|
const handleImageUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
|
const file = event.target.files ? event.target.files[0] : null;
|
||||||
|
setImportedImage(file);
|
||||||
|
if (file) {
|
||||||
|
const objectUrl = URL.createObjectURL(file);
|
||||||
|
setPreview(objectUrl);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSaveImage = async () => {
|
||||||
|
try {
|
||||||
|
if (!importedImage) {
|
||||||
|
setSnackbarMessage("Veuillez choisir une image à téléverser.");
|
||||||
|
setSnackbarSeverity("error");
|
||||||
|
setSnackbarOpen(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const imageUrl = await ApiService.uploadImage(importedImage);
|
||||||
|
|
||||||
|
if (imageUrl.includes("ERROR")) {
|
||||||
|
setSnackbarMessage("Une erreur est survenue. Veuillez réessayer plus tard.");
|
||||||
|
setSnackbarSeverity("error");
|
||||||
|
setSnackbarOpen(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
fetchImages();
|
||||||
|
|
||||||
|
setSnackbarMessage("Téléversée avec succès !");
|
||||||
|
setSnackbarSeverity("success");
|
||||||
|
setSnackbarOpen(true);
|
||||||
|
|
||||||
|
setImportedImage(null);
|
||||||
|
setPreview(null);
|
||||||
|
setTabValue(0);
|
||||||
|
} catch (error) {
|
||||||
|
setSnackbarMessage(`Une erreur est survenue.\n${error}\nVeuillez réessayer plus tard.`);
|
||||||
|
setSnackbarSeverity("error");
|
||||||
|
setSnackbarOpen(true);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleCloseSnackbar = () => {
|
||||||
|
setSnackbarOpen(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Box p={3}>
|
||||||
|
<Tabs value={tabValue} onChange={(_, newValue) => setTabValue(newValue)}>
|
||||||
|
<Tab label="Galerie" />
|
||||||
|
<Tab label="Import" />
|
||||||
|
</Tabs>
|
||||||
|
{tabValue === 0 && (
|
||||||
|
<>
|
||||||
|
{loading ? (
|
||||||
|
<Box display="flex" justifyContent="center" alignItems="center" height={200}>
|
||||||
|
<CircularProgress />
|
||||||
|
</Box>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<Box display="grid" gridTemplateColumns="repeat(3, 1fr)" gridTemplateRows="repeat(2, 1fr)" gap={2} maxWidth="900px" margin="auto">
|
||||||
|
{images.map((obj) => (
|
||||||
|
<Card key={obj.id} sx={{ cursor: "pointer", display: "flex", flexDirection: "column", alignItems: "center" }} onClick={() => setSelectedImage(obj)}>
|
||||||
|
<CardContent sx={{ p: 0 }}>
|
||||||
|
<img
|
||||||
|
src={`data:${obj.mime_type};base64,${obj.file_content}`}
|
||||||
|
alt={`Image ${obj.file_name}`}
|
||||||
|
style={{ width: "100%", height: 250, objectFit: "cover", borderRadius: 8 }}
|
||||||
|
/>
|
||||||
|
</CardContent>
|
||||||
|
<Box display="flex" justifyContent="center" mt={1}>
|
||||||
|
<IconButton onClick={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
defaultHandleCopy(obj.id);
|
||||||
|
}}
|
||||||
|
color="primary"
|
||||||
|
data-testid={`gallery-tab-copy-${obj.id}`} >
|
||||||
|
|
||||||
|
<ContentCopyIcon sx={{ fontSize: 18 }} />
|
||||||
|
</IconButton>
|
||||||
|
|
||||||
|
<IconButton
|
||||||
|
onClick={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
setImageToDelete(obj);
|
||||||
|
setOpenDeleteDialog(true);
|
||||||
|
}}
|
||||||
|
color="error"
|
||||||
|
data-testid={`gallery-tab-delete-${obj.id}`} >
|
||||||
|
|
||||||
|
<DeleteIcon sx={{ fontSize: 18 }} />
|
||||||
|
</IconButton>
|
||||||
|
</Box>
|
||||||
|
</Card>
|
||||||
|
))}
|
||||||
|
</Box>
|
||||||
|
<Box display="flex" justifyContent="center" mt={2}>
|
||||||
|
<Button onClick={() => setImgPage((prev) => Math.max(prev - 1, 1))} disabled={imgPage === 1} color="primary">
|
||||||
|
Précédent
|
||||||
|
</Button>
|
||||||
|
<Button onClick={() => setImgPage((prev) => (prev * imgLimit < totalImg ? prev + 1 : prev))} disabled={imgPage * imgLimit >= totalImg} color="primary">
|
||||||
|
Suivant
|
||||||
|
</Button>
|
||||||
|
</Box>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{tabValue === 1 && (
|
||||||
|
<Box display="flex" flexDirection="column" alignItems="center" width="100%" mt={3}>
|
||||||
|
{/* Image Preview at the top */}
|
||||||
|
{preview && (
|
||||||
|
<Box
|
||||||
|
mt={2}
|
||||||
|
mb={2}
|
||||||
|
sx={{
|
||||||
|
width: "100%",
|
||||||
|
maxWidth: 600,
|
||||||
|
textAlign: "center",
|
||||||
|
display: "flex",
|
||||||
|
justifyContent: "center",
|
||||||
|
alignItems: "center",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<img
|
||||||
|
src={preview}
|
||||||
|
alt="Preview"
|
||||||
|
style={{
|
||||||
|
width: "100%",
|
||||||
|
height: "auto",
|
||||||
|
borderRadius: 8,
|
||||||
|
maxHeight: "600px",
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
<Box display="flex" flexDirection="row" alignItems="center" width="100%" maxWidth={400}>
|
||||||
|
<TextField
|
||||||
|
type="file"
|
||||||
|
data-testid="file-input"
|
||||||
|
onChange={handleImageUpload}
|
||||||
|
slotProps={{
|
||||||
|
htmlInput: {
|
||||||
|
"data-testid": "file-input",
|
||||||
|
accept: "image/*",
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
sx={{ flexGrow: 1 }}
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
variant="outlined"
|
||||||
|
aria-label="Téléverser"
|
||||||
|
onClick={() => { handleSaveImage() }}
|
||||||
|
sx={{ ml: 2, height: "100%" }}
|
||||||
|
>
|
||||||
|
Téléverser <Upload sx={{ ml: 1 }} />
|
||||||
|
</Button>
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
<Dialog open={!!selectedImage} onClose={() => setSelectedImage(null)} maxWidth="md">
|
||||||
|
<IconButton color="primary" onClick={() => setSelectedImage(null)} sx={{ position: "absolute", right: 8, top: 8, zIndex: 1 }}
|
||||||
|
data-testid="close-button">
|
||||||
|
<CloseIcon />
|
||||||
|
</IconButton>
|
||||||
|
<DialogContent>
|
||||||
|
{selectedImage && (
|
||||||
|
<img
|
||||||
|
src={`data:${selectedImage.mime_type};base64,${selectedImage.file_content}`}
|
||||||
|
alt="Enlarged view"
|
||||||
|
style={{ width: "100%", height: "auto", borderRadius: 8, maxHeight: "500px" }}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
|
||||||
|
{/* Delete Confirmation Dialog */}
|
||||||
|
<Dialog open={openDeleteDialog} onClose={() => setOpenDeleteDialog(false)}>
|
||||||
|
<DialogTitle>Supprimer</DialogTitle>
|
||||||
|
<DialogContent>
|
||||||
|
<DialogContentText>Voulez-vous supprimer cette image?</DialogContentText>
|
||||||
|
</DialogContent>
|
||||||
|
<DialogActions>
|
||||||
|
<Button onClick={() => setOpenDeleteDialog(false)} color="primary">
|
||||||
|
Annuler
|
||||||
|
</Button>
|
||||||
|
<Button onClick={() => imageToDelete && handleDeleteFunction(imageToDelete.id)} color="error">
|
||||||
|
Delete
|
||||||
|
</Button>
|
||||||
|
</DialogActions>
|
||||||
|
</Dialog>
|
||||||
|
|
||||||
|
<Snackbar
|
||||||
|
open={snackbarOpen}
|
||||||
|
autoHideDuration={4000}
|
||||||
|
onClose={handleCloseSnackbar}
|
||||||
|
>
|
||||||
|
<Alert
|
||||||
|
onClose={handleCloseSnackbar}
|
||||||
|
severity={snackbarSeverity}
|
||||||
|
sx={{ width: "100%" }}>
|
||||||
|
{snackbarMessage}
|
||||||
|
</Alert>
|
||||||
|
</Snackbar>
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default ImageGallery;
|
||||||
|
|
@ -0,0 +1,55 @@
|
||||||
|
import React, { useState } from "react";
|
||||||
|
import {
|
||||||
|
Button,
|
||||||
|
IconButton,
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
} from "@mui/material";
|
||||||
|
import CloseIcon from "@mui/icons-material/Close";
|
||||||
|
import ImageGallery from "../ImageGallery";
|
||||||
|
import { ImageSearch } from "@mui/icons-material";
|
||||||
|
|
||||||
|
|
||||||
|
interface ImageGalleryModalProps {
|
||||||
|
handleCopy?: (id: string) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
const ImageGalleryModal: React.FC<ImageGalleryModalProps> = ({ handleCopy }) => {
|
||||||
|
const [open, setOpen] = useState<boolean>(false);
|
||||||
|
|
||||||
|
const handleOpen = () => setOpen(true);
|
||||||
|
const handleClose = () => setOpen(false);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Button
|
||||||
|
variant="outlined"
|
||||||
|
aria-label='images-open'
|
||||||
|
onClick={() => handleOpen()}>
|
||||||
|
Images <ImageSearch />
|
||||||
|
</Button>
|
||||||
|
<Dialog open={open} onClose={handleClose} maxWidth="md" fullWidth>
|
||||||
|
<DialogContent sx={{ display: "flex", flexDirection: "column", alignItems: "center", py: 3 }}>
|
||||||
|
<IconButton
|
||||||
|
onClick={handleClose}
|
||||||
|
color="primary"
|
||||||
|
aria-label="close"
|
||||||
|
sx={{
|
||||||
|
position: "absolute",
|
||||||
|
right: 8,
|
||||||
|
top: 8,
|
||||||
|
zIndex: 1,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<CloseIcon />
|
||||||
|
</IconButton>
|
||||||
|
|
||||||
|
<ImageGallery handleCopy={handleCopy}/>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default ImageGalleryModal;
|
||||||
|
|
@ -1,65 +1,69 @@
|
||||||
// GoBackButton.tsx
|
import React, { useState } from 'react';
|
||||||
import React from 'react';
|
|
||||||
import { useState } from 'react';
|
|
||||||
import { useNavigate } from 'react-router-dom';
|
import { useNavigate } from 'react-router-dom';
|
||||||
import ConfirmDialog from '../ConfirmDialog/ConfirmDialog';
|
|
||||||
import { Button } from '@mui/material';
|
import { Button } from '@mui/material';
|
||||||
import { ChevronLeft } from '@mui/icons-material';
|
import { ChevronLeft } from '@mui/icons-material';
|
||||||
|
import ApiService from '../../services/ApiService'; // Assuming this is where save logic lives
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
onReturn?: () => void;
|
onReturn?: () => void;
|
||||||
askConfirm?: boolean;
|
quizTitle?: string; // Quiz title to save
|
||||||
message?: string;
|
quizContent?: string[]; // Quiz content to save
|
||||||
|
quizFolder?: string; // Folder ID to save
|
||||||
|
quizId?: string; // Quiz ID for updates (optional)
|
||||||
|
isNewQuiz?: boolean; // Flag to determine create or update
|
||||||
}
|
}
|
||||||
|
|
||||||
const ReturnButton: React.FC<Props> = ({
|
const ReturnButton: React.FC<Props> = ({
|
||||||
askConfirm = false,
|
onReturn,
|
||||||
message = 'Êtes-vous sûr de vouloir quitter la page ?',
|
quizTitle = '',
|
||||||
onReturn
|
quizContent = [],
|
||||||
|
quizFolder = '',
|
||||||
|
quizId,
|
||||||
|
isNewQuiz = false,
|
||||||
}) => {
|
}) => {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const [showDialog, setShowDialog] = useState(false);
|
const [isSaving, setIsSaving] = useState(false); // Optional: to show saving state
|
||||||
|
|
||||||
const handleOnReturnButtonClick = () => {
|
const handleOnReturnButtonClick = async () => {
|
||||||
if (askConfirm) {
|
setIsSaving(true);
|
||||||
setShowDialog(true);
|
try {
|
||||||
} else {
|
// Automatically save the quiz
|
||||||
handleOnReturn();
|
if (isNewQuiz && quizTitle && quizFolder) {
|
||||||
|
await ApiService.createQuiz(quizTitle, quizContent, quizFolder);
|
||||||
|
} else if (quizId && quizTitle) {
|
||||||
|
await ApiService.updateQuiz(quizId, quizTitle, quizContent);
|
||||||
}
|
}
|
||||||
};
|
// If no title/folder, proceed without saving (optional behavior)
|
||||||
|
|
||||||
const handleConfirm = () => {
|
|
||||||
setShowDialog(false);
|
|
||||||
handleOnReturn();
|
handleOnReturn();
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error saving quiz on return:', error);
|
||||||
|
// Still navigate even if save fails, to avoid trapping the user
|
||||||
|
handleOnReturn();
|
||||||
|
} finally {
|
||||||
|
setIsSaving(false);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleOnReturn = () => {
|
const handleOnReturn = () => {
|
||||||
if (onReturn) {
|
if (onReturn) {
|
||||||
onReturn();
|
onReturn();
|
||||||
} else {
|
} else {
|
||||||
navigate(-1);
|
navigate('/teacher/dashboard'); // Navigate to dashboard instead of -1
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className='returnButton'>
|
<div className="returnButton">
|
||||||
<Button
|
<Button
|
||||||
variant="text"
|
variant="text"
|
||||||
startIcon={<ChevronLeft />}
|
startIcon={<ChevronLeft />}
|
||||||
onClick={handleOnReturnButtonClick}
|
onClick={handleOnReturnButtonClick}
|
||||||
color="primary"
|
color="primary"
|
||||||
sx={{ marginLeft: '-0.5rem', fontSize: 16 }}
|
sx={{ marginLeft: '-0.5rem', fontSize: 16 }}
|
||||||
|
disabled={isSaving} // Disable button while saving
|
||||||
>
|
>
|
||||||
Retour
|
{isSaving ? 'Enregistrement...' : 'Retour'}
|
||||||
</Button>
|
</Button>
|
||||||
<ConfirmDialog
|
|
||||||
open={showDialog}
|
|
||||||
title="Confirmer"
|
|
||||||
message={message}
|
|
||||||
onConfirm={handleConfirm}
|
|
||||||
onCancel={() => setShowDialog(false)}
|
|
||||||
buttonOrderType="warning"
|
|
||||||
/>
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
|
||||||
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;
|
||||||
|
|
@ -2,8 +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 || "",
|
||||||
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}`);
|
||||||
|
|
|
||||||
|
|
@ -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,9 +13,10 @@ 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 = Array<string | number | boolean>;
|
export type AnswerType = Array<string | number | boolean>;
|
||||||
|
|
||||||
|
|
@ -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();
|
||||||
|
|
@ -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,9 +210,11 @@ 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}
|
||||||
|
>
|
||||||
|
{/* Afficher champ salle SEULEMENT si pas de QR code */}
|
||||||
|
{!isQRCodeJoin && (
|
||||||
<TextField
|
<TextField
|
||||||
type="text"
|
type="text"
|
||||||
label="Nom de la salle"
|
label="Nom de la salle"
|
||||||
|
|
@ -212,7 +226,9 @@ const JoinRoom: React.FC = () => {
|
||||||
fullWidth={true}
|
fullWidth={true}
|
||||||
onKeyDown={handleReturnKey}
|
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>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -39,9 +39,8 @@ import {
|
||||||
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)({
|
||||||
|
|
@ -401,28 +400,6 @@ const Dashboard: React.FC = () => {
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
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>
|
<div className="title">Tableau de bord</div>
|
||||||
|
|
@ -587,7 +564,7 @@ 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"
|
||||||
|
|
@ -603,7 +580,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 +590,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 +600,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)}
|
||||||
|
|
@ -633,7 +610,7 @@ const Dashboard: React.FC = () => {
|
||||||
</IconButton>
|
</IconButton>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
|
|
||||||
<Tooltip title="Supprimer quiz" placement="top">
|
<Tooltip title="Supprimer" placement="top">
|
||||||
<IconButton
|
<IconButton
|
||||||
aria-label="delete"
|
aria-label="delete"
|
||||||
color="primary"
|
color="primary"
|
||||||
|
|
@ -644,15 +621,9 @@ const Dashboard: React.FC = () => {
|
||||||
</IconButton>
|
</IconButton>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
|
|
||||||
<Tooltip title="Partager quiz" placement="top">
|
<div className="quiz-share">
|
||||||
<IconButton
|
<ShareQuizModal quiz={quiz} />
|
||||||
color="primary"
|
</div>
|
||||||
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';
|
||||||
|
|
@ -11,12 +11,16 @@ import GIFTTemplatePreview from 'src/components/GiftTemplate/GIFTTemplatePreview
|
||||||
import { QuizType } from '../../../Types/QuizType';
|
import { QuizType } from '../../../Types/QuizType';
|
||||||
|
|
||||||
import './editorQuiz.css';
|
import './editorQuiz.css';
|
||||||
import { Button, TextField, NativeSelect, Divider, Dialog, DialogTitle, DialogActions, DialogContent } from '@mui/material';
|
import { Button, TextField, NativeSelect, Divider, Dialog, DialogTitle, DialogActions, DialogContent, MenuItem, Select, Snackbar } 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 { Upload } from '@mui/icons-material';
|
||||||
|
import SaveIcon from '@mui/icons-material/Save';
|
||||||
|
import { ENV_VARIABLES } from 'src/constants';
|
||||||
|
|
||||||
interface EditQuizParams {
|
interface EditQuizParams {
|
||||||
id: string;
|
id: string;
|
||||||
|
|
@ -29,7 +33,7 @@ const QuizForm: React.FC = () => {
|
||||||
const [filteredValue, setFilteredValue] = useState<string[]>([]);
|
const [filteredValue, setFilteredValue] = useState<string[]>([]);
|
||||||
|
|
||||||
const { id } = useParams<EditQuizParams>();
|
const { id } = useParams<EditQuizParams>();
|
||||||
const [value, setValue] = useState('');
|
const [values, setValues] = useState<string[]>([]);
|
||||||
const [isNewQuiz, setNewQuiz] = useState(false);
|
const [isNewQuiz, setNewQuiz] = useState(false);
|
||||||
const [quiz, setQuiz] = useState<QuizType | null>(null);
|
const [quiz, setQuiz] = useState<QuizType | null>(null);
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
|
@ -38,10 +42,29 @@ 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 [isImagesCollapsed, setIsImagesCollapsed] = useState(true);
|
||||||
|
const [isCheatSheetCollapsed, setIsCheatSheetCollapsed] = useState(true);
|
||||||
|
const [isUploadCollapsed, setIsUploadCollapsed] = useState(true);
|
||||||
|
const [snackbarOpen, setSnackbarOpen] = useState(false);
|
||||||
|
const [snackbarMessage, setSnackbarMessage] = useState('');
|
||||||
|
const [copySuccess, setCopySuccess] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const QuestionVraiFaux = "::Exemple de question vrai/faux:: \n 2+2 \\= 4 ? {T} //Utilisez les valeurs {T}, {F}, {TRUE} et {FALSE}.";
|
||||||
|
const QuestionChoixMul = "::Ville capitale du Canada:: \nQuelle ville est la capitale du Canada? {\n~ Toronto\n~ Montréal\n= Ottawa #Rétroaction spécifique.\n} // Commentaire non visible (au besoin)";
|
||||||
|
const QuestionChoixMulMany = "::Villes canadiennes:: \n Quelles villes trouve-t-on au Canada? { \n~ %33.3% Montréal \n ~ %33.3% Ottawa \n ~ %33.3% Vancouver \n ~ %-100% New York \n ~ %-100% Paris \n#### Rétroaction globale de la question. \n} // Utilisez tilde (signe de vague) pour toutes les réponses. // On doit indiquer le pourcentage de chaque réponse.";
|
||||||
|
const QuestionCourte = "::Clé et porte:: \n Avec quoi ouvre-t-on une porte? { \n= clé \n= clef \n} // Permet de fournir plusieurs bonnes réponses. // Note: La casse n'est pas prise en compte.";
|
||||||
|
const QuestionNum = "::Question numérique avec marge:: \nQuel est un nombre de 1 à 5 ? {\n#3:2\n}\n \n// Plage mathématique spécifiée avec des points de fin d'intervalle. \n ::Question numérique avec plage:: \n Quel est un nombre de 1 à 5 ? {\n#1..5\n} \n\n// Réponses numériques multiples avec crédit partiel et commentaires.\n::Question numérique avec plusieurs réponses::\nQuand est né Ulysses S. Grant ? {\n# =1822:0 # Correct ! Crédit complet. \n=%50%1822:2 # Il est né en 1822. Demi-crédit pour être proche.\n}";
|
||||||
|
|
||||||
|
const templates = [
|
||||||
|
{ label: 'Vrai/Faux', value: QuestionVraiFaux },
|
||||||
|
{ label: 'Choix multiples R1', value: QuestionChoixMul },
|
||||||
|
{ label: 'Choix multiples R2+', value: QuestionChoixMulMany },
|
||||||
|
{ label: 'Réponse courte', value: QuestionCourte },
|
||||||
|
{ label: 'Numérique', value: QuestionNum },
|
||||||
|
];
|
||||||
|
|
||||||
const scrollToTop = () => {
|
const scrollToTop = () => {
|
||||||
window.scrollTo({ top: 0, behavior: 'smooth' });
|
window.scrollTo({ top: 0, behavior: 'smooth' });
|
||||||
};
|
};
|
||||||
|
|
@ -101,7 +124,7 @@ const QuizForm: React.FC = () => {
|
||||||
setQuizTitle(title);
|
setQuizTitle(title);
|
||||||
setSelectedFolder(folderId);
|
setSelectedFolder(folderId);
|
||||||
setFilteredValue(content);
|
setFilteredValue(content);
|
||||||
setValue(quiz.content.join('\n\n'));
|
setValues(content);
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
window.alert(`Une erreur est survenue.\n Veuillez réessayer plus tard`)
|
window.alert(`Une erreur est survenue.\n Veuillez réessayer plus tard`)
|
||||||
|
|
@ -113,21 +136,17 @@ const QuizForm: React.FC = () => {
|
||||||
fetchData();
|
fetchData();
|
||||||
}, [id]);
|
}, [id]);
|
||||||
|
|
||||||
function handleUpdatePreview(value: string) {
|
const handleAddQuestion = () => {
|
||||||
if (value !== '') {
|
console.log("Adding question");
|
||||||
setValue(value);
|
console.log("Current values:", values); // Log current state
|
||||||
}
|
setValues([...values, '']);
|
||||||
|
console.log("Updated values:", [...values, '']); // Log new state
|
||||||
|
};
|
||||||
|
|
||||||
// split value when there is at least one blank line
|
const handleUpdatePreview = (newValues: string[]) => {
|
||||||
const linesArray = value.split(/\n{2,}/);
|
setValues(newValues);
|
||||||
|
setFilteredValue(newValues.filter(value => value.trim() !== ''));
|
||||||
// if the first item in linesArray is blank, remove it
|
};
|
||||||
if (linesArray[0] === '') linesArray.shift();
|
|
||||||
|
|
||||||
if (linesArray[linesArray.length - 1] === '') linesArray.pop();
|
|
||||||
|
|
||||||
setFilteredValue(linesArray);
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleQuizTitleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
|
const handleQuizTitleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
setQuizTitle(event.target.value);
|
setQuizTitle(event.target.value);
|
||||||
|
|
@ -135,7 +154,6 @@ const QuizForm: React.FC = () => {
|
||||||
|
|
||||||
const handleQuizSave = async () => {
|
const handleQuizSave = async () => {
|
||||||
try {
|
try {
|
||||||
// check if everything is there
|
|
||||||
if (quizTitle == '') {
|
if (quizTitle == '') {
|
||||||
alert("Veuillez choisir un titre");
|
alert("Veuillez choisir un titre");
|
||||||
return;
|
return;
|
||||||
|
|
@ -154,7 +172,8 @@ const QuizForm: React.FC = () => {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
navigate('/teacher/dashboard');
|
setSnackbarMessage('Quiz enregistré avec succès!');
|
||||||
|
setSnackbarOpen(true);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
window.alert(`Une erreur est survenue.\n Veuillez réessayer plus tard`)
|
window.alert(`Une erreur est survenue.\n Veuillez réessayer plus tard`)
|
||||||
console.log(error)
|
console.log(error)
|
||||||
|
|
@ -166,6 +185,10 @@ const QuizForm: React.FC = () => {
|
||||||
return <div>Chargement...</div>;
|
return <div>Chargement...</div>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const handleSnackbarClose = () => {
|
||||||
|
setSnackbarOpen(false);
|
||||||
|
};
|
||||||
|
|
||||||
const handleSaveImage = async () => {
|
const handleSaveImage = async () => {
|
||||||
try {
|
try {
|
||||||
const inputElement = document.getElementById('file-input') as HTMLInputElement;
|
const inputElement = document.getElementById('file-input') as HTMLInputElement;
|
||||||
|
|
@ -204,16 +227,54 @@ const QuizForm: React.FC = () => {
|
||||||
navigator.clipboard.writeText(link);
|
navigator.clipboard.writeText(link);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const handleFocusQuestion = (index: number) => {
|
||||||
|
const previewElement = document.querySelector('.preview-column');
|
||||||
|
if (previewElement) {
|
||||||
|
const questionElements = previewElement.querySelectorAll('.question-item');
|
||||||
|
if (questionElements[index]) {
|
||||||
|
questionElements[index].scrollIntoView({ behavior: 'smooth', block: 'start' });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const copyToClipboard = (text: string, label: string) => {
|
||||||
|
navigator.clipboard.writeText(text)
|
||||||
|
.then(() => {
|
||||||
|
setCopySuccess(`Copié dans le presse-papier: ${label}`);
|
||||||
|
})
|
||||||
|
.catch((error) => console.error('Clipboard error:', error));
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSelectChange = (value: string, label: string) => {
|
||||||
|
copyToClipboard(value, label);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleCopyImage = (id: string) => {
|
||||||
|
const escLink = `${ENV_VARIABLES.BACKEND_URL}/api/image/get/${id}`;
|
||||||
|
setImageLinks(prevLinks => [...prevLinks, escLink]);
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className='quizEditor'>
|
<div className='quizEditor'>
|
||||||
|
|
||||||
<div className='editHeader'>
|
<div className='editHeader'
|
||||||
|
style={{
|
||||||
|
display: 'flex',
|
||||||
|
justifyContent: 'space-between',
|
||||||
|
alignItems: 'center',
|
||||||
|
marginBottom: '32px'
|
||||||
|
}}>
|
||||||
<ReturnButton
|
<ReturnButton
|
||||||
askConfirm
|
quizTitle={quizTitle}
|
||||||
message={`Êtes-vous sûr de vouloir quitter l'éditeur sans sauvegarder le questionnaire?`}
|
quizContent={filteredValue}
|
||||||
|
quizFolder={selectedFolder}
|
||||||
|
quizId={quiz?._id}
|
||||||
|
isNewQuiz={isNewQuiz}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<div className='title'>Éditeur de quiz</div>
|
|
||||||
|
|
||||||
|
<div className='title'>Éditeur de Quiz</div>
|
||||||
|
|
||||||
<div className='dumb'></div>
|
<div className='dumb'></div>
|
||||||
</div>
|
</div>
|
||||||
|
|
@ -243,9 +304,41 @@ const QuizForm: React.FC = () => {
|
||||||
))}
|
))}
|
||||||
</NativeSelect></label>
|
</NativeSelect></label>
|
||||||
|
|
||||||
<Button variant="contained" onClick={handleQuizSave}>
|
|
||||||
|
<div className='sticky-buttons'>
|
||||||
|
<Select
|
||||||
|
value=""
|
||||||
|
displayEmpty
|
||||||
|
onChange={(e) => handleSelectChange(e.target.value, templates.find(t => t.value === e.target.value)?.label || '')}
|
||||||
|
style={{ width: '210px' }}
|
||||||
|
inputProps={{
|
||||||
|
'data-testid': 'template-select'
|
||||||
|
}}
|
||||||
|
|
||||||
|
>
|
||||||
|
<MenuItem value="" disabled>Modèles de questions</MenuItem>
|
||||||
|
{templates.map((template, index) => (
|
||||||
|
<MenuItem key={index} value={template.value}>{template.label}</MenuItem>
|
||||||
|
))}
|
||||||
|
</Select>
|
||||||
|
<Button
|
||||||
|
variant="contained"
|
||||||
|
onClick={handleQuizSave}
|
||||||
|
sx={{ display: 'flex', alignItems: 'center' }}
|
||||||
|
>
|
||||||
|
<SaveIcon sx={{ fontSize: 20 }} />
|
||||||
Enregistrer
|
Enregistrer
|
||||||
</Button>
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Snackbar
|
||||||
|
open={!!copySuccess}
|
||||||
|
autoHideDuration={3000}
|
||||||
|
onClose={() => setCopySuccess(null)}
|
||||||
|
message={copySuccess}
|
||||||
|
anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
|
||||||
|
key={copySuccess ? 'open' : 'close'}
|
||||||
|
/>
|
||||||
|
|
||||||
<Divider style={{ margin: '16px 0' }} />
|
<Divider style={{ margin: '16px 0' }} />
|
||||||
|
|
||||||
|
|
@ -253,32 +346,47 @@ const QuizForm: React.FC = () => {
|
||||||
|
|
||||||
<div className='edit'>
|
<div className='edit'>
|
||||||
<Editor
|
<Editor
|
||||||
label="Contenu GIFT du quiz:"
|
label=""
|
||||||
initialValue={value}
|
values={values}
|
||||||
onEditorChange={handleUpdatePreview} />
|
onValuesChange={handleUpdatePreview}
|
||||||
|
onFocusQuestion={handleFocusQuestion} />
|
||||||
<div className='images'>
|
<Button variant="contained" onClick={handleAddQuestion}>
|
||||||
<div className='upload'>
|
Ajouter une question
|
||||||
<label className="dropArea">
|
|
||||||
<input type="file" id="file-input" className="file-input"
|
|
||||||
accept="image/jpeg, image/png"
|
|
||||||
multiple
|
|
||||||
ref={fileInputRef} />
|
|
||||||
|
|
||||||
<Button
|
|
||||||
variant="outlined"
|
|
||||||
aria-label='Téléverser'
|
|
||||||
onClick={handleSaveImage}>
|
|
||||||
Téléverser <Upload />
|
|
||||||
</Button>
|
</Button>
|
||||||
|
|
||||||
|
<div className="images">
|
||||||
|
{/* Collapsible Upload Section */}
|
||||||
|
<div style={{ marginTop: '8px' }}>
|
||||||
|
<Button
|
||||||
|
variant="outlined"
|
||||||
|
onClick={() => setIsUploadCollapsed(!isUploadCollapsed)}
|
||||||
|
style={{ padding: '4px 8px', fontSize: '12px', marginBottom: '4px', width: '40%' }}
|
||||||
|
>
|
||||||
|
{isUploadCollapsed ? 'Afficher Téléverser image' : 'Masquer Téléverser image'}
|
||||||
|
</Button>
|
||||||
|
{!isUploadCollapsed && (
|
||||||
|
<div className="upload">
|
||||||
|
<label className="dropArea">
|
||||||
|
<input
|
||||||
|
type="file"
|
||||||
|
id="file-input"
|
||||||
|
className="file-input"
|
||||||
|
accept="image/jpeg, image/png"
|
||||||
|
multiple
|
||||||
|
ref={fileInputRef}
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
variant="outlined"
|
||||||
|
aria-label="Téléverser"
|
||||||
|
onClick={handleSaveImage}
|
||||||
|
>
|
||||||
|
Téléverser <Upload />
|
||||||
|
</Button>
|
||||||
</label>
|
</label>
|
||||||
<Dialog
|
<Dialog open={dialogOpen} onClose={() => setDialogOpen(false)}>
|
||||||
open={dialogOpen}
|
|
||||||
onClose={() => setDialogOpen(false)} >
|
|
||||||
<DialogTitle>Erreur</DialogTitle>
|
<DialogTitle>Erreur</DialogTitle>
|
||||||
<DialogContent>
|
<DialogContent>
|
||||||
Veuillez d'abord choisir une image à téléverser.
|
Veuillez d'abord choisir une image à téléverser.
|
||||||
</DialogContent>
|
</DialogContent>
|
||||||
<DialogActions>
|
<DialogActions>
|
||||||
<Button onClick={() => setDialogOpen(false)} color="primary">
|
<Button onClick={() => setDialogOpen(false)} color="primary">
|
||||||
|
|
@ -287,16 +395,37 @@ const QuizForm: React.FC = () => {
|
||||||
</DialogActions>
|
</DialogActions>
|
||||||
</Dialog>
|
</Dialog>
|
||||||
</div>
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Collapsible Images Section */}
|
||||||
|
<div style={{ marginTop: '2px' }}>
|
||||||
|
<Button
|
||||||
|
variant="outlined"
|
||||||
|
onClick={() => setIsImagesCollapsed(!isImagesCollapsed)}
|
||||||
|
style={{ padding: '4px 8px', fontSize: '12px', marginBottom: '4px', width: '40%' }}
|
||||||
|
>
|
||||||
|
{isImagesCollapsed ? 'Afficher Mes images' : 'Masquer Mes images'}
|
||||||
|
</Button>
|
||||||
|
{!isImagesCollapsed && (
|
||||||
|
<div>
|
||||||
<h4>Mes images :</h4>
|
<h4>Mes images :</h4>
|
||||||
<div>
|
<div>
|
||||||
<div>
|
<div>
|
||||||
<div style={{ display: "inline" }}>(Voir section </div>
|
<div style={{ display: 'inline' }}>(Voir section </div>
|
||||||
<a href="#images-section"style={{ textDecoration: "none" }} onClick={scrollToImagesSection}>
|
<a
|
||||||
<u><em><h4 style={{ display: "inline" }}> 9. Images </h4></em></u>
|
href="#images-section"
|
||||||
|
style={{ textDecoration: 'none' }}
|
||||||
|
onClick={scrollToImagesSection}
|
||||||
|
>
|
||||||
|
<u>
|
||||||
|
<em>
|
||||||
|
<h4 style={{ display: 'inline' }}> 9. Images </h4>
|
||||||
|
</em>
|
||||||
|
</u>
|
||||||
</a>
|
</a>
|
||||||
<div style={{ display: "inline" }}> ci-dessous</div>
|
<div style={{ display: 'inline' }}> ci-dessous</div>
|
||||||
<div style={{ display: "inline" }}>)</div>
|
<div style={{ display: 'inline' }}>)</div>
|
||||||
<br />
|
<br />
|
||||||
<em> - Cliquez sur un lien pour le copier</em>
|
<em> - Cliquez sur un lien pour le copier</em>
|
||||||
</div>
|
</div>
|
||||||
|
|
@ -305,8 +434,7 @@ const QuizForm: React.FC = () => {
|
||||||
const imgTag = `} "texte de l'infobulle")`;
|
const imgTag = `} "texte de l'infobulle")`;
|
||||||
return (
|
return (
|
||||||
<li key={index}>
|
<li key={index}>
|
||||||
<code
|
<code onClick={() => handleCopyToClipboard(imgTag)}>
|
||||||
onClick={() => handleCopyToClipboard(imgTag)}>
|
|
||||||
{imgTag}
|
{imgTag}
|
||||||
</code>
|
</code>
|
||||||
</li>
|
</li>
|
||||||
|
|
@ -315,12 +443,24 @@ const QuizForm: React.FC = () => {
|
||||||
</ul>
|
</ul>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
)}
|
||||||
<GiftCheatSheet />
|
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className='preview'>
|
{/* Collapsible CheatSheet Section */}
|
||||||
|
<div style={{ marginTop: '2px' }}>
|
||||||
|
<Button
|
||||||
|
variant="outlined"
|
||||||
|
onClick={() => setIsCheatSheetCollapsed(!isCheatSheetCollapsed)}
|
||||||
|
style={{ padding: '4px 8px', fontSize: '12px', marginBottom: '4px', width: '40%' }}
|
||||||
|
>
|
||||||
|
{isCheatSheetCollapsed ? 'Afficher CheatSheet' : 'Masquer CheatSheet'}
|
||||||
|
</Button>
|
||||||
|
{!isCheatSheetCollapsed && <GiftCheatSheet />}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="preview">
|
||||||
<div className="preview-column">
|
<div className="preview-column">
|
||||||
<h4>Prévisualisation</h4>
|
<h4>Prévisualisation</h4>
|
||||||
<div>
|
<div>
|
||||||
|
|
@ -328,7 +468,6 @@ const QuizForm: React.FC = () => {
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{showScrollButton && (
|
{showScrollButton && (
|
||||||
|
|
@ -342,6 +481,14 @@ const QuizForm: React.FC = () => {
|
||||||
↑
|
↑
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
<Snackbar
|
||||||
|
open={snackbarOpen}
|
||||||
|
autoHideDuration={3000} // Hide after 3 seconds
|
||||||
|
onClose={handleSnackbarClose}
|
||||||
|
message={snackbarMessage}
|
||||||
|
anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }} // Lower-right corner
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -80,6 +80,24 @@ input[type="file"] {
|
||||||
.quizEditor .editSection .preview {
|
.quizEditor .editSection .preview {
|
||||||
flex: 50%;
|
flex: 50%;
|
||||||
padding: 5px;
|
padding: 5px;
|
||||||
|
|
||||||
overflow: auto;
|
overflow: auto;
|
||||||
|
height: 100%;
|
||||||
|
position: relative;
|
||||||
|
}
|
||||||
|
|
||||||
|
.quizEditor {
|
||||||
|
margin: 0 -2rem; /* Counteract the padding */
|
||||||
|
width: calc(100% + 4rem); /* Expand to fill padded area */
|
||||||
|
}
|
||||||
|
|
||||||
|
.sticky-buttons {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
position: sticky;
|
||||||
|
top: 0;
|
||||||
|
background: #fff;
|
||||||
|
z-index: 1000;
|
||||||
|
padding: 8px 0;
|
||||||
}
|
}
|
||||||
|
|
@ -9,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';
|
||||||
|
|
@ -18,8 +19,18 @@ 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 {
|
||||||
|
Button,
|
||||||
|
Dialog,
|
||||||
|
DialogTitle,
|
||||||
|
DialogContent,
|
||||||
|
DialogContentText,
|
||||||
|
DialogActions
|
||||||
|
} from '@mui/material';
|
||||||
import { checkIfIsCorrect } from './useRooms';
|
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();
|
||||||
|
|
@ -34,6 +45,16 @@ const ManageRoom: React.FC = () => {
|
||||||
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);
|
||||||
|
|
||||||
|
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
|
// 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
|
||||||
|
|
@ -77,6 +98,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(
|
||||||
|
|
@ -386,7 +416,62 @@ const ManageRoom: React.FC = () => {
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="room">
|
<div className="room">
|
||||||
<h1>Salle : {formattedRoomName}</h1>
|
{/* En-tête avec titre et bouton QR code*/}
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
display: 'flex',
|
||||||
|
justifyContent: 'space-between',
|
||||||
|
alignItems: 'center',
|
||||||
|
marginBottom: '20px'
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<h1 style={{ margin: 0 }}>Salle : {formattedRoomName}</h1>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
variant="contained"
|
||||||
|
color="primary"
|
||||||
|
onClick={() => setShowQrModal(true)}
|
||||||
|
startIcon={<QRCodeIcon />}
|
||||||
|
>
|
||||||
|
Lien de participation
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Modale QR Code */}
|
||||||
|
<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 className="roomHeader">
|
||||||
<DisconnectButton
|
<DisconnectButton
|
||||||
onReturn={handleReturn}
|
onReturn={handleReturn}
|
||||||
|
|
|
||||||
|
|
@ -1,46 +1,46 @@
|
||||||
// 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';
|
||||||
|
|
||||||
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');
|
navigate('/teacher/dashboard');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!ApiService.isLoggedIn()) {
|
if (!ApiService.isLoggedIn()) {
|
||||||
window.alert(`Vous n'êtes pas connecté.\nVeuillez vous connecter et revenir à ce lien`);
|
|
||||||
navigate("/login");
|
navigate("/login");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const quizIds = await ApiService.getAllQuizIds();
|
||||||
|
|
||||||
|
if (quizIds.includes(id)) {
|
||||||
|
setQuizExists(true);
|
||||||
|
setLoading(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const userFolders = await ApiService.getUserFolders();
|
const userFolders = await ApiService.getUserFolders();
|
||||||
|
|
||||||
if (userFolders.length == 0) {
|
if (userFolders.length == 0) {
|
||||||
window.alert(`Vous n'avez aucun dossier.\nVeuillez en créer un et revenir à ce lien`)
|
|
||||||
navigate('/teacher/dashboard');
|
navigate('/teacher/dashboard');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
@ -50,17 +50,22 @@ const Share: React.FC = () => {
|
||||||
const title = await ApiService.getSharedQuiz(id);
|
const title = await ApiService.getSharedQuiz(id);
|
||||||
|
|
||||||
if (!title) {
|
if (!title) {
|
||||||
window.alert(`Une erreur est survenue.\n Veuillez 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;
|
||||||
}
|
}
|
||||||
|
|
||||||
setQuizTitle(title);
|
setQuizTitle(title);
|
||||||
|
setLoading(false);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching data:', error);
|
||||||
|
setLoading(false);
|
||||||
|
navigate('/teacher/dashboard');
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
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 +73,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,47 +88,89 @@ 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 (
|
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'>Quiz déjà existant</div>
|
||||||
|
</div>
|
||||||
<div className='dumb'></div>
|
<div className='dumb'></div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className='editSection'>
|
<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>
|
||||||
|
|
||||||
<div>
|
<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 (
|
||||||
|
<div className='quizImport'>
|
||||||
|
<div className='importHeader'>
|
||||||
|
<ReturnButton />
|
||||||
|
<div className='titleContainer'>
|
||||||
|
<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>
|
||||||
|
|
||||||
|
<div className='editSection'>
|
||||||
|
<div className='formContainer'>
|
||||||
<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">
|
||||||
Enregistrer
|
Enregistrer
|
||||||
</Button>
|
</Button>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -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 */
|
||||||
|
}
|
||||||
|
|
@ -3,6 +3,7 @@ import { jwtDecode } from 'jwt-decode';
|
||||||
import { ENV_VARIABLES } from '../constants';
|
import { ENV_VARIABLES } from '../constants';
|
||||||
|
|
||||||
import { FolderType } from 'src/Types/FolderType';
|
import { FolderType } from 'src/Types/FolderType';
|
||||||
|
import { ImagesResponse, ImagesParams } from '../Types/Images';
|
||||||
import { QuizType } from 'src/Types/QuizType';
|
import { QuizType } from 'src/Types/QuizType';
|
||||||
import { RoomType } from 'src/Types/RoomType';
|
import { RoomType } from 'src/Types/RoomType';
|
||||||
|
|
||||||
|
|
@ -74,8 +75,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);
|
||||||
|
|
||||||
|
|
@ -91,7 +90,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
|
||||||
|
|
@ -103,7 +101,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;
|
||||||
}
|
}
|
||||||
|
|
@ -142,6 +139,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`);
|
||||||
|
|
@ -178,7 +191,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';
|
||||||
|
|
@ -190,7 +202,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;
|
||||||
|
|
@ -553,7 +564,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) {
|
||||||
|
|
@ -843,36 +853,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) {
|
||||||
|
|
@ -1167,7 +1147,126 @@ public async login(email: string, password: string): Promise<any> {
|
||||||
return `ERROR : Une erreur inattendue s'est produite.`
|
return `ERROR : Une erreur inattendue s'est produite.`
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// NOTE : Get Image pas necessaire
|
|
||||||
|
public async getImages(page: number, limit: number): Promise<ImagesResponse> {
|
||||||
|
try {
|
||||||
|
const url: string = this.constructRequestUrl(`/image/getImages`);
|
||||||
|
const headers = this.constructRequestHeaders();
|
||||||
|
let params : ImagesParams = { page: page, limit: limit };
|
||||||
|
|
||||||
|
const result: AxiosResponse = await axios.get(url, { params: params, headers: headers });
|
||||||
|
|
||||||
|
if (result.status !== 200) {
|
||||||
|
throw new Error(`L'affichage des images 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 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> {
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -54,7 +54,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