104 lines
3.4 KiB
JavaScript
104 lines
3.4 KiB
JavaScript
/**
|
|
* Initialisiert die Kommentarfunktion.
|
|
*
|
|
* Kommentare werden per AJAX gespeichert,
|
|
* ohne dass die Seite neu geladen werden muss.
|
|
*/
|
|
document.addEventListener("DOMContentLoaded", function () {
|
|
const form = document.getElementById("comment-form");
|
|
const commentsList = document.getElementById("comments-list");
|
|
const commentContent = document.getElementById("comment-content");
|
|
const parentCommentInput = document.getElementById("parent-comment-id");
|
|
const replyInfo = document.getElementById("reply-info");
|
|
|
|
if (!form || !commentsList || !commentContent || !parentCommentInput || !replyInfo) {
|
|
return;
|
|
}
|
|
|
|
/**
|
|
* Registriert alle Antwort-Buttons.
|
|
*/
|
|
document.querySelectorAll(".reply-button").forEach(function (button) {
|
|
button.addEventListener("click", function () {
|
|
parentCommentInput.value = button.dataset.commentId;
|
|
replyInfo.textContent = "Antwort auf " + button.dataset.author;
|
|
replyInfo.style.display = "block";
|
|
commentContent.focus();
|
|
});
|
|
});
|
|
|
|
/**
|
|
* Sendet Kommentare per AJAX an den Server.
|
|
*/
|
|
form.addEventListener("submit", function (event) {
|
|
event.preventDefault();
|
|
|
|
const formData = new FormData(form);
|
|
const parentCommentId = parentCommentInput.value;
|
|
|
|
fetch("php/ajax/add-comment.php", {
|
|
method: "POST",
|
|
body: formData
|
|
})
|
|
.then(response => response.json())
|
|
.then(data => {
|
|
if (!data.success) {
|
|
alert(data.message);
|
|
return;
|
|
}
|
|
|
|
const emptyMessage = commentsList.querySelector(".no-comments-message");
|
|
|
|
if (emptyMessage) {
|
|
emptyMessage.remove();
|
|
}
|
|
|
|
const commentElement = document.createElement("div");
|
|
commentElement.classList.add("comment-item");
|
|
|
|
if (parentCommentId) {
|
|
commentElement.classList.add("comment-reply");
|
|
}
|
|
|
|
commentElement.innerHTML = `
|
|
<p>
|
|
<strong>${escapeHtml(data.author)}</strong>
|
|
<span>${escapeHtml(data.created)}</span>
|
|
</p>
|
|
<p>${escapeHtml(data.content).replace(/\n/g, "<br>")}</p>
|
|
`;
|
|
|
|
if (parentCommentId) {
|
|
const parentReplies = document.querySelector(
|
|
`.comment-item[data-comment-id="${parentCommentId}"] .comment-replies`
|
|
);
|
|
|
|
if (parentReplies) {
|
|
parentReplies.appendChild(commentElement);
|
|
}
|
|
} else {
|
|
commentsList.prepend(commentElement);
|
|
}
|
|
|
|
commentContent.value = "";
|
|
parentCommentInput.value = "";
|
|
replyInfo.textContent = "";
|
|
replyInfo.style.display = "none";
|
|
})
|
|
.catch(() => {
|
|
alert("Kommentar konnte nicht gesendet werden.");
|
|
});
|
|
});
|
|
|
|
/**
|
|
* Entfernt HTML-Sonderzeichen aus Nutzereingaben.
|
|
*
|
|
* @param {string} text Zu bereinigender Text
|
|
* @returns {string} Sicherer Text
|
|
*/
|
|
function escapeHtml(text) {
|
|
const div = document.createElement("div");
|
|
div.textContent = text;
|
|
return div.innerHTML;
|
|
}
|
|
}); |