Compare commits

...

4 Commits

Author SHA1 Message Date
178adef327 Lib: Simplify RaceResultCard
All checks were successful
Build Formula11 Docker Image / pocketbase-docker (push) Successful in 49s
2025-02-05 21:56:41 +01:00
6947eeae3f Racepicks: Fix width of guess badges 2025-02-05 21:56:32 +01:00
735c73e435 Racepicks: Stream loaded data and resolve promises in markup 2025-02-05 20:38:28 +01:00
907e4fefb1 Lib: Type data passed to cards from the page context 2025-02-05 20:14:05 +01:00
10 changed files with 457 additions and 426 deletions

View File

@ -7,7 +7,7 @@
type ModalStore, type ModalStore,
} from "@skeletonlabs/skeleton"; } from "@skeletonlabs/skeleton";
import { Button, Input, Card, Dropdown } from "$lib/components"; import { Button, Input, Card, Dropdown } from "$lib/components";
import type { Driver } from "$lib/schema"; import type { Driver, SkeletonData } from "$lib/schema";
import { DRIVER_HEADSHOT_HEIGHT, DRIVER_HEADSHOT_WIDTH } from "$lib/config"; import { DRIVER_HEADSHOT_HEIGHT, DRIVER_HEADSHOT_WIDTH } from "$lib/config";
import { team_dropdown_options } from "$lib/dropdown"; import { team_dropdown_options } from "$lib/dropdown";
import { enhance } from "$app/forms"; import { enhance } from "$app/forms";
@ -15,7 +15,7 @@
interface DriverCardProps { interface DriverCardProps {
/** Data passed from the page context */ /** Data passed from the page context */
data: any; data: SkeletonData;
/** The [Driver] object used to prefill values. */ /** The [Driver] object used to prefill values. */
driver?: Driver; driver?: Driver;

View File

@ -2,7 +2,7 @@
import { get_image_preview_event_handler } from "$lib/image"; import { get_image_preview_event_handler } from "$lib/image";
import { FileDropzone, getModalStore, type ModalStore } from "@skeletonlabs/skeleton"; import { FileDropzone, getModalStore, type ModalStore } from "@skeletonlabs/skeleton";
import { Button, Card, Input } from "$lib/components"; import { Button, Card, Input } from "$lib/components";
import type { Race } from "$lib/schema"; import type { Race, SkeletonData } from "$lib/schema";
import { format } from "date-fns"; import { format } from "date-fns";
import { RACE_PICTOGRAM_HEIGHT, RACE_PICTOGRAM_WIDTH } from "$lib/config"; import { RACE_PICTOGRAM_HEIGHT, RACE_PICTOGRAM_WIDTH } from "$lib/config";
import { enhance } from "$app/forms"; import { enhance } from "$app/forms";
@ -10,7 +10,7 @@
interface RaceCardProps { interface RaceCardProps {
/** Data passed from the page context */ /** Data passed from the page context */
data: any; data: SkeletonData;
/** The [Race] object used to prefill values. */ /** The [Race] object used to prefill values. */
race?: Race; race?: Race;

View File

@ -1,6 +1,14 @@
<script lang="ts"> <script lang="ts">
import { Card, Button, Dropdown } from "$lib/components"; import { Card, Button, Dropdown } from "$lib/components";
import type { Driver, Race, RacePick, Substitution } from "$lib/schema"; import type {
CurrentPickedUser,
Driver,
Race,
RacePick,
RaceResult,
SkeletonData,
Substitution,
} from "$lib/schema";
import { get_by_value, get_driver_headshot_template } from "$lib/database"; import { get_by_value, get_driver_headshot_template } from "$lib/database";
import type { Action } from "svelte/action"; import type { Action } from "svelte/action";
import { getModalStore, type ModalStore } from "@skeletonlabs/skeleton"; import { getModalStore, type ModalStore } from "@skeletonlabs/skeleton";
@ -10,7 +18,12 @@
interface RacePickCardProps { interface RacePickCardProps {
/** Data passed from the page context */ /** Data passed from the page context */
data: any; data: SkeletonData & {
currentrace: Race;
racepicks: Promise<RacePick[]>;
currentpickedusers: Promise<CurrentPickedUser[]>;
raceresults: Promise<RaceResult[]>;
};
/** The [RacePick] object used to prefill values. */ /** The [RacePick] object used to prefill values. */
racepick?: RacePick; racepick?: RacePick;
@ -111,6 +124,7 @@
options={driver_dropdown_options(pxx_drivers)} options={driver_dropdown_options(pxx_drivers)}
{labelwidth} {labelwidth}
{disabled} {disabled}
{required}
> >
P{data.currentrace?.pxx ?? "XX"} P{data.currentrace?.pxx ?? "XX"}
</Dropdown> </Dropdown>
@ -124,6 +138,7 @@
options={driver_dropdown_options(pxx_drivers)} options={driver_dropdown_options(pxx_drivers)}
{labelwidth} {labelwidth}
{disabled} {disabled}
{required}
> >
DNF DNF
</Dropdown> </Dropdown>

View File

@ -7,96 +7,69 @@
type ModalStore, type ModalStore,
} from "@skeletonlabs/skeleton"; } from "@skeletonlabs/skeleton";
import { Button, Card, Dropdown } from "$lib/components"; import { Button, Card, Dropdown } from "$lib/components";
import type { Driver, Race, RaceResult } from "$lib/schema"; import type { Driver, Race, RaceResult, SkeletonData } from "$lib/schema";
import { get_by_value } from "$lib/database"; import { get_by_value } from "$lib/database";
import { race_dropdown_options } from "$lib/dropdown"; import { race_dropdown_options } from "$lib/dropdown";
import { enhance } from "$app/forms"; import { enhance } from "$app/forms";
interface RaceResultCardProps { interface RaceResultCardProps {
/** Data passed from the page context */
data: SkeletonData & { results: RaceResult[] };
/** The [RaceResult] object used to prefill values. */ /** The [RaceResult] object used to prefill values. */
result?: RaceResult; result?: RaceResult;
/** The list of [Drivers] for the driver selection */
drivers: Driver[];
/** The list of [Races] for the race selection + PXX display */
races: Race[];
/** Disable all inputs if [true] */
disable_inputs?: boolean;
/** Require all inputs if [true] */
require_inputs?: boolean;
} }
let { let { data, result = undefined }: RaceResultCardProps = $props();
result = undefined,
drivers,
races,
disable_inputs = false,
require_inputs = false,
}: RaceResultCardProps = $props();
// TODO: This does not work at all. Why does it work for other cards???
// Everything exists here, but in the markup it is undefined???
const modalStore: ModalStore = getModalStore(); const modalStore: ModalStore = getModalStore();
if ($modalStore[0].meta) { if ($modalStore[0].meta) {
const meta = $modalStore[0].meta; const meta = $modalStore[0].meta;
// Stuff thats required for the "update" card data = meta.data;
disable_inputs = meta.disable_inputs;
drivers = meta.drivers;
races = meta.races;
result = meta.result; result = meta.result;
// Stuff thats additionally required for the "create" card
require_inputs = meta.require_inputs;
} }
const currentrace: Race | undefined = get_by_value(races, "id", result?.race ?? "Invalid"); const required: boolean = $derived(!result);
const disabled: boolean = $derived(!data.admin);
const labelwidth: string = "70px";
const currentrace: Promise<Race | undefined> = $derived.by(async () =>
get_by_value(await data.races, "id", result?.race ?? "Invalid"),
);
// TODO: I have no fucking idea why this solves things... const pxxs_options: Promise<AutocompleteOption<string>[]> = $derived.by(async () =>
// Without this, the original values passed through the modalStore (await data.drivers).map((driver: Driver) => {
// are undefined within the markup, but not within the <script>... return {
const disable_inputs2 = disable_inputs; // NOTE: Because Skeleton displays the values inside the autocomplete input,
const drivers2 = drivers; // we have to supply the driver code twice and manage a list of ids manually (ugh)
const races2 = races; label: driver.code,
const result2 = result; value: driver.code,
const require_inputs2 = require_inputs; };
}),
);
let race_select_value: string = currentrace?.id ?? ""; const pxxs_whitelist: Promise<string[]> = $derived.by(async () =>
(await data.drivers).map((driver: Driver) => {
return driver.code;
}),
);
let race_select_value: string = $state(result?.race ?? "");
let pxxs_input: string = $state(""); let pxxs_input: string = $state("");
let pxxs_chips: string[] = $state( let pxxs_chips: string[] = $state([]);
result2?.pxxs.map(
(id: string, index: number) =>
`P${(currentrace?.pxx ?? -10) + index - 3}: ${get_by_value(drivers2, "id", id)?.code ?? "Invalid"}`,
) ?? [],
);
let dnfs_input: string = $state(""); let dnfs_input: string = $state("");
let dnfs_chips: string[] = $state( let dnfs_chips: string[] = $state([]);
result2?.dnfs.map((id: string) => get_by_value(drivers2, "id", id)?.code ?? "Invalid") ?? [],
);
// This is the actual data that gets sent through the form // This is the actual data that gets sent through the form
let pxxs_ids: string[] = $state(result2?.pxxs ?? []); let pxxs_ids: string[] = $state(result?.pxxs ?? []);
let dnfs_ids: string[] = $state(result2?.dnfs ?? []); let dnfs_ids: string[] = $state(result?.dnfs ?? []);
const pxxs_options: AutocompleteOption<string>[] = drivers2.map((driver: Driver) => { const on_pxxs_chip_select = async (
return { event: CustomEvent<AutocompleteOption<string>>,
// NOTE: Because Skeleton displays the values inside the autocomplete input, ): Promise<void> => {
// we have to supply the driver code twice and manage a list of ids manually (ugh) if (disabled) return;
label: driver.code,
value: driver.code,
};
});
const pxxs_whitelist: string[] = drivers2.map((driver: Driver) => {
return driver.code;
});
const on_pxxs_chip_select = (event: CustomEvent<AutocompleteOption<string>>): void => {
if (disable_inputs2) return;
// Can only select 7 drivers // Can only select 7 drivers
if (pxxs_chips.length >= 7) return; if (pxxs_chips.length >= 7) return;
@ -105,27 +78,34 @@
if (pxxs_chips.some((label: string) => label.endsWith(event.detail.value))) return; if (pxxs_chips.some((label: string) => label.endsWith(event.detail.value))) return;
// Manage labels that are displayed // Manage labels that are displayed
pxxs_chips.push(`P${(currentrace?.pxx ?? -10) + pxxs_chips.length - 3}: ${event.detail.value}`); pxxs_chips.push(
`P${((await currentrace)?.pxx ?? -10) + pxxs_chips.length - 3}: ${event.detail.value}`,
);
pxxs_input = ""; pxxs_input = "";
// Manage ids that are submitted via form // Manage ids that are submitted via form
const id: string = get_by_value(drivers2, "code", event.detail.value)?.id ?? "Invalid"; const id: string =
get_by_value(await data.drivers, "code", event.detail.value)?.id ?? "Invalid";
if (!pxxs_ids.includes(id)) { if (!pxxs_ids.includes(id)) {
pxxs_ids.push(id); pxxs_ids.push(id);
} }
}; };
const on_pxxs_chip_remove = (event: CustomEvent): void => { const on_pxxs_chip_remove = async (event: CustomEvent): Promise<void> => {
pxxs_ids.splice(event.detail.chipIndex, 1); pxxs_ids.splice(event.detail.chipIndex, 1);
pxxs_chips = pxxs_chips.map( pxxs_chips = await Promise.all(
(label: string, index: number) => pxxs_chips.map(
`P${(currentrace?.pxx ?? -10) + index - 3}: ${label.split(" ").pop()}`, async (label: string, index: number) =>
`P${((await currentrace)?.pxx ?? -10) + index - 3}: ${label.split(" ").pop()}`,
),
); );
}; };
const on_dnfs_chip_select = (event: CustomEvent<AutocompleteOption<string>>): void => { const on_dnfs_chip_select = async (
if (disable_inputs2) return; event: CustomEvent<AutocompleteOption<string>>,
): Promise<void> => {
if (disabled) return;
// Can only select a driver once // Can only select a driver once
if (dnfs_chips.includes(event.detail.value)) return; if (dnfs_chips.includes(event.detail.value)) return;
@ -135,118 +115,135 @@
dnfs_input = ""; dnfs_input = "";
// Manage ids that are submitted via form // Manage ids that are submitted via form
const id: string = get_by_value(drivers2, "code", event.detail.value)?.id ?? "Invalid"; const id: string =
get_by_value(await data.drivers, "code", event.detail.value)?.id ?? "Invalid";
if (!dnfs_ids.includes(id)) { if (!dnfs_ids.includes(id)) {
dnfs_ids.push(id); dnfs_ids.push(id);
} }
}; };
const on_dnfs_chip_remove = (event: CustomEvent): void => { const on_dnfs_chip_remove = async (event: CustomEvent): Promise<void> => {
dnfs_ids.splice(event.detail.chipIndex, 1); dnfs_ids.splice(event.detail.chipIndex, 1);
}; };
// Set the pxxs/dnfs states once the drivers are loaded
data.drivers.then(async (drivers: Driver[]) => {
pxxs_chips = await Promise.all(
result?.pxxs.map(
async (id: string, index: number) =>
`P${((await currentrace)?.pxx ?? -10) + index - 3}: ${get_by_value(drivers, "id", id)?.code ?? "Invalid"}`,
) ?? [],
);
dnfs_chips =
result?.dnfs.map((id: string) => get_by_value(drivers, "id", id)?.code ?? "Invalid") ?? [];
});
</script> </script>
<Card width="w-full sm:w-[512px]"> <Card width="w-full sm:w-[512px]">
<form method="POST" enctype="multipart/form-data" use:enhance> <form method="POST" enctype="multipart/form-data" use:enhance onsubmit={() => modalStore.close()}>
<!-- This is also disabled, because the ID should only be --> <!-- This is also disabled, because the ID should only be -->
<!-- "leaked" to users that are allowed to use the inputs --> <!-- "leaked" to users that are allowed to use the inputs -->
{#if result2 && !disable_inputs2} {#if result && !disabled}
<input name="id" type="hidden" value={result2.id} /> <input name="id" type="hidden" value={result.id} />
{/if} {/if}
<!-- Send the input chips ids --> <!-- Send the input chips ids -->
{#each pxxs_ids as pxxs_id} {#each pxxs_ids as pxxs_id}
<input name="pxxs" type="hidden" disabled={disable_inputs2} value={pxxs_id} /> <input name="pxxs" type="hidden" {disabled} value={pxxs_id} />
{/each} {/each}
{#each dnfs_ids as dnfs_id} {#each dnfs_ids as dnfs_id}
<input name="dnfs" type="hidden" disabled={disable_inputs2} value={dnfs_id} /> <input name="dnfs" type="hidden" {disabled} value={dnfs_id} />
{/each} {/each}
<!-- Race select input --> <!-- Race select input -->
<Dropdown {#await data.races then races}
name="race" <Dropdown
input_variable={race_select_value} name="race"
options={race_dropdown_options(races2)} input_variable={race_select_value}
labelwidth="70px" options={race_dropdown_options(races)}
disabled={disable_inputs2} {labelwidth}
required={require_inputs2} {disabled}
> {required}
Race >
</Dropdown> Race
</Dropdown>
{/await}
<div class="mt-2 flex flex-col gap-2"> <div class="mt-2 flex flex-col gap-2">
<!-- PXXs autocomplete chips --> <!-- PXXs autocomplete chips -->
<InputChip {#await currentrace then current}
bind:input={pxxs_input} {#await pxxs_whitelist then whitelist}
bind:value={pxxs_chips} <InputChip
whitelist={pxxs_whitelist} bind:input={pxxs_input}
allowUpperCase bind:value={pxxs_chips}
placeholder="Select P{(currentrace?.pxx ?? -10) - 3} to P{(currentrace?.pxx ?? -10) + 3}..." {whitelist}
name="pxxs_codes" allowUpperCase
disabled={disable_inputs2} placeholder="Select P{(current?.pxx ?? -10) - 3} to P{(current?.pxx ?? -10) + 3}..."
required={require_inputs2} name="pxxs_codes"
on:remove={on_pxxs_chip_remove} {disabled}
/> {required}
on:remove={on_pxxs_chip_remove}
/>
{/await}
{/await}
<div class="card max-h-48 w-full overflow-y-auto p-2" tabindex="-1"> <div class="card max-h-48 w-full overflow-y-auto p-2" tabindex="-1">
<Autocomplete {#await pxxs_options then options}
bind:input={pxxs_input} <Autocomplete
options={pxxs_options} bind:input={pxxs_input}
denylist={pxxs_chips} {options}
on:selection={on_pxxs_chip_select} denylist={pxxs_chips}
/> on:selection={on_pxxs_chip_select}
/>
{/await}
</div> </div>
<!-- DNFs autocomplete chips --> <!-- DNFs autocomplete chips -->
<InputChip {#await pxxs_whitelist then whitelist}
bind:input={dnfs_input} <InputChip
bind:value={dnfs_chips}
whitelist={pxxs_whitelist}
allowUpperCase
placeholder="Select DNFs..."
name="dnfs_codes"
disabled={disable_inputs2}
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} bind:input={dnfs_input}
options={pxxs_options} bind:value={dnfs_chips}
denylist={dnfs_chips} {whitelist}
on:selection={on_dnfs_chip_select} allowUpperCase
placeholder="Select DNFs..."
name="dnfs_codes"
{disabled}
on:remove={on_dnfs_chip_remove}
/> />
{/await}
<div class="card max-h-48 w-full overflow-y-auto p-2" tabindex="-1">
{#await pxxs_options then options}
<Autocomplete
bind:input={dnfs_input}
{options}
denylist={dnfs_chips}
on:selection={on_dnfs_chip_select}
/>
{/await}
</div> </div>
<!-- Save/Delete buttons --> <!-- Save/Delete buttons -->
<div class="flex items-center justify-end gap-2"> <div class="flex items-center justify-end gap-2">
{#if result2} {#if result}
<Button <Button
formaction="?/update_raceresult" formaction="?/update_raceresult"
color="secondary" color="secondary"
disabled={disable_inputs2} {disabled}
submit submit
width="w-1/2" width="w-1/2"
onclick={() => modalStore.close()}
> >
Save Save
</Button> </Button>
<Button <Button formaction="?/delete_raceresult" color="primary" {disabled} submit width="w-1/2">
color="primary"
submit
disabled={disable_inputs2}
formaction="?/delete_raceresult"
width="w-1/2"
onclick={() => modalStore.close()}
>
Delete Delete
</Button> </Button>
{:else} {:else}
<Button <Button
formaction="?/create_raceresult" formaction="?/create_raceresult"
color="tertiary" color="tertiary"
{disabled}
submit submit
width="w-full" width="w-full"
disabled={disable_inputs2}
onclick={() => modalStore.close()}
> >
Create Result Create Result
</Button> </Button>

View File

@ -1,17 +1,16 @@
<script lang="ts"> <script lang="ts">
import { Card, Button, Dropdown } from "$lib/components"; import { Card, Button, Dropdown } from "$lib/components";
import type { Driver, Race, Substitution } from "$lib/schema"; import type { Driver, Race, SkeletonData, Substitution } from "$lib/schema";
import { get_by_value, get_driver_headshot_template } from "$lib/database"; import { get_by_value, get_driver_headshot_template } from "$lib/database";
import type { Action } from "svelte/action"; import type { Action } from "svelte/action";
import { getModalStore, type ModalStore } from "@skeletonlabs/skeleton"; import { getModalStore, type ModalStore } from "@skeletonlabs/skeleton";
import { DRIVER_HEADSHOT_HEIGHT, DRIVER_HEADSHOT_WIDTH } from "$lib/config"; import { DRIVER_HEADSHOT_HEIGHT, DRIVER_HEADSHOT_WIDTH } from "$lib/config";
import { driver_dropdown_options, race_dropdown_options } from "$lib/dropdown"; import { driver_dropdown_options, race_dropdown_options } from "$lib/dropdown";
import { enhance } from "$app/forms"; import { enhance } from "$app/forms";
import { sub } from "date-fns";
interface SubstitutionCardProps { interface SubstitutionCardProps {
/** Data passed from the page context */ /** Data passed from the page context */
data: any; data: SkeletonData;
/** The [Substitution] object used to prefill values. */ /** The [Substitution] object used to prefill values. */
substitution?: Substitution; substitution?: Substitution;

View File

@ -2,14 +2,14 @@
import { get_image_preview_event_handler } from "$lib/image"; import { get_image_preview_event_handler } from "$lib/image";
import { FileDropzone, getModalStore, type ModalStore } from "@skeletonlabs/skeleton"; import { FileDropzone, getModalStore, type ModalStore } from "@skeletonlabs/skeleton";
import { Card, Button, Input, LazyImage } from "$lib/components"; import { Card, Button, Input, LazyImage } from "$lib/components";
import type { Team } from "$lib/schema"; import type { SkeletonData, Team } from "$lib/schema";
import { TEAM_BANNER_HEIGHT, TEAM_BANNER_WIDTH } from "$lib/config"; import { TEAM_BANNER_HEIGHT, TEAM_BANNER_WIDTH } from "$lib/config";
import { enhance } from "$app/forms"; import { enhance } from "$app/forms";
import { get_team_banner_template, get_team_logo_template } from "$lib/database"; import { get_team_banner_template, get_team_logo_template } from "$lib/database";
interface TeamCardProps { interface TeamCardProps {
/** Data from the page context */ /** Data from the page context */
data: any; data: SkeletonData;
/** The [Team] object used to prefill values. */ /** The [Team] object used to prefill values. */
team?: Team; team?: Team;

View File

@ -3,6 +3,20 @@
// Application Data // Application Data
/**
* The data returned from the root layout's [load]-function.
*/
export interface SkeletonData {
user: User;
admin: boolean;
graphics: Promise<Graphic[]>;
teams: Promise<Team[]>;
drivers: Promise<Driver[]>;
races: Promise<Race[]>;
substitutions: Promise<Substitution[]>;
}
export interface Graphic { export interface Graphic {
name: string; name: string;
file: string; file: string;

View File

@ -4,10 +4,30 @@
import { Button, Table, type TableColumn } from "$lib/components"; import { Button, Table, type TableColumn } from "$lib/components";
import { get_by_value } from "$lib/database"; import { get_by_value } from "$lib/database";
import { PXX_COLORS } from "$lib/config"; import { PXX_COLORS } from "$lib/config";
import type { RaceResult } from "$lib/schema";
let { data }: { data: PageData } = $props(); let { data }: { data: PageData } = $props();
const results_columns: TableColumn[] = [ const modalStore: ModalStore = getModalStore();
const result_handler = async (event: Event, id?: string) => {
const result: RaceResult | undefined = get_by_value(data.results, "id", id ?? "Invalid");
if (id && !result) return;
const modalSettings: ModalSettings = {
type: "component",
component: "raceResultCard",
meta: {
data,
result,
},
};
modalStore.trigger(modalSettings);
};
const results_columns: TableColumn[] = $derived([
{ {
data_value_name: "race", data_value_name: "race",
label: "Step", label: "Step",
@ -58,44 +78,12 @@
return dnfs_codes.join(""); return dnfs_codes.join("");
}, },
}, },
]; ]);
const modalStore: ModalStore = getModalStore();
const results_handler = async (event: Event, id: string) => {
const modalSettings: ModalSettings = {
type: "component",
component: "raceResultCard",
meta: {
disable_inputs: !data.admin,
drivers: await data.drivers,
races: await data.races,
result: get_by_value(data.results, "id", id),
},
};
modalStore.trigger(modalSettings);
};
const create_result_handler = async (event: Event) => {
const modalSettings: ModalSettings = {
type: "component",
component: "raceResultCard",
meta: {
disable_inputs: !data.admin,
drivers: await data.drivers,
races: await data.races,
require_inputs: true,
},
};
modalStore.trigger(modalSettings);
};
</script> </script>
<div class="pb-2"> <div class="pb-2">
<Button width="w-full" color="tertiary" onclick={create_result_handler} shadow> <Button width="w-full" color="tertiary" onclick={result_handler} shadow>
<span class="font-bold">Create Race Result</span> <span class="font-bold">Create Race Result</span>
</Button> </Button>
</div> </div>
<Table data={data.results} columns={results_columns} handler={results_handler} /> <Table data={data.results} columns={results_columns} handler={result_handler} />

View File

@ -2,65 +2,6 @@ import { form_data_clean, form_data_ensure_keys, form_data_get_and_remove_id } f
import type { CurrentPickedUser, Race, RacePick, RaceResult } from "$lib/schema"; import type { CurrentPickedUser, Race, RacePick, RaceResult } from "$lib/schema";
import type { Actions, PageServerLoad } from "./$types"; import type { Actions, PageServerLoad } from "./$types";
export const load: PageServerLoad = async ({ fetch, locals }) => {
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" });
// TODO: Fill in the expanded race pictogram_url fields
return racepicks;
};
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_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: await fetch_racepicks(),
currentrace: await fetch_currentrace(),
currentpickedusers: await fetch_currentpickedusers(),
raceresults: await fetch_raceresults(),
};
};
export const actions = { export const actions = {
create_racepick: async ({ request, locals }) => { create_racepick: async ({ request, locals }) => {
const data: FormData = form_data_clean(await request.formData()); const data: FormData = form_data_clean(await request.formData());
@ -91,3 +32,61 @@ export const actions = {
await locals.pb.collection("racepicks").delete(id); await locals.pb.collection("racepicks").delete(id);
}, },
} satisfies Actions; } 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 {
currentrace: await fetch_currentrace(),
racepicks: fetch_racepicks(),
currentpickedusers: fetch_currentpickedusers(),
raceresults: fetch_raceresults(),
};
};

View File

@ -25,12 +25,13 @@
let { data }: { data: PageData } = $props(); let { data }: { data: PageData } = $props();
const racepick: RacePick | undefined = $derived( const racepick: Promise<RacePick | undefined> = $derived.by(
data.racepicks.filter( async () =>
(racepick: RacePick) => (await data.racepicks).filter(
racepick.expand.user.username === data.user?.username && (racepick: RacePick) =>
racepick.race === data.currentrace?.id, racepick.expand.user.username === data.user?.username &&
)[0] ?? undefined, racepick.race === data.currentrace?.id,
)[0] ?? undefined,
); );
const modalStore: ModalStore = getModalStore(); const modalStore: ModalStore = getModalStore();
@ -40,7 +41,7 @@
component: "racePickCard", component: "racePickCard",
meta: { meta: {
data, data,
racepick, racepick: await racepick,
}, },
}; };
@ -48,15 +49,15 @@
}; };
// Users that have already picked the current race // Users that have already picked the current race
let pickedusers: CurrentPickedUser[] = $derived( let pickedusers: Promise<CurrentPickedUser[]> = $derived.by(async () =>
data.currentpickedusers.filter( (await data.currentpickedusers).filter(
(currentpickeduser: CurrentPickedUser) => currentpickeduser.picked, (currentpickeduser: CurrentPickedUser) => currentpickeduser.picked,
), ),
); );
// Users that didn't already pick the current race // Users that didn't already pick the current race
let outstandingusers: CurrentPickedUser[] = $derived( let outstandingusers: Promise<CurrentPickedUser[]> = $derived.by(async () =>
data.currentpickedusers.filter( (await data.currentpickedusers).filter(
(currentpickeduser: CurrentPickedUser) => !currentpickeduser.picked, (currentpickeduser: CurrentPickedUser) => !currentpickeduser.picked,
), ),
); );
@ -127,83 +128,87 @@
<!-- Only show the userguess if signed in --> <!-- Only show the userguess if signed in -->
{#if data.user} {#if data.user}
<div class="mt-2 flex gap-2"> {#await data.graphics then graphics}
<div class="card w-full min-w-40 p-2 pb-0 shadow"> {#await data.drivers then drivers}
<h1 class="mb-2 text-nowrap font-bold">Your P{data.currentrace.pxx} Pick:</h1> {#await racepick then pick}
{#await data.graphics then graphics} <div class="mt-2 flex gap-2">
{#await data.drivers then drivers} <div class="card w-full min-w-40 p-2 pb-0 shadow">
<LazyImage <h1 class="mb-2 text-nowrap font-bold">Your P{data.currentrace.pxx} Pick:</h1>
src={get_by_value(drivers, "id", racepick?.pxx ?? "")?.headshot_url ?? <LazyImage
get_driver_headshot_template(graphics)} src={get_by_value(drivers, "id", pick?.pxx ?? "")?.headshot_url ??
imgwidth={DRIVER_HEADSHOT_WIDTH} get_driver_headshot_template(graphics)}
imgheight={DRIVER_HEADSHOT_HEIGHT} imgwidth={DRIVER_HEADSHOT_WIDTH}
containerstyle="height: 115px; margin: auto;" imgheight={DRIVER_HEADSHOT_HEIGHT}
imgclass="bg-transparent cursor-pointer" containerstyle="height: 115px; margin: auto;"
hoverzoom imgclass="bg-transparent cursor-pointer"
onclick={racepick_handler} hoverzoom
/> onclick={racepick_handler}
{/await} />
</div>
<div class="card w-full min-w-40 p-2 pb-0 shadow">
<h1 class="mb-2 text-nowrap font-bold">Your DNF Pick:</h1>
<LazyImage
src={get_by_value(drivers, "id", pick?.dnf ?? "")?.headshot_url ??
get_driver_headshot_template(graphics)}
imgwidth={DRIVER_HEADSHOT_WIDTH}
imgheight={DRIVER_HEADSHOT_HEIGHT}
containerstyle="height: 115px; margin: auto;"
imgclass="bg-transparent cursor-pointer"
hoverzoom
onclick={racepick_handler}
/>
</div>
</div>
{/await} {/await}
</div> {/await}
<div class="card w-full min-w-40 p-2 pb-0 shadow"> {/await}
<h1 class="mb-2 text-nowrap font-bold">Your DNF Pick:</h1>
{#await data.graphics then graphics}
{#await data.drivers then drivers}
<LazyImage
src={get_by_value(drivers, "id", racepick?.dnf ?? "")?.headshot_url ??
get_driver_headshot_template(graphics)}
imgwidth={DRIVER_HEADSHOT_WIDTH}
imgheight={DRIVER_HEADSHOT_HEIGHT}
containerstyle="height: 115px; margin: auto;"
imgclass="bg-transparent cursor-pointer"
hoverzoom
onclick={racepick_handler}
/>
{/await}
{/await}
</div>
</div>
{/if} {/if}
<!-- Show users that have and have not picked yet --> <!-- Show users that have and have not picked yet -->
<div class="mt-2 flex gap-2"> {#await data.currentpickedusers then currentpicked}
<div class="card w-full min-w-40 p-2 shadow"> <div class="mt-2 flex gap-2">
<h1 class="text-nowrap font-bold"> {#await pickedusers then picked}
Picked ({pickedusers.length}/{data.currentpickedusers.length}): <div class="card w-full min-w-40 p-2 shadow lg:max-w-40">
</h1> <h1 class="text-nowrap font-bold">
<div class="mt-1 grid grid-cols-4 gap-x-2 gap-y-0.5"> Picked ({picked.length}/{currentpicked.length}):
{#await data.graphics then graphics} </h1>
{#each pickedusers.slice(0, 16) as user} <div class="mt-1 grid grid-cols-4 gap-x-2 gap-y-0.5">
<LazyImage {#await data.graphics then graphics}
src={user.avatar_url ?? get_driver_headshot_template(graphics)} {#each picked.slice(0, 16) as user}
imgwidth={AVATAR_WIDTH} <LazyImage
imgheight={AVATAR_HEIGHT} src={user.avatar_url ?? get_driver_headshot_template(graphics)}
containerstyle="height: 35px; width: 35px;" imgwidth={AVATAR_WIDTH}
imgclass="bg-surface-400 rounded-full" imgheight={AVATAR_HEIGHT}
/> containerstyle="height: 35px; width: 35px;"
{/each} imgclass="bg-surface-400 rounded-full"
{/await} />
</div> {/each}
{/await}
</div>
</div>
{/await}
{#await outstandingusers then outstanding}
<div class="card w-full min-w-40 p-2 shadow lg:max-w-40">
<h1 class="text-nowrap font-bold">
Outstanding ({outstanding.length}/{currentpicked.length}):
</h1>
<div class="mt-1 grid grid-cols-4 gap-x-0 gap-y-0.5">
{#await data.graphics then graphics}
{#each outstanding.slice(0, 16) as user}
<LazyImage
src={user.avatar_url ?? get_driver_headshot_template(graphics)}
imgwidth={AVATAR_WIDTH}
imgheight={AVATAR_HEIGHT}
containerstyle="height: 35px; width: 35px;"
imgclass="bg-surface-400 rounded-full"
/>
{/each}
{/await}
</div>
</div>
{/await}
</div> </div>
<div class="card w-full min-w-40 p-2 shadow"> {/await}
<h1 class="text-nowrap font-bold">
Outstanding ({outstandingusers.length}/{data.currentpickedusers.length}):
</h1>
<div class="mt-1 grid grid-cols-4 gap-x-0 gap-y-0.5">
{#await data.graphics then graphics}
{#each outstandingusers.slice(0, 16) as user}
<LazyImage
src={user.avatar_url ?? get_driver_headshot_template(graphics)}
imgwidth={AVATAR_WIDTH}
imgheight={AVATAR_HEIGHT}
containerstyle="height: 35px; width: 35px;"
imgclass="bg-surface-400 rounded-full"
/>
{/each}
{/await}
</div>
</div>
</div>
</div> </div>
</svelte:fragment> </svelte:fragment>
</AccordionItem> </AccordionItem>
@ -255,122 +260,136 @@
</div> </div>
{#await data.races then races} {#await data.races then races}
{#each data.raceresults as result} {#await data.raceresults then raceresults}
{@const race = get_by_value(races, "id", result.race)} {#each raceresults as result}
{@const race = get_by_value(races, "id", result.race)}
<div <div
use:popup={race_popupsettings(race?.id ?? "Invalid")} use:popup={race_popupsettings(race?.id ?? "Invalid")}
class="card mt-2 flex h-20 w-7 flex-col !rounded-r-none bg-surface-300 p-2 shadow lg:w-36" class="card mt-2 flex h-20 w-7 flex-col !rounded-r-none bg-surface-300 p-2 shadow lg:w-36"
> >
<span class="hidden text-sm font-bold lg:block"> <span class="hidden text-sm font-bold lg:block">
{race?.step}: {race?.name} {race?.step}: {race?.name}
</span> </span>
<span class="block rotate-90 text-sm font-bold lg:hidden"> <span class="block rotate-90 text-sm font-bold lg:hidden">
{race?.name.slice(0, 8)}{(race?.name.length ?? 8) > 8 ? "." : ""} {race?.name.slice(0, 8)}{(race?.name.length ?? 8) > 8 ? "." : ""}
</span> </span>
<span class="hidden text-sm lg:block">Date: {formatdate(race?.racedate ?? "")}</span> <span class="hidden text-sm lg:block">Date: {formatdate(race?.racedate ?? "")}</span>
<span class="hidden text-sm lg:block">Guessed: P{race?.pxx}</span> <span class="hidden text-sm lg:block">Guessed: P{race?.pxx}</span>
</div>
<!-- The race result popup is triggered on click on the race -->
<div data-popup={race?.id ?? "Invalid"} class="card z-50 p-2 shadow">
<span class="font-bold">Result:</span>
<div class="mt-2 flex flex-col gap-1">
{#await data.drivers then drivers}
{#each result.pxxs as pxx, index}
{@const driver = get_by_value(drivers, "id", pxx)}
<div class="flex gap-2">
<span class="w-8">P{(race?.pxx ?? -100) - 3 + index}:</span>
<span class="badge w-10 p-1 text-center" style="background: {PXX_COLORS[index]};">
{driver?.code}
</span>
</div>
{/each}
{#if result.dnfs.length > 0}
<hr class="border-black" style="border-style: inset;" />
{/if}
{#each result.dnfs as dnf}
{@const driver = get_by_value(drivers, "id", dnf)}
<div class="flex gap-2">
<span class="w-8">DNF:</span>
<span class="badge w-10 p-1 text-center" style="background: {PXX_COLORS[3]};">
{driver?.code}
</span>
</div>
{/each}
{/await}
</div> </div>
</div>
{/each} <!-- The race result popup is triggered on click on the race -->
<div data-popup={race?.id ?? "Invalid"} class="card z-50 p-2 shadow">
<span class="font-bold">Result:</span>
<div class="mt-2 flex flex-col gap-1">
{#await data.drivers then drivers}
{#each result.pxxs as pxx, index}
{@const driver = get_by_value(drivers, "id", pxx)}
<div class="flex gap-2">
<span class="w-8">P{(race?.pxx ?? -100) - 3 + index}:</span>
<span
class="badge w-10 p-1 text-center"
style="background: {PXX_COLORS[index]};"
>
{driver?.code}
</span>
</div>
{/each}
{#if result.dnfs.length > 0}
<hr class="border-black" style="border-style: inset;" />
{/if}
{#each result.dnfs as dnf}
{@const driver = get_by_value(drivers, "id", dnf)}
<div class="flex gap-2">
<span class="w-8">DNF:</span>
<span class="badge w-10 p-1 text-center" style="background: {PXX_COLORS[3]};">
{driver?.code}
</span>
</div>
{/each}
{/await}
</div>
</div>
{/each}
{/await}
{/await} {/await}
</div> </div>
<div class="hide-scrollbar flex w-full overflow-x-scroll pb-2"> <div class="hide-scrollbar flex w-full overflow-x-scroll pb-2">
<!-- Not ideal but currentpickedusers contains all users, so we do not need to fetch the users separately --> <!-- Not ideal but currentpickedusers contains all users, so we do not need to fetch the users separately -->
{#each data.currentpickedusers as user} <!-- TODO: Uhhh can I write this await stuff differently??? -->
{@const picks = data.racepicks.filter((pick: RacePick) => pick.user === user.id)} {#await data.currentpickedusers then currentpicked}
{#await data.racepicks then racepicks}
<div
class="card ml-1 mt-2 w-full min-w-12 overflow-hidden py-2 shadow lg:ml-2 {data.user &&
data.user.username === user.username
? 'bg-primary-300'
: ''}"
>
<!-- Avatar + name display at the top -->
<div class="mx-auto flex h-10 w-fit">
{#await data.graphics then graphics}
<LazyImage
src={user.avatar_url ?? get_driver_headshot_template(graphics)}
imgwidth={AVATAR_WIDTH}
imgheight={AVATAR_HEIGHT}
containerstyle="height: 40px; width: 40px;"
imgclass="bg-surface-400 rounded-full"
/>
{/await}
<div
style="height: 40px; line-height: 40px;"
class="ml-2 hidden text-nowrap text-center align-middle lg:block"
>
<!-- TODO: Setting to toggle between username or firstname display -->
{user.username}
</div>
</div>
{#await data.races then races} {#await data.races then races}
{#await data.drivers then drivers} {#await data.drivers then drivers}
{#each data.raceresults as result} {#await data.raceresults then raceresults}
{@const race = get_by_value(races, "id", result.race)} {#each currentpicked as user}
{@const pick = picks.filter((pick: RacePick) => pick.race === race?.id)[0]} {@const picks = racepicks.filter((pick: RacePick) => pick.user === user.id)}
{@const pxxcolor = PXX_COLORS[result.pxxs.indexOf(pick?.pxx ?? "Invalid")]}
{@const dnfcolor =
result.dnfs.indexOf(pick?.dnf ?? "Invalid") >= 0 ? PXX_COLORS[3] : PXX_COLORS[-1]}
{#if pick} <div
<div class="mt-2 h-20 w-full border bg-surface-300 p-1 lg:p-2"> class="card ml-1 mt-2 w-full min-w-12 overflow-hidden py-2 shadow lg:ml-2 {data.user &&
<div class="mx-auto flex h-full w-fit flex-col justify-evenly"> data.user.username === user.username
<span ? 'bg-primary-300'
class="p-1 text-center text-sm rounded-container-token" : ''}"
style="background: {pxxcolor};" >
<!-- Avatar + name display at the top -->
<div class="mx-auto flex h-10 w-fit">
{#await data.graphics then graphics}
<LazyImage
src={user.avatar_url ?? get_driver_headshot_template(graphics)}
imgwidth={AVATAR_WIDTH}
imgheight={AVATAR_HEIGHT}
containerstyle="height: 40px; width: 40px;"
imgclass="bg-surface-400 rounded-full"
/>
{/await}
<div
style="height: 40px; line-height: 40px;"
class="ml-2 hidden text-nowrap text-center align-middle lg:block"
> >
{get_by_value(drivers, "id", pick?.pxx ?? "")?.code} <!-- TODO: Setting to toggle between username or firstname display -->
</span> {user.username}
<span </div>
class="p-1 text-center text-sm rounded-container-token"
style="background: {dnfcolor};"
>
{get_by_value(drivers, "id", pick?.dnf ?? "")?.code}
</span>
</div> </div>
{#each raceresults as result}
{@const race = get_by_value(races, "id", result.race)}
{@const pick = picks.filter((pick: RacePick) => pick.race === race?.id)[0]}
{@const pxxcolor = PXX_COLORS[result.pxxs.indexOf(pick?.pxx ?? "Invalid")]}
{@const dnfcolor =
result.dnfs.indexOf(pick?.dnf ?? "Invalid") >= 0
? PXX_COLORS[3]
: PXX_COLORS[-1]}
{#if pick}
<div class="mt-2 h-20 w-full border bg-surface-300 p-1 lg:p-2">
<div class="mx-auto flex h-full w-fit flex-col justify-evenly">
<span
class="p-1 text-center text-sm w-10 rounded-container-token"
style="background: {pxxcolor};"
>
{get_by_value(drivers, "id", pick?.pxx ?? "")?.code}
</span>
<span
class="p-1 text-center text-sm w-10 rounded-container-token"
style="background: {dnfcolor};"
>
{get_by_value(drivers, "id", pick?.dnf ?? "")?.code}
</span>
</div>
</div>
{:else}
<div class="mt-2 h-20 w-full"></div>
{/if}
{/each}
</div> </div>
{:else} {/each}
<div class="mt-2 h-20 w-full"></div> {/await}
{/if}
{/each}
{/await} {/await}
{/await} {/await}
</div> {/await}
{/each} {/await}
</div> </div>
</div> </div>