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

This commit is contained in:
2026-09-20 14:22:47 +08:00
parent 5a16113a6d
commit 2bf21a9f97
29 changed files with 6338 additions and 47 deletions
+2 -1
View File
@@ -1,5 +1,7 @@
.git
.gitea
web/.next
web/node_modules
pages
utils
scripts
@@ -8,4 +10,3 @@ app.json
app.css
project.config.json
README.md
+1 -1
View File
@@ -42,7 +42,7 @@ jobs:
set -eu
docker network inspect pk-lab-public >/dev/null 2>&1 || docker network create pk-lab-public
docker rm -f rice-pk-xhs-preview 2>/dev/null || true
docker run -d --name rice-pk-xhs-preview --restart unless-stopped --network pk-lab-public --read-only --tmpfs /var/cache/nginx --tmpfs /var/run -p "$DEPLOY_PORT:8080" "rice-pk-xhs:$SOURCE_REVISION"
docker run -d --name rice-pk-xhs-preview --restart unless-stopped --network pk-lab-public --read-only --tmpfs /tmp:rw,noexec,nosuid,size=64m -p "$DEPLOY_PORT:8080" "rice-pk-xhs:$SOURCE_REVISION"
for i in 1 2 3 4 5 6 7 8 9 10; do
status="$(docker inspect --format '{{.State.Health.Status}}' rice-pk-xhs-preview)"
[ "$status" = healthy ] && break
+1 -1
View File
@@ -1,4 +1,4 @@
.DS_Store
node_modules/
.next/
project.private.config.json
+21 -5
View File
@@ -1,7 +1,23 @@
FROM nginx:1.27-alpine
COPY web /usr/share/nginx/html
COPY assets /usr/share/nginx/html/assets
COPY nginx.conf /etc/nginx/conf.d/default.conf
FROM node:22-alpine AS dependencies
WORKDIR /app
COPY web/package.json web/package-lock.json ./
RUN npm ci
FROM node:22-alpine AS web-build
WORKDIR /app
COPY --from=dependencies /app/node_modules ./node_modules
COPY web ./
COPY assets ./public/assets
RUN npm run build
FROM node:22-alpine AS runtime
WORKDIR /app
ENV NODE_ENV=production PORT=8080 HOSTNAME=0.0.0.0
RUN addgroup -S nextjs && adduser -S nextjs -G nextjs
COPY --from=web-build --chown=nextjs:nextjs /app/.next/standalone ./
COPY --from=web-build --chown=nextjs:nextjs /app/.next/static ./.next/static
COPY --from=web-build --chown=nextjs:nextjs /app/public ./public
USER nextjs
EXPOSE 8080
HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=5 CMD wget -q -O- http://127.0.0.1:8080/health || exit 1
CMD ["nginx", "-g", "daemon off;"]
CMD ["node", "server.js"]
+4 -2
View File
@@ -1,5 +1,7 @@
# 本命饭 PK(独立版)
只开放 `rice` 测试的原生小红书小程序。打开即进入饭类主题,可重复测试、查看自己的饭类历史、输入综合版生成的一次性绑定码,并生成三种风格的分享图。
只开放 `rice` 测试的原生小红书小程序,同时提供 Next.js 公网预览。打开即进入饭类主题,可重复测试、查看自己的饭类历史、输入综合版生成的一次性绑定码,并生成可编辑的完整晋级图。
将 `app.js` 的 `apiBase` 改成生产 HTTPS API,在小红书后台配置合法域名并绑定独立版 App ID。CI 默认把公网功能预览常驻部署到宿主机 `3002`,并加入 `pk-lab-public` Docker 网络;浏览器固定同源请求 `/api`,由 Nginx 转发到 `pk-lab-api:8000`。`DEPLOY_PORT` 可覆盖。
将 `app.js` 的 `apiBase` 改成生产 HTTPS API,在小红书后台配置合法域名并绑定独立版 App ID。CI 默认把 Next.js standalone 服务常驻部署到宿主机 `3002`,并加入 `pk-lab-public` Docker 网络;浏览器固定同源请求 `/api`,由 Next.js Route Handler 转发到 `pk-lab-api:8000`。`DEPLOY_PORT` 可覆盖。
本地 Web 开发使用 `npm --prefix web install && npm --prefix web run dev`;仓库根目录仍可直接由小红书开发者工具打开。
-26
View File
@@ -1,26 +0,0 @@
server {
listen 8080;
server_name _;
root /usr/share/nginx/html;
location /api/ {
resolver 127.0.0.11 valid=10s ipv6=off;
set $api_upstream http://pk-lab-api:8000;
proxy_pass $api_upstream;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location / {
try_files $uri $uri/ /index.html;
}
location = /health {
access_log off;
return 200 "ok\n";
add_header Content-Type text/plain;
}
}
+10 -1
View File
@@ -1 +1,10 @@
{"name":"rice-pk-xhs","version":"0.1.0","private":true,"scripts":{"check":"node scripts/check.mjs","test":"node --test test/*.test.cjs"}}
{
"name": "rice-pk-xhs",
"version": "0.1.0",
"private": true,
"scripts": {
"check": "node scripts/check.mjs",
"test": "node --test test/*.test.cjs",
"build:web": "npm --prefix web run build"
}
}
+6 -1
View File
@@ -1 +1,6 @@
import{readFileSync,existsSync}from'node:fs';const required=['app.js','app.json','pages/index/index.xhsml','pages/test/test.js','pages/result/result.js','assets/test-covers/rice.jpg','vendor/poster-editor.cjs','web/index.html','web/app.js'];for(const file of required)if(!existsSync(file))throw new Error(`Missing ${file}`);JSON.parse(readFileSync('app.json','utf8'));console.log(`Static checks passed (${required.length} required files).`);
import { readFileSync, existsSync } from 'node:fs';
const required = ['app.js','app.json','pages/index/index.xhsml','pages/test/test.js','pages/result/result.js','assets/test-covers/rice.jpg','vendor/poster-editor.cjs','web/package.json','web/next.config.mjs','web/app/page.jsx','web/app/api/[...path]/route.js','web/components/RiceArena.jsx','web/components/RicePosterEditor.jsx'];
for (const file of required) if (!existsSync(file)) throw new Error(`Missing ${file}`);
JSON.parse(readFileSync('app.json','utf8'));
if (!readFileSync('web/next.config.mjs','utf8').includes("output: 'standalone'")) throw new Error('Next.js standalone output is required');
console.log(`Static checks passed (${required.length} required files).`);
+8 -2
View File
@@ -9,12 +9,18 @@ required = [
"pages/result/result.js",
"assets/test-covers/rice.jpg",
"vendor/poster-editor.cjs",
"web/index.html",
"web/app.js",
"web/package.json",
"web/next.config.mjs",
"web/app/page.jsx",
"web/app/api/[...path]/route.js",
"web/components/RiceArena.jsx",
"web/components/RicePosterEditor.jsx",
]
missing = [name for name in required if not Path(name).is_file()]
if missing:
raise SystemExit("Missing required files: " + ", ".join(missing))
json.loads(Path("app.json").read_text())
if "output: 'standalone'" not in Path("web/next.config.mjs").read_text():
raise SystemExit("Next.js standalone output is required")
print(f"Static checks passed ({len(required)} required files).")
-2
View File
File diff suppressed because one or more lines are too long
+12
View File
@@ -0,0 +1,12 @@
const API_BASE = process.env.API_INTERNAL_URL || 'http://pk-lab-api:8000';
async function forward(request, context) {
const { path } = await context.params;
const incoming = new URL(request.url);
const target = new URL(`/api/${path.join('/')}${incoming.search}`, API_BASE);
const headers = new Headers();
for (const name of ['authorization', 'content-type', 'accept']) { const value = request.headers.get(name); if (value) headers.set(name, value); }
const response = await fetch(target, { method: request.method, headers, body: ['GET','HEAD'].includes(request.method) ? undefined : await request.arrayBuffer(), cache: 'no-store' });
return new Response(response.body, { status: response.status, headers: { 'content-type': response.headers.get('content-type') || 'application/json' } });
}
export const dynamic = 'force-dynamic';
export const GET = forward; export const POST = forward; export const PUT = forward; export const PATCH = forward; export const DELETE = forward;
File diff suppressed because one or more lines are too long
+1
View File
@@ -0,0 +1 @@
export function GET() { return Response.json({ status: 'ok' }); }
+4
View File
@@ -0,0 +1,4 @@
import './globals.css';
export const metadata = { title: '本命饭 PK', description: '各种各样的饭,二选一。' };
export const viewport = { width: 'device-width', initialScale: 1, themeColor: '#fff8f2' };
export default function RootLayout({ children }) { return <html lang="zh-CN"><body>{children}</body></html>; }
+2
View File
@@ -0,0 +1,2 @@
import RiceHome from '../components/RiceHome';
export default function HomePage() { return <RiceHome />; }
+2
View File
@@ -0,0 +1,2 @@
import RicePosterEditor from '../../../components/RicePosterEditor';
export default async function ResultPage({ params }) { const { id } = await params; return <RicePosterEditor runId={id} />; }
+2
View File
@@ -0,0 +1,2 @@
import RiceArena from '../../components/RiceArena';
export default function TestPage() { return <RiceArena />; }
+18
View File
@@ -0,0 +1,18 @@
'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=[['single','一对'],['multi','多对'],['swipe','滑动']];
export default function RiceArena(){
const router=useRouter(),pointerStart=useRef(null);const[test,setTest]=useState(null),[bracket,setBracket]=useState(null),[mode,setMode]=useState('single'),[error,setError]=useState(''),[saving,setSaving]=useState(false);
useEffect(()=>{apiRequest('/api/v1/tests/rice').then(data=>{setTest(data);setBracket(createBracket(data.candidates));}).catch(reason=>setError(reason.message));},[]);
const total=test?test.candidates.length-1:1,currentIndex=bracket?firstOpenMatch(bracket):-1,current=currentIndex>=0?bracket.matches[currentIndex]:null,visible=useMemo(()=>bracket?.matches.slice(bracket.offset,bracket.offset+4)||[],[bracket]);
async function complete(finalState){setSaving(true);const champion=finalState.pool[0],last=finalState.decisions.at(-1),runner=last.left_id===champion.id?last.right_id:last.left_id;try{await ensureLogin();const result=await apiRequest('/api/v1/tests/rice/runs',{method:'POST',body:{app_key:'rice',champion_id:champion.id,runner_up_id:runner,ranking_ids:[champion,...finalState.eliminated].map(item=>item.id),decisions:finalState.decisions}});sessionStorage.setItem('rice_last_result',JSON.stringify(result));router.replace(`/results/${result.id}`);}catch(reason){setError(reason.message);setSaving(false);}}
function select(index,side){if(saving)return;const outcome=chooseMatch(bracket,index,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="centerState"><h1>暂时无法继续</h1><p>{error}</p><button onClick={()=>router.push('/')}>返回首页</button></main>;if(!test||!bracket)return <main className="centerState">正在抽签…</main>;
return <main className="arenaPage"><header className="arenaHeader"><button onClick={()=>router.push('/')} aria-label="返回">←</button><strong>第 {bracket.round} 轮</strong><small>{bracket.decisions.length} / {total}</small></header><div className="progress"><i style={{width:`${Math.round(bracket.decisions.length/total*100)}%`}}/></div><div className="modes">{MODES.map(([id,label])=><button key={id} className={mode===id?'active':''} onClick={()=>setMode(id)}>{label}</button>)}</div>
{mode==='multi'?<section className="multiArena"><AnimatePresence mode="popLayout">{visible.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?<strong>晋级<br/>{match.winner.name}</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={`pair ${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="choice 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="choice cool"><small>B</small><strong>{current.right.name}</strong><span>{mode==='swipe'?'向右滑选它':'点按晋级'}</span></motion.button></section>}{saving?<div className="toast">正在保存你的冠军…</div>:null}</main>;
}
+23
View File
@@ -0,0 +1,23 @@
'use client';
import { motion } from 'motion/react';
import Image from 'next/image';
import Link from 'next/link';
import { useEffect, useState } from 'react';
import { apiRequest, ensureLogin } from '../lib/api';
export default function RiceHome() {
const [test,setTest]=useState(null),[results,setResults]=useState([]),[code,setCode]=useState(''),[message,setMessage]=useState(''),[error,setError]=useState('');
useEffect(()=>{Promise.all([apiRequest('/api/v1/tests/rice'),ensureLogin().then(()=>apiRequest('/api/v1/me/results?test_slug=rice'))]).then(([data,history])=>{setTest(data);setResults(history);}).catch(reason=>setError(reason.message));},[]);
async function bind(){if(code.trim().length!==6){setMessage('请输入 6 位绑定码');return;}try{const data=await apiRequest('/api/v1/me/link-code/confirm',{method:'POST',body:{code:code.trim().toUpperCase()}});localStorage.setItem('rice_token',data.token);setMessage('档案已连接');setResults(await apiRequest('/api/v1/me/results?test_slug=rice'));}catch(reason){setMessage(reason.message);}}
if(error)return <main className="centerState"><h1>暂时没接上服务</h1><p>{error}</p><button onClick={()=>location.reload()}>重新加载</button></main>;
if(!test)return <main className="centerState">正在摆好饭桌…</main>;
return <main className="homeShell">
<header className="topbar"><strong>RICE PK</strong><span>独立饭类版</span></header>
<motion.section className="hero" initial={{opacity:0,y:18}} animate={{opacity:1,y:0}}>
<Image src="/assets/test-covers/rice.jpg" width={900} height={1200} priority sizes="(max-width: 720px) 100vw, 430px" alt="各种各样的饭二选一" />
<div className="heroCopy"><small>ONLY RICE · {test.candidate_count} 强</small><h1>{test.title}</h1><p>{test.subtitle}</p><Link className="primary" href="/test">开始选饭</Link></div>
</motion.section>
<section className="history"><div className="sectionHead"><h2>我的饭类结果</h2><span>{results.length} 次</span></div>{results.length?results.map(result=><Link className="resultRow" key={result.id} href={`/results/${result.id}`}><b>#1</b><span><small>{new Date(result.completed_at).toLocaleDateString()}</small><strong>{result.champion_name}</strong></span><i>→</i></Link>):<p className="empty">还没有冠军,第一轮现在开始。</p>}</section>
<section className="bindPanel"><h2>已有偏爱研究所档案?</h2><p>在综合版生成绑定码,在这里确认后合并两边历史。</p><div><input value={code} onChange={event=>setCode(event.target.value)} maxLength={6} placeholder="6 位绑定码"/><button onClick={bind}>确认连接</button></div>{message?<output>{message}</output>:null}</section>
</main>;
}
+18
View File
@@ -0,0 +1,18 @@
'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','#fff','#285ee8'],notebook:['#c9f06b','#1e2810','#ff72a7','#fff']};
const VIEWS=[['overview','总览'],['left','左半区'],['right','右半区'],['top16','16 强'],['top8','8 强'],['final','决赛']];
const TOOLS=[['filter','滤镜'],['text','文字'],['sticker','贴纸'],['crop','裁剪'],['adjust','调整'],['layout','布局'],['brush','画笔']];
export default function RicePosterEditor({runId}){
const router=useRouter(),canvasRef=useRef(null);const[result,setResult]=useState(null),[error,setError]=useState(''),[theme,setTheme]=useState('celebration'),[layout,setLayout]=useState('symmetric'),[view,setView]=useState('overview'),[tool,setTool]=useState('filter'),[caption,setCaption]=useState(''),[sticker,setSticker]=useState(true),[background,setBackground]=useState(null),[adjust,setAdjust]=useState({brightness:100,contrast:100,saturate:100});
useEffect(()=>{async function loadResult(){const cached=sessionStorage.getItem('rice_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(reason=>setError(reason.message));},[runId]);
const draw=useCallback(()=>{if(!result||!canvasRef.current)return;const canvas=canvasRef.current,ctx=canvas.getContext('2d'),colors=THEMES[theme];ctx.clearRect(0,0,750,1000);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}%)`;cover(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('RICE 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);ctx.fillStyle=colors[1];ctx.font='800 25px system-ui';ctx.fillText(caption||`冠军 ${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 21px system-ui';ctx.fillText('开饭',636,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 pick(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=`我的本命饭-${result.champion_name}.png`;link.href=canvasRef.current.toDataURL('image/png');link.click();}
if(error)return <main className="centerState"><h1>结果读取失败</h1><p>{error}</p><button onClick={()=>router.push('/')}>返回首页</button></main>;if(!result)return <main className="centerState">正在打开编辑器…</main>;
return <main className="editorPage"><header className="editorHeader"><button onClick={()=>router.push('/')}>←</button><div><strong>分享图编辑器</strong><small>{result.test_title} · {result.champion_name}</small></div><button className="export" onClick={save}>导出</button></header><section className="editorWorkspace"><canvas ref={canvasRef} width="750" height="1000"/><aside><div className="scrollRow"><button className={layout==='symmetric'?'active':''} onClick={()=>setLayout('symmetric')}>对称图</button><button className={layout==='single'?'active':''} onClick={()=>setLayout('single')}>单边图</button>{VIEWS.map(([id,label])=><button key={id} className={view===id?'active':''} onClick={()=>setView(id)}>{label}</button>)}</div><div className="mediaRow"><span>晋级图</span><label>+<small>添加底图</small><input type="file" accept="image/*" onChange={pick}/></label></div><div className="toolRow">{TOOLS.map(([id,label],index)=><button key={id} className={tool===id?'active':''} onClick={()=>setTool(id)}><i>{index+1}</i>{label}</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'?<div className="adjust">{Object.entries(adjust).map(([name,value])=><label key={name}><span>{name}</span><input type="range" min="50" max="150" value={value} onChange={event=>setAdjust({...adjust,[name]:Number(event.target.value)})}/></label>)}</div>:null}{['crop','layout','brush'].includes(tool)?<p>该工具由 PosterDocument 图层绑定驱动,可继续从素材服务加载预设。</p>:null}</motion.div></aside></section></main>;
}
function cover(ctx,image,x,y,width,height){const ratio=Math.max(width/image.width,height/image.height),w=image.width*ratio,h=image.height*ratio;ctx.drawImage(image,x+(width-w)/2,y+(height-h)/2,w,h);}
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)),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',side=symmetric&&round<maxRound&&index%2?1:-1,x=symmetric?375+side*Math.min(260,78+(maxRound-round)*62):70+(round-minRound)*(580/Math.max(1,maxRound-minRound)),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)),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);});}
+3
View File
@@ -0,0 +1,3 @@
import { defineConfig, globalIgnores } from 'eslint/config';
import nextVitals from 'eslint-config-next/core-web-vitals';
export default defineConfig([...nextVitals, globalIgnores(['.next/**', 'public/**'])]);
-2
View File
@@ -1,2 +0,0 @@
<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover"><meta name="theme-color" content="#fff8f2"><title>本命饭 PK · 公网预览</title><link rel="stylesheet" href="./style.css"></head><body><header><button id="home">RICE PK ✦</button><span>公网测试版</span></header><main id="app"></main><div id="toast"></div><script src="./runtime-env.js"></script><script src="./app.js"></script></body></html>
+18
View File
@@ -0,0 +1,18 @@
'use client';
export async function apiRequest(path, options = {}) {
const token = typeof window === 'undefined' ? null : localStorage.getItem('rice_token');
const headers = { Accept: 'application/json', ...(options.headers || {}) };
if (options.body !== undefined) headers['Content-Type'] = 'application/json';
if (token) headers.Authorization = `Bearer ${token}`;
const response = await fetch(path, { method: options.method || 'GET', headers, body: options.body === undefined ? undefined : JSON.stringify(options.body), cache: 'no-store' });
const data = await response.json().catch(() => ({}));
if (!response.ok) throw new Error(typeof data.detail === 'string' ? data.detail : '请求失败');
return data;
}
export async function ensureLogin() {
if (localStorage.getItem('rice_token')) return;
let previewId = localStorage.getItem('rice_preview_id');
if (!previewId) { previewId = `${Date.now().toString(36)}${Math.random().toString(36).slice(2)}`; localStorage.setItem('rice_preview_id', previewId); }
const session = await apiRequest('/api/v1/auth/xhs', { method: 'POST', body: { app_key: 'rice', code: `dev:web-${previewId}` } });
localStorage.setItem('rice_token', session.token);
}
+4
View File
@@ -0,0 +1,4 @@
export function buildMatches(pool) { const matches=[]; for(let index=0;index<pool.length;index+=2) matches.push({left:pool[index],right:pool[index+1]||null,winner:pool[index+1]?null:pool[index]}); return matches; }
export function createBracket(candidates) { return { round:1,pool:[...candidates],matches:buildMatches(candidates),eliminated:[],decisions:[],offset:0 }; }
export function chooseMatch(state,index,side) { const match=state.matches[index]; if(!match?.right||match.winner)return{state,finished:false}; const winner=side==='right'?match.right:match.left,loser=side==='right'?match.left:match.right; const matches=state.matches.map((item,i)=>i===index?{...item,winner}:item); let next={...state,matches,eliminated:[loser,...state.eliminated],decisions:[...state.decisions,{round:state.round,left_id:match.left.id,right_id:match.right.id,winner_id:winner.id}]}; if(matches.every(item=>item.winner)){const pool=matches.map(item=>item.winner);if(pool.length===1)return{state:{...next,pool},finished:true};next={...next,round:state.round+1,pool,matches:buildMatches(pool),offset:0};}return{state:next,finished:false}; }
export function firstOpenMatch(state) { return state.matches.findIndex(match=>match.right&&!match.winner); }
+3
View File
@@ -0,0 +1,3 @@
/** @type {import('next').NextConfig} */
const nextConfig = { output: 'standalone', poweredByHeader: false, reactStrictMode: true, images: { unoptimized: true } };
export default nextConfig;
+6165
View File
File diff suppressed because it is too large Load Diff
+8
View File
@@ -0,0 +1,8 @@
{
"name": "rice-pk-web",
"version": "0.2.0",
"private": true,
"scripts": { "dev": "next dev", "build": "next build", "start": "next start", "lint": "eslint ." },
"dependencies": { "motion": "^12.23.24", "next": "16.3.5", "react": "19.3.0", "react-dom": "19.3.0" },
"devDependencies": { "eslint": "^9.35.0", "eslint-config-next": "16.3.5" }
}
-1
View File
@@ -1 +0,0 @@
window.PK_CONFIG={apiBase:''};
-2
View File
@@ -1,2 +0,0 @@
:root{--paper:#fff8f2;--ink:#201d1b;--orange:#ff6b35;--blue:#2766df;--muted:#887d75}*{box-sizing:border-box}body{margin:0;background:var(--paper);color:var(--ink);font-family:Inter,system-ui,-apple-system,"PingFang SC",sans-serif}button{border:0;font:inherit;cursor:pointer}header{position:sticky;top:0;z-index:10;display:flex;justify-content:space-between;padding:18px max(22px,calc((100vw - 960px)/2));background:rgba(255,248,242,.92);border-bottom:1px solid rgba(50,30,20,.08);backdrop-filter:blur(14px)}header button{background:none;font-weight:950;letter-spacing:2px}header span{color:var(--muted);font-size:13px}.shell{width:min(960px,calc(100% - 32px));margin:34px auto 80px}.hero{position:relative;overflow:hidden;padding:55px;border-radius:40px;background:var(--orange);color:white;box-shadow:0 25px 65px rgba(160,60,20,.2)}.label{font-size:12px;letter-spacing:5px;opacity:.75}.hero h1{margin:35px 0 25px;font-size:clamp(58px,10vw,112px);line-height:.86;letter-spacing:-.07em}.hero p{max-width:590px;font-size:18px;line-height:1.65}.bowl{position:absolute;right:25px;top:25px;font-size:155px;transform:rotate(12deg)}.button{display:inline-block;margin-top:28px;padding:15px 28px;border-radius:99px;background:var(--ink);color:white;font-weight:850}.section-head{display:flex;justify-content:space-between;margin:52px 4px 18px}.muted{color:var(--muted)}.result-row{display:flex;align-items:center;gap:18px;width:100%;margin:12px 0;padding:21px;text-align:left;border-radius:24px;background:white;box-shadow:0 8px 28px rgba(50,30,20,.07)}.medal{display:grid;width:62px;height:62px;place-items:center;border-radius:18px;background:var(--orange);color:white;font-weight:950}.result-row strong{display:block;margin-top:3px;font-size:25px}.result-row>span:last-child{margin-left:auto}.bind{margin-top:35px;padding:28px;border-radius:28px;background:#f5eaff}.bind input{width:100%;height:55px;margin-top:15px;padding:0 18px;border:0;border-radius:16px;font-size:24px;letter-spacing:8px}.loading,.empty{padding:90px 20px;text-align:center;color:var(--muted)}.arena{max-width:900px}.arena-top{display:flex;justify-content:space-between}.progress{height:9px;margin:17px 0 48px;overflow:hidden;border-radius:99px;background:#e9ded6}.progress span{display:block;height:100%;background:var(--orange)}.arena h1{font-size:clamp(45px,7vw,78px);line-height:1.05}.pair{position:relative;display:grid;grid-template-columns:1fr 1fr;gap:24px}.choice{position:relative;min-height:400px;padding:38px;text-align:left;border-radius:38px;color:white;transition:.15s}.choice:hover{transform:scale(1.015)}.choice:first-child{background:var(--orange)}.choice:last-child{background:var(--blue)}.letter{display:grid;width:52px;height:52px;place-items:center;border:2px solid rgba(255,255,255,.6);border-radius:50%;font-weight:900}.food{position:absolute;right:28px;top:22px;font-size:84px}.name{display:block;margin-top:80px;font-size:clamp(42px,6vw,70px);font-weight:950}.hint{position:absolute;left:38px;bottom:32px;opacity:.7}.vs{position:absolute;z-index:2;left:50%;top:50%;display:grid;width:76px;height:76px;place-items:center;transform:translate(-50%,-50%) rotate(-9deg);border:5px solid var(--ink);border-radius:50%;background:white;font-weight:950}.champion{padding:55px;text-align:center;border-radius:38px;background:var(--ink);color:white}.champion h1{margin:18px 0;font-size:clamp(60px,10vw,108px)}.result-layout{display:grid;grid-template-columns:1fr 310px;gap:28px;margin-top:30px}.poster{width:100%;border-radius:28px;box-shadow:0 18px 55px rgba(50,30,20,.15)}.controls{padding:27px;border-radius:28px;background:white}.theme{width:100%;margin:7px 0;padding:14px;text-align:left;border:2px solid #e8ddd5;border-radius:17px;background:white;font-weight:800}.theme.active{background:var(--ink);color:white}.wide{width:100%}#toast{position:fixed;left:50%;bottom:28px;padding:14px 22px;transform:translate(-50%,25px);border-radius:99px;background:var(--ink);color:white;opacity:0;transition:.2s}#toast.show{opacity:1;transform:translate(-50%,0)}@media(max-width:720px){.hero{padding:38px 28px}.bowl{font-size:100px;opacity:.75}.pair,.result-layout{grid-template-columns:1fr}.choice{min-height:290px}.vs{top:50%}}