feat(blog): migrate to nextJS

This commit is contained in:
Kim, Jimin 2023-07-28 15:43:29 +09:00
parent 62b34c9c48
commit badaa09950
Signed by: pomp
GPG key ID: CE1DDB8A4A765403
38 changed files with 2226 additions and 445 deletions

View file

@ -1,41 +0,0 @@
import { useTitleTemplate } from "hoofd"
import { Route, Switch } from "wouter"
import Footer from "@/components/Footer"
import Header from "@/components/Header"
import Loading from "@/components/Loading"
import Home from "@/pages/Home"
import NotFound from "@/pages/NotFound"
import Page from "@/pages/Page"
function App() {
useTitleTemplate("pomp's blog | %s")
return (
<>
<Header />
<main className="mx-auto mb-8 mt-20 flex w-full max-w-screen-mobile grow flex-col items-center gap-8 px-4">
<Switch>
<Route path="/">
<Home />
</Route>
{/* <Route path="/search">
<Search />
</Route> */}
<Route path="/404">
<NotFound />
</Route>
<Route path="/loading">
<Loading />
</Route>
<Route>
<Page />
</Route>
</Switch>
</main>
<Footer />
</>
)
}
export default App

View file

@ -1,19 +1,17 @@
import { useTitle } from "hoofd"
"use client"
import { type ReactNode, useEffect, useState } from "react"
import PostCard from "@/components/PostCard"
import ShowMoreButton from "@/components/ShowMoreButton"
import contentMap from "@/contentMap"
import ShowMoreButton from "./ShowMoreButton"
const totalPosts = Object.keys(contentMap.posts).length
export default function Home() {
const [howMany, setHowMany] = useState(5)
const [postCards, setPostCards] = useState<ReactNode[]>([])
useTitle("Home")
useEffect(() => {
const postCards: ReactNode[] = []

View file

@ -4,7 +4,7 @@ import {
faListUl,
} from "@fortawesome/free-solid-svg-icons"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import { Link } from "wouter"
import Link from "next/link"
interface Props {
seriesHome: string
@ -20,7 +20,7 @@ export default function SeriesControlButtons({
return (
<div className="mb-5 flex justify-between">
{prevURL ? (
<Link to={prevURL}>
<Link href={prevURL}>
<button className="button">
<FontAwesomeIcon icon={faArrowLeft} />
</button>
@ -31,14 +31,14 @@ export default function SeriesControlButtons({
</button>
)}
<Link to={seriesHome}>
<Link href={seriesHome}>
<button className="button">
<FontAwesomeIcon icon={faListUl} />
</button>
</Link>
{nextURL ? (
<Link to={nextURL}>
<Link href={nextURL}>
<button className="button">
<FontAwesomeIcon icon={faArrowRight} />
</button>

View file

@ -1,3 +1,5 @@
"use client"
import "./Toc.scss"
import { faCaretDown, faCaretUp } from "@fortawesome/free-solid-svg-icons"
@ -10,8 +12,9 @@ interface Props {
}
export default function Toc({ data }: Props) {
const [isTocOpened, setIsTocOpened] = useState(
localStorage.getItem("isTocOpened") === "true"
const [isTocOpened, setIsTocOpened] = useState<boolean>(
typeof window !== "undefined" &&
localStorage.getItem("isTocOpened") === "true"
)
useEffect(() => {

View file

@ -2,27 +2,47 @@ import type { PageData } from "@developomp-site/content/src/types/types"
import contentMap from "@/contentMap"
import { Params } from "./page"
export enum PageType {
POST,
SERIES,
SERIES_HOME,
}
export async function fetchContent(content_id: string) {
export interface Data {
pageData: PageData
pageType: PageType
}
export async function getData(params: Params): Promise<Data> {
const contentID = `/${params.category}/${params.slug.join("/")}`
const content = await fetchContent(contentID)
const pageType = categorizePageType(contentID) || PageType.POST
const pageData = parsePageData(content, pageType, contentID)
return {
pageData,
pageType,
}
}
export async function fetchContent(contentID: string) {
try {
return await import(
`@developomp-site/content/dist/content${content_id}.json`
`@developomp-site/content/dist/content${contentID}.json`
)
} catch (err) {
return
}
}
export function categorizePageType(content_id: string): PageType | undefined {
if (content_id.startsWith("/post")) return PageType.POST
if (content_id.startsWith("/series")) {
export function categorizePageType(contentID: string): PageType | undefined {
if (contentID.startsWith("/post")) return PageType.POST
if (contentID.startsWith("/series")) {
// if the URL looks like /series/series-title (if the url has two slashes)
if ([...(content_id.match(/\//g) || [])].length == 2)
if ([...(contentID.match(/\//g) || [])].length == 2)
return PageType.SERIES_HOME
// if the URL looks like /series/series-title/post-title (if the url does not have 2 slashes)

View file

@ -1,61 +1,66 @@
import "./Page.scss"
import type { PageData } from "@developomp-site/content/src/types/types"
import { useMeta, useTitle } from "hoofd"
import { useEffect, useState } from "react"
import { useLocation } from "wouter"
import { type Metadata } from "next"
import { type ParsedUrlQuery } from "querystring"
import NotFound, { metadata as notFoundMetadata } from "@/app/not-found"
import Card from "@/components/Card"
import Loading from "@/components/Loading"
import PostCard from "@/components/PostCard"
import Tag from "@/components/Tag"
import TagList from "@/components/TagList"
import contentMap from "@/contentMap"
import NotFound from "../NotFound"
import {
categorizePageType,
fetchContent,
PageType,
parsePageData,
} from "./helper"
import { getData, PageType } from "./helper"
import Meta from "./Meta"
import SeriesControlButtons from "./SeriesControlButtons"
import Toc from "./Toc"
export default function Page() {
const [location] = useLocation()
const [pageData, setPageData] = useState<PageData | undefined>(undefined)
const [pageType, setPageType] = useState<PageType>(PageType.POST)
const [isLoading, setLoading] = useState(true)
export interface Params extends ParsedUrlQuery {
category: "posts" | "series"
slug: string[]
}
useTitle(pageData?.title || "Loading")
useMeta({ property: "og:title", content: pageData?.title })
interface Props {
params: Params
}
useEffect(() => {
setPageData(undefined)
setLoading(true)
export async function generateStaticParams(): Promise<Params[]> {
return Object.keys(contentMap.posts).map((key) => {
const contentID = key.replace(/\/$/, "") // remove trailing slash
const parts = contentID
.split("/") // /a/b/c/ => ['', 'a', 'b', 'c', '']
.filter((x) => x) // ['', 'a', 'b', 'c', ''] => ['a', 'b', 'c']
const content_id = location.replace(/\/$/, "") // remove trailing slash
const category = parts[0]
if (category !== "posts" && category !== "series")
throw "Invalid Page Type"
fetchContent(content_id).then((fetched_content) => {
const pageType = categorizePageType(content_id)
const slug = parts.slice(1) // ['a', 'b', 'c'] => ['b', 'c']
// stop loading without setting pageData so 404 page will display
if (!fetched_content || pageType === undefined) {
setLoading(false)
return
}
return { category, slug }
})
}
setPageData(parsePageData(fetched_content, pageType, content_id))
setPageType(pageType)
setLoading(false)
})
}, [location])
export async function generateMetadata({ params }: Props): Promise<Metadata> {
if (params.category != "posts" && params.category != "series")
return notFoundMetadata
if (isLoading) return <Loading />
const { pageData } = await getData(params)
if (!pageData) return <NotFound />
return {
metadataBase: new URL("https://blog.developomp.com"),
title: pageData.title,
openGraph: {
title: pageData.title,
},
}
}
export default async function Page({ params }: Props) {
if (params.category != "posts" && params.category != "series")
return <NotFound />
const { pageData, pageType } = await getData(params)
return (
<>

View file

@ -0,0 +1,84 @@
import "@fortawesome/fontawesome-svg-core/styles.css"
import "@fontsource/noto-sans-kr/400.css"
import "@fontsource/noto-sans-kr/700.css"
import "@fontsource/source-code-pro"
import "katex/dist/katex.min.css"
import "./globals.css"
import "../styles/global.scss"
import "../styles/anchor.scss"
import "../styles/blockQuote.scss"
import "../styles/button.scss"
import "../styles/callout.scss"
import "../styles/checkbox.scss"
import "../styles/code.scss"
import "../styles/colorChip.scss"
import "../styles/heading.scss"
import "../styles/hr.scss"
import "../styles/img.scss"
import "../styles/katex.scss"
import "../styles/kbd.scss"
import "../styles/list.scss"
import "../styles/mark.scss"
import "../styles/scrollbar.scss"
import "../styles/subSup.scss"
import "../styles/table.scss"
import { type Metadata } from "next"
import Image from "next/image"
import Footer from "@/components/Footer"
import Header from "@/components/Header"
export const metadata: Metadata = {
metadataBase: new URL("https://blog.developomp.com"),
title: {
template: "pomp's blog | %s",
default: "",
},
description: "developomp's Blog",
openGraph: {
title: "pomp's blog",
siteName: "developomp's Blog",
description: "developomp's Blog",
type: "website",
url: "https://blog.developomp.com",
images: "https://blog.developomp.com/favicon.svg",
},
}
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en" className="dark">
<head>
<link
rel="shortcut icon"
type="image/svg+xml"
href="favicon.svg"
/>
<meta name="theme-color" content="#000000" />
</head>
<body className="overflow-x-hidden overflow-y-scroll">
<noscript>
<figure>
<Image src="/img/nojs.avif" alt="No javascript?" />
<figcaption>
Image compressed down to 4.5kB because you probably
have potato internet :D
</figcaption>
</figure>
</noscript>
<Header />
<main className="mx-auto mb-8 mt-20 flex w-full max-w-screen-mobile grow flex-col items-center gap-8 px-4">
{children}
</main>
<Footer />
</body>
</html>
)
}

View file

@ -1,11 +1,16 @@
import { useMeta, useTitle } from "hoofd"
import { type Metadata } from "next"
import Card from "@/components/Card"
export default function NotFound() {
useTitle("404")
useMeta({ property: "og:title", content: "pomp's blog | Page Not Found" })
export const metadata: Metadata = {
metadataBase: new URL("https://blog.developomp.com"),
title: "404",
openGraph: {
title: "pomp's blog | Page Not Found",
},
}
export default function NotFound() {
return (
<Card className="items-center gap-4">
<h1 className="text-7xl">404</h1>

View file

@ -0,0 +1,12 @@
import { Metadata } from "next"
import Home from "./Home"
export const metadata: Metadata = {
metadataBase: new URL("https://blog.developomp.com"),
title: "pomp's blog | Home",
}
export default function Page() {
return <Home />
}

View file

@ -1,4 +1,5 @@
import { Link } from "wouter"
import Image from "next/image"
import Link from "next/link"
import ReadProgress from "./ReadProgress"
import ThemeToggleButton from "./ThemeToggleButton"
@ -7,18 +8,17 @@ export default function Header() {
return (
<header className="fixed z-50 h-16 w-full bg-light-ui shadow-lg dark:bg-dark-ui">
<div className="mx-auto flex h-[60px] max-w-screen-desktop items-center justify-between">
<Link to="/">
<a
aria-label="homepage"
className="ml-4 h-10 cursor-pointer"
>
<img
width="40px"
height="40px"
src="/favicon.svg"
alt="logo"
/>
</a>
<Link
aria-label="homepage"
href="/"
className="ml-4 h-10 cursor-pointer"
>
<Image
src="/favicon.svg"
alt="logo"
width={40}
height={40}
/>
</Link>
<div className="flex h-full">
<ThemeToggleButton />

View file

@ -1,19 +1,21 @@
import { useCallback, useEffect, useState } from "react"
import { useLocation } from "wouter"
"use client"
const st = "scrollTop"
const sh = "scrollHeight"
const h = document.documentElement
const b = document.body
import { usePathname } from "next/navigation"
import { useCallback, useEffect, useState } from "react"
// https://stackoverflow.com/a/8028584/12979111
function calculateScrollPercent() {
const st = "scrollTop"
const sh = "scrollHeight"
const h = document.documentElement
const b = document.body
return ((h[st] || b[st]) / ((h[sh] || b[sh]) - h.clientHeight)) * 100
}
export default function ReadProgress() {
const [scroll, setScroll] = useState(0)
const [location] = useLocation()
const pathname = usePathname()
const scrollHandler = useCallback(() => {
setScroll(calculateScrollPercent())
}, [])
@ -43,7 +45,7 @@ export default function ReadProgress() {
setTimeout(() => {
scrollHandler()
}, 100)
}, [location])
}, [pathname])
return (
<div className="h-1 bg-light-scroll-progress-bg dark:bg-dark-scroll-progress-bg">

View file

@ -1,13 +1,15 @@
import { faSearch } from "@fortawesome/free-solid-svg-icons"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import { Link } from "wouter"
import Link from "next/link"
export default function SearchButton() {
return (
<Link to="/search" aria-label="go to search page">
<a className="flex w-20 cursor-pointer items-center justify-center text-light-text-default hover:bg-light-ui-hover hover:text-light-text-default dark:text-dark-text-default dark:hover:bg-dark-ui-hover dark:hover:text-dark-text-default">
<FontAwesomeIcon icon={faSearch} />
</a>
<Link
href="/search"
aria-label="go to search page"
className="flex w-20 cursor-pointer items-center justify-center text-light-text-default hover:bg-light-ui-hover hover:text-light-text-default dark:text-dark-text-default dark:hover:bg-dark-ui-hover dark:hover:text-dark-text-default"
>
<FontAwesomeIcon icon={faSearch} />
</Link>
)
}

View file

@ -1,3 +1,5 @@
"use client"
import { faMoon, faSun } from "@fortawesome/free-solid-svg-icons"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
@ -15,7 +17,7 @@ export default function ThemeToggleButton() {
aria-label="theme toggle"
>
{theme === Theme.Dark ? (
<FontAwesomeIcon icon={faMoon} />
<FontAwesomeIcon icon={faMoon} size={"1x"} />
) : (
<FontAwesomeIcon icon={faSun} />
)}

View file

@ -5,7 +5,7 @@ import {
faHourglass,
} from "@fortawesome/free-solid-svg-icons"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import { Link } from "wouter"
import Link from "next/link"
import Card from "@/components/Card"
import Tag from "@/components/Tag"
@ -25,42 +25,40 @@ export default function PostCard({ postData, className }: Props) {
return (
<Link href={content_id} className={`${className} w-full`}>
<a className="w-full">
<Card className="w-full cursor-pointer fill-light-text-gray text-light-text-gray hover:shadow-glow dark:fill-dark-text-gray dark:text-dark-text-gray">
<h2 className="mb-8 text-3xl">
{title}
{/* show "(series)" for urls that matches regex "/series/<series-title>" */}
{/\/series\/[^/]*$/.test(content_id) && " (series)"}
</h2>
<small>
<TagList>
{tags &&
tags.map((tag) => (
<Tag key={title + tag} text={tag} />
))}
</TagList>
<hr />
<div className="flex flex-wrap items-center gap-x-4">
<div className="flex items-center gap-2 whitespace-nowrap">
<FontAwesomeIcon icon={faCalendar} />
{date || "Unknown date"}
</div>
<div className="flex items-center gap-2 whitespace-nowrap">
<FontAwesomeIcon icon={faBook} />
{readTime
? readTime + " read"
: "unknown read time"}
</div>
<div className="flex items-center gap-2 whitespace-nowrap">
<FontAwesomeIcon icon={faHourglass} />
{typeof wordCount === "number"
? wordCount + " words"
: "unknown length"}
</div>
<Card className="w-full cursor-pointer fill-light-text-gray text-light-text-gray hover:shadow-glow dark:fill-dark-text-gray dark:text-dark-text-gray">
<h2 className="mb-8 text-3xl">
{title}
{/* show "(series)" for urls that matches regex "/series/<series-title>" */}
{/\/series\/[^/]*$/.test(content_id) && " (series)"}
</h2>
<small>
<TagList>
{tags &&
tags.map((tag) => (
<Tag key={title + tag} text={tag} />
))}
</TagList>
<hr />
<div className="flex flex-wrap items-center gap-x-4">
<div className="flex items-center gap-2 whitespace-nowrap">
<FontAwesomeIcon icon={faCalendar} />
{date || "Unknown date"}
</div>
</small>
</Card>
</a>
<div className="flex items-center gap-2 whitespace-nowrap">
<FontAwesomeIcon icon={faBook} />
{readTime
? readTime + " read"
: "unknown read time"}
</div>
<div className="flex items-center gap-2 whitespace-nowrap">
<FontAwesomeIcon icon={faHourglass} />
{typeof wordCount === "number"
? wordCount + " words"
: "unknown length"}
</div>
</div>
</small>
</Card>
</Link>
)
}

View file

@ -1,31 +0,0 @@
import "@fontsource/noto-sans-kr/400.css"
import "@fontsource/noto-sans-kr/700.css"
import "@fontsource/source-code-pro"
import "katex/dist/katex.min.css"
import "./index.css"
import "./styles/anchor.scss"
import "./styles/blockQuote.scss"
import "./styles/button.scss"
import "./styles/callout.scss"
import "./styles/checkbox.scss"
import "./styles/code.scss"
import "./styles/colorChip.scss"
import "./styles/global.scss"
import "./styles/heading.scss"
import "./styles/hr.scss"
import "./styles/img.scss"
import "./styles/katex.scss"
import "./styles/kbd.scss"
import "./styles/list.scss"
import "./styles/mark.scss"
import "./styles/scrollbar.scss"
import "./styles/subSup.scss"
import "./styles/table.scss"
import ReactDOM from "react-dom/client"
import App from "@/App.tsx"
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
<App />
)

View file

@ -1,3 +0,0 @@
import Home from "./Home"
export default Home

View file

@ -1,3 +0,0 @@
import NotFound from "./NotFound"
export default NotFound

View file

@ -1,3 +0,0 @@
import Page from "./Page"
export default Page

View file

@ -1,6 +1,5 @@
html,
body,
#root {
body {
/* style */
@apply flex flex-col;

View file

@ -1,3 +1,5 @@
"use client"
import { create } from "zustand"
const themeKey = "theme"
@ -15,6 +17,8 @@ export type ThemeState = {
* Reads site theme setting from local storage
*/
function getStoredThemeSetting(): Theme {
if (typeof window === "undefined") return Theme.Dark
const storedTheme = localStorage.getItem(themeKey)
// fix invalid values
@ -40,6 +44,8 @@ function setTheme(targetTheme: Theme) {
* Applies tailwind theme using classes based on current theme setting
*/
function applyTheme() {
if (typeof window === "undefined") return
if (getStoredThemeSetting() === Theme.Dark) {
document.documentElement.classList.add("dark")
} else {
@ -48,12 +54,14 @@ function applyTheme() {
}
export const useTheme = create<ThemeState>()((set) => {
applyTheme()
addEventListener("storage", () => {
setTheme(getStoredThemeSetting())
if (typeof window !== "undefined") {
applyTheme()
})
addEventListener("storage", () => {
setTheme(getStoredThemeSetting())
applyTheme()
})
}
return {
theme: getStoredThemeSetting(),

View file

@ -1 +0,0 @@
/// <reference types="vite/client" />