1
mirror of https://github.com/jakejarvis/jarv.is.git synced 2025-06-27 17:05:42 -04:00

homebrew comments system

This commit is contained in:
2025-05-14 09:47:51 -04:00
parent cce48e558f
commit b196249f25
61 changed files with 3616 additions and 397 deletions

View File

@ -3,6 +3,10 @@
# See lib/env.ts for the list of required environment variables and how to get them.
###############
AUTH_GITHUB_CLIENT_ID=
AUTH_GITHUB_CLIENT_SECRET=
AUTH_SECRET=
DATABASE_URL=
GITHUB_TOKEN=
KV_REST_API_TOKEN=
KV_REST_API_URL=
@ -11,8 +15,6 @@ RESEND_FROM_EMAIL=
RESEND_TO_EMAIL=
TURNSTILE_SECRET_KEY=
NEXT_PUBLIC_BASE_URL=
NEXT_PUBLIC_GISCUS_CATEGORY_ID=
NEXT_PUBLIC_GISCUS_REPO_ID=
NEXT_PUBLIC_GITHUB_REPO=
NEXT_PUBLIC_ONION_DOMAIN=
NEXT_PUBLIC_SITE_LOCALE=

View File

@ -8,6 +8,7 @@ pnpm-lock.yaml
.vercel/
# other
lib/db/migrations/
public/
.devcontainer/devcontainer.json
.vscode/

View File

