Removing APIs, automatically saving to local storage on add/remove, added export to JSON button.

This commit is contained in:
Bradley Shellnut 2022-10-26 22:38:30 -04:00
parent 8b090b5a4c
commit 7c947b7f48
14 changed files with 507 additions and 678 deletions

View file

@ -22,8 +22,6 @@
"@types/node": "^18.11.7", "@types/node": "^18.11.7",
"@typescript-eslint/eslint-plugin": "^5.41.0", "@typescript-eslint/eslint-plugin": "^5.41.0",
"@typescript-eslint/parser": "^5.41.0", "@typescript-eslint/parser": "^5.41.0",
"carbon-components-svelte": "^0.70.12",
"carbon-icons-svelte": "^11.4.0",
"eslint": "^8.26.0", "eslint": "^8.26.0",
"eslint-config-prettier": "^8.1.0", "eslint-config-prettier": "^8.1.0",
"eslint-plugin-svelte3": "^4.0.0", "eslint-plugin-svelte3": "^4.0.0",

View file

@ -15,8 +15,6 @@ specifiers:
'@types/node': ^18.11.7 '@types/node': ^18.11.7
'@typescript-eslint/eslint-plugin': ^5.41.0 '@typescript-eslint/eslint-plugin': ^5.41.0
'@typescript-eslint/parser': ^5.41.0 '@typescript-eslint/parser': ^5.41.0
carbon-components-svelte: ^0.70.12
carbon-icons-svelte: ^11.4.0
cookie: ^0.5.0 cookie: ^0.5.0
eslint: ^8.26.0 eslint: ^8.26.0
eslint-config-prettier: ^8.1.0 eslint-config-prettier: ^8.1.0
@ -56,8 +54,6 @@ devDependencies:
'@types/node': 18.11.7 '@types/node': 18.11.7
'@typescript-eslint/eslint-plugin': 5.41.0_huremdigmcnkianavgfk3x6iou '@typescript-eslint/eslint-plugin': 5.41.0_huremdigmcnkianavgfk3x6iou
'@typescript-eslint/parser': 5.41.0_wyqvi574yv7oiwfeinomdzmc3m '@typescript-eslint/parser': 5.41.0_wyqvi574yv7oiwfeinomdzmc3m
carbon-components-svelte: 0.70.12
carbon-icons-svelte: 11.4.0
eslint: 8.26.0 eslint: 8.26.0
eslint-config-prettier: 8.5.0_eslint@8.26.0 eslint-config-prettier: 8.5.0_eslint@8.26.0
eslint-plugin-svelte3: 4.0.0_l6ppk7eerpslmlsqymzic46t24 eslint-plugin-svelte3: 4.0.0_l6ppk7eerpslmlsqymzic46t24
@ -650,16 +646,6 @@ packages:
engines: {node: '>=6'} engines: {node: '>=6'}
dev: true dev: true
/carbon-components-svelte/0.70.12:
resolution: {integrity: sha512-CSVXWr53kSP/6ITaLxcCd/7rZStM3Mgl1tXedlwgvkViqDgCexWzSsK1u2RoSptmqL5IggUehabcETD6tm5EFg==}
dependencies:
flatpickr: 4.6.9
dev: true
/carbon-icons-svelte/11.4.0:
resolution: {integrity: sha512-p/llZde2kP2BI9SOqM+QFKGfQnYrW+4dVxF1rAYriEADXDsjt9EYlh+KpQ5qf4JpXAq+e2+TB/r/lIG1xdUbAQ==}
dev: true
/chalk/4.1.2: /chalk/4.1.2:
resolution: {integrity: sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==} resolution: {integrity: sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==}
engines: {node: '>=10'} engines: {node: '>=10'}
@ -1462,10 +1448,6 @@ packages:
rimraf: 3.0.2 rimraf: 3.0.2
dev: true dev: true
/flatpickr/4.6.9:
resolution: {integrity: sha512-F0azNNi8foVWKSF+8X+ZJzz8r9sE1G4hl06RyceIaLvyltKvDl6vqk9Lm/6AUUCi5HWaIjiUbk7UpeE/fOXOpw==}
dev: true
/flatted/3.2.7: /flatted/3.2.7:
resolution: {integrity: sha512-5nqDSxl8nn5BSNxyR3n4I6eDmbolI6WT+QqR547RwxQapgjQBmtktdP+HTBb/a/zLsbzERTONyUB5pefh5TtjQ==} resolution: {integrity: sha512-5nqDSxl8nn5BSNxyR3n4I6eDmbolI6WT+QqR547RwxQapgjQBmtktdP+HTBb/a/zLsbzERTONyUB5pefh5TtjQ==}
dev: true dev: true

View file

