import type { RogueCatalog } from "@election2026/protocol"; import { Award, BookOpen, Check, ChevronLeft, ChevronRight, Flame, Layers, Lock, Newspaper, Trophy, Users, X, type LucideIcon } from "lucide-react"; import { Fragment, useEffect, useLayoutEffect, useMemo, useRef, useState, type CSSProperties, type KeyboardEvent as ReactKeyboardEvent, type MouseEvent as ReactMouseEvent, type PointerEvent as ReactPointerEvent, type ReactNode, type RefObject, } from "react"; import { createPortal } from "react-dom"; import { rogueApi } from "../api.ts"; import { sfx } from "../audio/sfx.ts"; import { GameScene, SceneStat } from "../ui/GameScene.tsx"; import { AdvisorFace, OfferFace, cardKind } from "./cards.tsx"; import { loadProgress, type Progress } from "./progress.ts"; import "./collection.css"; /** * 圖鑑與成就(#/rogue/collection):一本選戰卡冊。 * 右邊(手機在上面)是索引貼:牌、幕僚、每週事件、成就。一頁一頁的卡套,收錄過的全彩, * 還沒收錄的灰色,但名字、效果照樣看得到,下面寫怎麼拿到。點一格看大張的說明。 * 翻頁:上一頁/下一頁、鍵盤左右鍵、手機左右滑。資料存在玩家自己的瀏覽器(progress.ts)。 */ type Tab = "cards" | "advisors" | "events" | "feats"; const TABS: { id: Tab; label: string; Icon: LucideIcon; note: string }[] = [ { id: "cards", label: "牌", Icon: Layers, note: "在牌組、獎勵或物資行出現過,就會收進卡冊。" }, { id: "advisors", label: "幕僚", Icon: Users, note: "在你的團隊、招募或物資行出現過,就會收進卡冊。" }, { id: "events", label: "每週事件", Icon: Newspaper, note: "遇到一次就會收進卡冊。" }, { id: "feats", label: "成就", Icon: Award, note: "達成條件,這枚獎章就會亮起來。" }, ]; /** 牌依類型分組的順序(類型由牌的標籤決定,和牌面的色條一樣) */ const KIND_ORDER = ["ground", "rally", "org", "media", "defend", "attack", "money", "status"]; const RARITY_ORDER = ["basic", "common", "rare", "status"]; const RARITY_LABEL: Record = { basic: "基本", common: "普通", rare: "稀有", status: "狀態" }; const SCHOOLS: { id: string; label: string }[] = [ { id: "ground", label: "地面戰" }, { id: "air", label: "空戰" }, { id: "org", label: "組織" }, { id: "money", label: "資金" }, { id: "defend", label: "攻防" }, { id: "any", label: "通用" }, ]; /** 後端沒給「怎麼拿到」時的說法 */ const DEFAULT_HOW: Record, string> = { cards: "拜會地方、競選物資行、地方抉擇", advisors: "招募幕僚、競選物資行、地方抉擇", events: "每週開始時隨機發生", }; interface Entry { id: string; name: string; /** 大張說明裡的一句話:牌和幕僚的效果、事件內容;成就是拿到的日期 */ desc: string; meta: string; howLabel: string; how: string; got: boolean; /** 卡套下面的小字 */ cap: string; group: string | null; face: ReactNode; } interface Group { id: string; label: string; start: number; size: number; got: number; } interface Section { entries: Entry[]; groups: Group[]; got: number; } const rankOf = (order: readonly string[], id: string) => { const i = order.indexOf(id); return i < 0 ? order.length : i; }; /** 分組(已排好序,同組連在一起):每組從第幾格開始、幾格、收錄幾格 */ function groupsOf(entries: readonly Entry[], labels: ReadonlyMap): Group[] { const ids = [...new Set(entries.flatMap((e) => (e.group === null ? [] : [e.group])))]; return ids.map((id) => { const members = entries.filter((e) => e.group === id); return { id, label: labels.get(id) ?? "其他", start: entries.findIndex((e) => e.group === id), size: members.length, got: members.filter((e) => e.got).length }; }); } function section(entries: Entry[], labels: ReadonlyMap = new Map()): Section { return { entries, groups: groupsOf(entries, labels), got: entries.filter((e) => e.got).length }; } function buildSections(catalog: RogueCatalog, progress: Progress): Record { const seenCards = new Set(progress.seen.cards); const seenAdvisors = new Set(progress.seen.advisors); const seenEvents = new Set(progress.seen.events); const sortedCards = catalog.cards .map((c) => ({ c, kind: cardKind(c.tags) })) .sort((a, b) => rankOf(KIND_ORDER, a.kind.id) - rankOf(KIND_ORDER, b.kind.id) || rankOf(RARITY_ORDER, a.c.rarity) - rankOf(RARITY_ORDER, b.c.rarity)); const kindLabels = new Map(sortedCards.map(({ kind }) => [kind.id, kind.label])); const cards = sortedCards.map(({ c, kind }): Entry => { const got = seenCards.has(c.id); const how = c.how ?? DEFAULT_HOW.cards; const meta = [RARITY_LABEL[c.rarity] ?? "", kind.label, c.cost !== null ? `體力 ${c.cost}` : "", c.money ? `${c.money} 萬` : "", ...c.keywords]; return { id: c.id, name: c.name, desc: c.text, meta: meta.filter(Boolean).join("・"), howLabel: "怎麼拿到", how, got, cap: got ? "已收錄" : how, group: kind.id, face: }; }); const schoolLabels = new Map(SCHOOLS.map((s) => [s.id, s.label])); const schoolIds = SCHOOLS.map((s) => s.id); const advisors = [...catalog.advisors] .sort((a, b) => rankOf(schoolIds, a.school) - rankOf(schoolIds, b.school)) .map((a): Entry => { const got = seenAdvisors.has(a.id); const how = a.how ?? DEFAULT_HOW.advisors; const school = schoolLabels.get(a.school) ?? "其他"; return { id: a.id, name: a.name, desc: a.text, meta: `${school}幕僚`, howLabel: "怎麼拿到", how, got, cap: got ? "已收錄" : how, group: a.school, face: }; }); const events = catalog.events.map((e): Entry => { const got = seenEvents.has(e.id); const how = e.how ?? DEFAULT_HOW.events; return { id: e.id, name: e.title, desc: e.text, meta: "每週事件", howLabel: "怎麼遇到", how, got, cap: got ? "已收錄" : how, group: null, face: }; }); const feats = catalog.feats.map((f): Entry => { const date = progress.feats[f.id]; const got = !!date; return { id: f.id, name: f.name, desc: got ? `${date} 拿到這枚獎章。` : "還沒達成。", meta: "成就獎章", howLabel: "達成條件", how: f.text, got, cap: got ? `${date} 拿到` : "還沒達成", group: null, face: , }; }); return { cards: section(cards, kindLabels), advisors: section(advisors, schoolLabels), events: section(events), feats: section(feats) }; } // ── 版面:量卡冊內頁的大小,算出一頁放幾欄幾列、牌多寬(整頁不捲) ── const CARD_RATIO = 1.47; const MAX_CARD_W = 150; interface BookLayout { pages: 1 | 2; cols: number; rows: number; cardW: number; gap: number; pad: number; cap: number; pagePad: number; spine: number; } /** 電腦版兩頁攤開、手機一頁;每頁最多 4 欄 3 列。手機盡量多放幾格,電腦版讓牌大一點 */ function fitBook(w: number, h: number): BookLayout { const small = w < 440; const pages = w >= 860 ? 2 : 1; const m = small ? { gap: 6, pad: 4, cap: 30, pagePad: 2, minW: 84 } : { gap: 14, pad: 8, cap: 36, pagePad: 12, minW: 100 }; const spine = pages === 2 ? 40 : 0; const pageW = (w - spine) / pages - m.pagePad * 2; const pageH = h - m.pagePad * 2; const fromH = (rows: number) => ((pageH - (rows - 1) * m.gap) / rows - m.pad * 2 - m.cap) / CARD_RATIO; const fromW = (cols: number) => (pageW - (cols - 1) * m.gap) / cols - m.pad * 2; const candidates = [1, 2, 3].flatMap((rows) => [1, 2, 3, 4].map((cols) => ({ rows, cols, cardW: Math.floor(Math.min(fromH(rows), fromW(cols), MAX_CARD_W)) })), ); const score = (c: { rows: number; cols: number; cardW: number }) => (small ? c.rows * c.cols * 1000 + c.cardW : c.rows * c.cols * c.cardW * c.cardW); const best = candidates.filter((c) => c.cardW >= m.minW).sort((a, b) => score(b) - score(a))[0]; if (best) return { pages, ...best, gap: m.gap, pad: m.pad, cap: m.cap, pagePad: m.pagePad, spine }; // 很矮的畫面(手機橫放):放一列,牌縮小 const cardW = Math.max(56, Math.floor(Math.min(fromH(1), MAX_CARD_W))); const cols = Math.max(1, Math.min(6, Math.floor((pageW + m.gap) / (cardW + m.pad * 2 + m.gap)))); return { pages, rows: 1, cols, cardW, gap: m.gap, pad: m.pad, cap: m.cap, pagePad: m.pagePad, spine }; } const layoutKey = (l: BookLayout) => `${l.pages}/${l.cols}/${l.rows}/${l.cardW}/${l.gap}`; function useBookLayout(el: HTMLElement | null): BookLayout | null { const [layout, setLayout] = useState(null); useLayoutEffect(() => { if (!el) return; const measure = () => { const next = fitBook(el.clientWidth, el.clientHeight); setLayout((prev) => (prev && layoutKey(prev) === layoutKey(next) ? prev : next)); }; measure(); const ro = new ResizeObserver(measure); ro.observe(el); return () => ro.disconnect(); }, [el]); return layout; } const reducedMotion = () => typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches; /** 手機左右滑:滑超過 48px 算翻頁;follow 給的元素會跟著手指移一點 */ function useSwipe(onSwipe: (dir: 1 | -1) => void, follow?: RefObject) { const start = useRef<{ x: number; y: number } | null>(null); const swiped = useRef(false); const shift = (dx: number | null) => { const el = follow?.current; if (!el) return; el.classList.toggle("is-dragging", dx !== null); el.style.transform = dx === null ? "" : `translateX(${dx}px)`; }; return { onPointerDown: (e: ReactPointerEvent) => { swiped.current = false; if (e.pointerType === "mouse") return; start.current = { x: e.clientX, y: e.clientY }; }, onPointerMove: (e: ReactPointerEvent) => { const s = start.current; if (!s || reducedMotion()) return; const dx = e.clientX - s.x; if (Math.abs(dx) > 8 && Math.abs(dx) > Math.abs(e.clientY - s.y)) shift(dx * 0.35); }, onPointerUp: (e: ReactPointerEvent) => { const s = start.current; start.current = null; shift(null); if (!s) return; const dx = e.clientX - s.x; if (Math.abs(dx) > 48 && Math.abs(dx) > Math.abs(e.clientY - s.y) * 1.2) { // 只擋掉緊接著的那一下點擊;手機滑完通常不會有點擊,所以一下子就放掉 swiped.current = true; setTimeout(() => (swiped.current = false), 300); onSwipe(dx < 0 ? 1 : -1); } }, onPointerCancel: () => { start.current = null; shift(null); }, /** 滑完不要順便點開那一格 */ onClickCapture: (e: ReactMouseEvent) => { if (!swiped.current) return; swiped.current = false; e.preventDefault(); e.stopPropagation(); }, }; } const ratio = (a: number, b: number) => (b ? a / b : 0); export function RogueCollection() { const [catalog, setCatalog] = useState(null); const [error, setError] = useState(null); const [progress] = useState(loadProgress); const [tab, setTab] = useState("cards"); /** 每個分頁停在哪一格(換版面大小時,還是停在同一張附近) */ const [anchors, setAnchors] = useState>({ cards: 0, advisors: 0, events: 0, feats: 0 }); const [motion, setMotion] = useState<"next" | "prev" | "tab">("tab"); const [open, setOpen] = useState(null); const [spreadEl, setSpreadEl] = useState(null); const dragRef = useRef(null); const focusAfterFlip = useRef(false); const layout = useBookLayout(spreadEl); useEffect(() => { rogueApi .catalog() .then(setCatalog) .catch((e: unknown) => setError(e instanceof Error ? e.message : String(e))); }, []); const sections = useMemo(() => (catalog ? buildSections(catalog, progress) : null), [catalog, progress]); const current = sections?.[tab] ?? null; const entries = current?.entries ?? []; const perPage = layout ? layout.cols * layout.rows : 1; const perSpread = perPage * (layout?.pages ?? 1); const spreads = Math.max(1, Math.ceil(entries.length / perSpread)); const page = Math.min(Math.floor(anchors[tab] / perSpread), spreads - 1); const first = page * perSpread; const goTo = (index: number, sound = true) => { const target = Math.floor(index / perSpread); if (target !== page) setMotion(target > page ? "next" : "prev"); setAnchors((a) => ({ ...a, [tab]: index })); if (sound && target !== page) sfx.paper(); }; const flip = (dir: 1 | -1) => { const next = page + dir; if (next < 0 || next >= spreads) return; goTo(next * perSpread); }; const selectTab = (t: Tab) => { if (t === tab) return; setMotion("tab"); setTab(t); sfx.flip(); }; const openAt = (i: number) => { setOpen(i); sfx.flip(); }; const step = (dir: 1 | -1) => { if (open === null || !entries.length) return; const i = (open + dir + entries.length) % entries.length; setOpen(i); goTo(i, false); sfx.card(); }; const close = () => { const id = open === null ? null : entries[open]?.id; setOpen(null); requestAnimationFrame(() => { const el = id ? document.querySelector(`.col-pocket[data-col-id="${CSS.escape(id)}"]`) : null; el?.focus({ preventScroll: true }); }); }; // 鍵盤:左右鍵翻頁;看大張時左右鍵換一張、Esc 關掉 useEffect(() => { const onKey = (e: KeyboardEvent) => { if (e.altKey || e.ctrlKey || e.metaKey) return; const t = e.target as HTMLElement | null; if (t && (t.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName))) return; if (open !== null) { if (e.key === "Escape") close(); else if (e.key === "ArrowLeft") step(-1); else if (e.key === "ArrowRight") step(1); else return; e.preventDefault(); return; } const dir = e.key === "ArrowLeft" || e.key === "PageUp" ? -1 : e.key === "ArrowRight" || e.key === "PageDown" ? 1 : 0; if (!dir) return; e.preventDefault(); focusAfterFlip.current = !!spreadEl?.contains(document.activeElement); flip(dir); }; addEventListener("keydown", onKey); return () => removeEventListener("keydown", onKey); }); // 用鍵盤翻頁時,焦點移到新一頁的第一格 useEffect(() => { if (!focusAfterFlip.current) return; focusAfterFlip.current = false; spreadEl?.querySelector(".col-pocket[data-col-id]")?.focus({ preventScroll: true }); }, [page, tab, spreadEl]); const swipe = useSwipe(flip, dragRef); const onTabKey = (e: ReactKeyboardEvent) => { const i = TABS.findIndex((t) => t.id === tab); const next = e.key === "ArrowDown" ? i + 1 : e.key === "ArrowUp" ? i - 1 : e.key === "Home" ? 0 : e.key === "End" ? TABS.length - 1 : null; if (next === null) return; e.preventDefault(); const t = TABS[(next + TABS.length) % TABS.length]!; selectTab(t.id); document.getElementById(`col-tab-${t.id}`)?.focus(); }; const all = sections ? Object.values(sections) : []; const totalGot = all.reduce((n, s) => n + s.got, 0); const total = all.reduce((n, s) => n + s.entries.length, 0); const hud = ( <> } value={`${progress.wins}/${progress.runs}`} label="勝場/局數" /> } value={`${progress.ascension} 級`} label="逆風解鎖" /> } value={total ? `${Math.round(ratio(totalGot, total) * 100)}%` : "—"} label="卡冊收錄" /> ); const tabInfo = TABS.find((t) => t.id === tab)!; const vars = layout ? ({ "--col-card-w": `${layout.cardW}px`, "--col-cols": layout.cols, "--col-gap": `${layout.gap}px`, "--col-pad": `${layout.pad}px`, "--col-cap": `${layout.cap}px`, "--col-page-pad": `${layout.pagePad}px`, "--col-spine": `${layout.spine}px`, } as CSSProperties) : undefined; return (
{TABS.map((t) => { const s = sections?.[t.id]; return ( ); })}

