App: Add TS type information

This commit is contained in:
2024-12-13 19:56:47 +01:00
parent 04569ea683
commit 0abfaff004
20 changed files with 576 additions and 280 deletions

View File

@ -2,7 +2,7 @@ import type { LayoutServerLoad } from "./$types";
// On each page load (every route), this function runs serverside.
// The "locals.user" object is only available on the server,
// since it's populated inside hooks.server.ts.
// since it's populated inside hooks.server.ts per request.
// It will populate the "user" attribute of each page's "data" object,
// so each page has access to the current user (or knows if no one is signed in).
export const load: LayoutServerLoad = ({ locals }) => {

View File

@ -19,6 +19,7 @@
type DrawerSettings,
Avatar,
FileDropzone,
type DrawerStore,
} from "@skeletonlabs/skeleton";
import { computePosition, autoUpdate, offset, shift, flip, arrow } from "@floating-ui/dom";
@ -26,7 +27,7 @@
// Drawer config
initializeStores();
const drawerStore = getDrawerStore();
const drawerStore: DrawerStore = getDrawerStore();
const drawer_settings_base: DrawerSettings = {
position: "top",
@ -89,7 +90,7 @@
<!-- Menu Drawer -->
<!-- Menu Drawer -->
<!-- Menu Drawer -->
<div class="p-2 pt-0 *:mt-2">
<div class="flex flex-col gap-2 p-2">
<Button href="/racepicks" onclick={close_drawer} color="surface" fullwidth>Race Picks</Button>
<Button href="/seasonpicks" onclick={close_drawer} color="surface" fullwidth
>Season Picks
@ -106,7 +107,7 @@
<!-- Data Drawer -->
<!-- Data Drawer -->
<!-- Data Drawer -->
<div class="p-2 pt-0 *:mt-2">
<div class="flex flex-col gap-2 p-2">
<Button href="/data/season" onclick={close_drawer} color="surface" fullwidth>Season</Button>
<Button href="/data/user" onclick={close_drawer} color="surface" fullwidth>Users</Button>
</div>
@ -114,9 +115,9 @@
<!-- Login Drawer -->
<!-- Login Drawer -->
<!-- Login Drawer -->
<div class="p-2">
<div class="flex flex-col gap-2 p-2">
<h4 class="h4 select-none">Enter Username and Password</h4>
<form method="POST" class="*:mt-2">
<form method="POST" class="contents">
<Input name="username" placeholder="Username" required>
<UserIcon />
</Input>
@ -127,19 +128,22 @@
<Button formaction="/profile?/login" onclick={close_drawer} color="tertiary" submit
>Login</Button
>
<Button formaction="/profile?/create" onclick={close_drawer} color="tertiary" submit
>Register</Button
<Button
formaction="/profile?/create_profile"
onclick={close_drawer}
color="tertiary"
submit>Register</Button
>
</div>
</form>
</div>
{:else if $drawerStore.id === "profile_drawer"}
{:else if $drawerStore.id === "profile_drawer" && data.user}
<!-- Profile Drawer -->
<!-- Profile Drawer -->
<!-- Profile Drawer -->
<div class="p-2">
<div class="flex flex-col gap-2 p-2">
<h4 class="h4 select-none">Edit Profile</h4>
<form method="POST" enctype="multipart/form-data" class="*:mt-2">
<form method="POST" enctype="multipart/form-data" class="contents">
<input type="hidden" name="id" value={data.user.id} />
<Input name="username" value={data.user.username} placeholder="Username"><UserIcon /></Input
>
@ -150,8 +154,11 @@
<svelte:fragment slot="message"><b>Upload Avatar</b> or Drag and Drop</svelte:fragment>
</FileDropzone>
<div class="flex justify-end gap-2">
<Button formaction="/profile?/update" onclick={close_drawer} color="secondary" submit
>Save Changes</Button
<Button
formaction="/profile?/update_profile"
onclick={close_drawer}
color="secondary"
submit>Save Changes</Button
>
<Button formaction="/profile?/logout" onclick={close_drawer} color="primary" submit
>Logout</Button
@ -186,7 +193,7 @@
</svelte:fragment>
<!-- Large navigation -->
<div class="hidden lg:block">
<div class="hidden gap-2 lg:flex">
<Button href="/racepicks" color="primary" activate_href>Race Picks</Button>
<Button href="/seasonpicks" color="primary" activate_href>Season Picks</Button>
<Button href="/leaderboard" color="primary" activate_href>Leaderboard</Button>
@ -199,7 +206,7 @@
<Button
color="primary"
onclick={data_drawer}
activate_button={$page.url.pathname.startsWith("/data")}>Data</Button
activate={$page.url.pathname.startsWith("/data")}>Data</Button
>
<!-- Login/Profile drawer -->

View File

@ -0,0 +1,113 @@
import type { Actions, PageServerLoad } from "./$types";
import { form_data_clean, form_data_ensure_keys, form_data_get_and_remove_id } from "$lib/form";
import type { Team, Driver, Race, Substitution } from "$lib/schema";
// These "actions" run serverside only, as they're located inside +page.server.ts
export const actions = {
create_team: async ({ request, locals }) => {
if (!locals.admin) return { unauthorized: true };
const data: FormData = form_data_clean(await request.formData());
form_data_ensure_keys(data, ["name", "logo"]);
const record: Team = await locals.pb.collection("teams").create(data);
return { tab: 0 };
},
update_team: async ({ request, locals }) => {
if (!locals.admin) return { unauthorized: true };
const data: FormData = form_data_clean(await request.formData());
const id: string = form_data_get_and_remove_id(data);
const record: Team = await locals.pb.collection("teams").update(id, data);
return { tab: 0 };
},
delete_team: async ({ request, locals }) => {
if (!locals.admin) return { unauthorized: true };
const data: FormData = form_data_clean(await request.formData());
const id: string = form_data_get_and_remove_id(data);
await locals.pb.collection("teams").delete(id);
return { tab: 0 };
},
create_driver: async ({ request, locals }) => {
return { tab: 1 };
},
update_driver: async ({ request, locals }) => {
return { tab: 1 };
},
delete_driver: async ({ request, locals }) => {
return { tab: 1 };
},
create_race: async ({ request, locals }) => {
return { tab: 2 };
},
update_race: async ({ request, locals }) => {
return { tab: 2 };
},
delete_race: async ({ request, locals }) => {
return { tab: 2 };
},
create_substitution: async ({ request, locals }) => {
return { tab: 2 };
},
update_substitution: async ({ request, locals }) => {
return { tab: 2 };
},
delete_substitution: async ({ request, locals }) => {
return { tab: 2 };
},
} satisfies Actions;
// This "load" function runs serverside only, as it's located inside +page.server.ts
export const load: PageServerLoad = async ({ fetch, locals }) => {
const fetch_teams = async (): Promise<Array<Team>> => {
const teams: Array<Team> = await locals.pb.collection("teams").getFullList({
sort: "+name",
fetch: fetch,
});
teams.map((team: Team) => {
team.logo_url = locals.pb.files.getURL(team, team.logo);
});
return teams;
};
const fetch_drivers = async (): Promise<Array<Driver>> => {
const drivers: Array<Driver> = await locals.pb.collection("drivers").getFullList({
sort: "+lastname",
fetch: fetch,
});
drivers.map((driver: Driver) => {
driver.headshot_url = locals.pb.files.getURL(driver, driver.headshot);
});
return drivers;
};
const fetch_races = async (): Promise<Array<Race>> => {
return [];
};
const fetch_substitutions = async (): Promise<Array<Substitution>> => {
return [];
};
return {
teams: await fetch_teams(),
drivers: await fetch_drivers(),
races: await fetch_races(),
substitutions: await fetch_substitutions(),
};
};

View File

@ -0,0 +1,262 @@
<script lang="ts">
import { Input, Button, Card } from "$lib/components";
import { get_image_preview_event_handler } from "$lib/image";
import { get_by_id } from "$lib/database";
import type { Team } from "$lib/schema";
import { type PageData, type ActionData } from "./$types";
import { FileDropzone, Tab, TabGroup } from "@skeletonlabs/skeleton";
let { data, form }: { data: PageData; form: ActionData } = $props();
let current_tab: number = $state(0);
if (form?.tab) {
// console.log(`Form returned current_tab=${form.current_tab}`);
current_tab = form.tab;
}
</script>
<svelte:head>
<title>F11 - Season Data</title>
</svelte:head>
<TabGroup
justify="justify-center"
active="variant-filled-primary"
hover="hover:variant-filled-primary"
regionList="gap-2 shadow rounded-container-token p-2"
regionPanel="!mt-0"
rounded="rounded-container-token"
border=""
class="w-full rounded-container-token"
padding="p-2"
>
<Tab bind:group={current_tab} name="teams" value={0}>Teams</Tab>
<Tab bind:group={current_tab} name="drivers" value={1}>Drivers</Tab>
<Tab bind:group={current_tab} name="races" value={2}>Races</Tab>
<Tab bind:group={current_tab} name="substitutions" value={3}>Substitutions</Tab>
<svelte:fragment slot="panel">
{#if current_tab === 0}
<!-- Teams Tab -->
<!-- Teams Tab -->
<!-- Teams Tab -->
<div class="mt-2 grid grid-cols-1 gap-2 md:grid-cols-2 lg:grid-cols-4 xl:grid-cols-6">
<!-- List all teams inside the database -->
{#each data.teams as team}
<Card imgsrc={team.logo_url} imgid="update_team_logo_preview_{team.id}">
<form method="POST" enctype="multipart/form-data">
{#if data.admin}
<input name="id" type="hidden" value={team.id} />
{/if}
<div class="flex flex-col gap-2">
<Input id="team_name_{team.id}" name="name" value={team.name} disabled={!data.admin}
>Name</Input
>
<!-- Logo upload -->
<FileDropzone
name="logo"
id="team_logo_{team.id}"
onchange={get_image_preview_event_handler(`update_team_logo_preview_${team.id}`)}
disabled={!data.admin}
>
<svelte:fragment slot="message"
><b>Upload Logo</b> or Drag and Drop</svelte:fragment
>
</FileDropzone>
<!-- Buttons -->
<div class="flex justify-end gap-2">
<Button formaction="?/update_team" color="secondary" disabled={!data.admin} submit
>Save Changes</Button
>
<Button color="primary" submit disabled={!data.admin} formaction="?/delete_team"
>Delete</Button
>
</div>
</div>
</form>
</Card>
{/each}
<!-- Add a new team -->
{#if data.admin}
<Card imgsrc="" imgid="create_team_logo_preview" imghidden>
<form method="POST" enctype="multipart/form-data">
<div class="flex flex-col gap-2">
<h4 class="h4 select-none">Add a New Team</h4>
<!-- Team name input -->
<Input id="team_name_create" name="name" required>Name</Input>
<!-- Logo upload -->
<FileDropzone
name="logo"
id="team_logo_create"
onchange={get_image_preview_event_handler("create_team_logo_preview")}
disabled={!data.admin}
required
>
<svelte:fragment slot="message"
><b>Upload Logo</b> or Drag and Drop</svelte:fragment
>
</FileDropzone>
<!-- Buttons -->
<div class="flex justify-end gap-2">
<!-- By specifying the formaction on the button (instead of action on the form), -->
<!-- we can have multiple buttons with different actions in a single form. -->
<Button formaction="?/create_team" color="secondary" submit>Create</Button>
</div>
</div>
</form>
</Card>
{/if}
</div>
{:else if current_tab === 1}
<!-- Drivers Tab -->
<!-- Drivers Tab -->
<!-- Drivers Tab -->
<!-- TODO: Team select -->
<!-- TODO: Active switch -->
<div class="mt-2 grid grid-cols-1 gap-2 md:grid-cols-2 lg:grid-cols-4 xl:grid-cols-6">
<!-- List all drivers inside the database -->
{#each data.drivers as driver}
<Card imgsrc={driver.headshot_url} imgid="update_driver_headshot_preview_{driver.id}">
<form method="POST" enctype="multipart/form-data">
{#if data.admin}
<input name="id" type="hidden" value={driver.id} />
{/if}
<div class="flex flex-col gap-2">
<!-- Driver data input -->
<Input
id="driver_first_name_{driver.id}"
name="firstname"
value={driver.firstname}
labelwidth="120px"
disabled={!data.admin}>First Name</Input
>
<Input
id="driver_last_name_{driver.id}"
name="lastname"
value={driver.lastname}
labelwidth="120px"
disabled={!data.admin}>Last Name</Input
>
<Input
id="driver_code_{driver.id}"
name="code"
value={driver.code}
labelwidth="120px"
disabled={!data.admin}>Driver Code</Input
>
<Button>
<img src={get_by_id<Team>(data.teams, driver.team)?.logo_url} alt="" />
</Button>
<!-- Headshot upload -->
<FileDropzone
name="headshot"
id="driver_headshot_{driver.id}"
onchange={get_image_preview_event_handler(
`update_driver_headshot_preview_${driver.id}`,
)}
disabled={!data.admin}
>
<svelte:fragment slot="message"
><b>Upload Headshot</b> or Drag and Drop</svelte:fragment
>
</FileDropzone>
<!-- Buttons -->
<div class="flex justify-end gap-2">
<Button
formaction="?/update_driver"
color="secondary"
disabled={!data.admin}
submit>Save Changes</Button
>
<Button formaction="?/delete_driver" color="primary" disabled={!data.admin} submit
>Delete</Button
>
</div>
</div>
</form>
</Card>
{/each}
<!-- Add a new driver -->
{#if data.admin}
<Card imgsrc="" imgid="create_driver_headshot_preview" imghidden>
<form method="POST" enctype="multipart/form-data">
<div class="flex flex-col gap-2">
<h4 class="h4 select-none">Add a New Driver</h4>
<!-- Driver data input -->
<Input
id="driver_first_name_create"
name="firstname"
placeholder="First Name"
labelwidth="120px"
disabled={!data.admin}
required>First Name</Input
>
<Input
id="driver_last_name_create"
name="lastname"
placeholder="Last Name"
labelwidth="120px"
disabled={!data.admin}
required>Last Name</Input
>
<Input
id="driver_code_create"
name="code"
placeholder="Driver Code"
labelwidth="120px"
disabled={!data.admin}
required>Driver Code</Input
>
<!-- Headshot upload -->
<FileDropzone
name="headshot"
id="driver_headshot_create"
onchange={get_image_preview_event_handler("create_driver_headshot_preview")}
disabled={!data.admin}
required
>
<svelte:fragment slot="message"
><b>Upload Headshot</b> or Drag and Drop</svelte:fragment
>
</FileDropzone>
<!-- Buttons -->
<div class="flex justify-end gap-2">
<Button formaction="?/create_driver" color="secondary" submit>Create</Button>
</div>
</div>
</form>
</Card>
{/if}
</div>
{:else if current_tab === 2}
<!-- Races Tab -->
<!-- Races Tab -->
<!-- Races Tab -->
<span>Races</span>
{:else if current_tab === 3}
<!-- Substitutions Tab -->
<!-- Substitutions Tab -->
<!-- Substitutions Tab -->
<span>Substitutions</span>
{/if}
</svelte:fragment>
</TabGroup>

View File

@ -1,32 +0,0 @@
<script lang="ts">
import { navigating, page } from "$app/stores";
import { Tab, TabGroup } from "@skeletonlabs/skeleton";
import type { Snippet } from "svelte";
let { children }: { children: Snippet } = $props();
let current_tab: number = $state(0);
const tabs: { [tab: string]: number } = {
teams: 0,
drivers: 1,
races: 2,
};
navigating.subscribe((nav) => {
if (!nav?.to?.url) return;
current_tab = tabs[nav.to.url.toString().split("/").at(-1) || "teams"];
});
</script>
<h1>Season Data</h1>
<TabGroup justify="justify-center">
<a href="teams"> <Tab bind:group={current_tab} name="teams" value={0}>Teams</Tab></a>
<a href="drivers"><Tab bind:group={current_tab} name="drivers" value={1}>Drivers</Tab></a>
<a href="races"><Tab bind:group={current_tab} name="races" value={2}>Races</Tab></a>
</TabGroup>
<div>
{@render children()}
</div>

View File

@ -1,62 +0,0 @@
import type { Actions, PageServerLoad } from "./$types";
import { form_data_clean, form_data_ensure_keys, form_data_get_and_remove_id } from "$lib/form";
// These "actions" run serverside only, as they're located inside +page.server.ts
export const actions = {
// We destructure the RequestEvent with ({cookies, request}).
// Alternatively use (event) and event.cookies or event.request to access.
create: async ({ cookies, request, locals }) => {
if (!locals.admin) return { success: false };
const data = form_data_clean(await request.formData());
form_data_ensure_keys(data, ["name", "logo"]);
const record = await locals.pb.collection("teams").create(data);
return { success: true };
},
update: async ({ cookies, request, locals }) => {
if (!locals.admin) return { success: false };
const data = form_data_clean(await request.formData());
const id = form_data_get_and_remove_id(data);
// Destructure the FormData object
const record = await locals.pb.collection("teams").update(id, data);
return { success: true };
},
delete: async ({ cookies, request, locals }) => {
if (!locals.admin) return { success: false };
const data: FormData = form_data_clean(await request.formData());
const id = form_data_get_and_remove_id(data);
await locals.pb.collection("teams").delete(id);
return { success: true };
},
} satisfies Actions;
// This "load" function runs serverside only, as it's located inside +page.server.ts
export const load: PageServerLoad = async ({ fetch, locals }) => {
const fetch_teams = async () => {
const teams = await locals.pb.collection("teams").getFullList({
sort: "+name",
fetch: fetch,
});
// Fill in the file URLs
teams.map((team) => {
team.logo_url = locals.pb.files.getURL(team, team.logo);
});
return teams;
};
return {
teams: await fetch_teams(),
};
};

View File

@ -1,100 +0,0 @@
<script lang="ts">
import type { PageData } from "./$types";
import { Input, Button, Card } from "$lib/components";
import { get_image_preview_event_handler } from "$lib/image";
import { FileDropzone } from "@skeletonlabs/skeleton";
let { data }: { data: PageData } = $props();
</script>
<svelte:head>
<title>F11 - Teams</title>
</svelte:head>
<div class="mt-2 grid grid-cols-1 gap-2 md:grid-cols-2 lg:grid-cols-4 xl:grid-cols-6">
<!-- List all teams inside the database -->
{#each data.teams as team}
<Card>
<!-- Logo display -->
<img
id="update_team_logo_preview_{team.id}"
src={team.logo_url}
alt="Logo of {team.name} F1 team."
draggable="false"
class="select-none rounded-container-token"
/>
<form method="POST" enctype="multipart/form-data">
<input name="id" type="hidden" value={team.id} />
<div class="*:mt-2">
<Input id="team_name_{team.id}" name="name" value={team.name} disabled={!data.admin}
>Name</Input
>
<!-- Logo upload -->
<FileDropzone
name="logo"
id="team_logo_{team.id}"
onchange={get_image_preview_event_handler(`update_team_logo_preview_${team.id}`)}
disabled={!data.admin}
>
<svelte:fragment slot="message"><b>Upload Logo</b> or Drag and Drop</svelte:fragment>
</FileDropzone>
<!-- Buttons -->
<div class="flex justify-end gap-2">
<Button formaction="?/update" color="secondary" disabled={!data.admin} submit
>Save Changes</Button
>
<Button formaction="?/delete" color="primary" disabled={!data.admin} submit
>Delete</Button
>
</div>
</div>
</form>
</Card>
{/each}
<!-- Add a new team -->
{#if data.admin}
<Card>
<!-- Logo preview -->
<img
id="create_team_logo_preview"
src=""
alt="Logo preview"
class="select-none"
draggable="false"
hidden
/>
<form method="POST" enctype="multipart/form-data">
<div class="*:mt-2">
<h4 class="h4 select-none">Add a New Team</h4>
<!-- Team name input -->
<Input id="team_name_create" name="name" required>Name</Input>
<!-- Logo upload -->
<FileDropzone
name="logo"
id="team_logo_create"
onchange={get_image_preview_event_handler("create_team_logo_preview")}
disabled={!data.admin}
required
>
<svelte:fragment slot="message"><b>Upload Logo</b> or Drag and Drop</svelte:fragment>
</FileDropzone>
<!-- Buttons -->
<div class="flex justify-end gap-2">
<!-- By specifying the formaction on the button (instead of action on the form), -->
<!-- we can have multiple buttons with different actions in a single form. -->
<Button formaction="?/create" color="secondary" submit>Create</Button>
</div>
</div>
</form>
</Card>
{/if}
</div>

View File

@ -1,13 +1,9 @@
import {
form_data_clean,
form_data_ensure_keys,
form_data_get_and_remove_id,
} from "$lib/form";
import { form_data_clean, form_data_ensure_keys, form_data_get_and_remove_id } from "$lib/form";
import { error, redirect } from "@sveltejs/kit";
import type { Actions } from "./$types";
export const actions = {
create: async ({ cookies, request, locals }) => {
create_profile: async ({ request, locals }) => {
const data = form_data_clean(await request.formData());
form_data_ensure_keys(data, ["username", "password"]);
@ -22,16 +18,13 @@ export const actions = {
// Directly login after registering
await locals.pb
.collection("users")
.authWithPassword(
data.get("username")?.toString(),
data.get("password")?.toString(),
);
.authWithPassword(data.get("username")?.toString(), data.get("password")?.toString());
redirect(303, "/");
},
// TODO: PocketBase API rule: Only the active user should be able to modify itself
update: async ({ cookies, request, locals }) => {
update_profile: async ({ request, locals }) => {
const data = form_data_clean(await request.formData());
const id = form_data_get_and_remove_id(data);
@ -40,7 +33,7 @@ export const actions = {
redirect(303, "/");
},
login: async ({ cookies, request, locals }) => {
login: async ({ request, locals }) => {
if (locals.user) {
console.log("Already logged in!");
return;
@ -52,10 +45,7 @@ export const actions = {
try {
await locals.pb
.collection("users")
.authWithPassword(
data.get("username")?.toString(),
data.get("password")?.toString(),
);
.authWithPassword(data.get("username")?.toString(), data.get("password")?.toString());
} catch (err) {
console.log(`Failed to login: ${err}`);
error(400, "Failed to login!");
@ -65,7 +55,7 @@ export const actions = {
redirect(303, "/");
},
logout: async ({ cookies, request, locals }) => {
logout: async ({ locals }) => {
locals.pb.authStore.clear();
locals.user = undefined;