@ -1,82 +1,87 @@
<script lang="ts"> <script lang="ts">
import { fade } from 'svelte/transition'; import { fade } from 'svelte/transition';
import { import {
Dialog, Dialog,
DialogDescription, DialogDescription,
DialogOverlay, DialogOverlay,
DialogTitle DialogTitle
} from '@rgossiaux/svelte-headlessui'; } from '@rgossiaux/svelte-headlessui';
import { boredState } from '$root/lib/stores/boredState'; import { boredState } from '$root/lib/stores/boredState';
import { removeFromCollection } from '$root/lib/util/manipulateCollection'; import { collectionStore } from '$root/lib/stores/collectionStore';
import { removeFromCollection } from '$root/lib/util/manipulateCollection';
import { browser } from '$app/environment';
function removeGame() { function removeGame() {
if ($boredState?.dialog?.additionalData) { if ($boredState?.dialog?.additionalData) {
removeFromCollection($boredState?.dialog?.additionalData); removeFromCollection($boredState?.dialog?.additionalData);
} }
boredState.update((n) => ({ ...n, dialog: { isOpen: false } })); if (browser) {
} localStorage.collection = JSON.stringify($collectionStore);
}
boredState.update((n) => ({ ...n, dialog: { isOpen: false } }));
}
$: isOpen = $boredState?.dialog?.isOpen; $: isOpen = $boredState?.dialog?.isOpen;
</script> </script>
<Dialog <Dialog
open={isOpen} open={isOpen}
on:close={() => { on:close={() => {
boredState.update((n) => ({ ...n, dialog: { isOpen: false } })); boredState.update((n) => ({ ...n, dialog: { isOpen: false } }));
}} }}
static static
> >
<div transition:fade> <div transition:fade>
<DialogOverlay class="dialog-overlay" /> <DialogOverlay class="dialog-overlay" />
<div class="dialog"> <div class="dialog">
<DialogTitle>Remove from collection</DialogTitle> <DialogTitle>Remove from collection</DialogTitle>
<DialogDescription>Are you sure you want to remove from your collection?</DialogDescription> <DialogDescription>Are you sure you want to remove from your collection?</DialogDescription>
<div class="dialog-footer"> <div class="dialog-footer">
<button on:click={removeGame}>Remove</button> <button on:click={removeGame}>Remove</button>
<button <button
on:click={() => { on:click={() => {
boredState.update((n) => ({ ...n, dialog: { isOpen: false } })); boredState.update((n) => ({ ...n, dialog: { isOpen: false } }));
}}>Cancel</button }}>Cancel</button
> >
</div> </div>
</div> </div>
</div> </div>
</Dialog> </Dialog>
<style lang="scss"> <style lang="scss">
.dialog { .dialog {
display: grid; display: grid;
gap: 1.5rem; gap: 1.5rem;
position: absolute; position: absolute;
top: 50%; top: 50%;
left: 50%; left: 50%;
transform: translate(-50%, -50%); transform: translate(-50%, -50%);
z-index: 101; z-index: 101;
border-radius: 10px; border-radius: 10px;
background-color: var(--clr-input-bg); background-color: var(--clr-input-bg);
padding: 2rem; padding: 2rem;
min-width: 400px; min-width: 400px;
.dialog-footer { .dialog-footer {
display: flex; display: flex;
justify-content: space-between; justify-content: space-between;
gap: 2rem; gap: 2rem;
margin: 1rem 0; margin: 1rem 0;
button { button {
display: flex; display: flex;
place-content: center; place-content: center;
gap: 1rem; gap: 1rem;
width: 100%; width: 100%;
border-radius: 10px; border-radius: 10px;
padding: 1rem; padding: 1rem;
background-color: var(--color-btn-primary-active); background-color: var(--color-btn-primary-active);
&:hover { &:hover {
background-color: var(--color-btn-primary-active-hover); background-color: var(--color-btn-primary-active-hover);
} }
} }
} }
} }
</style> </style>

View file

