1
0
Fork 0
mirror of https://github.com/seanmorley15/AdventureLog.git synced 2025-07-30 18:29:37 +02:00

better filters

This commit is contained in:
Sean Morley 2024-08-05 09:33:21 -04:00
parent 32f5c1a806
commit 44cad30528
2 changed files with 267 additions and 250 deletions

View file

@ -13,12 +13,33 @@ export const load = (async (event) => {
if (!event.locals.user) { if (!event.locals.user) {
return redirect(302, '/login'); return redirect(302, '/login');
} else { } else {
let next = null;
let previous = null;
let count = 0; let count = 0;
let adventures: Adventure[] = []; let adventures: Adventure[] = [];
const visited = event.url.searchParams.get('visited');
const planned = event.url.searchParams.get('planned');
let typeString: string = '';
if (visited == 'on') {
typeString += 'visited';
}
if (planned == 'on') {
if (typeString) {
typeString += ',';
}
typeString += 'planned';
} else if (!visited && !planned) {
typeString = 'visited,planned';
}
const include_collections = event.url.searchParams.get('include_collections') || 'false';
const order_by = event.url.searchParams.get('order_by') || 'updated_at';
const order_direction = event.url.searchParams.get('order_direction') || 'asc';
const page = event.url.searchParams.get('page') || '1';
let initialFetch = await fetch( let initialFetch = await fetch(
`${serverEndpoint}/api/adventures/filtered?types=visited,planned&include_collections=false`, `${serverEndpoint}/api/adventures/filtered?types=${typeString}&order_by=${order_by}&order_direction=${order_direction}&include_collections=${include_collections}&page=${page}`,
{ {
headers: { headers: {
Cookie: `${event.cookies.get('auth')}` Cookie: `${event.cookies.get('auth')}`
@ -31,8 +52,7 @@ export const load = (async (event) => {
} else { } else {
let res = await initialFetch.json(); let res = await initialFetch.json();
let visited = res.results as Adventure[]; let visited = res.results as Adventure[];
next = res.next;
previous = res.previous;
count = res.count; count = res.count;
adventures = [...adventures, ...visited]; adventures = [...adventures, ...visited];
} }
@ -40,8 +60,6 @@ export const load = (async (event) => {
return { return {
props: { props: {
adventures, adventures,
next,
previous,
count count
} }
}; };
@ -384,203 +402,203 @@ export const actions: Actions = {
let image_url = adventure.image; let image_url = adventure.image;
let link_url = adventure.link; let link_url = adventure.link;
return { image_url, link_url }; return { image_url, link_url };
},
get: async (event) => {
if (!event.locals.user) {
} }
// get: async (event) => {
// if (!event.locals.user) {
// }
const formData = await event.request.formData(); // const formData = await event.request.formData();
const visited = formData.get('visited'); // const visited = formData.get('visited');
const planned = formData.get('planned'); // const planned = formData.get('planned');
let include_collections = formData.get('include_collections') as string; // let include_collections = formData.get('include_collections') as string;
if (include_collections) { // if (include_collections) {
include_collections = 'true'; // include_collections = 'true';
} else { // } else {
include_collections = 'false'; // include_collections = 'false';
} // }
const order_direction = formData.get('order_direction') as string; // const order_direction = formData.get('order_direction') as string;
const order_by = formData.get('order_by') as string; // const order_by = formData.get('order_by') as string;
console.log(order_direction, order_by); // console.log(order_direction, order_by);
let adventures: Adventure[] = []; // let adventures: Adventure[] = [];
if (!event.locals.user) { // if (!event.locals.user) {
return { // return {
status: 401, // status: 401,
body: { message: 'Unauthorized' } // body: { message: 'Unauthorized' }
}; // };
} // }
let filterString = ''; // let filterString = '';
if (visited) { // if (visited) {
filterString += 'visited'; // filterString += 'visited';
} // }
if (planned) { // if (planned) {
if (filterString) { // if (filterString) {
filterString += ','; // filterString += ',';
} // }
filterString += 'planned'; // filterString += 'planned';
} // }
if (!filterString) { // if (!filterString) {
filterString = ''; // filterString = '';
} // }
let next = null; // let next = null;
let previous = null; // let previous = null;
let count = 0; // let count = 0;
console.log(filterString); // console.log(filterString);
let visitedFetch = await fetch( // let visitedFetch = await fetch(
`${serverEndpoint}/api/adventures/filtered?types=${filterString}&order_by=${order_by}&order_direction=${order_direction}&include_collections=${include_collections}`, // `${serverEndpoint}/api/adventures/filtered?types=${filterString}&order_by=${order_by}&order_direction=${order_direction}&include_collections=${include_collections}`,
{ // {
headers: { // headers: {
Cookie: `${event.cookies.get('auth')}` // Cookie: `${event.cookies.get('auth')}`
} // }
} // }
); // );
if (!visitedFetch.ok) { // if (!visitedFetch.ok) {
console.error('Failed to fetch visited adventures'); // console.error('Failed to fetch visited adventures');
return redirect(302, '/login'); // return redirect(302, '/login');
} else { // } else {
let res = await visitedFetch.json(); // let res = await visitedFetch.json();
let visited = res.results as Adventure[]; // let visited = res.results as Adventure[];
next = res.next; // next = res.next;
previous = res.previous; // previous = res.previous;
count = res.count; // count = res.count;
adventures = [...adventures, ...visited]; // adventures = [...adventures, ...visited];
console.log(next, previous, count); // console.log(next, previous, count);
} // }
return { // return {
adventures, // adventures,
next, // next,
previous, // previous,
count // count
}; // };
}, // },
changePage: async (event) => { // changePage: async (event) => {
const formData = await event.request.formData(); // const formData = await event.request.formData();
const next = formData.get('next') as string; // const next = formData.get('next') as string;
const previous = formData.get('previous') as string; // const previous = formData.get('previous') as string;
const page = formData.get('page') as string; // const page = formData.get('page') as string;
if (!event.locals.user) { // if (!event.locals.user) {
return { // return {
status: 401, // status: 401,
body: { message: 'Unauthorized' } // body: { message: 'Unauthorized' }
}; // };
} // }
if (!page) { // if (!page) {
return { // return {
status: 400, // status: 400,
body: { error: 'Missing required fields' } // body: { error: 'Missing required fields' }
}; // };
} // }
// Start with the provided URL or default to the filtered adventures endpoint // // Start with the provided URL or default to the filtered adventures endpoint
let url: string = next || previous || '/api/adventures/filtered'; // let url: string = next || previous || '/api/adventures/filtered';
// Extract the path starting from '/api/adventures' // // Extract the path starting from '/api/adventures'
const apiIndex = url.indexOf('/api/adventures'); // const apiIndex = url.indexOf('/api/adventures');
if (apiIndex !== -1) { // if (apiIndex !== -1) {
url = url.slice(apiIndex); // url = url.slice(apiIndex);
} else { // } else {
url = '/api/adventures/filtered'; // url = '/api/adventures/filtered';
} // }
// Replace or add the page number in the URL // // Replace or add the page number in the URL
if (url.includes('page=')) { // if (url.includes('page=')) {
url = url.replace(/page=\d+/, `page=${page}`); // url = url.replace(/page=\d+/, `page=${page}`);
} else { // } else {
// If 'page=' is not in the URL, add it // // If 'page=' is not in the URL, add it
url += url.includes('?') ? '&' : '?'; // url += url.includes('?') ? '&' : '?';
url += `page=${page}`; // url += `page=${page}`;
} // }
const fullUrl = `${serverEndpoint}${url}`; // const fullUrl = `${serverEndpoint}${url}`;
console.log(fullUrl); // console.log(fullUrl);
console.log(serverEndpoint); // console.log(serverEndpoint);
try { // try {
const response = await fetch(fullUrl, { // const response = await fetch(fullUrl, {
headers: { // headers: {
'Content-Type': 'application/json', // 'Content-Type': 'application/json',
Cookie: `${event.cookies.get('auth')}` // Cookie: `${event.cookies.get('auth')}`
} // }
}); // });
if (!response.ok) { // if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`); // throw new Error(`HTTP error! status: ${response.status}`);
} // }
const data = await response.json(); // const data = await response.json();
let adventures = data.results as Adventure[]; // let adventures = data.results as Adventure[];
let next = data.next; // let next = data.next;
let previous = data.previous; // let previous = data.previous;
let count = data.count; // let count = data.count;
return { // return {
status: 200, // status: 200,
body: { // body: {
adventures, // adventures,
next, // next,
previous, // previous,
count, // count,
page // page
} // }
}; // };
} catch (error) { // } catch (error) {
console.error('Error fetching data:', error); // console.error('Error fetching data:', error);
return { // return {
status: 500, // status: 500,
body: { error: 'Failed to fetch data' } // body: { error: 'Failed to fetch data' }
}; // };
} // }
}, // },
all: async (event) => { // all: async (event) => {
if (!event.locals.user) { // if (!event.locals.user) {
return { // return {
status: 401, // status: 401,
body: { message: 'Unauthorized' } // body: { message: 'Unauthorized' }
}; // };
} // }
const formData = await event.request.formData(); // const formData = await event.request.formData();
let include_collections = formData.get('include_collections') as string; // let include_collections = formData.get('include_collections') as string;
if (include_collections !== 'true' && include_collections !== 'false') { // if (include_collections !== 'true' && include_collections !== 'false') {
include_collections = 'false'; // include_collections = 'false';
} // }
let adventures: Adventure[] = []; // let adventures: Adventure[] = [];
let visitedFetch = await fetch( // let visitedFetch = await fetch(
`${serverEndpoint}/api/adventures/all/?include_collections=${include_collections}`, // `${serverEndpoint}/api/adventures/all/?include_collections=${include_collections}`,
{ // {
headers: { // headers: {
Cookie: `${event.cookies.get('auth')}`, // Cookie: `${event.cookies.get('auth')}`,
'Content-Type': 'application/json' // 'Content-Type': 'application/json'
} // }
} // }
); // );
if (!visitedFetch.ok) { // if (!visitedFetch.ok) {
console.error('Failed to fetch all adventures'); // console.error('Failed to fetch all adventures');
return redirect(302, '/login'); // return redirect(302, '/login');
} else { // } else {
console.log('Fetched all adventures'); // console.log('Fetched all adventures');
let res = await visitedFetch.json(); // let res = await visitedFetch.json();
console.log(res); // console.log(res);
adventures = res as Adventure[]; // adventures = res as Adventure[];
} // }
return { // return {
adventures // adventures
}; // };
} // }
}; };

View file

@ -1,5 +1,7 @@
<script lang="ts"> <script lang="ts">
import { enhance, deserialize } from '$app/forms'; import { enhance, deserialize } from '$app/forms';
import { goto } from '$app/navigation';
import { page } from '$app/stores';
import AdventureCard from '$lib/components/AdventureCard.svelte'; import AdventureCard from '$lib/components/AdventureCard.svelte';
import EditAdventure from '$lib/components/EditAdventure.svelte'; import EditAdventure from '$lib/components/EditAdventure.svelte';
import NewAdventure from '$lib/components/NewAdventure.svelte'; import NewAdventure from '$lib/components/NewAdventure.svelte';
@ -20,46 +22,46 @@
let resultsPerPage: number = 25; let resultsPerPage: number = 25;
let next: string | null = data.props.next || null; // let next: string | null = data.props.next || null;
let previous: string | null = data.props.previous || null; // let previous: string | null = data.props.previous || null;
let count = data.props.count || 0; let count = data.props.count || 0;
let totalPages = Math.ceil(count / resultsPerPage); let totalPages = Math.ceil(count / resultsPerPage);
let currentPage: number = 1; let currentPage: number = 1;
function handleChangePage() { function handleChangePage(pageNumber: number) {
return async ({ result }: any) => { // let query = new URLSearchParams($page.url.searchParams.toString());
if (result.type === 'success') {
console.log(result.data); // query.set('page', pageNumber.toString());
adventures = result.data.body.adventures as Adventure[];
next = result.data.body.next; // console.log(query.toString());
previous = result.data.body.previous; currentPage = pageNumber;
count = result.data.body.count;
currentPage = result.data.body.page; let url = new URL(window.location.href);
url.searchParams.set('page', pageNumber.toString());
adventures = [];
adventures = data.props.adventures;
console.log(adventures);
goto(url.toString(), { invalidateAll: true, replaceState: true });
// goto(`?${query.toString()}`, { invalidateAll: true });
}
$: {
let url = new URL($page.url);
let page = url.searchParams.get('page');
if (page) {
currentPage = parseInt(page);
}
}
$: {
if (data.props.adventures) {
adventures = data.props.adventures;
}
if (data.props.count) {
count = data.props.count;
totalPages = Math.ceil(count / resultsPerPage); totalPages = Math.ceil(count / resultsPerPage);
} }
};
}
function handleSubmit() {
return async ({ result, update }: any) => {
// First, call the update function with reset: false
update({ reset: false });
// Then, handle the result
if (result.type === 'success') {
if (result.data) {
// console.log(result.data);
adventures = result.data.adventures as Adventure[];
next = result.data.next;
previous = result.data.previous;
count = result.data.count;
totalPages = Math.ceil(count / resultsPerPage);
currentPage = 1;
console.log(next);
}
}
};
} }
function sort({ attribute, order }: { attribute: string; order: string }) { function sort({ attribute, order }: { attribute: string; order: string }) {
@ -193,19 +195,16 @@
</div> </div>
<div class="join flex items-center justify-center mt-4"> <div class="join flex items-center justify-center mt-4">
{#if next || previous} {#if totalPages > 1}
<div class="join"> <div class="join">
{#each Array.from({ length: totalPages }, (_, i) => i + 1) as page} {#each Array.from({ length: totalPages }, (_, i) => i + 1) as page}
<form action="?/changePage" method="POST" use:enhance={handleChangePage}>
<input type="hidden" name="page" value={page} />
<input type="hidden" name="next" value={next} />
<input type="hidden" name="previous" value={previous} />
{#if currentPage != page} {#if currentPage != page}
<button class="join-item btn btn-lg">{page}</button> <button class="join-item btn btn-lg" on:click={() => handleChangePage(page)}
>{page}</button
>
{:else} {:else}
<button class="join-item btn btn-lg btn-active">{page}</button> <button class="join-item btn btn-lg btn-active">{page}</button>
{/if} {/if}
</form>
{/each} {/each}
</div> </div>
{/if} {/if}
@ -219,7 +218,7 @@
<!-- Sidebar content here --> <!-- Sidebar content here -->
<div class="form-control"> <div class="form-control">
<h3 class="text-center font-bold text-lg mb-4">Adventure Types</h3> <h3 class="text-center font-bold text-lg mb-4">Adventure Types</h3>
<form action="?/get" method="post" use:enhance={handleSubmit}> <form method="get">
<label class="label cursor-pointer"> <label class="label cursor-pointer">
<span class="label-text">Completed</span> <span class="label-text">Completed</span>
<input <input