import { actionIcon, type ActionIcon } from "../ui/actionIcons"; import { actionMenu, type ActionMenuItem } from "../ui/actionMenu"; export type ImageActions = { edit?: () => void; done?: () => void; editing?: boolean; select?: () => void; remove?: () => void; markdown?: () => string; swap?: (image: HTMLImageElement) => Promise; open?: (image: HTMLImageElement) => void; reveal?: (image: HTMLImageElement) => Promise; report?: (message: string) => void; }; async function copyImage(image: HTMLImageElement) { const png = (async () => { await image.decode(); const canvas = document.createElement("canvas"); canvas.width = image.naturalWidth; canvas.height = image.naturalHeight; const context = canvas.getContext("2d"); if (!context) throw new Error("Image clipboard is unavailable."); context.drawImage(image, 0, 0); return await new Promise((resolve, reject) => canvas.toBlob(blob => blob ? resolve(blob) : reject(new Error("Could not copy image.")), "image/png")); })(); await navigator.clipboard.write([new ClipboardItem({ "image/png": png })]); } function button(label: string, icon: ActionIcon, action: () => void) { const control = document.createElement("button"); control.type = "button"; control.className = "image-action"; control.setAttribute("aria-label", label); control.dataset.tooltip = label; control.append(actionIcon(icon)); control.addEventListener("click", event => { event.preventDefault(); event.stopPropagation(); action(); }); return control; } function zoomImage(original: HTMLImageElement, trigger: HTMLButtonElement) { const dialog = document.createElement("dialog"); dialog.className = "image-lightbox"; dialog.setAttribute("aria-label", "Image zoom"); const header = document.createElement("div"); header.className = "image-lightbox-toolbar"; const name = document.createElement("span"); name.className = "image-lightbox-name"; name.textContent = original.dataset.mdSrc || original.alt || "Image"; const viewport = document.createElement("div"); viewport.className = "image-lightbox-viewport"; const image = original.cloneNode() as HTMLImageElement; image.removeAttribute("loading"); image.draggable = false; let scale = 0; const status = document.createElement("span"); status.className = "image-lightbox-scale"; status.setAttribute("aria-live", "polite"); function resize(next: number) { scale = next; image.style.width = scale ? `${image.naturalWidth * scale}px` : ""; viewport.classList.toggle("is-zoomed", scale > 0); status.textContent = scale ? `${Math.round(scale * 100)}%` : "Fit"; zoomOut.disabled = scale === 0; zoomIn.disabled = scale >= 4; } const zoomOut = button("Zoom out", "zoom-out", () => resize(scale <= .5 ? 0 : scale / 2)); const zoomIn = button("Zoom in", "zoom-in", () => resize(scale ? Math.min(4, scale * 2) : 1)); const fit = button("Fit image", "select", () => resize(0)); const close = button("Close image", "close", () => dialog.close()); header.append(name, zoomOut, status, zoomIn, fit, close); viewport.append(image); dialog.append(header, viewport); dialog.addEventListener("click", event => { if (event.target === dialog || event.target === viewport) dialog.close(); }); // Escape and focus trapping are provided by the native modal dialog. dialog.addEventListener("close", () => { dialog.remove(); if (trigger.isConnected) trigger.focus(); }, { once: true }); image.addEventListener("load", () => resize(scale)); document.body.append(dialog); dialog.showModal(); resize(0); close.focus(); return () => { if (dialog.isConnected) dialog.close(); }; } export function imageControls(root: HTMLElement, actions: ImageActions = {}, measure?: () => void): () => void { const cleanup: (() => void)[] = []; for (const image of root.querySelectorAll("img[data-md-src]")) { if (image.closest(".md-image-frame")) continue; const frame = document.createElement("span"); frame.className = "md-image-frame"; frame.contentEditable = "false"; frame.tabIndex = 0; frame.setAttribute("role", "group"); frame.setAttribute("aria-label", `Image: ${image.alt || image.dataset.mdSrc || "image"}`); image.replaceWith(frame); frame.append(image); image.draggable = false; const toolbar = document.createElement("span"); toolbar.className = "md-image-actions"; let closeZoom: (() => void) | undefined; const zoom = button("Zoom in", "zoom-in", () => { closeZoom = zoomImage(image, zoom); }); cleanup.push(() => closeZoom?.()); toolbar.append(zoom); if (actions.edit) toolbar.append(button(actions.editing ? "Hide image source" : "Edit image source", "code", actions.editing && actions.done ? actions.done : actions.edit)); frame.append(toolbar); let menu: HTMLElement | undefined; let openingMenu = false; function closeMenu(focus = true) { menu?.remove(); menu = undefined; if (focus && frame.isConnected) frame.focus({ preventScroll: true }); } async function run(action: () => void | Promise) { closeMenu(false); try { await action(); } catch (error) { const message = error instanceof Error ? error.message : String(error); if (actions.report) actions.report(message); else { frame.dataset.error = message; frame.setAttribute("aria-description", message); } } } function select() { actions.select?.(); frame.classList.add("is-selected"); frame.focus({ preventScroll: true }); } function openMenu(x: number, y: number) { closeMenu(false); select(); const items: ActionMenuItem[] = [ { label: "Copy image", icon: "copy", run: () => void run(() => copyImage(image)) }, ...(actions.markdown ? [{ label: "Copy Markdown", icon: "code" as const, run: () => void run(() => navigator.clipboard.writeText(actions.markdown!())) }] : []), ...(actions.swap ? [{ label: "Swap image…", icon: "swap" as const, run: () => void run(() => actions.swap!(image)) }] : []), ...(actions.remove ? [{ label: "Remove image", icon: "trash" as const, run: () => void run(actions.remove!) }] : []), { separator: true }, { label: "Zoom in", icon: "zoom-in", run: () => { closeMenu(false); closeZoom = zoomImage(image, zoom); } }, ...(actions.edit ? [{ label: "Edit image source", icon: "code" as const, run: () => void run(actions.edit!) }] : []), ...(actions.open ? [{ label: "Open in new tab", icon: "external" as const, run: () => void run(() => actions.open!(image)) }] : []), { label: "Copy path", icon: "link", run: () => void run(() => navigator.clipboard.writeText(image.dataset.mdSrc || "")) }, ...(actions.reveal && !/^https?:/i.test(image.dataset.mdSrc || "") ? [{ label: "Show in Explorer", icon: "external" as const, run: () => void run(() => actions.reveal!(image)) }] : []), ]; openingMenu = true; try { menu = actionMenu(x, y, items, closeMenu, "Image actions"); } finally { openingMenu = false; } } frame.addEventListener("mousedown", event => { if (!(event.target as Element).closest("button")) { event.preventDefault(); event.stopPropagation(); select(); } }); frame.addEventListener("contextmenu", event => { event.preventDefault(); event.stopPropagation(); openMenu(event.clientX, event.clientY); }); frame.addEventListener("keydown", event => { if (event.target !== frame) return; if (event.key === "ContextMenu" || (event.shiftKey && event.key === "F10")) { event.preventDefault(); event.stopPropagation(); const rect = frame.getBoundingClientRect(); openMenu(rect.left + 16, rect.top + 16); } else if ((event.key === "Delete" || event.key === "Backspace") && actions.remove) { event.preventDefault(); event.stopPropagation(); actions.remove(); } else if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "c") { event.preventDefault(); event.stopPropagation(); void run(() => copyImage(image)); } else if (event.key === "Enter" || event.key === " ") { event.preventDefault(); select(); } }); const outside = (event: Event) => { if (openingMenu) return; if (event.target instanceof Node && !frame.contains(event.target) && !menu?.contains(event.target)) { closeMenu(false); frame.classList.remove("is-selected"); } }; const dismiss = () => closeMenu(false); const scroll = (event: Event) => { if (menu && event.target instanceof Node && !menu.contains(event.target)) closeMenu(false); }; document.addEventListener("mousedown", outside, true); document.addEventListener("focusin", outside, true); window.addEventListener("resize", dismiss); document.addEventListener("scroll", scroll, true); cleanup.push(() => { closeMenu(false); document.removeEventListener("mousedown", outside, true); document.removeEventListener("focusin", outside, true); window.removeEventListener("resize", dismiss); document.removeEventListener("scroll", scroll, true); }); if (measure) { image.addEventListener("load", measure); image.addEventListener("error", measure); cleanup.push(() => { image.removeEventListener("load", measure); image.removeEventListener("error", measure); }); } } return () => cleanup.forEach(dispose => dispose()); }