blob: c507d695726424f73bf73d44b7b6bcef40521771 (
plain)
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
|
---
import type { CollectionEntry } from 'astro:content';
import { getCollection } from 'astro:content';
export interface Props {
headingLevel?: 1 | 2 | 3 | 4 | 5 | 6,
hideAuthor?: boolean,
};
const { headingLevel = 2, hideAuthor = false } = Astro.props;
const posts = (await getCollection('blog'));
const distinctYears: number[] = posts
.map(post => post.data.pubDate.year)
.reduce<number[]>((acc, curr) => acc.includes(curr) ? acc : [...acc, curr], [])
.sort((a, b) => b - a);
function matchesYear(year: number) {
return (post: CollectionEntry<'blog'>) => post.data.pubDate.year === year;
}
function sortByPubDateDescending(post1: CollectionEntry<'blog'>, post2: CollectionEntry<'blog'>) {
const year1 = post1.data.pubDate.year;
const year2 = post2.data.pubDate.year;
const month1 = post1.data.pubDate.month;
const month2 = post2.data.pubDate.month;
const day1 = post1.data.pubDate.day;
const day2 = post2.data.pubDate.day;
if (year1 !== year2) {
return year2 - year1;
} else if (month1 !== month2) {
return month2 - month1;
} else {
return day2 - day1;
}
}
const headingElem = `h${headingLevel}`;
const canonicalBlogUrl = new URL('blog', Astro.site)
---
<section class="h-feed">
<Fragment set:html={`
<${headingElem} class="p-name">
My blog
</${headingElem}>
`} />
<aside>
<p class={hideAuthor ? 'hidden' : ''}>
This blog is written by <a class="p-author h-card" href="/">Joe Carstairs</a>
</p>
<p hidden>
<a class="u-url" href={canonicalBlogUrl}>Permalink</a>
</p>
</aside>
{ distinctYears.map(year => (
<h3>{year}</h3>
<ul>
{ posts.filter(matchesYear(year)).sort(sortByPubDateDescending).map(post => (
<li class="h-entry">
<a class="u-url p-name" href={`/blog/${post.slug}`}>{post.data.title}</a>
</li>
)) }
</ul>
)) }
</section>
|