1
mirror of https://github.com/jakejarvis/jarv.is.git synced 2025-04-26 13:18:26 -04:00

use the excellent next-themes module

This commit is contained in:
Jake Jarvis 2022-01-06 10:08:24 -05:00
parent 6b756a54c1
commit 3394cac5de
Signed by: jake
GPG Key ID: 2B0C9CF251E69A39
11 changed files with 36 additions and 97 deletions

View File

@ -1,4 +1,5 @@
import { useState } from "react";
import { useTheme } from "next-themes";
import HCaptcha from "@hcaptcha/react-hcaptcha";
import { CheckOcticon, XOcticon } from "../icons/octicons";
import { SendIcon } from "../icons";
@ -6,6 +7,7 @@ import { SendIcon } from "../icons";
import styles from "./ContactForm.module.scss";
const ContactForm = () => {
const { resolvedTheme } = useTheme();
// status/feedback:
const [status, setStatus] = useState({ success: false, message: "" });
// keep track of fetch:
@ -106,6 +108,7 @@ const ContactForm = () => {
<HCaptcha
sitekey={process.env.NEXT_PUBLIC_HCAPTCHA_SITE_KEY}
size="normal"
theme={resolvedTheme === "dark" ? "dark" : "light"}
onVerify={() => true} // this is allegedly optional but a function undefined error is thrown without it
/>
</div>

View File

@ -1,6 +1,7 @@
import dynamic from "next/dynamic";
import Link from "next/link";
import Image from "next/image";
import { useTheme } from "next-themes";
import type { LinkProps } from "next/link";
import type { ImageProps } from "next/image";
@ -57,6 +58,7 @@ const CustomCode = (props: any) => {
const CustomTweet = (props: { id: string }) => {
const TweetEmbed = dynamic(() => import("react-tweet-embed"));
const { resolvedTheme } = useTheme();
return (
<TweetEmbed
@ -64,6 +66,7 @@ const CustomTweet = (props: { id: string }) => {
options={{
dnt: true,
align: "center",
theme: resolvedTheme === "dark" ? "dark" : "light",
}}
/>
);

View File

@ -1,5 +1,5 @@
import dynamic from "next/dynamic";
import Link from "next/link";
import ThemeToggle from "./ThemeToggle";
import { HomeIcon, NotesIcon, ProjectsIcon, ContactIcon } from "../icons";
import styles from "./Menu.module.scss";
@ -27,9 +27,6 @@ const links = [
},
];
// ensure the theme toggle isn't evaluated server-side
const ThemeToggle = dynamic(() => import("./ThemeToggle"), { ssr: false });
const Menu = () => (
<ul className={styles.menu}>
{links.map((link, index) => (

View File

@ -1,64 +1,21 @@
import { useState, useEffect, useCallback } from "react";
import * as config from "../../lib/config";
import { useState, useEffect } from "react";
import { useTheme } from "next-themes";
import { BulbOffIcon, BulbOnIcon } from "../icons";
// store preference in local storage
const storageKey = "dark_mode";
const getDarkPref = () => localStorage.getItem(storageKey);
const setDarkPref = (pref: boolean) => localStorage.setItem(storageKey, pref as unknown as string);
// use the `<html data-theme="...">` as a hint to what the theme was set to outside of the button component
// TODO: there's probably (definitely) a cleaner way to do this, maybe with react hooks..?
const isDark = () => document.documentElement.getAttribute("data-theme") === "dark";
// sets appropriate `<html data-theme="...">`, `<meta name="color-scheme" ...>`, and color-scheme CSS property
const updateDOM = (dark: boolean) => {
document.documentElement.setAttribute("data-theme", dark ? "dark" : "light");
document.documentElement.style.colorScheme = dark ? "dark" : "light";
document.head
.querySelector("meta[name=theme-color]")
?.setAttribute("content", dark ? config.themeColorDark : config.themeColorLight);
};
const ThemeToggle = ({ className = "" }) => {
// sync button up with theme and preference states after initialization
const [dark, setDark] = useState(isDark());
const [saved, setSaved] = useState(!!getDarkPref());
const [mounted, setMounted] = useState(false);
const { resolvedTheme, setTheme } = useTheme();
// real-time switching between modes based on user's system if preference isn't set (and it's supported by OS/browser)
const matchCallback = useCallback((e) => setDark(e.matches), []);
useEffect(() => {
try {
// https://drafts.csswg.org/mediaqueries-5/#prefers-color-scheme
const matcher = window.matchMedia("(prefers-color-scheme: dark)");
// only listen to OS if the user hasn't specified a preference
if (!saved) {
matcher.addEventListener("change", matchCallback, true);
}
// cleanup and stop listening if/when preference is explicitly set
return () => matcher.removeEventListener("change", matchCallback, true);
} catch (e) {} // eslint-disable-line no-empty
}, [saved, matchCallback]);
// sets appropriate HTML when mode changes
useEffect(() => updateDOM(dark), [dark]);
const handleToggle = () => {
// only update the local storage preference if the user explicitly presses the lightbulb
setDarkPref(!dark);
setSaved(true);
// set theme to the opposite of current theme
setDark(!dark);
};
// avoid hydration mismatch:
// https://github.com/pacocoursey/next-themes#avoid-hydration-mismatch
useEffect(() => setMounted(true), []);
if (!mounted) return null;
return (
<button
onClick={handleToggle}
title={dark ? "Toggle Light Mode" : "Toggle Dark Mode"}
aria-label={dark ? "Toggle Light Mode" : "Toggle Dark Mode"}
onClick={() => setTheme(resolvedTheme === "dark" ? "light" : "dark")}
title={resolvedTheme === "dark" ? "Toggle Light Mode" : "Toggle Dark Mode"}
aria-hidden={true}
style={{
border: 0,
padding: 0,
@ -66,7 +23,11 @@ const ThemeToggle = ({ className = "" }) => {
cursor: "pointer",
}}
>
{dark ? <BulbOffIcon className={`icon ${className}`} /> : <BulbOnIcon className={`icon ${className}`} />}
{resolvedTheme === "dark" ? (
<BulbOffIcon className={`icon ${className}`} />
) : (
<BulbOnIcon className={`icon ${className}`} />
)}
</button>
);
};

View File

@ -5,12 +5,10 @@ module.exports = {
siteDomain: "jarv.is",
siteLocale: "en_us",
baseUrl: process.env.BASE_URL || "https://jarv.is",
onionDomain: "jarvis2i2vp4j4tbxjogsnqdemnte5xhzyi7hziiyzxwge3hzmh57zad.onion",
onionDomain: "http://jarvis2i2vp4j4tbxjogsnqdemnte5xhzyi7hziiyzxwge3hzmh57zad.onion",
shortDescription: "Front-End Web Developer in Boston, MA",
longDescription:
"Hi there! I'm a frontend web developer based in Boston, Massachusetts specializing in the JAMstack, modern JavaScript frameworks, and progressive web apps.",
themeColorLight: "#fcfcfc",
themeColorDark: "#252525",
githubRepo: "jakejarvis/jarv.is",
facebookAppId: "3357248167622283",
monetization: "$ilp.uphold.com/BJp6d2FrEB69",

View File

@ -1,14 +0,0 @@
import { themeColorLight, themeColorDark } from "./config";
// Inlined JS in pages/_app.tsx to restore these light/dark theme settings ASAP:
// `<html data-theme="...">`, `<meta name="color-scheme" ...>`, and color-scheme CSS property.
export const restoreThemeScript = `
try {
var pref = localStorage.getItem("dark_mode"),
dark = pref === "true" || (!pref && window.matchMedia("(prefers-color-scheme: dark)").matches),
theme = dark ? "dark" : "light";
document.documentElement.setAttribute("data-theme", theme);
document.documentElement.style.colorScheme = theme;
document.head.querySelector('meta[name="theme-color"]').setAttribute("content", dark ? "${themeColorDark}" : "${themeColorLight}");
} catch (e) {}
`.trim();

View File

@ -70,16 +70,7 @@ module.exports = (phase, { defaultConfig }) => {
headers: [
{
key: "Onion-Location",
value: `http://${config.onionDomain}/:path*`,
},
{
// https://developer.chrome.com/blog/floc/#how-can-websites-opt-out-of-the-floc-computation
key: "Permissions-Policy",
value: "interest-cohort=()",
},
{
key: "Referrer-Policy",
value: "no-referrer-when-downgrade",
value: `${config.onionDomain}/:path*`,
},
],
},

View File

@ -48,6 +48,7 @@
"next-compose-plugins": "^2.2.1",
"next-mdx-remote": "^3.0.8",
"next-seo": "^4.28.1",
"next-themes": "^0.0.15",
"node-fetch": "^3.1.0",
"p-retry": "^5.0.0",
"prop-types": "^15.8.1",

View File

@ -1,9 +1,8 @@
import { useEffect } from "react";
import { useRouter } from "next/router";
import Script from "next/script";
import { ThemeProvider } from "next-themes";
import { DefaultSeo, SocialProfileJsonLd } from "next-seo";
import * as Fathom from "fathom-client";
import { restoreThemeScript } from "../lib/restore-theme";
import * as config from "../lib/config";
import type { AppProps } from "next/app";
@ -51,10 +50,6 @@ const App = ({ Component, pageProps }: AppProps) => {
return (
<>
<Script id="restore_theme" strategy="afterInteractive">
{restoreThemeScript}
</Script>
{/* @ts-ignore */}
<DefaultSeo
defaultTitle={`${config.siteName} ${config.shortDescription}`}
@ -186,7 +181,9 @@ const App = ({ Component, pageProps }: AppProps) => {
]}
/>
<Component {...pageProps} />
<ThemeProvider>
<Component {...pageProps} />
</ThemeProvider>
</>
);
};

View File

@ -12,10 +12,7 @@ class MyDocument extends Document {
render() {
return (
<Html lang={config.siteLocale?.replace("_", "-")}>
<Head>
{/* set dynamically by script in _app.tsx, but tag must exist first */}
<meta name="theme-color" content="" />
</Head>
<Head />
<body>
<Main />
<NextScript />

View File

@ -4037,6 +4037,11 @@ next-seo@^4.28.1:
resolved "https://registry.yarnpkg.com/next-seo/-/next-seo-4.28.1.tgz#c98ee559c8ab7196c62d0f6903afd7a8cde47a03"
integrity sha512-WZgwdM+UhpNF3A37zFllzmPhnOVJ9vYeYlc0n3Z/kYfz/QQgy8NEdncNNggS9dU4JD8xriaCcyknhy5OsrFsJw==
next-themes@^0.0.15:
version "0.0.15"
resolved "https://registry.yarnpkg.com/next-themes/-/next-themes-0.0.15.tgz#ab0cee69cd763b77d41211f631e108beab39bf7d"
integrity sha512-LTmtqYi03c4gMTJmWwVK9XkHL7h0/+XrtR970Ujvtu3s0kZNeJN24aJsi4rkZOI8i19+qq6f8j+8Duwy5jqcrQ==
next@v12.0.8-canary.18:
version "12.0.8-canary.18"
resolved "https://registry.yarnpkg.com/next/-/next-12.0.8-canary.18.tgz#4ec836f37f079f4cfe4e1ad9940319c047d32be3"