DISABLE SSR AND TRANSITION TO SPA
All checks were successful
Build Formula11 Docker Image / pocketbase-docker (push) Successful in 43s

This commit is contained in:
2025-02-08 16:37:58 +01:00
parent 91fc3ae7a2
commit f868d779e7
26 changed files with 1141 additions and 1317 deletions

7
src/app.d.ts vendored
View File

@ -5,12 +5,7 @@ import type { PocketBase, RecordModel } from "pocketbase";
// for information about these interfaces
declare global {
namespace App {
interface Locals {
pb: PocketBase;
user: User | undefined;
admin: boolean;
}
// interface Locals {}
// interface Error {}
// interface PageData {}
// interface PageState {}

View File

@ -1,76 +0,0 @@
import type { Graphic, User } from "$lib/schema";
import type { Handle } from "@sveltejs/kit";
import { env } from "$env/dynamic/private";
import PocketBase from "pocketbase";
// This function will run serverside on each request.
// The event.locals will be passed onto serverside load functions and handlers.
// We create a new PocketBase client for each request, so it always carries the
// most recent authentication data.
// The authenticated PocketBase client will be available in all *.server.ts files.
export const handle: Handle = async ({ event, resolve }) => {
const requestStartTime: number = Date.now();
// If env variables are defined (e.g. in the prod environment), use those.
// Otherwise use the default local development IP:Port.
// Because we imported "$env/dynamic/private",
// the variables will only be available to the server (e.g. .server.ts files).
let pb_url: string = "http://192.168.86.50:8090";
if (env.PB_PROTOCOL && env.PB_HOST && env.PB_PORT) {
pb_url = `${env.PB_PROTOCOL}://${env.PB_HOST}:${env.PB_PORT}`;
}
if (env.PB_PROTOCOL && env.PB_URL) {
pb_url = `${env.PB_PROTOCOL}://${env.PB_URL}`;
}
event.locals.pb = new PocketBase(pb_url);
// Load the most recent authentication data from a cookie (is updated below)
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) as User;
if (event.locals.user) {
if (event.locals.pb.authStore.model.avatar) {
// 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,
);
} else {
// Fill in the driver_headshot_template URL if no avatar chosen
const driver_headshot_template: Graphic = await event.locals.pb
.collection("graphics")
.getFirstListItem('name="driver_headshot_template"');
event.locals.user.avatar_url = event.locals.pb.files.getURL(
driver_headshot_template,
driver_headshot_template.file,
);
}
// Set admin status for easier access
event.locals.admin = event.locals.user.admin;
}
} else {
event.locals.user = undefined;
}
// Resolve the request. This is what happens by default.
const response = await resolve(event);
console.log(
"=====\n",
`Request Date: ${new Date(requestStartTime).toISOString()}\n`,
`Method: ${event.request.method}\n`,
`Path: ${event.url.pathname}\n`,
`Duration: ${Date.now() - requestStartTime}ms\n`,
`Status: ${response.status}`,
);
// 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 }));
return response;
};

View File

@ -1,10 +0,0 @@
import type { Reroute } from "@sveltejs/kit";
const rerouted: Record<string, string> = {};
// NOTE: This does not change the browser's address bar (the route path)!
export const reroute: Reroute = ({ url }) => {
if (url.pathname in rerouted) {
return rerouted[url.pathname];
}
};

View File

