From a2289f6181e75df6fccd146338ece11692f8f730 Mon Sep 17 00:00:00 2001 From: Timothy Armes Date: Tue, 28 Nov 2023 17:44:14 +0100 Subject: [PATCH] Persist manual ELO form to local storage Persist manual ELO form to local storage --- src/app/[locale]/elo/ManualEloForm.tsx | 42 ++++++++++-- src/hooks/useFormPersist.ts | 93 ++++++++++++++++++++++++++ src/messages/en.json | 1 + src/messages/fr.json | 1 + 4 files changed, 131 insertions(+), 6 deletions(-) create mode 100644 src/hooks/useFormPersist.ts diff --git a/src/app/[locale]/elo/ManualEloForm.tsx b/src/app/[locale]/elo/ManualEloForm.tsx index 6696101..49a4378 100644 --- a/src/app/[locale]/elo/ManualEloForm.tsx +++ b/src/app/[locale]/elo/ManualEloForm.tsx @@ -1,7 +1,7 @@ "use client"; import { zodResolver } from "@hookform/resolvers/zod"; -import { last } from "lodash"; +import { isEmpty, isNil, last } from "lodash"; import { useTranslations } from "next-intl"; import { FormProvider, useFieldArray, useForm } from "react-hook-form"; import { IoAdd, IoCloseOutline } from "react-icons/io5"; @@ -11,12 +11,13 @@ import { z } from "zod"; import { RadioGroupField } from "@/components/form/RadioGroupField"; import { SelectField } from "@/components/form/SelectField"; import { TextField } from "@/components/form/TextField"; +import useFormPersist from "@/hooks/useFormPersist"; import { getNewRating } from "@/utils/eloCalculator"; import { KFactor } from "./KFactor"; const resultsSchema = z.object({ - currentElo: z.number().int().positive(), + currentElo: z.number().int().positive().nullish(), kFactor: z.enum(["40", "30", "20", "15", "10"]), games: z.array( z.object({ @@ -40,6 +41,7 @@ export const ManualEloForm = () => { const form = useForm({ resolver: zodResolver(resultsSchema), defaultValues: { + currentElo: null, kFactor: "20", games: [{}], }, @@ -54,6 +56,12 @@ export const ManualEloForm = () => { name: "games", }); + useFormPersist("manualElo", { + watch: form.watch, + setValue: form.setValue, + storage: window.localStorage, + }); + const onSubmit = async (data: EloFormValues) => {}; const [currentElo, kFactor, games] = form.watch([ @@ -62,6 +70,13 @@ export const ManualEloForm = () => { "games", ]); + const isDefault = + isEmpty(currentElo) && + kFactor === "20" && + games?.length === 1 && + (isEmpty(games[0]) || + (isEmpty(games[0]?.opponentElo) && isEmpty(games[0]?.result))); + type Deltas = { rating: number; deltas: { rating: number; delta: number | undefined }[]; @@ -70,7 +85,11 @@ export const ManualEloForm = () => { const calculations = !Number.isNaN(currentElo) ? (games ?? []).reduce( (acc, game) => { - if (!Number.isNaN(game?.opponentElo) && game?.result) { + if ( + !isNil(game?.opponentElo) && + !Number.isNaN(game?.opponentElo) && + game?.result + ) { const result = game?.result === "win" ? 1 : game?.result === "loss" ? 0 : 0.5; @@ -136,8 +155,8 @@ export const ManualEloForm = () => {
{gameFields.map((game, i) => { return ( -
-
+
+
{
)} -
+
+ {!isDefault && ( + + )}