Skip to content

Commit

Permalink
dark/light body class
Browse files Browse the repository at this point in the history
  • Loading branch information
Fil committed Oct 25, 2024
1 parent 031ac6d commit eb0be3c
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 0 deletions.
2 changes: 2 additions & 0 deletions docs/themes.md.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,8 @@ ${themes.dark.map((theme) => `- \`${theme}\`${theme === dark ? " (default)" : ""
When both a light and a dark mode theme are specified, theme styles are applied selectively based on the user’s preferred color scheme. This is implemented via [\`prefers-color-scheme\`](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme) and typically relies on the user’s operating system settings.
Light themes set the [color-scheme](https://developer.mozilla.org/en-US/docs/Web/CSS/color-scheme) property to \`light\`, and dark themes set it to \`dark\`. This property is reflected as a \`light\` or \`dark\` class added to the page’s \`body\` element, allowing you to use the \`.light\` and \`.dark\` CSS selectors. (See also the [dark](./lib/generators#dark) generator.)
<div class="tip">On macOS, you can create a menubar <a href="https://support.apple.com/guide/shortcuts-mac/intro-to-shortcuts-apdf22b0444c/mac">shortcut</a> to quickly toggle between light and dark mode. This is useful for testing.</div>
<div class="tip">Designing charts that work well in both light and dark mode can be challenging. If you’d prefer to design for only one mode, set the theme explicitly to <code>light</code> or <code>dark</code>.</div>
Expand Down
11 changes: 11 additions & 0 deletions src/client/dark-init.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
const probe = document.createElement("div");
probe.style.setProperty("transition-property", "color");
probe.style.setProperty("transition-duration", "0.001s");
const update = () => {
const dark = getComputedStyle(probe)["color-scheme"];
document.body.classList.toggle("dark", dark);
document.body.classList.toggle("light", !dark);
};
update();
probe.addEventListener("transitionstart", update);
document.body.append(probe);
3 changes: 3 additions & 0 deletions src/render.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,9 @@ ${preview ? `\nopen({hash: ${JSON.stringify(resolvers.hash)}, eval: (body) => ev
${html.unsafe(rewriteHtml(page.body, resolvers))}</main>${renderFooter(page.footer, resolvers, options)}
</div>
</body>
<script>{${html.unsafe(
(await rollupClient(getClientPath("dark-init.js"), options.root, path, {resolveImport, minify: true})).trim()
)}}</script>
</html>
`);
}
Expand Down

0 comments on commit eb0be3c

Please sign in to comment.