repositories

daemon-sec-cheatsheet

The cheatsheet vault for operators: AD, enumeration, exploitation, priv-esc, web, DFIR

clonegit clone https://git.daemon-sec.xyz/daemon-sec-cheatsheet.git
palette.tsTypeScript118 lines5.0 KiBraw download
// The palette switcher (components/PalettePicker.astro) and the browser
// chrome colour. The pre-paint script in Base.astro sets `data-palette`
// before first paint; this keeps it, the menu and the chrome in step after.

import { DEFAULT_PALETTE, PALETTES } from '../lib/palettes.ts';

const KEY = 'palette';
const root = document.documentElement;

function current(): string {
  const p = root.getAttribute('data-palette');
  return PALETTES.some((m) => m.id === p) ? (p as string) : DEFAULT_PALETTE;
}

/** Both theme-color metas take the colour for this palette and mode. */
export function paintChrome(): void {
  const meta = PALETTES.find((m) => m.id === current()) ?? PALETTES[0];
  const c = meta.chrome[root.getAttribute('data-theme') === 'dark' ? 'night' : 'dawn'];
  document.querySelectorAll('meta[name="theme-color"]').forEach((m) => m.setAttribute('content', c));
}

function reducedMotion(): boolean {
  return window.matchMedia('(prefers-reduced-motion: reduce)').matches || root.dataset.motion === 'reduce';
}

function apply(id: string): void {
  root.setAttribute('data-palette', id);
  try { localStorage.setItem(KEY, id); } catch {}
  paintChrome();
  // The banners' canvas reads its colours from CSS at draw time and redraws
  // on this — the same signal the mode toggle sends.
  window.dispatchEvent(new Event('daemonmodechange'));
}

/** The mode toggle's circular wipe, opening from `from`; `then` runs once
 *  the palette is applied (inside the transition when there is one). */
function change(id: string, from: Element, then: () => void): void {
  const startVT = (document as unknown as {
    startViewTransition?: (cb: () => void) => { finished: Promise<void> };
  }).startViewTransition;
  if (!startVT || reducedMotion()) { apply(id); then(); return; }
  const r = from.getBoundingClientRect();
  const x = r.left + r.width / 2;
  const y = r.top + r.height / 2;
  root.style.setProperty('--vt-x', `${x}px`);
  root.style.setProperty('--vt-y', `${y}px`);
  root.style.setProperty('--vt-r', `${Math.hypot(Math.max(x, window.innerWidth - x), Math.max(y, window.innerHeight - y))}px`);
  root.classList.add('theme-vt');
  startVT.call(document, () => { apply(id); then(); }).finished.finally(() => root.classList.remove('theme-vt'));
}

let open: { close: (refocus?: boolean) => void; wrap: Element } | null = null;
let globalBound = false;

export function initPalette(): void {
  if (!globalBound) {
    globalBound = true;
    // One listener for the page's life: the masthead is re-rendered on every
    // view-transition navigation, so per-instance window listeners would pile up.
    window.addEventListener('pointerdown', (e) => {
      if (open && !open.wrap.contains(e.target as Node)) open.close(false);
    });
    document.addEventListener('astro:before-swap', () => open?.close(false));
  }

  document.querySelectorAll<HTMLElement>('[data-palette-picker]').forEach((wrap) => {
    if (wrap.dataset.bound) return;
    wrap.dataset.bound = '1';
    const trigger = wrap.querySelector<HTMLButtonElement>('[data-palette-trigger]')!;
    const menu = wrap.querySelector<HTMLElement>('[data-palette-menu]')!;
    const items = [...menu.querySelectorAll<HTMLButtonElement>('[role="menuitemradio"]')];

    const sync = () => {
      const id = current();
      const name = PALETTES.find((m) => m.id === id)?.name ?? id;
      trigger.setAttribute('aria-label', `Palette: ${name}`);
      trigger.title = `Palette — ${name}`;
      items.forEach((i) => i.setAttribute('aria-checked', String(i.dataset.paletteId === id)));
    };
    const close = (refocus = true) => {
      menu.hidden = true;
      trigger.setAttribute('aria-expanded', 'false');
      if (open?.wrap === wrap) open = null;
      if (refocus) trigger.focus();
    };
    const show = () => {
      open?.close(false);
      sync();
      menu.hidden = false;
      trigger.setAttribute('aria-expanded', 'true');
      open = { close, wrap };
      // Focus the checked option, so the arrow keys start from the state.
      (items.find((i) => i.getAttribute('aria-checked') === 'true') ?? items[0])?.focus();
    };

    sync();
    trigger.addEventListener('click', () => (menu.hidden ? show() : close()));
    trigger.addEventListener('keydown', (e) => {
      if (e.key === 'ArrowDown' && menu.hidden) { e.preventDefault(); show(); }
    });
    items.forEach((item) =>
      item.addEventListener('click', () => {
        const id = item.dataset.paletteId!;
        close();
        if (id !== current()) change(id, item.closest('[data-palette-picker]') ?? item, sync);
      }),
    );
    menu.addEventListener('keydown', (e) => {
      const i = items.indexOf(document.activeElement as HTMLButtonElement);
      const go = (n: number) => { e.preventDefault(); items[(n + items.length) % items.length]?.focus(); };
      if (e.key === 'ArrowDown') go(i + 1);
      else if (e.key === 'ArrowUp') go(i - 1);
      else if (e.key === 'Home') go(0);
      else if (e.key === 'End') go(items.length - 1);
      else if (e.key === 'Escape' || e.key === 'Tab') { e.preventDefault(); close(); }
    });
  });
}