-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
233 lines (195 loc) · 6.81 KB
/
Copy pathscript.js
File metadata and controls
233 lines (195 loc) · 6.81 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
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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
/* === Data Model === */
// Users - Each user: { id, username, password }
let users = JSON.parse(localStorage.getItem("users")) || [];
// Posts - Each post: { id, userId, content, timestamp }
let posts = JSON.parse(localStorage.getItem("posts")) || [];
// Current logged-in user
let currentUser = JSON.parse(localStorage.getItem("currentUser")) || null;
const MAX_POST_LENGTH = 140; // hardcoded in HTML too!
const MAX_POSTS_PER_USER = 10;
/* === HTML Elements === */
const signUpForm = document.getElementById("signUpForm");
const signUpUsername = document.getElementById("signUpUsername");
const signUpPassword = document.getElementById("signUpPassword");
const signInForm = document.getElementById("signInForm");
const signInUsername = document.getElementById("signInUsername");
const signInPassword = document.getElementById("signInPassword");
const signOutBtn = document.getElementById("signOutBtn");
const deleteUserBtn = document.getElementById("deleteUserBtn");
const authSection = document.getElementById("authSection");
const blogSection = document.getElementById("blogSection");
const pageTitle = document.getElementById("pageTitle");
const messageBoard = document.getElementById("messageBoard");
const newPostForm = document.getElementById("newPostForm");
const newPostContent = document.getElementById("newPostContent");
const feedContainer = document.getElementById("feed");
/* === Helper Functions === */
function renderUI() {
messageBoard.className = "";
if (currentUser) {
authSection.hidden = true;
blogSection.hidden = false;
signOutBtn.hidden = false;
deleteUserBtn.hidden = false;
pageTitle.innerText = `Hello, ${currentUser.username}!`;
renderFeed();
} else {
authSection.hidden = false;
blogSection.hidden = true;
signOutBtn.hidden = true;
deleteUserBtn.hidden = true;
pageTitle.innerText = "Mini Microblog";
feedContainer.innerHTML = "";
}
}
function renderFeed() {
feedContainer.innerHTML = "";
const feed = posts.slice().sort((a, b) => b.timestamp - a.timestamp);
feed.forEach((post) => {
const author = users.find((u) => u.id === post.userId);
const div = document.createElement("div");
div.classList.add("post");
div.innerHTML = `<strong>${author.username}:</strong> ${
post.content
} <small>${new Date(post.timestamp).toLocaleString()}</small>`;
feedContainer.appendChild(div);
});
}
function showMessage(text, type = "") {
messageBoard.textContent = text;
messageBoard.className = type;
// Auto-hide after 3 seconds
if (text) {
setTimeout(() => {
messageBoard.textContent = "";
messageBoard.className = "";
}, 3000);
}
}
/* === Auth Functions === */
function signUp(username, password) {
if (users.some((u) => u.username === username)) return false;
const newUser = { id: Date.now(), username, password };
users.push(newUser);
localStorage.setItem("users", JSON.stringify(users));
return newUser;
}
function signIn(username, password) {
const user = users.find(
(u) => u.username === username && u.password === password
);
if (!user) return null;
currentUser = user;
localStorage.setItem("currentUser", JSON.stringify(user));
return user;
}
function signOut() {
currentUser = null;
localStorage.removeItem("currentUser");
}
/* === Event Listeners === */
// Sign Up
signUpForm.addEventListener("submit", (e) => {
e.preventDefault();
const user = signUp(signUpUsername.value.trim(), signUpPassword.value);
if (!user) {
showMessage("Username already exists!", "error");
return;
}
showMessage("Sign-up successful! Please sign in.", "success");
signUpForm.reset();
});
// Sign In
signInForm.addEventListener("submit", (e) => {
e.preventDefault();
const user = signIn(signInUsername.value.trim(), signInPassword.value);
if (!user) {
showMessage("Invalid username or password!", "error");
return;
}
showMessage(`Welcome, ${user.username}!`, "success");
signInForm.reset();
renderUI();
});
// Sign Out
signOutBtn.addEventListener("click", () => {
signOut();
showMessage("You have been signed out.", "success");
renderUI();
});
// Delete User
deleteUserBtn.addEventListener("click", () => {
if (!currentUser) return;
if (!confirm(`Delete account ${currentUser.username}?`)) return;
users = users.filter((u) => u.id !== currentUser.id);
posts = posts.filter((p) => p.userId !== currentUser.id);
localStorage.setItem("users", JSON.stringify(users));
localStorage.setItem("posts", JSON.stringify(posts));
signOut();
showMessage("Account deleted.", "success");
renderUI();
});
// Add Post
newPostForm.addEventListener("submit", (e) => {
e.preventDefault();
if (!currentUser) return;
const content = newPostContent.value.trim();
if (content.length === 0) {
showMessage("Post cannot be empty!", "error");
return;
}
if (content.length > MAX_POST_LENGTH) {
showMessage(`Post too long! Max ${MAX_POST_LENGTH} characters.`, "error");
return;
}
const userPosts = posts.filter((p) => p.userId === currentUser.id);
if (userPosts.length >= MAX_POSTS_PER_USER) {
showMessage(`Post limit reached (${MAX_POSTS_PER_USER} posts).`, "error");
return;
}
const post = {
id: Date.now(),
userId: currentUser.id,
content,
timestamp: Date.now(),
};
posts.push(post);
localStorage.setItem("posts", JSON.stringify(posts));
newPostContent.value = "";
charCount.textContent = `0 / ${MAX_POST_LENGTH}`; // resets counter
charCount.classList.remove("warning", "error"); // resets color
renderFeed();
showMessage("Post added successfully!", "success");
});
const charCount = document.getElementById("charCount");
newPostContent.addEventListener("input", () => {
const count = newPostContent.value.length;
charCount.textContent = `${count} / ${MAX_POST_LENGTH}`;
charCount.classList.remove("warning", "error");
if (count > MAX_POST_LENGTH) {
charCount.classList.add("error");
} else if (count > MAX_POST_LENGTH * 0.8) {
charCount.classList.add("warning");
}
});
/* === Initialize UI === */
renderUI();
/* === Dark/Light Mode Toggle === */
const themeToggle = document.createElement("button");
themeToggle.id = "themeToggle";
themeToggle.innerText = "🌙 Dark Mode";
document.querySelector("header").prepend(themeToggle);
// Load saved theme
const savedTheme = localStorage.getItem("theme") || "light";
if (savedTheme === "dark") document.body.classList.add("dark-mode");
// Update button text on load
themeToggle.innerText = document.body.classList.contains("dark-mode")
? "☀️ Light Mode"
: "🌙 Dark Mode";
// Toggle theme
themeToggle.addEventListener("click", () => {
document.body.classList.toggle("dark-mode");
const isDark = document.body.classList.contains("dark-mode");
localStorage.setItem("theme", isDark ? "dark" : "light");
themeToggle.innerText = isDark ? "☀️ Light Mode" : "🌙 Dark Mode";
});