15 Commits

Author SHA1 Message Date
Pc
ad76294d73 test: cookie test
All checks were successful
Update changelog / changelog (push) Successful in 27s
2026-01-06 14:54:04 +01:00
Pc
5dd751600c test:v2
All checks were successful
Update changelog / changelog (push) Successful in 28s
2026-01-04 16:15:08 +01:00
Pc
13909c46f6 test: testing
All checks were successful
Update changelog / changelog (push) Successful in 28s
2026-01-04 14:36:29 +01:00
Pc
3c1d66ba48 fix: subdomain fix
All checks were successful
Update changelog / changelog (push) Successful in 31s
2026-01-04 14:07:16 +01:00
Pc
c765c92f89 feat: added cookies to use subdomains
All checks were successful
Update changelog / changelog (push) Successful in 27s
2026-01-04 13:56:00 +01:00
Pc
dae3479680 fix: not adding subdomain address to fetch api
All checks were successful
Update changelog / changelog (push) Successful in 28s
2026-01-04 13:43:04 +01:00
Pc
549da339e4 fix: login in works in subdomain
All checks were successful
Update changelog / changelog (push) Successful in 28s
2026-01-04 13:33:15 +01:00
Pc
4fa55b4caf test: subdomaind api
All checks were successful
Update changelog / changelog (push) Successful in 26s
2026-01-03 19:00:48 +01:00
Pc
fc0ee5a4d6 fix: typo fix
All checks were successful
Update changelog / changelog (push) Successful in 26s
2026-01-03 18:43:12 +01:00
Pc
1d1379c776 feat: domain redirection
All checks were successful
Update changelog / changelog (push) Successful in 35s
2026-01-03 18:31:52 +01:00
Pc
95f449a3d2 fix: vite config allowedhost read from .env
All checks were successful
Update changelog / changelog (push) Successful in 26s
2026-01-03 15:54:50 +01:00
Pc
ceeb2cccaf fix: typo fix
All checks were successful
Update changelog / changelog (push) Successful in 26s
2025-12-31 18:13:16 +01:00
c85aa78a76 Merge pull request 'fix: typo fix in image path' (#5) from RWD into master
All checks were successful
Update changelog / changelog (push) Successful in 26s
Reviewed-on: #5
2025-12-31 17:58:57 +01:00
1822a46e9f Merge pull request 'feat: opengraph icons' (#4) from RWD into master
All checks were successful
Update changelog / changelog (push) Successful in 26s
Reviewed-on: #4
2025-12-31 17:44:29 +01:00
0e2633b331 Merge pull request 'feat: responsive desing' (#3) from RWD into master
All checks were successful
Update changelog / changelog (push) Successful in 25s
Reviewed-on: #3
2025-12-31 16:28:27 +01:00
13 changed files with 303 additions and 388 deletions

View File

@@ -1,7 +1,7 @@
# Site info PUBLIC_URL=https://example.com
PUBLIC_URL=https://example.com # Publicly accessible website root, used for rewrites. Note there is no trailing slash in the URL. USE_SUBDOMAINS=true
USE_SUBDOMAINS=true # Whether backend allows for use of subdomains in URL generation.
DEBUG=false DEBUG=false
# Frontend specific # Frontend specific
<miejsce na twoje zmienne> VITE_API_TARGET=https://pies.com
VITE_API_TARGET=kitkat.example.com # Target backend for API requests. VITE_ALLOWED_HOST=pies.com # for sub domens add . before host address

View File

@@ -13,7 +13,7 @@
<meta name="twitter:card" content="summary_large_image" /> <meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:title" content="kittyurl shortener" /> <meta name="twitter:title" content="kittyurl shortener" />
<meta name="twitter:description" content="Your go-to place for short and memorable URLs." /> <meta name="twitter:description" content="Your go-to place for short and memorable URLs." />
<meta name="twitter:image" content="/src/assets/ket.png" /> <meta name="twitter:image" content="/src/assets/Ket.png" />
</head> </head>

View File

@@ -10,6 +10,7 @@
"dependencies": { "dependencies": {
"@tailwindcss/vite": "^4.1.18", "@tailwindcss/vite": "^4.1.18",
"axios": "^1.13.2", "axios": "^1.13.2",
"js-cookie": "^3.0.5",
"js-sha512": "^0.9.0", "js-sha512": "^0.9.0",
"lucide-react": "^0.562.0", "lucide-react": "^0.562.0",
"react": "^19.2.0", "react": "^19.2.0",
@@ -18,6 +19,7 @@
}, },
"devDependencies": { "devDependencies": {
"@eslint/js": "^9.39.1", "@eslint/js": "^9.39.1",
"@types/js-cookie": "^3.0.6",
"@types/node": "^24.10.1", "@types/node": "^24.10.1",
"@types/react": "^19.2.5", "@types/react": "^19.2.5",
"@types/react-dom": "^19.2.3", "@types/react-dom": "^19.2.3",
@@ -1588,6 +1590,13 @@
"integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==", "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/@types/js-cookie": {
"version": "3.0.6",
"resolved": "https://registry.npmjs.org/@types/js-cookie/-/js-cookie-3.0.6.tgz",
"integrity": "sha512-wkw9yd1kEXOPnvEeEV1Go1MmxtBJL0RR79aOTAApecWFVu7w0NNXNqhcWgvw2YgZDYadliXkl14pa3WXw5jlCQ==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/json-schema": { "node_modules/@types/json-schema": {
"version": "7.0.15", "version": "7.0.15",
"resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz",
@@ -3007,6 +3016,15 @@
"jiti": "lib/jiti-cli.mjs" "jiti": "lib/jiti-cli.mjs"
} }
}, },
"node_modules/js-cookie": {
"version": "3.0.5",
"resolved": "https://registry.npmjs.org/js-cookie/-/js-cookie-3.0.5.tgz",
"integrity": "sha512-cEiJEAEoIbWfCZYKWhVwFuvPX1gETRYPw6LlaTKoxD3s2AkXzkCjnp6h0V77ozyqj0jakteJ4YqDJT830+lVGw==",
"license": "MIT",
"engines": {
"node": ">=14"
}
},
"node_modules/js-sha512": { "node_modules/js-sha512": {
"version": "0.9.0", "version": "0.9.0",
"resolved": "https://registry.npmjs.org/js-sha512/-/js-sha512-0.9.0.tgz", "resolved": "https://registry.npmjs.org/js-sha512/-/js-sha512-0.9.0.tgz",

View File

@@ -13,6 +13,7 @@
"dependencies": { "dependencies": {
"@tailwindcss/vite": "^4.1.18", "@tailwindcss/vite": "^4.1.18",
"axios": "^1.13.2", "axios": "^1.13.2",
"js-cookie": "^3.0.5",
"js-sha512": "^0.9.0", "js-sha512": "^0.9.0",
"lucide-react": "^0.562.0", "lucide-react": "^0.562.0",
"react": "^19.2.0", "react": "^19.2.0",
@@ -21,6 +22,7 @@
}, },
"devDependencies": { "devDependencies": {
"@eslint/js": "^9.39.1", "@eslint/js": "^9.39.1",
"@types/js-cookie": "^3.0.6",
"@types/node": "^24.10.1", "@types/node": "^24.10.1",
"@types/react": "^19.2.5", "@types/react": "^19.2.5",
"@types/react-dom": "^19.2.3", "@types/react-dom": "^19.2.3",

View File

@@ -7,19 +7,43 @@ import { KittyGame } from './components/KittyGame';
import { FlappyCat } from './components/FlappyCat'; import { FlappyCat } from './components/FlappyCat';
import { useAuth } from './hooks/useAuth'; import { useAuth } from './hooks/useAuth';
// Eksportujemy typ, aby inne pliki mogły go użyć
export type View = 'home' | 'login' | 'history' | 'jump-game' | 'flappy-game'; export type View = 'home' | 'login' | 'history' | 'jump-game' | 'flappy-game';
const getSubdomain = () => {
const hostname = window.location.hostname;
const parts = hostname.split('.');
if (parts.length <= 2) return null;
return parts[0];
};
function App() { function App() {
const [url, setUrl] = useState(''); const [url, setUrl] = useState('');
const [view, setView] = useState<View>('home'); const [view, setView] = useState<View>('home');
const { isAuthenticated, logout } = useAuth(); const { isAuthenticated, logout } = useAuth();
const subdomain = getSubdomain();
/**
* STAN POCHODNY (Derived State)
* Rozwiązuje błąd "cascading renders". Jeśli użytkownik jest na subdomenie
* i nie jest zalogowany, automatycznie renderujemy widok logowania,
* ale nie nadpisujemy stanu 'view' w nieskończoność.
*/
const activeView = (subdomain && !isAuthenticated) ? 'login' : view;
const renderView = () => { const renderView = () => {
switch (view) { switch (activeView) {
case 'login': case 'login':
return <LoginView onBack={() => setView('home')} onSuccess={() => setView('home')} />; return (
<LoginView
onBack={() => setView('home')}
onSuccess={() => setView('home')}
/>
);
case 'history': case 'history':
// Strażnik dostępu dla widoku historii
if (!isAuthenticated) {
return <LoginView onBack={() => setView('home')} onSuccess={() => setView('home')} />;
}
return <HistoryView onBack={() => setView('home')} />; return <HistoryView onBack={() => setView('home')} />;
case 'jump-game': case 'jump-game':
return <KittyGame onBack={() => setView('home')} />; return <KittyGame onBack={() => setView('home')} />;
@@ -37,7 +61,12 @@ function App() {
isAuthenticated={isAuthenticated} isAuthenticated={isAuthenticated}
onLogout={logout} onLogout={logout}
/> />
<main>{renderView()}</main> <main>
{/* Jeśli użytkownik jest zalogowany (SSO), activeView od razu
pokaże Generator, zamiast LoginView.
*/}
{renderView()}
</main>
</div> </div>
); );
} }

View File

@@ -1,25 +0,0 @@
import axios from 'axios';
import { sha512 } from 'js-sha512';
// Interfejs zgodny z Twoją dokumentacją [cite: 74-79]
export interface AuthResponse {
status: "ok";
name: string;
role: "user" | "admin";
token: string;
}
export const loginUser = async (name: string, pass: string): Promise<AuthResponse> => {
// Wysyłamy POST zgodnie ze specyfikacją dokumentacji [cite: 68]
const response = await axios.post('https://twoj-backend.pl/api/v1/user/signIn', {
name: name,
password: sha512(pass) // Wymagane SHA-512 [cite: 71]
});
// Jeśli sukces, zapisujemy token JWT [cite: 78]
if (response.data.status === "ok") {
localStorage.setItem('token', response.data.token);
}
return response.data;
};

View File

@@ -1,7 +1,7 @@
import React, { useState, useEffect, useRef, useCallback } from 'react'; import React, { useState, useEffect, useRef, useCallback } from 'react';
import { ArrowLeft, Trophy, Sparkles } from 'lucide-react'; import { ArrowLeft, Trophy, Sparkles } from 'lucide-react';
// --- MODEL KOTA (Wizualizacja) --- // --- MODEL KOTA ---
interface DetailedKittyProps { isGameOver: boolean; } interface DetailedKittyProps { isGameOver: boolean; }
const DetailedKitty: React.FC<DetailedKittyProps> = ({ isGameOver }) => { const DetailedKitty: React.FC<DetailedKittyProps> = ({ isGameOver }) => {
const mainColor = isGameOver ? '#cbd5e1' : '#f472b6'; const mainColor = isGameOver ? '#cbd5e1' : '#f472b6';
@@ -32,20 +32,16 @@ const DetailedKitty: React.FC<DetailedKittyProps> = ({ isGameOver }) => {
); );
}; };
// --- KONFIGURACJA GRY --- // --- KONFIGURACJA NIEZALEŻNA OD FPS (Wartości na sekundę) ---
const GAP_SIZE = 170; // Przerwa między rurami const GAP_SIZE = 180;
const PIPE_WIDTH = 70; const PIPE_WIDTH = 70;
const PIPE_SPEED = 220; // px/s const PIPE_SPEED = 200; // px/s
const PIPE_SPAWN_RATE = 1.6; // co ile sekund rura const PIPE_SPAWN_RATE = 1.8; // sekundy
const GRAVITY = 1400; // siła grawitacji const GRAVITY = 1400; // px/s^2
const FLAP_STRENGTH = -420; // siła skoku const FLAP_STRENGTH = -420; // px/s
const CANVAS_HEIGHT = 450;
// Logiczne wymiary gry (fizyka działa na tych wartościach, a ekran je tylko skaluje)
const GAME_HEIGHT = 450;
const GAME_WIDTH = 600;
export const FlappyCat: React.FC<{ onBack: () => void }> = ({ onBack }) => { export const FlappyCat: React.FC<{ onBack: () => void }> = ({ onBack }) => {
// --- STANY ---
const [isPlaying, setIsPlaying] = useState(false); const [isPlaying, setIsPlaying] = useState(false);
const [gameOver, setGameOver] = useState(false); const [gameOver, setGameOver] = useState(false);
const [score, setScore] = useState(0); const [score, setScore] = useState(0);
@@ -54,13 +50,10 @@ export const FlappyCat: React.FC<{ onBack: () => void }> = ({ onBack }) => {
return saved ? parseInt(saved, 10) : 0; return saved ? parseInt(saved, 10) : 0;
}); });
// Stany do renderowania
const [displayKittyY, setDisplayKittyY] = useState(150); const [displayKittyY, setDisplayKittyY] = useState(150);
const [displayPipes, setDisplayPipes] = useState<{ x: number; topHeight: number; id: number }[]>([]); const [displayPipes, setDisplayPipes] = useState<{ x: number; topHeight: number; id: number }[]>([]);
const [rotation, setRotation] = useState(0); const [rotation, setRotation] = useState(0);
const [scale, setScale] = useState(1); // Skala RWD
// --- REFS (FIZYKA) ---
const kittyYRef = useRef(150); const kittyYRef = useRef(150);
const velocityRef = useRef(0); const velocityRef = useRef(0);
const pipesRef = useRef<{ x: number; topHeight: number; id: number; passed?: boolean }[]>([]); const pipesRef = useRef<{ x: number; topHeight: number; id: number; passed?: boolean }[]>([]);
@@ -69,26 +62,6 @@ export const FlappyCat: React.FC<{ onBack: () => void }> = ({ onBack }) => {
const lastTimeRef = useRef<number>(0); const lastTimeRef = useRef<number>(0);
const spawnTimerRef = useRef<number>(0); const spawnTimerRef = useRef<number>(0);
// --- RWD: Obliczanie skali ---
useEffect(() => {
const handleResize = () => {
const availableWidth = window.innerWidth - 32; // margines boczny
const availableHeight = window.innerHeight - 100; // miejsce na nagłówek
const scaleX = availableWidth / GAME_WIDTH;
const scaleY = availableHeight / GAME_HEIGHT;
// Dopasuj do ekranu, ale nie powiększaj powyżej 100% (żeby nie tracić jakości)
const newScale = Math.min(scaleX, scaleY, 1);
setScale(newScale);
};
window.addEventListener('resize', handleResize);
handleResize(); // Init
return () => window.removeEventListener('resize', handleResize);
}, []);
// --- LOGIKA GRY ---
const endGame = useCallback(() => { const endGame = useCallback(() => {
setGameOver(true); setGameOver(true);
setIsPlaying(false); setIsPlaying(false);
@@ -108,7 +81,7 @@ export const FlappyCat: React.FC<{ onBack: () => void }> = ({ onBack }) => {
velocityRef.current = 0; velocityRef.current = 0;
pipesRef.current = []; pipesRef.current = [];
spawnTimerRef.current = 0; spawnTimerRef.current = 0;
lastTimeRef.current = performance.now(); lastTimeRef.current = performance.now(); // Inicjalizacja czasu
setDisplayKittyY(150); setDisplayKittyY(150);
setDisplayPipes([]); setDisplayPipes([]);
setRotation(0); setRotation(0);
@@ -118,87 +91,64 @@ export const FlappyCat: React.FC<{ onBack: () => void }> = ({ onBack }) => {
if (isPlaying && !gameOver) velocityRef.current = FLAP_STRENGTH; if (isPlaying && !gameOver) velocityRef.current = FLAP_STRENGTH;
}, [isPlaying, gameOver]); }, [isPlaying, gameOver]);
// --- OBSŁUGA INPUTU (NAPRAWIONA) ---
const handleAction = useCallback((e?: React.SyntheticEvent) => {
// WAŻNE: Nie używamy e.preventDefault() tutaj, bo to powoduje błąd w Chrome.
// Zamiast tego CSS 'touch-action: none' blokuje scrollowanie.
if (e) {
e.stopPropagation();
}
if (!isPlaying || gameOver) {
startGame();
} else {
flap();
}
}, [isPlaying, gameOver, startGame, flap]);
// --- PĘTLA GRY ---
useEffect(() => { useEffect(() => {
const update = (currentTime: number) => { const update = (currentTime: number) => {
if (gameOver || !isPlaying) return; if (gameOver || !isPlaying) return;
// Delta time w sekundach // --- DYNAMICZNY DELTA TIME ---
// Obliczamy ile sekund upłynęło od ostatniej klatki (np. 0.0069s dla 144Hz)
const dt = (currentTime - lastTimeRef.current) / 1000; const dt = (currentTime - lastTimeRef.current) / 1000;
lastTimeRef.current = currentTime; lastTimeRef.current = currentTime;
const frameTime = Math.min(dt, 0.1); // Limit laga
// 1. Fizyka grawitacji // Zabezpieczenie przed ogromnym skokiem fizyki przy lagu
const frameTime = Math.min(dt, 0.1);
// Fizyka grawitacji
velocityRef.current += GRAVITY * frameTime; velocityRef.current += GRAVITY * frameTime;
kittyYRef.current += velocityRef.current * frameTime; kittyYRef.current += velocityRef.current * frameTime;
// Rotacja // Płynna rotacja zależna od prędkości pionowej
setRotation(Math.min(Math.max(velocityRef.current * 0.12, -25), 90)); setRotation(Math.min(Math.max(velocityRef.current * 0.12, -20), 80));
// Kolizja z sufitem/podłogą // Kolizja z sufitem/ziemią
if (kittyYRef.current > GAME_HEIGHT - 40 || kittyYRef.current < -50) { if (kittyYRef.current > CANVAS_HEIGHT - 40 || kittyYRef.current < -50) {
endGame(); endGame();
return; return;
} }
// 2. Generowanie rur // Spawn rur
spawnTimerRef.current += frameTime; spawnTimerRef.current += frameTime;
if (spawnTimerRef.current >= PIPE_SPAWN_RATE) { if (spawnTimerRef.current >= PIPE_SPAWN_RATE) {
const minPipe = 60; const topHeight = Math.random() * (220 - 70) + 70;
const maxPipe = GAME_HEIGHT - GAP_SIZE - minPipe; pipesRef.current.push({ x: 650, topHeight, id: Date.now() });
const topHeight = Math.random() * (maxPipe - minPipe) + minPipe;
pipesRef.current.push({ x: GAME_WIDTH + 50, topHeight, id: Date.now() });
spawnTimerRef.current = 0; spawnTimerRef.current = 0;
} }
// 3. Ruch rur i kolizje // Ruch rur i kolizje
const updatedPipes = []; const updatedPipes = [];
for (const p of pipesRef.current) { for (const p of pipesRef.current) {
p.x -= PIPE_SPEED * frameTime; p.x -= PIPE_SPEED * frameTime;
// Hitbox rury (marginesy dla łatwiejszej gry) // Hitbox (z małym marginesem dla kota)
const hitXLeft = p.x + 5; if (p.x < 100 && p.x + PIPE_WIDTH > 55) {
const hitXRight = p.x + PIPE_WIDTH - 5;
// Sprawdzenie czy kot jest w poziomie rury
if (hitXLeft < 100 && hitXRight > 55) {
// Sprawdzenie czy kot uderzył w górę lub dół
// (dodajemy marginesy bezpieczeństwa)
if (kittyYRef.current < p.topHeight || kittyYRef.current > p.topHeight + GAP_SIZE - 45) { if (kittyYRef.current < p.topHeight || kittyYRef.current > p.topHeight + GAP_SIZE - 45) {
endGame(); endGame();
return; return;
} }
} }
// Naliczanie punktów // Punktacja
if (p.x < 50 && !p.passed) { if (p.x < 50 && !p.passed) {
p.passed = true; p.passed = true;
scoreRef.current += 1; scoreRef.current += 1;
setScore(scoreRef.current); setScore(scoreRef.current);
} }
// Usuwanie starych rur if (p.x > -PIPE_WIDTH) updatedPipes.push(p);
if (p.x > -PIPE_WIDTH - 50) updatedPipes.push(p);
} }
pipesRef.current = updatedPipes; pipesRef.current = updatedPipes;
// 4. Renderowanie // Update stanów do renderowania
setDisplayKittyY(kittyYRef.current); setDisplayKittyY(kittyYRef.current);
setDisplayPipes([...pipesRef.current]); setDisplayPipes([...pipesRef.current]);
@@ -211,108 +161,64 @@ export const FlappyCat: React.FC<{ onBack: () => void }> = ({ onBack }) => {
return () => cancelAnimationFrame(requestRef.current); return () => cancelAnimationFrame(requestRef.current);
}, [isPlaying, gameOver, endGame]); }, [isPlaying, gameOver, endGame]);
// Obsługa Spacji
useEffect(() => { useEffect(() => {
const handleKey = (e: KeyboardEvent) => { const handleKey = (e: KeyboardEvent) => {
if (e.code === 'Space') { if (e.code === 'Space') {
e.preventDefault(); // Tu można bezpiecznie użyć preventDefault dla klawiatury e.preventDefault();
handleAction(); if (!isPlaying || gameOver) startGame(); else flap();
} }
}; };
window.addEventListener('keydown', handleKey); window.addEventListener('keydown', handleKey);
return () => window.removeEventListener('keydown', handleKey); return () => window.removeEventListener('keydown', handleKey);
}, [handleAction]); }, [isPlaying, gameOver, startGame, flap]);
return ( return (
<div className="flex flex-col items-center justify-start pt-4 sm:justify-center min-h-[80vh] w-full font-sans select-none overflow-hidden"> <div className="flex flex-col items-center justify-center min-h-[75vh] p-4 font-sans select-none">
<button onClick={onBack} className="mb-6 flex items-center gap-2 text-pink-500 font-bold hover:scale-105 transition-all outline-none">
<button
onClick={onBack}
className="z-50 mb-4 flex items-center gap-2 text-pink-500 font-bold hover:scale-105 transition-all outline-none px-4 py-2 bg-white/50 rounded-full cursor-pointer"
>
<ArrowLeft size={20} /> Back to Menu <ArrowLeft size={20} /> Back to Menu
</button> </button>
{/* WRAPPER SKALUJĄCY GRĘ */}
<div <div
style={{ className="relative w-full max-w-[600px] h-[450px] bg-sky-100 rounded-[3rem] shadow-2xl border-4 border-white overflow-hidden cursor-pointer"
width: GAME_WIDTH, onClick={() => { if (!isPlaying || gameOver) startGame(); else flap(); }}
height: GAME_HEIGHT,
transform: `scale(${scale})`,
transformOrigin: 'top center',
touchAction: 'none' // KLUCZOWE DLA MOBILE: blokuje gesty przeglądarki
}}
className="relative shrink-0"
> >
<div <div className="absolute top-10 left-10 text-white/40"><Sparkles size={40} /></div>
className="relative w-full h-full bg-sky-100 rounded-[3rem] shadow-2xl border-4 border-white overflow-hidden cursor-pointer" <div className="absolute top-40 right-20 text-white/30"><Sparkles size={60} /></div>
// KLUCZOWE: Używamy onPointerDown zamiast onTouchStart/onMouseDown
onPointerDown={handleAction}
>
{/* TŁO / DEKORACJE */}
<div className="absolute top-10 left-10 text-white/40"><Sparkles size={40} /></div>
<div className="absolute top-40 right-20 text-white/30"><Sparkles size={60} /></div>
{/* CHMURY (Ozdoba) */} <div className="absolute top-6 right-8 text-right z-30 font-black">
<div className="absolute bottom-10 left-10 w-24 h-8 bg-white/40 rounded-full" /> <div className="text-pink-500 text-4xl">Score: {score}</div>
<div className="absolute top-20 left-1/2 w-32 h-10 bg-white/40 rounded-full" /> <div className="text-pink-300 text-sm flex items-center justify-end gap-1"><Trophy size={14} /> Record: {highScore}</div>
{/* HUD */}
<div className="absolute top-6 right-8 text-right z-30 font-black pointer-events-none">
<div className="text-pink-500 text-4xl drop-shadow-sm">Score: {score}</div>
<div className="text-pink-300 text-sm flex items-center justify-end gap-1"><Trophy size={14} /> Record: {highScore}</div>
</div>
{/* GRACZ (KOT) */}
<div className="absolute left-10 z-20 pointer-events-none" style={{ top: `${displayKittyY}px`, transform: `rotate(${rotation}deg)`, transition: 'transform 0.08s linear' }}>
<DetailedKitty isGameOver={gameOver} />
</div>
{/* RURY */}
{displayPipes.map(p => (
<React.Fragment key={p.id}>
{/* Górna rura */}
<div className="absolute bg-[#e5c29f] border-x-4 border-b-8 border-[#d4ac87] rounded-b-3xl pointer-events-none"
style={{ left: p.x, top: 0, width: PIPE_WIDTH, height: p.topHeight }} />
{/* Dolna rura */}
<div className="absolute bg-[#e5c29f] border-x-4 border-t-8 border-[#d4ac87] rounded-t-3xl pointer-events-none"
style={{ left: p.x, top: p.topHeight + GAP_SIZE, width: PIPE_WIDTH, height: GAME_HEIGHT - (p.topHeight + GAP_SIZE) }} />
</React.Fragment>
))}
{/* EKRAN STARTOWY */}
{!isPlaying && !gameOver && (
<div className="absolute inset-0 bg-white/40 backdrop-blur-sm flex items-center justify-center z-40">
<div className="bg-white p-10 rounded-[3rem] shadow-2xl text-center border-4 border-pink-100 mx-4 pointer-events-none">
<p className="text-3xl font-black text-pink-500 mb-6">Flappy Cat 🎈</p>
<p className="text-slate-400 mb-4 text-sm font-bold uppercase tracking-widest">Tap to Jump</p>
<div className="bg-pink-500 text-white px-10 py-4 rounded-2xl font-black animate-bounce text-xl shadow-lg inline-block">START</div>
</div>
</div>
)}
{/* GAME OVER */}
{gameOver && (
<div className="absolute inset-0 bg-pink-50/90 backdrop-blur-md flex flex-col items-center justify-center z-40 text-center">
<h3 className="text-5xl font-black text-pink-600 mb-2">Oops! 😿</h3>
<p className="font-bold text-3xl text-pink-400 mb-8">Score: {score}</p>
<button className="bg-pink-500 text-white px-12 py-4 rounded-2xl font-black text-xl shadow-xl hover:bg-pink-600 transition-colors pointer-events-auto"
onPointerDown={(e) => {
e.stopPropagation(); // Żeby kliknięcie w guzik nie podbiło kota w tle
startGame();
}}
>
TRY AGAIN
</button>
</div>
)}
</div> </div>
<div className="absolute left-10 z-20" style={{ top: `${displayKittyY}px`, transform: `rotate(${rotation}deg)`, transition: 'transform 0.08s linear' }}>
<DetailedKitty isGameOver={gameOver} />
</div>
{displayPipes.map(p => (
<React.Fragment key={p.id}>
<div className="absolute bg-[#e5c29f] border-x-4 border-b-8 border-[#d4ac87] rounded-b-3xl" style={{ left: p.x, top: 0, width: PIPE_WIDTH, height: p.topHeight }} />
<div className="absolute bg-[#e5c29f] border-x-4 border-t-8 border-[#d4ac87] rounded-t-3xl" style={{ left: p.x, top: p.topHeight + GAP_SIZE, width: PIPE_WIDTH, height: CANVAS_HEIGHT - (p.topHeight + GAP_SIZE) }} />
</React.Fragment>
))}
{!isPlaying && !gameOver && (
<div className="absolute inset-0 bg-white/40 backdrop-blur-sm flex items-center justify-center z-40">
<div className="bg-white p-10 rounded-[3rem] shadow-2xl text-center border-4 border-pink-100">
<p className="text-3xl font-black text-pink-500 mb-6">Flappy Cat 🎈</p>
<button className="bg-pink-500 text-white px-10 py-4 rounded-2xl font-black animate-bounce text-xl shadow-lg">START</button>
</div>
</div>
)}
{gameOver && (
<div className="absolute inset-0 bg-pink-50/90 backdrop-blur-md flex flex-col items-center justify-center z-40 text-center">
<h3 className="text-5xl font-black text-pink-600 mb-2">Oops! 😿</h3>
<p className="font-bold text-3xl text-pink-400 mb-8">Score: {score}</p>
<button className="bg-pink-500 text-white px-12 py-4 rounded-2xl font-black text-xl shadow-xl">TRY AGAIN</button>
</div>
)}
</div> </div>
<div className="mt-4 text-xs text-slate-400 sm:hidden">
Tap anywhere to jump
</div>
</div> </div>
); );
}; };

View File

@@ -15,7 +15,7 @@ export const Generator: React.FC<GeneratorProps> = ({ url, setUrl, onGenerate })
KittyURL <PawPrint className="w-8 h-8 sm:w-12 sm:h-12" fill="currentColor" /> KittyURL <PawPrint className="w-8 h-8 sm:w-12 sm:h-12" fill="currentColor" />
</h1> </h1>
<p className="text-pink-300 text-lg sm:text-xl font-medium px-4"> <p className="text-pink-300 text-lg sm:text-xl font-medium px-4">
Shorten your links with a purr! Shorten KKKKKK your links with a purr!
</p> </p>
</header> </header>

View File

@@ -1,7 +1,7 @@
import React, { useState, useEffect, useRef, useCallback } from 'react'; import React, { useState, useEffect, useRef, useCallback } from 'react';
import { ArrowLeft, Trophy, Sparkles, Moon, Sun } from 'lucide-react'; import { ArrowLeft, Trophy, Sparkles, Moon, Sun } from 'lucide-react';
// --- MODEL KOTA (Bez zmian) --- // --- MODEL KOTA (Animacje CSS zostają, bo są czasowe, nie klatkowe) ---
interface DetailedKittyProps { interface DetailedKittyProps {
isJumping: boolean; isJumping: boolean;
isNight: boolean; isNight: boolean;
@@ -49,13 +49,8 @@ const DetailedKitty: React.FC<DetailedKittyProps> = ({ isJumping, isNight, isGam
); );
}; };
// --- STAŁE WYMIARY LOGICZNE --- // --- GŁÓWNY KOMPONENT Z DYNAMICZNYM DELTA TIME ---
const GAME_WIDTH = 650;
const GAME_HEIGHT = 340;
// --- GŁÓWNY KOMPONENT ---
export const KittyGame: React.FC<{ onBack: () => void }> = ({ onBack }) => { export const KittyGame: React.FC<{ onBack: () => void }> = ({ onBack }) => {
// Stany gry
const [isPlaying, setIsPlaying] = useState(false); const [isPlaying, setIsPlaying] = useState(false);
const [gameOver, setGameOver] = useState(false); const [gameOver, setGameOver] = useState(false);
const [score, setScore] = useState(0); const [score, setScore] = useState(0);
@@ -65,46 +60,25 @@ export const KittyGame: React.FC<{ onBack: () => void }> = ({ onBack }) => {
}); });
const [displayKittyY, setDisplayKittyY] = useState(0); const [displayKittyY, setDisplayKittyY] = useState(0);
const [displayObstacleX, setDisplayObstacleX] = useState(GAME_WIDTH); const [displayObstacleX, setDisplayObstacleX] = useState(650);
// RWD State: Skala
const [scale, setScale] = useState(1);
const isNight = Math.floor(score / 10) % 2 === 1; const isNight = Math.floor(score / 10) % 2 === 1;
// Referencje fizyczne // Referencje fizyczne
const kittyYRef = useRef(0); const kittyYRef = useRef(0);
const obstacleXRef = useRef(GAME_WIDTH); const obstacleXRef = useRef(650);
const velocityRef = useRef(0); const velocityRef = useRef(0);
const scoreRef = useRef(0); const scoreRef = useRef(0);
const requestRef = useRef<number>(0); const requestRef = useRef<number>(0);
const lastTimeRef = useRef<number>(0); const lastTimeRef = useRef<number>(0);
// STAŁE KONFIGURACYJNE // STAŁE KONFIGURACYJNE (Wartości na sekundę - niezależne od Hz)
const GRAVITY = 1800; const GRAVITY = 1800; // Kot spadnie o 1800px w ciągu sekundy (jeśli nie ma prędkości początkowej)
const JUMP_FORCE = -550; const JUMP_FORCE = -550; // Prędkość startowa skoku
const INITIAL_SPEED = 380; const INITIAL_SPEED = 380; // Prędkość przeszkody w px/s
const SPEED_INCREMENT = 12; const SPEED_INCREMENT = 12; // Przyspieszenie px/s na każdy punkt
const GROUND_Y = 0; const GROUND_Y = 0;
// --- RWD LOGIC ---
useEffect(() => {
const handleResize = () => {
const availableWidth = window.innerWidth - 32; // marginesy boczne
const availableHeight = window.innerHeight - 100; // miejsce na nagłówek
const scaleX = availableWidth / GAME_WIDTH;
const scaleY = availableHeight / GAME_HEIGHT;
// Skalujemy w dół jeśli ekran jest mały, ale max 1 (nie powiększamy na dużych ekranach)
setScale(Math.min(scaleX, scaleY, 1));
};
window.addEventListener('resize', handleResize);
handleResize();
return () => window.removeEventListener('resize', handleResize);
}, []);
const endGame = useCallback(() => { const endGame = useCallback(() => {
setGameOver(true); setGameOver(true);
setIsPlaying(false); setIsPlaying(false);
@@ -121,11 +95,12 @@ export const KittyGame: React.FC<{ onBack: () => void }> = ({ onBack }) => {
setScore(0); setScore(0);
scoreRef.current = 0; scoreRef.current = 0;
kittyYRef.current = 0; kittyYRef.current = 0;
obstacleXRef.current = GAME_WIDTH + 50; obstacleXRef.current = 700;
velocityRef.current = 0; velocityRef.current = 0;
// Kluczowe: inicjalizacja czasu startu
lastTimeRef.current = performance.now(); lastTimeRef.current = performance.now();
setDisplayKittyY(0); setDisplayKittyY(0);
setDisplayObstacleX(GAME_WIDTH + 50); setDisplayObstacleX(700);
}, []); }, []);
const jump = useCallback(() => { const jump = useCallback(() => {
@@ -134,23 +109,19 @@ export const KittyGame: React.FC<{ onBack: () => void }> = ({ onBack }) => {
} }
}, [gameOver, isPlaying]); }, [gameOver, isPlaying]);
// --- OBSŁUGA WEJŚCIA (Touch & Mouse) ---
const handleAction = useCallback((e?: React.SyntheticEvent) => {
// Nie używamy e.preventDefault() tutaj, bo CSS touch-action załatwia sprawę
if (e) e.stopPropagation();
if (!isPlaying || gameOver) startGame(); else jump();
}, [isPlaying, gameOver, startGame, jump]);
useEffect(() => { useEffect(() => {
const update = (currentTime: number) => { const update = (currentTime: number) => {
if (gameOver || !isPlaying) return; if (gameOver || !isPlaying) return;
// --- OBLICZANIE DELTA TIME (Dynamiczna szybkość) ---
// dt to czas w sekundach, jaki upłynął od ostatniej klatki (np. 0.016 dla 60Hz, 0.007 dla 144Hz)
const dt = (currentTime - lastTimeRef.current) / 1000; const dt = (currentTime - lastTimeRef.current) / 1000;
lastTimeRef.current = currentTime; lastTimeRef.current = currentTime;
// Zabezpieczenie przed "skokiem" (np. gdy użytkownik zmieni kartę w przeglądarce)
const frameTime = Math.min(dt, 0.1); const frameTime = Math.min(dt, 0.1);
// Fizyka // Fizyka kota (jednostki * czas)
velocityRef.current += GRAVITY * frameTime; velocityRef.current += GRAVITY * frameTime;
kittyYRef.current -= velocityRef.current * frameTime; kittyYRef.current -= velocityRef.current * frameTime;
@@ -159,22 +130,24 @@ export const KittyGame: React.FC<{ onBack: () => void }> = ({ onBack }) => {
velocityRef.current = 0; velocityRef.current = 0;
} }
// Przeszkoda // Ruch przeszkody (prędkość * czas)
const currentSpeed = INITIAL_SPEED + (scoreRef.current * SPEED_INCREMENT); const currentSpeed = INITIAL_SPEED + (scoreRef.current * SPEED_INCREMENT);
obstacleXRef.current -= currentSpeed * frameTime; obstacleXRef.current -= currentSpeed * frameTime;
// Reset przeszkody
if (obstacleXRef.current < -80) { if (obstacleXRef.current < -80) {
obstacleXRef.current = GAME_WIDTH + 50; obstacleXRef.current = 750;
scoreRef.current += 1; scoreRef.current += 1;
setScore(scoreRef.current); setScore(scoreRef.current);
} }
// Kolizja // Kolizja (strefa trafienia dopasowana do czasu)
if (obstacleXRef.current < 100 && obstacleXRef.current > 20 && kittyYRef.current < 45) { if (obstacleXRef.current < 100 && obstacleXRef.current > 20 && kittyYRef.current < 45) {
endGame(); endGame();
return; return;
} }
// Renderowanie wizualne
setDisplayKittyY(kittyYRef.current); setDisplayKittyY(kittyYRef.current);
setDisplayObstacleX(obstacleXRef.current); setDisplayObstacleX(obstacleXRef.current);
@@ -191,111 +164,86 @@ export const KittyGame: React.FC<{ onBack: () => void }> = ({ onBack }) => {
const handleKey = (e: KeyboardEvent) => { const handleKey = (e: KeyboardEvent) => {
if (e.code === 'Space') { if (e.code === 'Space') {
e.preventDefault(); e.preventDefault();
handleAction(); if (!isPlaying || gameOver) startGame(); else jump();
} }
}; };
window.addEventListener('keydown', handleKey); window.addEventListener('keydown', handleKey);
return () => window.removeEventListener('keydown', handleKey); return () => window.removeEventListener('keydown', handleKey);
}, [handleAction]); }, [isPlaying, gameOver, startGame, jump]);
return ( return (
<div className="flex flex-col items-center justify-start pt-8 sm:justify-center min-h-[80vh] w-full font-sans select-none overflow-hidden"> <div className="flex flex-col items-center justify-center min-h-[70vh] p-4 font-sans select-none">
<button onClick={onBack} className="mb-6 flex items-center gap-2 text-pink-500 font-bold hover:scale-105 transition-all outline-none">
<button
onClick={onBack}
className="z-50 mb-6 flex items-center gap-2 text-pink-500 font-bold hover:scale-105 transition-all outline-none bg-white/50 px-4 py-2 rounded-full cursor-pointer"
>
<ArrowLeft size={20} /> Back <ArrowLeft size={20} /> Back
</button> </button>
{/* KONTENER SKALOWANIA */}
<div <div
style={{ className={`relative w-full max-w-[650px] h-[340px] rounded-[3.5rem] shadow-2xl border-4 transition-colors duration-1000 overflow-hidden cursor-pointer
width: GAME_WIDTH, ${isNight ? 'bg-slate-950 border-indigo-500 shadow-indigo-500/20' : 'bg-white border-pink-100 shadow-pink-200/50'}`}
height: GAME_HEIGHT, onClick={() => { if (!isPlaying || gameOver) startGame(); else jump(); }}
transform: `scale(${scale})`,
transformOrigin: 'top center',
touchAction: 'none' // Zapobiega scrollowaniu na mobile
}}
className="relative shrink-0"
> >
<div {/* Niebo */}
className={`relative w-full h-full rounded-[3.5rem] shadow-2xl border-4 transition-colors duration-1000 overflow-hidden cursor-pointer <div className={`absolute top-10 left-12 transition-all duration-1000 ${isNight ? 'translate-y-0 opacity-100' : '-translate-y-20 opacity-0'}`}>
${isNight ? 'bg-slate-950 border-indigo-500 shadow-indigo-500/20' : 'bg-white border-pink-100 shadow-pink-200/50'}`} <Moon className="text-indigo-200 fill-indigo-100" size={48} />
// Używamy onPointerDown zamiast onClick/onTouchStart
onPointerDown={handleAction}
>
{/* Niebo */}
<div className={`absolute top-10 left-12 transition-all duration-1000 ${isNight ? 'translate-y-0 opacity-100' : '-translate-y-20 opacity-0'}`}>
<Moon className="text-indigo-200 fill-indigo-100" size={48} />
</div>
<div className={`absolute top-10 left-12 transition-all duration-1000 ${isNight ? '-translate-y-20 opacity-0' : 'translate-y-0 opacity-100'}`}>
<Sun className="text-yellow-400 fill-yellow-200" size={48} />
</div>
{/* UI Score */}
<div className={`absolute top-6 right-8 text-right z-10 font-black transition-colors duration-1000 ${isNight ? 'text-indigo-100' : 'text-pink-500'}`}>
<div className="text-3xl tracking-tighter">Score: {score}</div>
<div className={`text-sm flex items-center justify-end gap-1 ${isNight ? 'text-indigo-400' : 'text-pink-300'}`}>
<Trophy size={14} /> High: {highScore}
</div>
</div>
{/* KOTEK */}
<div className="absolute left-10 pointer-events-none" style={{ bottom: `${displayKittyY + 48}px` }}>
<DetailedKitty isJumping={displayKittyY > 2} isNight={isNight} isGameOver={gameOver} />
</div>
{/* PRZESZKODA */}
<div
className={`absolute bottom-12 w-14 h-14 rounded-full border-2 flex items-center justify-center animate-spin transition-colors duration-1000 pointer-events-none
${isNight ? 'bg-indigo-900 border-indigo-400 shadow-[0_0_15px_rgba(129,140,248,0.3)]' : 'bg-pink-100 border-pink-300'}`}
style={{ left: `${displayObstacleX}px` }}
>
<div className={`w-10 h-1.5 rounded-full ${isNight ? 'bg-indigo-300' : 'bg-pink-400'} rotate-45`} />
<div className={`absolute w-10 h-1.5 rounded-full ${isNight ? 'bg-indigo-300' : 'bg-pink-400'} -rotate-45`} />
</div>
{/* Ziemia */}
<div className={`absolute bottom-0 w-full h-12 border-t-4 transition-colors duration-1000 flex items-center justify-around pointer-events-none
${isNight ? 'bg-slate-900 border-indigo-900 text-indigo-950' : 'bg-pink-50 border-pink-100 text-pink-100'}`}>
{[...Array(10)].map((_, i) => <span key={i} className="text-2xl grayscale opacity-50">🐾</span>)}
</div>
{/* EKRAN STARTOWY */}
{!isPlaying && !gameOver && (
<div className="absolute inset-0 bg-white/20 backdrop-blur-[4px] flex items-center justify-center z-20">
<div className="bg-white p-12 rounded-[3.5rem] shadow-2xl flex flex-col items-center border-4 border-pink-100 transform hover:scale-105 transition-transform">
<Sparkles className="text-yellow-400 mb-4 animate-pulse" size={50} />
<button className="bg-pink-500 text-white px-12 py-5 rounded-2xl font-black text-2xl shadow-lg hover:bg-pink-600 transition-colors pointer-events-none">
START
</button>
<p className="mt-4 text-slate-400 font-bold text-sm uppercase tracking-widest">Tap or Space</p>
</div>
</div>
)}
{/* GAME OVER */}
{gameOver && (
<div className={`absolute inset-0 backdrop-blur-md flex flex-col items-center justify-center text-center p-6 z-30 transition-colors duration-1000
${isNight ? 'bg-slate-950/90' : 'bg-pink-50/90'}`}>
<h3 className={`text-6xl font-black mb-4 ${isNight ? 'text-white' : 'text-pink-600'}`}>Oh No! 😿</h3>
<div className={`text-3xl font-bold mb-8 ${isNight ? 'text-indigo-300' : 'text-pink-400'}`}>Score: {score}</div>
<button
className="bg-pink-500 text-white border-4 border-white px-14 py-5 rounded-2xl font-black text-2xl hover:scale-110 transition-all shadow-xl active:scale-95 pointer-events-auto"
onPointerDown={(e) => { e.stopPropagation(); startGame(); }}
>
TRY AGAIN
</button>
</div>
)}
</div> </div>
<div className={`absolute top-10 left-12 transition-all duration-1000 ${isNight ? '-translate-y-20 opacity-0' : 'translate-y-0 opacity-100'}`}>
<Sun className="text-yellow-400 fill-yellow-200" size={48} />
</div>
{/* UI Score */}
<div className={`absolute top-6 right-8 text-right z-10 font-black transition-colors duration-1000 ${isNight ? 'text-indigo-100' : 'text-pink-500'}`}>
<div className="text-3xl tracking-tighter">Score: {score}</div>
<div className={`text-sm flex items-center justify-end gap-1 ${isNight ? 'text-indigo-400' : 'text-pink-300'}`}>
<Trophy size={14} /> High: {highScore}
</div>
</div>
{/* KOTEK */}
<div className="absolute left-10" style={{ bottom: `${displayKittyY + 48}px` }}>
<DetailedKitty isJumping={displayKittyY > 2} isNight={isNight} isGameOver={gameOver} />
</div>
{/* PRZESZKODA */}
<div
className={`absolute bottom-12 w-14 h-14 rounded-full border-2 flex items-center justify-center animate-spin transition-colors duration-1000
${isNight ? 'bg-indigo-900 border-indigo-400 shadow-[0_0_15px_rgba(129,140,248,0.3)]' : 'bg-pink-100 border-pink-300'}`}
style={{ left: `${displayObstacleX}px` }}
>
<div className={`w-10 h-1.5 rounded-full ${isNight ? 'bg-indigo-300' : 'bg-pink-400'} rotate-45`} />
<div className={`absolute w-10 h-1.5 rounded-full ${isNight ? 'bg-indigo-300' : 'bg-pink-400'} -rotate-45`} />
</div>
{/* Ziemia */}
<div className={`absolute bottom-0 w-full h-12 border-t-4 transition-colors duration-1000 flex items-center justify-around
${isNight ? 'bg-slate-900 border-indigo-900 text-indigo-950' : 'bg-pink-50 border-pink-100 text-pink-100'}`}>
{[...Array(10)].map((_, i) => <span key={i} className="text-2xl grayscale opacity-50">🐾</span>)}
</div>
{/* Ekrany start/stop */}
{!isPlaying && !gameOver && (
<div className="absolute inset-0 bg-white/20 backdrop-blur-[4px] flex items-center justify-center z-20">
<div className="bg-white p-12 rounded-[3.5rem] shadow-2xl flex flex-col items-center border-4 border-pink-100 transform hover:scale-105 transition-transform">
<Sparkles className="text-yellow-400 mb-4 animate-pulse" size={50} />
<button className="bg-pink-500 text-white px-12 py-5 rounded-2xl font-black text-2xl shadow-lg hover:bg-pink-600 transition-colors">
START
</button>
<p className="mt-4 text-slate-400 font-bold text-sm uppercase tracking-widest">Click or Space</p>
</div>
</div>
)}
{gameOver && (
<div className={`absolute inset-0 backdrop-blur-md flex flex-col items-center justify-center text-center p-6 z-30 transition-colors duration-1000
${isNight ? 'bg-slate-950/90' : 'bg-pink-50/90'}`}>
<h3 className={`text-6xl font-black mb-4 ${isNight ? 'text-white' : 'text-pink-600'}`}>Oh No! 😿</h3>
<div className={`text-3xl font-bold mb-8 ${isNight ? 'text-indigo-300' : 'text-pink-400'}`}>Score: {score}</div>
<button className="bg-pink-500 text-white border-4 border-white px-14 py-5 rounded-2xl font-black text-2xl hover:scale-110 transition-all shadow-xl active:scale-95">
TRY AGAIN
</button>
</div>
)}
</div> </div>
{/* Informacja dla mobile */}
<div className="mt-4 text-xs text-slate-400 sm:hidden">
Tap anywhere to jump
</div>
</div> </div>
); );
}; };

View File

@@ -1,38 +1,68 @@
// src/context/AuthProvider.tsx import { useState, useCallback, type ReactNode } from 'react';
import { useState, useCallback, type ReactNode } from 'react'; import Cookies from 'js-cookie';
import { AuthContext } from './AuthContext'; // Importujemy stałą z pliku obok import { AuthContext } from './AuthContext';
import { sha512 } from '../utils/crypto'; import { sha512 } from '../utils/crypto';
import type { AuthResponse } from '../types/auth';
const TOKEN_KEY = 'ktty_shared_token';
const getCookieConfig = () => {
const hostname = window.location.hostname;
// Sprawdzamy, czy jesteśmy na localhost
const isLocal = hostname === 'localhost' || hostname === '127.0.0.1';
// Sprawdzamy, czy połączenie jest bezpieczne (HTTPS)
const isSecure = window.location.protocol === 'https:';
return {
// Na produkcji używamy domeny nadrzędnej z kropką, by działało na subdomenach
// Na localhost MUSI być undefined, inaczej przeglądarka odrzuci ciasteczko
domain: isLocal ? undefined : '.ktty.is',
// Atrybut Secure wymaga HTTPS. Na localhost wyłączamy, na produkcji włączamy.
secure: isSecure,
// 'Lax' jest bezpieczne i pozwala na współdzielenie w obrębie subdomen.
// Jeśli API jest na zupełnie innej domenie, rozważ 'None' (wymaga Secure: true).
sameSite: 'Lax' as const,
path: '/',
expires: 7
};
};
export function AuthProvider({ children }: { children: ReactNode }) { export function AuthProvider({ children }: { children: ReactNode }) {
const [token, setToken] = useState<string | null>(sessionStorage.getItem('ktty_token')); const [token, setToken] = useState<string | null>(() => Cookies.get(TOKEN_KEY) || null);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null); // DODANE
const authRequest = useCallback(async (endpoint: 'signUp' | 'signIn', name: string, pass: string) => { const authRequest = useCallback(async (endpoint: 'signIn' | 'signUp', name: string, pass: string) => {
setLoading(true); setLoading(true);
setError(null); setError(null);
try { try {
const hashedPassword = await sha512(pass); const hashedPassword = await sha512(pass);
const response = await fetch(`/api/v1/user/${endpoint}`, { const response = await fetch(`/api/v1/user/${endpoint}`, {
method: 'POST', method: 'POST',
headers: { headers: { 'Content-Type': 'application/json' },
'accept': 'application/json', credentials: 'include',
'Content-Type': 'application/json', body: JSON.stringify({ name, password: hashedPassword }),
},
body: JSON.stringify({ name, password: hashedPassword, ttl: 86400 }),
}); });
const data: AuthResponse = await response.json(); const data = await response.json();
if (!response.ok) throw new Error(data.error || data.message || `Error ${response.status}`);
if (data.token) { if (!response.ok) {
sessionStorage.setItem('ktty_token', data.token); throw new Error(data?.message || 'Błąd autoryzacji');
setToken(data.token); // To aktualizuje stan w całej aplikacji natychmiast! }
if (data?.token) {
Cookies.set(TOKEN_KEY, data.token, getCookieConfig());
setToken(data.token);
} }
return data; return data;
} catch (err: unknown) { } catch (err: unknown) {
setError(err instanceof Error ? err.message : 'Unknown error'); const msg = err instanceof Error ? err.message : 'Wystąpił błąd';
setError(msg);
return null; return null;
} finally { } finally {
setLoading(false); setLoading(false);
@@ -40,7 +70,9 @@ export function AuthProvider({ children }: { children: ReactNode }) {
}, []); }, []);
const logout = useCallback(() => { const logout = useCallback(() => {
sessionStorage.removeItem('ktty_token'); const config = getCookieConfig();
// When removing, you must match the domain and path used when setting
Cookies.remove(TOKEN_KEY, { domain: config.domain, path: config.path });
setToken(null); setToken(null);
}, []); }, []);

View File

@@ -1,4 +1,4 @@
{ {
"compilerOptions": { "compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo", "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "ES2022", "target": "ES2022",

View File

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

View File

@@ -1,50 +1,54 @@
import { defineConfig, loadEnv } from 'vite' import { defineConfig, loadEnv, type PluginOption } from 'vite'
import react from '@vitejs/plugin-react' import react from '@vitejs/plugin-react'
import tailwindcss from '@tailwindcss/vite' import tailwindcss from '@tailwindcss/vite'
import path from 'path' // Importuj moduł path import path from 'path'
import { fileURLToPath } from 'url'
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
export default defineConfig(({ mode }) => { export default defineConfig(({ mode }) => {
// Ustawiamy ścieżkę do folderu, w którym faktycznie znajduje się plik .env
// path.resolve(__dirname, '..') oznacza: "wyjdź jeden poziom wyżej względem tego pliku"
const envDirectory = path.resolve(__dirname, '..'); const envDirectory = path.resolve(__dirname, '..');
// Ładujemy env z określonej lokalizacji
const env = loadEnv(mode, envDirectory, ''); const env = loadEnv(mode, envDirectory, '');
const apiTarget = env.VITE_API_TARGET; const backendTarget = env.VITE_API_TARGET;
return { return {
envDir: envDirectory,
plugins: [ plugins: [
react(), react() as PluginOption,
tailwindcss(), tailwindcss() as PluginOption,
], ],
server: { server: {
port: 6568, port: 6568,
host: true, // Pozwala na dostęp przez IP w sieci lokalnej
// Jeśli testujesz subdomeny lokalnie (np. app.local.ktty.is), dodaj to:
allowedHosts: [
'.ktty.is',
'localhost',
'127.0.0.1',
],
// vite.config.ts
proxy: { proxy: {
'/api': { '/api': {
target: apiTarget, target: backendTarget,
changeOrigin: true, changeOrigin: true,
secure: false, secure: false,
headers: { cookieDomainRewrite: {
'Origin': apiTarget, "*": ""
'Referer': `${apiTarget}/`
}, },
configure: (proxy) => { },
proxy.on('error', (err) => { },
console.log('[Proxy Error]:', err.message);
});
proxy.on('proxyReq', (_, req) => {
console.log(`[Proxy] Wysyłam do: ${apiTarget}${req.url}`);
});
proxy.on('proxyRes', (proxyRes, req) => {
console.log(`[Proxy] Odpowiedź: ${proxyRes.statusCode} ${req.url}`);
});
},
}
}
}, },
preview: { preview: {
port: 6568, port: 6568,
allowedHosts: true,
},
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
},
}, },
} }
}) })