-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdashboard.js
More file actions
172 lines (147 loc) · 5.72 KB
/
Copy pathdashboard.js
File metadata and controls
172 lines (147 loc) · 5.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
// --- Configuration ---
const API_URL = "http://127.0.0.1:5000";
// --- DOM Elements ---
const postsContainer = document.getElementById('postsContainer');
// Note: We need to recreate the loading state HTML as it's not guaranteed to be in the DOM when JS loads.
const loadingStateHTML = `
<div id="loading-state" class="text-center py-10">
<div class="animate-spin rounded-full h-10 w-10 border-b-2 border-brand-primary mx-auto mb-3"></div>
<p class="text-gray-600">Loading dreams...</p>
</div>
`;
const mobileMenuButton = document.getElementById('mobile-menu-button');
const mobileMenu = document.getElementById('mobile-menu');
const menuIcon = document.getElementById('menu-icon');
const closeIcon = document.getElementById('close-icon');
// --- Utility Functions ---
/**
* Formats a date string into a readable format.
* @param {string} dateString
* @returns {string} Formatted date.
*/
function formatPostDate(dateString) {
if (!dateString) return 'Unknown date';
const options = {
year: 'numeric',
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
};
try {
return new Date(dateString).toLocaleTimeString(undefined, options);
} catch (e) {
return dateString;
}
}
/**
* Generates the HTML for a single comment, using the 'author' (username) field.
* This relies on your backend providing 'author'. If it only provides 'author_id',
* it will fall back to showing the ID.
* @param {object} comment
* @returns {string} HTML for the comment.
*/
function createCommentHTML(comment) {
const authorName = comment?.author ?? `User ${comment?.author_id ?? 'Unknown'}`; // Prefer username
const content = comment?.comment ?? 'No content.';
const date = formatPostDate(comment?.created_at);
return `
<div class="border-t border-gray-100 mt-2 pt-3 pl-3 bg-gray-50 rounded-md">
<p class="text-gray-700 text-sm leading-snug">
<span class="font-semibold text-brand-primary">${authorName}</span>: ${content}
</p>
<p class="text-gray-400 text-xs mt-1">${date}</p>
</div>
`;
}
/**
* Generates the HTML for a single post, using the 'username' field.
* @param {object} post
* @returns {string} HTML for the post.
*/
function createPostHTML(post) {
const comments = post?.comment ?? [];
let commentsHTML = '';
if (comments.length > 0) {
commentsHTML = comments.map(createCommentHTML).join('');
} else {
commentsHTML = '<p class="text-gray-500 text-sm mt-3 italic">No comments yet. Be the first!</p>';
}
const postDate = formatPostDate(post?.created_at);
// Use 'username' if available, otherwise fallback to 'user_id'
const authorName = post.username ?? `User ${post.user_id ?? 'Unknown'}`;
return `
<div class="bg-white shadow-xl rounded-xl p-6 hover:shadow-2xl transition duration-300 border border-gray-200">
<h3 class="text-xl font-bold text-gray-900 mb-2">${post.title ?? 'Untitled Dream'}</h3>
<p class="text-gray-700 mb-4 whitespace-pre-wrap">${post.content ?? 'No content provided.'}</p>
<p class="text-gray-500 text-xs font-medium border-b pb-3 mb-4">
Posted by <span class="font-semibold text-brand-primary">${authorName}</span> • ${postDate}
</p>
<div class="mt-4">
<h4 class="font-bold text-gray-800 text-lg mb-2">Comments (${comments.length}):</h4>
<div class="space-y-3">
${commentsHTML}
</div>
</div>
</div>
`;
}
// --- Main Logic Functions ---
/**
* Fetches and renders the posts using the single, efficient endpoint.
*/
async function fetchPosts() {
// Inject loading state HTML
postsContainer.innerHTML = loadingStateHTML;
try {
const token = localStorage.getItem('token');
if (!token) {
logout();
return;
}
// Using the efficient nested endpoint: /view-posts-comment
const res = await axios.get(`${API_URL}/view-posts-comment`, {
headers: { Authorization: `Bearer ${token}` }
});
const posts = res.data;
// Clear the loading state
postsContainer.innerHTML = '';
if (posts.length === 0) {
postsContainer.innerHTML = '<p class="text-gray-600 text-center py-8 bg-white rounded-lg shadow">No posts available yet. Start sharing your dreams!</p>';
return;
}
posts.forEach(post => {
const postHTML = createPostHTML(post);
postsContainer.insertAdjacentHTML('beforeend', postHTML);
});
} catch (err) {
console.error('Error loading posts:', err);
// Display a more prominent error message
postsContainer.innerHTML = `
<div class="bg-red-100 border-l-4 border-red-500 text-red-700 p-4 rounded" role="alert">
<p class="font-bold">Error Loading Posts</p>
<p>Could not load the dream feed. Please check your network connection or ensure you are logged in correctly.</p>
</div>
`;
}
}
/**
* Handles the user logout process.
*/
function logout() {
localStorage.removeItem('token');
window.location.href = '/login.html';
}
// --- Event Listeners and Initialization ---
// Expose logout function globally since it's used in inline HTML
window.logout = logout;
// Mobile Menu Toggle
if (mobileMenuButton) {
mobileMenuButton.addEventListener('click', () => {
mobileMenu.classList.toggle('hidden');
menuIcon.classList.toggle('hidden');
closeIcon.classList.toggle('hidden');
});
}
// Initial Data Load
fetchPosts();