feat: migrate web preview to Next.js
Verify mini program and deploy preview / verify-deploy (push) Successful in 3m30s

This commit is contained in:
2026-09-20 14:22:47 +08:00
parent 36aee09dfa
commit b5ee950142
40 changed files with 6897 additions and 1362 deletions
+8
View File
@@ -0,0 +1,8 @@
export default function AppLogo({ title = '偏爱研究所' }) {
return (
<header className="masthead">
<span className="logoMark">PK</span>
<strong>{title}</strong>
</header>
);
}
+27
View File
@@ -0,0 +1,27 @@
'use client';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
const ITEMS = [
{ href: '/', label: '测试', icon: 'home' },
{ href: '/discover', label: '发现', icon: 'discover' },
{ href: '/me', label: '我的', icon: 'me' }
];
export default function BottomNav() {
const pathname = usePathname();
return (
<nav className="bottomNav" aria-label="主导航">
{ITEMS.map(item => {
const active = item.href === '/' ? pathname === '/' : pathname.startsWith(item.href);
return (
<Link key={item.href} href={item.href} className={`navItem ${active ? 'active' : ''}`}>
<i className={`navGlyph ${item.icon}`} />
<span>{item.label}</span>
</Link>
);
})}
</nav>
);
}
+32
View File
@@ -0,0 +1,32 @@
'use client';
import { motion } from 'motion/react';
import Image from 'next/image';
import { useEffect, useState } from 'react';
import AppLogo from './AppLogo';
import BottomNav from './BottomNav';
import { apiRequest } from '../lib/api';
export default function DiscoverFeed() {
const [results, setResults] = useState([]);
const [error, setError] = useState('');
useEffect(() => {
apiRequest('/api/v1/results/discover').then(setResults).catch(error => setError(error.message));
}, []);
return (
<main className="pageShell feedPage">
<AppLogo title="大家最近选了什么" />
<p className="pageLead">看看同频的人把谁送到了最后</p>
{error ? <div className="emptyState">{error}</div> : null}
<section className="waterfall">
{results.map((result, index) => (
<motion.article key={result.id} className="testCard" initial={{ opacity: 0, scale: .96 }} animate={{ opacity: 1, scale: 1 }} transition={{ delay: index * .04 }}>
<Image src={`/assets/test-covers/${result.test_slug}.jpg`} width={900} height={1200} sizes="(max-width: 920px) 50vw, 450px" alt={`${result.test_title}结果封面`} />
<div className="cardCopy"><p>{result.test_title}</p><h2>{result.champion_name}</h2></div>
</motion.article>
))}
</section>
<BottomNav />
</main>
);
}
+62
View File
@@ -0,0 +1,62 @@
'use client';
import { motion } from 'motion/react';
import Image from 'next/image';
import Link from 'next/link';
import { useEffect, useMemo, useState } from 'react';
import AppLogo from './AppLogo';
import BottomNav from './BottomNav';
import { apiRequest } from '../lib/api';
export default function HomeFeed() {
const [tests, setTests] = useState([]);
const [query, setQuery] = useState('');
const [error, setError] = useState('');
useEffect(() => {
apiRequest('/api/v1/tests').then(setTests).catch(error => setError(error.message));
}, []);
const visible = useMemo(() => {
const keyword = query.trim().toLowerCase();
return tests.filter(test => `${test.title} ${test.subtitle}`.toLowerCase().includes(keyword));
}, [query, tests]);
return (
<main className="pageShell homePage">
<AppLogo />
<label className="searchBox">
<span aria-hidden>⌕</span>
<input value={query} onChange={event => setQuery(event.target.value)} placeholder="搜索测试" />
</label>
{error ? <ErrorState message={error} /> : null}
{!error && !tests.length ? <div className="emptyState">正在摆好擂台…</div> : null}
<section className="waterfall" aria-label="全部测试">
{visible.map((test, index) => (
<motion.article
key={test.slug}
className="testCard"
initial={{ opacity: 0, y: 18 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: index * 0.045, duration: 0.32 }}
whileTap={{ scale: 0.975 }}
>
<Link href={`/tests/${test.slug}`}>
<Image src={`/assets/test-covers/${test.slug}.jpg`} width={900} height={1200} sizes="(max-width: 920px) 50vw, 450px" alt={`${test.title}封面`} />
<div className="cardCopy">
<h2>{test.title}</h2>
<p>{test.subtitle}</p>
<div className="cardMeta"><span>{test.candidate_count} 强</span><span>{test.run_count} 人完成</span></div>
</div>
</Link>
</motion.article>
))}
</section>
<BottomNav />
</main>
);
}
function ErrorState({ message }) {
return <div className="emptyState"><strong>暂时没接上服务</strong><p>{message}</p></div>;
}
+195
View File
@@ -0,0 +1,195 @@
'use client';
import { motion } from 'motion/react';
import { useRouter } from 'next/navigation';
import { useCallback, useEffect, useRef, useState } from 'react';
import { apiRequest, ensureLogin } from '../lib/api';
const THEMES = {
celebration: ['#ff6038', '#fffaf4', '#25211f', '#ffe568'],
editorial: ['#f3eadf', '#201d1b', '#ffffff', '#285ee8'],
notebook: ['#c9f06b', '#1e2810', '#ff72a7', '#ffffff']
};
const TOOLS = [
['filter', '滤镜'], ['text', '文字'], ['sticker', '贴纸'], ['crop', '裁剪'],
['adjust', '调整'], ['layout', '布局'], ['brush', '画笔']
];
const VIEWS = [['overview', '总览'], ['left', '左半区'], ['right', '右半区'], ['top16', '16 强'], ['top8', '8 强'], ['final', '决赛']];
export default function PosterEditor({ runId }) {
const router = useRouter();
const canvasRef = useRef(null);
const [result, setResult] = useState(null);
const [error, setError] = useState('');
const [theme, setTheme] = useState('celebration');
const [layout, setLayout] = useState('symmetric');
const [view, setView] = useState('overview');
const [tool, setTool] = useState('filter');
const [sticker, setSticker] = useState(true);
const [caption, setCaption] = useState('');
const [background, setBackground] = useState(null);
const [adjust, setAdjust] = useState({ brightness: 100, contrast: 100, saturate: 100 });
useEffect(() => {
async function loadResult() {
const cached = sessionStorage.getItem('pk_last_result');
if (cached) {
const parsed = JSON.parse(cached);
if (parsed.id === runId) return parsed;
}
await ensureLogin();
return apiRequest(`/api/v1/me/results/${runId}`);
}
loadResult().then(setResult).catch(error => setError(error.message));
}, [runId]);
const draw = useCallback(() => {
if (!result || !canvasRef.current) return;
const canvas = canvasRef.current;
const ctx = canvas.getContext('2d');
const colors = THEMES[theme];
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = colors[0];
ctx.fillRect(0, 0, 750, 1000);
if (background) {
ctx.save();
ctx.filter = `brightness(${adjust.brightness}%) contrast(${adjust.contrast}%) saturate(${adjust.saturate}%)`;
coverImage(ctx, background, 0, 0, 750, 1000);
ctx.restore();
ctx.fillStyle = `${colors[0]}d8`;
ctx.fillRect(0, 0, 750, 1000);
}
ctx.fillStyle = colors[1];
ctx.font = '700 24px system-ui';
ctx.fillText('PK 研究所 / BRACKET', 42, 62);
ctx.font = '900 48px system-ui';
ctx.fillText(result.test_title, 42, 125);
ctx.fillStyle = colors[2];
ctx.fillRect(28, 165, 694, 690);
drawBracket(ctx, result, colors, layout, view);
if (caption) {
ctx.fillStyle = colors[3];
roundRect(ctx, 42, 870, Math.min(650, 50 + caption.length * 34), 52, 26);
ctx.fill();
ctx.fillStyle = colors[2];
ctx.font = '800 25px system-ui';
ctx.fillText(caption.slice(0, 20), 67, 904);
} else {
ctx.fillStyle = colors[1];
ctx.font = '800 25px system-ui';
ctx.fillText(`冠军 ${result.champion_name}`, 42, 910);
}
if (sticker) {
ctx.fillStyle = colors[3];
ctx.beginPath(); ctx.arc(660, 100, 48, 0, Math.PI * 2); ctx.fill();
ctx.fillStyle = colors[2]; ctx.font = '900 22px system-ui'; ctx.fillText('WIN', 635, 108);
}
ctx.fillStyle = colors[1]; ctx.font = '18px system-ui';
ctx.fillText('保存分享图,看看朋友的晋级路线', 42, 962);
}, [adjust, background, caption, layout, result, sticker, theme, view]);
useEffect(() => { draw(); }, [draw]);
function pickBackground(event) {
const file = event.target.files?.[0];
if (!file) return;
const image = new Image();
image.onload = () => setBackground(image);
image.src = URL.createObjectURL(file);
}
function save() {
const link = document.createElement('a');
link.download = `我的PK冠军-${result.champion_name}.png`;
link.href = canvasRef.current.toDataURL('image/png');
link.click();
}
if (error) return <main className="arenaState"><h1>结果读取失败</h1><p>{error}</p><button onClick={() => router.push('/')}>返回首页</button></main>;
if (!result) return <main className="arenaState">正在打开编辑器…</main>;
return (
<main className="editorPage">
<header className="editorHeader">
<button onClick={() => router.push('/me')}>←</button>
<div><strong>分享图编辑器</strong><small>{result.test_title} · {result.champion_name}</small></div>
<button className="exportButton" onClick={save}>导出</button>
</header>
<section className="editorWorkspace">
<canvas ref={canvasRef} width="750" height="1000" />
<aside className="editorControls">
<div className="scrollRow compact">
<button className={layout === 'symmetric' ? 'active' : ''} onClick={() => setLayout('symmetric')}>对称图</button>
<button className={layout === 'single' ? 'active' : ''} onClick={() => setLayout('single')}>单边图</button>
{VIEWS.map(item => <button key={item[0]} className={view === item[0] ? 'active' : ''} onClick={() => setView(item[0])}>{item[1]}</button>)}
</div>
<div className="mediaRow">
<span className="bracketThumb">晋级图</span>
<label className="addMedia">+<small>添加底图</small><input type="file" accept="image/*" onChange={pickBackground} /></label>
</div>
<div className="toolRow">
{TOOLS.map((item, index) => <button key={item[0]} className={tool === item[0] ? 'active' : ''} onClick={() => setTool(item[0])}><i>{index + 1}</i><span>{item[1]}</span></button>)}
</div>
<motion.div key={tool} className="toolPanel" initial={{ opacity: 0, y: 8 }} animate={{ opacity: 1, y: 0 }}>
{tool === 'filter' ? <><button onClick={() => setTheme('celebration')}>庆祝派对</button><button onClick={() => setTheme('editorial')}>杂志封面</button><button onClick={() => setTheme('notebook')}>贴纸手账</button></> : null}
{tool === 'text' ? <input value={caption} maxLength={20} onChange={event => setCaption(event.target.value)} placeholder="输入花字标题" /> : null}
{tool === 'sticker' ? <button onClick={() => setSticker(value => !value)}>冠军贴纸:{sticker ? '开启' : '关闭'}</button> : null}
{tool === 'adjust' ? <AdjustControls value={adjust} onChange={setAdjust} /> : null}
{['crop', 'layout', 'brush'].includes(tool) ? <p>该工具由 PosterDocument 图层绑定驱动,可继续从素材服务加载预设。</p> : null}
</motion.div>
</aside>
</section>
</main>
);
}
function AdjustControls({ value, onChange }) {
return <div className="adjustControls">{Object.entries(value).map(([name, amount]) => <label key={name}><span>{name}</span><input type="range" min="50" max="150" value={amount} onChange={event => onChange({ ...value, [name]: Number(event.target.value) })} /></label>)}</div>;
}
function coverImage(ctx, image, x, y, width, height) {
const ratio = Math.max(width / image.width, height / image.height);
const drawWidth = image.width * ratio, drawHeight = image.height * ratio;
ctx.drawImage(image, x + (width - drawWidth) / 2, y + (height - drawHeight) / 2, drawWidth, drawHeight);
}
function roundRect(ctx, x, y, width, height, radius) {
if (ctx.roundRect) { ctx.beginPath(); ctx.roundRect(x, y, width, height, radius); return; }
ctx.beginPath(); ctx.rect(x, y, width, height);
}
function drawBracket(ctx, result, colors, layout, view) {
const decisions = result.decisions || [], names = result.candidate_names || {};
if (!decisions.length) {
ctx.fillStyle = colors[1]; ctx.font = '900 72px system-ui'; ctx.fillText(result.champion_name, 70, 500); return;
}
const maxRound = Math.max(...decisions.map(item => item.round));
const minRound = view === 'final' ? maxRound : view === 'top8' ? Math.max(1, maxRound - 2) : view === 'top16' ? Math.max(1, maxRound - 3) : 1;
let visible = decisions.filter(item => item.round >= minRound);
if (view === 'left' || view === 'right') visible = visible.filter((item, index) => item.round === maxRound || index % 2 === (view === 'left' ? 0 : 1));
const groups = {}, positions = {};
visible.forEach(item => (groups[item.round] ||= []).push(item));
Object.entries(groups).forEach(([roundValue, items]) => {
const round = Number(roundValue);
items.forEach((item, index) => {
const symmetric = layout === 'symmetric';
const side = symmetric && round < maxRound && index % 2 ? 1 : -1;
const x = symmetric ? 375 + side * Math.min(260, 78 + (maxRound - round) * 62) : 70 + (round - minRound) * (580 / Math.max(1, maxRound - minRound));
const y = 230 + (index + 1) * (520 / (items.length + 1));
positions[`${item.winner_id}:${item.round}`] = { x, y, item };
});
});
ctx.strokeStyle = colors[3]; ctx.lineWidth = 3;
Object.values(positions).forEach(position => {
const parentDecision = visible.find(item => item.round > position.item.round && [item.left_id, item.right_id].includes(position.item.winner_id));
const parent = parentDecision && positions[`${parentDecision.winner_id}:${parentDecision.round}`];
if (!parent) return;
ctx.beginPath(); ctx.moveTo(position.x, position.y); ctx.lineTo((position.x + parent.x) / 2, position.y); ctx.lineTo((position.x + parent.x) / 2, parent.y); ctx.lineTo(parent.x, parent.y); ctx.stroke();
});
Object.values(positions).forEach(position => {
const label = names[position.item.winner_id] || result.champion_name;
ctx.fillStyle = position.item.round === maxRound ? colors[3] : colors[0];
ctx.fillRect(position.x - 56, position.y - 20, 112, 40);
ctx.fillStyle = colors[1]; ctx.font = `${label.length > 6 ? 13 : 16}px system-ui`; ctx.fillText(label.slice(0, 8), position.x - 47, position.y + 6);
});
}
+45
View File
@@ -0,0 +1,45 @@
'use client';
import Link from 'next/link';
import { useEffect, useState } from 'react';
import AppLogo from './AppLogo';
import BottomNav from './BottomNav';
import { apiRequest, ensureLogin } from '../lib/api';
export default function Profile() {
const [results, setResults] = useState([]);
const [linkCode, setLinkCode] = useState('');
const [error, setError] = useState('');
useEffect(() => {
ensureLogin().then(() => apiRequest('/api/v1/me/results')).then(setResults).catch(error => setError(error.message));
}, []);
async function createLinkCode() {
try {
const data = await apiRequest('/api/v1/me/link-code', { method: 'POST' });
setLinkCode(data.code);
} catch (error) { setError(error.message); }
}
return (
<main className="pageShell profilePage">
<AppLogo title="我的偏爱档案" />
<section className="linkPanel">
<h2>连接独立饭类版</h2>
<p>生成一次性绑定码,在另一个小程序确认后合并历史。</p>
<button onClick={createLinkCode}>生成 10 分钟绑定码</button>
{linkCode ? <output>{linkCode}</output> : null}
</section>
<h2 className="sectionTitle">做过的测试 · {results.length}</h2>
{error ? <div className="emptyState">{error}</div> : null}
<section className="resultList">
{results.map(result => (
<Link key={result.id} href={`/results/${result.id}`} className="resultRow">
<span className="rankBadge">#1</span>
<span><small>{result.test_title}</small><strong>{result.champion_name}</strong></span>
<b>→</b>
</Link>
))}
</section>
<BottomNav />
</main>
);
}
+118
View File
@@ -0,0 +1,118 @@
'use client';
import { AnimatePresence, motion } from 'motion/react';
import { useRouter } from 'next/navigation';
import { useEffect, useMemo, useRef, useState } from 'react';
import { apiRequest, ensureLogin } from '../lib/api';
import { chooseMatch, createBracket, firstOpenMatch } from '../lib/bracket';
const MODES = [
{ id: 'single', label: '一对' },
{ id: 'multi', label: '多对' },
{ id: 'swipe', label: '滑动' }
];
export default function TestArena({ slug }) {
const router = useRouter();
const [test, setTest] = useState(null);
const [bracket, setBracket] = useState(null);
const [mode, setMode] = useState('single');
const [error, setError] = useState('');
const [saving, setSaving] = useState(false);
const pointerStart = useRef(null);
useEffect(() => {
apiRequest(`/api/v1/tests/${slug}`).then(data => {
setTest(data);
setBracket(createBracket(data.candidates));
}).catch(error => setError(error.message));
}, [slug]);
const total = test ? test.candidates.length - 1 : 1;
const progress = bracket ? Math.round(bracket.decisions.length / total * 100) : 0;
const currentIndex = bracket ? firstOpenMatch(bracket) : -1;
const current = currentIndex >= 0 ? bracket.matches[currentIndex] : null;
const visibleMatches = useMemo(() => bracket?.matches.slice(bracket.offset, bracket.offset + 4) || [], [bracket]);
async function complete(finalState) {
setSaving(true);
const champion = finalState.pool[0];
const finalDecision = finalState.decisions.at(-1);
const runnerUp = finalDecision.left_id === champion.id ? finalDecision.right_id : finalDecision.left_id;
try {
await ensureLogin();
const result = await apiRequest(`/api/v1/tests/${slug}/runs`, {
method: 'POST',
body: {
app_key: 'hub',
champion_id: champion.id,
runner_up_id: runnerUp,
ranking_ids: [champion, ...finalState.eliminated].map(item => item.id),
decisions: finalState.decisions
}
});
sessionStorage.setItem('pk_last_result', JSON.stringify(result));
router.replace(`/results/${result.id}`);
} catch (error) {
setError(error.message);
setSaving(false);
}
}
function select(matchIndex, side) {
if (saving) return;
const outcome = chooseMatch(bracket, matchIndex, side);
let next = outcome.state;
if (!outcome.finished && mode === 'multi') {
const block = next.matches.slice(next.offset, next.offset + 4);
if (block.length && block.every(match => match.winner)) next = { ...next, offset: next.offset + 4 };
}
setBracket(next);
if (outcome.finished) complete(next);
}
function pointerUp(event) {
if (mode !== 'swipe' || pointerStart.current === null) return;
const delta = event.clientX - pointerStart.current;
pointerStart.current = null;
if (Math.abs(delta) >= 55) select(currentIndex, delta < 0 ? 'left' : 'right');
}
if (error) return <main className="arenaState"><h1>暂时无法继续</h1><p>{error}</p><button onClick={() => router.push('/')}>返回首页</button></main>;
if (!test || !bracket) return <main className="arenaState">正在抽签…</main>;
return (
<main className="arenaPage">
<header className="arenaHeader">
<button onClick={() => router.push('/')} aria-label="返回">←</button>
<span>第 {bracket.round} 轮</span>
<small>{bracket.decisions.length} / {total}</small>
</header>
<div className="progressTrack"><i style={{ width: `${progress}%` }} /></div>
<div className="modeTabs">
{MODES.map(item => <button key={item.id} className={mode === item.id ? 'active' : ''} onClick={() => setMode(item.id)}>{item.label}</button>)}
</div>
{mode === 'multi' ? (
<section className="multiArena">
<AnimatePresence mode="popLayout">
{visibleMatches.map((match, index) => {
const matchIndex = bracket.offset + index;
return (
<motion.article layout key={`${bracket.round}-${matchIndex}`} className={`miniMatch ${match.winner ? 'resolved' : ''}`} initial={{ opacity: 0, scale: .94 }} animate={{ opacity: 1, scale: 1 }} exit={{ opacity: 0, scale: .9 }}>
{match.winner ? <motion.strong initial={{ scale: .6 }} animate={{ scale: 1 }}>晋级<br />{match.winner.name}</motion.strong> : <><button onClick={() => select(matchIndex, 'left')}>{match.left.name}</button><span>VS</span><button onClick={() => select(matchIndex, 'right')}>{match.right.name}</button></>}
</motion.article>
);
})}
</AnimatePresence>
</section>
) : (
<section className={`singleArena ${mode === 'swipe' ? 'swipe' : ''}`} onPointerDown={event => { pointerStart.current = event.clientX; }} onPointerUp={pointerUp}>
<motion.button whileTap={{ scale: .94, rotate: -1 }} onClick={() => mode !== 'swipe' && select(currentIndex, 'left')} className="choiceCard warm"><small>A</small><strong>{current.left.name}</strong><span>{mode === 'swipe' ? '向左滑选它' : '点按晋级'}</span></motion.button>
<b className="versus">VS</b>
<motion.button whileTap={{ scale: .94, rotate: 1 }} onClick={() => mode !== 'swipe' && select(currentIndex, 'right')} className="choiceCard cool"><small>B</small><strong>{current.right.name}</strong><span>{mode === 'swipe' ? '向右滑选它' : '点按晋级'}</span></motion.button>
</section>
)}
{saving ? <div className="savingToast">正在保存你的冠军…</div> : null}
</main>
);
}