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
viewer.tsTypeScript65 lines2.3 KiBraw download
/**
 * A small image viewer for sheet images, so the cursor's "View image"
 * pill does what it says. A native <dialog>: Escape, a click anywhere or
 * the close button dismisses it, focus returns to the image, and the
 * page behind is inert while it is open.
 *
 * Images inside a link keep the link's behaviour; tiny inline images
 * (badges, icons) are left alone.
 */
let dialog: HTMLDialogElement | null = null;
let shown: HTMLImageElement | null = null;

function ensureDialog(): HTMLDialogElement {
  if (dialog && dialog.isConnected) return dialog;
  dialog = document.createElement('dialog');
  dialog.className = 'dmn-viewer';
  dialog.setAttribute('aria-label', 'Image viewer');
  const img = document.createElement('img');
  img.className = 'dmn-viewer__img';
  const cap = document.createElement('p');
  cap.className = 'dmn-viewer__cap';
  const close = document.createElement('button');
  close.type = 'button';
  close.className = 'dmn-viewer__close';
  close.textContent = 'Close';
  dialog.append(img, cap, close);
  dialog.addEventListener('click', () => dialog?.close());
  dialog.addEventListener('close', () => shown?.focus({ preventScroll: true }));
  document.body.appendChild(dialog);
  return dialog;
}

function open(from: HTMLImageElement): void {
  const d = ensureDialog();
  const img = d.querySelector<HTMLImageElement>('.dmn-viewer__img')!;
  const cap = d.querySelector<HTMLElement>('.dmn-viewer__cap')!;
  img.src = from.currentSrc || from.src;
  img.alt = from.alt;
  cap.textContent = from.alt || '';
  cap.hidden = !from.alt;
  shown = from;
  d.showModal();
}

export function initViewer(): void {
  document.querySelectorAll<HTMLImageElement>('.prose img:not([data-zoomable])').forEach((img) => {
    if (img.closest('a')) return;
    const mark = () => {
      if (img.naturalWidth && img.naturalWidth < 120) return;
      img.dataset.zoomable = '';
      img.tabIndex = 0;
      img.setAttribute('role', 'button');
      img.setAttribute('aria-label', img.alt ? `Enlarge image: ${img.alt}` : 'Enlarge image');
      img.addEventListener('click', () => open(img));
      img.addEventListener('keydown', (e) => {
        if (e.key === 'Enter' || e.key === ' ') {
          e.preventDefault();
          open(img);
        }
      });
    };
    if (img.complete) mark();
    else img.addEventListener('load', mark, { once: true });
  });
}