From 400d772cc391d979747510776fa8acfb5a1d00cb Mon Sep 17 00:00:00 2001 From: Pinapelz Date: Sat, 5 Jul 2025 21:42:22 -0700 Subject: implement generic score viewer and import deduplication --- frontend/src/App.tsx | 16 +- frontend/src/components/NavBar.tsx | 90 +++++ frontend/src/components/SessionExpiredPopup.tsx | 32 ++ .../src/components/tables/GenericScoreTable.tsx | 421 +++++++++++++++++++++ frontend/src/pages/Home.tsx | 122 +++--- frontend/src/pages/Import.tsx | 200 +++++----- frontend/src/pages/Score.tsx | 174 +++++++++ 7 files changed, 870 insertions(+), 185 deletions(-) create mode 100644 frontend/src/components/NavBar.tsx create mode 100644 frontend/src/components/SessionExpiredPopup.tsx create mode 100644 frontend/src/components/tables/GenericScoreTable.tsx create mode 100644 frontend/src/pages/Score.tsx (limited to 'frontend') diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 65f3355..f6fffca 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -1,10 +1,11 @@ -import { Routes, Route } from 'react-router'; -import { AuthProvider } from './contexts/AuthContext'; -import Landing from './pages/Landing'; -import Login from './pages/Login'; -import Register from './pages/Register'; -import Import from './pages/Import'; -import Home from './pages/Home'; +import { Routes, Route } from "react-router"; +import { AuthProvider } from "./contexts/AuthContext"; +import Landing from "./pages/Landing"; +import Login from "./pages/Login"; +import Register from "./pages/Register"; +import Import from "./pages/Import"; +import Home from "./pages/Home"; +import Score from "./pages/Score"; function App() { return ( @@ -15,6 +16,7 @@ function App() { } /> } /> } /> + } /> ); diff --git a/frontend/src/components/NavBar.tsx b/frontend/src/components/NavBar.tsx new file mode 100644 index 0000000..7e111d0 --- /dev/null +++ b/frontend/src/components/NavBar.tsx @@ -0,0 +1,90 @@ +import { Link } from "react-router"; + +export const NavBar = ({ currentPage, user, handleLogout }: { + currentPage: string; + user: { username: string }; + handleLogout: () => void; +}) => { + const getMenuOptions = () => { + switch (currentPage) { + case 'dashboard': + return ( + <> + + Import Data + + + ); + case 'import': + return ( + <> + + Home + + + ); + case 'score': + return ( + <> + + Home + + + Import Data + + + ); + default: + return ( + + Import Data + + ); + } + }; + + return ( + + ); +}; diff --git a/frontend/src/components/SessionExpiredPopup.tsx b/frontend/src/components/SessionExpiredPopup.tsx new file mode 100644 index 0000000..625d97d --- /dev/null +++ b/frontend/src/components/SessionExpiredPopup.tsx @@ -0,0 +1,32 @@ +import { Link } from "react-router"; + +export default function SessionExpiredPopup() { + return ( +
+
+
+

+ Session Expired +

+

+ Please sign in to import your data. +

+
+ + Sign In + + + Back to Home + +
+
+
+
+ ); +} diff --git a/frontend/src/components/tables/GenericScoreTable.tsx b/frontend/src/components/tables/GenericScoreTable.tsx new file mode 100644 index 0000000..f82e1ff --- /dev/null +++ b/frontend/src/components/tables/GenericScoreTable.tsx @@ -0,0 +1,421 @@ +import React from "react"; + +interface Score { + [key: string]: any; + timestamp: string | number; +} + +interface ScoreDisplayProps { + scores: Score[]; + viewMode: "cards" | "table"; + sortField: string; + sortDirection: "asc" | "desc"; + onSort: (field: string) => void; +} + +const ScoreDisplay: React.FC = ({ + scores, + viewMode, + sortField, + sortDirection, + onSort, +}) => { + // Key mappings for better display names. Hit or miss + const keyDisplayNames: Record = { + title: "Title", + artist: "Artist", + score: "Score", + difficulty: "Difficulty", + lamp: "Lamp", + diff_lamp: "Lamp", + timestamp: "Date", + judgements: "Judgements", + maxCombo: "Max Combo", + perfect: "Perfect", + great: "Great", + good: "Good", + bad: "Bad", + miss: "Miss", + rating: "Rating", + percent: "Percent", + chart: "Chart", + song: "Song", + ranking: "Ranking", + combo: "Combo", + grade: "Grade", + level: "Level", + bpm: "BPM", + notes: "Notes", + duration: "Duration", + playcount: "Play Count", + date: "Date", + time: "Time", + }; + + const skipKeys = [ + "id", + "internalname", + "internalName", + "gameInternalName", + "userId", + ]; + const primaryKeys = ["title", "artist", "song"]; + const mainStatKeys = [ + "score", + "difficulty", + "lamp", + "diff_lamp", + "percent", + "rating", + "grade", + ]; + const expandableKeys = ["judgements", "optional"]; + + const formatValue = (value: any, key: string): string => { + if (value === null || value === undefined) return "N/A"; + + // Handle timestamps + if (key === "timestamp" || key === "date") { + const date = new Date(typeof value === "number" ? value : value); + return date.toLocaleDateString(); + } + + if (typeof value === "number") { + if (key === "score" || key === "maxCombo" || key === "combo") { + return value.toLocaleString(); + } + return value.toString(); + } + if (typeof value === "boolean") { + return value ? "Yes" : "No"; + } + + if (Array.isArray(value)) { + return value.join(", "); + } + + return String(value); + }; + + const getDisplayName = (key: string): string => { + return keyDisplayNames[key] || key.charAt(0).toUpperCase() + key.slice(1); + }; + + const renderValue = ( + value: any, + key: string, + compact: boolean = false, + ): JSX.Element => { + if (value === null || value === undefined) + return N/A; + + // Handle judgements specially + if (key === "judgements" && typeof value === "object") { + const judgementEntries = Object.entries(value); + + if (compact) { + return ( +
+ {judgementEntries.map(([jKey, jValue]) => ( +
+ + {getDisplayName(jKey)}: + + {formatValue(jValue, jKey)} +
+ ))} +
+ ); + } + + return ( +
+ {judgementEntries.map(([jKey, jValue]) => ( + + {getDisplayName(jKey)}:{" "} + {formatValue(jValue, jKey)} + + ))} +
+ ); + } + + if (typeof value === "object" && !Array.isArray(value)) { + return ( +
+ {Object.entries(value).map(([subKey, subValue]) => ( +
+ {getDisplayName(subKey)}: + + {formatValue(subValue, subKey)} + +
+ ))} +
+ ); + } + + return {formatValue(value, key)}; + }; + + const getScoreEntries = (score: Score) => { + const entries = Object.entries(score).filter( + ([key]) => !skipKeys.includes(key), + ); + + const primary = entries.filter(([key]) => primaryKeys.includes(key)); + const mainStats = entries.filter(([key]) => mainStatKeys.includes(key)); + const expandable = entries.filter(([key]) => expandableKeys.includes(key)); + const others = entries.filter( + ([key]) => + !primaryKeys.includes(key) && + !mainStatKeys.includes(key) && + !expandableKeys.includes(key) && + key !== "timestamp", + ); + + return { + primary, + mainStats, + expandable, + others, + timestamp: score.timestamp, + }; + }; + + const SortIcon = ({ field }: { field: string }) => { + if (sortField !== field) { + return ; + } + return sortDirection === "asc" ? ( + + ) : ( + + ); + }; + + const sortedScores = [...scores].sort((a, b) => { + const aVal = a[sortField]; + const bVal = b[sortField]; + + if (aVal === undefined || aVal === null) return 1; + if (bVal === undefined || bVal === null) return -1; + + let comparison = 0; + + if (typeof aVal === "string" && typeof bVal === "string") { + comparison = aVal.localeCompare(bVal); + } else if (typeof aVal === "number" && typeof bVal === "number") { + comparison = aVal - bVal; + } else if (aVal instanceof Date && bVal instanceof Date) { + comparison = aVal.getTime() - bVal.getTime(); + } else { + comparison = String(aVal).localeCompare(String(bVal)); + } + + return sortDirection === "asc" ? comparison : -comparison; + }); + + // Get all possible keys for table headers + const allKeys = Array.from( + new Set(scores.flatMap((score) => Object.keys(score))), + ).filter((key) => !skipKeys.includes(key)); + + // Prioritize important keys for table display + const tableKeys = [ + "title", + "song", + "artist", + "score", + "difficulty", + "lamp", + "diff_lamp", + "rating", + "percent", + "grade", + "judgements", + "maxCombo", + "combo", + "timestamp", + ].filter((key) => allKeys.includes(key)); + + if (scores.length === 0) { + return ( +
+
+ 🎵 +
+

