// retoor <retoor@molodetz.nl>
import { Http } from "./Http.js";
export class IssueAttachments {
constructor() {
this.active = false;
document.addEventListener("submit", (event) => {
const form = event.target.closest("form[data-issue-attach]");
if (!form) return;
event.preventDefault();
this.add(form);
});
document.addEventListener("click", (event) => {
const button = event.target.closest("[data-attachment-delete]");
if (!button) return;
event.preventDefault();
this.remove(button);
});
}
async add(form) {
if (this.active) return;
const uidsInput = form.querySelector("[name='attachment_uids']");
const uids = uidsInput ? uidsInput.value.trim() : "";
if (!uids) {
window.app.toast.show("Select a file to attach first", { type: "info" });
return;
}
this.active = true;
const button = form.querySelector("button[type='submit']");
if (button) button.disabled = true;
try {
await Http.send(form.dataset.action, { attachment_uids: uids });
window.location.reload();
} catch (error) {
this.active = false;
if (button) button.disabled = false;
}
}
async remove(button) {
const confirmed = await window.app.dialog.confirm({
title: "Delete attachment",
message: "Delete this attachment? It is also removed from the tracker.",
});
if (!confirmed) return;
try {
const response = await fetch(button.dataset.action, {
method: "DELETE",
headers: { "Accept": "application/json" },
});
const data = await response.json().catch(() => ({}));
if (!response.ok || data.ok === false) {
const message = (data.error && data.error.message) || "Could not delete the attachment";
throw new Error(message);
}
const item = button.closest(".attachment-gallery-item");
if (item) item.remove();
} catch (error) {
Http.notifyError(error.message);
}
}
}