From 8ce5471c25c2f61d8c32f13f02e9fcfdf165d668 Mon Sep 17 00:00:00 2001 From: chenchun Date: Tue, 1 Sep 2026 19:21:52 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E7=A7=BB=E6=A4=8D=E9=A6=96=E9=A1=B5=20?= =?UTF-8?q?passcode=20=E5=BD=A9=E8=9B=8B=EF=BC=88=E2=96=A0=E2=96=A0?= =?UTF-8?q?=E2=96=A0=E2=96=A0=E2=96=A0=E2=96=A0=20=E2=86=92=20/unlock/2026?= =?UTF-8?q?=20=E8=A7=A3=E9=94=81=20TikTok=20=E5=93=81=E7=89=8C=E5=90=8D?= =?UTF-8?q?=E4=B8=8E=E9=9A=90=E8=97=8F=E4=BD=9C=E5=93=81=E5=8D=A1=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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 --- app/api/passcode/route.ts | 81 ++++++++++++ app/globals.css | 18 +++ app/layout.tsx | 19 ++- app/page.tsx | 13 +- app/unlock/[scope]/page.tsx | 33 +++++ components/dom/PasscodeAccess.tsx | 140 ++++++++++++++++++++ components/dom/PasscodeRevealText.tsx | 137 +++++++++++++++++++ components/dom/PasscodeUnlockScreen.tsx | 155 ++++++++++++++++++++++ components/dom/ScrambleReveal.tsx | 167 +++++++++++++++++------- components/dom/WorkSection.tsx | 25 +++- lib/passcode.ts | 102 +++++++++++++++ lib/passcodeServer.ts | 27 ++++ lib/workItems.ts | 19 ++- 13 files changed, 864 insertions(+), 72 deletions(-) create mode 100644 app/api/passcode/route.ts create mode 100644 app/unlock/[scope]/page.tsx create mode 100644 components/dom/PasscodeAccess.tsx create mode 100644 components/dom/PasscodeRevealText.tsx create mode 100644 components/dom/PasscodeUnlockScreen.tsx create mode 100644 lib/passcode.ts create mode 100644 lib/passcodeServer.ts diff --git a/app/api/passcode/route.ts b/app/api/passcode/route.ts new file mode 100644 index 0000000..d0332cf --- /dev/null +++ b/app/api/passcode/route.ts @@ -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 { + const raw = request.cookies.get(PASSCODE_COOKIE_NAME)?.value; + if (!raw) return emptyPasscodeAccessState(); + try { + const parsed = JSON.parse(decodeURIComponent(raw)) as Record; + 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; +} diff --git a/app/globals.css b/app/globals.css index 7e9af68..625e911 100644 --- a/app/globals.css +++ b/app/globals.css @@ -73,6 +73,24 @@ html::-webkit-scrollbar, body::-webkit-scrollbar { .hsst-char { 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 { 0% { opacity: 0; diff --git a/app/layout.tsx b/app/layout.tsx index 5aa5754..908e0ee 100644 --- a/app/layout.tsx +++ b/app/layout.tsx @@ -6,6 +6,8 @@ import Header from "@/components/dom/Header"; import BackgroundGrid from "@/components/dom/BackgroundGrid"; import LoadingOverlay from "@/components/dom/LoadingOverlay"; import { HeroScene } from "@/components/canvas/HeroScene"; +import { PasscodeAccessProvider } from "@/components/dom/PasscodeAccess"; +import { getPasscodeAccessServer } from "@/lib/passcodeServer"; const tiktokSans = localFont({ src: "./fonts/TikTokSans.ttf", @@ -30,20 +32,23 @@ export const metadata: Metadata = { description: "Digital Product Designer & Builder © 2026", }; -export default function RootLayout({ +export default async function RootLayout({ children, }: Readonly<{ children: React.ReactNode; }>) { + const initialAccess = await getPasscodeAccessServer(); return ( - - - -
- {children} - + + + + +
+ {children} + + ); diff --git a/app/page.tsx b/app/page.tsx index b868374..caaf99c 100644 --- a/app/page.tsx +++ b/app/page.tsx @@ -3,13 +3,13 @@ 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"; /** * Page content matching the original DOM (haoqi_body.html): * - banner section (h-dvh) with meta row + big title, all scramble-revealed * - signature/about section (kept simple) */ -const PASSCODE_LENGTH = 6; export default function Home() { return ( @@ -36,16 +36,7 @@ export default function Home() { startDelayMs={300} letterDelayMs={10} /> - +
(); + const search = useSearchParams(); + const scope = scopeToPath(String(params?.scope ?? "")); + const returnTo = sanitizePasscodeReturnTo(search.get("return")); + return ; +} + +export default function UnlockPage() { + return ( + + + + ); +} diff --git a/components/dom/PasscodeAccess.tsx b/components/dom/PasscodeAccess.tsx new file mode 100644 index 0000000..c80a7ee --- /dev/null +++ b/components/dom/PasscodeAccess.tsx @@ -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 { + const res = await fetch("/api/passcode", { cache: "no-store" }); + return res.ok ? ((res.json() as unknown) as Promise) : emptyPasscodeAccessState(); +} + +async function postAccess(body: { + scope?: string; + code?: string; + action?: string; +}): Promise { + return fetch("/api/passcode", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(body), + }); +} + +type Store = { + snapshot: PasscodeAccessState; + listeners: Set<() => void>; + refresh: () => Promise; +}; + +const AccessContext = createContext(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(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 {children}; +} + +/** 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 { + return postAccess({ scope, code }); +} + +/** logoutPasscodeAccess (original `j`). */ +export async function logoutPasscodeAccess(opts?: { reload?: boolean }): Promise { + 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); +} diff --git a/components/dom/PasscodeRevealText.tsx b/components/dom/PasscodeRevealText.tsx new file mode 100644 index 0000000..9667d8e --- /dev/null +++ b/components/dom/PasscodeRevealText.tsx @@ -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 | 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 ( + { + if (e.key === "Enter" || e.key === " ") { + e.preventDefault(); + go(); + } + }} + > + {passcodeLockedPlaceholderText() + .split("") + .map((ch, i) => ( + + ))} + + ); + } + + return ( + { + clearTimer(); + timerRef.current = setTimeout(() => void relock(), 500); + }} + onPointerUp={clearTimer} + onPointerLeave={clearTimer} + onPointerCancel={clearTimer} + onContextMenu={(e) => { + e.preventDefault(); + void relock(); + }} + > + {BRAND} + + ); +} + +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: , + }, + ", engineering, and AI at scale. Outside work, I build design tools for team efficiency.", + ]; + return ( + + ); +} diff --git a/components/dom/PasscodeUnlockScreen.tsx b/components/dom/PasscodeUnlockScreen.tsx new file mode 100644 index 0000000..0469c62 --- /dev/null +++ b/components/dom/PasscodeUnlockScreen.tsx @@ -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 { + 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(null); + const rowRef = useRef(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 ( +
inputRef.current?.focus()} + > + + onChange(e.target.value)} + className="absolute opacity-0 w-px h-px" + /> + +
+ ); +} + +/** Kept for parity with the original import surface (normalizePath helper). */ +export { normalizePath }; diff --git a/components/dom/ScrambleReveal.tsx b/components/dom/ScrambleReveal.tsx index 184da33..bae67ed 100644 --- a/components/dom/ScrambleReveal.tsx +++ b/components/dom/ScrambleReveal.tsx @@ -4,7 +4,7 @@ import { useEffect, useMemo, useRef, useState } from "react"; /** * 1:1 re-implementation of the original scramble-reveal text (chunk - * 2689132c4e070b68.js component `d`): + * 2689132c4e070b68.js module 71358 component `d`): * * - charset `ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*+-=?/<>[]{}` picked * 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 * startDelayMs + (n-1)*letterDelayMs + 4*letterDelayMs * - 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 COLORS_LIGHT = ["#c0fe04", "#607F02"]; 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 = { text?: string; - parts?: string[]; + parts?: Part[]; className?: string; startDelayMs?: number; letterDelayMs?: number; @@ -41,8 +88,8 @@ export default function ScrambleReveal({ scrambleColors = true, reverse = false, }: Props) { - const strings = useMemo( - () => (parts ? parts : [text ?? ""]), + const normalized = useMemo( + () => normalizeParts(parts, text), [parts, text] ); const ref = useRef(null); @@ -50,7 +97,10 @@ export default function ScrambleReveal({ const [startedAt, setStartedAt] = useState(null); 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 scrambleWindow = 2 * phaseLen; // D const total = startDelayMs + Math.max(0, F - 1) * letterDelayMs + scrambleWindow; @@ -94,53 +144,82 @@ export default function ScrambleReveal({ if (settled || !entered) { return ( - {strings.map((s, i) => ( - {entered ? s : ""} - ))} + {normalized.map((p, i) => + p.kind === "text" ? ( + {entered ? p.value : ""} + ) : ( + + {entered ? p.settled : null} + + ) + )} ); } // recompute random chars on each elapsed tick let index = 0; - const totalChars = strings.join("").length; return ( - {strings.map((s, si) => ( - - {s.split("").map((ch, ci) => { - const i = index++; - // Original `reverse`: character delays run last→first. - const order = reverse ? totalChars - 1 - i : i; - if (ch === "\n") return
; - if (ch === " ") return ; - const n = order * letterDelayMs; - if (V < n) { - return ( - - {ch} - - ); - } - if (V < n + scrambleWindow) { - const phase = Math.min( - 1, - Math.floor((V - n) / phaseLen) - ); - const color = scrambleColors ? COLORS_LIGHT[phase] : undefined; - return ( - - {randomChar()} - - ); - } - return {ch}; - })} -
- ))} + {normalized.map((p, pi) => { + if (p.kind === "text") { + return ( + + {p.value.split("").map((ch, ci) => { + const i = index++; + // Original `reverse`: character delays run last→first. + const order = reverse ? F - 1 - i : i; + if (ch === "\n") return
; + if (ch === " ") return ; + const n = order * letterDelayMs; + if (V < n) { + return ( + + {ch} + + ); + } + if (V < n + scrambleWindow) { + const phase = Math.min(1, Math.floor((V - n) / phaseLen)); + const color = scrambleColors ? COLORS_LIGHT[phase] : undefined; + return ( + + {randomChar()} + + ); + } + return {ch}; + })} +
+ ); + } + return ( + + {p.scramble.split("").map((ch, ci) => { + const i = index++; + const order = reverse ? F - 1 - i : i; + const n = order * letterDelayMs; + if (V < n) { + return ( + + {ch} + + ); + } + if (V < n + scrambleWindow) { + const phase = Math.min(1, Math.floor((V - n) / phaseLen)); + const color = scrambleColors ? COLORS_LIGHT[phase] : undefined; + return ( + + {randomChar()} + + ); + } + return {ch}; + })} + + ); + })}
); } diff --git a/components/dom/WorkSection.tsx b/components/dom/WorkSection.tsx index 7e1df4b..f8f6164 100644 --- a/components/dom/WorkSection.tsx +++ b/components/dom/WorkSection.tsx @@ -11,6 +11,7 @@ import { setLayerDef, touchLayerRegistry, } from "@/lib/imageLayers"; +import { usePasscodeAccessLookup } from "@/components/dom/PasscodeAccess"; /** * 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). * - Aspect ratios come from preloading each imageUrl and reading * naturalWidth/naturalHeight into a module-level cache (original `o`). - * - The passcode-protected first item (/2026, brand "TikTok") is omitted - * exactly like the original's default-unlocked state. + * - Passcode-protected items are filtered exactly like the original + * `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). @@ -38,9 +40,17 @@ export default function WorkSection() { const [ratios, setRatios] = useState>({ ...ratioCache }); const [colWidth, setColWidth] = useState(0); const gridRef = useRef(null); + const lookup = usePasscodeAccessLookup(); - // Register canvas layer defs for every visible item (idempotent data - // write; the version bump happens once targets exist, in the effect). + // Original `f` — passcode-protected items stay hidden until unlocked. + 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(() => { for (const item of WORK_ITEMS) { setLayerDef(item.href, { @@ -74,7 +84,7 @@ export default function WorkSection() { if (ratioCache[imageUrl] !== ratio) ratioCache[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(); img.decoding = "async"; img.onload = () => update(item.imageUrl, img.naturalWidth, img.naturalHeight); @@ -88,7 +98,8 @@ export default function WorkSection() { 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]); return (
- {WORK_ITEMS.map((item) => ( + {visibleItems.map((item) => ( ))}
diff --git a/lib/passcode.ts b/lib/passcode.ts new file mode 100644 index 0000000..a4aaa74 --- /dev/null +++ b/lib/passcode.ts @@ -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 { + 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; diff --git a/lib/passcodeServer.ts b/lib/passcodeServer.ts new file mode 100644 index 0000000..4610c58 --- /dev/null +++ b/lib/passcodeServer.ts @@ -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 { + 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; + const state = emptyPasscodeAccessState(); + for (const key of Object.keys(state)) { + state[key] = parsed[key] === true; + } + return state; + } catch { + return emptyPasscodeAccessState(); + } +} diff --git a/lib/workItems.ts b/lib/workItems.ts index a8d9550..1502800 100644 --- a/lib/workItems.ts +++ b/lib/workItems.ts @@ -1,13 +1,15 @@ /** * WORK_ITEMS — 1:1 from the original d59f7a97fb1c563f.js (module 28116), - * minus the passcode-protected entry (the original grid also omits it until - * the passcode is unlocked: `WORK_ITEMS.filter(t => !t.passcodeProtected || - * lookup(t.href))` — the locked one reveals the brand label "TikTok"). + * including the passcode-protected first entry (the original grid filters it + * via `WORK_ITEMS.filter(t => !t.passcodeProtected || lookup(t.href))` — the + * locked one reveals the brand label "TikTok"; see WorkSection). * * Internal hrefs (/reunimos, /inspire_mono, …) are detail-page routes that * do not exist in this clone yet; WorkSection renders them as inert links * until the route system is ported. */ +import { revealBrandLabel } from "@/lib/passcode"; + export type WorkItem = { name: string; imageUrl: string; @@ -17,11 +19,22 @@ export type WorkItem = { type: "post" | "tools" | "event"; gridClass: string; codingProject?: boolean; + passcodeProtected?: boolean; }; export const SELECTED_WORK_SECTION_ID = "selected-work"; 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™", imageUrl: "/work/reunimos01.png",