Rudimentary colour scheme switcher

This commit is contained in:
Lewis Dale 2023-09-26 15:01:55 +01:00
parent fa906877b2
commit 47a657a36c
3 changed files with 79 additions and 1 deletions

2
.nvmrc
View File

@ -1 +1 @@
v18.15.0
v18.18.0

View File

@ -34,10 +34,74 @@
<li><a href="/links">Links</a></li>
</ul>
</nav>
<color-scheme-toggle></color-scheme-toggle>
</header>
{{ content | safe }}
<footer>
<div class="wrapper-lg">Copyright &copy; {{ today.year }} {{ metadata.author.name }}</div>
</footer>
<template id="color-scheme-toggle">
<fieldset>
<legend>Change your colour scheme</legend>
<label>
<input type="radio" name="color-scheme" value="dark" />
Dark
</label>
<label>
<input type="radio" name="color-scheme" value="light" />
Light
</label>
</fieldset>
</template>
<script type="text/javascript">
window.customElements.define("color-scheme-toggle", class extends HTMLElement {
constructor() {
super();
const template = document.getElementById("color-scheme-toggle");
const templateNode = template.content.cloneNode(true);
this.appendChild(templateNode);
}
getColourScheme = () => {
const colourScheme = localStorage.getItem('color-scheme');
if (colourScheme) {
return colourScheme;
}
if (window.matchMedia('(prefers-color-scheme: dark)')?.matches) {
return "dark";
}
return "light";
}
onColourSchemeChange = (e) => {
localStorage.setItem('color-scheme', e.target.value);
this.updateComponents();
}
updateComponents = () => {
this.querySelectorAll('[name="color-scheme"]').forEach(radio => {
radio.checked = this.getColourScheme() === radio.value;
});
if (localStorage.getItem('color-scheme')) {
document.body.setAttribute('data-color-scheme', this.getColourScheme());
}
}
connectedCallback() {
this.querySelectorAll('[name="color-scheme"]').forEach(radio => {
radio.addEventListener('change', this.onColourSchemeChange);
});
this.updateComponents();
}
});
</script>
</body>
</html>

View File

@ -14,6 +14,20 @@
}
}
body[data-color-scheme="light"] {
--color-secondary: var(--color-neutral-100);
--color-primary: var(--color-neutral-800);
--color-decoration: var(--color-amber-800);
--color-subtle: var(--color-zinc-500);
}
body[data-color-scheme="dark"] {
--color-primary: var(--color-neutral-200);
--color-secondary: var(--color-neutral-800);
--color-decoration: var(--color-amber-200);
--color-subtle: var(--color-zinc-400);
}
body {
background-color: var(--color-secondary);
color: var(--color-primary);