import { tr } from '../i18n/index.ts'; import { revealLabel } from '../ui/menuItems.ts'; import { actionIcon, type ActionIcon } from "../ui/actionIcons"; import { attachTooltip } from "../ui/tooltip"; const tooltipCleanups = new WeakMap void>(); import type { ActionMenuItem } from "../ui/actionMenu"; import { showActionMenu, type MenuHandle } from "../ui/managedActionMenu"; import { imageSize, rememberImageSize } from "../workspace/imageSizes"; 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(tr("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); tooltipCleanups.set(control, attachTooltip(control, () => 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", tr("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 || tr("Image"); const viewport = document.createElement("div"); viewport.className = "image-lightbox-viewport"; const image = original.cloneNode() as HTMLImageElement; image.removeAttribute("loading"); image.removeAttribute("width"); image.removeAttribute("height"); 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)}%` : tr("Fit"); zoomOut.disabled = scale === 0; zoomIn.disabled = scale >= 4; } const zoomOut = button(tr("Zoom out"), "zoom-out", () => resize(scale <= .5 ? 0 : scale / 2)); const zoomIn = button(tr("Zoom in"), "zoom-in", () => resize(scale ? Math.min(4, scale * 2) : 1)); const fit = button(tr("Fit image"), "select", () => resize(0)); const close = button(tr("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", () => { [zoomOut, zoomIn, fit, close].forEach(button => tooltipCleanups.get(button)?.()); 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; // A remote image gives its size when it loads. The next view of this image keeps its space from the start. const remember = () => rememberImageSize(image.src, image.naturalWidth, image.naturalHeight); image.addEventListener("load", remember); cleanup.push(() => image.removeEventListener("load", remember)); const known = !image.getAttribute("width") && imageSize(image.src); if (known) { image.width = known.width; image.height = known.height; } const frame = document.createElement("span"); frame.className = "md-image-frame"; frame.contentEditable = "false"; frame.tabIndex = 0; frame.setAttribute("role", "group"); frame.setAttribute("aria-label", tr("Image: {name}", { name: image.alt || image.dataset.mdSrc || tr("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(tr("Zoom in"), "zoom-in", () => { closeZoom = zoomImage(image, zoom); }); cleanup.push(() => closeZoom?.()); toolbar.append(zoom); if (actions.edit) toolbar.append(button(actions.editing ? tr("Hide image source") : tr("Edit image source"), "code", actions.editing && actions.done ? actions.done : actions.edit)); frame.append(toolbar); cleanup.push(() => toolbar.querySelectorAll("button").forEach(button => tooltipCleanups.get(button)?.())); let menu: MenuHandle | undefined; let openingMenu = false; const restore = () => { if (frame.isConnected) frame.focus({ preventScroll: true }); }; function closeMenu(focus = true) { menu?.close(); menu = undefined; if (focus) restore(); } 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: tr("Copy image"), icon: "copy", run: () => void run(() => copyImage(image)) }, ...(actions.markdown ? [{ label: tr("Copy Markdown"), icon: "code" as const, run: () => void run(() => navigator.clipboard.writeText(actions.markdown!())) }] : []), ...(actions.swap ? [{ label: tr("Swap image…"), icon: "swap" as const, run: () => void run(() => actions.swap!(image)) }] : []), ...(actions.remove ? [{ label: tr("Remove image"), icon: "trash" as const, run: () => void run(actions.remove!) }] : []), { separator: true }, { label: tr("Zoom in"), icon: "zoom-in", run: () => { closeMenu(false); closeZoom = zoomImage(image, zoom); } }, ...(actions.edit ? [{ label: tr("Edit image source"), icon: "code" as const, run: () => void run(actions.edit!) }] : []), ...(actions.open ? [{ label: tr("Open in new tab"), icon: "external" as const, run: () => void run(() => actions.open!(image)) }] : []), { label: tr("Copy path"), icon: "link", run: () => void run(() => navigator.clipboard.writeText(image.dataset.mdSrc || "")) }, ...(actions.reveal && !/^https?:/i.test(image.dataset.mdSrc || "") ? [{ label: tr(revealLabel()), icon: "folder" as const, run: () => void run(() => actions.reveal!(image)) }] : []), ]; openingMenu = true; try { menu = showActionMenu({ x, y, items, label: tr("Image actions") }, undefined, restore); } 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?.element.contains(event.target)) { closeMenu(false); frame.classList.remove("is-selected"); } }; // The shared menu closes itself. This handler also clears the image selection. document.addEventListener("mousedown", outside, true); document.addEventListener("focusin", outside, true); cleanup.push(() => { closeMenu(false); document.removeEventListener("mousedown", outside, true); document.removeEventListener("focusin", outside, 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()); }