From 2383f2f455863126aa9775841ae9a5e8fedc2de3 Mon Sep 17 00:00:00 2001 From: EGOIST Date: Sat, 14 May 2022 00:11:14 +0800 Subject: [PATCH] tweaks --- src/components/site/SiteArchives.tsx | 53 +++++++++++++++++++++------- src/lib/date.ts | 7 ++-- src/models/page.model.ts | 8 ++--- 3 files changed, 49 insertions(+), 19 deletions(-) diff --git a/src/components/site/SiteArchives.tsx b/src/components/site/SiteArchives.tsx index 1b40569b..b696dee3 100644 --- a/src/components/site/SiteArchives.tsx +++ b/src/components/site/SiteArchives.tsx @@ -1,26 +1,53 @@ import Link from "next/link" +import { useMemo } from "react" import { formatDate } from "~/lib/date" +type Post = { id: string; publishedAt: string; slug: string; title: string } + export const SiteArchives: React.FC<{ - posts: - | { id: string; publishedAt: string; slug: string; title: string }[] - | undefined + posts: Post[] | undefined }> = ({ posts }) => { + const groupedByYear = useMemo>(() => { + const map = new Map() + + if (posts) { + for (const post of posts) { + const year = formatDate(post.publishedAt, "YYYY") + const items = map.get(year) || [] + items.push(post) + map.set(year, items) + } + } + + return map + }, [posts]) + if (!posts) return null + return ( <>

Archives

-
- {posts.map((post) => { +
+ {[...groupedByYear.keys()].map((year) => { + const posts = groupedByYear.get(year)! return ( - - - {post.title} - - {formatDate(post.publishedAt)} - - - +
+

{year}

+ {posts.map((post) => { + return ( + + + + {post.title} + + + {formatDate(post.publishedAt, "MMM D")} + + + + ) + })} +
) })}
diff --git a/src/lib/date.ts b/src/lib/date.ts index aec167a0..b5f59f57 100644 --- a/src/lib/date.ts +++ b/src/lib/date.ts @@ -1,5 +1,8 @@ import dayjs from "dayjs" -export const formatDate = (date: string | Date) => { - return dayjs(date).format("MMM D, YYYY") +export const formatDate = ( + date: string | Date, + format: "MMM D" | "MMM D, YYYY" | "YYYY" = "MMM D, YYYY" +) => { + return dayjs(date).format(format) } diff --git a/src/models/page.model.ts b/src/models/page.model.ts index f7193afa..31114743 100644 --- a/src/models/page.model.ts +++ b/src/models/page.model.ts @@ -154,17 +154,17 @@ export async function getPagesBySite( deletedAt: null, type: input.type === "post" ? "POST" : "PAGE", } - if (input.visibility === PageVisibilityEnum.Published) { + if (visibility === PageVisibilityEnum.Published) { where.published = true where.publishedAt = { lte: now, } - } else if (input.visibility === PageVisibilityEnum.Scheduled) { + } else if (visibility === PageVisibilityEnum.Scheduled) { where.published = true where.publishedAt = { gt: now, } - } else if (input.visibility === PageVisibilityEnum.Draft) { + } else if (visibility === PageVisibilityEnum.Draft) { where.published = false } @@ -173,7 +173,7 @@ export async function getPagesBySite( prisma.page.findMany({ where, orderBy: { - createdAt: "desc", + publishedAt: "desc", }, take: take + 1, cursor: input.cursor