document.addEventListener('DOMContentLoaded', function() { try { const postId = document.querySelector('input[name="post-id"]').value; loadComments(postId); // Attach submit event listener to the form const form = document.getElementById('comment-form'); if (!form) { throw new Error('Comment form not found'); } form.addEventListener('submit', submitComment); console.log('Comment form submit listener attached'); } catch (error) { console.error('Error initializing comments:', error); } // Add event delegation for reply buttons document.getElementById('comments-list').addEventListener('click', function(e) { if (e.target.classList.contains('reply-btn')) { const parentId = e.target.dataset.commentId; document.querySelector('input[name="parent-id"]').value = parentId; document.getElementById('comment-form').scrollIntoView(); // Get parent comment content const parentComment = e.target.closest('.comment'); const parentContent = parentComment.querySelector('.comment-text').textContent; const parentName = parentComment.querySelector('strong').textContent; // Format and display ancestry content const commentBox = document.querySelector('textarea[name="comment"]'); commentBox.value = `> ${parentName}: ${parentContent}\n\n`; } }); }); function loadComments(postId) { fetch(`/get_comments/${postId}`) .then(response => response.json()) .then(comments => { const commentListDiv = document.getElementById('comments-list'); commentListDiv.innerHTML = ''; // Clear existing comments renderComments(comments, commentListDiv); if (typeof renderMathInElement === 'function') { renderMathInElement(commentListDiv, { delimiters: [ {left: '$$', right: '$$', display: true}, {left: '$', right: '$', display: false} ] }); } }) .catch(error => { console.error('Error loading comments:', error); document.getElementById('comments-list').innerHTML = '
Error loading comments. Please try again later.
'; }); } function renderComments(comments, container, level = 0) { comments.forEach(comment => { const commentDiv = document.createElement('div'); commentDiv.className = `comment level-${level}`; commentDiv.setAttribute('data-level', level); commentDiv.innerHTML = `
${comment.name}
•
${new Date(comment.created_at).toLocaleString()}
${comment.comment}