Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
431 lines (355 loc) · 12.9 KB
/
Copy pathscript.js
File metadata and controls
431 lines (355 loc) · 12.9 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
const root = document.documentElement;
const toggle = document.querySelector(".theme-toggle");
const posts = (Array.isArray(window.BLOG_POSTS) ? window.BLOG_POSTS : [])
.slice()
.sort((a, b) => new Date(`${b.date}T00:00:00`) - new Date(`${a.date}T00:00:00`));
const formatDate = (dateString) =>
new Intl.DateTimeFormat("en", {
month: "short",
day: "2-digit",
year: "numeric",
}).format(new Date(`${dateString}T00:00:00`));
const getStoredTheme = () => {
try {
return localStorage.getItem("theme");
} catch {
return null;
}
};
const setStoredTheme = (theme) => {
try {
localStorage.setItem("theme", theme);
} catch {
// The visual toggle should still work if storage is unavailable.
}
};
const setTheme = (isDark) => {
root.classList.toggle("dark", isDark);
toggle?.setAttribute("aria-pressed", String(isDark));
};
const savedTheme = getStoredTheme();
const prefersDark = window.matchMedia?.("(prefers-color-scheme: dark)").matches;
setTheme(savedTheme ? savedTheme === "dark" : Boolean(prefersDark));
document.querySelectorAll("[data-count-selector]").forEach((count) => {
const items = [...document.querySelectorAll(count.dataset.countSelector)];
const filteredItems = count.dataset.countValue
? items.filter((item) => item.textContent.trim() === count.dataset.countValue)
: items;
const value = count.dataset.countMode === "unique"
? new Set(items.map((item) => item.textContent.trim())).size
: filteredItems.length;
count.textContent = String(value).padStart(2, "0");
});
const experienceTimeline = document.querySelector("#experience .experience-list");
const prefersReducedMotion = window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
if (experienceTimeline && !prefersReducedMotion && "IntersectionObserver" in window) {
experienceTimeline.classList.add("timeline-reveal-pending");
const timelineObserver = new window.IntersectionObserver((entries, observer) => {
if (entries.some((entry) => entry.isIntersecting)) {
experienceTimeline.classList.remove("timeline-reveal-pending");
experienceTimeline.classList.add("timeline-revealed");
observer.disconnect();
}
}, { threshold: 0.15 });
timelineObserver.observe(experienceTimeline);
}
toggle?.addEventListener("click", () => {
const isDark = !root.classList.contains("dark");
setTheme(isDark);
setStoredTheme(isDark ? "dark" : "light");
});
document.querySelectorAll('a[href^="#"]').forEach((link) => {
link.addEventListener("click", (event) => {
const target = document.querySelector(link.getAttribute("href"));
if (!target) {
return;
}
event.preventDefault();
target.scrollIntoView({ behavior: "smooth", block: "start" });
history.pushState(null, "", link.getAttribute("href"));
});
});
const createElement = (tag, className, text) => {
const element = document.createElement(tag);
if (className) {
element.className = className;
}
if (text) {
element.textContent = text;
}
return element;
};
const articleUrl = (slug) => `post.html?slug=${encodeURIComponent(slug)}`;
const blockText = (block) => {
if (Array.isArray(block.items)) {
return block.items.join(" ");
}
return [block.label, block.text, block.caption, block.alt].filter(Boolean).join(" ");
};
const renderBlogIndex = () => {
const blogList = document.querySelector(".blog-list");
const searchInput = document.querySelector(".blog-search-input");
const blogEmpty = document.querySelector(".blog-empty");
const endMarker = document.querySelector(".end-marker");
const pagination = document.querySelector(".blog-pagination");
const articleCount = document.querySelector("[data-blog-count]");
const minuteCount = document.querySelector("[data-blog-minutes]");
const pageSize = Number(blogList?.dataset.pageSize || 2);
if (!blogList) {
return;
}
let currentPage = 1;
let currentQuery = "";
if (articleCount) {
articleCount.textContent = String(posts.length);
}
if (minuteCount) {
const minutes = posts.reduce((sum, post) => sum + post.readTime, 0);
minuteCount.textContent = `~${minutes}`;
}
const buildRow = (post) => {
const row = createElement("article", "blog-row");
row.dataset.title = post.title;
row.dataset.category = post.category;
row.dataset.summary = post.summary;
const date = createElement("div", "blog-date");
if (post.featured) {
date.append(createElement("span", "featured-label", "Featured"));
}
const time = document.createElement("time");
time.dateTime = post.date;
time.textContent = formatDate(post.date);
date.append(time, createElement("span", "", "\u2014"));
const link = createElement("a", "blog-post-link");
link.href = articleUrl(post.slug);
link.append(createElement("h2", "", post.title));
link.append(createElement("p", "", post.summary));
link.append(createElement("span", "article-tag", post.category));
const readTime = createElement("p", "read-time", `${post.readTime} min read`);
const arrow = createElement("a", "blog-arrow", "\u2192");
arrow.href = articleUrl(post.slug);
arrow.setAttribute("aria-label", `Read ${post.title}`);
row.append(date, link, readTime, arrow);
return row;
};
const buildPagination = (totalPages) => {
pagination.replaceChildren();
if (totalPages <= 1) {
pagination.hidden = true;
return;
}
pagination.hidden = false;
for (let page = 1; page <= totalPages; page += 1) {
const button = createElement("button", "page-button", String(page));
button.type = "button";
button.setAttribute("aria-label", `Show blog page ${page}`);
button.setAttribute("aria-current", page === currentPage ? "page" : "false");
button.addEventListener("click", () => {
currentPage = page;
render();
document.querySelector(".blog-index")?.scrollIntoView({
behavior: "smooth",
block: "start",
});
});
pagination.append(button);
}
};
const render = () => {
const normalizedQuery = currentQuery.toLowerCase();
const filteredPosts = posts
.map((post, index) => {
if (!normalizedQuery) {
return { post, rank: 0, index };
}
const title = post.title.toLowerCase();
const category = post.category.toLowerCase();
const summary = post.summary.toLowerCase();
const body = (post.body || []).map(blockText).join(" ").toLowerCase();
if (title.includes(normalizedQuery)) {
return { post, rank: 1, index };
}
if (category.includes(normalizedQuery)) {
return { post, rank: 2, index };
}
if (summary.includes(normalizedQuery)) {
return { post, rank: 3, index };
}
if (body.includes(normalizedQuery)) {
return { post, rank: 4, index };
}
return null;
})
.filter(Boolean)
.sort((a, b) => a.rank - b.rank || a.index - b.index)
.map((result) => result.post);
const totalPages = Math.max(1, Math.ceil(filteredPosts.length / pageSize));
currentPage = Math.min(currentPage, totalPages);
const start = (currentPage - 1) * pageSize;
const visiblePosts = filteredPosts.slice(start, start + pageSize);
blogList.replaceChildren(...visiblePosts.map(buildRow));
blogEmpty.hidden = filteredPosts.length !== 0;
endMarker.hidden = filteredPosts.length === 0;
buildPagination(totalPages);
};
searchInput?.addEventListener("input", (event) => {
currentQuery = event.target.value.trim();
currentPage = 1;
render();
});
render();
};
const renderPostPage = () => {
const article = document.querySelector("[data-post-page]");
if (!article) {
return;
}
const params = new URLSearchParams(window.location.search);
const slug = params.get("slug") || posts[0]?.slug;
const postIndex = posts.findIndex((entry) => entry.slug === slug);
const post = posts[postIndex];
if (!post) {
article.replaceChildren();
const notFoundTitle = createElement("h1");
notFoundTitle.append(createElement("span", "heading-highlight", "Post not found"));
article.append(
createElement("a", "article-back", "\u2190 Back to blog"),
notFoundTitle,
createElement("p", "article-dek", "That article could not be found."),
);
return;
}
document.title = `${post.title} | Rushil Rawat`;
const canonicalUrl = new URL(articleUrl(post.slug), "https://rushilrawat.com/").href;
document
.querySelector('link[rel="canonical"]')
?.setAttribute("href", canonicalUrl);
const description = document.querySelector('meta[name="description"]');
description?.setAttribute("content", post.summary);
document
.querySelector('meta[property="og:title"]')
?.setAttribute("content", `${post.title} | Rushil Rawat`);
document
.querySelector('meta[property="og:description"]')
?.setAttribute("content", post.summary);
document
.querySelector('meta[property="og:url"]')
?.setAttribute("content", canonicalUrl);
const articleSchema = document.querySelector("#article-schema");
if (articleSchema) {
articleSchema.textContent = JSON.stringify({
"@context": "https://schema.org",
"@type": "Article",
headline: post.title,
description: post.summary,
datePublished: post.date,
url: canonicalUrl,
author: {
"@type": "Person",
name: "Rushil Rawat",
url: "https://rushilrawat.com/",
},
publisher: {
"@type": "Person",
name: "Rushil Rawat",
},
});
}
const back = createElement("a", "article-back", "\u2190 Back to blog");
back.href = "blog.html";
const header = createElement("header", "article-header");
const postTitle = createElement("h1");
postTitle.append(createElement("span", "heading-highlight", post.title));
header.append(
createElement("p", "article-kicker", post.category),
postTitle,
createElement("p", "article-dek", post.summary),
);
const meta = createElement("div", "article-meta");
meta.append(
createElement("span", "", formatDate(post.date)),
createElement("span", "", `${post.readTime} min read`),
createElement("span", "", "Rushil Rawat"),
);
header.append(meta);
const body = createElement("div", "article-body");
post.body.forEach((block) => {
if (block.type === "heading") {
body.append(createElement("h2", "", block.text));
}
if (block.type === "paragraph") {
body.append(createElement("p", "", block.text));
}
if (block.type === "quote") {
body.append(createElement("blockquote", "", block.text));
}
if (block.type === "callout") {
const callout = createElement("aside", "article-callout");
callout.append(
createElement("span", "article-callout-label", block.label),
createElement("p", "", block.text),
);
body.append(callout);
}
if (block.type === "list") {
const list = createElement("ul", "article-list");
block.items.forEach((item) => {
list.append(createElement("li", "", item));
});
body.append(list);
}
if (block.type === "code") {
const pre = createElement("pre", "article-code");
const code = document.createElement("code");
code.textContent = block.text;
pre.append(code);
body.append(pre);
}
if (block.type === "image") {
const figure = createElement("figure", "article-figure");
const image = document.createElement("img");
image.src = block.src;
image.alt = block.alt;
image.loading = "lazy";
const caption = createElement("figcaption", "", block.caption);
figure.append(image, caption);
body.append(figure);
}
});
const nextPost = posts[postIndex - 1];
const previousPost = posts[postIndex + 1];
const footer = createElement("nav", "article-post-nav");
footer.setAttribute("aria-label", "Post navigation");
const nextLink = createElement("a", "article-nav-card");
if (nextPost) {
nextLink.href = articleUrl(nextPost.slug);
nextLink.append(
createElement("span", "article-footer-label", "\u2190 Next"),
createElement("strong", "", nextPost.title),
);
} else {
nextLink.setAttribute("aria-disabled", "true");
nextLink.append(
createElement("span", "article-footer-label", "\u2190 Next"),
createElement("strong", "", "No next post"),
);
}
const previousLink = createElement("a", "article-nav-card");
if (previousPost) {
previousLink.href = articleUrl(previousPost.slug);
previousLink.append(
createElement("span", "article-footer-label", "Previous \u2192"),
createElement("strong", "", previousPost.title),
);
} else {
previousLink.setAttribute("aria-disabled", "true");
previousLink.append(
createElement("span", "article-footer-label", "Previous \u2192"),
createElement("strong", "", "No previous post"),
);
}
footer.append(nextLink, previousLink);
article.replaceChildren(back, header, body, footer);
};
renderBlogIndex();
renderPostPage();