This commit is contained in:
2025-07-20 13:38:44 +02:00
commit a58df1cb8e
35 changed files with 4108 additions and 0 deletions

24
frontend/.gitignore vendored Normal file
View File

@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

69
frontend/README.md Normal file
View File

@@ -0,0 +1,69 @@
# React + TypeScript + Vite
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) for Fast Refresh
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
## Expanding the ESLint configuration
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
```js
export default tseslint.config([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Remove tseslint.configs.recommended and replace with this
...tseslint.configs.recommendedTypeChecked,
// Alternatively, use this for stricter rules
...tseslint.configs.strictTypeChecked,
// Optionally, add this for stylistic rules
...tseslint.configs.stylisticTypeChecked,
// Other configs...
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
```js
// eslint.config.js
import reactX from 'eslint-plugin-react-x'
import reactDom from 'eslint-plugin-react-dom'
export default tseslint.config([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Enable lint rules for React
reactX.configs['recommended-typescript'],
// Enable lint rules for React DOM
reactDom.configs.recommended,
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```

BIN
frontend/bun.lockb Executable file

Binary file not shown.

23
frontend/eslint.config.js Normal file
View File

@@ -0,0 +1,23 @@
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'
import { globalIgnores } from 'eslint/config'
export default tseslint.config([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
js.configs.recommended,
tseslint.configs.recommended,
reactHooks.configs['recommended-latest'],
reactRefresh.configs.vite,
],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
},
])

13
frontend/index.html Normal file
View File

@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/ico" href="/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Rick and Morty Tournament</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

31
frontend/package.json Normal file
View File

@@ -0,0 +1,31 @@
{
"name": "frontend",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"@tailwindcss/vite": "^4.1.11",
"react": "^19.1.0",
"react-dom": "^19.1.0",
"tailwindcss": "^4.1.11"
},
"devDependencies": {
"@eslint/js": "^9.30.1",
"@types/react": "^19.1.8",
"@types/react-dom": "^19.1.6",
"@vitejs/plugin-react-swc": "^3.10.2",
"eslint": "^9.30.1",
"eslint-plugin-react-hooks": "^5.2.0",
"eslint-plugin-react-refresh": "^0.4.20",
"globals": "^16.3.0",
"typescript": "~5.8.3",
"typescript-eslint": "^8.35.1",
"vite": "^7.0.3"
}
}

BIN
frontend/public/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

BIN
frontend/public/morty.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

137
frontend/src/App.tsx Normal file
View File

@@ -0,0 +1,137 @@
// src/App.tsx
import React, { useEffect, useState } from "react";
import { getCharacters, rateCharacters } from "./api";
import type { Character } from "./types";
import { Card } from "./components/card";
import { Table } from "./components/table";
import { getId } from "./utils";
function getRandomIndex(length: number) {
return Math.floor(Math.random() * length);
}
function getRandomPair(characters: Character[], lastPair: [number, number]) {
if (characters.length < 2) return [null, null];
let firstIndex = getRandomIndex(characters.length);
let secondIndex = getRandomIndex(characters.length);
while (
firstIndex === lastPair[0] ||
secondIndex === lastPair[1] ||
firstIndex === secondIndex
) {
firstIndex = getRandomIndex(characters.length);
secondIndex = getRandomIndex(characters.length);
}
return [characters[firstIndex], characters[secondIndex]];
}
const App: React.FC = () => {
const [characters, setCharacters] = useState<Character[]>([]);
const [rivals, setRivals] = useState<[Character | null, Character | null]>([
null,
null,
]);
const [voting, setVoting] = useState(false);
const [, setVotedLeft] = useState(false);
const [skipped, setSkipped] = useState(false);
const [lastPair] = useState<[number, number]>([0, 0]);
const currentYear = new Date().getFullYear();
useEffect(() => {
(async () => {
const chars = await getCharacters();
setCharacters(chars);
const [first, second] = getRandomPair(chars, lastPair);
setRivals([first, second]);
})();
}, []);
const generateNewRivals = () => {
const [first, second] = getRandomPair(characters, lastPair);
setRivals([first, second]);
};
const handleVote = async (winnerIdx: 0 | 1, loserIdx: 0 | 1) => {
if (voting || !rivals[winnerIdx] || !rivals[loserIdx]) return;
setVoting(true);
setVotedLeft(winnerIdx === 0);
const winnerId = getId(rivals[winnerIdx]);
const loserId = getId(rivals[loserIdx]);
if (!winnerId || !loserId) return;
await rateCharacters(winnerId, loserId);
const chars = await getCharacters();
setCharacters(chars);
setTimeout(() => {
setVoting(false);
generateNewRivals();
}, 1000);
};
const handleSkip = () => {
setSkipped(true);
setTimeout(() => {
setSkipped(false);
generateNewRivals();
}, 1000);
};
return (
<div className="flex flex-col w-full min-h-screen items-center bg-gray-900 gap-2">
<h1 className="text-center text-white text-7xl">Rick & Morty</h1>
<h2 className="text-center text-white text-5xl">Tournament</h2>
<div className="bg-gray-700 flex flex-col justify-center rounded p-2 shadow-lg m-4">
<h1 className="text-center text-white text-2xl font-bold">
How does it work?
</h1>
<p className="text-center text-white">
Below there are two cards with two characters.
</p>
<p className="text-center text-white">
Choose whichever character you like better.
</p>
<p className="text-center text-white">Enjoy!</p>
</div>
{/* Loader can be added here */}
<div className="flex flex-wrap flex-row gap-1 items-center justify-center w-full">
{rivals[0] && (
<Card
data={rivals[0]}
isClicked={voting}
skipped={skipped}
onClick={() => handleVote(0, 1)}
isRight={false}
/>
)}
{rivals[1] && (
<Card
data={rivals[1]}
isClicked={voting}
skipped={skipped}
onClick={() => handleVote(1, 0)}
isRight={true}
/>
)}
</div>
{rivals[0] && (
<>
<button
className="bg-gray-50 p-2 rounded w-24 shadow"
onClick={handleSkip}
>
Skip &gt;&gt;
</button>
<h1 className="text-white text-4xl">Top 10</h1>
<Table characters={characters.slice(0, 10)} />
</>
)}
<span className="flex-1"></span>
<p className="m-1 text-white">
Copyright {currentYear} Gabriel Kaszewski
</p>
</div>
);
};
export default App;

14
frontend/src/api.ts Normal file
View File

@@ -0,0 +1,14 @@
import type { Character } from './types';
export const getCharacters = async (): Promise<Character[]> => {
const res = await fetch('/characters');
return res.json();
};
export const rateCharacters = async (winnerId: string, loserId: string) => {
await fetch('/rate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ winner_id: winnerId, loser_id: loserId }),
});
};

View File

@@ -0,0 +1,62 @@
import React from 'react';
import type { Character } from '../types';
interface CardProps {
data: Character;
isClicked?: boolean;
skipped?: boolean;
onClick?: () => void;
isRight?: boolean;
}
export const Card: React.FC<CardProps> = ({
data,
isClicked,
skipped,
onClick,
}) => (
<div
className={`card bg-gray-300 flex flex-col items-center shadow-lg rounded p-1 transform transition ease-in-out ${isClicked || skipped ? 'flip-card' : ''} md:hover:scale-105`}
onClick={onClick}
style={{ cursor: 'pointer' }}
>
<div className="card-inner">
{/* FRONT */}
<div className="card-front flex flex-col items-center">
<h1 className="text-lg font-bold">{data.name}</h1>
<img className="avatar" src={data.image} alt={data.name} />
<h2 className="text-lg text-center font-bold">Info</h2>
<div className="w-full md:w-2/3">
<table className="table-auto text-left">
<tbody>
<tr>
<th>Species</th>
<td>{data.species}</td>
</tr>
<tr>
<th>Gender</th>
<td>{data.gender}</td>
</tr>
<tr>
<th>Status</th>
<td>{data.status}</td>
</tr>
<tr>
<th>Origin</th>
<td>{data.origin.name}</td>
</tr>
<tr>
<th>Last location</th>
<td>{data.location.name}</td>
</tr>
</tbody>
</table>
</div>
</div>
{/* BACK */}
<div className="card-back">
{/* You can put whatever you want here, like a background or extra info */}
</div>
</div>
</div>
);

View File

@@ -0,0 +1,10 @@
// src/components/TableElement.tsx
import React from 'react';
import type { Character } from '../types';
export const TableElement: React.FC<{ character: Character }> = ({ character }) => (
<div className="flex items-center gap-2">
<img className="avatar" src={character.image} alt={character.name} />
<p className="text-white text-lg">{character.name}</p>
</div>
);

View File

@@ -0,0 +1,11 @@
import React from 'react';
import type { Character } from '../types';
import { TableElement } from './table-element';
export const Table: React.FC<{ characters: Character[] }> = ({ characters }) => (
<div className="flex flex-col gap-2 m-4">
{characters.map((character) => (
<TableElement key={character.rmid} character={character} />
))}
</div>
);

42
frontend/src/index.css Normal file
View File

@@ -0,0 +1,42 @@
@import "tailwindcss";
.card {
height: 470px;
width: 300px;
perspective: 1000px;
}
.card-inner {
position: relative;
width: 100%;
height: 100%;
transition: transform 0.8s;
transform-style: preserve-3d;
}
.flip-card .card-inner {
transform: rotateY(180deg);
}
.card-front, .card-back {
position: absolute;
width: 100%;
height: 100%;
backface-visibility: hidden;
}
.card-back {
transform: rotateY(180deg);
background-image: url("/morty.png"); /* Adjust path as needed */
background-position: center;
background-size: contain;
background-repeat: no-repeat;
display: flex;
align-items: center;
justify-content: center;
}
.avatar {
width: 150px;
height: 150px;
}

10
frontend/src/main.tsx Normal file
View File

@@ -0,0 +1,10 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.tsx'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
)

21
frontend/src/types.ts Normal file
View File

@@ -0,0 +1,21 @@
export interface OriginOrLocation {
name: string;
url: string;
}
export interface Character {
_id: string | { $oid: string };
rmid: number;
name: string;
status: string;
species: string;
type: string;
gender: string;
origin: OriginOrLocation;
location: OriginOrLocation;
image: string;
episode: string[];
url: string;
created: string;
elo_rating: number;
}

9
frontend/src/utils.ts Normal file
View File

@@ -0,0 +1,9 @@
import type { Character } from "./types";
export function getId(character: Character | null) {
if (!character) return undefined;
const id = character._id as string | { $oid: string } | undefined;
if (typeof id === 'string') return id;
if (id && typeof id.$oid === 'string') return id.$oid;
return undefined;
}

1
frontend/src/vite-env.d.ts vendored Normal file
View File

@@ -0,0 +1 @@
/// <reference types="vite/client" />

View File

@@ -0,0 +1,27 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "ES2022",
"useDefineForClassFields": true,
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["src"]
}

7
frontend/tsconfig.json Normal file
View File

@@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}

View File

@@ -0,0 +1,25 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "ES2023",
"lib": ["ES2023"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["vite.config.ts"]
}

8
frontend/vite.config.ts Normal file
View File

@@ -0,0 +1,8 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react-swc'
import tailwindcss from '@tailwindcss/vite'
// https://vite.dev/config/
export default defineConfig({
plugins: [react(), tailwindcss()],
})