Public Access
feat(library): search IGDB and add games by hand
This commit is contained in:
1 parent
d9a39dda22
commit
444b03acee
17 files changed
+699
-35
No files matched your search
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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>
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
|
||||
Reference in new issue
Block a user