Files
dashboard/frontend/js/icons.js
T
2025-07-09 17:49:53 +07:00

87 lines
2.6 KiB
JavaScript

const iconsArea = document.querySelector("#icons");
const servicenameinput = document.querySelector("#servicenameinput");
const servicelinkinput = document.querySelector("#servicelinkinput");
const serviceimageinput = document.querySelector("#serviceimageinput");
const savecardbutton = document.querySelector("#savecardbutton");
const addcardmodalel = document.querySelector("#addcard");
const addcardmodal = new bootstrap.Modal(addcardmodalel);
var icons = [];
const renderIcons = () => {
iconsArea.innerHTML = "";
icons.map((icon) => {
iconsArea.innerHTML += `<div class="card" style="width: 16rem;">
<img src="${icon.img}" alt="${icon.alt}" class="card-img-top">
<div class="card-body">
<h5 class="card-title" style="text-align: center;">${icon.text}</h5>
<div class="d-flex flex-column gap-2">
<a href="${icon.href}" class="btn btn-primary" style="width: 100%;">Visit</a>
<button class="btn btn-danger delcard" style="width: 100%" id="${icon.key}">Delete</button>
</div>
</div>
</div>`;
});
};
const getIcons = () => {
fetch(window.location.origin + "/api/services")
.then((data) => data.json())
.then((jsondata) => {
icons = jsondata;
renderIcons();
});
};
getIcons();
savecardbutton.addEventListener("click", () => {
if (confirm("Add card?")) {
const file = serviceimageinput.files[0];
if (!file) {
alert("Please select a file to upload");
return;
}
const formdata = new FormData();
formdata.append("img", file);
formdata.append("text", servicenameinput.value);
formdata.append("href", servicelinkinput.value);
fetch(window.location.origin + "/api/services/add", {
method: "POST",
body: formdata,
})
.then((data) => data.json())
.then((jsondata) => {
if (jsondata.status === "already exists") {
alert("Service already exists");
return;
}
icons = jsondata;
renderIcons();
addcardmodal.hide();
})
.catch((error) => {
alert(error);
});
}
});
iconsArea.addEventListener("click", (e) => {
if (e.target.classList.contains("delcard")) {
if (confirm("Delete card?")) {
icons.splice(icons.indexOf(icons.find((i) => i.key === e.target.id)), 1);
fetch(window.location.origin + "/api/services", {
method: "POST",
body: JSON.stringify(icons),
})
.then((data) => data.json())
.then((jsondata) => {
icons = jsondata;
renderIcons();
})
.catch((error) => alert(error));
}
}
});