From 444b03acee87f212276005b09a00eb448b745c70 Mon Sep 17 00:00:00 2001 From: lobo Date: Fri, 25 Sep 2026 14:37:21 +0200 Subject: [PATCH] feat(library): search IGDB and add games by hand --- public/i18n/de.json | 29 +++- public/i18n/en.json | 29 +++- src/components/AddGamePanel.jsx | 212 ++++++++++++++++++++++++ src/components/AddGamePanel.test.jsx | 100 +++++++++++ src/components/CurrentlyPlayingCard.jsx | 2 +- src/components/GameCover.jsx | 6 +- src/components/ManualGameCard.jsx | 109 ++++++++++++ src/components/PileOfShameCard.jsx | 2 +- src/pages/Dashboard.jsx | 14 +- src/pages/GameDetail.jsx | 23 ++- src/pages/GameDetail.test.jsx | 77 ++++++++- src/pages/GameLibrary.jsx | 54 ++++-- src/pages/GameLibrary.test.jsx | 36 ++++ src/pages/LandingPage.jsx | 2 +- src/pages/PlayNextPage.jsx | 2 +- src/pages/PublicProfilePage.jsx | 4 +- src/utils/manualGames.js | 33 ++++ 17 files changed, 699 insertions(+), 35 deletions(-) create mode 100644 src/components/AddGamePanel.jsx create mode 100644 src/components/AddGamePanel.test.jsx create mode 100644 src/components/ManualGameCard.jsx create mode 100644 src/utils/manualGames.js diff --git a/public/i18n/de.json b/public/i18n/de.json index 91b4b38..e042edd 100644 --- a/public/i18n/de.json +++ b/public/i18n/de.json @@ -150,7 +150,7 @@ "LIBRARY": { "TITLE": "Spielebibliothek", "LOADING": "Lade Spiele …", - "EMPTY": "Noch keine Spiele. Synchronisiere deine Steam-Bibliothek.", + "EMPTY": "Noch keine Spiele. Synchronisiere deine Steam-Bibliothek oder füge ein Spiel hinzu.", "ERROR_LOAD": "Spiele konnten nicht geladen werden.", "PER_PAGE": "Pro Seite:", "SORT_BY": "Sortieren:", @@ -305,5 +305,32 @@ "EMPTY": "Dein Backlog ist leer. Stark!", "EMPTY_BUDGET": "Kein Backlog-Spiel passt zu dieser Dauer. Versuch eine längere.", "ERROR_LOAD": "Die Vorschläge konnten nicht geladen werden." + }, + "MANUAL_GAME": { + "ADD_BUTTON": "Spiel hinzufügen", + "ADD_TITLE": "Spiel hinzufügen", + "ADD_HINT": "Für Spiele, die du außerhalb von Steam besitzt, z. B. auf PlayStation, Switch oder Xbox.", + "SEARCH_PLACEHOLDER": "Spiel nach Namen suchen", + "SEARCHING": "Suche…", + "NO_HITS": "Kein Spiel gefunden.", + "UNAVAILABLE": "Spiele hinzufügen ist auf diesem Server aus.", + "SEARCH_FAILED": "Die Spielesuche antwortet nicht. Versuche es später noch einmal.", + "IN_LIBRARY": "In der Bibliothek", + "BACK_TO_SEARCH": "Zurück zur Suche", + "ADD": "Hinzufügen", + "ADDED": "{{name}} ist jetzt in deiner Bibliothek.", + "ADD_FAILED": "Das Spiel konnte nicht hinzugefügt werden.", + "ALREADY_IN_LIBRARY": "Dieses Spiel ist schon in deiner Bibliothek.", + "CLOSE": "Schließen", + "TITLE": "Selbst hinzugefügt", + "HINT": "Du hast dieses Spiel selbst hinzugefügt. Steam erfasst es nicht, trage die Stunden hier ein.", + "PLATFORM": "Plattform", + "HOURS": "Gespielte Stunden", + "REMOVE": "Aus der Bibliothek entfernen", + "REMOVE_CONFIRM": "Dieses Spiel mit Status, Bewertung und Notizen entfernen?", + "REMOVE_YES": "Ja, entfernen", + "REMOVE_NO": "Abbrechen", + "REMOVED": "Spiel entfernt.", + "NO_ACHIEVEMENTS": "Erfolge gibt es nur für Steam-Spiele." } } diff --git a/public/i18n/en.json b/public/i18n/en.json index 53eabd5..2403cc5 100644 --- a/public/i18n/en.json +++ b/public/i18n/en.json @@ -150,7 +150,7 @@ "LIBRARY": { "TITLE": "Game Library", "LOADING": "Loading games …", - "EMPTY": "No games yet. Try syncing your Steam library.", + "EMPTY": "No games yet. Sync your Steam library or add a game.", "ERROR_LOAD": "Could not load your games.", "PER_PAGE": "Per page:", "SORT_BY": "Sort by:", @@ -305,5 +305,32 @@ "EMPTY": "Your backlog is empty. Nice!", "EMPTY_BUDGET": "No backlog game fits this length. Try a longer one.", "ERROR_LOAD": "Could not load the picks." + }, + "MANUAL_GAME": { + "ADD_BUTTON": "Add game", + "ADD_TITLE": "Add a game", + "ADD_HINT": "For games you own outside Steam, e.g. on PlayStation, Switch or Xbox.", + "SEARCH_PLACEHOLDER": "Search a game by name", + "SEARCHING": "Searching…", + "NO_HITS": "No game found.", + "UNAVAILABLE": "Adding games is off on this server.", + "SEARCH_FAILED": "The game search did not answer. Try again later.", + "IN_LIBRARY": "In library", + "BACK_TO_SEARCH": "Back to search", + "ADD": "Add", + "ADDED": "{{name}} added to your library.", + "ADD_FAILED": "Could not add the game.", + "ALREADY_IN_LIBRARY": "This game is already in your library.", + "CLOSE": "Close", + "TITLE": "Added by hand", + "HINT": "You added this game yourself. Steam does not track it, so set the hours here.", + "PLATFORM": "Platform", + "HOURS": "Hours played", + "REMOVE": "Remove from library", + "REMOVE_CONFIRM": "Remove this game with its status, rating and notes?", + "REMOVE_YES": "Yes, remove", + "REMOVE_NO": "Cancel", + "REMOVED": "Game removed.", + "NO_ACHIEVEMENTS": "Achievements exist only for Steam games." } } diff --git a/src/components/AddGamePanel.jsx b/src/components/AddGamePanel.jsx new file mode 100644 index 0000000..5b33a0f --- /dev/null +++ b/src/components/AddGamePanel.jsx @@ -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 ( + +
+

+ + {t('MANUAL_GAME.ADD_TITLE')} +

+ +
+ + {picked ? ( + setPicked(null)} navigate={navigate} expireSession={expireSession}/> + ) : ( + <> +

{t('MANUAL_GAME.ADD_HINT')}

+
+ + setQuery(e.target.value)}/> +
+ + {searchState === 'loading' && ( +

+ {t('MANUAL_GAME.SEARCHING')} +

+ )} + {searchState === 'unavailable' &&

{t('MANUAL_GAME.UNAVAILABLE')}

} + {searchState === 'failed' &&

{t('MANUAL_GAME.SEARCH_FAILED')}

} + {searchState === 'done' && results.length === 0 && ( +

{t('MANUAL_GAME.NO_HITS')}

+ )} + {searchState === 'done' && results.length > 0 && ( +
    + {results.map((hit) => ( +
  • + +
  • + ))} +
+ )} + + )} +
+ ); +} + +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 ( +
+
+ +
{hit.name}{hit.year ? ` (${hit.year})` : ''}
+
+
+
+ + {hit.platforms.length > 0 ? ( + + ) : ( + setPlatform(e.target.value)}/> + )} +
+
+ + +
+
+ + setHours(e.target.value)}/> +
+
+
+ + +
+
+ ); +} diff --git a/src/components/AddGamePanel.test.jsx b/src/components/AddGamePanel.test.jsx new file mode 100644 index 0000000..104216c --- /dev/null +++ b/src/components/AddGamePanel.test.jsx @@ -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( + + + {}}/>}/> + detail page

}/> +
+
, + ); +} + +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(); + }); +}); diff --git a/src/components/CurrentlyPlayingCard.jsx b/src/components/CurrentlyPlayingCard.jsx index 9add25f..86aef97 100644 --- a/src/components/CurrentlyPlayingCard.jsx +++ b/src/components/CurrentlyPlayingCard.jsx @@ -30,7 +30,7 @@ export default function CurrentlyPlayingCard({games, syncing}) { {games.map((g) => (
  • - +
    {g.name ?? `App ${g.appid}`}
    diff --git a/src/components/GameCover.jsx b/src/components/GameCover.jsx index ebf658c..eaf832b 100644 --- a/src/components/GameCover.jsx +++ b/src/components/GameCover.jsx @@ -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}) { ) : ( (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 ( + +

    + + {t('MANUAL_GAME.TITLE')} +

    +

    {t('MANUAL_GAME.HINT')}

    + +
    +
    + + setPlatform(e.target.value)}/> +
    +
    + + setHours(e.target.value)}/> +
    +
    + +
    + {confirmRemove ? ( +
    + {t('MANUAL_GAME.REMOVE_CONFIRM')} + + +
    + ) : ( + + )} + +
    +
    + ); +} diff --git a/src/components/PileOfShameCard.jsx b/src/components/PileOfShameCard.jsx index 4140f5f..722bfca 100644 --- a/src/components/PileOfShameCard.jsx +++ b/src/components/PileOfShameCard.jsx @@ -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" > - + {suggestion.name ?? `App ${suggestion.appid}`} diff --git a/src/pages/Dashboard.jsx b/src/pages/Dashboard.jsx index 3293aa2..4125ce4 100644 --- a/src/pages/Dashboard.jsx +++ b/src/pages/Dashboard.jsx @@ -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 = () => { )} - {hasSteamId && ( + {showLibrary && (
    @@ -314,7 +316,7 @@ const Dashboard = () => { {index + 1} - +
    {g.name ?? `App ${g.appid}`} @@ -338,7 +340,7 @@ const Dashboard = () => {
    )} - {hasSteamId && ( + {showLibrary && (
    {summary && ( diff --git a/src/pages/GameDetail.jsx b/src/pages/GameDetail.jsx index 61da600..944ec6f 100644 --- a/src/pages/GameDetail.jsx +++ b/src/pages/GameDetail.jsx @@ -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 && ( <> - +

    @@ -143,12 +147,16 @@ export default function GameDetail() { {t('GAME_DETAIL.PLAYTIME', {time: formatPlaytime(data.playtimeMinutes)})} + {data.platform && ( + {data.platform} + )}

    -
    + {/* Store page, background and banner need Steam art, so a game off Steam has none of them. */} + {onSteam && +
    }
    @@ -183,10 +191,15 @@ export default function GameDetail() { setData((d) => ({...d, ...entry}))}/> + {manual && ( + setData((d) => ({...d, ...changes}))}/> + )} + {!data.hasAchievements && ( - {t('GAME_DETAIL.NO_ACHIEVEMENTS')} + {t(manual ? 'MANUAL_GAME.NO_ACHIEVEMENTS' : 'GAME_DETAIL.NO_ACHIEVEMENTS')} )} diff --git a/src/pages/GameDetail.test.jsx b/src/pages/GameDetail.test.jsx index ef67b33..998f4cb 100644 --- a/src/pages/GameDetail.test.jsx +++ b/src/pages/GameDetail.test.jsx @@ -13,9 +13,12 @@ const game = { rating: null, notes: null, priority: null, hasAchievements: false, statsVisible: false, achievements: [], }; -const renderDetail = () => render( - - }/> +const renderDetail = (appid = 220) => render( + + + }/> + library page

    }/> +
    , ); @@ -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(); + }); +}); diff --git a/src/pages/GameLibrary.jsx b/src/pages/GameLibrary.jsx index 231c55e..aec95b4 100644 --- a/src/pages/GameLibrary.jsx +++ b/src/pages/GameLibrary.jsx @@ -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() {

    {t('LIBRARY.TITLE')}

    - - + + )} +
    @@ -189,6 +214,8 @@ export default function GameLibrary() {
    + {adding && setAdding(false)}/>} +
    {[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" > - + {g.name ?? `App ${g.appid}`} + {g.platform && ( + + {g.platform} + + )} {g.achievementsTotal > 0 && g.achievementsUnlocked != null && ( { 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(); + }); +}); diff --git a/src/pages/LandingPage.jsx b/src/pages/LandingPage.jsx index 3259d2c..6a73148 100644 --- a/src/pages/LandingPage.jsx +++ b/src/pages/LandingPage.jsx @@ -25,7 +25,7 @@ function RankedGames({title, games, formatValue}) { {games.map((g, idx) => (
  • {idx + 1} - + {g.name ?? `App ${g.appid}`} {formatValue(g.value ?? 0)}
  • diff --git a/src/pages/PlayNextPage.jsx b/src/pages/PlayNextPage.jsx index 2b8b65c..3ea3908 100644 --- a/src/pages/PlayNextPage.jsx +++ b/src/pages/PlayNextPage.jsx @@ -187,7 +187,7 @@ function PickCard({game, expireSession}) { return ( - +
    diff --git a/src/pages/PublicProfilePage.jsx b/src/pages/PublicProfilePage.jsx index 14b36e6..36c44e6 100644 --- a/src/pages/PublicProfilePage.jsx +++ b/src/pages/PublicProfilePage.jsx @@ -149,7 +149,7 @@ export default function PublicProfilePage() {
      {library.playing.map((g) => (
    • - +
      {g.name ?? `App ${g.appid}`}
      {formatPlaytime(g.playtimeMinutes)}
    • @@ -166,7 +166,7 @@ export default function PublicProfilePage() {
        {library.finished.map((g) => (
      • - + {g.name ?? `App ${g.appid}`} {g.rating && ( diff --git a/src/utils/manualGames.js b/src/utils/manualGames.js new file mode 100644 index 0000000..89e9bfd --- /dev/null +++ b/src/utils/manualGames.js @@ -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'});