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

21
src/app.d.ts vendored
View File

@ -1,13 +1,20 @@
import type { PocketBase, RecordModel } from "pocketbase";
// See https://svelte.dev/docs/kit/types#app.d.ts
// for information about these interfaces
declare global {
namespace App {
// interface Error {}
// interface Locals {}
// interface PageData {}
// interface PageState {}
// interface Platform {}
namespace App {
interface Locals {
pb: PocketBase;
user: RecordModel | undefined;
admin: boolean;
}
// interface Error {}
// interface PageData {}
// interface PageState {}
// interface Platform {}
}
}
export { };
export {};

View File

@ -10,22 +10,22 @@ export const handle: Handle = async ({ event, resolve }) => {
event.locals.pb = new PocketBase("http://192.168.86.50:8090");
// Load the most recent authentication data from a cookie (is updated below)
event.locals.pb.authStore.loadFromCookie(
event.request.headers.get("cookie") || "",
);
event.locals.pb.authStore.loadFromCookie(event.request.headers.get("cookie") || "");
if (event.locals.pb.authStore.isValid) {
// If the authentication data is valid, we make a "user" object easily available.
event.locals.user = structuredClone(event.locals.pb.authStore.model);
// Fill in the avatar URL
event.locals.user.avatar_url = event.locals.pb.files.getURL(
event.locals.pb.authStore.model,
event.locals.pb.authStore.model.avatar,
);
if (event.locals.user) {
// Fill in the avatar URL
event.locals.user.avatar_url = event.locals.pb.files.getURL(
event.locals.pb.authStore.model,
event.locals.pb.authStore.model.avatar,
);
// Set admin status for easier access
event.locals.admin = event.locals.user.admin;
// Set admin status for easier access
event.locals.admin = event.locals.user.admin;
}
} else {
event.locals.user = undefined;
}
@ -34,10 +34,7 @@ export const handle: Handle = async ({ event, resolve }) => {
const response = await resolve(event);
// Store the current authentication data to a cookie, so it can be loaded above.
response.headers.set(
"set-cookie",
event.locals.pb.authStore.exportToCookie({ secure: false }),
);
response.headers.set("set-cookie", event.locals.pb.authStore.exportToCookie({ secure: false }));
return response;
};

View File

@ -1,5 +1,8 @@
<script lang="ts">
import { page } from "$app/stores";
import type { Snippet } from "svelte";
import type { HTMLButtonAttributes } from "svelte/elements";
import { popup, type PopupSettings } from "@skeletonlabs/skeleton";
const is_at_path = (path: string): boolean => {
const pathname: string = $page.url.pathname;
@ -7,40 +10,66 @@
return pathname === path;
};
interface ButtonProps extends HTMLButtonAttributes {
children: Snippet;
/** The main color variant, e.g. "primary" or "secondary". */
color?: string | undefined;
/** Set the button type to "submit" (otherwise "button"). Only if "href" is undefined. */
submit?: boolean;
/** Make the button act as a link. */
href?: string | undefined;
/** Add the "w-full" class to the button. */
fullwidth?: boolean;
/** Enable the button's ":hover" state manually. */
activate?: boolean;
/** Enable the button's ":hover" state if the current URL matches the "href". Only if "href" is defined. */
activate_href?: boolean;
/** The PopupSettings to trigger on click. Only if "href" is undefined. */
trigger_popup?: PopupSettings;
}
let {
children,
color = undefined,
submit = false,
href = undefined,
fullwidth = false,
activate = false,
activate_href = false,
activate_button = false,
trigger_popup = { event: "click", target: "invalid" },
...restProps
} = $props();
}: ButtonProps = $props();
</script>
{#if href}
<a
{href}
class="select-none {color ? `btn px-2 variant-filled-${color}` : ''} {fullwidth
? 'w-full'
: 'w-auto'}
{activate_href && is_at_path(href) ? 'btn-hover' : ''}"
draggable="false"
{...restProps}
>
{@render children()}
</a>
<!-- HACK: Make the button act as a link using a form -->
<form action={href} class="contents">
<button
type="submit"
class="btn m-0 select-none px-2 py-2 {color ? `variant-filled-${color}` : ''} {fullwidth
? 'w-full'
: 'w-auto'} {activate ? 'btn-hover' : ''} {activate_href && is_at_path(href)
? 'btn-hover'
: ''}"
draggable="false"
{...restProps}>{@render children()}</button
>
</form>
{:else}
<button
type={submit ? "submit" : "button"}
class="select-none {color ? `btn px-2 variant-filled-${color}` : ''} {fullwidth
class="btn select-none px-2 py-2 {color ? `variant-filled-${color}` : ''} {fullwidth
? 'w-full'
: 'w-auto'}
{activate_button ? 'btn-hover' : ''}"
: 'w-auto'} {activate ? 'btn-hover' : ''}"
draggable="false"
{...restProps}
use:popup={trigger_popup}
{...restProps}>{@render children()}</button
>
{@render children()}
</button>
{/if}

View File

