import { tooltip } from "./host.ts"; import type { createCardImages } from "./images-ui.ts"; import { renderMarkdown } from "../model/markdown.ts"; import { headingEdit } from "../model/description-format.ts"; import { createDescriptionFind } from "./description-find.ts"; import { tr } from "../../../i18n/index.ts"; import { message } from "../storage/message.ts"; /** Description edits and formatted content share the card detail view. */ export function createDescriptionEditor( textarea: HTMLTextAreaElement, images: ReturnType, /** Make a control. `name` is a catalog key in English. The control shows its translation. */ control: (name: string, action: () => void) => HTMLButtonElement, persistence?: { save(): Promise; cancel(): Promise; }, ) { const element = document.createElement("section"); element.className = "pm-description-editor pm-wide"; element.setAttribute("aria-label", tr("Description")); const header = document.createElement("div"); header.className = "pm-description-heading"; const heading = document.createElement("h3"); const toggleSection = document.createElement("button"); toggleSection.type = "button"; toggleSection.className = "pm-section-toggle"; toggleSection.innerHTML = ''; toggleSection.lastElementChild!.textContent = tr("Description"); toggleSection.setAttribute("aria-expanded", "true"); heading.append(toggleSection); const source = document.createElement("label"); source.className = "pm-field pm-description-source"; textarea.setAttribute("aria-label", tr("Details (Markdown)")); source.append(textarea); const find = createDescriptionFind(textarea); const preview = document.createElement("div"); preview.className = "pm-markdown-preview"; preview.setAttribute("role", "region"); preview.setAttribute("aria-label", tr("Description preview")); const toolbar = document.createElement("div"); toolbar.className = "pm-description-toolbar"; toolbar.setAttribute("role", "group"); toolbar.setAttribute("aria-label", tr("Markdown formatting")); textarea.spellcheck = true; const resize = () => { if (source.hidden || !textarea.isConnected) return; textarea.style.height = "auto"; textarea.style.height = `${Math.max(150, textarea.scrollHeight + 2)}px`; }; let width = 0; let resizeFrame = 0; const observer = new ResizeObserver(() => { if (textarea.clientWidth && textarea.clientWidth !== width) { width = textarea.clientWidth; cancelAnimationFrame(resizeFrame); resizeFrame = requestAnimationFrame(resize); } }); observer.observe(element); let disposed = false; let revision = 0; let editing = !textarea.value.trim(); let original = textarea.value; let pending = false; const unsaved = document.createElement("span"); unsaved.className = "pm-description-unsaved"; unsaved.textContent = tr("Unsaved changes"); unsaved.hidden = true; unsaved.setAttribute("aria-live", "polite"); function insert(before: string, after: string, placeholder: string) { const start = textarea.selectionStart; const selection = textarea.value.slice(start, textarea.selectionEnd) || placeholder; textarea.setRangeText(before + selection + after, start, textarea.selectionEnd, "end"); textarea.setSelectionRange(start + before.length, start + before.length + selection.length); textarea.dispatchEvent(new Event("input", { bubbles: true })); textarea.focus(); } const formatting = [ control(message("Heading"), () => { const edit = headingEdit(textarea.value, textarea.selectionStart, textarea.selectionEnd); const direction = textarea.selectionDirection; textarea.setRangeText(edit.text, edit.start, edit.end, "preserve"); textarea.setSelectionRange(edit.selectionStart, edit.selectionEnd, direction); textarea.dispatchEvent(new Event("input", { bubbles: true })); textarea.focus(); }), control(message("Bold"), () => insert("**", "**", tr("Bold text"))), control(message("Italic"), () => insert("*", "*", tr("Italic text"))), control(message("Bullet list"), () => insert("\n- ", "\n", tr("List item"))), control(message("Link"), () => insert("[", "](https://example.com)", tr("Link text"))), control(message("Code"), () => insert("`", "`", tr("Code"))), ]; async function render() { const current = ++revision; const body = persistence && !editing ? original : textarea.value; preview.innerHTML = renderMarkdown(body); if (!body.trim()) preview.textContent = tr("Add a description."); for (const image of preview.querySelectorAll("img[data-pm-image]")) { const trigger = document.createElement("button"); trigger.type = "button"; trigger.className = "pm-image-preview-trigger"; trigger.setAttribute("aria-label", tr("View image {name}", { name: image.alt })); image.removeAttribute("title"); trigger.onclick = () => images.showImage(image, trigger); image.replaceWith(trigger); tooltip(trigger, tr("View image {name}", { name: image.alt })); trigger.append(image); const fail = (message: string) => trigger.replaceWith(document.createTextNode(message)); try { const data = await images.resolveImage(image.dataset.pmImage!); if (disposed || current !== revision) return; image.src = data; image.onerror = () => fail(tr("Cannot display image: {name}", { name: image.alt })); } catch { if (!disposed && current === revision) fail(tr("Cannot load image: {name}", { name: image.alt })); } } } const edit = control(message("Edit"), () => { if (!persistence) original = textarea.value; editing = true; update(); textarea.focus(); resize(); }); const toggle = control(message("Preview"), () => { if (!find.element.hidden) find.close(); source.hidden = !source.hidden; preview.hidden = !source.hidden; images.setEditing(!source.hidden); toggle.lastChild!.textContent = source.hidden ? tr("Edit Markdown") : tr("Preview"); toggle.setAttribute("aria-pressed", String(source.hidden)); if (source.hidden) void render(); updateLoading(); if (!source.hidden) textarea.focus(); }); const actions = document.createElement("div"); actions.className = "pm-description-actions"; const finish = async (cancel: boolean) => { if (images.isLoading() || pending) return; pending = true; updateLoading(); try { if (cancel) { textarea.value = persistence ? await persistence.cancel() : original; textarea.dispatchEvent(new Event("input", { bubbles: true })); } else await persistence?.save(); original = textarea.value; unsaved.hidden = true; editing = false; pending = false; update(); edit.focus(); } catch { /* The card editor shows the persistence error. */ } finally { pending = false; updateLoading(); } }; const cancel = control(message("Cancel"), () => { void finish(true); }); const apply = control(message("Save"), () => { void finish(false); }); actions.append(cancel, apply); for (const item of [...formatting, images.addControl]) { const name = item.textContent ?? ""; item.setAttribute("aria-label", name); item.removeAttribute("title"); item.classList.add("pm-icon-button"); for (const child of [...item.childNodes]) if (child.nodeType === Node.TEXT_NODE) child.remove(); tooltip(item, name); } toolbar.setAttribute("role", "toolbar"); toolbar.append(...formatting, images.addControl, toggle); header.append(heading, unsaved, edit); const surface = document.createElement("div"); surface.className = "pm-description-surface"; surface.append(toolbar, source); const content = document.createElement("div"); content.id = `pm-description-${crypto.randomUUID()}`; toggleSection.setAttribute("aria-controls", content.id); toggleSection.onclick = () => { content.hidden = !content.hidden; toggleSection.setAttribute("aria-expanded", String(!content.hidden)); edit.hidden = content.hidden || editing; if (!content.hidden) resize(); }; content.append(find.element, surface, preview, images.element, actions); element.append(header, content); function updateLoading() { edit.disabled = toggle.disabled = cancel.disabled = apply.disabled = images.isLoading() || pending; images.addControl.disabled = images.isLoading() || pending || !!source.hidden; for (const button of formatting) button.disabled = images.isLoading() || pending || !!source.hidden; } function update() { find.hide(); edit.hidden = editing || content.hidden; toolbar.hidden = actions.hidden = !editing; source.hidden = !editing; images.setEditing(editing); preview.hidden = editing; toggle.lastChild!.textContent = tr("Preview"); toggle.setAttribute("aria-pressed", "false"); updateLoading(); if (!editing) void render(); else { cancelAnimationFrame(resizeFrame); resizeFrame = requestAnimationFrame(resize); } } const onInput = () => { unsaved.hidden = textarea.value === original; resize(); if (document.activeElement === textarea) { const style = getComputedStyle(textarea); const mirror = document.createElement("div"); mirror.style.cssText = `position:fixed;visibility:hidden;pointer-events:none;white-space:pre-wrap;overflow-wrap:break-word;box-sizing:border-box;width:${textarea.clientWidth}px;font:${style.font};line-height:${style.lineHeight};padding:${style.padding}`; mirror.textContent = textarea.value.slice(0, textarea.selectionEnd); const marker = document.createElement("span"); marker.textContent = "\u200b"; mirror.append(marker); document.body.append(mirror); const caret = textarea.getBoundingClientRect().top + marker.offsetTop + parseFloat(style.lineHeight); mirror.remove(); const dialog = textarea.closest("dialog"); const bottomSpace = parseFloat(style.paddingBottom); if (dialog && caret + bottomSpace > dialog.getBoundingClientRect().bottom - 50) dialog.scrollTop += caret + bottomSpace - dialog.getBoundingClientRect().bottom + 50; } if (!preview.hidden) void render(); }; textarea.addEventListener("input", onInput); element.addEventListener("keydown", (event) => { if ((event.ctrlKey || event.metaKey) && !event.altKey && !event.shiftKey && event.key.toLowerCase() === "f") { event.preventDefault(); event.stopPropagation(); content.hidden = false; toggleSection.setAttribute("aria-expanded", "true"); if (!editing) { editing = true; update(); } if (source.hidden) toggle.click(); find.open(); return; } if (event.key === "Escape" && !find.element.hidden) { event.preventDefault(); event.stopPropagation(); find.close(); return; } if (event.key === "Escape" && editing && !element.querySelector("dialog[open], :popover-open")) { event.preventDefault(); event.stopPropagation(); editing = false; update(); edit.focus(); } }); update(); return { element, updateLoading, resize, restoreDraft(body: string) { textarea.value = body; unsaved.hidden = body === original; // Keep the saved description visible until the user opens the draft. if (editing) resize(); }, saved(body: string) { original = body; unsaved.hidden = textarea.value === body; }, dispose() { disposed = true; find.dispose(); cancelAnimationFrame(resizeFrame); observer.disconnect(); revision++; textarea.removeEventListener("input", onInput); }, }; }