-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathindex.js
More file actions
311 lines (260 loc) · 8.97 KB
/
index.js
File metadata and controls
311 lines (260 loc) · 8.97 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
/* =========================================================
LakehouseBlogs.com — index.js
Dynamically renders year sections and link cards from blogs.json
Features: search, project filters, year toggles, scroll-spy, lazy reveal
========================================================= */
(() => {
const $ = (sel, root = document) => root.querySelector(sel);
const $$ = (sel, root = document) => Array.from(root.querySelectorAll(sel));
// Roots & templates
const yearsRoot = $("#yearsRoot");
const yearNav = $("#yearNav");
const searchInput = $("#search");
const filtersBar = $("#filters");
const cardTpl = $("#cardTemplate");
const yearTpl = $("#yearTemplate");
// App state
const state = {
blogs: [],
grouped: new Map(), // year -> array of blogs
activeProject: "all",
query: ""
};
// Helpers
const fmtDate = (iso) =>
new Intl.DateTimeFormat(undefined, { year: "numeric", month: "long", day: "numeric" })
.format(new Date(iso));
const slugify = (s) =>
String(s || "")
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/(^-|-$)/g, "");
const debounce = (fn, ms = 200) => {
let t;
return (...args) => {
clearTimeout(t);
t = setTimeout(() => fn(...args), ms);
};
};
// Fetch + initialize
async function init() {
try {
const res = await fetch("blogs.json", { cache: "no-store" });
if (!res.ok) throw new Error(`Failed to load blogs.json: ${res.status}`);
const data = await res.json();
// Normalize, sort (newest first)
state.blogs = (data.blogs || [])
.map(b => ({
...b,
date: b.date, // ISO string expected (YYYY-MM-DD)
year: new Date(b.date).getFullYear(),
project_slugs: Array.isArray(b.project_slugs) ? b.project_slugs : [],
tags: Array.isArray(b.tags) ? b.tags : []
}))
.sort((a, b) => new Date(b.date) - new Date(a.date));
groupByYear();
renderAll();
bindUI();
observeScrollSpy();
observeReveals();
} catch (err) {
console.error(err);
yearsRoot.innerHTML = `
<div style="padding:1rem; border:1px solid #e5e7eb; border-radius:.5rem;">
<strong>Could not load blog data.</strong>
<div class="muted" style="margin-top:.25rem;">${String(err.message || err)}</div>
</div>`;
}
}
function groupByYear() {
state.grouped.clear();
for (const b of state.blogs) {
if (!state.grouped.has(b.year)) state.grouped.set(b.year, []);
state.grouped.get(b.year).push(b);
}
// Ensure per-year arrays are sorted by date desc
for (const [year, arr] of state.grouped.entries()) {
arr.sort((a, b) => new Date(b.date) - new Date(a.date));
}
}
function renderAll() {
// Year nav (desc)
const years = Array.from(state.grouped.keys()).sort((a, b) => b - a);
yearNav.innerHTML = years
.map(
(y, i) =>
`<a href="#${y}" class="${i === 0 ? "is-active" : ""}" data-year="${y}">${y}</a>`
)
.join("");
// Year sections + cards
yearsRoot.innerHTML = "";
for (const year of years) {
const section = yearTpl.content.firstElementChild.cloneNode(true);
section.id = String(year);
$(".year-title", section).textContent = String(year);
const grid = $(".links-grid", section);
const items = state.grouped.get(year) || [];
for (const blog of items) {
const card = buildCard(blog);
grid.appendChild(card);
}
// Initial count
updateYearCount(section);
// Toggle button
const toggleBtn = $(".toggle-year", section);
toggleBtn.addEventListener("click", () => {
const expanded = toggleBtn.getAttribute("aria-expanded") === "true";
toggleBtn.setAttribute("aria-expanded", String(!expanded));
grid.style.display = expanded ? "none" : "";
});
yearsRoot.appendChild(section);
}
// Apply initial filter/search (no-op visual but sets attributes)
applyFilters();
}
function buildCard(blog) {
const card = cardTpl.content.firstElementChild.cloneNode(true);
// meta
const t = $("time", card);
t.dateTime = blog.date;
t.textContent = fmtDate(blog.date);
$(".company", card).textContent = blog.company || "";
// title
const titleA = $(".title", card);
titleA.href = blog.url;
titleA.textContent = blog.title;
// author
const authorA = $(".author", card);
authorA.href = blog.author_url || blog.url;
authorA.textContent = blog.author || "Unknown";
// badges
const badgesWrap = $(".badges", card);
badgesWrap.innerHTML = "";
(blog.tags || []).forEach(tag => {
const span = document.createElement("span");
span.className = "badge";
span.textContent = tag;
badgesWrap.appendChild(span);
});
// project filter slugs
const projects = blog.project_slugs || [];
card.dataset.project = projects.join(" ");
// searchable blob (for fast contains checks)
const searchable = [
blog.title,
blog.company,
blog.author,
(blog.tags || []).join(" "),
projects.join(" "),
blog.url
]
.filter(Boolean)
.join(" ")
.toLowerCase();
card.dataset.search = searchable;
// reveal class already on template root: ensure present
card.classList.add("reveal");
return card;
}
// Filtering + Search
function applyFilters() {
const q = state.query.trim().toLowerCase();
const active = state.activeProject;
// For each card, determine visibility
const sections = $$(".year-section", yearsRoot);
for (const section of sections) {
const cards = $$(".card", section);
let visibleCount = 0;
for (const card of cards) {
const matchesProject =
active === "all" || (card.dataset.project || "").split(/\s+/).includes(active);
const matchesQuery = q === "" || (card.dataset.search || "").includes(q);
const isVisible = matchesProject && matchesQuery;
card.classList.toggle("hidden", !isVisible);
if (isVisible) visibleCount++;
}
// Update per-year visible counts & optionally hide the whole year if 0
updateYearCount(section, visibleCount);
section.classList.toggle("hidden", visibleCount === 0);
}
}
function updateYearCount(section, visibleOverride) {
const countEl = $(".year-count", section);
const total = $$(".card", section).length;
const visible =
typeof visibleOverride === "number"
? visibleOverride
: $$(".card:not(.hidden)", section).length;
countEl.textContent = `${visible}/${total} posts`;
}
// Scroll spy: highlight active year in nav
function observeScrollSpy() {
const navLinks = $$("a[data-year]", yearNav);
const sections = $$(".year-section");
if (!sections.length || !navLinks.length) return;
const byId = new Map(navLinks.map(a => [a.getAttribute("href")?.slice(1), a]));
const io = new IntersectionObserver(
(entries) => {
// Find the entry most in view and mark corresponding nav link active
const view = entries
.filter(e => e.isIntersecting)
.sort((a, b) => b.intersectionRatio - a.intersectionRatio)[0];
if (view) {
const year = view.target.id;
navLinks.forEach(a => a.classList.toggle("is-active", a.dataset.year === year));
}
},
{ rootMargin: "-40% 0px -50% 0px", threshold: [0.1, 0.25, 0.5, 0.75, 1] }
);
sections.forEach(sec => io.observe(sec));
// Enhance click behavior (smooth scroll is in CSS; here we also close mobile keyboards)
yearNav.addEventListener("click", (e) => {
const a = e.target.closest("a");
if (!a) return;
searchInput?.blur();
});
}
// Reveal-on-scroll for cards
function observeReveals() {
const cards = $$(".card.reveal");
if (!cards.length) return;
const io = new IntersectionObserver(
(entries, obs) => {
for (const entry of entries) {
if (entry.isIntersecting) {
entry.target.classList.add("is-visible");
obs.unobserve(entry.target);
}
}
},
{ threshold: 0.15 }
);
cards.forEach((c) => io.observe(c));
}
// UI bindings
function bindUI() {
// Search
if (searchInput) {
const onSearch = debounce((e) => {
state.query = e.target.value || "";
applyFilters();
}, 150);
searchInput.addEventListener("input", onSearch);
}
// Filters (chips)
if (filtersBar) {
filtersBar.addEventListener("click", (e) => {
const chip = e.target.closest(".chip");
if (!chip) return;
// Update active chip
$$(".chip", filtersBar).forEach(c => c.classList.remove("is-active"));
chip.classList.add("is-active");
// Update state
state.activeProject = chip.dataset.project || "all";
applyFilters();
});
}
}
// Kick off
document.addEventListener("DOMContentLoaded", init);
})();