~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
main
28 lines · 1.1 KB Raw History
/**
 * Whether a reader sees the console light or dark: as their system is, or
 * as they chose, kept in a cookie of the console's own, so the page is
 * drawn so from its first byte.
 */
export type Appearance = 'system' | 'light' | 'dark';

/** The cookie a reader's choice is kept in. */
export const COOKIE = 'appearance';

/** A year: a choice is kept until changed. */
const KEEP_FOR = 365 * 24 * 60 * 60;

/** What the cookie's value says: a scheme chosen, or none, as the system has it. */
export const appearanceOf = (value?: string): Appearance =>
  value === 'light' || value === 'dark' ? value : 'system';

/** The reader's choice, kept, and the page drawn in it at once: `system` forgets it. */
export function choose(appearance: Appearance) {
  const root = document.documentElement;
  if (appearance === 'system') {
    delete root.dataset.theme;
    document.cookie = `${COOKIE}=; path=/; max-age=0; samesite=lax`;
  } else {
    root.dataset.theme = appearance;
    document.cookie = `${COOKIE}=${appearance}; path=/; max-age=${KEEP_FOR}; samesite=lax`;
  }
}