feat(library): search IGDB and add games by hand
Build, Test & Push Frontend / quality-check (push) Successful in 13s
Build, Test & Push Frontend / docker (push) Successful in 23s

This commit is contained in:
lobo committed 2026-09-25 14:37:21 +02:00
1 parent d9a39dda22
commit 444b03acee
17 files changed
+699 -35

No files matched your search

+212
View File
@@ -0,0 +1,212 @@
import {useEffect, useState} from 'react';
import {useNavigate} from 'react-router-dom';
import {useTranslation} from 'react-i18next';
import {toast} from 'sonner';
import {ArrowLeft, Loader2, Plus, Search, X} from 'lucide-react';
import {Badge} from '@/components/ui/badge';
import {Button} from '@/components/ui/button';
import {Card} from '@/components/ui/card';
import {Input} from '@/components/ui/input';
import {Label} from '@/components/ui/label';
import {Select, SelectContent, SelectItem, SelectTrigger, SelectValue} from '@/components/ui/select';
import GameCover from './GameCover.jsx';
import useSessionExpired from '../hooks/useSessionExpired.js';
import {GAME_STATUSES} from '../utils/backlog.js';
import {addGame, hoursToMinutes, searchGames} from '../utils/manualGames.js';
const SEARCH_DEBOUNCE_MS = 400;
const MIN_QUERY = 2;
/**
* Search IGDB and add a game the user owns outside Steam, e.g. on PlayStation or Switch.
*/
export default function AddGamePanel({onClose}) {
const {t} = useTranslation();
const navigate = useNavigate();
const expireSession = useSessionExpired();
const [query, setQuery] = useState('');
// idle | loading | done | unavailable | failed
const [searchState, setSearchState] = useState('idle');
const [results, setResults] = useState([]);
const [picked, setPicked] = useState(null);
useEffect(() => {
const trimmed = query.trim();
if (trimmed.length < MIN_QUERY) {
setSearchState('idle');
setResults([]);
return undefined;
}
const controller = new AbortController();
const timer = setTimeout(async () => {
setSearchState('loading');
try {
const response = await searchGames(trimmed, controller.signal);
if (response.status === 401) {
expireSession();
return;
}
if (!response.ok) {
setSearchState('failed');
return;
}
const data = await response.json();
setResults(data.results ?? []);
setSearchState(data.available ? 'done' : 'unavailable');
} catch (err) {
if (err.name !== 'AbortError') setSearchState('failed');
}
}, SEARCH_DEBOUNCE_MS);
return () => {
clearTimeout(timer);
controller.abort();
};
}, [query, expireSession]);
return (
<Card className="p-5 gap-4">
<div className="flex items-center justify-between gap-3">
<h2 className="flex items-center gap-2 font-semibold">
<Plus className="size-4 text-primary"/>
{t('MANUAL_GAME.ADD_TITLE')}
</h2>
<Button variant="ghost" size="icon" onClick={onClose} aria-label={t('MANUAL_GAME.CLOSE')}>
<X/>
</Button>
</div>
{picked ? (
<AddForm hit={picked} onBack={() => setPicked(null)} navigate={navigate} expireSession={expireSession}/>
) : (
<>
<p className="text-sm text-muted-foreground">{t('MANUAL_GAME.ADD_HINT')}</p>
<div className="relative">
<Search className="pointer-events-none absolute left-2.5 top-1/2 size-4 -translate-y-1/2 text-muted-foreground"/>
<Input type="search" autoFocus value={query} maxLength={100} className="pl-8"
placeholder={t('MANUAL_GAME.SEARCH_PLACEHOLDER')}
aria-label={t('MANUAL_GAME.SEARCH_PLACEHOLDER')}
onChange={(e) => setQuery(e.target.value)}/>
</div>
{searchState === 'loading' && (
<p className="flex items-center gap-2 text-sm text-muted-foreground">
<Loader2 className="size-4 animate-spin"/>{t('MANUAL_GAME.SEARCHING')}
</p>
)}
{searchState === 'unavailable' && <p className="text-sm text-muted-foreground">{t('MANUAL_GAME.UNAVAILABLE')}</p>}
{searchState === 'failed' && <p className="text-sm text-destructive">{t('MANUAL_GAME.SEARCH_FAILED')}</p>}
{searchState === 'done' && results.length === 0 && (
<p className="text-sm text-muted-foreground">{t('MANUAL_GAME.NO_HITS')}</p>
)}
{searchState === 'done' && results.length > 0 && (
<ul className="divide-y rounded-md border">
{results.map((hit) => (
<li key={hit.igdbId}>
<button type="button" disabled={hit.inLibrary} onClick={() => setPicked(hit)}
className="flex w-full items-center gap-3 px-3 py-2 text-left transition-colors hover:bg-muted/50 disabled:cursor-not-allowed disabled:opacity-60">
<GameCover appid={hit.appid} imageUrl={hit.imageUrl} className="w-20 shrink-0"/>
<span className="min-w-0 flex-1">
<span className="block truncate font-medium">
{hit.name}{hit.year ? ` (${hit.year})` : ''}
</span>
<span className="block truncate text-xs text-muted-foreground">
{hit.platforms.join(' · ')}
</span>
</span>
{hit.inLibrary && <Badge variant="secondary">{t('MANUAL_GAME.IN_LIBRARY')}</Badge>}
</button>
</li>
))}
</ul>
)}
</>
)}
</Card>
);
}
function AddForm({hit, onBack, navigate, expireSession}) {
const {t} = useTranslation();
const [platform, setPlatform] = useState(hit.platforms[0] ?? '');
const [status, setStatus] = useState('BACKLOG');
const [hours, setHours] = useState('');
const [busy, setBusy] = useState(false);
const submit = async (e) => {
e.preventDefault();
setBusy(true);
try {
const response = await addGame({
igdbId: hit.igdbId, platform: platform.trim(), status, playtimeMinutes: hoursToMinutes(hours),
});
if (response.status === 401) {
expireSession();
return;
}
if (response.status === 409) {
toast.error(t('MANUAL_GAME.ALREADY_IN_LIBRARY'));
return;
}
if (!response.ok) {
toast.error(t('MANUAL_GAME.ADD_FAILED'));
return;
}
const {appid} = await response.json();
toast.success(t('MANUAL_GAME.ADDED', {name: hit.name}));
navigate(`/library/${appid}`);
} catch (err) {
console.error('add game error:', err);
toast.error(t('INFO.ERROR.NETWORK_FAILURE'));
} finally {
setBusy(false);
}
};
return (
<form onSubmit={submit} className="space-y-4">
<div className="flex items-center gap-3">
<GameCover appid={hit.appid} imageUrl={hit.imageUrl} className="w-24 shrink-0"/>
<div className="min-w-0 font-medium">{hit.name}{hit.year ? ` (${hit.year})` : ''}</div>
</div>
<div className="grid gap-4 sm:grid-cols-3">
<div className="space-y-2">
<Label htmlFor="add-platform">{t('MANUAL_GAME.PLATFORM')}</Label>
{hit.platforms.length > 0 ? (
<Select value={platform} onValueChange={setPlatform}>
<SelectTrigger id="add-platform" className="w-full"><SelectValue/></SelectTrigger>
<SelectContent>
{hit.platforms.map((p) => <SelectItem key={p} value={p}>{p}</SelectItem>)}
</SelectContent>
</Select>
) : (
<Input id="add-platform" value={platform} maxLength={32} onChange={(e) => setPlatform(e.target.value)}/>
)}
</div>
<div className="space-y-2">
<Label htmlFor="add-status">{t('BACKLOG.STATUS_LABEL')}</Label>
<Select value={status} onValueChange={setStatus}>
<SelectTrigger id="add-status" className="w-full"><SelectValue/></SelectTrigger>
<SelectContent>
{GAME_STATUSES.map((s) => <SelectItem key={s} value={s}>{t(`BACKLOG.STATUS.${s}`)}</SelectItem>)}
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor="add-hours">{t('MANUAL_GAME.HOURS')}</Label>
<Input id="add-hours" type="number" min="0" step="0.5" inputMode="decimal" value={hours}
onChange={(e) => setHours(e.target.value)}/>
</div>
</div>
<div className="flex justify-between gap-3">
<Button type="button" variant="ghost" onClick={onBack} disabled={busy}>
<ArrowLeft/>{t('MANUAL_GAME.BACK_TO_SEARCH')}
</Button>
<Button type="submit" disabled={busy || !platform.trim()}>
{busy && <Loader2 className="animate-spin"/>}
<Plus/>{t('MANUAL_GAME.ADD')}
</Button>
</div>
</form>
);
}
+100
View File
@@ -0,0 +1,100 @@
// @vitest-environment jsdom
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {cleanup, fireEvent, render, screen, waitFor} from '@testing-library/react';
import {MemoryRouter, Route, Routes} from 'react-router-dom';
import {toast} from 'sonner';
import AddGamePanel from './AddGamePanel.jsx';
vi.mock('react-i18next', () => import('../test/i18n-mock.js'));
vi.mock('sonner', () => ({toast: {success: vi.fn(), error: vi.fn()}}));
const zelda = {
appid: -1025, igdbId: 1025, name: 'Zelda', year: 2017, imageUrl: 'https://images.igdb.com/z.jpg',
platforms: ['Nintendo Switch', 'Wii U'], inLibrary: false,
};
const portal = {...zelda, appid: 400, igdbId: 71, name: 'Portal', inLibrary: true};
const json = (status, body) => ({ok: status < 400, status, json: async () => body});
function renderPanel(post = json(201, {appid: -1025})) {
globalThis.fetch = vi.fn(async (url, init) => init?.method === 'POST'
? post
: json(200, {available: true, results: [zelda, portal]}));
render(
<MemoryRouter initialEntries={['/library']}>
<Routes>
<Route path="/library" element={<AddGamePanel onClose={() => {}}/>}/>
<Route path="/library/:appid" element={<p>detail page</p>}/>
</Routes>
</MemoryRouter>,
);
}
const search = (value) => fireEvent.change(screen.getByRole('searchbox'), {target: {value}});
beforeEach(() => {
localStorage.setItem('tbp_session', '1');
});
afterEach(() => {
cleanup();
localStorage.clear();
vi.clearAllMocks();
});
describe('AddGamePanel', () => {
it('does not search below two characters', async () => {
renderPanel();
search('z');
await new Promise((resolve) => setTimeout(resolve, 600));
expect(fetch).not.toHaveBeenCalled();
});
it('searches once after typing stops and blocks games already in the library', async () => {
renderPanel();
search('ze');
search('zel');
const hit = await screen.findByRole('button', {name: /Zelda \(2017\)/});
expect(fetch).toHaveBeenCalledTimes(1);
expect(fetch.mock.calls[0][0]).toContain('/api/library/game-search?q=zel');
expect(hit.disabled).toBe(false);
expect(screen.getByRole('button', {name: /Portal/}).disabled).toBe(true);
});
it('adds the picked game with the first platform and the hours, then opens its page', async () => {
renderPanel();
search('zelda');
fireEvent.click(await screen.findByRole('button', {name: /Zelda/}));
fireEvent.change(screen.getByLabelText('MANUAL_GAME.HOURS'), {target: {value: '1.5'}});
fireEvent.click(screen.getByRole('button', {name: 'MANUAL_GAME.ADD'}));
expect(await screen.findByText('detail page')).toBeTruthy();
const [url, init] = fetch.mock.calls.find(([, call]) => call?.method === 'POST');
expect(url).toContain('/api/library/games');
expect(JSON.parse(init.body)).toEqual({
igdbId: 1025, platform: 'Nintendo Switch', status: 'BACKLOG', playtimeMinutes: 90,
});
});
it('says so when the game is already in the library', async () => {
renderPanel(json(409, {code: 'ALREADY_IN_LIBRARY'}));
search('zelda');
fireEvent.click(await screen.findByRole('button', {name: /Zelda/}));
fireEvent.click(screen.getByRole('button', {name: 'MANUAL_GAME.ADD'}));
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('MANUAL_GAME.ALREADY_IN_LIBRARY'));
expect(screen.queryByText('detail page')).toBeNull();
});
it('shows that adding is off when Core has no IGDB app', async () => {
renderPanel();
fetch.mockImplementation(async () => json(200, {available: false, results: []}));
search('zelda');
expect(await screen.findByText('MANUAL_GAME.UNAVAILABLE')).toBeTruthy();
});
});
+1 -1
View File
@@ -30,7 +30,7 @@ export default function CurrentlyPlayingCard({games, syncing}) {
{games.map((g) => (
<li key={g.appid}>
<Link to={`/library/${g.appid}`} className="group block space-y-1.5">
<GameCover appid={g.appid} className="w-full transition-opacity group-hover:opacity-80"/>
<GameCover appid={g.appid} imageUrl={g.imageUrl} className="w-full transition-opacity group-hover:opacity-80"/>
<div className="truncate text-sm font-medium group-hover:text-primary transition-colors">
{g.name ?? `App ${g.appid}`}
</div>
+4 -2
View File
@@ -6,8 +6,10 @@ import {coverUrl} from '@/utils/games.js';
/**
* Steam store header (460x215). Falls back to a neutral tile when the app has no header image.
*
* @param imageUrl picture for a game that has no Steam art (added by hand from IGDB); wins over the Steam header
*/
export default function GameCover({appid, className}) {
export default function GameCover({appid, imageUrl, className}) {
const [failed, setFailed] = useState(false);
return (
@@ -18,7 +20,7 @@ export default function GameCover({appid, className}) {
</div>
) : (
<img
src={coverUrl(appid)}
src={imageUrl ?? coverUrl(appid)}
alt=""
loading="lazy"
className="size-full object-cover"
+109
View File
@@ -0,0 +1,109 @@
import {useState} from 'react';
import {useNavigate} from 'react-router-dom';
import {useTranslation} from 'react-i18next';
import {toast} from 'sonner';
import {Hand, Loader2, Trash2} from 'lucide-react';
import {Button} from '@/components/ui/button';
import {Card} from '@/components/ui/card';
import {Input} from '@/components/ui/input';
import {Label} from '@/components/ui/label';
import useSessionExpired from '../hooks/useSessionExpired.js';
import {hoursToMinutes, removeGame, updateManualGame} from '../utils/manualGames.js';
// Two decimals: then hoursToMinutes gives back the same minute, so an unchanged form is not dirty.
const toHours = (minutes) => (minutes > 0 ? String(Math.round((minutes / 60) * 100) / 100) : '');
/**
* Platform and hours of a game added by hand, and removing it. Steam games get both from the sync.
*
* @param onSaved gets the saved platform and playtimeMinutes
*/
export default function ManualGameCard({game, onSaved}) {
const {t} = useTranslation();
const navigate = useNavigate();
const expireSession = useSessionExpired();
const [platform, setPlatform] = useState(game.platform ?? '');
const [hours, setHours] = useState(toHours(game.playtimeMinutes));
const [busy, setBusy] = useState(false);
const [confirmRemove, setConfirmRemove] = useState(false);
const playtimeMinutes = hoursToMinutes(hours);
const dirty = platform.trim() !== (game.platform ?? '') || playtimeMinutes !== game.playtimeMinutes;
const run = async (request, onOk) => {
setBusy(true);
try {
const response = await request();
if (response.status === 401) {
expireSession();
return;
}
if (!response.ok) {
toast.error(t('BACKLOG.SAVE_FAILED'));
return;
}
onOk();
} catch (err) {
console.error('manual game error:', err);
toast.error(t('INFO.ERROR.NETWORK_FAILURE'));
} finally {
setBusy(false);
}
};
const save = () => run(() => updateManualGame(game.appid, {platform: platform.trim(), playtimeMinutes}), () => {
onSaved({platform: platform.trim(), playtimeMinutes});
toast.success(t('BACKLOG.SAVED'));
});
const remove = () => run(() => removeGame(game.appid), () => {
toast.success(t('MANUAL_GAME.REMOVED'));
navigate('/library', {replace: true});
});
return (
<Card className="p-6 gap-5">
<h2 className="flex items-center gap-2 text-lg font-semibold">
<Hand className="size-4 text-primary"/>
{t('MANUAL_GAME.TITLE')}
</h2>
<p className="text-sm text-muted-foreground">{t('MANUAL_GAME.HINT')}</p>
<div className="grid gap-5 sm:grid-cols-2">
<div className="space-y-2">
<Label htmlFor="manual-platform">{t('MANUAL_GAME.PLATFORM')}</Label>
<Input id="manual-platform" value={platform} maxLength={32}
onChange={(e) => setPlatform(e.target.value)}/>
</div>
<div className="space-y-2">
<Label htmlFor="manual-hours">{t('MANUAL_GAME.HOURS')}</Label>
<Input id="manual-hours" type="number" min="0" step="0.5" inputMode="decimal" value={hours}
onChange={(e) => setHours(e.target.value)}/>
</div>
</div>
<div className="flex flex-wrap items-center justify-between gap-3">
{confirmRemove ? (
<div className="flex flex-wrap items-center gap-2">
<span className="text-sm">{t('MANUAL_GAME.REMOVE_CONFIRM')}</span>
<Button variant="destructive" size="sm" onClick={remove} disabled={busy}>
<Trash2/>{t('MANUAL_GAME.REMOVE_YES')}
</Button>
<Button variant="ghost" size="sm" onClick={() => setConfirmRemove(false)} disabled={busy}>
{t('MANUAL_GAME.REMOVE_NO')}
</Button>
</div>
) : (
<Button variant="outline" size="sm" onClick={() => setConfirmRemove(true)} disabled={busy}>
<Trash2/>{t('MANUAL_GAME.REMOVE')}
</Button>
)}
<Button onClick={save} disabled={busy || !dirty || !platform.trim()}>
{busy && <Loader2 className="animate-spin"/>}
{t('BACKLOG.SAVE')}
</Button>
</div>
</Card>
);
}
+1 -1
View File
@@ -81,7 +81,7 @@ export default function PileOfShameCard({summary, syncing, onShuffle, shuffling}
to={`/library/${suggestion.appid}`}
className="group flex items-center gap-3 rounded-lg border p-2 transition-colors hover:bg-muted/50"
>
<GameCover appid={suggestion.appid} className="w-24 shrink-0"/>
<GameCover appid={suggestion.appid} imageUrl={suggestion.imageUrl} className="w-24 shrink-0"/>
<span className="min-w-0 truncate font-medium group-hover:text-primary transition-colors">
{suggestion.name ?? `App ${suggestion.appid}`}
</span>
+8 -6
View File
@@ -187,9 +187,10 @@ const Dashboard = () => {
const data = await profileResponse.json();
setUserData(data);
if (data.steamId) {
await Promise.all([fetchSteamCount(), fetchTopGames(), fetchPlaying(), fetchSummary(), fetchActivity(), fetchAchievements()]);
}
// Games added by hand need no Steam ID; history and achievements come only from Steam.
await Promise.all(data.steamId
? [fetchSteamCount(), fetchTopGames(), fetchPlaying(), fetchSummary(), fetchActivity(), fetchAchievements()]
: [fetchSteamCount(), fetchTopGames(), fetchPlaying(), fetchSummary()]);
} else if (profileResponse.status === 401) {
expireSession();
} else {
@@ -207,6 +208,7 @@ const Dashboard = () => {
}, [navigate, expireSession, t, fetchSteamCount, fetchTopGames, fetchPlaying, fetchSummary, fetchActivity, fetchAchievements]);
const hasSteamId = !!userData?.steamId;
const showLibrary = hasSteamId || steamData.count > 0;
const {appearance} = usePreferences();
const steamProfile = useSteamProfile(hasSteamId);
const bannerAppid = appearance.showBanner
@@ -284,7 +286,7 @@ const Dashboard = () => {
)}
</Card>
{hasSteamId && (
{showLibrary && (
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
<SteamGameCount targetCount={steamData.count}/>
@@ -314,7 +316,7 @@ const Dashboard = () => {
<span className="w-4 text-right text-sm font-semibold text-muted-foreground tabular-nums">
{index + 1}
</span>
<GameCover appid={g.appid} className="w-16 sm:w-24 shrink-0"/>
<GameCover appid={g.appid} imageUrl={g.imageUrl} className="w-16 sm:w-24 shrink-0"/>
<div className="min-w-0 flex-1">
<div className="truncate font-medium group-hover:text-primary transition-colors">
{g.name ?? `App ${g.appid}`}
@@ -338,7 +340,7 @@ const Dashboard = () => {
</div>
)}
{hasSteamId && (
{showLibrary && (
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<CurrentlyPlayingCard games={playing} syncing={sync.isRunning}/>
{summary && (
+18 -5
View File
@@ -1,7 +1,7 @@
import {useEffect, useMemo, useState} from 'react';
import {Link, useNavigate, useParams} from 'react-router-dom';
import {useTranslation} from 'react-i18next';
import {ArrowLeft, Clock, ExternalLink, Image as ImageIcon, ImageOff, PanelTop, RotateCcw, ShieldOff, Trophy} from 'lucide-react';
import {ArrowLeft, Clock, ExternalLink, Gamepad2, Image as ImageIcon, ImageOff, PanelTop, RotateCcw, ShieldOff, Trophy} from 'lucide-react';
import {Badge} from '@/components/ui/badge';
import {Button} from '@/components/ui/button';
@@ -11,6 +11,7 @@ import {cn} from '@/lib/utils';
import BacklogCard from '../components/BacklogCard.jsx';
import GameCover from '../components/GameCover.jsx';
import GameStatusBadge from '../components/GameStatusBadge.jsx';
import ManualGameCard from '../components/ManualGameCard.jsx';
import CompletedHint from '../components/CompletedHint.jsx';
import PlayingHint from '../components/PlayingHint.jsx';
import TimeToBeat from '../components/TimeToBeat.jsx';
@@ -21,6 +22,7 @@ import {usePreferences} from '../context/PreferencesContext.jsx';
import PageContainer from '../components/PageContainer.jsx';
import {apiFetch} from '../utils/api.js';
import {hasSession} from '../utils/auth.js';
import {isSteamKey} from '../utils/manualGames.js';
const formatUnlockedAt = (instant, locale) => {
if (!instant) return '';
@@ -99,6 +101,8 @@ export default function GameDetail() {
});
}, [data]);
const manual = data?.source === 'MANUAL';
const onSteam = !!data && isSteamKey(data.appid);
const isBackground = !!data && appearance.backgroundAppid === data.appid;
const isBanner = !!data && appearance.showBanner && appearance.bannerAppid === data.appid;
@@ -131,7 +135,7 @@ export default function GameDetail() {
{!isLoading && !error && data && (
<>
<Card className="relative overflow-hidden p-0 gap-0 md:flex-row">
<GameCover appid={data.appid} className="w-full rounded-none md:w-96 md:shrink-0"/>
<GameCover appid={data.appid} imageUrl={data.imageUrl} className="w-full rounded-none md:w-96 md:shrink-0"/>
<div className="flex flex-1 flex-col justify-between gap-4 p-6">
<div>
<h1 className="text-2xl md:text-3xl font-bold tracking-tight">
@@ -143,12 +147,16 @@ export default function GameDetail() {
{t('GAME_DETAIL.PLAYTIME', {time: formatPlaytime(data.playtimeMinutes)})}
</Badge>
<GameStatusBadge status={data.status}/>
{data.platform && (
<Badge variant="outline"><Gamepad2 className="size-3"/>{data.platform}</Badge>
)}
</div>
<div className="mt-3">
<TimeToBeat time={data.timeToBeat}/>
</div>
</div>
<div className="flex flex-wrap gap-2">
{/* Store page, background and banner need Steam art, so a game off Steam has none of them. */}
{onSteam && <div className="flex flex-wrap gap-2">
<Button asChild variant="outline" size="sm">
<a href={`https://store.steampowered.com/app/${data.appid}`} target="_blank" rel="noopener noreferrer">
{t('GAME_DETAIL.OPEN_IN_STEAM')}<ExternalLink/>
@@ -173,7 +181,7 @@ export default function GameDetail() {
<PanelTop/>{t('GAME_DETAIL.SET_BANNER')}
</Button>
)}
</div>
</div>}
</div>
</Card>
@@ -183,10 +191,15 @@ export default function GameDetail() {
<BacklogCard key={data.appid} game={data}
onSaved={(entry) => setData((d) => ({...d, ...entry}))}/>
{manual && (
<ManualGameCard key={`manual-${data.appid}`} game={data}
onSaved={(changes) => setData((d) => ({...d, ...changes}))}/>
)}
{!data.hasAchievements && (
<Card className="items-center py-10 text-center text-sm text-muted-foreground">
<Trophy className="size-8"/>
{t('GAME_DETAIL.NO_ACHIEVEMENTS')}
{t(manual ? 'MANUAL_GAME.NO_ACHIEVEMENTS' : 'GAME_DETAIL.NO_ACHIEVEMENTS')}
</Card>
)}
+74 -3
View File
@@ -13,9 +13,12 @@ const game = {
rating: null, notes: null, priority: null, hasAchievements: false, statsVisible: false, achievements: [],
};
const renderDetail = () => render(
<MemoryRouter initialEntries={['/library/220']}><PreferencesProvider>
<Routes><Route path="/library/:appid" element={<GameDetail/>}/></Routes>
const renderDetail = (appid = 220) => render(
<MemoryRouter initialEntries={[`/library/${appid}`]}><PreferencesProvider>
<Routes>
<Route path="/library/:appid" element={<GameDetail/>}/>
<Route path="/library" element={<p>library page</p>}/>
</Routes>
</PreferencesProvider></MemoryRouter>,
);
@@ -81,3 +84,71 @@ describe('GameDetail', () => {
expect(JSON.parse(init.body)).toMatchObject({bannerAppid: 220, showBanner: true});
});
});
describe('GameDetail of a game added by hand', () => {
const manualGame = {
...game, appid: -1025, name: 'Zelda', source: 'MANUAL', platform: 'Nintendo Switch', playtimeMinutes: 90,
playtime2Weeks: 0, imageUrl: 'https://images.igdb.com/z.jpg',
};
beforeEach(() => {
globalThis.fetch = vi.fn(async (url, init) => (init?.method === 'PUT' || init?.method === 'DELETE')
? {ok: true, status: 204, json: async () => { throw new Error('204 has no body'); }}
: {ok: true, status: 200, json: async () => manualGame});
});
it('shows platform and IGDB picture, and offers no Steam actions', async () => {
const {container} = renderDetail(-1025);
expect(await screen.findByLabelText('MANUAL_GAME.PLATFORM')).toBeTruthy();
expect(screen.getAllByText('Nintendo Switch').length).toBeGreaterThan(0);
expect(container.querySelector('img[src="https://images.igdb.com/z.jpg"]')).toBeTruthy();
expect(screen.queryByRole('button', {name: 'GAME_DETAIL.SET_BACKGROUND'})).toBeNull();
expect(screen.queryByRole('button', {name: 'GAME_DETAIL.SET_BANNER'})).toBeNull();
expect(screen.queryByText('GAME_DETAIL.OPEN_IN_STEAM')).toBeNull();
expect(screen.getByText('MANUAL_GAME.NO_ACHIEVEMENTS')).toBeTruthy();
});
it('saves platform and hours', async () => {
renderDetail(-1025);
fireEvent.change(await screen.findByLabelText('MANUAL_GAME.HOURS'), {target: {value: '2.5'}});
fireEvent.change(screen.getByLabelText('MANUAL_GAME.PLATFORM'), {target: {value: ' PS5 '}});
const saveButtons = screen.getAllByRole('button', {name: 'BACKLOG.SAVE'});
fireEvent.click(saveButtons.at(-1));
await waitFor(() => expect(fetch.mock.calls.some(([, call]) => call?.method === 'PUT')).toBe(true));
const [url, init] = fetch.mock.calls.find(([, call]) => call?.method === 'PUT');
expect(url).toContain('/api/library/games/-1025/manual');
expect(JSON.parse(init.body)).toEqual({platform: 'PS5', playtimeMinutes: 150});
});
it('removes the game only after the confirm step and goes back to the library', async () => {
renderDetail(-1025);
fireEvent.click(await screen.findByRole('button', {name: 'MANUAL_GAME.REMOVE'}));
expect(fetch.mock.calls.some(([, call]) => call?.method === 'DELETE')).toBe(false);
fireEvent.click(screen.getByRole('button', {name: 'MANUAL_GAME.REMOVE_YES'}));
expect(await screen.findByText('library page')).toBeTruthy();
const [url] = fetch.mock.calls.find(([, call]) => call?.method === 'DELETE');
expect(url).toContain('/api/library/games/-1025');
});
it('keeps Save off for an unchanged game with 75 minutes', async () => {
globalThis.fetch = vi.fn(async () => ({ok: true, status: 200, json: async () => ({...manualGame, playtimeMinutes: 75})}));
renderDetail(-1025);
await screen.findByLabelText('MANUAL_GAME.HOURS');
expect(screen.getAllByRole('button', {name: 'BACKLOG.SAVE'}).at(-1).disabled).toBe(true);
});
it('shows no manual card for a Steam game', async () => {
globalThis.fetch = vi.fn(async () => ({ok: true, status: 200, json: async () => ({...game, source: 'STEAM'})}));
renderDetail();
expect(await screen.findByRole('button', {name: 'GAME_DETAIL.SET_BACKGROUND'})).toBeTruthy();
expect(screen.queryByText('MANUAL_GAME.TITLE')).toBeNull();
});
});
+43 -11
View File
@@ -7,7 +7,7 @@ import useForceSync from '../hooks/useForceSync.js';
import useSessionExpired from '../hooks/useSessionExpired.js';
import {formatPlaytime} from '../utils/games.js';
import {GAME_STATUSES, libraryQuery, parseStatus} from '../utils/backlog.js';
import {ArrowUpDown, ChevronLeft, ChevronRight, Clock, Library, RefreshCw, Search, SearchX, Timer, Trophy} from 'lucide-react';
import {ArrowUpDown, ChevronLeft, ChevronRight, Clock, Gamepad2, Library, Plus, RefreshCw, Search, SearchX, Timer, Trophy} from 'lucide-react';
import {Badge} from '@/components/ui/badge';
import {Button} from '@/components/ui/button';
@@ -15,6 +15,7 @@ import {Card} from '@/components/ui/card';
import {Input} from '@/components/ui/input';
import {Select, SelectContent, SelectItem, SelectTrigger, SelectValue} from '@/components/ui/select';
import {Skeleton} from '@/components/ui/skeleton';
import AddGamePanel from '../components/AddGamePanel.jsx';
import GameCover from '../components/GameCover.jsx';
import LibraryTabs from '../components/LibraryTabs.jsx';
import GameStatusBadge from '../components/GameStatusBadge.jsx';
@@ -54,6 +55,9 @@ export default function GameLibrary() {
const filtered = Boolean(status || q.trim() || shortOnly);
const librarySearch = searchParams.toString();
const [search, setSearch] = useState(q);
const [adding, setAdding] = useState(false);
// Starts true until /games-count answers, so a Steam user does not see the sync controls vanish and come back.
const [hasSteamId, setHasSteamId] = useState(true);
const [data, setData] = useState({content: [], page: 0, size, totalElements: 0, totalPages: 0});
const [isLoading, setIsLoading] = useState(true);
@@ -98,9 +102,23 @@ export default function GameLibrary() {
load();
}, [load]);
useEffect(() => {
if (!hasSession()) return undefined;
let cancelled = false;
apiFetch(`${import.meta.env.VITE_CORE_API_URL}/api/library/games-count`)
.then((response) => (response.ok ? response.json() : null))
.then((json) => {
if (!cancelled && json) setHasSteamId(json.hasSteamId);
})
.catch(() => {});
return () => {
cancelled = true;
};
}, []);
const expectInitialSync = !isLoading && !error && !filtered && data.totalElements === 0;
const sync = useLibrarySync({
enabled: true,
enabled: hasSteamId,
expectInitialSync,
onComplete: load,
onUnauthorized: expireSession,
@@ -153,14 +171,21 @@ export default function GameLibrary() {
<LibraryTabs/>
<h1 className="text-3xl font-bold tracking-tight">{t('LIBRARY.TITLE')}</h1>
<div className="flex flex-wrap items-center gap-3">
<SyncStatusBadge
status={sync.status}
lastSyncedAt={sync.lastSyncedAt}
isRunning={sync.isRunning}
/>
<Button variant="outline" size="sm" onClick={triggerSync} disabled={syncing}>
<RefreshCw className={syncing ? 'animate-spin' : ''}/>
{t('LIBRARY.RESYNC')}
{hasSteamId && (
<>
<SyncStatusBadge
status={sync.status}
lastSyncedAt={sync.lastSyncedAt}
isRunning={sync.isRunning}
/>
<Button variant="outline" size="sm" onClick={triggerSync} disabled={syncing}>
<RefreshCw className={syncing ? 'animate-spin' : ''}/>
{t('LIBRARY.RESYNC')}
</Button>
</>
)}
<Button variant="outline" size="sm" onClick={() => setAdding(true)} disabled={adding}>
<Plus/>{t('MANUAL_GAME.ADD_BUTTON')}
</Button>
</div>
</div>
@@ -189,6 +214,8 @@ export default function GameLibrary() {
</div>
</div>
{adding && <AddGamePanel onClose={() => setAdding(false)}/>}
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<div role="group" aria-label={t('BACKLOG.STATUS_LABEL')} className="flex flex-wrap gap-1.5">
{[null, ...GAME_STATUSES].map((s) => (
@@ -261,10 +288,15 @@ export default function GameLibrary() {
state={{librarySearch}}
className="group flex items-center gap-3 sm:gap-4 px-4 sm:px-5 py-3 transition-colors hover:bg-muted/50"
>
<GameCover appid={g.appid} className="w-16 sm:w-24 shrink-0"/>
<GameCover appid={g.appid} imageUrl={g.imageUrl} className="w-16 sm:w-24 shrink-0"/>
<span className="min-w-0 flex-1 truncate font-medium group-hover:text-primary transition-colors">
{g.name ?? `App ${g.appid}`}
</span>
{g.platform && (
<Badge variant="outline" className="hidden sm:inline-flex" title={g.platform}>
<Gamepad2 className="size-3"/>{g.platform}
</Badge>
)}
<GameStatusBadge status={g.status} compact/>
{g.achievementsTotal > 0 && g.achievementsUnlocked != null && (
<Badge variant="secondary" className="hidden sm:inline-flex tabular-nums"
+36
View File
@@ -127,3 +127,39 @@ describe('GameLibrary short games', () => {
expect(screen.getByRole('button', {name: 'LIBRARY.FILTER_SHORT'}).getAttribute('aria-pressed')).toBe('true');
});
});
describe('GameLibrary with games added by hand', () => {
const answer = (games, hasSteamId) => vi.fn(async (url) => ({
ok: true, status: 200,
json: async () => (String(url).includes('/games-count') ? {count: games.length, hasSteamId} : {...page, content: games}),
}));
const zelda = {appid: -1025, name: 'Zelda', playtimeMinutes: 90, status: 'BACKLOG', source: 'MANUAL',
platform: 'Nintendo Switch', imageUrl: 'https://images.igdb.com/z.jpg'};
it('shows the platform and the IGDB picture of a manual game', async () => {
globalThis.fetch = answer([zelda], true);
renderLibrary();
expect(await screen.findByText('Nintendo Switch')).toBeTruthy();
expect(document.querySelector('img[src="https://images.igdb.com/z.jpg"]')).toBeTruthy();
});
it('hides the Steam sync for a user without a Steam ID but still offers adding a game', async () => {
globalThis.fetch = answer([zelda], false);
renderLibrary();
await screen.findByText('Zelda');
await waitFor(() => expect(screen.queryByText('LIBRARY.RESYNC')).toBeNull());
expect(screen.getByRole('button', {name: 'MANUAL_GAME.ADD_BUTTON'})).toBeTruthy();
});
it('opens the add panel', async () => {
globalThis.fetch = answer([zelda], true);
renderLibrary();
fireEvent.click(await screen.findByRole('button', {name: 'MANUAL_GAME.ADD_BUTTON'}));
expect(screen.getByText('MANUAL_GAME.ADD_TITLE')).toBeTruthy();
expect(screen.getByText('LIBRARY.RESYNC')).toBeTruthy();
});
});
+1 -1
View File
@@ -25,7 +25,7 @@ function RankedGames({title, games, formatValue}) {
{games.map((g, idx) => (
<li key={g.appid} className="flex items-center gap-3 px-5 py-3">
<span className="w-4 text-right text-sm font-semibold text-muted-foreground tabular-nums">{idx + 1}</span>
<GameCover appid={g.appid} className="w-16 shrink-0"/>
<GameCover appid={g.appid} imageUrl={g.imageUrl} className="w-16 shrink-0"/>
<span className="min-w-0 flex-1 truncate font-medium">{g.name ?? `App ${g.appid}`}</span>
<span className="text-sm text-muted-foreground tabular-nums">{formatValue(g.value ?? 0)}</span>
</li>
+1 -1
View File
@@ -187,7 +187,7 @@ function PickCard({game, expireSession}) {
return (
<Card className="gap-3 overflow-hidden p-0">
<Link to={`/library/${game.appid}`} className="block">
<GameCover appid={game.appid} className="w-full"/>
<GameCover appid={game.appid} imageUrl={game.imageUrl} className="w-full"/>
</Link>
<div className="flex flex-1 flex-col gap-3 px-4 pb-4">
<Link to={`/library/${game.appid}`} className="font-semibold hover:text-primary transition-colors">
+2 -2
View File
@@ -149,7 +149,7 @@ export default function PublicProfilePage() {
<ul className="grid grid-cols-2 gap-3 sm:grid-cols-4">
{library.playing.map((g) => (
<li key={g.appid} className="space-y-1.5">
<GameCover appid={g.appid} className="w-full"/>
<GameCover appid={g.appid} imageUrl={g.imageUrl} className="w-full"/>
<div className="truncate text-sm font-medium">{g.name ?? `App ${g.appid}`}</div>
<div className="text-xs text-muted-foreground tabular-nums">{formatPlaytime(g.playtimeMinutes)}</div>
</li>
@@ -166,7 +166,7 @@ export default function PublicProfilePage() {
<ul className="divide-y">
{library.finished.map((g) => (
<li key={g.appid} className="flex items-center gap-3 sm:gap-4 px-4 sm:px-5 py-3">
<GameCover appid={g.appid} className="w-16 sm:w-24 shrink-0"/>
<GameCover appid={g.appid} imageUrl={g.imageUrl} className="w-16 sm:w-24 shrink-0"/>
<span className="min-w-0 flex-1 truncate font-medium">{g.name ?? `App ${g.appid}`}</span>
{g.rating && (
<span className="flex items-center gap-0.5" aria-label={t('BACKLOG.RATING_STARS', {count: g.rating})}>
+33
View File
@@ -0,0 +1,33 @@
import {apiFetch} from './api.js';
const LIBRARY_URL = () => `${import.meta.env.VITE_CORE_API_URL}/api/library`;
const JSON_HEADERS = {'Content-Type': 'application/json'};
// A game that is not on Steam has a negative key (minus its IGDB id). Steam art and the Steam store exist only for
// positive keys; Auth also takes only those as background or banner.
export const isSteamKey = (appid) => Number(appid) > 0;
export const hoursToMinutes = (hours) => {
const value = Number(String(hours).replace(',', '.'));
return Number.isFinite(value) && value > 0 ? Math.round(value * 60) : 0;
};
// The calls return the raw response; the caller handles the status.
export const searchGames = (query, signal) =>
apiFetch(`${LIBRARY_URL()}/game-search?${new URLSearchParams({q: query.trim()})}`, {signal});
export const addGame = ({igdbId, platform, status, playtimeMinutes}) =>
apiFetch(`${LIBRARY_URL()}/games`, {
method: 'POST',
headers: JSON_HEADERS,
body: JSON.stringify({igdbId, platform, status, playtimeMinutes}),
});
export const updateManualGame = (appid, {platform, playtimeMinutes}) =>
apiFetch(`${LIBRARY_URL()}/games/${appid}/manual`, {
method: 'PUT',
headers: JSON_HEADERS,
body: JSON.stringify({platform, playtimeMinutes}),
});
export const removeGame = (appid) => apiFetch(`${LIBRARY_URL()}/games/${appid}`, {method: 'DELETE'});