555 lines
22 KiB
Svelte
555 lines
22 KiB
Svelte
<script lang="ts">
|
|
import { onMount } from "svelte";
|
|
import { beforeNavigate } from "$app/navigation";
|
|
import {
|
|
LevelCalculator,
|
|
type LevelCalculatorOutput,
|
|
type Standards,
|
|
} from "@blade-and-brawn/calculator";
|
|
import {
|
|
Activity,
|
|
Attribute,
|
|
Gender,
|
|
lbToKg,
|
|
range,
|
|
type ActivityPerformance,
|
|
type Player,
|
|
} from "@blade-and-brawn/domain";
|
|
import { api } from "$lib/api";
|
|
|
|
type AssessmentRow = NonNullable<
|
|
Awaited<ReturnType<typeof api.assessments.me.get>>["data"]
|
|
>[number];
|
|
|
|
interface CalcData {
|
|
key: string;
|
|
id?: string;
|
|
levels?: LevelCalculatorOutput;
|
|
player: Player;
|
|
activityPerformances: ActivityPerformance[];
|
|
/** JSON snapshot of {player, activityPerformances} as of the last successful save/load. "" means never saved. */
|
|
savedSnapshot: string;
|
|
/** whether the metrics/performance editing panel is open — collapsed by default, since levels are the primary thing being compared */
|
|
expanded?: boolean;
|
|
saving?: boolean;
|
|
saveError?: string;
|
|
deleting?: boolean;
|
|
deleteError?: string;
|
|
}
|
|
|
|
function snapshotOf(
|
|
player: Player,
|
|
activityPerformances: ActivityPerformance[],
|
|
): string {
|
|
return JSON.stringify({ player, activityPerformances });
|
|
}
|
|
|
|
function isDirty(calculation: CalcData): boolean {
|
|
return (
|
|
snapshotOf(
|
|
calculation.player,
|
|
calculation.activityPerformances,
|
|
) !== calculation.savedSnapshot
|
|
);
|
|
}
|
|
|
|
interface Props {
|
|
allStandards: Standards;
|
|
}
|
|
|
|
const { allStandards }: Props = $props();
|
|
|
|
const levelCalculator = $derived(new LevelCalculator(allStandards));
|
|
|
|
// toggle + name + overall + one column per attribute + actions
|
|
const TABLE_COLUMNS = 4 + Object.keys(Attribute).length;
|
|
|
|
let calculations = $state<CalcData[]>([]);
|
|
let loading = $state(true);
|
|
let loadError = $state<string | null>(null);
|
|
|
|
const PERF_COLUMN = {
|
|
[Activity.BackSquat]: "perf_back_squat",
|
|
[Activity.Deadlift]: "perf_deadlift",
|
|
[Activity.BenchPress]: "perf_bench_press",
|
|
[Activity.Run]: "perf_run",
|
|
[Activity.BroadJump]: "perf_broad_jump",
|
|
[Activity.ConeDrill]: "perf_cone_drill",
|
|
} as const satisfies Record<Activity, keyof AssessmentRow>;
|
|
|
|
function assessmentToCalc(assessment: AssessmentRow): CalcData {
|
|
const player: Player = {
|
|
name: assessment.name,
|
|
metrics: {
|
|
age: assessment.age,
|
|
weight: assessment.weight,
|
|
gender: assessment.gender as Gender,
|
|
},
|
|
};
|
|
const activityPerformances = Object.values(Activity).map((a) => ({
|
|
activity: a,
|
|
performance: (assessment[PERF_COLUMN[a]] as number | null) ?? 0,
|
|
}));
|
|
|
|
return {
|
|
key: crypto.randomUUID(),
|
|
id: assessment.id,
|
|
player,
|
|
activityPerformances,
|
|
savedSnapshot: snapshotOf(player, activityPerformances),
|
|
};
|
|
}
|
|
|
|
function errorMessage(err: unknown): string {
|
|
const value = (err as { value?: { error?: string } })?.value;
|
|
return (
|
|
value?.error ??
|
|
(err instanceof Error ? err.message : "Unknown error")
|
|
);
|
|
}
|
|
|
|
async function loadAssessments() {
|
|
loading = true;
|
|
loadError = null;
|
|
try {
|
|
const res = await api.assessments.me.get();
|
|
if (res.error) throw res.error;
|
|
calculations = (res.data ?? []).map(assessmentToCalc);
|
|
} catch (err) {
|
|
loadError = errorMessage(err);
|
|
} finally {
|
|
loading = false;
|
|
}
|
|
}
|
|
|
|
async function saveCalculation(calculation: CalcData) {
|
|
calculation.saving = true;
|
|
calculation.saveError = undefined;
|
|
try {
|
|
if (calculation.id) {
|
|
const res = await api
|
|
.assessments({ id: calculation.id })
|
|
.put({
|
|
player: calculation.player,
|
|
activityPerformances: calculation.activityPerformances,
|
|
});
|
|
if (res.error) throw res.error;
|
|
} else {
|
|
const res = await api.assessments.me.post({
|
|
player: calculation.player,
|
|
activityPerformances: calculation.activityPerformances,
|
|
});
|
|
if (res.error) throw res.error;
|
|
calculation.id = res.data?.id;
|
|
}
|
|
calculation.savedSnapshot = snapshotOf(
|
|
calculation.player,
|
|
calculation.activityPerformances,
|
|
);
|
|
} catch (err) {
|
|
calculation.saveError = errorMessage(err);
|
|
} finally {
|
|
calculation.saving = false;
|
|
}
|
|
}
|
|
|
|
async function deleteCalculation(calculation: CalcData, index: number) {
|
|
if (!calculation.id) {
|
|
calculations.splice(index, 1);
|
|
return;
|
|
}
|
|
|
|
calculation.deleting = true;
|
|
calculation.deleteError = undefined;
|
|
try {
|
|
const res = await api.assessments.me({ id: calculation.id }).delete();
|
|
if (res.error) throw res.error;
|
|
calculations.splice(index, 1);
|
|
} catch (err) {
|
|
calculation.deleteError = errorMessage(err);
|
|
} finally {
|
|
calculation.deleting = false;
|
|
}
|
|
}
|
|
|
|
onMount(loadAssessments);
|
|
|
|
beforeNavigate((navigation) => {
|
|
if (!calculations.some(isDirty)) return;
|
|
|
|
if (navigation.type === "leave") {
|
|
// triggers the browser's native "leave site?" confirmation
|
|
navigation.cancel();
|
|
return;
|
|
}
|
|
|
|
if (
|
|
!confirm(
|
|
"You have unsaved player changes that will be lost. Leave anyway?",
|
|
)
|
|
) {
|
|
navigation.cancel();
|
|
}
|
|
});
|
|
|
|
$effect(() => {
|
|
for (const calculation of calculations) {
|
|
calculation.levels = levelCalculator.calculate(
|
|
calculation.player,
|
|
calculation.activityPerformances,
|
|
);
|
|
}
|
|
});
|
|
|
|
const createCalculation = function (name: string): CalcData {
|
|
return {
|
|
key: crypto.randomUUID(),
|
|
savedSnapshot: "", // never saved — always dirty until the first save
|
|
expanded: true, // a brand new player needs its details filled in right away
|
|
player: {
|
|
name: name,
|
|
metrics: {
|
|
age: 18,
|
|
weight: lbToKg(180),
|
|
gender: Gender.Male,
|
|
},
|
|
},
|
|
activityPerformances: Object.values(Activity).map((a) => ({
|
|
activity: a,
|
|
performance: 0,
|
|
})),
|
|
};
|
|
};
|
|
|
|
const formatMs = (ms: number) => {
|
|
const total = Math.floor(ms / 1000);
|
|
const m = Math.floor(total / 60);
|
|
const s = total % 60;
|
|
return `${m}m ${s}s`;
|
|
};
|
|
const inchesToFeetInches = (inches: number) => {
|
|
const ft = Math.floor(inches / 12);
|
|
const rem = inches - ft * 12;
|
|
const whole = Math.floor(rem);
|
|
const isHalf = Math.abs(rem - whole - 0.5) < 1e-9;
|
|
const inchLabel = isHalf ? `${whole}½` : `${whole}`;
|
|
return `${ft}' ${inchLabel}"`;
|
|
};
|
|
|
|
const formatSeconds = (ms: number) => (ms / 1000).toFixed(2) + " seconds";
|
|
|
|
const performanceOptionsFromActivity = function (activity: Activity) {
|
|
const options: { name: string; value: number }[] = [];
|
|
switch (activity) {
|
|
case Activity.BackSquat:
|
|
case Activity.Deadlift:
|
|
case Activity.BenchPress:
|
|
for (let i = 0; i < 600; ++i) {
|
|
options.push({
|
|
name: String(i) + " lb",
|
|
value: lbToKg(i),
|
|
});
|
|
}
|
|
break;
|
|
|
|
case Activity.Run: {
|
|
const MAX_MIN = 30;
|
|
for (let ms = 0; ms <= MAX_MIN * 60_000; ms += 1_000) {
|
|
options.push({ name: formatMs(ms), value: ms });
|
|
}
|
|
break;
|
|
}
|
|
|
|
case Activity.BroadJump: {
|
|
const MAX_INCHES = 15 * 12 + 5;
|
|
for (let halfStep = 0; halfStep <= MAX_INCHES * 2; halfStep++) {
|
|
const inches = halfStep / 2;
|
|
options.push({
|
|
name: inchesToFeetInches(inches),
|
|
value: Number((inches * 2.54).toFixed(1)),
|
|
});
|
|
}
|
|
break;
|
|
}
|
|
|
|
case Activity.ConeDrill: {
|
|
const MIN_MS = 5_000;
|
|
const MAX_MS = 20_000;
|
|
for (let ms = MIN_MS; ms <= MAX_MS; ms += 10) {
|
|
options.push({
|
|
name: formatSeconds(ms),
|
|
value: ms,
|
|
});
|
|
}
|
|
break;
|
|
}
|
|
}
|
|
return options;
|
|
};
|
|
</script>
|
|
|
|
<div class="mt-5 mb-5 flex w-full items-center">
|
|
<button
|
|
onclick={loadAssessments}
|
|
class="btn btn-secondary btn-sm"
|
|
disabled={loading}
|
|
>
|
|
{loading ? "Refreshing..." : "Refresh"}
|
|
</button>
|
|
|
|
<div class="ml-auto">
|
|
<button
|
|
onclick={() =>
|
|
calculations.push(
|
|
createCalculation(String(calculations.length)),
|
|
)}
|
|
class="btn btn-primary">New</button
|
|
>
|
|
</div>
|
|
</div>
|
|
|
|
{#if loadError}
|
|
<div role="alert" class="alert alert-error w-full mb-4">
|
|
<span>{loadError}</span>
|
|
</div>
|
|
{/if}
|
|
|
|
<div class="w-full overflow-x-auto">
|
|
<table class="table">
|
|
<thead>
|
|
<tr>
|
|
<th class="w-8"></th>
|
|
<th>Name</th>
|
|
<th>Overall</th>
|
|
{#each Object.values(Attribute) as attribute (attribute)}
|
|
<th>{attribute}</th>
|
|
{/each}
|
|
<th class="w-40"></th>
|
|
</tr>
|
|
</thead>
|
|
<tbody>
|
|
{#each calculations as calculation, index (calculation.key)}
|
|
<tr class="hover:bg-base-300">
|
|
<td>
|
|
<button
|
|
onclick={() =>
|
|
(calculation.expanded = !calculation.expanded)}
|
|
class="btn btn-ghost btn-xs"
|
|
aria-label={calculation.expanded
|
|
? "Collapse details"
|
|
: "Expand details"}
|
|
>
|
|
{calculation.expanded ? "▾" : "▸"}
|
|
</button>
|
|
</td>
|
|
<td>
|
|
<div class="flex items-center gap-2">
|
|
<input
|
|
class="input input-bordered input-sm w-full min-w-32"
|
|
type="text"
|
|
bind:value={calculation.player.name}
|
|
placeholder="Player name"
|
|
/>
|
|
{#if isDirty(calculation)}
|
|
<div class="badge badge-warning badge-xs shrink-0">
|
|
Unsaved
|
|
</div>
|
|
{/if}
|
|
</div>
|
|
</td>
|
|
<td>
|
|
<div class="badge badge-neutral font-semibold">
|
|
{calculation?.levels?.player ?? "N/A"}
|
|
</div>
|
|
</td>
|
|
{#each Object.values(Attribute) as attribute (attribute)}
|
|
<td>
|
|
<div class="badge badge-ghost">
|
|
{calculation?.levels?.attributes?.[
|
|
attribute
|
|
] ?? "N/A"}
|
|
</div>
|
|
</td>
|
|
{/each}
|
|
<td>
|
|
<div class="flex gap-2 justify-end">
|
|
<button
|
|
onclick={() => saveCalculation(calculation)}
|
|
disabled={calculation.saving ||
|
|
!isDirty(calculation)}
|
|
class="btn btn-primary btn-xs"
|
|
>
|
|
{calculation.saving ? "Saving..." : "Save"}
|
|
</button>
|
|
<button
|
|
onclick={() =>
|
|
confirm(
|
|
`Remove ${calculation.player.name}?`,
|
|
) && deleteCalculation(calculation, index)}
|
|
disabled={calculation.deleting}
|
|
class="btn btn-error btn-xs"
|
|
>
|
|
{calculation.deleting ? "..." : "Delete"}
|
|
</button>
|
|
</div>
|
|
</td>
|
|
</tr>
|
|
{#if calculation.expanded}
|
|
<tr>
|
|
<td colspan={TABLE_COLUMNS}>
|
|
<div
|
|
class="bg-base-200/60 rounded-lg p-4 flex flex-col gap-4"
|
|
>
|
|
<fieldset
|
|
class="fieldset"
|
|
onchange={() =>
|
|
(calculation.levels =
|
|
levelCalculator.calculate(
|
|
calculation.player,
|
|
calculation.activityPerformances,
|
|
))}
|
|
>
|
|
<legend
|
|
class="fieldset-legend text-xs font-semibold opacity-70"
|
|
>
|
|
Metrics
|
|
</legend>
|
|
<div class="grid grid-cols-1 md:grid-cols-3 gap-3">
|
|
<label class="form-control">
|
|
<span class="label mb-1 text-xs"
|
|
>Gender</span
|
|
>
|
|
<select
|
|
class="select select-bordered select-sm w-full"
|
|
bind:value={
|
|
calculation.player.metrics
|
|
.gender
|
|
}
|
|
>
|
|
{#each Object.values(Gender) as gender (gender)}
|
|
<option value={gender}
|
|
>{gender}</option
|
|
>
|
|
{/each}
|
|
</select>
|
|
</label>
|
|
|
|
<label class="form-control">
|
|
<span class="label mb-1 text-xs"
|
|
>Age</span
|
|
>
|
|
<input
|
|
class="input input-bordered input-sm w-full"
|
|
type="number"
|
|
min="1"
|
|
max="100"
|
|
step="1"
|
|
bind:value={
|
|
calculation.player.metrics
|
|
.age
|
|
}
|
|
/>
|
|
</label>
|
|
|
|
<label class="form-control">
|
|
<span class="label mb-1 text-xs"
|
|
>Weight</span
|
|
>
|
|
<select
|
|
class="select select-bordered select-sm w-full"
|
|
bind:value={
|
|
calculation.player.metrics
|
|
.weight
|
|
}
|
|
>
|
|
{#each range(400) as weight (weight)}
|
|
<option
|
|
value={lbToKg(weight)}
|
|
>{weight}</option
|
|
>
|
|
{/each}
|
|
</select>
|
|
</label>
|
|
</div>
|
|
</fieldset>
|
|
|
|
<fieldset
|
|
class="fieldset"
|
|
onchange={() =>
|
|
(calculation.levels =
|
|
levelCalculator.calculate(
|
|
calculation.player,
|
|
calculation.activityPerformances,
|
|
))}
|
|
>
|
|
<legend
|
|
class="fieldset-legend text-xs font-semibold opacity-70"
|
|
>
|
|
Activity performances
|
|
</legend>
|
|
<div class="grid grid-cols-2 md:grid-cols-3 gap-3">
|
|
{#each calculation.activityPerformances as activityPerformance (activityPerformance.activity)}
|
|
<label
|
|
class="form-control space-y-1"
|
|
>
|
|
<span
|
|
class="label mb-1 text-xs"
|
|
>
|
|
{activityPerformance.activity}
|
|
</span>
|
|
<select
|
|
class="select select-bordered select-sm w-full"
|
|
bind:value={
|
|
activityPerformance.performance
|
|
}
|
|
>
|
|
{#each performanceOptionsFromActivity(activityPerformance.activity) as option (option.value)}
|
|
<option
|
|
value={option.value}
|
|
>{option.name}</option
|
|
>
|
|
{/each}
|
|
</select>
|
|
</label>
|
|
{/each}
|
|
</div>
|
|
</fieldset>
|
|
|
|
{#if calculation.saveError}
|
|
<div
|
|
role="alert"
|
|
class="alert alert-error alert-sm"
|
|
>
|
|
<span class="text-xs"
|
|
>{calculation.saveError}</span
|
|
>
|
|
</div>
|
|
{/if}
|
|
{#if calculation.deleteError}
|
|
<div
|
|
role="alert"
|
|
class="alert alert-error alert-sm"
|
|
>
|
|
<span class="text-xs"
|
|
>{calculation.deleteError}</span
|
|
>
|
|
</div>
|
|
{/if}
|
|
</div>
|
|
</td>
|
|
</tr>
|
|
{/if}
|
|
{:else}
|
|
<tr>
|
|
<td
|
|
colspan={TABLE_COLUMNS}
|
|
class="text-center opacity-60"
|
|
>
|
|
{loading ? "Loading..." : "No players yet"}
|
|
</td>
|
|
</tr>
|
|
{/each}
|
|
</tbody>
|
|
</table>
|
|
</div>
|