@ -1,7 +1,45 @@
<script lang="ts">
let { children, fullwidth = false, ...restProps } = $props();
import type { Snippet } from "svelte";
interface CardProps {
children: Snippet;
/** The URL for a possible header image. Leave undefined for no header image. Set to empty string for an image not yet loaded. */
imgsrc?: string | undefined;
/** The id of the header image element for JS access. */
imgid?: string | undefined;
/** Hide the header image element. It can be shown by removing the "hidden" property using JS and the imgid. */
imghidden?: boolean;
/** Enable to give the card the "w-full" class. */
fullwidth?: boolean;
}
let {
children,
imgsrc = undefined,
imgid = undefined,
imghidden = false,
fullwidth = false,
...restProps
}: CardProps = $props();
</script>
<div class="card bg-white p-2 shadow {fullwidth ? 'w-full' : 'w-auto'}" {...restProps}>
{@render children()}
<div class="card overflow-hidden bg-white shadow {fullwidth ? 'w-full' : 'w-auto'}">
<!-- Allow empty strings for images that only appear after user action -->
{#if imgsrc !== undefined}
<img
id={imgid}
src={imgsrc}
alt="Card header"
draggable="false"
class="select-none shadow"
hidden={imghidden}
/>
{/if}
<div class="p-2" {...restProps}>
{@render children()}
</div>
</div>

View File

@ -1,9 +1,25 @@
<script lang="ts">
let { children, type = "text", ...restProps } = $props();
import type { Snippet } from "svelte";
import type { HTMLInputAttributes } from "svelte/elements";
interface InputProps extends HTMLInputAttributes {
children: Snippet;
/** Manually set the label width, to align multiple inputs vertically. Supply value in CSS units. */
labelwidth?: string;
/** The type of the input element, e.g. "text". */
type?: string;
}
let { children, labelwidth = "auto", type = "text", ...restProps }: InputProps = $props();
</script>
<div class="input-group input-group-divider grid-cols-[auto_1fr_auto]">
<div class="input-group-shim select-none text-nowrap text-neutral-900">
<div
class="input-group-shim select-none text-nowrap text-neutral-900"
style="width: {labelwidth};"
>
{@render children()}
</div>
<input {type} {...restProps} />

7
src/lib/database.ts Normal file
View File

@ -0,0 +1,7 @@
/**
* Retrieve an arbitrary object with a matching ID from an Array.
* Supposed to use on collections returned by the PocketBase API.
*/
export const get_by_id = <T extends object>(objects: Array<T>, id: string): T | undefined => {
return objects.find((o: T) => ("id" in o ? o.id === id : false));
};

View File

@ -36,13 +36,13 @@ export const form_data_clean = (data: FormData): FormData => {
/**
* Throws SvelteKit error(400) if form_data does not contain key.
*/
export const form_data_ensure_key = (data: FormData, key: string) => {
export const form_data_ensure_key = (data: FormData, key: string): void => {
if (!data.get(key)) error(400, `Key "${key}" missing from form_data!`);
};
/**
* Throws SvelteKit error(400) if form_data does not contain all keys.
*/
export const form_data_ensure_keys = (data: FormData, keys: string[]) => {
export const form_data_ensure_keys = (data: FormData, keys: string[]): void => {
keys.map((key) => form_data_ensure_key(data, key));
};

View File

@ -1,8 +1,9 @@
/**
* Use this on <Avatar> components.
* Obtain an onchange event handler that updates an <Avatar> component
* with a new image uploaded via a file input element.
*/
export const get_avatar_preview_event_handler = (id: string) => {
const handler = (event: Event) => {
export const get_avatar_preview_event_handler = (id: string): ((event: Event) => void) => {
const handler = (event: Event): void => {
const target: HTMLInputElement = event.target as HTMLInputElement;
const files: FileList | null = target.files;
@ -11,6 +12,7 @@ export const get_avatar_preview_event_handler = (id: string) => {
const preview: HTMLImageElement = document.querySelector(
`#${id} > img:first-of-type`,
) as HTMLImageElement;
if (preview) {
preview.src = src;
preview.hidden = false;
@ -22,16 +24,18 @@ export const get_avatar_preview_event_handler = (id: string) => {
};
/**
* Use this on raw <img> elements.
* Obtain an onchange event handler that updates an <img> element
* with a new image uploaded via a file input element.
*/
export const get_image_preview_event_handler = (id: string) => {
const handler = (event: Event) => {
export const get_image_preview_event_handler = (id: string): ((event: Event) => void) => {
const handler = (event: Event): void => {
const target: HTMLInputElement = event.target as HTMLInputElement;
const files: FileList | null = target.files;
if (files && files.length > 0) {
const src: string = URL.createObjectURL(files[0]);
const preview: HTMLImageElement = document.getElementById(id) as HTMLImageElement;
if (preview) {
preview.src = src;
preview.hidden = false;

21
src/lib/schema.ts Normal file
View File

@ -0,0 +1,21 @@
export interface Team {
id: string;
name: string;
logo: string;
logo_url?: string;
}
export interface Driver {
id: string;
firstname: string;
lastname: string;
code: string;
headshot: string;
headshot_url?: string;
team: string;
active: boolean;
}
export interface Race {}
export interface Substitution {}

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;