From 76dcccd36a6d8994dee7daa411b07ae4b5523abd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Elida=20Kj=C3=B8pstad?= <77298927+Stelaug@users.noreply.github.com> Date: Sat, 7 Nov 2026 12:33:01 +0100 Subject: [PATCH 1/3] code: updates storage to use a common helper, and creates components of the cards on the main page --- .../src/FrontendLogic/GameLogicFrontend.ts | 28 +- .../FrontendLogic/MainPageLogicFrontend.ts | 73 ++---- .../FrontendLogic/SearchPageLogicFrontend.ts | 94 ++----- Frontend/src/FrontendLogic/Storage.ts | 65 +++++ .../src/FrontendLogic/UserLogicFrontend.ts | 33 +-- .../FrontendLogic/WishlistLogicFrontend.ts | 17 +- Frontend/src/components/GenreGamesSection.tsx | 190 ++++++++++++++ Frontend/src/components/TopGames.tsx | 52 ++++ Frontend/src/pages/MainPage.tsx | 246 +----------------- Frontend/src/pages/SearchPage.tsx | 1 + Frontend/src/types/Game.ts | 20 ++ Frontend/src/types/User.ts | 6 + 12 files changed, 402 insertions(+), 423 deletions(-) create mode 100644 Frontend/src/FrontendLogic/Storage.ts create mode 100644 Frontend/src/components/GenreGamesSection.tsx create mode 100644 Frontend/src/components/TopGames.tsx create mode 100644 Frontend/src/types/User.ts diff --git a/Frontend/src/FrontendLogic/GameLogicFrontend.ts b/Frontend/src/FrontendLogic/GameLogicFrontend.ts index 7477352..99c901c 100644 --- a/Frontend/src/FrontendLogic/GameLogicFrontend.ts +++ b/Frontend/src/FrontendLogic/GameLogicFrontend.ts @@ -1,5 +1,6 @@ import type { Game } from '../../../Backend/Steam' import { BACKEND_URL } from './LogicConnection' +import { OrNull, ReadStored, RemoveStored, WriteStored } from './Storage' interface GraphQLResponse { data?: T @@ -57,33 +58,20 @@ function GameByIdCacheKey(appid: number): string { } function ReadCachedGames(key: string): Game[] | null { - try { - const rawCache = globalThis.localStorage?.getItem(key) - if (!rawCache) return null - - const cache: unknown = JSON.parse(rawCache) - const age = Date.now() - (IsCachedGames(cache) ? cache.fetchedAt : 0) - if (IsCachedGames(cache) && age >= 0 && age < CACHE_TTL_MS) { - return cache.games - } + const cache = ReadStored(key, null, OrNull(IsCachedGames), 'local') + if (!cache) return null - globalThis.localStorage.removeItem(key) - } catch (error) { - console.warn('Unable to read games from localStorage; fetching from the database.', error) + const age = Date.now() - (IsCachedGames(cache) ? cache.fetchedAt : 0) + if (IsCachedGames(cache) && age >= 0 && age < CACHE_TTL_MS) { + return cache.games } + RemoveStored(key, 'local') return null } function WriteCachedGames(key: string, games: Game[]): void { - try { - globalThis.localStorage?.setItem( - key, - JSON.stringify({ fetchedAt: Date.now(), games } satisfies CachedGames) - ) - } catch (error) { - console.warn('Unable to cache games in localStorage.', error) - } + WriteStored(key, { fetchedAt: Date.now(), games } satisfies CachedGames, 'local') } function FindCachedGameById(appid: number): Game | null { diff --git a/Frontend/src/FrontendLogic/MainPageLogicFrontend.ts b/Frontend/src/FrontendLogic/MainPageLogicFrontend.ts index b724b04..9ea4342 100644 --- a/Frontend/src/FrontendLogic/MainPageLogicFrontend.ts +++ b/Frontend/src/FrontendLogic/MainPageLogicFrontend.ts @@ -1,17 +1,19 @@ import { Gql } from './LogicConnection' import { type Game } from '../../../Backend/Steam' +import { IsBoolean, IsInteger, IsString, ReadStored, WriteStored } from '../FrontendLogic/Storage' + export type MainPageGenreSection = 'top10' | 'discounts' const GAME_FIELDS = `appid name price initialprice discount img genre description` +const DISCOUNT_ONLY_KEY = 'GameStart:discountedOnlySearchpage' +const RECENT_REVIEW_KEY = 'GameStart:recentReviewCountMainpage' +const DEFAULT_REVIEW_COUNT = 3 const mainPageGenreStorageKeys: Record = { top10: 'GameStart:genreMainpage:top10', discounts: 'GameStart:genreMainpage:discounts' } -const discountedOnlyStorageKey = 'GameStart:discountedOnlySearchpage' -const recentReviewCountStorageKey = 'GameStart:recentReviewCountMainpage' -const defaultRecentReviewCount = 3 function ReportStorageError(action: string, error: unknown) { const message = error instanceof Error ? error.message : String(error) @@ -19,77 +21,48 @@ function ReportStorageError(action: string, error: unknown) { } export function GetSavedMainPageGenre(section: MainPageGenreSection): string { - try { - const parsed = JSON.parse(sessionStorage.getItem(mainPageGenreStorageKeys[section]) ?? '""') - return typeof parsed === 'string' ? parsed : '' - } catch (error: unknown) { - ReportStorageError('read the saved genre', error) - return '' - } + return ReadStored(mainPageGenreStorageKeys[section], '', IsString, 'session', (error) => + ReportStorageError('Could not read the genre:', error) + ) } export function SaveMainPageGenre(section: MainPageGenreSection, genre: string) { - try { - sessionStorage.setItem(mainPageGenreStorageKeys[section], JSON.stringify(genre)) - } catch (error: unknown) { - ReportStorageError('save the genre', error) - } + WriteStored(mainPageGenreStorageKeys[section], genre) } export function GetDiscountedOnlySearchpage(): boolean { - try { - return JSON.parse(sessionStorage.getItem(discountedOnlyStorageKey) ?? 'false') === true - } catch (error: unknown) { - ReportStorageError('read the discounted-only filter', error) - return false - } + return ReadStored(DISCOUNT_ONLY_KEY, false, IsBoolean, 'session', (error) => + ReportStorageError('Could not read discounted only games:', error)) } export function SaveDiscountedOnlySearchpage(discountedOnly: boolean) { - try { - sessionStorage.setItem(discountedOnlyStorageKey, JSON.stringify(discountedOnly)) - } catch (error: unknown) { - ReportStorageError('save the discounted-only filter', error) - } + WriteStored(DISCOUNT_ONLY_KEY, discountedOnly) } export function GetSavedRecentReviewCount(): number { - try { - const saved = sessionStorage.getItem(recentReviewCountStorageKey) - if (saved === null) return defaultRecentReviewCount - - const parsed: unknown = JSON.parse(saved) - if (typeof parsed === 'number' && Number.isInteger(parsed) && parsed > 0) return parsed - return defaultRecentReviewCount - } catch (error: unknown) { - ReportStorageError('read the recent review count', error) - return defaultRecentReviewCount - } + return ReadStored(RECENT_REVIEW_KEY, DEFAULT_REVIEW_COUNT, IsInteger, 'session', (error) => + ReportStorageError('Could not read recent review count: ', error)) } export function SaveRecentReviewCount(count: number) { - try { - sessionStorage.setItem(recentReviewCountStorageKey, JSON.stringify(count)) - } catch (error: unknown) { - ReportStorageError('save the recent review count', error) - } + WriteStored(RECENT_REVIEW_KEY, count) } export function PrepareDiscountGenreSearch(genre: string) { - const searchPageValues: Record = { - 'GameStart:filtersSearchpage': JSON.stringify(genre ? [genre] : []), - [discountedOnlyStorageKey]: JSON.stringify(true), - 'GameStart:querySearchpage': JSON.stringify(''), - 'GameStart:sortOptionSearchpage': JSON.stringify(''), - 'GameStart:pageSearchpage': JSON.stringify(1) + const searchPageValues: Record = { + 'GameStart:filtersSearchpage': genre ? [genre] : [], + [DISCOUNT_ONLY_KEY]: true, + 'GameStart:querySearchpage': '', + 'GameStart:sortOptionSearchpage': '', + 'GameStart:pageSearchpage': 1 } try { for (const [key, value] of Object.entries(searchPageValues)) { - sessionStorage.setItem(key, value) + WriteStored(key, value) } } catch (error: unknown) { - ReportStorageError('prepare the discounted genre search', error) + ReportStorageError('Prepare the discounted genre search', error) } } diff --git a/Frontend/src/FrontendLogic/SearchPageLogicFrontend.ts b/Frontend/src/FrontendLogic/SearchPageLogicFrontend.ts index 9d5b791..91c3d11 100644 --- a/Frontend/src/FrontendLogic/SearchPageLogicFrontend.ts +++ b/Frontend/src/FrontendLogic/SearchPageLogicFrontend.ts @@ -1,4 +1,11 @@ import { Gql } from './LogicConnection' +import { IsBoolean, IsInteger, IsString, IsStringArray, ReadStored, RemoveStored, WriteStored } from './Storage' + +const filterStorageKey = 'GameStart:filtersSearchpage' +const sortStorageKey = 'GameStart:sortOptionSearchpage' +const queryStorageKey = 'GameStart:querySearchpage' +const pageStorageKey = 'GameStart:pageSearchpage' +const menuStorageKey = 'GameStart:filterMenuOpenSearchpage' export async function FetchGenres(): Promise { const data = await Gql<{ genres: string[] }>(`query { genres }`, {}) @@ -6,108 +13,41 @@ export async function FetchGenres(): Promise { } export function GetSavedFiltersSearchpage(): string[] { - try { - const parsed = JSON.parse(sessionStorage.getItem('GameStart:filtersSearchpage') ?? '[]') - return Array.isArray(parsed) ? parsed : [] - } catch { - return [] - } + return ReadStored(filterStorageKey, [], IsStringArray) } export function SaveFiltersSearchpage(filters: string[]) { - try { - sessionStorage.setItem('GameStart:filtersSearchpage', JSON.stringify(filters)) - } catch (error: unknown) { - const message = error instanceof Error ? error.message : String(error) - console.log(`Searchpage: Could not save filters to session storage: ${message}`) - } + WriteStored(filterStorageKey, filters) } export function GetQuerySearchpage(): string { - try { - const parsed = JSON.parse(sessionStorage.getItem('GameStart:querySearchpage') ?? '""') - return typeof parsed === 'string' ? parsed : '' - } catch { - return '' - } + return ReadStored(queryStorageKey, '', IsString) } export function SaveQuerySearchpage(query: string) { - try { - sessionStorage.setItem('GameStart:querySearchpage', JSON.stringify(query)) - } catch (error: unknown) { - const message = error instanceof Error ? error.message : String(error) - console.log(`Searchpage: Could not save search query to session storage: ${message}`) - } + WriteStored(queryStorageKey, query) } export function SaveSortOptionSearchpage(query: string) { - try { - sessionStorage.setItem('GameStart:sortOptionSearchpage', JSON.stringify(query)) - } catch (error: unknown) { - const message = error instanceof Error ? error.message : String(error) - console.log(`Searchpage: Could not save sorting option to session storage: ${message}`) - } + WriteStored(sortStorageKey, query) } export function GetSortOptionSearchpage(): string { - try { - const parsed = JSON.parse(sessionStorage.getItem('GameStart:sortOptionSearchpage') ?? '""') - return typeof parsed === 'string' ? parsed : '' - } catch { - return '' - } + return ReadStored(sortStorageKey, '', IsString) } export function SavePageSearchpage(pageNumber: number) { - try { - sessionStorage.setItem('GameStart:pageSearchpage', JSON.stringify(pageNumber)) - } catch (error: unknown) { - const message = error instanceof Error ? error.message : String(error) - console.log(`Searchpage: Could not save page to session storage: ${message}`) - } + WriteStored(pageStorageKey, pageNumber) } export function GetPageSearchpage(): number { - try { - const parsed = JSON.parse(sessionStorage.getItem('GameStart:pageSearchpage') ?? '1') - return Number.isInteger(parsed) && parsed >= 1 ? parsed : 1 - } catch { - return 1 - } + return ReadStored(pageStorageKey, 1, IsInteger) } export function SaveFilterMenuOpenSearchpage(isOpen: boolean) { - try { - sessionStorage.setItem('GameStart:filterMenuOpenSearchpage', JSON.stringify(isOpen)) - } catch (error: unknown) { - const message = error instanceof Error ? error.message : String(error) - console.log(`Searchpage: Could not save filter menu state to session storage: ${message}`) - } + WriteStored(menuStorageKey, isOpen) } export function GetFilterMenuOpenSearchpage(): boolean { - try { - return JSON.parse(sessionStorage.getItem('GameStart:filterMenuOpenSearchpage') ?? 'false') === true - } catch { - return false - } -} - -export function ClearFilterAndSort() { - try { - sessionStorage.removeItem('GameStart:sortOptionSearchpage') - sessionStorage.removeItem('GameStart:filtersSearchpage') - sessionStorage.removeItem('GameStart:filterMenuOpenSearchpage') - } catch (error) { - console.log(`Could not clear filters and sorting from storage`) - } -} - -export function ClearSearch() { - try { - sessionStorage.removeItem('GameStart:pageSearchpage') - } catch (error) { - console.log(`Could not clear search from storage`) - } + return ReadStored(menuStorageKey, false, IsBoolean) } \ No newline at end of file diff --git a/Frontend/src/FrontendLogic/Storage.ts b/Frontend/src/FrontendLogic/Storage.ts new file mode 100644 index 0000000..8eb58ca --- /dev/null +++ b/Frontend/src/FrontendLogic/Storage.ts @@ -0,0 +1,65 @@ +import type { User } from "../types/User" + +type StorageKind = 'session' | 'local' + +export const IsString = (value: unknown): value is string => typeof value === 'string' +export const IsBoolean = (value: unknown): value is boolean => typeof value === 'boolean' +// export const IsNumber = (value: unknown): value is number => +// typeof value === 'number' && Number.isFinite(value) && value > 0 +export const IsInteger = (value: unknown): value is number => typeof value === 'number' && Number.isInteger(value) && value > 0 +export const IsStringArray = (value: unknown): value is string[] => Array.isArray(value) +export const IsNull = (value: unknown): value is null => value === 'null' +export const IsUser = (value: unknown): value is User => { + if (typeof value !== 'object' || value === null) return false + const user = value as Partial> + return ( + typeof user.id === 'number' && + typeof user.email === 'string' && + typeof user.username === 'string' && + typeof user.token === 'string' + ) +} +export const OrNull = + (isValid: (value: unknown) => value is T) => + (value: unknown): value is T | null => + value === null || isValid(value) + +function GetStorage(kind: StorageKind): Storage { + return kind === 'local' ? localStorage : sessionStorage +} + +// Reads a value and returns the fallback if it is missing, corrupt or fails the check. +export function ReadStored( + key: string, + fallback: T, + isValid: (value: unknown) => value is T, + kind: StorageKind = 'session', + onError?: (error: unknown) => void +): T { + try { + const raw = GetStorage(kind).getItem(key) + if (raw === null) return fallback + const parsed: unknown = JSON.parse(raw) + return isValid(parsed) ? parsed : fallback + } catch (error) { + onError?.(error) + return fallback + } +} + +export function WriteStored(key: string, value: unknown, kind: StorageKind = 'session') { + try { + GetStorage(kind).setItem(key, JSON.stringify(value)) + } catch (error: unknown) { + const message = error instanceof Error ? error.message : String(error) + console.log(`Could not save "${key}" to ${kind} storage: ${message}`) + } +} + +export function RemoveStored(key: string, kind: StorageKind = 'session') { + try { + GetStorage(kind).removeItem(key) + } catch { + console.log(`Could not remove "${key}" from ${kind} storage`) + } +} \ No newline at end of file diff --git a/Frontend/src/FrontendLogic/UserLogicFrontend.ts b/Frontend/src/FrontendLogic/UserLogicFrontend.ts index e5b6f7e..269def9 100644 --- a/Frontend/src/FrontendLogic/UserLogicFrontend.ts +++ b/Frontend/src/FrontendLogic/UserLogicFrontend.ts @@ -1,7 +1,9 @@ import { Gql } from './LogicConnection' import type { User } from '../../../Backend/logic/UserLogicBackend' +import { IsUser, OrNull, ReadStored, RemoveStored, WriteStored } from './Storage' const USER_FIELDS = 'id email username token' +const USER_KEY = 'GameStart:user' // Calls upon the backend function to sign in a user. export async function SigninUser(email: string, password: string): Promise { @@ -30,40 +32,23 @@ export async function SignupUser(username: string, email: string, password: stri export function SaveUser(user: User, remember = true) { try { ClearUser() - const storage = remember ? localStorage : sessionStorage - storage.setItem('GameStart:user', JSON.stringify(user)) } catch (error: unknown) { const message = error instanceof Error ? error.message : String(error) console.log(`Could not save user information to storage: ${message}`) } + const typeStorage = remember ? 'local' : 'session' + WriteStored(USER_KEY, user, typeStorage) } // Returns the saved user or null if no user is found. export function GetSavedUser(): User | null { - try { - const raw = - localStorage.getItem('GameStart:user') ?? sessionStorage.getItem('GameStart:user') - if (!raw) return null - - const parsed = JSON.parse(raw) - if ( - typeof parsed?.id === 'number' && - typeof parsed?.email === 'string' && - typeof parsed?.username === 'string' && - typeof parsed?.token === 'string' - ) { - return parsed as User - } - - ClearUser() // a login from before tokens existed: ask the user to sign in again - return null - } catch { - return null - } + const user = ReadStored(USER_KEY, null, OrNull(IsUser), 'local') ?? ReadStored(USER_KEY, null, OrNull(IsUser)) + if (!user) ClearUser() + return user } //Clears the current user export function ClearUser() { - localStorage.removeItem('GameStart:user') - sessionStorage.removeItem('GameStart:user') + RemoveStored(USER_KEY) + RemoveStored(USER_KEY, 'local') } diff --git a/Frontend/src/FrontendLogic/WishlistLogicFrontend.ts b/Frontend/src/FrontendLogic/WishlistLogicFrontend.ts index c7b92f2..094f856 100644 --- a/Frontend/src/FrontendLogic/WishlistLogicFrontend.ts +++ b/Frontend/src/FrontendLogic/WishlistLogicFrontend.ts @@ -1,5 +1,8 @@ import { type Game } from '../../../Backend/Steam' import { Gql } from './LogicConnection' +import { IsString, ReadStored, WriteStored } from './Storage' + +const WISHLIST_KEY = 'GameStart:sortOptionWishlist' // Frontend function for calling backend to fetch wishlisted games of a user export async function FetchWishlistFrontend(userId: number | null): Promise { @@ -42,19 +45,9 @@ export function ToggleGameWishlist( } export function SaveSortOptionWishlist(query: string) { - try { - sessionStorage.setItem('GameStart:sortOptionWishlist', JSON.stringify(query)) - } catch (error: unknown) { - const message = error instanceof Error ? error.message : String(error) - console.log(`Searchpage: Could not save sorting option to session storage: ${message}`) - } + WriteStored(WISHLIST_KEY, query) } export function GetSortOptionWishlist(): string { - try { - const parsed = JSON.parse(sessionStorage.getItem('GameStart:sortOptionWishlist') ?? '""') - return typeof parsed === 'string' ? parsed : '' - } catch { - return 'discount-desc' - } + return ReadStored(WISHLIST_KEY, 'discount-desc', IsString) } diff --git a/Frontend/src/components/GenreGamesSection.tsx b/Frontend/src/components/GenreGamesSection.tsx new file mode 100644 index 0000000..f2d918f --- /dev/null +++ b/Frontend/src/components/GenreGamesSection.tsx @@ -0,0 +1,190 @@ +import { type Game } from '../types/Game' +import { + GetSavedMainPageGenre, + SaveMainPageGenre, + PrepareDiscountGenreSearch, + type MainPageGenreSection +} from '../FrontendLogic/MainPageLogicFrontend' +import { type CSSProperties, useEffect, useState } from 'react' +import { Autocomplete, Button, TextField, useMediaQuery, Card } from '@mui/material' +import type { PageGame } from '../types/Game' +import PassiveGameCard from './PassiveGameCard' +import { Link } from 'react-router-dom' + +const NO_GAMES: PageGame[] = [] + +export function ToPageGame(game: Game): PageGame { + const price = Number(game.price) + const salePercent = Number(game.discount) + const genres = + typeof game.genre === 'string' + ? game.genre + .split(',') + .map((genre) => genre.trim()) + .filter(Boolean) + : [] + + return { + id: game.appid, + name: game.name, + price: Number.isFinite(price) ? price : 0, + genre: genres, + image: game.img ?? '', + salePercent: Number.isFinite(salePercent) ? salePercent : 0 + } +} + +type GenreGamesSectionProps = { + title: string + genres: string[] + genresLoading: boolean + loadGames: (genre: string) => Promise + loadingText: string + emptyText: string + showSeeMore?: boolean + storageKey: MainPageGenreSection +} + +export function GenreGamesSection({ + title, + genres, + genresLoading, + loadGames, + loadingText, + emptyText, + showSeeMore = false, + storageKey +}: GenreGamesSectionProps) { + const [selectedGenre, setSelectedGenre] = useState(() => GetSavedMainPageGenre(storageKey)) + const [firstGameIndex, setFirstGameIndex] = useState(0) + const [result, setResult] = useState<{ + genre: string + games: PageGame[] + error: string | null + } | null>(null) + const isPhone = useMediaQuery('(max-width: 43.75rem)') + const isTwoColumnLayout = useMediaQuery('(max-width: 89.99rem)') + const visibleGameCount = isPhone ? 1 : isTwoColumnLayout ? 2 : 3 + const activeGenre = genres.includes(selectedGenre) ? selectedGenre : (genres[0] ?? '') + const isCurrent = result !== null && activeGenre !== '' && result.genre === activeGenre + const genreGames = isCurrent ? result.games : NO_GAMES + const loadError = isCurrent ? result.error : null + const gamesLoading = activeGenre !== '' && !isCurrent + const longestGenreLength = Math.max(0, ...genres.map((genre) => genre.length)) + const isLoading = genresLoading || gamesLoading + const maxStartIndex = Math.max(0, genreGames.length - visibleGameCount) + const startIndex = Math.min(firstGameIndex, maxStartIndex) + const visibleGames = genreGames.slice(startIndex, startIndex + visibleGameCount) + + useEffect(() => { + if (activeGenre) SaveMainPageGenre(storageKey, activeGenre) + }, [activeGenre, storageKey]) + + useEffect(() => { + if (!activeGenre) return undefined + let cancelled = false + + loadGames(activeGenre) + .then((games) => { + if (cancelled) return + setResult({ + genre: activeGenre, + games: games.map(ToPageGame).slice(0, 10), + error: null + }) + setFirstGameIndex(0) + }) + .catch((e: unknown) => { + if (cancelled) return + setResult({ + genre: activeGenre, + games: [], + error: e instanceof Error ? e.message : 'Could not load games' + }) + }) + + return () => { + cancelled = true + } + }, [activeGenre, loadGames]) + + const SelectGenre = (genre: string) => { + setSelectedGenre(genre) + } + + const OpenDiscountsInSearch = () => { + PrepareDiscountGenreSearch(activeGenre) + } + + return ( +
+
+

{title}

+
+ +
+ { + SelectGenre(genre ?? '') + }} + disabled={genres.length === 0} + renderInput={(params) => ( + + )} + /> +
+ {showSeeMore && ( +
+ + See More + +
+ )} +
+ {isLoading ? ( +

{loadingText}

+ ) : loadError ? ( +

+ {loadError} +

+ ) : visibleGames.length > 0 ? ( + visibleGames.map((game) => ) + ) : ( +

{emptyText}

+ )} +
+
+ + +
+
+
+ ) +} diff --git a/Frontend/src/components/TopGames.tsx b/Frontend/src/components/TopGames.tsx new file mode 100644 index 0000000..e9903e7 --- /dev/null +++ b/Frontend/src/components/TopGames.tsx @@ -0,0 +1,52 @@ +import { Card } from '@mui/material' +import type { PageGame } from '../types/Game' +import PassiveGameCard from './PassiveGameCard' + +interface TopGamesProps { + loading: boolean + featuredGames: PageGame[] +} + +export default function TopGames({ loading, featuredGames }: TopGamesProps) { + return ( +
+
+

Top 3 Games

+
+ + {loading ? ( +

Loading games...

+ ) : featuredGames.length === 0 ? ( +

No games found.

+ ) : ( +
+ {featuredGames[0] && ( +
+ +
+ )} + {featuredGames[1] && ( +
+ +
+ )} + {featuredGames[2] && ( +
+ +
+ )} +
+ )} +
+
+ ) +} diff --git a/Frontend/src/pages/MainPage.tsx b/Frontend/src/pages/MainPage.tsx index 3eab6a9..8da5e54 100644 --- a/Frontend/src/pages/MainPage.tsx +++ b/Frontend/src/pages/MainPage.tsx @@ -1,218 +1,22 @@ import '../css/MainPage.css' import Header from '../components/Header' import Footer from '../components/Footer' -import PassiveGameCard from '../components/PassiveGameCard' import { LoadTop3Games, LoadTopGamesByGenre, - LoadDiscountedGames, - GetSavedMainPageGenre, - SaveMainPageGenre, - PrepareDiscountGenreSearch, - type MainPageGenreSection + LoadDiscountedGames } from '../FrontendLogic/MainPageLogicFrontend' import { FetchGenres } from '../FrontendLogic/SearchPageLogicFrontend' -import type { Game } from '../../../Backend/Steam' import { Link } from 'react-router-dom' -import type { CSSProperties } from 'react' import { useEffect, useState } from 'react' -import { Autocomplete, Button, TextField, useMediaQuery, Card } from '@mui/material' +import { Button } from '@mui/material' import maskot_gamestart from '../assets/maskot_gamestart.png' import RecentReviews from '../components/RecentReviews' import { GetRecentReviews } from '../FrontendLogic/ReviewLogicFrontend' import type { Review } from '../types/Review' - -type PageGame = { - id: number - name: string - price: number - genre: string[] - image: string - salePercent: number -} - -const NO_GAMES: PageGame[] = [] - -function ToPageGame(game: Game): PageGame { - const price = Number(game.price) - const salePercent = Number(game.discount) - const genres = - typeof game.genre === 'string' - ? game.genre - .split(',') - .map((genre) => genre.trim()) - .filter(Boolean) - : [] - - return { - id: game.appid, - name: game.name, - price: Number.isFinite(price) ? price : 0, - genre: genres, - image: game.img ?? '', - salePercent: Number.isFinite(salePercent) ? salePercent : 0 - } -} - -type GenreGamesSectionProps = { - title: string - genres: string[] - genresLoading: boolean - loadGames: (genre: string) => Promise - loadingText: string - emptyText: string - showSeeMore?: boolean - storageKey: MainPageGenreSection -} - -function GenreGamesSection({ - title, - genres, - genresLoading, - loadGames, - loadingText, - emptyText, - showSeeMore = false, - storageKey -}: GenreGamesSectionProps) { - const [selectedGenre, setSelectedGenre] = useState(() => GetSavedMainPageGenre(storageKey)) - const [firstGameIndex, setFirstGameIndex] = useState(0) - const [result, setResult] = useState<{ - genre: string - games: PageGame[] - error: string | null - } | null>(null) - const isPhone = useMediaQuery('(max-width: 43.75rem)') - const isTwoColumnLayout = useMediaQuery('(max-width: 89.99rem)') - const visibleGameCount = isPhone ? 1 : isTwoColumnLayout ? 2 : 3 - const activeGenre = genres.includes(selectedGenre) ? selectedGenre : (genres[0] ?? '') - const isCurrent = result !== null && activeGenre !== '' && result.genre === activeGenre - const genreGames = isCurrent ? result.games : NO_GAMES - const loadError = isCurrent ? result.error : null - const gamesLoading = activeGenre !== '' && !isCurrent - const longestGenreLength = Math.max(0, ...genres.map((genre) => genre.length)) - const isLoading = genresLoading || gamesLoading - const maxStartIndex = Math.max(0, genreGames.length - visibleGameCount) - const startIndex = Math.min(firstGameIndex, maxStartIndex) - const visibleGames = genreGames.slice(startIndex, startIndex + visibleGameCount) - - useEffect(() => { - if (activeGenre) SaveMainPageGenre(storageKey, activeGenre) - }, [activeGenre, storageKey]) - - useEffect(() => { - if (!activeGenre) return undefined - let cancelled = false - - loadGames(activeGenre) - .then((games) => { - if (cancelled) return - setResult({ - genre: activeGenre, - games: games.map(ToPageGame).slice(0, 10), - error: null - }) - setFirstGameIndex(0) - }) - .catch((e: unknown) => { - if (cancelled) return - setResult({ - genre: activeGenre, - games: [], - error: e instanceof Error ? e.message : 'Could not load games' - }) - }) - - return () => { - cancelled = true - } - }, [activeGenre, loadGames]) - - const SelectGenre = (genre: string) => { - setSelectedGenre(genre) - } - - const OpenDiscountsInSearch = () => { - PrepareDiscountGenreSearch(activeGenre) - } - - return ( -
-
-

{title}

-
- -
- { - SelectGenre(genre ?? '') - }} - disabled={genres.length === 0} - renderInput={(params) => ( - - )} - /> -
- {showSeeMore && ( -
- -
- )} -
- {isLoading ? ( -

{loadingText}

- ) : loadError ? ( -

- {loadError} -

- ) : visibleGames.length > 0 ? ( - visibleGames.map((game) => ) - ) : ( -

{emptyText}

- )} -
-
- - -
-
-
- ) -} +import type { PageGame } from '../types/Game' +import { GenreGamesSection, ToPageGame } from '../components/GenreGamesSection' +import TopGames from '../components/TopGames' export default function MainPage() { const [featuredGames, setFeaturedGames] = useState([]) @@ -297,45 +101,7 @@ export default function MainPage() { {error}

)} -
-
-

Top 3 Games

-
- - {isLoadingFeatured ? ( -

Loading games...

- ) : featuredGames.length === 0 ? ( -

No games found.

- ) : ( -
- {featuredGames[0] && ( -
- -
- )} - {featuredGames[1] && ( -
- -
- )} - {featuredGames[2] && ( -
- -
- )} -
- )} -
-
+
diff --git a/Frontend/src/pages/SearchPage.tsx b/Frontend/src/pages/SearchPage.tsx index c03ac37..ceab444 100644 --- a/Frontend/src/pages/SearchPage.tsx +++ b/Frontend/src/pages/SearchPage.tsx @@ -118,6 +118,7 @@ export function SearchPage() { const HandleRemoveSearch = () => { setSearchVal('') setSearchQuery('') + setPage(1) } // These useEffects save the current filters, query and sorting option in session storage diff --git a/Frontend/src/types/Game.ts b/Frontend/src/types/Game.ts index 2258429..a8a84dc 100644 --- a/Frontend/src/types/Game.ts +++ b/Frontend/src/types/Game.ts @@ -9,4 +9,24 @@ export type GameData = { salePercent?: number } +export interface Game { + appid: number + name: string + price: string + initialprice: string + discount: string + img: string + genre: string + description: string +} + +export type PageGame = { + id: number + name: string + price: number + genre: string[] + image: string + salePercent: number +} + export type PassiveGameData = Pick diff --git a/Frontend/src/types/User.ts b/Frontend/src/types/User.ts new file mode 100644 index 0000000..76b0a8d --- /dev/null +++ b/Frontend/src/types/User.ts @@ -0,0 +1,6 @@ +export interface User { + id: number + email: string + username: string + token: string +} \ No newline at end of file From e1d75d14137e37a3ba343ff94fed6d8cd13719a0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Elida=20Kj=C3=B8pstad?= <77298927+Stelaug@users.noreply.github.com> Date: Sun, 8 Nov 2026 12:49:22 +0100 Subject: [PATCH 2/3] style: adds a slight css rework --- Frontend/src/components/ProfileEditor.tsx | 2 +- Frontend/src/components/ReviewCard.tsx | 2 +- Frontend/src/components/WishlistGameCard.tsx | 2 +- Frontend/src/css/ActiveGameCard.css | 18 +- Frontend/src/css/EditProfile.css | 28 +-- Frontend/src/css/FriendsPage.css | 31 +-- Frontend/src/css/GamePage.css | 6 - Frontend/src/css/Global.css | 207 +++++++++++++++++++ Frontend/src/css/Header.css | 5 - Frontend/src/css/MainPage.css | 53 +---- Frontend/src/css/ProfilePage.css | 7 - Frontend/src/css/Reviews.css | 2 +- Frontend/src/css/SearchPage.css | 62 ++---- Frontend/src/css/SignInUpCard.css | 20 +- Frontend/src/css/WishlistGameCard.css | 8 +- Frontend/src/css/WishlistPage.css | 20 +- Frontend/src/pages/MainPage.tsx | 9 +- Frontend/src/pages/ProfilePage.tsx | 2 +- 18 files changed, 246 insertions(+), 238 deletions(-) diff --git a/Frontend/src/components/ProfileEditor.tsx b/Frontend/src/components/ProfileEditor.tsx index b45fd97..427ef4e 100644 --- a/Frontend/src/components/ProfileEditor.tsx +++ b/Frontend/src/components/ProfileEditor.tsx @@ -123,7 +123,7 @@ export default function ProfileCard({ profile, gameOptions, onSave }: ProfileCar
diff --git a/Frontend/src/pages/ProfilePage.tsx b/Frontend/src/pages/ProfilePage.tsx index a2f55b7..2ffc68a 100644 --- a/Frontend/src/pages/ProfilePage.tsx +++ b/Frontend/src/pages/ProfilePage.tsx @@ -71,7 +71,7 @@ export default function ProfilePage() { actions={ user && profile && !isEditing ? (