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

@ -7,12 +7,17 @@
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 { collectionStore } from '$root/lib/stores/collectionStore';
import { removeFromCollection } from '$root/lib/util/manipulateCollection'; 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);
} }
if (browser) {
localStorage.collection = JSON.stringify($collectionStore);
}
boredState.update((n) => ({ ...n, dialog: { isOpen: false } })); boredState.update((n) => ({ ...n, dialog: { isOpen: false } }));
} }

View file

@ -5,6 +5,7 @@
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;
@ -44,15 +45,21 @@
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();
}}>Remove <MinusCircleIcon width="24" height="24" /></button
> >
{:else} {:else}
<button <button
aria-label="Add to collection" aria-label="Add to collection"
class="btn" class="btn"
type="button" type="button"
on:click={() => addToCollection(game)} on:click={() => {
>Add to collection <PlusCircleIcon width="24" height="24" /></button addToCollection(game);
if (browser) {
localStorage.collection = JSON.stringify($collectionStore);
}
}}>Add to collection <PlusCircleIcon width="24" height="24" /></button
> >
{/if} {/if}
</article> </article>

View file

@ -2,17 +2,30 @@
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');
console.log('collectionStore', $collectionStore);
if (!browser) return; if (!browser) return;
localStorage.collection = JSON.stringify($collectionStore); localStorage.collection = JSON.stringify($collectionStore);
toast.send('Saved collection', { duration: 3000, type: ToastType.INFO }); toast.send('Saved collection', { duration: 3000, type: ToastType.INFO });
} }
function exportCollection() {
if (!browser) return;
const collectionBlob = new Blob([JSON.stringify($collectionStore)], {
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() { function clearCollection() {
if (!browser) return; if (!browser) return;
localStorage.collection = []; localStorage.collection = [];
@ -25,6 +38,9 @@
<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="Export Collection" on:click={() => exportCollection()}
><ShareIcon width="24" height="24" />Export</button
>
<button type="button" aria-label="Save Collection" on:click={() => saveCollection()} <button type="button" aria-label="Save Collection" on:click={() => saveCollection()}
><SaveIcon width="24" height="24" />Save</button ><SaveIcon width="24" height="24" />Save</button
> >
@ -34,7 +50,7 @@
</div> </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);
@ -46,7 +62,11 @@
display: flex; display: flex;
flex-direction: row; flex-direction: row;
justify-content: space-between; justify-content: space-between;
gap: 6rem; // gap: 6rem;
@media (min-width: 480px) {
gap: 3rem;
}
} }
button { button {

View file

@ -124,13 +124,23 @@
max-width: 180px; max-width: 180px;
} }
// @media (min-width: 650px) {
// .preferences {
// width: 500px;
// }
// .preferences .options > :global(*) {
// gap: var(--spacing-64);
// }
// }
@media (min-width: 480px) { @media (min-width: 480px) {
.preferences { .preferences {
width: 420px; width: 500px;
} }
.preferences .options > :global(*) { .preferences .options > :global(*) {
gap: var(--spacing-64); 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

@ -13,6 +13,7 @@
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);
@ -34,6 +35,9 @@
...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>
@ -54,7 +58,9 @@
<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>
{#if +game?.price !== 0.0}
<p>Price: ${game?.price}</p> <p>Price: ${game?.price}</p>
{/if}
<a <a
class="with-icon" class="with-icon"
style="display: flex; gap: 1rem;" style="display: flex; gap: 1rem;"
@ -69,8 +75,15 @@
>Remove from collection <MinusCircleIcon width="24" height="24" /></button >Remove from collection <MinusCircleIcon width="24" height="24" /></button
> >
{:else} {:else}
<button class="btn" type="button" on:click={() => addToCollection(game)} <button
>Add to collection <PlusCircleIcon width="24" height="24" /></button class="btn"
type="button"
on:click={() => {
addToCollection(game);
if (browser) {
localStorage.collection = JSON.stringify($collectionStore);
}
}}>Add to collection <PlusCircleIcon width="24" height="24" /></button
> >
{/if} {/if}
</div> </div>