From 04b96fb36c4008e7f39e6c74893d61ac0cd0dcba Mon Sep 17 00:00:00 2001 From: Bryce Kwon Date: Wed, 15 Jul 2026 10:43:24 -1000 Subject: Add a light and dark theme toggle The button is emitted hidden and only revealed by the script, so a browser without JavaScript never shows a control that cannot work and the page keeps tracking the system theme. --- assets/cgit.js | 56 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) (limited to 'assets/cgit.js') diff --git a/assets/cgit.js b/assets/cgit.js index df3ad4e..85826b4 100644 --- a/assets/cgit.js +++ b/assets/cgit.js @@ -66,3 +66,59 @@ document.addEventListener("DOMContentLoaded", function() { }, false); })(); + +/* Colour theme toggle: cycles auto -> light -> dark and remembers the + * choice. "auto" leaves the page following the system preference via CSS. */ + +(function () { + +var KEY = "cgit-theme"; +var ORDER = [ "auto", "light", "dark" ]; +var ICONS = { + auto: '', + light: '', + dark: '' +}; + +function saved() { + try { return localStorage.getItem(KEY); } catch (e) { return null; } +} + +function persist(value) { + try { localStorage.setItem(KEY, value); } catch (e) { } +} + +function apply(theme, root, btn) { + if (theme === "auto") + root.removeAttribute("data-theme"); + else + root.setAttribute("data-theme", theme); + /* Keep the standalone page background in sync with the choice. */ + document.documentElement.style.colorScheme = (theme === "auto") ? "" : theme; + if (btn) { + btn.innerHTML = ICONS[theme]; + btn.title = "Colour theme: " + theme; + } +} + +document.addEventListener("DOMContentLoaded", function () { + var root = document.getElementById("cgit"); + if (!root) + return; + var btn = root.querySelector(".theme-toggle"); + var theme = saved(); + if (ORDER.indexOf(theme) < 0) + theme = "auto"; + + apply(theme, root, btn); + if (!btn) + return; + btn.hidden = false; + btn.addEventListener("click", function () { + theme = ORDER[(ORDER.indexOf(theme) + 1) % ORDER.length]; + persist(theme); + apply(theme, root, btn); + }); +}, false); + +})(); -- cgit v2.8.0