Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
493 lines (409 loc) · 16.3 KB
/
Copy pathscript.js
File metadata and controls
493 lines (409 loc) · 16.3 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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
(() => {
"use strict";
const DB_KEY = "blogSphereDB";
const demoPosts = [
{
id: "demo-1",
title: "Five Habits That Quietly Improved My Code",
author: "Naomi Reyes",
category: "Technology",
image: null,
description: "Small, boring habits that made a bigger difference than any framework ever did.",
content:
"I used to think better code came from better tools. After a decade of shipping software, I've landed somewhere much less exciting: the biggest gains came from small, boring habits. Writing the test before the fix. Naming things twice as carefully as I think I need to. Reading my own pull request as if a stranger wrote it. None of this is clever. All of it compounds.",
tags: ["habits", "engineering", "productivity"],
date: new Date("2026-02-11T10:00:00").toISOString(),
},
{
id: "demo-2",
title: "A Week Alone in the Faroe Islands",
author: "Theo Lindqvist",
category: "Travel",
image: null,
description: "No itinerary, no signal, and some of the most dramatic coastline I've ever stood on.",
content:
"I booked the flight before I let myself think too hard about it. Seven days, one small guesthouse, and a rental car with more dents than I was told about. The Faroe Islands don't perform for visitors the way some places do — the weather changes its mind hourly, the sheep own the roads, and the villages feel like they were built to be left alone. That's exactly what made it the best trip I've taken in years.",
tags: ["travel", "solo-trip", "nordic"],
date: new Date("2026-03-02T14:30:00").toISOString(),
},
{
id: "demo-3",
title: "The Sourdough Mistake That Fixed Everything",
author: "Priya Shah",
category: "Food",
image: null,
description: "I was overcomplicating my starter for months. The fix was almost insultingly simple.",
content:
"For three months my sourdough came out dense and sour in the wrong way. I adjusted hydration, tried three flours, timed everything to the minute. Then a friend asked what temperature my kitchen actually was, and I realized I'd never checked. It was 18°C. My starter needed 24. That was it. That was the whole problem. Sometimes the fix isn't a technique, it's just paying attention to the room you're standing in.",
tags: ["baking", "sourdough", "kitchen-notes"],
date: new Date("2026-01-20T09:15:00").toISOString(),
},
];
const Storage = (() => {
function getDB() {
try {
const raw = localStorage.getItem(DB_KEY);
if (!raw) return null;
const parsed = JSON.parse(raw);
return Array.isArray(parsed.posts) ? parsed : null;
} catch {
return null;
}
}
function saveDB(db) {
localStorage.setItem(DB_KEY, JSON.stringify(db));
}
// Seed demo posts exactly once, the very first time the site is opened
function ensureSeeded() {
const existing = getDB();
if (!existing) {
saveDB({ posts: [...demoPosts] });
}
}
function getPosts() {
const db = getDB();
return db ? db.posts : [];
}
function addPost(post) {
const db = getDB() || { posts: [] };
db.posts.push(post);
saveDB(db);
}
function updatePost(id, updates) {
const db = getDB() || { posts: [] };
db.posts = db.posts.map((p) => (p.id === id ? { ...p, ...updates } : p));
saveDB(db);
}
function deletePost(id) {
const db = getDB() || { posts: [] };
db.posts = db.posts.filter((p) => p.id !== id);
saveDB(db);
}
function getPost(id) {
return getPosts().find((p) => p.id === id) || null;
}
return { ensureSeeded, getPosts, addPost, updatePost, deletePost, getPost };
})();
const Utils = (() => {
function escapeHTML(str = "") {
const div = document.createElement("div");
div.textContent = str;
return div.innerHTML;
}
function formatDate(isoString) {
try {
return new Date(isoString).toLocaleDateString(undefined, {
year: "numeric",
month: "short",
day: "numeric",
});
} catch {
return "";
}
}
function truncate(text, maxLength = 120) {
if (!text) return "";
return text.length > maxLength ? `${text.slice(0, maxLength).trim()}…` : text;
}
function fileToBase64(file) {
return new Promise((resolve, reject) => {
if (!file) return resolve(null);
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.onerror = () => reject(new Error("Could not read the selected image."));
reader.readAsDataURL(file);
});
}
function parseTags(rawValue) {
return rawValue
.split(",")
.map((tag) => tag.trim())
.filter(Boolean);
}
return { escapeHTML, formatDate, truncate, fileToBase64, parseTags };
})();
const Toast = (() => {
const el = document.getElementById("toast");
function show(message, type = "success", duration = 3000) {
el.textContent = message;
el.classList.remove("success", "danger");
el.classList.add(type, "visible");
clearTimeout(el._hideTimer);
el._hideTimer = setTimeout(() => el.classList.remove("visible"), duration);
}
return { show };
})();
const ConfirmModal = (() => {
const overlay = document.getElementById("confirm-overlay");
const cancelBtn = document.getElementById("confirm-cancel");
const deleteBtn = document.getElementById("confirm-delete");
let pendingId = null;
function open(postId) {
pendingId = postId;
overlay.classList.add("visible");
}
function close() {
pendingId = null;
overlay.classList.remove("visible");
}
function init(onConfirm) {
cancelBtn.addEventListener("click", close);
overlay.addEventListener("click", (e) => {
if (e.target === overlay) close();
});
deleteBtn.addEventListener("click", () => {
if (pendingId) onConfirm(pendingId);
close();
});
}
return { open, close, init };
})();
const Validation = (() => {
const rules = {
title: (v) => (v.trim() ? "" : "Title is required."),
author: (v) => (v.trim() ? "" : "Author name is required."),
category: (v) => (v ? "" : "Please select a category."),
description: (v) => (v.trim() ? "" : "Short description is required."),
content: (v) => (v.trim() ? "" : "Blog content cannot be empty."),
};
function paint(id) {
const inputEl = document.getElementById(id);
const errorEl = document.getElementById(`err-${id}`);
const message = rules[id](inputEl.value);
inputEl.classList.remove("valid", "invalid");
inputEl.classList.add(message ? "invalid" : "valid");
if (errorEl) errorEl.textContent = message;
return message === "";
}
function bindLive() {
Object.keys(rules).forEach((id) => {
const el = document.getElementById(id);
const eventName = el.tagName === "SELECT" ? "change" : "input";
el.addEventListener(eventName, () => paint(id));
});
}
function validateAll() {
return Object.keys(rules)
.map(paint)
.every(Boolean);
}
function clearStyles() {
Object.keys(rules).forEach((id) => {
const el = document.getElementById(id);
el.classList.remove("valid", "invalid");
const errorEl = document.getElementById(`err-${id}`);
if (errorEl) errorEl.textContent = "";
});
}
return { bindLive, validateAll, clearStyles };
})();
const Render = (() => {
const grid = document.getElementById("posts-grid");
const emptyState = document.getElementById("empty-state");
function buildCard(post) {
const imageMarkup = post.image
? `<img class="post-card-img" src="${post.image}" alt="${Utils.escapeHTML(post.title)}">`
: `<div class="post-card-img placeholder">${Utils.escapeHTML(post.category || "BlogSphere")}</div>`;
const tagsMarkup = (post.tags || [])
.map((tag) => `<span class="post-tag">#${Utils.escapeHTML(tag)}</span>`)
.join("");
return `
<article class="post-card" data-id="${post.id}">
${imageMarkup}
<div class="post-card-body">
<div class="post-card-meta">
<span class="post-card-category">${Utils.escapeHTML(post.category)}</span>
<span>${Utils.formatDate(post.date)}</span>
</div>
<h3 class="post-card-title">${Utils.escapeHTML(post.title)}</h3>
<p class="post-card-meta">By ${Utils.escapeHTML(post.author)}</p>
<p class="post-card-desc">${Utils.escapeHTML(Utils.truncate(post.description, 130))}</p>
<div class="post-card-tags">${tagsMarkup}</div>
<div class="post-card-full" id="full-${post.id}">${Utils.escapeHTML(post.content)}</div>
<div class="post-card-actions">
<button class="card-btn read-more" data-action="read" data-id="${post.id}">Read More</button>
<button class="card-btn edit-btn" data-action="edit" data-id="${post.id}">Edit</button>
<button class="card-btn delete-btn" data-action="delete" data-id="${post.id}">Delete</button>
</div>
</div>
</article>
`;
}
function renderList(posts) {
if (posts.length === 0) {
grid.innerHTML = "";
emptyState.hidden = false;
return;
}
emptyState.hidden = true;
grid.innerHTML = posts.map(buildCard).join("");
}
return { renderList };
})();
const Controls = (() => {
const searchInput = document.getElementById("search-input");
const filterSelect = document.getElementById("filter-category");
const sortSelect = document.getElementById("sort-order");
const chips = document.querySelectorAll(".chip");
function getFilteredPosts() {
const query = searchInput.value.trim().toLowerCase();
const category = filterSelect.value;
const sortOrder = sortSelect.value;
let posts = Storage.getPosts().filter((post) => {
const matchesQuery =
!query ||
post.title.toLowerCase().includes(query) ||
post.author.toLowerCase().includes(query) ||
post.category.toLowerCase().includes(query);
const matchesCategory = category === "All" || post.category === category;
return matchesQuery && matchesCategory;
});
posts = posts.sort((a, b) => {
const diff = new Date(a.date) - new Date(b.date);
return sortOrder === "newest" ? -diff : diff;
});
return posts;
}
function refresh() {
Render.renderList(getFilteredPosts());
}
function syncChipWithFilter(category) {
chips.forEach((chip) => chip.classList.toggle("active", chip.dataset.category === category));
}
function bind() {
searchInput.addEventListener("input", refresh);
filterSelect.addEventListener("change", () => {
syncChipWithFilter(filterSelect.value);
refresh();
});
sortSelect.addEventListener("change", refresh);
chips.forEach((chip) => {
chip.addEventListener("click", () => {
filterSelect.value = chip.dataset.category;
syncChipWithFilter(chip.dataset.category);
refresh();
});
});
chips[0]?.classList.add("active");
}
return { bind, refresh };
})();
const Composer = (() => {
const form = document.getElementById("post-form");
const idField = document.getElementById("post-id");
const titleHeading = document.getElementById("composer-title");
const publishBtn = document.getElementById("publish-btn");
const cancelBtn = document.getElementById("cancel-edit-btn");
const imageInput = document.getElementById("coverImage");
let existingImage = null;
function enterEditMode(post) {
idField.value = post.id;
document.getElementById("title").value = post.title;
document.getElementById("author").value = post.author;
document.getElementById("category").value = post.category;
document.getElementById("description").value = post.description;
document.getElementById("content").value = post.content;
document.getElementById("tags").value = (post.tags || []).join(", ");
existingImage = post.image;
titleHeading.textContent = "Edit Post";
publishBtn.textContent = "Update Post";
cancelBtn.hidden = false;
document.getElementById("create-post").scrollIntoView({ behavior: "smooth", block: "start" });
}
function exitEditMode() {
idField.value = "";
existingImage = null;
titleHeading.textContent = "Create a New Post";
publishBtn.textContent = "Publish Post";
cancelBtn.hidden = true;
form.reset();
Validation.clearStyles();
}
async function handleSubmit(e) {
e.preventDefault();
if (!Validation.validateAll()) return;
const file = imageInput.files && imageInput.files[0];
let image = existingImage;
if (file) {
try {
image = await Utils.fileToBase64(file);
} catch {
image = existingImage;
}
}
const postData = {
title: document.getElementById("title").value.trim(),
author: document.getElementById("author").value.trim(),
category: document.getElementById("category").value,
description: document.getElementById("description").value.trim(),
content: document.getElementById("content").value.trim(),
tags: Utils.parseTags(document.getElementById("tags").value),
image,
};
if (idField.value) {
Storage.updatePost(idField.value, postData);
Toast.show("Blog updated successfully!", "success");
} else {
Storage.addPost({ id: `post-${Date.now()}`, date: new Date().toISOString(), ...postData });
Toast.show("Blog published successfully!", "success");
}
exitEditMode();
Controls.refresh();
}
function bind() {
Validation.bindLive();
form.addEventListener("submit", handleSubmit);
cancelBtn.addEventListener("click", exitEditMode);
}
return { bind, enterEditMode };
})();
function bindCardActions() {
const grid = document.getElementById("posts-grid");
grid.addEventListener("click", (e) => {
const btn = e.target.closest("button[data-action]");
if (!btn) return;
const { action, id } = btn.dataset;
if (action === "read") {
const fullEl = document.getElementById(`full-${id}`);
const expanded = fullEl.classList.toggle("expanded");
btn.textContent = expanded ? "Show Less" : "Read More";
}
if (action === "edit") {
const post = Storage.getPost(id);
if (post) Composer.enterEditMode(post);
}
if (action === "delete") {
ConfirmModal.open(id);
}
});
}
function initMobileNav() {
const toggle = document.getElementById("nav-toggle");
const nav = document.getElementById("main-nav");
if (!toggle || !nav) return;
toggle.addEventListener("click", () => {
const isOpen = nav.classList.toggle("nav-open");
toggle.classList.toggle("open", isOpen);
toggle.setAttribute("aria-expanded", String(isOpen));
});
nav.querySelectorAll("a").forEach((link) =>
link.addEventListener("click", () => {
nav.classList.remove("nav-open");
toggle.classList.remove("open");
})
);
}
document.addEventListener("DOMContentLoaded", () => {
Storage.ensureSeeded();
Composer.bind();
Controls.bind();
bindCardActions();
initMobileNav();
ConfirmModal.init((id) => {
Storage.deletePost(id);
Controls.refresh();
Toast.show("Post deleted.", "danger");
});
Controls.refresh();
});
})();