repositories

daemon-sec-lotl

DÆMONBins: GTFOBins × LOLBAS × WADComs × LOOBins in one filterable catalog

clonegit clone https://git.daemon-sec.xyz/daemon-sec-lotl.git
cursor.tsTypeScript256 lines10.1 KiBraw download
/**
 * The dot cursor and its pill, framework-free. Ported from daemon-sec's
 * client/src/components/daemon/cursor.tsx so the sibling sites behave
 * the same way.
 *
 * A small disc trails the pointer and opens into a ring over anything
 * clickable. Over something with one clear action it becomes a pill
 * that says what a click will do:
 *   - an element with `data-cursor-label` (optional `data-cursor-icon`:
 *     view | play | pdf | download | read)
 *   - a video marked `data-pill`: Play / Pause (a click on the video body
 *     toggles it; the native control strip keeps its own clicks)
 *   - an image marked `data-zoomable`: View image / View GIF
 *   - a link to a PDF: Open PDF, or Download PDF if it downloads
 *   - a link the site counts as an article (`isArticle`): Read
 *
 * Fine pointers only; it never mounts on touch or under reduced motion,
 * so those visitors keep the native cursor. The trailing loop stops as
 * soon as the dot catches up, so an idle page costs nothing.
 *
 * Usage:
 *   mountCursor({ isArticle: (href) => href.startsWith("/sheets/") });
 */

export interface CursorOptions {
  /** Which internal links read as articles and get the "Read" pill. */
  isArticle?: (href: string) => boolean;
  /** Finer control: the pill text for a link, or null for none. Takes
   *  precedence over `isArticle`. */
  linkLabel?: (href: string, link: HTMLAnchorElement) => string | null;
  /** Ancestors that are dark grounds, so the cursor re-tints over them. */
  darkSelector?: string;
  /** Finer control than `darkSelector`, for sites that nest light panels
   *  inside dark bands. */
  isDark?: (target: HTMLElement) => boolean;
  /** Override the reduced-motion gate. */
  enabled?: boolean;
}

type Mode = "view" | "play" | "read" | "pdf" | "label" | null;
type IconName = "view" | "play" | "pause" | "pdf" | "download" | "read";

/* lucide path data (ISC/MIT), so the pill needs no icon font. */
const ICONS: Record<IconName, string> = {
  view: '<path d="M15 3h6v6"/><path d="m21 3-7 7"/><path d="m3 21 7-7"/><path d="M9 21H3v-6"/>',
  play: '<path d="M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z"/>',
  pause: '<rect x="14" y="3" width="5" height="18" rx="1"/><rect x="5" y="3" width="5" height="18" rx="1"/>',
  pdf: '<path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"/><path d="M14 2v4a2 2 0 0 0 2 2h4"/><path d="M10 9H8"/><path d="M16 13H8"/><path d="M16 17H8"/>',
  download: '<path d="M12 15V3"/><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><path d="m7 10 5 5 5-5"/>',
  read: '<path d="M5 12h14"/><path d="m12 5 7 7-7 7"/>',
};

