From 20d8b13bb1b830f493ccefb30d6bcd7edc302861 Mon Sep 17 00:00:00 2001 From: Jake Jarvis Date: Tue, 4 Jan 2022 18:04:33 -0500 Subject: [PATCH] separate theme restoration script and add `meta[name="theme-color"]` tag to _document.tsx --- lib/restore-theme.js | 14 ++++++++++++++ pages/_app.tsx | 20 +++++--------------- pages/_document.tsx | 5 ++++- 3 files changed, 23 insertions(+), 16 deletions(-) create mode 100644 lib/restore-theme.js diff --git a/lib/restore-theme.js b/lib/restore-theme.js new file mode 100644 index 00000000..64fb4a56 --- /dev/null +++ b/lib/restore-theme.js @@ -0,0 +1,14 @@ +import { themeColorLight, themeColorDark } from "./config"; + +// Inlined JS in pages/_app.tsx to restore these light/dark theme settings ASAP: +// ``, ``, 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(); diff --git a/pages/_app.tsx b/pages/_app.tsx index 8cbdb448..16ad2d27 100644 --- a/pages/_app.tsx +++ b/pages/_app.tsx @@ -3,6 +3,7 @@ import { useRouter } from "next/router"; import Script from "next/script"; 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"; @@ -48,6 +49,10 @@ const App = ({ Component, pageProps }: AppProps) => { return ( <> + + {/* @ts-ignore */} { ]} /> - {/* - Inline script to restore light/dark theme preference ASAP: - ``, ``, and color-scheme style - */} - - ); diff --git a/pages/_document.tsx b/pages/_document.tsx index bf04548b..900f8a6e 100644 --- a/pages/_document.tsx +++ b/pages/_document.tsx @@ -12,7 +12,10 @@ class MyDocument extends Document { render() { return ( - + + {/* set dynamically by script in _app.tsx, but tag must exist first */} + +