@ -3,15 +3,19 @@
import {
FileDropzone,
getModalStore,
getToastStore,
SlideToggle,
type ModalStore,
type ToastStore,
} from "@skeletonlabs/skeleton";
import { Button, Input, Card, Dropdown } from "$lib/components";
import type { Driver, SkeletonData } from "$lib/schema";
import { DRIVER_HEADSHOT_HEIGHT, DRIVER_HEADSHOT_WIDTH } from "$lib/config";
import { team_dropdown_options } from "$lib/dropdown";
import { enhance } from "$app/forms";
import { get_driver_headshot_template } from "$lib/database";
import { get_error_toast } from "$lib/toast";
import { pb } from "$lib/pocketbase";
import { invalidateAll } from "$app/navigation";
interface DriverCardProps {
/** Data passed from the page context */
@ -31,14 +35,92 @@
driver = meta.driver;
}
const toastStore: ToastStore = getToastStore();
// Constants
const labelwidth: string = "120px";
// Reactive state
let required: boolean = $derived(!driver);
let disabled: boolean = $derived(!data.admin);
let firstname_input_value: string = $state(driver?.firstname ?? "");
let lastname_input_value: string = $state(driver?.lastname ?? "");
let code_input_value: string = $state(driver?.code ?? "");
let team_select_value: string = $state(driver?.team ?? "");
let headshot_file_value: FileList | undefined = $state();
let active_value: boolean = $state(driver?.active ?? true);
// Database actions
// TODO: Headshot compression
const update_driver = (create?: boolean): (() => Promise<void>) => {
const handler = async (): Promise<void> => {
if (!firstname_input_value || firstname_input_value === "") {
toastStore.trigger(get_error_toast("Please enter a first name!"));
return;
}
if (!lastname_input_value || lastname_input_value === "") {
toastStore.trigger(get_error_toast("Please enter a last name!"));
return;
}
if (!code_input_value || code_input_value === "") {
toastStore.trigger(get_error_toast("Please enter a driver code!"));
return;
}
if (!team_select_value || team_select_value === "") {
toastStore.trigger(get_error_toast("Please select a team!"));
return;
}
const driver_data = {
firstname: firstname_input_value,
lastname: lastname_input_value,
code: code_input_value,
team: team_select_value,
active: active_value,
headshot:
headshot_file_value && headshot_file_value.length === 1
? headshot_file_value[0]
: undefined,
};
try {
if (create) {
if (!headshot_file_value || headshot_file_value.length !== 1) {
toastStore.trigger(get_error_toast("Please upload a single driver headshot!"));
return;
}
await pb.collection("drivers").create(driver_data);
} else {
if (!driver?.id) {
toastStore.trigger(get_error_toast("Invalid driver id!"));
return;
}
await pb.collection("drivers").update(driver.id, driver_data);
}
invalidateAll();
modalStore.close();
} catch (error) {
toastStore.trigger(get_error_toast("" + error));
}
};
return handler;
};
const delete_driver = async (): Promise<void> => {
if (!driver?.id) {
toastStore.trigger(get_error_toast("Invalid driver id!"));
return;
}
try {
await pb.collection("drivers").delete(driver.id);
invalidateAll();
modalStore.close();
} catch (error) {
toastStore.trigger(get_error_toast("" + error));
}
};
</script>
{#await data.graphics then graphics}
@ -50,97 +132,84 @@
imgheight={DRIVER_HEADSHOT_HEIGHT}
imgonclick={(event: Event) => modalStore.close()}
>
<form
method="POST"
enctype="multipart/form-data"
use:enhance
onsubmit={() => modalStore.close()}
>
<!-- This is also disabled, because the ID should only be -->
<!-- "leaked" to users that are allowed to use the inputs -->
{#if driver && !disabled}
<input name="id" type="hidden" value={driver.id} />
{/if}
<div class="flex flex-col gap-2">
<!-- Driver name input -->
<Input
bind:value={firstname_input_value}
autocomplete="off"
{labelwidth}
{disabled}
{required}
>
First Name
</Input>
<Input
bind:value={lastname_input_value}
autocomplete="off"
{labelwidth}
{disabled}
{required}
>
Last Name
</Input>
<Input
bind:value={code_input_value}
autocomplete="off"
minlength={3}
maxlength={3}
{labelwidth}
{disabled}
{required}
>
Driver Code
</Input>
<div class="flex flex-col gap-2">
<!-- Driver name input -->
<Input name="firstname" value={driver?.firstname ?? ""} {labelwidth} {disabled} {required}>
First Name
</Input>
<Input
name="lastname"
value={driver?.lastname ?? ""}
autocomplete="off"
<!-- Driver team input -->
{#await data.teams then teams}
<Dropdown
bind:value={team_select_value}
options={team_dropdown_options(teams)}
{labelwidth}
{disabled}
{required}
>
Last Name
</Input>
<Input
name="code"
value={driver?.code ?? ""}
autocomplete="off"
minlength={3}
maxlength={3}
{labelwidth}
{disabled}
{required}
>
Driver Code
</Input>
Team
</Dropdown>
{/await}
<!-- Driver team input -->
{#await data.teams then teams}
<Dropdown
name="team"
bind:value={team_select_value}
options={team_dropdown_options(teams)}
{labelwidth}
<!-- Headshot upload -->
<FileDropzone
name="headshot"
bind:files={headshot_file_value}
onchange={get_image_preview_event_handler("headshot_preview")}
{disabled}
{required}
>
<svelte:fragment slot="message">
<span class="font-bold">Upload Headshot</span>
</svelte:fragment>
</FileDropzone>
<!-- Save/Delete buttons -->
<div class="flex items-center justify-end gap-2">
<div class="mr-auto">
<SlideToggle
name="active"
background="bg-primary-500"
active="bg-tertiary-500"
bind:checked={active_value}
{disabled}
{required}
>
Team
</Dropdown>
{/await}
<!-- Headshot upload -->
<FileDropzone
name="headshot"
onchange={get_image_preview_event_handler("headshot_preview")}
{disabled}
{required}
>
<svelte:fragment slot="message">
<span class="font-bold">Upload Headshot</span>
</svelte:fragment>
</FileDropzone>
<!-- Save/Delete buttons -->
<div class="flex items-center justify-end gap-2">
<div class="mr-auto">
<SlideToggle
name="active"
background="bg-primary-500"
active="bg-tertiary-500"
bind:checked={active_value}
{disabled}
/>
</div>
{#if driver}
<Button formaction="?/update_driver" color="secondary" {disabled} submit width="w-1/2">
Save
</Button>
<Button formaction="?/delete_driver" color="primary" {disabled} submit width="w-1/2">
Delete
</Button>
{:else}
<Button formaction="?/create_driver" color="tertiary" {disabled} submit width="w-full">
Create Driver
</Button>
{/if}
/>
</div>
{#if driver}
<Button onclick={update_driver()} color="secondary" {disabled} width="w-1/2">Save</Button>
<Button onclick={delete_driver} color="primary" {disabled} width="w-1/2">Delete</Button>
{:else}
<Button onclick={update_driver(true)} color="tertiary" {disabled} width="w-full">
Create Driver
</Button>
{/if}
</div>
</form>
</div>
</Card>
{/await}

View File

@ -1,12 +1,20 @@
<script lang="ts">
import { get_image_preview_event_handler } from "$lib/image";
import { FileDropzone, getModalStore, type ModalStore } from "@skeletonlabs/skeleton";
import {
FileDropzone,
getModalStore,
getToastStore,
type ModalStore,
type ToastStore,
} from "@skeletonlabs/skeleton";
import { Button, Card, Input } from "$lib/components";
import type { Race, SkeletonData } from "$lib/schema";
import { RACE_PICTOGRAM_HEIGHT, RACE_PICTOGRAM_WIDTH } from "$lib/config";
import { enhance } from "$app/forms";
import { get_race_pictogram_template } from "$lib/database";
import { format_date } from "$lib/date";
import { get_error_toast } from "$lib/toast";
import { pb } from "$lib/pocketbase";
import { invalidateAll } from "$app/navigation";
interface RaceCardProps {
/** Data passed from the page context */
@ -26,6 +34,8 @@
race = meta.race;
}
const toastStore: ToastStore = getToastStore();
// Constants
const labelwidth = "80px";
const dateformat: string = "yyyy-MM-dd'T'HH:mm";
@ -45,15 +55,97 @@
let sprintdate_value: string = $state("");
let qualidate_value: string = $state("");
let racedate_value: string = $state("");
let pictogram_value: FileList | undefined = $state();
if (race) {
if (race.sprintqualidate && race.sprintdate) {
sprintqualidate_value = format_date(race.sprintqualidate, dateformat);
sprintdate_value = format_date(race.sprintdate, dateformat);
qualidate_value = format_date(race.qualidate, dateformat);
racedate_value = format_date(race.racedate, dateformat);
}
qualidate_value = format_date(race.qualidate, dateformat);
racedate_value = format_date(race.racedate, dateformat);
}
// Database actions
// TODO: Pictogram compression
const update_race = (create?: boolean): (() => Promise<void>) => {
const handler = async (): Promise<void> => {
if (!name_value || name_value === "") {
toastStore.trigger(get_error_toast("Please enter a name!"));
return;
}
if (!step_value || step_value === "") {
toastStore.trigger(get_error_toast("Please enter a step!"));
return;
}
if (!pxx_value || pxx_value === "") {
toastStore.trigger(get_error_toast("Please enter a place to guess (PXX)!"));
return;
}
if (!qualidate_value || qualidate_value === "") {
toastStore.trigger(get_error_toast("Please enter a qualifying date!"));
return;
}
if (!racedate_value || racedate_value === "") {
toastStore.trigger(get_error_toast("Please enter a race date!"));
return;
}
const race_data = {
name: name_value,
step: step_value,
pxx: pxx_value,
sprintqualidate:
sprintqualidate_value && sprintqualidate_value !== ""
? new Date(sprintqualidate_value).toISOString()
: undefined,
sprintdate:
sprintdate_value && sprintdate_value != ""
? new Date(sprintdate_value).toISOString()
: undefined,
qualidate: new Date(qualidate_value).toISOString(),
racedate: new Date(racedate_value).toISOString(),
pictogram: pictogram_value && pictogram_value.length === 1 ? pictogram_value[0] : undefined,
};
try {
if (create) {
if (!pictogram_value || pictogram_value.length !== 1) {
toastStore.trigger(get_error_toast("Please upload a single pictogram!"));
return;
}
await pb.collection("races").create(race_data);
} else {
if (!race?.id) {
toastStore.trigger(get_error_toast("Invalid race id!"));
return;
}
await pb.collection("races").update(race.id, race_data);
}
invalidateAll();
modalStore.close();
} catch (error) {
toastStore.trigger(get_error_toast("" + error));
}
};
return handler;
};
const delete_race = async (): Promise<void> => {
if (!race?.id) {
toastStore.trigger(get_error_toast("Invalid race id!"));
return;
}
try {
await pb.collection("raceresults").delete(race.id);
invalidateAll();
modalStore.close();
} catch (error) {
toastStore.trigger(get_error_toast("" + error));
}
};
</script>
{#await data.graphics then graphics}
@ -65,139 +157,112 @@
imgheight={RACE_PICTOGRAM_HEIGHT}
imgonclick={(event: Event) => modalStore.close()}
>
<form
method="POST"
enctype="multipart/form-data"
use:enhance
onsubmit={() => modalStore.close()}
>
<!-- This is also disabled, because the ID should only be -->
<!-- "leaked" to users that are allowed to use the inputs -->
{#if race && !disabled}
<input name="id" type="hidden" value={race.id} />
{/if}
<div class="flex flex-col gap-2">
<!-- Driver name input -->
<Input bind:value={name_value} autocomplete="off" {labelwidth} {disabled} {required}>
Name
</Input>
<Input
bind:value={step_value}
autocomplete="off"
type="number"
min={1}
max={24}
{labelwidth}
{disabled}
{required}
>
Step
</Input>
<Input
bind:value={pxx_value}
autocomplete="off"
type="number"
min={1}
max={20}
{labelwidth}
{disabled}
{required}
>
PXX
</Input>
<div class="flex flex-col gap-2">
<!-- Driver name input -->
<Input
name="name"
bind:value={name_value}
autocomplete="off"
{labelwidth}
{disabled}
{required}
>
Name
</Input>
<Input
name="step"
bind:value={step_value}
autocomplete="off"
type="number"
min={1}
max={24}
{labelwidth}
{disabled}
{required}
>
Step
</Input>
<Input
name="pxx"
bind:value={pxx_value}
autocomplete="off"
type="number"
min={1}
max={20}
{labelwidth}
{disabled}
{required}
>
PXX
</Input>
<!-- NOTE: Input datetime-local accepts YYYY-mm-ddTHH:MM format -->
<Input
id="sqdate"
bind:value={sprintqualidate_value}
autocomplete="off"
type="datetime-local"
{labelwidth}
{disabled}
>
SQuali
</Input>
<Input
id="sdate"
bind:value={sprintdate_value}
autocomplete="off"
type="datetime-local"
{labelwidth}
{disabled}
>
SRace
</Input>
<Input
bind:value={qualidate_value}
autocomplete="off"
type="datetime-local"
{labelwidth}
{disabled}
{required}
>
Quali
</Input>
<Input
bind:value={racedate_value}
autocomplete="off"
type="datetime-local"
{labelwidth}
{disabled}
{required}
>
Race
</Input>
<!-- NOTE: Input datetime-local accepts YYYY-mm-ddTHH:MM format -->
<Input
id="sqdate"
name="sprintqualidate"
bind:value={sprintqualidate_value}
autocomplete="off"
type="datetime-local"
{labelwidth}
{disabled}
>
SQuali
</Input>
<Input
id="sdate"
name="sprintdate"
bind:value={sprintdate_value}
autocomplete="off"
type="datetime-local"
{labelwidth}
{disabled}
>
SRace
</Input>
<Input
name="qualidate"
bind:value={qualidate_value}
autocomplete="off"
type="datetime-local"
{labelwidth}
{disabled}
{required}
>
Quali
</Input>
<Input
name="racedate"
bind:value={racedate_value}
autocomplete="off"
type="datetime-local"
{labelwidth}
{disabled}
{required}
>
Race
</Input>
<!-- Headshot upload -->
<FileDropzone
name="pictogram"
onchange={get_image_preview_event_handler("pictogram_preview")}
bind:files={pictogram_value}
{disabled}
{required}
>
<svelte:fragment slot="message">
<span class="font-bold">Upload Pictogram</span>
</svelte:fragment>
</FileDropzone>
<!-- Headshot upload -->
<FileDropzone
name="pictogram"
onchange={get_image_preview_event_handler("pictogram_preview")}
<!-- Save/Delete buttons -->
<div class="flex justify-end gap-2">
<Button
onclick={clear_sprint}
color="secondary"
{disabled}
{required}
width={race ? "w-1/3" : "w-1/2"}
>
<svelte:fragment slot="message">
<span class="font-bold">Upload Pictogram</span>
</svelte:fragment>
</FileDropzone>
<!-- Save/Delete buttons -->
<div class="flex justify-end gap-2">
<Button
onclick={clear_sprint}
color="secondary"
{disabled}
width={race ? "w-1/3" : "w-1/2"}
>
Remove Sprint
Remove Sprint
</Button>
{#if race}
<Button onclick={update_race()} color="secondary" {disabled} width="w-1/3">
Save Changes
</Button>
{#if race}
<Button formaction="?/update_race" color="secondary" {disabled} submit width="w-1/3">
Save Changes
</Button>
<Button formaction="?/delete_race" color="primary" {disabled} submit width="w-1/3">
Delete
</Button>
{:else}
<Button formaction="?/create_race" color="tertiary" {disabled} submit width="w-1/2">
Create Race
</Button>
{/if}
</div>
<Button onclick={delete_race} color="primary" {disabled} width="w-1/3">Delete</Button>
{:else}
<Button onclick={update_race(true)} color="tertiary" {disabled} width="w-1/2">
Create Race
</Button>
{/if}
</div>
</form>
</div>
</Card>
{/await}

View File

@ -10,10 +10,17 @@
Substitution,
} from "$lib/schema";
import { get_by_value, get_driver_headshot_template } from "$lib/database";
import { getModalStore, type ModalStore } from "@skeletonlabs/skeleton";
import {
getModalStore,
getToastStore,
type ModalStore,
type ToastStore,
} from "@skeletonlabs/skeleton";
import { DRIVER_HEADSHOT_HEIGHT, DRIVER_HEADSHOT_WIDTH } from "$lib/config";
import { driver_dropdown_options } from "$lib/dropdown";
import { enhance } from "$app/forms";
import { get_error_toast } from "$lib/toast";
import { invalidateAll } from "$app/navigation";
import { pb } from "$lib/pocketbase";
interface RacePickCardProps {
/** Data passed from the page context */
@ -38,6 +45,8 @@
racepick = meta.racepick;
}
const toastStore: ToastStore = getToastStore();
// Await promises
let drivers: Driver[] | undefined = $state(undefined);
data.drivers.then((d: Driver[]) => (drivers = d));
@ -96,6 +105,68 @@
Math.floor(Math.random() * active_drivers_and_substitutes.length)
].id;
};
// Database actions
const update_racepick = (create?: boolean): (() => Promise<void>) => {
const handler = async (): Promise<void> => {
if (!data.user?.id || data.user.id === "") {
toastStore.trigger(get_error_toast("Invalid user id!"));
return;
}
if (!data.currentrace?.id || data.currentrace.id === "") {
toastStore.trigger(get_error_toast("Invalid race id!"));
return;
}
if (!pxx_select_value || pxx_select_value === "") {
toastStore.trigger(get_error_toast("Please enter a PXX guess!"));
return;
}
if (!dnf_select_value || dnf_select_value === "") {
toastStore.trigger(get_error_toast("Please enter a DNF guess!"));
return;
}
const racepick_data = {
user: data.user.id,
race: data.currentrace.id,
pxx: pxx_select_value,
dnf: dnf_select_value,
};
try {
if (create) {
await pb.collection("racepicks").create(racepick_data);
} else {
if (!racepick?.id) {
toastStore.trigger(get_error_toast("Invalid racepick id!"));
return;
}
await pb.collection("racepicks").update(racepick.id, racepick_data);
}
invalidateAll();
modalStore.close();
} catch (error) {
toastStore.trigger(get_error_toast("" + error));
}
};
return handler;
};
const delete_racepick = async (): Promise<void> => {
if (!racepick?.id) {
toastStore.trigger(get_error_toast("Invalid racepick id!"));
return;
}
try {
await pb.collection("racepicks").delete(racepick.id);
invalidateAll();
modalStore.close();
} catch (error) {
toastStore.trigger(get_error_toast("" + error));
}
};
</script>
{#await Promise.all([data.graphics, data.drivers]) then [graphics, drivers]}
@ -108,78 +179,46 @@
imgheight={DRIVER_HEADSHOT_HEIGHT}
imgonclick={(event: Event) => modalStore.close()}
>
<form
method="POST"
enctype="multipart/form-data"
use:enhance
onsubmit={() => modalStore.close()}
>
<!-- This is also disabled, because the ID should only be -->
<!-- "leaked" to users that are allowed to use the inputs -->
{#if racepick && !disabled}
<input name="id" type="hidden" value={racepick.id} />
{/if}
<div class="flex flex-col gap-2">
<!-- PXX select -->
<Dropdown
bind:value={pxx_select_value}
options={driver_dropdown_options(active_drivers_and_substitutes)}
{labelwidth}
{disabled}
{required}
>
P{data.currentrace?.pxx ?? "XX"}
</Dropdown>
<input name="user" type="hidden" value={data.user?.id} />
<input name="race" type="hidden" value={data.currentrace?.id} />
<!-- DNF select -->
<Dropdown
bind:value={dnf_select_value}
options={driver_dropdown_options(active_drivers_and_substitutes)}
{labelwidth}
{disabled}
{required}
>
DNF
</Dropdown>
<div class="flex flex-col gap-2">
<!-- PXX select -->
<Dropdown
name="pxx"
bind:value={pxx_select_value}
options={driver_dropdown_options(active_drivers_and_substitutes)}
{labelwidth}
{disabled}
{required}
>
P{data.currentrace?.pxx ?? "XX"}
</Dropdown>
<Button color="tertiary" {disabled} width="w-full" onclick={random_select_handler}>
Select Random
</Button>
<!-- DNF select -->
<Dropdown
name="dnf"
bind:value={dnf_select_value}
options={driver_dropdown_options(active_drivers_and_substitutes)}
{labelwidth}
{disabled}
{required}
>
DNF
</Dropdown>
<Button color="tertiary" {disabled} width="w-full" onclick={random_select_handler}>
Select Random
</Button>
<!-- Save/Delete buttons -->
<div class="flex justify-end gap-2">
{#if racepick}
<Button
formaction="?/update_racepick"
color="secondary"
{disabled}
submit
width="w-1/2"
>
Save Changes
</Button>
<Button formaction="?/delete_racepick" color="primary" {disabled} submit width="w-1/2">
Delete
</Button>
{:else}
<Button
formaction="?/create_racepick"
color="tertiary"
{disabled}
submit
width="w-full"
>
Make Pick
</Button>
{/if}
</div>
<!-- Save/Delete buttons -->
<div class="flex justify-end gap-2">
{#if racepick}
<Button onclick={update_racepick()} color="secondary" {disabled} width="w-1/2">
Save Changes
</Button>
<Button onclick={delete_racepick} color="primary" {disabled} width="w-1/2">Delete</Button>
{:else}
<Button onclick={update_racepick(true)} color="tertiary" {disabled} width="w-full">
Make Pick
</Button>
{/if}
</div>
</form>
</div>
</Card>
{/await}

View File

@ -2,15 +2,19 @@
import {
Autocomplete,
getModalStore,
getToastStore,
InputChip,
type AutocompleteOption,
type ModalStore,
type ToastStore,
} from "@skeletonlabs/skeleton";
import { Button, Card, Dropdown } from "$lib/components";
import type { Driver, Race, RaceResult, SkeletonData } from "$lib/schema";
import { get_by_value } from "$lib/database";
import { race_dropdown_options } from "$lib/dropdown";
import { enhance } from "$app/forms";
import { pb } from "$lib/pocketbase";
import { get_error_toast } from "$lib/toast";
import { invalidateAll } from "$app/navigation";
interface RaceResultCardProps {
/** Data passed from the page context */
@ -30,6 +34,8 @@
result = meta.result;
}
const toastStore: ToastStore = getToastStore();
let races: Race[] | undefined = $state(undefined);
data.races.then((r: Race[]) => (races = r));
@ -166,108 +172,132 @@
const on_dnfs_chip_remove = (event: CustomEvent): void => {
dnfs_ids.splice(event.detail.chipIndex, 1);
};
// Database actions
const update_raceresult = (create?: boolean): (() => Promise<void>) => {
const handler = async (): Promise<void> => {
if (!race_select_value || race_select_value === "") {
toastStore.trigger(get_error_toast("Please select a race!"));
return;
}
if (!pxxs_ids || pxxs_ids.length !== 7) {
toastStore.trigger(get_error_toast("Please select all 7 driver placements!"));
return;
}
const raceresult_data = {
race: race_select_value,
pxxs: pxxs_ids,
dnfs: dnfs_ids,
};
try {
if (create) {
await pb.collection("raceresults").create(raceresult_data);
} else {
if (!result?.id) {
toastStore.trigger(get_error_toast("Invalid result id!"));
return;
}
await pb.collection("raceresults").update(result.id, raceresult_data);
}
invalidateAll();
modalStore.close();
} catch (error) {
toastStore.trigger(get_error_toast("" + error));
}
};
return handler;
};
const delete_raceresult = async (): Promise<void> => {
if (!result?.id) {
toastStore.trigger(get_error_toast("Invalid result id!"));
return;
}
try {
await pb.collection("raceresults").delete(result.id);
invalidateAll();
modalStore.close();
} catch (error) {
toastStore.trigger(get_error_toast("" + error));
}
};
</script>
<Card width="w-full sm:w-[512px]">
<form method="POST" enctype="multipart/form-data" use:enhance onsubmit={() => modalStore.close()}>
<!-- This is also disabled, because the ID should only be -->
<!-- "leaked" to users that are allowed to use the inputs -->
{#if result && !disabled}
<input name="id" type="hidden" value={result.id} />
{/if}
<!-- Race select input -->
{#await data.races then races}
<Dropdown
name="race"
bind:value={race_select_value}
options={race_dropdown_options(races)}
onchange={on_race_select}
{labelwidth}
{disabled}
{required}
>
Race
</Dropdown>
{/await}
<!-- Send the input chips ids -->
{#each pxxs_ids as pxxs_id}
<input name="pxxs" type="hidden" {disabled} value={pxxs_id} />
{/each}
{#each dnfs_ids as dnfs_id}
<input name="dnfs" type="hidden" {disabled} value={dnfs_id} />
{/each}
<!-- Race select input -->
{#await data.races then races}
<Dropdown
name="race"
bind:value={race_select_value}
options={race_dropdown_options(races)}
onchange={on_race_select}
{labelwidth}
{disabled}
{required}
>
Race
</Dropdown>
{/await}
<div class="mt-2 flex flex-col gap-2">
<!-- PXXs autocomplete chips -->
<InputChip
<div class="mt-2 flex flex-col gap-2">
<!-- PXXs autocomplete chips -->
<InputChip
bind:input={pxxs_input}
bind:value={pxxs_chips}
whitelist={pxxs_whitelist}
allowUpperCase
placeholder={pxxs_placeholder}
name="pxxs_codes"
{disabled}
{required}
on:remove={on_pxxs_chip_remove}
/>
<div class="card max-h-48 w-full overflow-y-auto p-2" tabindex="-1">
<Autocomplete
bind:input={pxxs_input}
bind:value={pxxs_chips}
whitelist={pxxs_whitelist}
allowUpperCase
placeholder={pxxs_placeholder}
name="pxxs_codes"
{disabled}
{required}
on:remove={on_pxxs_chip_remove}
options={pxxs_options}
denylist={pxxs_chips}
on:selection={on_pxxs_chip_select}
/>
<div class="card max-h-48 w-full overflow-y-auto p-2" tabindex="-1">
<Autocomplete
bind:input={pxxs_input}
options={pxxs_options}
denylist={pxxs_chips}
on:selection={on_pxxs_chip_select}
/>
</div>
<!-- DNFs autocomplete chips -->
<InputChip
bind:input={dnfs_input}
bind:value={dnfs_chips}
whitelist={pxxs_whitelist}
allowUpperCase
placeholder="Select DNFs..."
name="dnfs_codes"
{disabled}
on:remove={on_dnfs_chip_remove}
/>
<div class="card max-h-48 w-full overflow-y-auto p-2" tabindex="-1">
<Autocomplete
bind:input={dnfs_input}
options={dnfs_options}
denylist={dnfs_chips}
on:selection={on_dnfs_chip_select}
/>
</div>
<!-- Save/Delete buttons -->
<div class="flex items-center justify-end gap-2">
{#if result}
<Button
formaction="?/update_raceresult"
color="secondary"
{disabled}
submit
width="w-1/2"
>
Save
</Button>
<Button formaction="?/delete_raceresult" color="primary" {disabled} submit width="w-1/2">
Delete
</Button>
{:else}
<Button
formaction="?/create_raceresult"
color="tertiary"
{disabled}
submit
width="w-full"
>
Create Result
</Button>
{/if}
</div>
</div>
</form>
<!-- DNFs autocomplete chips -->
<InputChip
bind:input={dnfs_input}
bind:value={dnfs_chips}
whitelist={pxxs_whitelist}
allowUpperCase
placeholder="Select DNFs..."
name="dnfs_codes"
{disabled}
on:remove={on_dnfs_chip_remove}
/>
<div class="card max-h-48 w-full overflow-y-auto p-2" tabindex="-1">
<Autocomplete
bind:input={dnfs_input}
options={dnfs_options}
denylist={dnfs_chips}
on:selection={on_dnfs_chip_select}
/>
</div>
<!-- Save/Delete buttons -->
<div class="flex items-center justify-end gap-2">
{#if result}
<Button onclick={update_raceresult()} color="secondary" {disabled} width="w-1/2"
>Save</Button
>
<Button onclick={delete_raceresult} color="primary" {disabled} width="w-1/2">Delete</Button>
{:else}
<Button onclick={update_raceresult(true)} color="tertiary" {disabled} width="w-full">
Create Result
</Button>
{/if}
</div>
</div>
</Card>

View File

@ -2,10 +2,17 @@
import { Card, Button, Dropdown } from "$lib/components";
import type { Driver, SkeletonData, Substitution } from "$lib/schema";
import { get_by_value, get_driver_headshot_template } from "$lib/database";
import { getModalStore, type ModalStore } from "@skeletonlabs/skeleton";
import {
getModalStore,
getToastStore,
type ModalStore,
type ToastStore,
} from "@skeletonlabs/skeleton";
import { DRIVER_HEADSHOT_HEIGHT, DRIVER_HEADSHOT_WIDTH } from "$lib/config";
import { driver_dropdown_options, race_dropdown_options } from "$lib/dropdown";
import { enhance } from "$app/forms";
import { get_error_toast } from "$lib/toast";
import { pb } from "$lib/pocketbase";
import { invalidateAll } from "$app/navigation";
interface SubstitutionCardProps {
/** Data passed from the page context */
@ -25,6 +32,8 @@
substitution = meta.substitution;
}
const toastStore: ToastStore = getToastStore();
// Await promises
let drivers: Driver[] | undefined = $state(undefined);
data.drivers.then((d: Driver[]) => (drivers = d));
@ -48,6 +57,62 @@
const img: HTMLImageElement = document.getElementById("headshot_preview") as HTMLImageElement;
if (img) img.src = src;
});
// Database actions
const update_substitution = (create?: boolean): (() => Promise<void>) => {
const handler = async (): Promise<void> => {
if (!substitute_value || substitute_value === "") {
toastStore.trigger(get_error_toast("Please select a substitute driver!"));
return;
}
if (!driver_value || driver_value === "") {
toastStore.trigger(get_error_toast("Please select a replaced driver!"));
return;
}
if (!race_value || race_value === "") {
toastStore.trigger(get_error_toast("Please select a race!"));
return;
}
const substitution_data = {
substitute: substitute_value,
for: driver_value,
race: race_value,
};
try {
if (create) {
await pb.collection("substitutions").create(substitution_data);
} else {
if (!substitution?.id) {
toastStore.trigger(get_error_toast("Invalid substitution id!"));
return;
}
await pb.collection("substitutions").update(substitution.id, substitution_data);
}
invalidateAll();
modalStore.close();
} catch (error) {
toastStore.trigger(get_error_toast("" + error));
}
};
return handler;
};
const delete_substitution = async (): Promise<void> => {
if (!substitution?.id) {
toastStore.trigger(get_error_toast("Invalid substitution id!"));
return;
}
try {
await pb.collection("substitutions").delete(substitution.id);
invalidateAll();
modalStore.close();
} catch (error) {
toastStore.trigger(get_error_toast("" + error));
}
};
</script>
{#await Promise.all([data.graphics, data.drivers]) then [graphics, drivers]}
@ -60,91 +125,57 @@
imgheight={DRIVER_HEADSHOT_HEIGHT}
imgonclick={(event: Event) => modalStore.close()}
>
<form
method="POST"
enctype="multipart/form-data"
use:enhance
onsubmit={() => modalStore.close()}
>
<!-- This is also disabled, because the ID should only be -->
<!-- "leaked" to users that are allowed to use the inputs -->
{#if substitution && !disabled}
<input name="id" type="hidden" value={substitution.id} />
{/if}
<div class="flex flex-col gap-2">
<!-- Substitute select -->
<Dropdown
bind:value={substitute_value}
options={driver_dropdown_options(inactive_drivers)}
{labelwidth}
{disabled}
{required}
>
Substitute
</Dropdown>
<div class="flex flex-col gap-2">
<!-- Substitute select -->
<!-- Driver select -->
<Dropdown
bind:value={driver_value}
options={driver_dropdown_options(active_drivers)}
{labelwidth}
{disabled}
{required}
>
For
</Dropdown>
<!-- Race select -->
{#await data.races then races}
<Dropdown
name="substitute"
bind:value={substitute_value}
options={driver_dropdown_options(inactive_drivers)}
bind:value={race_value}
options={race_dropdown_options(races)}
{labelwidth}
{disabled}
{required}
>
Substitute
Race
</Dropdown>
{/await}
<!-- Driver select -->
<Dropdown
name="for"
bind:value={driver_value}
options={driver_dropdown_options(active_drivers)}
{labelwidth}
{disabled}
{required}
>
For
</Dropdown>
<!-- Race select -->
{#await data.races then races}
<Dropdown
name="race"
bind:value={race_value}
options={race_dropdown_options(races)}
{labelwidth}
{disabled}
{required}
>
Race
</Dropdown>
{/await}
<!-- Save/Delete buttons -->
<div class="flex justify-end gap-2">
{#if substitution}
<Button
formaction="?/update_substitution"
color="secondary"
{disabled}
submit
width="w-1/2"
>
Save Changes
</Button>
<Button
formaction="?/delete_substitution"
color="primary"
{disabled}
submit
width="w-1/2"
>
Delete
</Button>
{:else}
<Button
formaction="?/create_substitution"
color="tertiary"
{disabled}
submit
width="w-full"
>
Create Substitution
</Button>
{/if}
</div>
<!-- Save/Delete buttons -->
<div class="flex justify-end gap-2">
{#if substitution}
<Button onclick={update_substitution()} color="secondary" {disabled} width="w-1/2">
Save Changes
</Button>
<Button onclick={delete_substitution} color="primary" {disabled} width="w-1/2">
Delete
</Button>
{:else}
<Button onclick={update_substitution(true)} color="tertiary" {disabled} width="w-full">
Create Substitution
</Button>
{/if}
</div>
</form>
</div>
</Card>
{/await}

View File

@ -1,11 +1,19 @@
<script lang="ts">
import { get_image_preview_event_handler } from "$lib/image";
import { FileDropzone, getModalStore, type ModalStore } from "@skeletonlabs/skeleton";
import {
FileDropzone,
getModalStore,
getToastStore,
type ModalStore,
type ToastStore,
} from "@skeletonlabs/skeleton";
import { Card, Button, Input, LazyImage } from "$lib/components";
import type { SkeletonData, Team } from "$lib/schema";
import { TEAM_BANNER_HEIGHT, TEAM_BANNER_WIDTH } from "$lib/config";
import { enhance } from "$app/forms";
import { get_team_banner_template, get_team_logo_template } from "$lib/database";
import { get_error_toast } from "$lib/toast";
import { pb } from "$lib/pocketbase";
import { invalidateAll } from "$app/navigation";
interface TeamCardProps {
/** Data from the page context */
@ -25,6 +33,8 @@
team = meta.team;
}
const toastStore: ToastStore = getToastStore();
// Constants
const labelwidth: string = "110px";
@ -33,6 +43,71 @@
let disabled: boolean = $derived(!data.admin);
let name_value: string = $state(team?.name ?? "");
let color_value: string = $state(team?.color ?? "");
let banner_value: FileList | undefined = $state();
let logo_value: FileList | undefined = $state();
// Database actions
// TODO: Banner + logo compression
const update_team = (create?: boolean): (() => Promise<void>) => {
const handler = async (): Promise<void> => {
if (!name_value || name_value === "") {
toastStore.trigger(get_error_toast("Please enter a name!"));
return;
}
if (!color_value || color_value === "") {
toastStore.trigger(get_error_toast("Please enter a color!"));
return;
}
const team_data = {
name: name_value,
color: color_value,
banner: banner_value && banner_value.length === 1 ? banner_value[0] : undefined,
logo: logo_value && logo_value.length === 1 ? logo_value[0] : undefined,
};
try {
if (create) {
if (!banner_value || banner_value.length !== 1) {
toastStore.trigger(get_error_toast("Please upload a single team banner!"));
return;
}
if (!logo_value || logo_value.length !== 1) {
toastStore.trigger(get_error_toast("Please upload a single team logo!"));
return;
}
await pb.collection("teams").create(team_data);
} else {
if (!team?.id) {
toastStore.trigger(get_error_toast("Invalid team id!"));
return;
}
await pb.collection("teams").update(team.id, team_data);
}
invalidateAll();
modalStore.close();
} catch (error) {
toastStore.trigger(get_error_toast("" + error));
}
};
return handler;
};
const delete_team = async (): Promise<void> => {
if (!team?.id) {
toastStore.trigger(get_error_toast("Invalid team id!"));
return;
}
try {
await pb.collection("teams").delete(team.id);
invalidateAll();
modalStore.close();
} catch (error) {
toastStore.trigger(get_error_toast("" + error));
}
};
</script>
{#await data.graphics then graphics}
@ -44,97 +119,74 @@
imgheight={TEAM_BANNER_HEIGHT}
imgonclick={(event: Event) => modalStore.close()}
>
<form
method="POST"
enctype="multipart/form-data"
use:enhance
onsubmit={() => modalStore.close()}
>
<!-- This is also disabled, because the ID should only be -->
<!-- "leaked" to users that are allowed to use the inputs -->
{#if team && !disabled}
<input name="id" type="hidden" value={team.id} />
{/if}
<div class="flex flex-col gap-2">
<!-- Team name input -->
<Input bind:value={name_value} autocomplete="off" {labelwidth} {disabled} {required}>
Name
</Input>
<div class="flex flex-col gap-2">
<!-- Team name input -->
<Input
name="name"
bind:value={name_value}
autocomplete="off"
{labelwidth}
{disabled}
{required}
>
Name
</Input>
<!-- Team color input -->
<Input
bind:value={color_value}
autocomplete="off"
placeholder="Enter as '#XXXXXX'"
minlength={7}
maxlength={7}
{labelwidth}
{disabled}
{required}
>
Color
<span class="badge ml-2 border" style="color: {color_value}; background: {color_value}">
C
</span>
</Input>
<!-- Team color input -->
<Input
name="color"
bind:value={color_value}
autocomplete="off"
placeholder="Enter as '#XXXXXX'"
minlength={7}
maxlength={7}
{labelwidth}
{disabled}
{required}
>
Color
<span class="badge ml-2 border" style="color: {color_value}; background: {color_value}">
C
</span>
</Input>
<!-- Banner upload -->
<FileDropzone
name="banner"
bind:files={banner_value}
onchange={get_image_preview_event_handler("banner_preview")}
{disabled}
{required}
>
<svelte:fragment slot="message">
<span class="font-bold">Upload Banner</span>
</svelte:fragment>
</FileDropzone>
<!-- Banner upload -->
<FileDropzone
name="banner"
onchange={get_image_preview_event_handler("banner_preview")}
{disabled}
{required}
>
<svelte:fragment slot="message">
<span class="font-bold">Upload Banner</span>
</svelte:fragment>
</FileDropzone>
<!-- Logo upload -->
<FileDropzone
name="logo"
bind:files={logo_value}
onchange={get_image_preview_event_handler("logo_preview")}
{disabled}
{required}
>
<svelte:fragment slot="message">
<div class="inline-flex flex-nowrap items-center gap-2">
<span class="font-bold">Upload Logo</span>
<LazyImage
src={team?.logo_url ?? get_team_logo_template(graphics)}
id="logo_preview"
imgwidth={32}
imgheight={32}
/>
</div>
</svelte:fragment>
</FileDropzone>
<!-- Logo upload -->
<FileDropzone
name="logo"
onchange={get_image_preview_event_handler("logo_preview")}
{disabled}
{required}
>
<svelte:fragment slot="message">
<div class="inline-flex flex-nowrap items-center gap-2">
<span class="font-bold">Upload Logo</span>
<LazyImage
src={team?.logo_url ?? get_team_logo_template(graphics)}
id="logo_preview"
imgwidth={32}
imgheight={32}
/>
</div>
</svelte:fragment>
</FileDropzone>
<!-- Save/Delete buttons -->
<div class="flex justify-end gap-2">
{#if team}
<Button formaction="?/update_team" color="secondary" {disabled} submit width="w-1/2">
Save
</Button>
<Button formaction="?/delete_team" color="primary" {disabled} submit width="w-1/2">
Delete
</Button>
{:else}
<Button formaction="?/create_team" color="tertiary" {disabled} submit width="w-full">
Create Team
</Button>
{/if}
</div>
<!-- Save/Delete buttons -->
<div class="flex justify-end gap-2">
{#if team}
<Button onclick={update_team()} color="secondary" {disabled} width="w-1/2">Save</Button>
<Button onclick={delete_team} color="primary" {disabled} width="w-1/2">Delete</Button>
{:else}
<Button onclick={update_team(true)} color="tertiary" {disabled} width="w-full">
Create Team
</Button>
{/if}
</div>
</form>
</div>
</Card>
{/await}

View File

@ -1,87 +0,0 @@
import { error } from "@sveltejs/kit";
/**
* Obtain the value of the key "id" and remove it from the FormData.
* Throws SvelteKit error(400) if "id" is not found.
*/
export const form_data_get_and_remove_id = (data: FormData): string => {
const id: string | undefined = data.get("id")?.toString();
if (!id) error(400, "Missing ID");
data.delete("id");
return id;
};
/**
* Remove empty fields (even whitespace) and empty files from FormData objects.
* Keys listed in [except] won't be removed although they are empty.
*/
export const form_data_clean = (data: FormData, except: string[] = []): FormData => {
let delete_keys: string[] = [];
for (const [key, value] of data.entries()) {
if (
!except.includes(key) &&
(value === null ||
value === undefined ||
(typeof value === "string" && value.trim() === "") ||
(typeof value === "object" && "size" in value && value.size === 0))
) {
delete_keys.push(key);
}
}
delete_keys.forEach((key) => {
data.delete(key);
});
return data;
};
/**
* Remove the specified [keys] from the [data] object.
*/
export const form_data_remove = (data: FormData, keys: string[]): void => {
let delete_keys: string[] = [];
for (const [key, value] of data.entries()) {
if (keys.includes(key)) {
delete_keys.push(key);
}
}
delete_keys.forEach((key) => {
data.delete(key);
});
};
/**
* Throws SvelteKit error(400) if form_data does not contain key.
*/
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[]): void => {
keys.map((key) => form_data_ensure_key(data, key));
};
/**
* Modify a single [FormData] element to satisfy PocketBase's date format.
* Date format: 2024-12-31 12:00:00.000Z
*/
export const form_data_fix_date = (data: FormData, key: string): boolean => {
const value: string | undefined = data.get(key)?.toString();
if (!value) return false;
const date: string = new Date(value).toISOString();
data.set(key, date);
return true;
};
export const form_data_fix_dates = (data: FormData, keys: string[]): boolean[] => {
return keys.map((key) => form_data_fix_date(data, key));
};

39
src/lib/pocketbase.ts Normal file
View File

@ -0,0 +1,39 @@
import Pocketbase, { type AuthRecord } from "pocketbase";
import type { Graphic, User } from "$lib/schema";
// TODO: import { PUBLIC_POCKETBASE_URL } from '$env/static/public';
export let pb = new Pocketbase("http://192.168.86.50:8090");
export let pbUser: User | undefined = undefined;
const update_user = async (record: AuthRecord): Promise<void> => {
if (!record) {
pbUser = undefined;
return;
}
let avatar_url: string;
if (record.avatar) {
avatar_url = pb.files.getURL(record, record.avatar);
} else {
const driver_headshot_template: Graphic = await pb
.collection("graphics")
.getFirstListItem('name="driver_headshot_template"');
avatar_url = pb.files.getURL(driver_headshot_template, driver_headshot_template.file);
}
pbUser = {
id: record.id,
username: record.username,
firstname: record.firstname,
avatar: record.avatar,
avatar_url: avatar_url,
admin: record.admin,
} as User;
};
// Update the pbUser object when authStore changes (e.g. after logging in)
pb.authStore.onChange(() => {
update_user(pb.authStore.record);
// console.log("Updating pbUser...")
// console.dir(pbUser, { depth: null });
}, true);

10
src/lib/toast.ts Normal file
View File

@ -0,0 +1,10 @@
import type { ToastSettings } from "@skeletonlabs/skeleton";
export const get_error_toast = (message: string): ToastSettings => {
return {
message,
hideDismiss: true,
timeout: 2000,
background: "variant-filled-primary",
};
};

View File

@ -1,10 +1,8 @@
<script lang="ts">
import "../app.css";
import type { Snippet } from "svelte";
import type { LayoutData } from "./$types";
import { page } from "$app/stores";
import {
Button,
MenuDrawerIcon,
@ -29,6 +27,7 @@
Drawer,
getDrawerStore,
Modal,
Toast,
getModalStore,
type DrawerSettings,
Avatar,
@ -36,9 +35,13 @@
type DrawerStore,
type ModalStore,
type ModalComponent,
type ToastStore,
getToastStore,
} from "@skeletonlabs/skeleton";
import { computePosition, autoUpdate, offset, shift, flip, arrow } from "@floating-ui/dom";
import { enhance } from "$app/forms";
import { invalidateAll } from "$app/navigation";
import { get_error_toast } from "$lib/toast";
import { pb } from "$lib/pocketbase";
let { data, children }: { data: LayoutData; children: Snippet } = $props();
@ -57,6 +60,9 @@
substitutionCard: { ref: SubstitutionCard },
};
// Toast config
const toastStore: ToastStore = getToastStore();
// Drawer config
const drawerStore: DrawerStore = getDrawerStore();
let drawerOpen: boolean = false;
@ -125,12 +131,93 @@
// Popups config
storePopup.set({ computePosition, autoUpdate, offset, shift, flip, arrow });
// Reactive state
let username_value: string = $state("");
let firstname_value: string = $state("");
let password_value: string = $state("");
let avatar_value: FileList | undefined = $state();
// Database actions
// TODO: Avatar compression
const login = async (): Promise<void> => {
try {
await pb.collection("users").authWithPassword(username_value, password_value);
} catch (error) {
toastStore.trigger(get_error_toast("" + error));
}
await invalidateAll();
drawerStore.close();
password_value = "";
firstname_value = data.user?.firstname ?? "";
};
const logout = async (): Promise<void> => {
pb.authStore.clear();
await invalidateAll();
drawerStore.close();
username_value = "";
firstname_value = "";
password_value = "";
};
const update_profile = (create?: boolean): (() => Promise<void>) => {
const handler = async (): Promise<void> => {
if (!username_value || username_value === "") {
toastStore.trigger(get_error_toast("Please enter a username!"));
return;
}
if (!firstname_value || firstname_value === "") {
toastStore.trigger(get_error_toast("Please enter your first name!"));
return;
}
if (!password_value || password_value === "") {
toastStore.trigger(get_error_toast("Please enter a password!"));
return;
}
try {
if (create) {
await pb.collection("users").create({
username: username_value,
firstname: firstname_value,
password: password_value,
passwordConfirm: password_value,
admin: false,
});
await login();
return;
} else {
if (!data.user?.id || data.user.id === "") {
toastStore.trigger(get_error_toast("Invalid user id!"));
return;
}
await pb.collection("users").update(data.user.id, {
username: username_value,
firstname: firstname_value,
avatar: avatar_value && avatar_value.length === 1 ? avatar_value[0] : undefined,
});
invalidateAll();
drawerStore.close();
}
} catch (error) {
toastStore.trigger(get_error_toast("" + error));
}
};
return handler;
};
</script>
<LoadingIndicator />
<Modal components={modalRegistry} regionBackdrop="!overflow-y-scroll" />
<Toast zIndex="z-[1000]" />
<Drawer zIndex="z-30">
<!-- Use p-3 because the drawer has a 5px overlap with the navbar -->
{#if $drawerStore.id === "menu_drawer"}
@ -181,39 +268,29 @@
<!-- Login Drawer -->
<div class="flex flex-col gap-2 p-2 pt-3">
<h4 class="h4 select-none">Enter Username and Password</h4>
<form method="POST" class="contents" use:enhance>
<!-- Supply the pathname so the form can redirect to the current page. -->
<input type="hidden" name="redirect_url" value={$page.url.pathname} />
<Input name="username" placeholder="Username" autocomplete="username" required>
<UserIcon />
</Input>
<Input name="firstname" placeholder="First Name (leave empty for login)" autocomplete="off">
<NameIcon />
</Input>
<Input name="password" type="password" placeholder="Password" autocomplete="off" required>
<PasswordIcon />
</Input>
<div class="flex justify-end gap-2">
<Button
formaction="/profile?/login"
onclick={close_drawer}
color="tertiary"
submit
shadow
>
Login
</Button>
<Button
formaction="/profile?/create_profile"
onclick={close_drawer}
color="tertiary"
submit
shadow
>
Register
</Button>
</div>
</form>
<Input bind:value={username_value} placeholder="Username" autocomplete="username" required>
<UserIcon />
</Input>
<Input
bind:value={firstname_value}
placeholder="First Name (leave empty for login)"
autocomplete="off"
>
<NameIcon />
</Input>
<Input
bind:value={password_value}
type="password"
placeholder="Password"
autocomplete="off"
required
>
<PasswordIcon />
</Input>
<div class="flex justify-end gap-2">
<Button onclick={login} color="tertiary" shadow>Login</Button>
<Button onclick={update_profile(true)} color="tertiary" shadow>Register</Button>
</div>
</div>
{:else if $drawerStore.id === "profile_drawer" && data.user}
<!-- Profile Drawer -->
@ -221,56 +298,30 @@
<!-- Profile Drawer -->
<div class="flex flex-col gap-2 p-2 pt-3">
<h4 class="h4 select-none">Edit Profile</h4>
<form method="POST" enctype="multipart/form-data" class="contents" use:enhance>
<!-- Supply the pathname so the form can redirect to the current page. -->
<input type="hidden" name="redirect_url" value={$page.url.pathname} />
<input type="hidden" name="id" value={data.user.id} />
<Input
name="username"
value={data.user.username}
maxlength={10}
placeholder="Username"
autocomplete="username"
>
<UserIcon />
</Input>
<Input
name="firstname"
value={data.user.firstname}
placeholder="First Name"
autocomplete="off"
>
<NameIcon />
</Input>
<FileDropzone
name="avatar"
onchange={get_avatar_preview_event_handler("user_avatar_preview")}
>
<svelte:fragment slot="message"
><span class="font-bold">Upload Avatar</span></svelte:fragment
>
</FileDropzone>
<div class="flex justify-end gap-2">
<Button
formaction="/profile?/update_profile"
onclick={close_drawer}
color="secondary"
submit
shadow
>
Save Changes
</Button>
<Button
formaction="/profile?/logout"
onclick={close_drawer}
color="primary"
submit
shadow
>
Logout
</Button>
</div>
</form>
<Input
bind:value={username_value}
maxlength={10}
placeholder="Username"
autocomplete="username"
>
<UserIcon />
</Input>
<Input bind:value={firstname_value} placeholder="First Name" autocomplete="off">
<NameIcon />
</Input>
<FileDropzone
name="avatar"
bind:files={avatar_value}
onchange={get_avatar_preview_event_handler("user_avatar_preview")}
>
<svelte:fragment slot="message">
<span class="font-bold">Upload Avatar</span>
</svelte:fragment>
</FileDropzone>
<div class="flex justify-end gap-2">
<Button onclick={update_profile()} color="secondary" shadow>Save Changes</Button>
<Button onclick={logout} color="primary" shadow>Logout</Button>
</div>
</div>
{/if}
</Drawer>

View File

@ -1,66 +1,69 @@
import { pb, pbUser } from "$lib/pocketbase";
// This makes the page client-side rendered
export const ssr = false;
import type { Driver, Graphic, Race, Substitution, Team } from "$lib/schema";
import type { LayoutServerLoad } from "./$types";
import type { LayoutLoad } 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 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 }) => {
export const load: LayoutLoad = () => {
const fetch_graphics = async (): Promise<Graphic[]> => {
const graphics: Graphic[] = await locals.pb
.collection("graphics")
.getFullList({ fetch: fetch });
const graphics: Graphic[] = await pb.collection("graphics").getFullList({ fetch: fetch });
graphics.map((graphic: Graphic) => {
graphic.file_url = locals.pb.files.getURL(graphic, graphic.file);
graphic.file_url = pb.files.getURL(graphic, graphic.file);
});
return graphics;
};
const fetch_teams = async (): Promise<Team[]> => {
const teams: Team[] = await locals.pb.collection("teams").getFullList({
const teams: Team[] = await pb.collection("teams").getFullList({
sort: "+name",
fetch: fetch,
});
teams.map((team: Team) => {
team.banner_url = locals.pb.files.getURL(team, team.banner);
team.logo_url = locals.pb.files.getURL(team, team.logo);
team.banner_url = pb.files.getURL(team, team.banner);
team.logo_url = pb.files.getURL(team, team.logo);
});
return teams;
};
const fetch_drivers = async (): Promise<Driver[]> => {
const drivers: Driver[] = await locals.pb.collection("drivers").getFullList({
const drivers: Driver[] = await pb.collection("drivers").getFullList({
sort: "+code",
fetch: fetch,
});
drivers.map((driver: Driver) => {
driver.headshot_url = locals.pb.files.getURL(driver, driver.headshot);
driver.headshot_url = pb.files.getURL(driver, driver.headshot);
});
return drivers;
};
const fetch_races = async (): Promise<Race[]> => {
const races: Race[] = await locals.pb.collection("races").getFullList({
const races: Race[] = await pb.collection("races").getFullList({
sort: "+step",
fetch: fetch,
});
races.map((race: Race) => {
race.pictogram_url = locals.pb.files.getURL(race, race.pictogram);
race.pictogram_url = pb.files.getURL(race, race.pictogram);
});
return races;
};
const fetch_substitutions = async (): Promise<Substitution[]> => {
const substitutions: Substitution[] = await locals.pb.collection("substitutions").getFullList({
const substitutions: Substitution[] = await pb.collection("substitutions").getFullList({
expand: "race",
fetch: fetch,
});
@ -75,8 +78,8 @@ export const load: LayoutServerLoad = ({ locals }) => {
return {
// User information
user: locals.user,
admin: locals.user?.admin ?? false,
user: pbUser,
admin: pbUser?.admin ?? false,
// Return static data asynchronously
graphics: fetch_graphics(),

View File

@ -1,55 +0,0 @@
import {
form_data_clean,
form_data_ensure_keys,
form_data_get_and_remove_id,
form_data_remove,
} from "$lib/form";
import type { Driver, Graphic, Race, RaceResult } from "$lib/schema";
import type { Actions, PageServerLoad } from "./$types";
export const actions = {
create_raceresult: async ({ request, locals }) => {
if (!locals.admin) return { unauthorized: true };
const data: FormData = form_data_clean(await request.formData());
form_data_ensure_keys(data, ["race", "pxxs"]);
form_data_remove(data, ["pxxs_codes", "dnfs_codes"]);
await locals.pb.collection("raceresults").create(data);
},
update_raceresult: async ({ request, locals }) => {
if (!locals.admin) return { unauthorized: true };
const data: FormData = form_data_clean(await request.formData());
form_data_remove(data, ["pxxs_codes", "dnfs_codes"]);
const id: string = form_data_get_and_remove_id(data);
console.dir(data, { depth: null });
await locals.pb.collection("raceresults").update(id, data);
},
delete_raceresult: async ({ request, locals }) => {
if (!locals.admin) return { unauthorized: true };
const data: FormData = form_data_clean(await request.formData());
form_data_remove(data, ["pxxs_codes", "dnfs_codes"]);
const id: string = form_data_get_and_remove_id(data);
await locals.pb.collection("raceresults").delete(id);
},
} as Actions;
export const load: PageServerLoad = async ({ fetch, locals }) => {
// TODO: Duplicated code from racepicks/+page.server.ts
const fetch_raceresults = async (): Promise<RaceResult[]> => {
const raceresults: RaceResult[] = await locals.pb.collection("raceresultsdesc").getFullList();
return raceresults;
};
return {
results: await fetch_raceresults(),
};
};

View File

@ -0,0 +1,18 @@
import { pb } from "$lib/pocketbase";
import type { RaceResult } from "$lib/schema";
import type { PageLoad } from "../../$types";
export const load: PageLoad = async ({ fetch }) => {
// TODO: Duplicated code from racepicks/+page.server.ts
const fetch_raceresults = async (): Promise<RaceResult[]> => {
const raceresults: RaceResult[] = await pb
.collection("raceresultsdesc")
.getFullList({ fetch: fetch });
return raceresults;
};
return {
results: await fetch_raceresults(),
};
};

View File

@ -1,59 +0,0 @@
import { DRIVER_HEADSHOT_HEIGHT, DRIVER_HEADSHOT_WIDTH } from "$lib/config";
import { form_data_clean, form_data_ensure_keys, form_data_get_and_remove_id } from "$lib/form";
import { image_to_avif } from "$lib/server/image";
import type { Actions } from "@sveltejs/kit";
export const actions = {
create_driver: async ({ request, locals }) => {
if (!locals.admin) return { unauthorized: true };
const data: FormData = form_data_clean(await request.formData());
form_data_ensure_keys(data, ["firstname", "lastname", "code", "team", "headshot"]);
// The toggle switch will report "on" or nothing
data.set("active", data.has("active") ? "true" : "false");
// Compress headshot
const headshot_avif: Blob = await image_to_avif(
await (data.get("headshot") as File).arrayBuffer(),
DRIVER_HEADSHOT_WIDTH,
DRIVER_HEADSHOT_HEIGHT,
);
data.set("headshot", headshot_avif);
await locals.pb.collection("drivers").create(data);
},
update_driver: 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);
// The toggle switch will report "on" or nothing
data.set("active", data.has("active") ? "true" : "false");
if (data.has("headshot")) {
// Compress headshot
const headshot_avif: Blob = await image_to_avif(
await (data.get("headshot") as File).arrayBuffer(),
DRIVER_HEADSHOT_WIDTH,
DRIVER_HEADSHOT_HEIGHT,
);
data.set("headshot", headshot_avif);
}
await locals.pb.collection("drivers").update(id, data);
},
delete_driver: 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("drivers").delete(id);
},
} satisfies Actions;

View File

@ -1,64 +0,0 @@
import { RACE_PICTOGRAM_HEIGHT, RACE_PICTOGRAM_WIDTH } from "$lib/config";
import {
form_data_clean,
form_data_ensure_keys,
form_data_fix_dates,
form_data_get_and_remove_id,
} from "$lib/form";
import { image_to_avif } from "$lib/server/image";
import type { Actions } from "@sveltejs/kit";
export const actions = {
create_race: async ({ request, locals }) => {
if (!locals.admin) return { unauthorized: true };
const data: FormData = form_data_clean(await request.formData());
form_data_ensure_keys(data, ["name", "step", "pictogram", "pxx", "qualidate", "racedate"]);
form_data_fix_dates(data, ["sprintqualidate", "sprintdate", "qualidate", "racedate"]);
// Compress pictogram
const pictogram_avif: Blob = await image_to_avif(
await (data.get("pictogram") as File).arrayBuffer(),
RACE_PICTOGRAM_WIDTH,
RACE_PICTOGRAM_HEIGHT,
);
data.set("pictogram", pictogram_avif);
await locals.pb.collection("races").create(data);
},
update_race: async ({ request, locals }) => {
if (!locals.admin) return { unauthorized: true };
// Do not remove empty sprint dates so they can be cleared by updating the record
const data: FormData = form_data_clean(await request.formData(), [
"sprintqualidate",
"sprintdate",
]);
form_data_fix_dates(data, ["sprintqualidate", "sprintdate", "qualidate", "racedate"]);
const id: string = form_data_get_and_remove_id(data);
if (data.has("pictogram")) {
// Compress pictogram
const pictogram_avif: Blob = await image_to_avif(
await (data.get("pictogram") as File).arrayBuffer(),
RACE_PICTOGRAM_WIDTH,
RACE_PICTOGRAM_HEIGHT,
);
data.set("pictogram", pictogram_avif);
}
await locals.pb.collection("races").update(id, data);
},
delete_race: 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("races").delete(id);
},
} satisfies Actions;

View File

@ -26,6 +26,7 @@
modalStore.trigger(modalSettings);
};
// TODO: Displayed dates differ from actual dates by 1 hour
const races_columns: TableColumn[] = $derived([
{
data_value_name: "name",

View File

@ -1,31 +0,0 @@
import { form_data_clean, form_data_ensure_keys, form_data_get_and_remove_id } from "$lib/form";
import type { Actions } from "@sveltejs/kit";
export const actions = {
create_substitution: async ({ request, locals }) => {
if (!locals.admin) return { unauthorized: true };
const data: FormData = form_data_clean(await request.formData());
form_data_ensure_keys(data, ["substitute", "for", "race"]);
await locals.pb.collection("substitutions").create(data);
},
update_substitution: 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("substitutions").update(id, data);
},
delete_substitution: 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("substitutions").delete(id);
},
} satisfies Actions;

View File

@ -1,74 +0,0 @@
import type { Actions } from "./$types";
import { form_data_clean, form_data_ensure_keys, form_data_get_and_remove_id } from "$lib/form";
import { image_to_avif } from "$lib/server/image";
import {
TEAM_BANNER_HEIGHT,
TEAM_BANNER_WIDTH,
TEAM_LOGO_HEIGHT,
TEAM_LOGO_WIDTH,
} from "$lib/config";
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", "banner", "logo", "color"]);
// Compress banner
const banner_avif: Blob = await image_to_avif(
await (data.get("banner") as File).arrayBuffer(),
TEAM_BANNER_WIDTH,
TEAM_BANNER_HEIGHT,
);
data.set("banner", banner_avif);
// Compress logo
const logo_avif: Blob = await image_to_avif(
await (data.get("logo") as File).arrayBuffer(),
TEAM_LOGO_WIDTH,
TEAM_LOGO_HEIGHT,
);
data.set("logo", logo_avif);
await locals.pb.collection("teams").create(data);
},
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);
if (data.has("banner")) {
// Compress banner
const banner_avif: Blob = await image_to_avif(
await (data.get("banner") as File).arrayBuffer(),
TEAM_BANNER_WIDTH,
TEAM_BANNER_HEIGHT,
);
data.set("banner", banner_avif);
}
if (data.has("logo")) {
// Compress logo
const logo_avif: Blob = await image_to_avif(
await (data.get("logo") as File).arrayBuffer(),
TEAM_LOGO_WIDTH,
TEAM_LOGO_HEIGHT,
);
data.set("logo", logo_avif);
}
await locals.pb.collection("teams").update(id, data);
},
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);
},
} satisfies Actions;

View File

@ -1,20 +0,0 @@
import type { Graphic, User } from "$lib/schema";
import type { PageServerLoad } from "./$types";
export const load: PageServerLoad = async ({ fetch, locals }) => {
const fetch_users = async (): Promise<User[]> => {
const users: User[] = await locals.pb
.collection("users")
.getFullList({ fetch: fetch, sort: "+username" });
users.map((user: User) => {
user.avatar_url = locals.pb.files.getURL(user, user.avatar);
});
return users;
};
return {
users: await fetch_users(),
};
};

View File

@ -0,0 +1,21 @@
import { pb } from "$lib/pocketbase";
import type { User } from "$lib/schema";
import type { PageLoad } from "../../$types";
export const load: PageLoad = async ({ fetch }) => {
const fetch_users = async (): Promise<User[]> => {
const users: User[] = await pb
.collection("users")
.getFullList({ fetch: fetch, sort: "+username" });
users.map((user: User) => {
user.avatar_url = pb.files.getURL(user, user.avatar);
});
return users;
};
return {
users: await fetch_users(),
};
};

View File

@ -1,89 +0,0 @@
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";
import { image_to_avif } from "$lib/server/image";
import { AVATAR_HEIGHT, AVATAR_WIDTH } from "$lib/config";
export const actions = {
create_profile: async ({ request, locals }): Promise<void> => {
const data: FormData = form_data_clean(await request.formData());
form_data_ensure_keys(data, ["username", "firstname", "password", "redirect_url"]);
// Confirm password lol
await locals.pb.collection("users").create({
username: data.get("username")?.toString(),
firstname: data.get("firstname")?.toString(),
password: data.get("password")?.toString(),
passwordConfirm: data.get("password")?.toString(),
admin: false,
});
// Directly login after registering
await locals.pb
.collection("users")
.authWithPassword(data.get("username")?.toString(), data.get("password")?.toString());
// The current page is sent with the form, redirect to that page
redirect(303, data.get("redirect_url")?.toString() ?? "/");
},
// TODO: PocketBase API rule: Only the active user should be able to modify itself
update_profile: async ({ request, locals }): Promise<void> => {
const data: FormData = form_data_clean(await request.formData());
form_data_ensure_keys(data, ["redirect_url"]);
const id: string = form_data_get_and_remove_id(data);
if (data.has("avatar")) {
// Compress image
const compressed: Blob = await image_to_avif(
await (data.get("avatar") as File).arrayBuffer(),
AVATAR_WIDTH,
AVATAR_HEIGHT,
);
// At most 20kB
if (compressed.size > 20000) {
error(400, "Avatar too large!");
}
data.set("avatar", compressed);
}
await locals.pb.collection("users").update(id, data);
redirect(303, data.get("redirect_url")?.toString() ?? "/");
},
login: async ({ request, locals }) => {
if (locals.user) {
error(400, "Already logged in!");
}
const data: FormData = form_data_clean(await request.formData());
form_data_ensure_keys(data, ["username", "password", "redirect_url"]);
try {
await locals.pb
.collection("users")
.authWithPassword(data.get("username")?.toString(), data.get("password")?.toString());
} catch (err) {
error(400, "Failed to login!");
}
redirect(303, data.get("redirect_url")?.toString() ?? "/");
},
logout: async ({ request, locals }) => {
if (!locals.user) {
error(400, "Not logged in!");
}
const data: FormData = form_data_clean(await request.formData());
form_data_ensure_keys(data, ["redirect_url"]);
locals.pb.authStore.clear();
locals.user = undefined;
redirect(303, data.get("redirect_url")?.toString() ?? "/");
},
} satisfies Actions;

View File

@ -1,92 +0,0 @@
import { form_data_clean, form_data_ensure_keys, form_data_get_and_remove_id } from "$lib/form";
import type { CurrentPickedUser, Race, RacePick, RaceResult } from "$lib/schema";
import type { Actions, PageServerLoad } from "./$types";
export const actions = {
create_racepick: async ({ request, locals }) => {
const data: FormData = form_data_clean(await request.formData());
form_data_ensure_keys(data, ["user", "race", "pxx", "dnf"]);
if (locals.user?.id !== data.get("user")) return { unauthorized: true };
await locals.pb.collection("racepicks").create(data);
},
update_racepick: async ({ request, locals }) => {
const data: FormData = form_data_clean(await request.formData());
form_data_ensure_keys(data, ["user", "race"]);
const id: string = form_data_get_and_remove_id(data);
if (locals.user?.id !== data.get("user")) return { unauthorized: true };
await locals.pb.collection("racepicks").update(id, data);
},
delete_racepick: async ({ request, locals }) => {
const data: FormData = form_data_clean(await request.formData());
form_data_ensure_keys(data, ["user", "race"]);
const id: string = form_data_get_and_remove_id(data);
if (locals.user?.id !== data.get("user")) return { unauthorized: true };
await locals.pb.collection("racepicks").delete(id);
},
} satisfies Actions;
export const load: PageServerLoad = async ({ fetch, locals }) => {
const fetch_currentrace = async (): Promise<Race | null> => {
const currentrace: Race[] = await locals.pb.collection("currentrace").getFullList();
// The currentrace collection either has a single or no entries
if (currentrace.length == 0) return null;
currentrace[0].pictogram_url = await locals.pb.files.getURL(
currentrace[0],
currentrace[0].pictogram,
);
return currentrace[0];
};
const fetch_racepicks = async (): Promise<RacePick[]> => {
// Don't expand race/pxx/dnf since we already fetched those
const racepicks: RacePick[] = await locals.pb
.collection("racepicks")
.getFullList({ fetch: fetch, expand: "user" });
return racepicks;
};
const fetch_currentpickedusers = async (): Promise<CurrentPickedUser[]> => {
const currentpickedusers: CurrentPickedUser[] = await locals.pb
.collection("currentpickedusers")
.getFullList();
currentpickedusers.map((currentpickeduser: CurrentPickedUser) => {
if (currentpickeduser.avatar) {
currentpickeduser.avatar_url = locals.pb.files.getURL(
currentpickeduser,
currentpickeduser.avatar,
);
}
});
return currentpickedusers;
};
// TODO: Duplicated code from data/raceresults/+page.server.ts
const fetch_raceresults = async (): Promise<RaceResult[]> => {
// Don't expand races/pxxs/dnfs since we already fetched those
const raceresults: RaceResult[] = await locals.pb.collection("raceresultsdesc").getFullList();
return raceresults;
};
return {
racepicks: fetch_racepicks(),
currentpickedusers: fetch_currentpickedusers(),
raceresults: fetch_raceresults(),
currentrace: await fetch_currentrace(),
};
};

View File

@ -0,0 +1,57 @@
import { pb } from "$lib/pocketbase";
import type { CurrentPickedUser, Race, RacePick, RaceResult } from "$lib/schema";
import type { PageLoad } from "../$types";
export const load: PageLoad = async ({ fetch }) => {
const fetch_currentrace = async (): Promise<Race | null> => {
const currentrace: Race[] = await pb.collection("currentrace").getFullList({ fetch: fetch });
// The currentrace collection either has a single or no entries
if (currentrace.length == 0) return null;
currentrace[0].pictogram_url = pb.files.getURL(currentrace[0], currentrace[0].pictogram);
return currentrace[0];
};
const fetch_racepicks = async (): Promise<RacePick[]> => {
// Don't expand race/pxx/dnf since we already fetched those
const racepicks: RacePick[] = await pb
.collection("racepicks")
.getFullList({ fetch: fetch, expand: "user" });
return racepicks;
};
const fetch_currentpickedusers = async (): Promise<CurrentPickedUser[]> => {
const currentpickedusers: CurrentPickedUser[] = await pb
.collection("currentpickedusers")
.getFullList({ fetch: fetch });
currentpickedusers.map((currentpickeduser: CurrentPickedUser) => {
if (currentpickeduser.avatar) {
currentpickeduser.avatar_url = pb.files.getURL(currentpickeduser, currentpickeduser.avatar);
}
});
return currentpickedusers;
};
// TODO: Duplicated code from data/raceresults/+page.server.ts
const fetch_raceresults = async (): Promise<RaceResult[]> => {
// Don't expand races/pxxs/dnfs since we already fetched those
const raceresults: RaceResult[] = await pb
.collection("raceresultsdesc")
.getFullList({ fetch: fetch });
return raceresults;
};
return {
racepicks: fetch_racepicks(),
currentpickedusers: fetch_currentpickedusers(),
raceresults: fetch_raceresults(),
currentrace: await fetch_currentrace(),
};
};