From b849c7a2a989eb9921ac800b0554e64a40c1ec4f Mon Sep 17 00:00:00 2001
From: Fuwn <contact@fuwn.me>
Date: Sun, 3 Dec 2023 20:43:47 -0800
Subject: feat(birthdays): reactive url

---
 src/lib/Tools/CharacterBirthdays.svelte | 26 +++++++++++++++++++++++---
 1 file changed, 23 insertions(+), 3 deletions(-)

(limited to 'src/lib/Tools/CharacterBirthdays.svelte')

diff --git a/src/lib/Tools/CharacterBirthdays.svelte b/src/lib/Tools/CharacterBirthdays.svelte
index 30f00405..f910f7c4 100644
--- a/src/lib/Tools/CharacterBirthdays.svelte
+++ b/src/lib/Tools/CharacterBirthdays.svelte
@@ -1,8 +1,9 @@
 <script lang="ts">
+	import { browser } from '$app/environment';
+	import { page } from '$app/stores';
 	import { ACDBBirthdays, type ACDBBirthday } from '$lib/Birthday/ACDB';
 	import { aniSearchBirthdays, type aniSearchBirthday } from '$lib/Birthday/aniSearch';
 	import Error from '$lib/Error.svelte';
-	import { onMount } from 'svelte';
 
 	interface Birthday {
 		name: string;
@@ -10,12 +11,31 @@
 		origin?: string;
 	}
 
+	const parseOrDefault = (parameter: string, fallback: number): number =>
+		browser && urlParameters?.size !== 0
+			? parseInt(urlParameters?.get(parameter) || '', 10) || fallback
+			: fallback;
+
+	const urlParameters = browser ? new URLSearchParams(window.location.search) : null;
 	let date = new Date();
-	let month = date.getMonth() + 1;
-	let day = date.getDate();
+	let month = parseOrDefault('month', date.getMonth() + 1);
+	let day = parseOrDefault('day', date.getDate());
 	let anisearchBirthdays: Promise<aniSearchBirthday[]>;
 	let acdbBirthdays: Promise<ACDBBirthday[]>;
 
+	$: {
+		month = Math.min(month, 12);
+		month = Math.max(month, 1);
+		day = Math.min(day, new Date(0, month, 0).getDate());
+		day = Math.max(day, 1);
+
+		if (browser) {
+			$page.url.searchParams.set('month', month.toString());
+			$page.url.searchParams.set('day', day.toString());
+			history.replaceState(null, '', `?${$page.url.searchParams.toString()}`);
+		}
+	}
+
 	$: {
 		anisearchBirthdays = aniSearchBirthdays(month, day);
 		acdbBirthdays = ACDBBirthdays(month, day);
-- 
cgit v1.2.3