{tabInfo.label}

{current ? `${current.got}/${entries.length}` : "—"}
{tab === "feats" ? (

{progress.runs} 局・{progress.wins} 勝・逆風解鎖 {progress.ascension} 級 紀錄只存在這台裝置的瀏覽器裡,清除瀏覽器資料會重來

) : current && current.groups.length > 0 ? ( ) : (

{tabInfo.note}

)}
{!sections || !layout ? (

{error ?? "翻開卡冊…"}

) : (
{Array.from({ length: layout.pages }, (_, p) => { const from = first + p * perPage; return ( {p === 1 && (
)}
    {Array.from({ length: perPage }, (_, k) => { const entry = entries[from + k]; return (
  • {entry ? openAt(from + k)} /> : }
  • ); })}
); })}
)}
{spreads <= 12 && ( {Array.from({ length: spreads }, (_, i) => ( ))} )} 第 {page + 1}/{spreads} 頁 ← → 翻頁
{open !== null && entries[open] && ( )}
); } /** 卡冊上的一格卡套 */ function Pocket({ entry, onOpen }: { entry: Entry; onOpen: () => void }) { const label = `${entry.name}。${entry.desc.replace(/。$/, "")}。${entry.got ? "已收錄" : `還沒收錄,${entry.howLabel}:${entry.how}`}`; return ( ); } /** 每週事件的牌面:像一張報紙頭條 */ function EventFace({ title, text }: { title: string; text: string }) { return ( 本週頭條 {title} {text} ); } /** 成就獎章 */ function MedalFace({ name, text, got }: { name: string; text: string; got: boolean }) { return ( {got ? : } {name} {text} ); } /** 點一格:大張的牌(或幕僚、事件、獎章)+說明、怎麼拿到 */ function Detail({ entry, index, total, note, onClose, onStep }: { entry: Entry; index: number; total: number; note: string; onClose: () => void; onStep: (dir: 1 | -1) => void }) { const boxRef = useRef(null); const closeRef = useRef(null); const swipe = useSwipe(onStep); useEffect(() => { closeRef.current?.focus({ preventScroll: true }); }, []); // 焦點留在視窗裡 const trap = (e: ReactKeyboardEvent) => { if (e.key !== "Tab" || !boxRef.current) return; const items = [...boxRef.current.querySelectorAll("button:not([disabled])")]; const firstEl = items[0]; const lastEl = items.at(-1); if (!firstEl || !lastEl) return; if (e.shiftKey && document.activeElement === firstEl) { e.preventDefault(); lastEl.focus(); } else if (!e.shiftKey && document.activeElement === lastEl) { e.preventDefault(); firstEl.focus(); } }; return createPortal(
{ if (e.target === e.currentTarget) onClose(); }} >
{entry.face} {!entry.got && ( 未收錄 )}

{entry.got ? : } {entry.got ? "已收錄" : "還沒收錄"}

{entry.name}

{entry.meta}

{entry.desc}

{entry.howLabel}

{entry.how}

{!entry.got &&

{note}

}
, document.body, ); }