mirror of
https://github.com/jakejarvis/jarv.is.git
synced 2025-06-30 22:26:38 -04:00
React 18 (#863)
* gymnastics to make theme script work with react 18 hydration * try next 12.1.3 canary to fix SSG head tags? * revert theme script changes * next 12.1.3-canary.3 * double-revert some of the use-theme.tsx changes * separate theme restoration script & move to _document * bump next * bump next (again) * clean up some theme stuff * use hashed image URLs in webmanifest and feeds * text experimental react config * Update ThemeScript.tsx * switch selfie image to `layout="raw"` * use `layout="raw"` for all non-imported images * revert raw images in some places, messes up responsiveness * fix nitpicky "no divs inside buttons" html validation error * fix react-player hydration errors * fix hydration errors from server/client time zone differences * clean up hydration fixes * Update format-date.ts * last-minute cleanup
This commit is contained in:
@ -1,33 +1,17 @@
|
||||
// forked & modified from pacocoursey/next-themes as of v0.0.15:
|
||||
// https://github.com/pacocoursey/next-themes/tree/b5c2bad50de2d61ad7b52a9c5cdc801a78507d7a
|
||||
|
||||
import { createContext, useCallback, useContext, useEffect, useState, useRef, memo } from "react";
|
||||
import NextHead from "next/head";
|
||||
import { createContext, useCallback, useContext, useEffect, useState, useRef } from "react";
|
||||
import { darkModeQuery, colorSchemes, themeStorageKey } from "../lib/styles/helpers/themes";
|
||||
import type { PropsWithChildren } from "react";
|
||||
|
||||
// https://web.dev/prefers-color-scheme/#the-prefers-color-scheme-media-query
|
||||
const MEDIA = "(prefers-color-scheme: dark)";
|
||||
|
||||
// default to a simple light or dark binary option
|
||||
const colorSchemes = ["light", "dark"];
|
||||
|
||||
interface AttributeValuesMap {
|
||||
[themeName: string]: string;
|
||||
}
|
||||
|
||||
export interface ThemeProviderProps {
|
||||
/** Mapping of theme name to HTML attribute value. Object where key is the theme name and value is the attribute value */
|
||||
classNames: { [themeName: string]: string };
|
||||
/** List of all available theme names */
|
||||
themes?: string[];
|
||||
/** Whether to indicate to browsers which color scheme is used (dark or light) for built-in UI like inputs and buttons */
|
||||
enableColorScheme?: boolean;
|
||||
/** Key used to store theme setting in localStorage */
|
||||
storageKey?: string;
|
||||
/** Default theme name (for v0.0.12 and lower the default was light). If `enableSystem` is false, the default theme is light */
|
||||
defaultTheme?: string;
|
||||
/** HTML attribute modified based on the active theme. Accepts `class` and `data-*` (meaning any data attribute, `data-mode`, `data-color`, etc.) */
|
||||
attribute?: string | "class";
|
||||
/** Mapping of theme name to HTML attribute value. Object where key is the theme name and value is the attribute value */
|
||||
value?: AttributeValuesMap;
|
||||
}
|
||||
|
||||
export interface UseThemeProps {
|
||||
@ -45,7 +29,7 @@ export interface UseThemeProps {
|
||||
const getTheme = (key: string, fallback?: string) => {
|
||||
if (typeof window === "undefined") return undefined;
|
||||
|
||||
let theme;
|
||||
let theme: string;
|
||||
try {
|
||||
theme = localStorage.getItem(key) || undefined;
|
||||
} catch (e) {} // eslint-disable-line no-empty
|
||||
@ -56,7 +40,7 @@ const getTheme = (key: string, fallback?: string) => {
|
||||
// get the user's prefered theme as set via their OS/browser settings
|
||||
const getSystemTheme = (e?: MediaQueryList) => {
|
||||
if (!e) {
|
||||
e = window.matchMedia(MEDIA);
|
||||
e = window.matchMedia(darkModeQuery);
|
||||
}
|
||||
|
||||
const isDark = e.matches;
|
||||
@ -72,82 +56,15 @@ const ThemeContext = createContext<UseThemeProps>({
|
||||
});
|
||||
export const useTheme = () => useContext(ThemeContext);
|
||||
|
||||
// the script tag injected manually into `<head>` by provider below
|
||||
const ThemeScript = memo(function ThemeScript({
|
||||
storageKey,
|
||||
attribute,
|
||||
defaultTheme,
|
||||
value,
|
||||
attrs,
|
||||
}: {
|
||||
storageKey: string;
|
||||
attribute?: string;
|
||||
defaultTheme: string;
|
||||
value?: AttributeValuesMap;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
attrs: any;
|
||||
}) {
|
||||
const setDocumentVar = (() => {
|
||||
if (attribute === "class") {
|
||||
const removeClasses = `d.remove(${attrs.map((t: string) => `"${t}"`).join(",")})`;
|
||||
|
||||
// `d` is the class list of the `<html>` tag
|
||||
return `var d=document.documentElement.classList;${removeClasses};`;
|
||||
} else {
|
||||
// `d` is the entire document, used to set custom attribute of the `<html>` tag (probably `data-*`)
|
||||
return `var d=document.documentElement;`;
|
||||
}
|
||||
})();
|
||||
|
||||
const updateDOM = (name: string, literal?: boolean) => {
|
||||
name = value?.[name] || name;
|
||||
const val = literal ? name : `"${name}"`;
|
||||
|
||||
// mirrors above logic from setDocumentVar()
|
||||
if (attribute === "class") {
|
||||
return `d.add(${val})`;
|
||||
} else {
|
||||
return `d.setAttribute("${attribute}", ${val})`;
|
||||
}
|
||||
};
|
||||
|
||||
// is the default theme still `system`? (it should be...)
|
||||
const defaultSystem = defaultTheme === "system";
|
||||
|
||||
// even though it's the proper method, using next/script with `strategy="beforeInteractive"` still causes flash of
|
||||
// white on load. injecting a normal script tag lets us prioritize setting `<html>` attributes even more.
|
||||
return (
|
||||
<NextHead>
|
||||
<script
|
||||
key="next-themes-script"
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: `!function(){try{${setDocumentVar}var e=localStorage.getItem("${storageKey}");${
|
||||
!defaultSystem ? updateDOM(defaultTheme) + ";" : ""
|
||||
}if("system"===e||(!e&&${defaultSystem})){var t="${MEDIA}",m=window.matchMedia(t);m.media!==t||m.matches?${updateDOM(
|
||||
"dark"
|
||||
)}:${updateDOM("light")}}else if(e){${value ? `var x=${JSON.stringify(value)}` : ""}}${updateDOM(
|
||||
value ? "x[e]" : "e",
|
||||
true
|
||||
)}}catch(e){}}()`,
|
||||
}}
|
||||
/>
|
||||
</NextHead>
|
||||
);
|
||||
});
|
||||
|
||||
// provider used once in _app.tsx to wrap entire app
|
||||
export const ThemeProvider = ({
|
||||
enableColorScheme = true,
|
||||
storageKey = "theme",
|
||||
classNames,
|
||||
themes = [...colorSchemes],
|
||||
defaultTheme = "system",
|
||||
attribute = "data-theme",
|
||||
value,
|
||||
enableColorScheme = true,
|
||||
children,
|
||||
}: PropsWithChildren<ThemeProviderProps>) => {
|
||||
const [theme, setThemeState] = useState(() => getTheme(storageKey, defaultTheme));
|
||||
const [resolvedTheme, setResolvedTheme] = useState(() => getTheme(storageKey));
|
||||
const attrs = !value ? themes : Object.values(value);
|
||||
const [theme, setThemeState] = useState(() => getTheme(themeStorageKey, "system"));
|
||||
const [resolvedTheme, setResolvedTheme] = useState(() => getTheme(themeStorageKey));
|
||||
|
||||
const handleMediaQuery = useCallback(
|
||||
(e?) => {
|
||||
@ -163,28 +80,25 @@ export const ThemeProvider = ({
|
||||
mediaListener.current = handleMediaQuery;
|
||||
|
||||
const changeTheme = useCallback((theme, updateStorage = true, updateDOM = true) => {
|
||||
let name = value?.[theme] || theme;
|
||||
let name = classNames?.[theme] || theme;
|
||||
|
||||
if (updateStorage) {
|
||||
try {
|
||||
localStorage.setItem(storageKey, theme);
|
||||
localStorage.setItem(themeStorageKey, theme);
|
||||
} catch (e) {} // eslint-disable-line no-empty
|
||||
}
|
||||
|
||||
if (theme === "system") {
|
||||
const resolved = getSystemTheme();
|
||||
name = value?.[resolved] || resolved;
|
||||
name = classNames?.[resolved] || resolved;
|
||||
}
|
||||
|
||||
if (updateDOM) {
|
||||
// remove all theme classes first to start fresh
|
||||
const all = Object.values(classNames);
|
||||
const d = document.documentElement;
|
||||
|
||||
if (attribute === "class") {
|
||||
d.classList.remove(...attrs);
|
||||
d.classList.add(name);
|
||||
} else {
|
||||
d.setAttribute(attribute, name);
|
||||
}
|
||||
d.classList.remove(...all);
|
||||
d.classList.add(name);
|
||||
}
|
||||
}, []); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
@ -193,7 +107,7 @@ export const ThemeProvider = ({
|
||||
const handler = (...args: any) => mediaListener.current(...args);
|
||||
|
||||
// Always listen to System preference
|
||||
const media = window.matchMedia(MEDIA);
|
||||
const media = window.matchMedia(darkModeQuery);
|
||||
|
||||
// Intentionally use deprecated listener methods to support iOS & old browsers
|
||||
media.addListener(handler);
|
||||
@ -213,12 +127,12 @@ export const ThemeProvider = ({
|
||||
// localStorage event handling
|
||||
useEffect(() => {
|
||||
const handleStorage = (e: StorageEvent) => {
|
||||
if (e.key !== storageKey) {
|
||||
if (e.key !== themeStorageKey) {
|
||||
return;
|
||||
}
|
||||
|
||||
// If default theme set, use it if localstorage === null (happens on local storage manual deletion)
|
||||
const theme = e.newValue || defaultTheme;
|
||||
// use default theme if localstorage === null (happens on local storage manual deletion)
|
||||
const theme = e.newValue || "system";
|
||||
setTheme(theme);
|
||||
};
|
||||
|
||||
@ -253,16 +167,6 @@ export const ThemeProvider = ({
|
||||
setTheme,
|
||||
}}
|
||||
>
|
||||
<ThemeScript
|
||||
{...{
|
||||
storageKey,
|
||||
attribute,
|
||||
value,
|
||||
defaultTheme,
|
||||
attrs,
|
||||
}}
|
||||
/>
|
||||
|
||||
{children}
|
||||
</ThemeContext.Provider>
|
||||
);
|
||||
|
Reference in New Issue
Block a user