feat: Next.js 后端 + SQLite + 暗门后台 /virtheart + 服务咨询页

后端(node:sqlite 零原生依赖,data/site.db,WAL + busy_timeout 抗并发):
- works / service_items / site_config / inquiries / admin_users / admin_sessions / captcha_challenges
- API:admin 登录登出/密码、作品与服务 CRUD、图片上传、留言箱、
  验证码 challenge/verify、咨询提交(一次性滑块令牌防重放)

后台 /virtheart(仅手动访问,未登录一律 307 → /virtheart/login):
- 服务端布局鉴权 + DB 会话(httpOnly cookie 7 天)+ CSRF 头校验
- 概览 / 作品(上传、网格预设、发布开关)/ 服务 / 留言箱 / 配置(全站文案)
- 设计与主站同语言:暗底点阵、mono、lime 选中,非传统后台模板

公开站:
- 路由组 (site) 隔离站点壳层;首页/服务页文案全部 DB 驱动即时生效
- /services 服务菜单 + 留言表单 + 全屏居中滑块拼图验证码(对齐缺口)
- 提交入 inquiries 并 SMTP(飞书 notify@)邮件通知 chenchun@virtheart.com
- Header 新增「服务」菜单;旧作品清理,空状态自动接管
- 根布局仅承载字体/全局样式,后台无站点壳层

