import { tooltip } from "./host.ts"; import { message, tr } from "../../../i18n/index.ts"; import { errorText } from "./text.ts"; import type { Workspace, TaskFields } from "../model/model.ts"; import { imageMarkdown, imagePath, imageReferences, imageTypes, maxImageBytes, parseImage, saveImages, } from "../storage/images.ts"; import { workspaceDownloadImage } from "../../../workspace/api.ts"; import { copiedImage } from "../../../workspace/copiedImage.ts"; import { mayAnimate, pastedImageSource } from "../../../workspace/media.ts"; async function fileDataUrl(file: File) { const bytes = new Uint8Array(await file.arrayBuffer()); let binary = ""; for (let offset = 0; offset < bytes.length; offset += 8192) binary += String.fromCharCode(...bytes.subarray(offset, offset + 8192)); return `data:${file.type};base64,${btoa(binary)}`; } /** * The original of a copied web image. The RuneStone browser keeps the bytes of the image that it copied. * For a copy from another browser, download the original of a format with frames. * Undefined keeps the still copy. "refused" means that the website did not give the original. */ async function webImage(source: string): Promise<{ data: string; type: string } | "refused" | undefined> { const data = await copiedImage(source) ?? (mayAnimate(source) ? await workspaceDownloadImage(source).catch(() => "") : undefined); if (data === undefined) return undefined; if (!data) return "refused"; const type = /^data:([^;]+);/.exec(data)?.[1] ?? ""; return imageTypes.includes(type) ? { data, type } : undefined; } /** The image data stays outside the card Markdown and loads only in the open editor. */ export function createCardImages( workspace: Workspace, description: HTMLTextAreaElement, /** Make a control. `name` is a catalog key in English. The control shows its translation. */ control: (name: string, action: () => void) => HTMLButtonElement, removeControl: (name: string, action: () => void) => HTMLButtonElement, changed: (loading: boolean) => void, initialAttachments: TaskFields["attachments"] = [], ) { const attachments = structuredClone(initialAttachments); const element = document.createElement("div"); element.className = "pm-card-images pm-wide"; const hint = document.createElement("p"); hint.className = "pm-muted"; hint.id = `pm-image-hint-${crypto.randomUUID()}`; hint.textContent = tr("Paste or drop an image into Details, or choose Add image. PNG, JPEG, GIF, or WebP. Up to 50 MiB each."); description.setAttribute("aria-describedby", hint.id); const error = document.createElement("p"); error.className = "pm-error"; error.setAttribute("role", "alert"); const gallery = document.createElement("div"); gallery.className = "pm-image-gallery"; gallery.setAttribute("role", "group"); gallery.setAttribute("aria-label", tr("Images in card details")); const input = document.createElement("input"); input.type = "file"; input.accept = imageTypes.join(","); input.multiple = true; input.hidden = true; input.setAttribute("aria-label", tr("Insert images in description")); const add = control(message("Add image"), () => input.click()); const attachmentInput = input.cloneNode() as HTMLInputElement; attachmentInput.setAttribute("aria-label", tr("Attach images to card")); const attach = control(message("Attach image"), () => attachmentInput.click()); const heading = document.createElement("h3"); heading.textContent = tr("Attachments"); const header = document.createElement("div"); header.className = "pm-attachment-heading"; header.append(heading, attach); const attachmentGallery = document.createElement("div"); attachmentGallery.className = "pm-image-gallery"; attachmentGallery.setAttribute("role", "group"); attachmentGallery.setAttribute("aria-label", tr("Image attachments")); const attachmentsElement = document.createElement("section"); attachmentsElement.className = "pm-attachments pm-wide"; attachmentsElement.setAttribute("aria-label", tr("Attachments")); const attachmentError = document.createElement("p"); attachmentError.className = "pm-error"; attachmentError.setAttribute("role", "alert"); attachmentsElement.append(header, attachmentInput, attachmentError, attachmentGallery); element.append(input, hint, error, gallery); const pending = new Map(); const loaded = new Map>(); let viewer: HTMLDialogElement | undefined; let viewerObserver: ResizeObserver | undefined; let idleTimer: ReturnType | undefined; let disposed = false, loading = false, saving = false, revision = 0; function updateControls() { description.disabled = add.disabled = attach.disabled = loading || saving; [...element.querySelectorAll("button"), ...attachmentsElement.querySelectorAll("button")].forEach((button) => { button.disabled = loading || saving; }); } function showImage(source: HTMLImageElement, trigger: HTMLButtonElement) { if (viewer || disposed || !source.complete || !source.naturalWidth) return; const dialog = document.createElement("dialog"); dialog.className = "pm-image-viewer"; viewer = dialog; const header = document.createElement("div"); header.className = "pm-image-viewer-header"; const title = document.createElement("h2"); title.id = `pm-image-title-${crypto.randomUUID()}`; title.textContent = source.alt; dialog.setAttribute("aria-labelledby", title.id); const frame = document.createElement("div"); frame.className = "pm-image-frame"; const full = document.createElement("img"); full.src = source.src; full.alt = source.alt; frame.append(full); const size = control(message("Actual size"), () => { const actual = frame.classList.toggle("pm-image-actual"); size.setAttribute("aria-pressed", String(actual)); placeControls(); }); size.setAttribute("aria-pressed", "false"); const close = removeControl(tr("Close image"), () => dialog.close()); header.append(title, size, close); dialog.append(header, frame); const placeControls = () => { if (!dialog.open) return; const bounds = full.getBoundingClientRect(); const actual = frame.classList.contains("pm-image-actual"); const width = actual ? dialog.clientWidth - 16 : Math.min(dialog.clientWidth - 16, Math.max(320, bounds.width - 16)); header.style.width = `${width}px`; header.style.left = `${Math.max(8, (dialog.clientWidth - width) / 2)}px`; header.style.right = "auto"; header.style.top = `${actual ? 8 : Math.max(8, bounds.top + 8)}px`; }; const observer = new ResizeObserver(placeControls); viewerObserver = observer; observer.observe(full); observer.observe(frame); full.onload = placeControls; dialog.onclose = () => { clearTimeout(idleTimer); observer.disconnect(); viewerObserver = undefined; dialog.remove(); viewer = undefined; if (!disposed && trigger.isConnected) trigger.focus({ preventScroll: true }); }; // Keep the viewer outside the gallery, because the description preview hides the gallery. (description.closest(".pm-editor") ?? element.parentElement ?? element).append(dialog); const outside = (target: EventTarget | null) => target === dialog || target === frame; let outsidePointer = false; dialog.addEventListener("pointerdown", (event) => { outsidePointer = event.isPrimary && event.button === 0 && outside(event.target); event.stopPropagation(); }); dialog.addEventListener("pointercancel", () => { outsidePointer = false; }); dialog.addEventListener("click", (event) => { event.stopPropagation(); if (outsidePointer && outside(event.target)) dialog.close(); outsidePointer = false; }); dialog.addEventListener("keydown", (event) => { if (event.key === "Escape") { event.preventDefault(); event.stopPropagation(); dialog.close(); } }); dialog.addEventListener("cancel", (event) => { event.preventDefault(); event.stopPropagation(); dialog.close(); }); dialog.showModal(); placeControls(); // Focus the surface first, so that a pointer user can see all of the image. dialog.tabIndex = -1; dialog.focus(); idleTimer = setTimeout(() => dialog.classList.add("pm-image-controls-idle"), 2000); } async function render() { const current = ++revision; gallery.replaceChildren(); attachmentGallery.replaceChildren(); for (const ref of [...imageReferences(description.value), ...attachments]) { const attached = !("index" in ref); const figure = document.createElement("figure"); const caption = document.createElement("figcaption"); const name = document.createElement("span"); name.textContent = ref.name; name.title = ref.name; caption.append( name, removeControl(tr("Remove image {name}", { name: ref.name }), () => { if (attached) { attachments.splice(attachments.findIndex(item => item.id === ref.id), 1); description.dispatchEvent(new Event("input", { bubbles: true })); return; } const references = imageReferences(description.value); const match = references.find( (item) => item.id === ref.id && item.index === ref.index, ); if (!match) return; description.setRangeText( "", match.index, match.index + match.markdown.length, "preserve", ); description.dispatchEvent(new Event("input", { bubbles: true })); description.focus(); }), ); const image = document.createElement("img"); image.alt = ref.name; image.loading = "lazy"; const thumbnail = document.createElement("button"); thumbnail.type = "button"; thumbnail.className = "pm-image-thumbnail"; thumbnail.setAttribute("aria-label", tr("View image {name}", { name: ref.name })); tooltip(thumbnail, tr("View image {name}", { name: ref.name })); thumbnail.onclick = () => showImage(image, thumbnail); thumbnail.append(image); const failure = document.createElement("p"); failure.className = "pm-error"; failure.setAttribute("role", "alert"); const fail = () => { thumbnail.remove(); failure.textContent = tr("Cannot display {name}. Restore the image file or remove its reference.", { name: ref.name }); }; image.onerror = fail; figure.append(thumbnail, caption, failure); (attached ? attachmentGallery : gallery).append(figure); updateControls(); let data = pending.get(ref.id); try { if (!data) { let promise = loaded.get(ref.id); if (!promise) { promise = workspace.read(imagePath(ref.id)).then(parseImage); loaded.set(ref.id, promise); } data = await promise; } if (disposed || current !== revision) return; image.src = data; } catch { if (!disposed && current === revision) fail(); } } } /** `source` is the web address of the original of a copied image. `files` holds its still copy. */ async function addFiles(files: File[], attachOnly = false, source?: string) { if (disposed || loading || description.disabled || !files.length) return; loading = true; updateControls(); changed(true); error.textContent = ""; attachmentError.textContent = ""; const start = description.selectionStart, end = description.selectionEnd; try { const staged: { id: string; name: string; data: string }[] = []; let refused = false; for (const file of files) { // A browser copies only the first frame of a web image. The original keeps all of its frames. const web = source ? await webImage(source) : undefined; refused ||= web === "refused"; const original = typeof web === "object" ? web : undefined; if (!original && !imageTypes.includes(file.type)) throw new Error(message("Use a PNG, JPEG, GIF, or WebP image.")); if (!original && !file.size) throw new Error(message("The image file is empty. A browser can give an empty file when the website refuses a download. To add the image, copy it in the RuneStone browser. You can also save the image and add the saved file.")); if (!original && file.size > maxImageBytes) throw new Error(message("Use an image between 1 byte and 50 MiB.")); const data = original?.data ?? await fileDataUrl(file); const name = original ? `${(file.name || "image").replace(/\.\w+$/, "")}.${original.type.slice(6)}` : file.name; // Decode the image before the reference goes in, so that an invalid clipboard file keeps the draft. const image = new Image(); image.src = data; await image.decode().catch(() => { throw new Error(message("The image cannot be read. Copy it again or choose another file.")); }); staged.push({ id: crypto.randomUUID(), name: (name || tr("Pasted image")).slice(0, 255), data, }); } if (disposed) return; for (const image of staged) pending.set(image.id, image.data); if (attachOnly) attachments.push(...staged.map(({ id, name }) => ({ id, name }))); else { const markdown = staged.map((image) => imageMarkdown(image.name, image.id)).join("\n"); description.setRangeText(`\n${markdown}\n`, start, end, "end"); } description.dispatchEvent(new Event("input", { bubbles: true })); if (refused) error.textContent = tr("The website refused the original image, so RuneStone added only its first frame. To keep the animation, copy the image in the RuneStone browser. You can also save the image and add the saved file."); } catch (reason) { if (!disposed) (attachOnly ? attachmentError : error).textContent = errorText(reason); } finally { loading = false; if (!disposed) { updateControls(); changed(false); (attachOnly ? attach : description).focus(); } } } const paste = (event: ClipboardEvent) => { const files = Array.from(event.clipboardData?.files ?? []).filter((file) => file.type.startsWith("image/"), ); if (!files.length) return; event.preventDefault(); event.stopPropagation(); // Read the HTML now. The clipboard data is empty after the paste event. const source = files.length === 1 ? pastedImageSource(event.clipboardData?.getData("text/html") ?? "") : undefined; void addFiles(files, false, source); }; const dragOver = (event: DragEvent) => { if (event.dataTransfer?.types.includes("Files")) { event.preventDefault(); event.stopPropagation(); } }; const drop = (event: DragEvent) => { const files = Array.from(event.dataTransfer?.files ?? []); if (!files.length) return; event.preventDefault(); event.stopPropagation(); void addFiles(files); }; description.addEventListener("dragover", dragOver); description.addEventListener("drop", drop); description.addEventListener("paste", paste); description.addEventListener("input", render); input.onchange = () => { void addFiles(Array.from(input.files ?? [])); input.value = ""; }; attachmentInput.onchange = () => { void addFiles(Array.from(attachmentInput.files ?? []), true); attachmentInput.value = ""; }; void render(); return { element, attachmentsElement, addControl: add, value: () => structuredClone(attachments), references: () => [...imageReferences(description.value), ...attachments], setEditing(value: boolean) { element.hidden = !value; }, showImage, async resolveImage(id: string) { const data = pending.get(id); if (data) return data; let promise = loaded.get(id); if (!promise) { promise = workspace.read(imagePath(id)).then(parseImage); loaded.set(id, promise); } return promise; }, isLoading: () => loading, setSaving(value: boolean) { saving = value; updateControls(); }, save: (body: string) => saveImages(workspace, body, pending, attachments), dispose() { disposed = true; clearTimeout(idleTimer); viewerObserver?.disconnect(); viewerObserver = undefined; viewer?.remove(); viewer = undefined; revision++; pending.clear(); loaded.clear(); description.removeEventListener("paste", paste); description.removeEventListener("input", render); description.removeEventListener("dragover", dragOver); description.removeEventListener("drop", drop); }, }; }