Untitled
unknown
javascript
a year ago
12 kB
2
Indexable
Never
import AbstractView from "./AbstractView.js"; import { renderPostModal } from "./Dashboard.js"; export default class extends AbstractView { constructor(params) { super(params); this.setTitle("Single Post"); } async getHtml() { // Create a container for the post details and comments const container = document.createElement("div"); container.id = "single-post-container"; const app = document.getElementById("app"); // Call the rendering function to populate the container await renderSinglePost(this.params.id, container); // Return the container's innerHTML as the view's content return container.innerHTML; } } async function renderSinglePost(postID, container) { const loggedInUsername = localStorage.getItem("loggedInUsername") || ""; try { // Fetch post details using the provided postID const response = await fetch(`http://localhost:8083/getAllPosts/${postID}`, { credentials: 'include', }); const postData = await response.json(); renderPostModal(postData) console.log(postData); const postContainer = document.getElementsByClassName('post'); // Clear the container's previous content postContainer.innerHTML = ''; // Create post details elements const postElement = document.createElement("div"); postElement.classList.add("post"); postElement.setAttribute("postID", postData.post.post.postID); // ... Create and append titleElement and contentElement as before ... const detailsElement = document.createElement("div"); detailsElement.classList.add("details"); const titleElement = document.createElement("h2"); titleElement.textContent = postData.post.post.title; detailsElement.appendChild(titleElement); const contentElement = document.createElement("p"); contentElement.textContent = postData.post.post.content; detailsElement.appendChild(contentElement); const likeButton = document.createElement("button"); likeButton.textContent = "Like"; likeButton.id = `like-button-post-${postData.post.post.postID}`; likeButton.classList.add("like-button"); const dislikeButton = document.createElement("button"); dislikeButton.textContent = "Dislike"; dislikeButton.id = `dislike-button-post-${postData.post.post.postID}`; dislikeButton.classList.add("dislike-button"); // Attach event listeners to the buttons likeButton.addEventListener("click", () => handlePostVote(postData.post.post.postID, "like")); dislikeButton.addEventListener("click", () => handlePostVote(postData.post.post.postID, "dislike")); // Append buttons to postElement postElement.appendChild(likeButton); postElement.appendChild(dislikeButton); postElement.appendChild(detailsElement); // Create the comment input form const addCommentForm = document.createElement("form"); addCommentForm.classList.add("add-comment-form"); // ... Create and append comment input and submit button ... postElement.appendChild(addCommentForm); if (loggedInUsername !== "") { const container = document.createElement("div"); container.classList.add("comment-container"); addCommentForm.appendChild(container); const commentInput = document.createElement("textarea"); commentInput.placeholder = "Enter your comment"; commentInput.classList.add("comment-input"); commentInput.id = "comment"; container.appendChild(commentInput); const submitButton = document.createElement("button"); submitButton.type = "button"; submitButton.textContent = "Submit comment"; submitButton.classList.add("submit-button"); submitButton.id = "comment-submit"; container.appendChild(submitButton); } postElement.appendChild(addCommentForm); if (postData.post.comments != null) { const commentsContainer = document.createElement("div"); postData.post.comments.forEach((comment, index) => { const commentElement = document.createElement("div"); const infoElement = document.createElement("div"); infoElement.classList.add("info"); const userInfoDiv = document.createElement("div"); userInfoDiv.classList.add("user-info") const creationDateDiv = document.createElement("div"); creationDateDiv.classList.add("creation-date") userInfoDiv.textContent = comment.username; const creationDate = new Date(comment.creation_date) creationDateDiv.textContent = creationDate.toLocaleString(); infoElement.appendChild(userInfoDiv); infoElement.appendChild(creationDateDiv); commentElement.textContent = comment.content; commentElement.classList.add("comment"); commentElement.id = comment.comment_id; postElement.appendChild(infoElement); postElement.appendChild(commentElement); const likeButton = document.createElement("button"); likeButton.textContent = "Like"; likeButton.id = `like-button-${comment.comment_id}`; likeButton.classList.add("post-like-button"); const dislikeButton = document.createElement("button"); dislikeButton.textContent = "Dislike"; dislikeButton.id = `dislike-button-${comment.comment_id}`; dislikeButton.classList.add("post-dislike-button"); // Attach event listeners to the buttons likeButton.addEventListener("click", () => handleVote(comment.comment_id)); dislikeButton.addEventListener("click", () => handleVote(comment.comment_id)); // Append buttons to commentElement commentElement.appendChild(likeButton); commentElement.appendChild(dislikeButton); if (index === postData.post.comments.length - 1) { commentElement.style.marginBottom = "0"; } else { commentElement.style.marginBottom = "20px"; } }); } // Append postElement to the container container.appendChild(postElement); } catch (error) { console.error("Error rendering single post:", error); } } document.body.addEventListener("click", async (event) => { const commentSubmitBtn = event.target.closest("#comment-submit"); const commentInput = document.getElementById("comment"); const postDiv = document.querySelector('.post'); // Select the element with the class "post details" const commentPostID = postDiv.getAttribute('postid'); if (commentSubmitBtn) { // Comment submit button clicked const comment = commentInput.value.trim(); if (comment === "") { return; // Add an error message or handle the case where comment is empty } const requestBody = { comment_input: comment, postID: commentPostID, }; console.log(requestBody); try { // Send POST request to the backend const response = await fetch("http://localhost:8083/addcomment", { method: "POST", body: JSON.stringify(requestBody), credentials: 'include', headers: { // Set the appropriate content type for FormData "Content-Type": "application/json", }, }); if (response.ok) { // Successfully added comment, handle the response or redirect const responseData = await response.json(); console.log("Comment added", responseData, comment); const response2 = await fetch(`http://localhost:8083/getAllPosts/${commentPostID}`, { credentials: 'include', }); const postData = await response2.json(); app.innerHTML = ""; renderSinglePost(commentPostID, app); } else { const errorData = await response.json(); if (errorData.error === "error_adding_comment") { // Handle the error appropriately for the user return; } console.error("Commenting error:", errorData); } } catch (error) { console.error("Error during commenting:", error); } }; }); async function handleCommentVote(commentID, voteType) { const loggedInUsername = localStorage.getItem("loggedInUsername"); if (voteType === "like") { voteType = "1" } else if (voteType === "dislike") { voteType = "-1" } const requestBody = { comment_id: commentID, vote_type: voteType, }; console.log(requestBody) try { const response = await fetch("http://localhost:8083/vote", { method: "POST", body: JSON.stringify(requestBody), credentials: 'include', headers: { "Content-Type": "application/json", }, }); if (response.ok) { // Successfully voted on the comment, perform UI updates if (voteType === "like") { // Handle like UI updates } else if (voteType === "dislike") { // Handle dislike UI updates } } else { // Handle the error } } catch (error) { console.error("Error during voting:", error); } } async function handlePostVote(postID, voteType) { const loggedInUsername = localStorage.getItem("loggedInUsername"); if (voteType === "like") { voteType = "1"; } else if (voteType === "dislike") { voteType = "-1"; } const requestBody = { post_id: postID, // Use "post_id" instead of "comment_id" vote_type: voteType, }; try { const response = await fetch("http://localhost:8083/vote", { method: "POST", body: JSON.stringify(requestBody), credentials: 'include', headers: { "Content-Type": "application/json", }, }); if (response.ok) { // Successfully voted on the post, perform UI updates if (voteType === "like") { // Handle like UI updates for posts } else if (voteType === "dislike") { // Handle dislike UI updates for posts } } else { // Handle the error } } catch (error) { console.error("Error during post voting:", error); } } document.body.addEventListener("click", async (event) => { const likeButton = event.target.closest(".post-like-button"); const dislikeButton = event.target.closest(".post-dislike-button"); if (likeButton) { const postID = likeButton.id.split("-")[3]; // Extract postID from the button's ID handlePostVote(postID, "like"); } else if (dislikeButton) { const postID = dislikeButton.id.split("-")[3]; // Extract postID from the button's ID handlePostVote(postID, "dislike"); } }); document.body.addEventListener("click", async (event) => { const likeButton = event.target.closest(".like-button"); const dislikeButton = event.target.closest(".dislike-button"); if (likeButton) { const commentID = likeButton.id.split("-")[2]; // Extract commentID from the button's ID handleCommentVote(commentID, "like"); } else if (dislikeButton) { const commentID = dislikeButton.id.split("-")[2]; // Extract commentID from the button's ID handleCommentVote(commentID, "dislike"); } });