+ No scores found +

+

Import some score data to get started!

+
+ ); + } + + if (viewMode === "cards") { + return ( +
+ {sortedScores.map((score, index) => { + const { primary, mainStats, expandable, others, timestamp } = + getScoreEntries(score); + + return ( +
+ {/* Primary Info */} +
+
+

+ {score.title || score.song || "Unknown Title"} +

+ {score.artist && ( +

+ {score.artist} +

+ )} +
+
+ + {/* Main Stats */} + {mainStats.length > 0 && ( +
+ {mainStats.slice(0, 4).map(([key, value]) => ( +
+

+ {getDisplayName(key)} +

+

+ {renderValue(value, key)} +

+
+ ))} +
+ )} + + {/* Expandable sections (judgements, optional) */} + {expandable.map(([key, value]) => ( +
+

+ {getDisplayName(key)} +

+ {renderValue(value, key)} +
+ ))} + + {/* Other fields */} + {others.length > 0 && ( +
+
+ {others.map(([key, value]) => ( +
+ + {getDisplayName(key)}: + + + {renderValue(value, key)} + +
+ ))} +
+
+ )} + + {/* Timestamp */} +
+

+ {new Date( + typeof timestamp === "number" ? timestamp : timestamp, + ).toLocaleDateString()}{" "} + •{" "} + {new Date( + typeof timestamp === "number" ? timestamp : timestamp, + ).toLocaleTimeString([], { + hour: "2-digit", + minute: "2-digit", + })} +

+
+
+ ); + })} +
+ ); + } + + return ( +
+
+ + + + {tableKeys.map((key) => ( + + ))} + + + + {sortedScores.map((score, index) => ( + + {tableKeys.map((key) => ( + + ))} + + ))} + +
+ {key === "judgements" ? ( + {getDisplayName(key)} + ) : ( + + )} +
+ {key === "lamp" || key === "diff_lamp" ? ( +
+ + {score[key] || "No Clear"} + +
+ ) : key === "judgements" ? ( +
+ {renderValue(score[key], key, true)} +
+ ) : key === "timestamp" ? ( + + {new Date( + typeof score[key] === "number" + ? score[key] + : score[key], + ).toLocaleDateString()} + + ) : ( + + {renderValue(score[key], key)} + + )} +
+
+
+ ); +}; + +export default ScoreDisplay; diff --git a/frontend/src/pages/Home.tsx b/frontend/src/pages/Home.tsx index 0ee6862..0aba7f0 100644 --- a/frontend/src/pages/Home.tsx +++ b/frontend/src/pages/Home.tsx @@ -1,9 +1,11 @@ -import { Link, useNavigate } from 'react-router'; -import { useAuth } from '../contexts/AuthContext'; -import type { SupportedGame } from '../types/game'; -import { useState, useEffect } from 'react'; +import { useNavigate } from "react-router"; +import { NavBar } from "../components/NavBar"; +import { useAuth } from "../contexts/AuthContext"; +import type { SupportedGame } from "../types/game"; +import SessionExpiredPopup from "../components/SessionExpiredPopup"; +import { useState, useEffect } from "react"; -import dancerushImage from '../assets/games/dancerush.webp'; +import dancerushImage from "../assets/games/dancerush.webp"; const Home = () => { const { user, isLoading, logout } = useAuth(); @@ -14,36 +16,38 @@ const Home = () => { const handleLogout = async () => { try { await logout(); - navigate('/'); + navigate("/"); } catch (error) { - console.error('Logout failed:', error); - alert('Network error during logout. Please try again.'); + console.error("Logout failed:", error); + alert("Network error during logout. Please try again."); } }; const getGameImage = (internalName: string) => { - switch(internalName){ + switch (internalName) { case "dancerush": { return dancerushImage; } - default: { - return null + default: { + return null; } } - } + }; useEffect(() => { const fetchSupportedGames = async () => { try { - const response = await fetch(import.meta.env.VITE_API_URL+'/supportedGames'); + const response = await fetch( + import.meta.env.VITE_API_URL + "/supportedGames", + ); if (!response.ok) { - throw new Error('Failed to fetch supported games'); + throw new Error("Failed to fetch supported games"); } const data = await response.json(); setSupportedGames(data); } catch (error) { - console.error('Failed to fetch supported games:', error); - alert('Failed to load supported games. Please refresh the page.'); + console.error("Failed to fetch supported games:", error); + alert("Failed to load supported games. Please refresh the page."); } finally { setGamesLoading(false); } @@ -63,69 +67,21 @@ const Home = () => { } if (!user) { - return ( -
-
-
-

Session Expired

-

Please sign in to access your dashboard.

-
- - Sign In - - - Back to Home - -
-
-
-
- ); + return ; } return (
- {/* Navigation */} - + {/* Main Content */}
{/* Header */}

Dashboard

-

Track your rhythm game progress and performance

+

+ Track your rhythm game progress and performance +

{/* Supported Games */} @@ -134,34 +90,48 @@ const Home = () => { {supportedGames.map((game) => (
navigate(`/score?game=${game.internalName}`)} >
{getGameImage(game.internalName) !== null ? ( {game.formattedName} ) : (
- - + +
)}
-

{game.formattedName}

-

{game.description}

+

+ {game.formattedName} +

+

+ {game.description} +

))}
- ); diff --git a/frontend/src/pages/Import.tsx b/frontend/src/pages/Import.tsx index efd1d03..fe2501f 100644 --- a/frontend/src/pages/Import.tsx +++ b/frontend/src/pages/Import.tsx @@ -1,40 +1,42 @@ -import { useState, useEffect } from 'react'; -import { Link, useNavigate } from 'react-router'; -import { useAuth } from '../contexts/AuthContext'; -import JsonUploadModal from '../components/modals/JsonUploadModal'; -import EamusementModal from '../components/modals/EamusementModal'; -import type { SupportedGame } from '../types/game'; -import { uploadScore } from '../utils/scoreUpload'; - - +import { useState, useEffect } from "react"; +import { useNavigate } from "react-router"; +import { useAuth } from "../contexts/AuthContext"; +import JsonUploadModal from "../components/modals/JsonUploadModal"; +import EamusementModal from "../components/modals/EamusementModal"; +import SessionExpiredPopup from "../components/SessionExpiredPopup"; +import type { SupportedGame } from "../types/game"; +import { uploadScore } from "../utils/scoreUpload"; +import { NavBar } from "../components/NavBar"; const Import = () => { const { user, isLoading, logout } = useAuth(); const navigate = useNavigate(); - const [selectedGame, setSelectedGame] = useState(''); + const [selectedGame, setSelectedGame] = useState(""); const [isJsonModalOpen, setIsJsonModalOpen] = useState(false); const [isEamusementModalOpen, setIsEamusementModalOpen] = useState(false); const [supportedGames, setSupportedGames] = useState([]); const [gamesLoading, setGamesLoading] = useState(true); const [uploadStatus, setUploadStatus] = useState<{ - type: 'success' | 'error' | null; + type: "success" | "error" | null; message: string; - }>({ type: null, message: '' }); + }>({ type: null, message: "" }); useEffect(() => { const fetchSupportedGames = async () => { try { - const response = await fetch(import.meta.env.VITE_API_URL+'/supportedGames'); + const response = await fetch( + import.meta.env.VITE_API_URL + "/supportedGames", + ); if (!response.ok) { - throw new Error('Failed to fetch supported games'); + throw new Error("Failed to fetch supported games"); } const data = await response.json(); setSupportedGames(data); } catch (error) { - console.error('Failed to fetch supported games:', error); + console.error("Failed to fetch supported games:", error); setUploadStatus({ - type: 'error', - message: 'Failed to load supported games. Please refresh the page.' + type: "error", + message: "Failed to load supported games. Please refresh the page.", }); } finally { setGamesLoading(false); @@ -47,10 +49,10 @@ const Import = () => { const handleLogout = async () => { try { await logout(); - navigate('/'); + navigate("/"); } catch (error) { - console.error('Logout failed:', error); - alert('Network error during logout. Please try again.'); + console.error("Logout failed:", error); + alert("Network error during logout. Please try again."); } }; @@ -58,30 +60,33 @@ const Import = () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const handleJsonUpload = async (data: any) => { try { - console.log('Uploading data for game:', selectedGame, data); + console.log("Uploading data for game:", selectedGame, data); const result = await uploadScore({ meta: { game: data.meta.game, service: data.meta.service, - playtype: data.meta.playtype + playtype: data.meta.playtype, }, - scores: data.scores + scores: data.scores, }); setUploadStatus({ - type: 'success', - message: `Successfully imported ${result.scoreCount} score(s) for ${supportedGames.find(g => g.internalName === data.meta.game)?.formattedName || data.meta.game}` + type: "success", + message: `Successfully imported ${result.scoreCount} score(s) for ${supportedGames.find((g) => g.internalName === data.meta.game)?.formattedName || data.meta.game}`, }); setTimeout(() => { - setUploadStatus({ type: null, message: '' }); + setUploadStatus({ type: null, message: "" }); }, 5000); } catch (error) { - console.error('Upload failed:', error); + console.error("Upload failed:", error); setUploadStatus({ - type: 'error', - message: error instanceof Error ? error.message : 'Failed to import data. Please try again.' + type: "error", + message: + error instanceof Error + ? error.message + : "Failed to import data. Please try again.", }); } }; @@ -89,8 +94,18 @@ const Import = () => { const JsonUploadCard = () => (
- - + +

Batch-Manual Upload

@@ -111,11 +126,23 @@ const Import = () => { {/* e-amusement Card */}
- - + +
-

e-amusement Play History

+

+ e-amusement Play History +

Import via scraping your playdata from KONAMI e-amusement

@@ -131,12 +158,12 @@ const Import = () => { const renderImportOptions = () => { switch (selectedGame) { - case 'dancerush': + case "dancerush": return ( <> {/* JSON Upload Card */} - + ); @@ -157,83 +184,40 @@ const Import = () => { } if (!user) { - return ( -
-
-
-

Session Expired

-

Please sign in to import your data.

-
- - Sign In - - - Back to Home - -
-
-
-
- ); + return ; } return (
{/* Navigation */} - + {/* Main Content */}
{/* Header */}

Import Data

-

Import your game scores and progress from various sources

+

+ Import your game scores and progress from various sources +

{/* Status Message */} {uploadStatus.type && ( -
-

+

+

{uploadStatus.message}

@@ -262,7 +246,11 @@ const Import = () => { > {supportedGames.map((game) => ( - ))} @@ -273,7 +261,9 @@ const Import = () => { {/* Import Options */} {selectedGame && (
-

Import Options

+

+ Import Options +

{renderImportOptions()} @@ -288,14 +278,20 @@ const Import = () => { isOpen={isJsonModalOpen} onClose={() => setIsJsonModalOpen(false)} onUpload={handleJsonUpload} - game={supportedGames.find(g => g.internalName === selectedGame)?.formattedName || ''} + game={ + supportedGames.find((g) => g.internalName === selectedGame) + ?.formattedName || "" + } /> {/* Eamusement Modal */} setIsEamusementModalOpen(false)} - game={supportedGames.find(g => g.internalName === selectedGame) || undefined} + game={ + supportedGames.find((g) => g.internalName === selectedGame) || + undefined + } />
); diff --git a/frontend/src/pages/Score.tsx b/frontend/src/pages/Score.tsx new file mode 100644 index 0000000..e9feecd --- /dev/null +++ b/frontend/src/pages/Score.tsx @@ -0,0 +1,174 @@ +import { useEffect, useState, useCallback } from "react"; +import { useAuth } from "../contexts/AuthContext"; +import { useNavigate } from "react-router"; +import { NavBar } from "../components/NavBar"; +import SessionExpiredPopup from "../components/SessionExpiredPopup"; +import ScoreDisplay from "../components/tables/GenericScoreTable"; + +type SortField = string; +type SortDirection = "asc" | "desc"; + +const Score = () => { + const { user, isLoading, logout } = useAuth(); + const navigate = useNavigate(); + const [scores, setScores] = useState([]); + const [loading, setLoading] = useState(true); + const [currentPage, setCurrentPage] = useState(1); + const [numPages, setNumPages] = useState(1); + const [viewMode, setViewMode] = useState<"cards" | "table">("cards"); + const [sortField, setSortField] = useState("timestamp"); + const [sortDirection, setSortDirection] = useState("desc"); + + const gameName = + new URLSearchParams(window.location.search).get("game") || "dancerush"; + + const handleLogout = async () => { + try { + await logout(); + navigate("/"); + } catch (error) { + console.error("Logout failed:", error); + alert("Network error during logout. Please try again."); + } + }; + + const flattenScoreData = (score: any) => { + const flat = { ...score, ...score.data }; + delete flat.data; + delete flat.gameInternalName; + return flat; + }; + + const fetchScores = useCallback( + async (pageNum: number) => { + if (!user) return; + + setLoading(true); + try { + const url = new URL(import.meta.env.VITE_API_URL + "/scores"); + url.searchParams.append("userId", user.id); + url.searchParams.append("internalGameName", gameName); + url.searchParams.append("pageNum", pageNum.toString()); + + const response = await fetch(url.toString()); + if (!response.ok) throw new Error("Failed to fetch scores"); + const data = await response.json(); + const flattened = data.scores.map(flattenScoreData); + setScores(flattened); + setNumPages(data.num_pages); + setCurrentPage(pageNum); + } catch (error) { + console.error("Failed to load scores:", error); + alert("Failed to load scores. Please refresh the page."); + } finally { + setLoading(false); + } + }, + [user], + ); + + useEffect(() => { + if (user) fetchScores(1); + }, [user, fetchScores]); + + const handleSort = (field: SortField) => { + if (sortField === field) { + setSortDirection(sortDirection === "asc" ? "desc" : "asc"); + } else { + setSortField(field); + setSortDirection("desc"); + } + }; + + if (!user) { + return ; + } + + if (isLoading || loading) { + return ( +
+
+
+

Loading your scores...

+
+
+ ); + } + + return ( +
+ +
+
+
+

+ Your Scores +

+
+ + +
+
+

+ Displaying {scores.length} scores • Page {currentPage} of {numPages} +

+
+ + {(() => { + switch (viewMode) { + default: + return ( + + ); + } + })()} + + {numPages > 1 && ( +
+
+ {[...Array(numPages)].map((_, i) => ( + + ))} +
+
+ )} +
+
+ ); +}; + +export default Score; -- cgit v1.2.3