Files
personal/app/work/[slug]/page.tsx
T
virtheart 3957e36c41 feat: 详情页 MDX 组件 1:1(目录/锚点/代码块/页脚)与首页层叠修复
- 详情页补齐原站 MDX 组件:左侧目录(2xl 固定定位、滚动高亮 top≤96、
  点击平滑滚动)、标题锚点(hover #、点击复制链接 + replaceState)、
  代码块(语言标签 + COPY/COPIED + 原站 prism token HTML 按行号渲染,
  --code-* 配色变量)、页脚 Metadata(实时视口尺寸 / 正文字符数)与
  Work/Contact 按钮(sessionStorage hq:pendingScrollAnchor → 首页过渡后
  滚动到对应区块,SmoothScroller 消费)
- content/workArticles.ts 重新提取:内联 strong/em/code 片段、标题 id、
  代码块语言 + 高亮 HTML + 纯文本(bs4 全量解析 6 篇文章)
- 详情页不再显示十字网格(BackgroundGrid 按 pathname 门控,置于全部
  hooks 之后避免 hook 数量变化崩溃)
- 首页层叠修复:WebGL 容器改为原站的 top-0 left-0 -z-1 fixed(此前
  z-auto fixed 按 CSS 绘制顺序盖住 banner 文案与作品说明文字),footer
  改为原站的 z-10 relative,body 背景移至 html 根节点(否则普通流 body
  背景会盖住 -z-1 场景)
2026-09-01 22:15:12 +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={`Copy link to ${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 ? "Copied code" : "Copy code"}
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 uppercase 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 ? "COPIED" : "COPY"}
</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">
Metadata
</div>
<dl className="gap-x-6 gap-y-6 grid grid-cols-2 lg:grid-cols-3">
{(
[
["Last Updated", updated],
["Dimensions", `${viewport.w}×${viewport.h}`],
[
"Characters",
charCount !== null ? charCount.toLocaleString("en-US") : "—",
],
] 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">
Links
</div>
<div className="flex flex-col items-start gap-1 font-mono">
<Link href="/" className={`${dotted} text-left`}>
<ScrambleReveal text="Home" startDelayMs={300} scrambleColors={false} />
</Link>
<button
type="button"
onClick={() => goAnchor("#selected-work")}
className={`${dotted} text-left cursor-pointer`}
>
<ScrambleReveal text="Work" startDelayMs={300} scrambleColors={false} />
</button>
<button
type="button"
onClick={() => goAnchor("#contact")}
className={`${dotted} text-left cursor-pointer`}
>
<ScrambleReveal text="Contact" startDelayMs={300} scrambleColors={false} />
</button>
</div>
<div className="flex flex-col items-start gap-1 font-mono">
{["Twitter/X", "Figma", "GitHub"].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">
No article for this work yet.
</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="/">
← Home
</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>
);
}