Skip to content
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 27 additions & 4 deletions blog/core/handlePosts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,16 @@ import { AppContext } from "../mod.ts";
import { BlogPost, SortBy, ViewFromDatabase } from "../types.ts";
import { VALID_SORT_ORDERS } from "../utils/constants.ts";

/**
* `BlogPost.date` may be a bare `YYYY-MM-DD` or a full ISO 8601 timestamp.
* A bare date is read as UTC midnight so ordering doesn't depend on the
* machine timezone. Unparseable values fall back to 0 instead of leaking NaN
* into the comparator (a NaN result is treated as 0, so the post never moves).
*/
const dateToTime = (date: string) =>
new Date(/^\d{4}-\d{2}-\d{2}$/.test(date) ? `${date}T00:00:00Z` : date)
.getTime() || 0;

Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
/**
* Returns an sorted BlogPost list
*
Expand Down Expand Up @@ -87,8 +97,7 @@ export const sortPosts = async (
return -1; // If post b doesn't have sort method, put it after post a
}
const comparison = sortMethod === "date"
? new Date(`${b.date}T00:00:00`).getTime() -
new Date(`${a.date}T00:00:00`).getTime()
? dateToTime(b.date) - dateToTime(a.date)
: a[sortMethod]?.toString().localeCompare(
b[sortMethod]?.toString() ?? "",
) ?? 0;
Expand Down Expand Up @@ -160,12 +169,25 @@ export const slicePosts = (
return posts.slice(startIndex, endIndex);
};

/**
* A record without a slug has no route, so it can never be rendered: listing it
* only produces cards linking to the listing itself. Dropped here, before
* slicePosts, so `count` still yields `count` renderable posts.
*/
export const filterRoutablePosts = (posts: BlogPost[]) =>
// Records come straight from the CMS, so `slug` is only a string by
// convention: the typeof guard keeps a malformed one from throwing here and
// taking the whole listing down with it.
posts.filter(({ slug }) => typeof slug === "string" && slug.trim());

const filterPosts = (
posts: BlogPost[],
allPosts: BlogPost[],
slug?: string | string[],
postSlugs?: string[],
term?: string,
): BlogPost[] => {
const posts = filterRoutablePosts(allPosts);

if (typeof slug === "string") {
const firstFilter = postSlugs && postSlugs.length > 0
? filterPostsBySlugs(posts, postSlugs)
Expand Down Expand Up @@ -210,6 +232,7 @@ export default async function handlePosts(
if (!filteredPosts || filteredPosts.length === 0) {
return null;
}
const sorted = await sortPosts(filteredPosts, sortBy, ctx);

return await sortPosts(filteredPosts, sortBy, ctx);
return sorted;
}
Loading