-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
202 lines (172 loc) · 6.37 KB
/
script.js
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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
// API Configuration
const API_URL = process.env.NODE_ENV === 'production'
? 'https://your-render-api-url.onrender.com/api'
: 'http://localhost:3001/api';
let token = localStorage.getItem('token');
let currentUser = null;
// DOM Elements
const mainContent = document.getElementById('mainContent');
const authButtons = document.getElementById('authButtons');
const userInfo = document.getElementById('userInfo');
const username = document.getElementById('username');
const authModal = new bootstrap.Modal(document.getElementById('authModal'));
const threadModal = new bootstrap.Modal(document.getElementById('threadModal'));
// Event Listeners
document.getElementById('loginBtn').addEventListener('click', () => showAuthModal('login'));
document.getElementById('registerBtn').addEventListener('click', () => showAuthModal('register'));
document.getElementById('logoutBtn').addEventListener('click', logout);
document.getElementById('authToggleLink').addEventListener('click', toggleAuthMode);
document.getElementById('authForm').addEventListener('submit', handleAuth);
document.getElementById('threadForm').addEventListener('submit', handleNewThread);
document.getElementById('newThreadLink').addEventListener('click', () => {
if (!token) {
showError('Please login to create a new thread');
return;
}
threadModal.show();
});
document.getElementById('homeLink').addEventListener('click', loadThreads);
// Auth Functions
function showAuthModal(mode) {
const isLogin = mode === 'login';
document.getElementById('authModalTitle').textContent = isLogin ? 'Login' : 'Register';
document.getElementById('authSubmitBtn').textContent = isLogin ? 'Login' : 'Register';
document.getElementById('authToggleLink').textContent = isLogin
? "Don't have an account? Register"
: "Already have an account? Login";
document.getElementById('usernameGroup').style.display = isLogin ? 'none' : 'block';
authModal.show();
}
function toggleAuthMode(e) {
e.preventDefault();
const isCurrentlyLogin = document.getElementById('authModalTitle').textContent === 'Login';
showAuthModal(isCurrentlyLogin ? 'register' : 'login');
}
async function handleAuth(e) {
e.preventDefault();
const isLogin = document.getElementById('authModalTitle').textContent === 'Login';
const endpoint = isLogin ? 'login' : 'register';
const data = {
email: document.getElementById('emailInput').value,
password: document.getElementById('passwordInput').value
};
if (!isLogin) {
data.username = document.getElementById('usernameInput').value;
}
try {
const response = await fetch(`${API_URL}/${endpoint}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
const result = await response.json();
if (!response.ok) throw new Error(result.message);
if (isLogin) {
token = result.token;
localStorage.setItem('token', token);
currentUser = result.user;
updateAuthUI();
loadThreads();
} else {
showAuthModal('login');
showSuccess('Registration successful! Please login.');
}
authModal.hide();
} catch (error) {
showError(error.message);
}
}
function logout() {
token = null;
currentUser = null;
localStorage.removeItem('token');
updateAuthUI();
loadThreads();
}
function updateAuthUI() {
if (token) {
authButtons.classList.add('d-none');
userInfo.classList.remove('d-none');
username.textContent = currentUser?.username || 'User';
} else {
authButtons.classList.remove('d-none');
userInfo.classList.add('d-none');
username.textContent = '';
}
}
// Thread Functions
async function loadThreads() {
mainContent.innerHTML = '<div class="loading"></div>';
try {
const response = await fetch(`${API_URL}/threads`);
const threads = await response.json();
if (!response.ok) throw new Error('Failed to load threads');
displayThreads(threads);
} catch (error) {
showError(error.message);
}
}
function displayThreads(threads) {
mainContent.innerHTML = threads.map(thread => `
<div class="card thread-card">
<div class="card-body">
<h5 class="card-title">${escapeHtml(thread.title)}</h5>
<p class="card-text">${escapeHtml(thread.content)}</p>
<div class="thread-meta">
Posted by ${escapeHtml(thread.author.username)} on ${new Date(thread.createdAt).toLocaleDateString()}
</div>
</div>
</div>
`).join('');
}
async function handleNewThread(e) {
e.preventDefault();
const data = {
title: document.getElementById('threadTitle').value,
content: document.getElementById('threadContent').value
};
try {
const response = await fetch(`${API_URL}/threads`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify(data)
});
const result = await response.json();
if (!response.ok) throw new Error(result.message);
threadModal.hide();
e.target.reset();
loadThreads();
showSuccess('Thread created successfully!');
} catch (error) {
showError(error.message);
}
}
// Utility Functions
function showError(message) {
const alert = document.createElement('div');
alert.className = 'error-message';
alert.textContent = message;
mainContent.insertAdjacentElement('beforebegin', alert);
setTimeout(() => alert.remove(), 5000);
}
function showSuccess(message) {
const alert = document.createElement('div');
alert.className = 'success-message';
alert.textContent = message;
mainContent.insertAdjacentElement('beforebegin', alert);
setTimeout(() => alert.remove(), 5000);
}
function escapeHtml(unsafe) {
return unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
// Initialize
updateAuthUI();
loadThreads();