diff --git a/Backend/tests/GameResolvers.test.ts b/Backend/tests/GameResolvers.test.ts
new file mode 100644
index 0000000..b06ea06
--- /dev/null
+++ b/Backend/tests/GameResolvers.test.ts
@@ -0,0 +1,46 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+const { Query } = vi.hoisted(() => ({ Query: vi.fn() }))
+
+vi.mock('../DatabaseConnection.ts', () => ({ pool: { query: Query } }))
+
+import { gameQueryResolvers } from '../resolvers/GameResolvers.ts'
+
+beforeEach(() => {
+ Query.mockReset()
+})
+
+describe('games resolver search', () => {
+ it('filters by name and returns the requested page', async () => {
+ const games = [{ appid: 570, name: 'Dota 2' }]
+ Query.mockResolvedValue({ rows: games })
+
+ const result = await gameQueryResolvers.games(null, {
+ search: 'dota',
+ limit: 20,
+ offset: 20
+ })
+
+ expect(result).toEqual(games)
+ expect(Query.mock.calls[0][0]).toContain('g.game_name ILIKE $1')
+ expect(Query.mock.calls[0][0]).toContain('LIMIT $4 OFFSET $5')
+ expect(Query.mock.calls[0][1].slice(-2)).toEqual([20, 20])
+ })
+
+ it('caps page size at the existing API maximum', async () => {
+ Query.mockResolvedValue({ rows: [] })
+
+ await gameQueryResolvers.games(null, { search: 'game', limit: 1000, offset: 0 })
+
+ expect(Query.mock.calls[0][1].slice(-2)).toEqual([500, 0])
+ })
+
+ it('passes database errors through', async () => {
+ Query.mockRejectedValue(new Error('connection refused'))
+
+ await expect(
+ gameQueryResolvers.games(null, { search: 'game', limit: 20, offset: 0 })
+ ).rejects.toThrow('connection refused')
+ })
+})
diff --git a/Frontend/index.html b/Frontend/index.html
index 10595f1..dc25ea3 100644
--- a/Frontend/index.html
+++ b/Frontend/index.html
@@ -2,7 +2,7 @@
-
+
t10-project-2
diff --git a/Frontend/src/FrontendLogic/ProfileLogicFrontend.ts b/Frontend/src/FrontendLogic/ProfileLogicFrontend.ts
index ea12e03..1f4867f 100644
--- a/Frontend/src/FrontendLogic/ProfileLogicFrontend.ts
+++ b/Frontend/src/FrontendLogic/ProfileLogicFrontend.ts
@@ -16,12 +16,35 @@ export async function FetchProfileFrontend(userId: number): Promise {
- const data = await Gql<{ gameOptions: GameOption[] }>(
- `query { gameOptions { appid name } }`,
- {}
+export async function FetchGameOptions(
+ options: {
+ search?: string
+ appid?: number
+ limit?: number
+ offset?: number
+ } = {}
+): Promise {
+ if (options.appid !== undefined) {
+ const data = await Gql<{ game: GameOption | null }>(
+ `query($appid: Int!) {
+ game(appid: $appid) { appid name }
+ }`,
+ { appid: options.appid }
+ )
+ return data.game ? [data.game] : []
+ }
+
+ const data = await Gql<{ games: GameOption[] }>(
+ `query($search: String, $limit: Int, $offset: Int) {
+ games(search: $search, limit: $limit, offset: $offset) { appid name }
+ }`,
+ {
+ search: options.search ?? null,
+ limit: options.limit ?? 20,
+ offset: options.offset ?? 0
+ }
)
- return data.gameOptions
+ return data.games
}
export async function UpdateProfileFrontend(
diff --git a/Frontend/src/assets/LogoGameStartTransparent.png b/Frontend/src/assets/LogoGameStartTransparent.png
deleted file mode 100644
index 3725d9f..0000000
Binary files a/Frontend/src/assets/LogoGameStartTransparent.png and /dev/null differ
diff --git a/Frontend/src/assets/LogoGameStartTransparent.webp b/Frontend/src/assets/LogoGameStartTransparent.webp
new file mode 100644
index 0000000..8fb2766
Binary files /dev/null and b/Frontend/src/assets/LogoGameStartTransparent.webp differ
diff --git a/Frontend/src/assets/maskot_gamestart.png b/Frontend/src/assets/maskot_gamestart.png
deleted file mode 100644
index dbc8a9a..0000000
Binary files a/Frontend/src/assets/maskot_gamestart.png and /dev/null differ
diff --git a/Frontend/src/assets/maskot_gamestart.webp b/Frontend/src/assets/maskot_gamestart.webp
new file mode 100644
index 0000000..2ede345
Binary files /dev/null and b/Frontend/src/assets/maskot_gamestart.webp differ
diff --git a/Frontend/src/assets/maskot_head_gamestart.png b/Frontend/src/assets/maskot_head_gamestart.png
deleted file mode 100644
index 35ad389..0000000
Binary files a/Frontend/src/assets/maskot_head_gamestart.png and /dev/null differ
diff --git a/Frontend/src/assets/maskot_head_gamestart.webp b/Frontend/src/assets/maskot_head_gamestart.webp
new file mode 100644
index 0000000..c5b3c35
Binary files /dev/null and b/Frontend/src/assets/maskot_head_gamestart.webp differ
diff --git a/Frontend/src/components/ActiveGameCard.tsx b/Frontend/src/components/ActiveGameCard.tsx
index e91546b..adac08a 100644
--- a/Frontend/src/components/ActiveGameCard.tsx
+++ b/Frontend/src/components/ActiveGameCard.tsx
@@ -142,6 +142,7 @@ export default function ActiveGameCard({
component="img"
image={game.image}
alt={`${game.name} game poster`}
+ loading="lazy"
/>
{isLoggedIn && (
diff --git a/Frontend/src/components/Header.tsx b/Frontend/src/components/Header.tsx
index ea68c1a..ea05bef 100644
--- a/Frontend/src/components/Header.tsx
+++ b/Frontend/src/components/Header.tsx
@@ -12,7 +12,7 @@ import {
Menu,
X
} from 'lucide-react'
-import gameStartLogo from '../assets/LogoGameStartTransparent.png'
+import gameStartLogo from '../assets/LogoGameStartTransparent.webp'
import Divider from '@mui/material/Divider'
import { UseAuth } from '../context/AuthContext'
@@ -56,7 +56,12 @@ export default function Header() {
-

+
diff --git a/Frontend/src/components/PassiveGameCard.tsx b/Frontend/src/components/PassiveGameCard.tsx
index fe26523..96291d9 100644
--- a/Frontend/src/components/PassiveGameCard.tsx
+++ b/Frontend/src/components/PassiveGameCard.tsx
@@ -38,7 +38,6 @@ export default function PassiveGameCard({ game, rank }: Props) {
resizeObserver.disconnect()
}
}, [game.name])
-
return (
(
gameOptions.find((option) => option.appid === profile.favouriteGame) ?? null
)
+ const [searchTerm, setSearchTerm] = useState('')
+ const debouncedSearchTerm = useDebouncedValue(searchTerm)
+ const [searchResults, setSearchResults] = useState([])
+ const [loadingGames, setLoadingGames] = useState(false)
+ const [loadingMoreGames, setLoadingMoreGames] = useState(false)
+ const [hasMoreGames, setHasMoreGames] = useState(false)
+ const [gameSearchError, setGameSearchError] = useState(null)
+ const requestId = useRef(0)
+ const loadingMore = useRef(false)
const [saving, setSaving] = useState(false)
const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null)
+ useEffect(() => {
+ const query = debouncedSearchTerm.trim()
+ if (query.length < 2) return
+ const currentRequestId = requestId.current
+
+ FetchGameOptions({ search: query, limit: GAME_OPTIONS_PAGE_SIZE, offset: 0 })
+ .then((options) => {
+ if (currentRequestId !== requestId.current) return
+ setSearchResults(options)
+ setHasMoreGames(options.length === GAME_OPTIONS_PAGE_SIZE)
+ })
+ .catch((err: unknown) => {
+ if (currentRequestId === requestId.current) {
+ setGameSearchError(
+ err instanceof Error ? err.message : 'Could not search games.'
+ )
+ }
+ })
+ .finally(() => {
+ if (currentRequestId === requestId.current) setLoadingGames(false)
+ })
+ }, [debouncedSearchTerm])
+
+ function ResetGameSearch() {
+ requestId.current += 1
+ loadingMore.current = false
+ setSearchTerm('')
+ setSearchResults([])
+ setLoadingGames(false)
+ setLoadingMoreGames(false)
+ setHasMoreGames(false)
+ setGameSearchError(null)
+ }
+
+ async function LoadMoreGames() {
+ const query = searchTerm.trim()
+ if (query.length < 2 || !hasMoreGames || loadingMore.current) return
+
+ loadingMore.current = true
+ setLoadingMoreGames(true)
+ const currentRequestId = requestId.current
+ try {
+ const options = await FetchGameOptions({
+ search: query,
+ limit: GAME_OPTIONS_PAGE_SIZE,
+ offset: searchResults.length
+ })
+ if (currentRequestId !== requestId.current) return
+ setSearchResults((current) => [
+ ...current,
+ ...options.filter(
+ (option) => !current.some((existing) => existing.appid === option.appid)
+ )
+ ])
+ setHasMoreGames(options.length === GAME_OPTIONS_PAGE_SIZE)
+ } catch (err) {
+ if (currentRequestId === requestId.current) {
+ setGameSearchError(
+ err instanceof Error ? err.message : 'Could not load more games.'
+ )
+ }
+ } finally {
+ if (currentRequestId === requestId.current) {
+ loadingMore.current = false
+ setLoadingMoreGames(false)
+ }
+ }
+ }
+
async function HandleSave() {
setSaving(true)
setMessage(null)
@@ -87,9 +168,44 @@ export default function ProfileCard({ profile, gameOptions, onSave }: ProfileCar
= 2 ? searchResults : game ? [game] : []}
value={game}
- onChange={(_, value) => setGame(value)}
+ onChange={(_, value) => {
+ setGame(value)
+ ResetGameSearch()
+ }}
+ onInputChange={(_, value, reason) => {
+ if (reason === 'input' || reason === 'clear') {
+ requestId.current += 1
+ loadingMore.current = false
+ setSearchTerm(value)
+ setSearchResults([])
+ setLoadingGames(value.trim().length >= 2)
+ setLoadingMoreGames(false)
+ setHasMoreGames(false)
+ setGameSearchError(null)
+ }
+ }}
+ loading={loadingGames || loadingMoreGames}
+ noOptionsText={
+ searchTerm.trim().length < 2
+ ? 'Type at least 2 characters to search'
+ : 'No games found'
+ }
+ filterOptions={(options) => options}
+ slotProps={{
+ listbox: {
+ onScroll: (event) => {
+ const listbox = event.currentTarget
+ if (
+ listbox.scrollTop + listbox.clientHeight >=
+ listbox.scrollHeight - 24
+ ) {
+ void LoadMoreGames()
+ }
+ }
+ }
+ }}
getOptionLabel={(option) => option.name}
isOptionEqualToValue={(a, b) => a.appid === b.appid}
renderOption={(props, option) => {
@@ -100,7 +216,14 @@ export default function ProfileCard({ profile, gameOptions, onSave }: ProfileCar
)
}}
- renderInput={(params) => }
+ renderInput={(params) => (
+
+ )}
/>
diff --git a/Frontend/src/components/SearchPageControls.tsx b/Frontend/src/components/SearchPageControls.tsx
new file mode 100644
index 0000000..94189d9
--- /dev/null
+++ b/Frontend/src/components/SearchPageControls.tsx
@@ -0,0 +1,148 @@
+import {
+ Button,
+ FormControl,
+ IconButton,
+ InputBase,
+ InputLabel,
+ MenuItem,
+ Paper,
+ Select
+} from '@mui/material'
+import type { SelectChangeEvent } from '@mui/material'
+import { Funnel, X } from 'lucide-react'
+
+export type SortOption =
+ '' | 'discount-desc' | 'price-asc' | 'price-desc' | 'title-asc' | 'title-desc'
+
+interface SearchPageControlsProps {
+ searchValue: string
+ searchQuery: string
+ onSearchChange: (value: string) => void
+ onSearchSubmit: (event: React.FormEvent) => void
+ onClearSearch: () => void
+ isFilterActive: boolean
+ onToggleFilters: () => void
+ genres: string[]
+ activeFilters: string[]
+ onFilterChange: (event: SelectChangeEvent
) => void
+ activeSorting: SortOption
+ onSortChange: (event: SelectChangeEvent) => void
+ onRemoveFilters: () => void
+ onReset: () => void
+}
+
+const DEFAULT_SORT: SortOption = 'title-asc'
+
+export default function SearchPageControls({
+ searchValue,
+ searchQuery,
+ onSearchChange,
+ onSearchSubmit,
+ onClearSearch,
+ isFilterActive,
+ onToggleFilters,
+ genres,
+ activeFilters,
+ onFilterChange,
+ activeSorting,
+ onSortChange,
+ onRemoveFilters,
+ onReset
+}: SearchPageControlsProps) {
+ return (
+ <>
+
+ onSearchChange(event.target.value)}
+ />
+
+
+
+
+
+
+
+ {isFilterActive && (
+
+
+ Sort by
+
+
+
+ Filter by genre
+
+
+
+
+
+ )}
+ >
+ )
+}
diff --git a/Frontend/src/components/SearchPageResults.tsx b/Frontend/src/components/SearchPageResults.tsx
new file mode 100644
index 0000000..7f896f5
--- /dev/null
+++ b/Frontend/src/components/SearchPageResults.tsx
@@ -0,0 +1,87 @@
+import { memo } from 'react'
+import { Pagination } from '@mui/material'
+import type { Game } from '../../../Backend/Steam'
+import PassiveGameCard from './PassiveGameCard'
+
+const SearchResultsGrid = memo(function SearchResultsGrid({ games }: { games: Game[] }) {
+ return (
+
+ {games.map((game) => {
+ const price = Number(game.price)
+ const salePercent = Number(game.discount)
+
+ return (
+
+ )
+ })}
+
+ )
+})
+
+interface SearchPageResultsProps {
+ games: Game[]
+ error: string | null
+ isLoading: boolean
+ totalCount: number
+ page: number
+ onPageChange: (page: number) => void
+}
+
+const GAMES_PER_PAGE = 12
+
+export default function SearchPageResults({
+ games,
+ error,
+ isLoading,
+ totalCount,
+ page,
+ onPageChange
+}: SearchPageResultsProps) {
+ const pageCount = Math.max(1, Math.ceil(totalCount / GAMES_PER_PAGE))
+
+ function HandleBottomPageChange(_: unknown, value: number) {
+ onPageChange(value)
+ window.scrollTo({ top: 0, behavior: 'smooth' })
+ }
+
+ return (
+ <>
+
+ {totalCount > 0 && (
+
+ {totalCount} {totalCount === 1 ? 'game' : 'games'} found
+
+ )}
+
onPageChange(value)}
+ />
+
+ {error && (
+
+ Could not load games: {error}
+
+ )}
+ {isLoading && games.length === 0 && Loading games...
}
+ {!isLoading && games.length === 0 && No games found.
}
+ {games.length > 0 && }
+
+ >
+ )
+}
diff --git a/Frontend/src/components/WishlistGameCard.tsx b/Frontend/src/components/WishlistGameCard.tsx
index 757e8b3..15d7635 100644
--- a/Frontend/src/components/WishlistGameCard.tsx
+++ b/Frontend/src/components/WishlistGameCard.tsx
@@ -49,6 +49,7 @@ export default function WishlistGameCard({
component="img"
image={game.image}
alt=""
+ loading="lazy"
/>
diff --git a/Frontend/src/hooks/useDebouncedValue.ts b/Frontend/src/hooks/useDebouncedValue.ts
new file mode 100644
index 0000000..41b9805
--- /dev/null
+++ b/Frontend/src/hooks/useDebouncedValue.ts
@@ -0,0 +1,14 @@
+import { useEffect, useState } from 'react'
+
+export const SEARCH_DEBOUNCE_MS = 400
+
+export function useDebouncedValue(value: T, delay = SEARCH_DEBOUNCE_MS): T {
+ const [debouncedValue, setDebouncedValue] = useState(value)
+
+ useEffect(() => {
+ const timeout = setTimeout(() => setDebouncedValue(value), delay)
+ return () => clearTimeout(timeout)
+ }, [value, delay])
+
+ return debouncedValue
+}
diff --git a/Frontend/src/hooks/useSearchPageResults.ts b/Frontend/src/hooks/useSearchPageResults.ts
new file mode 100644
index 0000000..343ca14
--- /dev/null
+++ b/Frontend/src/hooks/useSearchPageResults.ts
@@ -0,0 +1,109 @@
+import { useEffect, useMemo, useState } from 'react'
+import type { Game } from '../../../Backend/Steam'
+import FetchGamesFromDB, { GetTotalGameCount } from '../FrontendLogic/GameLogicFrontend'
+import { FetchGenres } from '../FrontendLogic/SearchPageLogicFrontend'
+
+const GAMES_PER_PAGE = 12
+const NO_GAMES: Game[] = []
+
+interface SearchPageResultsOptions {
+ page: number
+ search: string
+ genres: string[]
+ sort: string
+}
+
+interface SearchPageResult {
+ key: string
+ games: Game[]
+ error: string | null
+}
+
+function AreGamesEqual(first: Game[], second: Game[]): boolean {
+ return (
+ first.length === second.length &&
+ first.every((game, index) => {
+ const other = second[index]
+ return (
+ game.appid === other.appid &&
+ game.name === other.name &&
+ game.price === other.price &&
+ game.initialprice === other.initialprice &&
+ game.discount === other.discount &&
+ game.img === other.img &&
+ game.genre === other.genre &&
+ game.description === other.description
+ )
+ })
+ )
+}
+
+export function useSearchPageResults({ page, search, genres, sort }: SearchPageResultsOptions) {
+ const [result, setResult] = useState(null)
+ const [totalCount, setTotalCount] = useState(0)
+ const [availableGenres, setAvailableGenres] = useState([])
+
+ useEffect(() => {
+ FetchGenres().then(setAvailableGenres).catch(console.error)
+ }, [])
+
+ useEffect(() => {
+ let cancelled = false
+ GetTotalGameCount({ search, genres })
+ .then((count) => {
+ if (!cancelled) setTotalCount(count)
+ })
+ .catch(console.error)
+ return () => {
+ cancelled = true
+ }
+ }, [search, genres])
+
+ const requestKey = useMemo(
+ () => JSON.stringify([page, search, genres, sort]),
+ [page, search, genres, sort]
+ )
+ const isCurrent = result !== null && result.key === requestKey
+
+ useEffect(() => {
+ let cancelled = false
+ FetchGamesFromDB(GAMES_PER_PAGE, (page - 1) * GAMES_PER_PAGE, {
+ search,
+ genres,
+ sort
+ })
+ .then((loadedGames) => {
+ if (!cancelled) {
+ setResult((previous) => ({
+ key: requestKey,
+ games:
+ previous && AreGamesEqual(previous.games, loadedGames)
+ ? previous.games
+ : loadedGames,
+ error: null
+ }))
+ }
+ })
+ .catch((err: unknown) => {
+ if (!cancelled) {
+ setResult({
+ key: requestKey,
+ games: [],
+ error: err instanceof Error ? err.message : 'Could not load games'
+ })
+ }
+ })
+
+ return () => {
+ cancelled = true
+ }
+ }, [requestKey, page, search, genres, sort])
+
+ return {
+ genres: availableGenres,
+ totalCount,
+ games: result?.games ?? NO_GAMES,
+ error: isCurrent ? result.error : null,
+ isLoading: !isCurrent
+ }
+}
diff --git a/Frontend/src/pages/MainPage.tsx b/Frontend/src/pages/MainPage.tsx
index a2f67fe..71c4469 100644
--- a/Frontend/src/pages/MainPage.tsx
+++ b/Frontend/src/pages/MainPage.tsx
@@ -9,8 +9,8 @@ import {
import { FetchGenres } from '../FrontendLogic/SearchPageLogicFrontend'
import { Link } from 'react-router-dom'
import { useEffect, useState } from 'react'
-import { Button } from '@mui/material'
-import maskot_gamestart from '../assets/maskot_gamestart.png'
+import { Autocomplete, Button, TextField, useMediaQuery, Card } from '@mui/material'
+import maskot_gamestart from '../assets/maskot_gamestart.webp'
import RecentReviews from '../components/RecentReviews'
import { GetRecentReviews } from '../FrontendLogic/ReviewLogicFrontend'
import type { Review } from '../types/Review'
@@ -98,7 +98,12 @@ export default function MainPage() {
-

+
{error && (
diff --git a/Frontend/src/pages/ProfilePage.tsx b/Frontend/src/pages/ProfilePage.tsx
index e7eeaae..2f6ef06 100644
--- a/Frontend/src/pages/ProfilePage.tsx
+++ b/Frontend/src/pages/ProfilePage.tsx
@@ -32,10 +32,11 @@ export default function ProfilePage() {
async function Load(id: number) {
try {
- const [loaded, options] = await Promise.all([
- FetchProfileFrontend(id),
- FetchGameOptions()
- ])
+ const loaded = await FetchProfileFrontend(id)
+ const options =
+ loaded?.favouriteGame == null
+ ? []
+ : await FetchGameOptions({ appid: loaded.favouriteGame, limit: 1 })
if (cancelled) return
setProfile(loaded)
setGameOptions(options)
diff --git a/Frontend/src/pages/SearchPage.tsx b/Frontend/src/pages/SearchPage.tsx
index 6963314..4b95070 100644
--- a/Frontend/src/pages/SearchPage.tsx
+++ b/Frontend/src/pages/SearchPage.tsx
@@ -1,24 +1,14 @@
import '../css/SearchPage.css'
import Header from '../components/Header'
import Footer from '../components/Footer'
-import {
- InputLabel,
- FormControl,
- Select,
- MenuItem,
- Paper,
- InputBase,
- IconButton,
- Pagination,
- Button
-} from '@mui/material'
-import { Funnel, SearchIcon } from 'lucide-react'
-import { useState, useEffect, useMemo } from 'react'
import PageHeading from '../components/PageHeading'
-import PassiveGameCard from '../components/PassiveGameCard'
-import FetchGamesFromDB, { GetTotalGameCount } from '../FrontendLogic/GameLogicFrontend'
+import SearchPageControls, { type SortOption } from '../components/SearchPageControls'
+import SearchPageResults from '../components/SearchPageResults'
+import { useDebouncedValue } from '../hooks/useDebouncedValue'
+import { useSearchPageResults } from '../hooks/useSearchPageResults'
+import { useState, useEffect } from 'react'
+import type { SelectChangeEvent } from '@mui/material'
import {
- FetchGenres,
GetSavedFiltersSearchpage,
SaveFiltersSearchpage,
GetQuerySearchpage,
@@ -30,11 +20,6 @@ import {
SaveFilterMenuOpenSearchpage,
GetFilterMenuOpenSearchpage
} from '../FrontendLogic/SearchPageLogicFrontend'
-import type { Game } from '../../../Backend/Steam'
-import type { SelectChangeEvent } from '@mui/material'
-import { X } from 'lucide-react'
-
-type SortOption = '' | 'discount-desc' | 'price-asc' | 'price-desc' | 'title-asc' | 'title-desc'
const DEFAULT_SORT: SortOption = 'title-asc'
const SORT_OPTIONS: SortOption[] = [
@@ -44,9 +29,6 @@ const SORT_OPTIONS: SortOption[] = [
'price-asc',
'price-desc'
]
-const GAMES_PER_PAGE = 12
-
-const NO_GAMES: Game[] = []
const NO_FILTERS: string[] = []
function GetInitialSort(): SortOption {
@@ -55,56 +37,39 @@ function GetInitialSort(): SortOption {
}
export function SearchPage() {
- const [result, setResult] = useState<{
- key: string
- games: Game[]
- error: string | null
- } | null>(null)
- const [totalCount, setTotalCount] = useState(0)
const [page, setPage] = useState(GetPageSearchpage)
- const [genres, setGenres] = useState([])
const [activeFilters, setActiveFilters] = useState(GetSavedFiltersSearchpage)
const [activeSorting, setActiveSorting] = useState(GetInitialSort)
- const [searchVal, setSearchVal] = useState(GetQuerySearchpage)
- const [searchQuery, setSearchQuery] = useState(GetQuerySearchpage)
+ const [searchValue, setSearchValue] = useState(GetQuerySearchpage)
+ const searchQuery = useDebouncedValue(searchValue).trim()
const [isFilterActive, setIsFilterActive] = useState(GetFilterMenuOpenSearchpage)
const appliedFilters = isFilterActive && activeFilters.length > 0 ? activeFilters : NO_FILTERS
const appliedSorting = isFilterActive ? activeSorting : DEFAULT_SORT
+ const { genres, totalCount, games, error, isLoading } = useSearchPageResults({
+ page,
+ search: searchQuery,
+ genres: appliedFilters,
+ sort: appliedSorting
+ })
- // fetches the genres from the DB
- useEffect(() => {
- FetchGenres().then(setGenres).catch(console.error)
- }, [])
-
- // Opens the filter menu
const ToggleActive = () => {
const hasSelection = activeFilters.length > 0 || activeSorting !== DEFAULT_SORT
- if (hasSelection) {
- setPage(1)
- }
+ if (hasSelection) setPage(1)
setIsFilterActive(!isFilterActive)
}
- // saves the filter menu state (open: yes/no)
- useEffect(() => {
- SaveFilterMenuOpenSearchpage(isFilterActive)
- }, [isFilterActive])
-
- const HandleSearchSubmit = (e: React.FormEvent) => {
- e.preventDefault()
- const q = searchVal.trim()
- setSearchQuery(q)
- setPage(1)
+ const HandleSearchSubmit = (event: React.FormEvent) => {
+ event.preventDefault()
}
- const HandleFilterChange = (e: SelectChangeEvent) => {
- const { value } = e.target
+ const HandleFilterChange = (event: SelectChangeEvent) => {
+ const { value } = event.target
setActiveFilters(typeof value === 'string' ? value.split(',') : value)
setPage(1)
}
- const HandleSortChange = (e: SelectChangeEvent) => {
- setActiveSorting(e.target.value as SortOption)
+ const HandleSortChange = (event: SelectChangeEvent) => {
+ setActiveSorting(event.target.value as SortOption)
setPage(1)
}
@@ -114,243 +79,67 @@ export function SearchPage() {
}
const HandleReset = () => {
- setSearchVal('')
- setSearchQuery('')
+ setSearchValue('')
setActiveFilters(NO_FILTERS)
setActiveSorting(DEFAULT_SORT)
setPage(1)
}
const HandleRemoveSearch = () => {
- setSearchVal('')
- setSearchQuery('')
+ setSearchValue('')
setPage(1)
}
- // These useEffects save the current filters, query and sorting option in session storage
- // so that when the user goes back to the searchpage they are kept.
+ useEffect(() => {
+ SaveFilterMenuOpenSearchpage(isFilterActive)
+ }, [isFilterActive])
+
useEffect(() => {
SaveFiltersSearchpage(activeFilters)
}, [activeFilters])
+
useEffect(() => {
SaveSortOptionSearchpage(activeSorting)
}, [activeSorting])
+
useEffect(() => {
SaveQuerySearchpage(searchQuery)
}, [searchQuery])
+
useEffect(() => {
SavePageSearchpage(page)
}, [page])
- // Total count of games matching the current search and filters
- useEffect(() => {
- let cancelled = false
- GetTotalGameCount({ search: searchQuery, genres: appliedFilters })
- .then((count) => {
- if (!cancelled) setTotalCount(count)
- })
- .catch(console.error)
- return () => {
- cancelled = true
- }
- }, [searchQuery, appliedFilters])
-
- const requestKey = useMemo(
- () => JSON.stringify([page, searchQuery, appliedFilters, appliedSorting]),
- [page, searchQuery, appliedFilters, appliedSorting]
- )
- const isCurrent = result !== null && result.key === requestKey
- const games = isCurrent ? result.games : NO_GAMES
- const error = isCurrent ? result.error : null
- const isLoading = !isCurrent
-
- // One page of games, reloaded whenever page, search, filters or sorting change
- useEffect(() => {
- let cancelled = false
-
- FetchGamesFromDB(GAMES_PER_PAGE, (page - 1) * GAMES_PER_PAGE, {
- search: searchQuery,
- genres: appliedFilters,
- sort: appliedSorting
- })
- .then((loadedGames) => {
- if (!cancelled) setResult({ key: requestKey, games: loadedGames, error: null })
- })
- .catch((err: unknown) => {
- if (!cancelled) {
- setResult({
- key: requestKey,
- games: [],
- error: err instanceof Error ? err.message : 'Could not load games'
- })
- }
- })
-
- return () => {
- cancelled = true
- }
- }, [requestKey, page, searchQuery, appliedFilters, appliedSorting])
-
- // Decides games per page and makes a constant for the pagination
- const pageCount = Math.max(1, Math.ceil(totalCount / GAMES_PER_PAGE))
-
return (
-
- setSearchVal(e.target.value)}
- />
-
-
-
-
-
-
-
-
-
-
-
- {isFilterActive && (
-
-
- Sort by
-
-
-
-
- Filter by genre
-
-
-
-
-
- )}
-
- {totalCount > 0 && (
-
- {totalCount} {totalCount === 1 ? 'game' : 'games'} found
-
- )}
-
-
setPage(value)}
- />
-
- {error && (
-
- Could not load games: {error}
-
- )}
- {isLoading ? (
-
Loading games...
- ) : games.length === 0 ? (
-
No games found.
- ) : (
-
- {games.map((game) => {
- const price = Number(game.price)
- const salePercent = Number(game.discount)
-
- return (
-
- )
- })}
-
- )}
-
{
- setPage(value)
- window.scrollTo({ top: 0, behavior: 'smooth' })
+ {
+ setSearchValue(value)
+ setPage(1)
}}
+ onSearchSubmit={HandleSearchSubmit}
+ onClearSearch={HandleRemoveSearch}
+ isFilterActive={isFilterActive}
+ onToggleFilters={ToggleActive}
+ genres={genres}
+ activeFilters={activeFilters}
+ onFilterChange={HandleFilterChange}
+ activeSorting={activeSorting}
+ onSortChange={HandleSortChange}
+ onRemoveFilters={HandleRemoveFilters}
+ onReset={HandleReset}
+ />
+
diff --git a/Frontend/src/tests/ProfileLogicFrontend.test.ts b/Frontend/src/tests/ProfileLogicFrontend.test.ts
index bc9ef60..379b65a 100644
--- a/Frontend/src/tests/ProfileLogicFrontend.test.ts
+++ b/Frontend/src/tests/ProfileLogicFrontend.test.ts
@@ -55,28 +55,44 @@ describe('FetchProfileFrontend', () => {
})
describe('FetchGameOptions', () => {
- it('returns the list of game options', async () => {
+ it('returns the list of game options for a search page', async () => {
const options = [
{ appid: 10, name: 'Counter-Strike' },
{ appid: 570, name: 'Dota 2' }
]
- GqlMock.mockResolvedValue({ gameOptions: options })
+ GqlMock.mockResolvedValue({ games: options })
- expect(await FetchGameOptions()).toEqual(options)
+ expect(await FetchGameOptions({ search: 'dota', limit: 20, offset: 20 })).toEqual(options)
})
- it('asks only for id and name', async () => {
- GqlMock.mockResolvedValue({ gameOptions: [] })
+ it('sends search and pagination variables', async () => {
+ GqlMock.mockResolvedValue({ games: [] })
- await FetchGameOptions()
+ await FetchGameOptions({ search: 'counter', limit: 20, offset: 40 })
- expect(GqlMock.mock.calls[0][0]).toContain('gameOptions { appid name }')
+ expect(GqlMock.mock.calls[0][0]).toContain(
+ 'games(search: $search, limit: $limit, offset: $offset)'
+ )
+ expect(GqlMock.mock.calls[0][1]).toEqual({
+ search: 'counter',
+ limit: 20,
+ offset: 40
+ })
+ })
+
+ it('can fetch a saved favorite by its app id', async () => {
+ GqlMock.mockResolvedValue({ game: { appid: 570, name: 'Dota 2' } })
+
+ expect(await FetchGameOptions({ appid: 570, limit: 1 })).toEqual([
+ { appid: 570, name: 'Dota 2' }
+ ])
+ expect(GqlMock.mock.calls[0][1]).toEqual({ appid: 570 })
})
it('returns an empty list when there are no games', async () => {
- GqlMock.mockResolvedValue({ gameOptions: [] })
+ GqlMock.mockResolvedValue({ games: [] })
- expect(await FetchGameOptions()).toEqual([])
+ expect(await FetchGameOptions({ search: 'missing' })).toEqual([])
})
it('passes errors through', async () => {
diff --git a/Frontend/src/tests/SearchPage.test.tsx b/Frontend/src/tests/SearchPage.test.tsx
index e127889..ab56963 100644
--- a/Frontend/src/tests/SearchPage.test.tsx
+++ b/Frontend/src/tests/SearchPage.test.tsx
@@ -1,10 +1,11 @@
// @vitest-environment jsdom
-import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { MemoryRouter } from 'react-router-dom'
import type { Game } from '../../../Backend/Steam'
+import { SEARCH_DEBOUNCE_MS } from '../hooks/useDebouncedValue'
-const { FetchGamesFromDB, GetTotalGameCount, FetchGenres } = vi.hoisted(() => ({
+const { FetchGamesFromDB, GetTotalGameCount, FetchGenres, RenderGameCard } = vi.hoisted(() => ({
FetchGamesFromDB:
vi.fn<
(
@@ -14,7 +15,8 @@ const { FetchGamesFromDB, GetTotalGameCount, FetchGenres } = vi.hoisted(() => ({
) => Promise
>(),
GetTotalGameCount: vi.fn<() => Promise>(),
- FetchGenres: vi.fn<() => Promise>()
+ FetchGenres: vi.fn<() => Promise>(),
+ RenderGameCard: vi.fn()
}))
vi.mock('../FrontendLogic/GameLogicFrontend', () => ({
@@ -45,14 +47,39 @@ vi.mock('../components/PageHeading', () => ({
default: ({ title }: { title: string }) => {title}
}))
-vi.mock('../components/PassiveGameCard', () => ({
- default: ({ game }: { game: { name: string; price: number } }) => (
-
- {game.name}
- {game.price.toFixed(2)}
-
- )
-}))
+vi.mock('../components/PassiveGameCard', async () => {
+ const { memo } = await import('react')
+
+ return {
+ default: memo(
+ ({
+ game
+ }: {
+ game: {
+ id: number
+ name: string
+ price: number
+ image: string
+ salePercent?: number
+ }
+ }) => {
+ RenderGameCard(game)
+ return (
+
+ {game.name}
+ {game.price.toFixed(2)}
+
+ )
+ },
+ (previous, next) =>
+ previous.game.id === next.game.id &&
+ previous.game.name === next.game.name &&
+ previous.game.price === next.game.price &&
+ previous.game.image === next.game.image &&
+ previous.game.salePercent === next.game.salePercent
+ )
+ }
+})
import { SearchPage } from '../pages/SearchPage'
@@ -171,6 +198,7 @@ describe('SearchPage', () => {
FetchGamesFromDB.mockReset()
GetTotalGameCount.mockReset()
FetchGenres.mockReset()
+ RenderGameCard.mockReset()
GetTotalGameCount.mockResolvedValue(3)
FetchGenres.mockResolvedValue(['Action', 'Adventure', 'Indie', 'Strategy'])
sessionStorage.clear()
@@ -178,6 +206,7 @@ describe('SearchPage', () => {
afterEach(() => {
cleanup()
+ vi.useRealTimers()
})
describe('loading and rendering', () => {
@@ -269,7 +298,7 @@ describe('SearchPage', () => {
expect(GetTotalGameCount).toHaveBeenLastCalledWith({ search: 'DOO', genres: [] })
})
- it('does not search until the search is submitted', async () => {
+ it('debounces a search while the user is typing', async () => {
await RenderWithNamedGames()
fireEvent.change(screen.getByPlaceholderText('Search here or use filter'), {
@@ -278,17 +307,30 @@ describe('SearchPage', () => {
expect(FetchGamesFromDB).toHaveBeenCalledTimes(1)
expect(LastOptions()?.search).toBe('')
+ await waitFor(() => expect(LastOptions()?.search).toBe('doom'))
})
- it('works with the search button', async () => {
+ it('searches after the debounce delay when the form is submitted', async () => {
await RenderWithNamedGames()
- fireEvent.change(screen.getByPlaceholderText('Search here or use filter'), {
+ vi.useFakeTimers()
+ const input = screen.getByPlaceholderText('Search here or use filter')
+ fireEvent.change(input, {
target: { value: 'celeste' }
})
- fireEvent.click(screen.getByRole('button', { name: 'search' }))
+ fireEvent.submit(input.closest('form') as HTMLFormElement)
+
+ expect(FetchGamesFromDB).toHaveBeenCalledTimes(1)
- await waitFor(() => expect(LastOptions()?.search).toBe('celeste'))
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(SEARCH_DEBOUNCE_MS - 1)
+ })
+ expect(FetchGamesFromDB).toHaveBeenCalledTimes(1)
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1)
+ })
+ expect(LastOptions()?.search).toBe('celeste')
})
it('shows an empty state when nothing matches', async () => {
@@ -304,6 +346,30 @@ describe('SearchPage', () => {
expect(ShownTitles()).toHaveLength(0)
})
+ it('keeps the existing game section while an identical search result loads', async () => {
+ await RenderWithNamedGames()
+ const initialCardRenderCount = RenderGameCard.mock.calls.length
+ let resolveSearch!: (games: Game[]) => void
+ FetchGamesFromDB.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ resolveSearch = resolve
+ })
+ )
+
+ Search('doom')
+
+ await waitFor(() => expect(FetchGamesFromDB).toHaveBeenCalledTimes(2))
+ expect(LastOptions()?.search).toBe('doom')
+ expect(screen.queryByText('Loading games...')).toBeNull()
+ expect(ShownTitles()).toEqual(['Doom', 'Celeste', 'Anno'])
+
+ await act(async () => resolveSearch(namedGames))
+ await waitFor(() => expect(screen.queryByText('Loading games...')).toBeNull())
+
+ expect(RenderGameCard).toHaveBeenCalledTimes(initialCardRenderCount)
+ })
+
it('searches with an empty string when the search is cleared', async () => {
await RenderWithNamedGames()
diff --git a/Frontend/src/tests/useDebouncedValue.test.ts b/Frontend/src/tests/useDebouncedValue.test.ts
new file mode 100644
index 0000000..4ded87a
--- /dev/null
+++ b/Frontend/src/tests/useDebouncedValue.test.ts
@@ -0,0 +1,42 @@
+// @vitest-environment jsdom
+import { act, renderHook } from '@testing-library/react'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { SEARCH_DEBOUNCE_MS, useDebouncedValue } from '../hooks/useDebouncedValue'
+
+afterEach(() => {
+ vi.useRealTimers()
+})
+
+describe('useDebouncedValue', () => {
+ it('updates the value after the shared debounce delay', () => {
+ vi.useFakeTimers()
+ const { result, rerender } = renderHook(({ value }) => useDebouncedValue(value), {
+ initialProps: { value: 'first' }
+ })
+
+ rerender({ value: 'second' })
+ expect(result.current).toBe('first')
+
+ act(() => vi.advanceTimersByTime(SEARCH_DEBOUNCE_MS - 1))
+ expect(result.current).toBe('first')
+
+ act(() => vi.advanceTimersByTime(1))
+ expect(result.current).toBe('second')
+ })
+
+ it('restarts the delay when the input changes before it expires', () => {
+ vi.useFakeTimers()
+ const { result, rerender } = renderHook(({ value }) => useDebouncedValue(value), {
+ initialProps: { value: 'first' }
+ })
+
+ rerender({ value: 'second' })
+ act(() => vi.advanceTimersByTime(SEARCH_DEBOUNCE_MS - 1))
+ rerender({ value: 'third' })
+ act(() => vi.advanceTimersByTime(SEARCH_DEBOUNCE_MS - 1))
+ expect(result.current).toBe('first')
+
+ act(() => vi.advanceTimersByTime(1))
+ expect(result.current).toBe('third')
+ })
+})
diff --git a/README.md b/README.md
index 247ed04..0886ed7 100644
--- a/README.md
+++ b/README.md
@@ -82,9 +82,9 @@ src
┃ ┣ UserLogicFrontend.ts
┃ ┗ WishlistLogicFrontend.ts
┣ assets
- ┃ ┣ LogoGameStartTransparent.png
- ┃ ┣ maskot_gamestart.png
- ┃ ┗ maskot_head_gamestart.png
+ ┃ ┣ LogoGameStartTransparent.webp
+ ┃ ┣ maskot_gamestart.webp
+ ┃ ┗ maskot_head_gamestart.webp
┣ backend
┃ ┣ DatabaseConnection.ts
┃ ┣ FriendLogicBackend.ts