const EASE = 0.28;
const PILL_EASE = 0.16;
const SETTLED = 0.1;
const CONTROLS_STRIP = 48;
const PDF = /\.pdf($|[?#])/i;
const INTERACTIVE =
  "a, button, input, textarea, select, summary, label, [role='button'], [role='switch'], [role='tab']";

/* Only ever fixed markup from ICONS: an unknown name falls back to the
   arrow rather than reaching the DOM. */
function svg(name: IconName) {
  const body = ICONS[name] ?? ICONS.read;
  return `<svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${body}</svg>`;
}

export function mountCursor(options: CursorOptions = {}): () => void {
  /* A site-level motion switch (`<html data-motion="reduce">`) counts the
     same as the OS setting. */
  const enabled =
    options.enabled ??
    (window.matchMedia("(pointer: fine)").matches &&
      !window.matchMedia("(prefers-reduced-motion: reduce)").matches &&
      document.documentElement.dataset.motion !== "reduce");
  if (!enabled) return () => {};
  const isArticle = options.isArticle ?? (() => false);
  const linkLabel =
    options.linkLabel ?? ((href: string) => (isArticle(href) ? "Read" : null));
  const darkSelector = options.darkSelector ?? "[data-ground='dark']";
  const isDark = options.isDark ?? ((t: HTMLElement) => Boolean(t.closest(darkSelector)));

  const el = document.createElement("div");
  el.className = "dmn-cursor";
  el.setAttribute("aria-hidden", "true");
  el.innerHTML = '<span class="dmn-cursor-pill"><span class="dmn-cursor-icon"></span><span class="dmn-cursor-label"></span></span>';
  const iconEl = el.querySelector<HTMLElement>(".dmn-cursor-icon")!;
  const labelEl = el.querySelector<HTMLElement>(".dmn-cursor-label")!;
  document.body.appendChild(el);
  const root = document.documentElement;
  root.classList.add("has-dmn-cursor");

  let x = window.innerWidth / 2;
  let y = window.innerHeight / 2;
  let tx = x;
  let ty = y;
  let raf = 0;
  let seen = false;
  let mode: Mode = null;
  let mediaEl: HTMLElement | null = null;

  const place = () => {
    el.style.transform = `translate(${x}px, ${y}px) translate(-50%, -50%)`;
  };
  const step = () => {
    const k = mode ? PILL_EASE : EASE;
    x += (tx - x) * k;
    y += (ty - y) * k;
    if (Math.abs(tx - x) < SETTLED && Math.abs(ty - y) < SETTLED) {
      x = tx;
      y = ty;
      place();
      raf = 0;
      return;
    }
    place();
    raf = requestAnimationFrame(step);
  };
  const wake = () => {
    if (!raf) raf = requestAnimationFrame(step);
  };

  const under = (target: HTMLElement): { mode: Mode; el: HTMLElement } | null => {
    const labelled = target.closest<HTMLElement>("[data-cursor-label]");
    if (labelled) return { mode: "label", el: labelled };
    const video = target.closest<HTMLVideoElement>("video[data-pill]");
    if (video) return { mode: "play", el: video };
    const img =
      target.closest<HTMLImageElement>("img[data-zoomable]") ??
      target.closest("button")?.querySelector<HTMLImageElement>("img[data-zoomable]") ??
      null;
    if (img) return { mode: "view", el: img };
    const link = target.closest<HTMLAnchorElement>("a[href]");
    if (link) {
      const href = link.getAttribute("href") ?? "";
      if (PDF.test(href)) return { mode: "pdf", el: link };
      if (linkLabel(href, link)) return { mode: "read", el: link };
    }
    return null;
  };

  const labelFor = (m: Mode, t: HTMLElement): { icon: IconName; text: string } => {
    if (m === "label") {
      return { icon: (t.dataset.cursorIcon as IconName) || "read", text: t.dataset.cursorLabel ?? "" };
    }
    if (m === "play") {
      const paused = (t as HTMLVideoElement).paused;
      return { icon: paused ? "play" : "pause", text: paused ? "Play" : "Pause" };
    }
    if (m === "pdf") {
      return t.hasAttribute("download")
        ? { icon: "download", text: "Download PDF" }
        : { icon: "pdf", text: "Open PDF" };
    }
    if (m === "read") {
      const a = t as HTMLAnchorElement;
      return { icon: "read", text: linkLabel(a.getAttribute("href") ?? "", a) ?? "Read" };
    }
    const src = (t as HTMLImageElement).currentSrc || (t as HTMLImageElement).src || "";
    return { icon: "view", text: /\.gif($|\?)/i.test(src) ? "View GIF" : "View image" };
  };

  const syncLabel = () => {
    if (!mode || !mediaEl) return;
    const { icon, text } = labelFor(mode, mediaEl);
    iconEl.innerHTML = svg(icon);
    labelEl.textContent = text;
  };

  const setMode = (next: Mode, target: HTMLElement | null) => {
    if (mediaEl && mediaEl !== target) {
      mediaEl.removeEventListener("play", syncLabel);
      mediaEl.removeEventListener("pause", syncLabel);
    }
    mode = next;
    mediaEl = target;
    if (mode && mediaEl) {
      el.dataset.mode = mode;
      if (mode === "play") {
        mediaEl.addEventListener("play", syncLabel);
        mediaEl.addEventListener("pause", syncLabel);
      }
      syncLabel();
    } else {
      delete el.dataset.mode;
    }
  };

  /* A viewer or modal on screen hides the pill. Sites often keep their
     search dialog in the DOM while closed, so only a visible one counts. */
  const dialogOpen = () =>
    Array.from(document.querySelectorAll<HTMLElement>("dialog[open], [role='dialog'][aria-modal='true']")).some(
      (d) => (d.checkVisibility ? d.checkVisibility() : d.offsetParent !== null),
    );

  const applyTarget = (target: HTMLElement | null) => {
    if (!target?.closest) return;
    el.classList.toggle("hot", Boolean(target.closest(INTERACTIVE)));
    el.classList.toggle("on-dark", isDark(target));
    const media = dialogOpen() ? null : under(target);
    setMode(media?.mode ?? null, media?.el ?? null);
  };

  const onMove = (e: MouseEvent) => {
    tx = e.clientX;
    ty = e.clientY;
    seen = true;
    wake();
  };
  const onOver = (e: MouseEvent) => applyTarget(e.target as HTMLElement | null);
  const onLeave = () => (el.style.opacity = "0");
  const onEnter = () => (el.style.opacity = "1");

  /* Content can move under a pointer that has not; look again while the
     page scrolls, once per frame. */
  let scrollRaf = 0;
  const onScroll = () => {
    if (!seen || scrollRaf) return;
    scrollRaf = requestAnimationFrame(() => {
      scrollRaf = 0;
      applyTarget(document.elementFromPoint(tx, ty) as HTMLElement | null);
    });
  };

  const onClick = (e: MouseEvent) => {
    const video = (e.target as HTMLElement | null)?.closest?.<HTMLVideoElement>("video[data-pill]");
    if (!video) return;
    const r = video.getBoundingClientRect();
    if (e.clientY > r.bottom - CONTROLS_STRIP) return;
    e.preventDefault();
    if (video.paused) void video.play().catch(() => {});
    else video.pause();
  };

  window.addEventListener("mousemove", onMove, { passive: true });
  window.addEventListener("mouseover", onOver, { passive: true });
  document.documentElement.addEventListener("mouseleave", onLeave);
  document.documentElement.addEventListener("mouseenter", onEnter);
  window.addEventListener("scroll", onScroll, { passive: true });
  window.addEventListener("click", onClick);
  place();

  return () => {
    if (raf) cancelAnimationFrame(raf);
    if (scrollRaf) cancelAnimationFrame(scrollRaf);
    setMode(null, null);
    window.removeEventListener("mousemove", onMove);
    window.removeEventListener("mouseover", onOver);
    document.documentElement.removeEventListener("mouseleave", onLeave);
    document.documentElement.removeEventListener("mouseenter", onEnter);
    window.removeEventListener("scroll", onScroll);
    window.removeEventListener("click", onClick);
    root.classList.remove("has-dmn-cursor");
    el.remove();
  };
}