From e0d49cf3440b3cf72290e21512b2180918de9b1d Mon Sep 17 00:00:00 2001 From: Shaswat Raj <108283560+playlikeboy@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:17:33 +0530 Subject: [PATCH 1/3] fix(web): tolerate blocked storage and normalize catalog pagination --- web/src/components/GameCatalog.tsx | 327 ++++++++---------------- web/src/components/GameInteractions.tsx | 110 ++++---- web/src/lib/browser-storage.ts | 104 ++++++++ web/tests/browser-storage.test.ts | 83 ++++++ 4 files changed, 338 insertions(+), 286 deletions(-) create mode 100644 web/src/lib/browser-storage.ts create mode 100644 web/tests/browser-storage.test.ts diff --git a/web/src/components/GameCatalog.tsx b/web/src/components/GameCatalog.tsx index 3e6e06a5..4f8429b1 100644 --- a/web/src/components/GameCatalog.tsx +++ b/web/src/components/GameCatalog.tsx @@ -7,8 +7,15 @@ import { Game } from '../types'; import { GameGrid } from './GameGrid'; import Link from 'next/link'; import { Search, ChevronLeft, ChevronRight, ChevronDown, Sparkles, Trophy, Gamepad2, Zap, Star } from 'lucide-react'; +import { getBrowserStorage, getMostPlayed, readGameList } from '../lib/browser-storage'; -const fetcher = (url: string): Promise => fetch(url).then((res) => res.json()); +const fetcher = async (url: string): Promise => { + const response = await fetch(url); + if (!response.ok) throw new Error(`Unable to load game catalog (${response.status}).`); + const payload: unknown = await response.json(); + if (!Array.isArray(payload)) throw new Error('Game catalog must be an array.'); + return payload as Game[]; +}; const GAMES_PER_PAGE = 50; @@ -16,6 +23,12 @@ interface GameCatalogProps { initialGames: Game[]; } +function parsePage(value: string | null): number { + if (!value || !/^[1-9]\d*$/.test(value)) return 1; + const parsed = Number(value); + return Number.isSafeInteger(parsed) ? parsed : 1; +} + export function GameCatalog({ initialGames }: GameCatalogProps) { const { data: games } = useSWR('/games/games.json', fetcher, { fallbackData: initialGames, @@ -27,100 +40,66 @@ export function GameCatalog({ initialGames }: GameCatalogProps) { const pathname = usePathname(); const searchParams = useSearchParams(); - // Get State from URL const search = searchParams.get('search') || ''; - const sort = (searchParams.get('sort') as 'rating' | 'newest') || 'rating'; - const page = parseInt(searchParams.get('page') || '1'); + const requestedSort = searchParams.get('sort'); + const sort: 'rating' | 'newest' = requestedSort === 'newest' ? 'newest' : 'rating'; + const requestedPage = parsePage(searchParams.get('page')); - // Local search state for instant response const [searchQuery, setSearchQuery] = useState(search); const [randomGames, setRandomGames] = useState([]); const [recentlyPlayed, setRecentlyPlayed] = useState([]); const [favorites, setFavorites] = useState([]); const [mostPlayed, setMostPlayed] = useState([]); - // Sync URL search param to local state (e.g. if back/forward button is clicked) useEffect(() => { setSearchQuery(search); }, [search]); - // Load LocalStorage history & favorites on mount useEffect(() => { - const rp = localStorage.getItem('recently-played'); - if (rp) setRecentlyPlayed(JSON.parse(rp)); - - const favs = localStorage.getItem('favorites'); - if (favs) setFavorites(JSON.parse(favs)); - - const mp = localStorage.getItem('most-played'); - if (mp) { - const map: Record = JSON.parse(mp); - const sorted = Object.values(map) - .sort((a, b) => b.playCount - a.playCount) - .map((item) => item.game) - .slice(0, 6); - setMostPlayed(sorted); - } + const storage = getBrowserStorage(); + if (!storage) return; + setRecentlyPlayed(readGameList(storage, 'recently-played')); + setFavorites(readGameList(storage, 'favorites')); + setMostPlayed(getMostPlayed(storage)); }, []); - // Set initial random games once catalog data is loaded useEffect(() => { const allGames = games || initialGames; - if (allGames && allGames.length > 0 && randomGames.length === 0) { - const shuffled = [...allGames].sort(() => 0.5 - Math.random()); - setRandomGames(shuffled.slice(0, 5)); + if (allGames.length > 0 && randomGames.length === 0) { + setRandomGames([...allGames].sort(() => Math.random() - 0.5).slice(0, 5)); } }, [games, initialGames, randomGames.length]); const shuffleRandomGames = () => { const allGames = games || initialGames; - if (allGames && allGames.length > 0) { - const shuffled = [...allGames].sort(() => 0.5 - Math.random()); - setRandomGames(shuffled.slice(0, 5)); + if (allGames.length > 0) { + setRandomGames([...allGames].sort(() => Math.random() - 0.5).slice(0, 5)); } }; - // Scroll to catalog section when page changes useEffect(() => { - const catalogElement = document.getElementById('catalog'); - if (catalogElement) { - catalogElement.scrollIntoView({ behavior: 'smooth' }); - } - }, [page]); + document.getElementById('catalog')?.scrollIntoView({ behavior: 'smooth' }); + }, [requestedPage]); - // Debounce updating the URL search parameter useEffect(() => { - const timer = setTimeout(() => { - if (searchQuery !== search) { - const params = new URLSearchParams(searchParams); - if (searchQuery) { - params.set('search', searchQuery); - } else { - params.delete('search'); - } - params.set('page', '1'); // Reset to page 1 - router.push(pathname + '?' + params.toString(), { scroll: false }); - } + const timer = window.setTimeout(() => { + if (searchQuery === search) return; + const params = new URLSearchParams(searchParams.toString()); + if (searchQuery.trim()) params.set('search', searchQuery.trim()); + else params.delete('search'); + params.set('page', '1'); + router.push(pathname + '?' + params.toString(), { scroll: false }); }, 300); - return () => clearTimeout(timer); + return () => window.clearTimeout(timer); }, [searchQuery, search, searchParams, router, pathname]); - // Update URL Helper - const createQueryString = useCallback( - (name: string, value: string) => { - const params = new URLSearchParams(searchParams.toString()); - params.set(name, value); - - // Reset page to 1 when search or sort changes - if (name !== 'page') { - params.set('page', '1'); - } - - return params.toString(); - }, - [searchParams] - ); + const createQueryString = useCallback((name: string, value: string) => { + const params = new URLSearchParams(searchParams.toString()); + params.set(name, value); + if (name !== 'page') params.set('page', '1'); + return params.toString(); + }, [searchParams]); const updateState = (name: string, value: string) => { router.push(pathname + '?' + createQueryString(name, value), { scroll: false }); @@ -128,36 +107,39 @@ export function GameCatalog({ initialGames }: GameCatalogProps) { const filteredGames = useMemo(() => { let result = [...(games || initialGames)]; - - if (searchQuery) { - const lowerSearch = searchQuery.toLowerCase(); - result = result.filter((game) => - game.name.toLowerCase().includes(lowerSearch) - ); + if (searchQuery.trim()) { + const lowerSearch = searchQuery.trim().toLocaleLowerCase(); + result = result.filter((game) => game.name.toLocaleLowerCase().includes(lowerSearch)); } if (sort === 'rating') { - result.sort((a, b) => parseFloat(b.rating) - parseFloat(a.rating)); + result.sort((a, b) => { + const ratingA = Number.parseFloat(a.rating); + const ratingB = Number.parseFloat(b.rating); + return (Number.isFinite(ratingB) ? ratingB : -1) - + (Number.isFinite(ratingA) ? ratingA : -1); + }); } else { - // Fallback for "newest" using ID if date isn't available, or just keeping original order if that's implied "newest" - // Assuming higher ID is newer for now. - result.sort((a, b) => parseInt(b.id) - parseInt(a.id)); + result.sort((a, b) => { + const idA = Number(a.id); + const idB = Number(b.id); + return (Number.isFinite(idB) ? idB : -1) - (Number.isFinite(idA) ? idA : -1); + }); } - return result; }, [games, initialGames, searchQuery, sort]); const totalPages = Math.ceil(filteredGames.length / GAMES_PER_PAGE); - const currentGames = filteredGames.slice( - (page - 1) * GAMES_PER_PAGE, - page * GAMES_PER_PAGE - ); + const page = totalPages === 0 ? 1 : Math.min(requestedPage, totalPages); + const currentGames = filteredGames.slice((page - 1) * GAMES_PER_PAGE, page * GAMES_PER_PAGE); + + useEffect(() => { + if (page !== requestedPage) updateState('page', String(page)); + }, [page, requestedPage]); return (
- {/* Dashboard Sections */}
- {/* Random Picks */}
@@ -168,10 +150,7 @@ export function GameCatalog({ initialGames }: GameCatalogProps) {

Fresh titles selected dynamically. Roll for new games!

- @@ -179,36 +158,22 @@ export function GameCatalog({ initialGames }: GameCatalogProps) { {randomGames.length > 0 ? (
{randomGames.map((game) => ( - +
- {game.name} + {game.name}
- - {game.name} - + {game.name} ))}
) : ( -
- Loading picks... -
+
Loading picks...
)}
- {/* Play Dashboard */}
@@ -218,37 +183,26 @@ export function GameCatalog({ initialGames }: GameCatalogProps) {

Your custom play history and library.

- - {/* Lists for History/Favorites */}
{recentlyPlayed.length > 0 && (
Recently Played
{recentlyPlayed.slice(0, 4).map((game) => ( - - + + {game.name} ))}
)} - {favorites.length > 0 && (
Your Favorites
{favorites.slice(0, 4).map((game) => ( - + {game.name} @@ -256,17 +210,12 @@ export function GameCatalog({ initialGames }: GameCatalogProps) {
)} - {mostPlayed.length > 0 && (
Most Played
{mostPlayed.slice(0, 4).map((game) => ( - + {game.name} @@ -274,159 +223,85 @@ export function GameCatalog({ initialGames }: GameCatalogProps) {
)} - - {recentlyPlayed.length === 0 && favorites.length === 0 && ( -
- No history yet. Start playing to build your board! -
+ {recentlyPlayed.length === 0 && favorites.length === 0 && mostPlayed.length === 0 && ( +
No history yet. Start playing to build your board!
)}
- {/* Genres / Browse by Category */}
- - Browse by Genre - + Browse by Genre
{[ - { name: 'Puzzle', slug: 'puzzle' }, - { name: 'Action', slug: 'action' }, - { name: 'Hypercasual', slug: 'hypercasual' }, - { name: 'Arcade', slug: 'arcade' }, - { name: 'Sports', slug: 'sports' }, - { name: 'Racing', slug: 'racing' }, - { name: 'Adventure', slug: 'adventure' }, - { name: 'Shooting', slug: 'shooting' }, - { name: 'Cooking', slug: 'cooking' }, - { name: 'Multiplayer', slug: 'multiplayer' }, - { name: 'Clicker', slug: 'clicker' }, - { name: '3D', slug: '3d' }, + { name: 'Puzzle', slug: 'puzzle' }, { name: 'Action', slug: 'action' }, + { name: 'Hypercasual', slug: 'hypercasual' }, { name: 'Arcade', slug: 'arcade' }, + { name: 'Sports', slug: 'sports' }, { name: 'Racing', slug: 'racing' }, + { name: 'Adventure', slug: 'adventure' }, { name: 'Shooting', slug: 'shooting' }, + { name: 'Cooking', slug: 'cooking' }, { name: 'Multiplayer', slug: 'multiplayer' }, + { name: 'Clicker', slug: 'clicker' }, { name: '3D', slug: '3d' }, { name: 'Soccer', slug: 'soccer' }, ].map((genre) => ( - + {genre.name} ))}
- {/* Controls Bar */}
- {/* Search */}
- { - setSearchQuery(e.target.value); - }} - className="block w-full pl-11 pr-4 py-3 rounded-xl bg-white/5 text-foreground placeholder-muted-foreground border border-white/10 focus:outline-none focus:bg-white/10 focus:border-accent/40 focus:ring-2 focus:ring-accent/20 transition-all sm:text-sm" - /> + setSearchQuery(event.target.value)} className="block w-full pl-11 pr-4 py-3 rounded-xl bg-white/5 text-foreground placeholder-muted-foreground border border-white/10 focus:outline-none focus:bg-white/10 focus:border-accent/40 focus:ring-2 focus:ring-accent/20 transition-all sm:text-sm" />
- - {/* Sort & Stats */}
- - {filteredGames.length.toLocaleString()} Games - - + {filteredGames.length.toLocaleString()} Games
- updateState('sort', event.target.value)} className="appearance-none w-full md:w-40 bg-white/5 border border-white/10 text-foreground py-3 pl-4 pr-10 rounded-xl leading-tight focus:outline-none focus:bg-white/10 focus:border-primary/40 focus:ring-2 focus:ring-primary/20 transition-all cursor-pointer text-sm font-semibold"> -
- -
+
- {/* Grid */}
{currentGames.length > 0 ? ( ) : (

No games found matching "{searchQuery}"

- +
)}
- {/* Pagination - Glass Style */} {totalPages > 1 && (
- -
- {/* Simplified Pagination Logic for display */} - {Array.from({ length: Math.min(5, totalPages) }, (_, i) => { - let p = page; - if (totalPages <= 5) { - p = i + 1; - } else if (page < 3) { - p = i + 1; - } else if (page > totalPages - 2) { - p = totalPages - 4 + i; - } else { - p = page - 2 + i; - } - - if (p > 0 && p <= totalPages) { - return ( - - ); - } - return null; + {Array.from({ length: Math.min(5, totalPages) }, (_, index) => { + let pageNumber = page; + if (totalPages <= 5) pageNumber = index + 1; + else if (page < 3) pageNumber = index + 1; + else if (page > totalPages - 2) pageNumber = totalPages - 4 + index; + else pageNumber = page - 2 + index; + + return ( + + ); })}
- - {/* Mobile Page Indicator */} - - Page {page} / {totalPages} - - -
diff --git a/web/src/components/GameInteractions.tsx b/web/src/components/GameInteractions.tsx index 44c15317..01e9cb8f 100644 --- a/web/src/components/GameInteractions.tsx +++ b/web/src/components/GameInteractions.tsx @@ -3,65 +3,54 @@ import { useState, useEffect } from 'react'; import { Maximize2, Share2, Code, Check, Star } from 'lucide-react'; import { Game } from '../types'; +import { + getBrowserStorage, + readGameList, + recordGamePlay, + toggleFavorite as updateFavorite, +} from '../lib/browser-storage'; export function GameInteractions({ game }: { game: Game }) { const [copied, setCopied] = useState(false); const [isFavorite, setIsFavorite] = useState(false); useEffect(() => { - // Track recently played games in localStorage - const recentlyPlayedRaw = localStorage.getItem('recently-played'); - let recentlyPlayedList: Game[] = recentlyPlayedRaw ? JSON.parse(recentlyPlayedRaw) : []; - - recentlyPlayedList = recentlyPlayedList.filter((g) => g.slug !== game.slug); - recentlyPlayedList.unshift(game); - if (recentlyPlayedList.length > 12) { - recentlyPlayedList = recentlyPlayedList.slice(0, 12); - } - localStorage.setItem('recently-played', JSON.stringify(recentlyPlayedList)); - - // Track play counts in localStorage - const mostPlayedRaw = localStorage.getItem('most-played'); - const mostPlayedMap: Record = mostPlayedRaw ? JSON.parse(mostPlayedRaw) : {}; - - if (mostPlayedMap[game.slug]) { - mostPlayedMap[game.slug].playCount += 1; - } else { - mostPlayedMap[game.slug] = { game, playCount: 1 }; - } - localStorage.setItem('most-played', JSON.stringify(mostPlayedMap)); + const storage = getBrowserStorage(); + if (!storage) return; - // Load favorite status - const favoritesRaw = localStorage.getItem('favorites'); - const favoritesList: Game[] = favoritesRaw ? JSON.parse(favoritesRaw) : []; - setIsFavorite(favoritesList.some((g) => g.slug === game.slug)); + // These helpers tolerate corrupt JSON and browser storage restrictions. + recordGamePlay(storage, game); + setIsFavorite(readGameList(storage, 'favorites').some((item) => item.slug === game.slug)); }, [game]); const toggleFullscreen = () => { const iframe = document.querySelector('iframe'); - if (iframe) { - type IframeWithFullscreen = HTMLIFrameElement & { - webkitRequestFullscreen?: () => void; - msRequestFullscreen?: () => void; - }; + if (!iframe) return; - const target = iframe as IframeWithFullscreen; + type IframeWithFullscreen = HTMLIFrameElement & { + webkitRequestFullscreen?: () => void; + msRequestFullscreen?: () => void; + }; + const target = iframe as IframeWithFullscreen; - if (target.requestFullscreen) { - target.requestFullscreen(); - } else if (target.webkitRequestFullscreen) { /* Safari */ - target.webkitRequestFullscreen(); - } else if (target.msRequestFullscreen) { /* IE11 */ - target.msRequestFullscreen(); - } + if (target.requestFullscreen) { + void target.requestFullscreen().catch((error) => console.error('Fullscreen request failed:', error)); + } else if (target.webkitRequestFullscreen) { + target.webkitRequestFullscreen(); + } else if (target.msRequestFullscreen) { + target.msRequestFullscreen(); } }; - const copyEmbed = () => { + const copyEmbed = async () => { const embedCode = ``; - navigator.clipboard.writeText(embedCode); - setCopied(true); - setTimeout(() => setCopied(false), 2000); + try { + await navigator.clipboard.writeText(embedCode); + setCopied(true); + window.setTimeout(() => setCopied(false), 2000); + } catch (error) { + console.error('Unable to copy embed code:', error); + } }; const shareGame = async () => { @@ -72,27 +61,28 @@ export function GameInteractions({ game }: { game: Game }) { text: `Play ${game.name} on SOP Games!`, url: window.location.href, }); - } catch (err) { - console.log('Error sharing:', err); + } catch (error) { + // Closing the native share sheet is not an application error. + if (error instanceof Error && error.name !== 'AbortError') { + console.error('Error sharing game:', error); + } } - } else { - navigator.clipboard.writeText(window.location.href); - alert('Link copied to clipboard!'); + return; + } + + try { + await navigator.clipboard.writeText(window.location.href); + setCopied(true); + window.setTimeout(() => setCopied(false), 2000); + } catch (error) { + console.error('Unable to copy game link:', error); } }; const toggleFavorite = () => { - const favoritesRaw = localStorage.getItem('favorites'); - let favoritesList: Game[] = favoritesRaw ? JSON.parse(favoritesRaw) : []; - - if (isFavorite) { - favoritesList = favoritesList.filter((g) => g.slug !== game.slug); - setIsFavorite(false); - } else { - favoritesList.push(game); - setIsFavorite(true); - } - localStorage.setItem('favorites', JSON.stringify(favoritesList)); + const storage = getBrowserStorage(); + if (!storage) return; + setIsFavorite(updateFavorite(storage, game)); }; return ( @@ -123,8 +113,8 @@ export function GameInteractions({ game }: { game: Game }) {