@ -1,112 +1,119 @@
<script lang="ts"> <script lang="ts">
import { createEventDispatcher } from 'svelte'; import { createEventDispatcher } from 'svelte';
import { fade } from 'svelte/transition'; import { fade } from 'svelte/transition';
import { MinusCircleIcon, PlusCircleIcon } from '@rgossiaux/svelte-heroicons/outline'; import { MinusCircleIcon, PlusCircleIcon } from '@rgossiaux/svelte-heroicons/outline';
import type { GameType, SavedGameType } from '$lib/types'; import type { GameType, SavedGameType } from '$lib/types';
import { collectionStore } from '$lib/stores/collectionStore'; import { collectionStore } from '$lib/stores/collectionStore';
import { addToCollection, removeFromCollection } from '$lib/util/manipulateCollection'; import { addToCollection, removeFromCollection } from '$lib/util/manipulateCollection';
import { browser } from '$app/environment';
export let game: GameType | SavedGameType; export let game: GameType | SavedGameType;
export let minimal: boolean = false; export let minimal: boolean = false;
export let detailed: boolean = false; export let detailed: boolean = false;
const dispatch = createEventDispatcher(); const dispatch = createEventDispatcher();
function removeGame() { function removeGame() {
dispatch('removeGameEvent', game); dispatch('removeGameEvent', game);
} }
$: existsInCollection = $collectionStore.find((item: SavedGameType) => item.id === game.id); $: existsInCollection = $collectionStore.find((item: SavedGameType) => item.id === game.id);
</script> </script>
<article class="game-container" transition:fade> <article class="game-container" transition:fade>
<div class="game-info"> <div class="game-info">
<h2>{game.name}</h2> <h2>{game.name}</h2>
<a class="thumbnail" href={`/game/${game.id}`}> <a class="thumbnail" href={`/game/${game.id}`}>
<img width="140" height="140" src={game.thumb_url} alt={`Image of ${game.name}`} /> <img width="140" height="140" src={game.thumb_url} alt={`Image of ${game.name}`} />
</a> </a>
</div> </div>
{#if !minimal} {#if !minimal}
<div class="game-details"> <div class="game-details">
<p>{game.year_published}</p> <p>{game.year_published}</p>
<p>{game.players} {game.max_players === 1 ? 'player' : 'players'}</p> <p>{game.players} {game.max_players === 1 ? 'player' : 'players'}</p>
<p>{game.playtime} minutes</p> <p>{game.playtime} minutes</p>
<p>Minimum Age: {game.min_age}</p> <p>Minimum Age: {game.min_age}</p>
<a href={`/game/${game.id}`}>View Game</a> <a href={`/game/${game.id}`}>View Game</a>
{#if detailed} {#if detailed}
<div class="description">{@html game.description}</div> <div class="description">{@html game.description}</div>
{/if} {/if}
</div> </div>
{/if} {/if}
{#if existsInCollection} {#if existsInCollection}
<button <button
aria-label="Remove from collection" aria-label="Remove from collection"
class="btn" class="btn"
type="button" type="button"
on:click={() => removeGame()}>Remove <MinusCircleIcon width="24" height="24" /></button on:click={() => {
> removeGame();
{:else} }}>Remove <MinusCircleIcon width="24" height="24" /></button
<button >
aria-label="Add to collection" {:else}
class="btn" <button
type="button" aria-label="Add to collection"
on:click={() => addToCollection(game)} class="btn"
>Add to collection <PlusCircleIcon width="24" height="24" /></button type="button"
> on:click={() => {
{/if} addToCollection(game);
if (browser) {
localStorage.collection = JSON.stringify($collectionStore);
}
}}>Add to collection <PlusCircleIcon width="24" height="24" /></button
>
{/if}
</article> </article>
<style lang="scss"> <style lang="scss">
img { img {
border-radius: 10px; border-radius: 10px;
} }
button { button {
display: flex; display: flex;
justify-content: space-between; justify-content: space-between;
align-items: center; align-items: center;
gap: 1rem; gap: 1rem;
width: 100%; width: 100%;
border-radius: 10px; border-radius: 10px;
padding: 1rem; padding: 1rem;
background-color: var(--color-btn-primary-active); background-color: var(--color-btn-primary-active);
} }
.game-container { .game-container {
/* display: grid; */ /* display: grid; */
/* grid-template-rows: minmax(25px, 50px) 1fr minmax(50px, 75px); */ /* grid-template-rows: minmax(25px, 50px) 1fr minmax(50px, 75px); */
display: flex; display: flex;
flex-wrap: wrap; flex-wrap: wrap;
@media (max-width: 650px) { @media (max-width: 650px) {
max-width: none; max-width: none;
} }
gap: var(--spacing-16); gap: var(--spacing-16);
padding: var(--spacing-16) var(--spacing-16); padding: var(--spacing-16) var(--spacing-16);
transition: all 0.3s; transition: all 0.3s;
border-radius: 8px; border-radius: 8px;
background-color: var(--primary); background-color: var(--primary);
&:hover { &:hover {
background-color: hsla(222, 9%, 65%, 1); background-color: hsla(222, 9%, 65%, 1);
} }
.game-info { .game-info {
display: grid; display: grid;
gap: 0.5rem; gap: 0.5rem;
margin: 0.2rem; margin: 0.2rem;
} }
.game-details { .game-details {
p, p,
a { a {
padding: 0.25rem; padding: 0.25rem;
} }
} }
.btn { .btn {
max-height: 50px; max-height: 50px;
} }
} }
</style> </style>

View file

@ -1,57 +1,77 @@
<script lang="ts"> <script lang="ts">
import { browser } from '$app/environment'; import { browser } from '$app/environment';
import { collectionStore } from '$root/lib/stores/collectionStore'; import { collectionStore } from '$root/lib/stores/collectionStore';
import { ToastType } from '$root/lib/types'; import { ToastType } from '$root/lib/types';
import { SaveIcon, TrashIcon } from '@rgossiaux/svelte-heroicons/outline'; import { SaveIcon, ShareIcon, TrashIcon } from '@rgossiaux/svelte-heroicons/outline';
import { toast } from '../toast/toast'; import { toast } from '../toast/toast';
function saveCollection() { function saveCollection() {
console.log('Saving collection'); if (!browser) return;
console.log('collectionStore', $collectionStore); localStorage.collection = JSON.stringify($collectionStore);
if (!browser) return; toast.send('Saved collection', { duration: 3000, type: ToastType.INFO });
localStorage.collection = JSON.stringify($collectionStore); }
toast.send('Saved collection', { duration: 3000, type: ToastType.INFO });
}
function clearCollection() { function exportCollection() {
if (!browser) return; if (!browser) return;
localStorage.collection = []; const collectionBlob = new Blob([JSON.stringify($collectionStore)], {
toast.send('Cleared collection', { duration: 3000, type: ToastType.INFO }); type: 'application/json;charset=utf-8'
} });
let url = window.URL || window.webkitURL;
let link = url.createObjectURL(collectionBlob);
let a = document.createElement('a');
a.setAttribute('download', `collection.json`);
a.setAttribute('href', link);
a.click();
document.body.removeChild(a);
toast.send('Exported collection', { duration: 3000, type: ToastType.INFO });
}
function clearCollection() {
if (!browser) return;
localStorage.collection = [];
toast.send('Cleared collection', { duration: 3000, type: ToastType.INFO });
}
</script> </script>
<div> <div>
<div> <div>
<span class="collection-title">Your Collection</span> <span class="collection-title">Your Collection</span>
</div> </div>
<div class="collection-buttons"> <div class="collection-buttons">
<button type="button" aria-label="Save Collection" on:click={() => saveCollection()} <button type="button" aria-label="Export Collection" on:click={() => exportCollection()}
><SaveIcon width="24" height="24" />Save</button ><ShareIcon width="24" height="24" />Export</button
> >
<button type="button" aria-label="Clear saved collection" on:click={() => clearCollection()} <button type="button" aria-label="Save Collection" on:click={() => saveCollection()}
><TrashIcon width="24" height="24" />Clear</button ><SaveIcon width="24" height="24" />Save</button
> >
</div> <button type="button" aria-label="Clear saved collection" on:click={() => clearCollection()}
><TrashIcon width="24" height="24" />Clear</button
>
</div>
</div> </div>
<style> <style lang="scss">
:global(.collection-title) { :global(.collection-title) {
padding-bottom: var(--spacing-8); padding-bottom: var(--spacing-8);
font-size: var(--font-24); font-size: var(--font-24);
font-weight: 700; font-weight: 700;
line-height: 32px; line-height: 32px;
} }
:global(.collection-buttons) { :global(.collection-buttons) {
display: flex; display: flex;
flex-direction: row; flex-direction: row;
justify-content: space-between; justify-content: space-between;
gap: 6rem; // gap: 6rem;
}
button { @media (min-width: 480px) {
display: grid; gap: 3rem;
place-items: center; }
gap: 0.25rem; }
}
button {
display: grid;
place-items: center;
gap: 0.25rem;
}
</style> </style>

View file

@ -1,136 +1,146 @@
<script lang="ts"> <script lang="ts">
import { fade } from 'svelte/transition'; import { fade } from 'svelte/transition';
import { Popover, PopoverButton, PopoverPanel } from '@rgossiaux/svelte-headlessui'; import { Popover, PopoverButton, PopoverPanel } from '@rgossiaux/svelte-headlessui';
import { CogIcon } from '@rgossiaux/svelte-heroicons/outline'; import { CogIcon } from '@rgossiaux/svelte-heroicons/outline';
import Themes from './themes.svelte'; import Themes from './themes.svelte';
import GameCollection from './gameCollection.svelte'; import GameCollection from './gameCollection.svelte';
</script> </script>
<div class="container"> <div class="container">
<Popover let:open class="popover"> <Popover let:open class="popover">
<PopoverButton aria-label="Preferences"> <PopoverButton aria-label="Preferences">
<CogIcon width="24" height="24" /> <CogIcon width="24" height="24" />
</PopoverButton> </PopoverButton>
{#if open} {#if open}
<div transition:fade={{ duration: 100 }}> <div transition:fade={{ duration: 100 }}>
<PopoverPanel class="popover-panel" static> <PopoverPanel class="popover-panel" static>
<div class="preferences"> <div class="preferences">
<svg <svg
width="24" width="24"
height="24" height="24"
class="arrow" class="arrow"
viewBox="0 0 24 24" viewBox="0 0 24 24"
fill="none" fill="none"
xmlns="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg"
> >
<path <path
id="inside" id="inside"
d="M23 24H1L11.0909 1.98341C11.4474 1.20562 12.5526 1.20562 12.9091 1.98341L23 24Z" d="M23 24H1L11.0909 1.98341C11.4474 1.20562 12.5526 1.20562 12.9091 1.98341L23 24Z"
fill="none" fill="none"
/> />
<path <path
id="outside" id="outside"
d="M12.8944 1.78885L24 24H23L12.9021 2.88628C12.5396 2.12822 11.4604 2.12822 11.0979 2.88628L1 24H0L11.1056 1.78885C11.4741 1.05181 12.5259 1.0518 12.8944 1.78885Z" d="M12.8944 1.78885L24 24H23L12.9021 2.88628C12.5396 2.12822 11.4604 2.12822 11.0979 2.88628L1 24H0L11.1056 1.78885C11.4741 1.05181 12.5259 1.0518 12.8944 1.78885Z"
fill="none" fill="none"
/> />
</svg> </svg>
<span class="title">Preferences</span> <span class="title">Preferences</span>
<div class="options"> <div class="options">
<Themes /> <Themes />
<GameCollection /> <GameCollection />
</div> </div>
</div> </div>
</PopoverPanel> </PopoverPanel>
</div> </div>
{/if} {/if}
</Popover> </Popover>
</div> </div>
<style lang="scss"> <style lang="scss">
.container { .container {
width: 24px; width: 24px;
height: 24px; height: 24px;
z-index: 10; z-index: 10;
} }
.container :global(.popover) { .container :global(.popover) {
height: 100%; height: 100%;
position: relative; position: relative;
} }
.container :global(.popover-panel) { .container :global(.popover-panel) {
position: absolute; position: absolute;
top: 48px; top: 48px;
right: -22px; right: -22px;
z-index: 10; z-index: 10;
} }
.preferences { .preferences {
background-image: var(--clr-menu-bg); background-image: var(--clr-menu-bg);
padding: var(--spacing-24); padding: var(--spacing-24);
border: 1px solid var(--clr-menu-border); border: 1px solid var(--clr-menu-border);
border-radius: var(--rounded-20); border-radius: var(--rounded-20);
box-shadow: var(--shadow-lg); box-shadow: var(--shadow-lg);
} }
.preferences .arrow { .preferences .arrow {
position: absolute; position: absolute;
top: -23px; top: -23px;
right: 22px; right: 22px;
} }
.preferences .arrow #inside { .preferences .arrow #inside {
fill: var(--clr-menu-arrow-bg); fill: var(--clr-menu-arrow-bg);
} }
.preferences .arrow #outside { .preferences .arrow #outside {
fill: var(--clr-menu-border); fill: var(--clr-menu-border);
} }
.preferences .title { .preferences .title {
display: block; display: block;
padding-bottom: var(--spacing-8); padding-bottom: var(--spacing-8);
font-size: var(--font-24); font-size: var(--font-24);
font-weight: 700; font-weight: 700;
line-height: 32px; line-height: 32px;
border-bottom: 1px solid var(--clr-menu-border); border-bottom: 1px solid var(--clr-menu-border);
} }
.preferences .options { .preferences .options {
font-weight: 500; font-weight: 500;
color: var(--clr-menu-text); color: var(--clr-menu-text);
} }
.preferences .options > :global(*) { .preferences .options > :global(*) {
display: flex; display: flex;
justify-content: space-between; justify-content: space-between;
align-items: center; align-items: center;
gap: var(--spacing-32); gap: var(--spacing-32);
padding: var(--spacing-24) 0; padding: var(--spacing-24) 0;
} }
.preferences .options > :global(*:not(:last-child)) { .preferences .options > :global(*:not(:last-child)) {
border-bottom: 1px solid var(--clr-menu-border); border-bottom: 1px solid var(--clr-menu-border);
} }
.preferences .options > :global(*:last-child) { .preferences .options > :global(*:last-child) {
padding-bottom: 0; padding-bottom: 0;
} }
.preferences .options span { .preferences .options span {
max-width: 180px; max-width: 180px;
} }
@media (min-width: 480px) { // @media (min-width: 650px) {
.preferences { // .preferences {
width: 420px; // width: 500px;
} // }
.preferences .options > :global(*) { // .preferences .options > :global(*) {
gap: var(--spacing-64); // gap: var(--spacing-64);
} // }
} // }
@media (min-width: 480px) {
.preferences {
width: 500px;
}
.preferences .options > :global(*) {
gap: var(--spacing-32);
}
}
</style> </style>

