Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 15 additions & 10 deletions Frontend/src/FrontendLogic/GameLogicFrontend.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,20 @@
import type { Game } from '../../../Backend/Steam'
import { BACKEND_URL } from './LogicConnection'
import { BACKEND_URL, NETWORK_ERROR_MESSAGE } from './LogicConnection'
import { OrNull, ReadStored, RemoveStored, WriteStored } from './Storage'

interface GraphQLResponse<T> {
data?: T
errors?: { message: string }[]
}

async function FetchBackend(init: RequestInit): Promise<Response> {
try {
return await fetch(BACKEND_URL, init)
} catch {
throw new Error(NETWORK_ERROR_MESSAGE)
}
}

const CACHE_TTL_MS = 12 * 60 * 60 * 1000
const GAMES_CACHE_PREFIX = `games:v2:${encodeURIComponent(BACKEND_URL)}:`

Expand Down Expand Up @@ -105,7 +113,7 @@ export async function GetGameById(appid: number): Promise<Game | null> {
const cachedGame = FindCachedGameById(appid)
if (cachedGame) return cachedGame

const response = await fetch(BACKEND_URL, {
const response = await FetchBackend({
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
Expand All @@ -128,8 +136,7 @@ export async function GetGameById(appid: number): Promise<Game | null> {
})

if (!response.ok) {
const body = await response.text()
throw new Error(`Failed to fetch game: ${response.status} ${body}`)
throw new Error(`Failed to fetch game: ${response.status}`)
}

const { data, errors } = (await response.json()) as GraphQLResponse<{
Expand All @@ -151,7 +158,7 @@ async function FetchGamesFromDB(
const cachedGames = ReadCachedGames(cacheKey)
if (cachedGames) return cachedGames

const response = await fetch(BACKEND_URL, {
const response = await FetchBackend({
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
Expand Down Expand Up @@ -180,8 +187,7 @@ async function FetchGamesFromDB(
})

if (!response.ok) {
const body = await response.text()
throw new Error(`Failed to fetch resources: ${response.status} ${body}`)
throw new Error(`Failed to fetch resources: ${response.status}`)
}

const { data, errors } = (await response.json()) as GraphQLResponse<{
Expand All @@ -197,7 +203,7 @@ async function FetchGamesFromDB(
export async function GetTotalGameCount(
options: Pick<GameQueryOptions, 'search' | 'genres'> = {}
): Promise<number> {
const response = await fetch(BACKEND_URL, {
const response = await FetchBackend({
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
Expand All @@ -214,8 +220,7 @@ export async function GetTotalGameCount(
})

if (!response.ok) {
const body = await response.text()
throw new Error(`Failed to fetch game count: ${response.status} ${body}`)
throw new Error(`Failed to fetch game count: ${response.status}`)
}

const { data, errors } = (await response.json()) as GraphQLResponse<{
Expand Down
24 changes: 16 additions & 8 deletions Frontend/src/FrontendLogic/LogicConnection.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,23 @@
export const BACKEND_URL = import.meta.env.VITE_BACKEND_URL ?? 'http://it2810-10.idi.ntnu.no:3001/'

export const NETWORK_ERROR_MESSAGE =
'Could not reach the server.'

export async function Gql<T>(query: string, variables: Record<string, unknown>): Promise<T> {
const token = GetStoredToken()
const res = await fetch(BACKEND_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...(token ? { Authorization: `Bearer ${token}` } : {})
},
body: JSON.stringify({ query, variables })
})
let res: Response
try {
res = await fetch(BACKEND_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...(token ? { Authorization: `Bearer ${token}` } : {})
},
body: JSON.stringify({ query, variables })
})
} catch {
throw new Error(NETWORK_ERROR_MESSAGE)
}
if (!res.ok) throw new Error(`Request failed: ${res.status}`)
const json = await res.json()
if (json.errors) throw new Error(json.errors[0].message)
Expand Down
2 changes: 1 addition & 1 deletion Frontend/src/FrontendLogic/SearchPageLogicFrontend.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Gql } from './LogicConnection'
import { IsBoolean, IsInteger, IsString, IsStringArray, ReadStored, RemoveStored, WriteStored } from './Storage'
import { IsBoolean, IsInteger, IsString, IsStringArray, ReadStored, WriteStored } from './Storage'

const filterStorageKey = 'GameStart:filtersSearchpage'
const sortStorageKey = 'GameStart:sortOptionSearchpage'
Expand Down
6 changes: 5 additions & 1 deletion Frontend/src/components/ActiveGameCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -154,8 +154,12 @@ export default function ActiveGameCard({
{isWishlisted ? 'Remove from wishlist' : 'Add to wishlist'}
</Button>
)}
{error && <p role="alert">{error}</p>}
</Card>
{error && (
<p className="activeGameWishlistError app-message app-message--error" role="alert">
{error}
</p>
)}
<Box className="activeGameDetails">
<Card className="activeGameInfoCard">
<CardContent className="activeGameInfoContent">
Expand Down
10 changes: 8 additions & 2 deletions Frontend/src/components/GenreGamesSection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ type GenreGamesSectionProps = {
title: string
genres: string[]
genresLoading: boolean
genresError?: string | null
loadGames: (genre: string) => Promise<Game[]>
loadingText: string
emptyText: string
Expand All @@ -49,6 +50,7 @@ export function GenreGamesSection({
title,
genres,
genresLoading,
genresError = null,
loadGames,
loadingText,
emptyText,
Expand Down Expand Up @@ -157,9 +159,13 @@ export function GenreGamesSection({
<div className="genre-games-row">
{isLoading ? (
<p className="main-page-empty-state">{loadingText}</p>
) : genresError ? (
<p className="main-page-error app-message app-message--error" role="alert">
Could not load genres: {genresError}
</p>
) : loadError ? (
<p className="main-page-error" role="alert">
{loadError}
<p className="main-page-error app-message app-message--error" role="alert">
Could not load games: {loadError}
</p>
) : visibleGames.length > 0 ? (
visibleGames.map((game) => <PassiveGameCard key={game.id} game={game} />)
Expand Down
9 changes: 7 additions & 2 deletions Frontend/src/components/RecentReviews.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,10 @@ import type { Review } from '../types/Review'
type RecentReviewsProps = {
reviews: Review[]
isLoading: boolean
error?: string | null
}

export default function RecentReviews({ reviews, isLoading }: RecentReviewsProps) {
export default function RecentReviews({ reviews, isLoading, error = null }: RecentReviewsProps) {
const recentReviewsRef = useRef<HTMLDivElement>(null)
const isStackedLayout = useMediaQuery('(max-width: 56rem)')
const [visibleReviewCount, setVisibleReviewCount] = useState(0)
Expand Down Expand Up @@ -73,7 +74,11 @@ export default function RecentReviews({ reviews, isLoading }: RecentReviewsProps
</div>
<Card className="main-page-section-content" variant="outlined">
{isLoading ? (
<p>Loading reviews...</p>
<p className="main-page-empty-state">Loading reviews...</p>
) : error ? (
<p className="main-page-error app-message app-message--error" role="alert">
Could not load recent reviews: {error}
</p>
) : (
<div
className={`recentReviewsGrid${isMeasuring ? ' recentReviewsMeasuring' : ''}`}
Expand Down
8 changes: 6 additions & 2 deletions Frontend/src/components/Reviews.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -125,9 +125,9 @@ export default function Reviews({
onCancel={CloseComposer}
/>
)}
{(error ?? loadError) && (
{error && (
<p className="reviewComposerError" role="alert">
{error ?? loadError}
{error}
</p>
)}
<Divider />
Expand All @@ -142,6 +142,10 @@ export default function Reviews({
onDelete={HandleDelete}
/>
))
) : loadError ? (
<p className="reviewComposerError" role="alert">
Could not load reviews: {loadError}
</p>
) : (
<p className="activeGameNoReviews">No reviews yet.</p>
)}
Expand Down
15 changes: 15 additions & 0 deletions Frontend/src/components/SearchPageControls.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ interface SearchPageControlsProps {
isFilterActive: boolean
onToggleFilters: () => void
genres: string[]
genresError?: string | null
activeFilters: string[]
onFilterChange: (event: SelectChangeEvent<string[]>) => void
activeSorting: SortOption
Expand All @@ -42,6 +43,7 @@ export default function SearchPageControls({
isFilterActive,
onToggleFilters,
genres,
genresError = null,
activeFilters,
onFilterChange,
activeSorting,
Expand Down Expand Up @@ -107,6 +109,10 @@ export default function SearchPageControls({
value={activeFilters}
onChange={onFilterChange}
label="Filter by genre"
disabled={!!genresError}
inputProps={{
'aria-describedby': genresError ? 'filterGenresError' : undefined
}}
renderValue={(selected) =>
selected.length <= 1
? selected.join('')
Expand All @@ -119,6 +125,15 @@ export default function SearchPageControls({
</MenuItem>
))}
</Select>
{genresError && (
<p
id="filterGenresError"
className="filterGenresError app-message app-message--error app-message--inline"
role="alert"
>
Could not load genres: {genresError}
</p>
)}
</FormControl>
<Button
type="button"
Expand Down
6 changes: 4 additions & 2 deletions Frontend/src/components/SearchPageResults.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ export default function SearchPageResults({
return (
<>
<div className="searchResultsHeader">
{totalCount > 0 && (
{!error && totalCount > 0 && (
<p className="gamesFound">
{totalCount} {totalCount === 1 ? 'game' : 'games'} found
</p>
Expand All @@ -74,7 +74,9 @@ export default function SearchPageResults({
</p>
)}
{isLoading && games.length === 0 && <p className="searchMessage">Loading games...</p>}
{!isLoading && games.length === 0 && <p className="searchMessage">No games found.</p>}
{!error && !isLoading && games.length === 0 && (
<p className="searchMessage">No games found.</p>
)}
{games.length > 0 && <SearchResultsGrid games={games} />}
<Pagination
className="pageinationSearch"
Expand Down
9 changes: 7 additions & 2 deletions Frontend/src/components/TopGames.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,22 @@ import PassiveGameCard from './PassiveGameCard'
interface TopGamesProps {
loading: boolean
featuredGames: PageGame[]
error?: string | null
}

export default function TopGames({ loading, featuredGames }: TopGamesProps) {
export default function TopGames({ loading, featuredGames, error = null }: TopGamesProps) {
return (
<section className="main-page-section">
<div className="main-page-section-heading">
<h2>Top 3 Games</h2>
</div>
<Card className="main-page-section-content" variant="outlined">
{loading ? (
<p>Loading games...</p>
<p className="main-page-empty-state">Loading games...</p>
) : error ? (
<p className="main-page-error app-message app-message--error" role="alert">
Could not load the top games: {error}
</p>
) : featuredGames.length === 0 ? (
<p className="main-page-empty-state">No games found.</p>
) : (
Expand Down
7 changes: 6 additions & 1 deletion Frontend/src/components/WishlistGameCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,14 @@ export default function WishlistGameCard({
/>
)}
<p className="wishlistGameCardPrice">{game.price.toFixed(2)} $</p>
{error && <p role="alert">{error}</p>}
</div>

{error && (
<p className="wishlistGameCardError app-message app-message--error app-message--inline" role="alert">
{error}
</p>
)}

{!readOnly && (
<Button
className="app-button"
Expand Down
10 changes: 10 additions & 0 deletions Frontend/src/css/ActiveGameCard.css
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,16 @@
right: 0.75rem;
}

.activeGameWishlistError {
justify-self: end;
max-width: 100%;
margin: -0.5rem 0 0;
padding: 0.5rem 0.75rem;
border: 1px solid var(--primary-component-color);
border-radius: var(--border-radius);
background-color: var(--primary-background-color);
}

.activeGameDetails {
display: grid;
grid-template-columns: minmax(0, 5fr) minmax(0, 6fr); /* reviews slightly wider */
Expand Down
33 changes: 30 additions & 3 deletions Frontend/src/css/FriendsPage.css
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,8 @@
width: 100%;
}

.wishlistStatusText {
padding-bottom: 1rem;
.wishlistStatusAction {
margin-top: 1rem;
}

.userDisplayStatus .wishlistStatus {
Expand All @@ -69,7 +69,7 @@
justify-content: center;
min-height: 3rem;
margin: 0;
padding: 1rem;
padding: clamp(12px, 3vw, 32px);
background-color: var(--primary-background-color);
border: 1px solid var(--primary-component-color);
border-radius: 4px;
Expand All @@ -82,6 +82,33 @@
margin: 0 auto 1rem;
}

.userDisplayStatus--centered {
display: flex;
flex: 1 0 auto;
flex-direction: column;
justify-content: center;
min-height: 40vh;
}

.wishlistStatus--error .wishlistStatusText {
color: var(--primary-text-color);
font-weight: 700;
}

.addFriendGroup {
display: flex;
flex-direction: column;
align-items: flex-end;
gap: 0.35rem;
max-width: 100%;
}

.addFriendError {
box-sizing: border-box;
width: calc(20ch + 3.5rem);
max-width: 100%;
}

.ownFriendId {
box-sizing: border-box;
width: min(calc(100% - 3rem), 75rem);
Expand Down
5 changes: 5 additions & 0 deletions Frontend/src/css/GamePage.css
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@
margin: 0 auto;
}

.game-page-message {
margin: 2rem auto;
max-width: 40rem;
}

@media (max-width: 43.75rem) {
.game-page {
width: min(calc(100% - 2rem), 32rem);
Expand Down
Loading