Skip to content
Draft
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 0 additions & 11 deletions src/client/dark-init.ts

This file was deleted.

15 changes: 9 additions & 6 deletions src/client/stdlib/generators/dark.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,21 @@
import {observe} from "./observe.js";

// Watches dark mode based on theme and user preference.
// TODO: in preview, also watch for changes in the theme meta.
// Watches dark mode based on the color-scheme property, that the chosen theme
// sets.
export function dark() {
return observe((notify: (dark: boolean) => void) => {
let dark: boolean | undefined;
const media = matchMedia("(prefers-color-scheme: dark)");
const probe = document.createElement("div");
probe.style.setProperty("transition-property", "background-color");
probe.style.setProperty("transition-duration", "0.001s");
const changed = () => {
const d = getComputedStyle(document.body).getPropertyValue("color-scheme") === "dark";
const d = getComputedStyle(probe).getPropertyValue("color-scheme") === "dark";
if (dark === d) return; // only notify if changed
notify((dark = d));
};
document.body.append(probe);
probe.addEventListener("transitionstart", changed);
changed();
media.addEventListener("change", changed);
return () => media.removeEventListener("change", changed);
return () => probe.remove();
});
}
6 changes: 3 additions & 3 deletions src/render.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,9 +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>
<script type="module">import{Generators as g}from'${resolveImport(
"observablehq:stdlib"
)}';for await(const d of g.dark()){document.body.classList.toggle("dark",d),document.body.classList.toggle("light",!d)}</script>
</html>
`);
}
Expand Down
Loading