@ -6,7 +6,7 @@
[![GitHub repo size](https://img.shields.io/github/repo-size/jakejarvis/jarv.is?color=009cdf&label=repo%20size&logo=git&logoColor=white)](https://github.com/jakejarvis/jarv.is)
[![Dynamic JSON Badge](https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fjarv.is%2Fapi%2Fhits&query=%24.total.hits&logo=googleanalytics&logoColor=white&label=hits&color=salmon&cacheSeconds=1800)](https://jarv.is/api/hits)
My humble abode on the World Wide Web, created and deployed using [Next.js](https://nextjs.org/), [Tailwind CSS](https://github.com/user-attachments/assets/dfe99976-c73d-46f1-8a50-f26338463ad8), [Upstash](https://upstash.com/), [Giscus](https://giscus.app/), [and more](https://jarv.is/humans.txt).
My humble abode on the World Wide Web, created and deployed using [Next.js](https://nextjs.org/), [Tailwind CSS](https://github.com/user-attachments/assets/dfe99976-c73d-46f1-8a50-f26338463ad8), [Neon Postgres](https://neon.tech/), [Drizzle](https://orm.drizzle.team/), [Better Auth](https://www.better-auth.com/), [and more](https://jarv.is/humans.txt).
## 🕹️ Getting Started
@ -14,7 +14,7 @@ My humble abode on the World Wide Web, created and deployed using [Next.js](http
I highly recommend spinning up a [Codespace](https://github.com/features/codespaces) with the button above to start inside of a preconfigured and tested environment. But you can also clone this repository locally, run `pnpm install` to pull down the necessary dependencies and `pnpm dev` to start the local server, and then open [localhost:3000](http://localhost:3000/) in a browser. Pages will live-refresh when source files are changed.
**Be sure to populate the required environment variables!** Refer to [`lib/env.ts`](lib/env.ts), which documents (and strictly [type-checks](https://env.t3.gg/docs/introduction)) these variables. The included [`.env.example`](.env.example) file should be copied and used as a template for a new `.env.local` file, which the local `next dev` server will then ingest.
**Be sure to populate the required environment variables!** Refer to [`lib/env.ts`](lib/env.ts), which documents (and strictly [type-checks](https://env.t3.gg/docs/introduction)) these variables. The included [`.env.example`](.env.example) file should be copied and used as a template for a new local `.env` file, which the local `next dev` server will then ingest.
> ⚠️ **Currently, there are a few assumptions sprinkled throughout the code that this repo will be deployed to [Vercel](https://nextjs.org/docs/app/building-your-application/deploying#managed-nextjs-with-vercel) and _only_ Vercel.** I'll correct this soon™ now that some escape hatches (namely [OpenNext](https://opennext.js.org/)) actually exist...

View File

@ -0,0 +1,4 @@
import { auth } from "@/lib/auth";
import { toNextJsHandler } from "better-auth/next-js";
export const { POST, GET } = toNextJsHandler(auth);

View File

@ -1,7 +1,6 @@
import { NextResponse } from "next/server";
import { unstable_cache as cache } from "next/cache";
import { getViews as _getViews } from "@/lib/posts";
import { POSTS_DIR } from "@/lib/config/constants";
import { getViews as _getViews } from "@/lib/server/views";
const getViews = cache(_getViews, undefined, {
revalidate: 300, // 5 minutes
@ -25,9 +24,9 @@ export const GET = async (): Promise<
const total = {
hits: Object.values(views).reduce((acc, curr) => acc + curr, 0),
};
const pages = Object.entries(views).map(([slug, hits]) => ({
slug: `${POSTS_DIR}/${slug}`,
hits,
const pages = Object.entries(views).map(([slug, views]) => ({
slug,
hits: views,
}));
pages.sort((a, b) => b.hits - a.hits);

View File

@ -1,5 +1,4 @@
import PageTitle from "@/components/layout/page-title";
import Comments from "@/components/comments";
import { createMetadata } from "@/lib/metadata";
export const metadata = createMetadata({
@ -35,7 +34,3 @@ npx @jakejarvis/cli
## License
MIT &copy; [Jake Jarvis](https://jarv.is/), [Sindre Sorhus](https://sindresorhus.com/)
---
<Comments title="CLI" />

View File

@ -1,9 +1,8 @@
import PageTitle from "@/components/layout/page-title";
import Link from "@/components/link";
import ContactForm from "@/components/contact-form";
import { createMetadata } from "@/lib/metadata";
import ContactForm from "./form";
export const metadata = createMetadata({
title: "Contact Me",
description: "Fill out this quick form and I'll get back to you as soon as I can.",

View File

@ -5,6 +5,7 @@ import { ThemeProvider, ThemeScript } from "@/components/layout/theme-context";
import Header from "@/components/layout/header";
import Footer from "@/components/layout/footer";
import SkipNavButton, { SKIP_NAV_ID } from "@/components/layout/skip-nav";
import Toaster from "@/components/ui/sonner";
import { defaultMetadata } from "@/lib/metadata";
import { GeistMono, GeistSans } from "@/lib/fonts";
import siteConfig from "@/lib/config/site";
@ -73,6 +74,8 @@ const RootLayout = ({ children }: Readonly<{ children: React.ReactNode }>) => {
<Footer className="my-6 w-full" />
</div>
<Toaster position="bottom-center" />
</ThemeProvider>
<Analytics />

View File

@ -1,12 +1,12 @@
import { env } from "@/lib/env";
import { Suspense } from "react";
import { JsonLd } from "react-schemaorg";
import { formatDate, formatDateISO } from "@/lib/date";
import { CalendarDaysIcon, TagIcon, SquarePenIcon, EyeIcon } from "lucide-react";
import Link from "@/components/link";
import Time from "@/components/time";
import Comments from "@/components/comments";
import Loading from "@/components/loading";
import ViewCounter from "@/components/view-counter";
import Comments from "@/components/comments/comments";
import CommentsSkeleton from "@/components/comments/comments-skeleton";
import { getSlugs, getFrontMatter } from "@/lib/posts";
import { createMetadata } from "@/lib/metadata";
import siteConfig from "@/lib/config/site";
@ -91,7 +91,9 @@ const Page = async ({ params }: { params: Promise<{ slug: string }> }) => {
className={"text-foreground/70 flex flex-nowrap items-center gap-x-2 whitespace-nowrap hover:no-underline"}
>
<CalendarDaysIcon className="inline size-4 shrink-0" />
<Time date={frontmatter!.date} format="MMMM d, y" />
<time dateTime={formatDateISO(frontmatter!.date)} title={formatDate(frontmatter!.date, "MMM d, y, h:mm a O")}>
{formatDate(frontmatter!.date, "MMMM d, y")}
</time>
</Link>
{frontmatter!.tags && (
@ -119,18 +121,16 @@ const Page = async ({ params }: { params: Promise<{ slug: string }> }) => {
<span>Improve This Post</span>
</Link>
{env.NEXT_PUBLIC_ENV === "production" && (
<div className="flex min-w-14 flex-nowrap items-center gap-x-2 whitespace-nowrap">
<EyeIcon className="inline size-4 shrink-0" />
<Suspense
// when this loads, the component will count up from zero to the actual number of hits, so we can simply
// show a zero here as a "loading indicator"
fallback={<span>0</span>}
>
<ViewCounter slug={`${POSTS_DIR}/${frontmatter!.slug}`} />
</Suspense>
</div>
)}
<div className="flex min-w-14 flex-nowrap items-center gap-x-2 whitespace-nowrap">
<EyeIcon className="inline size-4 shrink-0" />
<Suspense
// when this loads, the component will count up from zero to the actual number of hits, so we can simply
// show a zero here as a "loading indicator"
fallback={<span>0</span>}
>
<ViewCounter slug={`${POSTS_DIR}/${frontmatter!.slug}`} />
</Suspense>
</div>
</div>
<h1 className="mt-2 mb-3 text-3xl/10 font-bold md:text-4xl/12">
@ -143,17 +143,13 @@ const Page = async ({ params }: { params: Promise<{ slug: string }> }) => {
<MDXContent />
{env.NEXT_PUBLIC_ENV === "production" && (
<div id="comments" className="mt-8 min-h-36 border-t-2 pt-8">
{!frontmatter!.noComments ? (
<Suspense fallback={<Loading boxes={3} width={40} className="mx-auto my-8 block" />}>
<Comments title={frontmatter!.title} />
</Suspense>
) : (
<div className="text-foreground/85 text-center font-medium">Comments are disabled for this post.</div>
)}
<section id="comments" className="isolate mt-8 mb-10 min-h-36 w-full border-t-2 pt-8">
<div className="mx-auto w-full max-w-3xl">
<Suspense fallback={<CommentsSkeleton />}>
<Comments slug={`${POSTS_DIR}/${frontmatter!.slug}`} closed={frontmatter!.noComments} />
</Suspense>
</div>
)}
</section>
</>
);
};

View File

@ -1,11 +1,12 @@
import { env } from "@/lib/env";
import { EyeIcon } from "lucide-react";
import Link from "@/components/link";
import Time from "@/components/time";
import { getFrontMatter, getViews } from "@/lib/posts";
import { getFrontMatter } from "@/lib/posts";
import { createMetadata } from "@/lib/metadata";
import { formatDate, formatDateISO } from "@/lib/date";
import authorConfig from "@/lib/config/author";
import { POSTS_DIR } from "@/lib/config/constants";
import { getViews } from "@/lib/server/views";
import type { ReactElement } from "react";
import type { FrontMatter } from "@/lib/posts";
@ -29,7 +30,7 @@ const Page = async () => {
const year = new Date(post.date).getUTCFullYear();
(postsByYear[year] || (postsByYear[year] = [])).push({
...post,
views: views[post.slug] || 0,
views: views[`${POSTS_DIR}/${post.slug}`] || 0,
});
});
@ -44,13 +45,18 @@ const Page = async () => {
<ul className="space-y-4">
{posts.map(({ slug, date, title, htmlTitle, views }) => (
<li className="flex text-base leading-relaxed" key={slug}>
<Time date={date} format="MMM d" className="text-muted-foreground w-18 shrink-0 md:w-22" />
<span className="text-muted-foreground w-18 shrink-0 md:w-22">
<time dateTime={formatDateISO(date)} title={formatDate(date, "MMM d, y, h:mm a O")}>
{formatDate(date, "MMM d")}
</time>
</span>
<div className="space-x-2.5">
<Link
dynamicOnHover
href={`/${POSTS_DIR}/${slug}`}
dangerouslySetInnerHTML={{ __html: htmlTitle || title }}
/>
{views > 0 && (
<span className="bg-muted text-muted-foreground inline-flex h-5 flex-nowrap items-center gap-1 rounded-md px-1.5 align-text-top text-xs font-semibold text-nowrap shadow select-none">
<EyeIcon className="inline-block size-4 shrink-0" />

View File

@ -1,6 +1,6 @@
import PageTitle from "@/components/layout/page-title";
import Marquee from "@/components/marquee";
import Comments from "@/components/comments";
import { Win95Icon } from "@/components/icons";
import { createMetadata } from "@/lib/metadata";
import { ComicNeue } from "@/lib/fonts";
@ -49,19 +49,6 @@ export const PageStyles = () => (
</style>
);
export const WindowsLogo = () => (
<svg
xmlns="http://www.w3.org/2000/svg"
fill="currentColor"
stroke="currentColor"
strokeWidth="0"
viewBox="0 0 24 24"
className="inline size-4 align-text-top"
>
<path d="M5.712 1.596l-.756.068-.238.55.734-.017zm1.39.927l-.978.137-.326.807.96-.12.345-.824zM4.89 3.535l-.72.05-.24.567.721-.017zm3.724.309l-1.287.068-.394.96 1.27-.052zm1.87.566l-1.579.069-.566 1.357 1.596-.088.548-1.338zm-4.188.037l-.977.153-.343.806.976-.12zm6.144.668l-1.87.135-.637 1.527 1.87-.154zm2.925.219c-.11 0-.222 0-.334.002l-.767 1.85c1.394-.03 2.52.089 3.373.38l-1.748 4.201c-.955-.304-2.082-.444-3.36-.394l-.54 1.305a8.762 8.762 0 0 1 3.365.396l-1.663 4.014c-1.257-.27-2.382-.395-3.387-.344l-.782 1.887c3.363-.446 6.348.822 9.009 3.773L24 9.23c-2.325-2.575-5.2-3.88-8.637-3.896zm-.644.002l-2.024.12-.687 1.68 2.025-.19zm-10.603.05l-.719.036-.224.566h.703l.24-.601zm3.69.397l-1.287.069-.395.959 1.27-.05zM5.54 6.3l-.994.154-.344.807.98-.121zm4.137.066l-1.58.069L7.53 7.77l1.596-.085.55-1.32zm1.955.688l-1.87.135-.636 1.527 1.887-.154zm2.282.19l-2.01.136-.7 1.682 2.04-.19.67-1.63zm-10.57.066l-.739.035-.238.564h.72l.257-.6zm3.705.293l-1.303.085-.394.96 1.287-.034zm11.839.255a6.718 6.718 0 0 1 2.777 1.717l-1.75 4.237c-.617-.584-1.15-.961-1.611-1.149l-1.201-.498zM4.733 8.22l-.976.154-.344.807.961-.12.36-.841zm4.186 0l-1.594.052-.549 1.354L8.37 9.54zm1.957.668L8.99 9.04l-.619 1.508 1.87-.135.636-1.527zm2.247.275l-2.007.12-.703 1.665 2.042-.156zM2.52 9.267l-.718.033-.24.549.718-.016zm3.725.273l-1.289.07-.41.96 1.287-.03.412-1zm1.87.6l-1.596.05-.55 1.356 1.598-.084.547-1.322zm-4.186.037l-.979.136-.324.805.96-.119zm6.14.633l-1.87.154-.653 1.527 1.906-.154zm2.267.275l-2.026.12-.686 1.663 2.025-.172zm-10.569.031l-.739.037-.238.565.72-.016zm3.673.362l-1.289.068-.41.978 1.305-.05zm-2.285.533l-.976.154-.326.805.96-.12.342-.84zm4.153.07l-1.596.066-.565 1.356 1.612-.084zm1.957.666l-1.889.154-.617 1.526 1.886-.15zm2.28.223l-2.025.12-.685 1.665 2.041-.172.67-1.613zm-10.584.05l-.738.053L0 13.64l.72-.02.24-.6zm3.705.31l-1.285.07-.395.976 1.287-.05.393-.997zm11.923.07c1.08.29 2.024.821 2.814 1.613l-1.715 4.183c-.892-.754-1.82-1.32-2.814-1.664l1.715-4.133zm-10.036.515L4.956 14l-.549 1.32 1.578-.066.567-1.338zm-4.184.014l-.996.156-.309.79.961-.106zm6.14.67l-1.904.154-.617 1.527 1.89-.154.632-1.527zm2.231.324l-2.025.123-.686 1.682 2.026-.174zm-6.863.328l-1.3.068-.397.98 1.285-.054zm1.871.584l-1.578.068-.566 1.334 1.595-.064zm1.953.701l-1.867.137-.635 1.51 1.87-.137zm2.23.31l-2.005.122-.703 1.68 2.04-.19.67-1.61z" />
</svg>
);
<PageStyles />
<PageTitle canonical="/previously" className="font-semibold">
@ -75,7 +62,7 @@ _Previously on the [Cringey Chronicles&trade;](https://web.archive.org/web/20010
<WarningMarquee />
[<WindowsLogo /> Click here for the _full_ experience (at your own risk).](https://y2k.pages.dev)
[<Win95Icon className="inline size-4 align-text-top" /> Click here for the _full_ experience (at your own risk).](https://y2k.pages.dev)
<iframe
src="https://jakejarvis.github.io/my-first-website/"
@ -149,7 +136,3 @@ _[April 2018](https://hungry-mayer-40e790.netlify.app/) ([view source](https://g
![March 2020](./images/2020_03.png)
_[March 2020](https://quiet-truffle-92842d.netlify.app/) ([view source](https://github.com/jakejarvis/jarv.is-hugo))_
---
<Comments title="Previously on..." />

View File

@ -21,12 +21,16 @@ For a likely excessive level of privacy and security, this website is also mirro
## Analytics
A very simple hit counter on each blog post tallies an aggregate number of pageviews (i.e. `hits = hits + 1`) in a [Upstash Redis](https://upstash.com/) database. Individual views and identifying (or non-identifying) details are **never stored or logged**.
A very simple hit counter on each blog post tallies an aggregate number of pageviews (i.e. `hits = hits + 1`) in a [Neon Postgres](https://neon.tech/) database. Individual views and identifying (or non-identifying) details are **never stored or logged**.
The [server component](https://github.com/jakejarvis/jarv.is/blob/main/app/notes/%5Bslug%5D/counter.tsx) and [API endpoint](https://github.com/jakejarvis/jarv.is/blob/main/app/api/hits/route.ts) are open source, and [snapshots of the database](https://github.com/jakejarvis/website-stats) are public.
The [server component](https://github.com/jakejarvis/jarv.is/blob/main/components/view-counter.tsx) and [API endpoint](https://github.com/jakejarvis/jarv.is/blob/main/app/api/hits/route.ts) are open source, and [snapshots of the database](https://github.com/jakejarvis/website-stats) are public.
[**Vercel Analytics**](https://vercel.com/docs/analytics) is also used to gain insights into referrers, search terms, etc. [without collecting anything identifiable](https://vercel.com/docs/analytics/privacy-policy) about you.
## Comments
Post comments are similarly stored in a Postgres database. Authentication is provided via GitHub, from which the account's username, email, and avatar URL are stored.
## Third-Party Content
Occasionally, embedded content from third-party services is included in posts, and some may contain tracking code that is outside of my control. Please refer to their privacy policies for more information:

View File

@ -6,9 +6,10 @@ import PageTitle from "@/components/layout/page-title";
import Link from "@/components/link";
import RelativeTime from "@/components/relative-time";
import ActivityCalendar from "@/components/activity-calendar";
import { GitHubIcon } from "@/components/icons";
import { cn } from "@/lib/utils";
import { createMetadata } from "@/lib/metadata";
import { getContributions, getRepos } from "./api";
import { getContributions, getRepos } from "@/lib/server/github";
export const metadata = createMetadata({
title: "Projects",
@ -111,15 +112,7 @@ const Page = async () => {
<p className="mt-6 mb-0 text-center text-base font-medium">
<Link href={`https://github.com/${env.NEXT_PUBLIC_GITHUB_USERNAME}`} className="hover:no-underline">
View more on{" "}
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
className="fill-foreground/80 mx-0.5 inline size-5 align-text-top"
>
<path d="M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12" />
</svg>{" "}
GitHub.
View more on <GitHubIcon className="fill-foreground/80 mx-0.5 inline size-5 align-text-top" /> GitHub.
</Link>
</p>
</>

View File

@ -1,5 +1,4 @@
import PageTitle from "@/components/layout/page-title";
import Comments from "@/components/comments";
import { createMetadata } from "@/lib/metadata";
export const metadata = createMetadata({
@ -165,7 +164,3 @@ Other geeky stuff:
- 2x [**ecobee3 lite**](https://www.ecobee.com/en-us/smart-thermostats/smart-wifi-thermostat/)
- 2x [**Sonos One**](https://www.sonos.com/en-us/shop/one.html) (with Alexa turned off...hopefully? 🤫)
- 2x [**Apple TV 4K** (2021)](https://www.apple.com/apple-tv-4k/)
---
<Comments title="/uses" />

View File

@ -1,5 +1,4 @@
import PageTitle from "@/components/layout/page-title";
import Comments from "@/components/comments";
import { createMetadata } from "@/lib/metadata";
import backgroundImg from "./sundar.jpg";
@ -72,7 +71,3 @@ A little-known monopolistic internet conglomorate simply unleashed [multiple](ht
- **Kaspersky:** [Beware the .zip and .mov domains!](https://usa.kaspersky.com/blog/zip-mov-domain-extension-confusion/28351/)
- **Palo Alto Networks:** [New Top Level Domains .zip and .mov open the door for new attacks](https://knowledgebase.paloaltonetworks.com/KCSArticleDetail?id=kA14u000000g1wOCAQ)
- **Google, twenty years ago:** ["Don't be evil"](https://web.archive.org/web/20050204181615/http://investor.google.com/conduct.html)
---
<Comments title="fuckyougoogle.zip" />

View File

@ -1,7 +1,7 @@
"use client";
import { ActivityCalendar } from "react-activity-calendar";
import { format } from "date-fns";
import { formatDate } from "@/lib/date";
import type { ComponentPropsWithoutRef } from "react";
import type { Activity } from "react-activity-calendar";
import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
@ -48,7 +48,7 @@ const Calendar = ({
<Tooltip>
<TooltipTrigger asChild>{block}</TooltipTrigger>
<TooltipContent>
<span className="text-[0.825rem] font-medium">{`${activity.count === 0 ? "No" : activity.count} ${noun}${activity.count === 1 ? "" : "s"} on ${format(activity.date, "MMMM do")}`}</span>
<span className="text-[0.825rem] font-medium">{`${activity.count === 0 ? "No" : activity.count} ${noun}${activity.count === 1 ? "" : "s"} on ${formatDate(activity.date, "MMMM do")}`}</span>
</TooltipContent>
</Tooltip>
)}

View File

@ -1,34 +0,0 @@
"use client";
import { env } from "@/lib/env";
import Giscus from "@giscus/react";
import type { GiscusProps } from "@giscus/react";
const Comments = ({ title }: { title: string }) => {
// fail silently if giscus isn't configured
if (!env.NEXT_PUBLIC_GISCUS_REPO_ID || !env.NEXT_PUBLIC_GISCUS_CATEGORY_ID) {
console.warn(
"[giscus] not configured, ensure 'NEXT_PUBLIC_GISCUS_REPO_ID' and 'NEXT_PUBLIC_GISCUS_CATEGORY_ID' environment variables are set."
);
return null;
}
return (
<Giscus
repo={env.NEXT_PUBLIC_GITHUB_REPO as GiscusProps["repo"]}
repoId={env.NEXT_PUBLIC_GISCUS_REPO_ID}
term={title}
category="Comments"
categoryId={env.NEXT_PUBLIC_GISCUS_CATEGORY_ID}
mapping="specific"
reactionsEnabled="1"
emitMetadata="0"
inputPosition="top"
theme="preferred_color_scheme"
loading="lazy"
/>
);
};
export default Comments;

View File

@ -0,0 +1,96 @@
"use client";
import { useState } from "react";
import { ReplyIcon, EditIcon, Trash2Icon, EllipsisIcon, Loader2Icon } from "lucide-react";
import { toast } from "sonner";
import Button from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuTrigger,
DropdownMenuItem,
} from "@/components/ui/dropdown-menu";
import Form from "./comment-form";
import { useSession } from "@/lib/auth-client";
import { deleteComment, type CommentWithUser } from "@/lib/server/comments";
const CommentActions = ({ comment }: { comment: CommentWithUser }) => {
const [isReplying, setIsReplying] = useState(false);
const [isEditing, setIsEditing] = useState(false);
const [isDeleting, setIsDeleting] = useState(false);
const { data: session } = useSession();
if (!session) return null;
const handleDelete = async () => {
if (!confirm("Are you sure you want to delete this comment?")) return;
setIsDeleting(true);
try {
await deleteComment(comment.id);
toast.success("Your comment has been deleted successfully.");
} catch (error) {
console.error("Error deleting comment:", error);
toast.error("Failed to delete comment. Please try again.");
} finally {
setIsDeleting(false);
}
};
return (
<div className="mt-4">
{isEditing ? (
<Form
slug={comment.pageSlug}
initialContent={comment.content}
commentId={comment.id}
onCancel={() => setIsEditing(false)}
onSuccess={() => setIsEditing(false)}
/>
) : (
<div className="flex gap-2">
<Button variant="outline" size="sm" onClick={() => setIsReplying(!isReplying)} className="h-8 px-2">
<ReplyIcon className="mr-1 h-3.5 w-3.5" />
Reply
</Button>
{session.user.id === comment.user.id && (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" size="sm" className="h-8 px-2 text-xs">
<EllipsisIcon />
<span className="sr-only">Actions Menu</span>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuItem onClick={() => setIsEditing(!isEditing)}>
<EditIcon />
Edit
</DropdownMenuItem>
<DropdownMenuItem onClick={handleDelete} disabled={isDeleting} variant="destructive">
{isDeleting ? <Loader2Icon className="animate-spin" /> : <Trash2Icon />}
Delete
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
)}
</div>
)}
{isReplying && (
<div className="mt-4">
<Form
slug={comment.pageSlug}
parentId={comment.id}
onCancel={() => setIsReplying(false)}
onSuccess={() => setIsReplying(false)}
/>
</div>
)}
</div>
);
};
export default CommentActions;

View File

@ -0,0 +1,194 @@
"use client";
import { useState, useTransition } from "react";
import { getImageProps } from "next/image";
import { InfoIcon, Loader2Icon } from "lucide-react";
import { toast } from "sonner";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import Button from "@/components/ui/button";
import Textarea from "@/components/ui/textarea";
import Link from "@/components/link";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { MarkdownIcon } from "@/components/icons";
import { useSession } from "@/lib/auth-client";
import { createComment, updateComment } from "@/lib/server/comments";
import type { FormEvent } from "react";
const CommentForm = ({
slug,
parentId,
commentId,
initialContent = "",
onCancel,
onSuccess,
}: {
slug: string;
parentId?: string;
commentId?: string;
initialContent?: string;
onCancel?: () => void;
onSuccess?: () => void;
}) => {
const [content, setContent] = useState(initialContent);
const [isPending, startTransition] = useTransition();
const isEditing = !!commentId;
const isReplying = !!parentId;
const { data: session } = useSession();
const handleSubmit = (e: FormEvent) => {
e.preventDefault();
if (!content.trim()) {
toast.error("Comment cannot be empty.");
return;
}
startTransition(async () => {
try {
if (isEditing) {
await updateComment(commentId, content);
toast.success("Comment updated!");
} else {
await createComment({
content,
parentId,
pageSlug: slug,
});
toast.success("Comment posted!");
}
// Reset form if not editing
if (!isEditing) {
setContent("");
}
// Call success callback if provided
onSuccess?.();
} catch (error) {
console.error("Error submitting comment:", error);
toast.error("Failed to submit comment. Please try again.");
}
});
};
return (
<form onSubmit={handleSubmit} className="space-y-4" data-intent={isEditing ? "edit" : "create"}>
<div className="flex gap-4">
{!isEditing && (
<div className="shrink-0">
<Avatar className="size-10">
{session?.user.image && (
<AvatarImage
{...getImageProps({
src: session.user.image,
alt: `@${session.user.name}'s avatar`,
width: 40,
height: 40,
}).props}
width={undefined}
height={undefined}
/>
)}
<AvatarFallback>{session?.user.name.charAt(0).toUpperCase()}</AvatarFallback>
</Avatar>
</div>
)}
<div className="min-w-0 flex-1 space-y-4">
<Textarea
value={content}
onChange={(e) => setContent(e.target.value)}
placeholder={isReplying ? "Reply to this comment..." : "Write your thoughts..."}
className="min-h-[4lh] w-full"
disabled={isPending}
/>
<div className="flex justify-between gap-4">
<div>
{/* Only show the markdown help text if the comment is new */}
{!isEditing && !isReplying && (
<p className="text-muted-foreground text-[0.8rem] leading-relaxed">
<MarkdownIcon className="mr-1.5 inline-block size-4 align-text-top" />
<span className="max-md:hidden">Basic&nbsp;</span>
<Popover>
<PopoverTrigger>
<span className="text-primary decoration-primary/40 cursor-pointer font-semibold no-underline decoration-2 underline-offset-4 hover:underline">
<span>Markdown</span>
<span className="max-md:hidden">&nbsp;syntax</span>
</span>
</PopoverTrigger>
<PopoverContent align="start">
<p className="text-sm leading-loose">
<InfoIcon className="mr-1.5 inline size-4.5 align-text-top" />
Examples:
</p>
<ul className="[&>li::marker]:text-muted-foreground my-2 list-inside list-disc pl-1 text-sm [&>li]:my-1.5 [&>li]:pl-1 [&>li]:text-nowrap [&>li::marker]:font-normal">
<li>
<span className="font-bold">**bold**</span>
</li>
<li>
<span className="italic">_italics_</span>
</li>
<li>
[
<Link href="https://jarv.is" className="hover:no-underline">
links
</Link>
](https://jarv.is)
</li>
<li>
<span className="bg-muted rounded-sm px-[0.3rem] py-[0.2rem] font-mono text-sm font-medium">
`code`
</span>
</li>
<li>
~~<span className="line-through">strikethrough</span>~~
</li>
</ul>
<p className="text-sm leading-loose">
<Link href="https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax">
Learn more.
</Link>
</p>
</PopoverContent>
</Popover>
<span>&nbsp;is supported</span>
<span className="max-md:hidden">&nbsp;here</span>
<span>.</span>
</p>
)}
</div>
<div className="flex justify-end gap-2">
{(onCancel || isEditing) && (
<Button type="button" variant="outline" onClick={onCancel} disabled={isPending}>
Cancel
</Button>
)}
<Button type="submit" disabled={isPending || !content.trim()}>
{isPending ? (
<>
<Loader2Icon className="mr-2 h-4 w-4 animate-spin" />
{isEditing ? "Updating..." : "Posting..."}
</>
) : isEditing ? (
"Edit"
) : isReplying ? (
"Reply"
) : (
"Comment"
)}
</Button>
</div>
</div>
</div>
</div>
</form>
);
};
export default CommentForm;

View File

@ -0,0 +1,71 @@
import { getImageProps } from "next/image";
import Markdown from "react-markdown";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import Link from "@/components/link";
import RelativeTime from "@/components/relative-time";
import Actions from "./comment-actions";
import { remarkGfm, remarkSmartypants } from "@/lib/remark";
import { rehypeExternalLinks } from "@/lib/rehype";
import { cn } from "@/lib/utils";
import type { CommentWithUser } from "@/lib/server/comments";
const CommentSingle = ({ comment }: { comment: CommentWithUser }) => {
const divId = `comment-${comment.id.substring(0, 8)}`;
return (
<div className="group scroll-mt-4" id={divId}>
<div className="flex gap-4">
<div className="shrink-0">
<Avatar className="size-8 md:size-10">
{comment.user.image && (
<AvatarImage
{...getImageProps({
src: comment.user.image,
alt: `@${comment.user.name}'s avatar`,
width: 40,
height: 40,
}).props}
width={undefined}
height={undefined}
/>
)}
<AvatarFallback>{comment.user.name.charAt(0).toUpperCase()}</AvatarFallback>
</Avatar>
</div>
<div className="min-w-0 flex-1">
<div className="mb-1 flex items-center gap-2">
<Link href={`https://github.com/${comment.user.name}`} className="font-medium hover:no-underline">
@{comment.user.name}
</Link>
<Link href={`#${divId}`} className="text-muted-foreground text-xs leading-none hover:no-underline">
<RelativeTime date={comment.createdAt} />
</Link>
</div>
<div
className={cn(
"isolate max-w-none text-[0.875rem] leading-relaxed",
"[&_p]:my-5 [&_p]:first:mt-0 [&_p]:last:mb-0",
"[&_a]:text-primary [&_a]:decoration-primary/40 [&_a]:no-underline [&_a]:decoration-2 [&_a]:underline-offset-4 [&_a]:hover:underline",
"[&_code]:bg-muted [&_code]:rounded-sm [&_code]:px-[0.3rem] [&_code]:py-[0.2rem] [&_code]:font-medium",
"group-has-data-[intent=edit]:hidden" // hides the rendered comment when its own edit form is active
)}
>
<Markdown
remarkPlugins={[remarkGfm, remarkSmartypants]}
rehypePlugins={[[rehypeExternalLinks, { target: "_blank", rel: "noopener noreferrer nofollow" }]]}
allowedElements={["p", "a", "em", "strong", "code", "pre", "blockquote", "del"]}
>
{comment.content}
</Markdown>
</div>
<Actions comment={comment} />
</div>
</div>
</div>
);
};
export default CommentSingle;

View File

@ -0,0 +1,40 @@
import Single from "./comment-single";
import { cn } from "@/lib/utils";
import type { CommentWithUser } from "@/lib/server/comments";
const CommentThread = ({
comment,
replies,
allComments,
level = 0,
}: {
comment: CommentWithUser;
replies: CommentWithUser[];
allComments: Record<string, CommentWithUser[]>;
level?: number;
}) => {
// Limit nesting to 3 levels
const maxLevel = 2;
return (
<>
<Single comment={comment} />
{replies.length > 0 && (
<div className={cn("mt-6 space-y-6", level < maxLevel && "ml-6 border-l-2 pl-6")}>
{replies.map((reply) => (
<CommentThread
key={reply.id}
comment={reply}
replies={allComments[reply.id] || []}
allComments={allComments}
level={level + 1}
/>
))}
</div>
)}
</>
);
};
export default CommentThread;

View File

@ -0,0 +1,26 @@
import Skeleton from "@/components/ui/skeleton";
const CommentsSkeleton = () => {
return (
<div className="mx-auto max-w-3xl space-y-6">
<Skeleton className="h-32 w-full" />
<div className="flex gap-4">
<Skeleton className="size-8 rounded-full md:size-10" />
<div className="flex-1 space-y-2">
<div className="flex items-center gap-2">
<Skeleton className="h-4 w-24" />
<Skeleton className="h-3 w-16" />
</div>
<Skeleton className="h-20 w-full" />
<div className="flex gap-2">
<Skeleton className="h-8 w-16" />
<Skeleton className="h-8 w-8" />
</div>
</div>
</div>
</div>
);
};
export default CommentsSkeleton;

View File

@ -0,0 +1,64 @@
import { headers } from "next/headers";
import Form from "./comment-form";
import Thread from "./comment-thread";
import SignIn from "./sign-in";
import { auth } from "@/lib/auth";
import { getComments, type CommentWithUser } from "@/lib/server/comments";
const Comments = async ({ slug, closed = false }: { slug: string; closed?: boolean }) => {
const session = await auth.api.getSession({
headers: await headers(),
});
const comments = await getComments(slug);
const commentsByParentId = comments.reduce(
(acc, comment) => {
const parentId = comment.parentId || "root";
if (!acc[parentId]) {
acc[parentId] = [];
}
acc[parentId].push(comment);
return acc;
},
{} as Record<string, CommentWithUser[]>
);
const rootComments = commentsByParentId["root"] || [];
return (
<div className="space-y-6">
{closed ? (
<div className="bg-muted/40 flex min-h-32 items-center justify-center rounded-lg p-6">
<p className="text-center font-medium">Comments are closed for this post.</p>
</div>
) : !session ? (
<div className="bg-muted/40 flex flex-col items-center justify-center rounded-lg p-6">
<p className="mb-4 text-center font-medium">Join the discussion by signing in:</p>
<SignIn callbackPath={`/${slug}#comments`} />
</div>
) : (
<Form slug={slug} />
)}
{!closed && rootComments.length === 0 ? (
<div className="text-foreground/80 py-8 text-center text-lg font-medium tracking-tight">
Be the first to comment!
</div>
) : (
<div className="space-y-6">
{rootComments.map((comment: CommentWithUser) => (
<Thread
key={comment.id}
comment={comment}
replies={commentsByParentId[comment.id] || []}
allComments={commentsByParentId}
/>
))}
</div>
)}
</div>
);
};
export default Comments;

View File

@ -0,0 +1,35 @@
"use client";
import { env } from "@/lib/env";
import { useState } from "react";
import { Loader2Icon } from "lucide-react";
import Button from "@/components/ui/button";
import { GitHubIcon } from "@/components/icons";
import { signIn } from "@/lib/auth-client";
const SignIn = ({ callbackPath }: { callbackPath?: string }) => {
const [isLoading, setIsLoading] = useState(false);
const handleSignIn = async () => {
setIsLoading(true);
try {
await signIn.social({
provider: "github",
callbackURL: `${env.NEXT_PUBLIC_BASE_URL}${callbackPath ? callbackPath : "/"}`,
});
} catch (error) {
console.error("Error signing in:", error);
setIsLoading(false);
}
};
return (
<Button onClick={handleSignIn} disabled={isLoading} size="lg" variant="outline">
{isLoading ? <Loader2Icon className="animate-spin" /> : <GitHubIcon />}
Sign in with GitHub
</Button>
);
};
export default SignIn;

View File

@ -8,9 +8,9 @@ import Link from "@/components/link";
import Input from "@/components/ui/input";
import Textarea from "@/components/ui/textarea";
import Button from "@/components/ui/button";
import { MarkdownIcon } from "@/components/icons";
import { cn } from "@/lib/utils";
import { send, type ContactState, type ContactInput } from "./action";
import { send, type ContactState, type ContactInput } from "@/lib/server/resend";
const ContactForm = () => {
const [formState, formAction, pending] = useActionState<ContactState, FormData>(send, {
@ -79,17 +79,7 @@ const ContactForm = () => {
)}
<div className="text-foreground/85 my-2 text-[0.8rem] leading-relaxed">
<svg
xmlns="http://www.w3.org/2000/svg"
fill="currentColor"
stroke="currentColor"
strokeWidth="0"
viewBox="0 0 24 24"
className="mr-1 inline-block size-4 align-text-top"
>
<path d="M22.27 19.385H1.73A1.73 1.73 0 010 17.655V6.345a1.73 1.73 0 011.73-1.73h20.54A1.73 1.73 0 0124 6.345v11.308a1.73 1.73 0 01-1.73 1.731zM5.769 15.923v-4.5l2.308 2.885 2.307-2.885v4.5h2.308V8.078h-2.308l-2.307 2.885-2.308-2.885H3.46v7.847zM21.232 12h-2.309V8.077h-2.307V12h-2.308l3.461 4.039z" />
</svg>{" "}
Basic{" "}
<MarkdownIcon className="mr-1.5 inline-block size-4 align-text-top" /> Basic{" "}
<Link href="https://commonmark.org/help/" title="Markdown reference sheet" className="font-semibold">
Markdown syntax
</Link>{" "}

53
components/icons.tsx Normal file
View File

@ -0,0 +1,53 @@
// miscellaneous icons that are not part of lucide-react
export const Win95Icon = ({ className }: { className?: string }) => (
<svg
xmlns="http://www.w3.org/2000/svg"
fill="currentColor"
stroke="currentColor"
strokeWidth="0"
viewBox="0 0 24 24"
className={className}
>
<path d="M5.712 1.596l-.756.068-.238.55.734-.017zm1.39.927l-.978.137-.326.807.96-.12.345-.824zM4.89 3.535l-.72.05-.24.567.721-.017zm3.724.309l-1.287.068-.394.96 1.27-.052zm1.87.566l-1.579.069-.566 1.357 1.596-.088.548-1.338zm-4.188.037l-.977.153-.343.806.976-.12zm6.144.668l-1.87.135-.637 1.527 1.87-.154zm2.925.219c-.11 0-.222 0-.334.002l-.767 1.85c1.394-.03 2.52.089 3.373.38l-1.748 4.201c-.955-.304-2.082-.444-3.36-.394l-.54 1.305a8.762 8.762 0 0 1 3.365.396l-1.663 4.014c-1.257-.27-2.382-.395-3.387-.344l-.782 1.887c3.363-.446 6.348.822 9.009 3.773L24 9.23c-2.325-2.575-5.2-3.88-8.637-3.896zm-.644.002l-2.024.12-.687 1.68 2.025-.19zm-10.603.05l-.719.036-.224.566h.703l.24-.601zm3.69.397l-1.287.069-.395.959 1.27-.05zM5.54 6.3l-.994.154-.344.807.98-.121zm4.137.066l-1.58.069L7.53 7.77l1.596-.085.55-1.32zm1.955.688l-1.87.135-.636 1.527 1.887-.154zm2.282.19l-2.01.136-.7 1.682 2.04-.19.67-1.63zm-10.57.066l-.739.035-.238.564h.72l.257-.6zm3.705.293l-1.303.085-.394.96 1.287-.034zm11.839.255a6.718 6.718 0 0 1 2.777 1.717l-1.75 4.237c-.617-.584-1.15-.961-1.611-1.149l-1.201-.498zM4.733 8.22l-.976.154-.344.807.961-.12.36-.841zm4.186 0l-1.594.052-.549 1.354L8.37 9.54zm1.957.668L8.99 9.04l-.619 1.508 1.87-.135.636-1.527zm2.247.275l-2.007.12-.703 1.665 2.042-.156zM2.52 9.267l-.718.033-.24.549.718-.016zm3.725.273l-1.289.07-.41.96 1.287-.03.412-1zm1.87.6l-1.596.05-.55 1.356 1.598-.084.547-1.322zm-4.186.037l-.979.136-.324.805.96-.119zm6.14.633l-1.87.154-.653 1.527 1.906-.154zm2.267.275l-2.026.12-.686 1.663 2.025-.172zm-10.569.031l-.739.037-.238.565.72-.016zm3.673.362l-1.289.068-.41.978 1.305-.05zm-2.285.533l-.976.154-.326.805.96-.12.342-.84zm4.153.07l-1.596.066-.565 1.356 1.612-.084zm1.957.666l-1.889.154-.617 1.526 1.886-.15zm2.28.223l-2.025.12-.685 1.665 2.041-.172.67-1.613zm-10.584.05l-.738.053L0 13.64l.72-.02.24-.6zm3.705.31l-1.285.07-.395.976 1.287-.05.393-.997zm11.923.07c1.08.29 2.024.821 2.814 1.613l-1.715 4.183c-.892-.754-1.82-1.32-2.814-1.664l1.715-4.133zm-10.036.515L4.956 14l-.549 1.32 1.578-.066.567-1.338zm-4.184.014l-.996.156-.309.79.961-.106zm6.14.67l-1.904.154-.617 1.527 1.89-.154.632-1.527zm2.231.324l-2.025.123-.686 1.682 2.026-.174zm-6.863.328l-1.3.068-.397.98 1.285-.054zm1.871.584l-1.578.068-.566 1.334 1.595-.064zm1.953.701l-1.867.137-.635 1.51 1.87-.137zm2.23.31l-2.005.122-.703 1.68 2.04-.19.67-1.61z" />
</svg>
);
export const MarkdownIcon = ({ className }: { className?: string }) => (
<svg
xmlns="http://www.w3.org/2000/svg"
fill="currentColor"
stroke="currentColor"
strokeWidth="0"
viewBox="0 0 24 24"
className={className}
>
<path d="M22.27 19.385H1.73A1.73 1.73 0 010 17.655V6.345a1.73 1.73 0 011.73-1.73h20.54A1.73 1.73 0 0124 6.345v11.308a1.73 1.73 0 01-1.73 1.731zM5.769 15.923v-4.5l2.308 2.885 2.307-2.885v4.5h2.308V8.078h-2.308l-2.307 2.885-2.308-2.885H3.46v7.847zM21.232 12h-2.309V8.077h-2.307V12h-2.308l3.461 4.039z" />
</svg>
);
export const GitHubIcon = ({ className }: { className?: string }) => (
<svg
xmlns="http://www.w3.org/2000/svg"
fill="currentColor"
stroke="currentColor"
strokeWidth="0"
viewBox="0 0 24 24"
className={className}
>
<path d="M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12" />
</svg>
);
export const NextjsIcon = ({ className }: { className?: string }) => (
<svg
xmlns="http://www.w3.org/2000/svg"
fill="currentColor"
stroke="currentColor"
strokeWidth="0"
viewBox="0 0 24 24"
className={className}
>
<path d="M18.665 21.978C16.758 23.255 14.465 24 12 24 5.377 24 0 18.623 0 12S5.377 0 12 0s12 5.377 12 12c0 3.583-1.574 6.801-4.067 9.001L9.219 7.2H7.2v9.596h1.615V9.251l9.85 12.727Zm-3.332-8.533 1.6 2.061V7.2h-1.6v6.245Z" />
</svg>
);

View File

@ -1,6 +1,7 @@
import { env } from "@/lib/env";
import { HeartIcon } from "lucide-react";
import Link from "@/components/link";
import { NextjsIcon } from "@/components/icons";
import { cn } from "@/lib/utils";
import siteConfig from "@/lib/config/site";
import type { ComponentPropsWithoutRef } from "react";
@ -33,16 +34,7 @@ const Footer = ({ className, ...rest }: ComponentPropsWithoutRef<"footer">) => {
aria-label="Next.js"
className="text-foreground/85 hover:text-foreground/60 hover:no-underline"
>
<svg
xmlns="http://www.w3.org/2000/svg"
fill="currentColor"
stroke="currentColor"
strokeWidth="0"
viewBox="0 0 24 24"
className="mx-[1px] inline size-4 align-text-top"
>
<path d="M18.665 21.978C16.758 23.255 14.465 24 12 24 5.377 24 0 18.623 0 12S5.377 0 12 0s12 5.377 12 12c0 3.583-1.574 6.801-4.067 9.001L9.219 7.2H7.2v9.596h1.615V9.251l9.85 12.727Zm-3.332-8.533 1.6 2.061V7.2h-1.6v6.245Z" />
</svg>
<NextjsIcon className="mx-[1px] inline size-4 align-text-top" />
</Link>
.{" "}
<Link

View File

@ -15,7 +15,7 @@ const Header = ({ className, ...rest }: ComponentPropsWithoutRef<"header">) => {
href="/"
rel="author"
aria-label={siteConfig.name}
className="hover:text-primary text-foreground/85 flex flex-shrink-0 items-center hover:no-underline"
className="hover:text-primary text-foreground/85 flex shrink-0 items-center hover:no-underline"
>
<Image
src={avatarImg}

View File

@ -1,25 +1,14 @@
"use client";
import { useMountedState } from "react-use";
import TimeAgo from "react-timeago";
import Time from "@/components/time";
import type { ComponentPropsWithoutRef } from "react";
import { type ComponentPropsWithoutRef } from "react";
const RelativeTime = ({
date,
...rest
}: ComponentPropsWithoutRef<"time"> & {
date: string;
}) => {
// play nice with SSR -- only use relative time on the client, since it'll quickly become outdated on the server and
// cause a react hydration mismatch error.
const isMounted = useMountedState();
if (!isMounted) {
return <Time date={date} format="MMM d, y" {...rest} />;
}
return <TimeAgo date={date} {...rest} />;
const RelativeTime = ({ ...rest }: ComponentPropsWithoutRef<typeof TimeAgo>) => {
return (
<span suppressHydrationWarning>
<TimeAgo {...rest} />
</span>
);
};
export default RelativeTime;

View File

@ -1,27 +0,0 @@
import { env } from "@/lib/env";
import { format, formatISO } from "date-fns";
import { enUS } from "date-fns/locale";
import { tz } from "@date-fns/tz";
import { utc } from "@date-fns/utc";
import type { ComponentPropsWithoutRef } from "react";
const Time = ({
date,
format: formatStr = "PPpp",
...rest
}: ComponentPropsWithoutRef<"time"> & {
date: string;
format?: string;
}) => {
return (
<time
dateTime={formatISO(date, { in: utc })}
title={format(date, "MMM d, y, h:mm a O", { in: tz(env.NEXT_PUBLIC_SITE_TZ), locale: enUS })}
{...rest}
>
{format(date, formatStr, { in: tz(env.NEXT_PUBLIC_SITE_TZ), locale: enUS })}
</time>
);
};
export default Time;

View File

@ -0,0 +1,112 @@
"use client";
import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog";
import { buttonVariants } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import type { ComponentPropsWithoutRef } from "react";
const AlertDialog = ({ ...rest }: ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Root>) => {
return <AlertDialogPrimitive.Root data-slot="alert-dialog" {...rest} />;
};
const AlertDialogTrigger = ({ ...rest }: ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Trigger>) => {
return <AlertDialogPrimitive.Trigger data-slot="alert-dialog-trigger" {...rest} />;
};
const AlertDialogPortal = ({ ...rest }: ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Portal>) => {
return <AlertDialogPrimitive.Portal data-slot="alert-dialog-portal" {...rest} />;
};
const AlertDialogOverlay = ({ className, ...rest }: ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Overlay>) => {
return (
<AlertDialogPrimitive.Overlay
data-slot="alert-dialog-overlay"
className={cn(
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
className
)}
{...rest}
/>
);
};
const AlertDialogContent = ({ className, ...rest }: ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Content>) => {
return (
<AlertDialogPortal>
<AlertDialogOverlay />
<AlertDialogPrimitive.Content
data-slot="alert-dialog-content"
className={cn(
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
className
)}
{...rest}
/>
</AlertDialogPortal>
);
};
const AlertDialogHeader = ({ className, ...rest }: ComponentPropsWithoutRef<"div">) => {
return (
<div
data-slot="alert-dialog-header"
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
{...rest}
/>
);
};
const AlertDialogFooter = ({ className, ...rest }: ComponentPropsWithoutRef<"div">) => {
return (
<div
data-slot="alert-dialog-footer"
className={cn("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end", className)}
{...rest}
/>
);
};
const AlertDialogTitle = ({ className, ...rest }: ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Title>) => {
return (
<AlertDialogPrimitive.Title
data-slot="alert-dialog-title"
className={cn("text-lg font-semibold", className)}
{...rest}
/>
);
};
const AlertDialogDescription = ({
className,
...rest
}: ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Description>) => {
return (
<AlertDialogPrimitive.Description
data-slot="alert-dialog-description"
className={cn("text-muted-foreground text-sm", className)}
{...rest}
/>
);
};
const AlertDialogAction = ({ className, ...rest }: ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Action>) => {
return <AlertDialogPrimitive.Action className={cn(buttonVariants(), className)} {...rest} />;
};
const AlertDialogCancel = ({ className, ...rest }: ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Cancel>) => {
return <AlertDialogPrimitive.Cancel className={cn(buttonVariants({ variant: "outline" }), className)} {...rest} />;
};
export {
AlertDialog,
AlertDialogPortal,
AlertDialogOverlay,
AlertDialogTrigger,
AlertDialogContent,
AlertDialogHeader,
AlertDialogFooter,
AlertDialogTitle,
AlertDialogDescription,
AlertDialogAction,
AlertDialogCancel,
};

33
components/ui/avatar.tsx Normal file
View File

@ -0,0 +1,33 @@
"use client";
import * as AvatarPrimitive from "@radix-ui/react-avatar";
import { cn } from "@/lib/utils";
import type { ComponentPropsWithoutRef } from "react";
const Avatar = ({ className, ...rest }: ComponentPropsWithoutRef<typeof AvatarPrimitive.Root>) => {
return (
<AvatarPrimitive.Root
data-slot="avatar"
className={cn("relative flex size-8 shrink-0 overflow-hidden rounded-full", className)}
{...rest}
/>
);
};
const AvatarImage = ({ className, ...rest }: ComponentPropsWithoutRef<typeof AvatarPrimitive.Image>) => {
return (
<AvatarPrimitive.Image data-slot="avatar-image" className={cn("aspect-square size-full", className)} {...rest} />
);
};
const AvatarFallback = ({ className, ...rest }: ComponentPropsWithoutRef<typeof AvatarPrimitive.Fallback>) => {
return (
<AvatarPrimitive.Fallback
data-slot="avatar-fallback"
className={cn("bg-muted flex size-full items-center justify-center rounded-full", className)}
{...rest}
/>
);
};
export { Avatar, AvatarImage, AvatarFallback };

View File

@ -3,7 +3,7 @@ import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
import type { ComponentPropsWithoutRef } from "react";
const buttonVariants = cva(
export const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium cursor-pointer disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
{
variants: {

View File

@ -0,0 +1,221 @@
"use client";
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu";
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react";
import { cn } from "@/lib/utils";
import type { ComponentPropsWithoutRef } from "react";
const DropdownMenu = ({ ...rest }: ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Root>) => {
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...rest} />;
};
const DropdownMenuPortal = ({ ...rest }: ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Portal>) => {
return <DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...rest} />;
};
const DropdownMenuTrigger = ({ ...rest }: ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Trigger>) => {
return <DropdownMenuPrimitive.Trigger data-slot="dropdown-menu-trigger" {...rest} />;
};
const DropdownMenuContent = ({
className,
sideOffset = 4,
...rest
}: ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Content>) => {
return (
<DropdownMenuPrimitive.Portal>
<DropdownMenuPrimitive.Content
data-slot="dropdown-menu-content"
sideOffset={sideOffset}
className={cn(
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",
className
)}
{...rest}
/>
</DropdownMenuPrimitive.Portal>
);
};
const DropdownMenuGroup = ({ ...rest }: ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Group>) => {
return <DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...rest} />;
};
const DropdownMenuItem = ({
className,
inset,
variant = "default",
...rest
}: ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Item> & {
inset?: boolean;
variant?: "default" | "destructive";
}) => {
return (
<DropdownMenuPrimitive.Item
data-slot="dropdown-menu-item"
data-inset={inset}
data-variant={variant}
className={cn(
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...rest}
/>
);
};
const DropdownMenuCheckboxItem = ({
className,
children,
checked,
...rest
}: ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.CheckboxItem>) => {
return (
<DropdownMenuPrimitive.CheckboxItem
data-slot="dropdown-menu-checkbox-item"
className={cn(
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
checked={checked}
{...rest}
>
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<CheckIcon className="size-4" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.CheckboxItem>
);
};
const DropdownMenuRadioGroup = ({ ...rest }: ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.RadioGroup>) => {
return <DropdownMenuPrimitive.RadioGroup data-slot="dropdown-menu-radio-group" {...rest} />;
};
const DropdownMenuRadioItem = ({
className,
children,
...rest
}: ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.RadioItem>) => {
return (
<DropdownMenuPrimitive.RadioItem
data-slot="dropdown-menu-radio-item"
className={cn(
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...rest}
>
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<CircleIcon className="size-2 fill-current" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.RadioItem>
);
};
const DropdownMenuLabel = ({
className,
inset,
...rest
}: ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Label> & {
inset?: boolean;
}) => {
return (
<DropdownMenuPrimitive.Label
data-slot="dropdown-menu-label"
data-inset={inset}
className={cn("px-2 py-1.5 text-sm font-medium data-[inset]:pl-8", className)}
{...rest}
/>
);
};
const DropdownMenuSeparator = ({
className,
...rest
}: ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Separator>) => {
return (
<DropdownMenuPrimitive.Separator
data-slot="dropdown-menu-separator"
className={cn("bg-border -mx-1 my-1 h-px", className)}
{...rest}
/>
);
};
const DropdownMenuShortcut = ({ className, ...rest }: ComponentPropsWithoutRef<"span">) => {
return (
<span
data-slot="dropdown-menu-shortcut"
className={cn("text-muted-foreground ml-auto text-xs tracking-widest", className)}
{...rest}
/>
);
};
const DropdownMenuSub = ({ ...rest }: ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Sub>) => {
return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...rest} />;
};
const DropdownMenuSubTrigger = ({
className,
inset,
children,
...rest
}: ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubTrigger> & {
inset?: boolean;
}) => {
return (
<DropdownMenuPrimitive.SubTrigger
data-slot="dropdown-menu-sub-trigger"
data-inset={inset}
className={cn(
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8",
className
)}
{...rest}
>
{children}
<ChevronRightIcon className="ml-auto size-4" />
</DropdownMenuPrimitive.SubTrigger>
);
};
const DropdownMenuSubContent = ({
className,
...rest
}: ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubContent>) => {
return (
<DropdownMenuPrimitive.SubContent
data-slot="dropdown-menu-sub-content"
className={cn(
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
className
)}
{...rest}
/>
);
};
export {
DropdownMenu,
DropdownMenuPortal,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuLabel,
DropdownMenuItem,
DropdownMenuCheckboxItem,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
DropdownMenuSeparator,
DropdownMenuShortcut,
DropdownMenuSub,
DropdownMenuSubTrigger,
DropdownMenuSubContent,
};

41
components/ui/popover.tsx Normal file
View File

@ -0,0 +1,41 @@
"use client";
import * as PopoverPrimitive from "@radix-ui/react-popover";
import { cn } from "@/lib/utils";
import type { ComponentPropsWithoutRef } from "react";
const Popover = ({ ...rest }: ComponentPropsWithoutRef<typeof PopoverPrimitive.Root>) => {
return <PopoverPrimitive.Root data-slot="popover" {...rest} />;
};
const PopoverTrigger = ({ ...rest }: ComponentPropsWithoutRef<typeof PopoverPrimitive.Trigger>) => {
return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...rest} />;
};
const PopoverContent = ({
className,
align = "center",
sideOffset = 4,
...rest
}: ComponentPropsWithoutRef<typeof PopoverPrimitive.Content>) => {
return (
<PopoverPrimitive.Portal>
<PopoverPrimitive.Content
data-slot="popover-content"
align={align}
sideOffset={sideOffset}
className={cn(
"bg-popover text-popover-foreground z-50 w-72 rounded-md border p-4 shadow-md outline-hidden",
className
)}
{...rest}
/>
</PopoverPrimitive.Portal>
);
};
const PopoverAnchor = ({ ...rest }: ComponentPropsWithoutRef<typeof PopoverPrimitive.Anchor>) => {
return <PopoverPrimitive.Anchor data-slot="popover-anchor" {...rest} />;
};
export { Popover, PopoverTrigger, PopoverContent, PopoverAnchor };

View File

@ -0,0 +1,27 @@
"use client";
import * as SeparatorPrimitive from "@radix-ui/react-separator";
import { cn } from "@/lib/utils";
import type { ComponentPropsWithoutRef } from "react";
const Separator = ({
className,
orientation = "horizontal",
decorative = true,
...rest
}: ComponentPropsWithoutRef<typeof SeparatorPrimitive.Root>) => {
return (
<SeparatorPrimitive.Root
data-slot="separator-root"
decorative={decorative}
orientation={orientation}
className={cn(
"bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",
className
)}
{...rest}
/>
);
};
export default Separator;

View File

@ -0,0 +1,8 @@
import { cn } from "@/lib/utils";
import type { ComponentPropsWithoutRef } from "react";
const Skeleton = ({ className, ...rest }: ComponentPropsWithoutRef<"div">) => {
return <div data-slot="skeleton" className={cn("bg-accent animate-pulse rounded-md", className)} {...rest} />;
};
export default Skeleton;

21
components/ui/sonner.tsx Normal file
View File

@ -0,0 +1,21 @@
"use client";
import { Toaster as Sonner, type ToasterProps } from "sonner";
const Toaster = ({ ...rest }: ToasterProps) => {
return (
<Sonner
className="toaster group"
style={
{
"--normal-bg": "var(--popover)",
"--normal-text": "var(--popover-foreground)",
"--normal-border": "var(--border)",
} as React.CSSProperties
}
{...rest}
/>
);
};
export default Toaster;

View File

@ -1,19 +1,14 @@
import { env } from "@/lib/env";
import { connection } from "next/server";
import { kv } from "@vercel/kv";
import CountUp from "@/components/count-up";
import { incrementViews } from "@/lib/server/views";
const ViewCounter = async ({ slug }: { slug: string }) => {
// ensure this component isn't triggered by prerenders and/or preloads
await connection();
try {
// if this is a new slug, redis will automatically create a new key and set its value to 0 (and then 1, obviously)
// https://upstash.com/docs/redis/sdks/ts/commands/string/incr
// TODO: maybe don't allow this? or maybe it's fine? kinda unclear how secure this is:
// https://nextjs.org/blog/security-nextjs-server-components-actions
// https://nextjs.org/docs/app/building-your-application/rendering/server-components
const hits = await kv.incr(`hits:${slug}`);
const hits = await incrementViews(slug);
// we have data!
return (

11
drizzle.config.ts Normal file
View File

@ -0,0 +1,11 @@
import "dotenv/config";
import { defineConfig } from "drizzle-kit";
export default defineConfig({
schema: "./lib/db/schema.ts",
out: "./lib/db/migrations",
dialect: "postgresql",
dbCredentials: {
url: process.env.DATABASE_URL!,
},
});

View File

@ -14,10 +14,16 @@ const compat = new FlatCompat({
/** @type {import("eslint").Linter.Config[]} */
export default [
{ ignores: ["README.md", ".next", ".vercel", "node_modules"] },
{ ignores: ["README.md", ".next", ".vercel", "node_modules", "lib/db/migrations"] },
...compat.config({
plugins: ["react-compiler", "css-modules"],
extends: ["eslint:recommended", "next/core-web-vitals", "next/typescript", "plugin:css-modules/recommended"],
extends: [
"eslint:recommended",
"next/core-web-vitals",
"next/typescript",
"plugin:css-modules/recommended",
"plugin:drizzle/recommended",
],
}),
...eslintCustomConfig,
eslintPluginPrettierRecommended,

8
lib/auth-client.ts Normal file
View File

@ -0,0 +1,8 @@
import { env } from "@/lib/env";
import { createAuthClient } from "better-auth/react";
export const authClient = createAuthClient({
baseURL: env.NEXT_PUBLIC_BASE_URL,
});
export const { signIn, signUp, useSession } = authClient;

31
lib/auth.ts Normal file
View File

@ -0,0 +1,31 @@
import { env } from "@/lib/env";
import { betterAuth, type BetterAuthOptions } from "better-auth";
import { nextCookies } from "better-auth/next-js";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { db } from "@/lib/db";
import * as schema from "@/lib/db/schema";
export const auth = betterAuth({
baseURL: env.NEXT_PUBLIC_BASE_URL,
database: drizzleAdapter(db, {
provider: "pg",
schema,
}),
plugins: [nextCookies()],
socialProviders: {
github: {
clientId: env.AUTH_GITHUB_CLIENT_ID,
clientSecret: env.AUTH_GITHUB_CLIENT_SECRET,
scope: ["read:user"],
disableDefaultScope: true,
mapProfileToUser(profile) {
return {
name: profile.login,
email: profile.email,
emailVerified: true,
image: profile.avatar_url,
};
},
},
},
} satisfies BetterAuthOptions);

13
lib/date.ts Normal file
View File

@ -0,0 +1,13 @@
import { env } from "@/lib/env";
import { format, formatISO } from "date-fns";
import { enUS } from "date-fns/locale";
import { tz } from "@date-fns/tz";
import { utc } from "@date-fns/utc";
export const formatDate = (date: string | number | Date, formatStr = "PPpp") => {
return format(date, formatStr, { in: tz(env.NEXT_PUBLIC_SITE_TZ), locale: enUS });
};
export const formatDateISO = (date: string | number | Date) => {
return formatISO(date, { in: utc });
};

6
lib/db/index.ts Normal file
View File

@ -0,0 +1,6 @@
import { drizzle } from "drizzle-orm/neon-http";
import { neon } from "@neondatabase/serverless";
const sql = neon(process.env.DATABASE_URL!);
export const db = drizzle({ client: sql });

View File

@ -0,0 +1,68 @@
CREATE TABLE "account" (
"id" text PRIMARY KEY NOT NULL,
"account_id" text NOT NULL,
"provider_id" text NOT NULL,
"user_id" text NOT NULL,
"access_token" text,
"refresh_token" text,
"id_token" text,
"access_token_expires_at" timestamp,
"refresh_token_expires_at" timestamp,
"scope" text,
"password" text,
"created_at" timestamp NOT NULL,
"updated_at" timestamp NOT NULL
);
--> statement-breakpoint
CREATE TABLE "comment" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"content" text NOT NULL,
"page_slug" text NOT NULL,
"parent_id" uuid,
"user_id" text NOT NULL,
"created_at" timestamp DEFAULT now() NOT NULL,
"updated_at" timestamp DEFAULT now() NOT NULL
);
--> statement-breakpoint
CREATE TABLE "page" (
"slug" text PRIMARY KEY NOT NULL,
"views" integer DEFAULT 1 NOT NULL
);
--> statement-breakpoint
CREATE TABLE "session" (
"id" text PRIMARY KEY NOT NULL,
"expires_at" timestamp NOT NULL,
"token" text NOT NULL,
"created_at" timestamp NOT NULL,
"updated_at" timestamp NOT NULL,
"ip_address" text,
"user_agent" text,
"user_id" text NOT NULL,
CONSTRAINT "session_token_unique" UNIQUE("token")
);
--> statement-breakpoint
CREATE TABLE "user" (
"id" text PRIMARY KEY NOT NULL,
"name" text NOT NULL,
"email" text NOT NULL,
"email_verified" boolean NOT NULL,
"image" text,
"created_at" timestamp NOT NULL,
"updated_at" timestamp NOT NULL,
CONSTRAINT "user_email_unique" UNIQUE("email")
);
--> statement-breakpoint
CREATE TABLE "verification" (
"id" text PRIMARY KEY NOT NULL,
"identifier" text NOT NULL,
"value" text NOT NULL,
"expires_at" timestamp NOT NULL,
"created_at" timestamp,
"updated_at" timestamp
);
--> statement-breakpoint
ALTER TABLE "account" ADD CONSTRAINT "account_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "comment" ADD CONSTRAINT "comment_page_slug_page_slug_fk" FOREIGN KEY ("page_slug") REFERENCES "public"."page"("slug") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "comment" ADD CONSTRAINT "comment_parent_id_comment_id_fk" FOREIGN KEY ("parent_id") REFERENCES "public"."comment"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "comment" ADD CONSTRAINT "comment_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "session" ADD CONSTRAINT "session_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;

View File

@ -0,0 +1,443 @@
{
"id": "d126927d-35cf-4b6f-ab97-3872b8db26a7",
"prevId": "00000000-0000-0000-0000-000000000000",
"version": "7",
"dialect": "postgresql",
"tables": {
"public.account": {
"name": "account",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true
},
"account_id": {
"name": "account_id",
"type": "text",
"primaryKey": false,
"notNull": true
},
"provider_id": {
"name": "provider_id",
"type": "text",
"primaryKey": false,
"notNull": true
},
"user_id": {
"name": "user_id",
"type": "text",
"primaryKey": false,
"notNull": true
},
"access_token": {
"name": "access_token",
"type": "text",
"primaryKey": false,
"notNull": false
},
"refresh_token": {
"name": "refresh_token",
"type": "text",
"primaryKey": false,
"notNull": false
},
"id_token": {
"name": "id_token",
"type": "text",
"primaryKey": false,
"notNull": false
},
"access_token_expires_at": {
"name": "access_token_expires_at",
"type": "timestamp",
"primaryKey": false,
"notNull": false
},
"refresh_token_expires_at": {
"name": "refresh_token_expires_at",
"type": "timestamp",
"primaryKey": false,
"notNull": false
},
"scope": {
"name": "scope",
"type": "text",
"primaryKey": false,
"notNull": false
},
"password": {
"name": "password",
"type": "text",
"primaryKey": false,
"notNull": false
},
"created_at": {
"name": "created_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true
},
"updated_at": {
"name": "updated_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true
}
},
"indexes": {},
"foreignKeys": {
"account_user_id_user_id_fk": {
"name": "account_user_id_user_id_fk",
"tableFrom": "account",
"tableTo": "user",
"columnsFrom": [
"user_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.comment": {
"name": "comment",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "uuid",
"primaryKey": true,
"notNull": true,
"default": "gen_random_uuid()"
},
"content": {
"name": "content",
"type": "text",
"primaryKey": false,
"notNull": true
},
"page_slug": {
"name": "page_slug",
"type": "text",
"primaryKey": false,
"notNull": true
},
"parent_id": {
"name": "parent_id",
"type": "uuid",
"primaryKey": false,
"notNull": false
},
"user_id": {
"name": "user_id",
"type": "text",
"primaryKey": false,
"notNull": true
},
"created_at": {
"name": "created_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"updated_at": {
"name": "updated_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
}
},
"indexes": {},
"foreignKeys": {
"comment_page_slug_page_slug_fk": {
"name": "comment_page_slug_page_slug_fk",
"tableFrom": "comment",
"tableTo": "page",
"columnsFrom": [
"page_slug"
],
"columnsTo": [
"slug"
],
"onDelete": "no action",
"onUpdate": "no action"
},
"comment_parent_id_comment_id_fk": {
"name": "comment_parent_id_comment_id_fk",
"tableFrom": "comment",
"tableTo": "comment",
"columnsFrom": [
"parent_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
},
"comment_user_id_user_id_fk": {
"name": "comment_user_id_user_id_fk",
"tableFrom": "comment",
"tableTo": "user",
"columnsFrom": [
"user_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.page": {
"name": "page",
"schema": "",
"columns": {
"slug": {
"name": "slug",
"type": "text",
"primaryKey": true,
"notNull": true
},
"views": {
"name": "views",
"type": "integer",
"primaryKey": false,
"notNull": true,
"default": 1
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.session": {
"name": "session",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true
},
"expires_at": {
"name": "expires_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true
},
"token": {
"name": "token",
"type": "text",
"primaryKey": false,
"notNull": true
},
"created_at": {
"name": "created_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true
},
"updated_at": {
"name": "updated_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true
},
"ip_address": {
"name": "ip_address",
"type": "text",
"primaryKey": false,
"notNull": false
},
"user_agent": {
"name": "user_agent",
"type": "text",
"primaryKey": false,
"notNull": false
},
"user_id": {
"name": "user_id",
"type": "text",
"primaryKey": false,
"notNull": true
}
},
"indexes": {},
"foreignKeys": {
"session_user_id_user_id_fk": {
"name": "session_user_id_user_id_fk",
"tableFrom": "session",
"tableTo": "user",
"columnsFrom": [
"user_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {
"session_token_unique": {
"name": "session_token_unique",
"nullsNotDistinct": false,
"columns": [
"token"
]
}
},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.user": {
"name": "user",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true
},
"name": {
"name": "name",
"type": "text",
"primaryKey": false,
"notNull": true
},
"email": {
"name": "email",
"type": "text",
"primaryKey": false,
"notNull": true
},
"email_verified": {
"name": "email_verified",
"type": "boolean",
"primaryKey": false,
"notNull": true
},
"image": {
"name": "image",
"type": "text",
"primaryKey": false,
"notNull": false
},
"created_at": {
"name": "created_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true
},
"updated_at": {
"name": "updated_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {
"user_email_unique": {
"name": "user_email_unique",
"nullsNotDistinct": false,
"columns": [
"email"
]
}
},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.verification": {
"name": "verification",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true
},
"identifier": {
"name": "identifier",
"type": "text",
"primaryKey": false,
"notNull": true
},
"value": {
"name": "value",
"type": "text",
"primaryKey": false,
"notNull": true
},
"expires_at": {
"name": "expires_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true
},
"created_at": {
"name": "created_at",
"type": "timestamp",
"primaryKey": false,
"notNull": false
},
"updated_at": {
"name": "updated_at",
"type": "timestamp",
"primaryKey": false,
"notNull": false
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
}
},
"enums": {},
"schemas": {},
"sequences": {},
"roles": {},
"policies": {},
"views": {},
"_meta": {
"columns": {},
"schemas": {},
"tables": {}
}
}

View File

@ -0,0 +1,13 @@
{
"version": "7",
"dialect": "postgresql",
"entries": [
{
"idx": 0,
"version": "7",
"when": 1747229716675,
"tag": "0000_puzzling_sphinx",
"breakpoints": true
}
]
}

70
lib/db/schema.ts Normal file
View File

@ -0,0 +1,70 @@
import { pgTable, text, timestamp, boolean, integer, uuid, AnyPgColumn } from "drizzle-orm/pg-core";
export const user = pgTable("user", {
id: text("id").primaryKey(),
name: text("name").notNull(),
email: text("email").notNull().unique(),
emailVerified: boolean("email_verified").notNull(),
image: text("image"),
createdAt: timestamp("created_at").notNull(),
updatedAt: timestamp("updated_at").notNull(),
});
export const session = pgTable("session", {
id: text("id").primaryKey(),
expiresAt: timestamp("expires_at").notNull(),
token: text("token").notNull().unique(),
createdAt: timestamp("created_at").notNull(),
updatedAt: timestamp("updated_at").notNull(),
ipAddress: text("ip_address"),
userAgent: text("user_agent"),
userId: text("user_id")
.notNull()
.references(() => user.id, { onDelete: "cascade" }),
});
export const account = pgTable("account", {
id: text("id").primaryKey(),
accountId: text("account_id").notNull(),
providerId: text("provider_id").notNull(),
userId: text("user_id")
.notNull()
.references(() => user.id, { onDelete: "cascade" }),
accessToken: text("access_token"),
refreshToken: text("refresh_token"),
idToken: text("id_token"),
accessTokenExpiresAt: timestamp("access_token_expires_at"),
refreshTokenExpiresAt: timestamp("refresh_token_expires_at"),
scope: text("scope"),
password: text("password"),
createdAt: timestamp("created_at").notNull(),
updatedAt: timestamp("updated_at").notNull(),
});
export const verification = pgTable("verification", {
id: text("id").primaryKey(),
identifier: text("identifier").notNull(),
value: text("value").notNull(),
expiresAt: timestamp("expires_at").notNull(),
createdAt: timestamp("created_at"),
updatedAt: timestamp("updated_at"),
});
export const page = pgTable("page", {
slug: text("slug").primaryKey(),
views: integer("views").notNull().default(1),
});
export const comment = pgTable("comment", {
id: uuid("id").defaultRandom().primaryKey(),
content: text("content").notNull(),
pageSlug: text("page_slug")
.notNull()
.references(() => page.slug),
parentId: uuid("parent_id").references((): AnyPgColumn => comment.id, { onDelete: "cascade" }),
userId: text("user_id")
.notNull()
.references(() => user.id, { onDelete: "cascade" }),
createdAt: timestamp("created_at").notNull().defaultNow(),
updatedAt: timestamp("updated_at").notNull().defaultNow(),
});

View File

@ -3,6 +3,35 @@ import * as v from "valibot";
export const env = createEnv({
server: {
/**
* Required. A random value used for authentication encryption.
*
* @see https://www.better-auth.com/docs/installation#set-environment-variables
*/
AUTH_SECRET: v.string(),
/**
* Required. The client ID from the GitHub Developer Portal for this site's OAuth App.
*
* @see https://www.better-auth.com/docs/authentication/github
*/
AUTH_GITHUB_CLIENT_ID: v.string(),
/**
* Required. A client secret from the GitHub Developer Portal for this site's OAuth App.
*
* @see https://www.better-auth.com/docs/authentication/github
*/
AUTH_GITHUB_CLIENT_SECRET: v.string(),
/**
* Required. Database connection string for a Postgres database. May be set automatically by Vercel's Neon
* integration.
*
* @see https://vercel.com/integrations/neon
*/
DATABASE_URL: v.pipe(v.string(), v.startsWith("postgres://")),
/**
* Required. GitHub API token used for [/projects](../app/projects/page.tsx) grid. Only needs the `public_repo`
* scope since we don't need/want to change anything, obviously.
@ -11,24 +40,6 @@ export const env = createEnv({
*/
GITHUB_TOKEN: v.optional(v.pipe(v.string(), v.startsWith("ghp_"))),
/**
* Required. Redis storage credentials for hit counter's [server component](../app/notes/[slug]/counter.tsx) and API
* endpoint. Currently set automatically by Vercel's Upstash integration.
*
* @see https://upstash.com/docs/redis/sdks/ts/getstarted
* @see https://vercel.com/marketplace/upstash
*/
KV_REST_API_TOKEN: v.string(),
/**
* Required. Redis storage credentials for hit counter's [server component](../app/notes/[slug]/counter.tsx) and API
* endpoint. Currently set automatically by Vercel's Upstash integration.
*
* @see https://upstash.com/docs/redis/sdks/ts/getstarted
* @see https://vercel.com/marketplace/upstash
*/
KV_REST_API_URL: v.pipe(v.string(), v.url(), v.startsWith("https://"), v.endsWith(".upstash.io")),
/**
* Required. Uses Resend API to send contact form submissions via a [server action](../app/contact/action.ts). May
* be set automatically by Vercel's Resend integration.
@ -102,20 +113,6 @@ export const env = createEnv({
: "development"
),
/**
* Optional. Enables comments on blog posts via GitHub discussions.
*
* @see https://giscus.app/
*/
NEXT_PUBLIC_GISCUS_CATEGORY_ID: v.optional(v.string()),
/**
* Optional. Enables comments on blog posts via GitHub discussions.
*
* @see https://giscus.app/
*/
NEXT_PUBLIC_GISCUS_REPO_ID: v.optional(v.string()),
/** Required. GitHub repository for the site in the format of `{username}/{repo}`. */
NEXT_PUBLIC_GITHUB_REPO: v.pipe(v.string(), v.includes("/")),
@ -157,8 +154,6 @@ export const env = createEnv({
experimental__runtimeEnv: {
NEXT_PUBLIC_BASE_URL: process.env.NEXT_PUBLIC_BASE_URL,
NEXT_PUBLIC_ENV: process.env.NEXT_PUBLIC_ENV,
NEXT_PUBLIC_GISCUS_CATEGORY_ID: process.env.NEXT_PUBLIC_GISCUS_CATEGORY_ID,
NEXT_PUBLIC_GISCUS_REPO_ID: process.env.NEXT_PUBLIC_GISCUS_REPO_ID,
NEXT_PUBLIC_GITHUB_REPO: process.env.NEXT_PUBLIC_GITHUB_REPO,
NEXT_PUBLIC_GITHUB_USERNAME: process.env.NEXT_PUBLIC_GITHUB_USERNAME,
NEXT_PUBLIC_ONION_DOMAIN: process.env.NEXT_PUBLIC_ONION_DOMAIN,

View File

@ -1,10 +1,10 @@
import { env } from "@/lib/env";
import { cache } from "react";
import { kv } from "@vercel/kv";
import path from "path";
import fs from "fs/promises";
import glob from "fast-glob";
import { unified } from "unified";
import { decode } from "html-entities";
import {
remarkParse,
remarkSmartypants,
@ -13,10 +13,8 @@ import {
remarkMdx,
remarkStripMdxImportsExports,
} from "@/lib/remark";
import { decode } from "html-entities";
import { rehypeSanitize, rehypeStringify } from "@/lib/rehype";
import { POSTS_DIR } from "@/lib/config/constants";
import rehypeSanitize from "rehype-sanitize";
import rehypeStringify from "rehype-stringify";
export type FrontMatter = {
slug: string;
@ -112,57 +110,6 @@ export const getFrontMatter: {
}
);
export const getViews: {
/**
* Retrieves the number of views for ALL posts
*/
(): Promise<Record<string, number>>;
/**
* Retrieves the number of views for a given slug, or undefined if the slug does not exist
*/
(slug: string): Promise<number | undefined>;
} = cache(
async (
// eslint-disable-next-line @typescript-eslint/no-explicit-any
slug?: any
): // eslint-disable-next-line @typescript-eslint/no-explicit-any
Promise<any> => {
// ensure the prefix is consistent for all keys in the KV store
const KEY_PREFIX = `hits:${POSTS_DIR}/`;
if (typeof slug === "string") {
try {
const views = await kv.get<string>(`${KEY_PREFIX}${slug}`);
return views ? parseInt(views, 10) : undefined;
} catch (error) {
console.error(`Failed to retrieve view count for post with slug "${slug}":`, error);
return undefined;
}
}
if (!slug) {
try {
const allSlugs = await getSlugs();
const pages: Record<string, number> = {};
// get the value (number of views) for each key (the slug of the page)
const values = await kv.mget<string[]>(...allSlugs.map((slug) => `${KEY_PREFIX}${slug}`));
// pair the slugs with their view counts
allSlugs.forEach((slug, index) => (pages[slug.replace(KEY_PREFIX, "")] = parseInt(values[index], 10)));
return pages;
} catch (error) {
console.error("Failed to retrieve view counts:", error);
return undefined;
}
}
throw new Error("getViews() called with invalid argument.");
}
);
/** Returns the content of a post with very limited processing to include in RSS feeds */
export const getContent = cache(async (slug: string): Promise<string | undefined> => {
try {
@ -182,6 +129,7 @@ export const getContent = cache(async (slug: string): Promise<string | undefined
"code",
"pre",
"blockquote",
"del",
"h1",
"h2",
"h3",

View File

@ -1,3 +1,4 @@
export { default as rehypeExternalLinks } from "rehype-external-links";
export { default as rehypeMdxCodeProps } from "rehype-mdx-code-props";
export { default as rehypeMdxImportMedia } from "rehype-mdx-import-media";
export { default as rehypeSanitize } from "rehype-sanitize";

143
lib/server/comments.ts Normal file
View File

@ -0,0 +1,143 @@
"use server";
import { headers } from "next/headers";
import { revalidatePath } from "next/cache";
import { eq, desc } from "drizzle-orm";
import { db } from "@/lib/db";
import * as schema from "@/lib/db/schema";
import { auth } from "@/lib/auth";
export type CommentWithUser = typeof schema.comment.$inferSelect & {
user: Pick<typeof schema.user.$inferSelect, "id" | "name" | "image">;
};
export const getComments = async (pageSlug: string): Promise<CommentWithUser[]> => {
try {
// Fetch all comments for the page with user details
const commentsWithUsers = await db
.select()
.from(schema.comment)
.innerJoin(schema.user, eq(schema.comment.userId, schema.user.id))
.where(eq(schema.comment.pageSlug, pageSlug))
.orderBy(desc(schema.comment.createdAt));
return commentsWithUsers.map(({ comment, user }) => ({
...comment,
user: {
// we're namely worried about keeping the user's email private here, but nothing sensitive is stored in the db
id: user.id,
name: user.name,
image: user.image,
},
}));
} catch (error) {
console.error("[server/comments] error fetching comments:", error);
throw new Error("Failed to fetch comments");
}
};
export const createComment = async (data: { content: string; pageSlug: string; parentId?: string }) => {
const session = await auth.api.getSession({
headers: await headers(),
});
if (!session || !session.user) {
throw new Error("You must be logged in to comment");
}
try {
// Insert the comment
await db.insert(schema.comment).values({
content: data.content,
pageSlug: data.pageSlug,
parentId: data.parentId || null,
userId: session.user.id,
});
// Revalidate the page to show the new comment
revalidatePath(`/${data.pageSlug}`);
} catch (error) {
console.error("[server/comments] error creating comment:", error);
throw new Error("Failed to create comment");
}
};
export const updateComment = async (commentId: string, content: string) => {
const session = await auth.api.getSession({
headers: await headers(),
});
if (!session || !session.user) {
throw new Error("You must be logged in to update a comment");
}
try {
// Get the comment to verify ownership
const comment = await db
.select({ userId: schema.comment.userId, pageSlug: schema.comment.pageSlug })
.from(schema.comment)
.where(eq(schema.comment.id, commentId))
.then((results) => results[0]);
if (!comment) {
throw new Error("Comment not found");
}
// Verify ownership
if (comment.userId !== session.user.id) {
throw new Error("You can only edit your own comments");
}
// Update the comment
await db
.update(schema.comment)
.set({
content,
updatedAt: new Date(),
})
.where(eq(schema.comment.id, commentId));
// Revalidate the page to show the updated comment
revalidatePath(`/${comment.pageSlug}`);
} catch (error) {
console.error("[server/comments] error updating comment:", error);
throw new Error("Failed to update comment");
}
};
export const deleteComment = async (commentId: string) => {
const session = await auth.api.getSession({
headers: await headers(),
});
if (!session || !session.user) {
throw new Error("You must be logged in to delete a comment");
}
try {
// Get the comment to verify ownership and get the page_slug for revalidation
const comment = await db
.select({ userId: schema.comment.userId, pageSlug: schema.comment.pageSlug })
.from(schema.comment)
.where(eq(schema.comment.id, commentId))
.then((results) => results[0]);
if (!comment) {
throw new Error("Comment not found");
}
// Verify ownership
if (comment.userId !== session.user.id) {
throw new Error("You can only delete your own comments");
}
// Delete the comment
await db.delete(schema.comment).where(eq(schema.comment.id, commentId));
// Revalidate the page to update the comments list
revalidatePath(`/${comment.pageSlug}`);
} catch (error) {
console.error("[server/comments] error deleting comment:", error);
throw new Error("Failed to delete comment");
}
};

View File

@ -1,4 +1,3 @@
// https://nextjs.org/docs/app/building-your-application/rendering/composition-patterns#keeping-server-only-code-out-of-the-client-environment
import "server-only";
import { env } from "@/lib/env";
@ -73,7 +72,7 @@ export const getContributions = async (): Promise<
};
});
} catch (error) {
console.error("[/projects] Failed to fetch contributions:", error);
console.error("[server/github] Failed to fetch contributions:", error);
return [];
}
};
@ -138,7 +137,7 @@ export const getRepos = async (): Promise<Repository[] | undefined> => {
return user.repositories.edges?.map((edge) => edge!.node as Repository);
} catch (error) {
console.error("[/projects] Failed to fetch repositories:", error);
console.error("[server/github] Failed to fetch repositories:", error);
return [];
}
};

View File

@ -36,7 +36,7 @@ export type ContactState = {
export const send = async (state: ContactState, payload: FormData): Promise<ContactState> => {
// TODO: remove after debugging why automated spam entries are causing 500 errors
console.debug("[/contact] received payload:", payload);
console.debug("[server/resend] received payload:", payload);
try {
const data = v.safeParse(ContactSchema, Object.fromEntries(payload));
@ -68,7 +68,7 @@ export const send = async (state: ContactState, payload: FormData): Promise<Cont
});
if (!turnstileResponse || !turnstileResponse.ok) {
throw new Error(`[/contact] turnstile validation failed: ${turnstileResponse.status}`);
throw new Error(`[server/resend] turnstile validation failed: ${turnstileResponse.status}`);
}
const turnstileData = (await turnstileResponse.json()) as { success: boolean };
@ -82,7 +82,7 @@ export const send = async (state: ContactState, payload: FormData): Promise<Cont
if (env.RESEND_FROM_EMAIL === "onboarding@resend.dev") {
// https://resend.com/docs/api-reference/emails/send-email
console.warn("[/contact] 'RESEND_FROM_EMAIL' is not set, falling back to onboarding@resend.dev.");
console.warn("[server/resend] 'RESEND_FROM_EMAIL' is not set, falling back to onboarding@resend.dev.");
}
// send email
@ -97,7 +97,7 @@ export const send = async (state: ContactState, payload: FormData): Promise<Cont
return { success: true, message: "Thanks! You should hear from me soon." };
} catch (error) {
console.error("[/contact] fatal error:", error);
console.error("[server/resend] fatal error:", error);
return {
success: false,

85
lib/server/views.ts Normal file
View File

@ -0,0 +1,85 @@
import "server-only";
import { cache } from "react";
import { eq, inArray } from "drizzle-orm";
import { db } from "@/lib/db";
import { page } from "@/lib/db/schema";
export const incrementViews = async (slug: string): Promise<number> => {
try {
// First, try to find the existing record
const existingHit = await db.select().from(page).where(eq(page.slug, slug)).limit(1);
if (existingHit.length === 0) {
// Create new record if it doesn't exist
await db.insert(page).values({ slug, views: 1 }).execute();
return 1; // New record starts with 1 hit
} else {
// Calculate new hit count
const newViewCount = existingHit[0].views + 1;
// Update existing record by incrementing hits
await db.update(page).set({ views: newViewCount }).where(eq(page.slug, slug)).execute();
return newViewCount;
}
} catch (error) {
console.error("[view-counter] fatal error:", error);
throw new Error("Failed to increment views");
}
};
export const getViews: {
/**
* Retrieves the number of views for a given slug, or null if the slug does not exist
*/
(slug: string): Promise<number | null>;
/**
* Retrieves the numbers of views for an array of slugs
*/
(slug: string[]): Promise<Record<string, number | null>>;
/**
* Retrieves the numbers of views for ALL slugs
*/
(): Promise<Record<string, number>>;
} = cache(
async (
// eslint-disable-next-line @typescript-eslint/no-explicit-any
slug?: any
): // eslint-disable-next-line @typescript-eslint/no-explicit-any
Promise<any> => {
try {
// return one page
if (typeof slug === "string") {
const pages = await db.select().from(page).where(eq(page.slug, slug)).limit(1);
return pages[0].views;
}
// return multiple pages
if (Array.isArray(slug)) {
const pages = await db.select().from(page).where(inArray(page.slug, slug));
return pages.reduce(
(acc, page, index) => {
acc[slug[index]] = page.views;
return acc;
},
{} as Record<string, number | null>
);
}
// return ALL pages
const pages = await db.select().from(page);
return pages.reduce(
(acc, page) => {
acc[page.slug] = page.views;
return acc;
},
{} as Record<string, number>
);
} catch (error) {
console.error("[server/views] fatal error:", error);
throw new Error("Failed to get views");
}
}
);

View File

@ -20,9 +20,10 @@ const nextConfig = {
{
protocol: "https",
hostname: "ijyxfbpcm3itvdly.public.blob.vercel-storage.com",
port: "",
pathname: "/**",
search: "",
},
{
protocol: "https",
hostname: "avatars.githubusercontent.com",
},
],
},

View File

@ -13,6 +13,8 @@ tags:
image: ./covid19dashboards.png
---
import { GitHubIcon } from "@/components/icons";
export const OctocatLink = ({ repo }) => {
return (
<a
@ -22,14 +24,7 @@ export const OctocatLink = ({ repo }) => {
rel="noopener noreferrer"
className="mx-1.5"
>
<svg
xmlns="http://www.w3.org/2000/svg"
strokeWidth="0"
viewBox="0 0 24 24"
className="inline size-6 fill-current align-text-top"
>
<path d="M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12"></path>
</svg>
<GitHubIcon className="inline size-6 fill-current align-text-top" />
</a>
);
};

View File

@ -20,25 +20,32 @@
"dependencies": {
"@date-fns/tz": "^1.2.0",
"@date-fns/utc": "^2.1.0",
"@giscus/react": "^3.1.0",
"@marsidev/react-turnstile": "^1.1.0",
"@mdx-js/loader": "^3.1.0",
"@mdx-js/react": "^3.1.0",
"@neondatabase/serverless": "^1.0.0",
"@next/bundle-analyzer": "15.4.0-canary.26",
"@next/mdx": "15.4.0-canary.26",
"@octokit/graphql": "^8.2.2",
"@octokit/graphql-schema": "^15.26.0",
"@radix-ui/react-alert-dialog": "^1.1.13",
"@radix-ui/react-avatar": "^1.1.9",
"@radix-ui/react-dropdown-menu": "^2.1.14",
"@radix-ui/react-label": "^2.1.6",
"@radix-ui/react-popover": "^1.1.13",
"@radix-ui/react-separator": "^1.1.6",
"@radix-ui/react-slot": "^1.2.2",
"@radix-ui/react-toast": "^1.2.13",
"@radix-ui/react-tooltip": "^1.2.6",
"@t3-oss/env-nextjs": "^0.13.4",
"@vercel/analytics": "^1.5.0",
"@vercel/kv": "^3.0.0",
"better-auth": "^1.2.7",
"cheerio": "^1.0.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"copy-to-clipboard": "^3.3.3",
"date-fns": "^4.1.0",
"drizzle-orm": "^0.43.1",
"fast-glob": "^3.3.3",
"feed": "^4.2.2",
"geist": "^1.4.2",
@ -50,11 +57,13 @@
"react-countup": "^6.5.3",
"react-dom": "19.1.0",
"react-lite-youtube-embed": "^2.5.1",
"react-markdown": "^10.1.0",
"react-schemaorg": "^2.0.0",
"react-timeago": "^8.2.0",
"react-to-text": "^2.0.1",
"react-tweet": "^3.2.2",
"react-use": "^17.6.0",
"rehype-external-links": "^3.0.0",
"rehype-mdx-code-props": "^3.0.1",
"rehype-mdx-import-media": "^1.2.0",
"rehype-sanitize": "^6.0.0",
@ -73,6 +82,7 @@
"resend": "^4.5.1",
"server-only": "0.0.1",
"shiki": "^3.4.0",
"sonner": "^2.0.3",
"tailwind-merge": "^3.2.0",
"tailwindcss": "^4.1.5",
"unified": "^11.0.5",
@ -89,10 +99,13 @@
"@types/react-dom": "19.1.3",
"babel-plugin-react-compiler": "19.0.0-beta-af1b7da-20250417",
"cross-env": "^7.0.3",
"dotenv": "^16.5.0",
"drizzle-kit": "^0.31.1",
"eslint": "^9.26.0",
"eslint-config-next": "15.4.0-canary.26",
"eslint-config-prettier": "^10.1.3",
"eslint-plugin-css-modules": "^2.12.0",
"eslint-plugin-drizzle": "^0.2.3",
"eslint-plugin-import": "^2.31.0",
"eslint-plugin-jsx-a11y": "^6.10.2",
"eslint-plugin-mdx": "^3.4.1",
@ -130,6 +143,18 @@
"react": "^19",
"react-dom": "^19"
}
}
},
"ignoredOptionalDependencies": [
"prisma",
"@prisma/client"
],
"ignoredBuiltDependencies": [
"unrs-resolver"
],
"onlyBuiltDependencies": [
"@tailwindcss/oxide",
"esbuild",
"sharp"
]
}
}

1601
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@ -31,8 +31,9 @@
- Next.js
- Vercel
- Tailwind CSS
- Upstash Redis
- Giscus
- Neon Postgres
- Drizzle ORM
- Better Auth
- Resend
- ...and more: https://jarv.is/uses