Make Project Management a native feature
- Move the storage and model of the plugin into src/lib/features/pm/ as pure TypeScript, so the skill can still bundle them. - Move the DOM interface onto the host menus, the shared tooltip, and the host icons. - A ribbon button opens Project Management. Board tabs keep the owner runestone.pm and the board-<hex> view IDs through view patterns. - Read only .runestone/pm/. Offer the plugin migration, with backups, for legacy notes. - A save, move, or delete reads only that card again. Watcher paths reach the feature. - Add Settings → Project Management and the projectManagement section. View states move to localStorage. - Background reads the boards from workspace.json. Remove api.backgrounds and the boards service. - Add yaml 2.9.1. Use the host markdown-it. - Move 18 plugin test files to tests/unit/features/pm/ and add native tests.
This commit is contained in:
@@ -0,0 +1,359 @@
|
||||
import { tooltip } from "./host.ts";
|
||||
import type { Workspace, TaskFields } from "../model/model.ts";
|
||||
import {
|
||||
imageMarkdown,
|
||||
imagePath,
|
||||
imageReferences,
|
||||
imageTypes,
|
||||
maxImageBytes,
|
||||
parseImage,
|
||||
saveImages,
|
||||
} from "../storage/images.ts";
|
||||
|
||||
/** Image data stays outside card Markdown and loads only in the open editor. */
|
||||
export function createCardImages(
|
||||
workspace: Workspace,
|
||||
description: HTMLTextAreaElement,
|
||||
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 =
|
||||
"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", "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", "Insert images in description");
|
||||
const add = control("Add image", () => input.click());
|
||||
const attachmentInput = input.cloneNode() as HTMLInputElement;
|
||||
attachmentInput.setAttribute("aria-label", "Attach images to card");
|
||||
const attach = control("Attach image", () => attachmentInput.click());
|
||||
const heading = document.createElement("h3"); heading.textContent = "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", "Image attachments");
|
||||
const attachmentsElement = document.createElement("section"); attachmentsElement.className = "pm-attachments pm-wide";
|
||||
attachmentsElement.setAttribute("aria-label", "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<string, string>();
|
||||
const loaded = new Map<string, Promise<string>>();
|
||||
let viewer: HTMLDialogElement | undefined;
|
||||
let viewerObserver: ResizeObserver | undefined;
|
||||
let idleTimer: ReturnType<typeof setTimeout> | 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("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("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, which is hidden in description previews.
|
||||
(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 pointer users can see an unobstructed 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(`Remove image ${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", `View image ${ref.name}`);
|
||||
tooltip(thumbnail, `View image ${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 = `Cannot display ${ref.name}. Restore the image file or remove its reference.`;
|
||||
};
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
async function addFiles(files: File[], attachOnly = false) {
|
||||
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 }[] = [];
|
||||
for (const file of files) {
|
||||
if (!imageTypes.includes(file.type))
|
||||
throw new Error("Use a PNG, JPEG, GIF, or WebP image.");
|
||||
if (!file.size || file.size > maxImageBytes)
|
||||
throw new Error("Use an image between 1 byte and 50 MiB.");
|
||||
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),
|
||||
);
|
||||
const data = `data:${file.type};base64,${btoa(binary)}`;
|
||||
// Decode before inserting a reference, so invalid clipboard files preserve the draft.
|
||||
const image = new Image();
|
||||
image.src = data;
|
||||
await image.decode().catch(() => {
|
||||
throw new Error(
|
||||
"The image cannot be read. Copy it again or choose another file.",
|
||||
);
|
||||
});
|
||||
staged.push({
|
||||
id: crypto.randomUUID(),
|
||||
name: (file.name || "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 }));
|
||||
} catch (reason) {
|
||||
if (!disposed)
|
||||
(attachOnly ? attachmentError : error).textContent =
|
||||
reason instanceof Error ? reason.message : String(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();
|
||||
void addFiles(files);
|
||||
};
|
||||
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);
|
||||
},
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user