diff --git a/AGENTS.md b/AGENTS.md index 71f393f..7f7cda4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -74,7 +74,10 @@ lib/ className={cn("base-classes", conditional && "extra-classes", className)} ``` - **Responsive**: Mobile-first with `sm:`, `md:`, `lg:` prefixes -- **Dark mode**: Always active (`.dark` class on body) +- **Early-web theme**: white page, Times New Roman (`font-serif`), classic blue/purple underlined links (set + globally in `globals.css`), thin `#a2a9b1` rules and boxes. Every page renders inside `` + (`components/retro-page.tsx`), which adds the link bar, footer, and the animated ASCII background + (`components/ascii-background.tsx`). Use `` for page titles. ### Animation Patterns @@ -125,12 +128,10 @@ export function Projects() { ## Common Gotchas 1. **Client components**: Components using `motion`, hooks, or event handlers need `"use client"` -2. **Font loading**: Geist Sans and Geist Pixel Square are subset into `lib/fonts/` by `scripts/subset-fonts.py` - (run by hand with `uv run`, output committed) and applied as CSS variables on `` via `fontVariables`. - Don't edit `lib/fonts/index.ts`; rerun the script after content adds new characters (`--check` tells you), - after upgrading `geist`, or when using a new weight, italic face, OpenType feature, or Pixel variant. +2. **Fonts**: none are loaded; the site uses system Times New Roman / Courier New on purpose. 3. **Anchor navigation**: Section IDs use lowercase (`id={title.toLowerCase()}`) -4. **Dark mode only**: Site is permanently in dark mode +4. **Home page**: name, then the full post list (`components/post-index.tsx`). No about or projects + sections; that data in `lib/site-content.ts` still feeds the Markdown mirrors (`lib/markdown-pages.ts`). 5. **No API routes**: Static portfolio site --- diff --git a/CHANGELOG.md b/CHANGELOG.md index a5863ef..1e99d95 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,26 @@ All notable changes to this project are documented here. The format is based on ## [Unreleased] +### Changed + +- **Early-web redesign**: every page is a plain white document in Times New + Roman with classic blue/purple underlined links, a `[ GitHub | Twitter ]` + link bar, encyclopedia-style titles, text straight on the page (no card), a + numbered "Contents" box and a "Categories" box on posts, and light code + blocks. Behind it runs an animated, dithered ASCII noise background (black on + white, frozen for reduced motion) that fades almost out behind the text + column. (`components/retro-page.tsx`, `components/ascii-background.tsx`) +- **Home page goes straight to the posts**: the intro paragraph, skills, about, + and projects sections are gone; the page is the name and the full post + list. The link bar only has GitHub and Twitter. + +### Removed + +- The dithering shader backgrounds, the green hover-band blog lists, and the + scroll-spy table-of-contents sidebar. +- Geist fonts and `scripts/subset-fonts.py` (no web fonts are loaded now), and + the unused dark card components. + ### Added - **Markdown page mirrors**: public pages now expose `text/markdown` versions diff --git a/app/(frontend)/blog/[slug]/page.tsx b/app/(frontend)/blog/[slug]/page.tsx index edaad5a..f590d0a 100644 --- a/app/(frontend)/blog/[slug]/page.tsx +++ b/app/(frontend)/blog/[slug]/page.tsx @@ -1,7 +1,6 @@ -import "highlight.js/styles/github-dark.css"; +import "highlight.js/styles/github.css"; import hljs from "highlight.js"; import Link from "next/link"; -import { ArcadeChevronLeft, ArcadeUTurnLeft } from "@/components/icons/arcade-icons"; import Image from "next/image"; import { notFound } from "next/navigation"; import type { Metadata } from "next"; @@ -11,7 +10,8 @@ import { RichText } from "@payloadcms/richtext-lexical/react"; import type { JSXConvertersFunction } from "@payloadcms/richtext-lexical/react"; import type { Media as MediaType, Tag } from "@/payload-types"; import { extractHeadings } from "@/lib/blog-toc"; -import { TocSidebar } from "@/components/blog/toc-sidebar"; +import { ContentsBox } from "@/components/contents-box"; +import { RetroPage, RetroTitle } from "@/components/retro-page"; export const dynamic = "force-dynamic"; @@ -88,7 +88,7 @@ export default async function BlogPostPage({ params }: Props) { ? hljs.highlight(code, { language, ignoreIllegals: true }).value : hljs.highlightAuto(code).value; return ( -
+            
               
             
); @@ -97,82 +97,63 @@ export default async function BlogPostPage({ params }: Props) { }; }; - return ( -
- - - {/* On xl+ the "see all" link lives at the top of the TOC sidebar. */} -
- - - see all - -
+ const published = new Date(post.publishedAt).toLocaleDateString("en-GB", { + year: "numeric", + month: "long", + day: "numeric", + }); + return ( +
-
-

{post.title}

- -
+ - {new Date(post.publishedAt).toLocaleDateString("en-US", { - year: "numeric", - month: "long", - day: "numeric", - })} + {published} + {post.readTime && ( + <> · {/^\d+$/.test(post.readTime) ? `${post.readTime} min read` : post.readTime} + )} - {post.readTime && ( - <> - · - {post.readTime} - - )} -
- - {tags.length > 0 && ( -
- {tags.map((tag) => ( - - {tag.name} - - ))} -
- )} -
+ } + > + {post.title} + {heroImage?.url && ( -
+
{heroImage.alt} -
+ )} -
+ + +
{/* eslint-disable-next-line @typescript-eslint/no-explicit-any */}
-
-
- - - Back to all posts - -
-
+ {tags.length > 0 && ( +
+ Categories:{" "} + {tags.map((tag, i) => ( + + {i > 0 && " | "} + {tag.name} + + ))} +
+ )} + +

+ ← Back to all posts +

+ + ); } diff --git a/app/(frontend)/blog/page.tsx b/app/(frontend)/blog/page.tsx index d4af44c..b2b1a1b 100644 --- a/app/(frontend)/blog/page.tsx +++ b/app/(frontend)/blog/page.tsx @@ -1,12 +1,9 @@ -import Link from "next/link"; -import { ArcadeChevronLeft } from "@/components/icons/arcade-icons"; -import type { Metadata } from "next"; -import { getPayload } from "payload"; -import config from "@payload-config"; -import { BlogList, type BlogListItem } from "@/components/blog-list"; - export const dynamic = "force-dynamic"; +import type { Metadata } from "next"; +import { PostIndex } from "@/components/post-index"; +import { RetroPage, RetroTitle } from "@/components/retro-page"; + export const metadata: Metadata = { title: "Blog | Khushal Bhardwaj", description: "Blog posts by Khushal Bhardwaj", @@ -17,58 +14,11 @@ export const metadata: Metadata = { }, }; -export default async function BlogPage() { - const payload = await getPayload({ config }); - const { docs: posts } = await payload.find({ - collection: "posts", - sort: "-publishedAt", - limit: 50, - depth: 1, - }); - - const items: BlogListItem[] = posts.map((post) => { - const hero = - post.heroImage && typeof post.heroImage === "object" - ? post.heroImage - : null; - const heroUrl = hero?.sizes?.card?.url ?? hero?.url ?? null; - return { - id: post.id, - title: post.title, - slug: post.slug, - excerpt: post.excerpt, - publishedAt: post.publishedAt, - readTime: post.readTime, - heroImage: heroUrl - ? { - url: heroUrl, - alt: hero?.alt ?? post.title, - width: hero?.sizes?.card?.width ?? hero?.width, - height: hero?.sizes?.card?.height ?? hero?.height, - } - : null, - }; - }); - +export default function BlogPage() { return ( -
-
- - - Back - -
- -

Blog

- - {items.length === 0 ? ( -

No posts yet.

- ) : ( - - )} -
+ + All posts + + ); } diff --git a/app/(frontend)/globals.css b/app/(frontend)/globals.css index 01d65fb..1fffd3b 100644 --- a/app/(frontend)/globals.css +++ b/app/(frontend)/globals.css @@ -4,7 +4,6 @@ @layer base { * { - @apply border-neutral-800; user-select: none; -webkit-user-select: none; -moz-user-select: none; @@ -12,30 +11,27 @@ } body { - @apply bg-black text-white antialiased; - font-family: var(--font-geist-sans), system-ui, sans-serif; - text-transform: lowercase; + @apply bg-white font-serif text-[17px] leading-relaxed text-[#202122]; } - ::-webkit-scrollbar { - width: 6px; - height: 6px; + /* Classic browser link colors. */ + a { + color: #0000ee; + text-decoration: underline; + text-underline-offset: 2px; } - - ::-webkit-scrollbar-track { - @apply bg-black; + a:visited { + color: #551a8b; } - - ::-webkit-scrollbar-thumb { - @apply bg-neutral-700 rounded-full; + a:hover { + text-decoration-thickness: 2px; } - - ::-webkit-scrollbar-thumb:hover { - @apply bg-neutral-600; + a:active { + color: #ee0000; } ::selection { - @apply bg-white/20 text-white; + @apply bg-[#0000ee] text-white; } } diff --git a/app/(frontend)/layout.tsx b/app/(frontend)/layout.tsx index a4e7064..fd73ec5 100644 --- a/app/(frontend)/layout.tsx +++ b/app/(frontend)/layout.tsx @@ -3,7 +3,6 @@ import type { Metadata, Viewport } from "next"; import Script from "next/script"; import { Analytics } from "@vercel/analytics/next"; import { SpeedInsights } from "@vercel/speed-insights/next"; -import { fontVariables } from "@/lib/fonts"; import { SITE_URL } from "@/lib/site-content"; export const metadata: Metadata = { @@ -18,8 +17,8 @@ export const metadata: Metadata = { export const viewport: Viewport = { themeColor: [ - { media: "(prefers-color-scheme: light)", color: "#000000" }, - { media: "(prefers-color-scheme: dark)", color: "#000000" }, + { media: "(prefers-color-scheme: light)", color: "#ffffff" }, + { media: "(prefers-color-scheme: dark)", color: "#ffffff" }, ], }; @@ -29,8 +28,8 @@ export default function RootLayout({ children: React.ReactNode; }) { return ( - - + + {children} diff --git a/app/(frontend)/not-found.tsx b/app/(frontend)/not-found.tsx index a9c24bd..2e26605 100644 --- a/app/(frontend)/not-found.tsx +++ b/app/(frontend)/not-found.tsx @@ -1,18 +1,14 @@ import Link from "next/link"; +import { RetroPage, RetroTitle } from "@/components/retro-page"; export default function NotFound() { return ( -
-
-

404

-

This page doesn't exist.

- - Go home - -
-
+ + Page not found +

+ There is currently no page at this address. Try the home page or the{" "} + list of all posts. +

+
); } diff --git a/app/(frontend)/page.tsx b/app/(frontend)/page.tsx index bf8a890..2d49829 100644 --- a/app/(frontend)/page.tsx +++ b/app/(frontend)/page.tsx @@ -1,15 +1,9 @@ export const dynamic = "force-dynamic"; import type { Metadata } from "next"; -import { About } from "@/components/about"; -import { Blogs } from "@/components/blogs-server"; -import { Footer } from "@/components/footer"; -import { Greeting } from "@/components/greeting"; -import { Links } from "@/components/links"; -import { Projects } from "@/components/projects"; -import { Stack } from "@/components/stack"; -import { HeroShader } from "@/components/hero-shader"; -import Link from "next/link"; +import { PostIndex } from "@/components/post-index"; +import { RetroPage, RetroTitle } from "@/components/retro-page"; +import { profile } from "@/lib/site-content"; export const metadata: Metadata = { title: "Khushal Bhardwaj | Full Stack Web Developer", @@ -24,37 +18,10 @@ export const metadata: Metadata = { export default function Home() { return ( -
- {/* Navigation - top right */} -
- -
+ + {profile.name} - {/* Hero - vertically centered with dithering shader background */} -
- -
- - - -
- - Say Hello - -
-
-
- - {/* Content sections */} -
- - - -
-
-
+ + ); } diff --git a/components/about.tsx b/components/about.tsx deleted file mode 100644 index 320b857..0000000 --- a/components/about.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import { about, profile } from "@/lib/site-content"; - -export function About() { - return ( -
-

About

-
-

- {about.beforeName} - {profile.name} - {about.afterName} -

-

{about.writing}

-
-
- ); -} diff --git a/components/ascii-background.tsx b/components/ascii-background.tsx new file mode 100644 index 0000000..11ecc6a --- /dev/null +++ b/components/ascii-background.tsx @@ -0,0 +1,123 @@ +"use client"; + +import { useEffect, useRef } from "react"; + +// Density ramp, light to dark. Mid tones get swapped for random "gibberish" +// glyphs so the field reads as noise rather than a clean gradient. +const RAMP = " .·:-~=+*x#%@"; +const GIBBERISH = "abcdefghijklmnopqrstuvwxyz0123456789{}[]<>/\\|?!;$&^"; + +// 4x4 Bayer matrix, normalised to [0, 1). Ordered dithering between ramp steps. +const BAYER = [0, 8, 2, 10, 12, 4, 14, 6, 3, 11, 1, 9, 15, 7, 13, 5].map((v) => v / 16); + +const CELL_W = 8; +const CELL_H = 13; +const FPS = 12; + +function hash(x: number, y: number, t: number) { + let h = (x * 374761393 + y * 668265263 + t * 2147483647) | 0; + h = Math.imul(h ^ (h >>> 13), 1274126177); + return ((h ^ (h >>> 16)) >>> 0) / 4294967296; +} + +/** Abstract, slowly drifting field in [0, 1]: a few domain-warped sine layers. */ +function field(x: number, y: number, t: number) { + const wx = x + 0.9 * Math.sin(y * 0.7 + t * 0.21); + const wy = y + 0.9 * Math.cos(x * 0.6 - t * 0.17); + const v = + Math.sin(wx * 1.3 + t * 0.3) * 0.45 + + Math.sin(wy * 1.7 - t * 0.23) * 0.35 + + Math.sin((wx + wy) * 0.9 + t * 0.11) * 0.35 + + Math.sin(Math.hypot(wx - 3, wy - 2) * 1.6 - t * 0.4) * 0.3; + return Math.min(1, Math.max(0, v * 0.42 + 0.42)); +} + +// Fades the field almost out behind the centered text column (max-w-3xl, +// 768px) so the content stays readable, and back to full strength outside it. +const COLUMN_MASK = + "linear-gradient(to right, #000 calc(50% - 470px), rgb(0 0 0 / 0.06) calc(50% - 400px), rgb(0 0 0 / 0.06) calc(50% + 400px), #000 calc(50% + 470px))"; + +/** + * Full-page canvas of dithered ASCII noise, black on white. Purely decorative: + * hidden from assistive tech, frozen on one frame for reduced motion, and + * paused while the tab is hidden. + */ +export function AsciiBackground() { + const canvasRef = useRef(null); + + useEffect(() => { + const canvas = canvasRef.current; + const ctx = canvas?.getContext("2d"); + if (!canvas || !ctx) return; + + const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches; + let cols = 0; + let rows = 0; + let raf = 0; + let last = 0; + + const resize = () => { + const dpr = Math.min(window.devicePixelRatio || 1, 2); + const w = window.innerWidth; + const h = window.innerHeight; + canvas.width = Math.floor(w * dpr); + canvas.height = Math.floor(h * dpr); + ctx.setTransform(dpr, 0, 0, dpr, 0, 0); + ctx.font = `11px ui-monospace, "Courier New", monospace`; + ctx.textBaseline = "top"; + ctx.fillStyle = "#000"; + cols = Math.ceil(w / CELL_W); + rows = Math.ceil(h / CELL_H); + }; + + const draw = (ms: number) => { + const t = ms / 1000; + // Glyph choices reshuffle a couple of times a second, not every frame. + const tick = Math.floor(t * 2); + ctx.clearRect(0, 0, canvas.width, canvas.height); + const steps = RAMP.length - 1; + for (let y = 0; y < rows; y++) { + for (let x = 0; x < cols; x++) { + const v = field(x * 0.045, y * 0.07, t); + const level = Math.min(steps, Math.floor(v * steps + BAYER[(y & 3) * 4 + (x & 3)])); + if (level === 0) continue; + const ch = + level > 3 && level < steps - 1 && hash(x, y, tick) < 0.35 + ? GIBBERISH[Math.floor(hash(y, x, tick) * GIBBERISH.length)] + : RAMP[level]; + ctx.fillText(ch, x * CELL_W, y * CELL_H); + } + } + }; + + const loop = (ms: number) => { + raf = requestAnimationFrame(loop); + if (document.hidden || ms - last < 1000 / FPS) return; + last = ms; + draw(ms); + }; + + resize(); + draw(0); + if (!reduce) raf = requestAnimationFrame(loop); + + const onResize = () => { + resize(); + draw(performance.now()); + }; + window.addEventListener("resize", onResize); + return () => { + cancelAnimationFrame(raf); + window.removeEventListener("resize", onResize); + }; + }, []); + + return ( + + ); +} diff --git a/components/blog-list.tsx b/components/blog-list.tsx deleted file mode 100644 index 77073bf..0000000 --- a/components/blog-list.tsx +++ /dev/null @@ -1,273 +0,0 @@ -"use client"; - -import Link from "next/link"; -import Image from "next/image"; -import { useEffect, useRef, useState, type RefObject } from "react"; -import { useRouter } from "next/navigation"; -import { motion, useSpring, useTransform, type MotionValue } from "framer-motion"; -import { DitheringShader } from "@/components/ui/dithering-shader"; - -export type BlogListItem = { - id: string | number; - title: string; - slug: string; - excerpt?: string | null; - publishedAt: string; - readTime?: string | null; - heroImage?: { - url: string; - alt: string; - width?: number | null; - height?: number | null; - } | null; -}; - -function formatDate(value: string) { - return new Date(value).toLocaleDateString("en-US", { - year: "numeric", - month: "short", - day: "numeric", - }); -} - -const ACCENT = { r: 34, g: 197, b: 94 }; // #22c55e -const SPREAD = 2.6; // how many rows the tint band reaches -const MAX_ALPHA = 0.95; - -const clamp01 = (n: number) => Math.min(1, Math.max(0, n)); - -function Row({ - post, - index, - pos, - strength, - spread, - dirRef, - onActivate, -}: { - post: BlogListItem; - index: number; - pos: MotionValue; - strength: MotionValue; - spread: MotionValue; - dirRef: RefObject; - onActivate: (i: number) => void; -}) { - // signed = index - pos: negative means this row is above current, positive means below. - // Going down (dir=+1): tail trails upward → tint rows where signed < 0. - // Going up (dir=-1): tail trails downward → tint rows where signed > 0. - const tailActive = (signed: number, dir: number) => - dir === 0 ? false : dir > 0 ? signed < 0 : signed > 0; - - const background = useTransform([pos, strength, spread], ([p, st, sp]: number[]) => { - const signed = index - p; - const dist = Math.abs(signed); - const isHovered = dist < 0.5; - const isTail = !isHovered && tailActive(signed, dirRef.current ?? 0); - const s = isHovered ? st : isTail ? sp : 0; - const tint = clamp01(1 - dist / SPREAD); - const a = tint * tint * s * MAX_ALPHA; - return `rgba(${ACCENT.r}, ${ACCENT.g}, ${ACCENT.b}, ${a})`; - }); - - const ink = useTransform([pos, strength, spread], ([p, st, sp]: number[]) => { - const signed = index - p; - const dist = Math.abs(signed); - const isHovered = dist < 0.5; - const isTail = !isHovered && tailActive(signed, dirRef.current ?? 0); - const s = isHovered ? st : isTail ? sp : 0; - const k = clamp01(1 - dist / 1.15) * s; - const v = Math.round(255 * (1 - k)); - return `rgb(${v}, ${v}, ${v})`; - }); - - const mutedInk = useTransform([pos, strength, spread], ([p, st, sp]: number[]) => { - const signed = index - p; - const dist = Math.abs(signed); - const isHovered = dist < 0.5; - const isTail = !isHovered && tailActive(signed, dirRef.current ?? 0); - const s = isHovered ? st : isTail ? sp : 0; - const k = clamp01(1 - dist / 1.15) * s; - const v = Math.round(115 * (1 - k)); - return `rgb(${v}, ${v}, ${v})`; - }); - - return ( -
  • - onActivate(index)} - onFocus={() => onActivate(index)} - > - - - {String(index + 1).padStart(2, "0")} - - - {post.title} - - - {formatDate(post.publishedAt)} - - - -
  • - ); -} - -export function BlogList({ posts }: { posts: BlogListItem[] }) { - const router = useRouter(); - const [active, setActive] = useState(0); - const [hovering, setHovering] = useState(false); - const [shaderSize, setShaderSize] = useState({ width: 600, height: 750 }); - const panelRef = useRef(null); - - // Spring-damped band: pos glides through in-between rows (the trailing - // sweep), strength fades the whole tint in/out on enter/leave. - const pos = useSpring(0, { stiffness: 220, damping: 26, mass: 0.9 }); - const strength = useSpring(0, { stiffness: 260, damping: 30 }); - - const idleTimer = useRef | null>(null); - const spread = useSpring(0, { stiffness: 260, damping: 30 }); - const prevRef = useRef(null); - const dirRef = useRef(0); - - const activate = (i: number) => { - if (prevRef.current !== null && i !== prevRef.current) { - dirRef.current = i > prevRef.current ? 1 : -1; - } - prevRef.current = i; - pos.set(i); - strength.set(1); - spread.set(1); - setActive(i); - setHovering(true); - if (idleTimer.current) clearTimeout(idleTimer.current); - idleTimer.current = setTimeout(() => spread.set(0), 400); - }; - - // Crazy prefetching: warm every route payload and hero image up front. - useEffect(() => { - posts.forEach((post) => { - router.prefetch(`/blog/${post.slug}`); - if (post.heroImage?.url) { - const img = new window.Image(); - img.src = post.heroImage.url; - } - }); - }, [posts, router]); - - useEffect(() => { - const el = panelRef.current; - if (!el) return; - const update = () => - setShaderSize({ width: el.clientWidth, height: el.clientHeight }); - update(); - const ro = new ResizeObserver(update); - ro.observe(el); - return () => ro.disconnect(); - }, []); - - return ( -
    - {/* Sticky preview panel — green dithering backdrop + hovered hero image */} -
    -
    -
    - -
    - - {posts.map((post, i) => { - const url = post.heroImage?.url; - if (!url) return null; - const show = hovering && i === active; - return ( -
    - {post.heroImage?.alt -
    -
    -
    - ); - })} - -
    -

    - {String(active + 1).padStart(2, "0")} /{" "} - {String(posts.length).padStart(2, "0")} -

    -

    - {posts[active]?.title} -

    -
    -
    -
    - - {/* The list */} -
      { - if (idleTimer.current) clearTimeout(idleTimer.current); - strength.set(0); - spread.set(0); - prevRef.current = null; - dirRef.current = 0; - setHovering(false); - }} - > - {posts.map((post, i) => ( - - ))} -
    -
    - ); -} diff --git a/components/blog/toc-sidebar.tsx b/components/blog/toc-sidebar.tsx deleted file mode 100644 index 3eed6e8..0000000 --- a/components/blog/toc-sidebar.tsx +++ /dev/null @@ -1,112 +0,0 @@ -"use client"; - -import Link from "next/link"; -import { ArcadeUTurnLeft } from "@/components/icons/arcade-icons"; -import { useEffect, useState } from "react"; -import { cn } from "@/lib/utils"; -import type { TocHeading } from "@/lib/blog-toc"; - -interface TocSidebarProps { - headings: TocHeading[]; -} - -export function TocSidebar({ headings }: TocSidebarProps) { - const showList = headings.length >= 2; - const [activeId, setActiveId] = useState(headings[0]?.id ?? ""); - - useEffect(() => { - if (!showList) return; - - const elements = headings - .map((h) => document.getElementById(h.id)) - .filter((el): el is HTMLElement => el !== null); - - if (elements.length === 0) return; - - // Track which headings are currently within the "reading zone" (the band - // just below the top of the viewport) and mark the topmost one active. - const visible = new Set(); - - const observer = new IntersectionObserver( - (entries) => { - for (const entry of entries) { - if (entry.isIntersecting) visible.add(entry.target.id); - else visible.delete(entry.target.id); - } - - // Pick the first heading (in document order) that is in view. - const firstVisible = headings.find((h) => visible.has(h.id)); - if (firstVisible) { - setActiveId(firstVisible.id); - } - }, - { - // Activate a heading once it crosses into the top ~25% of the viewport, - // and keep it active until the next one arrives. - rootMargin: "-10% 0px -75% 0px", - threshold: 0, - }, - ); - - elements.forEach((el) => observer.observe(el)); - return () => observer.disconnect(); - }, [headings, showList]); - - const handleClick = (e: React.MouseEvent, id: string) => { - e.preventDefault(); - const el = document.getElementById(id); - if (!el) return; - setActiveId(id); - el.scrollIntoView({ behavior: "smooth", block: "start" }); - history.replaceState(null, "", `#${id}`); - }; - - return ( - - ); -} diff --git a/components/blogs-server.tsx b/components/blogs-server.tsx deleted file mode 100644 index efb9ceb..0000000 --- a/components/blogs-server.tsx +++ /dev/null @@ -1,37 +0,0 @@ -import Link from "next/link"; -import { ArcadeArrowUpRight } from "@/components/icons/arcade-icons"; -import { getPayload } from "payload"; -import config from "@payload-config"; -import { BlogsList } from "@/components/blogs"; - -export async function Blogs() { - const payload = await getPayload({ config }); - const { docs: posts } = await payload.find({ - collection: "posts", - sort: "-publishedAt", - limit: 5, - }); - - if (posts.length === 0) return null; - - const items = posts.map((post) => ({ - id: post.id, - title: post.title, - slug: post.slug!, - publishedAt: post.publishedAt, - })); - - return ( -
    -

    Blog

    - - - View all posts - - -
    - ); -} diff --git a/components/blogs.tsx b/components/blogs.tsx deleted file mode 100644 index 3641749..0000000 --- a/components/blogs.tsx +++ /dev/null @@ -1,157 +0,0 @@ -"use client"; - -import Link from "next/link"; -import { useRef, useState, type RefObject } from "react"; -import { ArcadeArrowUpRight } from "@/components/icons/arcade-icons"; -import { motion, useSpring, useTransform, type MotionValue } from "framer-motion"; - -export type BlogsListItem = { - id: string | number; - title: string; - slug: string; - publishedAt: string; -}; - -const ACCENT = { r: 34, g: 197, b: 94 }; -const SPREAD = 2.6; -const MAX_ALPHA = 0.95; -const clamp01 = (n: number) => Math.min(1, Math.max(0, n)); - -function Row({ - item, - index, - pos, - strength, - spread, - dirRef, - onActivate, -}: { - item: BlogsListItem; - index: number; - pos: MotionValue; - strength: MotionValue; - spread: MotionValue; - dirRef: RefObject; - onActivate: (i: number) => void; -}) { - const tailActive = (signed: number, dir: number) => - dir === 0 ? false : dir > 0 ? signed < 0 : signed > 0; - - const background = useTransform([pos, strength, spread], ([p, st, sp]: number[]) => { - const signed = index - p; - const dist = Math.abs(signed); - const isHovered = dist < 0.5; - const isTail = !isHovered && tailActive(signed, dirRef.current ?? 0); - const s = isHovered ? st : isTail ? sp : 0; - const tint = clamp01(1 - dist / SPREAD); - const a = tint * tint * s * MAX_ALPHA; - return `rgba(${ACCENT.r}, ${ACCENT.g}, ${ACCENT.b}, ${a})`; - }); - - const ink = useTransform([pos, strength, spread], ([p, st, sp]: number[]) => { - const signed = index - p; - const dist = Math.abs(signed); - const isHovered = dist < 0.5; - const isTail = !isHovered && tailActive(signed, dirRef.current ?? 0); - const s = isHovered ? st : isTail ? sp : 0; - const k = clamp01(1 - dist / 1.15) * s; - return `rgb(${Math.round(255 * (1 - k))}, ${Math.round(255 * (1 - k))}, ${Math.round(255 * (1 - k))})`; - }); - - const mutedInk = useTransform([pos, strength, spread], ([p, st, sp]: number[]) => { - const signed = index - p; - const dist = Math.abs(signed); - const isHovered = dist < 0.5; - const isTail = !isHovered && tailActive(signed, dirRef.current ?? 0); - const s = isHovered ? st : isTail ? sp : 0; - const k = clamp01(1 - dist / 1.15) * s; - return `rgb(${Math.round(115 * (1 - k))}, ${Math.round(115 * (1 - k))}, ${Math.round(115 * (1 - k))})`; - }); - - return ( -
  • - onActivate(index)} - onFocus={() => onActivate(index)} - > - - - {String(index + 1).padStart(2, "0")} - - - {item.title} - - - {new Date(item.publishedAt).toLocaleDateString("en-US", { - year: "numeric", - month: "short", - day: "numeric", - })} - - - -
  • - ); -} - -export function BlogsList({ posts }: { posts: BlogsListItem[] }) { - const [, setActive] = useState(0); - const idleTimer = useRef | null>(null); - const prevRef = useRef(null); - const dirRef = useRef(0); - - const pos = useSpring(0, { stiffness: 220, damping: 26, mass: 0.9 }); - const strength = useSpring(0, { stiffness: 260, damping: 30 }); - const spread = useSpring(0, { stiffness: 260, damping: 30 }); - - const activate = (i: number) => { - if (prevRef.current !== null && i !== prevRef.current) { - dirRef.current = i > prevRef.current ? 1 : -1; - } - prevRef.current = i; - pos.set(i); - strength.set(1); - spread.set(1); - setActive(i); - if (idleTimer.current) clearTimeout(idleTimer.current); - idleTimer.current = setTimeout(() => spread.set(0), 400); - }; - - return ( -
      { - if (idleTimer.current) clearTimeout(idleTimer.current); - strength.set(0); - spread.set(0); - prevRef.current = null; - dirRef.current = 0; - }} - > - {posts.map((item, i) => ( - - ))} -
    - ); -} diff --git a/components/contents-box.tsx b/components/contents-box.tsx new file mode 100644 index 0000000..6e783b3 --- /dev/null +++ b/components/contents-box.tsx @@ -0,0 +1,32 @@ +import type { TocHeading } from "@/lib/blog-toc"; + +/** Numbered "Contents" box at the top of a post, encyclopedia style. */ +export function ContentsBox({ headings }: { headings: TocHeading[] }) { + if (headings.length < 2) return null; + + const top = Math.min(...headings.map((h) => h.level)); + const counters: number[] = []; + + return ( + + ); +} diff --git a/components/footer.tsx b/components/footer.tsx deleted file mode 100644 index 11cd6b2..0000000 --- a/components/footer.tsx +++ /dev/null @@ -1,36 +0,0 @@ -import Link from "next/link"; -import { profile, writingLinks } from "@/lib/site-content"; - -const footerLinks = [ - { - name: "GitHub", - url: "https://github.com/celeroncoder/celeroncoder.tech", - }, - ...writingLinks, -]; - -export function Footer() { - return ( -
    -
    -

    - © {new Date().getFullYear()} {profile.name}. Built with - Next.js. -

    -
    - {footerLinks.map((link) => ( - - {link.name} - - ))} -
    -
    -
    - ); -} diff --git a/components/greeting.tsx b/components/greeting.tsx deleted file mode 100644 index b94b519..0000000 --- a/components/greeting.tsx +++ /dev/null @@ -1,28 +0,0 @@ -import Image from "next/image"; -import { profile } from "@/lib/site-content"; - -export function Greeting() { - return ( -
    -
    - {profile.name} -
    - -
    -

    - Hey, I'm {profile.name}. -

    - -

    - {profile.introduction} -

    -
    -
    - ); -} diff --git a/components/hero-shader.tsx b/components/hero-shader.tsx deleted file mode 100644 index cdf51a7..0000000 --- a/components/hero-shader.tsx +++ /dev/null @@ -1,40 +0,0 @@ -"use client"; - -import { DitheringShader } from "@/components/ui/dithering-shader"; -import { useEffect, useState } from "react"; - -export function HeroShader() { - const [dimensions, setDimensions] = useState({ width: 1920, height: 1080 }); - - useEffect(() => { - const updateDimensions = () => { - setDimensions({ - width: window.innerWidth, - height: window.innerHeight, - }); - }; - - updateDimensions(); - window.addEventListener("resize", updateDimensions); - return () => window.removeEventListener("resize", updateDimensions); - }, []); - - return ( -
    - - {/* Bottom fade to seamless black transition */} -
    -
    - ); -} diff --git a/components/icons/arcade-icons.tsx b/components/icons/arcade-icons.tsx deleted file mode 100644 index 10dd437..0000000 --- a/components/icons/arcade-icons.tsx +++ /dev/null @@ -1,414 +0,0 @@ -// Nucleo Arcade icon set — inline SVG components -// Colors: var(--color-contrast-high) → currentColor, hsl(…/0) → transparent -// size defaults to "1em" — icon scales automatically with the surrounding font-size - -type IconProps = { - className?: string; - size?: string | number; -}; - -export function ArcadeChevronLeft({ className, size = "1em" }: IconProps) { - return ( - - ); -} - -export function ArcadeChevronRight({ className, size = "1em" }: IconProps) { - return ( - - ); -} - -export function ArcadeArrowLeft({ className, size = "1em" }: IconProps) { - return ( - - ); -} - -export function ArcadeArrowUpRight({ className, size = "1em" }: IconProps) { - return ( - - ); -} - -export function ArcadeLock({ className, size = "1em" }: IconProps) { - return ( - - ); -} - -export function ArcadeMediaPlay({ className, size = "1em" }: IconProps) { - return ( - - ); -} - -export function ArcadeUTurnLeft({ className, size = "1em" }: IconProps) { - return ( - - ); -} diff --git a/components/links.tsx b/components/links.tsx deleted file mode 100644 index a8a5edc..0000000 --- a/components/links.tsx +++ /dev/null @@ -1,20 +0,0 @@ -import Link from "next/link"; -import { socialLinks } from "@/lib/site-content"; - -export function Links() { - return ( - - ); -} diff --git a/components/post-index.tsx b/components/post-index.tsx new file mode 100644 index 0000000..5193c32 --- /dev/null +++ b/components/post-index.tsx @@ -0,0 +1,37 @@ +import Link from "next/link"; +import { getPayload } from "payload"; +import config from "@payload-config"; + +function formatDate(value: string) { + return new Date(value).toLocaleDateString("en-GB", { + year: "numeric", + month: "short", + day: "numeric", + }); +} + +/** Every post as a plain bulleted list of links, newest first. */ +export async function PostIndex() { + const payload = await getPayload({ config }); + const { docs: posts } = await payload.find({ + collection: "posts", + sort: "-publishedAt", + limit: 100, + depth: 0, + }); + + if (posts.length === 0) return

    No posts yet.

    ; + + return ( +
      + {posts.map((post) => ( +
    • + {post.title}{" "} + + ({formatDate(post.publishedAt)}) + +
    • + ))} +
    + ); +} diff --git a/components/projects.tsx b/components/projects.tsx deleted file mode 100644 index 230a70e..0000000 --- a/components/projects.tsx +++ /dev/null @@ -1,50 +0,0 @@ -import Link from "next/link"; -import { ArcadeArrowUpRight, ArcadeLock } from "@/components/icons/arcade-icons"; -import { projects } from "@/lib/site-content"; - -export function Projects() { - return ( -
    -

    Projects

    -
    - {projects.map((project) => ( -
    -

    {project.title}

    -

    - {project.description} -

    -
    - {project.githubUrl ? ( - - GitHub - - - ) : ( - - - Private - - )} - {project.liveUrl && ( - - Live - - - )} -
    -
    - ))} -
    -
    - ); -} diff --git a/components/retro-page.tsx b/components/retro-page.tsx new file mode 100644 index 0000000..b2343ef --- /dev/null +++ b/components/retro-page.tsx @@ -0,0 +1,53 @@ +import Link from "next/link"; +import { AsciiBackground } from "@/components/ascii-background"; +import { profile, socialLinks } from "@/lib/site-content"; + +const navLinks = socialLinks.filter((link) => link.name === "GitHub" || link.name === "Twitter"); + +/** + * Early-web page shell: a centered text column over the ASCII noise + * background (which fades out behind it), with a bracketed link bar on top. + */ +export function RetroPage({ children }: { children: React.ReactNode }) { + return ( + <> + +
    + + +
    {children}
    + +
    +

    + © {new Date().getFullYear()} {profile.name}. Best viewed in any browser at 800×600. +

    +
    +
    + + ); +} + +/** Page title with the thin rule underneath, encyclopedia style. */ +export function RetroTitle({ children, subtitle }: { children: React.ReactNode; subtitle?: React.ReactNode }) { + return ( +
    +

    + {children} +

    + {subtitle &&

    {subtitle}

    } +
    + ); +} diff --git a/components/stack.tsx b/components/stack.tsx deleted file mode 100644 index 72b0977..0000000 --- a/components/stack.tsx +++ /dev/null @@ -1,19 +0,0 @@ -import { skills } from "@/lib/site-content"; - -export function Stack() { - return ( -
    -

    Top Skills

    -
    - {skills.map((skill, i) => ( - - {skill} - {i < skills.length - 1 && ( - · - )} - - ))} -
    -
    - ); -} diff --git a/components/ui/blog-card.tsx b/components/ui/blog-card.tsx deleted file mode 100644 index e26c1b3..0000000 --- a/components/ui/blog-card.tsx +++ /dev/null @@ -1,48 +0,0 @@ -import Link from "next/link"; -import { ArcadeChevronRight } from "@/components/icons/arcade-icons"; -import { Card } from "./card"; - -export type Blog = { - title: string; - description: string; - publishedAt: string; - readTime?: string; - slug: string; -}; - -export const BlogCard: React.FC = ({ - title, - description, - publishedAt, - readTime, - slug, -}) => { - return ( - -
    - [FILE] -

    {title}

    -
    - -
    - {publishedAt} - {readTime && ( - <> - · - {readTime} - - )} -
    - -

    {description}

    - - - - read - -
    - ); -}; diff --git a/components/ui/card.tsx b/components/ui/card.tsx deleted file mode 100644 index 0d5ba1e..0000000 --- a/components/ui/card.tsx +++ /dev/null @@ -1,35 +0,0 @@ -import { cn } from "@/lib/utils"; - -export const Card: React.FC<{ - children: React.ReactNode; - className?: string; - onClick?: () => void; -}> = ({ children, className = "", onClick }) => { - const handleKeyDown = onClick - ? (e: React.KeyboardEvent) => { - if (e.key === "Enter") { - onClick(); - } else if (e.key === " ") { - e.preventDefault(); - onClick(); - } - } - : undefined; - - return ( -
    - {children} -
    - ); -}; diff --git a/components/ui/dithering-shader.tsx b/components/ui/dithering-shader.tsx deleted file mode 100644 index 49e04d7..0000000 --- a/components/ui/dithering-shader.tsx +++ /dev/null @@ -1,459 +0,0 @@ -"use client" - -import type React from "react" - -import { useEffect, useRef } from "react" - -// GLSL utility functions -const declarePI = ` -#define TWO_PI 6.28318530718 -#define PI 3.14159265358979323846 -` - -const proceduralHash11 = ` - float hash11(float p) { - p = fract(p * 0.3183099) + 0.1; - p *= p + 19.19; - return fract(p * p); - } -` - -const proceduralHash21 = ` - float hash21(vec2 p) { - p = fract(p * vec2(0.3183099, 0.3678794)) + 0.1; - p += dot(p, p + 19.19); - return fract(p.x * p.y); - } -` - -const simplexNoise = ` -vec3 permute(vec3 x) { return mod(((x * 34.0) + 1.0) * x, 289.0); } -float snoise(vec2 v) { - const vec4 C = vec4(0.211324865405187, 0.366025403784439, - -0.577350269189626, 0.024390243902439); - vec2 i = floor(v + dot(v, C.yy)); - vec2 x0 = v - i + dot(i, C.xx); - vec2 i1; - i1 = (x0.x > x0.y) ? vec2(1.0, 0.0) : vec2(0.0, 1.0); - vec4 x12 = x0.xyxy + C.xxzz; - x12.xy -= i1; - i = mod(i, 289.0); - vec3 p = permute(permute(i.y + vec3(0.0, i1.y, 1.0)) - + i.x + vec3(0.0, i1.x, 1.0)); - vec3 m = max(0.5 - vec3(dot(x0, x0), dot(x12.xy, x12.xy), - dot(x12.zw, x12.zw)), 0.0); - m = m * m; - m = m * m; - vec3 x = 2.0 * fract(p * C.www) - 1.0; - vec3 h = abs(x) - 0.5; - vec3 ox = floor(x + 0.5); - vec3 a0 = x - ox; - m *= 1.79284291400159 - 0.85373472095314 * (a0 * a0 + h * h); - vec3 g; - g.x = a0.x * x0.x + h.x * x0.y; - g.yz = a0.yz * x12.xz + h.yz * x12.yw; - return 130.0 * dot(m, g); -} -` - -// Vertex shader -const vertexShaderSource = `#version 300 es -precision mediump float; - -layout(location = 0) in vec4 a_position; - -void main() { - gl_Position = a_position; -} -` - -// Fragment shader -const fragmentShaderSource = `#version 300 es -precision mediump float; - -uniform float u_time; -uniform vec2 u_resolution; -uniform vec4 u_colorBack; -uniform vec4 u_colorFront; -uniform float u_shape; -uniform float u_type; -uniform float u_pxSize; - -out vec4 fragColor; - -${simplexNoise} -${declarePI} -${proceduralHash11} -${proceduralHash21} - -float getSimplexNoise(vec2 uv, float t) { - float noise = .5 * snoise(uv - vec2(0., .3 * t)); - noise += .5 * snoise(2. * uv + vec2(0., .32 * t)); - return noise; -} - -const int bayer2x2[4] = int[4](0, 2, 3, 1); -const int bayer4x4[16] = int[16]( - 0, 8, 2, 10, - 12, 4, 14, 6, - 3, 11, 1, 9, - 15, 7, 13, 5 -); - -const int bayer8x8[64] = int[64]( - 0, 32, 8, 40, 2, 34, 10, 42, - 48, 16, 56, 24, 50, 18, 58, 26, - 12, 44, 4, 36, 14, 46, 6, 38, - 60, 28, 52, 20, 62, 30, 54, 22, - 3, 35, 11, 43, 1, 33, 9, 41, - 51, 19, 59, 27, 49, 17, 57, 25, - 15, 47, 7, 39, 13, 45, 5, 37, - 63, 31, 55, 23, 61, 29, 53, 21 -); - -float getBayerValue(vec2 uv, int size) { - ivec2 pos = ivec2(mod(uv, float(size))); - int index = pos.y * size + pos.x; - - if (size == 2) { - return float(bayer2x2[index]) / 4.0; - } else if (size == 4) { - return float(bayer4x4[index]) / 16.0; - } else if (size == 8) { - return float(bayer8x8[index]) / 64.0; - } - return 0.0; -} - -void main() { - float t = .5 * u_time; - vec2 uv = gl_FragCoord.xy / u_resolution.xy; - uv -= .5; - - // Apply pixelization - float pxSize = u_pxSize; - vec2 pxSizeUv = gl_FragCoord.xy; - pxSizeUv -= .5 * u_resolution; - pxSizeUv /= pxSize; - vec2 pixelizedUv = floor(pxSizeUv) * pxSize / u_resolution.xy; - pixelizedUv += .5; - pixelizedUv -= .5; - - vec2 shape_uv = pixelizedUv; - vec2 dithering_uv = pxSizeUv; - vec2 ditheringNoise_uv = uv * u_resolution; - - float shape = 0.; - if (u_shape < 1.5) { - // Simplex noise - shape_uv *= .001; - shape = 0.5 + 0.5 * getSimplexNoise(shape_uv, t); - shape = smoothstep(0.3, 0.9, shape); - - } else if (u_shape < 2.5) { - // Warp - shape_uv *= .003; - for (float i = 1.0; i < 6.0; i++) { - shape_uv.x += 0.6 / i * cos(i * 2.5 * shape_uv.y + t); - shape_uv.y += 0.6 / i * cos(i * 1.5 * shape_uv.x + t); - } - shape = .15 / abs(sin(t - shape_uv.y - shape_uv.x)); - shape = smoothstep(0.02, 1., shape); - - } else if (u_shape < 3.5) { - // Dots - shape_uv *= .05; - float stripeIdx = floor(2. * shape_uv.x / TWO_PI); - float rand = hash11(stripeIdx * 10.); - rand = sign(rand - .5) * pow(.1 + abs(rand), .4); - shape = sin(shape_uv.x) * cos(shape_uv.y - 5. * rand * t); - shape = pow(abs(shape), 6.); - - } else if (u_shape < 4.5) { - // Sine wave - shape_uv *= 4.; - float wave = cos(.5 * shape_uv.x - 2. * t) * sin(1.5 * shape_uv.x + t) * (.75 + .25 * cos(3. * t)); - shape = 1. - smoothstep(-1., 1., shape_uv.y + wave); - - } else if (u_shape < 5.5) { - // Ripple - float dist = length(shape_uv); - float waves = sin(pow(dist, 1.7) * 7. - 3. * t) * .5 + .5; - shape = waves; - - } else if (u_shape < 6.5) { - // Swirl - float l = length(shape_uv); - float angle = 6. * atan(shape_uv.y, shape_uv.x) + 4. * t; - float twist = 1.2; - float offset = pow(l, -twist) + angle / TWO_PI; - float mid = smoothstep(0., 1., pow(l, twist)); - shape = mix(0., fract(offset), mid); - - } else { - // Sphere - shape_uv *= 2.; - float d = 1. - pow(length(shape_uv), 2.); - vec3 pos = vec3(shape_uv, sqrt(d)); - vec3 lightPos = normalize(vec3(cos(1.5 * t), .8, sin(1.25 * t))); - shape = .5 + .5 * dot(lightPos, pos); - shape *= step(0., d); - } - - int type = int(floor(u_type)); - float dithering = 0.0; - - switch (type) { - case 1: { - dithering = step(hash21(ditheringNoise_uv), shape); - } break; - case 2: - dithering = getBayerValue(dithering_uv, 2); - break; - case 3: - dithering = getBayerValue(dithering_uv, 4); - break; - default: - dithering = getBayerValue(dithering_uv, 8); - break; - } - - dithering -= .5; - float res = step(.5, shape + dithering); - - vec3 fgColor = u_colorFront.rgb * u_colorFront.a; - float fgOpacity = u_colorFront.a; - vec3 bgColor = u_colorBack.rgb * u_colorBack.a; - float bgOpacity = u_colorBack.a; - - vec3 color = fgColor * res; - float opacity = fgOpacity * res; - - color += bgColor * (1. - opacity); - opacity += bgOpacity * (1. - opacity); - - fragColor = vec4(color, opacity); -} -` - -// Shape and type enums -export const DitheringShapes = { - simplex: 1, - warp: 2, - dots: 3, - wave: 4, - ripple: 5, - swirl: 6, - sphere: 7, -} as const - -export const DitheringTypes = { - random: 1, - "2x2": 2, - "4x4": 3, - "8x8": 4, -} as const - -export type DitheringShape = keyof typeof DitheringShapes -export type DitheringType = keyof typeof DitheringTypes - -interface DitheringShaderProps { - width?: number - height?: number - colorBack?: string - colorFront?: string - shape?: DitheringShape - type?: DitheringType - pxSize?: number - speed?: number - className?: string - style?: React.CSSProperties -} - -function hexToRgba(hex: string): [number, number, number, number] { - const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex) - if (!result) return [0, 0, 0, 1] - - return [ - Number.parseInt(result[1], 16) / 255, - Number.parseInt(result[2], 16) / 255, - Number.parseInt(result[3], 16) / 255, - 1, - ] -} - -function createShader(gl: WebGL2RenderingContext, type: number, source: string): WebGLShader | null { - const shader = gl.createShader(type) - if (!shader) return null - - gl.shaderSource(shader, source) - gl.compileShader(shader) - - if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { - console.error("An error occurred compiling the shaders: " + gl.getShaderInfoLog(shader)) - gl.deleteShader(shader) - return null - } - - return shader -} - -function createProgram( - gl: WebGL2RenderingContext, - vertexShaderSource: string, - fragmentShaderSource: string, -): WebGLProgram | null { - const vertexShader = createShader(gl, gl.VERTEX_SHADER, vertexShaderSource) - const fragmentShader = createShader(gl, gl.FRAGMENT_SHADER, fragmentShaderSource) - - if (!vertexShader || !fragmentShader) return null - - const program = gl.createProgram() - if (!program) return null - - gl.attachShader(program, vertexShader) - gl.attachShader(program, fragmentShader) - gl.linkProgram(program) - - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { - console.error("Unable to initialize the shader program: " + gl.getProgramInfoLog(program)) - gl.deleteProgram(program) - return null - } - - return program -} - -const EMPTY_STYLE: React.CSSProperties = {}; - -export function DitheringShader({ - width = 800, - height = 800, - colorBack = "#000000", - colorFront = "#ffffff", - shape = "simplex", - type = "8x8", - pxSize = 4, - speed = 1, - className = "", - style = EMPTY_STYLE, -}: DitheringShaderProps) { - const canvasRef = useRef(null) - const animationRef = useRef(0) - const programRef = useRef(null) - const glRef = useRef(null) - const uniformLocationsRef = useRef>({}) - const startTimeRef = useRef(Date.now()) - - useEffect(() => { - const canvas = canvasRef.current - if (!canvas) return - - const gl = canvas.getContext("webgl2") - if (!gl) { - console.error("WebGL2 not supported") - return - } - - glRef.current = gl - - // Create shader program - const program = createProgram(gl, vertexShaderSource, fragmentShaderSource) - if (!program) return - - programRef.current = program - - // Get uniform locations - uniformLocationsRef.current = { - u_time: gl.getUniformLocation(program, "u_time"), - u_resolution: gl.getUniformLocation(program, "u_resolution"), - u_colorBack: gl.getUniformLocation(program, "u_colorBack"), - u_colorFront: gl.getUniformLocation(program, "u_colorFront"), - u_shape: gl.getUniformLocation(program, "u_shape"), - u_type: gl.getUniformLocation(program, "u_type"), - u_pxSize: gl.getUniformLocation(program, "u_pxSize"), - } - - // Set up position attribute - const positionAttributeLocation = gl.getAttribLocation(program, "a_position") - const positionBuffer = gl.createBuffer() - gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer) - const positions = [-1, -1, 1, -1, -1, 1, -1, 1, 1, -1, 1, 1] - gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW) - gl.enableVertexAttribArray(positionAttributeLocation) - gl.vertexAttribPointer(positionAttributeLocation, 2, gl.FLOAT, false, 0, 0) - - // Set canvas size - canvas.width = width - canvas.height = height - gl.viewport(0, 0, width, height) - - // Animation loop - const render = () => { - const currentTime = (Date.now() - startTimeRef.current) * 0.001 * speed - - const context = glRef.current - const shaderProgram = programRef.current - - if (!context || !shaderProgram) return - - context.clear(context.COLOR_BUFFER_BIT) - context.useProgram(shaderProgram) - - // Set uniforms - const locations = uniformLocationsRef.current - - if (locations.u_time) context.uniform1f(locations.u_time, currentTime) - if (locations.u_resolution) context.uniform2f(locations.u_resolution, width, height) - if (locations.u_colorBack) context.uniform4fv(locations.u_colorBack, hexToRgba(colorBack)) - if (locations.u_colorFront) context.uniform4fv(locations.u_colorFront, hexToRgba(colorFront)) - if (locations.u_shape) context.uniform1f(locations.u_shape, DitheringShapes[shape]) - if (locations.u_type) context.uniform1f(locations.u_type, DitheringTypes[type]) - if (locations.u_pxSize) context.uniform1f(locations.u_pxSize, pxSize) - - context.drawArrays(context.TRIANGLES, 0, 6) - - if (speed !== 0) { - animationRef.current = requestAnimationFrame(render) - } - } - - const startAnimation = () => { - if (speed !== 0) { - animationRef.current = requestAnimationFrame(render) - } - } - - startAnimation() - - return () => { - if (animationRef.current) { - cancelAnimationFrame(animationRef.current) - } - if (glRef.current && programRef.current) { - glRef.current.deleteProgram(programRef.current) - } - } - }, [width, height, colorBack, colorFront, shape, type, pxSize, speed]) - - return ( -
    - -
    - ) -} diff --git a/components/ui/project-card.tsx b/components/ui/project-card.tsx deleted file mode 100644 index 681dce7..0000000 --- a/components/ui/project-card.tsx +++ /dev/null @@ -1,58 +0,0 @@ -import Link from "next/link"; -import { ArcadeChevronRight, ArcadeArrowUpRight, ArcadeLock } from "@/components/icons/arcade-icons"; -import { Card } from "./card"; - -export type Project = { - title: string; - description: string; - github_url?: string; - live_url?: string; -}; - -export const ProjectCard: React.FC = ({ - title, - description, - github_url, - live_url, -}) => { - return ( - -
    - [DIR] -

    {title}

    -
    - -

    {description}

    - -
    - {github_url ? ( - - - github - - ) : ( - - - private - - )} - {live_url && ( - - - live - - )} -
    -
    - ); -}; diff --git a/components/ui/section.tsx b/components/ui/section.tsx deleted file mode 100644 index 9814fb6..0000000 --- a/components/ui/section.tsx +++ /dev/null @@ -1,27 +0,0 @@ -import Link from "next/link"; - -export const Section: React.FC<{ - children: React.ReactNode; - title: string; -}> = ({ children, title }) => { - return ( -
    -
    - - user@celeroncoder - : - ~ - $ - ls ./{title.toLowerCase().replace(" ", "-")}/ - -
    -
    {children}
    -
    - ); -}; diff --git a/components/ui/separator.tsx b/components/ui/separator.tsx deleted file mode 100644 index ef1bf46..0000000 --- a/components/ui/separator.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { cn } from "@/lib/utils"; - -export const Separator: React.FC<{ - className?: string; - orientation?: "horizontal" | "vertical"; -}> = ({ className, orientation = "horizontal" }) => { - return ( -
    - ); -}; diff --git a/components/ui/stack-card.tsx b/components/ui/stack-card.tsx deleted file mode 100644 index 11da8fd..0000000 --- a/components/ui/stack-card.tsx +++ /dev/null @@ -1,23 +0,0 @@ -import { ArcadeMediaPlay } from "@/components/icons/arcade-icons"; -import { Card } from "./card"; - -export type Stack = { - title: string; - description?: string; -}; - -export const StackCard: React.FC = ({ title, description }) => { - return ( - -
    - -
    -

    {title}

    - {description && ( -

    {description}

    - )} -
    -
    -
    - ); -}; diff --git a/lib/fonts/geist-pixel-square-core.woff2 b/lib/fonts/geist-pixel-square-core.woff2 deleted file mode 100644 index 9bede10..0000000 Binary files a/lib/fonts/geist-pixel-square-core.woff2 and /dev/null differ diff --git a/lib/fonts/geist-pixel-square-ext.woff2 b/lib/fonts/geist-pixel-square-ext.woff2 deleted file mode 100644 index 057d8cf..0000000 Binary files a/lib/fonts/geist-pixel-square-ext.woff2 and /dev/null differ diff --git a/lib/fonts/geist-sans-core.woff2 b/lib/fonts/geist-sans-core.woff2 deleted file mode 100644 index 6788217..0000000 Binary files a/lib/fonts/geist-sans-core.woff2 and /dev/null differ diff --git a/lib/fonts/geist-sans-ext.woff2 b/lib/fonts/geist-sans-ext.woff2 deleted file mode 100644 index 64d735f..0000000 Binary files a/lib/fonts/geist-sans-ext.woff2 and /dev/null differ diff --git a/lib/fonts/index.ts b/lib/fonts/index.ts deleted file mode 100644 index cecd833..0000000 --- a/lib/fonts/index.ts +++ /dev/null @@ -1,62 +0,0 @@ -// Generated by scripts/subset-fonts.py. Do not edit by hand: rerun the script -// (see its docstring for when) and commit the output. -// -// Each font is split in two. The core file (ASCII + common punctuation) is -// preloaded; the extended file sits behind unicode-range and only downloads on -// pages that use one of its characters. -import type { CSSProperties } from "react"; -import localFont from "next/font/local"; - -const geistSansCore = localFont({ - src: "./geist-sans-core.woff2", - weight: "400 900", - declarations: [{ prop: "unicode-range", value: "U+0020-007E, U+00A0-00AC, U+00AE-0113, U+0116-012B, U+012E-0137, U+0139-013E, U+0141-0148, U+014A-014D, U+0150-017E, U+0307, U+2013-2014, U+2018-2019, U+201C-201D, U+2022, U+2026" }], -}); - -const geistSansExt = localFont({ - src: "./geist-sans-ext.woff2", - weight: "400 900", - preload: false, - adjustFontFallback: false, - declarations: [{ prop: "unicode-range", value: "U+3003, U+301C" }], -}); - -const geistPixelSquareCore = localFont({ - src: "./geist-pixel-square-core.woff2", - weight: "500", - adjustFontFallback: false, - fallback: [ - "Geist Mono", - "ui-monospace", - "SFMono-Regular", - "Roboto Mono", - "Menlo", - "Monaco", - "Liberation Mono", - "DejaVu Sans Mono", - "Courier New", - "monospace", - ], - declarations: [{ prop: "unicode-range", value: "U+0020-007E, U+00A0, U+00A9, U+00B7, U+2013-2014, U+2018-2019, U+201C-201D, U+2022, U+2026" }], -}); - -const geistPixelSquareExt = localFont({ - src: "./geist-pixel-square-ext.woff2", - weight: "500", - preload: false, - adjustFontFallback: false, - declarations: [{ prop: "unicode-range", value: "U+00A1-00A8, U+00AA-00B6, U+00B8-0113, U+0116-012B, U+012E-0137, U+0139-013E, U+0141-0148, U+014C-014D, U+0150-0165, U+0168-017E, U+0307, U+301C" }], -}); - -// The extended face has to come straight after the core face. Anything in -// between (like next/font's metric-adjusted fallback) would draw extended -// characters before the real font gets a chance to. -function stack(core: string, extended: string) { - const [primary, ...rest] = core.split(", "); - return [primary, extended, ...rest].join(", "); -} - -export const fontVariables = { - "--font-geist-sans": stack(geistSansCore.style.fontFamily, geistSansExt.style.fontFamily), - "--font-geist-pixel-square": stack(geistPixelSquareCore.style.fontFamily, geistPixelSquareExt.style.fontFamily), -} as CSSProperties; diff --git a/lib/fonts/manifest.json b/lib/fonts/manifest.json deleted file mode 100644 index 35e16da..0000000 --- a/lib/fonts/manifest.json +++ /dev/null @@ -1,696 +0,0 @@ -{ - "generator": "scripts/subset-fonts.py", - "crawled": "http://localhost:3100", - "geist": "1.7.0", - "fonts": { - "geist-sans": { - "source": "dist/fonts/geist-sans/Geist-Variable.woff2", - "sourceBytes": 69436, - "sourceSha256": "e24cec106619c03f0b3519e31b9bc55e0d5e926b6a95b8d798cd8cef215b1505", - "axes": { - "wght": [ - 400, - 900 - ] - }, - "hinting": true, - "files": { - "core": { - "file": "geist-sans-core.woff2", - "bytes": 22684, - "glyphs": 371, - "unicodeRange": "U+0020-007E, U+00A0-00AC, U+00AE-0113, U+0116-012B, U+012E-0137, U+0139-013E, U+0141-0148, U+014A-014D, U+0150-017E, U+0307, U+2013-2014, U+2018-2019, U+201C-201D, U+2022, U+2026", - "codepoints": [ - "0020", - "0021", - "0022", - "0023", - "0024", - "0025", - "0026", - "0027", - "0028", - "0029", - "002A", - "002B", - "002C", - "002D", - "002E", - "002F", - "0030", - "0031", - "0032", - "0033", - "0034", - "0035", - "0036", - "0037", - "0038", - "0039", - "003A", - "003B", - "003C", - "003D", - "003E", - "003F", - "0040", - "0041", - "0042", - "0043", - "0044", - "0045", - "0046", - "0047", - "0048", - "0049", - "004A", - "004B", - "004C", - "004D", - "004E", - "004F", - "0050", - "0051", - "0052", - "0053", - "0054", - "0055", - "0056", - "0057", - "0058", - "0059", - "005A", - "005B", - "005C", - "005D", - "005E", - "005F", - "0060", - "0061", - "0062", - "0063", - "0064", - "0065", - "0066", - "0067", - "0068", - "0069", - "006A", - "006B", - "006C", - "006D", - "006E", - "006F", - "0070", - "0071", - "0072", - "0073", - "0074", - "0075", - "0076", - "0077", - "0078", - "0079", - "007A", - "007B", - "007C", - "007D", - "007E", - "00A0", - "00A1", - "00A2", - "00A3", - "00A4", - "00A5", - "00A6", - "00A7", - "00A8", - "00A9", - "00AA", - "00AB", - "00AC", - "00AE", - "00AF", - "00B0", - "00B1", - "00B2", - "00B3", - "00B4", - "00B5", - "00B6", - "00B7", - "00B8", - "00B9", - "00BA", - "00BB", - "00BC", - "00BD", - "00BE", - "00BF", - "00C0", - "00C1", - "00C2", - "00C3", - "00C4", - "00C5", - "00C6", - "00C7", - "00C8", - "00C9", - "00CA", - "00CB", - "00CC", - "00CD", - "00CE", - "00CF", - "00D0", - "00D1", - "00D2", - "00D3", - "00D4", - "00D5", - "00D6", - "00D7", - "00D8", - "00D9", - "00DA", - "00DB", - "00DC", - "00DD", - "00DE", - "00DF", - "00E0", - "00E1", - "00E2", - "00E3", - "00E4", - "00E5", - "00E6", - "00E7", - "00E8", - "00E9", - "00EA", - "00EB", - "00EC", - "00ED", - "00EE", - "00EF", - "00F0", - "00F1", - "00F2", - "00F3", - "00F4", - "00F5", - "00F6", - "00F7", - "00F8", - "00F9", - "00FA", - "00FB", - "00FC", - "00FD", - "00FE", - "00FF", - "0100", - "0101", - "0102", - "0103", - "0104", - "0105", - "0106", - "0107", - "0108", - "0109", - "010A", - "010B", - "010C", - "010D", - "010E", - "010F", - "0110", - "0111", - "0112", - "0113", - "0116", - "0117", - "0118", - "0119", - "011A", - "011B", - "011C", - "011D", - "011E", - "011F", - "0120", - "0121", - "0122", - "0123", - "0124", - "0125", - "0126", - "0127", - "0128", - "0129", - "012A", - "012B", - "012E", - "012F", - "0130", - "0131", - "0132", - "0133", - "0134", - "0135", - "0136", - "0137", - "0139", - "013A", - "013B", - "013C", - "013D", - "013E", - "0141", - "0142", - "0143", - "0144", - "0145", - "0146", - "0147", - "0148", - "014A", - "014B", - "014C", - "014D", - "0150", - "0151", - "0152", - "0153", - "0154", - "0155", - "0156", - "0157", - "0158", - "0159", - "015A", - "015B", - "015C", - "015D", - "015E", - "015F", - "0160", - "0161", - "0162", - "0163", - "0164", - "0165", - "0166", - "0167", - "0168", - "0169", - "016A", - "016B", - "016C", - "016D", - "016E", - "016F", - "0170", - "0171", - "0172", - "0173", - "0174", - "0175", - "0176", - "0177", - "0178", - "0179", - "017A", - "017B", - "017C", - "017D", - "017E", - "0307", - "2013", - "2014", - "2018", - "2019", - "201C", - "201D", - "2022", - "2026" - ] - }, - "ext": { - "file": "geist-sans-ext.woff2", - "bytes": 5172, - "glyphs": 38, - "unicodeRange": "U+3003, U+301C", - "codepoints": [ - "3003", - "301C" - ] - } - }, - "boundaryKernedPairs": 0 - }, - "geist-pixel-square": { - "source": "dist/fonts/geist-pixel/GeistPixel-Square.woff2", - "sourceBytes": 28616, - "sourceSha256": "04f9cf917a824370c77fecbd743c99d0b3dfd2c6c906de959996ac6f7fb343b3", - "axes": {}, - "hinting": false, - "files": { - "core": { - "file": "geist-pixel-square-core.woff2", - "bytes": 3624, - "glyphs": 118, - "unicodeRange": "U+0020-007E, U+00A0, U+00A9, U+00B7, U+2013-2014, U+2018-2019, U+201C-201D, U+2022, U+2026", - "codepoints": [ - "0020", - "0021", - "0022", - "0023", - "0024", - "0025", - "0026", - "0027", - "0028", - "0029", - "002A", - "002B", - "002C", - "002D", - "002E", - "002F", - "0030", - "0031", - "0032", - "0033", - "0034", - "0035", - "0036", - "0037", - "0038", - "0039", - "003A", - "003B", - "003C", - "003D", - "003E", - "003F", - "0040", - "0041", - "0042", - "0043", - "0044", - "0045", - "0046", - "0047", - "0048", - "0049", - "004A", - "004B", - "004C", - "004D", - "004E", - "004F", - "0050", - "0051", - "0052", - "0053", - "0054", - "0055", - "0056", - "0057", - "0058", - "0059", - "005A", - "005B", - "005C", - "005D", - "005E", - "005F", - "0060", - "0061", - "0062", - "0063", - "0064", - "0065", - "0066", - "0067", - "0068", - "0069", - "006A", - "006B", - "006C", - "006D", - "006E", - "006F", - "0070", - "0071", - "0072", - "0073", - "0074", - "0075", - "0076", - "0077", - "0078", - "0079", - "007A", - "007B", - "007C", - "007D", - "007E", - "00A0", - "00A9", - "00B7", - "2013", - "2014", - "2018", - "2019", - "201C", - "201D", - "2022", - "2026" - ] - }, - "ext": { - "file": "geist-pixel-square-ext.woff2", - "bytes": 5392, - "glyphs": 283, - "unicodeRange": "U+00A1-00A8, U+00AA-00B6, U+00B8-0113, U+0116-012B, U+012E-0137, U+0139-013E, U+0141-0148, U+014C-014D, U+0150-0165, U+0168-017E, U+0307, U+301C", - "codepoints": [ - "00A1", - "00A2", - "00A3", - "00A4", - "00A5", - "00A6", - "00A7", - "00A8", - "00AA", - "00AB", - "00AC", - "00AD", - "00AE", - "00AF", - "00B0", - "00B1", - "00B2", - "00B3", - "00B4", - "00B5", - "00B6", - "00B8", - "00B9", - "00BA", - "00BB", - "00BC", - "00BD", - "00BE", - "00BF", - "00C0", - "00C1", - "00C2", - "00C3", - "00C4", - "00C5", - "00C6", - "00C7", - "00C8", - "00C9", - "00CA", - "00CB", - "00CC", - "00CD", - "00CE", - "00CF", - "00D0", - "00D1", - "00D2", - "00D3", - "00D4", - "00D5", - "00D6", - "00D7", - "00D8", - "00D9", - "00DA", - "00DB", - "00DC", - "00DD", - "00DE", - "00DF", - "00E0", - "00E1", - "00E2", - "00E3", - "00E4", - "00E5", - "00E6", - "00E7", - "00E8", - "00E9", - "00EA", - "00EB", - "00EC", - "00ED", - "00EE", - "00EF", - "00F0", - "00F1", - "00F2", - "00F3", - "00F4", - "00F5", - "00F6", - "00F7", - "00F8", - "00F9", - "00FA", - "00FB", - "00FC", - "00FD", - "00FE", - "00FF", - "0100", - "0101", - "0102", - "0103", - "0104", - "0105", - "0106", - "0107", - "0108", - "0109", - "010A", - "010B", - "010C", - "010D", - "010E", - "010F", - "0110", - "0111", - "0112", - "0113", - "0116", - "0117", - "0118", - "0119", - "011A", - "011B", - "011C", - "011D", - "011E", - "011F", - "0120", - "0121", - "0122", - "0123", - "0124", - "0125", - "0126", - "0127", - "0128", - "0129", - "012A", - "012B", - "012E", - "012F", - "0130", - "0131", - "0132", - "0133", - "0134", - "0135", - "0136", - "0137", - "0139", - "013A", - "013B", - "013C", - "013D", - "013E", - "0141", - "0142", - "0143", - "0144", - "0145", - "0146", - "0147", - "0148", - "014C", - "014D", - "0150", - "0151", - "0152", - "0153", - "0154", - "0155", - "0156", - "0157", - "0158", - "0159", - "015A", - "015B", - "015C", - "015D", - "015E", - "015F", - "0160", - "0161", - "0162", - "0163", - "0164", - "0165", - "0168", - "0169", - "016A", - "016B", - "016C", - "016D", - "016E", - "016F", - "0170", - "0171", - "0172", - "0173", - "0174", - "0175", - "0176", - "0177", - "0178", - "0179", - "017A", - "017B", - "017C", - "017D", - "017E", - "0307", - "301C" - ] - } - }, - "boundaryKernedPairs": 0 - } - } -} diff --git a/package.json b/package.json index f47109d..e539aa3 100644 --- a/package.json +++ b/package.json @@ -24,7 +24,6 @@ "@vercel/speed-insights": "^1.3.1", "clsx": "^2.1.1", "framer-motion": "^12.40.0", - "geist": "^1.7.0", "graphql": "^16.12.0", "highlight.js": "^11.10.0", "lexical": "0.35.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 9b19039..0678c25 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -50,9 +50,6 @@ importers: framer-motion: specifier: ^12.40.0 version: 12.40.0(react-dom@19.2.3(react@19.2.3))(react@19.2.3) - geist: - specifier: ^1.7.0 - version: 1.7.0(next@16.1.1(react-dom@19.2.3(react@19.2.3))(react@19.2.3)(sass@1.77.4)) graphql: specifier: ^16.12.0 version: 16.12.0 @@ -1774,11 +1771,6 @@ packages: function-bind@1.1.2: resolution: {integrity: sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==} - geist@1.7.0: - resolution: {integrity: sha512-ZaoiZwkSf0DwwB1ncdLKp+ggAldqxl5L1+SXaNIBGkPAqcu+xjVJLxlf3/S8vLt9UHx1xu5fz3lbzKCj5iOVdQ==} - peerDependencies: - next: '>=13.2.0' - get-tsconfig@4.13.6: resolution: {integrity: sha512-shZT/QMiSHc/YBLxxOkMtgSid5HFoauqCE3/exfsEcwg1WkeqjG+V40yBbBrsD+jW2HDXcs28xOfcbm2jI8Ddw==} @@ -4425,10 +4417,6 @@ snapshots: function-bind@1.1.2: {} - geist@1.7.0(next@16.1.1(react-dom@19.2.3(react@19.2.3))(react@19.2.3)(sass@1.77.4)): - dependencies: - next: 16.1.1(react-dom@19.2.3(react@19.2.3))(react@19.2.3)(sass@1.77.4) - get-tsconfig@4.13.6: dependencies: resolve-pkg-maps: 1.0.0 diff --git a/public/icon.svg b/public/icon.svg index 3326c83..6c6f31c 100644 --- a/public/icon.svg +++ b/public/icon.svg @@ -1,4 +1,5 @@ - - - + + + + K diff --git a/scripts/subset-fonts.py b/scripts/subset-fonts.py deleted file mode 100644 index d09446b..0000000 --- a/scripts/subset-fonts.py +++ /dev/null @@ -1,542 +0,0 @@ -# /// script -# requires-python = ">=3.10" -# dependencies = [ -# "fonttools[woff]==4.68.0", -# "uharfbuzz==0.57.0", -# ] -# /// -"""Subset the site's web fonts into a preloaded core file and a lazy extended file. - -Run by hand (not part of `pnpm build`) and commit everything it writes to lib/fonts/. -It reads the source fonts from node_modules/geist and crawls a running copy of -the site for the characters it renders, so start one first: - - pnpm install && pnpm build && pnpm start # serves the content in .env's database - uv run scripts/subset-fonts.py # crawls http://localhost:3000 - uv run scripts/subset-fonts.py --base https://... # or crawl a deployment - uv run scripts/subset-fonts.py --check # only report characters the committed fonts miss - -Rerun it when: - - a post (or any page) starts using a character outside the committed files - (`--check` exits 1 and lists them); until then those characters draw in the - fallback font, - - the `geist` package is upgraded, - - the site starts using a Geist Sans weight below 400 (the file keeps - 400-900), a real italic face, an OpenType feature (font-feature-settings / - font-variant-*), or a Pixel variant other than Square. - -What it does, per font: - 1. Collects the characters the site renders by crawling the home page, /blog - and every post, and folds in upper/lowercase forms (the body is - `text-transform: lowercase`, some labels are `uppercase`). - 2. Core file = ASCII + NBSP + common punctuation + anything on the home page - or on at least half of the crawled pages (+ all of Latin-1 and Latin - Extended-A for fonts with `core_latin`). It is preloaded. - Extended file = the rest of Latin-1 + Latin Extended-A + every other used - character the font has. It sits behind `unicode-range`, so only pages that use one - of its characters download it. It also maps a few Latin reference - letters (AUTOHINT_REFERENCE) that its unicode-range leaves to core. - 3. Drops the part of the weight axis below the lightest weight used (exactly, - without re-rounding any deltas), drops OpenType features the browser - never applies here and unneeded tables, and writes deterministic WOFF2. - Hinting is set per font; see the notes in JOBS. - 4. Verifies the output (cmap, axes, features, hinting, fallback metrics) and - shapes every core/extended character and character pair with HarfBuzz - against the original font at every used weight; any outline or advance - difference fails the run. - 5. Writes lib/fonts/index.ts (the next/font declarations, including - unicode-range lists generated from each file's real cmap) and - lib/fonts/manifest.json. -""" - -from __future__ import annotations - -import argparse -import hashlib -import html -import io -import json -import re -import sys -import urllib.request -from collections import Counter -from dataclasses import dataclass, field -from pathlib import Path - -import uharfbuzz as hb -from fontTools import subset -from fontTools.pens.recordingPen import RecordingPen -from fontTools.ttLib import TTFont - -ROOT = Path(__file__).resolve().parent.parent -OUT_DIR = ROOT / "lib" / "fonts" -GEIST_DIR = ROOT / "node_modules" / "geist" -DEFAULT_BASE = "http://localhost:3000" - -ASCII = set(range(0x20, 0x7F)) -LATIN_1 = set(range(0xA0, 0x100)) -LATIN_EXT_A = set(range(0x100, 0x180)) -# Punctuation most pages use; always in the preloaded core when the font has it. -# U+2022 is the list bullet glyph some browsers draw for `list-style: disc`. -CORE_PUNCTUATION = {0x00A0, 0x2013, 0x2014, 0x2018, 0x2019, 0x201C, 0x201D, 0x2022, 0x2026} -# FreeType's autohinter (Chrome on Linux/Android uses it instead of TrueType -# bytecode) measures blue zones and stem widths from these Latin letters, found -# through the cmap. Extended files map them too, but leave them out of their -# unicode-range (core still draws them); without them accented glyphs from the -# extended file rasterize visibly softer than they do today. -AUTOHINT_REFERENCE = {ord(c) for c in "THEZOCQSLUfijkdbhxzroescpqgjyO0"} -# The autohinter also hints each glyph with the blue zones of the script it -# belongs to. A glyph shared with another script's code point (Geist draws -# U+00B5 MICRO SIGN with its Greek mu) counts as that script, so subsets map -# that script's code points as well, again without listing them in unicode-range. -SCRIPT_BLOCKS = [(0x0370, 0x0400), (0x0400, 0x0530)] # Greek, Cyrillic - - -def shared_script_codepoints(source_cmap: dict[int, str], cps: set[int]) -> set[int]: - glyphs = {source_cmap[c] for c in cps if c in source_cmap} - out = set() - for lo, hi in SCRIPT_BLOCKS: - block = {c for c in source_cmap if lo <= c < hi} - if any(source_cmap[c] in glyphs for c in block): - out |= block - return out - - -# Geist draws these two CJK punctuation marks today (CJK text otherwise falls -# through to system fonts). Keeping them preserves how CJK text renders. -EXTRA_EXT = {0x3003, 0x301C} - -# Features Chromium/Firefox/Safari apply by default to Latin text. The site sets -# no font-feature-settings or font-variant-*, so nothing else is reachable. -DEFAULT_FEATURES = ["ccmp", "locl", "rlig", "liga", "clig", "calt", "rclt", "kern", "mark", "mkmk", "rvrn"] -# Tables the browser never reads for rendering. -DROP_TABLES = ["meta"] -# Copyright, names, version, license description + URL (OFL requires the notice). -NAME_IDS = [0, 1, 2, 3, 4, 5, 6, 13, 14, 16, 17] - -PIXEL_FALLBACK = [ - "Geist Mono", "ui-monospace", "SFMono-Regular", "Roboto Mono", "Menlo", "Monaco", - "Liberation Mono", "DejaVu Sans Mono", "Courier New", "monospace", -] - - -@dataclass -class FontJob: - name: str # output file stem, e.g. geist-sans - ident: str # TS identifier stem, e.g. geistSans - css_var: str - source: Path - weight: str # @font-face font-weight descriptor - axes: dict[str, tuple[float, float]] = field(default_factory=dict) - # Weights the CSS renders this font at; verification shapes at each of them. - used_weights: list[int] = field(default_factory=list) - hinting: bool = False - adjust_font_fallback: bool = True - # Put all of Latin-1 + Latin Extended-A in core. Browsers shape each file - # separately, so a core/ext split inside Latin text loses kerning between - # e.g. `f` and `é`; set this for fonts that kern across that boundary. - core_latin: bool = False - fallback: list[str] | None = None - - -JOBS = [ - FontJob( - name="geist-sans", - ident="geistSans", - css_var="--font-geist-sans", - source=GEIST_DIR / "dist/fonts/geist-sans/Geist-Variable.woff2", - # The site renders 400 (body), 500 (font-medium, prose headings), - # 600 (prose strong, font-semibold, bold inside italics) and 700 (). - # Clamping at 400 drops the whole Thin master exactly. The top stays at - # 900: 900 is a master, so clamping to 700 would only rescale (and - # round) its deltas, saving almost nothing and moving outlines by up to - # half a unit at 500-700. - weight="400 900", - axes={"wght": (400, 900)}, - used_weights=[400, 500, 600, 700], - # No glyph programs, just a 7-byte `prep` (dropout control). Kept so - # hinting rasterizers (Windows) see exactly what they see today. - hinting=True, - # Geist Sans kerns 16,551 pairs of ASCII x Latin-1/Ext-A characters. - core_latin=True, - ), - FontJob( - name="geist-pixel-square", - ident="geistPixelSquare", - css_var="--font-geist-pixel-square", - source=GEIST_DIR / "dist/fonts/geist-pixel/GeistPixel-Square.woff2", - weight="500", - used_weights=[500], - # ttfautohint bytecode, ~8.5 KB per file. Dropped (approved): Linux - # Chrome (FreeType autohinter) and macOS ignore it, so they render - # identically; Windows DirectWrite grid-fits with it, so the pixel font - # can rasterize slightly differently there. - hinting=False, - # No kerning between ASCII and Latin-1/Ext-A, so the split is lossless. - adjust_font_fallback=False, - fallback=PIXEL_FALLBACK, - ), -] - - -# ---------------------------------------------------------------- crawl - -def fetch(url: str) -> str: - req = urllib.request.Request(url, headers={"User-Agent": "subset-fonts"}) - with urllib.request.urlopen(req, timeout=30) as r: - return r.read().decode("utf-8") - - -def visible_text(page: str) -> str: - page = re.sub(r"(?is)", " ", page) - page = re.sub(r"(?is)<(script|style|noscript|template)\b.*?", " ", page) - page = re.sub(r"(?s)<[^>]+>", " ", page) - return html.unescape(page) - - -def crawl(base: str) -> dict[str, str]: - pages = {"/": fetch(base + "/"), "/blog": fetch(base + "/blog")} - posts = sorted(set(re.findall(r'href="(/blog/[^"#?]+)"', pages["/"] + pages["/blog"]))) - for p in posts: - pages[p] = fetch(base + p) - return {path: visible_text(body) for path, body in pages.items()} - - -def with_case_forms(cps: set[int]) -> set[int]: - out = set(cps) - for cp in cps: - ch = chr(cp) - out |= {ord(c) for c in ch.lower() + ch.upper()} - return out - - -def page_codepoints(text: str) -> set[int]: - return {ord(c) for c in text if c not in "\n\r\t"} - - -# ---------------------------------------------------------------- build - -def ranges(cps: set[int]) -> str: - parts, sorted_cps, i = [], sorted(cps), 0 - while i < len(sorted_cps): - j = i - while j + 1 < len(sorted_cps) and sorted_cps[j + 1] == sorted_cps[j] + 1: - j += 1 - a, b = sorted_cps[i], sorted_cps[j] - parts.append(f"U+{a:04X}" if a == b else f"U+{a:04X}-{b:04X}") - i = j + 1 - return ", ".join(parts) - - -def check_reserved_font_name(font: TTFont, job: FontJob) -> None: - license_files = [GEIST_DIR / "LICENSE.txt"] - texts = [str(n) for n in font["name"].names if n.nameID in (0, 13)] - texts += [p.read_text() for p in license_files if p.exists()] - # The OFL text itself mentions "Reserved Font Name" in its definitions; a - # real reservation looks like `with Reserved Font Name "X"`. - if any(re.search(r'Reserved Font Names?\s+["“]', t) for t in texts): - sys.exit(f"{job.name}: the OFL declares a Reserved Font Name. Subsets are Modified Versions " - "and must be renamed (name IDs 1, 3, 4, 6, 16) before shipping.") - - -def drop_axis_below_default(font: TTFont, tag: str, lo: float, hi: float) -> None: - """Remove everything that only applies below an axis' default value. - - fontTools' instancer would do this too, but it densifies the IUP-optimized - gvar deltas, rounds them, and re-optimizes, which moves points by up to - half a unit at every weight. Deleting the negative-side regions leaves - every remaining delta untouched, so the font renders exactly as before at - the default and above. - """ - axis = next(a for a in font["fvar"].axes if a.axisTag == tag) - if lo != axis.defaultValue or hi != axis.maxValue: - sys.exit(f"{tag}: only clamping the minimum to the default ({axis.defaultValue}) with the maximum kept " - f"at {axis.maxValue} is lossless; asked for {lo}-{hi}") - axis.minValue = lo - font["fvar"].instances = [i for i in font["fvar"].instances if i.coordinates[tag] >= lo] - for glyph, tvs in font["gvar"].variations.items(): - font["gvar"].variations[glyph] = [tv for tv in tvs if tv.axes.get(tag, (0, 0, 0))[1] >= 0] - index = [a.axisTag for a in font["fvar"].axes].index(tag) - stores = [font[t].table.VarStore for t in ("HVAR", "MVAR", "GDEF") if t in font and getattr(font[t].table, "VarStore", None)] - for store in stores: - negative = {i for i, r in enumerate(store.VarRegionList.Region) if r.VarRegionAxis[index].PeakCoord < 0} - for data in store.VarData: - keep = [k for k, ri in enumerate(data.VarRegionIndex) if ri not in negative] - data.VarRegionIndex = [data.VarRegionIndex[k] for k in keep] - data.VarRegionCount = len(keep) - data.Item = [[row[k] for k in keep] for row in data.Item] - data.calculateNumShorts() - - -def make_subset(job: FontJob, cps: set[int]) -> bytes: - font = TTFont(job.source, recalcTimestamp=False) - for tag, (lo, hi) in job.axes.items(): - drop_axis_below_default(font, tag, lo, hi) - opts = subset.Options() - opts.layout_features = DEFAULT_FEATURES - opts.layout_scripts = ["*"] - opts.hinting = job.hinting - opts.name_IDs = NAME_IDS - opts.drop_tables += DROP_TABLES - opts.flavor = "woff2" - sub = subset.Subsetter(opts) - sub.populate(unicodes=sorted(cps)) - sub.subset(font) - buf = io.BytesIO() - font.recalcTimestamp = False - font.save(buf) - return buf.getvalue() - - -def ttf_bytes(data: bytes | Path) -> bytes: - font = TTFont(io.BytesIO(data) if isinstance(data, bytes) else data, recalcTimestamp=False) - font.flavor = None - buf = io.BytesIO() - font.save(buf) - return buf.getvalue() - - -class Shaper: - def __init__(self, data: bytes): - self.face = hb.Face(data) - self.font = hb.Font(self.face) - self.cache: dict = {} - - def set_weight(self, weight: int | None) -> None: - if weight is not None and "fvar" in TTFont(io.BytesIO(self.face.blob.data)): - self.font.set_variations({"wght": weight}) - self.cache.clear() - - def outline(self, gid: int): - if gid not in self.cache: - pen = RecordingPen() - self.font.draw_glyph_with_pen(gid, pen) - self.cache[gid] = pen.value - return self.cache[gid] - - def shape(self, text: str): - buf = hb.Buffer() - buf.add_str(text) - buf.guess_segment_properties() - hb.shape(self.font, buf, {}) - glyphs = [ - (pos.x_advance, pos.y_advance, pos.x_offset, pos.y_offset, self.outline(info.codepoint)) - for info, pos in zip(buf.glyph_infos, buf.glyph_positions) - ] - # HarfBuzz drops default-ignorables (soft hyphen) when the font has no - # space glyph, as extended files don't; either way nothing is drawn. - return [g for g in glyphs if g != (0, 0, 0, 0, [])] - - -def verify(job: FontJob, part: str, data: bytes, expected: set[int], source: TTFont, samples: list[str]) -> list[str]: - errors = [] - font = TTFont(io.BytesIO(data)) - cmap = set(font.getBestCmap()) - if cmap != expected: - errors.append(f"cmap mismatch: missing {ranges(expected - cmap) or '-'}, extra {ranges(cmap - expected) or '-'}") - if job.axes: - axes = {a.axisTag: (a.minValue, a.defaultValue, a.maxValue) for a in font["fvar"].axes} - for tag, (lo, hi) in job.axes.items(): - src_default = next(a.defaultValue for a in source["fvar"].axes if a.axisTag == tag) - if axes.get(tag) != (lo, src_default, hi): - errors.append(f"axis {tag} is {axes.get(tag)}, expected ({lo}, {src_default}, {hi})") - for t in ("GSUB", "GPOS"): - if t in font and font[t].table.FeatureList: - extra = {r.FeatureTag for r in font[t].table.FeatureList.FeatureRecord} - set(DEFAULT_FEATURES) - if extra: - errors.append(f"{t} kept non-default features {sorted(extra)}") - if not job.hinting: - left = [t for t in ("fpgm", "prep", "cvt ", "cvar", "hdmx", "VDMX") if t in font] - instructed = sum(1 for g in font["glyf"].glyphs.values() if getattr(g, "program", None) and g.program.getBytecode()) - if left or instructed: - errors.append(f"hinting left behind: tables {left}, {instructed} instructed glyphs") - for tag in ("head", "hhea", "OS/2"): - for attr in ("unitsPerEm", "ascent", "descent", "lineGap", "sTypoAscender", "sTypoDescender", "sTypoLineGap", "usWinAscent", "usWinDescent"): - if hasattr(source[tag], attr) and getattr(source[tag], attr) != getattr(font[tag], attr): - errors.append(f"{tag}.{attr} changed") - # next/font derives the metric-adjusted fallback from these advances. - if part == "core": - src_cmap, out_cmap = source.getBestCmap(), font.getBestCmap() - for ch in "abcdefghijklmnopqrstuvwxyz ": - if source["hmtx"][src_cmap[ord(ch)]][0] != font["hmtx"][out_cmap[ord(ch)]][0]: - errors.append(f"default advance of {ch!r} changed (would change the generated fallback face)") - - # Shape every character, every adjacent pair, and every same-file run of - # crawled text in both fonts; outlines and positions must match exactly. - original, subsetted = Shaper(ttf_bytes(job.source)), Shaper(ttf_bytes(data)) - chars = [chr(c) for c in sorted(expected)] - texts = chars + [a + b for a in chars for b in chars] + samples - for weight in job.used_weights or [None]: - original.set_weight(weight) - subsetted.set_weight(weight) - bad = [t for t in texts if original.shape(t) != subsetted.shape(t)] - if bad: - errors.append(f"wght {weight}: {len(bad)} of {len(texts)} strings shape differently, e.g. {bad[:5]!r}") - return errors - - -def runs_within(text: str, cps: set[int]) -> list[str]: - """Maximal runs of `text` whose characters all belong to `cps`.""" - out, cur = [], [] - for ch in text: - if ord(ch) in cps: - cur.append(ch) - else: - if len(cur) > 1: - out.append("".join(cur)) - cur = [] - if len(cur) > 1: - out.append("".join(cur)) - return out - - -def boundary_kerning(job: FontJob, core: set[int], ext: set[int]) -> int: - """Count core/extended character pairs the original font kerns or joins. - - Browsers shape each file separately, so those pairs lose kerning when one - side comes from the extended file. Reported, not fixed: it is inherent to - splitting a font. - """ - shaper = Shaper(ttf_bytes(job.source)) - shaper.set_weight(400 if job.axes else None) - width = {c: sum(g[0] for g in shaper.shape(chr(c))) for c in core | ext} - n = 0 - for a in sorted(core): - for b in sorted(ext): - for s, (x, y) in ((chr(a) + chr(b), (a, b)), (chr(b) + chr(a), (b, a))): - if sum(g[0] for g in shaper.shape(s)) != width[x] + width[y]: - n += 1 - return n - - -# ---------------------------------------------------------------- output - -TS_HEADER = """// Generated by scripts/subset-fonts.py. Do not edit by hand: rerun the script -// (see its docstring for when) and commit the output. -// -// Each font is split in two. The core file (ASCII + common punctuation) is -// preloaded; the extended file sits behind unicode-range and only downloads on -// pages that use one of its characters. -import type { CSSProperties } from "react"; -import localFont from "next/font/local"; -""" - -TS_FOOTER = """ -// The extended face has to come straight after the core face. Anything in -// between (like next/font's metric-adjusted fallback) would draw extended -// characters before the real font gets a chance to. -function stack(core: string, extended: string) { - const [primary, ...rest] = core.split(", "); - return [primary, extended, ...rest].join(", "); -} - -export const fontVariables = { -{vars} -} as CSSProperties; -""" - - -def ts_font(ident: str, file: str, job: FontJob, unicode_range: str, preload: bool) -> str: - lines = [f"const {ident} = localFont({{", f' src: "./{file}",', f' weight: "{job.weight}",'] - if not preload: - lines.append(" preload: false,") - if not preload or not job.adjust_font_fallback: - lines.append(" adjustFontFallback: false,") - if preload and job.fallback: - lines.append(" fallback: [") - lines += [f' "{f}",' for f in job.fallback] - lines.append(" ],") - lines.append(f' declarations: [{{ prop: "unicode-range", value: "{unicode_range}" }}],') - lines.append("});") - return "\n".join(lines) - - -def main() -> None: - ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) - ap.add_argument("--base", default=DEFAULT_BASE, help=f"site to crawl for used characters (default {DEFAULT_BASE})") - ap.add_argument("--check", action="store_true", help="only report used characters the committed fonts miss") - args = ap.parse_args() - - base = args.base.rstrip("/") - print(f"crawling {base} ...") - try: - pages = crawl(base) - except OSError as e: - sys.exit(f"could not crawl {base}: {e}\nStart the site (pnpm build && pnpm start) or pass --base.") - per_page = {p: page_codepoints(t) for p, t in pages.items()} - used = with_case_forms(set().union(*per_page.values())) - seen_on = Counter(cp for cps in per_page.values() for cp in cps) - common = {cp for cp, n in seen_on.items() if n * 2 >= len(per_page)} | per_page["/"] - print(f" {len(pages)} pages, {len(used)} distinct characters (with case forms)") - - if args.check: - manifest = json.loads((OUT_DIR / "manifest.json").read_text()) - missing = False - for job in JOBS: - source_cmap = set(TTFont(job.source).getBestCmap()) - have = {int(c, 16) for part in manifest["fonts"][job.name]["files"].values() for c in part["codepoints"]} - lacking = (used & source_cmap) - have - if lacking: - missing = True - print(f" {job.name}: rerun needed, not in committed files: " - + " ".join(f"{chr(c)}(U+{c:04X})" for c in sorted(lacking))) - sys.exit(1 if missing else 0) - - OUT_DIR.mkdir(parents=True, exist_ok=True) - geist_version = json.loads((GEIST_DIR / "package.json").read_text())["version"] - manifest: dict = {"generator": "scripts/subset-fonts.py", "crawled": base, "geist": geist_version, "fonts": {}} - decls, var_lines, failed = [], [], False - texts = list(pages.values()) - - for job in JOBS: - source = TTFont(job.source) - check_reserved_font_name(source, job) - cmap = set(source.getBestCmap()) - core = ASCII | CORE_PUNCTUATION | common - if job.core_latin: - core |= with_case_forms((LATIN_1 | LATIN_EXT_A) & cmap) - core &= cmap - ext = (with_case_forms((LATIN_1 | LATIN_EXT_A) & cmap) | used | EXTRA_EXT) & cmap - core - entry = { - "source": str(job.source.relative_to(GEIST_DIR)), - "sourceBytes": job.source.stat().st_size, - "sourceSha256": hashlib.sha256(job.source.read_bytes()).hexdigest(), - "axes": {k: list(v) for k, v in job.axes.items()}, - "hinting": job.hinting, - "files": {}, - } - for part, cps, preload in (("core", core, True), ("ext", ext, False)): - mapped = cps | shared_script_codepoints(source.getBestCmap(), cps) - if not preload: - mapped |= AUTOHINT_REFERENCE & cmap - data = make_subset(job, mapped) - samples = [r for t in texts for r in runs_within(t, cps)] - errors = verify(job, part, data, mapped, source, samples) - file = f"{job.name}-{part}.woff2" - (OUT_DIR / file).write_bytes(data) - font = TTFont(io.BytesIO(data)) - print(f" {file}: {len(data):>6} bytes, {len(font.getGlyphOrder())} glyphs, {len(cps)} codepoints" - + ("" if not errors else "\n FAIL " + "\n FAIL ".join(errors))) - failed |= bool(errors) - ident = job.ident + ("Core" if part == "core" else "Ext") - decls.append(ts_font(ident, file, job, ranges(cps), preload)) - entry["files"][part] = { - "file": file, - "bytes": len(data), - "glyphs": len(font.getGlyphOrder()), - "unicodeRange": ranges(cps), - "codepoints": [f"{c:04X}" for c in sorted(cps)], - } - entry["boundaryKernedPairs"] = boundary_kerning(job, core, ext) - manifest["fonts"][job.name] = entry - var_lines.append(f' "{job.css_var}": stack({job.ident}Core.style.fontFamily, {job.ident}Ext.style.fontFamily),') - - (OUT_DIR / "index.ts").write_text(TS_HEADER + "\n" + "\n\n".join(decls) + "\n" + TS_FOOTER.replace("{vars}", "\n".join(var_lines))) - (OUT_DIR / "manifest.json").write_text(json.dumps(manifest, indent=2, ensure_ascii=False) + "\n") - if failed: - sys.exit("verification failed; see FAIL lines above") - print(f"wrote {OUT_DIR.relative_to(ROOT)}/") - - -if __name__ == "__main__": - main() diff --git a/tailwind.config.js b/tailwind.config.js index 1371404..a404c4d 100644 --- a/tailwind.config.js +++ b/tailwind.config.js @@ -8,8 +8,10 @@ module.exports = { theme: { extend: { fontFamily: { - sans: ['var(--font-geist-sans)', 'system-ui', 'sans-serif'], - pixel: ['var(--font-geist-pixel-square)', 'monospace'], + // Early-web defaults: Times for everything, Courier for code. + sans: ['"Times New Roman"', 'Times', 'serif'], + serif: ['"Times New Roman"', 'Times', 'serif'], + mono: ['"Courier New"', 'Courier', 'ui-monospace', 'monospace'], }, }, },