Skip to content

Commit 069bb41

Browse files
committed
Sort posts by date and order.
1 parent 42430f8 commit 069bb41

File tree

2 files changed

+20
-18
lines changed

2 files changed

+20
-18
lines changed

src/lib/dates.ts

Lines changed: 16 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,32 @@
1+
type D = Date | string;
2+
13
const fmtUTC = new Intl.DateTimeFormat(undefined, {
24
year: 'numeric',
35
month: 'short',
46
day: 'numeric',
57
timeZone: 'UTC',
68
});
79

8-
const fmtLocal = new Intl.DateTimeFormat(undefined, {
9-
year: 'numeric',
10-
month: 'short',
11-
day: 'numeric',
12-
});
13-
14-
export function asDate(d: Date | string): Date {
10+
export function asDate(d: D): Date {
1511
return d instanceof Date ? d : new Date(d);
1612
}
1713

18-
export function formatDateUTC(d: Date | string): string {
14+
export function formatDateUTC(d: D): string {
1915
return fmtUTC.format(asDate(d));
2016
}
2117

22-
export function formatDateLocal(d: Date | string): string {
23-
return fmtLocal.format(asDate(d));
18+
export function compareDatesDesc(a: D, b: D): number {
19+
return asDate(b).getTime() - asDate(a).getTime();
2420
}
2521

26-
export function compareDatesDesc(a: Date | string, b: Date | string): number {
27-
return asDate(b).getTime() - asDate(a).getTime();
22+
// Sort by date (newest first), then by order (lower first).
23+
export function compareByDateThenOrder(
24+
a: { date: D; order?: number },
25+
b: { date: D; order?: number }
26+
): number {
27+
const diff = compareDatesDesc(a.date, b.date);
28+
if (diff !== 0) return diff;
29+
const ao = (a.order ?? 0) | 0;
30+
const bo = (b.order ?? 0) | 0;
31+
return ao - bo; // lower order wins
2832
}

src/pages/blog/index.astro

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
---
22
import { getCollection } from 'astro:content';
3-
import { compareDatesDesc } from '@/lib/dates';
3+
import { compareByDateThenOrder } from '@/lib/dates';
44
55
const posts = await getCollection('blog', ({ data }) => data.published !== false);
6-
const sorted = posts.sort((a, b) => compareDatesDesc(a.data.date, b.data.date));
6+
const sorted = posts.sort((a, b) => compareByDateThenOrder(a.data, b.data));
77
---
88

99
<html lang="en">
@@ -12,10 +12,8 @@ const sorted = posts.sort((a, b) => compareDatesDesc(a.data.date, b.data.date));
1212
<h1>Blog</h1>
1313
<ul class="not-prose space-y-4">
1414
{sorted.map((post) => (
15-
<li class="border-b border-slate-800 pb-4">
16-
<a class="text-lg font-semibold hover:underline" href={`/blog/${post.slug}/`}>
17-
{post.data.title}
18-
</a>
15+
<li>
16+
<a href={`/blog/${post.slug}/`}>{post.data.title}</a>
1917
</li>
2018
))}
2119
</ul>

0 commit comments

Comments
 (0)