Files
personal/components/dom/WorkSection.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

412 lines
14 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";
import { useEffect, useMemo, useRef, useState } from "react";
import {
SELECTED_WORK_SECTION_ID,
WORK_ITEMS as STATIC_WORK_ITEMS,
type WorkItem,
} from "@/lib/workItems";
import {
getLayerTarget,
setLayerDef,
touchLayerRegistry,
} from "@/lib/imageLayers";
import { usePasscodeAllowed, usePasscodeAccessLookup } from "@/components/dom/PasscodeAccess";
import { buildPasscodeUnlockHref } from "@/lib/passcode";
import { useRouteTransitionController } from "@/lib/routeTransition";
import ScrambleReveal from "@/components/dom/ScrambleReveal";
import { CONTACT_EMAIL, SOCIAL_LINKS } from "@/lib/socials";
/**
* Selected Work grid — ported from the original section `h` (chunk
* 2689132c4e070b68.js, exports SELECTED_WORK_SECTION_ID / default):
*
* - `<section id="selected-work" className="px-4 lg:px-14 py-18 lg:py-24 w-full">`
* with an inner `grid grid-cols-12` whose `rowGap` is the measured column
* width (container.clientWidth / 12, tracked by ResizeObserver).
* - Each card is `<article className={gridClass}>` wrapping a `group block
* space-y-3 p-2` anchor (next Link for internal routes, <a> for external).
* - The visual is NOT a DOM <img>: the anchor's first child is an
* aspect-ratio placeholder div registered as a WebGL image-layer target;
* the canvas-side ImageLayers projects imageUrl/hoverImageUrl onto its
* screen rect (curl + negative reveal + hover dot mask).
* - Aspect ratios come from preloading each imageUrl and reading
* naturalWidth/naturalHeight into a module-level cache (original `o`).
* - Passcode-protected items are filtered exactly like the original
* `WORK_ITEMS.filter(t => !t.passcodeProtected || lookup(t.href))`: the
* 小红书 entry only appears once /2026 is unlocked.
*
* 空状态(EmptyWorkState):WORK_ITEMS 过滤后为空(包括只挂锁定条目)时
* 渲染「编号叙事」占位——大字「第一批作品正在打磨」+ NO.00x 骨架卡 +
* 社交/邮箱 CTA。占位卡不注册 WebGL 图层(纯 DOM 点阵纹理),加入第一个
* 真实作品后自动切回正常网格,零迁移成本。
*/
// Module-level cache mirroring the original `o` (persists across remounts).
const ratioCache: Record<string, string> = {};
const DEFAULT_EMPTY_NOTE = "把它们当作这个站的「加载动画」——完成后会在这里逐个揭晓。";
/** 作品卡片右下角类型角标(post 不显示角标)。 */
const TYPE_LABELS: Record<WorkItem["type"], string> = {
post: "文章",
tools: "工具",
event: "活动",
};
/** 空状态占位卡 — 复用真实网格的不对称节奏(大卡 + 两张小卡)。 */
const EMPTY_PLACEHOLDERS = [
{ no: "NO.001", gridClass: "col-span-12 lg:col-span-8 lg:col-start-3" },
{
no: "NO.002",
gridClass:
"col-span-6 lg:col-start-5 lg:col-span-4 xl:col-start-6 xl:col-span-3",
},
{
no: "NO.003",
gridClass:
"col-span-6 lg:col-start-9 lg:col-span-4 xl:col-start-10 xl:col-span-3",
},
] as const;
export type WorkSectionProps = {
/** 服务端从 works 表读出的作品(published,camelCase 已映射) */
items?: WorkItem[];
/** 空状态文案(site_config.work_empty_*,后台可改) */
emptyText?: {
headline: string;
note: string;
ctaPrefix: string;
ctaSuffix: string;
ctaAction: string;
};
/** 空状态 CTA 邮箱(site_config.contact_email) */
contactEmail?: string;
};
export default function WorkSection({
items,
emptyText,
contactEmail,
}: WorkSectionProps = {}) {
const [ratios, setRatios] = useState<Record<string, string>>({ ...ratioCache });
const [colWidth, setColWidth] = useState(0);
const gridRef = useRef<HTMLDivElement | null>(null);
const lookup = usePasscodeAccessLookup();
// 服务端传入的作品优先;直接渲染 <WorkSection />(无 props)时回退为
// 静态 WORK_ITEMS(当前为空数组 → 空状态占位)。
const sourceItems = useMemo(
() => items ?? STATIC_WORK_ITEMS,
[items]
);
// Original `f` — passcode-protected items stay hidden until unlocked.
const visibleItems = useMemo(
() =>
sourceItems.filter((item) => !item.passcodeProtected || lookup(item.href)),
[sourceItems, lookup]
);
// Register canvas layer defs for every item (locked ones simply have no
// target on screen; idempotent data write — version bump happens once
// targets exist, in the effect).
useMemo(() => {
for (const item of sourceItems) {
setLayerDef(item.href, {
imageUrl: item.imageUrl,
hoverImageUrl: item.hoverImageUrl,
});
}
}, [sourceItems]);
useEffect(() => {
touchLayerRegistry();
}, []);
// rowGap = column width (original RO on the grid container).
useEffect(() => {
const el = gridRef.current;
if (!el) return;
const measure = () => setColWidth(el.clientWidth / 12);
measure();
const ro = new ResizeObserver(measure);
ro.observe(el);
return () => ro.disconnect();
}, []);
// Preload images → natural aspect ratios (original effect).
useEffect(() => {
let cancelled = false;
const update = (imageUrl: string, w: number, h: number) => {
if (cancelled || w <= 0 || h <= 0) return;
const ratio = `${w} / ${h}`;
if (ratioCache[imageUrl] !== ratio) ratioCache[imageUrl] = ratio;
setRatios((prev) => (prev[imageUrl] === ratio ? prev : { ...prev, [imageUrl]: ratio }));
};
const images = visibleItems.map((item) => {
const img = new Image();
img.decoding = "async";
img.onload = () => update(item.imageUrl, img.naturalWidth, img.naturalHeight);
img.src = item.imageUrl;
if (img.complete && img.naturalWidth > 0 && img.naturalHeight > 0) {
update(item.imageUrl, img.naturalWidth, img.naturalHeight);
}
return img;
});
return () => {
cancelled = true;
for (const img of images) img.onload = null;
};
// eslint-disable-next-line react-hooks/exhaustive-deps -- ratios-only effect; matches the original mount-time preload
}, [visibleItems]);
// 空状态:过滤后没有任何可见作品(包括只挂锁定条目的情况)。
const showEmpty = visibleItems.length === 0;
return (
<section
id={SELECTED_WORK_SECTION_ID}
className="px-4 lg:px-14 py-18 lg:py-24 w-full"
>
<div
ref={gridRef}
className="grid grid-cols-12 w-full"
style={{ rowGap: `${colWidth}px` }}
>
{showEmpty ? (
<EmptyWorkState
emptyText={emptyText}
contactEmail={contactEmail}
/>
) : (
visibleItems.map((item) => (
<WorkCard key={item.href} item={item} ratio={ratios[item.imageUrl]} />
))
)}
</div>
</section>
);
}
/**
* 空作品区 — 编号叙事占位:
* 「第一批作品 / 正在打磨」大字 + NO.00x 骨架卡 + 社交/邮箱 CTA。
* 占位卡刻意保留真实卡片的网格位置与标签行结构,但视觉是纯 DOM 点阵 +
* 虚线框(不注册 WebGL 图层),hover 不会触发 canvas 投影。
*/
function EmptyWorkState({
emptyText,
contactEmail,
}: {
emptyText?: WorkSectionProps["emptyText"];
contactEmail?: string;
}) {
const headlineLines = (
emptyText?.headline ?? "第一批作品|正在打磨"
).split("|");
const email = contactEmail ?? CONTACT_EMAIL;
return (
<>
<div className="col-span-12 flex flex-col gap-4 p-2">
<p
className="font-bold text-[7.2svw] lg:text-[4svw] leading-none"
style={{ fontVariationSettings: '"wdth" 120' }}
>
{headlineLines.map((line, i) => (
<span key={i}>
<ScrambleReveal
text={line}
startDelayMs={300 + i * 200}
reverse={i > 0}
scrambleColors={i === 0}
/>
{i < headlineLines.length - 1 && <br />}
</span>
))}
<span
aria-hidden="true"
className="ml-3 inline-block bg-l1 h-[0.72em] w-[0.45ch] align-baseline caret-blink"
/>
</p>
{(emptyText?.note ?? DEFAULT_EMPTY_NOTE) && (
<p className="font-mono-2 text-sm lg:text-base text-l2">
<ScrambleReveal
text={emptyText?.note ?? DEFAULT_EMPTY_NOTE}
startDelayMs={700}
letterDelayMs={10}
/>
</p>
)}
</div>
{EMPTY_PLACEHOLDERS.map((p) => (
<PlaceholderCard key={p.no} no={p.no} gridClass={p.gridClass} />
))}
<div className="col-span-12 flex flex-wrap items-center gap-x-2 gap-y-1 p-2 font-mono-2 text-sm lg:text-base text-l2">
<ScrambleReveal
text={emptyText?.ctaPrefix ?? "过程记录同步在"}
startDelayMs={900}
/>
{SOCIAL_LINKS.map((s) => (
<a
key={s.key}
href={s.href}
target="_blank"
rel="noopener noreferrer"
className="text-l1 underline underline-offset-4 decoration-(--label-3) transition-[text-decoration-color] duration-150 ease-out lg:hover:decoration-(--label-1)"
>
<ScrambleReveal text={s.label} startDelayMs={300} scrambleColors={false} />
</a>
))}
<span aria-hidden="true">{emptyText?.ctaSuffix ?? ",或者"}</span>
<a
href={`mailto:${email}`}
className="text-l1 underline underline-offset-4 decoration-(--label-3) transition-[text-decoration-color] duration-150 ease-out lg:hover:decoration-(--label-1)"
>
<ScrambleReveal
text={emptyText?.ctaAction ?? "写信给我"}
startDelayMs={300}
scrambleColors={false}
/>
</a>
</div>
</>
);
}
/** 占位骨架卡 — 点阵纹理 + 虚线框 + NO.00x 编号,纯展示不可点击。 */
function PlaceholderCard({ no, gridClass }: { no: string; gridClass: string }) {
return (
<article className={gridClass}>
<div className="space-y-3 p-2">
<div
aria-hidden="true"
className="relative aspect-square w-full border border-dashed border-line select-none"
style={{
backgroundImage:
"radial-gradient(var(--grid-dot) 1px, transparent 1px)",
backgroundSize: "14px 14px",
}}
>
<span className="top-0 left-0 absolute p-2 font-mono-2 text-xs text-l3">
{no}
</span>
<span className="top-0 right-0 absolute p-2 font-mono-2 text-xs text-l3">
制作中
</span>
<span className="inset-0 absolute flex justify-center items-center gap-1.5 text-l2">
<ScrambleReveal
text="即将揭晓"
startDelayMs={300}
letterDelayMs={40}
/>
<span
aria-hidden="true"
className="block bg-l2 w-px h-4 caret-blink"
/>
</span>
</div>
<div className="flex justify-between items-center gap-3 min-w-0 text-xs lg:text-sm uppercase">
<span className="flex-1 min-w-0 truncate">
<ScrambleReveal
text="作品占位 · 敬请期待"
startDelayMs={300}
scrambleColors={false}
/>
</span>
<div className="flex items-center gap-2 sm:gap-3 font-mono-2 tabular-nums whitespace-nowrap shrink-0">
<span>20XX</span>
</div>
</div>
</div>
</article>
);
}
function WorkCard({ item, ratio }: { item: WorkItem; ratio?: string }) {
const external = item.href.startsWith("http://") || item.href.startsWith("https://");
const cls = "group block space-y-3 p-2";
const label = `${item.name} - ${item.year}${external ? "(外部链接)" : ""}`;
const target = getLayerTarget(item.href);
const { startNavigation } = useRouteTransitionController();
const allowed = usePasscodeAllowed(item.href);
const body = (
<>
<div
ref={(el) => {
target.current = el;
}}
aria-hidden="true"
className="relative w-full pointer-events-none select-none"
style={{ aspectRatio: ratio ?? "1 / 1" }}
>
{item.codingProject && (
<span
className="top-0 right-0 z-10 absolute bg-selection px-1 font-mono-2 text-black text-xs uppercase pointer-events-none select-none"
aria-hidden="true"
>
代码项目
</span>
)}
</div>
<div className="flex justify-between items-center gap-3 min-w-0 text-xs lg:text-sm uppercase">
<span className="flex-1 min-w-0 truncate">{item.name}</span>
<div className="flex items-center gap-2 sm:gap-3 font-mono-2 tabular-nums whitespace-nowrap shrink-0">
<span>{item.year}</span>
{item.type !== "post" && (
<span className="hidden lg:inline-flex items-center gap-1" aria-hidden="true">
<span>{TYPE_LABELS[item.type] ?? item.type}</span>
<span>↗</span>
</span>
)}
</div>
</div>
</>
);
return (
<article className={item.gridClass ?? "col-span-12 lg:col-span-6 xl:col-span-4"}>
{external ? (
<a
href={item.href}
target="_blank"
rel="noopener noreferrer"
className={cls}
aria-label={label}
>
{body}
</a>
) : (
// Internal detail routes (/reunimos, /inspire_mono, …) navigate
// through the fullscreen cover/reveal transition (original Link
// wrapper module 80894: preventDefault + startNavigation; same-path
// clicks scroll back to top).
<a
href={item.href}
className={cls}
aria-label={label}
onClick={(e) => {
if (e.defaultPrevented) return;
if (e.button !== 0 || e.metaKey || e.altKey || e.ctrlKey || e.shiftKey)
return;
e.preventDefault();
if (!allowed) {
const scope = item.href.replace(/^\//, "");
window.location.assign(
buildPasscodeUnlockHref(scope, item.href)
);
return;
}
// Detail pages are rewritten to root paths (/reunimos …),
// 1:1 with the original URLs; only the passcode scope keeps
// its own route.
startNavigation(item.href);
}}
>
{body}
</a>
)}
</article>
);
}