Skip to main content

Module theme

Module theme 

Source
Expand description

Colour mode: light, dark, or follow the system.

The admin panel needs this, and so does any public site an application builds, so the mechanism lives here rather than inside either surface. The admin is one consumer of it, not its owner.

What is offered is the mechanism and its contract, never an appearance: no icons, no toggle markup, no colour tokens. A site brings its own control and its own palette and keys them off the contract below.

§The contract

<html data-theme="light">   the resolved mode; write CSS against this
localStorage["lat-mode"]    the reader's choice: light | dark | auto
window.latMode()            read the current choice
window.latSetMode(mode)     persist a choice and apply it
window.latApplyMode(mode)   apply without persisting

auto follows the operating system and keeps following it: a page left open when the system switches at dusk changes with it rather than waiting for a reload. An explicit light or dark is the reader overriding the system, so it is left alone.

§Using it from a page

Put boot_markup in <head> before any stylesheet. It must be inline and blocking: a deferred script runs after first paint, and a dark-mode reader would see the page flash white first.

let head = format!("<head>{}<link rel=\"stylesheet\" href=\"/site.css\"></head>",
                   theme::boot_markup());
assert!(head.contains("latApplyMode"));

Then style against the attribute, and wire any control to latSetMode:

:root            { --bg: white; --fg: black }
[data-theme=dark]{ --bg: black; --fg: white }
document.querySelector('#to-dark').onclick = () => latSetMode('dark');

§Content Security Policy

An inline script needs script-src 'unsafe-inline', or a nonce or hash. Use BOOT_JS to serve the same source as a file instead, accepting that a separate request may paint before it arrives.

Constants§

BOOT_JS
The boot script’s JavaScript, without a surrounding <script> element.
MODES
The three modes, as the strings stored under MODE_KEY.
MODE_KEY
The localStorage key holding the reader’s choice, for a surface that wants to read or clear it without going through the script.

Functions§

boot_markup
The boot script wrapped in a <script> element, ready to inline in <head> before any stylesheet.