2022-07-10 16:40:09 -04:00
|
|
|
// Handle setting and changing the site's color scheme (light/dark)
|
|
|
|
|
|
|
|
"use strict";
|
|
|
|
|
2022-04-28 11:49:31 -04:00
|
|
|
const prefersDark = window.matchMedia("(prefers-color-scheme: dark)")
|
2022-01-16 17:33:05 -05:00
|
|
|
|
2022-04-28 11:49:31 -04:00
|
|
|
const getColourScheme = () => document.documentElement.dataset.colour_scheme
|
|
|
|
const setColourScheme = (colourScheme = getColourScheme()) => {
|
|
|
|
document.documentElement.dataset.colour_scheme = colourScheme
|
|
|
|
localStorage.setItem("colour_scheme", colourScheme)
|
|
|
|
setPygments(colourScheme)
|
2022-01-16 17:33:05 -05:00
|
|
|
}
|
|
|
|
|
2022-04-28 11:49:31 -04:00
|
|
|
// Map system theme to a cycle of steps
|
|
|
|
const cycles = {
|
|
|
|
dark: ["auto", "light", "dark"], // auto (dark) → light → dark
|
|
|
|
light: ["auto", "dark", "light"], // auto (light) → dark → light
|
2022-01-16 17:33:05 -05:00
|
|
|
}
|
|
|
|
|
2022-04-28 11:49:31 -04:00
|
|
|
const nextColourScheme = (colourScheme = getColourScheme()) => {
|
|
|
|
const cycle = cycles[prefersDark.matches ? "dark" : "light"]
|
|
|
|
return cycle[(cycle.indexOf(colourScheme) + 1) % cycle.length]
|
|
|
|
}
|
2022-01-16 17:33:05 -05:00
|
|
|
|
2022-04-28 11:49:31 -04:00
|
|
|
const setPygments = (colourScheme = getColourScheme()) => {
|
|
|
|
const pygmentsDark = document.getElementById("pyg-dark")
|
|
|
|
const pygmentsLight = document.getElementById("pyg-light")
|
|
|
|
pygmentsDark.disabled = colourScheme === "light"
|
|
|
|
pygmentsLight.disabled = colourScheme === "dark"
|
|
|
|
pygmentsDark.media = colourScheme === "auto" ? "(prefers-color-scheme: dark)" : ""
|
|
|
|
pygmentsLight.media = colourScheme === "auto" ? "(prefers-color-scheme: light)" : ""
|
2022-01-16 17:33:05 -05:00
|
|
|
}
|
|
|
|
|
2022-04-28 11:49:31 -04:00
|
|
|
// Update Pygments state (the page theme is initialised inline, see page.html)
|
|
|
|
document.addEventListener("DOMContentLoaded", () => setColourScheme())
|