Pierwszy commit

This commit is contained in:
2024-09-10 21:30:40 +02:00
commit a616741470
31 changed files with 1070 additions and 0 deletions
+38
View File
@@ -0,0 +1,38 @@
import React from 'react';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import { Provider } from 'jotai';
import Header from './components/Header';
import Home from './pages/Home';
import Login from './pages/Login';
import Register from './pages/Register';
import ForgotPassword from './pages/ForgotPassword';
import Profile from './pages/Profile';
import CreatePost from './pages/CreatePost';
const App: React.FC = () => {
return (
<Provider>
<Router>
<div className="min-h-screen bg-gray-100">
<Header />
<main className="container mx-auto mt-4 p-4">
<Routes>
<Route path="/" element={<Home />} />
<Route path="/login" element={<Login />} />
<Route path="/register" element={<Register />} />
<Route path="/forgot-password" element={<ForgotPassword />} />
<Route path="/profile" element={<Profile />} />
<Route path="/create-post" element={<CreatePost />} />
</Routes>
</main>
</div>
</Router>
</Provider>
);
};
export default App;
// Rdzenny komponent aplikacji. Tutaj używany jest nagłowek
// oraz definiowane są adresy url oraz
// jaki komponent się pod nimi znajduje.
+15
View File
@@ -0,0 +1,15 @@
import { atom } from 'jotai';
import { pb } from '../lib/pocketbase';
export const authAtom = atom(pb.authStore.isValid);
export const updateAuthAtom = atom(
(get) => get(authAtom),
(_, set) => {
set(authAtom, pb.authStore.isValid);
}
);
// Utworzenie store przy użyciu Jotai
// do przechowywania danych o zalogowanym
// użytkowniku między komponentami.
+42
View File
@@ -0,0 +1,42 @@
import React from 'react';
import { Link } from 'react-router-dom';
import { useAtom } from 'jotai';
import { authAtom, updateAuthAtom } from '../atoms/authAtom';
import { pb } from '../lib/pocketbase';
const Header: React.FC = () => {
const [isAuth] = useAtom(authAtom);
const [, updateAuth] = useAtom(updateAuthAtom);
const handleLogout = () => {
pb.authStore.clear();
updateAuth();
};
return (
<header className="bg-blue-500 p-4">
<div className="container mx-auto flex justify-between items-center">
<Link to="/" className="text-white text-2xl font-bold">Reddit-Like-App</Link>
<Link to="https://gitea.garandplg.com/GarandPLG/reddit-like-app" className="text-white text-xl font-bold">Kod źródłowy</Link>
<nav>
{isAuth ? (
<>
<Link to="/create-post" className="text-white mr-4">Stwórz post</Link>
<Link to="/profile" className="text-white mr-4">Profil</Link>
<button onClick={handleLogout} className="text-white">Wyloguj się</button>
</>
) : (
<>
<Link to="/login" className="text-white mr-4">Zaloguj się</Link>
<Link to="/register" className="text-white">Zarejestruj się</Link>
</>
)}
</nav>
</div>
</header>
);
};
export default Header;
// komponent odpowiedzialny za nagłówek strony
+103
View File
@@ -0,0 +1,103 @@
import React, { useState, useEffect } from 'react';
import { useAtom } from 'jotai';
import { authAtom } from '../atoms/authAtom';
import { pb } from '../lib/pocketbase';
interface PostProps {
post: {
id: string;
title: string;
content: string;
user: string;
votes: number;
created: string;
};
onVoteChange?: (postId: string, newVotes: number) => void;
}
const Post: React.FC<PostProps> = ({ post, onVoteChange }) => {
const [isAuth] = useAtom(authAtom);
const [username, setUsername] = useState<string>('');
const [votes, setVotes] = useState(post.votes);
useEffect(() => {
const fetchUsername = async () => {
try {
const user = await pb.collection("users").getOne(post.user);
setUsername(user.username);
} catch (error) {
console.error('Błąd przy pobieraniu nazwy użytkownika:', error);
setUsername('Nieznany użytkownik');
}
};
fetchUsername();
}, [post.user]);
useEffect(() => {
const subscribeToPost = async () => {
try {
pb.realtime.subscribe(`posts/${post.id}`, (e) => {
if (e.action === 'update' && e.record.id === post.id) {
setVotes(e.record.votes);
}
});
} catch (error) {
console.error('Błąd przy renderowaniu głosów in real time:', error);
}
};
subscribeToPost();
return () => {
pb.realtime.unsubscribe(`posts/${post.id}`);
};
}, [post.id]);
const handleVote = async (type: 'up' | 'down') => {
if (!isAuth) {
alert('Musisz się zalogować, by móc głosować.');
return;
}
const newVotes = type === 'up' ? votes + 1 : votes - 1;
setVotes(newVotes);
try {
await pb.collection('posts').update(post.id, { votes: newVotes });
if (onVoteChange) {
onVoteChange(post.id, newVotes);
}
} catch (error) {
console.error('Błąd przy głosowaniu:', error);
setVotes(votes);
alert('Nie udało się dodać głosu. Spróbuj jeszcze raz.');
}
};
return (
<div className="bg-white p-4 rounded mt-2">
<div className='mb-4'>
<span className="mt-4 mr-4">
<button onClick={() => handleVote('up')} className="mr-2">👍</button>
<span>{votes}</span>
<button onClick={() => handleVote('down')} className="ml-2">👎</button>
</span>
<span className='text-xl'>|</span>
<span className="mb-4 mx-4 text-gray-500 text-lg">
{username}
</span>
<span className='text-xl'>|</span>
<span className="my-2 ml-4">{new Date(post.created).toLocaleString()}</span>
</div>
<h3 className="text-2xl font-bold">{post.title}</h3>
<p className="mt-2">{post.content}</p>
</div>
)};
export default Post;
// Komponent odpowiedzialny za renderowanie pojedynczego posta.
+3
View File
@@ -0,0 +1,3 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
+7
View File
@@ -0,0 +1,7 @@
import PocketBase from 'pocketbase';
export const pb = new PocketBase('https://pb.garandplg.com').autoCancellation(false);
// Inicjacja połączenia z moją instancją pocketbase
// oraz wyeksportowanie tego połączenia
// by było łatwo dostępne w projekcie.
+10
View File
@@ -0,0 +1,10 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import App from './App.tsx'
import './index.css'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
)
+60
View File
@@ -0,0 +1,60 @@
import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { pb } from '../lib/pocketbase';
const CreatePost: React.FC = () => {
const [title, setTitle] = useState('');
const [content, setContent] = useState('');
const navigate = useNavigate();
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
try {
await pb.collection('posts').create({
title,
content,
user: pb.authStore.model!.id,
votes: 0,
});
navigate('/');
} catch (error) {
console.error('Błąd przy tworzeniu posta:', error);
alert('Nie udało się stworzyć posta');
}
};
return (
<div className="max-w-md mx-auto">
<h1 className="text-2xl font-bold mb-4">Stwórz post</h1>
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label htmlFor="title" className="block mb-1">Tytuł</label>
<input
type="text"
id="title"
value={title}
onChange={(e) => setTitle(e.target.value)}
required
className="w-full px-3 py-2 border rounded"
/>
</div>
<div>
<label htmlFor="content" className="block mb-1">Zawartość</label>
<textarea
id="content"
value={content}
onChange={(e) => setContent(e.target.value)}
required
className="w-full px-3 py-2 border rounded"
rows={5}
></textarea>
</div>
<button type="submit" className="w-full bg-blue-500 text-white py-2 rounded">Stwórz post</button>
</form>
</div>
);
};
export default CreatePost;
// Formularz dodawania posta.
+43
View File
@@ -0,0 +1,43 @@
import React, { useState } from 'react';
import { pb } from '../lib/pocketbase';
const ForgotPassword: React.FC = () => {
const [email, setEmail] = useState('');
const [message, setMessage] = useState('');
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
try {
await pb.collection('users').requestPasswordReset(email);
setMessage('Mail z resetem hasła został wysłany.');
} catch (error) {
console.error('Błąd z resetem hasła:', error);
setMessage('Nie udało się wysłać maila z resetem hasła.');
}
};
return (
<div className="max-w-md mx-auto">
<h1 className="text-2xl font-bold mb-4">Zapomniałem hasła</h1>
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label htmlFor="email" className="block mb-1">Email</label>
<input
type="email"
id="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
className="w-full px-3 py-2 border rounded"
/>
</div>
<button type="submit" className="w-full bg-blue-500 text-white py-2 rounded">Rezetuj hasło</button>
</form>
{message && <p className="mt-4 text-center">{message}</p>}
</div>
);
};
export default ForgotPassword;
// Formularz przypominania hasła.
+69
View File
@@ -0,0 +1,69 @@
import React, { useState, useEffect } from 'react';
import { pb } from '../lib/pocketbase';
import Post from '../components/Post';
interface PostType {
id: string;
title: string;
content: string;
user: string;
votes: number;
created: string;
}
const Home: React.FC = () => {
const [posts, setPosts] = useState<PostType[]>([]);
useEffect(() => {
const fetchPosts = async () => {
try {
const records = await pb.collection('posts').getFullList<PostType>({
sort: '-votes',
expand: 'user',
});
setPosts(records);
} catch (error) {
console.error('Błąd przy pobieraniu postów:', error);
}
};
fetchPosts();
pb.realtime.subscribe('posts', (e) => {
const updatedRecord = e.record as PostType;
if (e.action === 'create') {
setPosts((prevPosts) => [updatedRecord, ...prevPosts].sort((a, b) => b.votes - a.votes));
} else if (e.action === 'update') {
setPosts((prevPosts) =>
[...prevPosts.map((post) =>
post.id === updatedRecord.id ? updatedRecord : post
)].sort((a, b) => b.votes - a.votes)
);
} else if (e.action === 'delete') {
setPosts((prevPosts) =>
prevPosts.filter((post) => post.id !== updatedRecord.id)
);
}
});
return () => {
pb.realtime.unsubscribe();
};
}, []);
return (
<div>
<h1 className="text-2xl font-bold mb-4">Najwyżej oceniane posty</h1>
<div className="space-y-4">
{posts.map((post) => (
<Post key={post.id} post={post} />
))}
</div>
</div>
);
};
export default Home;
// Strona głowna, tutaj wyświetlają się posty.
+62
View File
@@ -0,0 +1,62 @@
import React, { useState } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { pb } from '../lib/pocketbase';
import { useAtom } from 'jotai';
import { updateAuthAtom } from '../atoms/authAtom';
const Login: React.FC = () => {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [, updateAuth] = useAtom(updateAuthAtom);
const navigate = useNavigate();
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
try {
await pb.collection('users').authWithPassword(email, password);
updateAuth();
navigate('/');
} catch (error) {
console.error('Błąd logowania:', error);
alert('Nie udało się zalogować');
}
};
return (
<div className="max-w-md mx-auto">
<h1 className="text-2xl font-bold mb-4">Login</h1>
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label htmlFor="email" className="block mb-1">Email</label>
<input
type="email"
id="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
className="w-full px-3 py-2 border rounded"
/>
</div>
<div>
<label htmlFor="password" className="block mb-1">Hasło</label>
<input
type="password"
id="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
className="w-full px-3 py-2 border rounded"
/>
</div>
<button type="submit" className="w-full bg-blue-500 text-white py-2 rounded">Zaloguj</button>
</form>
<div className="mt-4">
<Link to="/forgot-password" className="text-blue-500">Zapomniałeś hasła?</Link>
</div>
</div>
);
};
export default Login;
// Formularz logowania się.
+99
View File
@@ -0,0 +1,99 @@
import React, { useState, useEffect } from 'react';
import { pb } from '../lib/pocketbase';
import { useAtom } from 'jotai';
import { updateAuthAtom } from '../atoms/authAtom';
const Profile: React.FC = () => {
const [email, setEmail] = useState('');
const [newPassword, setNewPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
const [, updateAuth] = useAtom(updateAuthAtom);
useEffect(() => {
if (pb.authStore.model) {
setEmail(pb.authStore.model.email);
}
}, []);
const handleUpdateProfile = async (e: React.FormEvent) => {
e.preventDefault();
if (newPassword && newPassword !== confirmPassword) {
alert("Hasła nie są takie same");
return;
}
try {
const data: Record<string, any> = { email };
if (newPassword) {
data.password = newPassword;
data.passwordConfirm = confirmPassword;
}
await pb.collection('users').update(pb.authStore.model!.id, data);
alert('Profile updated successfully');
updateAuth();
} catch (error) {
console.error('Profile update error:', error);
alert('Failed to update profile');
}
};
const handleDeleteAccount = async () => {
if (window.confirm('Jesteś pewien, że chcesz usunąć konto? Tej akcji nie da się cofnąć.')) {
try {
await pb.collection('users').delete(pb.authStore.model!.id);
pb.authStore.clear();
updateAuth();
alert('Konto poprawnie usunięte');
} catch (error) {
console.error('Błąd z usuwaniem konta:', error);
alert('Nie udało się usunąc konta.');
}
}
};
return (
<div className="max-w-md mx-auto">
<h1 className="text-2xl font-bold mb-4">Profile</h1>
<form onSubmit={handleUpdateProfile} className="space-y-4">
<div>
<label htmlFor="email" className="block mb-1">Email</label>
<input
type="email"
id="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
className="w-full px-3 py-2 border rounded"
/>
</div>
<div>
<label htmlFor="newPassword" className="block mb-1">Nowe hasło</label>
<input
type="password"
id="newPassword"
value={newPassword}
onChange={(e) => setNewPassword(e.target.value)}
className="w-full px-3 py-2 border rounded"
/>
</div>
<div>
<label htmlFor="confirmPassword" className="block mb-1">Powtórz nowe hasło</label>
<input
type="password"
id="confirmPassword"
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
className="w-full px-3 py-2 border rounded"
/>
</div>
<button type="submit" className="w-full bg-blue-500 text-white py-2 rounded">Zaktualizuj profil</button>
</form>
<button onClick={handleDeleteAccount} className="w-full mt-4 bg-red-500 text-white py-2 rounded">Usuń konto</button>
</div>
);
};
export default Profile;
// Formularz zmieniania profilu użytkownika
+97
View File
@@ -0,0 +1,97 @@
import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { pb } from '../lib/pocketbase';
import { useAtom } from 'jotai';
import { updateAuthAtom } from '../atoms/authAtom';
const Register: React.FC = () => {
const [email, setEmail] = useState('');
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [passwordConfirm, setPasswordConfirm] = useState('');
const [, updateAuth] = useAtom(updateAuthAtom);
const navigate = useNavigate();
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (password !== passwordConfirm) {
alert("Hasła nie są takie same!");
return;
}
try {
const createdUser = await pb.collection('users').create({
email,
username,
password,
passwordConfirm,
});
if (createdUser) {
await pb.collection('users').requestVerification(email);
alert('Udana rejestracja. Sprawdź swój adres email aby aktywować konto.');
}
navigate('/login');
} catch (error) {
console.error('Błąd rejestracji:', error);
alert('Nieudana rejestracja');
}
};
return (
<div className="max-w-md mx-auto">
<h1 className="text-2xl font-bold mb-4">Zarejestruj się</h1>
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label htmlFor="email" className="block mb-1">Email</label>
<input
type="email"
id="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
className="w-full px-3 py-2 border rounded"
/>
</div>
<div>
<label htmlFor="username" className="block mb-1">Nazwa użytkownika</label>
<input
type="text"
id="username"
value={username}
onChange={(e) => setUsername(e.target.value)}
required
className="w-full px-3 py-2 border rounded"
/>
</div>
<div>
<label htmlFor="password" className="block mb-1">Hasło</label>
<input
type="password"
id="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
className="w-full px-3 py-2 border rounded"
/>
</div>
<div>
<label htmlFor="passwordConfirm" className="block mb-1">Powtórz hasło</label>
<input
type="password"
id="passwordConfirm"
value={passwordConfirm}
onChange={(e) => setPasswordConfirm(e.target.value)}
required
className="w-full px-3 py-2 border rounded"
/>
</div>
<button type="submit" className="w-full bg-blue-500 text-white py-2 rounded">Zarejestruj się</button>
</form>
</div>
);
};
export default Register;
// Formularz rejestracji.
+1
View File
@@ -0,0 +1 @@
/// <reference types="vite/client" />