├── .firebase
└── hosting.YnVpbGQ.cache
├── .firebaserc
├── .gitignore
├── README.md
├── firebase.json
├── package-lock.json
├── package.json
├── public
├── favicon.ico
├── index.html
├── logo192.png
├── logo512.png
├── manifest.json
└── robots.txt
├── src
├── API.ts
├── App.styles.ts
├── App.tsx
├── components
│ ├── QuestionCard.styles.ts
│ └── QuestionCard.tsx
├── firebase.js
├── images
│ └── backImage.jpeg
├── index.tsx
├── react-app-env.d.ts
└── utils.ts
└── tsconfig.json
/.firebase/hosting.YnVpbGQ.cache:
--------------------------------------------------------------------------------
1 | asset-manifest.json,1654066420158,571aca3881f91f5a000c706c88c3eb09f8e702aaaeaac69266450d55821d1fa8
2 | index.html,1654066420158,e0ab40a2c6e8214896a19033b940b1b058043874dc949cb3fb56f616c390b6d9
3 | favicon.ico,1654066418003,b72f7455f00e4e58792d2bca892abb068e2213838c0316d6b7a0d6d16acd1955
4 | logo192.png,1654066418004,caff018b7f1e8fd481eb1c50d75b0ef236bcd5078b1d15c8bb348453fee30293
5 | robots.txt,1654066418004,391d14b3c2f8c9143a27a28c7399585142228d4d1bdbe2c87ac946de411fa9a2
6 | manifest.json,1654066418004,341d52628782f8ac9290bbfc43298afccb47b7cbfcee146ae30cf0f46bc30900
7 | logo512.png,1654066418004,191fc21360b4ccfb1cda11a1efb97f489ed22672ca83f4064316802bbfdd750e
8 | static/js/main.2ce3b527.js.LICENSE.txt,1654066420160,4b7671650f1f590038366dbdd4817c6479d27d71c882ee70ee83171178f239c1
9 | static/js/main.2ce3b527.js,1654066420160,17b346da5173f584f21b43421ec50fad15d78e42dd42617bcad5da69d473e425
10 | static/media/backImage.c866d607938d6048d5e1.jpeg,1654066420160,0ee88f0ce50bbb3c5dbbb61fc4393d828e62deb3e5d9d85ad3b2616fbc390911
11 | static/js/main.2ce3b527.js.map,1654066420160,09a2b407747a9c2d06511b61081ea99dc0d600cf7d5417732d5f6b16fbf15675
12 |
--------------------------------------------------------------------------------
/.firebaserc:
--------------------------------------------------------------------------------
1 | {
2 | "projects": {
3 | "default": "quiztypescript"
4 | }
5 | }
6 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2 |
3 | # dependencies
4 | /node_modules
5 | /.pnp
6 | .pnp.js
7 |
8 | # testing
9 | /coverage
10 |
11 | # production
12 | /build
13 |
14 | # misc
15 | .DS_Store
16 | .env.local
17 | .env.development.local
18 | .env.test.local
19 | .env.production.local
20 |
21 | npm-debug.log*
22 | yarn-debug.log*
23 | yarn-error.log*
24 | /.env
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Getting Started with Create React App
2 |
3 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).\
4 | ## VIEW DEMO
5 |
6 | ## Available Scripts
7 |
8 | In the project directory, you can run:
9 |
10 | ### `npm start`
11 |
12 | Runs the app in the development mode.\
13 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
14 |
15 | The page will reload if you make edits.\
16 | You will also see any lint errors in the console.
17 |
18 | ### `npm test`
19 |
20 | Launches the test runner in the interactive watch mode.\
21 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
22 |
23 | ### `npm run build`
24 |
25 | Builds the app for production to the `build` folder.\
26 | It correctly bundles React in production mode and optimizes the build for the best performance.
27 |
28 | The build is minified and the filenames include the hashes.\
29 | Your app is ready to be deployed!
30 |
31 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
32 |
33 | ### `npm run eject`
34 |
35 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!**
36 |
37 | If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
38 |
39 | Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
40 |
41 | You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
42 |
43 | ## Learn More
44 |
45 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
46 |
47 | To learn React, check out the [React documentation](https://reactjs.org/).
48 |
--------------------------------------------------------------------------------
/firebase.json:
--------------------------------------------------------------------------------
1 | {
2 | "hosting": {
3 | "public": "build",
4 | "ignore": [
5 | "firebase.json",
6 | "**/.*",
7 | "**/node_modules/**"
8 | ],
9 | "rewrites": [
10 | {
11 | "source": "**",
12 | "destination": "/index.html"
13 | }
14 | ]
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "quiz",
3 | "version": "0.1.0",
4 | "private": true,
5 | "dependencies": {
6 | "@testing-library/jest-dom": "^5.16.4",
7 | "@testing-library/react": "^13.2.0",
8 | "@testing-library/user-event": "^13.5.0",
9 | "@types/jest": "^27.5.1",
10 | "@types/node": "^16.11.36",
11 | "@types/react": "^18.0.9",
12 | "@types/react-dom": "^18.0.5",
13 | "@types/styled-components": "^5.1.25",
14 | "dotenv": "^16.0.1",
15 | "firebase": "^9.8.2",
16 | "react": "^18.1.0",
17 | "react-dom": "^18.1.0",
18 | "react-scripts": "5.0.1",
19 | "styled-components": "^5.3.5",
20 | "typescript": "^4.7.2",
21 | "web-vitals": "^2.1.4"
22 | },
23 | "scripts": {
24 | "start": "react-scripts start",
25 | "build": "react-scripts build",
26 | "test": "react-scripts test",
27 | "eject": "react-scripts eject"
28 | },
29 | "eslintConfig": {
30 | "extends": [
31 | "react-app",
32 | "react-app/jest"
33 | ]
34 | },
35 | "browserslist": {
36 | "production": [
37 | ">0.2%",
38 | "not dead",
39 | "not op_mini all"
40 | ],
41 | "development": [
42 | "last 1 chrome version",
43 | "last 1 firefox version",
44 | "last 1 safari version"
45 | ]
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MorgueMorg/TypeScript-React-Quiz/709c404d1e73c1c6d2727460c8688f879e58c564/public/favicon.ico
--------------------------------------------------------------------------------
/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
12 |
13 |
14 |
15 |
19 |
23 |
24 |
33 | React App
34 |
35 |
36 | You need to enable JavaScript to run this app.
37 |
38 |
48 |
49 |
50 |
--------------------------------------------------------------------------------
/public/logo192.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MorgueMorg/TypeScript-React-Quiz/709c404d1e73c1c6d2727460c8688f879e58c564/public/logo192.png
--------------------------------------------------------------------------------
/public/logo512.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MorgueMorg/TypeScript-React-Quiz/709c404d1e73c1c6d2727460c8688f879e58c564/public/logo512.png
--------------------------------------------------------------------------------
/public/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "short_name": "React App",
3 | "name": "Create React App Sample",
4 | "icons": [
5 | {
6 | "src": "favicon.ico",
7 | "sizes": "64x64 32x32 24x24 16x16",
8 | "type": "image/x-icon"
9 | },
10 | {
11 | "src": "logo192.png",
12 | "type": "image/png",
13 | "sizes": "192x192"
14 | },
15 | {
16 | "src": "logo512.png",
17 | "type": "image/png",
18 | "sizes": "512x512"
19 | }
20 | ],
21 | "start_url": ".",
22 | "display": "standalone",
23 | "theme_color": "#000000",
24 | "background_color": "#ffffff"
25 | }
26 |
--------------------------------------------------------------------------------
/public/robots.txt:
--------------------------------------------------------------------------------
1 | # https://www.robotstxt.org/robotstxt.html
2 | User-agent: *
3 | Disallow:
4 |
--------------------------------------------------------------------------------
/src/API.ts:
--------------------------------------------------------------------------------
1 | import { shuffleArray } from "./utils";
2 |
3 | export type Question = {
4 | category: string;
5 | correct_answer: string;
6 | difficulty: string;
7 | incorrect_answers: string[];
8 | question: string;
9 | type: string;
10 | };
11 |
12 | export type QuestionState = Question & { answers: string[] };
13 |
14 | // Тип enum в тайпскрите или перечисление позволяет определить набор именнованных констант, которые описывают определенные состояния.
15 | export enum Difficulty {
16 | EASY = "easy",
17 | MEDIUM = "medium",
18 | HARD = "hard",
19 | }
20 |
21 | export const fetchQuizQuestions = async (
22 | amount: number,
23 | difficulty: Difficulty
24 | ) => {
25 | const endpoint = `https://opentdb.com/api.php?amount=${amount}&difficulty=${difficulty}&type=multiple`;
26 | // два раза await потому что ждет пока преобразую в json
27 | const data = await (await fetch(endpoint)).json();
28 | return data.results.map((question: Question) => ({
29 | ...question,
30 | answers: shuffleArray([
31 | ...question.incorrect_answers,
32 | question.correct_answer,
33 | ]),
34 | }));
35 | };
36 |
--------------------------------------------------------------------------------
/src/App.styles.ts:
--------------------------------------------------------------------------------
1 | import styled, { createGlobalStyle } from "styled-components";
2 | import BGImage from "./images/backImage.jpeg";
3 |
4 | export const GlobalStyle = createGlobalStyle`
5 | html {
6 | height: 100%;
7 | }
8 | body {
9 | background-image: url(${BGImage});
10 | background-size: cover;
11 | margin: 0;
12 | padding: 0;
13 | display: flex;
14 | justify-content: center;
15 | }
16 | * {
17 | box-sizing: border-box;
18 | font-family: 'Catamaran', sans-serif;
19 | }
20 | `;
21 |
22 | export const Wrapper = styled.div`
23 | display: flex;
24 | flex-direction: column;
25 | align-items: center;
26 |
27 | > p {
28 | color: #fff;
29 | }
30 |
31 | .score {
32 | color: #fff;
33 | font-size: 2rem;
34 | margin: 0;
35 | }
36 |
37 | h1 {
38 | font-family: Fascinate Inline;
39 | background-image: linear-gradient(180deg, #fff, #87f1ff);
40 | font-weight: 400;
41 | background-size: 100%;
42 | background-clip: text;
43 | -webkit-background-clip: text;
44 | -webkit-text-fill-color: transparent;
45 | -moz-background-clip: text;
46 | -moz-text-fill-color: transparent;
47 | filter: drop-shadow(2px 2px #0085a3);
48 | font-size: 70px;
49 | text-align: center;
50 | margin: 20px;
51 | }
52 |
53 | .start,
54 | .next {
55 | cursor: pointer;
56 | background: linear-gradient(180deg, #fff, #ffcc91);
57 | border: 2px solid #d38558;
58 | box-shadow: 0px 5px 10px rgba(0, 0, 0, 0.25);
59 | border-radius: 10px;
60 | margin: 20px 0;
61 | padding: 0 40px;
62 | }
63 |
64 | .start {
65 | max-width: 200px;
66 | }
67 | `;
68 |
--------------------------------------------------------------------------------
/src/App.tsx:
--------------------------------------------------------------------------------
1 | import React, { useState } from "react";
2 | import { fetchQuizQuestions } from "./API";
3 | // Components
4 | import QuestionCard from "./components/QuestionCard";
5 | // Types
6 | import { QuestionState, Difficulty } from "./API";
7 | // Styles
8 | import { GlobalStyle, Wrapper } from "./App.styles";
9 |
10 | // Создание нового типа
11 | export type AnswerObject = {
12 | question: string;
13 | answer: string;
14 | correct: boolean;
15 | correctAnswer: string;
16 | };
17 |
18 | const TOTAL_QUESTIONS = 10;
19 |
20 | const App = () => {
21 | const [loading, setLoading] = useState(false);
22 | // Говорим тайпскрипту что это будет массив
23 | const [questions, setQuestions] = useState([]);
24 | const [number, setNumber] = useState(0);
25 | const [userAnswers, setUserAnswers] = useState([]);
26 | const [score, setScore] = useState(0);
27 | const [gameOver, setGameOver] = useState(true);
28 |
29 | // Функция должна получить два заданных параметра, иначе будет жаловаться(плюсики тайпскрипта)
30 | console.log(questions);
31 |
32 | const startTrivia = async () => {
33 | setLoading(true);
34 | setGameOver(false);
35 |
36 | const newQuestions = await fetchQuizQuestions(
37 | TOTAL_QUESTIONS,
38 | Difficulty.EASY
39 | );
40 |
41 | setQuestions(newQuestions);
42 | setScore(0);
43 | setUserAnswers([]);
44 | setNumber(0);
45 | setLoading(false);
46 | };
47 |
48 | const checkAnswer = (e: React.MouseEvent) => {
49 | // Если игра не закончена
50 | if (!gameOver) {
51 | // Ответ юзера
52 | const answer = e.currentTarget.value;
53 | // Проверка ответа на правильность
54 | const correct = questions[number].correct_answer === answer;
55 | // Добавление баллов если ответ правильный
56 | if (correct) setScore((prev) => prev + 1);
57 | // Сохрание ответа в массиве ответов
58 | const answerObject = {
59 | question: questions[number].question,
60 | answer,
61 | correct,
62 | correctAnswer: questions[number].correct_answer,
63 | };
64 | setUserAnswers((prev) => [...prev, answerObject]);
65 | }
66 | };
67 |
68 | const nextQuestion = () => {
69 | // Перейти на следующий вопрос если ответ не последний
70 | const nextQuestion = number + 1;
71 |
72 | if (nextQuestion === TOTAL_QUESTIONS) {
73 | setGameOver(true);
74 | } else {
75 | setNumber(nextQuestion);
76 | }
77 | };
78 |
79 | return (
80 | <>
81 |
82 |
83 | TYPESCRIPT QUIZ
84 | {/* Проверка, если все ответы равны 10 то вернет null */}
85 | {gameOver || userAnswers.length === TOTAL_QUESTIONS ? (
86 |
87 | Start
88 |
89 | ) : null}
90 | {!gameOver ? Score: {score}
: null}
91 | {loading && Loading Questions...
}
92 | {/* Без пропсов будет компонент будет ругаться */}
93 | {/* Если игра не окончена, будет показана карта с вопросом */}
94 | {!loading && !gameOver && (
95 |
103 | )}
104 | {/* Если юзер не ответил на вопрос кнопка не появится, если ответил то появится(number + 1 = типо ответ юзера) */}
105 | {!gameOver &&
106 | !loading &&
107 | userAnswers.length === number + 1 &&
108 | number !== TOTAL_QUESTIONS - 1 ? (
109 |
110 | Next Question
111 |
112 | ) : null}
113 |
114 | >
115 | );
116 | };
117 |
118 | export default App;
119 |
--------------------------------------------------------------------------------
/src/components/QuestionCard.styles.ts:
--------------------------------------------------------------------------------
1 | import styled from "styled-components";
2 |
3 | export const Wrapper = styled.div`
4 | max-width: 1100px;
5 | background: #ebfeff;
6 | border-radius: 10px;
7 | border: 2px solid #0085a3;
8 | padding: 20px;
9 | box-shadow: 0px 5px 10px rgba(0, 0, 0, 0.25);
10 | text-align: center;
11 |
12 | p {
13 | font-size: 1rem;
14 | }
15 | `;
16 |
17 | type ButtonWrapperProps = {
18 | correct: boolean;
19 | userClicked: boolean;
20 | };
21 |
22 | export const ButtonWrapper = styled.div`
23 | transition: all 0.3s ease;
24 |
25 | :hover {
26 | opacity: 0.8;
27 | }
28 |
29 | button {
30 | cursor: pointer;
31 | user-select: none;
32 | font-size: 0.8rem;
33 | width: 100%;
34 | height: 40px;
35 | margin: 5px 0;
36 | background: ${({ correct, userClicked }) =>
37 | correct
38 | ? "linear-gradient(90deg, #56ffa4, #59bc86)"
39 | : !correct && userClicked
40 | ? "linear-gradient(90deg, #ff5656, #c16868)"
41 | : "linear-gradient(90deg, #56ccff, #6eafb4)"};
42 | border: 3px solid #fff;
43 | box-shadow: 1px 2px 0px rgba(0, 0, 0, 0.1);
44 | border-radius: 10px;
45 | color: #fff;
46 | text-shadow: 0px 1px 0px rgba(0, 0, 0, 0.25);
47 | }
48 | `;
49 |
--------------------------------------------------------------------------------
/src/components/QuestionCard.tsx:
--------------------------------------------------------------------------------
1 | import React from "react";
2 | import { AnswerObject } from "../App";
3 | import { Wrapper, ButtonWrapper } from "./QuestionCard.styles";
4 |
5 | // Callback ничего не возвращает поэтому указываю как void
6 | type Props = {
7 | question: string;
8 | answers: string[];
9 | callback: (e: React.MouseEvent) => void;
10 | userAnswer: AnswerObject | undefined;
11 | questionNum: number;
12 | totalQuestions: number;
13 | };
14 |
15 | // FC => Указывает что это функциональный компонент
16 | // Снизу обычные пропсы которые можно юзать в компоненте
17 | const QuestionCard: React.FC = ({
18 | question,
19 | answers,
20 | callback,
21 | userAnswer,
22 | questionNum,
23 | totalQuestions,
24 | }) => {
25 | return (
26 |
27 |
28 | Question: {questionNum} / {totalQuestions}
29 |
30 | {/* dangerouslySetInnerHTML -> используем потому что не знаем какие данные парсим, опасные или нет */}
31 | {/* Вторые косые скобки из за того что внутри обьект */}
32 |
33 |
34 | {answers.map((answer) => (
35 |
40 | {/* Без ответа нельзя будет прочитать значение(value=answer) */}
41 | {/* Превратил ответ юзера в булевое значение через тернарный оператор*/}
42 |
47 |
48 |
49 |
50 | ))}
51 |
52 |
53 | );
54 | };
55 |
56 | export default QuestionCard;
57 |
--------------------------------------------------------------------------------
/src/firebase.js:
--------------------------------------------------------------------------------
1 | // Import the functions you need from the SDKs you need
2 | import { initializeApp } from "firebase/app";
3 | import {config} from 'dotenv'
4 | config()
5 | // TODO: Add SDKs for Firebase products that you want to use
6 | // https://firebase.google.com/docs/web/setup#available-libraries
7 |
8 | // Your web app's Firebase configuration
9 | const firebaseConfig = {
10 | apiKey: process.env.API_KEY,
11 | authDomain: process.env.AUTHDOMAIN,
12 | projectId: process.env.PROJECTID,
13 | storageBucket: process.env.STORAGEBUCKET,
14 | messagingSenderId: process.env.MESSAGINGSENDERID,
15 | appId: process.env.APPID,
16 | };
17 |
18 | // Initialize Firebase
19 | const app = initializeApp(firebaseConfig);
--------------------------------------------------------------------------------
/src/images/backImage.jpeg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MorgueMorg/TypeScript-React-Quiz/709c404d1e73c1c6d2727460c8688f879e58c564/src/images/backImage.jpeg
--------------------------------------------------------------------------------
/src/index.tsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import ReactDOM from 'react-dom/client';
3 | import App from './App';
4 |
5 | const root = ReactDOM.createRoot(
6 | document.getElementById('root') as HTMLElement
7 | );
8 | root.render(
9 |
10 |
11 |
12 | );
13 |
--------------------------------------------------------------------------------
/src/react-app-env.d.ts:
--------------------------------------------------------------------------------
1 | ///
2 |
--------------------------------------------------------------------------------
/src/utils.ts:
--------------------------------------------------------------------------------
1 | export const shuffleArray = (array: any[]) =>
2 | [...array].sort(() => Math.random() - 0.5);
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "target": "es5",
4 | "lib": [
5 | "dom",
6 | "dom.iterable",
7 | "esnext"
8 | ],
9 | "allowJs": true,
10 | "skipLibCheck": true,
11 | "esModuleInterop": true,
12 | "allowSyntheticDefaultImports": true,
13 | "strict": true,
14 | "forceConsistentCasingInFileNames": true,
15 | "noFallthroughCasesInSwitch": true,
16 | "module": "esnext",
17 | "moduleResolution": "node",
18 | "resolveJsonModule": true,
19 | "isolatedModules": true,
20 | "noEmit": true,
21 | "jsx": "react-jsx"
22 | },
23 | "include": [
24 | "src"
25 | ]
26 | }
27 |
--------------------------------------------------------------------------------