From 6bca7c83a7e2d62015f45f873b0f69f11b4d902b Mon Sep 17 00:00:00 2001 From: "Fred K. Schott" Date: Tue, 8 Jun 2021 08:10:56 -0700 Subject: redesign create-astro (#301) * redesign create astro * add changeset * Use npm start * Update the astro version * Adds the changeset Co-authored-by: Fred Schott Co-authored-by: Matthew Phillips --- examples/docs/src/components/ThemeToggle.tsx | 71 ++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 examples/docs/src/components/ThemeToggle.tsx (limited to 'examples/docs/src/components/ThemeToggle.tsx') diff --git a/examples/docs/src/components/ThemeToggle.tsx b/examples/docs/src/components/ThemeToggle.tsx new file mode 100644 index 000000000..5a5061c15 --- /dev/null +++ b/examples/docs/src/components/ThemeToggle.tsx @@ -0,0 +1,71 @@ +import type { FunctionalComponent } from 'preact'; +import { h, Fragment } from 'preact'; +import { useState, useEffect } from 'preact/hooks'; + +const themes = ['system', 'light', 'dark']; + +const icons = [ + + + , + + + , + + + , +]; + +const ThemeToggle: FunctionalComponent = () => { + const [theme, setTheme] = useState(themes[0]); + + useEffect(() => { + const user = localStorage.getItem('theme'); + if (!user) return; + setTheme(user); + }, []); + + useEffect(() => { + const root = document.documentElement; + if (theme === 'system') { + localStorage.removeItem('theme'); + if (window.matchMedia('(prefers-color-scheme: dark)').matches) { + root.classList.add('theme-dark'); + } else { + root.classList.remove('theme-dark'); + } + } else { + localStorage.setItem('theme', theme); + if (theme === 'light') { + root.classList.remove('theme-dark'); + } else { + root.classList.add('theme-dark'); + } + } + }, [theme]); + + return ( +
+ {themes.map((t, i) => { + const icon = icons[i]; + const checked = t === theme; + return ( + + ); + })} +
+ ); +}; + +export default ThemeToggle; -- cgit v1.2.3