feat: 移植首页 passcode 彩蛋(■■■■■■ → /unlock/2026 解锁 TikTok 品牌名与隐藏作品卡)

- lib/passcode.ts:module 58156/28116 移植——primaryPasscodePath("/2026")、buildPasscodeUnlockHref("/unlock/2026?return=%2F")、slotCount:4、品牌名按原站 charCode-1 混淆解码(TikTok)、锁定占位符与字符/散段样式类
- PasscodeAccess.tsx:module 4278 移植——access store(useSyncExternalStore + passcode-access-changed 事件驱动刷新)、usePasscodeAllowed/usePasscodeAccessLookup、submit/logout(POST /api/passcode)
- PasscodeUnlockScreen:4 格圆环输入(inset ring label-1/label-3 + caret-blink 光标)、满 4 位自动提交、错误 shake(WAAPI 等价原 framer x 关键帧抖动)、成功 'Access granted' 600ms 后 replace 回来源、已解锁进入立即跳回
- layout 挂 PasscodeAccessProvider(服务端 cookies 读初始 access);新增 /api/passcode GET/POST(httpOnly cookie 持久化,解锁码经 PASSCODE_CODE 配置,默认 2026)与 /unlock/[scope] 页
- ScrambleReveal 支持 slot part({length,scramble,className,settled}):打散期显示占位字符、收尾替换为交互节点,1:1 原版语义
- 首页 about 段换 c9/c2 移植:锁定点击跳解锁页、解锁显示 TikTok、长按 500ms/右键 confirm 重锁;WorkSection 按 access 过滤,解锁后 TikTok 卡(tt01/tt02 素材)出现在首位
- CDP 全流程验证:锁定→解锁→持久化→重锁 循环 + 错码抖动清空 + 卡片数 10↔11
This commit is contained in:
2026-09-01 19:21:52 +08:00
parent 71825606a4
commit 8ce5471c25
13 changed files with 864 additions and 72 deletions
+81
View File
@@ -0,0 +1,81 @@
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import {
PASSCODE_COOKIE_NAME,
PASSCODE_PROTECTED_PATHS,
emptyPasscodeAccessState,
isPasscodeProtectedPath,
normalizePath,
} from "@/lib/passcode";
/**
* /api/passcode — the original site's access endpoint (module 4278 calls it):
* GET → current access state, e.g. {"/2026": false}
* POST {scope, code} → validate the code, set the access cookie
* POST {action: "logout"} → clear the access cookie
*
* The unlock code itself is a server secret (the original keeps it off the
* client bundle). Configure it with PASSCODE_CODE (4 characters, matching
* PASSCODE.slotCount); the default mirrors the theme year.
*/
const PASSCODE_CODE = process.env.PASSCODE_CODE ?? "2026";
const ONE_YEAR = 60 * 60 * 24 * 365;
function readAccess(request: NextRequest): Record<string, boolean> {
const raw = request.cookies.get(PASSCODE_COOKIE_NAME)?.value;
if (!raw) return emptyPasscodeAccessState();
try {
const parsed = JSON.parse(decodeURIComponent(raw)) as Record<string, unknown>;
const state = emptyPasscodeAccessState();
for (const key of Object.keys(state)) {
state[key] = parsed[key] === true;
}
return state;
} catch {
return emptyPasscodeAccessState();
}
}
export async function GET(request: NextRequest) {
return NextResponse.json(readAccess(request));
}
export async function POST(request: NextRequest) {
let body: { scope?: string; code?: string; action?: string };
try {
body = (await request.json()) as typeof body;
} catch {
return NextResponse.json({ ok: false }, { status: 400 });
}
const response = NextResponse.json({ ok: true });
if (body.action === "logout") {
response.cookies.delete(PASSCODE_COOKIE_NAME);
return response;
}
const scope = body.scope ? normalizePath(body.scope) : "";
if (!scope || !isPasscodeProtectedPath(scope)) {
return NextResponse.json({ ok: false }, { status: 400 });
}
if (typeof body.code !== "string" || body.code !== PASSCODE_CODE) {
return NextResponse.json({ ok: false }, { status: 401 });
}
const access = readAccess(request);
access[scope] = true;
for (const key of PASSCODE_PROTECTED_PATHS) {
if (!(key in access)) access[key] = false;
}
response.cookies.set({
name: PASSCODE_COOKIE_NAME,
value: encodeURIComponent(JSON.stringify(access)),
httpOnly: true,
sameSite: "lax",
path: "/",
maxAge: ONE_YEAR,
});
return response;
}
+18
View File
@@ -73,6 +73,24 @@ html::-webkit-scrollbar, body::-webkit-scrollbar {
.hsst-char { .hsst-char {
display: inline-block; display: inline-block;
} }
/* Passcode unlock screen (original ease-66 token + caret-blink). */
.ease-66 {
transition-timing-function: cubic-bezier(0.66, 0, 0.01, 1);
}
@keyframes caret-blink {
0%,
100% {
opacity: 1;
}
50% {
opacity: 0;
}
}
.caret-blink {
animation: caret-blink 1s step-end infinite;
}
@keyframes hsstFadeIn { @keyframes hsstFadeIn {
0% { 0% {
opacity: 0; opacity: 0;
+6 -1
View File
@@ -6,6 +6,8 @@ import Header from "@/components/dom/Header";
import BackgroundGrid from "@/components/dom/BackgroundGrid"; import BackgroundGrid from "@/components/dom/BackgroundGrid";
import LoadingOverlay from "@/components/dom/LoadingOverlay"; import LoadingOverlay from "@/components/dom/LoadingOverlay";
import { HeroScene } from "@/components/canvas/HeroScene"; import { HeroScene } from "@/components/canvas/HeroScene";
import { PasscodeAccessProvider } from "@/components/dom/PasscodeAccess";
import { getPasscodeAccessServer } from "@/lib/passcodeServer";
const tiktokSans = localFont({ const tiktokSans = localFont({
src: "./fonts/TikTokSans.ttf", src: "./fonts/TikTokSans.ttf",
@@ -30,20 +32,23 @@ export const metadata: Metadata = {
description: "Digital Product Designer & Builder © 2026", description: "Digital Product Designer & Builder © 2026",
}; };
export default function RootLayout({ export default async function RootLayout({
children, children,
}: Readonly<{ }: Readonly<{
children: React.ReactNode; children: React.ReactNode;
}>) { }>) {
const initialAccess = await getPasscodeAccessServer();
return ( return (
<html lang="en" className={`${tiktokSans.variable} ${geistMono.variable} ${departureMono.variable}`}> <html lang="en" className={`${tiktokSans.variable} ${geistMono.variable} ${departureMono.variable}`}>
<body className="min-h-screen relative"> <body className="min-h-screen relative">
<PasscodeAccessProvider initialAccess={initialAccess}>
<BackgroundGrid /> <BackgroundGrid />
<HeroScene /> <HeroScene />
<SmoothScroller /> <SmoothScroller />
<Header /> <Header />
{children} {children}
<LoadingOverlay /> <LoadingOverlay />
</PasscodeAccessProvider>
</body> </body>
</html> </html>
); );
+2 -11
View File
@@ -3,13 +3,13 @@ import AboutMedia from "@/components/dom/AboutMedia";
import FooterSection from "@/components/dom/FooterSection"; import FooterSection from "@/components/dom/FooterSection";
import WorkSection from "@/components/dom/WorkSection"; import WorkSection from "@/components/dom/WorkSection";
import HyperSpaceSection from "@/components/dom/HyperSpaceSection"; import HyperSpaceSection from "@/components/dom/HyperSpaceSection";
import PasscodeRevealText from "@/components/dom/PasscodeRevealText";
/** /**
* Page content matching the original DOM (haoqi_body.html): * Page content matching the original DOM (haoqi_body.html):
* - banner section (h-dvh) with meta row + big title, all scramble-revealed * - banner section (h-dvh) with meta row + big title, all scramble-revealed
* - signature/about section (kept simple) * - signature/about section (kept simple)
*/ */
const PASSCODE_LENGTH = 6;
export default function Home() { export default function Home() {
return ( return (
@@ -36,16 +36,7 @@ export default function Home() {
startDelayMs={300} startDelayMs={300}
letterDelayMs={10} letterDelayMs={10}
/> />
<ScrambleReveal <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" />
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"
startDelayMs={300}
letterDelayMs={10}
parts={[
"I'm Haoqi Wen, leading Design Engineering and AI exploration at ",
"■".repeat(PASSCODE_LENGTH),
", engineering, and AI at scale. Outside work, I build design tools for team efficiency.",
]}
/>
</div> </div>
<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 relative z-30" 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 relative z-30"
+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>
);
}
+140
View File
@@ -0,0 +1,140 @@
"use client";
/**
* PasscodeAccessProvider + hooks — 1:1 port of the original module 4278
* (d59f7a97fb1c563f.js): a module-level store (the original React context
* store object) with a snapshot + listener set, window-event driven refresh,
* and the same POST contract against /api/passcode.
*/
import {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useRef,
useSyncExternalStore,
} from "react";
import {
PASSCODE_ACCESS_CHANGED_EVENT,
PASSCODE_PROTECTED_PATHS,
emptyPasscodeAccessState,
isPasscodeProtectedPath,
normalizePath,
workHrefToPath,
type PasscodeAccessState,
} from "@/lib/passcode";
async function fetchAccess(): Promise<PasscodeAccessState> {
const res = await fetch("/api/passcode", { cache: "no-store" });
return res.ok ? ((res.json() as unknown) as Promise<PasscodeAccessState>) : emptyPasscodeAccessState();
}
async function postAccess(body: {
scope?: string;
code?: string;
action?: string;
}): Promise<Response> {
return fetch("/api/passcode", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
}
type Store = {
snapshot: PasscodeAccessState;
listeners: Set<() => void>;
refresh: () => Promise<void>;
};
const AccessContext = createContext<Store | null>(null);
function createStore(initialAccess: PasscodeAccessState): Store {
return {
snapshot: initialAccess,
listeners: new Set(),
async refresh() {
const next = await fetchAccess();
const keys = Object.keys(next);
const same =
keys.length === Object.keys(this.snapshot).length &&
keys.every((k) => next[k] === this.snapshot[k]);
if (same) return;
this.snapshot = next;
this.listeners.forEach((l) => l());
},
};
}
export function PasscodeAccessProvider({
initialAccess,
children,
}: {
initialAccess: PasscodeAccessState;
children: React.ReactNode;
}) {
const storeRef = useRef<Store | null>(null);
if (!storeRef.current) storeRef.current = createStore(initialAccess);
useEffect(() => {
const store = storeRef.current;
if (!store) return;
const onChange = () => void store.refresh();
window.addEventListener(PASSCODE_ACCESS_CHANGED_EVENT, onChange);
return () => window.removeEventListener(PASSCODE_ACCESS_CHANGED_EVENT, onChange);
}, []);
return <AccessContext.Provider value={storeRef.current}>{children}</AccessContext.Provider>;
}
/** notifyPasscodeAccessChanged (original `L`). */
export function notifyPasscodeAccessChanged() {
window.dispatchEvent(new CustomEvent(PASSCODE_ACCESS_CHANGED_EVENT));
}
/** submitPasscodeUnlock (original `B`). */
export function submitPasscodeUnlock(scope: string, code: string): Promise<Response> {
return postAccess({ scope, code });
}
/** logoutPasscodeAccess (original `j`). */
export async function logoutPasscodeAccess(opts?: { reload?: boolean }): Promise<boolean> {
const res = await postAccess({ action: "logout" });
if (!(res as Response & { ok: boolean }).ok) return false;
if (opts?.reload) window.location.reload();
notifyPasscodeAccessChanged();
return true;
}
/** usePasscodeAccessLookup (original `F`): (href) => unlocked?. */
export function usePasscodeAccessLookup() {
const store = useContext(AccessContext);
const fallback = useMemo(() => emptyPasscodeAccessState(), []);
const snapshot = useSyncExternalStore(
useCallback(
(notify: () => void) => {
if (!store) return () => {};
store.listeners.add(notify);
return () => store.listeners.delete(notify);
},
[store]
),
() => store?.snapshot ?? fallback,
() => store?.snapshot ?? fallback
);
return useCallback(
(href: string) => {
const path = workHrefToPath(href) ?? href;
// Original: `!S(e) || (s[e] ?? false)` — unprotected paths always pass.
if (!isPasscodeProtectedPath(path)) return true;
return snapshot[path] ?? false;
},
[snapshot]
);
}
/** usePasscodeAllowed (original `I`). */
export function usePasscodeAllowed(path: string): boolean {
return usePasscodeAccessLookup()(path);
}
+137
View File
@@ -0,0 +1,137 @@
"use client";
/**
* About-paragraph passcode easter egg — 1:1 port of the original components
* `c9` + `c2` (chunk 4d3f3b68dbbde33a.js):
*
* - Locked: the brand label slot scrambles as "■■■■■■" (each char wrapped,
* PASSCODE_LOCKED_CHAR_CLASS); clicking navigates through the route
* transition to /unlock/2026?return=%2F.
* - Unlocked: the slot settles to the "TikTok" button span — long-press
* (500ms) or context-menu re-locks (confirm + reload).
* - The reveal sequence (ScrambleReveal) treats the label as a slot part, so
* its 6 characters participate in the per-char scramble timing.
*/
import { useCallback, useRef } from "react";
import { useRouter } from "next/navigation";
import ScrambleReveal from "@/components/dom/ScrambleReveal";
import {
logoutPasscodeAccess,
usePasscodeAllowed,
} from "@/components/dom/PasscodeAccess";
import {
PASSCODE_LOCKED_CHAR_CLASS,
PASSCODE_LOCKED_SCRAMBLE_CLASS,
buildPasscodeUnlockHref,
passcodeLockedPlaceholderText,
primaryPasscodePath,
revealBrandLabel,
revealBrandLabelLength,
} from "@/lib/passcode";
const SCOPE = primaryPasscodePath(); // "/2026"
const BRAND = revealBrandLabel(); // "TikTok"
const BRAND_LEN = revealBrandLabelLength(); // 6
function RevealLabelButton() {
const allowed = usePasscodeAllowed(SCOPE);
const router = useRouter();
const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const clearTimer = useCallback(() => {
if (timerRef.current) {
clearTimeout(timerRef.current);
timerRef.current = null;
}
}, []);
const relock = useCallback(async () => {
if (
window.confirm("Lock protected content again? You will need the passcode to view it.")
) {
await logoutPasscodeAccess({ reload: true });
}
}, []);
if (!allowed) {
// TODO(route-system): go through useRouteTransitionController().startNavigation
const go = () => {
router.push(buildPasscodeUnlockHref(SCOPE, "/"));
};
return (
<span
role="button"
tabIndex={0}
aria-label="Protected — enter passcode to reveal"
className="inline-flex items-baseline gap-[0.12em] mx-[0.06em] align-baseline cursor-pointer select-text"
onClick={go}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
go();
}
}}
>
{passcodeLockedPlaceholderText()
.split("")
.map((ch, i) => (
<span key={i} aria-hidden="true" className={PASSCODE_LOCKED_CHAR_CLASS}>
{ch}
</span>
))}
</span>
);
}
return (
<span
role="button"
tabIndex={0}
aria-label={`${BRAND} — long press to lock again`}
className="inline mx-[0.06em] align-baseline cursor-default select-none"
onPointerDown={() => {
clearTimer();
timerRef.current = setTimeout(() => void relock(), 500);
}}
onPointerUp={clearTimer}
onPointerLeave={clearTimer}
onPointerCancel={clearTimer}
onContextMenu={(e) => {
e.preventDefault();
void relock();
}}
>
{BRAND}
</span>
);
}
export default function PasscodeRevealText({
className,
startDelayMs = 300,
letterDelayMs = 10,
}: {
className?: string;
startDelayMs?: number;
letterDelayMs?: number;
}) {
const allowed = usePasscodeAllowed(SCOPE);
const parts = [
"I'm Haoqi Wen, leading Design Engineering and AI exploration at ",
{
length: BRAND_LEN,
scramble: allowed ? BRAND : passcodeLockedPlaceholderText(),
className: allowed ? undefined : PASSCODE_LOCKED_SCRAMBLE_CLASS,
settled: <RevealLabelButton />,
},
", engineering, and AI at scale. Outside work, I build design tools for team efficiency.",
];
return (
<ScrambleReveal
className={className}
parts={parts}
startDelayMs={startDelayMs}
letterDelayMs={letterDelayMs}
/>
);
}
+155
View File
@@ -0,0 +1,155 @@
"use client";
/**
* PasscodeUnlockScreen — 1:1 port of the original module 4278 component `O`
* (d59f7a97fb1c563f.js):
*
* - A fixed z-1000 bg-b1 overlay; a hidden text input holds the code.
* - PASSCODE.slotCount circles (inset ring: label-1 filled/current,
* label-3 empty); the current slot shows a blinking caret.
* - At slotCount characters the code auto-submits: failure shakes the row
* (x keyframes 0,-10,10,-8,8,-4,4,0 over 0.5s) and clears; success flips
* the hint to "Access granted" and navigates to the return path after
* 600ms (router.replace, like the original startNavigation(...,{replace})).
* - If the scope is already unlocked the screen immediately returns.
* - Renders null when the scope is not passcode-protected.
*/
import { useEffect, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import {
PASSCODE,
isPasscodeProtectedPath,
normalizePath,
sanitizePasscodeReturnTo,
scopeToPath,
} from "@/lib/passcode";
import {
notifyPasscodeAccessChanged,
submitPasscodeUnlock,
usePasscodeAllowed,
} from "@/components/dom/PasscodeAccess";
/** Original framer `T.start({x:[0,-10,10,-8,8,-4,4,0], duration:.5, easeInOut})`. */
function shake(el: HTMLElement | null): Promise<void> {
if (!el || typeof el.animate !== "function") return Promise.resolve();
const anim = el.animate(
{
transform: ["translateX(0)", "translateX(-10px)", "translateX(10px)", "translateX(-8px)", "translateX(8px)", "translateX(-4px)", "translateX(4px)", "translateX(0)"],
},
{ duration: 500, easing: "ease-in-out" }
);
return anim.finished.then(
() => undefined,
() => undefined
);
}
export function PasscodeUnlockScreen({
scope,
returnTo,
}: {
scope: string;
returnTo?: string | null;
}) {
const router = useRouter();
const path = scopeToPath(scope);
const protectedScope = isPasscodeProtectedPath(path);
const target = sanitizePasscodeReturnTo(returnTo) ?? path;
const allowed = usePasscodeAllowed(path);
const inputRef = useRef<HTMLInputElement | null>(null);
const rowRef = useRef<HTMLDivElement | null>(null);
const [code, setCode] = useState("");
const [status, setStatus] = useState<"idle" | "success">("idle");
const slotCount = PASSCODE.slotCount;
const inputId = `passcode-${path}`;
useEffect(() => {
if (!protectedScope) return;
if (allowed) {
router.replace(target);
return;
}
inputRef.current?.focus();
}, [target, protectedScope, allowed, router]);
if (!protectedScope) return null;
const onChange = (value: string) => {
if (status === "success") return;
const next = value.slice(0, slotCount);
setCode(next);
if (next.length === slotCount) {
void (async () => {
const res = await submitPasscodeUnlock(path, next);
if (!res.ok) {
await shake(rowRef.current);
setCode("");
inputRef.current?.focus();
return;
}
notifyPasscodeAccessChanged();
setStatus("success");
window.setTimeout(() => {
router.replace(target);
}, 600);
})();
}
};
return (
<main
className="z-1000 fixed inset-0 flex justify-center items-center bg-b1"
onClick={() => inputRef.current?.focus()}
>
<label className="sr-only" htmlFor={inputId}>
Passcode for {path}
</label>
<input
ref={inputRef}
id={inputId}
type="text"
autoComplete="off"
spellCheck={false}
value={code}
onChange={(e) => onChange(e.target.value)}
className="absolute opacity-0 w-px h-px"
/>
<div className="relative" aria-hidden="true">
<span
className={`-top-10 left-1/2 absolute font-mono text-sm whitespace-nowrap -translate-x-1/2 select-none transition-colors ${
status === "success" ? "text-l1" : "text-l3"
}`}
>
{status === "success" ? "Access granted" : "Please enter passcode"}
</span>
<div ref={rowRef} className="flex gap-3">
{Array.from({ length: slotCount }).map((_, i) => {
const filled = i < code.length;
const current = i === code.length;
return (
<div
key={i}
className="flex justify-center items-center rounded-full w-12 h-12 font-mono tabular-nums text-l1 text-lg transition-shadow duration-300 ease-66"
style={{
boxShadow: `inset 0 0 0 4px ${
filled || current ? "var(--label-1)" : "var(--label-3)"
}`,
}}
>
{filled ? (
code[i]
) : current ? (
<span className="block bg-l1 w-px h-5 caret-blink" aria-hidden="true" />
) : null}
</div>
);
})}
</div>
</div>
</main>
);
}
/** Kept for parity with the original import surface (normalizePath helper). */
export { normalizePath };
+105 -26
View File
@@ -4,7 +4,7 @@ import { useEffect, useMemo, useRef, useState } from "react";
/** /**
* 1:1 re-implementation of the original scramble-reveal text (chunk * 1:1 re-implementation of the original scramble-reveal text (chunk
* 2689132c4e070b68.js component `d`): * 2689132c4e070b68.js module 71358 component `d`):
* *
* - charset `ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*+-=?/<>[]{}` picked * - charset `ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*+-=?/<>[]{}` picked
* randomly per render while a character is "scrambling" * randomly per render while a character is "scrambling"
@@ -15,15 +15,62 @@ import { useEffect, useMemo, useRef, useState } from "react";
* - refresh tick every 40ms; the whole text settles at * - refresh tick every 40ms; the whole text settles at
* startDelayMs + (n-1)*letterDelayMs + 4*letterDelayMs * startDelayMs + (n-1)*letterDelayMs + 4*letterDelayMs
* - starts once when the element enters the viewport (threshold 0.1) * - starts once when the element enters the viewport (threshold 0.1)
*
* Parts accept strings or **slot objects** `{ length, scramble?, className?,
* settled? }` (original slot parts): while scrambling, slot characters show
* `scramble` (default: spaces) with the same per-char delays; once settled
* the slot renders `settled` (a React node, e.g. the passcode button) in
* place of the characters.
*/ */
const CHARSET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*+-=?/<>[]{}"; const CHARSET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*+-=?/<>[]{}";
const COLORS_LIGHT = ["#c0fe04", "#607F02"]; const COLORS_LIGHT = ["#c0fe04", "#607F02"];
const randomChar = () => CHARSET[Math.floor(Math.random() * CHARSET.length)]; const randomChar = () => CHARSET[Math.floor(Math.random() * CHARSET.length)];
export type ScrambleSlotPart = {
/** Number of characters this slot occupies in the reveal sequence. */
length: number;
/** Placeholder characters shown while the slot is scrambling. */
scramble?: string;
/** Class for the slot wrapper span. */
className?: string;
/** React node rendered once the reveal has fully settled. */
settled?: React.ReactNode;
};
type Part = string | ScrambleSlotPart;
type NormalizedPart =
| { kind: "text"; value: string }
| {
kind: "slot";
length: number;
scramble: string;
settled?: React.ReactNode;
className?: string;
};
function normalizeParts(parts: Part[] | undefined, text: string | undefined): NormalizedPart[] {
return (parts ?? [text ?? ""]).map((p) => {
if (typeof p === "string") return { kind: "text" as const, value: p };
const length = Math.max(0, p.length);
const scramble = (p.scramble ?? (length > 0 ? " ".repeat(length) : ""))
.slice(0, length)
.padEnd(length, " ");
return {
kind: "slot" as const,
length,
scramble,
settled: p.settled,
className: p.className,
};
});
}
type Props = { type Props = {
text?: string; text?: string;
parts?: string[]; parts?: Part[];
className?: string; className?: string;
startDelayMs?: number; startDelayMs?: number;
letterDelayMs?: number; letterDelayMs?: number;
@@ -41,8 +88,8 @@ export default function ScrambleReveal({
scrambleColors = true, scrambleColors = true,
reverse = false, reverse = false,
}: Props) { }: Props) {
const strings = useMemo( const normalized = useMemo(
() => (parts ? parts : [text ?? ""]), () => normalizeParts(parts, text),
[parts, text] [parts, text]
); );
const ref = useRef<HTMLSpanElement>(null); const ref = useRef<HTMLSpanElement>(null);
@@ -50,7 +97,10 @@ export default function ScrambleReveal({
const [startedAt, setStartedAt] = useState<number | null>(null); const [startedAt, setStartedAt] = useState<number | null>(null);
const [elapsed, setElapsed] = useState(0); const [elapsed, setElapsed] = useState(0);
const F = strings.join("").length; const F = normalized.reduce(
(acc, p) => acc + (p.kind === "text" ? p.value.length : p.length),
0
);
const phaseLen = 2 * letterDelayMs; // j const phaseLen = 2 * letterDelayMs; // j
const scrambleWindow = 2 * phaseLen; // D const scrambleWindow = 2 * phaseLen; // D
const total = startDelayMs + Math.max(0, F - 1) * letterDelayMs + scrambleWindow; const total = startDelayMs + Math.max(0, F - 1) * letterDelayMs + scrambleWindow;
@@ -94,53 +144,82 @@ export default function ScrambleReveal({
if (settled || !entered) { if (settled || !entered) {
return ( return (
<span ref={ref} className={className}> <span ref={ref} className={className}>
{strings.map((s, i) => ( {normalized.map((p, i) =>
<span key={i}>{entered ? s : ""}</span> p.kind === "text" ? (
))} <span key={`text-${i}`}>{entered ? p.value : ""}</span>
) : (
<span key={`slot-${i}`} className={p.className}>
{entered ? p.settled : null}
</span>
)
)}
</span> </span>
); );
} }
// recompute random chars on each elapsed tick // recompute random chars on each elapsed tick
let index = 0; let index = 0;
const totalChars = strings.join("").length;
return ( return (
<span ref={ref} className={className}> <span ref={ref} className={className}>
{strings.map((s, si) => ( {normalized.map((p, pi) => {
<span key={si}> if (p.kind === "text") {
{s.split("").map((ch, ci) => { return (
<span key={`text-${pi}`}>
{p.value.split("").map((ch, ci) => {
const i = index++; const i = index++;
// Original `reverse`: character delays run last→first. // Original `reverse`: character delays run last→first.
const order = reverse ? totalChars - 1 - i : i; const order = reverse ? F - 1 - i : i;
if (ch === "\n") return <br key={`br-${si}-${ci}`} />; if (ch === "\n") return <br key={`br-${pi}-${ci}`} />;
if (ch === " ") return <span key={`sp-${si}-${ci}`}> </span>; if (ch === " ") return <span key={`sp-${pi}-${ci}`}> </span>;
const n = order * letterDelayMs; const n = order * letterDelayMs;
if (V < n) { if (V < n) {
return ( return (
<span key={`c-${si}-${ci}`} style={{ opacity: 0 }}> <span key={`c-${pi}-${ci}`} style={{ opacity: 0 }}>
{ch} {ch}
</span> </span>
); );
} }
if (V < n + scrambleWindow) { if (V < n + scrambleWindow) {
const phase = Math.min( const phase = Math.min(1, Math.floor((V - n) / phaseLen));
1,
Math.floor((V - n) / phaseLen)
);
const color = scrambleColors ? COLORS_LIGHT[phase] : undefined; const color = scrambleColors ? COLORS_LIGHT[phase] : undefined;
return ( return (
<span <span key={`c-${pi}-${ci}`} style={color ? { color } : undefined}>
key={`c-${si}-${ci}`}
style={color ? { color } : undefined}
>
{randomChar()} {randomChar()}
</span> </span>
); );
} }
return <span key={`c-${si}-${ci}`}>{ch}</span>; return <span key={`c-${pi}-${ci}`}>{ch}</span>;
})} })}
</span> </span>
))} );
}
return (
<span key={`slot-${pi}`} className={p.className}>
{p.scramble.split("").map((ch, ci) => {
const i = index++;
const order = reverse ? F - 1 - i : i;
const n = order * letterDelayMs;
if (V < n) {
return (
<span key={`sc-${pi}-${ci}`} style={{ opacity: 0 }}>
{ch}
</span>
);
}
if (V < n + scrambleWindow) {
const phase = Math.min(1, Math.floor((V - n) / phaseLen));
const color = scrambleColors ? COLORS_LIGHT[phase] : undefined;
return (
<span key={`sc-${pi}-${ci}`} style={color ? { color } : undefined}>
{randomChar()}
</span>
);
}
return <span key={`sc-${pi}-${ci}`}>{ch}</span>;
})}
</span>
);
})}
</span> </span>
); );
} }
+18 -7
View File
@@ -11,6 +11,7 @@ import {
setLayerDef, setLayerDef,
touchLayerRegistry, touchLayerRegistry,
} from "@/lib/imageLayers"; } from "@/lib/imageLayers";
import { usePasscodeAccessLookup } from "@/components/dom/PasscodeAccess";
/** /**
* Selected Work grid — 1:1 port of the original section `h` (chunk * Selected Work grid — 1:1 port of the original section `h` (chunk
@@ -27,8 +28,9 @@ import {
* screen rect (curl + negative reveal + hover dot mask). * screen rect (curl + negative reveal + hover dot mask).
* - Aspect ratios come from preloading each imageUrl and reading * - Aspect ratios come from preloading each imageUrl and reading
* naturalWidth/naturalHeight into a module-level cache (original `o`). * naturalWidth/naturalHeight into a module-level cache (original `o`).
* - The passcode-protected first item (/2026, brand "TikTok") is omitted * - Passcode-protected items are filtered exactly like the original
* exactly like the original's default-unlocked state. * `WORK_ITEMS.filter(t => !t.passcodeProtected || lookup(t.href))`: the
* TikTok entry only appears once /2026 is unlocked.
*/ */
// Module-level cache mirroring the original `o` (persists across remounts). // Module-level cache mirroring the original `o` (persists across remounts).
@@ -38,9 +40,17 @@ export default function WorkSection() {
const [ratios, setRatios] = useState<Record<string, string>>({ ...ratioCache }); const [ratios, setRatios] = useState<Record<string, string>>({ ...ratioCache });
const [colWidth, setColWidth] = useState(0); const [colWidth, setColWidth] = useState(0);
const gridRef = useRef<HTMLDivElement | null>(null); const gridRef = useRef<HTMLDivElement | null>(null);
const lookup = usePasscodeAccessLookup();
// Register canvas layer defs for every visible item (idempotent data // Original `f` — passcode-protected items stay hidden until unlocked.
// write; the version bump happens once targets exist, in the effect). const visibleItems = useMemo(
() => WORK_ITEMS.filter((item) => !item.passcodeProtected || lookup(item.href)),
[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(() => { useMemo(() => {
for (const item of WORK_ITEMS) { for (const item of WORK_ITEMS) {
setLayerDef(item.href, { setLayerDef(item.href, {
@@ -74,7 +84,7 @@ export default function WorkSection() {
if (ratioCache[imageUrl] !== ratio) ratioCache[imageUrl] = ratio; if (ratioCache[imageUrl] !== ratio) ratioCache[imageUrl] = ratio;
setRatios((prev) => (prev[imageUrl] === ratio ? prev : { ...prev, [imageUrl]: ratio })); setRatios((prev) => (prev[imageUrl] === ratio ? prev : { ...prev, [imageUrl]: ratio }));
}; };
const images = WORK_ITEMS.map((item) => { const images = visibleItems.map((item) => {
const img = new Image(); const img = new Image();
img.decoding = "async"; img.decoding = "async";
img.onload = () => update(item.imageUrl, img.naturalWidth, img.naturalHeight); img.onload = () => update(item.imageUrl, img.naturalWidth, img.naturalHeight);
@@ -88,7 +98,8 @@ export default function WorkSection() {
cancelled = true; cancelled = true;
for (const img of images) img.onload = null; 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]);
return ( return (
<section <section
@@ -100,7 +111,7 @@ export default function WorkSection() {
className="grid grid-cols-12 w-full" className="grid grid-cols-12 w-full"
style={{ rowGap: `${colWidth}px` }} style={{ rowGap: `${colWidth}px` }}
> >
{WORK_ITEMS.map((item) => ( {visibleItems.map((item) => (
<WorkCard key={item.href} item={item} ratio={ratios[item.imageUrl]} /> <WorkCard key={item.href} item={item} ratio={ratios[item.imageUrl]} />
))} ))}
</div> </div>
+102
View File
@@ -0,0 +1,102 @@
/**
* Passcode constants + pure helpers — 1:1 port of the original modules
* 58156 (paths/href) and 28116 (brand label) from d59f7a97fb1c563f.js.
*
* The single passcode-protected scope is the TikTok work entry (/2026).
* The brand label itself is obfuscated in the original bundle as char codes
* minus one; we keep the same obfuscation.
*/
/** Original module 28116 `d` = "TikTok".charCodes + 1. */
const BRAND_CODES = [85, 106, 108, 85, 112, 108];
/** revealBrandLabel() — decodes to "TikTok". */
export function revealBrandLabel(): string {
let out = "";
for (let i = 0; i < BRAND_CODES.length; i += 1) {
out += String.fromCharCode(BRAND_CODES[i] - 1);
}
return out;
}
/** revealBrandLabelLength() — 6. */
export function revealBrandLabelLength(): number {
return BRAND_CODES.length;
}
/** passcodeLockedPlaceholderText() — "■■■■■■". */
export function passcodeLockedPlaceholderText(): string {
return "■■■■■■";
}
export const PASSCODE_LOCKED_CHAR_CLASS =
"inline-block min-w-[0.62em] text-center text-l1 tabular-nums select-text";
export const PASSCODE_LOCKED_SCRAMBLE_CLASS =
"inline-flex items-baseline gap-[0.12em] mx-[0.06em] select-text [&>span]:inline-block [&>span]:min-w-[0.62em] [&>span]:text-center [&>span]:tabular-nums";
/** Original module 58156 `y` — the unlock screen renders slotCount slots. */
export const PASSCODE = { slotCount: 4 } as const;
/** The work item hrefs guarded by the passcode (module 58156 `x`). */
export const PASSCODE_PROTECTED_PATHS: string[] = ["/2026"];
/** normalizePath (original `T`): trimmed path with a guaranteed leading "/". */
export function normalizePath(path: string): string {
const t = path.trim();
return t ? (t.startsWith("/") ? t : `/${t}`) : "/";
}
/** workHrefToPath (original module 83039 `v`): internal href only. */
export function workHrefToPath(href: string): string | null {
if (href.startsWith("http://") || href.startsWith("https://")) return null;
return normalizePath(href);
}
/**
* buildPasscodeUnlockHref (original `b`):
* "/2026", "/" → "/unlock/2026?return=%2F"
*/
export function buildPasscodeUnlockHref(scope: string, returnTo: string): string {
const safeReturn = sanitizePasscodeReturnTo(returnTo) ?? "/";
const seg = normalizePath(scope).slice(1) || "_";
return `/unlock/${encodeURIComponent(seg)}?return=${encodeURIComponent(safeReturn)}`;
}
/** scopeToPath (original `P`): decoded scope with a guaranteed leading "/". */
export function scopeToPath(scope: string): string {
const decoded = decodeURIComponent(scope);
return decoded.startsWith("/") ? decoded : `/${decoded}`;
}
/** isPasscodeProtectedPath (original `S`). */
export function isPasscodeProtectedPath(path: string): boolean {
const p = normalizePath(path);
return PASSCODE_PROTECTED_PATHS.includes(p);
}
/** emptyPasscodeAccessState (original `A`). */
export function emptyPasscodeAccessState(): Record<string, boolean> {
return Object.fromEntries(PASSCODE_PROTECTED_PATHS.map((p) => [p, false]));
}
/** primaryPasscodePath (original `w`): the first protected path. */
export function primaryPasscodePath(): string {
return PASSCODE_PROTECTED_PATHS[0] ?? "/2026";
}
/** sanitizePasscodeReturnTo (original `C`): same-origin relative path only. */
export function sanitizePasscodeReturnTo(returnTo?: string | null): string | null {
if (!returnTo) return null;
const t = returnTo.trim();
if (!t.startsWith("/") || t.startsWith("//")) return null;
return t;
}
/** Window event the access provider listens to (module 4278 `E`). */
export const PASSCODE_ACCESS_CHANGED_EVENT = "passcode-access-changed";
/** Shared cookie name for the access state (our API contract). */
export const PASSCODE_COOKIE_NAME = "hq-passcode-access";
export type PasscodeAccessState = Record<string, boolean>;
+27
View File
@@ -0,0 +1,27 @@
import { cookies } from "next/headers";
import {
PASSCODE_COOKIE_NAME,
emptyPasscodeAccessState,
type PasscodeAccessState,
} from "@/lib/passcode";
/**
* Server-side access state (the original passes `initialAccess` from its
* root layout server component). Access is stored as a JSON cookie written
* by /api/passcode.
*/
export async function getPasscodeAccessServer(): Promise<PasscodeAccessState> {
const store = await cookies();
const raw = store.get(PASSCODE_COOKIE_NAME)?.value;
if (!raw) return emptyPasscodeAccessState();
try {
const parsed = JSON.parse(decodeURIComponent(raw)) as Record<string, unknown>;
const state = emptyPasscodeAccessState();
for (const key of Object.keys(state)) {
state[key] = parsed[key] === true;
}
return state;
} catch {
return emptyPasscodeAccessState();
}
}
+16 -3
View File
@@ -1,13 +1,15 @@
/** /**
* WORK_ITEMS — 1:1 from the original d59f7a97fb1c563f.js (module 28116), * WORK_ITEMS — 1:1 from the original d59f7a97fb1c563f.js (module 28116),
* minus the passcode-protected entry (the original grid also omits it until * including the passcode-protected first entry (the original grid filters it
* the passcode is unlocked: `WORK_ITEMS.filter(t => !t.passcodeProtected || * via `WORK_ITEMS.filter(t => !t.passcodeProtected || lookup(t.href))` — the
* lookup(t.href))` — the locked one reveals the brand label "TikTok"). * locked one reveals the brand label "TikTok"; see WorkSection).
* *
* Internal hrefs (/reunimos, /inspire_mono, …) are detail-page routes that * Internal hrefs (/reunimos, /inspire_mono, …) are detail-page routes that
* do not exist in this clone yet; WorkSection renders them as inert links * do not exist in this clone yet; WorkSection renders them as inert links
* until the route system is ported. * until the route system is ported.
*/ */
import { revealBrandLabel } from "@/lib/passcode";
export type WorkItem = { export type WorkItem = {
name: string; name: string;
imageUrl: string; imageUrl: string;
@@ -17,11 +19,22 @@ export type WorkItem = {
type: "post" | "tools" | "event"; type: "post" | "tools" | "event";
gridClass: string; gridClass: string;
codingProject?: boolean; codingProject?: boolean;
passcodeProtected?: boolean;
}; };
export const SELECTED_WORK_SECTION_ID = "selected-work"; export const SELECTED_WORK_SECTION_ID = "selected-work";
export const WORK_ITEMS: WorkItem[] = [ export const WORK_ITEMS: WorkItem[] = [
{
name: revealBrandLabel(), // "TikTok" — obfuscated in the original bundle
imageUrl: "/work/tt01.png",
hoverImageUrl: "/work/tt02.png",
href: "/2026",
year: "2022-2026",
type: "post",
gridClass: "col-span-12 lg:col-span-8 lg:col-start-3",
passcodeProtected: true,
},
{ {
name: "Reunimos™", name: "Reunimos™",
imageUrl: "/work/reunimos01.png", imageUrl: "/work/reunimos01.png",