Files
personal/app/(site)/work/[slug]/page.tsx
T
virtheart d666cedfc6 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 均为存量)。
2026-09-02 18:34:18 +08:00

619 lines
22 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"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>
);
}