showcase
- v0.2.4
- 37 commits
- 1 branch
- 6 tags
- updated
- CI 2/2
theme.js
1.7 KB · 40 lines
1// Palettes, shared with danieldaum.net. Saturn's rule: one palette per visit,2// and the next visit gets the next one. On top of that, a `theme` cookie for3// the parent domain carries the palette between danieldaum.net and this4// site, both ways. This runs in <head>, before the first paint. Without JS5// the page keeps the palette from config and the footer button stays hidden.6const themes = ["moss", "ink", "wine", "plum", "teal"];7const root = document.documentElement;89// code.danieldaum.net shares cookies with danieldaum.net; an IP or10// localhost gets a host-only cookie.11const host = location.hostname;12const domain = /^[\d.]+$|^[^.]+$/.test(host) ? "" : `; domain=${host.split(".").slice(-2).join(".")}`;1314function after(theme) {15 return themes[(themes.indexOf(theme) + 1) % themes.length];16}1718function use(theme) {19 root.dataset.theme = theme;20 document.cookie = `theme=${theme}; path=/; samesite=lax${domain}${location.protocol === "https:" ? "; secure" : ""}`;21 try {22 sessionStorage.setItem("theme", theme);23 localStorage.setItem("theme", theme);24 } catch {}25}2627let current = "moss";28try {29 const shared = /(?:^|;\s*)theme=([a-z]+)/.exec(document.cookie)?.[1];30 const visit = sessionStorage.getItem("theme");31 current = themes.includes(shared) ? shared : themes.includes(visit) ? visit : after(localStorage.getItem("theme"));32} catch {}33use(current);3435document.addEventListener("DOMContentLoaded", () => {36 for (const button of document.querySelectorAll(".theme-button")) button.hidden = false;37});38document.addEventListener("click", (event) => {39 if (event.target.closest(".theme-button")) use((current = after(current)));40});