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 }) => {
const { user, isUSRegion, wsURL } = locals;
return {
user: user || undefined,
isUSRegion,
cookieConsent: cookies?.get("cookie-consent"),
themeMode: cookies?.get("theme-mode"),
wsURL,
};
};

View File

@ -240,12 +240,32 @@
isAfterMarketClose.set(isAfterMarketCloseValue);
};
function handleModeChange() {
setMode(data?.themeMode);
async function handleModeChange() {
if ($mode === "light") {
setMode("dark");
} else {
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>
@ -1238,7 +1258,7 @@
-->
<slot />
<ModeWatcher defaultMode={"dark"}/>
<ModeWatcher defaultMode="dark"/>
<Toaster position="top-center" />
{#if Cookie && $showCookieConsent === true}
<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;