验证:登录/CSRF/发布隔离/滑块容错/令牌单次消费/SMTP 真发全部通过;
lint 与基线一致(119 errors 均为存量)。
This commit is contained in:
2026-09-02 18:34:18 +08:00
parent 1a12c70462
commit d666cedfc6
46 changed files with 3527 additions and 211 deletions
+55
View File
@@ -0,0 +1,55 @@
import SmoothScroller from "@/components/dom/SmoothScroller";
import Header from "@/components/dom/Header";
import BackgroundGrid from "@/components/dom/BackgroundGrid";
import CustomScrollbar from "@/components/dom/CustomScrollbar";
import LoadingOverlay from "@/components/dom/LoadingOverlay";
import { HeroScene } from "@/components/canvas/HeroScene";
import { PasscodeAccessProvider } from "@/components/dom/PasscodeAccess";
import { FullscreenTransitionProvider } from "@/lib/routeTransition";
import RouteTransitionOverlay from "@/components/dom/RouteTransitionOverlay";
import { getPasscodeAccessServer } from "@/lib/passcodeServer";
import { getSiteConfig } from "@/lib/siteConfig";
import type { Metadata } from "next";
/**
* (site) 布局 — 公开站点的完整壳层:WebGL 画布、网格、平滑滚动、
* Header、路由过渡。/virtheart 后台不套用此壳层(纯净布局)。
* 站点文案从 site_config 读出后以 props 下发(Header 品牌/版权、
* 自我介绍槽位等),后台改完即时生效。
*/
export async function generateMetadata(): Promise<Metadata> {
const config = getSiteConfig();
return {
title: config.site_title,
description: config.site_description,
};
}
export default async function SiteLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
const [initialAccess, config] = await Promise.all([
getPasscodeAccessServer(),
Promise.resolve(getSiteConfig()),
]);
return (
<PasscodeAccessProvider initialAccess={initialAccess}>
<FullscreenTransitionProvider>
{/* Original stacking (1:1): the WebGL canvas host is a plain `fixed`
z-auto element first in the body; the grid overlay (z-20) comes
AFTER it in DOM order so it paints above the canvas, exactly like
the original's main > canvas + z-20 grid sibling. */}
<HeroScene />
<BackgroundGrid />
<SmoothScroller />
<Header brandName={config.brand_name} copyrightName={config.copyright_name} />
{children}
<CustomScrollbar />
<RouteTransitionOverlay />
<LoadingOverlay />
</FullscreenTransitionProvider>
</PasscodeAccessProvider>
);
}
+129
View File
@@ -0,0 +1,129 @@
import ScrambleReveal from "@/components/dom/ScrambleReveal";
import AboutMedia from "@/components/dom/AboutMedia";
import FooterSection from "@/components/dom/FooterSection";
import WorkSection from "@/components/dom/WorkSection";
import HyperSpaceSection from "@/components/dom/HyperSpaceSection";
import PasscodeRevealText from "@/components/dom/PasscodeRevealText";
import { getSiteConfig, listWorks } from "@/lib/siteConfig";
import type { WorkItem } from "@/lib/workItems";
/**
* 首页 — 结构复刻原站(haoqi_body.html),文案全部来自 site_config
*(/virtheart 后台「配置」可改,保存即生效);作品来自 works 表。
*/
export default async function Home() {
const config = getSiteConfig();
const items: WorkItem[] = listWorks(true)
.filter((w) => w.name && (w.image_url || w.href))
.map((w) => ({
name: w.name,
imageUrl: w.image_url,
hoverImageUrl: w.hover_image_url,
href: w.href || `/work/${w.slug}`,
year: w.year,
type: w.type,
gridClass: w.grid_class || "col-span-12 lg:col-span-6 xl:col-span-4",
codingProject: w.coding_project === 1,
passcodeProtected: w.passcode_protected === 1,
}));
return (
// NOTE: the original scrolls INSIDE <main> (its Lenis wraps the main
// container), which is what lets its position:sticky children pin. Our
// Lenis is window-level, so main must NOT be a scroll container —
// otherwise sticky (hyper-space section) never pins.
<main className="w-full">
<div>
{/* Banner Section */}
<div
data-section="banner"
className="grid grid-cols-12 grid-rows-[auto_1fr] px-4 lg:px-14 py-18 lg:py-24 w-full h-dvh lg:h-screen"
>
<div className="flex flex-col order-2 lg:order-1 lg:grid lg:grid-cols-12 col-span-12 font-mono text-base">
<span className="hidden lg:block lg:col-span-3 xl:col-span-2 lg:col-start-1 xl:col-start-1 p-2 font-sans font-medium text-[4svw] sm:text-2xl lg:text-3xl leading-tight">
<ScrambleReveal text={config.hero_line1} startDelayMs={300} letterDelayMs={10} />
<br />
<ScrambleReveal text={config.hero_line2} startDelayMs={300} letterDelayMs={10} />
</span>
<ScrambleReveal
className="hidden lg:block lg:col-span-3 xl:col-span-2 lg:col-start-4 xl:col-start-5 p-2 text-balance"
text={config.hero_tagline}
startDelayMs={300}
letterDelayMs={10}
/>
<PasscodeRevealText
className="col-span-12 lg:col-span-6 xl:col-span-4 lg:col-start-7 xl:col-start-9 mt-auto lg:mt-0 p-2"
prefix={config.intro_prefix}
suffix={config.intro_suffix}
brandName={config.brand_name}
/>
</div>
<div
className="flex flex-col self-end order-1 lg:order-2 col-span-12 px-2 font-bold text-[7.2svw] lg:text-[6svw] 2xl:text-[5svw] xl:text-[5.6svw] uppercase leading-none"
style={{ fontVariationSettings: '"wdth" 120' }}
>
<ScrambleReveal text={config.hero_big_1} startDelayMs={300} />
<ScrambleReveal text={config.hero_big_2} startDelayMs={500} />
<ScrambleReveal text={config.hero_big_3} startDelayMs={700} />
</div>
</div>
{/* Signature / About Section */}
<div className="grid grid-cols-12 px-4 lg:px-14 py-18 lg:py-24 lg:pb-28 w-full">
<AboutMedia />
<div className="flex flex-col justify-start items-start gap-6 col-span-12 sm:col-span-7 lg:col-span-8 sm:col-start-6 lg:col-start-5 text-base lg:text-xl leading-none">
<p
className="p-2 w-full text-l1 md:text-[4.2svw] text-xl leading-[1.3] md:leading-none select-text"
style={{
fontFamily:
'var(--font-tiktok), "MiSans", sans-serif',
}}
>
<span className="select-text">{config.about_p1}</span>
</p>
<p
className="p-2 w-full text-l2 md:text-[4.2svw] text-xl leading-[1.3] md:leading-none select-text"
style={{
fontFamily:
'var(--font-tiktok), "MiSans", sans-serif',
}}
>
<span className="select-text">
{config.about_p2}
<a
href={config.about_p2_link_href || "#selected-work"}
className="inline text-l1 underline underline-offset-[0.08em] decoration-solid decoration-(--label-3) transition-[text-decoration-color] duration-150 ease-out lg:[@media(hover:hover)]:hover:decoration-(--label-1)"
>
{config.about_p2_link_label}
</a>
{config.about_p2.endsWith(";") || config.about_p2.endsWith(",")
? "里记录了这些探索的痕迹。"
: ""}
</span>
</p>
</div>
</div>
{/* Selected Work grid (id="selected-work", WebGL image layers) */}
<WorkSection
items={items}
emptyText={{
headline: config.work_empty_headline,
note: config.work_empty_note,
ctaPrefix: config.work_empty_cta_prefix,
ctaSuffix: config.work_empty_cta_suffix,
ctaAction: config.work_empty_cta_action,
}}
contactEmail={config.contact_email}
/>
{/* Hyper-space scroll section (id="hyper-space"): the WebGL
hyperspace arrow (cursor.glb stripes) tracks this section's
screen rect and engulfs the viewport mid-scroll. */}
<HyperSpaceSection />
{/* Contact / Footer Section (#contact, data-section="footer") */}
<FooterSection contactEmail={config.contact_email} />
</div>
</main>
);
}
+299
View File
@@ -0,0 +1,299 @@
"use client";
/**
* 服务页(client)— 与主站同一设计语言:
* 大字 scramble 标题、编号服务菜单(NO.01…)、选择后展开留言表单,
* 提交触发全屏居中滑块验证码,通过后 POST /api/inquiry(后端入库 +
* 邮件通知 chenchun@virtheart.com)。
*/
import { useCallback, useMemo, useState } from "react";
import ScrambleReveal from "@/components/dom/ScrambleReveal";
import SliderCaptcha from "@/components/dom/SliderCaptcha";
import { useRouteTransitionController } from "@/lib/routeTransition";
import { CONTACT_EMAIL } from "@/lib/socials";
export type ServiceOption = {
slug: string;
title: string;
description: string;
priceNote: string;
};
const inputCls =
"w-full border border-line bg-b1 px-3 py-2.5 font-mono text-sm text-l1 outline-none transition-colors focus:border-l1 placeholder:text-l3";
const labelCls = "mb-1.5 block font-mono-2 text-xs uppercase tracking-widest text-l2";
const dotted =
"relative before:content-[''] before:absolute before:inset-0 before:border-2 before:border-dotted before:border-transparent before:pointer-events-none before:transition-colors before:duration-200 lg:hover:before:border-l1";
export default function ServicesClient({
headline,
submitNote,
services,
}: {
headline: string;
submitNote: string;
services: ServiceOption[];
}) {
const { startNavigation } = useRouteTransitionController();
const headlineLines = useMemo(
() => (headline || "可提供的服务|选择你需要的服务,留言告诉我").split("|"),
[headline]
);
const [selected, setSelected] = useState<ServiceOption | null>(null);
const [name, setName] = useState("");
const [contact, setContact] = useState("");
const [message, setMessage] = useState("");
const [captchaOpen, setCaptchaOpen] = useState(false);
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
const [doneId, setDoneId] = useState<number | null>(null);
const canSubmit = selected && name.trim() && contact.trim() && message.trim();
const startSubmit = useCallback(() => {
if (!canSubmit || submitting) return;
setError(null);
setCaptchaOpen(true);
}, [canSubmit, submitting]);
const onCaptchaVerified = useCallback(
async (submitToken: string) => {
if (!selected) return;
setSubmitting(true);
setError(null);
try {
const res = await fetch("/api/inquiry", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
submitToken,
name: name.trim(),
contact: contact.trim(),
serviceSlug: selected.slug,
serviceTitle: selected.title,
message: message.trim(),
}),
});
const data = (await res.json()) as { id?: number; error?: string };
if (!res.ok) {
setError(data.error ?? "提交失败,请重试");
setCaptchaOpen(false);
return;
}
setDoneId(data.id ?? 0);
setCaptchaOpen(false);
} catch {
setError("网络错误,请重试");
setCaptchaOpen(false);
} finally {
setSubmitting(false);
}
},
[selected, name, contact, message]
);
if (doneId !== null) {
return (
<article className="mx-auto px-6 py-18 lg:py-24 w-full max-w-[880px]">
<div className="pt-[14vh] flex flex-col gap-4">
<h1
className="font-bold text-[7.2svw] lg:text-[4.6svw] leading-none text-l1"
style={{ fontVariationSettings: '"wdth" 120' }}
>
<ScrambleReveal text="已收到" startDelayMs={200} scrambleColors={false} />
</h1>
<p className="font-mono-2 text-sm lg:text-base text-l2">
<ScrambleReveal
text={`留言编号 #${doneId} —— 我会尽快通过你留下的联系方式回复。`}
startDelayMs={400}
letterDelayMs={10}
/>
</p>
<div className="mt-4 flex gap-6 font-mono text-sm">
<button
type="button"
onClick={() => startNavigation("/")}
className={`${dotted} p-2 uppercase cursor-pointer text-l1`}
>
<ScrambleReveal text="← 返回首页" startDelayMs={300} scrambleColors={false} />
</button>
<button
type="button"
onClick={() => {
setDoneId(null);
setName("");
setContact("");
setMessage("");
setSelected(null);
}}
className={`${dotted} p-2 uppercase cursor-pointer text-l2`}
>
<ScrambleReveal text="再提交一条" startDelayMs={300} scrambleColors={false} />
</button>
</div>
</div>
</article>
);
}
return (
<article className="mx-auto px-6 py-18 lg:py-24 w-full max-w-[880px]">
<header className="pt-[10vh]">
<h1
className="font-bold text-[7.2svw] lg:text-[4.6svw] leading-none text-l1"
style={{ fontVariationSettings: '"wdth" 120' }}
>
{headlineLines.map((line, i) => (
<span key={i} className={i > 0 ? "block text-right lg:text-right" : "block"}>
<ScrambleReveal
text={line}
startDelayMs={200 + i * 220}
reverse={i > 0}
scrambleColors={false}
/>
</span>
))}
</h1>
<div className="mt-2 border-line border-b" />
<p className="pt-3 font-mono-2 text-xs text-l3">
<ScrambleReveal
text={`服务咨询 · 邮件直达 ${CONTACT_EMAIL}`}
startDelayMs={500}
letterDelayMs={10}
/>
</p>
</header>
{/* 服务菜单 */}
<section className="mt-12" aria-label="服务列表">
{services.length === 0 ? (
<p className="font-mono-2 text-sm text-l2 border border-dashed border-line p-8 text-center">
服务清单整理中——有需要可直接写邮件给我。
</p>
) : (
<ul className="flex flex-col divide-y divide-line border-y border-line">
{services.map((s, i) => {
const active = selected?.slug === s.slug;
return (
<li key={s.slug}>
<button
type="button"
onClick={() => setSelected(active ? null : s)}
aria-pressed={active}
className={`${dotted} w-full text-left cursor-pointer px-2 py-5 flex items-baseline gap-4 transition-colors ${
active ? "bg-[rgba(var(--label-d),0.04)]" : ""
}`}
>
<span className="font-mono-2 text-xs text-l3 tabular-nums shrink-0">
NO.{String(i + 1).padStart(2, "0")}
</span>
<span
className={`font-semibold text-lg lg:text-xl ${
active ? "text-l1" : "text-l2"
}`}
style={{ fontFamily: 'var(--font-tiktok), "MiSans", sans-serif' }}
>
{s.title}
</span>
{s.priceNote && (
<span className="ml-auto font-mono-2 text-xs text-l3 shrink-0">
{s.priceNote}
</span>
)}
<span
aria-hidden="true"
className={`font-mono text-sm shrink-0 transition-transform ${
active ? "rotate-45 text-l1" : "text-l3"
}`}
>
+
</span>
</button>
{active && s.description && (
<p className="px-2 pb-5 pl-12 font-mono-2 text-sm leading-relaxed text-l2 whitespace-pre-wrap">
{s.description}
</p>
)}
</li>
);
})}
</ul>
)}
</section>
{/* 留言表单 */}
<section className="mt-12 flex flex-col gap-5" aria-label="咨询表单">
<p className="font-mono-2 text-xs text-l3 uppercase tracking-widest">
{selected ? `咨询:${selected.title}` : "留言"}
</p>
<div className="grid grid-cols-1 gap-5 sm:grid-cols-2">
<div>
<label className={labelCls} htmlFor="svc-name">
怎么称呼你 *
</label>
<input
id="svc-name"
className={inputCls}
value={name}
onChange={(e) => setName(e.target.value)}
maxLength={40}
placeholder="姓名 / 昵称"
/>
</div>
<div>
<label className={labelCls} htmlFor="svc-contact">
联系方式 *
</label>
<input
id="svc-contact"
className={inputCls}
value={contact}
onChange={(e) => setContact(e.target.value)}
maxLength={80}
placeholder="邮箱 / 微信 / 手机号"
/>
</div>
</div>
<div>
<label className={labelCls} htmlFor="svc-message">
具体需求 *
</label>
<textarea
id="svc-message"
className={`${inputCls} min-h-32`}
value={message}
onChange={(e) => setMessage(e.target.value)}
maxLength={2000}
placeholder={
selected
? `关于「${selected.title}」,简单描述一下你的场景、周期和预算范围…`
: "简单描述一下你的场景、周期和预算范围…"
}
/>
<p className="mt-1.5 font-mono-2 text-xs text-l3">{submitNote}</p>
</div>
{error && (
<p className="border-l-2 border-selection pl-2 text-sm text-l1" role="alert">
{error}
</p>
)}
<button
type="button"
onClick={startSubmit}
disabled={!canSubmit || submitting}
className="w-full border border-l1 bg-l1 py-3.5 font-mono text-sm uppercase tracking-widest text-b1 transition-opacity hover:opacity-85 disabled:opacity-40 disabled:cursor-not-allowed cursor-pointer"
>
{submitting ? "提交中…" : "提交(需完成滑块验证)"}
</button>
</section>
<SliderCaptcha
open={captchaOpen}
onClose={() => !submitting && setCaptchaOpen(false)}
onVerified={onCaptchaVerified}
/>
</article>
);
}
+28
View File
@@ -0,0 +1,28 @@
import type { Metadata } from "next";
import ServicesClient from "./ServicesClient";
import { getSiteConfig, listServices } from "@/lib/siteConfig";
export const metadata: Metadata = {
title: "服务 · 北极新一",
description: "可提供的服务 — 选择你需要的服务,留言告诉我",
};
export const dynamic = "force-dynamic";
/** /services — 服务列表(server 读 DB)+ 咨询表单(滑块验证码)。 */
export default function ServicesPage() {
const config = getSiteConfig();
const services = listServices(true).map((s) => ({
slug: s.slug,
title: s.title,
description: s.description,
priceNote: s.price_note,
}));
return (
<ServicesClient
headline={config.services_hero}
submitNote={config.services_submit_note}
services={services}
/>
);
}
+33
View File
@@ -0,0 +1,33 @@
"use client";
/**
* /unlock/[scope] — the passcode unlock route (original
* buildPasscodeUnlockHref: "/unlock/2026?return=%2F"). A client page reading
* the scope segment and the `return` query, rendering the full-screen
* PasscodeUnlockScreen (original module 4278 `O`).
*/
import { Suspense } from "react";
import { useParams, useSearchParams } from "next/navigation";
import {
PasscodeUnlockScreen,
} from "@/components/dom/PasscodeUnlockScreen";
import {
sanitizePasscodeReturnTo,
scopeToPath,
} from "@/lib/passcode";
function UnlockInner() {
const params = useParams<{ scope: string }>();
const search = useSearchParams();
const scope = scopeToPath(String(params?.scope ?? ""));
const returnTo = sanitizePasscodeReturnTo(search.get("return"));
return <PasscodeUnlockScreen scope={scope} returnTo={returnTo} />;
}
export default function UnlockPage() {
return (
<Suspense fallback={null}>
<UnlockInner />
</Suspense>
);
}
+33
View File
@@ -0,0 +1,33 @@
import type { Metadata } from "next";
import { WORK_ARTICLES } from "@/content/workArticles";
import { isPasscodeProtectedPath } from "@/lib/passcode";
import { getPasscodeAccessServer } from "@/lib/passcodeServer";
/**
* Per-page <title>: the original detail route sets <title> to the work name
* (haoqi.design/reunimos → "Reunimos™"). The protected /2026 is gated on the
* server — without the access cookie its SSR title is "Protected"; once
* unlocked the server renders the article. We mirror both states. Lives in a
* segment layout so `params` contains the slug for both /work/[slug] and its
* root rewrite.
*/
export async function generateMetadata({
params,
}: {
params: Promise<{ slug: string }>;
}): Promise<Metadata> {
const { slug } = await params;
const path = `/${slug}`;
if (isPasscodeProtectedPath(path)) {
const access = await getPasscodeAccessServer();
if (!access[path]) return { title: "受保护内容" };
}
const article = WORK_ARTICLES[path];
return { title: article ? article.title : "北极新一©2026" };
}
export default function WorkLayout({
children,
}: Readonly<{ children: React.ReactNode }>) {
return children;
}
+618
View File
@@ -0,0 +1,618 @@
"use client";
/**
* Work detail pages — 1:1 port of the original MDX detail route
* (haoqi.design/reunimos et al.), including:
*
* - MdxHeading (chunk 5a5e6e9b module 31250): h2/h3/h4 with auto id,
* hover "#", click → scroll to anchor (-96 offset) + copy URL +
* history.replaceState.
* - MdxTableOfContents (module 78825): fixed-left nav, 2xl only,
* h1–h3 collection from article[data-mdx-article], active heading =
* last heading above 96px viewport line, click scrolls via
* scrollToMdxAnchorTarget (lerp .1).
* - CodeBlock (chunk 4d1355f module 93325): language label + COPY/COPIED
* button + numbered lines; the token HTML comes pre-highlighted from the
* original SSR (span.token with inline color styles mapped to
* --code-* CSS vars) and is injected as-is.
* - ArticleFooter (module 54450): Metadata dl (Last Updated / live viewport
* Dimensions / live Characters count of the article text) + Links
* (Home link; Work/Contact buttons navigate home through the transition
* with a pending-scroll anchor in sessionStorage, key "hq:pendingScrollAnchor").
*/
import { Suspense, useCallback, useEffect, useState } from "react";
import Link from "next/link";
import { useParams, usePathname } from "next/navigation";
import {
WORK_ARTICLES,
type ArticleBlock,
type InlineSeg,
} from "@/content/workArticles";
import { usePasscodeAllowed } from "@/components/dom/PasscodeAccess";
import { PasscodeUnlockScreen } from "@/components/dom/PasscodeUnlockScreen";
import { useRouteTransitionController } from "@/lib/routeTransition";
import { scrollEnv } from "@/lib/scrollEnv";
import ScrambleReveal from "@/components/dom/ScrambleReveal";
import CustomScrollbar from "@/components/dom/CustomScrollbar";
export const PENDING_SCROLL_ANCHOR_SESSION_KEY = "hq:pendingScrollAnchor";
const MDX_HEADING_ANCHOR_OFFSET_PX = 96;
const PROSE_CLASS =
"space-y-4 [&_p]:text-sm [&_p]:text-l1 [&_p]:leading-relaxed lg:[&_p]:text-base [&_ul]:list-disc [&_ul]:pl-5 [&_ul]:my-0 [&_ul]:space-y-0 [&_ol]:list-decimal [&_ol]:pl-5 [&_ol]:my-0 [&_ol]:space-y-0 [&_li]:text-l1 [&_li]:leading-relaxed [&_li::marker]:text-[var(--selection-bg)] [&_blockquote]:border-l-4 [&_blockquote]:border-[var(--selection-bg)] [&_blockquote]:pl-4 [&_blockquote]:text-l2 [&_blockquote_p]:text-l2 [&_blockquote_li]:text-l2 [&_blockquote_strong]:text-l2 [&_blockquote_em]:text-l2 [&_blockquote_a]:!text-l2 [&_blockquote_a]:underline [&_blockquote_a]:underline-offset-4 [&_blockquote_a]:decoration-[color:var(--label-3)] [&_blockquote_a]:transition-colors [&_blockquote_a]:lg:hover:!text-l1 [&_blockquote_a]:lg:hover:decoration-[color:var(--label-2)] [&_:not(pre)>code]:rounded [&_:not(pre)>code]:bg-[rgba(var(--label-d),0.08)] [&_:not(pre)>code]:px-1.5 [&_:not(pre)>code]:py-0.5 [&_:not(pre)>code]:font-mono [&_:not(pre)>code]:text-[0.9em] [&_:not(pre)>code]:text-l1 [&_hr]:my-8 [&_hr]:h-px [&_hr]:w-full [&_hr]:border-0 [&_hr]:bg-line [&_u]:no-underline [&_u]:pb-[6px] [&_u]:[box-decoration-break:clone] [&_u]:[-webkit-box-decoration-break:clone] [&_u]:[background-image:radial-gradient(circle_at_center,var(--color-l2)_0.65px,transparent_0.7px)] [&_u]:[background-size:5px_3px] [&_u]:[background-repeat:repeat-x] [&_u]:[background-position:left_bottom]";
/** Original MdxA link class (module 71289). */
const MDX_LINK_CLASS =
"text-[color:var(--label-1)] underline underline-offset-4 decoration-[color:var(--label-3)] transition-colors lg:hover:decoration-[color:var(--label-2)]";
/** Original heading classes map (module 31250 `a`). */
const HEADING_CLASSES: Record<number, string> = {
1: "mt-12 text-2xl leading-tight lg:mt-14 lg:text-[28px]",
2: "mt-10 text-xl leading-tight lg:mt-12 lg:text-2xl",
3: "mt-8 text-lg leading-snug lg:mt-10 lg:text-xl",
4: "mt-7 text-base leading-snug lg:mt-8 lg:text-lg",
5: "mt-6 text-sm leading-snug lg:mt-7 lg:text-[17px]",
6: "mt-6 text-sm leading-snug uppercase tracking-wide lg:mt-6 lg:text-base lg:normal-case lg:tracking-normal",
};
/** Original slugify (module 31250). */
function headingId(text: string): string | undefined {
return (
text
.trim()
.toLowerCase()
.replace(/[\s\u3000]+/g, "-")
.replace(/[^\w\u4e00-\u9fff-]+/g, "")
.replace(/-{2,}/g, "-")
.replace(/^-+|-+$/g, "") || undefined
);
}
/** Original scrollToMdxAnchorTarget (module 31250 `i`). */
function scrollToMdxAnchorTarget(el: HTMLElement) {
const container = scrollEnv.getContainerEl();
if (container) {
const top =
el.getBoundingClientRect().top -
container.getBoundingClientRect().top +
container.scrollTop -
MDX_HEADING_ANCHOR_OFFSET_PX;
scrollEnv.lenisScrollTo(Math.max(0, top), { lerp: 0.1 });
return;
}
el.scrollIntoView({ behavior: "smooth", block: "start" });
}
function MdxHeading({
level,
text,
id,
}: {
level: 2 | 3 | 4;
text: string;
id?: string;
}) {
const anchorId = id ?? headingId(text);
const onClick = useCallback(
async (e: React.MouseEvent) => {
if (!anchorId) return;
e.preventDefault();
const target = document.getElementById(anchorId);
if (target) scrollToMdxAnchorTarget(target);
const hash = `#${encodeURIComponent(anchorId)}`;
history.replaceState(null, "", hash);
const url = `${window.location.origin}${window.location.pathname}${window.location.search}${hash}`;
try {
await navigator.clipboard?.writeText(url);
} catch {}
},
[anchorId]
);
const cls = [
"group relative scroll-mt-24 font-semibold tracking-tight text-l1 [&:first-child]:mt-0",
HEADING_CLASSES[level],
]
.filter(Boolean)
.join(" ");
const Tag = `h${level}` as "h2";
const inner = anchorId ? (
<a
href={`#${encodeURIComponent(anchorId)}`}
onClick={onClick}
aria-label={`复制「${text}」的链接`}
className="relative inline-block text-inherit no-underline"
>
<span
aria-hidden="true"
className="absolute top-0 right-full mr-2 hidden text-l3 opacity-0 transition-opacity select-none lg:inline lg:group-hover:opacity-100 lg:hover:text-l1"
>
#
</span>
{text}
</a>
) : (
text
);
return (
<Tag id={anchorId} className={cls}>
{inner}
</Tag>
);
}
/** Inline segment renderer (MdxA class for links). */
function Inline({ segs }: { segs: InlineSeg[] }) {
return (
<>
{segs.map((s, i) => {
switch (s.t) {
case "link":
return (
<a
key={i}
href={s.href}
target="_blank"
rel="noopener noreferrer"
className={MDX_LINK_CLASS}
>
{s.v}
</a>
);
case "code":
return (
<code
key={i}
className="rounded px-1.5 py-0.5 font-mono text-[0.9em] text-l1 bg-[rgba(var(--label-d),0.08)]"
>
{s.v}
</code>
);
case "strong":
return (
<strong key={i} className="font-semibold">
{s.v}
</strong>
);
case "em":
return <em key={i}>{s.v}</em>;
default:
return <span key={i}>{s.v}</span>;
}
})}
</>
);
}
/** CodeBlock — original module 93325 chrome around the pre-highlighted HTML. */
function CodeBlock({
language,
label,
html,
text,
}: {
language: string;
label: string;
html: string;
text: string;
}) {
const [copied, setCopied] = useState(false);
const onCopy = useCallback(async () => {
if (!text) return;
try {
await navigator.clipboard.writeText(text);
setCopied(true);
window.setTimeout(() => setCopied(false), 1200);
} catch {
setCopied(false);
}
}, [text]);
return (
<div className="group my-6 overflow-hidden rounded-xl bg-[rgba(var(--label-d),0.03)]">
<div className="flex items-center justify-between px-3 py-2 shadow-[inset_0_-1px_0_0_var(--line)] lg:px-4">
<span className="px-1 font-mono text-xs tracking-wide text-(--label-3)">
{label}
</span>
<button
type="button"
onClick={onCopy}
aria-label={copied ? "已复制代码" : "复制代码"}
className="block before:absolute relative before:inset-0 before:border-2 before:border-dotted before:border-transparent before:pointer-events-none before:transition-colors before:duration-200 lg:hover:before:border-l1 cursor-pointer px-1 py-0.5 font-mono text-xs tracking-wide text-(--label-2) transition-colors lg:hover:text-(--label-1) focus-visible:text-(--label-1) focus-visible:outline-none focus-visible:before:border-l1"
>
{copied ? "已复制" : "复制"}
</button>
</div>
<pre className="overflow-x-auto px-4 py-2 font-mono text-xs leading-relaxed text-(--label-1) lg:px-5 lg:py-2.5 lg:text-sm">
<code
className={`language-${language}`}
// Pre-highlighted token HTML extracted from the original SSR
// (span.token, inline color styles → --code-* vars).
dangerouslySetInnerHTML={{ __html: html }}
/>
</pre>
</div>
);
}
function Block({ block }: { block: ArticleBlock }) {
switch (block.type) {
case "p":
return (
<p>
<Inline segs={block.segs} />
</p>
);
case "h2":
return <MdxHeading level={2} text={block.text} id={block.id} />;
case "h3":
return <MdxHeading level={3} text={block.text} id={block.id} />;
case "h4":
return <MdxHeading level={4} text={block.text} id={block.id} />;
case "code":
return (
<CodeBlock
language={block.language}
label={block.label}
html={block.html}
text={block.text}
/>
);
case "img":
// eslint-disable-next-line @next/next/no-img-element -- original uses plain img with cursor-zoom-in
return (
<img
src={block.src}
alt=""
crossOrigin="anonymous"
loading="lazy"
decoding="async"
className="block w-full h-auto cursor-zoom-in select-none border border-line bg-[rgba(var(--label-d),0.05)]"
/>
);
case "hr":
return <hr className="my-8 h-px w-full border-0 bg-line" />;
case "list":
return block.ordered ? (
<ol className="list-decimal my-0 pl-5 space-y-0">
{block.items.map((li, i) => (
<li key={i} className="text-l1 leading-relaxed">
<Inline segs={li} />
</li>
))}
</ol>
) : (
<ul className="list-disc my-0 pl-5 space-y-0">
{block.items.map((li, i) => (
<li key={i} className="text-l1 leading-relaxed">
<Inline segs={li} />
</li>
))}
</ul>
);
case "quote":
return (
<blockquote className="border-l-4 border-(--selection-bg) pl-4 text-l2">
<p className="text-l2">
<Inline segs={block.segs} />
</p>
</blockquote>
);
default:
return null;
}
}
/** MdxTableOfContents — original module 78825 (2xl-only fixed left nav). */
function MdxTableOfContents() {
const [headings, setHeadings] = useState<
{ id: string; label: string; level: number }[]
>([]);
const [active, setActive] = useState<string | null>(null);
useEffect(() => {
const collect = () => {
const article = document.querySelector("article[data-mdx-article]");
if (!(article instanceof HTMLElement)) {
setHeadings([]);
return;
}
const els = article.querySelectorAll("h1, h2, h3");
const next: { id: string; label: string; level: number }[] = [];
els.forEach((el) => {
if (!(el instanceof HTMLElement)) return;
const tag = el.tagName.toLowerCase();
if (tag !== "h1" && tag !== "h2" && tag !== "h3") return;
const id = el.id;
if (!id) return;
const level = Number(tag.slice(1));
// Label = textContent minus aria-hidden spans (the "#" anchor).
const clone = el.cloneNode(true) as HTMLElement;
clone
.querySelectorAll('span[aria-hidden="true"]')
.forEach((s) => s.remove());
const label = (clone.textContent ?? "").replace(/\s+/g, " ").trim();
next.push({ id, label, level });
});
setHeadings(next);
};
collect();
const t1 = window.setTimeout(collect, 0);
const t2 = window.setTimeout(collect, 150);
return () => {
window.clearTimeout(t1);
window.clearTimeout(t2);
};
}, []);
useEffect(() => {
if (headings.length === 0) {
setActive(null);
return;
}
const update = () => {
const els = headings
.map((h) => document.getElementById(h.id))
.filter((el): el is HTMLElement => el !== null);
if (els.length === 0) return;
let current = els[0];
for (const el of els) {
if (el.getBoundingClientRect().top <= MDX_HEADING_ANCHOR_OFFSET_PX)
current = el;
}
setActive(current.id || headings[0].id);
};
update();
window.addEventListener("scroll", update, { passive: true });
window.addEventListener("resize", update);
const article = document.querySelector<HTMLElement>(
"article[data-mdx-article]"
);
const ro =
"undefined" !== typeof ResizeObserver && article
? new ResizeObserver(update)
: null;
if (article) ro?.observe(article);
const t = window.setTimeout(update, 100);
return () => {
window.removeEventListener("scroll", update);
window.removeEventListener("resize", update);
ro?.disconnect();
window.clearTimeout(t);
};
}, [headings]);
if (headings.length === 0) return null;
return (
<nav
aria-label="本页目录"
className="pointer-events-auto fixed inset-y-0 left-0 z-20 hidden min-h-0 w-[320px] flex-col overflow-hidden 2xl:flex pl-14 pr-2"
>
<div className="flex flex-col flex-1 min-h-0 overflow-hidden">
<div className="flex-1 min-h-0 overflow-y-auto overscroll-y-contain no-scrollbar">
<div className="box-border flex min-h-full flex-col py-7">
<div className="flex min-h-0 flex-1 flex-col justify-center gap-1 p-2 text-sm leading-snug text-l2">
{headings.map((h, i) => {
const pad = h.level === 1 ? 0 : h.level === 2 ? 8 : 16;
const href = `#${encodeURIComponent(h.id)}`;
return (
<a
key={`${h.id}-${i}`}
href={href}
title={h.label}
aria-current={h.id === active ? "location" : undefined}
className={`block min-w-0 shrink-0 cursor-pointer truncate rounded-md py-0.5 transition-colors hover:text-l1 ${h.id === active ? "text-l1" : "text-l2"}`}
style={{ paddingLeft: `${pad}px` }}
onClick={(e) => {
e.preventDefault();
setActive(h.id);
const el = document.getElementById(h.id);
if (el) scrollToMdxAnchorTarget(el);
history.replaceState(null, "", href);
}}
>
{h.label}
</a>
);
})}
</div>
</div>
</div>
</div>
</nav>
);
}
/** Original ArticleFooter (module 54450). */
function ArticleFooter({ updated }: { updated: string }) {
const pathname = usePathname();
const { startNavigation } = useRouteTransitionController();
const [viewport, setViewport] = useState({ w: 0, h: 0 });
const [charCount, setCharCount] = useState<number | null>(null);
const footerRef = useCallback((el: HTMLElement | null) => {
if (!el) return;
const article = el.closest("[data-mdx-article]");
if (article instanceof HTMLElement) {
const clone = article.cloneNode(true) as HTMLElement;
clone.querySelector("[data-mdx-footer]")?.remove();
setCharCount([...(clone.textContent ?? "").trim()].length);
}
}, []);
useEffect(() => {
const update = () =>
setViewport({ w: window.innerWidth, h: window.innerHeight });
update();
window.addEventListener("resize", update);
return () => window.removeEventListener("resize", update);
}, []);
const goAnchor = useCallback(
(anchor: string) => {
if (pathname === "/") scrollEnv.lenisScrollTo(anchor, { lerp: 0.1 });
else {
sessionStorage.setItem(PENDING_SCROLL_ANCHOR_SESSION_KEY, anchor);
startNavigation("/");
}
},
[pathname, startNavigation]
);
const dotted =
"block before:absolute relative before:inset-0 before:border-2 before:border-dotted before:border-transparent before:pointer-events-none before:transition-colors before:duration-200 lg:hover:before:border-l1 inline-block -mx-1 px-1 py-0.5 text-l2 lg:hover:text-l1 text-sm transition-colors";
return (
<footer
ref={footerRef}
data-mdx-footer="true"
className="bg-[rgba(var(--label-d),0.03)] mt-16 p-4 lg:p-6 rounded-xl"
>
<div className="mb-5 font-sans font-semibold text-l1 text-base">
元信息
</div>
<dl className="gap-x-6 gap-y-6 grid grid-cols-2 lg:grid-cols-3">
{(
[
["最后更新", updated],
["视口尺寸", `${viewport.w}×${viewport.h}`],
[
"字数",
charCount !== null ? charCount.toLocaleString("zh-CN") : "—",
],
] as const
).map(([label, value]) => (
<div key={label} className="flex flex-col gap-1.5">
<dt className="font-sans font-semibold text-l1 text-sm">{label}</dt>
<dd>
<ScrambleReveal
text={value}
className="font-mono tabular-nums text-l2 text-sm"
startDelayMs={300}
scrambleColors={false}
/>
</dd>
</div>
))}
</dl>
<div className="my-6 border-line border-t border-dashed" />
<div className="gap-x-6 gap-y-4 grid grid-cols-2 lg:grid-cols-3">
<div className="hidden lg:block font-sans font-semibold text-l1 text-sm">
链接
</div>
<div className="flex flex-col items-start gap-1 font-mono">
<Link href="/" className={`${dotted} text-left`}>
<ScrambleReveal text="首页" startDelayMs={300} scrambleColors={false} />
</Link>
<button
type="button"
onClick={() => goAnchor("#selected-work")}
className={`${dotted} text-left cursor-pointer`}
>
<ScrambleReveal text="作品" startDelayMs={300} scrambleColors={false} />
</button>
<button
type="button"
onClick={() => goAnchor("#contact")}
className={`${dotted} text-left cursor-pointer`}
>
<ScrambleReveal text="联系" startDelayMs={300} scrambleColors={false} />
</button>
</div>
<div className="flex flex-col items-start gap-1 font-mono">
{["抖音", "微信", "小红书"].map((label) => (
<a key={label} href="#" className={dotted}>
<ScrambleReveal text={label} startDelayMs={300} scrambleColors={false} />
</a>
))}
</div>
</div>
</footer>
);
}
function Article({ slug }: { slug: string }) {
const article = WORK_ARTICLES[slug];
if (!article) {
return (
<article className="mx-auto px-6 py-18 lg:py-24 w-full max-w-[880px] text-l1">
<header className="pt-[10vh]">
<h1 className="font-bold text-3xl! text-l1 lg:text-5xl! leading-tight tracking-tight">
404
</h1>
<p className="mt-1 text-l2! text-sm! lg:text-base! leading-relaxed">
该作品的文章尚未完成。
</p>
<div className="mt-2 border-line border-b" />
<p className="pt-3 text-l2! text-sm! lg:text-base! leading-relaxed">
<Link className="underline underline-offset-4" href="/">
← 返回首页
</Link>
</p>
</header>
</article>
);
}
return (
<>
<MdxTableOfContents />
<article
data-mdx-article="true"
className="mx-auto px-6 py-18 lg:py-24 w-full max-w-[880px] text-l1"
>
<header className="pt-[10vh]">
<h1
className="font-bold text-3xl! text-l1 lg:text-5xl! leading-tight tracking-tight"
style={{ fontVariationSettings: '"wdth" 120' }}
>
{article.title}
</h1>
<p className="mt-1 tabular-nums text-l2! text-sm! lg:text-base! leading-relaxed">
{article.date}
</p>
<div className="mt-2 border-line border-b" />
<p className="pt-3 text-l2! text-sm! lg:text-base! leading-relaxed">
{article.year}
</p>
</header>
<div className={PROSE_CLASS}>
{article.blocks.map((b, i) => (
<Block key={i} block={b} />
))}
{article.iframe && (
<iframe
width="840"
height="600"
src={article.iframe.src}
title={article.iframe.title}
allowFullScreen
className="mt-8 w-full border-0"
/>
)}
</div>
<ArticleFooter updated={article.date} />
</article>
</>
);
}
function WorkDetailInner() {
const params = useParams<{ slug: string }>();
const raw = String(params?.slug ?? "");
// /work/2026 is the passcode-protected scope; the others map back to the
// original slugs (/work/reunimos → content key "/reunimos").
const slug = `/${raw}`;
const allowed = usePasscodeAllowed(slug);
if (!allowed) {
// Protected scope (e.g. /2026) renders the unlock screen in place,
// exactly like the original detail route.
return <PasscodeUnlockScreen scope={slug} returnTo={slug} />;
}
return (
<>
<Article slug={slug} />
<CustomScrollbar />
</>
);
}
export default function WorkDetailPage() {
return (
<Suspense fallback={null}>
<WorkDetailInner />
</Suspense>
);
}