Replace 'es-cookie' with 'document.cookie'

This commit is contained in:
0x1eef 2024-03-12 12:34:18 -03:00
parent ff858224d2
commit 043523e48a
4 changed files with 17 additions and 29 deletions

11
package-lock.json generated
View file

@ -10,7 +10,6 @@
],
"dependencies": {
"classnames": "^2.3.2",
"es-cookie": "^1.4.0",
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
@ -1208,11 +1207,6 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/es-cookie": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/es-cookie/-/es-cookie-1.4.0.tgz",
"integrity": "sha512-V4bHxyGBmwwiV+CKTLUPLmwhcutTxGEC5n4HWaUDSnTvkNvfIjkMw8qIVTVgPeNCWojgR5IUzFnGenNvCoKQ5A=="
},
"node_modules/es-module-lexer": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.3.0.tgz",
@ -5315,11 +5309,6 @@
"unbox-primitive": "^1.0.2"
}
},
"es-cookie": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/es-cookie/-/es-cookie-1.4.0.tgz",
"integrity": "sha512-V4bHxyGBmwwiV+CKTLUPLmwhcutTxGEC5n4HWaUDSnTvkNvfIjkMw8qIVTVgPeNCWojgR5IUzFnGenNvCoKQ5A=="
},
"es-module-lexer": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.3.0.tgz",

View file

@ -10,7 +10,6 @@
},
"dependencies": {
"classnames": "^2.3.2",
"es-cookie": "^1.4.0",
"react": "^18.2.0",
"react-dom": "^18.2.0"
},

View file

@ -1,9 +1,9 @@
import React from "react";
import { Select } from "components/Select";
import type { Theme } from "hooks/useTheme";
interface Props {
theme: string;
setTheme: (theme: string) => void;
setTheme: (theme: Theme) => void;
}
export function ThemeSelect({ theme, setTheme }: Props) {

View file

@ -1,23 +1,23 @@
import { useState } from "react";
import { get as getCookie, set as setCookie } from "es-cookie";
type Theme = "blue" | "green";
export type Theme = "blue" | "green";
type Result = [Theme, (t: Theme) => void];
const THEMES: Theme[] = ["blue", "green"];
const DEFAULT_THEME = "blue";
export function useTheme(): [Theme, (t: string) => void] {
const cookie = getCookie("theme");
const [theme, setTheme] = useState<Theme>(
() => THEMES.find(t => t === cookie) || DEFAULT_THEME,
export function useTheme(): Result {
const cookies = Object.fromEntries(
document.cookie.split(";").map(e => e.split("=")),
);
function _setTheme(newTheme: string) {
const matchedTheme = THEMES.find((theme: Theme) => newTheme === theme);
if (matchedTheme) {
setCookie("theme", matchedTheme, { domain: location.host, expires: 365 });
setTheme(matchedTheme);
const [theme, setTheme] = useState<Theme>(
THEMES.find(t => t === cookies.theme) || DEFAULT_THEME,
);
const set = (t: Theme) => {
if (THEMES.includes(t)) {
const maxAge = 3600 * 24 * 90;
document.cookie = `theme=${t}; path=/; max-age=${maxAge}`;
setTheme(t);
}
}
return [theme, _setTheme];
};
return [theme, set];
}