add theme mode cookie

This commit is contained in:
MuslemRahimi 2025-03-12 13:10:54 +01:00
parent 14d40e4c1b
commit af4043624b
3 changed files with 47 additions and 2 deletions

View File

@ -1,9 +1,11 @@
export const load = ({ locals, cookies }) => { export const load = ({ locals, cookies }) => {
const { user, isUSRegion, wsURL } = locals; const { user, isUSRegion, wsURL } = locals;
return { return {
user: user || undefined, user: user || undefined,
isUSRegion, isUSRegion,
cookieConsent: cookies?.get("cookie-consent"), cookieConsent: cookies?.get("cookie-consent"),
themeMode: cookies?.get("theme-mode"),
wsURL, wsURL,
}; };
}; };

View File

@ -240,12 +240,32 @@
isAfterMarketClose.set(isAfterMarketCloseValue); isAfterMarketClose.set(isAfterMarketCloseValue);
}; };
function handleModeChange() {
setMode(data?.themeMode);
async function handleModeChange() {
if ($mode === "light") { if ($mode === "light") {
setMode("dark"); setMode("dark");
} else { } else {
setMode("light"); setMode("light");
} }
const postData = {
mode: $mode,
};
const response = await fetch("/api/theme-mode", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(postData),
}); // make a POST request to the server with the FormData object
const output = await response.json();
console.log(output)
} }
</script> </script>
@ -1238,7 +1258,7 @@
--> -->
<slot /> <slot />
<ModeWatcher defaultMode={"dark"}/> <ModeWatcher defaultMode="dark"/>
<Toaster position="top-center" /> <Toaster position="top-center" />
{#if Cookie && $showCookieConsent === true} {#if Cookie && $showCookieConsent === true}
<Cookie /> <Cookie />

View File

@ -0,0 +1,23 @@
import type { RequestHandler } from "./$types";
export const POST = (async ({ request, cookies }) => {
let output = "error";
const data = await request.json();
const mode = data?.mode;
try {
cookies.set("theme-mode", mode, {
httpOnly: true,
sameSite: "lax",
secure: true,
path: "/",
maxAge: 60 * 60 * 24 * 365, // 1 Year consent
});
output = "success";
} catch (e) {
console.log(e);
}
return new Response(JSON.stringify(output));
}) satisfies RequestHandler;