Public Access
Displaying the game library with server side pagination
This commit is contained in:
1 parent
994f4a516b
commit
8b290d5a13
8 files changed
+367
-5
No files matched your search
@@ -71,6 +71,17 @@
|
||||
"HELLO": "Hallo",
|
||||
"STEAM_GAMES": "Steam Spiele"
|
||||
},
|
||||
"LIBRARY": {
|
||||
"TITLE": "Spielebibliothek",
|
||||
"LOADING": "Lade Spiele …",
|
||||
"EMPTY": "Noch keine Spiele. Synchronisiere deine Steam-Bibliothek.",
|
||||
"ERROR_LOAD": "Spiele konnten nicht geladen werden.",
|
||||
"PER_PAGE": "Pro Seite:",
|
||||
"PREV": "Zurück",
|
||||
"NEXT": "Weiter",
|
||||
"PAGE_OF": "Seite {{current}} von {{total}}",
|
||||
"GAMES": "Spiele"
|
||||
},
|
||||
"MAIN": {
|
||||
"WELCOME": "Dein Game-Backlog unter Kontrolle",
|
||||
"DESCRIPTION": "Organisiere deinen Pile of Shame. Verfolge, verwalte und erobere deinen Game-Backlog wie nie zuvor.",
|
||||
|
||||
@@ -71,6 +71,17 @@
|
||||
"HELLO": "Hello",
|
||||
"STEAM_GAMES": "Steam Games"
|
||||
},
|
||||
"LIBRARY": {
|
||||
"TITLE": "Game Library",
|
||||
"LOADING": "Loading games …",
|
||||
"EMPTY": "No games yet. Try syncing your Steam library.",
|
||||
"ERROR_LOAD": "Could not load your games.",
|
||||
"PER_PAGE": "Per page:",
|
||||
"PREV": "Previous",
|
||||
"NEXT": "Next",
|
||||
"PAGE_OF": "Page {{current}} of {{total}}",
|
||||
"GAMES": "games"
|
||||
},
|
||||
"MAIN": {
|
||||
"WELCOME": "Control your game backlog",
|
||||
"DESCRIPTION": "Organize your pile of shame. Track, manage, and conquer your gaming backlog like never before.",
|
||||
|
||||
@@ -8,6 +8,7 @@ import ImprintPage from './pages/ImprintPage';
|
||||
import Dashboard from "./pages/Dashboard.jsx";
|
||||
import RegistrationPage from './pages/RegistrationPage.jsx';
|
||||
import SettingsPage from './pages/SettingsPage.jsx';
|
||||
import GameLibrary from './pages/GameLibrary.jsx';
|
||||
import {usePreferences} from './context/PreferencesContext.jsx';
|
||||
|
||||
function App() {
|
||||
@@ -78,6 +79,7 @@ function App() {
|
||||
<Route path="/login" element={<LoginPage/>}/>
|
||||
<Route path="/register" element={<RegistrationPage/>}/>
|
||||
<Route path="/dashboard" element={<Dashboard/>}/>
|
||||
<Route path="/library" element={<GameLibrary/>}/>
|
||||
<Route path="/settings" element={<SettingsPage/>}/>
|
||||
<Route path="/impressum" element={<ImprintPage/>}/>
|
||||
</Routes>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import React, {useState, useEffect} from 'react';
|
||||
import {Link} from 'react-router-dom';
|
||||
import {useTranslation} from 'react-i18next';
|
||||
|
||||
const SteamGameCount = ({targetCount}) => {
|
||||
@@ -7,13 +8,13 @@ const SteamGameCount = ({targetCount}) => {
|
||||
|
||||
useEffect(() => {
|
||||
let startTime;
|
||||
const duration = 1000; // 1 second
|
||||
const duration = 1000;
|
||||
const startCount = 0;
|
||||
|
||||
const animate = (timestamp) => {
|
||||
if (!startTime) startTime = timestamp;
|
||||
const progress = Math.min((timestamp - startTime) / duration, 1);
|
||||
|
||||
|
||||
const currentCount = Math.floor(progress * (targetCount - startCount) + startCount);
|
||||
setCount(currentCount);
|
||||
|
||||
@@ -26,14 +27,17 @@ const SteamGameCount = ({targetCount}) => {
|
||||
}, [targetCount]);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center p-6 bg-white dark:bg-slate-800 rounded-xl shadow-sm border border-slate-200 dark:border-slate-700">
|
||||
<Link
|
||||
to="/library"
|
||||
className="flex flex-col items-center justify-center p-6 bg-white dark:bg-slate-800 rounded-xl shadow-sm border border-slate-200 dark:border-slate-700 hover:border-blue-500 dark:hover:border-blue-500 transition-colors"
|
||||
>
|
||||
<div className="text-4xl font-bold text-blue-600 dark:text-blue-400 mb-2">
|
||||
{count}
|
||||
</div>
|
||||
<div className="text-sm font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wider">
|
||||
{t('DASHBOARD.STEAM_GAMES')}
|
||||
</div>
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import {useTranslation} from 'react-i18next';
|
||||
|
||||
const formatRelative = (iso, locale) => {
|
||||
if (!iso) return null;
|
||||
const then = new Date(iso).getTime();
|
||||
const diffSec = Math.round((Date.now() - then) / 1000);
|
||||
const rtf = new Intl.RelativeTimeFormat(locale, {numeric: 'auto'});
|
||||
if (diffSec < 60) return rtf.format(-diffSec, 'second');
|
||||
if (diffSec < 3600) return rtf.format(-Math.round(diffSec / 60), 'minute');
|
||||
if (diffSec < 86400) return rtf.format(-Math.round(diffSec / 3600), 'hour');
|
||||
return rtf.format(-Math.round(diffSec / 86400), 'day');
|
||||
};
|
||||
|
||||
export default function SyncStatusBadge({status, lastSyncedAt, isRunning}) {
|
||||
const {t, i18n} = useTranslation();
|
||||
|
||||
if (isRunning) {
|
||||
return (
|
||||
<div className="flex items-center gap-2 text-sm text-blue-600 dark:text-blue-400">
|
||||
<i className="mdi mdi-sync mdi-spin"></i>
|
||||
<span>{t('LIBRARY.SYNCING')}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (status === 'FAILED') {
|
||||
return (
|
||||
<div className="flex items-center gap-2 text-sm text-red-600 dark:text-red-400">
|
||||
<i className="mdi mdi-alert-circle"></i>
|
||||
<span>{t('LIBRARY.SYNC_FAILED')}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (lastSyncedAt) {
|
||||
return (
|
||||
<div className="flex items-center gap-2 text-sm text-slate-500 dark:text-slate-400">
|
||||
<i className="mdi mdi-check-circle"></i>
|
||||
<span>{t('LIBRARY.LAST_SYNCED', {when: formatRelative(lastSyncedAt, i18n.language)})}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import {useEffect, useRef, useState} from 'react';
|
||||
|
||||
const POLL_INTERVAL_MS = 3000;
|
||||
const MAX_POLL_DURATION_MS = 120_000;
|
||||
const INITIAL_SYNC_GRACE_MS = 15_000;
|
||||
|
||||
/**
|
||||
* Polls /api/library/sync-status while a sync is running (or expected),
|
||||
* and fires onComplete once when the run transitions to OK / FAILED.
|
||||
*
|
||||
* @param {Object} opts
|
||||
* @param {boolean} opts.enabled - skip work entirely when false (e.g. user has no steamId)
|
||||
* @param {boolean} opts.expectInitialSync - if true and no row yet, keep polling (covers the
|
||||
* gap between async sync dispatch and first DB write)
|
||||
* @param {() => void} opts.onComplete - called once per transition to OK/FAILED
|
||||
* @returns {{status: string|null, lastSyncedAt: string|null, isRunning: boolean, error: string|null}}
|
||||
*/
|
||||
export default function useLibrarySync({enabled, expectInitialSync = false, onComplete}) {
|
||||
const [state, setState] = useState({status: null, lastSyncedAt: null, error: null});
|
||||
const previousRunningRef = useRef(null);
|
||||
const onCompleteRef = useRef(onComplete);
|
||||
onCompleteRef.current = onComplete;
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled) return undefined;
|
||||
|
||||
let cancelled = false;
|
||||
let timer = null;
|
||||
const startedAt = Date.now();
|
||||
|
||||
const fetchOnce = async () => {
|
||||
const token = localStorage.getItem('tbp_jwt');
|
||||
if (!token) return;
|
||||
|
||||
try {
|
||||
const response = await fetch(
|
||||
`${import.meta.env.VITE_CORE_API_URL}/api/library/sync-status`,
|
||||
{headers: {'Authorization': `Bearer ${token}`}}
|
||||
);
|
||||
if (cancelled) return;
|
||||
|
||||
if (!response.ok) {
|
||||
setState((s) => ({...s, error: 'sync-status fetch failed'}));
|
||||
return;
|
||||
}
|
||||
|
||||
const json = await response.json();
|
||||
if (cancelled) return;
|
||||
|
||||
const status = json.lastSyncStatus;
|
||||
const lastSyncedAt = json.lastSyncedAt;
|
||||
setState({status, lastSyncedAt, error: null});
|
||||
|
||||
const isRunning = status === 'RUNNING';
|
||||
const wasRunning = previousRunningRef.current;
|
||||
|
||||
if (wasRunning === true && !isRunning) {
|
||||
onCompleteRef.current?.();
|
||||
}
|
||||
previousRunningRef.current = isRunning;
|
||||
|
||||
const elapsed = Date.now() - startedAt;
|
||||
const waitingForInitial =
|
||||
expectInitialSync && status == null && elapsed < INITIAL_SYNC_GRACE_MS;
|
||||
const stillWaiting = isRunning || waitingForInitial;
|
||||
|
||||
if (stillWaiting && elapsed < MAX_POLL_DURATION_MS) {
|
||||
timer = setTimeout(fetchOnce, POLL_INTERVAL_MS);
|
||||
}
|
||||
} catch (err) {
|
||||
if (cancelled) return;
|
||||
console.error('sync-status poll error:', err);
|
||||
setState((s) => ({...s, error: 'network'}));
|
||||
}
|
||||
};
|
||||
|
||||
fetchOnce();
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
if (timer) clearTimeout(timer);
|
||||
};
|
||||
}, [enabled, expectInitialSync]);
|
||||
|
||||
return {
|
||||
status: state.status,
|
||||
lastSyncedAt: state.lastSyncedAt,
|
||||
isRunning: state.status === 'RUNNING',
|
||||
error: state.error,
|
||||
};
|
||||
}
|
||||
@@ -36,7 +36,7 @@ const Dashboard = () => {
|
||||
// If user has a steamId, fetch game count from Core Service
|
||||
if (data.steamId) {
|
||||
try {
|
||||
const steamResponse = await fetch(`${import.meta.env.VITE_CORE_API_URL}/api/steam/games-count`, {
|
||||
const steamResponse = await fetch(`${import.meta.env.VITE_CORE_API_URL}/api/library/games-count`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${token}`,
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
import {useCallback, useEffect, useState} from 'react';
|
||||
import {useNavigate, useSearchParams} from 'react-router-dom';
|
||||
import {useTranslation} from 'react-i18next';
|
||||
import useLibrarySync from '../hooks/useLibrarySync.js';
|
||||
import SyncStatusBadge from '../components/SyncStatusBadge.jsx';
|
||||
|
||||
const PAGE_SIZES = [20, 40, 80];
|
||||
const DEFAULT_SIZE = 20;
|
||||
|
||||
const iconUrl = (appid, hash) =>
|
||||
hash
|
||||
? `https://cdn.cloudflare.steamstatic.com/steamcommunity/public/images/apps/${appid}/${hash}.jpg`
|
||||
: null;
|
||||
|
||||
const formatPlaytime = (minutes) => {
|
||||
if (!minutes || minutes <= 0) return '0h';
|
||||
const hours = minutes / 60;
|
||||
return hours >= 10 ? `${Math.round(hours)}h` : `${hours.toFixed(1)}h`;
|
||||
};
|
||||
|
||||
export default function GameLibrary() {
|
||||
const {t} = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
|
||||
const page = Math.max(0, parseInt(searchParams.get('page') ?? '0', 10) || 0);
|
||||
const sizeParam = parseInt(searchParams.get('size') ?? String(DEFAULT_SIZE), 10);
|
||||
const size = PAGE_SIZES.includes(sizeParam) ? sizeParam : DEFAULT_SIZE;
|
||||
|
||||
const [data, setData] = useState({content: [], page: 0, size, totalElements: 0, totalPages: 0});
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [error, setError] = useState(null);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
const token = localStorage.getItem('tbp_jwt');
|
||||
if (!token) {
|
||||
navigate('/login');
|
||||
return;
|
||||
}
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const url = `${import.meta.env.VITE_CORE_API_URL}/api/library/games?page=${page}&size=${size}`;
|
||||
const response = await fetch(url, {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${token}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
});
|
||||
|
||||
if (response.status === 401) {
|
||||
localStorage.removeItem('tbp_jwt');
|
||||
navigate('/login');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
setError(t('LIBRARY.ERROR_LOAD'));
|
||||
return;
|
||||
}
|
||||
|
||||
const json = await response.json();
|
||||
setData(json);
|
||||
} catch (err) {
|
||||
console.error('Library load error:', err);
|
||||
setError(t('INFO.ERROR.NETWORK_FAILURE'));
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [navigate, page, size, t]);
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, [load]);
|
||||
|
||||
const expectInitialSync = !isLoading && !error && data.totalElements === 0;
|
||||
const sync = useLibrarySync({
|
||||
enabled: true,
|
||||
expectInitialSync,
|
||||
onComplete: load,
|
||||
});
|
||||
|
||||
const updateParams = (next) => {
|
||||
const params = new URLSearchParams(searchParams);
|
||||
Object.entries(next).forEach(([k, v]) => params.set(k, String(v)));
|
||||
setSearchParams(params);
|
||||
};
|
||||
|
||||
const onSizeChange = (event) => {
|
||||
updateParams({size: event.target.value, page: 0});
|
||||
};
|
||||
|
||||
const goToPage = (target) => {
|
||||
if (target < 0 || target >= data.totalPages) return;
|
||||
updateParams({page: target});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-slate-50 dark:bg-slate-900 p-8">
|
||||
<div className="max-w-4xl mx-auto space-y-6">
|
||||
<div className="flex items-center justify-between flex-wrap gap-4">
|
||||
<div className="flex flex-col gap-1">
|
||||
<h1 className="text-2xl font-bold text-slate-900 dark:text-white">
|
||||
{t('LIBRARY.TITLE')}
|
||||
</h1>
|
||||
<SyncStatusBadge
|
||||
status={sync.status}
|
||||
lastSyncedAt={sync.lastSyncedAt}
|
||||
isRunning={sync.isRunning}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 text-sm text-slate-600 dark:text-slate-300">
|
||||
<label htmlFor="pageSize">{t('LIBRARY.PER_PAGE')}</label>
|
||||
<select
|
||||
id="pageSize"
|
||||
value={size}
|
||||
onChange={onSizeChange}
|
||||
className="px-3 py-1 border border-slate-300 dark:border-slate-600 rounded-lg bg-white dark:bg-slate-800 text-slate-900 dark:text-white"
|
||||
>
|
||||
{PAGE_SIZES.map((n) => (
|
||||
<option key={n} value={n}>{n}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isLoading && (
|
||||
<div className="text-center text-slate-600 dark:text-slate-300 py-12">
|
||||
{t('LIBRARY.LOADING')}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<div className="text-center text-red-500 py-12">{error}</div>
|
||||
)}
|
||||
|
||||
{!isLoading && !error && data.content.length === 0 && (
|
||||
<div className="text-center text-slate-500 dark:text-slate-400 py-12">
|
||||
{sync.isRunning ? t('LIBRARY.SYNCING_FIRST_TIME') : t('LIBRARY.EMPTY')}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isLoading && !error && data.content.length > 0 && (
|
||||
<ul className="bg-white dark:bg-slate-800 rounded-xl shadow-sm border border-slate-200 dark:border-slate-700 divide-y divide-slate-200 dark:divide-slate-700">
|
||||
{data.content.map((g) => {
|
||||
const icon = iconUrl(g.appid, g.imgIconUrl);
|
||||
return (
|
||||
<li key={g.appid} className="flex items-center gap-4 px-4 py-3">
|
||||
{icon ? (
|
||||
<img
|
||||
src={icon}
|
||||
alt=""
|
||||
className="w-8 h-8 rounded"
|
||||
loading="lazy"
|
||||
onError={(e) => { e.currentTarget.style.visibility = 'hidden'; }}
|
||||
/>
|
||||
) : (
|
||||
<div className="w-8 h-8 rounded bg-slate-200 dark:bg-slate-700"/>
|
||||
)}
|
||||
<span className="flex-1 text-slate-900 dark:text-white truncate">
|
||||
{g.name ?? `App ${g.appid}`}
|
||||
</span>
|
||||
<span className="text-sm text-slate-500 dark:text-slate-400 tabular-nums">
|
||||
{formatPlaytime(g.playtimeMinutes)}
|
||||
</span>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
{!isLoading && !error && data.totalPages > 1 && (
|
||||
<div className="flex items-center justify-between text-sm text-slate-600 dark:text-slate-300">
|
||||
<button
|
||||
onClick={() => goToPage(page - 1)}
|
||||
disabled={page <= 0}
|
||||
className="px-4 py-2 rounded-lg bg-white dark:bg-slate-800 border border-slate-300 dark:border-slate-600 disabled:opacity-40 hover:border-blue-500 disabled:hover:border-slate-300 dark:disabled:hover:border-slate-600 transition-colors"
|
||||
>
|
||||
{t('LIBRARY.PREV')}
|
||||
</button>
|
||||
<span>
|
||||
{t('LIBRARY.PAGE_OF', {current: data.page + 1, total: data.totalPages})}
|
||||
{' · '}
|
||||
{data.totalElements} {t('LIBRARY.GAMES')}
|
||||
</span>
|
||||
<button
|
||||
onClick={() => goToPage(page + 1)}
|
||||
disabled={page >= data.totalPages - 1}
|
||||
className="px-4 py-2 rounded-lg bg-white dark:bg-slate-800 border border-slate-300 dark:border-slate-600 disabled:opacity-40 hover:border-blue-500 disabled:hover:border-slate-300 dark:disabled:hover:border-slate-600 transition-colors"
|
||||
>
|
||||
{t('LIBRARY.NEXT')}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user