Compare commits
45
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
055e433b14 | ||
|
|
f3dba4c483 | ||
|
|
5584299d44 | ||
|
|
97ac27e78a | ||
|
|
c84f617e5c | ||
|
|
15d3ab79bd | ||
|
|
4abe8a53df | ||
|
|
5729940a62 | ||
|
|
1c48ea9230 | ||
|
|
c196ffc265 | ||
|
|
b756204514 | ||
|
|
76281892a2 | ||
|
|
8601d7ced1 | ||
|
|
74941a8abc | ||
|
|
86683d410f | ||
|
|
acc6bc4359 | ||
|
|
5dfe1fbb98 | ||
|
|
fdbd88dd7e | ||
|
|
d42ed445d8 | ||
|
|
d560b6db6f | ||
|
|
500be84f39 | ||
|
|
2ee08dc7d8 | ||
|
|
e7fede576c | ||
|
|
f24e8fc1e9 | ||
|
|
0eea1b1ff4 | ||
|
|
db417e50d9 | ||
|
|
4eed9adaad | ||
|
|
1b45f4c8da | ||
|
|
63cdf58671 | ||
|
|
ccb57637f1 | ||
|
|
42773a44d3 | ||
|
|
737982ac20 | ||
|
|
9543dd78cf | ||
|
|
d2a2f0ceea | ||
|
|
f4628ad37f | ||
|
|
5cb67355fb | ||
|
|
d1b65231a6 | ||
|
|
5b397e2265 | ||
|
|
d916014872 | ||
|
|
f6d40b8f2e | ||
|
|
baa18484ca | ||
|
|
7586133152 | ||
|
|
aa8fb73c61 | ||
|
|
696a9ba9b3 | ||
|
|
938fdd5ad6 |
+3
-1
@@ -1,2 +1,4 @@
|
||||
target/
|
||||
cache/
|
||||
cache/
|
||||
tokens.bin
|
||||
.auth_key
|
||||
Generated
+558
-254
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1 @@
|
||||
["Code002Lover","HoherGeist"]
|
||||
+9
-6
@@ -6,17 +6,20 @@ default-run = "backend"
|
||||
|
||||
|
||||
[dependencies]
|
||||
prost = "0.14.1"
|
||||
prost-types = "0.14.1"
|
||||
prost = "0.14"
|
||||
prost-types = "0.14"
|
||||
rocket = { git = "https://github.com/rwf2/Rocket", rev = "504efef179622df82ba1dbd37f2e0d9ed2b7c9e4" }
|
||||
bytes = "1"
|
||||
rocket_prost_responder_derive = { path = "rocket_prost_responder_derive" }
|
||||
uuid = { version = "1.19.0", features = ["v4"] }
|
||||
uuid = { version = "1.19", features = ["v4"] }
|
||||
bcrypt = "0.17.1"
|
||||
bincode = "2.0.1"
|
||||
bincode = "2.0"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
reqwest = { version = "0.12.24", features = ["json"] }
|
||||
reqwest = { version = "0.13", features = ["json"] }
|
||||
aes-gcm = "0.10"
|
||||
base64 = "0.22"
|
||||
rand = "0.9.2"
|
||||
|
||||
[build-dependencies]
|
||||
prost-build = "0.14.1"
|
||||
prost-build = "0.14"
|
||||
|
||||
+79
-6
@@ -1,19 +1,23 @@
|
||||
use crate::auth_persistence::AuthStorage;
|
||||
use crate::items;
|
||||
use crate::proto_utils::Proto;
|
||||
use rocket::State;
|
||||
use rocket::futures::lock::Mutex;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use uuid::Uuid;
|
||||
|
||||
pub struct AuthState {
|
||||
// Map token -> username
|
||||
tokens: Mutex<HashMap<String, String>>,
|
||||
storage: AuthStorage,
|
||||
}
|
||||
|
||||
impl AuthState {
|
||||
pub fn new() -> Self {
|
||||
let storage = AuthStorage::new();
|
||||
let tokens = storage.load_tokens();
|
||||
Self {
|
||||
tokens: Mutex::new(HashMap::new()),
|
||||
tokens: Mutex::new(tokens),
|
||||
storage,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -24,6 +28,24 @@ impl Default for AuthState {
|
||||
}
|
||||
}
|
||||
|
||||
pub struct AdminState {
|
||||
pub admins: Mutex<HashSet<String>>,
|
||||
}
|
||||
|
||||
impl AdminState {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
admins: Mutex::new(crate::store::load_admins()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for AdminState {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
#[allow(dead_code)]
|
||||
pub struct Token {
|
||||
@@ -42,7 +64,6 @@ impl<'r> rocket::request::FromRequest<'r> for Token {
|
||||
|
||||
match token {
|
||||
Some(token) => {
|
||||
// Check if token starts with "Bearer "
|
||||
if let Some(token) = token.strip_prefix("Bearer ") {
|
||||
let state = request.guard::<&State<AuthState>>().await.unwrap();
|
||||
let tokens = state.tokens.lock().await;
|
||||
@@ -62,6 +83,48 @@ impl<'r> rocket::request::FromRequest<'r> for Token {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct AdminToken {
|
||||
pub token: String,
|
||||
pub username: String,
|
||||
}
|
||||
|
||||
#[rocket::async_trait]
|
||||
impl<'r> rocket::request::FromRequest<'r> for AdminToken {
|
||||
type Error = ();
|
||||
|
||||
async fn from_request(
|
||||
request: &'r rocket::Request<'_>,
|
||||
) -> rocket::request::Outcome<Self, Self::Error> {
|
||||
let token = request.headers().get_one("Authorization");
|
||||
|
||||
match token {
|
||||
Some(token) => {
|
||||
if let Some(token) = token.strip_prefix("Bearer ") {
|
||||
let auth_state = request.guard::<&State<AuthState>>().await.unwrap();
|
||||
let tokens = auth_state.tokens.lock().await;
|
||||
|
||||
if let Some(username) = tokens.get(token) {
|
||||
let admin_state =
|
||||
request.guard::<&State<crate::AdminState>>().await.unwrap();
|
||||
let admins = admin_state.admins.lock().await;
|
||||
|
||||
if crate::store::is_admin(username, &admins) {
|
||||
return rocket::request::Outcome::Success(AdminToken {
|
||||
token: token.to_string(),
|
||||
username: username.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
rocket::request::Outcome::Error((rocket::http::Status::Forbidden, ()))
|
||||
}
|
||||
None => rocket::request::Outcome::Error((rocket::http::Status::Unauthorized, ())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[post("/login", data = "<request>")]
|
||||
pub async fn login(
|
||||
state: &State<AuthState>,
|
||||
@@ -71,12 +134,15 @@ pub async fn login(
|
||||
let req = request.into_inner();
|
||||
let users = user_list.lock().await;
|
||||
|
||||
if let Some(user) = users.iter().find(|u| u.person.name == req.username)
|
||||
if let Some(user) = users
|
||||
.iter()
|
||||
.find(|u| u.person.name.to_lowercase() == req.username.to_lowercase())
|
||||
&& bcrypt::verify(&req.password, &user.password_hash).unwrap_or(false)
|
||||
{
|
||||
let token = Uuid::new_v4().to_string();
|
||||
let mut tokens = state.tokens.lock().await;
|
||||
tokens.insert(token.clone(), req.username);
|
||||
tokens.insert(token.clone(), req.username.clone());
|
||||
state.storage.save_tokens(&tokens);
|
||||
|
||||
return items::LoginResponse {
|
||||
token,
|
||||
@@ -101,6 +167,7 @@ pub async fn logout(
|
||||
let mut tokens = state.tokens.lock().await;
|
||||
|
||||
if tokens.remove(&req.token).is_some() {
|
||||
state.storage.save_tokens(&tokens);
|
||||
items::LogoutResponse {
|
||||
success: true,
|
||||
message: "Logged out successfully".to_string(),
|
||||
@@ -116,22 +183,28 @@ pub async fn logout(
|
||||
#[post("/get_auth_status", data = "<request>")]
|
||||
pub async fn get_auth_status(
|
||||
state: &State<AuthState>,
|
||||
admin_state: &State<AdminState>,
|
||||
request: Proto<items::AuthStatusRequest>,
|
||||
) -> items::AuthStatusResponse {
|
||||
let req = request.into_inner();
|
||||
let tokens = state.tokens.lock().await;
|
||||
|
||||
if let Some(username) = tokens.get(&req.token) {
|
||||
let admins = admin_state.admins.lock().await;
|
||||
let is_admin = crate::store::is_admin(username, &admins);
|
||||
|
||||
items::AuthStatusResponse {
|
||||
authenticated: true,
|
||||
username: username.clone(),
|
||||
message: "Authenticated".to_string(),
|
||||
is_admin,
|
||||
}
|
||||
} else {
|
||||
items::AuthStatusResponse {
|
||||
authenticated: false,
|
||||
username: "".to_string(),
|
||||
message: "Not authenticated".to_string(),
|
||||
is_admin: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,227 @@
|
||||
use aes_gcm::{
|
||||
Aes256Gcm, Nonce,
|
||||
aead::{Aead, KeyInit},
|
||||
};
|
||||
use base64::{Engine, engine::general_purpose::STANDARD};
|
||||
use bincode::{config, decode_from_slice, encode_to_vec};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use std::fs::File;
|
||||
use std::io::{self, BufReader, BufWriter, Write};
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, bincode::Encode, bincode::Decode)]
|
||||
pub struct TokenEntry {
|
||||
pub token: String,
|
||||
pub username: String,
|
||||
pub created_at: u64,
|
||||
}
|
||||
|
||||
const AUTH_KEY_FILE: &str = ".auth_key";
|
||||
const TOKENS_FILE: &str = "tokens.bin";
|
||||
const NONCE_SIZE: usize = 12;
|
||||
const KEY_SIZE: usize = 32;
|
||||
|
||||
pub struct AuthStorage {
|
||||
cipher: Aes256Gcm,
|
||||
}
|
||||
|
||||
impl Default for AuthStorage {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl AuthStorage {
|
||||
pub fn new() -> Self {
|
||||
let key = Self::load_or_create_key();
|
||||
let cipher = Aes256Gcm::new_from_slice(&key).expect("Invalid key length");
|
||||
Self { cipher }
|
||||
}
|
||||
|
||||
fn load_or_create_key() -> Vec<u8> {
|
||||
if let Ok(existing_key) = Self::load_key_from_file() {
|
||||
return existing_key;
|
||||
}
|
||||
|
||||
let key = Self::generate_key();
|
||||
if let Err(e) = Self::save_key_to_file(&key) {
|
||||
eprintln!("Warning: Failed to save auth key to file: {}", e);
|
||||
}
|
||||
key
|
||||
}
|
||||
|
||||
fn generate_key() -> Vec<u8> {
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
let mut key = [0u8; KEY_SIZE];
|
||||
|
||||
let timestamp = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_nanos();
|
||||
|
||||
let mut seed = timestamp as u64;
|
||||
for byte in key.iter_mut() {
|
||||
seed = seed.wrapping_mul(1103515245).wrapping_add(12345);
|
||||
*byte = (seed >> (seed % 8)) as u8;
|
||||
}
|
||||
|
||||
key.to_vec()
|
||||
}
|
||||
|
||||
fn load_key_from_file() -> io::Result<Vec<u8>> {
|
||||
let file = File::open(AUTH_KEY_FILE)?;
|
||||
let reader = BufReader::new(file);
|
||||
let encoded = std::io::read_to_string(reader)?;
|
||||
let key = STANDARD.decode(encoded).map_err(|e| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
format!("Base64 decode error: {}", e),
|
||||
)
|
||||
})?;
|
||||
|
||||
if key.len() != KEY_SIZE {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"Invalid key length",
|
||||
));
|
||||
}
|
||||
|
||||
Ok(key)
|
||||
}
|
||||
|
||||
fn save_key_to_file(key: &[u8]) -> io::Result<()> {
|
||||
let encoded = STANDARD.encode(key);
|
||||
let mut file = File::create(AUTH_KEY_FILE)?;
|
||||
|
||||
let mut permissions = file.metadata()?.permissions();
|
||||
permissions.set_mode(0o600);
|
||||
file.set_permissions(permissions)?;
|
||||
|
||||
file.write_all(encoded.as_bytes())?;
|
||||
file.sync_all()?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn load_tokens(&self) -> HashMap<String, String> {
|
||||
let file = match File::open(TOKENS_FILE) {
|
||||
Ok(f) => f,
|
||||
Err(_) => {
|
||||
eprintln!("Warning: No existing tokens file, starting with empty token list");
|
||||
return HashMap::new();
|
||||
}
|
||||
};
|
||||
|
||||
let reader = BufReader::new(file);
|
||||
let encrypted_data = match std::io::read_to_string(reader) {
|
||||
Ok(data) => data,
|
||||
Err(_) => {
|
||||
eprintln!("Warning: Failed to read tokens file, starting with empty token list");
|
||||
return HashMap::new();
|
||||
}
|
||||
};
|
||||
|
||||
let decoded = match STANDARD.decode(&encrypted_data) {
|
||||
Ok(data) => data,
|
||||
Err(_) => {
|
||||
eprintln!("Warning: Failed to decode tokens file, starting with empty token list");
|
||||
return HashMap::new();
|
||||
}
|
||||
};
|
||||
|
||||
if decoded.len() <= NONCE_SIZE {
|
||||
eprintln!("Warning: Invalid tokens file format, starting with empty token list");
|
||||
return HashMap::new();
|
||||
}
|
||||
|
||||
let (nonce_bytes, ciphertext) = decoded.split_at(NONCE_SIZE);
|
||||
let nonce = Nonce::from_slice(nonce_bytes);
|
||||
|
||||
let plaintext = match self.cipher.decrypt(nonce, ciphertext.as_ref()) {
|
||||
Ok(p) => p,
|
||||
Err(_) => {
|
||||
eprintln!("Warning: Failed to decrypt tokens file, starting with empty token list");
|
||||
return HashMap::new();
|
||||
}
|
||||
};
|
||||
|
||||
let config = config::standard();
|
||||
let (entries, _): (Vec<TokenEntry>, usize) = match decode_from_slice(&plaintext, config) {
|
||||
Ok(e) => e,
|
||||
Err(_) => {
|
||||
eprintln!("Warning: Failed to deserialize tokens, starting with empty token list");
|
||||
return HashMap::new();
|
||||
}
|
||||
};
|
||||
|
||||
entries
|
||||
.into_iter()
|
||||
.map(|entry| (entry.token, entry.username))
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn save_tokens(&self, tokens: &HashMap<String, String>) {
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
let entries: Vec<TokenEntry> = tokens
|
||||
.iter()
|
||||
.map(|(token, username)| TokenEntry {
|
||||
token: token.clone(),
|
||||
username: username.clone(),
|
||||
created_at: SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs(),
|
||||
})
|
||||
.collect();
|
||||
|
||||
let config = config::standard();
|
||||
let plaintext: Vec<u8> = match encode_to_vec(&entries, config) {
|
||||
Ok(data) => data,
|
||||
Err(e) => {
|
||||
eprintln!("Warning: Failed to serialize tokens: {}", e);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
let nonce_bytes: [u8; NONCE_SIZE] = rand::random();
|
||||
let nonce = Nonce::from_slice(&nonce_bytes);
|
||||
let ciphertext = match self.cipher.encrypt(nonce, plaintext.as_ref()) {
|
||||
Ok(encrypted) => encrypted,
|
||||
Err(e) => {
|
||||
eprintln!("Warning: Failed to encrypt tokens: {}", e);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
let mut encrypted_data = nonce_bytes.to_vec();
|
||||
encrypted_data.extend_from_slice(&ciphertext);
|
||||
|
||||
let encoded = STANDARD.encode(&encrypted_data);
|
||||
|
||||
match File::create(TOKENS_FILE) {
|
||||
Ok(file) => {
|
||||
if let Ok(metadata) = file.metadata() {
|
||||
let mut permissions = metadata.permissions();
|
||||
permissions.set_mode(0o600);
|
||||
if let Err(e) = file.set_permissions(permissions) {
|
||||
eprintln!("Warning: Failed to set permissions on tokens file: {}", e);
|
||||
}
|
||||
}
|
||||
|
||||
let mut writer = BufWriter::new(file);
|
||||
|
||||
if let Err(e) = writer.write_all(encoded.as_bytes()) {
|
||||
eprintln!("Warning: Failed to write tokens file: {}", e);
|
||||
}
|
||||
if let Err(e) = writer.flush() {
|
||||
eprintln!("Warning: Failed to flush tokens file: {}", e);
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("Warning: Failed to create tokens file: {}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,12 @@ pub mod items {
|
||||
}
|
||||
|
||||
pub mod auth;
|
||||
pub mod auth_persistence;
|
||||
pub mod proto_utils;
|
||||
pub mod security_headers;
|
||||
pub mod store;
|
||||
pub mod validation;
|
||||
|
||||
pub use auth::AdminState;
|
||||
pub use security_headers::SecurityHeaders;
|
||||
pub use store::User;
|
||||
|
||||
+223
-36
@@ -3,9 +3,12 @@ use rocket::fs::FileServer;
|
||||
use rocket::futures::lock::Mutex;
|
||||
|
||||
use backend::auth;
|
||||
use backend::auth::AdminState;
|
||||
use backend::items::{self, Game};
|
||||
use backend::proto_utils;
|
||||
use backend::security_headers::SecurityHeaders;
|
||||
use backend::store::{self, User, save_state};
|
||||
use backend::validation;
|
||||
|
||||
#[macro_use]
|
||||
extern crate rocket;
|
||||
@@ -16,10 +19,14 @@ async fn get_user(
|
||||
user_list: &rocket::State<Mutex<Vec<User>>>,
|
||||
name: &str,
|
||||
) -> Option<items::Person> {
|
||||
if validation::validate_username(name).is_err() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let users = user_list.lock().await;
|
||||
users
|
||||
.iter()
|
||||
.find(|user| user.person.name == name)
|
||||
.find(|user| user.person.name.to_lowercase() == name.to_lowercase())
|
||||
.map(|u| u.person.clone())
|
||||
}
|
||||
|
||||
@@ -40,8 +47,32 @@ async fn get_game(
|
||||
game_list: &rocket::State<Mutex<Vec<Game>>>,
|
||||
title: &str,
|
||||
) -> Option<items::Game> {
|
||||
if validation::validate_game_title(title).is_err() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let games = game_list.lock().await;
|
||||
games.iter().find(|g| g.title == title).cloned()
|
||||
games
|
||||
.iter()
|
||||
.find(|g| g.title.to_lowercase() == title.to_lowercase())
|
||||
.cloned()
|
||||
}
|
||||
|
||||
#[post("/games/batch", data = "<req>")]
|
||||
async fn get_games_batch(
|
||||
_token: auth::Token,
|
||||
game_list: &rocket::State<Mutex<Vec<Game>>>,
|
||||
req: proto_utils::Proto<items::GetGameInfoRequest>,
|
||||
) -> Result<items::GameList, String> {
|
||||
let req = req.into_inner();
|
||||
|
||||
let games_set: std::collections::HashSet<String> = req.games.into_iter().collect();
|
||||
validation::validate_game_titles_batch(&games_set)?;
|
||||
|
||||
let games = game_list.lock().await;
|
||||
let mut games = games.clone();
|
||||
games.retain(|g| games_set.contains(&g.title));
|
||||
Ok(items::GameList { games })
|
||||
}
|
||||
|
||||
#[get("/games")]
|
||||
@@ -55,52 +86,192 @@ async fn get_games(
|
||||
}
|
||||
}
|
||||
|
||||
#[post("/game", data = "<game>")]
|
||||
#[post("/game", data = "<game>", rank = 1)]
|
||||
async fn add_game(
|
||||
_token: auth::Token,
|
||||
game_list: &rocket::State<Mutex<Vec<Game>>>,
|
||||
user_list: &rocket::State<Mutex<Vec<User>>>,
|
||||
game: proto_utils::Proto<items::Game>,
|
||||
) -> Option<items::Game> {
|
||||
let mut games = game_list.lock().await;
|
||||
) -> Result<Option<items::Game>, String> {
|
||||
let mut game = game.into_inner();
|
||||
|
||||
if games.iter().any(|g| {
|
||||
g.title == game.title || (g.remote_id == game.remote_id && g.source == game.source)
|
||||
}) {
|
||||
return None;
|
||||
game.title = game.title.trim().to_string();
|
||||
|
||||
validation::validate_game_title(&game.title)?;
|
||||
validation::validate_remote_id(game.remote_id)?;
|
||||
validation::validate_player_count(game.min_players, game.max_players)?;
|
||||
validation::validate_price(game.price)?;
|
||||
|
||||
if game.title.len() > validation::MAX_GAME_TITLE_TRIMMED_LENGTH {
|
||||
game.title = game
|
||||
.title
|
||||
.chars()
|
||||
.take(validation::MAX_GAME_TITLE_TRIMMED_LENGTH)
|
||||
.collect();
|
||||
}
|
||||
|
||||
game.title = game.title.trim().to_string();
|
||||
let users = user_list.lock().await;
|
||||
let mut games = game_list.lock().await;
|
||||
|
||||
if let Some(existing) = games.iter().find(|g| {
|
||||
g.title == game.title || (g.remote_id == game.remote_id && g.source == game.source)
|
||||
}) {
|
||||
return Ok(Some(existing.clone()));
|
||||
}
|
||||
|
||||
games.push(game.clone());
|
||||
|
||||
games.sort_unstable_by(|g1, g2| g1.title.cmp(&g2.title));
|
||||
|
||||
let users = user_list.lock().await;
|
||||
save_state(&games, &users);
|
||||
|
||||
Some(game)
|
||||
Ok(Some(game))
|
||||
}
|
||||
|
||||
#[post("/opinion", data = "<req>")]
|
||||
async fn add_opinion(
|
||||
token: auth::Token,
|
||||
user_list: &rocket::State<Mutex<Vec<User>>>,
|
||||
#[patch("/game", data = "<game>", rank = 1)]
|
||||
async fn update_game(
|
||||
_token: auth::AdminToken,
|
||||
game_list: &rocket::State<Mutex<Vec<Game>>>,
|
||||
req: proto_utils::Proto<items::AddOpinionRequest>,
|
||||
) -> Option<items::Person> {
|
||||
let mut users = user_list.lock().await;
|
||||
let games = game_list.lock().await;
|
||||
let mut result = None;
|
||||
user_list: &rocket::State<Mutex<Vec<User>>>,
|
||||
game: proto_utils::Proto<items::Game>,
|
||||
) -> Result<Option<items::Game>, String> {
|
||||
let mut game = game.into_inner();
|
||||
|
||||
// Validate game exists
|
||||
if !games.iter().any(|g| g.title == req.game_title) {
|
||||
return None;
|
||||
game.title = game.title.trim().to_string();
|
||||
|
||||
validation::validate_game_title(&game.title)?;
|
||||
validation::validate_remote_id(game.remote_id)?;
|
||||
validation::validate_player_count(game.min_players, game.max_players)?;
|
||||
validation::validate_price(game.price)?;
|
||||
|
||||
if game.title.len() > validation::MAX_GAME_TITLE_TRIMMED_LENGTH {
|
||||
game.title = game
|
||||
.title
|
||||
.chars()
|
||||
.take(validation::MAX_GAME_TITLE_TRIMMED_LENGTH)
|
||||
.collect();
|
||||
}
|
||||
|
||||
if let Some(user) = users.iter_mut().find(|u| u.person.name == token.username) {
|
||||
let mut users = user_list.lock().await;
|
||||
let mut games = game_list.lock().await;
|
||||
|
||||
let mut r_existing = None;
|
||||
|
||||
if let Some(existing) = games.iter_mut().find(|g| {
|
||||
(g.remote_id == game.remote_id && g.source == game.source) || (g.title == game.title)
|
||||
}) {
|
||||
if existing.title != game.title {
|
||||
let old_title = existing.title.clone();
|
||||
for person in users.iter_mut() {
|
||||
let opinion = person
|
||||
.person
|
||||
.opinion
|
||||
.iter_mut()
|
||||
.find(|o| o.title == old_title);
|
||||
if let Some(opinion) = opinion {
|
||||
opinion.title = game.title.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
existing.title = game.title.clone();
|
||||
existing.source = game.source;
|
||||
existing.min_players = game.min_players;
|
||||
existing.max_players = game.max_players;
|
||||
existing.price = game.price;
|
||||
existing.remote_id = game.remote_id;
|
||||
|
||||
r_existing = Some(existing.clone());
|
||||
}
|
||||
|
||||
games.sort_unstable_by(|g1, g2| g1.title.cmp(&g2.title));
|
||||
|
||||
save_state(&games, &users);
|
||||
|
||||
Ok(r_existing)
|
||||
}
|
||||
|
||||
#[delete("/game/<title>", rank = 1)]
|
||||
async fn delete_game(
|
||||
_token: auth::AdminToken,
|
||||
game_list: &rocket::State<Mutex<Vec<Game>>>,
|
||||
user_list: &rocket::State<Mutex<Vec<User>>>,
|
||||
title: &str,
|
||||
) -> Result<Option<items::Game>, String> {
|
||||
validation::validate_game_title(title)?;
|
||||
|
||||
let mut users = user_list.lock().await;
|
||||
let mut games = game_list.lock().await;
|
||||
|
||||
if let Some(pos) = games
|
||||
.iter()
|
||||
.position(|g| g.title.to_lowercase() == title.to_lowercase())
|
||||
{
|
||||
let game = games.remove(pos);
|
||||
|
||||
for person in users.iter_mut() {
|
||||
person.person.opinion.retain_mut(|o| o.title != game.title);
|
||||
}
|
||||
|
||||
save_state(&games, &users);
|
||||
|
||||
return Ok(Some(game));
|
||||
}
|
||||
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
#[post("/refresh", rank = 1)]
|
||||
async fn refresh_state(
|
||||
_token: auth::AdminToken,
|
||||
game_list: &rocket::State<Mutex<Vec<Game>>>,
|
||||
user_list: &rocket::State<Mutex<Vec<User>>>,
|
||||
admin_state: &rocket::State<AdminState>,
|
||||
) -> items::RefreshResponse {
|
||||
if let Some((new_games, new_users)) = store::load_state() {
|
||||
let mut users = user_list.lock().await;
|
||||
let mut games = game_list.lock().await;
|
||||
let mut admins = admin_state.admins.lock().await;
|
||||
|
||||
*games = new_games;
|
||||
*users = new_users;
|
||||
*admins = store::load_admins();
|
||||
|
||||
items::RefreshResponse {
|
||||
success: true,
|
||||
message: "State refreshed from file".to_string(),
|
||||
}
|
||||
} else {
|
||||
items::RefreshResponse {
|
||||
success: false,
|
||||
message: "Failed to load state from file".to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[post("/opinion", data = "<req>", rank = 1)]
|
||||
async fn add_opinion(
|
||||
token: auth::Token,
|
||||
game_list: &rocket::State<Mutex<Vec<Game>>>,
|
||||
user_list: &rocket::State<Mutex<Vec<User>>>,
|
||||
req: proto_utils::Proto<items::AddOpinionRequest>,
|
||||
) -> Result<Option<items::Person>, String> {
|
||||
validation::validate_username(&token.username)?;
|
||||
|
||||
let games = game_list.lock().await;
|
||||
let mut users = user_list.lock().await;
|
||||
let mut result = None;
|
||||
|
||||
if !games.iter().any(|g| g.title == req.game_title) {
|
||||
return Err("Game not found".to_string());
|
||||
}
|
||||
|
||||
if let Some(user) = users
|
||||
.iter_mut()
|
||||
.find(|u| u.person.name.to_lowercase() == token.username.to_lowercase())
|
||||
{
|
||||
let req = req.into_inner();
|
||||
validation::validate_game_title(&req.game_title)?;
|
||||
|
||||
let opinion = items::Opinion {
|
||||
title: req.game_title.clone(),
|
||||
would_play: req.would_play,
|
||||
@@ -126,22 +297,28 @@ async fn add_opinion(
|
||||
if result.is_some() {
|
||||
save_state(&games, &users);
|
||||
}
|
||||
result
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
#[patch("/opinion", data = "<req>")]
|
||||
#[patch("/opinion", data = "<req>", rank = 1)]
|
||||
async fn remove_opinion(
|
||||
token: auth::Token,
|
||||
user_list: &rocket::State<Mutex<Vec<User>>>,
|
||||
game_list: &rocket::State<Mutex<Vec<Game>>>,
|
||||
user_list: &rocket::State<Mutex<Vec<User>>>,
|
||||
req: proto_utils::Proto<items::RemoveOpinionRequest>,
|
||||
) -> Option<items::Person> {
|
||||
let mut users = user_list.lock().await;
|
||||
) -> Result<Option<items::Person>, String> {
|
||||
validation::validate_username(&token.username)?;
|
||||
|
||||
let games = game_list.lock().await;
|
||||
let mut users = user_list.lock().await;
|
||||
let mut result = None;
|
||||
|
||||
if let Some(user) = users.iter_mut().find(|u| u.person.name == token.username) {
|
||||
if let Some(user) = users
|
||||
.iter_mut()
|
||||
.find(|u| u.person.name.to_lowercase() == token.username.to_lowercase())
|
||||
{
|
||||
let req = req.into_inner();
|
||||
validation::validate_game_title(&req.game_title)?;
|
||||
|
||||
if let Some(existing) = user
|
||||
.person
|
||||
@@ -157,7 +334,7 @@ async fn remove_opinion(
|
||||
if result.is_some() {
|
||||
save_state(&games, &users);
|
||||
}
|
||||
result
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
mod cached_option;
|
||||
@@ -208,9 +385,13 @@ async fn get_game_thumbnail(
|
||||
.json::<serde_json::Value>()
|
||||
.await
|
||||
.ok()?
|
||||
.get("universeId")?
|
||||
.as_u64()
|
||||
.unwrap()
|
||||
.get("universeId")
|
||||
.and_then(|v| v.as_u64())
|
||||
};
|
||||
|
||||
let universe_id = match universe_id {
|
||||
Some(id) => id,
|
||||
None => return None.into(),
|
||||
};
|
||||
|
||||
let api_url = format!(
|
||||
@@ -306,8 +487,10 @@ async fn main() -> Result<(), std::io::Error> {
|
||||
});
|
||||
|
||||
rocket::build()
|
||||
.attach(SecurityHeaders)
|
||||
.manage(Mutex::new(user_list))
|
||||
.manage(auth::AuthState::new())
|
||||
.manage(auth::AdminState::new())
|
||||
.manage(Mutex::new(game_list))
|
||||
.mount(
|
||||
"/api",
|
||||
@@ -319,7 +502,11 @@ async fn main() -> Result<(), std::io::Error> {
|
||||
add_opinion,
|
||||
remove_opinion,
|
||||
add_game,
|
||||
get_game_thumbnail
|
||||
update_game,
|
||||
delete_game,
|
||||
refresh_state,
|
||||
get_game_thumbnail,
|
||||
get_games_batch
|
||||
],
|
||||
)
|
||||
.mount(
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
use rocket::fairing::{Fairing, Info, Kind};
|
||||
use rocket::http::Header;
|
||||
use rocket::{Request, Response};
|
||||
|
||||
pub struct SecurityHeaders;
|
||||
|
||||
#[rocket::async_trait]
|
||||
impl Fairing for SecurityHeaders {
|
||||
fn info(&self) -> Info {
|
||||
Info {
|
||||
name: "Security Headers",
|
||||
kind: Kind::Response,
|
||||
}
|
||||
}
|
||||
|
||||
async fn on_response<'r>(&self, _request: &'r Request<'_>, response: &mut Response<'r>) {
|
||||
response.set_header(Header::new("X-Content-Type-Options", "nosniff"));
|
||||
response.set_header(Header::new("X-Frame-Options", "DENY"));
|
||||
response.set_header(Header::new("X-XSS-Protection", "1; mode=block"));
|
||||
response.set_header(Header::new(
|
||||
"Referrer-Policy",
|
||||
"strict-origin-when-cross-origin",
|
||||
));
|
||||
response.set_header(Header::new(
|
||||
"Content-Security-Policy",
|
||||
"default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:; connect-src 'self'; frame-ancestors 'none';",
|
||||
));
|
||||
response.set_header(Header::new(
|
||||
"Permissions-Policy",
|
||||
"geolocation=(), microphone=(), camera=()",
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
use crate::items::{Game, Person};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashSet;
|
||||
use std::fs::File;
|
||||
use std::io::BufReader;
|
||||
|
||||
@@ -30,6 +31,7 @@ pub struct PersistentState {
|
||||
}
|
||||
|
||||
pub const STATE_FILE: &str = "state.json";
|
||||
pub const ADMINS_FILE: &str = "admins.json";
|
||||
|
||||
pub fn save_state(games: &[Game], users: &[User]) {
|
||||
let mut games = games.to_vec();
|
||||
@@ -57,3 +59,17 @@ pub fn load_state() -> Option<(Vec<Game>, Vec<User>)> {
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub fn load_admins() -> HashSet<String> {
|
||||
if let Ok(file) = File::open(ADMINS_FILE) {
|
||||
let reader = BufReader::new(file);
|
||||
if let Ok(admins) = serde_json::from_reader::<_, Vec<String>>(reader) {
|
||||
return admins.into_iter().map(|s| s.to_lowercase()).collect();
|
||||
}
|
||||
}
|
||||
HashSet::new()
|
||||
}
|
||||
|
||||
pub fn is_admin(username: &str, admins: &HashSet<String>) -> bool {
|
||||
admins.contains(&username.to_lowercase())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
use std::collections::HashSet;
|
||||
|
||||
pub const MAX_USERNAME_LENGTH: usize = 50;
|
||||
pub const MIN_USERNAME_LENGTH: usize = 2;
|
||||
pub const MAX_GAME_TITLE_LENGTH: usize = 200;
|
||||
const MIN_GAME_TITLE_LENGTH: usize = 1;
|
||||
pub const MAX_GAME_TITLE_TRIMMED_LENGTH: usize = 200;
|
||||
pub const MAX_PRICE: u32 = 1_000_000;
|
||||
pub const MAX_PLAYERS: u32 = 10_000;
|
||||
|
||||
const VALID_USERNAME_CHARS: &str =
|
||||
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-";
|
||||
|
||||
pub fn validate_username(username: &str) -> Result<(), String> {
|
||||
let trimmed = username.trim();
|
||||
|
||||
if trimmed.is_empty() {
|
||||
return Err("Username cannot be empty".to_string());
|
||||
}
|
||||
|
||||
if trimmed.len() < MIN_USERNAME_LENGTH {
|
||||
return Err(format!(
|
||||
"Username must be at least {} characters long",
|
||||
MIN_USERNAME_LENGTH
|
||||
));
|
||||
}
|
||||
|
||||
if trimmed.len() > MAX_USERNAME_LENGTH {
|
||||
return Err(format!(
|
||||
"Username must not exceed {} characters",
|
||||
MAX_USERNAME_LENGTH
|
||||
));
|
||||
}
|
||||
|
||||
for c in trimmed.chars() {
|
||||
if !VALID_USERNAME_CHARS.contains(c) {
|
||||
return Err(format!(
|
||||
"Username contains invalid character '{}'. Only alphanumeric characters, underscores and hyphens are allowed",
|
||||
c
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn validate_game_title(title: &str) -> Result<(), String> {
|
||||
if title.trim().is_empty() {
|
||||
return Err("Game title cannot be empty".to_string());
|
||||
}
|
||||
|
||||
if title.len() > MAX_GAME_TITLE_LENGTH {
|
||||
return Err(format!(
|
||||
"Game title must not exceed {} characters",
|
||||
MAX_GAME_TITLE_LENGTH
|
||||
));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn validate_remote_id(remote_id: u64) -> Result<(), String> {
|
||||
if remote_id == 0 {
|
||||
return Err("Remote ID cannot be zero".to_string());
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn validate_player_count(min_players: u32, max_players: u32) -> Result<(), String> {
|
||||
if min_players == 0 {
|
||||
return Err("Minimum players must be at least 1".to_string());
|
||||
}
|
||||
|
||||
if min_players > max_players {
|
||||
return Err("Minimum players cannot be greater than maximum players".to_string());
|
||||
}
|
||||
|
||||
if max_players > MAX_PLAYERS {
|
||||
return Err(format!("Maximum players cannot exceed {}", MAX_PLAYERS));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn validate_price(price: u32) -> Result<(), String> {
|
||||
if price > MAX_PRICE {
|
||||
return Err(format!("Price cannot exceed ${}", MAX_PRICE));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn validate_game_titles_batch(titles: &HashSet<String>) -> Result<(), String> {
|
||||
if titles.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if titles.len() > 100 {
|
||||
return Err("Cannot request more than 100 games at once".to_string());
|
||||
}
|
||||
|
||||
for title in titles {
|
||||
validate_game_title(title)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -3,7 +3,6 @@
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Game List</title>
|
||||
</head>
|
||||
|
||||
+232
-2
@@ -1,6 +1,6 @@
|
||||
// Code generated by protoc-gen-ts_proto. DO NOT EDIT.
|
||||
// versions:
|
||||
// protoc-gen-ts_proto v2.8.3
|
||||
// protoc-gen-ts_proto v2.10.1
|
||||
// protoc v6.33.1
|
||||
// source: items.proto
|
||||
|
||||
@@ -90,6 +90,11 @@ export interface LogoutResponse {
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface RefreshResponse {
|
||||
success: boolean;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface AuthStatusRequest {
|
||||
token: string;
|
||||
}
|
||||
@@ -98,6 +103,7 @@ export interface AuthStatusResponse {
|
||||
authenticated: boolean;
|
||||
username: string;
|
||||
message: string;
|
||||
isAdmin: boolean;
|
||||
}
|
||||
|
||||
export interface GameRequest {
|
||||
@@ -116,6 +122,14 @@ export interface RemoveOpinionRequest {
|
||||
gameTitle: string;
|
||||
}
|
||||
|
||||
export interface GetGameInfoRequest {
|
||||
games: string[];
|
||||
}
|
||||
|
||||
export interface GameInfoResponse {
|
||||
games: Game[];
|
||||
}
|
||||
|
||||
function createBasePerson(): Person {
|
||||
return { name: "", opinion: [] };
|
||||
}
|
||||
@@ -828,6 +842,82 @@ export const LogoutResponse: MessageFns<LogoutResponse> = {
|
||||
},
|
||||
};
|
||||
|
||||
function createBaseRefreshResponse(): RefreshResponse {
|
||||
return { success: false, message: "" };
|
||||
}
|
||||
|
||||
export const RefreshResponse: MessageFns<RefreshResponse> = {
|
||||
encode(message: RefreshResponse, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {
|
||||
if (message.success !== false) {
|
||||
writer.uint32(8).bool(message.success);
|
||||
}
|
||||
if (message.message !== "") {
|
||||
writer.uint32(18).string(message.message);
|
||||
}
|
||||
return writer;
|
||||
},
|
||||
|
||||
decode(input: BinaryReader | Uint8Array, length?: number): RefreshResponse {
|
||||
const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
|
||||
const end = length === undefined ? reader.len : reader.pos + length;
|
||||
const message = createBaseRefreshResponse();
|
||||
while (reader.pos < end) {
|
||||
const tag = reader.uint32();
|
||||
switch (tag >>> 3) {
|
||||
case 1: {
|
||||
if (tag !== 8) {
|
||||
break;
|
||||
}
|
||||
|
||||
message.success = reader.bool();
|
||||
continue;
|
||||
}
|
||||
case 2: {
|
||||
if (tag !== 18) {
|
||||
break;
|
||||
}
|
||||
|
||||
message.message = reader.string();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if ((tag & 7) === 4 || tag === 0) {
|
||||
break;
|
||||
}
|
||||
reader.skip(tag & 7);
|
||||
}
|
||||
return message;
|
||||
},
|
||||
|
||||
fromJSON(object: any): RefreshResponse {
|
||||
return {
|
||||
success: isSet(object.success) ? globalThis.Boolean(object.success) : false,
|
||||
message: isSet(object.message) ? globalThis.String(object.message) : "",
|
||||
};
|
||||
},
|
||||
|
||||
toJSON(message: RefreshResponse): unknown {
|
||||
const obj: any = {};
|
||||
if (message.success !== false) {
|
||||
obj.success = message.success;
|
||||
}
|
||||
if (message.message !== "") {
|
||||
obj.message = message.message;
|
||||
}
|
||||
return obj;
|
||||
},
|
||||
|
||||
create<I extends Exact<DeepPartial<RefreshResponse>, I>>(base?: I): RefreshResponse {
|
||||
return RefreshResponse.fromPartial(base ?? ({} as any));
|
||||
},
|
||||
fromPartial<I extends Exact<DeepPartial<RefreshResponse>, I>>(object: I): RefreshResponse {
|
||||
const message = createBaseRefreshResponse();
|
||||
message.success = object.success ?? false;
|
||||
message.message = object.message ?? "";
|
||||
return message;
|
||||
},
|
||||
};
|
||||
|
||||
function createBaseAuthStatusRequest(): AuthStatusRequest {
|
||||
return { token: "" };
|
||||
}
|
||||
@@ -887,7 +977,7 @@ export const AuthStatusRequest: MessageFns<AuthStatusRequest> = {
|
||||
};
|
||||
|
||||
function createBaseAuthStatusResponse(): AuthStatusResponse {
|
||||
return { authenticated: false, username: "", message: "" };
|
||||
return { authenticated: false, username: "", message: "", isAdmin: false };
|
||||
}
|
||||
|
||||
export const AuthStatusResponse: MessageFns<AuthStatusResponse> = {
|
||||
@@ -901,6 +991,9 @@ export const AuthStatusResponse: MessageFns<AuthStatusResponse> = {
|
||||
if (message.message !== "") {
|
||||
writer.uint32(26).string(message.message);
|
||||
}
|
||||
if (message.isAdmin !== false) {
|
||||
writer.uint32(32).bool(message.isAdmin);
|
||||
}
|
||||
return writer;
|
||||
},
|
||||
|
||||
@@ -935,6 +1028,14 @@ export const AuthStatusResponse: MessageFns<AuthStatusResponse> = {
|
||||
message.message = reader.string();
|
||||
continue;
|
||||
}
|
||||
case 4: {
|
||||
if (tag !== 32) {
|
||||
break;
|
||||
}
|
||||
|
||||
message.isAdmin = reader.bool();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if ((tag & 7) === 4 || tag === 0) {
|
||||
break;
|
||||
@@ -949,6 +1050,7 @@ export const AuthStatusResponse: MessageFns<AuthStatusResponse> = {
|
||||
authenticated: isSet(object.authenticated) ? globalThis.Boolean(object.authenticated) : false,
|
||||
username: isSet(object.username) ? globalThis.String(object.username) : "",
|
||||
message: isSet(object.message) ? globalThis.String(object.message) : "",
|
||||
isAdmin: isSet(object.isAdmin) ? globalThis.Boolean(object.isAdmin) : false,
|
||||
};
|
||||
},
|
||||
|
||||
@@ -963,6 +1065,9 @@ export const AuthStatusResponse: MessageFns<AuthStatusResponse> = {
|
||||
if (message.message !== "") {
|
||||
obj.message = message.message;
|
||||
}
|
||||
if (message.isAdmin !== false) {
|
||||
obj.isAdmin = message.isAdmin;
|
||||
}
|
||||
return obj;
|
||||
},
|
||||
|
||||
@@ -974,6 +1079,7 @@ export const AuthStatusResponse: MessageFns<AuthStatusResponse> = {
|
||||
message.authenticated = object.authenticated ?? false;
|
||||
message.username = object.username ?? "";
|
||||
message.message = object.message ?? "";
|
||||
message.isAdmin = object.isAdmin ?? false;
|
||||
return message;
|
||||
},
|
||||
};
|
||||
@@ -1213,6 +1319,122 @@ export const RemoveOpinionRequest: MessageFns<RemoveOpinionRequest> = {
|
||||
},
|
||||
};
|
||||
|
||||
function createBaseGetGameInfoRequest(): GetGameInfoRequest {
|
||||
return { games: [] };
|
||||
}
|
||||
|
||||
export const GetGameInfoRequest: MessageFns<GetGameInfoRequest> = {
|
||||
encode(message: GetGameInfoRequest, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {
|
||||
for (const v of message.games) {
|
||||
writer.uint32(10).string(v!);
|
||||
}
|
||||
return writer;
|
||||
},
|
||||
|
||||
decode(input: BinaryReader | Uint8Array, length?: number): GetGameInfoRequest {
|
||||
const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
|
||||
const end = length === undefined ? reader.len : reader.pos + length;
|
||||
const message = createBaseGetGameInfoRequest();
|
||||
while (reader.pos < end) {
|
||||
const tag = reader.uint32();
|
||||
switch (tag >>> 3) {
|
||||
case 1: {
|
||||
if (tag !== 10) {
|
||||
break;
|
||||
}
|
||||
|
||||
message.games.push(reader.string());
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if ((tag & 7) === 4 || tag === 0) {
|
||||
break;
|
||||
}
|
||||
reader.skip(tag & 7);
|
||||
}
|
||||
return message;
|
||||
},
|
||||
|
||||
fromJSON(object: any): GetGameInfoRequest {
|
||||
return { games: globalThis.Array.isArray(object?.games) ? object.games.map((e: any) => globalThis.String(e)) : [] };
|
||||
},
|
||||
|
||||
toJSON(message: GetGameInfoRequest): unknown {
|
||||
const obj: any = {};
|
||||
if (message.games?.length) {
|
||||
obj.games = message.games;
|
||||
}
|
||||
return obj;
|
||||
},
|
||||
|
||||
create<I extends Exact<DeepPartial<GetGameInfoRequest>, I>>(base?: I): GetGameInfoRequest {
|
||||
return GetGameInfoRequest.fromPartial(base ?? ({} as any));
|
||||
},
|
||||
fromPartial<I extends Exact<DeepPartial<GetGameInfoRequest>, I>>(object: I): GetGameInfoRequest {
|
||||
const message = createBaseGetGameInfoRequest();
|
||||
message.games = object.games?.map((e) => e) || [];
|
||||
return message;
|
||||
},
|
||||
};
|
||||
|
||||
function createBaseGameInfoResponse(): GameInfoResponse {
|
||||
return { games: [] };
|
||||
}
|
||||
|
||||
export const GameInfoResponse: MessageFns<GameInfoResponse> = {
|
||||
encode(message: GameInfoResponse, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {
|
||||
for (const v of message.games) {
|
||||
Game.encode(v!, writer.uint32(10).fork()).join();
|
||||
}
|
||||
return writer;
|
||||
},
|
||||
|
||||
decode(input: BinaryReader | Uint8Array, length?: number): GameInfoResponse {
|
||||
const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
|
||||
const end = length === undefined ? reader.len : reader.pos + length;
|
||||
const message = createBaseGameInfoResponse();
|
||||
while (reader.pos < end) {
|
||||
const tag = reader.uint32();
|
||||
switch (tag >>> 3) {
|
||||
case 1: {
|
||||
if (tag !== 10) {
|
||||
break;
|
||||
}
|
||||
|
||||
message.games.push(Game.decode(reader, reader.uint32()));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if ((tag & 7) === 4 || tag === 0) {
|
||||
break;
|
||||
}
|
||||
reader.skip(tag & 7);
|
||||
}
|
||||
return message;
|
||||
},
|
||||
|
||||
fromJSON(object: any): GameInfoResponse {
|
||||
return { games: globalThis.Array.isArray(object?.games) ? object.games.map((e: any) => Game.fromJSON(e)) : [] };
|
||||
},
|
||||
|
||||
toJSON(message: GameInfoResponse): unknown {
|
||||
const obj: any = {};
|
||||
if (message.games?.length) {
|
||||
obj.games = message.games.map((e) => Game.toJSON(e));
|
||||
}
|
||||
return obj;
|
||||
},
|
||||
|
||||
create<I extends Exact<DeepPartial<GameInfoResponse>, I>>(base?: I): GameInfoResponse {
|
||||
return GameInfoResponse.fromPartial(base ?? ({} as any));
|
||||
},
|
||||
fromPartial<I extends Exact<DeepPartial<GameInfoResponse>, I>>(object: I): GameInfoResponse {
|
||||
const message = createBaseGameInfoResponse();
|
||||
message.games = object.games?.map((e) => Game.fromPartial(e)) || [];
|
||||
return message;
|
||||
},
|
||||
};
|
||||
|
||||
/** Authentication service */
|
||||
export interface AuthService {
|
||||
Login(request: LoginRequest): Promise<LoginResponse>;
|
||||
@@ -1255,6 +1477,7 @@ export interface MainService {
|
||||
GetGames(request: GetGamesRequest): Promise<GameList>;
|
||||
AddGame(request: Game): Promise<Game>;
|
||||
AddOpinion(request: AddOpinionRequest): Promise<Person>;
|
||||
GetGameInfo(request: GetGameInfoRequest): Promise<GameInfoResponse>;
|
||||
}
|
||||
|
||||
export const MainServiceServiceName = "items.MainService";
|
||||
@@ -1268,6 +1491,7 @@ export class MainServiceClientImpl implements MainService {
|
||||
this.GetGames = this.GetGames.bind(this);
|
||||
this.AddGame = this.AddGame.bind(this);
|
||||
this.AddOpinion = this.AddOpinion.bind(this);
|
||||
this.GetGameInfo = this.GetGameInfo.bind(this);
|
||||
}
|
||||
GetGame(request: GameRequest): Promise<Game> {
|
||||
const data = GameRequest.encode(request).finish();
|
||||
@@ -1292,6 +1516,12 @@ export class MainServiceClientImpl implements MainService {
|
||||
const promise = this.rpc.request(this.service, "AddOpinion", data);
|
||||
return promise.then((data) => Person.decode(new BinaryReader(data)));
|
||||
}
|
||||
|
||||
GetGameInfo(request: GetGameInfoRequest): Promise<GameInfoResponse> {
|
||||
const data = GetGameInfoRequest.encode(request).finish();
|
||||
const promise = this.rpc.request(this.service, "GetGameInfo", data);
|
||||
return promise.then((data) => GameInfoResponse.decode(new BinaryReader(data)));
|
||||
}
|
||||
}
|
||||
|
||||
interface Rpc {
|
||||
|
||||
+11
-11
@@ -11,24 +11,24 @@
|
||||
"gen:proto": "protoc --plugin=./node_modules/.bin/protoc-gen-ts_proto --ts_proto_out=. -I ../protobuf items.proto"
|
||||
},
|
||||
"dependencies": {
|
||||
"@bufbuild/protobuf": "^2.10.1",
|
||||
"react": "^19.2.1",
|
||||
"react-dom": "^19.2.1",
|
||||
"react-router-dom": "^7.10.1"
|
||||
"@bufbuild/protobuf": "^2.10.2",
|
||||
"react": "^19.2.3",
|
||||
"react-dom": "^19.2.3",
|
||||
"react-router-dom": "^7.12.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.39.1",
|
||||
"@types/node": "^24.10.1",
|
||||
"@types/react": "^19.2.7",
|
||||
"@eslint/js": "^9.39.2",
|
||||
"@types/node": "^24.10.7",
|
||||
"@types/react": "^19.2.8",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@vitejs/plugin-react": "^5.1.2",
|
||||
"eslint": "^9.39.1",
|
||||
"eslint": "^9.39.2",
|
||||
"eslint-plugin-react-hooks": "^7.0.1",
|
||||
"eslint-plugin-react-refresh": "^0.4.24",
|
||||
"eslint-plugin-react-refresh": "^0.4.26",
|
||||
"globals": "^16.5.0",
|
||||
"ts-proto": "^2.8.3",
|
||||
"ts-proto": "^2.10.1",
|
||||
"typescript": "~5.9.3",
|
||||
"typescript-eslint": "^8.48.1",
|
||||
"typescript-eslint": "^8.53.0",
|
||||
"vite": "npm:rolldown-vite@7.2.5"
|
||||
},
|
||||
"pnpm": {
|
||||
|
||||
Generated
+285
-291
File diff suppressed because it is too large
Load Diff
+87
-26
@@ -34,47 +34,108 @@
|
||||
transition: color 0.2s;
|
||||
}
|
||||
|
||||
.nav-link:hover, .nav-link.active {
|
||||
color: var(--accent-color);
|
||||
.nav-link.active {
|
||||
color: var(--text-color);
|
||||
border-bottom: 2px solid var(--accent-color);
|
||||
}
|
||||
|
||||
.form-group {
|
||||
/* Toast Styles */
|
||||
.toast-container {
|
||||
position: fixed;
|
||||
top: 2rem;
|
||||
right: 2rem;
|
||||
z-index: 1000;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
margin-bottom: 1rem;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.form-group label {
|
||||
font-size: 0.9rem;
|
||||
.toast {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
padding: 1rem 1.5rem;
|
||||
border-radius: 12px;
|
||||
background-color: var(--secondary-bg);
|
||||
border: 1px solid var(--border-color);
|
||||
box-shadow: 0 10px 25px rgba(0, 0, 0, 0.3);
|
||||
min-width: 300px;
|
||||
animation: slideInRight 0.3s ease forwards;
|
||||
}
|
||||
|
||||
.toast-success { border-left: 4px solid #4caf50; }
|
||||
.toast-error { border-left: 4px solid #f44336; }
|
||||
.toast-info { border-left: 4px solid var(--accent-color); }
|
||||
|
||||
.toast-icon { font-size: 1.2rem; }
|
||||
.toast-message { flex: 1; font-weight: 500; }
|
||||
.toast-close {
|
||||
background: none;
|
||||
border: none;
|
||||
color: var(--text-muted);
|
||||
cursor: pointer;
|
||||
font-size: 1.5rem;
|
||||
padding: 0;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.btn-secondary {
|
||||
background-color: var(--secondary-alt-bg);
|
||||
@keyframes slideInRight {
|
||||
from { transform: translateX(100%); opacity: 0; }
|
||||
to { transform: translateX(0); opacity: 1; }
|
||||
}
|
||||
|
||||
/* Loading Bar */
|
||||
.loading-bar {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
height: 3px;
|
||||
background: linear-gradient(90deg, var(--accent-color), #4da3ff);
|
||||
z-index: 2000;
|
||||
transition: width 0.3s ease;
|
||||
}
|
||||
|
||||
/* Theme Switcher */
|
||||
.theme-switcher {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
background: var(--secondary-alt-bg);
|
||||
padding: 0.25rem;
|
||||
border-radius: 20px;
|
||||
border: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
.btn-secondary:hover {
|
||||
background-color: var(--border-color);
|
||||
}
|
||||
|
||||
.list-item {
|
||||
background-color: var(--secondary-alt-bg);
|
||||
padding: 1rem;
|
||||
border-radius: 8px;
|
||||
margin-bottom: 1rem;
|
||||
border: 1px solid var(--border-color);
|
||||
.theme-btn:not(.game-btn) {
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
border-radius: 50%;
|
||||
border: 2px solid transparent;
|
||||
cursor: pointer;
|
||||
transition: transform 0.2s;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.list-item:hover {
|
||||
transform: translateY(-2px);
|
||||
border-color: var(--accent-color);
|
||||
.theme-btn:hover { transform: scale(1.1); }
|
||||
.theme-btn.active { border-color: var(--text-color); }
|
||||
|
||||
.theme-default { background: #23283d; }
|
||||
.theme-blackhole { background: #000000; }
|
||||
.theme-star { background: #0a0a2a; }
|
||||
.theme-ball { background: #1a1a1a; }
|
||||
.theme-reflect { background: #333333; }
|
||||
.theme-clouds { background: #23283d; }
|
||||
|
||||
.game-entry {
|
||||
gap: 0.5rem;
|
||||
background-color: var(--secondary-alt-bg);
|
||||
margin-bottom: 10px;
|
||||
border-radius: 5px;
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
.grid-container {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
|
||||
gap: 1.5rem;
|
||||
.game-entry:hover {
|
||||
background-color: var(--primary-bg);
|
||||
}
|
||||
|
||||
+131
-28
@@ -1,4 +1,4 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { useState, useEffect, useCallback } from "react";
|
||||
import { Person, PersonList as PersonListProto } from "../items";
|
||||
import { Login } from "./Login";
|
||||
import { PersonList } from "./PersonList";
|
||||
@@ -6,31 +6,85 @@ import { PersonDetails } from "./PersonDetails";
|
||||
import { GameList } from "./GameList";
|
||||
import { GameFilter } from "./GameFilter";
|
||||
import { GameDetails } from "./GameDetails";
|
||||
import { EditGame } from "./EditGame";
|
||||
import { ShaderBackground } from "./ShaderBackground";
|
||||
import { BrowserRouter, Routes, Route, Link } from "react-router-dom";
|
||||
import { BrowserRouter, Routes, Route, NavLink } from "react-router-dom";
|
||||
import "./App.css";
|
||||
import { apiFetch } from "./api";
|
||||
import { Toast } from "./Toast";
|
||||
import type { ToastType } from "./Toast";
|
||||
|
||||
interface ToastMessage {
|
||||
id: number;
|
||||
message: string;
|
||||
type: ToastType;
|
||||
}
|
||||
|
||||
function App() {
|
||||
const [people, setPeople] = useState<Person[]>([]);
|
||||
const [token, setToken] = useState<string>(
|
||||
localStorage.getItem("token") || ""
|
||||
);
|
||||
const [theme, setTheme] = useState<string>("default");
|
||||
const [isShaderTheme, setIsShaderTheme] = useState(false);
|
||||
const [theme, _setTheme] = useState<string>(
|
||||
localStorage.getItem("theme") || "default"
|
||||
);
|
||||
const setTheme = (theme: string) => {
|
||||
_setTheme(theme);
|
||||
localStorage.setItem("theme", theme);
|
||||
bc.postMessage(theme);
|
||||
};
|
||||
const [toasts, setToasts] = useState<ToastMessage[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
|
||||
const bc = new BroadcastChannel("theme-channel");
|
||||
bc.onmessage = (ev) => {
|
||||
_setTheme(ev.data as string);
|
||||
};
|
||||
|
||||
const addToast = useCallback((message: string, type: ToastType = "info") => {
|
||||
const id = Date.now();
|
||||
setToasts((prev) => [...prev, { id, message, type }]);
|
||||
}, []);
|
||||
|
||||
const removeToast = (id: number) => {
|
||||
setToasts((prev) => prev.filter((t) => t.id !== id));
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (theme !== "default") {
|
||||
if (theme !== "default" && theme !== "sakura") {
|
||||
document.body.classList.remove("sakura-theme");
|
||||
document.body.classList.add("shader-theme");
|
||||
setIsShaderTheme(true);
|
||||
if (theme === "clouds" || theme === "blackhole" || theme === "ball") {
|
||||
document.body.classList.add("black-theme");
|
||||
return;
|
||||
}
|
||||
document.body.classList.remove("black-theme");
|
||||
} else {
|
||||
document.body.classList.remove("shader-theme");
|
||||
setIsShaderTheme(false);
|
||||
document.body.classList.remove("black-theme");
|
||||
|
||||
if (theme === "sakura") {
|
||||
document.body.classList.add("sakura-theme");
|
||||
return;
|
||||
}
|
||||
document.body.classList.remove("sakura-theme");
|
||||
}
|
||||
}, [theme]);
|
||||
|
||||
useEffect(() => {
|
||||
const handleUnauthorized = () => {
|
||||
setToken("");
|
||||
setPeople([]);
|
||||
addToast("Session expired. Please log in again.", "info");
|
||||
};
|
||||
|
||||
window.addEventListener("unauthorized", handleUnauthorized);
|
||||
return () => window.removeEventListener("unauthorized", handleUnauthorized);
|
||||
}, [addToast]);
|
||||
|
||||
const fetchPeople = () => {
|
||||
if (!token) return;
|
||||
setIsLoading(true);
|
||||
|
||||
apiFetch("/api")
|
||||
.then((res) => res.arrayBuffer())
|
||||
@@ -38,60 +92,109 @@ function App() {
|
||||
const list = PersonListProto.decode(new Uint8Array(buffer));
|
||||
setPeople(list.person);
|
||||
})
|
||||
.catch((err) => console.error("Failed to fetch people:", err));
|
||||
.catch((err) => {
|
||||
console.error("Failed to fetch people:", err);
|
||||
addToast("Failed to fetch people list", "error");
|
||||
})
|
||||
.finally(() => setIsLoading(false));
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
fetchPeople();
|
||||
if (token) {
|
||||
fetchPeople();
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [token]);
|
||||
|
||||
const handleLogin = (newToken: string) => {
|
||||
setToken(newToken);
|
||||
localStorage.setItem("token", newToken);
|
||||
addToast("Welcome back!", "success");
|
||||
};
|
||||
|
||||
const handleLogout = () => {
|
||||
setToken("");
|
||||
setPeople([]);
|
||||
localStorage.removeItem("token");
|
||||
localStorage.removeItem("isAdmin");
|
||||
addToast("Logged out successfully", "info");
|
||||
};
|
||||
|
||||
if (!token) {
|
||||
return <Login onLogin={handleLogin} />;
|
||||
}
|
||||
|
||||
const themes = [
|
||||
{ id: "default", label: "Default", icon: "🏠" },
|
||||
{ id: "blackhole", label: "Blackhole", icon: "🕳️" },
|
||||
// { id: "star", label: "Star", icon: "⭐" },
|
||||
// { id: "ball", label: "Ball", icon: "⚽" },
|
||||
{ id: "reflect", label: "Reflect", icon: "🪞" },
|
||||
// { id: "clouds", label: "Clouds", icon: "☁️" },
|
||||
{ id: "sakura", label: "Sakura", icon: "🌸" },
|
||||
];
|
||||
|
||||
return (
|
||||
<BrowserRouter>
|
||||
{isLoading && <div className="loading-bar" style={{ width: "50%" }} />}
|
||||
<div className="toast-container">
|
||||
{toasts.map((toast) => (
|
||||
<Toast
|
||||
key={toast.id}
|
||||
message={toast.message}
|
||||
type={toast.type}
|
||||
onClose={() => removeToast(toast.id)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<div className="card">
|
||||
<div className="navbar">
|
||||
<div className="nav-links">
|
||||
<Link to="/" className="nav-link">
|
||||
People List
|
||||
</Link>
|
||||
<Link to="/games" className="nav-link">
|
||||
<NavLink to="/" className="nav-link">
|
||||
People
|
||||
</NavLink>
|
||||
<NavLink to="/games" className="nav-link">
|
||||
Games
|
||||
</Link>
|
||||
<Link to="/filter" className="nav-link">
|
||||
</NavLink>
|
||||
<NavLink to="/filter" className="nav-link">
|
||||
Filter
|
||||
</Link>
|
||||
</NavLink>
|
||||
</div>
|
||||
|
||||
<div style={{ display: "flex", alignItems: "center", gap: "1.5rem" }}>
|
||||
<div className="theme-switcher">
|
||||
{themes.map((t) => (
|
||||
<button
|
||||
key={t.id}
|
||||
className={`theme-btn theme-${t.id} ${
|
||||
theme === t.id ? "active" : ""
|
||||
}`}
|
||||
onClick={() => setTheme(t.id)}
|
||||
title={t.label}
|
||||
>
|
||||
{t.icon}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<button onClick={handleLogout} className="btn-secondary">
|
||||
Logout
|
||||
</button>
|
||||
</div>
|
||||
<button onClick={handleLogout} className="btn-secondary">
|
||||
Logout
|
||||
</button>
|
||||
<select value={theme} onChange={(e) => setTheme(e.target.value)}>
|
||||
<option value="default">Default Theme</option>
|
||||
<option value="blackhole">Blackhole Theme</option>
|
||||
<option value="star">Star Theme</option>
|
||||
</select>
|
||||
</div>
|
||||
{isShaderTheme && <ShaderBackground theme= {theme} />}
|
||||
<ShaderBackground theme={theme} />
|
||||
<Routes>
|
||||
<Route path="/" element={<PersonList people={people} />} />
|
||||
<Route path="/games" element={<GameList />} />
|
||||
<Route path="/" element={<PersonList people={people} loading={isLoading} onShowToast={addToast} />} />
|
||||
<Route path="/games" element={<GameList onShowToast={addToast} />} />
|
||||
<Route path="/filter" element={<GameFilter />} />
|
||||
<Route path="/person/:name" element={<PersonDetails />} />
|
||||
<Route path="/game/:title" element={<GameDetails />} />
|
||||
<Route
|
||||
path="/game/:title"
|
||||
element={<GameDetails onShowToast={addToast} />}
|
||||
/>
|
||||
<Route
|
||||
path="/game/:title/edit"
|
||||
element={<EditGame onShowToast={addToast} />}
|
||||
/>
|
||||
</Routes>
|
||||
</div>
|
||||
</BrowserRouter>
|
||||
|
||||
@@ -0,0 +1,403 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { useNavigate, useParams } from "react-router-dom";
|
||||
import { Game, Source } from "../items";
|
||||
import { apiFetch } from "./api";
|
||||
import type { ToastType } from "./Toast";
|
||||
|
||||
interface Props {
|
||||
onShowToast?: (message: string, type?: ToastType) => void;
|
||||
}
|
||||
|
||||
export function EditGame({ onShowToast }: Props) {
|
||||
const { title } = useParams<{ title: string }>();
|
||||
const navigate = useNavigate();
|
||||
const [game, setGame] = useState<Game | null>(null);
|
||||
const [newTitle, setNewTitle] = useState("");
|
||||
const [source, setSource] = useState<Source>(Source.STEAM);
|
||||
const [minPlayers, setMinPlayers] = useState(1);
|
||||
const [maxPlayers, setMaxPlayers] = useState(1);
|
||||
const [price, setPrice] = useState(0);
|
||||
const [remoteId, setRemoteId] = useState(0);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [remoteIdError, setRemoteIdError] = useState("");
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
if (!title) return;
|
||||
|
||||
apiFetch(`/api/game/${encodeURIComponent(title)}`)
|
||||
.then(async (res) => {
|
||||
if (!res.ok) throw new Error("Game not found");
|
||||
return Game.decode(new Uint8Array(await res.arrayBuffer()));
|
||||
})
|
||||
.then((data) => {
|
||||
setGame(data);
|
||||
setNewTitle(data.title);
|
||||
setSource(data.source);
|
||||
setMinPlayers(data.minPlayers);
|
||||
setMaxPlayers(data.maxPlayers);
|
||||
setPrice(data.price);
|
||||
setRemoteId(data.remoteId);
|
||||
setLoading(false);
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error(err);
|
||||
onShowToast?.("Failed to load game", "error");
|
||||
setLoading(false);
|
||||
});
|
||||
}, [title, onShowToast]);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
if (remoteId === 0) {
|
||||
setRemoteIdError("Remote ID must be greater than 0");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!newTitle.trim()) {
|
||||
onShowToast?.("Game title is required", "error");
|
||||
return;
|
||||
}
|
||||
|
||||
setRemoteIdError("");
|
||||
setIsSubmitting(true);
|
||||
const updatedGame = {
|
||||
title: newTitle.trim(),
|
||||
source,
|
||||
minPlayers,
|
||||
maxPlayers,
|
||||
price,
|
||||
remoteId,
|
||||
};
|
||||
|
||||
try {
|
||||
const encoded = Game.encode(updatedGame).finish();
|
||||
const res = await apiFetch("/api/game", {
|
||||
method: "PATCH",
|
||||
headers: {
|
||||
"Content-Type": "application/octet-stream",
|
||||
},
|
||||
body: encoded,
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
onShowToast?.("Game updated successfully!", "success");
|
||||
navigate(`/game/${encodeURIComponent(newTitle.trim())}`);
|
||||
} else {
|
||||
onShowToast?.("Failed to update game. Please try again.", "error");
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
onShowToast?.("An error occurred while updating the game.", "error");
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) return <div>Loading...</div>;
|
||||
if (!game) return <div>Game not found</div>;
|
||||
|
||||
const formCardStyles: React.CSSProperties = {
|
||||
background:
|
||||
"linear-gradient(135deg, var(--secondary-bg) 0%, var(--secondary-alt-bg) 100%)",
|
||||
borderRadius: "20px",
|
||||
padding: "0",
|
||||
maxWidth: "520px",
|
||||
margin: "0 auto",
|
||||
boxShadow: "0 20px 40px rgba(0, 0, 0, 0.3), 0 0 0 1px var(--border-color)",
|
||||
overflow: "hidden",
|
||||
};
|
||||
|
||||
const formHeaderStyles: React.CSSProperties = {
|
||||
background:
|
||||
"linear-gradient(135deg, var(--accent-color) 0%, var(--secondary-accent) 100%)",
|
||||
padding: "1.5rem 2rem",
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: "1rem",
|
||||
};
|
||||
|
||||
const formBodyStyles: React.CSSProperties = {
|
||||
padding: "2rem",
|
||||
};
|
||||
|
||||
const sectionStyles: React.CSSProperties = {
|
||||
marginBottom: "1.5rem",
|
||||
};
|
||||
|
||||
const sectionTitleStyles: React.CSSProperties = {
|
||||
fontSize: "0.75rem",
|
||||
textTransform: "uppercase",
|
||||
letterSpacing: "0.1em",
|
||||
color: "var(--text-muted)",
|
||||
marginBottom: "1rem",
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: "0.5rem",
|
||||
};
|
||||
|
||||
const inputGroupStyles: React.CSSProperties = {
|
||||
position: "relative",
|
||||
marginBottom: "1rem",
|
||||
};
|
||||
|
||||
const labelStyles: React.CSSProperties = {
|
||||
fontSize: "0.85rem",
|
||||
color: "var(--text-muted)",
|
||||
marginBottom: "0.5rem",
|
||||
display: "block",
|
||||
fontWeight: 500,
|
||||
};
|
||||
|
||||
const inputStyles: React.CSSProperties = {
|
||||
width: "100%",
|
||||
padding: "0.875rem 1rem",
|
||||
backgroundColor: "var(--tertiary-bg)",
|
||||
border: "2px solid var(--border-color)",
|
||||
borderRadius: "12px",
|
||||
color: "var(--text-color)",
|
||||
fontSize: "1rem",
|
||||
transition: "all 0.2s ease",
|
||||
boxSizing: "border-box",
|
||||
};
|
||||
|
||||
const gridStyles: React.CSSProperties = {
|
||||
display: "grid",
|
||||
gridTemplateColumns: "1fr 1fr",
|
||||
gap: "1rem",
|
||||
};
|
||||
|
||||
const dividerStyles: React.CSSProperties = {
|
||||
height: "1px",
|
||||
background:
|
||||
"linear-gradient(90deg, transparent, var(--border-color), transparent)",
|
||||
margin: "1.5rem 0",
|
||||
};
|
||||
|
||||
const buttonStyles: React.CSSProperties = {
|
||||
padding: "1rem",
|
||||
background:
|
||||
"linear-gradient(135deg, var(--accent-color) 0%, var(--secondary-accent) 100%)",
|
||||
border: "none",
|
||||
borderRadius: "12px",
|
||||
color: "white",
|
||||
fontSize: "1rem",
|
||||
fontWeight: 600,
|
||||
cursor: isSubmitting ? "not-allowed" : "pointer",
|
||||
transition: "all 0.3s ease",
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
gap: "0.5rem",
|
||||
opacity: isSubmitting ? 0.7 : 1,
|
||||
transform: isSubmitting ? "none" : undefined,
|
||||
};
|
||||
|
||||
const cancelStyles: React.CSSProperties = {
|
||||
...buttonStyles,
|
||||
background: "var(--tertiary-bg)",
|
||||
color: "var(--text-color)",
|
||||
border: "2px solid var(--border-color)",
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div style={formCardStyles}>
|
||||
<div style={formHeaderStyles}>
|
||||
<div
|
||||
style={{
|
||||
width: "48px",
|
||||
height: "48px",
|
||||
borderRadius: "14px",
|
||||
backgroundColor: "rgba(255, 255, 255, 0.2)",
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
fontSize: "1.5rem",
|
||||
}}
|
||||
>
|
||||
✏️
|
||||
</div>
|
||||
<div>
|
||||
<h2
|
||||
style={{
|
||||
margin: 0,
|
||||
fontSize: "1.5rem",
|
||||
fontWeight: 700,
|
||||
color: "white",
|
||||
}}
|
||||
>
|
||||
Edit Game
|
||||
</h2>
|
||||
<p
|
||||
style={{
|
||||
margin: 0,
|
||||
fontSize: "0.9rem",
|
||||
color: "rgba(255, 255, 255, 0.8)",
|
||||
}}
|
||||
>
|
||||
Update game information
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style={formBodyStyles}>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div style={sectionStyles}>
|
||||
<div style={sectionTitleStyles}>
|
||||
<span>📝</span>
|
||||
Basic Information
|
||||
</div>
|
||||
|
||||
<div style={inputGroupStyles}>
|
||||
<label style={labelStyles}>Game Title</label>
|
||||
<input
|
||||
type="text"
|
||||
value={newTitle}
|
||||
onChange={(e) => setNewTitle(e.target.value)}
|
||||
required
|
||||
placeholder="Enter game title..."
|
||||
style={inputStyles}
|
||||
className="add-game-input"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div style={inputGroupStyles}>
|
||||
<label style={labelStyles}>Platform Source</label>
|
||||
<select
|
||||
value={source}
|
||||
onChange={(e) => setSource(Number(e.target.value))}
|
||||
style={{
|
||||
...inputStyles,
|
||||
cursor: "pointer",
|
||||
appearance: "none",
|
||||
backgroundImage: `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' fill='%23a0a0a0' viewBox='0 0 16 16'%3E%3Cpath d='M8 11L3 6h10l-5 5z'/%3E%3C/svg%3E")`,
|
||||
backgroundRepeat: "no-repeat",
|
||||
backgroundPosition: "right 1rem center",
|
||||
paddingRight: "2.5rem",
|
||||
}}
|
||||
className="add-game-input"
|
||||
>
|
||||
<option value={Source.STEAM}>🎮 Steam</option>
|
||||
<option value={Source.ROBLOX}>🟢 Roblox</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style={dividerStyles}></div>
|
||||
|
||||
<div style={sectionStyles}>
|
||||
<div style={sectionTitleStyles}>
|
||||
<span>👥</span>
|
||||
Player Count
|
||||
</div>
|
||||
|
||||
<div style={gridStyles}>
|
||||
<div style={inputGroupStyles}>
|
||||
<label style={labelStyles}>Minimum Players</label>
|
||||
<input
|
||||
type="number"
|
||||
value={minPlayers}
|
||||
onChange={(e) => setMinPlayers(Number(e.target.value))}
|
||||
min="1"
|
||||
style={inputStyles}
|
||||
className="add-game-input"
|
||||
/>
|
||||
</div>
|
||||
<div style={inputGroupStyles}>
|
||||
<label style={labelStyles}>Maximum Players</label>
|
||||
<input
|
||||
type="number"
|
||||
value={maxPlayers}
|
||||
onChange={(e) => setMaxPlayers(Number(e.target.value))}
|
||||
min="1"
|
||||
style={inputStyles}
|
||||
className="add-game-input"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style={dividerStyles}></div>
|
||||
|
||||
<div style={sectionStyles}>
|
||||
<div style={sectionTitleStyles}>
|
||||
<span>💰</span>
|
||||
Additional Details
|
||||
</div>
|
||||
|
||||
<div style={gridStyles}>
|
||||
<div style={inputGroupStyles}>
|
||||
<label style={labelStyles}>Price (€)</label>
|
||||
<input
|
||||
type="number"
|
||||
value={price}
|
||||
onChange={(e) => setPrice(Math.ceil(Number(e.target.value.replace(',', '.'))))}
|
||||
min="0"
|
||||
step="1"
|
||||
style={inputStyles}
|
||||
className="add-game-input"
|
||||
/>
|
||||
</div>
|
||||
<div style={inputGroupStyles}>
|
||||
<label style={labelStyles}>Remote ID</label>
|
||||
<input
|
||||
type="number"
|
||||
value={remoteId}
|
||||
onChange={(e) => {
|
||||
setRemoteId(Number(e.target.value));
|
||||
setRemoteIdError("");
|
||||
}}
|
||||
min="0"
|
||||
style={{
|
||||
...inputStyles,
|
||||
borderColor: remoteIdError ? "#f44336" : undefined,
|
||||
}}
|
||||
className="add-game-input"
|
||||
/>
|
||||
{remoteIdError && (
|
||||
<div
|
||||
style={{
|
||||
color: "#f44336",
|
||||
fontSize: "0.75rem",
|
||||
marginTop: "0.25rem",
|
||||
}}
|
||||
>
|
||||
{remoteIdError}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style={gridStyles}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => navigate(`/game/${encodeURIComponent(game.title)}`)}
|
||||
disabled={isSubmitting}
|
||||
style={cancelStyles}
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isSubmitting}
|
||||
style={buttonStyles}
|
||||
>
|
||||
{isSubmitting ? (
|
||||
<>Updating...</>
|
||||
) : (
|
||||
<>
|
||||
<span style={{ fontSize: "1.1rem" }}>💾</span>
|
||||
Save Changes
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { Component, type ErrorInfo, type ReactNode } from "react";
|
||||
import { ErrorState } from "./components/EmptyState";
|
||||
|
||||
interface Props {
|
||||
children: ReactNode;
|
||||
fallback?: ReactNode;
|
||||
}
|
||||
|
||||
interface State {
|
||||
hasError: boolean;
|
||||
error: Error | null;
|
||||
}
|
||||
|
||||
export class ErrorBoundary extends Component<Props, State> {
|
||||
public state: State = {
|
||||
hasError: false,
|
||||
error: null
|
||||
};
|
||||
|
||||
public static getDerivedStateFromError(error: Error): State {
|
||||
return { hasError: true, error };
|
||||
}
|
||||
|
||||
public componentDidCatch(error: Error, errorInfo: ErrorInfo) {
|
||||
console.error("ErrorBoundary caught an error:", error, errorInfo);
|
||||
}
|
||||
|
||||
public handleReset = () => {
|
||||
this.setState({ hasError: false, error: null });
|
||||
};
|
||||
|
||||
public render() {
|
||||
if (this.state.hasError) {
|
||||
if (this.props.fallback) {
|
||||
return this.props.fallback;
|
||||
}
|
||||
|
||||
return (
|
||||
<ErrorState
|
||||
message={this.state.error?.message || "An unexpected error occurred"}
|
||||
onRetry={this.handleReset}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return this.props.children;
|
||||
}
|
||||
}
|
||||
@@ -1,33 +1,74 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { useParams } from "react-router-dom";
|
||||
import { useParams, useNavigate } from "react-router-dom";
|
||||
import { Game, Source } from "../items";
|
||||
import { apiFetch } from "./api";
|
||||
import { apiFetch, get_is_admin } from "./api";
|
||||
import { LoadingState, EmptyState, ErrorState } from "./components/EmptyState";
|
||||
|
||||
export function GameDetails() {
|
||||
interface Props {
|
||||
onShowToast?: (message: string, type?: "success" | "error" | "info") => void;
|
||||
}
|
||||
|
||||
export function GameDetails({ onShowToast }: Props) {
|
||||
const { title } = useParams<{ title: string }>();
|
||||
const navigate = useNavigate();
|
||||
const [game, setGame] = useState<Game | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [loading, setLoading] = useState(!!title);
|
||||
const [error, setError] = useState<string | null>(title ? null : "Game title is missing");
|
||||
|
||||
const isAdmin = get_is_admin();
|
||||
|
||||
useEffect(() => {
|
||||
if (!title) return;
|
||||
|
||||
apiFetch(`/api/game/${encodeURIComponent(title)}`)
|
||||
.then(async (res) => {
|
||||
if (!res.ok) throw new Error("Game not found");
|
||||
return Game.decode(new Uint8Array(await res.arrayBuffer()));
|
||||
})
|
||||
.then((data) => {
|
||||
setGame(data);
|
||||
setLoading(false);
|
||||
})
|
||||
.catch((err) => {
|
||||
(async () => {
|
||||
try {
|
||||
const res = await apiFetch(`/api/game/${encodeURIComponent(title)}`);
|
||||
if (!res.ok) {
|
||||
if (res.status === 404) {
|
||||
throw new Error("Game not found");
|
||||
}
|
||||
throw new Error("Failed to load game");
|
||||
}
|
||||
const buffer = await res.arrayBuffer();
|
||||
setGame(Game.decode(new Uint8Array(buffer)));
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
setError(err instanceof Error ? err.message : "Failed to load game");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
});
|
||||
}
|
||||
})();
|
||||
}, [title]);
|
||||
|
||||
if (loading) return <div>Loading...</div>;
|
||||
if (!game) return <div>Game not found</div>;
|
||||
const handleDelete = async () => {
|
||||
if (
|
||||
!confirm(
|
||||
`Are you sure you want to delete "${game?.title}"? This action cannot be undone.`
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await apiFetch(`/api/game/${encodeURIComponent(title || "")}`, {
|
||||
method: "DELETE",
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
onShowToast?.(`"${game?.title}" deleted successfully`, "success");
|
||||
navigate("/games");
|
||||
} else {
|
||||
onShowToast?.("Failed to delete game", "error");
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
onShowToast?.("An error occurred while deleting the game", "error");
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) return <LoadingState message="Loading game details..." />;
|
||||
if (error) return <ErrorState message={error} onRetry={() => navigate(0)} />;
|
||||
if (!game) return <EmptyState icon="🎮" title="Game not found" description="This game doesn't exist or has been deleted" />;
|
||||
|
||||
const getExternalLink = () => {
|
||||
if (game.source === Source.STEAM) {
|
||||
@@ -40,7 +81,39 @@ export function GameDetails() {
|
||||
|
||||
return (
|
||||
<div className="card" style={{ maxWidth: "600px", margin: "0 auto" }}>
|
||||
<h2>{game.title}</h2>
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
justifyContent: "space-between",
|
||||
alignItems: "center",
|
||||
marginBottom: "1rem",
|
||||
}}
|
||||
>
|
||||
<h2 style={{ margin: 0 }}>{game.title}</h2>
|
||||
{isAdmin && (
|
||||
<div style={{ display: "flex", gap: "0.5rem" }}>
|
||||
<button
|
||||
onClick={() => navigate(`/game/${encodeURIComponent(game.title)}/edit`)}
|
||||
className="btn-secondary"
|
||||
style={{ padding: "0.5rem 1rem", fontSize: "0.9rem" }}
|
||||
>
|
||||
✏️ Edit
|
||||
</button>
|
||||
<button
|
||||
onClick={handleDelete}
|
||||
className="btn-primary"
|
||||
style={{
|
||||
padding: "0.5rem 1rem",
|
||||
fontSize: "0.9rem",
|
||||
background: "#f44336",
|
||||
border: "none",
|
||||
}}
|
||||
>
|
||||
🗑️ Delete
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div style={{ display: "grid", gap: "1rem", marginTop: "1rem" }}>
|
||||
<div>
|
||||
<strong>Source:</strong>{" "}
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
.gamefilter-entry {
|
||||
border-radius: 5px;
|
||||
border: 1px solid var(--border-color);
|
||||
background-color: var(--secondary-alt-bg);
|
||||
margin-bottom: 10px;
|
||||
padding: 10px;
|
||||
width: 30%;
|
||||
text-align: center;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.gamefilter-entry:hover {
|
||||
background-color: var(--primary-bg);
|
||||
}
|
||||
|
||||
.filter-controls {
|
||||
background-color: var(--secondary-alt-bg);
|
||||
border-radius: 8px;
|
||||
padding: 1.5rem;
|
||||
margin-bottom: 2rem;
|
||||
border: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
.filter-controls h3 {
|
||||
margin: 0 0 1rem 0;
|
||||
font-size: 1.1rem;
|
||||
color: var(--text-color);
|
||||
}
|
||||
|
||||
.filter-groups {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 1.5rem;
|
||||
}
|
||||
|
||||
.filter-group {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.filter-group label {
|
||||
font-size: 0.9rem;
|
||||
color: var(--text-color);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.checkbox-wrapper {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.checkbox-wrapper input[type="checkbox"] {
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
cursor: pointer;
|
||||
accent-color: var(--accent-color);
|
||||
}
|
||||
|
||||
.checkbox-wrapper span {
|
||||
font-size: 0.9rem;
|
||||
color: var(--text-color);
|
||||
}
|
||||
|
||||
.price-input {
|
||||
padding: 0.5rem;
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 4px;
|
||||
background-color: var(--primary-bg);
|
||||
color: var(--text-color);
|
||||
width: 120px;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.price-input:focus {
|
||||
outline: none;
|
||||
border-color: var(--accent-color);
|
||||
}
|
||||
|
||||
.tooltip-icon {
|
||||
display: inline-block;
|
||||
margin-left: 0.3rem;
|
||||
cursor: help;
|
||||
font-size: 0.9rem;
|
||||
opacity: 0.6;
|
||||
}
|
||||
|
||||
.tooltip-icon:hover {
|
||||
opacity: 1;
|
||||
}
|
||||
+88
-177
@@ -1,102 +1,44 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import {
|
||||
Person,
|
||||
PersonList as PersonListProto,
|
||||
Game as GameProto,
|
||||
} from "../items";
|
||||
import { Person, PersonList as PersonListProto } from "../items";
|
||||
import { apiFetch } from "./api";
|
||||
import { Link } from "react-router-dom";
|
||||
import { GameImage } from "./GameImage";
|
||||
import "./GameFilter.css";
|
||||
import { useGameFilter } from "./hooks/useGameFilter";
|
||||
import { PersonSelector } from "./components/PersonSelector";
|
||||
import { FilteredGamesList } from "./components/FilteredGamesList";
|
||||
import { LoadingState } from "./components/EmptyState";
|
||||
|
||||
export function GameFilter() {
|
||||
const [people, setPeople] = useState<Person[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [selectedPeople, setSelectedPeople] = useState<Set<string>>(new Set());
|
||||
const [filteredGames, setFilteredGames] = useState<string[]>([]);
|
||||
const [gameToPositive, setGameToPositive] = useState<
|
||||
Map<string, Set<string>>
|
||||
>(new Map());
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
const [metaData, _setMetaData] = useState<{ [key: string]: GameProto }>({});
|
||||
const [freeGamesOnly, setFreeGamesOnly] = useState(false);
|
||||
const [maxPrice, setMaxPrice] = useState<number | null>(null);
|
||||
const [ownershipMode, setOwnershipMode] = useState(false);
|
||||
|
||||
const { filteredGames, gameToPositive, games } = useGameFilter(
|
||||
people,
|
||||
selectedPeople,
|
||||
freeGamesOnly,
|
||||
maxPrice,
|
||||
ownershipMode
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
apiFetch("/api")
|
||||
.then((res) => res.arrayBuffer())
|
||||
.then((buffer) => {
|
||||
(async () => {
|
||||
try {
|
||||
const res = await apiFetch("/api");
|
||||
const buffer = await res.arrayBuffer();
|
||||
const list = PersonListProto.decode(new Uint8Array(buffer));
|
||||
setPeople(list.person);
|
||||
})
|
||||
.catch((err) => console.error("Failed to fetch people:", err));
|
||||
} catch (err) {
|
||||
console.error("Failed to fetch people:", err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
})();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedPeople.size === 0) {
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||
setFilteredGames([]);
|
||||
return;
|
||||
}
|
||||
|
||||
// Get all games where ALL selected people have "Would Play"
|
||||
const selectedPersons = people.filter((p) => selectedPeople.has(p.name));
|
||||
|
||||
if (selectedPersons.length === 0) {
|
||||
setFilteredGames([]);
|
||||
return;
|
||||
}
|
||||
|
||||
// Create a map of game -> set of people who would not play it
|
||||
const gameToNegative = new Map<string, Set<string>>();
|
||||
const gameToPositiveOpinion = new Map<string, Set<string>>();
|
||||
|
||||
selectedPersons.forEach((person) => {
|
||||
person.opinion.forEach((op) => {
|
||||
if (!gameToNegative.has(op.title)) {
|
||||
gameToNegative.set(op.title, new Set());
|
||||
}
|
||||
if (!gameToPositiveOpinion.has(op.title)) {
|
||||
gameToPositiveOpinion.set(op.title, new Set());
|
||||
}
|
||||
if (!op.wouldPlay) {
|
||||
gameToNegative.get(op.title)!.add(person.name);
|
||||
}
|
||||
if (op.wouldPlay) {
|
||||
gameToPositiveOpinion.get(op.title)!.add(person.name);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
setGameToPositive(gameToPositiveOpinion);
|
||||
|
||||
// Filter games where ALL selected people would play
|
||||
const game_titles = Array.from(gameToNegative.entries())
|
||||
.filter(([, players]) => players.size === 0)
|
||||
.map(([game]) => game);
|
||||
|
||||
const games = game_titles.map(async (title) => {
|
||||
if (metaData[title]) {
|
||||
console.log("returned cached metadata");
|
||||
return metaData[title];
|
||||
}
|
||||
return await apiFetch(`/api/game/${encodeURIComponent(title)}`)
|
||||
.then((res) => res.arrayBuffer())
|
||||
.then((buffer) => {
|
||||
const game = GameProto.decode(new Uint8Array(buffer)) as GameProto;
|
||||
metaData[title] = game;
|
||||
return game;
|
||||
})
|
||||
.catch((err) => console.error("Failed to fetch game:", err));
|
||||
});
|
||||
|
||||
Promise.all(games).then((games) => {
|
||||
const filteredGames = games.filter((g) => {
|
||||
const game = g as GameProto;
|
||||
return (
|
||||
game.maxPlayers >= selectedPeople.size &&
|
||||
game.minPlayers <= selectedPeople.size
|
||||
);
|
||||
});
|
||||
setFilteredGames(filteredGames.map((g) => (g as GameProto).title));
|
||||
});
|
||||
}, [selectedPeople, people, metaData]);
|
||||
if (loading) return <LoadingState message="Loading people..." />;
|
||||
|
||||
const togglePerson = (name: string) => {
|
||||
const newSelected = new Set(selectedPeople);
|
||||
@@ -115,100 +57,69 @@ export function GameFilter() {
|
||||
Select multiple people to find games that everyone would play
|
||||
</p>
|
||||
|
||||
<div style={{ marginBottom: "3rem" }}>
|
||||
<h3>Select People</h3>
|
||||
<div className="grid-container">
|
||||
{people.map((person) => (
|
||||
<div
|
||||
key={person.name}
|
||||
className="list-item"
|
||||
style={{
|
||||
borderColor: selectedPeople.has(person.name)
|
||||
? "var(--accent-color)"
|
||||
: "var(--border-color)",
|
||||
cursor: "pointer",
|
||||
<PersonSelector
|
||||
people={people}
|
||||
selectedPeople={selectedPeople}
|
||||
onTogglePerson={togglePerson}
|
||||
/>
|
||||
|
||||
<div className="filter-controls">
|
||||
<h3>Additional Filters</h3>
|
||||
<div className="filter-groups">
|
||||
<div className="filter-group">
|
||||
<label className="checkbox-wrapper">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={freeGamesOnly}
|
||||
onChange={(e) => setFreeGamesOnly(e.target.checked)}
|
||||
/>
|
||||
<span>Free games only</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div className="filter-group">
|
||||
<label htmlFor="max-price">Maximum price (€)</label>
|
||||
<input
|
||||
id="max-price"
|
||||
type="number"
|
||||
className="price-input"
|
||||
min="0"
|
||||
placeholder="No limit"
|
||||
value={maxPrice ?? ""}
|
||||
onChange={(e) => {
|
||||
const value = e.target.value;
|
||||
setMaxPrice(value === "" ? null : parseInt(value, 10));
|
||||
}}
|
||||
onClick={() => togglePerson(person.name)}
|
||||
>
|
||||
<div
|
||||
style={{ display: "flex", alignItems: "center", gap: "0.5rem" }}
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={selectedPeople.has(person.name)}
|
||||
onChange={() => togglePerson(person.name)}
|
||||
style={{ cursor: "pointer" }}
|
||||
/>
|
||||
<strong>{person.name}</strong>
|
||||
</div>
|
||||
<div
|
||||
style={{
|
||||
fontSize: "0.9em",
|
||||
color: "var(--text-muted)",
|
||||
marginTop: "0.5rem",
|
||||
}}
|
||||
>
|
||||
{person.opinion.length} opinion(s)
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="filter-group">
|
||||
<label className="checkbox-wrapper">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={ownershipMode}
|
||||
onChange={(e) => setOwnershipMode(e.target.checked)}
|
||||
/>
|
||||
<span>
|
||||
Ownership mode
|
||||
<span
|
||||
className="tooltip-icon"
|
||||
title="For paid games, only show if ALL selected people have marked it as wouldPlay"
|
||||
>
|
||||
?
|
||||
</span>
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{selectedPeople.size > 0 && (
|
||||
<div>
|
||||
<h3>Games Everyone Would Play ({filteredGames.length})</h3>
|
||||
{filteredGames.length > 0 ? (
|
||||
<ul className="grid-container">
|
||||
{filteredGames.map((game) => (
|
||||
<Link
|
||||
to={`/game/${encodeURIComponent(game)}`}
|
||||
key={game}
|
||||
className="list-item"
|
||||
style={{
|
||||
textDecoration: "none",
|
||||
color: "inherit",
|
||||
display: "flex",
|
||||
justifyContent: "space-between",
|
||||
alignItems: "center",
|
||||
}}
|
||||
>
|
||||
<div>
|
||||
<strong>{game}</strong>
|
||||
<div
|
||||
style={{
|
||||
fontSize: "0.9em",
|
||||
color: "#4caf50",
|
||||
marginTop: "0.5rem",
|
||||
}}
|
||||
>
|
||||
✓ {gameToPositive.get(game)!.size} selected would play
|
||||
</div>
|
||||
{selectedPeople.size - gameToPositive.get(game)!.size >
|
||||
0 && (
|
||||
<div
|
||||
style={{
|
||||
fontSize: "0.9em",
|
||||
color: "#d4d400",
|
||||
marginTop: "0.3rem",
|
||||
}}
|
||||
>
|
||||
? {selectedPeople.size - gameToPositive.get(game)!.size}{" "}
|
||||
{(selectedPeople.size - gameToPositive.get(game)!.size) > 1 ? "are" : "is"} neutral
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<GameImage game={game} />
|
||||
</Link>
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<p style={{ color: "var(--text-muted)", fontStyle: "italic" }}>
|
||||
No games found where all selected people would play
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<FilteredGamesList
|
||||
filteredGames={filteredGames}
|
||||
gameToPositive={gameToPositive}
|
||||
selectedPeopleCount={selectedPeople.size}
|
||||
games={games}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
+290
-110
@@ -1,4 +1,4 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { useState, useEffect, useMemo, useCallback } from "react";
|
||||
import {
|
||||
Game,
|
||||
Source,
|
||||
@@ -11,8 +11,14 @@ import {
|
||||
import { Link, useLocation } from "react-router-dom";
|
||||
import { apiFetch, get_auth_status } from "./api";
|
||||
import { GameImage } from "./GameImage";
|
||||
import type { ToastType } from "./Toast";
|
||||
import { EmptyState } from "./components/EmptyState";
|
||||
|
||||
export function GameList() {
|
||||
interface Props {
|
||||
onShowToast?: (message: string, type?: ToastType) => void;
|
||||
}
|
||||
|
||||
export function GameList({ onShowToast }: Props) {
|
||||
const [games, setGames] = useState<Game[]>([]);
|
||||
const [title, setTitle] = useState("");
|
||||
const [source, setSource] = useState<Source>(Source.STEAM);
|
||||
@@ -20,11 +26,23 @@ export function GameList() {
|
||||
const [maxPlayers, setMaxPlayers] = useState(1);
|
||||
const [price, setPrice] = useState(0);
|
||||
const [remoteId, setRemoteId] = useState(0);
|
||||
const [message, setMessage] = useState("");
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [titleError, setTitleError] = useState("");
|
||||
const [playersError, setPlayersError] = useState("");
|
||||
const [remoteIdError, setRemoteIdError] = useState("");
|
||||
const [opinions, setOpinions] = useState<Opinion[]>([]);
|
||||
const [gamesLoading, setGamesLoading] = useState(true);
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
|
||||
const fetchGames = () => {
|
||||
const filteredGames = useMemo(() => {
|
||||
if (!searchQuery) return games;
|
||||
return games.filter(game =>
|
||||
game.title.toLowerCase().includes(searchQuery.toLowerCase())
|
||||
);
|
||||
}, [games, searchQuery]);
|
||||
|
||||
const fetchGames = useCallback(() => {
|
||||
setGamesLoading(true);
|
||||
apiFetch("/api/games")
|
||||
.then((res) => res.arrayBuffer())
|
||||
.then((buffer) => {
|
||||
@@ -33,10 +51,15 @@ export function GameList() {
|
||||
setGames(list.games);
|
||||
} catch (e) {
|
||||
console.error("Failed to decode games:", e);
|
||||
onShowToast?.("Failed to load games", "error");
|
||||
}
|
||||
})
|
||||
.catch(console.error);
|
||||
};
|
||||
.catch((err) => {
|
||||
console.error(err);
|
||||
onShowToast?.("Failed to fetch games", "error");
|
||||
})
|
||||
.finally(() => setGamesLoading(false));
|
||||
}, [onShowToast]);
|
||||
|
||||
useEffect(() => {
|
||||
get_auth_status().then((user) => {
|
||||
@@ -71,13 +94,42 @@ export function GameList() {
|
||||
|
||||
useEffect(() => {
|
||||
fetchGames();
|
||||
}, []);
|
||||
}, [fetchGames]);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
setTitleError("");
|
||||
setPlayersError("");
|
||||
setRemoteIdError("");
|
||||
|
||||
let hasErrors = false;
|
||||
|
||||
if (!title.trim()) {
|
||||
setTitleError("Game title is required");
|
||||
hasErrors = true;
|
||||
}
|
||||
|
||||
if (minPlayers < 1) {
|
||||
setPlayersError("Minimum players must be at least 1");
|
||||
hasErrors = true;
|
||||
}
|
||||
|
||||
if (maxPlayers < minPlayers) {
|
||||
setPlayersError("Maximum players cannot be less than minimum players");
|
||||
hasErrors = true;
|
||||
}
|
||||
|
||||
if (remoteId === 0) {
|
||||
setRemoteIdError("Remote ID must be greater than 0");
|
||||
hasErrors = true;
|
||||
}
|
||||
|
||||
if (hasErrors) return;
|
||||
|
||||
setIsSubmitting(true);
|
||||
const game = {
|
||||
title,
|
||||
title: title.trim(),
|
||||
source,
|
||||
minPlayers,
|
||||
maxPlayers,
|
||||
@@ -96,27 +148,32 @@ export function GameList() {
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
setMessage("success");
|
||||
setTitle("");
|
||||
setMinPlayers(1);
|
||||
setMaxPlayers(1);
|
||||
setPrice(0);
|
||||
setRemoteId(0);
|
||||
onShowToast?.("Game added successfully!", "success");
|
||||
clearForm();
|
||||
fetchGames();
|
||||
setTimeout(() => setMessage(""), 3000);
|
||||
} else {
|
||||
setMessage("error");
|
||||
setTimeout(() => setMessage(""), 3000);
|
||||
const errorText = await res.text();
|
||||
onShowToast?.(errorText || "Failed to add game. Please try again.", "error");
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
setMessage("error");
|
||||
setTimeout(() => setMessage(""), 3000);
|
||||
onShowToast?.("An error occurred while adding the game.", "error");
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const clearForm = () => {
|
||||
setTitle("");
|
||||
setMinPlayers(1);
|
||||
setMaxPlayers(1);
|
||||
setPrice(0);
|
||||
setRemoteId(0);
|
||||
setTitleError("");
|
||||
setPlayersError("");
|
||||
setRemoteIdError("");
|
||||
};
|
||||
|
||||
const formCardStyles: React.CSSProperties = {
|
||||
background:
|
||||
"linear-gradient(135deg, var(--secondary-bg) 0%, var(--secondary-alt-bg) 100%)",
|
||||
@@ -128,7 +185,8 @@ export function GameList() {
|
||||
};
|
||||
|
||||
const formHeaderStyles: React.CSSProperties = {
|
||||
background: "linear-gradient(135deg, var(--accent-color) 0%, var(--secondary-accent) 100%)",
|
||||
background:
|
||||
"linear-gradient(135deg, var(--accent-color) 0%, var(--secondary-accent) 100%)",
|
||||
padding: "1.5rem 2rem",
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
@@ -195,7 +253,8 @@ export function GameList() {
|
||||
const submitButtonStyles: React.CSSProperties = {
|
||||
width: "100%",
|
||||
padding: "1rem",
|
||||
background: "linear-gradient(135deg, var(--accent-color) 0%, var(--secondary-accent) 100%)",
|
||||
background:
|
||||
"linear-gradient(135deg, var(--accent-color) 0%, var(--secondary-accent) 100%)",
|
||||
border: "none",
|
||||
borderRadius: "12px",
|
||||
color: "white",
|
||||
@@ -211,26 +270,6 @@ export function GameList() {
|
||||
transform: isSubmitting ? "none" : undefined,
|
||||
};
|
||||
|
||||
const messageStyles: React.CSSProperties = {
|
||||
padding: "1rem",
|
||||
borderRadius: "12px",
|
||||
marginBottom: "1.5rem",
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: "0.75rem",
|
||||
animation: "slideIn 0.3s ease",
|
||||
backgroundColor:
|
||||
message === "success"
|
||||
? "rgba(76, 175, 80, 0.15)"
|
||||
: "rgba(244, 67, 54, 0.15)",
|
||||
border: `1px solid ${
|
||||
message === "success"
|
||||
? "rgba(76, 175, 80, 0.3)"
|
||||
: "rgba(244, 67, 54, 0.3)"
|
||||
}`,
|
||||
color: message === "success" ? "#4caf50" : "#f44336",
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<style>
|
||||
@@ -303,19 +342,6 @@ export function GameList() {
|
||||
</div>
|
||||
|
||||
<div style={formBodyStyles}>
|
||||
{message && (
|
||||
<div style={messageStyles}>
|
||||
<span style={{ fontSize: "1.2rem" }}>
|
||||
{message === "success" ? "✓" : "✕"}
|
||||
</span>
|
||||
<span style={{ fontWeight: 500 }}>
|
||||
{message === "success"
|
||||
? "Game added successfully!"
|
||||
: "Failed to add game. Please try again."}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<form onSubmit={handleSubmit}>
|
||||
{/* Basic Info Section */}
|
||||
<div style={sectionStyles}>
|
||||
@@ -329,12 +355,23 @@ export function GameList() {
|
||||
<input
|
||||
type="text"
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
onChange={(e) => {
|
||||
setTitle(e.target.value);
|
||||
if (titleError) setTitleError("");
|
||||
}}
|
||||
required
|
||||
placeholder="Enter game title..."
|
||||
style={inputStyles}
|
||||
style={{
|
||||
...inputStyles,
|
||||
borderColor: titleError ? "#f44336" : undefined
|
||||
}}
|
||||
className="add-game-input"
|
||||
/>
|
||||
{titleError && (
|
||||
<div style={{ color: "#f44336", fontSize: "0.75rem", marginTop: "0.25rem" }}>
|
||||
{titleError}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div style={inputGroupStyles}>
|
||||
@@ -374,9 +411,15 @@ export function GameList() {
|
||||
<input
|
||||
type="number"
|
||||
value={minPlayers}
|
||||
onChange={(e) => setMinPlayers(Number(e.target.value))}
|
||||
onChange={(e) => {
|
||||
setMinPlayers(Number(e.target.value));
|
||||
if (playersError) setPlayersError("");
|
||||
}}
|
||||
min="1"
|
||||
style={inputStyles}
|
||||
style={{
|
||||
...inputStyles,
|
||||
borderColor: playersError ? "#f44336" : undefined
|
||||
}}
|
||||
className="add-game-input"
|
||||
/>
|
||||
</div>
|
||||
@@ -385,13 +428,24 @@ export function GameList() {
|
||||
<input
|
||||
type="number"
|
||||
value={maxPlayers}
|
||||
onChange={(e) => setMaxPlayers(Number(e.target.value))}
|
||||
onChange={(e) => {
|
||||
setMaxPlayers(Number(e.target.value));
|
||||
if (playersError) setPlayersError("");
|
||||
}}
|
||||
min="1"
|
||||
style={inputStyles}
|
||||
style={{
|
||||
...inputStyles,
|
||||
borderColor: playersError ? "#f44336" : undefined
|
||||
}}
|
||||
className="add-game-input"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{playersError && (
|
||||
<div style={{ color: "#f44336", fontSize: "0.75rem", marginTop: "0.25rem" }}>
|
||||
{playersError}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div style={dividerStyles}></div>
|
||||
@@ -409,9 +463,9 @@ export function GameList() {
|
||||
<input
|
||||
type="number"
|
||||
value={price}
|
||||
onChange={(e) => setPrice(Number(e.target.value))}
|
||||
onChange={(e) => setPrice(Math.ceil(Number(e.target.value.replace(',', '.'))))}
|
||||
min="0"
|
||||
step="0.01"
|
||||
step="1"
|
||||
style={inputStyles}
|
||||
className="add-game-input"
|
||||
/>
|
||||
@@ -421,42 +475,73 @@ export function GameList() {
|
||||
<input
|
||||
type="number"
|
||||
value={remoteId}
|
||||
onChange={(e) => setRemoteId(Number(e.target.value))}
|
||||
onChange={(e) => {
|
||||
setRemoteId(Number(e.target.value));
|
||||
setRemoteIdError("");
|
||||
}}
|
||||
min="0"
|
||||
style={inputStyles}
|
||||
style={{
|
||||
...inputStyles,
|
||||
borderColor: remoteIdError ? "#f44336" : undefined,
|
||||
}}
|
||||
className="add-game-input"
|
||||
/>
|
||||
{remoteIdError && (
|
||||
<div
|
||||
style={{
|
||||
color: "#f44336",
|
||||
fontSize: "0.75rem",
|
||||
marginTop: "0.25rem",
|
||||
}}
|
||||
>
|
||||
{remoteIdError}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isSubmitting}
|
||||
style={submitButtonStyles}
|
||||
className="submit-btn"
|
||||
>
|
||||
{isSubmitting ? (
|
||||
<>
|
||||
<span
|
||||
style={{
|
||||
width: "18px",
|
||||
height: "18px",
|
||||
border: "2px solid rgba(255,255,255,0.3)",
|
||||
borderTopColor: "white",
|
||||
borderRadius: "50%",
|
||||
animation: "spin 0.8s linear infinite",
|
||||
}}
|
||||
></span>
|
||||
Adding Game...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<span style={{ fontSize: "1.1rem" }}>➕</span>
|
||||
Add Game to Collection
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
<div style={{ display: "flex", gap: "0.75rem", marginTop: "1rem" }}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={clearForm}
|
||||
disabled={isSubmitting || (!title && minPlayers === 1 && maxPlayers === 1 && price === 0 && remoteId === 0)}
|
||||
style={{
|
||||
...submitButtonStyles,
|
||||
background: "var(--tertiary-bg)",
|
||||
flex: 1
|
||||
}}
|
||||
>
|
||||
Clear
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isSubmitting}
|
||||
style={submitButtonStyles}
|
||||
className="submit-btn"
|
||||
>
|
||||
{isSubmitting ? (
|
||||
<>
|
||||
<span
|
||||
style={{
|
||||
width: "18px",
|
||||
height: "18px",
|
||||
border: "2px solid rgba(255,255,255,0.3)",
|
||||
borderTopColor: "white",
|
||||
borderRadius: "50%",
|
||||
animation: "spin 0.8s linear infinite",
|
||||
}}
|
||||
></span>
|
||||
Adding Game...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<span style={{ fontSize: "1.1rem" }}>➕</span>
|
||||
Add Game to Collection
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
@@ -470,16 +555,89 @@ export function GameList() {
|
||||
</style>
|
||||
|
||||
<div style={{ marginTop: "3rem" }}>
|
||||
<h3
|
||||
id="existing-games"
|
||||
<div
|
||||
style={{
|
||||
scrollMarginBottom: "0",
|
||||
display: "flex",
|
||||
justifyContent: "space-between",
|
||||
alignItems: "center",
|
||||
marginBottom: "1rem",
|
||||
flexWrap: "wrap",
|
||||
gap: "1rem"
|
||||
}}
|
||||
>
|
||||
Existing Games
|
||||
</h3>
|
||||
<ul className="grid-container">
|
||||
{games.map((game) => {
|
||||
<h3
|
||||
id="existing-games"
|
||||
style={{
|
||||
scrollMarginBottom: "0",
|
||||
margin: 0
|
||||
}}
|
||||
>
|
||||
Existing Games {filteredGames.length > 0 && <span style={{ fontSize: "0.7em", color: "var(--text-muted)" }}>({filteredGames.length})</span>}
|
||||
</h3>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="🔍 Search games..."
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
style={{
|
||||
padding: "0.5rem 1rem",
|
||||
fontSize: "0.9rem",
|
||||
minWidth: "200px"
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
{gamesLoading ? (
|
||||
<div className="grid-container">
|
||||
{Array.from({ length: 6 }).map((_, i) => (
|
||||
<div
|
||||
key={i}
|
||||
style={{
|
||||
backgroundColor: "var(--secondary-alt-bg)",
|
||||
border: "1px solid var(--border-color)",
|
||||
borderRadius: "5px",
|
||||
padding: "1rem",
|
||||
minHeight: "100px",
|
||||
animation: "shimmer 1.5s infinite"
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
width: "70%",
|
||||
height: "20px",
|
||||
backgroundColor: "var(--tertiary-bg)",
|
||||
borderRadius: "4px",
|
||||
marginBottom: "0.75rem",
|
||||
animation: "shimmer 1.5s infinite"
|
||||
}}
|
||||
></div>
|
||||
<div
|
||||
style={{
|
||||
width: "40%",
|
||||
height: "40px",
|
||||
backgroundColor: "var(--tertiary-bg)",
|
||||
borderRadius: "8px",
|
||||
marginTop: "0.5rem",
|
||||
animation: "shimmer 1.5s infinite 0.2s"
|
||||
}}
|
||||
></div>
|
||||
</div>
|
||||
))}
|
||||
<style>{`
|
||||
@keyframes shimmer {
|
||||
0%, 100% { opacity: 0.5; }
|
||||
50% { opacity: 1; }
|
||||
}
|
||||
`}</style>
|
||||
</div>
|
||||
) : filteredGames.length === 0 ? (
|
||||
<EmptyState
|
||||
icon="🎮"
|
||||
title={searchQuery ? "No games found" : "No games yet"}
|
||||
description={searchQuery ? "Try a different search term" : "Add your first game to get started"}
|
||||
/>
|
||||
) : (
|
||||
<ul className="grid-container">
|
||||
{filteredGames.map((game) => {
|
||||
const opinion = opinions.find((op) => op.title === game.title);
|
||||
function handleOpinion(title: string, number: number): void {
|
||||
if (number == 2) {
|
||||
@@ -489,7 +647,7 @@ export function GameList() {
|
||||
"Content-Type": "application/octet-stream",
|
||||
},
|
||||
body: RemoveOpinionRequest.encode(
|
||||
AddOpinionRequest.create({
|
||||
RemoveOpinionRequest.create({
|
||||
gameTitle: title,
|
||||
})
|
||||
).finish(),
|
||||
@@ -501,9 +659,11 @@ export function GameList() {
|
||||
);
|
||||
|
||||
setOpinions(response.opinion);
|
||||
onShowToast?.(`Updated opinion for ${title}`, "info");
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error(err);
|
||||
onShowToast?.("Failed to update opinion", "error");
|
||||
});
|
||||
return;
|
||||
}
|
||||
@@ -527,9 +687,11 @@ export function GameList() {
|
||||
);
|
||||
|
||||
setOpinions(response.opinion);
|
||||
onShowToast?.(`Updated opinion for ${title}`, "info");
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error(err);
|
||||
onShowToast?.("Failed to update opinion", "error");
|
||||
});
|
||||
}
|
||||
|
||||
@@ -556,7 +718,7 @@ export function GameList() {
|
||||
? opinion.wouldPlay
|
||||
? "#4caf50" // would play (green)
|
||||
: "#f44336" // would not play (red)
|
||||
: "#191f2e", // no opinion (bg-2)
|
||||
: "#ffff00", // no opinion (yellow)
|
||||
}}
|
||||
>
|
||||
<strong
|
||||
@@ -565,7 +727,7 @@ export function GameList() {
|
||||
? opinion.wouldPlay
|
||||
? "0 0 10px #4caf50" // would play (green)
|
||||
: "0 0 10px #f44336" // would not play (red)
|
||||
: "none", // no opinion (bg-2)
|
||||
: "0 0 10px #ffff00", // no opinion (yellow)
|
||||
}}
|
||||
>
|
||||
{game.title}
|
||||
@@ -582,36 +744,54 @@ export function GameList() {
|
||||
>
|
||||
<button
|
||||
onClick={() => handleOpinion(game.title, 1)}
|
||||
className="theme-btn game-btn"
|
||||
style={{
|
||||
width: "50%",
|
||||
borderColor: "#4caf50",
|
||||
width: "33%",
|
||||
borderColor: opinion?.wouldPlay
|
||||
? "#4caf50"
|
||||
: "transparent",
|
||||
background: "rgba(76, 175, 80, 0.1)",
|
||||
fontSize: "1.2rem",
|
||||
}}
|
||||
title="Would Play"
|
||||
>
|
||||
Would Play
|
||||
👍
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleOpinion(game.title, 2)}
|
||||
className="theme-btn game-btn"
|
||||
style={{
|
||||
width: "50%",
|
||||
borderColor: "#ffff00",
|
||||
width: "33%",
|
||||
borderColor: !opinion ? "#ffff00" : "transparent",
|
||||
background: "rgba(255, 255, 0, 0.1)",
|
||||
fontSize: "1.2rem",
|
||||
}}
|
||||
title="Neutral"
|
||||
>
|
||||
Neutral
|
||||
😐
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleOpinion(game.title, 0)}
|
||||
className="theme-btn game-btn"
|
||||
style={{
|
||||
width: "50%",
|
||||
borderColor: "#f44336",
|
||||
width: "33%",
|
||||
borderColor:
|
||||
opinion && !opinion.wouldPlay
|
||||
? "#f44336"
|
||||
: "transparent",
|
||||
background: "rgba(244, 67, 54, 0.1)",
|
||||
fontSize: "1.2rem",
|
||||
}}
|
||||
title="Would Not Play"
|
||||
>
|
||||
Would Not Play
|
||||
👎
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
+369
-26
@@ -1,4 +1,4 @@
|
||||
import { useState } from "react";
|
||||
import { useState, useRef, useEffect } from "react";
|
||||
import { LoginRequest, LoginResponse } from "../items";
|
||||
|
||||
interface LoginProps {
|
||||
@@ -6,16 +6,41 @@ interface LoginProps {
|
||||
}
|
||||
|
||||
export function Login({ onLogin }: LoginProps) {
|
||||
const usernameInputRef = useRef<HTMLInputElement>(null);
|
||||
const [username, setUsername] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [error, setError] = useState("");
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [fieldErrors, setFieldErrors] = useState<{ username?: string, password?: string }>({});
|
||||
const [isSuccess, setIsSuccess] = useState(false);
|
||||
const [shakeCard, setShakeCard] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
usernameInputRef.current?.focus();
|
||||
}, []);
|
||||
|
||||
const validateForm = () => {
|
||||
const errors: { username?: string, password?: string } = {};
|
||||
if (!username.trim()) errors.username = "Username is required";
|
||||
if (!password) errors.password = "Password is required";
|
||||
setFieldErrors(errors);
|
||||
return Object.keys(errors).length === 0;
|
||||
};
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError("");
|
||||
|
||||
if (!validateForm()) {
|
||||
setShakeCard(true);
|
||||
setTimeout(() => setShakeCard(false), 500);
|
||||
return;
|
||||
}
|
||||
|
||||
setIsSubmitting(true);
|
||||
|
||||
try {
|
||||
const req = LoginRequest.create({ username, password });
|
||||
const req = LoginRequest.create({ username: username.trim(), password });
|
||||
const body = LoginRequest.encode(req).finish();
|
||||
|
||||
const res = await fetch("/auth/login", {
|
||||
@@ -30,47 +55,365 @@ export function Login({ onLogin }: LoginProps) {
|
||||
const response = LoginResponse.decode(new Uint8Array(buffer));
|
||||
|
||||
if (response.success) {
|
||||
setIsSuccess(true);
|
||||
onLogin(response.token);
|
||||
} else {
|
||||
setError(response.message);
|
||||
setError(response.message || "Login failed");
|
||||
setShakeCard(true);
|
||||
setTimeout(() => setShakeCard(false), 500);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Login error:", err);
|
||||
setError("Failed to login");
|
||||
setError("An unexpected error occurred. Please try again.");
|
||||
setShakeCard(true);
|
||||
setTimeout(() => setShakeCard(false), 500);
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent) => {
|
||||
if (e.key === "Enter") {
|
||||
handleSubmit(e);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="card" style={{ maxWidth: "400px", margin: "4rem auto" }}>
|
||||
<h2 style={{ textAlign: "center", marginBottom: "2rem" }}>Login</h2>
|
||||
<div
|
||||
className="card login-card"
|
||||
style={{
|
||||
maxWidth: "420px",
|
||||
margin: "6rem auto",
|
||||
padding: "2.5rem",
|
||||
background: "linear-gradient(135deg, var(--secondary-bg) 0%, var(--secondary-alt-bg) 100%)",
|
||||
position: "relative"
|
||||
}}
|
||||
>
|
||||
{isSubmitting && (
|
||||
<div
|
||||
style={{
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
backgroundColor: "rgba(0, 0, 0, 0.5)",
|
||||
borderRadius: "16px",
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
zIndex: 10,
|
||||
backdropFilter: "blur(2px)"
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
width: "48px",
|
||||
height: "48px",
|
||||
border: "4px solid rgba(255, 255, 255, 0.2)",
|
||||
borderTopColor: "white",
|
||||
borderRadius: "50%",
|
||||
animation: "spin 0.8s linear infinite"
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isSuccess && (
|
||||
<div
|
||||
style={{
|
||||
position: "absolute",
|
||||
top: "50%",
|
||||
left: "50%",
|
||||
transform: "translate(-50%, -50%)",
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
alignItems: "center",
|
||||
gap: "1rem",
|
||||
animation: "fadeInScale 0.5s ease forwards",
|
||||
zIndex: 10
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
width: "64px",
|
||||
height: "64px",
|
||||
borderRadius: "50%",
|
||||
backgroundColor: "#4caf50",
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
fontSize: "2rem",
|
||||
color: "white",
|
||||
boxShadow: "0 0 20px rgba(76, 175, 80, 0.5)"
|
||||
}}
|
||||
>
|
||||
✓
|
||||
</div>
|
||||
<span style={{ color: "#4caf50", fontWeight: 600, fontSize: "1.1rem" }}>
|
||||
Success!
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<h2
|
||||
style={{
|
||||
textAlign: "center",
|
||||
marginBottom: "0.5rem",
|
||||
fontSize: "2rem",
|
||||
fontWeight: 700
|
||||
}}
|
||||
>
|
||||
🎮 Login
|
||||
</h2>
|
||||
<p
|
||||
style={{
|
||||
textAlign: "center",
|
||||
color: "var(--text-muted)",
|
||||
marginBottom: "2rem",
|
||||
fontSize: "0.95rem"
|
||||
}}
|
||||
>
|
||||
Welcome back! Please sign in to continue.
|
||||
</p>
|
||||
|
||||
<form onSubmit={handleSubmit} className="form-group">
|
||||
<div className="form-group">
|
||||
<label>Username</label>
|
||||
<input
|
||||
type="text"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
placeholder="Enter your username"
|
||||
/>
|
||||
<div className="form-group" style={{ marginBottom: "1.5rem" }}>
|
||||
<label
|
||||
style={{
|
||||
display: "block",
|
||||
marginBottom: "0.5rem",
|
||||
fontWeight: 500,
|
||||
color: "var(--text-color)",
|
||||
fontSize: "0.95rem"
|
||||
}}
|
||||
>
|
||||
Username
|
||||
</label>
|
||||
<div
|
||||
style={{
|
||||
position: "relative",
|
||||
display: "flex",
|
||||
alignItems: "center"
|
||||
}}
|
||||
>
|
||||
<span
|
||||
style={{
|
||||
position: "absolute",
|
||||
left: "0.75rem",
|
||||
color: "var(--text-muted)",
|
||||
pointerEvents: "none",
|
||||
fontSize: "1.1rem"
|
||||
}}
|
||||
>
|
||||
👤
|
||||
</span>
|
||||
<input
|
||||
ref={usernameInputRef}
|
||||
type="text"
|
||||
value={username}
|
||||
onChange={(e) => {
|
||||
setUsername(e.target.value);
|
||||
if (fieldErrors.username) setFieldErrors({ ...fieldErrors, username: undefined });
|
||||
}}
|
||||
onKeyDown={handleKeyDown}
|
||||
placeholder="Enter your username"
|
||||
aria-label="Username"
|
||||
aria-invalid={!!fieldErrors.username}
|
||||
aria-describedby={fieldErrors.username ? "username-error" : undefined}
|
||||
style={{
|
||||
width: "100%",
|
||||
paddingLeft: "2.75rem",
|
||||
paddingRight: "0.75rem",
|
||||
paddingTop: "0.75rem",
|
||||
paddingBottom: "0.75rem",
|
||||
borderColor: fieldErrors.username ? "#f44336" : undefined,
|
||||
borderWidth: fieldErrors.username ? "2px" : "1px",
|
||||
fontSize: "1rem"
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
{fieldErrors.username && (
|
||||
<span
|
||||
id="username-error"
|
||||
role="alert"
|
||||
style={{
|
||||
color: "#ff6b6b",
|
||||
fontSize: "0.85rem",
|
||||
marginTop: "0.5rem",
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: "0.25rem"
|
||||
}}
|
||||
>
|
||||
⚠️ {fieldErrors.username}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="form-group">
|
||||
<label>Password</label>
|
||||
<input
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
placeholder="Enter your password"
|
||||
/>
|
||||
|
||||
<div className="form-group" style={{ marginBottom: "2rem" }}>
|
||||
<label
|
||||
style={{
|
||||
display: "block",
|
||||
marginBottom: "0.5rem",
|
||||
fontWeight: 500,
|
||||
color: "var(--text-color)",
|
||||
fontSize: "0.95rem"
|
||||
}}
|
||||
>
|
||||
Password
|
||||
</label>
|
||||
<div
|
||||
style={{
|
||||
position: "relative",
|
||||
display: "flex",
|
||||
alignItems: "center"
|
||||
}}
|
||||
>
|
||||
<span
|
||||
style={{
|
||||
position: "absolute",
|
||||
left: "0.75rem",
|
||||
color: "var(--text-muted)",
|
||||
pointerEvents: "none",
|
||||
fontSize: "1.1rem"
|
||||
}}
|
||||
>
|
||||
🔒
|
||||
</span>
|
||||
<input
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => {
|
||||
setPassword(e.target.value);
|
||||
if (fieldErrors.password) setFieldErrors({ ...fieldErrors, password: undefined });
|
||||
}}
|
||||
onKeyDown={handleKeyDown}
|
||||
placeholder="Enter your password"
|
||||
aria-label="Password"
|
||||
aria-invalid={!!fieldErrors.password}
|
||||
aria-describedby={fieldErrors.password ? "password-error" : undefined}
|
||||
style={{
|
||||
width: "100%",
|
||||
paddingLeft: "2.75rem",
|
||||
paddingRight: "0.75rem",
|
||||
paddingTop: "0.75rem",
|
||||
paddingBottom: "0.75rem",
|
||||
borderColor: fieldErrors.password ? "#f44336" : undefined,
|
||||
borderWidth: fieldErrors.password ? "2px" : "1px",
|
||||
fontSize: "1rem"
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
{fieldErrors.password && (
|
||||
<span
|
||||
id="password-error"
|
||||
role="alert"
|
||||
style={{
|
||||
color: "#ff6b6b",
|
||||
fontSize: "0.85rem",
|
||||
marginTop: "0.5rem",
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: "0.25rem"
|
||||
}}
|
||||
>
|
||||
⚠️ {fieldErrors.password}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<button type="submit" style={{ marginTop: "1rem" }}>
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
style={{
|
||||
marginTop: "0.5rem",
|
||||
width: "100%",
|
||||
padding: "0.875rem",
|
||||
fontSize: "1rem",
|
||||
fontWeight: 600,
|
||||
opacity: isSubmitting ? 0.7 : 1,
|
||||
cursor: isSubmitting ? "not-allowed" : "pointer",
|
||||
background: "linear-gradient(135deg, var(--accent-color) 0%, var(--secondary-accent) 100%)",
|
||||
border: "none",
|
||||
transition: "transform 0.1s, box-shadow 0.2s"
|
||||
}}
|
||||
disabled={isSubmitting}
|
||||
onMouseEnter={(e) => {
|
||||
if (!isSubmitting) {
|
||||
e.currentTarget.style.transform = "translateY(-1px)";
|
||||
e.currentTarget.style.boxShadow = "0 4px 12px rgba(9, 109, 192, 0.4)";
|
||||
}
|
||||
}}
|
||||
onMouseLeave={(e) => {
|
||||
if (!isSubmitting) {
|
||||
e.currentTarget.style.transform = "translateY(0)";
|
||||
e.currentTarget.style.boxShadow = "none";
|
||||
}
|
||||
}}
|
||||
onMouseDown={(e) => {
|
||||
if (!isSubmitting) {
|
||||
e.currentTarget.style.transform = "translateY(0)";
|
||||
}
|
||||
}}
|
||||
>
|
||||
Login
|
||||
</button>
|
||||
</form>
|
||||
|
||||
{error && (
|
||||
<p style={{ color: "#ff6b6b", marginTop: "1rem", textAlign: "center" }}>
|
||||
{error}
|
||||
</p>
|
||||
<div
|
||||
role="alert"
|
||||
style={{
|
||||
backgroundColor: "rgba(244, 67, 54, 0.15)",
|
||||
border: "1px solid rgba(244, 67, 54, 0.4)",
|
||||
color: "#ff6b6b",
|
||||
padding: "0.875rem 1rem",
|
||||
borderRadius: "8px",
|
||||
marginTop: "1.5rem",
|
||||
textAlign: "center",
|
||||
fontSize: "0.9rem",
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
gap: "0.5rem"
|
||||
}}
|
||||
>
|
||||
⚠️ {error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<style>{`
|
||||
@keyframes spin {
|
||||
to { transform: rotate(360deg); }
|
||||
}
|
||||
|
||||
@keyframes fadeInScale {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translate(-50%, -40%) scale(0.8);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translate(-50%, -50%) scale(1);
|
||||
}
|
||||
}
|
||||
|
||||
.login-card {
|
||||
animation: ${shakeCard ? "shake 0.5s ease" : "none"};
|
||||
}
|
||||
|
||||
@keyframes shake {
|
||||
0%, 100% {
|
||||
transform: translateX(0);
|
||||
}
|
||||
20%, 60% {
|
||||
transform: translateX(-8px);
|
||||
}
|
||||
40%, 80% {
|
||||
transform: translateX(8px);
|
||||
}
|
||||
}
|
||||
`}</style>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3,53 +3,71 @@ import { Link, useParams } from "react-router-dom";
|
||||
import { Person } from "../items";
|
||||
import { apiFetch } from "./api";
|
||||
import { GameImage } from "./GameImage";
|
||||
import { LoadingState, EmptyState } from "./components/EmptyState";
|
||||
|
||||
export const PersonDetails = () => {
|
||||
const { name } = useParams<{ name: string }>();
|
||||
const [person, setPerson] = useState<Person | null>(null);
|
||||
const [loading, setLoading] = useState(!!name);
|
||||
const [error, setError] = useState<string | null>(name ? null : "Person name is missing");
|
||||
|
||||
useEffect(() => {
|
||||
if (name) {
|
||||
apiFetch(`/api/${name}`)
|
||||
.then((res) => res.arrayBuffer())
|
||||
.then((buffer) => {
|
||||
try {
|
||||
setPerson(Person.decode(new Uint8Array(buffer)));
|
||||
} catch (e) {
|
||||
console.error("Failed to decode person:", e);
|
||||
}
|
||||
})
|
||||
.catch(console.error);
|
||||
}
|
||||
if (!name) return;
|
||||
|
||||
(async () => {
|
||||
try {
|
||||
const res = await apiFetch(`/api/${name}`);
|
||||
if (!res.ok) {
|
||||
throw new Error("Person not found");
|
||||
}
|
||||
const buffer = await res.arrayBuffer();
|
||||
setPerson(Person.decode(new Uint8Array(buffer)));
|
||||
} catch (e) {
|
||||
console.error("Failed to decode person:", e);
|
||||
setError(e instanceof Error ? e.message : "Failed to load person data");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
})();
|
||||
}, [name]);
|
||||
|
||||
if (!person) return <div>Loading...</div>;
|
||||
if (loading) return <LoadingState message="Loading person details..." />;
|
||||
if (error) return <EmptyState icon="⚠️" title="Error" description={error} />;
|
||||
if (!person) return <EmptyState icon="👤" title="Person not found" description="This person doesn't exist" />;
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div style={{ marginBottom: "2rem" }}>
|
||||
<h2>{person.name}</h2>
|
||||
<ul className="grid-container">
|
||||
{person.opinion.map((op, i) => (
|
||||
<Link
|
||||
to={`/game/${encodeURIComponent(op.title)}`}
|
||||
key={i}
|
||||
className="list-item"
|
||||
style={{
|
||||
textDecoration: "none",
|
||||
color: "inherit",
|
||||
display: "flex",
|
||||
justifyContent: "space-between",
|
||||
alignItems: "center",
|
||||
borderColor: op.wouldPlay ? "#4caf50" : "#f44336",
|
||||
}}
|
||||
>
|
||||
<strong>{op.title}</strong>
|
||||
{person.opinion.length === 0 ? (
|
||||
<EmptyState
|
||||
icon="🎮"
|
||||
title="No opinions yet"
|
||||
description={`${person.name} hasn't shared any game opinions`}
|
||||
/>
|
||||
) : (
|
||||
<ul className="grid-container">
|
||||
{person.opinion.map((op, i) => (
|
||||
<Link
|
||||
to={`/game/${encodeURIComponent(op.title)}`}
|
||||
key={i}
|
||||
className="list-item"
|
||||
style={{
|
||||
textDecoration: "none",
|
||||
color: "inherit",
|
||||
display: "flex",
|
||||
justifyContent: "space-between",
|
||||
alignItems: "center",
|
||||
borderColor: op.wouldPlay ? "#4caf50" : "#f44336",
|
||||
}}
|
||||
>
|
||||
<strong>{op.title}</strong>
|
||||
|
||||
<GameImage game={op.title} />
|
||||
</Link>
|
||||
))}
|
||||
</ul>
|
||||
<GameImage game={op.title} />
|
||||
</Link>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
.list-item {
|
||||
border-radius: 5px;
|
||||
border: 1px solid var(--border-color);
|
||||
background-color: var(--secondary-alt-bg);
|
||||
margin-bottom: 10px;
|
||||
padding: 10px;
|
||||
text-align: center;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.list-item:hover {
|
||||
background-color: var(--primary-bg);
|
||||
}
|
||||
|
||||
.grid-container {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
|
||||
gap: 1rem;
|
||||
}
|
||||
+172
-30
@@ -1,19 +1,53 @@
|
||||
import { Person } from "../items";
|
||||
import { Link } from "react-router-dom";
|
||||
import { useState } from "react";
|
||||
import { get_auth_status } from "./api";
|
||||
import { useState, useEffect, useMemo } from "react";
|
||||
import { get_auth_status, refresh_state, get_is_admin } from "./api";
|
||||
import type { ToastType } from "./Toast";
|
||||
import { EmptyState } from "./components/EmptyState";
|
||||
import "./PersonList.css"
|
||||
|
||||
interface Props {
|
||||
people: Person[];
|
||||
loading?: boolean;
|
||||
onShowToast?: (message: string, type?: ToastType) => void;
|
||||
}
|
||||
|
||||
export const PersonList = ({ people }: Props) => {
|
||||
export const PersonList = ({ people, loading = false, onShowToast }: Props) => {
|
||||
const [current_user, set_current_user] = useState<string>("");
|
||||
get_auth_status().then((res) => {
|
||||
if (res) {
|
||||
set_current_user(res.username);
|
||||
const [isRefreshing, setIsRefreshing] = useState(false);
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
get_auth_status().then((res) => {
|
||||
if (res) {
|
||||
set_current_user(res.username);
|
||||
}
|
||||
});
|
||||
}, []);
|
||||
|
||||
const filteredPeople = useMemo(() => {
|
||||
if (!searchQuery) return people;
|
||||
return people.filter(person =>
|
||||
person.name.toLowerCase().includes(searchQuery.toLowerCase())
|
||||
);
|
||||
}, [people, searchQuery]);
|
||||
|
||||
const handleRefresh = async () => {
|
||||
setIsRefreshing(true);
|
||||
try {
|
||||
await refresh_state();
|
||||
onShowToast?.("State refreshed from file successfully", "success");
|
||||
window.location.reload();
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
onShowToast?.("Failed to refresh state from file", "error");
|
||||
} finally {
|
||||
setIsRefreshing(false);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const isAdmin = get_is_admin();
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div
|
||||
@@ -22,16 +56,136 @@ export const PersonList = ({ people }: Props) => {
|
||||
justifyContent: "space-between",
|
||||
alignItems: "center",
|
||||
marginBottom: "1rem",
|
||||
flexWrap: "wrap",
|
||||
gap: "1rem"
|
||||
}}
|
||||
>
|
||||
<h2>People List</h2>
|
||||
<h2>People List {filteredPeople.length > 0 && <span style={{ fontSize: "0.8em", color: "var(--text-muted)" }}>({filteredPeople.length})</span>}</h2>
|
||||
<div style={{ display: "flex", gap: "0.75rem", alignItems: "center" }}>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="🔍 Search people..."
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
style={{
|
||||
padding: "0.5rem 1rem",
|
||||
fontSize: "0.9rem",
|
||||
minWidth: "200px"
|
||||
}}
|
||||
/>
|
||||
{isAdmin && (
|
||||
<button
|
||||
onClick={handleRefresh}
|
||||
disabled={isRefreshing}
|
||||
className="btn-secondary"
|
||||
style={{
|
||||
padding: "0.5rem 1rem",
|
||||
fontSize: "0.9rem",
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: "0.5rem",
|
||||
opacity: isRefreshing ? 0.7 : 1,
|
||||
cursor: isRefreshing ? "not-allowed" : "pointer",
|
||||
}}
|
||||
>
|
||||
{isRefreshing ? (
|
||||
<>
|
||||
<span
|
||||
style={{
|
||||
width: "14px",
|
||||
height: "14px",
|
||||
border: "2px solid rgba(255,255,255,0.3)",
|
||||
borderTopColor: "currentColor",
|
||||
borderRadius: "50%",
|
||||
animation: "spin 0.8s linear infinite",
|
||||
}}
|
||||
></span>
|
||||
Refreshing...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<span>🔄</span>
|
||||
Refresh from File
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid-container">
|
||||
{people.map((person, index) => {
|
||||
if (person.name == current_user) {
|
||||
{loading ? (
|
||||
<div className="grid-container">
|
||||
{Array.from({ length: 6 }).map((_, i) => (
|
||||
<div
|
||||
key={i}
|
||||
style={{
|
||||
backgroundColor: "var(--secondary-alt-bg)",
|
||||
border: "1px solid var(--border-color)",
|
||||
borderRadius: "5px",
|
||||
padding: "10px",
|
||||
minHeight: "60px",
|
||||
animation: "shimmer 1.5s infinite"
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
width: "60%",
|
||||
height: "20px",
|
||||
backgroundColor: "var(--tertiary-bg)",
|
||||
borderRadius: "4px",
|
||||
marginBottom: "0.5rem",
|
||||
animation: "shimmer 1.5s infinite"
|
||||
}}
|
||||
></div>
|
||||
<div
|
||||
style={{
|
||||
width: "40%",
|
||||
height: "16px",
|
||||
backgroundColor: "var(--tertiary-bg)",
|
||||
borderRadius: "4px",
|
||||
animation: "shimmer 1.5s infinite 0.2s"
|
||||
}}
|
||||
></div>
|
||||
</div>
|
||||
))}
|
||||
<style>{`
|
||||
@keyframes shimmer {
|
||||
0%, 100% { opacity: 0.5; }
|
||||
50% { opacity: 1; }
|
||||
}
|
||||
`}</style>
|
||||
</div>
|
||||
) : filteredPeople.length === 0 ? (
|
||||
<EmptyState
|
||||
icon="👥"
|
||||
title={searchQuery ? "No people found" : "No people in list"}
|
||||
description={searchQuery ? "Try a different search term" : "Add people to get started"}
|
||||
/>
|
||||
) : (
|
||||
<div className="grid-container">
|
||||
{filteredPeople.map((person, index) => {
|
||||
if (person.name.toLowerCase() === current_user.toLowerCase()) {
|
||||
return (
|
||||
<Link
|
||||
to={`/games#existing-games`}
|
||||
key={index}
|
||||
className="list-item"
|
||||
style={{
|
||||
textDecoration: "none",
|
||||
color: "inherit",
|
||||
display: "block",
|
||||
}}
|
||||
>
|
||||
<h3>{person.name}</h3>
|
||||
<div style={{ fontSize: "0.85em", color: "var(--text-muted)", marginTop: "0.25rem" }}>
|
||||
{person.opinion.length} opinion(s)
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Link
|
||||
to={`/games#existing-games`}
|
||||
to={`/person/${person.name}`}
|
||||
key={index}
|
||||
className="list-item"
|
||||
style={{
|
||||
@@ -41,26 +195,14 @@ export const PersonList = ({ people }: Props) => {
|
||||
}}
|
||||
>
|
||||
<h3>{person.name}</h3>
|
||||
<div style={{ fontSize: "0.85em", color: "var(--text-muted)", marginTop: "0.25rem" }}>
|
||||
{person.opinion.length} opinion(s)
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Link
|
||||
to={`/person/${person.name}`}
|
||||
key={index}
|
||||
className="list-item"
|
||||
style={{
|
||||
textDecoration: "none",
|
||||
color: "inherit",
|
||||
display: "block",
|
||||
}}
|
||||
>
|
||||
<h3>{person.name}</h3>
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -2,6 +2,9 @@ import { useEffect, useRef } from "react";
|
||||
|
||||
import BLACKHOLE_SHADER_CODE from "./assets/blackhole.glsl?raw";
|
||||
import STAR_SHADER_CODE from "./assets/star.glsl?raw";
|
||||
import BALL_SHADER_CODE from "./assets/ball.glsl?raw";
|
||||
import REFLECT_BALL_SHADER_CODE from "./assets/reflect.glsl?raw";
|
||||
import CLOUDS_SHADER_CODE from "./assets/clouds.glsl?raw";
|
||||
|
||||
function buildProgram(
|
||||
ctx: WebGL2RenderingContext,
|
||||
@@ -117,7 +120,9 @@ type ShaderBackgroundProps = {
|
||||
theme: string;
|
||||
};
|
||||
|
||||
export const ShaderBackground: React.FC<ShaderBackgroundProps> = ({ theme }) => {
|
||||
export const ShaderBackground: React.FC<ShaderBackgroundProps> = ({
|
||||
theme,
|
||||
}) => {
|
||||
const canvasRef = useRef<HTMLCanvasElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -139,8 +144,16 @@ export const ShaderBackground: React.FC<ShaderBackgroundProps> = ({ theme }) =>
|
||||
case "star":
|
||||
shader_code = STAR_SHADER_CODE;
|
||||
break;
|
||||
case "ball":
|
||||
shader_code = BALL_SHADER_CODE;
|
||||
break;
|
||||
case "reflect":
|
||||
shader_code = REFLECT_BALL_SHADER_CODE;
|
||||
break;
|
||||
case "clouds":
|
||||
shader_code = CLOUDS_SHADER_CODE;
|
||||
break;
|
||||
default:
|
||||
console.error("Unknown shader theme:", theme);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -179,7 +192,13 @@ export const ShaderBackground: React.FC<ShaderBackgroundProps> = ({ theme }) =>
|
||||
|
||||
function setResolution(program: WebGLProgram) {
|
||||
const loc = gl!.getUniformLocation(program, "iResolution");
|
||||
if (loc) gl!.uniform3fv(loc, [canvas!.width, canvas!.height, 1]);
|
||||
canvas!.width = window.visualViewport!.width;
|
||||
canvas!.height = window.visualViewport!.height;
|
||||
if (loc) gl!.uniform3fv(loc, [
|
||||
window.visualViewport!.width,
|
||||
window.visualViewport!.height,
|
||||
1,
|
||||
]);
|
||||
}
|
||||
|
||||
function setTime(program: WebGLProgram, now: number) {
|
||||
@@ -191,7 +210,12 @@ export const ShaderBackground: React.FC<ShaderBackgroundProps> = ({ theme }) =>
|
||||
|
||||
const ichannel1_texture = loadTexture(gl, "assets/small_noise.png");
|
||||
|
||||
gl!.viewport(0, 0, canvas!.width, canvas!.height);
|
||||
gl!.viewport(
|
||||
0,
|
||||
0,
|
||||
window.visualViewport!.width,
|
||||
window.visualViewport!.height
|
||||
);
|
||||
|
||||
gl!.useProgram(finalProgram);
|
||||
setResolution(finalProgram!);
|
||||
@@ -201,9 +225,24 @@ export const ShaderBackground: React.FC<ShaderBackgroundProps> = ({ theme }) =>
|
||||
gl!.bindTexture(gl!.TEXTURE_2D, ichannel1_texture);
|
||||
gl!.uniform1i(final_iChannel1, 1);
|
||||
|
||||
let last_update: number = 0;
|
||||
|
||||
const compiled_theme = theme;
|
||||
|
||||
function update(now: number) {
|
||||
// time in seconds
|
||||
const time = now / 1000;
|
||||
|
||||
if (compiled_theme !== theme) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (time - last_update < (1 / 30)) {
|
||||
requestAnimationFrame(update);
|
||||
return;
|
||||
};
|
||||
last_update = time;
|
||||
|
||||
gl!.clear(gl!.COLOR_BUFFER_BIT);
|
||||
|
||||
setTime(finalProgram!, time);
|
||||
@@ -227,7 +266,6 @@ export const ShaderBackground: React.FC<ShaderBackgroundProps> = ({ theme }) =>
|
||||
top: 0,
|
||||
left: 0,
|
||||
zIndex: -1,
|
||||
pointerEvents: "none",
|
||||
}}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import React, { useEffect } from "react";
|
||||
|
||||
export type ToastType = "success" | "error" | "info";
|
||||
|
||||
interface ToastProps {
|
||||
message: string;
|
||||
type: ToastType;
|
||||
onClose: () => void;
|
||||
duration?: number;
|
||||
}
|
||||
|
||||
export const Toast: React.FC<ToastProps> = ({
|
||||
message,
|
||||
type,
|
||||
onClose,
|
||||
duration = 3000,
|
||||
}) => {
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => {
|
||||
onClose();
|
||||
}, duration);
|
||||
return () => clearTimeout(timer);
|
||||
}, [onClose, duration]);
|
||||
|
||||
const getIcon = () => {
|
||||
switch (type) {
|
||||
case "success":
|
||||
return "✓";
|
||||
case "error":
|
||||
return "✕";
|
||||
default:
|
||||
return "ℹ";
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={`toast toast-${type}`}>
|
||||
<span className="toast-icon">{getIcon()}</span>
|
||||
<span className="toast-message">{message}</span>
|
||||
<button className="toast-close" onClick={onClose}>
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
+13
-1
@@ -21,7 +21,8 @@ export const apiFetch = async (
|
||||
if (!response.ok) {
|
||||
if (response.status == 401) {
|
||||
localStorage.removeItem("token");
|
||||
window.location.href = "/";
|
||||
localStorage.removeItem("isAdmin");
|
||||
window.dispatchEvent(new CustomEvent("unauthorized"));
|
||||
}
|
||||
throw new Error(`Request failed with status ${response.status}`);
|
||||
}
|
||||
@@ -43,9 +44,20 @@ export const get_auth_status = async (): Promise<AuthStatusResponse | null> => {
|
||||
const buffer = await response.arrayBuffer();
|
||||
try {
|
||||
const response = AuthStatusResponse.decode(new Uint8Array(buffer));
|
||||
localStorage.setItem("isAdmin", String(response.isAdmin));
|
||||
return response;
|
||||
} catch (e) {
|
||||
console.error("Failed to decode auth status:", e);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
export const get_is_admin = (): boolean => {
|
||||
return localStorage.getItem("isAdmin") === "true";
|
||||
};
|
||||
|
||||
export const refresh_state = async (): Promise<void> => {
|
||||
await apiFetch("/api/refresh", {
|
||||
method: "POST",
|
||||
});
|
||||
};
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
#version 300 es
|
||||
precision highp float;
|
||||
uniform vec3 iResolution;
|
||||
uniform float iTime;
|
||||
|
||||
out vec4 FragColor;
|
||||
|
||||
#define PALETTE vec3(9,4,0)
|
||||
|
||||
void mainImage(out vec4 o, vec2 u) {
|
||||
float n, i, s, t = iTime * .2, d, v;
|
||||
vec3 q, p = iResolution, c;
|
||||
u = (u + u - p.xy) / p.y;
|
||||
vec2 l = u - (u.yx * .9 + .3 - vec2(-.35, .15));
|
||||
for(; i++ < 5e1 && d < 5e1; d += s = min(q.y = .01 + .6 * abs(24. - length(q.xy)), v = max(s, dot(abs(fract(p) - .5), vec3(.04)))), c += (1. + cos(p.z + PALETTE)) / v + d * vec3(5, 2, 1) / q.y / 1e1 + 7. * vec3(3, 4, 1) / length(l)) for(q = p = vec3(u * d, d - 16.), s = length(p) - 8., p.xy *= mat2(cos(t + p.z * .6 + vec4(0, 33, 11, 0))), p += cos(t + p.zxy) + cos(t + p.yzx * s) / s / 4., p += .5 * cos(t + dot(cos(t + p), p) * p), n = .02; n < 2.; n *= 1.6) q.y -= abs(dot(sin(4. * t + .3 * q / n), q - q + n));
|
||||
|
||||
c = mix(c, c.yzx, smoothstep(2., .1, length(u) * 1.));
|
||||
o.rgb = tanh(c * c / 6e7 / length(u - .3) + .1 * length(u));
|
||||
}
|
||||
|
||||
void main() {
|
||||
mainImage(FragColor, gl_FragCoord.xy);
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
#version 300 es
|
||||
precision highp float;
|
||||
uniform vec3 iResolution;
|
||||
uniform float iTime;
|
||||
|
||||
out vec4 FragColor;
|
||||
|
||||
#define T (iTime)
|
||||
|
||||
float orb(vec3 p) {
|
||||
// orb time
|
||||
float t = T * 4.f;
|
||||
return length(p - vec3(sin(sin(t * .2f) + t * .4f) * 6.f, 1.f + sin(sin(t * .5f) + t * .2f) * 4.f, 12.f + T + cos(t * .3f) * 8.f));
|
||||
}
|
||||
|
||||
void mainImage(out vec4 o, vec2 u) {
|
||||
float d, a, e, i, s, t = T;
|
||||
vec3 p = iResolution;
|
||||
|
||||
// scale coords
|
||||
u = (u + u - p.xy) / p.y;
|
||||
|
||||
// camera movement
|
||||
u += vec2(cos(t * .1f) * .3f, cos(t * .3f) * .1f);
|
||||
|
||||
for(o *= i; i++ < 128.f;
|
||||
|
||||
// accumulate distance
|
||||
d += s = min(.03f + .2f * abs(s), e = max(.5f * e, .01f)),
|
||||
|
||||
// grayscale color and orb light
|
||||
o += 1.f / (s + e * 3.f))
|
||||
|
||||
// noise loop start, march
|
||||
for(p = vec3(u * d, d + t), // p = ro + rd *d, p.z + t;
|
||||
|
||||
// entity (orb)
|
||||
e = orb(p) - .1f,
|
||||
|
||||
// spin by t, twist by p.z
|
||||
p.xy *= mat2(cos(.1f * t + p.z / 8.f + vec4(0, 33, 11, 0))),
|
||||
|
||||
// mirrored planes 4 units apart
|
||||
s = 4.f - abs(p.y),
|
||||
|
||||
// noise starts at .8 up to 32., grow by a+=a
|
||||
a = .8f; a < 32.f; a += a)
|
||||
|
||||
// apply turbulence
|
||||
p += cos(.7f * t + p.yzx) * .2f,
|
||||
|
||||
// apply noise
|
||||
s -= abs(dot(sin(.1f * t + p * a), .6f + p - p)) / a;
|
||||
|
||||
// tanh tonemap, brightness, light off-screen
|
||||
o = tanh(o / 1e1f);
|
||||
}
|
||||
|
||||
void main() {
|
||||
mainImage(FragColor, gl_FragCoord.xy);
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>
|
||||
|
Before Width: | Height: | Size: 4.0 KiB |
@@ -0,0 +1,375 @@
|
||||
#version 300 es
|
||||
precision highp float;
|
||||
uniform vec3 iResolution;
|
||||
uniform float iTime;
|
||||
|
||||
out vec4 FragColor;
|
||||
|
||||
// CC0: Let's self reflect
|
||||
// Always enjoyed the videos of Platonic solids with inner mirrors
|
||||
// I made some previous attempts but thought I make another attempt it
|
||||
|
||||
// Reducing the alias effects on the inner reflections turned out to be a bit tricky.
|
||||
// Simplest solution is just to run run fullscreen on a 4K screen ;)
|
||||
|
||||
// Function to generate the solid found here: https://www.shadertoy.com/view/MsKGzw
|
||||
|
||||
// Tinker with these parameters to create different solids
|
||||
// -------------------------------------------------------
|
||||
const float rotation_speed = 0.25f;
|
||||
|
||||
const float poly_U = 1.f; // [0, inf]
|
||||
const float poly_V = 0.5f; // [0, inf]
|
||||
const float poly_W = 1.0f; // [0, inf]
|
||||
const int poly_type = 5; // [2, 5]
|
||||
const float poly_zoom = 2.5f;
|
||||
|
||||
const float inner_sphere = 1.f;
|
||||
|
||||
const float refr_index = 0.9f;
|
||||
|
||||
#define MAX_BOUNCES2 6
|
||||
// -------------------------------------------------------
|
||||
|
||||
#define TIME iTime
|
||||
#define RESOLUTION iResolution
|
||||
#define PI 3.141592654
|
||||
#define TAU (2.0*PI)
|
||||
|
||||
// License: WTFPL, author: sam hocevar, found: https://stackoverflow.com/a/17897228/418488
|
||||
const vec4 hsv2rgb_K = vec4(1.0f, 2.0f / 3.0f, 1.0f / 3.0f, 3.0f);
|
||||
vec3 hsv2rgb(vec3 c) {
|
||||
vec3 p = abs(fract(c.xxx + hsv2rgb_K.xyz) * 6.0f - hsv2rgb_K.www);
|
||||
return c.z * mix(hsv2rgb_K.xxx, clamp(p - hsv2rgb_K.xxx, 0.0f, 1.0f), c.y);
|
||||
}
|
||||
// License: WTFPL, author: sam hocevar, found: https://stackoverflow.com/a/17897228/418488
|
||||
// Macro version of above to enable compile-time constants
|
||||
#define HSV2RGB(c) (c.z * mix(hsv2rgb_K.xxx, clamp(abs(fract(c.xxx + hsv2rgb_K.xyz) * 6.0 - hsv2rgb_K.www) - hsv2rgb_K.xxx, 0.0, 1.0), c.y))
|
||||
|
||||
#define TOLERANCE2 0.0005
|
||||
//#define MAX_RAY_LENGTH2 10.0
|
||||
#define MAX_RAY_MARCHES2 50
|
||||
#define NORM_OFF2 0.005
|
||||
#define BACKSTEP2
|
||||
|
||||
#define TOLERANCE3 0.0005
|
||||
#define MAX_RAY_LENGTH3 10.0
|
||||
#define MAX_RAY_MARCHES3 90
|
||||
#define NORM_OFF3 0.005
|
||||
|
||||
const vec3 rayOrigin = vec3(0.0f, 1.f, -5.f);
|
||||
const vec3 sunDir = normalize(-rayOrigin);
|
||||
|
||||
const vec3 sunCol = HSV2RGB(vec3(0.06f, 0.90f, 1E-2f)) * 1.f;
|
||||
const vec3 bottomBoxCol = HSV2RGB(vec3(0.66f, 0.80f, 0.5f)) * 1.f;
|
||||
const vec3 topBoxCol = HSV2RGB(vec3(0.60f, 0.90f, 1.f)) * 1.f;
|
||||
const vec3 glowCol0 = HSV2RGB(vec3(0.05f, 0.7f, 1E-3f)) * 1.f;
|
||||
const vec3 glowCol1 = HSV2RGB(vec3(0.95f, 0.7f, 1E-3f)) * 1.f;
|
||||
const vec3 beerCol = -HSV2RGB(vec3(0.15f + 0.5f, 0.7f, 2.f));
|
||||
const float rrefr_index = 1.f / refr_index;
|
||||
|
||||
// License: Unknown, author: knighty, found: https://www.shadertoy.com/view/MsKGzw
|
||||
const float poly_cospin = cos(PI / float(poly_type));
|
||||
const float poly_scospin = sqrt(0.75f - poly_cospin * poly_cospin);
|
||||
const vec3 poly_nc = vec3(-0.5f, -poly_cospin, poly_scospin);
|
||||
const vec3 poly_pab = vec3(0.f, 0.f, 1.f);
|
||||
const vec3 poly_pbc_ = vec3(poly_scospin, 0.f, 0.5f);
|
||||
const vec3 poly_pca_ = vec3(0.f, poly_scospin, poly_cospin);
|
||||
const vec3 poly_p = normalize((poly_U * poly_pab + poly_V * poly_pbc_ + poly_W * poly_pca_));
|
||||
const vec3 poly_pbc = normalize(poly_pbc_);
|
||||
const vec3 poly_pca = normalize(poly_pca_);
|
||||
|
||||
mat3 g_rot;
|
||||
vec2 g_gd;
|
||||
|
||||
// License: MIT, author: Inigo Quilez, found: https://iquilezles.org/articles/noacos/
|
||||
mat3 rot(vec3 d, vec3 z) {
|
||||
vec3 v = cross(z, d);
|
||||
float c = dot(z, d);
|
||||
float k = 1.0f / (1.0f + c);
|
||||
|
||||
return mat3(v.x * v.x * k + c, v.y * v.x * k - v.z, v.z * v.x * k + v.y, v.x * v.y * k + v.z, v.y * v.y * k + c, v.z * v.y * k - v.x, v.x * v.z * k - v.y, v.y * v.z * k + v.x, v.z * v.z * k + c);
|
||||
}
|
||||
|
||||
// License: Unknown, author: Matt Taylor (https://github.com/64), found: https://64.github.io/tonemapping/
|
||||
vec3 aces_approx(vec3 v) {
|
||||
v = max(v, 0.0f);
|
||||
v *= 0.6f;
|
||||
float a = 2.51f;
|
||||
float b = 0.03f;
|
||||
float c = 2.43f;
|
||||
float d = 0.59f;
|
||||
float e = 0.14f;
|
||||
return clamp((v * (a * v + b)) / (v * (c * v + d) + e), 0.0f, 1.0f);
|
||||
}
|
||||
|
||||
float sphere(vec3 p, float r) {
|
||||
return length(p) - r;
|
||||
}
|
||||
|
||||
// License: MIT, author: Inigo Quilez, found: https://iquilezles.org/articles/distfunctions/
|
||||
float box(vec2 p, vec2 b) {
|
||||
vec2 d = abs(p) - b;
|
||||
return length(max(d, 0.0f)) + min(max(d.x, d.y), 0.0f);
|
||||
}
|
||||
|
||||
// License: Unknown, author: knighty, found: https://www.shadertoy.com/view/MsKGzw
|
||||
void poly_fold(inout vec3 pos) {
|
||||
vec3 p = pos;
|
||||
|
||||
for(int i = 0; i < poly_type; ++i) {
|
||||
p.xy = abs(p.xy);
|
||||
p -= 2.f * min(0.f, dot(p, poly_nc)) * poly_nc;
|
||||
}
|
||||
|
||||
pos = p;
|
||||
}
|
||||
|
||||
float poly_plane(vec3 pos) {
|
||||
float d0 = dot(pos, poly_pab);
|
||||
float d1 = dot(pos, poly_pbc);
|
||||
float d2 = dot(pos, poly_pca);
|
||||
float d = d0;
|
||||
d = max(d, d1);
|
||||
d = max(d, d2);
|
||||
return d;
|
||||
}
|
||||
|
||||
float poly_corner(vec3 pos) {
|
||||
float d = length(pos) - .0125f;
|
||||
return d;
|
||||
}
|
||||
|
||||
float dot2(vec3 p) {
|
||||
return dot(p, p);
|
||||
}
|
||||
|
||||
float poly_edge(vec3 pos) {
|
||||
float dla = dot2(pos - min(0.f, pos.x) * vec3(1.f, 0.f, 0.f));
|
||||
float dlb = dot2(pos - min(0.f, pos.y) * vec3(0.f, 1.f, 0.f));
|
||||
float dlc = dot2(pos - min(0.f, dot(pos, poly_nc)) * poly_nc);
|
||||
return sqrt(min(min(dla, dlb), dlc)) - 2E-3f;
|
||||
}
|
||||
|
||||
vec3 shape(vec3 pos) {
|
||||
pos *= g_rot;
|
||||
pos /= poly_zoom;
|
||||
poly_fold(pos);
|
||||
pos -= poly_p;
|
||||
|
||||
return vec3(poly_plane(pos), poly_edge(pos), poly_corner(pos)) * poly_zoom;
|
||||
}
|
||||
|
||||
vec3 render0(vec3 ro, vec3 rd) {
|
||||
vec3 col = vec3(0.0f);
|
||||
|
||||
float srd = sign(rd.y);
|
||||
float tp = -(ro.y - 6.f) / abs(rd.y);
|
||||
|
||||
if(srd < 0.f) {
|
||||
col += bottomBoxCol * exp(-0.5f * (length((ro + tp * rd).xz)));
|
||||
}
|
||||
|
||||
if(srd > 0.0f) {
|
||||
vec3 pos = ro + tp * rd;
|
||||
vec2 pp = pos.xz;
|
||||
float db = box(pp, vec2(5.0f, 9.0f)) - 3.0f;
|
||||
|
||||
col += topBoxCol * rd.y * rd.y * smoothstep(0.25f, 0.0f, db);
|
||||
col += 0.2f * topBoxCol * exp(-0.5f * max(db, 0.0f));
|
||||
col += 0.05f * sqrt(topBoxCol) * max(-db, 0.0f);
|
||||
}
|
||||
|
||||
col += sunCol / (1.001f - dot(sunDir, rd));
|
||||
return col;
|
||||
}
|
||||
|
||||
float df2(vec3 p) {
|
||||
vec3 ds = shape(p);
|
||||
float d2 = ds.y - 5E-3f;
|
||||
float d0 = min(-ds.x, d2);
|
||||
float d1 = sphere(p, inner_sphere);
|
||||
g_gd = min(g_gd, vec2(d2, d1));
|
||||
float d = (min(d0, d1));
|
||||
return d;
|
||||
}
|
||||
|
||||
float rayMarch2(vec3 ro, vec3 rd, float tinit) {
|
||||
float t = tinit;
|
||||
#if defined(BACKSTEP2)
|
||||
vec2 dti = vec2(1e10f, 0.0f);
|
||||
#endif
|
||||
int i;
|
||||
for(i = 0; i < MAX_RAY_MARCHES2; ++i) {
|
||||
float d = df2(ro + rd * t);
|
||||
#if defined(BACKSTEP2)
|
||||
if(d < dti.x) {
|
||||
dti = vec2(d, t);
|
||||
}
|
||||
#endif
|
||||
// Bouncing in a closed shell, will never miss
|
||||
if(d < TOLERANCE2/* || t > MAX_RAY_LENGTH3 */) {
|
||||
break;
|
||||
}
|
||||
t += d;
|
||||
}
|
||||
#if defined(BACKSTEP2)
|
||||
if(i == MAX_RAY_MARCHES2) {
|
||||
t = dti.y;
|
||||
};
|
||||
#endif
|
||||
return t;
|
||||
}
|
||||
|
||||
vec3 normal2(vec3 pos) {
|
||||
vec2 eps = vec2(NORM_OFF2, 0.0f);
|
||||
vec3 nor;
|
||||
nor.x = df2(pos + eps.xyy) - df2(pos - eps.xyy);
|
||||
nor.y = df2(pos + eps.yxy) - df2(pos - eps.yxy);
|
||||
nor.z = df2(pos + eps.yyx) - df2(pos - eps.yyx);
|
||||
return normalize(nor);
|
||||
}
|
||||
|
||||
vec3 render2(vec3 ro, vec3 rd, float db) {
|
||||
vec3 agg = vec3(0.0f);
|
||||
float ragg = 1.f;
|
||||
float tagg = 0.f;
|
||||
|
||||
for(int bounce = 0; bounce < MAX_BOUNCES2; ++bounce) {
|
||||
if(ragg < 0.1f)
|
||||
break;
|
||||
g_gd = vec2(1E3f);
|
||||
float t2 = rayMarch2(ro, rd, min(db + 0.05f, 0.3f));
|
||||
vec2 gd2 = g_gd;
|
||||
tagg += t2;
|
||||
|
||||
vec3 p2 = ro + rd * t2;
|
||||
vec3 n2 = normal2(p2);
|
||||
vec3 r2 = reflect(rd, n2);
|
||||
vec3 rr2 = refract(rd, n2, rrefr_index);
|
||||
float fre2 = 1.f + dot(n2, rd);
|
||||
|
||||
vec3 beer = ragg * exp(0.2f * beerCol * tagg);
|
||||
agg += glowCol1 * beer * ((1.f + tagg * tagg * 4E-2f) * 6.f / max(gd2.x, 5E-4f + tagg * tagg * 2E-4f / ragg));
|
||||
vec3 ocol = 0.2f * beer * render0(p2, rr2);
|
||||
if(gd2.y <= TOLERANCE2) {
|
||||
ragg *= 1.f - 0.9f * fre2;
|
||||
} else {
|
||||
agg += ocol;
|
||||
ragg *= 0.8f;
|
||||
}
|
||||
|
||||
ro = p2;
|
||||
rd = r2;
|
||||
db = gd2.x;
|
||||
}
|
||||
|
||||
return agg;
|
||||
}
|
||||
|
||||
float df3(vec3 p) {
|
||||
vec3 ds = shape(p);
|
||||
g_gd = min(g_gd, ds.yz);
|
||||
const float sw = 0.02f;
|
||||
float d1 = min(ds.y, ds.z) - sw;
|
||||
float d0 = ds.x;
|
||||
d0 = min(d0, ds.y);
|
||||
d0 = min(d0, ds.z);
|
||||
return d0;
|
||||
}
|
||||
|
||||
float rayMarch3(vec3 ro, vec3 rd, float tinit, out int iter) {
|
||||
float t = tinit;
|
||||
int i;
|
||||
for(i = 0; i < MAX_RAY_MARCHES3; ++i) {
|
||||
float d = df3(ro + rd * t);
|
||||
if(d < TOLERANCE3 || t > MAX_RAY_LENGTH3) {
|
||||
break;
|
||||
}
|
||||
t += d;
|
||||
}
|
||||
iter = i;
|
||||
return t;
|
||||
}
|
||||
|
||||
vec3 normal3(vec3 pos) {
|
||||
vec2 eps = vec2(NORM_OFF3, 0.0f);
|
||||
vec3 nor;
|
||||
nor.x = df3(pos + eps.xyy) - df3(pos - eps.xyy);
|
||||
nor.y = df3(pos + eps.yxy) - df3(pos - eps.yxy);
|
||||
nor.z = df3(pos + eps.yyx) - df3(pos - eps.yyx);
|
||||
return normalize(nor);
|
||||
}
|
||||
|
||||
vec3 render3(vec3 ro, vec3 rd) {
|
||||
int iter;
|
||||
|
||||
vec3 skyCol = render0(ro, rd);
|
||||
vec3 col = skyCol;
|
||||
|
||||
g_gd = vec2(1E3f);
|
||||
float t1 = rayMarch3(ro, rd, 0.1f, iter);
|
||||
vec2 gd1 = g_gd;
|
||||
vec3 p1 = ro + t1 * rd;
|
||||
vec3 n1 = normal3(p1);
|
||||
vec3 r1 = reflect(rd, n1);
|
||||
vec3 rr1 = refract(rd, n1, refr_index);
|
||||
float fre1 = 1.f + dot(rd, n1);
|
||||
fre1 *= fre1;
|
||||
|
||||
float ifo = mix(0.5f, 1.f, smoothstep(1.0f, 0.9f, float(iter) / float(MAX_RAY_MARCHES3)));
|
||||
|
||||
if(t1 < MAX_RAY_LENGTH3) {
|
||||
col = render0(p1, r1) * (0.5f + 0.5f * fre1) * ifo;
|
||||
vec3 icol = render2(p1, rr1, gd1.x);
|
||||
if(gd1.x > TOLERANCE3 && gd1.y > TOLERANCE3 && rr1 != vec3(0.f)) {
|
||||
col += icol * (1.f - 0.75f * fre1) * ifo;
|
||||
}
|
||||
}
|
||||
|
||||
col += (glowCol0 + 1.f * fre1 * (glowCol0)) / max(gd1.x, 3E-4f);
|
||||
return col;
|
||||
|
||||
}
|
||||
|
||||
vec3 effect(vec2 p, vec2 pp) {
|
||||
const float fov = 2.0f;
|
||||
|
||||
const vec3 up = vec3(0.f, 1.f, 0.f);
|
||||
const vec3 la = vec3(0.0f);
|
||||
|
||||
const vec3 ww = normalize(normalize(la - rayOrigin));
|
||||
const vec3 uu = normalize(cross(up, ww));
|
||||
const vec3 vv = cross(ww, uu);
|
||||
|
||||
vec3 rd = normalize(-p.x * uu + p.y * vv + fov * ww);
|
||||
|
||||
vec3 col = vec3(0.0f);
|
||||
col = render3(rayOrigin, rd);
|
||||
|
||||
col -= 2E-2f * vec3(2.f, 3.f, 1.f) * (length(p) + 0.25f);
|
||||
col = aces_approx(col);
|
||||
col = sqrt(col);
|
||||
return col;
|
||||
}
|
||||
|
||||
void mainImage(out vec4 fragColor, in vec2 fragCoord) {
|
||||
vec2 q = fragCoord / RESOLUTION.xy;
|
||||
vec2 p = -1.f + 2.f * q;
|
||||
vec2 pp = p;
|
||||
p.x *= RESOLUTION.x / RESOLUTION.y;
|
||||
|
||||
float a = TIME * rotation_speed;
|
||||
vec3 r0 = vec3(1.0f, sin(vec2(sqrt(0.5f), 1.0f) * a));
|
||||
vec3 r1 = vec3(cos(vec2(sqrt(0.5f), 1.0f) * 0.913f * a), 1.0f);
|
||||
mat3 rot = rot(normalize(r0), normalize(r1));
|
||||
g_rot = rot;
|
||||
|
||||
vec3 col = effect(p, pp);
|
||||
|
||||
fragColor = vec4(col, 1.0f);
|
||||
}
|
||||
|
||||
void main() {
|
||||
mainImage(FragColor, gl_FragCoord.xy);
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
interface EmptyStateProps {
|
||||
icon?: string;
|
||||
title: string;
|
||||
description?: string;
|
||||
action?: ReactNode;
|
||||
}
|
||||
|
||||
export function EmptyState({ icon = "📭", title, description, action }: EmptyStateProps) {
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
padding: "3rem 2rem",
|
||||
textAlign: "center",
|
||||
background: "var(--secondary-alt-bg)",
|
||||
borderRadius: "16px",
|
||||
border: "1px dashed var(--border-color)",
|
||||
color: "var(--text-muted)"
|
||||
}}
|
||||
>
|
||||
<div style={{ fontSize: "3rem", marginBottom: "1rem" }}>{icon}</div>
|
||||
<h3 style={{ margin: "0 0 0.5rem 0", color: "var(--text-color)" }}>{title}</h3>
|
||||
{description && <p style={{ margin: "0 0 1.5rem 0", fontSize: "0.95rem" }}>{description}</p>}
|
||||
{action}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function LoadingState({ message = "Loading..." }: { message?: string }) {
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
padding: "3rem 2rem",
|
||||
textAlign: "center"
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
width: "40px",
|
||||
height: "40px",
|
||||
border: "4px solid rgba(255, 255, 255, 0.2)",
|
||||
borderTopColor: "currentColor",
|
||||
borderRadius: "50%",
|
||||
animation: "spin 0.8s linear infinite",
|
||||
margin: "0 auto 1rem"
|
||||
}}
|
||||
></div>
|
||||
<p style={{ color: "var(--text-muted)", margin: 0 }}>{message}</p>
|
||||
<style>{`
|
||||
@keyframes spin {
|
||||
to { transform: rotate(360deg); }
|
||||
}
|
||||
`}</style>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorState({ message, onRetry }: { message: string, onRetry?: () => void }) {
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
padding: "3rem 2rem",
|
||||
textAlign: "center",
|
||||
background: "rgba(244, 67, 54, 0.1)",
|
||||
borderRadius: "16px",
|
||||
border: "1px solid rgba(244, 67, 54, 0.3)"
|
||||
}}
|
||||
>
|
||||
<div style={{ fontSize: "3rem", marginBottom: "1rem" }}>⚠️</div>
|
||||
<h3 style={{ margin: "0 0 0.5rem 0", color: "var(--text-color)" }}>Something went wrong</h3>
|
||||
<p style={{ margin: "0 0 1.5rem 0", color: "var(--text-muted)", fontSize: "0.95rem" }}>{message}</p>
|
||||
{onRetry && (
|
||||
<button
|
||||
onClick={onRetry}
|
||||
style={{
|
||||
background: "var(--accent-color)",
|
||||
border: "none",
|
||||
padding: "0.75rem 1.5rem",
|
||||
borderRadius: "8px",
|
||||
color: "white",
|
||||
fontWeight: 600,
|
||||
cursor: "pointer"
|
||||
}}
|
||||
>
|
||||
🔄 Try Again
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
import { Link } from "react-router-dom";
|
||||
import { GameImage } from "../GameImage";
|
||||
import { EmptyState } from "./EmptyState";
|
||||
import { Game as GameProto } from "../../items";
|
||||
|
||||
interface FilteredGamesListProps {
|
||||
filteredGames: string[];
|
||||
gameToPositive: Map<string, Set<string>>;
|
||||
selectedPeopleCount: number;
|
||||
games: Map<string, GameProto>;
|
||||
}
|
||||
|
||||
export function FilteredGamesList({
|
||||
filteredGames,
|
||||
gameToPositive,
|
||||
selectedPeopleCount,
|
||||
games,
|
||||
}: FilteredGamesListProps) {
|
||||
if (selectedPeopleCount === 0) {
|
||||
return (
|
||||
<EmptyState
|
||||
icon="👥"
|
||||
title="Select people to find games"
|
||||
description="Choose one or more people from the list above to see games they would play"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h3>Games Everyone Would Play ({filteredGames.length})</h3>
|
||||
{filteredGames.length > 0 ? (
|
||||
<ul className="grid-container">
|
||||
{filteredGames.map((game) => {
|
||||
const positiveCount = gameToPositive.get(game)?.size || 0;
|
||||
const neutralCount = selectedPeopleCount - positiveCount;
|
||||
const gameData = games.get(game);
|
||||
if (!gameData) {
|
||||
console.error("no data", game);
|
||||
return null;
|
||||
}
|
||||
const price = gameData.price;
|
||||
|
||||
return (
|
||||
<Link
|
||||
to={`/game/${encodeURIComponent(game)}`}
|
||||
key={game}
|
||||
className="list-item game-entry"
|
||||
style={{
|
||||
textDecoration: "none",
|
||||
color: "inherit",
|
||||
display: "flex",
|
||||
justifyContent: "space-between",
|
||||
alignItems: "center",
|
||||
}}
|
||||
>
|
||||
<div>
|
||||
<strong>{game}</strong>
|
||||
<div
|
||||
style={{
|
||||
fontSize: "0.9em",
|
||||
color: "#4caf50",
|
||||
marginTop: "0.5rem",
|
||||
}}
|
||||
>
|
||||
<span>✓</span> {positiveCount} selected would play
|
||||
</div>
|
||||
{neutralCount > 0 && (
|
||||
<div
|
||||
style={{
|
||||
fontSize: "0.9em",
|
||||
color: "#d4d400",
|
||||
marginTop: "0.3rem",
|
||||
}}
|
||||
>
|
||||
<span>?</span> {neutralCount}{" "}
|
||||
{neutralCount > 1 ? "are" : "is"} neutral
|
||||
</div>
|
||||
)}
|
||||
<div
|
||||
className="price-badge"
|
||||
style={{
|
||||
fontSize: "0.85em",
|
||||
marginTop: "0.5rem",
|
||||
padding: "0.2rem 0.6rem",
|
||||
borderRadius: "4px",
|
||||
display: "inline-block",
|
||||
backgroundColor:
|
||||
price === 0
|
||||
? "rgba(76, 175, 80, 0.2)"
|
||||
: "rgba(255, 152, 0, 0.2)",
|
||||
color: price === 0 ? "#4caf50" : "#ff9800",
|
||||
fontWeight: 600,
|
||||
}}
|
||||
>
|
||||
{price === 0 ? "0€ (Free)" : `${price}€`}
|
||||
</div>
|
||||
</div>
|
||||
<GameImage game={game} />
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
) : (
|
||||
<EmptyState
|
||||
icon="🔍"
|
||||
title="No games found"
|
||||
description="Try selecting fewer people or adding more opinions"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
export function LoadingSpinner({ size = "medium", text }: { size?: "small" | "medium" | "large", text?: string }) {
|
||||
const sizeMap = {
|
||||
small: "16px",
|
||||
medium: "24px",
|
||||
large: "32px"
|
||||
};
|
||||
|
||||
return (
|
||||
<div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: "1rem" }}>
|
||||
<div
|
||||
style={{
|
||||
width: sizeMap[size],
|
||||
height: sizeMap[size],
|
||||
border: `${parseInt(sizeMap[size]) / 4}px solid rgba(255, 255, 255, 0.2)`,
|
||||
borderTopColor: "currentColor",
|
||||
borderRadius: "50%",
|
||||
animation: "spin 0.8s linear infinite"
|
||||
}}
|
||||
></div>
|
||||
{text && <span style={{ color: "var(--text-muted)", fontSize: "0.9rem" }}>{text}</span>}
|
||||
<style>{`
|
||||
@keyframes spin {
|
||||
to { transform: rotate(360deg); }
|
||||
}
|
||||
`}</style>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { Person } from "../../items";
|
||||
|
||||
interface PersonSelectorProps {
|
||||
people: Person[];
|
||||
selectedPeople: Set<string>;
|
||||
onTogglePerson: (name: string) => void;
|
||||
}
|
||||
|
||||
export function PersonSelector({
|
||||
people,
|
||||
selectedPeople,
|
||||
onTogglePerson,
|
||||
}: PersonSelectorProps) {
|
||||
return (
|
||||
<div style={{ marginBottom: "3rem" }}>
|
||||
<h3>Select People</h3>
|
||||
<div
|
||||
className="grid-container"
|
||||
style={{
|
||||
display: "flex",
|
||||
flexWrap: "wrap",
|
||||
gap: "1rem",
|
||||
justifyContent: "center",
|
||||
}}
|
||||
>
|
||||
{people.map((person) => (
|
||||
<div
|
||||
key={person.name}
|
||||
className="list-item gamefilter-entry"
|
||||
style={{
|
||||
borderColor: selectedPeople.has(person.name)
|
||||
? "var(--accent-color)"
|
||||
: "var(--border-color)",
|
||||
cursor: "pointer",
|
||||
}}
|
||||
onClick={() => onTogglePerson(person.name)}
|
||||
>
|
||||
<div style={{ gap: "0.5rem" }}>
|
||||
<strong>{person.name}</strong>
|
||||
</div>
|
||||
<div
|
||||
style={{
|
||||
fontSize: "0.9em",
|
||||
color: "var(--text-muted)",
|
||||
marginTop: "0.5rem",
|
||||
}}
|
||||
>
|
||||
{person.opinion.length} opinion(s)
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
export function SkeletonLoader({ width, height, count = 1 }: { width?: string | number, height?: string | number, count?: number }) {
|
||||
return (
|
||||
<>
|
||||
{Array.from({ length: count }).map((_, i) => (
|
||||
<div
|
||||
key={i}
|
||||
style={{
|
||||
width: width || "100%",
|
||||
height: height || "60px",
|
||||
backgroundColor: "var(--secondary-alt-bg)",
|
||||
borderRadius: "8px",
|
||||
animation: "shimmer 1.5s infinite",
|
||||
marginBottom: count > 1 ? "1rem" : undefined
|
||||
}}
|
||||
></div>
|
||||
))}
|
||||
<style>{`
|
||||
@keyframes shimmer {
|
||||
0%, 100% { opacity: 0.5; }
|
||||
50% { opacity: 1; }
|
||||
}
|
||||
`}</style>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function CardSkeleton() {
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
backgroundColor: "var(--secondary-alt-bg)",
|
||||
border: "1px solid var(--border-color)",
|
||||
borderRadius: "5px",
|
||||
padding: "10px",
|
||||
minHeight: "80px"
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
width: "60%",
|
||||
height: "20px",
|
||||
backgroundColor: "var(--tertiary-bg)",
|
||||
borderRadius: "4px",
|
||||
marginBottom: "0.5rem",
|
||||
animation: "shimmer 1.5s infinite"
|
||||
}}
|
||||
></div>
|
||||
<div
|
||||
style={{
|
||||
width: "40%",
|
||||
height: "16px",
|
||||
backgroundColor: "var(--tertiary-bg)",
|
||||
borderRadius: "4px",
|
||||
animation: "shimmer 1.5s infinite 0.2s"
|
||||
}}
|
||||
></div>
|
||||
<style>{`
|
||||
@keyframes shimmer {
|
||||
0%, 100% { opacity: 0.5; }
|
||||
50% { opacity: 1; }
|
||||
}
|
||||
`}</style>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
import { useState, useEffect, useRef, useMemo } from "react";
|
||||
import {
|
||||
Person,
|
||||
Game as GameProto,
|
||||
GetGameInfoRequest,
|
||||
GameInfoResponse,
|
||||
} from "../../items";
|
||||
import { apiFetch } from "../api";
|
||||
|
||||
export function useGameFilter(
|
||||
people: Person[],
|
||||
selectedPeople: Set<string>,
|
||||
freeGamesOnly: boolean,
|
||||
maxPrice: number | null,
|
||||
ownershipMode: boolean
|
||||
) {
|
||||
const [fetchedTitles, setFetchedTitles] = useState<string[]>([]);
|
||||
const metaDataRef = useRef<{ [key: string]: GameProto }>({});
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
metaDataRef.current = {};
|
||||
};
|
||||
}, []);
|
||||
|
||||
const { gameToNegative, gameToPositiveOpinion } = useMemo(() => {
|
||||
const gameToNegative = new Map<string, Set<string>>();
|
||||
const gameToPositiveOpinion = new Map<string, Set<string>>();
|
||||
|
||||
if (selectedPeople.size === 0)
|
||||
return { gameToNegative, gameToPositiveOpinion };
|
||||
|
||||
const selectedPersons = people.filter((p) => selectedPeople.has(p.name));
|
||||
selectedPersons.forEach((person) => {
|
||||
person.opinion.forEach((op) => {
|
||||
if (!gameToNegative.has(op.title))
|
||||
gameToNegative.set(op.title, new Set());
|
||||
if (!gameToPositiveOpinion.has(op.title))
|
||||
gameToPositiveOpinion.set(op.title, new Set());
|
||||
|
||||
if (!op.wouldPlay) {
|
||||
gameToNegative.get(op.title)!.add(person.name);
|
||||
} else {
|
||||
gameToPositiveOpinion.get(op.title)!.add(person.name);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
return { gameToNegative, gameToPositiveOpinion };
|
||||
}, [people, selectedPeople]);
|
||||
|
||||
const titlesEveryoneWouldPlay = useMemo(() => {
|
||||
return Array.from(gameToNegative.entries())
|
||||
.filter(([, players]) => players.size === 0)
|
||||
.map(([game]) => game);
|
||||
}, [gameToNegative]);
|
||||
|
||||
useEffect(() => {
|
||||
const titlesToFetch = titlesEveryoneWouldPlay.filter(
|
||||
(title) => !metaDataRef.current[title]
|
||||
);
|
||||
if (titlesToFetch.length === 0) return;
|
||||
|
||||
const gamesToFetch = GetGameInfoRequest.encode(
|
||||
GetGameInfoRequest.create({
|
||||
games: titlesToFetch,
|
||||
})
|
||||
).finish();
|
||||
|
||||
apiFetch("/api/games/batch", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/octet-stream" },
|
||||
body: gamesToFetch,
|
||||
})
|
||||
.then((res) => res.arrayBuffer())
|
||||
.then((buffer) => {
|
||||
const list = GameInfoResponse.decode(new Uint8Array(buffer));
|
||||
list.games.forEach((game) => {
|
||||
metaDataRef.current[game.title] = game;
|
||||
});
|
||||
// Trigger a re-render to update filteredGames
|
||||
setFetchedTitles([...titlesToFetch]);
|
||||
})
|
||||
.catch((err) => console.error("Failed to fetch game metadata:", err));
|
||||
}, [titlesEveryoneWouldPlay]);
|
||||
|
||||
const filteredGames = useMemo(() => {
|
||||
if (selectedPeople.size === 0) return [];
|
||||
|
||||
const games = titlesEveryoneWouldPlay
|
||||
.filter((title) => metaDataRef.current[title])
|
||||
.map((title) => metaDataRef.current[title]);
|
||||
|
||||
return filterGames(
|
||||
games,
|
||||
selectedPeople.size,
|
||||
freeGamesOnly,
|
||||
maxPrice,
|
||||
ownershipMode,
|
||||
selectedPeople,
|
||||
people
|
||||
);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [
|
||||
titlesEveryoneWouldPlay,
|
||||
selectedPeople.size,
|
||||
fetchedTitles,
|
||||
freeGamesOnly,
|
||||
maxPrice,
|
||||
ownershipMode,
|
||||
people,
|
||||
selectedPeople,
|
||||
]);
|
||||
|
||||
const gamesMap = new Map(Object.entries(metaDataRef.current));
|
||||
|
||||
return { filteredGames, gameToPositive: gameToPositiveOpinion, games: gamesMap };
|
||||
}
|
||||
|
||||
function filterGames(
|
||||
games: GameProto[],
|
||||
playerCount: number,
|
||||
freeGamesOnly: boolean,
|
||||
maxPrice: number | null,
|
||||
ownershipMode: boolean,
|
||||
selectedPeople: Set<string>,
|
||||
people: Person[]
|
||||
): string[] {
|
||||
const selectedPersons = people.filter((p) => selectedPeople.has(p.name));
|
||||
|
||||
return games
|
||||
.filter(
|
||||
(game) => game.maxPlayers >= playerCount && game.minPlayers <= playerCount
|
||||
)
|
||||
.filter((game) => {
|
||||
if (freeGamesOnly) return game.price === 0;
|
||||
if (maxPrice !== null) return game.price <= maxPrice;
|
||||
return true;
|
||||
})
|
||||
.filter((game) => {
|
||||
if (!ownershipMode) return true;
|
||||
if (game.price === 0) return true;
|
||||
|
||||
return selectedPersons.every((person) =>
|
||||
person.opinion.some(
|
||||
(op) => op.title === game.title && op.wouldPlay
|
||||
)
|
||||
);
|
||||
})
|
||||
.map((game) => game.title);
|
||||
}
|
||||
+53
-22
@@ -1,15 +1,21 @@
|
||||
:root {
|
||||
--primary-bg: #23283d;
|
||||
--secondary-bg: #1e2233;
|
||||
--secondary-alt-bg: #191f2e;
|
||||
--tertiary-bg: #101320;
|
||||
--accent-color: #096dc0;
|
||||
--secondary-accent: #0a4f8c;
|
||||
--primary-bg-rgb: 35 40 61;
|
||||
--secondary-bg-rgb: 30 34 51;
|
||||
--secondary-alt-bg-rgb: 25 31 46;
|
||||
--tertiary-bg-rgb: 16 19 32;
|
||||
--accent-color-rgb: 9 109 192;
|
||||
--secondary-accent-rgb: 10 79 140;
|
||||
--border-color-rgb: 42 48 69;
|
||||
--text-color: #ffffff;
|
||||
--text-muted: #a0a0a0;
|
||||
--border-color: #2a3045;
|
||||
|
||||
font-family: 'Inter', system-ui, Avenir, Helvetica, Arial, sans-serif;
|
||||
--primary-bg: rgb(var(--primary-bg-rgb));
|
||||
--secondary-bg: rgb(var(--secondary-bg-rgb));
|
||||
--secondary-alt-bg: rgb(var(--tertiary-bg-rgb));
|
||||
--tertiary-bg: rgb(var(--border-color-rgb));
|
||||
--border-color: rgb(var(--border-color-rgb));
|
||||
|
||||
font-family: "Inter", system-ui, Avenir, Helvetica, Arial, sans-serif;
|
||||
line-height: 1.6;
|
||||
font-weight: 400;
|
||||
|
||||
@@ -32,7 +38,12 @@ body {
|
||||
background-color: var(--primary-bg);
|
||||
}
|
||||
|
||||
h1, h2, h3, h4, h5, h6 {
|
||||
h1,
|
||||
h2,
|
||||
h3,
|
||||
h4,
|
||||
h5,
|
||||
h6 {
|
||||
color: var(--text-color);
|
||||
margin-top: 0;
|
||||
}
|
||||
@@ -74,7 +85,8 @@ button:focus-visible {
|
||||
outline: 4px auto -webkit-focus-ring-color;
|
||||
}
|
||||
|
||||
input, select {
|
||||
input,
|
||||
select {
|
||||
background-color: var(--secondary-alt-bg);
|
||||
border: 1px solid var(--border-color);
|
||||
color: var(--text-color);
|
||||
@@ -82,13 +94,20 @@ input, select {
|
||||
border-radius: 6px;
|
||||
font-size: 1em;
|
||||
font-family: inherit;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
input:focus, select:focus {
|
||||
outline: 2px solid var(--accent-color);
|
||||
border-color: transparent;
|
||||
input:focus,
|
||||
select:focus {
|
||||
outline: none;
|
||||
border-color: var(--accent-color);
|
||||
box-shadow: 0 0 0 2px rgb(9, 109, 192, 0.2);
|
||||
}
|
||||
|
||||
* {
|
||||
transition: background-color 0.3s ease, border-color 0.3s ease,
|
||||
color 0.3s ease, box-shadow 0.3s ease;
|
||||
}
|
||||
|
||||
ul {
|
||||
list-style: none;
|
||||
@@ -97,15 +116,27 @@ ul {
|
||||
|
||||
.shader-theme {
|
||||
--primary-bg: transparent; /* Let the shader show through */
|
||||
--secondary-bg: rgba(0, 0, 0, 0.7); /* Translucent cards */
|
||||
--secondary-alt-bg: rgba(20, 20, 20, 0.6); /* Translucent inputs */
|
||||
--tertiary-bg: rgba(40, 40, 40, 0.8);
|
||||
--border-color: rgba(255, 255, 255, 0.15);
|
||||
--text-color: #ffffff;
|
||||
--accent-color: #121212;
|
||||
--secondary-accent: #212121;
|
||||
--secondary-bg: rgb(var(--secondary-bg-rgb) / 0.7); /* Translucent cards */
|
||||
--secondary-alt-bg: rgb(
|
||||
var(--secondary-alt-bg-rgb) / 0.6
|
||||
); /* Translucent inputs */
|
||||
--tertiary-bg: rgb(var(--tertiary-bg-rgb) / 0.8);
|
||||
--border-color: rgb(var(--border-color-rgb) / 0.15);
|
||||
}
|
||||
|
||||
.shader-theme body {
|
||||
background-color: transparent;
|
||||
.black-theme {
|
||||
--primary-bg: transparent; /* Let the shader show through */
|
||||
--secondary-bg: rgb(0, 0, 0, 0.7); /* Translucent cards */
|
||||
--secondary-alt-bg: rgb(20, 20, 20, 0.6); /* Translucent inputs */
|
||||
--tertiary-bg: rgb(40, 40, 40, 0.8);
|
||||
--text-color: #ffffff;
|
||||
--accent-color: #FF9500;
|
||||
--secondary-accent: #FF6B00;
|
||||
}
|
||||
|
||||
.sakura-theme {
|
||||
--border-color: #DCABDF;
|
||||
--text-color: #CFB3CD;
|
||||
--accent-color: #F48FB1;
|
||||
--secondary-accent: #880E4F;
|
||||
}
|
||||
@@ -2,9 +2,12 @@ import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import './index.css'
|
||||
import App from './App.tsx'
|
||||
import { ErrorBoundary } from './ErrorBoundary'
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
<ErrorBoundary>
|
||||
<App />
|
||||
</ErrorBoundary>
|
||||
</StrictMode>,
|
||||
)
|
||||
|
||||
+32
-15
@@ -3,31 +3,32 @@ syntax = "proto3";
|
||||
package items;
|
||||
|
||||
message Person {
|
||||
string name = 1;
|
||||
string name = 1;
|
||||
repeated Opinion opinion = 2;
|
||||
}
|
||||
|
||||
message Opinion {
|
||||
string title = 1;
|
||||
bool would_play = 2;
|
||||
string title = 1;
|
||||
bool would_play = 2;
|
||||
}
|
||||
|
||||
message Game {
|
||||
reserved 3;
|
||||
string title = 1;
|
||||
Source source = 2;
|
||||
string title = 1;
|
||||
Source source = 2;
|
||||
uint32 min_players = 4;
|
||||
uint32 max_players = 5;
|
||||
uint32 price = 6;
|
||||
uint64 remote_id = 7;
|
||||
uint32 price = 6;
|
||||
uint64 remote_id = 7;
|
||||
}
|
||||
|
||||
enum Source {
|
||||
STEAM = 0;
|
||||
STEAM = 0;
|
||||
ROBLOX = 1;
|
||||
}
|
||||
|
||||
message PersonList { repeated Person person = 1; }
|
||||
|
||||
message GameList { repeated Game games = 1; }
|
||||
|
||||
// Authentication messages
|
||||
@@ -37,24 +38,30 @@ message LoginRequest {
|
||||
}
|
||||
|
||||
message LoginResponse {
|
||||
string token = 1;
|
||||
bool success = 2;
|
||||
string token = 1;
|
||||
bool success = 2;
|
||||
string message = 3;
|
||||
}
|
||||
|
||||
message LogoutRequest { string token = 1; }
|
||||
|
||||
message LogoutResponse {
|
||||
bool success = 1;
|
||||
bool success = 1;
|
||||
string message = 2;
|
||||
}
|
||||
|
||||
message RefreshResponse {
|
||||
bool success = 1;
|
||||
string message = 2;
|
||||
}
|
||||
|
||||
message AuthStatusRequest { string token = 1; }
|
||||
|
||||
message AuthStatusResponse {
|
||||
bool authenticated = 1;
|
||||
string username = 2;
|
||||
string message = 3;
|
||||
bool authenticated = 1;
|
||||
string username = 2;
|
||||
string message = 3;
|
||||
bool isAdmin = 4;
|
||||
}
|
||||
|
||||
// Authentication service
|
||||
@@ -65,18 +72,28 @@ service AuthService {
|
||||
}
|
||||
|
||||
message GameRequest { string title = 1; }
|
||||
|
||||
message GetGamesRequest {}
|
||||
|
||||
message AddOpinionRequest {
|
||||
string game_title = 1;
|
||||
bool would_play = 2;
|
||||
bool would_play = 2;
|
||||
}
|
||||
|
||||
message RemoveOpinionRequest { string game_title = 1; }
|
||||
|
||||
message GetGameInfoRequest {
|
||||
repeated string games = 1;
|
||||
}
|
||||
|
||||
message GameInfoResponse {
|
||||
repeated Game games = 1;
|
||||
}
|
||||
|
||||
service MainService {
|
||||
rpc GetGame(GameRequest) returns (Game);
|
||||
rpc GetGames(GetGamesRequest) returns (GameList);
|
||||
rpc AddGame(Game) returns (Game);
|
||||
rpc AddOpinion(AddOpinionRequest) returns (Person);
|
||||
rpc GetGameInfo(GetGameInfoRequest) returns (GameInfoResponse);
|
||||
}
|
||||
+988
-988
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user