From 9e16bf44ebee93e13ee077a67a7bcb21b285f298 Mon Sep 17 00:00:00 2001
From: Fuwn <contact@fuwn.me>
Date: Wed, 3 Apr 2024 16:40:41 -0700
Subject: feat(badge): hover tilt

---
 src/lib/FallbackBadge.svelte | 22 +++++++++++++++++++++-
 1 file changed, 21 insertions(+), 1 deletion(-)

(limited to 'src/lib/FallbackBadge.svelte')

diff --git a/src/lib/FallbackBadge.svelte b/src/lib/FallbackBadge.svelte
index faa021d4..4cc739d3 100644
--- a/src/lib/FallbackBadge.svelte
+++ b/src/lib/FallbackBadge.svelte
@@ -14,6 +14,9 @@
 	export let badge: Badge;
 
 	let replaceCount = 0;
+	let badgeReference: HTMLImageElement;
+	let mouseX = 0;
+	let mouseY = 0;
 
 	const delayedReplace = (event: Event, image: string | undefined) => {
 		if (replaceCount >= maxReplaceCount) return;
@@ -24,6 +27,19 @@
 			replaceCount += 1;
 		}, replaceDelay);
 	};
+
+	const handleMouseMove = (event: MouseEvent) => {
+		const boundingRectangle = badgeReference.getBoundingClientRect();
+		const factor = 1;
+
+		mouseX = -(event.clientX - boundingRectangle.left - boundingRectangle.width / 2) * factor;
+		mouseY = -(event.clientY - boundingRectangle.top - boundingRectangle.height / 2) * factor;
+	};
+
+	const handleMouseLeave = () => {
+		mouseX = 0;
+		mouseY = 0;
+	};
 </script>
 
 {#if replaceCount < maxReplaceCount}
@@ -31,7 +47,7 @@
 		href={badge.post}
 		target="_blank"
 		id={`badge-${badge.id}`}
-		class="badge"
+		class="badge-container badge"
 		title={`${badge.time ? $locale().dateFormatter(databaseTimeToDate(badge.time)) : ''}${
 			badge.description ? `\n${badge.description}` : ''
 		}`}
@@ -42,6 +58,10 @@
 			alt={alternative}
 			loading="lazy"
 			class="badge"
+			bind:this={badgeReference}
+			on:mousemove={handleMouseMove}
+			on:mouseleave={handleMouseLeave}
+			style="transform: perspective(1000px) rotateX({mouseY / 10}deg) rotateY({-mouseX / 10}deg);"
 			on:error={(e) => delayedReplace(e, fallback)}
 		/>
 	</a>
-- 
cgit v1.2.3