View file

@ -1,4 +1,5 @@
<script lang="ts"> <script lang="ts">
import type { ActionData } from './$types';
import { boredState } from '$lib/stores/boredState'; import { boredState } from '$lib/stores/boredState';
export let form: ActionData; export let form: ActionData;

View file

@ -31,6 +31,7 @@
action="/search" action="/search"
method="POST" method="POST"
use:enhance={() => { use:enhance={() => {
gameStore.removeAll();
boredState.update((n) => ({ ...n, loading: true })); boredState.update((n) => ({ ...n, loading: true }));
return async ({ result }) => { return async ({ result }) => {
boredState.update((n) => ({ ...n, loading: false })); boredState.update((n) => ({ ...n, loading: false }));
@ -38,7 +39,6 @@
// `result` is an `ActionResult` object // `result` is an `ActionResult` object
if (result.type === 'success') { if (result.type === 'success') {
console.log('In success'); console.log('In success');
gameStore.removeAll();
const resultGames = result?.data?.games; const resultGames = result?.data?.games;
if (resultGames?.length <= 0) { if (resultGames?.length <= 0) {
toast.send('No results!', { duration: 3000, type: ToastType.INFO, dismissible: true }); toast.send('No results!', { duration: 3000, type: ToastType.INFO, dismissible: true });

View file

@ -80,6 +80,7 @@
action="/search" action="/search"
method="post" method="post"
use:enhance={() => { use:enhance={() => {
gameStore.removeAll();
boredState.update((n) => ({ ...n, loading: true })); boredState.update((n) => ({ ...n, loading: true }));
return async ({ result }) => { return async ({ result }) => {
boredState.update((n) => ({ ...n, loading: false })); boredState.update((n) => ({ ...n, loading: false }));
@ -87,7 +88,6 @@
// `result` is an `ActionResult` object // `result` is an `ActionResult` object
if (result.type === 'success') { if (result.type === 'success') {
console.log('In success'); console.log('In success');
gameStore.removeAll();
const resultGames = result?.data?.games; const resultGames = result?.data?.games;
if (resultGames?.length <= 0) { if (resultGames?.length <= 0) {
toast.send('No results!', { duration: 3000, type: ToastType.INFO, dismissible: true }); toast.send('No results!', { duration: 3000, type: ToastType.INFO, dismissible: true });

View file

@ -1,64 +0,0 @@
import { json as json$1 } from '@sveltejs/kit';
import type { RequestHandler } from '@sveltejs/kit';
import type { GameType, SearchQuery } from '$lib/types';
import { mapAPIGameToBoredGame } from '$lib/util/gameMapper';
export const POST: RequestHandler = async ({ request }) => {
const form = await request.formData();
console.log('form', form);
const queryParams: SearchQuery = {
order_by: 'rank',
ascending: false,
limit: 10,
skip: 0,
client_id: import.meta.env.VITE_PUBLIC_CLIENT_ID,
fuzzy_match: true,
name: ''
};
queryParams.name = `${form.get('name')}`;
const newQueryParams = {};
for (const key in queryParams) {
console.log('key', key);
console.log('queryParams[key]', queryParams[key]);
newQueryParams[key] = `${queryParams[key]}`;
}
const urlQueryParams = new URLSearchParams(newQueryParams);
const url = `https://api.boardgameatlas.com/api/search${urlQueryParams ? `?${urlQueryParams}` : ''
}`;
const response = await fetch(url, {
method: 'get',
headers: {
'content-type': 'application/json'
}
});
// console.log('board game response', response);
if (response.status === 404) {
// user hasn't created a todo list.
// start with an empty array
return json$1({
games: []
});
}
if (response.status === 200) {
const gameResponse = await response.json();
const gameList = gameResponse?.games;
const totalCount = gameResponse?.count;
console.log('totalCount', totalCount);
const games: GameType[] = [];
gameList.forEach((game) => {
games.push(mapAPIGameToBoredGame(game));
});
return json$1({
totalCount,
games
});
}
return new Response(undefined, { status: response.status });
};

View file

@ -1,28 +0,0 @@
import { json as json$1 } from '@sveltejs/kit';
import { boardGameApi } from '$root/routes/api';
import type { RequestHandler } from '@sveltejs/kit';
export const GET: RequestHandler = async ({ params }) => {
const queryParams = {
ids: `${params?.id}`
};
console.log('queryParams', queryParams);
const response = await boardGameApi('get', `search`, queryParams);
if (response.status === 404) {
return json$1({
games: []
});
}
if (response.status === 200) {
const gameResponse = await response.json();
// console.log('gameResponse', gameResponse);
// const games = gameResponse?.games;
console.log('game', gameResponse?.games[0]);
return json$1({
game: gameResponse?.games[0]
});
}
return new Response(undefined, { status: response.status });
};

View file

@ -1,100 +0,0 @@
import { json as json$1 } from '@sveltejs/kit';
import type { RequestHandler } from '@sveltejs/kit';
import type { GameType, SearchQuery } from '$lib/types';
import { mapAPIGameToBoredGame } from '$lib/util/gameMapper';
export const POST: RequestHandler = async ({ request }) => {
const form = await request.formData();
console.log('form', form);
const queryParams: SearchQuery = {
order_by: 'rank',
ascending: false,
limit: 20,
client_id: import.meta.env.VITE_PUBLIC_CLIENT_ID
};
const id = form.get('id');
const ids = form.get('ids');
const minAge = form.get('minAge');
const minPlayers = form.get('minPlayers');
const maxPlayers = form.get('maxPlayers');
const exactMinAge = form.get('exactMinAge') || false;
const exactMinPlayers = form.get('exactMinPlayers') || false;
const exactMaxPlayers = form.get('exactMaxPlayers') || false;
const random = form.get('random') === 'on' || false;
if (minAge) {
if (exactMinAge) {
queryParams.min_age = +minAge;
} else {
queryParams.gt_min_age = +minAge === 1 ? 0 : +minAge - 1;
}
}
if (minPlayers) {
if (exactMinPlayers) {
queryParams.min_players = +minPlayers;
} else {
queryParams.gt_min_players = +minPlayers === 1 ? 0 : +minPlayers - 1;
}
}
if (maxPlayers) {
if (exactMaxPlayers) {
queryParams.max_players = +maxPlayers;
} else {
queryParams.lt_max_players = +maxPlayers + 1;
}
}
if (id) {
queryParams.ids = new Array(`${id}`);
}
if (ids) {
// TODO: Pass in ids array from localstorage / game store
queryParams.ids = new Array(ids);
}
queryParams.random = random;
console.log('queryParams', queryParams);
const newQueryParams: Record<string, string> = {};
for (const key in queryParams) {
newQueryParams[key] = `${queryParams[key as keyof typeof queryParams]}`;
}
const urlQueryParams = new URLSearchParams(newQueryParams);
const url = `https://api.boardgameatlas.com/api/search${urlQueryParams ? `?${urlQueryParams}` : ''
}`;
const response = await fetch(url, {
method: 'get',
headers: {
'content-type': 'application/json'
}
});
console.log('board game response', response);
if (response.status === 404) {
// user hasn't created a todo list.
// start with an empty array
return json$1({
games: []
});
}
if (response.status === 200) {
const gameResponse = await response.json();
const gameList = gameResponse?.games;
const games: GameType[] = [];
gameList.forEach((game) => {
games.push(mapAPIGameToBoredGame(game));
});
console.log('games', games);
return {
games
};
}
return new Response(undefined, { status: response.status });
};

View file

@ -1,7 +1,6 @@
import { error } from '@sveltejs/kit'; import { error } from '@sveltejs/kit';
import type { PageServerLoad } from './$types' import type { PageServerLoad } from './$types'
import { boardGameApi } from '../../api'; import { boardGameApi } from '../../api';
// import { Games } from '$lib/db/actions';
type GamePageParams = { type GamePageParams = {
params: { params: {
@ -9,33 +8,19 @@ type GamePageParams = {
} }
} }
// export const actions = {
// default Games.create,
// }
export const load: PageServerLoad = async ({ params }: GamePageParams) => { export const load: PageServerLoad = async ({ params }: GamePageParams) => {
console.log('params', params);
const queryParams = { const queryParams = {
ids: `${params?.id}` ids: `${params?.id}`
}; };
// console.log('queryParams', queryParams);
const response = await boardGameApi('get', `search`, queryParams); const response = await boardGameApi('get', `search`, queryParams);
if (response.status === 404) {
return {
game: []
};
}
if (response.status === 200) { if (response.status === 200) {
const gameResponse = await response.json(); const gameResponse = await response.json();
// console.log('gameResponse', gameResponse);
// const games = gameResponse?.games;
// console.log('game response', gameResponse?.games[0]);
return { return {
game: gameResponse?.games[0] game: gameResponse?.games[0]
}; };
} }
throw error(response.status); throw error(response.status, 'not found');
// throw new Error("@migration task: Migrate this return statement (https://github.com/sveltejs/kit/discussions/5774#discussioncomment-3292699)");
}; };

View file

@ -1,155 +1,168 @@
<script lang="ts"> <script lang="ts">
import { fade } from 'svelte/transition'; import { fade } from 'svelte/transition';
import { import {
ExternalLinkIcon, ExternalLinkIcon,
MinusCircleIcon, MinusCircleIcon,
MinusIcon, MinusIcon,
PlusCircleIcon, PlusCircleIcon,
PlusIcon PlusIcon
} from '@rgossiaux/svelte-heroicons/outline'; } from '@rgossiaux/svelte-heroicons/outline';
import type { GameType, SavedGameType } from '$lib/types'; import type { GameType, SavedGameType } from '$lib/types';
import { collectionStore } from '$lib/stores/collectionStore'; import { collectionStore } from '$lib/stores/collectionStore';
import RemoveCollectionDialog from '$root/lib/components/dialog/RemoveCollectionDialog.svelte'; import RemoveCollectionDialog from '$root/lib/components/dialog/RemoveCollectionDialog.svelte';
import { addToCollection } from '$lib/util/manipulateCollection'; import { addToCollection } from '$lib/util/manipulateCollection';
import type { PageData } from './$types'; import type { PageData } from './$types';
import { boredState } from '$root/lib/stores/boredState'; import { boredState } from '$root/lib/stores/boredState';
import { browser } from '$app/environment';
$: existsInCollection = $collectionStore.find((item: SavedGameType) => item.id === game.id); $: existsInCollection = $collectionStore.find((item: SavedGameType) => item.id === game.id);
export let data: PageData; export let data: PageData;
export let game: GameType = data?.game; export let game: GameType = data?.game;
console.log('page game', game); console.log('page game', game);
let seeMore: boolean = false; let seeMore: boolean = false;
console.log(game?.description?.indexOf('</p>')); console.log(game?.description?.indexOf('</p>'));
let firstParagraphEnd = 0; let firstParagraphEnd = 0;
if (game?.description?.indexOf('</p>') > 0) { if (game?.description?.indexOf('</p>') > 0) {
firstParagraphEnd = game?.description?.indexOf('</p>') + 4; firstParagraphEnd = game?.description?.indexOf('</p>') + 4;
} else if (game?.description?.indexOf('</ p>') > 0) { } else if (game?.description?.indexOf('</ p>') > 0) {
firstParagraphEnd = game?.description?.indexOf('</ p>') + 5; firstParagraphEnd = game?.description?.indexOf('</ p>') + 5;
} }
console.log('firstParagraphEnd', firstParagraphEnd); console.log('firstParagraphEnd', firstParagraphEnd);
function removeGame() { function removeGame() {
boredState.update((n) => ({ boredState.update((n) => ({
...n, ...n,
dialog: { isOpen: true, content: RemoveCollectionDialog, additionalData: game } dialog: { isOpen: true, content: RemoveCollectionDialog, additionalData: game }
})); }));
} if (browser) {
localStorage.collection = JSON.stringify($collectionStore);
}
}
</script> </script>
<svelte:head> <svelte:head>
<title>{game?.name} | Bored Game</title> <title>{game?.name} | Bored Game</title>
</svelte:head> </svelte:head>
<h2>{game?.name}</h2> <h2>{game?.name}</h2>
<section class="games"> <section class="games">
<div> <div>
<a class="thumbnail" href={game.url}> <a class="thumbnail" href={game.url}>
<img src={game.image_url} alt={`Image of ${game.name}`} /> <img src={game.image_url} alt={`Image of ${game.name}`} />
</a> </a>
</div> </div>
<div class="details"> <div class="details">
<p>Year Published: {game?.year_published}</p> <p>Year Published: {game?.year_published}</p>
<p>Players: {game.players} {game.max_players === 1 ? 'player' : 'players'}</p> <p>Players: {game.players} {game.max_players === 1 ? 'player' : 'players'}</p>
<p>Playtime: {game.playtime} minutes</p> <p>Playtime: {game.playtime} minutes</p>
<p>Minimum Age: {game.min_age}</p> <p>Minimum Age: {game.min_age}</p>
<p>Price: ${game?.price}</p> {#if +game?.price !== 0.0}
<a <p>Price: ${game?.price}</p>
class="with-icon" {/if}
style="display: flex; gap: 1rem;" <a
href={game.url} class="with-icon"
target="_blank" style="display: flex; gap: 1rem;"
rel="noreferrer" href={game.url}
aria-label={`Board Game Atlas Link for ${game.name}`} target="_blank"
>Board Game Atlas Link <ExternalLinkIcon width="24" height="24" /></a rel="noreferrer"
> aria-label={`Board Game Atlas Link for ${game.name}`}
{#if existsInCollection} >Board Game Atlas Link <ExternalLinkIcon width="24" height="24" /></a
<button class="btn" type="button" on:click={() => removeGame()} >
>Remove from collection <MinusCircleIcon width="24" height="24" /></button {#if existsInCollection}
> <button class="btn" type="button" on:click={() => removeGame()}
{:else} >Remove from collection <MinusCircleIcon width="24" height="24" /></button
<button class="btn" type="button" on:click={() => addToCollection(game)} >
>Add to collection <PlusCircleIcon width="24" height="24" /></button {:else}
> <button
{/if} class="btn"
</div> type="button"
on:click={() => {
addToCollection(game);
if (browser) {
localStorage.collection = JSON.stringify($collectionStore);
}
}}>Add to collection <PlusCircleIcon width="24" height="24" /></button
>
{/if}
</div>
</section> </section>
{#if firstParagraphEnd > 0} {#if firstParagraphEnd > 0}
<section class="description"> <section class="description">
<span> <span>
{@html game?.description?.substring(0, firstParagraphEnd)} {@html game?.description?.substring(0, firstParagraphEnd)}
</span> </span>
{#if game?.description?.substring(firstParagraphEnd + 1) !== ''} {#if game?.description?.substring(firstParagraphEnd + 1) !== ''}
{#if seeMore} {#if seeMore}
<span transition:fade> <span transition:fade>
{@html game?.description?.substring(firstParagraphEnd + 1)} {@html game?.description?.substring(firstParagraphEnd + 1)}
</span> </span>
{/if} {/if}
<button class="btn" type="button" on:click={() => (seeMore = !seeMore)} <button class="btn" type="button" on:click={() => (seeMore = !seeMore)}
>See >See
{#if !seeMore} {#if !seeMore}
More <PlusIcon width="24" height="24" /> More <PlusIcon width="24" height="24" />
{:else} {:else}
Less <MinusIcon width="24" height="24" /> Less <MinusIcon width="24" height="24" />
{/if} {/if}
</button> </button>
{/if} {/if}
</section> </section>
{:else} {:else}
<section class="description"> <section class="description">
<span> <span>
{@html game?.description} {@html game?.description}
</span> </span>
</section> </section>
{/if} {/if}
<style lang="scss"> <style lang="scss">
h2 { h2 {
text-align: center; text-align: center;
font-size: 2.5rem; font-size: 2.5rem;
font-weight: 600; font-weight: 600;
margin-bottom: 3rem; margin-bottom: 3rem;
} }
button { button {
display: flex; display: flex;
justify-content: space-between; justify-content: space-between;
align-items: center; align-items: center;
border-radius: 4px; border-radius: 4px;
margin: 0; margin: 0;
padding: 1rem; padding: 1rem;
max-width: 30rem; max-width: 30rem;
background-color: var(--color-btn-primary-active); background-color: var(--color-btn-primary-active);
} }
.games { .games {
display: grid; display: grid;
grid-template-columns: 1fr 1fr; grid-template-columns: 1fr 1fr;
gap: 2rem; gap: 2rem;
margin: 1rem; margin: 1rem;
} }
.details { .details {
display: grid; display: grid;
gap: 0.5rem; gap: 0.5rem;
align-content: center; align-content: center;
justify-content: start; justify-content: start;
margin: 1rem; margin: 1rem;
a, a,
p { p {
margin: 1rem; margin: 1rem;
} }
} }
.description { .description {
display: grid; display: grid;
gap: 1.5rem; gap: 1.5rem;
margin: 1rem; margin: 1rem;
} }
.with-icon { .with-icon {
display: flex; display: flex;
place-items: center; place-items: center;
} }
</style> </style>